@jxburros/ai-nugget 0.4.1 → 0.7.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/README.md +158 -382
- package/UPGRADING.md +182 -0
- package/dist/adapters/engines/anthropic.d.ts +7 -1
- package/dist/adapters/engines/anthropic.js +82 -37
- package/dist/adapters/engines/base.d.ts +29 -2
- package/dist/adapters/engines/base.js +52 -8
- package/dist/adapters/engines/google.d.ts +7 -1
- package/dist/adapters/engines/google.js +80 -29
- package/dist/adapters/engines/ollama.d.ts +2 -1
- package/dist/adapters/engines/ollama.js +57 -15
- package/dist/adapters/engines/openaiChat.d.ts +8 -1
- package/dist/adapters/engines/openaiChat.js +109 -29
- package/dist/adapters/profiles.d.ts +21 -1
- package/dist/adapters/profiles.js +12 -2
- package/dist/agent/loop.d.ts +45 -1
- package/dist/agent/loop.js +117 -12
- package/dist/cjs/adapters/engines/anthropic.js +326 -0
- package/dist/cjs/adapters/engines/base.js +147 -0
- package/dist/cjs/adapters/engines/google.js +291 -0
- package/dist/cjs/adapters/engines/ollama.js +205 -0
- package/dist/cjs/adapters/engines/openaiChat.js +312 -0
- package/dist/cjs/adapters/index.js +22 -0
- package/dist/cjs/adapters/profiles.js +125 -0
- package/dist/cjs/agent/index.js +18 -0
- package/dist/cjs/agent/loop.js +373 -0
- package/dist/cjs/agent/tools.js +51 -0
- package/dist/cjs/connect.js +27 -0
- package/dist/cjs/errors.js +110 -0
- package/dist/cjs/handler.js +586 -0
- package/dist/cjs/index.js +28 -0
- package/dist/cjs/json.js +121 -0
- package/dist/cjs/keys.js +81 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/policy.js +42 -0
- package/dist/cjs/reasoning.js +159 -0
- package/dist/cjs/redact.js +78 -0
- package/dist/cjs/tokens.js +22 -0
- package/dist/cjs/transport.js +172 -0
- package/dist/cjs/types.js +6 -0
- package/dist/cjs/util.js +126 -0
- package/dist/errors.js +25 -1
- package/dist/handler.d.ts +67 -1
- package/dist/handler.js +266 -61
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/reasoning.d.ts +45 -0
- package/dist/reasoning.js +154 -0
- package/dist/redact.d.ts +18 -0
- package/dist/redact.js +29 -1
- package/dist/transport.d.ts +3 -1
- package/dist/transport.js +21 -1
- package/dist/types.d.ts +112 -2
- package/dist/util.d.ts +22 -0
- package/dist/util.js +59 -0
- package/nugget/VERSION.txt +2 -2
- package/nugget/dist/adapters/engines/anthropic.d.ts +14 -0
- package/nugget/dist/adapters/engines/anthropic.d.ts.map +1 -0
- package/nugget/dist/adapters/engines/anthropic.js +323 -0
- package/nugget/dist/adapters/engines/anthropic.js.map +1 -0
- package/nugget/dist/adapters/engines/base.d.ts +50 -0
- package/nugget/dist/adapters/engines/base.d.ts.map +1 -0
- package/nugget/dist/adapters/engines/base.js +137 -0
- package/nugget/dist/adapters/engines/base.js.map +1 -0
- package/nugget/dist/adapters/engines/google.d.ts +24 -0
- package/nugget/dist/adapters/engines/google.d.ts.map +1 -0
- package/nugget/dist/adapters/engines/google.js +288 -0
- package/nugget/dist/adapters/engines/google.js.map +1 -0
- package/nugget/dist/adapters/engines/ollama.d.ts +11 -0
- package/nugget/dist/adapters/engines/ollama.d.ts.map +1 -0
- package/nugget/dist/adapters/engines/ollama.js +202 -0
- package/nugget/dist/adapters/engines/ollama.js.map +1 -0
- package/nugget/dist/adapters/engines/openaiChat.d.ts +22 -0
- package/nugget/dist/adapters/engines/openaiChat.d.ts.map +1 -0
- package/nugget/dist/adapters/engines/openaiChat.js +308 -0
- package/nugget/dist/adapters/engines/openaiChat.js.map +1 -0
- package/nugget/dist/adapters/index.d.ts +5 -0
- package/nugget/dist/adapters/index.d.ts.map +1 -0
- package/nugget/dist/adapters/index.js +17 -0
- package/nugget/dist/adapters/index.js.map +1 -0
- package/nugget/dist/adapters/profiles.d.ts +62 -0
- package/nugget/dist/adapters/profiles.d.ts.map +1 -0
- package/nugget/dist/adapters/profiles.js +121 -0
- package/nugget/dist/adapters/profiles.js.map +1 -0
- package/nugget/dist/agent/index.d.ts +3 -0
- package/nugget/dist/agent/index.d.ts.map +1 -0
- package/nugget/dist/agent/index.js +3 -0
- package/nugget/dist/agent/index.js.map +1 -0
- package/nugget/dist/agent/loop.d.ts +114 -0
- package/nugget/dist/agent/loop.d.ts.map +1 -0
- package/nugget/dist/agent/loop.js +371 -0
- package/nugget/dist/agent/loop.js.map +1 -0
- package/nugget/dist/agent/tools.d.ts +29 -0
- package/nugget/dist/agent/tools.d.ts.map +1 -0
- package/nugget/dist/agent/tools.js +48 -0
- package/nugget/dist/agent/tools.js.map +1 -0
- package/nugget/dist/cjs/adapters/engines/anthropic.js +326 -0
- package/nugget/dist/cjs/adapters/engines/base.js +147 -0
- package/nugget/dist/cjs/adapters/engines/google.js +291 -0
- package/nugget/dist/cjs/adapters/engines/ollama.js +205 -0
- package/nugget/dist/cjs/adapters/engines/openaiChat.js +312 -0
- package/nugget/dist/cjs/adapters/index.js +22 -0
- package/nugget/dist/cjs/adapters/profiles.js +125 -0
- package/nugget/dist/cjs/agent/index.js +18 -0
- package/nugget/dist/cjs/agent/loop.js +373 -0
- package/nugget/dist/cjs/agent/tools.js +51 -0
- package/nugget/dist/cjs/connect.js +27 -0
- package/nugget/dist/cjs/errors.js +110 -0
- package/nugget/dist/cjs/handler.js +586 -0
- package/nugget/dist/cjs/index.js +28 -0
- package/nugget/dist/cjs/json.js +121 -0
- package/nugget/dist/cjs/keys.js +81 -0
- package/nugget/dist/cjs/package.json +3 -0
- package/nugget/dist/cjs/policy.js +42 -0
- package/nugget/dist/cjs/reasoning.js +159 -0
- package/nugget/dist/cjs/redact.js +78 -0
- package/nugget/dist/cjs/tokens.js +22 -0
- package/nugget/dist/cjs/transport.js +172 -0
- package/nugget/dist/cjs/types.js +6 -0
- package/nugget/dist/cjs/util.js +126 -0
- package/nugget/dist/connect.d.ts +31 -0
- package/nugget/dist/connect.d.ts.map +1 -0
- package/nugget/dist/connect.js +25 -0
- package/nugget/dist/connect.js.map +1 -0
- package/nugget/dist/errors.d.ts +22 -0
- package/nugget/dist/errors.d.ts.map +1 -0
- package/nugget/dist/errors.js +104 -0
- package/nugget/dist/errors.js.map +1 -0
- package/nugget/dist/handler.d.ts +114 -0
- package/nugget/dist/handler.d.ts.map +1 -0
- package/nugget/dist/handler.js +582 -0
- package/nugget/dist/handler.js.map +1 -0
- package/nugget/dist/index.d.ts +13 -0
- package/nugget/dist/index.d.ts.map +1 -0
- package/nugget/dist/index.js +13 -0
- package/nugget/dist/index.js.map +1 -0
- package/nugget/dist/json.d.ts +7 -0
- package/nugget/dist/json.d.ts.map +1 -0
- package/nugget/dist/json.js +114 -0
- package/nugget/dist/json.js.map +1 -0
- package/nugget/dist/keys.d.ts +7 -0
- package/nugget/dist/keys.d.ts.map +1 -0
- package/nugget/dist/keys.js +75 -0
- package/nugget/dist/keys.js.map +1 -0
- package/nugget/dist/policy.d.ts +6 -0
- package/nugget/dist/policy.d.ts.map +1 -0
- package/nugget/dist/policy.js +37 -0
- package/nugget/dist/policy.js.map +1 -0
- package/nugget/dist/reasoning.d.ts +45 -0
- package/nugget/dist/reasoning.d.ts.map +1 -0
- package/nugget/dist/reasoning.js +154 -0
- package/nugget/dist/reasoning.js.map +1 -0
- package/nugget/dist/redact.d.ts +26 -0
- package/nugget/dist/redact.d.ts.map +1 -0
- package/nugget/dist/redact.js +74 -0
- package/nugget/dist/redact.js.map +1 -0
- package/nugget/dist/tokens.d.ts +5 -0
- package/nugget/dist/tokens.d.ts.map +1 -0
- package/nugget/dist/tokens.js +18 -0
- package/nugget/dist/tokens.js.map +1 -0
- package/nugget/dist/transport.d.ts +30 -0
- package/nugget/dist/transport.d.ts.map +1 -0
- package/nugget/dist/transport.js +165 -0
- package/nugget/dist/transport.js.map +1 -0
- package/nugget/dist/types.d.ts +301 -0
- package/nugget/dist/types.d.ts.map +1 -0
- package/nugget/dist/types.js +4 -0
- package/nugget/dist/types.js.map +1 -0
- package/nugget/dist/util.d.ts +31 -0
- package/nugget/dist/util.d.ts.map +1 -0
- package/nugget/dist/util.js +114 -0
- package/nugget/dist/util.js.map +1 -0
- package/nugget/src/adapters/engines/anthropic.ts +78 -37
- package/nugget/src/adapters/engines/base.ts +50 -7
- package/nugget/src/adapters/engines/google.ts +79 -29
- package/nugget/src/adapters/engines/ollama.ts +56 -17
- package/nugget/src/adapters/engines/openaiChat.ts +104 -30
- package/nugget/src/adapters/profiles.ts +53 -3
- package/nugget/src/agent/loop.ts +156 -13
- package/nugget/src/errors.ts +25 -1
- package/nugget/src/handler.ts +308 -59
- package/nugget/src/index.ts +1 -0
- package/nugget/src/reasoning.ts +174 -0
- package/nugget/src/redact.ts +32 -1
- package/nugget/src/transport.ts +20 -1
- package/nugget/src/types.ts +113 -1
- package/nugget/src/util.ts +64 -0
- package/package.json +18 -5
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AnthropicAdapter = void 0;
|
|
4
|
+
const errors_js_1 = require("../../errors.js");
|
|
5
|
+
const tokens_js_1 = require("../../tokens.js");
|
|
6
|
+
const transport_js_1 = require("../../transport.js");
|
|
7
|
+
const util_js_1 = require("../../util.js");
|
|
8
|
+
const base_js_1 = require("./base.js");
|
|
9
|
+
const JSON_MODE_TOOL = 'json_output';
|
|
10
|
+
class AnthropicAdapter {
|
|
11
|
+
provider;
|
|
12
|
+
constructor(provider) {
|
|
13
|
+
this.provider = provider;
|
|
14
|
+
}
|
|
15
|
+
async chat(conn, req) {
|
|
16
|
+
let result;
|
|
17
|
+
for await (const event of this.stream(conn, req)) {
|
|
18
|
+
if (event.type === 'done')
|
|
19
|
+
result = event.result;
|
|
20
|
+
if (event.type === 'error')
|
|
21
|
+
throw event.error;
|
|
22
|
+
}
|
|
23
|
+
if (!result)
|
|
24
|
+
throw new errors_js_1.AIError('Anthropic stream ended without a result', { kind: 'invalid_response', provider: conn.provider });
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
async *stream(conn, req) {
|
|
28
|
+
const started = Date.now();
|
|
29
|
+
const jsonMode = req.responseFormat?.type === 'json' && !req.tools?.length;
|
|
30
|
+
let firstTokenMs = null;
|
|
31
|
+
let text = '';
|
|
32
|
+
let inputTokens;
|
|
33
|
+
let outputTokens;
|
|
34
|
+
let stopReason;
|
|
35
|
+
let sawTerminal = false;
|
|
36
|
+
const emittedTools = [];
|
|
37
|
+
// Partial tool_use blocks keyed by content-block index (input_json_delta accumulation).
|
|
38
|
+
const blocks = new Map();
|
|
39
|
+
const timeout = (0, base_js_1.streamTimeout)(conn, req.signal);
|
|
40
|
+
yield { type: 'start', callId: '', provider: conn.provider, model: req.model };
|
|
41
|
+
// Anthropic JSON mode is implemented as a forced `json_output` tool, which
|
|
42
|
+
// cannot coexist with the caller's own tools — same silent-downgrade shape
|
|
43
|
+
// as Gemini, so it gets the same signal rather than quietly dropping.
|
|
44
|
+
if (req.responseFormat?.type === 'json' && req.tools?.length) {
|
|
45
|
+
yield {
|
|
46
|
+
type: 'context',
|
|
47
|
+
kind: 'json_mode_downgraded',
|
|
48
|
+
data: { reason: 'Anthropic JSON mode uses a forced tool and cannot be combined with caller tools; the request was sent without JSON mode', provider: conn.provider },
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const res = await (0, transport_js_1.postResponse)(`${conn.baseUrl}/v1/messages`, body(req, jsonMode), conn.headers, timeout.signal, conn.provider);
|
|
53
|
+
const contentType = res.headers.get('content-type') ?? '';
|
|
54
|
+
if (!contentType.includes('text/event-stream')) {
|
|
55
|
+
const data = await res.json();
|
|
56
|
+
const parsed = parseResponse(data);
|
|
57
|
+
inputTokens = parsed.inputTokens;
|
|
58
|
+
outputTokens = parsed.outputTokens;
|
|
59
|
+
stopReason = parsed.stopReason;
|
|
60
|
+
sawTerminal = true;
|
|
61
|
+
if (jsonMode) {
|
|
62
|
+
text = jsonTextFrom(parsed.toolCalls, parsed.text);
|
|
63
|
+
if (text)
|
|
64
|
+
yield { type: 'delta', text };
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
text = parsed.text;
|
|
68
|
+
if (text)
|
|
69
|
+
yield { type: 'delta', text };
|
|
70
|
+
for (const call of parsed.toolCalls) {
|
|
71
|
+
emittedTools.push(call);
|
|
72
|
+
yield { type: 'tool_call', call };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
for await (const line of (0, transport_js_1.sseLines)(res)) {
|
|
78
|
+
timeout.bump();
|
|
79
|
+
const record = (0, util_js_1.asRecord)((0, base_js_1.safeParse)(line));
|
|
80
|
+
if (!record)
|
|
81
|
+
continue;
|
|
82
|
+
const type = (0, util_js_1.asString)(record.type);
|
|
83
|
+
if (type === 'message_start') {
|
|
84
|
+
const usage = (0, util_js_1.asRecord)((0, util_js_1.asRecord)(record.message)?.usage);
|
|
85
|
+
inputTokens = (0, util_js_1.asNumber)(usage?.input_tokens) ?? inputTokens;
|
|
86
|
+
outputTokens = (0, util_js_1.asNumber)(usage?.output_tokens) ?? outputTokens;
|
|
87
|
+
}
|
|
88
|
+
else if (type === 'content_block_start') {
|
|
89
|
+
const index = (0, util_js_1.asNumber)(record.index) ?? 0;
|
|
90
|
+
const block = (0, util_js_1.asRecord)(record.content_block);
|
|
91
|
+
if (block?.type === 'tool_use') {
|
|
92
|
+
blocks.set(index, { id: (0, util_js_1.asString)(block.id) ?? (0, base_js_1.randomId)(), name: (0, util_js_1.asString)(block.name) ?? 'unknown', raw: '' });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
else if (type === 'content_block_delta') {
|
|
96
|
+
const index = (0, util_js_1.asNumber)(record.index) ?? 0;
|
|
97
|
+
const delta = (0, util_js_1.asRecord)(record.delta);
|
|
98
|
+
if (delta?.type === 'text_delta') {
|
|
99
|
+
const piece = (0, util_js_1.asString)(delta.text) ?? '';
|
|
100
|
+
if (piece) {
|
|
101
|
+
if (firstTokenMs === null)
|
|
102
|
+
firstTokenMs = Date.now() - started;
|
|
103
|
+
text += piece;
|
|
104
|
+
yield { type: 'delta', text: piece };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else if (delta?.type === 'thinking_delta') {
|
|
108
|
+
// Extended-thinking tokens ride the reasoning channel, kept out of `text`.
|
|
109
|
+
const piece = (0, util_js_1.asString)(delta.thinking) ?? '';
|
|
110
|
+
if (piece)
|
|
111
|
+
yield { type: 'reasoning', text: piece };
|
|
112
|
+
}
|
|
113
|
+
else if (delta?.type === 'input_json_delta') {
|
|
114
|
+
const partial = blocks.get(index);
|
|
115
|
+
if (partial)
|
|
116
|
+
partial.raw += (0, util_js_1.asString)(delta.partial_json) ?? '';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else if (type === 'content_block_stop') {
|
|
120
|
+
const index = (0, util_js_1.asNumber)(record.index) ?? 0;
|
|
121
|
+
const partial = blocks.get(index);
|
|
122
|
+
if (partial) {
|
|
123
|
+
const call = { id: partial.id, name: partial.name, raw: partial.raw, arguments: (0, base_js_1.parseArgs)(partial.raw) };
|
|
124
|
+
blocks.delete(index);
|
|
125
|
+
if (jsonMode && call.name === JSON_MODE_TOOL) {
|
|
126
|
+
text = jsonTextFrom([call], text);
|
|
127
|
+
if (firstTokenMs === null)
|
|
128
|
+
firstTokenMs = Date.now() - started;
|
|
129
|
+
yield { type: 'delta', text };
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
emittedTools.push(call);
|
|
133
|
+
yield { type: 'tool_call', call };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (type === 'message_stop') {
|
|
138
|
+
sawTerminal = true;
|
|
139
|
+
}
|
|
140
|
+
else if (type === 'message_delta') {
|
|
141
|
+
const delta = (0, util_js_1.asRecord)(record.delta);
|
|
142
|
+
if ((0, util_js_1.asString)(delta?.stop_reason))
|
|
143
|
+
sawTerminal = true;
|
|
144
|
+
stopReason = (0, util_js_1.asString)(delta?.stop_reason) ?? stopReason;
|
|
145
|
+
const usage = (0, util_js_1.asRecord)(record.usage);
|
|
146
|
+
outputTokens = (0, util_js_1.asNumber)(usage?.output_tokens) ?? outputTokens;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (!sawTerminal)
|
|
151
|
+
yield (0, base_js_1.streamAnomaly)('stream ended without a stop_reason or message_stop');
|
|
152
|
+
const hasTools = emittedTools.length > 0;
|
|
153
|
+
yield { type: 'done', result: {
|
|
154
|
+
text,
|
|
155
|
+
toolCalls: hasTools ? emittedTools : undefined,
|
|
156
|
+
finishReason: mapStop(stopReason, hasTools),
|
|
157
|
+
usage: inputTokens !== undefined || outputTokens !== undefined ? { inputTokens, outputTokens, estimated: false } : (0, tokens_js_1.estimatedUsage)((0, util_js_1.textFromMessages)(req.messages), text),
|
|
158
|
+
timing: { firstTokenMs, totalMs: Date.now() - started },
|
|
159
|
+
model: req.model,
|
|
160
|
+
source: { provider: conn.provider, connectionId: conn.id, baseUrl: conn.baseUrl },
|
|
161
|
+
} };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
throw (0, base_js_1.streamError)(error, timeout, conn.provider);
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
timeout.done();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Lists models from Anthropic's `/v1/models` endpoint (auth + version headers
|
|
172
|
+
* already applied to `conn.headers`). The endpoint does not report a context
|
|
173
|
+
* window, so `contextWindow` is left undefined rather than guessed.
|
|
174
|
+
*/
|
|
175
|
+
async listModels(conn) {
|
|
176
|
+
const { data } = await (0, transport_js_1.fetchJson)((0, util_js_1.joinUrl)(conn.baseUrl, '/v1/models'), {
|
|
177
|
+
method: 'GET',
|
|
178
|
+
headers: conn.headers,
|
|
179
|
+
timeoutMs: Math.min(conn.timeoutMs ?? base_js_1.DEFAULT_TIMEOUT_MS, 15_000),
|
|
180
|
+
provider: conn.provider,
|
|
181
|
+
});
|
|
182
|
+
const rows = Array.isArray((0, util_js_1.asRecord)(data)?.data) ? (0, util_js_1.asRecord)(data).data : [];
|
|
183
|
+
return rows
|
|
184
|
+
.map((row) => (0, util_js_1.asString)((0, util_js_1.asRecord)(row)?.id))
|
|
185
|
+
.filter((id) => Boolean(id))
|
|
186
|
+
.map((id) => ({ id, source: { provider: conn.provider, connectionId: conn.id, baseUrl: conn.baseUrl } }));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
exports.AnthropicAdapter = AnthropicAdapter;
|
|
190
|
+
function body(req, jsonMode) {
|
|
191
|
+
const system = req.messages.filter((m) => m.role === 'system').map((m) => textContent(m.content)).join('\n\n') || undefined;
|
|
192
|
+
const base = {
|
|
193
|
+
model: req.model,
|
|
194
|
+
max_tokens: req.maxTokens ?? 4096,
|
|
195
|
+
temperature: req.temperature,
|
|
196
|
+
top_p: req.topP,
|
|
197
|
+
stop_sequences: req.stopSequences,
|
|
198
|
+
system,
|
|
199
|
+
messages: toAnthropicMessages(req.messages.filter((m) => m.role !== 'system')),
|
|
200
|
+
stream: true,
|
|
201
|
+
};
|
|
202
|
+
if (jsonMode) {
|
|
203
|
+
// Forced-tool JSON mode: Anthropic has no response_format, so we make the
|
|
204
|
+
// model answer through a single required tool whose input is the JSON we want.
|
|
205
|
+
base.tools = [{ name: JSON_MODE_TOOL, description: 'Return the answer as a JSON object.', input_schema: schemaFor(req) }];
|
|
206
|
+
base.tool_choice = { type: 'tool', name: JSON_MODE_TOOL };
|
|
207
|
+
}
|
|
208
|
+
else if (req.tools?.length) {
|
|
209
|
+
base.tools = req.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }));
|
|
210
|
+
if (typeof req.toolChoice === 'object')
|
|
211
|
+
base.tool_choice = { type: 'tool', name: req.toolChoice.name };
|
|
212
|
+
else if (req.toolChoice === 'auto')
|
|
213
|
+
base.tool_choice = { type: 'auto' };
|
|
214
|
+
else if (req.toolChoice === 'none')
|
|
215
|
+
base.tool_choice = { type: 'none' };
|
|
216
|
+
}
|
|
217
|
+
if (req.reasoningEffort !== undefined) {
|
|
218
|
+
// First-class reasoning effort → extended thinking. Anthropic requires
|
|
219
|
+
// `budget_tokens < max_tokens` and rejects temperature/top_p alongside
|
|
220
|
+
// thinking, so the budget is fitted under max_tokens (raising max_tokens
|
|
221
|
+
// when the caller's value leaves no room) and the samplers are dropped.
|
|
222
|
+
if (req.reasoningEffort === 'none') {
|
|
223
|
+
base.thinking = { type: 'disabled' };
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
const budget = util_js_1.REASONING_BUDGET_TOKENS[req.reasoningEffort];
|
|
227
|
+
const maxTokens = typeof base.max_tokens === 'number' ? base.max_tokens : 4096;
|
|
228
|
+
if (maxTokens <= budget)
|
|
229
|
+
base.max_tokens = budget + 1024;
|
|
230
|
+
base.thinking = { type: 'enabled', budget_tokens: budget };
|
|
231
|
+
delete base.temperature;
|
|
232
|
+
delete base.top_p;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// providerOptions carries Anthropic-native fields (`thinking`, `metadata`,
|
|
236
|
+
// top-level `cache_control` extras, `service_tier`, …) without a release.
|
|
237
|
+
return (0, util_js_1.applyProviderOptions)(base, req.providerOptions);
|
|
238
|
+
}
|
|
239
|
+
function toAnthropicMessages(messages) {
|
|
240
|
+
const out = [];
|
|
241
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
242
|
+
const message = messages[index];
|
|
243
|
+
if (message.role !== 'tool') {
|
|
244
|
+
out.push(toAnthropicMessage(message));
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const content = [];
|
|
248
|
+
while (index < messages.length && messages[index]?.role === 'tool') {
|
|
249
|
+
const toolMessage = messages[index];
|
|
250
|
+
content.push({ type: 'tool_result', tool_use_id: toolMessage.toolCallId ?? '', content: textContent(toolMessage.content) });
|
|
251
|
+
index += 1;
|
|
252
|
+
}
|
|
253
|
+
index -= 1;
|
|
254
|
+
out.push({ role: 'user', content });
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
function toAnthropicMessage(m) {
|
|
259
|
+
// Tool-role messages are handled by toAnthropicMessages' batching loop and
|
|
260
|
+
// never reach here, so no tool branch is needed.
|
|
261
|
+
// assistant turns that carried tool calls replay them as tool_use blocks,
|
|
262
|
+
// preserving any text/image content parts that accompanied the calls.
|
|
263
|
+
if (m.role === 'assistant' && m.toolCalls?.length) {
|
|
264
|
+
const content = [...contentBlocks(m.content)];
|
|
265
|
+
for (const call of m.toolCalls)
|
|
266
|
+
content.push({ type: 'tool_use', id: call.id, name: call.name, input: call.arguments ?? {} });
|
|
267
|
+
return { role: 'assistant', content };
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
role: m.role === 'assistant' ? 'assistant' : 'user',
|
|
271
|
+
content: typeof m.content === 'string' ? m.content : contentBlocks(m.content),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/** Maps text/image content — a string or a ContentPart[] — onto Anthropic content blocks. */
|
|
275
|
+
function contentBlocks(content) {
|
|
276
|
+
if (typeof content === 'string')
|
|
277
|
+
return content ? [{ type: 'text', text: content }] : [];
|
|
278
|
+
return content.map((part) => part.type === 'image'
|
|
279
|
+
? { type: 'image', source: { type: 'base64', media_type: part.mimeType ?? 'image/png', data: part.imageBase64 ?? '' } }
|
|
280
|
+
: { type: 'text', text: part.text ?? '' });
|
|
281
|
+
}
|
|
282
|
+
function textContent(content) {
|
|
283
|
+
if (typeof content === 'string')
|
|
284
|
+
return content;
|
|
285
|
+
if (!content)
|
|
286
|
+
return '';
|
|
287
|
+
return content.filter((part) => part.type === 'text').map((part) => part.text ?? '').join('\n');
|
|
288
|
+
}
|
|
289
|
+
function parseResponse(data) {
|
|
290
|
+
const record = (0, util_js_1.asRecord)(data);
|
|
291
|
+
const content = Array.isArray(record?.content) ? record.content : [];
|
|
292
|
+
let text = '';
|
|
293
|
+
const toolCalls = [];
|
|
294
|
+
for (const blockValue of content) {
|
|
295
|
+
const block = (0, util_js_1.asRecord)(blockValue);
|
|
296
|
+
if (block?.type === 'text')
|
|
297
|
+
text += (0, util_js_1.asString)(block.text) ?? '';
|
|
298
|
+
if (block?.type === 'tool_use') {
|
|
299
|
+
toolCalls.push({
|
|
300
|
+
id: (0, util_js_1.asString)(block.id) ?? (0, base_js_1.randomId)(),
|
|
301
|
+
name: (0, util_js_1.asString)(block.name) ?? 'unknown',
|
|
302
|
+
arguments: block.input ?? {},
|
|
303
|
+
raw: JSON.stringify(block.input ?? {}),
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const usage = (0, util_js_1.asRecord)(record?.usage);
|
|
308
|
+
return { text, inputTokens: (0, util_js_1.asNumber)(usage?.input_tokens), outputTokens: (0, util_js_1.asNumber)(usage?.output_tokens), stopReason: (0, util_js_1.asString)(record?.stop_reason), toolCalls };
|
|
309
|
+
}
|
|
310
|
+
function schemaFor(req) {
|
|
311
|
+
const schema = req.responseFormat?.type === 'json' ? req.responseFormat.schema : undefined;
|
|
312
|
+
return schema ?? { type: 'object' };
|
|
313
|
+
}
|
|
314
|
+
function jsonTextFrom(toolCalls, fallback) {
|
|
315
|
+
const json = toolCalls.find((call) => call.name === JSON_MODE_TOOL) ?? toolCalls[0];
|
|
316
|
+
if (json)
|
|
317
|
+
return json.raw && json.raw.trim() ? json.raw : JSON.stringify(json.arguments ?? {});
|
|
318
|
+
return fallback;
|
|
319
|
+
}
|
|
320
|
+
function mapStop(stop, hasTools) {
|
|
321
|
+
if (stop === 'tool_use' && hasTools)
|
|
322
|
+
return 'tool';
|
|
323
|
+
if (stop === 'max_tokens')
|
|
324
|
+
return 'length';
|
|
325
|
+
return 'stop';
|
|
326
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.streamError = streamError;
|
|
5
|
+
exports.streamTimeout = streamTimeout;
|
|
6
|
+
exports.listOpenModels = listOpenModels;
|
|
7
|
+
exports.health = health;
|
|
8
|
+
exports.parseArgs = parseArgs;
|
|
9
|
+
exports.safeParse = safeParse;
|
|
10
|
+
exports.randomId = randomId;
|
|
11
|
+
exports.streamAnomaly = streamAnomaly;
|
|
12
|
+
const errors_js_1 = require("../../errors.js");
|
|
13
|
+
const transport_js_1 = require("../../transport.js");
|
|
14
|
+
const util_js_1 = require("../../util.js");
|
|
15
|
+
exports.DEFAULT_TIMEOUT_MS = 120_000;
|
|
16
|
+
/**
|
|
17
|
+
* Maps a raw streaming failure onto a typed {@link AIError}. A fired timeout is
|
|
18
|
+
* reported as `timeout` regardless of how the underlying `fetch` surfaced the
|
|
19
|
+
* abort; anything else is normalized through {@link fromUnknown} (which passes
|
|
20
|
+
* an existing {@link AIError} through untouched, preserving retryability).
|
|
21
|
+
*/
|
|
22
|
+
function streamError(error, timeout, provider) {
|
|
23
|
+
if (timeout.timedOut())
|
|
24
|
+
return new errors_js_1.AIError('Request timed out', { kind: 'timeout', provider });
|
|
25
|
+
return (0, errors_js_1.fromUnknown)(error, provider);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Create a timeout/abort scope covering the full stream lifetime, plus an
|
|
29
|
+
* optional idle timeout (`conn.idleTimeoutMs`) that the engine rearms via
|
|
30
|
+
* `bump()` on each received chunk.
|
|
31
|
+
*/
|
|
32
|
+
function streamTimeout(conn, signal) {
|
|
33
|
+
return (0, transport_js_1.withTimeout)(conn.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS, signal, conn.idleTimeoutMs);
|
|
34
|
+
}
|
|
35
|
+
async function listOpenModels(conn, profile) {
|
|
36
|
+
if (!profile.listModelsPath)
|
|
37
|
+
return [];
|
|
38
|
+
const { data } = await (0, transport_js_1.fetchJson)((0, util_js_1.joinUrl)(conn.baseUrl, profile.listModelsPath), {
|
|
39
|
+
method: 'GET',
|
|
40
|
+
headers: conn.headers,
|
|
41
|
+
timeoutMs: conn.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS,
|
|
42
|
+
provider: conn.provider,
|
|
43
|
+
});
|
|
44
|
+
const record = (0, util_js_1.asRecord)(data);
|
|
45
|
+
const items = Array.isArray(record?.data) ? record.data : Array.isArray(record?.models) ? record.models : [];
|
|
46
|
+
const models = [];
|
|
47
|
+
for (const item of items) {
|
|
48
|
+
const row = (0, util_js_1.asRecord)(item);
|
|
49
|
+
const id = (0, util_js_1.asString)(row?.id) ?? (0, util_js_1.asString)(row?.name);
|
|
50
|
+
if (!id)
|
|
51
|
+
continue;
|
|
52
|
+
const contextWindow = asContextWindow(row);
|
|
53
|
+
const capabilities = asCapabilities(row);
|
|
54
|
+
const model = {
|
|
55
|
+
id,
|
|
56
|
+
source: { provider: conn.provider, connectionId: conn.id, baseUrl: conn.baseUrl },
|
|
57
|
+
};
|
|
58
|
+
if (contextWindow !== undefined)
|
|
59
|
+
model.contextWindow = contextWindow;
|
|
60
|
+
if (capabilities)
|
|
61
|
+
model.capabilities = capabilities;
|
|
62
|
+
models.push(model);
|
|
63
|
+
}
|
|
64
|
+
return models;
|
|
65
|
+
}
|
|
66
|
+
async function health(conn, profile) {
|
|
67
|
+
const path = profile.healthPath ?? profile.listModelsPath;
|
|
68
|
+
if (!path)
|
|
69
|
+
return { ok: true };
|
|
70
|
+
try {
|
|
71
|
+
await (0, transport_js_1.fetchJson)((0, util_js_1.joinUrl)(conn.baseUrl, path), {
|
|
72
|
+
method: 'GET',
|
|
73
|
+
headers: conn.headers,
|
|
74
|
+
timeoutMs: Math.min(conn.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS, 10_000),
|
|
75
|
+
provider: conn.provider,
|
|
76
|
+
});
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
return { ok: false, detail: error instanceof Error ? error.message : 'Health check failed' };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Coerce a provider's tool-call `arguments` into an object. Providers disagree
|
|
85
|
+
* on the shape: OpenAI/Anthropic stream a JSON *string*, Google and Ollama send
|
|
86
|
+
* a native object — but Ollama-compatible backends (llama.cpp and friends)
|
|
87
|
+
* sometimes send a string too. Malformed JSON degrades to `{}` so a single bad
|
|
88
|
+
* tool call surfaces as an argument-validation error rather than a stream crash.
|
|
89
|
+
*/
|
|
90
|
+
function parseArgs(raw) {
|
|
91
|
+
if (raw === undefined || raw === null)
|
|
92
|
+
return {};
|
|
93
|
+
if (typeof raw !== 'string')
|
|
94
|
+
return raw;
|
|
95
|
+
if (!raw.trim())
|
|
96
|
+
return {};
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(raw);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return {};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** JSON.parse that returns undefined instead of throwing — for per-line stream frames. */
|
|
105
|
+
function safeParse(line) {
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(line);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Stable-enough id for a tool call a provider didn't give one for. */
|
|
114
|
+
function randomId() {
|
|
115
|
+
return globalThis.crypto?.randomUUID?.() ?? `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A stream that ended without the provider's terminal marker (an OpenAI
|
|
119
|
+
* `finish_reason`, an Anthropic `message_delta.stop_reason`, a Google
|
|
120
|
+
* `finishReason`, an Ollama `done`) was almost certainly truncated. Every
|
|
121
|
+
* engine yields this so a dropped connection is diagnosable identically
|
|
122
|
+
* regardless of provider.
|
|
123
|
+
*/
|
|
124
|
+
function streamAnomaly(reason = 'stream ended without a terminal finish reason') {
|
|
125
|
+
return { type: 'context', kind: 'stream_anomaly', data: { reason } };
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Pulls a context-window figure out of the many shapes providers use for it
|
|
129
|
+
* (OpenRouter `context_length`, OpenAI-style `context_window`, Ollama
|
|
130
|
+
* `/api/show` `model_info` entries surfaced as `contextWindow`).
|
|
131
|
+
*/
|
|
132
|
+
function asContextWindow(row) {
|
|
133
|
+
if (!row)
|
|
134
|
+
return undefined;
|
|
135
|
+
const direct = row['context_length'] ?? row['context_window'] ?? row['contextWindow'];
|
|
136
|
+
return typeof direct === 'number' && Number.isFinite(direct) ? direct : undefined;
|
|
137
|
+
}
|
|
138
|
+
function asCapabilities(row) {
|
|
139
|
+
if (!row)
|
|
140
|
+
return undefined;
|
|
141
|
+
const value = row['capabilities'] ?? (0, util_js_1.asRecord)(row['architecture'])?.['modality'];
|
|
142
|
+
if (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))
|
|
143
|
+
return value;
|
|
144
|
+
if (typeof value === 'string')
|
|
145
|
+
return [value];
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|