@eserstack/ai 0.0.0-bootstrap.0 → 5.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/LICENSE +13 -0
- package/README.md +498 -0
- package/dist/adapters/ajan-bridge.d.ts +69 -0
- package/dist/adapters/ajan-bridge.js +661 -0
- package/dist/adapters/anthropic.d.ts +25 -0
- package/dist/adapters/anthropic.js +567 -0
- package/dist/adapters/claude-code.d.ts +28 -0
- package/dist/adapters/claude-code.js +462 -0
- package/dist/adapters/cli-shared.d.ts +36 -0
- package/dist/adapters/cli-shared.js +207 -0
- package/dist/adapters/gemini.d.ts +19 -0
- package/dist/adapters/gemini.js +91 -0
- package/dist/adapters/google-shared.d.ts +58 -0
- package/dist/adapters/google-shared.js +424 -0
- package/dist/adapters/kiro.d.ts +19 -0
- package/dist/adapters/kiro.js +195 -0
- package/dist/adapters/mod.d.ts +61 -0
- package/dist/adapters/mod.js +129 -0
- package/dist/adapters/ollama.d.ts +20 -0
- package/dist/adapters/ollama.js +226 -0
- package/dist/adapters/openai.d.ts +25 -0
- package/dist/adapters/openai.js +553 -0
- package/dist/adapters/opencode.d.ts +19 -0
- package/dist/adapters/opencode.js +158 -0
- package/dist/adapters/vertexai.d.ts +19 -0
- package/dist/adapters/vertexai.js +96 -0
- package/dist/batch.d.ts +35 -0
- package/dist/batch.js +2 -0
- package/dist/commands/ask.d.ts +30 -0
- package/dist/commands/ask.js +404 -0
- package/dist/commands/list.d.ts +2 -0
- package/dist/commands/list.js +35 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +16 -0
- package/dist/content.d.ts +14 -0
- package/dist/content.js +103 -0
- package/dist/detect.d.ts +9 -0
- package/dist/detect.js +125 -0
- package/dist/errors.d.ts +62 -0
- package/dist/errors.js +135 -0
- package/dist/generation.d.ts +126 -0
- package/dist/generation.js +96 -0
- package/dist/main.d.ts +22 -0
- package/dist/main.js +42 -0
- package/dist/mod.d.ts +16 -0
- package/dist/mod.js +11 -0
- package/dist/model.d.ts +27 -0
- package/dist/model.js +12 -0
- package/dist/module.d.ts +10 -0
- package/dist/module.js +21 -0
- package/dist/package.json +74 -0
- package/dist/registry.d.ts +22 -0
- package/dist/registry.js +97 -0
- package/dist/streams/layers.d.ts +4 -0
- package/dist/streams/layers.js +33 -0
- package/dist/streams/mod.d.ts +2 -0
- package/dist/streams/mod.js +5 -0
- package/dist/streams/sources.d.ts +6 -0
- package/dist/streams/sources.js +76 -0
- package/dist/types.d.ts +79 -0
- package/dist/types.js +2 -0
- package/package.json +63 -1
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as results from "@eserstack/primitives/results";
|
|
3
|
+
import * as generation from "../generation.js";
|
|
4
|
+
import * as content from "../content.js";
|
|
5
|
+
import * as errors from "../errors.js";
|
|
6
|
+
// =============================================================================
|
|
7
|
+
// Anthropic Model
|
|
8
|
+
// =============================================================================
|
|
9
|
+
export class AnthropicModel {
|
|
10
|
+
capabilities = [
|
|
11
|
+
"text_generation",
|
|
12
|
+
"streaming",
|
|
13
|
+
"tool_calling",
|
|
14
|
+
"vision",
|
|
15
|
+
"batch_processing",
|
|
16
|
+
"structured_output",
|
|
17
|
+
// A thinking budget turns on adaptive thinking, and the reply carries the
|
|
18
|
+
// thinking blocks.
|
|
19
|
+
"reasoning",
|
|
20
|
+
];
|
|
21
|
+
provider = "anthropic";
|
|
22
|
+
modelId;
|
|
23
|
+
// The SDK is loaded lazily by the factory; its client type is not in scope.
|
|
24
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
25
|
+
client;
|
|
26
|
+
config;
|
|
27
|
+
// Takes the lazily imported SDK client stored in the field above.
|
|
28
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
29
|
+
constructor(client, cfg) {
|
|
30
|
+
this.client = client;
|
|
31
|
+
this.config = cfg;
|
|
32
|
+
this.modelId = cfg.model;
|
|
33
|
+
}
|
|
34
|
+
async generateText(options, signal) {
|
|
35
|
+
try {
|
|
36
|
+
const params = buildParams(this.config, options);
|
|
37
|
+
const response = await this.client.messages.create(params, {
|
|
38
|
+
signal,
|
|
39
|
+
timeout: this.config.requestTimeoutMs,
|
|
40
|
+
});
|
|
41
|
+
return results.ok(mapResponse(response, this.modelId));
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
return results.fail(classifyError(err));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async *streamText(options, signal) {
|
|
48
|
+
try {
|
|
49
|
+
const params = buildParams(this.config, options);
|
|
50
|
+
const stream = await this.client.messages.create({ ...params, stream: true }, { signal, timeout: this.config.requestTimeoutMs });
|
|
51
|
+
let currentToolCallId = null;
|
|
52
|
+
let currentToolCallName = null;
|
|
53
|
+
let currentToolCallArgs = "";
|
|
54
|
+
// A thinking block's text and signature arrive in separate deltas; the
|
|
55
|
+
// block is yielded whole at its stop, since only the finished block can
|
|
56
|
+
// be replayed.
|
|
57
|
+
let currentThinking = null;
|
|
58
|
+
let inputTokens = 0;
|
|
59
|
+
let outputTokens = 0;
|
|
60
|
+
for await (const event of stream) {
|
|
61
|
+
if (event.type === "message_start") {
|
|
62
|
+
inputTokens = event.message?.usage?.input_tokens ?? 0;
|
|
63
|
+
}
|
|
64
|
+
else if (event.type === "content_block_start") {
|
|
65
|
+
if (event.content_block?.type === "tool_use") {
|
|
66
|
+
currentToolCallId = event.content_block.id ?? null;
|
|
67
|
+
currentToolCallName = event.content_block.name ?? null;
|
|
68
|
+
currentToolCallArgs = "";
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const started = toThinkingPart(event.content_block);
|
|
72
|
+
currentThinking =
|
|
73
|
+
started === null
|
|
74
|
+
? null
|
|
75
|
+
: {
|
|
76
|
+
text: started.text,
|
|
77
|
+
signature: started.signature ?? "",
|
|
78
|
+
redactedData: started.redactedData ?? null,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else if (event.type === "content_block_delta") {
|
|
83
|
+
if (event.delta?.type === "text_delta") {
|
|
84
|
+
yield { kind: "content_delta", textDelta: event.delta.text };
|
|
85
|
+
}
|
|
86
|
+
else if (event.delta?.type === "input_json_delta") {
|
|
87
|
+
currentToolCallArgs += event.delta.partial_json ?? "";
|
|
88
|
+
yield {
|
|
89
|
+
kind: "tool_call_delta",
|
|
90
|
+
textDelta: event.delta.partial_json,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
else if (event.delta?.type === "thinking_delta" &&
|
|
94
|
+
currentThinking !== null) {
|
|
95
|
+
currentThinking.text += event.delta.thinking ?? "";
|
|
96
|
+
}
|
|
97
|
+
else if (event.delta?.type === "signature_delta" &&
|
|
98
|
+
currentThinking !== null) {
|
|
99
|
+
currentThinking.signature += event.delta.signature ?? "";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
else if (event.type === "content_block_stop") {
|
|
103
|
+
if (currentThinking !== null) {
|
|
104
|
+
yield {
|
|
105
|
+
kind: "thinking",
|
|
106
|
+
thinking: finishThinking(currentThinking),
|
|
107
|
+
};
|
|
108
|
+
currentThinking = null;
|
|
109
|
+
}
|
|
110
|
+
if (currentToolCallId !== null && currentToolCallName !== null) {
|
|
111
|
+
let args = {};
|
|
112
|
+
if (currentToolCallArgs !== "") {
|
|
113
|
+
try {
|
|
114
|
+
args = JSON.parse(currentToolCallArgs);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// Keep empty args on parse failure
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
yield {
|
|
121
|
+
kind: "tool_call_delta",
|
|
122
|
+
toolCall: {
|
|
123
|
+
id: currentToolCallId,
|
|
124
|
+
name: currentToolCallName,
|
|
125
|
+
arguments: args,
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
currentToolCallId = null;
|
|
129
|
+
currentToolCallName = null;
|
|
130
|
+
currentToolCallArgs = "";
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
else if (event.type === "message_delta") {
|
|
134
|
+
outputTokens = event.usage?.output_tokens ?? outputTokens;
|
|
135
|
+
const stopReason = mapStopReason(event.delta?.stop_reason);
|
|
136
|
+
yield {
|
|
137
|
+
kind: "message_done",
|
|
138
|
+
stopReason,
|
|
139
|
+
usage: {
|
|
140
|
+
inputTokens,
|
|
141
|
+
outputTokens,
|
|
142
|
+
totalTokens: inputTokens + outputTokens,
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
yield { kind: "error", error: classifyError(err) };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async submitBatch(request, signal) {
|
|
153
|
+
try {
|
|
154
|
+
const requests = request.items.map((item) => ({
|
|
155
|
+
custom_id: item.customId,
|
|
156
|
+
params: buildParams(this.config, item.options),
|
|
157
|
+
}));
|
|
158
|
+
const result = await this.client.beta.messages.batches.create({ requests }, { signal });
|
|
159
|
+
return mapBatchJob(result);
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
throw classifyError(err);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async getBatchJob(jobId, signal) {
|
|
166
|
+
try {
|
|
167
|
+
const result = await this.client.beta.messages.batches.retrieve(jobId, {
|
|
168
|
+
signal,
|
|
169
|
+
});
|
|
170
|
+
return mapBatchJob(result);
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
throw classifyError(err);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async listBatchJobs(options, signal) {
|
|
177
|
+
try {
|
|
178
|
+
const result = await this.client.beta.messages.batches.list({
|
|
179
|
+
limit: options?.limit,
|
|
180
|
+
after_id: options?.after,
|
|
181
|
+
}, { signal });
|
|
182
|
+
const jobs = [];
|
|
183
|
+
for (const item of result.data ?? []) {
|
|
184
|
+
jobs.push(mapBatchJob(item));
|
|
185
|
+
}
|
|
186
|
+
return jobs;
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
throw classifyError(err);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async downloadBatchResults(job, signal) {
|
|
193
|
+
try {
|
|
194
|
+
const results = await this.client.beta.messages.batches.results(job.id, {
|
|
195
|
+
signal,
|
|
196
|
+
});
|
|
197
|
+
const batchResults = [];
|
|
198
|
+
for await (const item of results) {
|
|
199
|
+
if (item.result?.type === "succeeded") {
|
|
200
|
+
batchResults.push({
|
|
201
|
+
customId: item.custom_id,
|
|
202
|
+
result: mapResponse(item.result.message, this.modelId),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
batchResults.push({
|
|
207
|
+
customId: item.custom_id,
|
|
208
|
+
error: item.result?.error?.message ?? "Unknown error",
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return batchResults;
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
throw classifyError(err);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async cancelBatchJob(jobId, signal) {
|
|
219
|
+
try {
|
|
220
|
+
await this.client.beta.messages.batches.cancel(jobId, { signal });
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
throw classifyError(err);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async close() {
|
|
227
|
+
// Anthropic SDK doesn't require explicit cleanup
|
|
228
|
+
}
|
|
229
|
+
getRawClient() {
|
|
230
|
+
return this.client;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// =============================================================================
|
|
234
|
+
// Factory
|
|
235
|
+
// =============================================================================
|
|
236
|
+
export const anthropicFactory = {
|
|
237
|
+
provider: "anthropic",
|
|
238
|
+
createModel: async (cfg) => {
|
|
239
|
+
// Dynamic import to avoid loading SDK when not needed
|
|
240
|
+
const anthropicSdk = await import("@anthropic-ai/sdk");
|
|
241
|
+
const clientOptions = {};
|
|
242
|
+
if (cfg.apiKey !== undefined) {
|
|
243
|
+
clientOptions["apiKey"] = cfg.apiKey;
|
|
244
|
+
}
|
|
245
|
+
if (cfg.baseUrl !== undefined) {
|
|
246
|
+
clientOptions["baseURL"] = cfg.baseUrl;
|
|
247
|
+
}
|
|
248
|
+
const client = new anthropicSdk.Anthropic(clientOptions);
|
|
249
|
+
return new AnthropicModel(client, cfg);
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
// =============================================================================
|
|
253
|
+
// Internal Helpers
|
|
254
|
+
// =============================================================================
|
|
255
|
+
const LOW_EFFORT_MAX_BUDGET = 1_000;
|
|
256
|
+
const HIGH_EFFORT_MIN_BUDGET = 10_000;
|
|
257
|
+
const mapEffort = (budget) => {
|
|
258
|
+
if (budget <= LOW_EFFORT_MAX_BUDGET)
|
|
259
|
+
return "low";
|
|
260
|
+
if (budget >= HIGH_EFFORT_MIN_BUDGET)
|
|
261
|
+
return "high";
|
|
262
|
+
return "medium";
|
|
263
|
+
};
|
|
264
|
+
const buildParams = (cfg, options) => {
|
|
265
|
+
// Keys follow the Anthropic Messages API request body.
|
|
266
|
+
const params = {
|
|
267
|
+
model: cfg.model,
|
|
268
|
+
max_tokens: options.maxTokens ?? cfg.maxTokens,
|
|
269
|
+
messages: mapMessages(options.messages),
|
|
270
|
+
};
|
|
271
|
+
if (options.system !== undefined) {
|
|
272
|
+
params["system"] = options.system;
|
|
273
|
+
}
|
|
274
|
+
// temperature and topP are not sent: API version 2026-10-21, which
|
|
275
|
+
// @anthropic-ai/sdk 1.x sends, rejects temperature, top_p and top_k on every
|
|
276
|
+
// model.
|
|
277
|
+
if (options.stopWords !== undefined) {
|
|
278
|
+
params["stop_sequences"] = options.stopWords;
|
|
279
|
+
}
|
|
280
|
+
if (options.tools !== undefined) {
|
|
281
|
+
params["tools"] = options.tools.map((tool) => ({
|
|
282
|
+
name: tool.name,
|
|
283
|
+
description: tool.description,
|
|
284
|
+
input_schema: tool.parameters ?? { type: "object", properties: {} },
|
|
285
|
+
}));
|
|
286
|
+
}
|
|
287
|
+
if (options.toolChoice !== undefined) {
|
|
288
|
+
// Anthropic names the forced choice "any"; "required" is rejected.
|
|
289
|
+
params["tool_choice"] = {
|
|
290
|
+
type: options.toolChoice === "required" ? "any" : options.toolChoice,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
if (options.thinkingBudget !== undefined) {
|
|
294
|
+
// A fixed thinking budget returns a 400 on Claude 4.7+ and the Claude 5
|
|
295
|
+
// models; the budget maps to an effort level instead.
|
|
296
|
+
params["thinking"] = { type: "adaptive" };
|
|
297
|
+
}
|
|
298
|
+
// An explicit effort wins over the level the budget maps to. With neither,
|
|
299
|
+
// nothing is sent and the model's default applies.
|
|
300
|
+
const effort = options.effort ??
|
|
301
|
+
(options.thinkingBudget === undefined
|
|
302
|
+
? undefined
|
|
303
|
+
: mapEffort(options.thinkingBudget));
|
|
304
|
+
const format = mapResponseFormat(options.responseFormat);
|
|
305
|
+
// Effort and format share one output_config object.
|
|
306
|
+
const outputConfig = {};
|
|
307
|
+
if (effort !== undefined) {
|
|
308
|
+
outputConfig["effort"] = effort;
|
|
309
|
+
}
|
|
310
|
+
if (format !== null) {
|
|
311
|
+
outputConfig["format"] = format;
|
|
312
|
+
}
|
|
313
|
+
if (Object.keys(outputConfig).length > 0) {
|
|
314
|
+
params["output_config"] = outputConfig;
|
|
315
|
+
}
|
|
316
|
+
return params;
|
|
317
|
+
};
|
|
318
|
+
/**
|
|
319
|
+
* Maps a json_schema response format to `output_config.format`. Claude has no
|
|
320
|
+
* JSON mode without a schema, so `json_object` and `text` map to null and the
|
|
321
|
+
* prompt alone decides the shape of the reply. The format's `name` has no field
|
|
322
|
+
* in the API and is not sent.
|
|
323
|
+
*
|
|
324
|
+
* @throws {errors.BadRequestError} for `json_schema` without an object
|
|
325
|
+
* `jsonSchema`.
|
|
326
|
+
*/
|
|
327
|
+
const mapResponseFormat = (responseFormat) => {
|
|
328
|
+
if (responseFormat?.type !== "json_schema") {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
type: "json_schema",
|
|
333
|
+
schema: generation.requireJsonSchema(responseFormat, "anthropic"),
|
|
334
|
+
};
|
|
335
|
+
};
|
|
336
|
+
const mapMessages = (messages) => {
|
|
337
|
+
const result = [];
|
|
338
|
+
for (const message of messages) {
|
|
339
|
+
if (message.role === "system") {
|
|
340
|
+
continue; // System messages handled separately in params
|
|
341
|
+
}
|
|
342
|
+
const contentParts = [];
|
|
343
|
+
for (const block of message.content) {
|
|
344
|
+
const part = mapContentBlock(block);
|
|
345
|
+
if (part !== null) {
|
|
346
|
+
contentParts.push(part);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
result.push({
|
|
350
|
+
role: message.role === "tool" ? "user" : message.role,
|
|
351
|
+
content: contentParts,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return result;
|
|
355
|
+
};
|
|
356
|
+
/**
|
|
357
|
+
* Maps one block to the Messages API. Returns null for a block the request
|
|
358
|
+
* must leave out: a thinking block with neither a signature nor redacted data,
|
|
359
|
+
* such as one another provider produced, cannot pass the API's check.
|
|
360
|
+
*/
|
|
361
|
+
const mapContentBlock = (block) => {
|
|
362
|
+
switch (block.kind) {
|
|
363
|
+
case "text": {
|
|
364
|
+
return { type: "text", text: block.text };
|
|
365
|
+
}
|
|
366
|
+
case "image": {
|
|
367
|
+
if (block.image.data !== undefined) {
|
|
368
|
+
return {
|
|
369
|
+
type: "image",
|
|
370
|
+
source: {
|
|
371
|
+
type: "base64",
|
|
372
|
+
media_type: block.image.mimeType ?? "image/png",
|
|
373
|
+
data: encodeBase64(block.image.data),
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
if (block.image.url !== undefined) {
|
|
378
|
+
if (content.isDataUrl(block.image.url)) {
|
|
379
|
+
const decoded = content.decodeDataUrl(block.image.url);
|
|
380
|
+
if (decoded !== null) {
|
|
381
|
+
return {
|
|
382
|
+
type: "image",
|
|
383
|
+
source: {
|
|
384
|
+
type: "base64",
|
|
385
|
+
media_type: decoded.mimeType,
|
|
386
|
+
data: encodeBase64(decoded.data),
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
type: "image",
|
|
393
|
+
source: { type: "url", url: block.image.url },
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
return { type: "text", text: "[unsupported image]" };
|
|
397
|
+
}
|
|
398
|
+
case "tool_call": {
|
|
399
|
+
return {
|
|
400
|
+
type: "tool_use",
|
|
401
|
+
id: block.toolCall.id,
|
|
402
|
+
name: block.toolCall.name,
|
|
403
|
+
input: block.toolCall.arguments,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
case "tool_result": {
|
|
407
|
+
return {
|
|
408
|
+
type: "tool_result",
|
|
409
|
+
tool_use_id: block.toolResult.toolCallId,
|
|
410
|
+
content: block.toolResult.content,
|
|
411
|
+
is_error: block.toolResult.isError,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
case "thinking": {
|
|
415
|
+
// Replayed exactly as the API returned it; the API checks the signature
|
|
416
|
+
// or the redacted data, so an empty one counts as missing (as in aifx).
|
|
417
|
+
const { redactedData, signature } = block.thinking;
|
|
418
|
+
if (redactedData !== undefined && redactedData !== "") {
|
|
419
|
+
return { type: "redacted_thinking", data: redactedData };
|
|
420
|
+
}
|
|
421
|
+
if (signature === undefined || signature === "") {
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
return {
|
|
425
|
+
type: "thinking",
|
|
426
|
+
thinking: block.thinking.text,
|
|
427
|
+
signature,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
default: {
|
|
431
|
+
return {
|
|
432
|
+
type: "text",
|
|
433
|
+
text: `[unsupported content: ${block.kind}]`,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
const mapResponse = (
|
|
439
|
+
// The response is untyped vendor JSON; only the mapped fields are read.
|
|
440
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
441
|
+
response, modelId) => {
|
|
442
|
+
const contentBlocks = [];
|
|
443
|
+
for (const block of response.content ?? []) {
|
|
444
|
+
const thinking = toThinkingPart(block);
|
|
445
|
+
if (block.type === "text") {
|
|
446
|
+
contentBlocks.push({ kind: "text", text: block.text });
|
|
447
|
+
}
|
|
448
|
+
else if (thinking !== null) {
|
|
449
|
+
// Kept as its own kind, never as text, and kept when the text is empty
|
|
450
|
+
// (Claude 5 omits it by default): a tool-use loop must send the
|
|
451
|
+
// signature back.
|
|
452
|
+
contentBlocks.push({ kind: "thinking", thinking });
|
|
453
|
+
}
|
|
454
|
+
else if (block.type === "tool_use") {
|
|
455
|
+
contentBlocks.push({
|
|
456
|
+
kind: "tool_call",
|
|
457
|
+
toolCall: {
|
|
458
|
+
id: block.id,
|
|
459
|
+
name: block.name,
|
|
460
|
+
arguments: block.input ?? {},
|
|
461
|
+
},
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return {
|
|
466
|
+
content: contentBlocks,
|
|
467
|
+
stopReason: mapStopReason(response.stop_reason),
|
|
468
|
+
usage: {
|
|
469
|
+
inputTokens: response.usage?.input_tokens ?? 0,
|
|
470
|
+
outputTokens: response.usage?.output_tokens ?? 0,
|
|
471
|
+
totalTokens: (response.usage?.input_tokens ?? 0) +
|
|
472
|
+
(response.usage?.output_tokens ?? 0),
|
|
473
|
+
},
|
|
474
|
+
modelId,
|
|
475
|
+
rawResponse: response,
|
|
476
|
+
};
|
|
477
|
+
};
|
|
478
|
+
/**
|
|
479
|
+
* Maps Anthropic's stop_reason. `model_context_window_exceeded` is a truncation
|
|
480
|
+
* like `max_tokens`: the reply was cut off because the context window filled.
|
|
481
|
+
*/
|
|
482
|
+
const mapStopReason = (reason) => {
|
|
483
|
+
if (reason === "end_turn") {
|
|
484
|
+
return "end_turn";
|
|
485
|
+
}
|
|
486
|
+
if (reason === "max_tokens" || reason === "model_context_window_exceeded") {
|
|
487
|
+
return "max_tokens";
|
|
488
|
+
}
|
|
489
|
+
if (reason === "tool_use") {
|
|
490
|
+
return "tool_use";
|
|
491
|
+
}
|
|
492
|
+
if (reason === "stop_sequence") {
|
|
493
|
+
return "stop";
|
|
494
|
+
}
|
|
495
|
+
if (reason === "refusal") {
|
|
496
|
+
return "refusal";
|
|
497
|
+
}
|
|
498
|
+
return "end_turn";
|
|
499
|
+
};
|
|
500
|
+
const finishThinking = (draft) => {
|
|
501
|
+
if (draft.redactedData !== null) {
|
|
502
|
+
return { text: "", redactedData: draft.redactedData };
|
|
503
|
+
}
|
|
504
|
+
return draft.signature === ""
|
|
505
|
+
? { text: draft.text }
|
|
506
|
+
: { text: draft.text, signature: draft.signature };
|
|
507
|
+
};
|
|
508
|
+
/**
|
|
509
|
+
* Reads an Anthropic thinking or redacted_thinking block as a thinking part,
|
|
510
|
+
* or returns null for any other block.
|
|
511
|
+
*/
|
|
512
|
+
const toThinkingPart = (
|
|
513
|
+
// A content block is untyped vendor JSON; only the mapped fields are read.
|
|
514
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
515
|
+
block) => {
|
|
516
|
+
if (block?.type === "thinking") {
|
|
517
|
+
return block.signature === undefined
|
|
518
|
+
? { text: block.thinking ?? "" }
|
|
519
|
+
: { text: block.thinking ?? "", signature: block.signature };
|
|
520
|
+
}
|
|
521
|
+
if (block?.type === "redacted_thinking") {
|
|
522
|
+
return { text: "", redactedData: block.data ?? "" };
|
|
523
|
+
}
|
|
524
|
+
return null;
|
|
525
|
+
};
|
|
526
|
+
// The batch job is untyped vendor JSON; only the mapped fields are read.
|
|
527
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
528
|
+
const mapBatchJob = (result) => {
|
|
529
|
+
return {
|
|
530
|
+
id: result.id,
|
|
531
|
+
status: mapBatchStatus(result.processing_status),
|
|
532
|
+
createdAt: new Date(result.created_at),
|
|
533
|
+
completedAt: result.ended_at !== undefined ? new Date(result.ended_at) : undefined,
|
|
534
|
+
totalCount: result.request_counts?.total ?? 0,
|
|
535
|
+
doneCount: result.request_counts?.succeeded ?? 0,
|
|
536
|
+
failedCount: result.request_counts?.errored ?? 0,
|
|
537
|
+
};
|
|
538
|
+
};
|
|
539
|
+
const mapBatchStatus = (status) => {
|
|
540
|
+
if (status === "in_progress") {
|
|
541
|
+
return "processing";
|
|
542
|
+
}
|
|
543
|
+
if (status === "ended") {
|
|
544
|
+
return "completed";
|
|
545
|
+
}
|
|
546
|
+
if (status === "canceling" || status === "canceled") {
|
|
547
|
+
return "cancelled";
|
|
548
|
+
}
|
|
549
|
+
return "pending";
|
|
550
|
+
};
|
|
551
|
+
const classifyError = (err) => {
|
|
552
|
+
if (err instanceof errors.AiError) {
|
|
553
|
+
return err;
|
|
554
|
+
}
|
|
555
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
556
|
+
// SDK errors carry the HTTP status on a field their type does not declare.
|
|
557
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
558
|
+
const statusCode = err?.status ?? err?.statusCode ?? 500;
|
|
559
|
+
return errors.classifyAndWrap("anthropic", statusCode, error);
|
|
560
|
+
};
|
|
561
|
+
const encodeBase64 = (data) => {
|
|
562
|
+
let binary = "";
|
|
563
|
+
for (let i = 0; i < data.length; i++) {
|
|
564
|
+
binary += String.fromCharCode(data[i]);
|
|
565
|
+
}
|
|
566
|
+
return btoa(binary);
|
|
567
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as results from "@eserstack/primitives/results";
|
|
2
|
+
import type * as types from "../types.ts";
|
|
3
|
+
import type * as config from "../config.ts";
|
|
4
|
+
import * as generation from "../generation.ts";
|
|
5
|
+
import type * as model from "../model.ts";
|
|
6
|
+
import * as errors from "../errors.ts";
|
|
7
|
+
export declare class ClaudeCodeModel implements model.LanguageModel {
|
|
8
|
+
#private;
|
|
9
|
+
readonly capabilities: readonly types.ProviderCapability[];
|
|
10
|
+
readonly provider = "claude-code";
|
|
11
|
+
readonly modelId: string;
|
|
12
|
+
private readonly binary;
|
|
13
|
+
private readonly config;
|
|
14
|
+
constructor(binary: string, cfg: config.ResolvedConfigTarget);
|
|
15
|
+
generateText(options: generation.GenerateTextOptions, signal?: AbortSignal): Promise<results.Result<generation.GenerateTextResult, errors.AiError>>;
|
|
16
|
+
streamText(options: generation.GenerateTextOptions, signal?: AbortSignal): AsyncIterable<generation.StreamEvent>;
|
|
17
|
+
close(): Promise<void>;
|
|
18
|
+
getRawClient(): unknown;
|
|
19
|
+
}
|
|
20
|
+
export declare const claudeCodeFactory: model.ProviderFactory;
|
|
21
|
+
/**
|
|
22
|
+
* Builds the claude CLI arguments for one request. Exported for tests.
|
|
23
|
+
*
|
|
24
|
+
* @throws {errors.BadRequestError} for a `json_schema` format without an
|
|
25
|
+
* object `jsonSchema`.
|
|
26
|
+
*/
|
|
27
|
+
export declare const buildArgs: (cfg: config.ResolvedConfigTarget, options: generation.GenerateTextOptions, outputFormat: "json" | "text" | "stream-json") => string[];
|
|
28
|
+
export declare const parseJsonResult: (rawOutput: string, modelId: string) => generation.GenerateTextResult;
|