@buildanagent/gateway 0.0.0-bootstrap.0 → 0.1.0-alpha.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 +52 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +298 -1
- package/dist/adapters/anthropic/adapter.d.ts +25 -0
- package/dist/adapters/anthropic/adapter.js +183 -0
- package/dist/adapters/anthropic/adapter.js.map +1 -0
- package/dist/adapters/anthropic/failure.d.ts +20 -0
- package/dist/adapters/anthropic/failure.js +46 -0
- package/dist/adapters/anthropic/failure.js.map +1 -0
- package/dist/adapters/anthropic/index.d.ts +3 -0
- package/dist/adapters/anthropic/index.js +3 -0
- package/dist/adapters/anthropic/index.js.map +1 -0
- package/dist/adapters/anthropic/request.d.ts +53 -0
- package/dist/adapters/anthropic/request.js +250 -0
- package/dist/adapters/anthropic/request.js.map +1 -0
- package/dist/adapters/anthropic/response.d.ts +31 -0
- package/dist/adapters/anthropic/response.js +212 -0
- package/dist/adapters/anthropic/response.js.map +1 -0
- package/dist/adapters/anthropic/usage.d.ts +26 -0
- package/dist/adapters/anthropic/usage.js +39 -0
- package/dist/adapters/anthropic/usage.js.map +1 -0
- package/dist/adapters/openai-chat/adapter.d.ts +18 -0
- package/dist/adapters/openai-chat/adapter.js +86 -0
- package/dist/adapters/openai-chat/adapter.js.map +1 -0
- package/dist/adapters/openai-chat/compat.d.ts +58 -0
- package/dist/adapters/openai-chat/compat.js +19 -0
- package/dist/adapters/openai-chat/compat.js.map +1 -0
- package/dist/adapters/openai-chat/failure.d.ts +25 -0
- package/dist/adapters/openai-chat/failure.js +33 -0
- package/dist/adapters/openai-chat/failure.js.map +1 -0
- package/dist/adapters/openai-chat/index.d.ts +4 -0
- package/dist/adapters/openai-chat/index.js +3 -0
- package/dist/adapters/openai-chat/index.js.map +1 -0
- package/dist/adapters/openai-chat/request.d.ts +47 -0
- package/dist/adapters/openai-chat/request.js +227 -0
- package/dist/adapters/openai-chat/request.js.map +1 -0
- package/dist/adapters/openai-chat/response.d.ts +22 -0
- package/dist/adapters/openai-chat/response.js +203 -0
- package/dist/adapters/openai-chat/response.js.map +1 -0
- package/dist/adapters/openai-chat/usage.d.ts +19 -0
- package/dist/adapters/openai-chat/usage.js +22 -0
- package/dist/adapters/openai-chat/usage.js.map +1 -0
- package/dist/adapters/strict-schema.d.ts +67 -0
- package/dist/adapters/strict-schema.js +269 -0
- package/dist/adapters/strict-schema.js.map +1 -0
- package/dist/adapters/wire.d.ts +77 -0
- package/dist/adapters/wire.js +137 -0
- package/dist/adapters/wire.js.map +1 -0
- package/dist/catalog.d.ts +65 -0
- package/dist/catalog.js +145 -0
- package/dist/catalog.js.map +1 -0
- package/dist/catalog.json +120 -0
- package/dist/classify.d.ts +25 -0
- package/dist/classify.js +37 -0
- package/dist/classify.js.map +1 -0
- package/dist/complete.d.ts +9 -0
- package/dist/complete.js +13 -0
- package/dist/complete.js.map +1 -0
- package/dist/cost.d.ts +42 -0
- package/dist/cost.js +122 -0
- package/dist/cost.js.map +1 -0
- package/dist/create-model.d.ts +7 -0
- package/dist/create-model.js +81 -0
- package/dist/create-model.js.map +1 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +11 -0
- package/dist/middleware.js +22 -0
- package/dist/middleware.js.map +1 -0
- package/dist/names.d.ts +72 -0
- package/dist/names.js +175 -0
- package/dist/names.js.map +1 -0
- package/dist/provider-config.d.ts +15 -0
- package/dist/provider-config.js +23 -0
- package/dist/provider-config.js.map +1 -0
- package/dist/request-dump.d.ts +28 -0
- package/dist/request-dump.js +52 -0
- package/dist/request-dump.js.map +1 -0
- package/dist/request-policy.d.ts +18 -0
- package/dist/request-policy.js +27 -0
- package/dist/request-policy.js.map +1 -0
- package/dist/retry.d.ts +30 -0
- package/dist/retry.js +191 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime-types.d.ts +112 -0
- package/dist/runtime-types.js +2 -0
- package/dist/runtime-types.js.map +1 -0
- package/dist/spec.d.ts +67 -0
- package/dist/spec.js +2 -0
- package/dist/spec.js.map +1 -0
- package/dist/sse.d.ts +15 -0
- package/dist/sse.js +73 -0
- package/dist/sse.js.map +1 -0
- package/dist/stream-contract.d.ts +23 -0
- package/dist/stream-contract.js +101 -0
- package/dist/stream-contract.js.map +1 -0
- package/dist/testing/guards.d.ts +16 -0
- package/dist/testing/guards.js +48 -0
- package/dist/testing/guards.js.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +13 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mock-transport.d.ts +49 -0
- package/dist/testing/mock-transport.js +101 -0
- package/dist/testing/mock-transport.js.map +1 -0
- package/dist/testing/random.d.ts +3 -0
- package/dist/testing/random.js +13 -0
- package/dist/testing/random.js.map +1 -0
- package/dist/testing/setup.d.ts +1 -0
- package/dist/testing/setup.js +12 -0
- package/dist/testing/setup.js.map +1 -0
- package/dist/transform-messages.d.ts +32 -0
- package/dist/transform-messages.js +291 -0
- package/dist/transform-messages.js.map +1 -0
- package/dist/types.d.ts +130 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage.d.ts +8 -0
- package/dist/usage.js +20 -0
- package/dist/usage.js.map +1 -0
- package/package.json +53 -3
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The replay pass that makes a transcript recorded on one model safe to send to another (SDK plan §3.2; guide §2;
|
|
3
|
+
* HD3 rule 1). It runs before every request, so it must be pure, deterministic and idempotent. As the transcript
|
|
4
|
+
* grows, an Anthropic target loses older turns' thinking only as a leading run, which Anthropic's rule on omitted
|
|
5
|
+
* thinking allows.
|
|
6
|
+
*/
|
|
7
|
+
import { isCanonicalName } from "./names.js";
|
|
8
|
+
// Every target gets tool-call ids that meet the canonical tool-name rule (names.ts). These two constants rebuild an id
|
|
9
|
+
// that breaks it, so they must stay in step with that rule.
|
|
10
|
+
const TOOL_CALL_ID_INVALID_CHARS = /[^A-Za-z0-9_-]/g;
|
|
11
|
+
const TOOL_CALL_ID_MAX_LENGTH = 64;
|
|
12
|
+
// Anthropic drops, without billing, the thinking blocks the target model cannot read, and verifies each block by its
|
|
13
|
+
// signature. Outside tool use, a request may omit earlier turns' thinking, but not a block between two kept blocks.
|
|
14
|
+
const ANTHROPIC_API = "anthropic-messages";
|
|
15
|
+
const IMAGE_PLACEHOLDER = "(image omitted: this model does not accept images)";
|
|
16
|
+
const MISSING_RESULT_TEXT = "No result was recorded for this tool call.";
|
|
17
|
+
// Anthropic requires the first message to come from the user, so an emptied opening user message leaves this note.
|
|
18
|
+
const CONTINUED_TEXT = "(continued)";
|
|
19
|
+
/**
|
|
20
|
+
* Prepares a transcript for one target model, so a conversation recorded on any provider can be sent to it. The
|
|
21
|
+
* pass returns a new array and never changes `messages`; the result may share unchanged blocks with the input.
|
|
22
|
+
*
|
|
23
|
+
* It applies five rules:
|
|
24
|
+
*
|
|
25
|
+
* 1. It skips assistant turns that ended in an error or an abort, together with the tool results that answer their
|
|
26
|
+
* calls, so a resumed request asks the model again.
|
|
27
|
+
* 2. It drops every reasoning block when `caps.reasoning` is false. Otherwise it drops reasoning written by another
|
|
28
|
+
* provider, and strips a signature the target cannot verify. An Anthropic target keeps every Anthropic-signed
|
|
29
|
+
* block unchanged, even one whose text is empty, and drops every block it cannot send signed. When one block must
|
|
30
|
+
* go, every older reasoning block goes with it, because Anthropic lets a request omit earlier thinking but not a
|
|
31
|
+
* block between two kept blocks. Any other target keeps the text of a block it cannot verify, unless the text is
|
|
32
|
+
* empty.
|
|
33
|
+
* 3. It replaces each image with a short text note when `caps.images` is false.
|
|
34
|
+
* 4. It rewrites tool-call ids that are not 1–64 letters, digits, `_` or `-`, or that repeat an earlier id, and
|
|
35
|
+
* updates each matching tool result.
|
|
36
|
+
* 5. It moves each tool result next to its call, however much later the result appears, drops results that answer
|
|
37
|
+
* no call, and gives every call that lacks a result a synthetic error result. A result answers the newest earlier
|
|
38
|
+
* call with its id from a completed turn, and answers a skipped turn's call only when no such call is waiting.
|
|
39
|
+
*
|
|
40
|
+
* It also keeps each message to the shape both providers accept. A user message carries no reasoning or tool calls,
|
|
41
|
+
* no message carries an empty text block, and a message left with no content is dropped. Adjacent user messages are
|
|
42
|
+
* merged into one, and so are adjacent assistant messages: the merged message takes the later one's stop reason,
|
|
43
|
+
* usage and cost, and drops the later one's reasoning if the earlier one has text or tool calls, so reasoning never
|
|
44
|
+
* follows a block it did not follow before. If the input holds a user message, the output starts with one, using a
|
|
45
|
+
* short placeholder note when the opening user message was emptied. An input left with nothing to send returns `[]`.
|
|
46
|
+
*
|
|
47
|
+
* Running the pass on its own output returns the same transcript.
|
|
48
|
+
*/
|
|
49
|
+
export function transformMessages(messages, target, caps) {
|
|
50
|
+
const cleaned = messages.map((message) => withSendableBlocks(message, caps));
|
|
51
|
+
const reasoned = caps.reasoning ? applyReasoningRules(cleaned, target) : cleaned;
|
|
52
|
+
const merged = mergeAdjacentMessages(pairToolCalls(reasoned), target);
|
|
53
|
+
return startWithUser(merged, messages.some((message) => message.role === "user"));
|
|
54
|
+
}
|
|
55
|
+
function isFailedTurn(message) {
|
|
56
|
+
return message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted");
|
|
57
|
+
}
|
|
58
|
+
// Blocks -------------------------------------------------------------------------------------------------------------
|
|
59
|
+
/**
|
|
60
|
+
* Removes the blocks no target accepts in this message: reasoning and tool calls in a user message, empty text, and
|
|
61
|
+
* reasoning when the target does not reason. Replaces images when the target takes none.
|
|
62
|
+
*/
|
|
63
|
+
function withSendableBlocks(message, caps) {
|
|
64
|
+
if (message.role === "tool")
|
|
65
|
+
return caps.images ? message : { ...message, content: message.content.map(imageToText) };
|
|
66
|
+
const content = message.content.flatMap((block) => sendableBlock(block, message.role === "user", caps));
|
|
67
|
+
return { ...message, content };
|
|
68
|
+
}
|
|
69
|
+
function sendableBlock(block, inUserMessage, caps) {
|
|
70
|
+
if (block.type === "text")
|
|
71
|
+
return block.text === "" ? [] : [block];
|
|
72
|
+
if (block.type === "image")
|
|
73
|
+
return [caps.images ? block : imageToText(block)];
|
|
74
|
+
if (block.type === "tool_call")
|
|
75
|
+
return inUserMessage ? [] : [block];
|
|
76
|
+
return inUserMessage || !caps.reasoning ? [] : [block];
|
|
77
|
+
}
|
|
78
|
+
function imageToText(block) {
|
|
79
|
+
return block.type === "image" ? { type: "text", text: IMAGE_PLACEHOLDER } : block;
|
|
80
|
+
}
|
|
81
|
+
// Reasoning ----------------------------------------------------------------------------------------------------------
|
|
82
|
+
/**
|
|
83
|
+
* Judges every reasoning block in a completed assistant turn. For an Anthropic target it then drops each one at or
|
|
84
|
+
* before the newest dropped block, because a request may omit the oldest run of thinking blocks, never one in the
|
|
85
|
+
* middle (HD3 rule 1). Keeping the newest run means a later drop only ever removes blocks older than itself, so older
|
|
86
|
+
* thinking leaves as a leading run. Other targets check no such order, so they lose only the blocks judged unsendable.
|
|
87
|
+
* Failed turns are skipped later, so their reasoning is not judged and does not count as a drop.
|
|
88
|
+
*/
|
|
89
|
+
function applyReasoningRules(messages, target) {
|
|
90
|
+
const verdicts = [];
|
|
91
|
+
for (const message of messages) {
|
|
92
|
+
if (message.role !== "assistant" || isFailedTurn(message))
|
|
93
|
+
continue;
|
|
94
|
+
for (const block of message.content) {
|
|
95
|
+
if (block.type === "reasoning")
|
|
96
|
+
verdicts.push(judgeReasoning(block, message.model, target));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const lastDropped = target.api === ANTHROPIC_API ? verdicts.lastIndexOf(undefined) : -1;
|
|
100
|
+
let position = 0;
|
|
101
|
+
const keep = () => {
|
|
102
|
+
const verdict = verdicts[position];
|
|
103
|
+
position += 1;
|
|
104
|
+
return position - 1 > lastDropped ? verdict : undefined;
|
|
105
|
+
};
|
|
106
|
+
return messages.map((message) => {
|
|
107
|
+
if (message.role !== "assistant" || isFailedTurn(message))
|
|
108
|
+
return message;
|
|
109
|
+
const content = message.content.flatMap((block) => {
|
|
110
|
+
if (block.type !== "reasoning")
|
|
111
|
+
return [block];
|
|
112
|
+
const kept = keep();
|
|
113
|
+
return kept === undefined ? [] : [kept];
|
|
114
|
+
});
|
|
115
|
+
return { ...message, content };
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** The block to send, or `undefined` to drop it. */
|
|
119
|
+
function judgeReasoning(block, source, target) {
|
|
120
|
+
if (source.api !== target.api || source.provider !== target.provider)
|
|
121
|
+
return undefined;
|
|
122
|
+
if (block.signature !== undefined && signatureFits(block.signature, target))
|
|
123
|
+
return block;
|
|
124
|
+
if (target.api === ANTHROPIC_API || block.text === "")
|
|
125
|
+
return undefined;
|
|
126
|
+
return block.signature === undefined ? block : { type: "reasoning", text: block.text };
|
|
127
|
+
}
|
|
128
|
+
function signatureFits(signature, target) {
|
|
129
|
+
if (signature.api !== target.api || signature.provider !== target.provider)
|
|
130
|
+
return false;
|
|
131
|
+
return target.api === ANTHROPIC_API || signature.model === target.id;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Pairs every result with a call made before it, across the whole transcript, then writes each completed turn
|
|
135
|
+
* followed by its calls' results in call order. User messages keep their place; a tool result appears only after the
|
|
136
|
+
* turn it answers.
|
|
137
|
+
*/
|
|
138
|
+
function pairToolCalls(messages) {
|
|
139
|
+
const allocateId = idAllocator();
|
|
140
|
+
const calls = [];
|
|
141
|
+
const turns = new Map();
|
|
142
|
+
messages.forEach((message, index) => {
|
|
143
|
+
if (message.role === "tool") {
|
|
144
|
+
answer(calls, message);
|
|
145
|
+
}
|
|
146
|
+
else if (message.role === "assistant" && isFailedTurn(message)) {
|
|
147
|
+
for (const block of message.content) {
|
|
148
|
+
if (block.type !== "tool_call")
|
|
149
|
+
continue;
|
|
150
|
+
calls.push({ original: block.callId, id: block.callId, turn: index, skipped: true, answered: false });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else if (message.role === "assistant" && message.content.length > 0) {
|
|
154
|
+
const turn = openTurn(message, index, allocateId);
|
|
155
|
+
calls.push(...turn.calls);
|
|
156
|
+
turns.set(index, turn);
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
const output = [];
|
|
160
|
+
messages.forEach((message, index) => {
|
|
161
|
+
const turn = turns.get(index);
|
|
162
|
+
if (turn !== undefined) {
|
|
163
|
+
output.push(turn.message, ...turn.calls.map((call) => call.result ?? syntheticResult(call.id)));
|
|
164
|
+
}
|
|
165
|
+
else if (message.role === "user" && message.content.length > 0) {
|
|
166
|
+
output.push(message);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
return output;
|
|
170
|
+
}
|
|
171
|
+
function openTurn(message, index, allocateId) {
|
|
172
|
+
const calls = [];
|
|
173
|
+
const content = message.content.map((block) => {
|
|
174
|
+
if (block.type !== "tool_call")
|
|
175
|
+
return block;
|
|
176
|
+
const id = allocateId(block.callId);
|
|
177
|
+
calls.push({ original: block.callId, id, turn: index, skipped: false, answered: false });
|
|
178
|
+
return id === block.callId ? block : { ...block, callId: id };
|
|
179
|
+
});
|
|
180
|
+
return { message: { ...message, content }, calls };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Gives a result to an unanswered earlier call with its id. A completed turn's call beats a skipped one, so a failed
|
|
184
|
+
* turn never takes a result a completed turn is waiting for; then the newest turn wins and, within it, the first
|
|
185
|
+
* call, so a repeated id pairs its results in order.
|
|
186
|
+
*/
|
|
187
|
+
function answer(calls, result) {
|
|
188
|
+
let best;
|
|
189
|
+
for (const call of calls) {
|
|
190
|
+
if (call.answered || call.original !== result.callId)
|
|
191
|
+
continue;
|
|
192
|
+
if (best === undefined || outranks(call, best))
|
|
193
|
+
best = call;
|
|
194
|
+
}
|
|
195
|
+
if (best === undefined)
|
|
196
|
+
return;
|
|
197
|
+
best.answered = true;
|
|
198
|
+
if (!best.skipped)
|
|
199
|
+
best.result = best.id === result.callId ? result : { ...result, callId: best.id };
|
|
200
|
+
}
|
|
201
|
+
function outranks(call, best) {
|
|
202
|
+
if (call.skipped !== best.skipped)
|
|
203
|
+
return !call.skipped;
|
|
204
|
+
return call.turn > best.turn;
|
|
205
|
+
}
|
|
206
|
+
function syntheticResult(callId) {
|
|
207
|
+
const content = [{ type: "text", text: MISSING_RESULT_TEXT }];
|
|
208
|
+
return { role: "tool", callId, content, isError: true };
|
|
209
|
+
}
|
|
210
|
+
// Message shape ------------------------------------------------------------------------------------------------------
|
|
211
|
+
/**
|
|
212
|
+
* Merges adjacent messages of the same role. When a merge drops reasoning and the target is Anthropic, every older
|
|
213
|
+
* reasoning block goes too, as in the reasoning rule, and a second merge joins the messages that leaves adjacent.
|
|
214
|
+
* That merge drops no reasoning, because none is left at or before the first merge's drop.
|
|
215
|
+
*/
|
|
216
|
+
function mergeAdjacentMessages(messages, target) {
|
|
217
|
+
const first = mergeOnce(messages);
|
|
218
|
+
if (first.droppedThrough < 0 || target.api !== ANTHROPIC_API)
|
|
219
|
+
return first.merged;
|
|
220
|
+
return mergeOnce(withoutReasoningThrough(first.merged, first.droppedThrough)).merged;
|
|
221
|
+
}
|
|
222
|
+
/** Joins each run of adjacent user or assistant messages into one, and drops messages left with no content. */
|
|
223
|
+
function mergeOnce(messages) {
|
|
224
|
+
const merged = [];
|
|
225
|
+
let droppedThrough = -1;
|
|
226
|
+
for (const message of messages) {
|
|
227
|
+
if (message.role !== "tool" && message.content.length === 0)
|
|
228
|
+
continue;
|
|
229
|
+
const last = merged.at(-1);
|
|
230
|
+
if (message.role === "user" && last?.role === "user") {
|
|
231
|
+
const joined = { role: "user", content: [...last.content, ...message.content] };
|
|
232
|
+
merged[merged.length - 1] = joined;
|
|
233
|
+
}
|
|
234
|
+
else if (message.role === "assistant" && last?.role === "assistant") {
|
|
235
|
+
const { joined, dropped } = joinAssistant(last, message);
|
|
236
|
+
merged[merged.length - 1] = joined;
|
|
237
|
+
if (dropped)
|
|
238
|
+
droppedThrough = merged.length - 1;
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
merged.push(message);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return { merged, droppedThrough };
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Appends a later assistant message to an earlier one. The later reasoning is dropped when the earlier message has
|
|
248
|
+
* text or tool calls, since it would otherwise follow them. Kept reasoning was judged against its own message's
|
|
249
|
+
* model, so the merged message keeps the earlier model when the earlier message carries reasoning.
|
|
250
|
+
*/
|
|
251
|
+
function joinAssistant(earlier, later) {
|
|
252
|
+
const hasBody = earlier.content.some((block) => block.type !== "reasoning");
|
|
253
|
+
const appended = hasBody ? later.content.filter((block) => block.type !== "reasoning") : later.content;
|
|
254
|
+
const model = earlier.content.some((block) => block.type === "reasoning") ? earlier.model : later.model;
|
|
255
|
+
const joined = { ...later, model, content: [...earlier.content, ...appended] };
|
|
256
|
+
return { joined, dropped: appended.length < later.content.length };
|
|
257
|
+
}
|
|
258
|
+
function withoutReasoningThrough(messages, through) {
|
|
259
|
+
return messages.map((message, index) => {
|
|
260
|
+
if (index > through || message.role !== "assistant")
|
|
261
|
+
return message;
|
|
262
|
+
return { ...message, content: message.content.filter((block) => block.type !== "reasoning") };
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
function startWithUser(messages, inputHadUser) {
|
|
266
|
+
if (!inputHadUser || messages.length === 0 || messages[0]?.role === "user")
|
|
267
|
+
return messages;
|
|
268
|
+
return [{ role: "user", content: [{ type: "text", text: CONTINUED_TEXT }] }, ...messages];
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Returns a function that maps each tool-call id, in transcript order, to a valid id no earlier call uses. A valid,
|
|
272
|
+
* unused id is kept, so a second pass changes nothing.
|
|
273
|
+
*/
|
|
274
|
+
function idAllocator() {
|
|
275
|
+
const taken = new Set();
|
|
276
|
+
return (original) => {
|
|
277
|
+
const base = isCanonicalName(original) ? original : sanitizeId(original);
|
|
278
|
+
let id = base;
|
|
279
|
+
for (let n = 2; taken.has(id); n += 1) {
|
|
280
|
+
const suffix = `_${n}`;
|
|
281
|
+
id = base.slice(0, TOOL_CALL_ID_MAX_LENGTH - suffix.length) + suffix;
|
|
282
|
+
}
|
|
283
|
+
taken.add(id);
|
|
284
|
+
return id;
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function sanitizeId(id) {
|
|
288
|
+
const cleaned = id.replace(TOOL_CALL_ID_INVALID_CHARS, "_").slice(0, TOOL_CALL_ID_MAX_LENGTH);
|
|
289
|
+
return cleaned === "" ? "call" : cleaned;
|
|
290
|
+
}
|
|
291
|
+
//# sourceMappingURL=transform-messages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../src/transform-messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAQ7C,uHAAuH;AACvH,4DAA4D;AAC5D,MAAM,0BAA0B,GAAG,iBAAiB,CAAC;AACrD,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAEnC,qHAAqH;AACrH,oHAAoH;AACpH,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAE3C,MAAM,iBAAiB,GAAG,oDAAoD,CAAC;AAC/E,MAAM,mBAAmB,GAAG,4CAA4C,CAAC;AACzE,mHAAmH;AACnH,MAAM,cAAc,GAAG,aAAa,CAAC;AAErC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,UAAU,iBAAiB,CAAC,QAA4B,EAAE,MAAgB,EAAE,IAAe;IAC/F,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;IAC7E,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,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M,IAAI,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,EAAE,GAAG,IAAI,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;YACtC,MAAM,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;YACvB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;QACvE,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACd,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,EAAU;IAC5B,MAAM,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,0BAA0B,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,CAAC,CAAC;IAC9F,OAAO,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * The replay pass that makes a transcript recorded on one model safe to send to another (SDK plan §3.2; guide §2;\n * HD3 rule 1). It runs before every request, so it must be pure, deterministic and idempotent. As the transcript\n * grows, an Anthropic target loses older turns' thinking only as a leading run, which Anthropic's rule on omitted\n * thinking allows.\n */\nimport { isCanonicalName } from \"./names.js\";\nimport type { ContentBlock, Message, ModelCaps, ModelContent, ModelRef } from \"./types.js\";\n\ntype Block<T extends ContentBlock[\"type\"]> = Extract<ContentBlock, { type: T }>;\ntype AssistantMessage = Extract<Message, { role: \"assistant\" }>;\ntype ToolMessage = Extract<Message, { role: \"tool\" }>;\ntype UserMessage = Extract<Message, { role: \"user\" }>;\n\n// Every target gets tool-call ids that meet the canonical tool-name rule (names.ts). These two constants rebuild an id\n// that breaks it, so they must stay in step with that rule.\nconst TOOL_CALL_ID_INVALID_CHARS = /[^A-Za-z0-9_-]/g;\nconst TOOL_CALL_ID_MAX_LENGTH = 64;\n\n// Anthropic drops, without billing, the thinking blocks the target model cannot read, and verifies each block by its\n// signature. Outside tool use, a request may omit earlier turns' thinking, but not a block between two kept blocks.\nconst ANTHROPIC_API = \"anthropic-messages\";\n\nconst IMAGE_PLACEHOLDER = \"(image omitted: this model does not accept images)\";\nconst MISSING_RESULT_TEXT = \"No result was recorded for this tool call.\";\n// Anthropic requires the first message to come from the user, so an emptied opening user message leaves this note.\nconst CONTINUED_TEXT = \"(continued)\";\n\n/**\n * Prepares a transcript for one target model, so a conversation recorded on any provider can be sent to it. The\n * pass returns a new array and never changes `messages`; the result may share unchanged blocks with the input.\n *\n * It applies five rules:\n *\n * 1. It skips assistant turns that ended in an error or an abort, together with the tool results that answer their\n * calls, so a resumed request asks the model again.\n * 2. It drops every reasoning block when `caps.reasoning` is false. Otherwise it drops reasoning written by another\n * provider, and strips a signature the target cannot verify. An Anthropic target keeps every Anthropic-signed\n * block unchanged, even one whose text is empty, and drops every block it cannot send signed. When one block must\n * go, every older reasoning block goes with it, because Anthropic lets a request omit earlier thinking but not a\n * block between two kept blocks. Any other target keeps the text of a block it cannot verify, unless the text is\n * empty.\n * 3. It replaces each image with a short text note when `caps.images` is false.\n * 4. It rewrites tool-call ids that are not 1–64 letters, digits, `_` or `-`, or that repeat an earlier id, and\n * updates each matching tool result.\n * 5. It moves each tool result next to its call, however much later the result appears, drops results that answer\n * no call, and gives every call that lacks a result a synthetic error result. A result answers the newest earlier\n * call with its id from a completed turn, and answers a skipped turn's call only when no such call is waiting.\n *\n * It also keeps each message to the shape both providers accept. A user message carries no reasoning or tool calls,\n * no message carries an empty text block, and a message left with no content is dropped. Adjacent user messages are\n * merged into one, and so are adjacent assistant messages: the merged message takes the later one's stop reason,\n * usage and cost, and drops the later one's reasoning if the earlier one has text or tool calls, so reasoning never\n * follows a block it did not follow before. If the input holds a user message, the output starts with one, using a\n * short placeholder note when the opening user message was emptied. An input left with nothing to send returns `[]`.\n *\n * Running the pass on its own output returns the same transcript.\n */\nexport function transformMessages(messages: readonly Message[], target: ModelRef, caps: ModelCaps): Message[] {\n const cleaned = messages.map((message) => withSendableBlocks(message, caps));\n const reasoned = caps.reasoning ? applyReasoningRules(cleaned, target) : cleaned;\n const merged = mergeAdjacentMessages(pairToolCalls(reasoned), target);\n return startWithUser(\n merged,\n messages.some((message) => message.role === \"user\"),\n );\n}\n\nfunction isFailedTurn(message: Message): boolean {\n return message.role === \"assistant\" && (message.stopReason === \"error\" || message.stopReason === \"aborted\");\n}\n\n// Blocks -------------------------------------------------------------------------------------------------------------\n\n/**\n * Removes the blocks no target accepts in this message: reasoning and tool calls in a user message, empty text, and\n * reasoning when the target does not reason. Replaces images when the target takes none.\n */\nfunction withSendableBlocks(message: Message, caps: ModelCaps): Message {\n if (message.role === \"tool\") return caps.images ? message : { ...message, content: message.content.map(imageToText) };\n const content = message.content.flatMap((block) => sendableBlock(block, message.role === \"user\", caps));\n return { ...message, content };\n}\n\nfunction sendableBlock(block: ContentBlock, inUserMessage: boolean, caps: ModelCaps): ContentBlock[] {\n if (block.type === \"text\") return block.text === \"\" ? [] : [block];\n if (block.type === \"image\") return [caps.images ? block : imageToText(block)];\n if (block.type === \"tool_call\") return inUserMessage ? [] : [block];\n return inUserMessage || !caps.reasoning ? [] : [block];\n}\n\nfunction imageToText<T extends ContentBlock>(block: T): T | Block<\"text\"> {\n return block.type === \"image\" ? { type: \"text\", text: IMAGE_PLACEHOLDER } : block;\n}\n\n// Reasoning ----------------------------------------------------------------------------------------------------------\n\n/**\n * Judges every reasoning block in a completed assistant turn. For an Anthropic target it then drops each one at or\n * before the newest dropped block, because a request may omit the oldest run of thinking blocks, never one in the\n * middle (HD3 rule 1). Keeping the newest run means a later drop only ever removes blocks older than itself, so older\n * thinking leaves as a leading run. Other targets check no such order, so they lose only the blocks judged unsendable.\n * Failed turns are skipped later, so their reasoning is not judged and does not count as a drop.\n */\nfunction applyReasoningRules(messages: readonly Message[], target: ModelRef): Message[] {\n const verdicts: Array<Block<\"reasoning\"> | undefined> = [];\n for (const message of messages) {\n if (message.role !== \"assistant\" || isFailedTurn(message)) continue;\n for (const block of message.content) {\n if (block.type === \"reasoning\") verdicts.push(judgeReasoning(block, message.model, target));\n }\n }\n const lastDropped = target.api === ANTHROPIC_API ? verdicts.lastIndexOf(undefined) : -1;\n let position = 0;\n const keep = (): Block<\"reasoning\"> | undefined => {\n const verdict = verdicts[position];\n position += 1;\n return position - 1 > lastDropped ? verdict : undefined;\n };\n return messages.map((message) => {\n if (message.role !== \"assistant\" || isFailedTurn(message)) return message;\n const content = message.content.flatMap((block): ContentBlock[] => {\n if (block.type !== \"reasoning\") return [block];\n const kept = keep();\n return kept === undefined ? [] : [kept];\n });\n return { ...message, content };\n });\n}\n\n/** The block to send, or `undefined` to drop it. */\nfunction judgeReasoning(block: Block<\"reasoning\">, source: ModelRef, target: ModelRef): Block<\"reasoning\"> | undefined {\n if (source.api !== target.api || source.provider !== target.provider) return undefined;\n if (block.signature !== undefined && signatureFits(block.signature, target)) return block;\n if (target.api === ANTHROPIC_API || block.text === \"\") return undefined;\n return block.signature === undefined ? block : { type: \"reasoning\", text: block.text };\n}\n\nfunction signatureFits(signature: NonNullable<Block<\"reasoning\">[\"signature\"]>, target: ModelRef): boolean {\n if (signature.api !== target.api || signature.provider !== target.provider) return false;\n return target.api === ANTHROPIC_API || signature.model === target.id;\n}\n\n// Tool calls and results ---------------------------------------------------------------------------------------------\n\ninterface Call {\n readonly original: string;\n readonly id: string;\n /** The index of the assistant message that made the call, so a result can prefer the newest turn. */\n readonly turn: number;\n /** True for a call from a failed turn: a result that answers it is dropped with the turn. */\n readonly skipped: boolean;\n answered: boolean;\n result?: ToolMessage;\n}\n\n/** A completed assistant turn with its calls in order, each of which later gets its result. */\ninterface Turn {\n readonly message: AssistantMessage;\n readonly calls: readonly Call[];\n}\n\n/**\n * Pairs every result with a call made before it, across the whole transcript, then writes each completed turn\n * followed by its calls' results in call order. User messages keep their place; a tool result appears only after the\n * turn it answers.\n */\nfunction pairToolCalls(messages: readonly Message[]): Message[] {\n const allocateId = idAllocator();\n const calls: Call[] = [];\n const turns = new Map<number, Turn>();\n messages.forEach((message, index) => {\n if (message.role === \"tool\") {\n answer(calls, message);\n } else if (message.role === \"assistant\" && isFailedTurn(message)) {\n for (const block of message.content) {\n if (block.type !== \"tool_call\") continue;\n calls.push({ original: block.callId, id: block.callId, turn: index, skipped: true, answered: false });\n }\n } else if (message.role === \"assistant\" && message.content.length > 0) {\n const turn = openTurn(message, index, allocateId);\n calls.push(...turn.calls);\n turns.set(index, turn);\n }\n });\n const output: Message[] = [];\n messages.forEach((message, index) => {\n const turn = turns.get(index);\n if (turn !== undefined) {\n output.push(turn.message, ...turn.calls.map((call) => call.result ?? syntheticResult(call.id)));\n } else if (message.role === \"user\" && message.content.length > 0) {\n output.push(message);\n }\n });\n return output;\n}\n\nfunction openTurn(message: AssistantMessage, index: number, allocateId: (id: string) => string): Turn {\n const calls: Call[] = [];\n const content = message.content.map((block): ContentBlock => {\n if (block.type !== \"tool_call\") return block;\n const id = allocateId(block.callId);\n calls.push({ original: block.callId, id, turn: index, skipped: false, answered: false });\n return id === block.callId ? block : { ...block, callId: id };\n });\n return { message: { ...message, content }, calls };\n}\n\n/**\n * Gives a result to an unanswered earlier call with its id. A completed turn's call beats a skipped one, so a failed\n * turn never takes a result a completed turn is waiting for; then the newest turn wins and, within it, the first\n * call, so a repeated id pairs its results in order.\n */\nfunction answer(calls: readonly Call[], result: ToolMessage): void {\n let best: Call | undefined;\n for (const call of calls) {\n if (call.answered || call.original !== result.callId) continue;\n if (best === undefined || outranks(call, best)) best = call;\n }\n if (best === undefined) return;\n best.answered = true;\n if (!best.skipped) best.result = best.id === result.callId ? result : { ...result, callId: best.id };\n}\n\nfunction outranks(call: Call, best: Call): boolean {\n if (call.skipped !== best.skipped) return !call.skipped;\n return call.turn > best.turn;\n}\n\nfunction syntheticResult(callId: string): ToolMessage {\n const content: ModelContent[] = [{ type: \"text\", text: MISSING_RESULT_TEXT }];\n return { role: \"tool\", callId, content, isError: true };\n}\n\n// Message shape ------------------------------------------------------------------------------------------------------\n\n/**\n * Merges adjacent messages of the same role. When a merge drops reasoning and the target is Anthropic, every older\n * reasoning block goes too, as in the reasoning rule, and a second merge joins the messages that leaves adjacent.\n * That merge drops no reasoning, because none is left at or before the first merge's drop.\n */\nfunction mergeAdjacentMessages(messages: readonly Message[], target: ModelRef): Message[] {\n const first = mergeOnce(messages);\n if (first.droppedThrough < 0 || target.api !== ANTHROPIC_API) return first.merged;\n return mergeOnce(withoutReasoningThrough(first.merged, first.droppedThrough)).merged;\n}\n\ninterface MergeResult {\n readonly merged: Message[];\n /** The index of the newest merged message that lost reasoning, or -1. */\n readonly droppedThrough: number;\n}\n\n/** Joins each run of adjacent user or assistant messages into one, and drops messages left with no content. */\nfunction mergeOnce(messages: readonly Message[]): MergeResult {\n const merged: Message[] = [];\n let droppedThrough = -1;\n for (const message of messages) {\n if (message.role !== \"tool\" && message.content.length === 0) continue;\n const last = merged.at(-1);\n if (message.role === \"user\" && last?.role === \"user\") {\n const joined: UserMessage = { role: \"user\", content: [...last.content, ...message.content] };\n merged[merged.length - 1] = joined;\n } else if (message.role === \"assistant\" && last?.role === \"assistant\") {\n const { joined, dropped } = joinAssistant(last, message);\n merged[merged.length - 1] = joined;\n if (dropped) droppedThrough = merged.length - 1;\n } else {\n merged.push(message);\n }\n }\n return { merged, droppedThrough };\n}\n\n/**\n * Appends a later assistant message to an earlier one. The later reasoning is dropped when the earlier message has\n * text or tool calls, since it would otherwise follow them. Kept reasoning was judged against its own message's\n * model, so the merged message keeps the earlier model when the earlier message carries reasoning.\n */\nfunction joinAssistant(\n earlier: AssistantMessage,\n later: AssistantMessage,\n): { joined: AssistantMessage; dropped: boolean } {\n const hasBody = earlier.content.some((block) => block.type !== \"reasoning\");\n const appended = hasBody ? later.content.filter((block) => block.type !== \"reasoning\") : later.content;\n const model = earlier.content.some((block) => block.type === \"reasoning\") ? earlier.model : later.model;\n const joined: AssistantMessage = { ...later, model, content: [...earlier.content, ...appended] };\n return { joined, dropped: appended.length < later.content.length };\n}\n\nfunction withoutReasoningThrough(messages: readonly Message[], through: number): Message[] {\n return messages.map((message, index) => {\n if (index > through || message.role !== \"assistant\") return message;\n return { ...message, content: message.content.filter((block) => block.type !== \"reasoning\") };\n });\n}\n\nfunction startWithUser(messages: Message[], inputHadUser: boolean): Message[] {\n if (!inputHadUser || messages.length === 0 || messages[0]?.role === \"user\") return messages;\n return [{ role: \"user\", content: [{ type: \"text\", text: CONTINUED_TEXT }] }, ...messages];\n}\n\n/**\n * Returns a function that maps each tool-call id, in transcript order, to a valid id no earlier call uses. A valid,\n * unused id is kept, so a second pass changes nothing.\n */\nfunction idAllocator(): (original: string) => string {\n const taken = new Set<string>();\n return (original) => {\n const base = isCanonicalName(original) ? original : sanitizeId(original);\n let id = base;\n for (let n = 2; taken.has(id); n += 1) {\n const suffix = `_${n}`;\n id = base.slice(0, TOOL_CALL_ID_MAX_LENGTH - suffix.length) + suffix;\n }\n taken.add(id);\n return id;\n };\n}\n\nfunction sanitizeId(id: string): string {\n const cleaned = id.replace(TOOL_CALL_ID_INVALID_CHARS, \"_\").slice(0, TOOL_CALL_ID_MAX_LENGTH);\n return cleaned === \"\" ? \"call\" : cleaned;\n}\n"]}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider-neutral transcript the gateway, the adapters, the test model and the loop share
|
|
3
|
+
* (SDK plan §3.2; SDK decisions 2 and 3; D3, D4).
|
|
4
|
+
*/
|
|
5
|
+
/** A provider-issued token that is valid only for the model that produced it, such as a reasoning signature. */
|
|
6
|
+
export interface OpaqueToken {
|
|
7
|
+
api: string;
|
|
8
|
+
provider: string;
|
|
9
|
+
model: string;
|
|
10
|
+
value: string;
|
|
11
|
+
}
|
|
12
|
+
/** One block of message content. */
|
|
13
|
+
export type ContentBlock = {
|
|
14
|
+
type: "text";
|
|
15
|
+
text: string;
|
|
16
|
+
}
|
|
17
|
+
/** Valid only for the model that made it; `transformMessages()` drops or converts it for other models. */
|
|
18
|
+
| {
|
|
19
|
+
type: "reasoning";
|
|
20
|
+
text: string;
|
|
21
|
+
signature?: OpaqueToken;
|
|
22
|
+
} | {
|
|
23
|
+
type: "image";
|
|
24
|
+
mediaType: string;
|
|
25
|
+
data: string;
|
|
26
|
+
} | {
|
|
27
|
+
type: "tool_call";
|
|
28
|
+
callId: string;
|
|
29
|
+
name: string;
|
|
30
|
+
input: unknown;
|
|
31
|
+
};
|
|
32
|
+
/** What a tool result may carry. */
|
|
33
|
+
export type ModelContent = Extract<ContentBlock, {
|
|
34
|
+
type: "text" | "image";
|
|
35
|
+
}>;
|
|
36
|
+
/** Identifies one model behind one wire protocol and one vendor. */
|
|
37
|
+
export interface ModelRef {
|
|
38
|
+
/** Wire protocol, for example `"anthropic-messages"`. */
|
|
39
|
+
api: string;
|
|
40
|
+
/** Vendor and price-catalog entry. */
|
|
41
|
+
provider: string;
|
|
42
|
+
id: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Token counts for one model response. There is deliberately no field named `input`: providers disagree on
|
|
46
|
+
* whether "input" includes cached tokens, so the uncached part says so in its name and `totalInput()` sums the parts.
|
|
47
|
+
*/
|
|
48
|
+
export interface Usage {
|
|
49
|
+
uncachedInput: number;
|
|
50
|
+
cacheRead: number;
|
|
51
|
+
/**
|
|
52
|
+
* Cache writes at the short and the long lifetime. The keys name Anthropic's 5-minute and 1-hour writes; the
|
|
53
|
+
* OpenAI-compatible adapter counts its 30-minute writes under `"5m"`.
|
|
54
|
+
*/
|
|
55
|
+
cacheWrite: {
|
|
56
|
+
"5m": number;
|
|
57
|
+
"1h": number;
|
|
58
|
+
};
|
|
59
|
+
output: number;
|
|
60
|
+
/** The part of `output` spent on reasoning. */
|
|
61
|
+
reasoning: number;
|
|
62
|
+
/** The provider's usage object, unchanged. */
|
|
63
|
+
raw: unknown;
|
|
64
|
+
}
|
|
65
|
+
/** The price of one response. `total` is `null` when the price is unknown, never a guessed zero. */
|
|
66
|
+
export interface Cost {
|
|
67
|
+
total: number | null;
|
|
68
|
+
basis: "provider" | "catalog" | "unknown";
|
|
69
|
+
currency: "USD";
|
|
70
|
+
catalogAsOf?: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A failure an adapter can name in provider-neutral terms. `"thinking_prefix_mismatch"`: the provider rejected a
|
|
74
|
+
* reasoning block because the transcript before it changed after the block was written.
|
|
75
|
+
*/
|
|
76
|
+
export type ModelErrorCode = "thinking_prefix_mismatch";
|
|
77
|
+
export interface AssistantMessage {
|
|
78
|
+
role: "assistant";
|
|
79
|
+
content: ContentBlock[];
|
|
80
|
+
model: ModelRef;
|
|
81
|
+
stopReason: "stop" | "length" | "tool_calls" | "error" | "aborted";
|
|
82
|
+
error?: {
|
|
83
|
+
kind: "retryable" | "overflow" | "quota" | "fatal";
|
|
84
|
+
message: string;
|
|
85
|
+
status?: number;
|
|
86
|
+
/** A provider-neutral name for a failure the caller may want to handle on its own, when the adapter knows one. */
|
|
87
|
+
code?: ModelErrorCode;
|
|
88
|
+
};
|
|
89
|
+
/** The tokens of every attempt the call made, failed attempts included, because the provider bills them all. */
|
|
90
|
+
usage: Usage;
|
|
91
|
+
/**
|
|
92
|
+
* The usage of the attempt that produced this message alone. `createModel()` sets it when a call was retried, so
|
|
93
|
+
* `usage` sums several requests; it is absent when `usage` is one request's.
|
|
94
|
+
*/
|
|
95
|
+
lastAttemptUsage?: Usage;
|
|
96
|
+
cost: Cost;
|
|
97
|
+
}
|
|
98
|
+
export type Message = {
|
|
99
|
+
role: "user";
|
|
100
|
+
content: ContentBlock[];
|
|
101
|
+
} | AssistantMessage | {
|
|
102
|
+
role: "tool";
|
|
103
|
+
callId: string;
|
|
104
|
+
content: ModelContent[];
|
|
105
|
+
isError: boolean;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* A tool as one model call sends it: a name, a description and a JSON Schema for the input. The SDK's
|
|
109
|
+
* `defineTool()` lowers its Standard Schema or JSON Schema input to this shape.
|
|
110
|
+
*/
|
|
111
|
+
export interface WireTool {
|
|
112
|
+
name: string;
|
|
113
|
+
description: string;
|
|
114
|
+
/** A JSON Schema object describing the tool's input. */
|
|
115
|
+
inputSchema: Record<string, unknown>;
|
|
116
|
+
}
|
|
117
|
+
/** What one model call sends. */
|
|
118
|
+
export interface ModelContext {
|
|
119
|
+
system: string;
|
|
120
|
+
messages: Message[];
|
|
121
|
+
tools: WireTool[];
|
|
122
|
+
}
|
|
123
|
+
/** The context window and output limit that context trimming and the budget need; filled from the price catalog. */
|
|
124
|
+
export interface ModelCaps {
|
|
125
|
+
/** The most input tokens one request can send, which is below the full window when the provider caps input. */
|
|
126
|
+
contextWindow: number;
|
|
127
|
+
maxOutputTokens: number;
|
|
128
|
+
images: boolean;
|
|
129
|
+
reasoning: boolean;
|
|
130
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * The provider-neutral transcript the gateway, the adapters, the test model and the loop share\n * (SDK plan §3.2; SDK decisions 2 and 3; D3, D4).\n */\n\n/** A provider-issued token that is valid only for the model that produced it, such as a reasoning signature. */\nexport interface OpaqueToken {\n api: string;\n provider: string;\n model: string;\n value: string;\n}\n\n/** One block of message content. */\nexport type ContentBlock =\n | { type: \"text\"; text: string }\n /** Valid only for the model that made it; `transformMessages()` drops or converts it for other models. */\n | { type: \"reasoning\"; text: string; signature?: OpaqueToken }\n | { type: \"image\"; mediaType: string; data: string }\n | { type: \"tool_call\"; callId: string; name: string; input: unknown };\n\n/** What a tool result may carry. */\nexport type ModelContent = Extract<ContentBlock, { type: \"text\" | \"image\" }>;\n\n/** Identifies one model behind one wire protocol and one vendor. */\nexport interface ModelRef {\n /** Wire protocol, for example `\"anthropic-messages\"`. */\n api: string;\n /** Vendor and price-catalog entry. */\n provider: string;\n id: string;\n}\n\n/**\n * Token counts for one model response. There is deliberately no field named `input`: providers disagree on\n * whether \"input\" includes cached tokens, so the uncached part says so in its name and `totalInput()` sums the parts.\n */\nexport interface Usage {\n uncachedInput: number;\n cacheRead: number;\n /**\n * Cache writes at the short and the long lifetime. The keys name Anthropic's 5-minute and 1-hour writes; the\n * OpenAI-compatible adapter counts its 30-minute writes under `\"5m\"`.\n */\n cacheWrite: { \"5m\": number; \"1h\": number };\n output: number;\n /** The part of `output` spent on reasoning. */\n reasoning: number;\n /** The provider's usage object, unchanged. */\n raw: unknown;\n}\n\n/** The price of one response. `total` is `null` when the price is unknown, never a guessed zero. */\nexport interface Cost {\n total: number | null;\n basis: \"provider\" | \"catalog\" | \"unknown\";\n currency: \"USD\";\n catalogAsOf?: string;\n}\n\n/**\n * A failure an adapter can name in provider-neutral terms. `\"thinking_prefix_mismatch\"`: the provider rejected a\n * reasoning block because the transcript before it changed after the block was written.\n */\nexport type ModelErrorCode = \"thinking_prefix_mismatch\";\n\nexport interface AssistantMessage {\n role: \"assistant\";\n content: ContentBlock[];\n model: ModelRef;\n stopReason: \"stop\" | \"length\" | \"tool_calls\" | \"error\" | \"aborted\";\n error?: {\n kind: \"retryable\" | \"overflow\" | \"quota\" | \"fatal\";\n message: string;\n status?: number;\n /** A provider-neutral name for a failure the caller may want to handle on its own, when the adapter knows one. */\n code?: ModelErrorCode;\n };\n /** The tokens of every attempt the call made, failed attempts included, because the provider bills them all. */\n usage: Usage;\n /**\n * The usage of the attempt that produced this message alone. `createModel()` sets it when a call was retried, so\n * `usage` sums several requests; it is absent when `usage` is one request's.\n */\n lastAttemptUsage?: Usage;\n cost: Cost;\n}\n\nexport type Message =\n | { role: \"user\"; content: ContentBlock[] }\n | AssistantMessage\n | { role: \"tool\"; callId: string; content: ModelContent[]; isError: boolean };\n\n/**\n * A tool as one model call sends it: a name, a description and a JSON Schema for the input. The SDK's\n * `defineTool()` lowers its Standard Schema or JSON Schema input to this shape.\n */\nexport interface WireTool {\n name: string;\n description: string;\n /** A JSON Schema object describing the tool's input. */\n inputSchema: Record<string, unknown>;\n}\n\n/** What one model call sends. */\nexport interface ModelContext {\n system: string;\n messages: Message[];\n tools: WireTool[];\n}\n\n/** The context window and output limit that context trimming and the budget need; filled from the price catalog. */\nexport interface ModelCaps {\n /** The most input tokens one request can send, which is below the full window when the provider caps input. */\n contextWindow: number;\n maxOutputTokens: number;\n images: boolean;\n reasoning: boolean;\n}\n"]}
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Usage helpers (D3). */
|
|
2
|
+
import type { Usage } from "./types.js";
|
|
3
|
+
/** All input tokens: uncached, cache reads and both cache-write lifetimes. */
|
|
4
|
+
export declare function totalInput(u: Usage): number;
|
|
5
|
+
/** Adds two usage records; the result keeps the second record's `raw`. */
|
|
6
|
+
export declare function addUsage(a: Usage, b: Usage): Usage;
|
|
7
|
+
/** A usage record with every count at zero. */
|
|
8
|
+
export declare function emptyUsage(raw?: unknown): Usage;
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** All input tokens: uncached, cache reads and both cache-write lifetimes. */
|
|
2
|
+
export function totalInput(u) {
|
|
3
|
+
return u.uncachedInput + u.cacheRead + u.cacheWrite["5m"] + u.cacheWrite["1h"];
|
|
4
|
+
}
|
|
5
|
+
/** Adds two usage records; the result keeps the second record's `raw`. */
|
|
6
|
+
export function addUsage(a, b) {
|
|
7
|
+
return {
|
|
8
|
+
uncachedInput: a.uncachedInput + b.uncachedInput,
|
|
9
|
+
cacheRead: a.cacheRead + b.cacheRead,
|
|
10
|
+
cacheWrite: { "5m": a.cacheWrite["5m"] + b.cacheWrite["5m"], "1h": a.cacheWrite["1h"] + b.cacheWrite["1h"] },
|
|
11
|
+
output: a.output + b.output,
|
|
12
|
+
reasoning: a.reasoning + b.reasoning,
|
|
13
|
+
raw: b.raw,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** A usage record with every count at zero. */
|
|
17
|
+
export function emptyUsage(raw = null) {
|
|
18
|
+
return { uncachedInput: 0, cacheRead: 0, cacheWrite: { "5m": 0, "1h": 0 }, output: 0, reasoning: 0, raw };
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=usage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AAGA,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,CAAQ;IACjC,OAAO,CAAC,CAAC,aAAa,GAAG,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AACjF,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,QAAQ,CAAC,CAAQ,EAAE,CAAQ;IACzC,OAAO;QACL,aAAa,EAAE,CAAC,CAAC,aAAa,GAAG,CAAC,CAAC,aAAa;QAChD,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS;QACpC,UAAU,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC5G,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM;QAC3B,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS;QACpC,GAAG,EAAE,CAAC,CAAC,GAAG;KACX,CAAC;AACJ,CAAC;AAED,+CAA+C;AAC/C,MAAM,UAAU,UAAU,CAAC,GAAG,GAAY,IAAI;IAC5C,OAAO,EAAE,aAAa,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC;AAC5G,CAAC","sourcesContent":["/** Usage helpers (D3). */\nimport type { Usage } from \"./types.js\";\n\n/** All input tokens: uncached, cache reads and both cache-write lifetimes. */\nexport function totalInput(u: Usage): number {\n return u.uncachedInput + u.cacheRead + u.cacheWrite[\"5m\"] + u.cacheWrite[\"1h\"];\n}\n\n/** Adds two usage records; the result keeps the second record's `raw`. */\nexport function addUsage(a: Usage, b: Usage): Usage {\n return {\n uncachedInput: a.uncachedInput + b.uncachedInput,\n cacheRead: a.cacheRead + b.cacheRead,\n cacheWrite: { \"5m\": a.cacheWrite[\"5m\"] + b.cacheWrite[\"5m\"], \"1h\": a.cacheWrite[\"1h\"] + b.cacheWrite[\"1h\"] },\n output: a.output + b.output,\n reasoning: a.reasoning + b.reasoning,\n raw: b.raw,\n };\n}\n\n/** A usage record with every count at zero. */\nexport function emptyUsage(raw: unknown = null): Usage {\n return { uncachedInput: 0, cacheRead: 0, cacheWrite: { \"5m\": 0, \"1h\": 0 }, output: 0, reasoning: 0, raw };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
{
|
|
2
|
-
"
|
|
3
|
-
"
|
|
1
|
+
{
|
|
2
|
+
"name": "@buildanagent/gateway",
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Model gateway for the buildanagent SDK: provider adapters, streaming, retries and cost accounting.",
|
|
5
|
+
"license": "Apache-2.0 OR MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/laudebugs/buildanagent.git",
|
|
9
|
+
"directory": "packages/gateway"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/laudebugs/buildanagent/tree/main/packages/gateway#readme",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"sideEffects": [
|
|
14
|
+
"./src/testing/setup.ts",
|
|
15
|
+
"./dist/testing/setup.js"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"LICENSE",
|
|
23
|
+
"LICENSE-APACHE",
|
|
24
|
+
"LICENSE-MIT"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./anthropic": {
|
|
32
|
+
"types": "./dist/adapters/anthropic/index.d.ts",
|
|
33
|
+
"default": "./dist/adapters/anthropic/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./openai-chat": {
|
|
36
|
+
"types": "./dist/adapters/openai-chat/index.d.ts",
|
|
37
|
+
"default": "./dist/adapters/openai-chat/index.js"
|
|
38
|
+
},
|
|
39
|
+
"./testing": {
|
|
40
|
+
"types": "./dist/testing/index.d.ts",
|
|
41
|
+
"default": "./dist/testing/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./testing/setup": {
|
|
44
|
+
"types": "./dist/testing/setup.d.ts",
|
|
45
|
+
"default": "./dist/testing/setup.js"
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
51
|
+
"test": "vitest run"
|
|
52
|
+
}
|
|
53
|
+
}
|