@juspay/neurolink 13.10.5 → 13.12.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/CHANGELOG.md +3 -3
- package/dist/agent/agent.js +7 -6
- package/dist/browser/neurolink.min.js +439 -439
- package/dist/cli/loop/optionsSchema.d.ts +1 -1
- package/dist/core/nativeGenerateLoop.js +241 -3
- package/dist/neurolink.d.ts +7 -0
- package/dist/neurolink.js +21 -0
- package/dist/providers/anthropic/client.d.ts +17 -0
- package/dist/providers/anthropic/client.js +155 -6
- package/dist/providers/anthropic/loopAdapter.js +86 -41
- package/dist/providers/anthropic/threads.d.ts +80 -0
- package/dist/providers/anthropic/threads.js +442 -0
- package/dist/server/routes/claudeProxyRoutes.js +19 -1
- package/dist/types/generate.d.ts +26 -0
- package/dist/types/loopEngine.d.ts +68 -0
- package/dist/types/stream.d.ts +25 -0
- package/docs-site/static/search-index.json +2 -0
- package/package.json +8 -6
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message threads for the native Anthropic loop (beta, `message-threads-2026-08-12`).
|
|
3
|
+
*
|
|
4
|
+
* Without a thread every step of a turn resends the whole conversation. With
|
|
5
|
+
* one, the first step sends it with `thread: {type: "create"}` and each later
|
|
6
|
+
* step sends only the messages since the last response, plus the previous
|
|
7
|
+
* response id. The API keeps the conversation in memory for a few minutes and
|
|
8
|
+
* is best-effort about it, so the caller stays the source of truth: this
|
|
9
|
+
* module only decides, per step, whether the thread can be continued, and
|
|
10
|
+
* otherwise plans a `create` that sends everything again.
|
|
11
|
+
*
|
|
12
|
+
* A thread can be continued only when nothing the API fixed at creation has
|
|
13
|
+
* changed (model, tools, system, tool choice, thinking, output config and the
|
|
14
|
+
* beta set) and the messages already sent are untouched. Anything that
|
|
15
|
+
* rewrites history, such as a context reclaim, therefore starts a new thread
|
|
16
|
+
* by itself.
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { CONVERSATION_INSTRUCTIONS } from "../../config/conversationMemory.js";
|
|
20
|
+
export const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
21
|
+
/** Stop reasons after which the API has stored the response as a continuable turn. */
|
|
22
|
+
const STORABLE_STOP_REASONS = new Set([
|
|
23
|
+
"end_turn",
|
|
24
|
+
"tool_use",
|
|
25
|
+
"stop_sequence",
|
|
26
|
+
]);
|
|
27
|
+
/**
|
|
28
|
+
* Record how a step's response ended. The API stores a thread turn only when
|
|
29
|
+
* the response ended normally; a refusal, a cut-off or an early end is resent
|
|
30
|
+
* in full by the next step.
|
|
31
|
+
*/
|
|
32
|
+
export function settleThread(session, response) {
|
|
33
|
+
if (!session.enabled) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (response.sawTerminalEvent &&
|
|
37
|
+
response.messageId !== undefined &&
|
|
38
|
+
response.stopReason !== undefined &&
|
|
39
|
+
STORABLE_STOP_REASONS.has(response.stopReason)) {
|
|
40
|
+
session.accept(response.messageId, response.stopReason);
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
session.reset();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const sha = (value) => createHash("sha256")
|
|
47
|
+
.update(JSON.stringify(value) ?? "")
|
|
48
|
+
.digest("hex");
|
|
49
|
+
// A cache breakpoint is a request for caching, not content: the same message
|
|
50
|
+
// carries a different one on the request that first sends it and the one that
|
|
51
|
+
// replays it, so it must not decide whether a prefix is unchanged.
|
|
52
|
+
const withoutCacheControl = (value) => {
|
|
53
|
+
if (Array.isArray(value)) {
|
|
54
|
+
return value.map(withoutCacheControl);
|
|
55
|
+
}
|
|
56
|
+
if (value !== null && typeof value === "object") {
|
|
57
|
+
const out = {};
|
|
58
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
59
|
+
if (key !== "cache_control") {
|
|
60
|
+
out[key] = withoutCacheControl(entry);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
};
|
|
67
|
+
// What conversation memory keeps of a message: its role and its text. Memory
|
|
68
|
+
// drops tool_use / tool_result blocks and anything that is not text, so that is
|
|
69
|
+
// all a later call can be compared on.
|
|
70
|
+
const textOfMessage = (message) => {
|
|
71
|
+
const content = message?.content;
|
|
72
|
+
if (typeof content === "string") {
|
|
73
|
+
return content;
|
|
74
|
+
}
|
|
75
|
+
if (!Array.isArray(content)) {
|
|
76
|
+
return "";
|
|
77
|
+
}
|
|
78
|
+
return content
|
|
79
|
+
.map((block) => {
|
|
80
|
+
const b = block;
|
|
81
|
+
if (b?.type === "text" && typeof b.text === "string") {
|
|
82
|
+
return b.text;
|
|
83
|
+
}
|
|
84
|
+
// An attachment (image, document) is part of what the model was given.
|
|
85
|
+
// It is compared by content, so a replaced one is a different message;
|
|
86
|
+
// an attachment memory does not hand back simply never matches, which
|
|
87
|
+
// costs a new thread and nothing else.
|
|
88
|
+
return b === null || b === undefined
|
|
89
|
+
? ""
|
|
90
|
+
: `\u0000${String(b.type)}:${sha(withoutCacheControl(b))}\u0000`;
|
|
91
|
+
})
|
|
92
|
+
.join("");
|
|
93
|
+
};
|
|
94
|
+
// By default conversation memory replays a turn's tool calls as one
|
|
95
|
+
// `[called <tool> → ok]` line each, in front of the assistant's own text. Those
|
|
96
|
+
// lines describe tool blocks the thread already holds in full, so they are
|
|
97
|
+
// left out of the comparison: what is compared is what the model said.
|
|
98
|
+
const TOOL_MARKER_LINE = /^\[called [^\n]*? → (?:ok|error|unknown)\](?:\n|$)/;
|
|
99
|
+
const withoutToolMarkers = (text) => {
|
|
100
|
+
let rest = text;
|
|
101
|
+
while (TOOL_MARKER_LINE.test(rest)) {
|
|
102
|
+
rest = rest.replace(TOOL_MARKER_LINE, "");
|
|
103
|
+
}
|
|
104
|
+
return rest;
|
|
105
|
+
};
|
|
106
|
+
const memoryHash = (role, text) => sha([role, role === "assistant" ? withoutToolMarkers(text) : text]);
|
|
107
|
+
const memoryHashOf = (message) => memoryHash(message?.role, textOfMessage(message));
|
|
108
|
+
// NeuroLink appends CONVERSATION_INSTRUCTIONS to the system prompt once a
|
|
109
|
+
// conversation has history, so a session's first call and its second carry
|
|
110
|
+
// different system prompts for the same conversation. The note is about
|
|
111
|
+
// history a continued thread already holds, so it is left out of the
|
|
112
|
+
// comparison; a continued call therefore runs without it.
|
|
113
|
+
const withoutConversationNote = (system) => {
|
|
114
|
+
if (typeof system === "string") {
|
|
115
|
+
return system.endsWith(CONVERSATION_INSTRUCTIONS)
|
|
116
|
+
? system.slice(0, -CONVERSATION_INSTRUCTIONS.length)
|
|
117
|
+
: system;
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(system)) {
|
|
120
|
+
return system.map((block) => {
|
|
121
|
+
const text = block?.text;
|
|
122
|
+
return typeof text === "string" &&
|
|
123
|
+
text.endsWith(CONVERSATION_INSTRUCTIONS)
|
|
124
|
+
? {
|
|
125
|
+
...block,
|
|
126
|
+
text: text.slice(0, -CONVERSATION_INSTRUCTIONS.length),
|
|
127
|
+
}
|
|
128
|
+
: block;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return system;
|
|
132
|
+
};
|
|
133
|
+
const TURN_ENDING_STOPS = new Set(["end_turn", "stop_sequence"]);
|
|
134
|
+
const FIXED_FIELDS = [
|
|
135
|
+
"model",
|
|
136
|
+
"system",
|
|
137
|
+
"tools",
|
|
138
|
+
"tool_choice",
|
|
139
|
+
"thinking",
|
|
140
|
+
"output_config",
|
|
141
|
+
"mcp_servers",
|
|
142
|
+
"context_management",
|
|
143
|
+
"container",
|
|
144
|
+
"cache_control",
|
|
145
|
+
];
|
|
146
|
+
const mergeBetas = (existing) => [
|
|
147
|
+
...new Set([...(existing ?? "").split(","), MESSAGE_THREADS_BETA]
|
|
148
|
+
.map((beta) => beta.trim())
|
|
149
|
+
.filter(Boolean)),
|
|
150
|
+
].join(",");
|
|
151
|
+
/**
|
|
152
|
+
* Start the thread state for one turn.
|
|
153
|
+
*
|
|
154
|
+
* @param betaHeader the `anthropic-beta` value the client already sends; the
|
|
155
|
+
* thread beta is added to it, identically on every request of the thread.
|
|
156
|
+
*/
|
|
157
|
+
export function createAnthropicThreadSession(betaHeader, carried) {
|
|
158
|
+
const headers = { "anthropic-beta": mergeBetas(betaHeader) };
|
|
159
|
+
let enabled = true;
|
|
160
|
+
let previousMessageId;
|
|
161
|
+
// What the thread holds after the last accepted response: the fingerprint of
|
|
162
|
+
// the fixed fields and one hash per message the request carried. The reply
|
|
163
|
+
// the API stored after them is not hashed; it is the API's own copy.
|
|
164
|
+
let stored;
|
|
165
|
+
let pending;
|
|
166
|
+
// The call's starting conversation as memory sees it, and how the last
|
|
167
|
+
// stored response ended: together they are what the next call is matched on.
|
|
168
|
+
let startAnchor;
|
|
169
|
+
// The call's starting messages, hashed exactly. A thread can be handed to the
|
|
170
|
+
// next call only while it still holds them unchanged: a reclaim that rewrites
|
|
171
|
+
// earlier history leaves a thread the caller's history no longer matches.
|
|
172
|
+
let startHashes;
|
|
173
|
+
let extendsStart = true;
|
|
174
|
+
let lastStop;
|
|
175
|
+
// A thread left by the previous call of the session, adopted by the first
|
|
176
|
+
// plan only if everything it was created with is still the same.
|
|
177
|
+
let handedOver = carried;
|
|
178
|
+
return {
|
|
179
|
+
get enabled() {
|
|
180
|
+
return enabled;
|
|
181
|
+
},
|
|
182
|
+
plan(params) {
|
|
183
|
+
const bag = { ...params };
|
|
184
|
+
const fixed = {
|
|
185
|
+
betas: headers["anthropic-beta"],
|
|
186
|
+
};
|
|
187
|
+
for (const field of FIXED_FIELDS) {
|
|
188
|
+
fixed[field] =
|
|
189
|
+
field === "system" ? withoutConversationNote(bag[field]) : bag[field];
|
|
190
|
+
}
|
|
191
|
+
const fingerprint = sha(fixed);
|
|
192
|
+
const hashes = params.messages.map((message) => sha(withoutCacheControl(message)));
|
|
193
|
+
const memory = params.messages.map(memoryHashOf);
|
|
194
|
+
startAnchor ??= memory;
|
|
195
|
+
startHashes ??= hashes;
|
|
196
|
+
if (hashes.length < startHashes.length ||
|
|
197
|
+
!startHashes.every((hash, index) => hashes[index] === hash)) {
|
|
198
|
+
extendsStart = false;
|
|
199
|
+
}
|
|
200
|
+
if (handedOver !== undefined) {
|
|
201
|
+
// The previous call ended on an assistant reply that memory now hands
|
|
202
|
+
// back, and this call adds one user message. The thread also holds the
|
|
203
|
+
// tool blocks memory dropped; that difference is the point of the
|
|
204
|
+
// session scope and is accepted, not detected.
|
|
205
|
+
const prior = handedOver;
|
|
206
|
+
handedOver = undefined;
|
|
207
|
+
const last = params.messages[params.messages.length - 1];
|
|
208
|
+
if (params.messages.length >= 3 &&
|
|
209
|
+
last.role === "user" &&
|
|
210
|
+
prior.fingerprint === fingerprint &&
|
|
211
|
+
prior.anchor.length === memory.length - 1 &&
|
|
212
|
+
prior.anchor.every((hash, index) => hash === memory[index])) {
|
|
213
|
+
previousMessageId = prior.previousMessageId;
|
|
214
|
+
stored = { fingerprint, hashes: hashes.slice(0, -2) };
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
pending = { fingerprint, hashes };
|
|
218
|
+
// The stored reply sits between the messages already sent and the new ones.
|
|
219
|
+
const held = stored ? stored.hashes.length + 1 : 0;
|
|
220
|
+
const canContinue = previousMessageId !== undefined &&
|
|
221
|
+
stored !== undefined &&
|
|
222
|
+
stored.fingerprint === fingerprint &&
|
|
223
|
+
params.messages.length > held &&
|
|
224
|
+
stored.hashes.every((hash, index) => hashes[index] === hash);
|
|
225
|
+
if (canContinue && previousMessageId !== undefined) {
|
|
226
|
+
// system and tools belong to the create request; sending either on a
|
|
227
|
+
// continue, even empty, is rejected.
|
|
228
|
+
const { system: _system, tools: _tools, ...rest } = params;
|
|
229
|
+
return {
|
|
230
|
+
mode: "continue",
|
|
231
|
+
params: {
|
|
232
|
+
...rest,
|
|
233
|
+
messages: params.messages.slice(held),
|
|
234
|
+
thread: {
|
|
235
|
+
type: "continue",
|
|
236
|
+
previous_message_id: previousMessageId,
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
headers,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
mode: "create",
|
|
244
|
+
params: { ...params, thread: { type: "create" } },
|
|
245
|
+
headers,
|
|
246
|
+
};
|
|
247
|
+
},
|
|
248
|
+
accept(messageId, stopReason) {
|
|
249
|
+
if (pending === undefined) {
|
|
250
|
+
previousMessageId = undefined;
|
|
251
|
+
stored = undefined;
|
|
252
|
+
lastStop = undefined;
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
previousMessageId = messageId;
|
|
256
|
+
stored = pending;
|
|
257
|
+
pending = undefined;
|
|
258
|
+
lastStop = stopReason;
|
|
259
|
+
},
|
|
260
|
+
reset() {
|
|
261
|
+
previousMessageId = undefined;
|
|
262
|
+
stored = undefined;
|
|
263
|
+
pending = undefined;
|
|
264
|
+
lastStop = undefined;
|
|
265
|
+
},
|
|
266
|
+
disable() {
|
|
267
|
+
enabled = false;
|
|
268
|
+
previousMessageId = undefined;
|
|
269
|
+
stored = undefined;
|
|
270
|
+
pending = undefined;
|
|
271
|
+
lastStop = undefined;
|
|
272
|
+
},
|
|
273
|
+
carry(assistantText) {
|
|
274
|
+
if (!enabled ||
|
|
275
|
+
previousMessageId === undefined ||
|
|
276
|
+
stored === undefined ||
|
|
277
|
+
startAnchor === undefined ||
|
|
278
|
+
!extendsStart ||
|
|
279
|
+
lastStop === undefined ||
|
|
280
|
+
!TURN_ENDING_STOPS.has(lastStop)) {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
previousMessageId,
|
|
285
|
+
fingerprint: stored.fingerprint,
|
|
286
|
+
anchor: [...startAnchor, memoryHash("assistant", assistantText)],
|
|
287
|
+
};
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** The API's `error.details.error_code` for a thread request that was refused, if there is one. */
|
|
292
|
+
export function threadErrorCode(error) {
|
|
293
|
+
if (typeof error !== "object" || error === null) {
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
const body = error.error;
|
|
297
|
+
const inner = typeof body === "object" && body !== null
|
|
298
|
+
? body.error
|
|
299
|
+
: undefined;
|
|
300
|
+
const details = typeof inner === "object" && inner !== null
|
|
301
|
+
? inner.details
|
|
302
|
+
: undefined;
|
|
303
|
+
const code = typeof details === "object" && details !== null
|
|
304
|
+
? details.error_code
|
|
305
|
+
: undefined;
|
|
306
|
+
return typeof code === "string" ? code : undefined;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* What to do after a thread request fails: send everything again as a new
|
|
310
|
+
* thread, send it without a thread at all, or neither (an ordinary error).
|
|
311
|
+
*/
|
|
312
|
+
export function threadRecovery(error) {
|
|
313
|
+
const code = threadErrorCode(error);
|
|
314
|
+
switch (code) {
|
|
315
|
+
case "thread_not_found":
|
|
316
|
+
case "thread_already_continued":
|
|
317
|
+
case "thread_continue_in_flight":
|
|
318
|
+
case "thread_fingerprint_mismatch":
|
|
319
|
+
return "recreate";
|
|
320
|
+
case "thread_unsupported_request":
|
|
321
|
+
return "unthreaded";
|
|
322
|
+
default:
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** How long a thread is kept for the next call of its session. */
|
|
327
|
+
const SESSION_THREAD_TTL_MS = 4 * 60 * 1000; // the API drops one after 5 minutes idle
|
|
328
|
+
const SESSION_THREAD_MAX = 500;
|
|
329
|
+
/**
|
|
330
|
+
* The threads a NeuroLink instance has left behind for its sessions' next
|
|
331
|
+
* calls. In memory and per process only: another process simply creates a new
|
|
332
|
+
* thread, which is always correct. An entry is taken out by the call that
|
|
333
|
+
* continues it, because a response id can be continued once, so two concurrent
|
|
334
|
+
* calls of one session cannot both continue the same thread.
|
|
335
|
+
*/
|
|
336
|
+
export class AnthropicThreadStore {
|
|
337
|
+
entries = new Map();
|
|
338
|
+
// Bumped when a session (or everything) is cleared. A call records the epoch
|
|
339
|
+
// when it starts and may leave a thread only if it is unchanged, so a stream
|
|
340
|
+
// that finishes after its conversation was cleared cannot bring the thread
|
|
341
|
+
// back. Coarse by design: a missed reuse costs one new thread.
|
|
342
|
+
globalEpoch = 0;
|
|
343
|
+
sessionEpochs = new Map();
|
|
344
|
+
sweepTimer;
|
|
345
|
+
/**
|
|
346
|
+
* The identity of a thread's owner: who asked, in which session, with which
|
|
347
|
+
* credential and endpoint. A thread belongs to the key that created it, so
|
|
348
|
+
* the credential is part of the key (hashed; the key itself is never kept).
|
|
349
|
+
*/
|
|
350
|
+
static keyOf(parts) {
|
|
351
|
+
return sha([
|
|
352
|
+
parts.userId ?? "",
|
|
353
|
+
parts.sessionId,
|
|
354
|
+
parts.credential,
|
|
355
|
+
parts.baseURL ?? "",
|
|
356
|
+
]);
|
|
357
|
+
}
|
|
358
|
+
take(key, now = Date.now()) {
|
|
359
|
+
const entry = this.entries.get(key);
|
|
360
|
+
if (entry === undefined) {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
this.entries.delete(key);
|
|
364
|
+
return entry.expiresAt > now ? entry.carry : undefined;
|
|
365
|
+
}
|
|
366
|
+
/** The epoch a call must hand back to `put` for its thread to be kept. */
|
|
367
|
+
epochOf(sessionId) {
|
|
368
|
+
return `${this.globalEpoch}:${this.sessionEpochs.get(sessionId) ?? 0}`;
|
|
369
|
+
}
|
|
370
|
+
put(key, sessionId, carry, epoch, now = Date.now()) {
|
|
371
|
+
if (epoch !== this.epochOf(sessionId)) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
this.sweep(now);
|
|
375
|
+
while (this.entries.size >= SESSION_THREAD_MAX) {
|
|
376
|
+
const oldest = this.entries.keys().next().value;
|
|
377
|
+
if (oldest === undefined) {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
this.entries.delete(oldest);
|
|
381
|
+
}
|
|
382
|
+
this.entries.set(key, {
|
|
383
|
+
sessionId,
|
|
384
|
+
carry,
|
|
385
|
+
expiresAt: now + SESSION_THREAD_TTL_MS,
|
|
386
|
+
});
|
|
387
|
+
this.armSweep();
|
|
388
|
+
}
|
|
389
|
+
/** Drop every entry that has expired. */
|
|
390
|
+
sweep(now = Date.now()) {
|
|
391
|
+
for (const [key, entry] of this.entries) {
|
|
392
|
+
if (entry.expiresAt <= now) {
|
|
393
|
+
this.entries.delete(key);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
// An idle store still lets go of its entries when they expire. The timer is
|
|
398
|
+
// unref'd, so it never keeps a process alive, and it stops once empty.
|
|
399
|
+
armSweep() {
|
|
400
|
+
if (this.sweepTimer !== undefined) {
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const timer = setTimeout(() => {
|
|
404
|
+
this.sweepTimer = undefined;
|
|
405
|
+
this.sweep();
|
|
406
|
+
if (this.entries.size > 0) {
|
|
407
|
+
this.armSweep();
|
|
408
|
+
}
|
|
409
|
+
}, SESSION_THREAD_TTL_MS + 1000);
|
|
410
|
+
timer.unref?.();
|
|
411
|
+
this.sweepTimer = timer;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Forget a session's thread, or every thread when no session is named, and
|
|
415
|
+
* fence any call still running from leaving one afterwards.
|
|
416
|
+
*/
|
|
417
|
+
forget(sessionId) {
|
|
418
|
+
if (sessionId === undefined) {
|
|
419
|
+
this.globalEpoch++;
|
|
420
|
+
this.sessionEpochs.clear();
|
|
421
|
+
this.entries.clear();
|
|
422
|
+
if (this.sweepTimer !== undefined) {
|
|
423
|
+
clearTimeout(this.sweepTimer);
|
|
424
|
+
this.sweepTimer = undefined;
|
|
425
|
+
}
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (this.sessionEpochs.size >= SESSION_THREAD_MAX) {
|
|
429
|
+
this.globalEpoch++;
|
|
430
|
+
this.sessionEpochs.clear();
|
|
431
|
+
}
|
|
432
|
+
this.sessionEpochs.set(sessionId, (this.sessionEpochs.get(sessionId) ?? 0) + 1);
|
|
433
|
+
for (const [key, entry] of this.entries) {
|
|
434
|
+
if (entry.sessionId === sessionId) {
|
|
435
|
+
this.entries.delete(key);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
get size() {
|
|
440
|
+
return this.entries.size;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
@@ -2204,6 +2204,12 @@ const SNAPSHOT_STABLE_HEADERS = new Set([
|
|
|
2204
2204
|
"x-stainless-timeout",
|
|
2205
2205
|
"x-subscription-tier",
|
|
2206
2206
|
]);
|
|
2207
|
+
/**
|
|
2208
|
+
* Anthropic message threads (beta). The Anthropic provider sends this on a
|
|
2209
|
+
* request that carries a `thread` field; the proxy forwards it when a client
|
|
2210
|
+
* names it. Kept as a literal here so the proxy does not import a provider.
|
|
2211
|
+
*/
|
|
2212
|
+
const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
2207
2213
|
const NON_CLAUDE_OAUTH_BETAS = [
|
|
2208
2214
|
"oauth-2025-04-20",
|
|
2209
2215
|
"claude-code-20250219",
|
|
@@ -6957,9 +6963,15 @@ async function prepareAnthropicAccountAttempt(args) {
|
|
|
6957
6963
|
const proxyBetas = isClaudeClientRequest
|
|
6958
6964
|
? CLAUDE_CODE_OAUTH_BETAS
|
|
6959
6965
|
: NON_CLAUDE_OAUTH_BETAS;
|
|
6966
|
+
// Message threads (opt-in per call by the client) must reach the upstream
|
|
6967
|
+
// intact: a request carrying a `thread` body field is rejected without the
|
|
6968
|
+
// beta. It stays out of proxyBetas, so it is only forwarded when a client
|
|
6969
|
+
// asks for it, and a tier that lacks it is skipped without re-ranking the
|
|
6970
|
+
// pool (clientSuppliedBetaForwarded below).
|
|
6960
6971
|
const knownBetas = new Set([
|
|
6961
6972
|
...CLAUDE_CODE_OAUTH_BETAS,
|
|
6962
6973
|
...NON_CLAUDE_OAUTH_BETAS,
|
|
6974
|
+
MESSAGE_THREADS_BETA,
|
|
6963
6975
|
]);
|
|
6964
6976
|
const clientBetas = (headers["anthropic-beta"] ?? "")
|
|
6965
6977
|
.split(",")
|
|
@@ -6970,7 +6982,13 @@ async function prepareAnthropicAccountAttempt(args) {
|
|
|
6970
6982
|
// not send; everyone else is held to the proxy's own set.
|
|
6971
6983
|
const existing = new Set(genuineClaudeCode
|
|
6972
6984
|
? clientBetas
|
|
6973
|
-
: clientBetas.filter((beta) => knownBetas.has(beta)
|
|
6985
|
+
: clientBetas.filter((beta) => knownBetas.has(beta) &&
|
|
6986
|
+
// Request-scoped: a beta replayed from a captured snapshot is
|
|
6987
|
+
// not this client's ask, and a tier without it would reject it.
|
|
6988
|
+
(beta !== MESSAGE_THREADS_BETA ||
|
|
6989
|
+
(filteredHeaders["anthropic-beta"] ?? "")
|
|
6990
|
+
.split(",")
|
|
6991
|
+
.some((own) => own.trim() === beta))));
|
|
6974
6992
|
clientSuppliedBetaForwarded = [...existing].some((beta) => !proxyBetas.includes(beta));
|
|
6975
6993
|
for (const beta of proxyBetas) {
|
|
6976
6994
|
existing.add(beta);
|
package/dist/types/generate.d.ts
CHANGED
|
@@ -30,6 +30,14 @@ import type { ProcessorPipelineConfig } from "./ioProcessor.js";
|
|
|
30
30
|
* Supports multimodal content while maintaining backward compatibility
|
|
31
31
|
*/
|
|
32
32
|
export type GenerateOptions = {
|
|
33
|
+
/**
|
|
34
|
+
* Send this call's steps as an Anthropic message thread (beta); `"session"`
|
|
35
|
+
* also keeps the thread for the session's next call. The same option and the
|
|
36
|
+
* same limits as `StreamOptions.messageThreads`: native Anthropic with
|
|
37
|
+
* API-key auth only, off by default, not zero-data-retention eligible, and no
|
|
38
|
+
* way to delete a thread. See that option for the trade-offs.
|
|
39
|
+
*/
|
|
40
|
+
messageThreads?: boolean | "session";
|
|
33
41
|
/**
|
|
34
42
|
* Input content for generation. Optional for media-only modes (avatar, music,
|
|
35
43
|
* video) where all configuration lives in `output`; the SDK synthesises an
|
|
@@ -1222,6 +1230,14 @@ export type FactoryEnhancedProvider = EnhancedProvider & {
|
|
|
1222
1230
|
* Extended to support video generation mode
|
|
1223
1231
|
*/
|
|
1224
1232
|
export type TextGenerationOptions = {
|
|
1233
|
+
/**
|
|
1234
|
+
* Send this call's steps as an Anthropic message thread (beta); `"session"`
|
|
1235
|
+
* also keeps the thread for the session's next call. The same option and the
|
|
1236
|
+
* same limits as `StreamOptions.messageThreads`: native Anthropic with
|
|
1237
|
+
* API-key auth only, off by default, not zero-data-retention eligible, and no
|
|
1238
|
+
* way to delete a thread. See that option for the trade-offs.
|
|
1239
|
+
*/
|
|
1240
|
+
messageThreads?: boolean | "session";
|
|
1225
1241
|
prompt?: string;
|
|
1226
1242
|
/**
|
|
1227
1243
|
* Fraction of the model's context window at which compaction runs for this
|
|
@@ -1916,3 +1932,13 @@ export type SingleShotResult = {
|
|
|
1916
1932
|
};
|
|
1917
1933
|
finishReason?: string;
|
|
1918
1934
|
};
|
|
1935
|
+
/** The part of a Zod issue that date revival in `validateToolInput` reads. */
|
|
1936
|
+
export type ToolDateIssue = {
|
|
1937
|
+
code?: unknown;
|
|
1938
|
+
expected?: unknown;
|
|
1939
|
+
path?: unknown;
|
|
1940
|
+
/** Zod 4: the issues of each branch of a union, with paths relative to it. */
|
|
1941
|
+
errors?: unknown;
|
|
1942
|
+
/** Zod 3: one entry per union branch, its issues carrying absolute paths. */
|
|
1943
|
+
unionErrors?: unknown;
|
|
1944
|
+
};
|
|
@@ -238,6 +238,68 @@ export type AgenticLoopAdapter<TConversation = unknown, TRaw = unknown> = {
|
|
|
238
238
|
* Anthropic has never had one, and setting it for both would change native
|
|
239
239
|
* Anthropic's behaviour under the guise of a shared refactor.
|
|
240
240
|
*/
|
|
241
|
+
/** The `thread` field of an Anthropic Messages request (message threads, beta). */
|
|
242
|
+
export type AnthropicThreadRef = {
|
|
243
|
+
type: "create";
|
|
244
|
+
} | {
|
|
245
|
+
type: "continue";
|
|
246
|
+
previous_message_id: string;
|
|
247
|
+
};
|
|
248
|
+
/** One step's request, shaped for a thread. */
|
|
249
|
+
export type AnthropicThreadPlan = {
|
|
250
|
+
/** `continue` sends only the new messages and leaves out `system` and `tools`. */
|
|
251
|
+
mode: "create" | "continue";
|
|
252
|
+
params: Anthropic.Messages.MessageCreateParams & AnthropicSamplingParams & {
|
|
253
|
+
thread: AnthropicThreadRef;
|
|
254
|
+
};
|
|
255
|
+
/** The `anthropic-beta` value for this request: the client's own plus the thread beta. */
|
|
256
|
+
headers: Record<string, string>;
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* What one call hands the next call of the same session so it can continue the
|
|
260
|
+
* thread instead of creating another: the last stored response, the fixed
|
|
261
|
+
* fields the thread was created with, and a hash of each message the call
|
|
262
|
+
* started from (the history conversation memory rebuilt for it).
|
|
263
|
+
*/
|
|
264
|
+
export type AnthropicThreadCarry = {
|
|
265
|
+
previousMessageId: string;
|
|
266
|
+
fingerprint: string;
|
|
267
|
+
anchor: string[];
|
|
268
|
+
};
|
|
269
|
+
/** A thread a NeuroLink instance keeps for its session's next call. */
|
|
270
|
+
export type AnthropicStoredThread = {
|
|
271
|
+
sessionId: string;
|
|
272
|
+
carry: AnthropicThreadCarry;
|
|
273
|
+
expiresAt: number;
|
|
274
|
+
};
|
|
275
|
+
/**
|
|
276
|
+
* The state of one Anthropic message thread across the steps of a turn.
|
|
277
|
+
*
|
|
278
|
+
* The thread lives on the server for minutes and is best-effort, so this is a
|
|
279
|
+
* cache of a conversation the caller still owns: whenever it is unsure, the
|
|
280
|
+
* next plan is a `create` that resends everything.
|
|
281
|
+
*/
|
|
282
|
+
export type AnthropicThreadSession = {
|
|
283
|
+
/** False once the API has said it cannot thread this request. */
|
|
284
|
+
readonly enabled: boolean;
|
|
285
|
+
/**
|
|
286
|
+
* What the next call of the same session needs to continue this thread, or
|
|
287
|
+
* undefined when it cannot: the turn did not end on a normal stop, or no
|
|
288
|
+
* response was stored. `assistantText` is the text the turn streamed, which
|
|
289
|
+
* is what conversation memory will hand back as the assistant's reply.
|
|
290
|
+
*/
|
|
291
|
+
carry(assistantText: string): AnthropicThreadCarry | undefined;
|
|
292
|
+
plan(params: Anthropic.Messages.MessageCreateParams & AnthropicSamplingParams): AnthropicThreadPlan;
|
|
293
|
+
/**
|
|
294
|
+
* The response was complete and stored: the next step may continue from it.
|
|
295
|
+
* `stopReason` says whether it also ended the turn.
|
|
296
|
+
*/
|
|
297
|
+
accept(messageId: string, stopReason?: string): void;
|
|
298
|
+
/** The next plan is a `create`. */
|
|
299
|
+
reset(): void;
|
|
300
|
+
/** Stop threading for the rest of the turn. */
|
|
301
|
+
disable(): void;
|
|
302
|
+
};
|
|
241
303
|
/**
|
|
242
304
|
* Construction input for `createAnthropicLoopAdapter`, shared by direct
|
|
243
305
|
* Anthropic and Claude-on-Vertex.
|
|
@@ -267,6 +329,12 @@ export type AnthropicLoopAdapterConfig<TMessage = Anthropic.Messages.MessagePara
|
|
|
267
329
|
/** Provider name recorded on each step's generation and used to price it. */
|
|
268
330
|
provider: string;
|
|
269
331
|
maxSteps: number;
|
|
332
|
+
/**
|
|
333
|
+
* Send the turn's steps as an Anthropic message thread. Only the direct
|
|
334
|
+
* Anthropic client sets it, and only on request; without it every step
|
|
335
|
+
* resends the whole conversation, as before.
|
|
336
|
+
*/
|
|
337
|
+
threads?: AnthropicThreadSession;
|
|
270
338
|
/**
|
|
271
339
|
* Build one step's request. A closure so the per-turn work the caller
|
|
272
340
|
* already does — system prompt, tool declarations, sampling, thinking
|
package/dist/types/stream.d.ts
CHANGED
|
@@ -562,6 +562,31 @@ export type StreamOptions = {
|
|
|
562
562
|
* Also rejected up front.
|
|
563
563
|
*/
|
|
564
564
|
executionControl?: ExecutionControlOptions;
|
|
565
|
+
/**
|
|
566
|
+
* Send this turn's steps as an Anthropic message thread (beta,
|
|
567
|
+
* `message-threads-2026-08-12`): the first step sends the whole conversation
|
|
568
|
+
* and a later step only the messages since the last response, while nothing
|
|
569
|
+
* the thread fixes has changed (otherwise it starts a new thread), so the
|
|
570
|
+
* request stops growing with the turn. Off by default.
|
|
571
|
+
*
|
|
572
|
+
* Native Anthropic (`stream()` and `generate()`) with API-key auth only;
|
|
573
|
+
* other providers and OAuth ignore it. The server keeps a thread for minutes and may drop it, in
|
|
574
|
+
* which case the step is resent in full; a change to the tools, system
|
|
575
|
+
* prompt, tool choice or earlier messages starts a new thread. Threads are
|
|
576
|
+
* not zero-data-retention eligible, and the API has no way to delete one
|
|
577
|
+
* (it expires within an hour). It was measured to shrink the request, not to
|
|
578
|
+
* lower time to first token when prompt caching is already on.
|
|
579
|
+
*
|
|
580
|
+
* `"session"` also keeps the thread for the session's next call (same user,
|
|
581
|
+
* session id, credential and endpoint; in memory on the NeuroLink instance,
|
|
582
|
+
* for up to four minutes), so that call sends only its new message. Two
|
|
583
|
+
* things to know. Conversation memory keeps only each turn's final text, so
|
|
584
|
+
* the thread still holds the tool calls and results that memory dropped: the
|
|
585
|
+
* model sees more than it would without a thread. And the thread outlives
|
|
586
|
+
* `clearConversationSession()`: NeuroLink forgets it, the server keeps it
|
|
587
|
+
* until it expires, up to an hour, and cannot be asked to delete it.
|
|
588
|
+
*/
|
|
589
|
+
messageThreads?: boolean | "session";
|
|
565
590
|
/** Max time with no progress before the turn ends as "stalled" (ms). Native Vertex loops only — see GenerateOptions.stallTimeoutMs. */
|
|
566
591
|
stallTimeoutMs?: number;
|
|
567
592
|
/** Remaining-time threshold that triggers the wrap-up nudge (ms). See GenerateOptions.wrapupTimeLeadMs. */
|
|
@@ -4822,6 +4822,8 @@
|
|
|
4822
4822
|
{"objectID":"7c0ca9930269015ceab0ba6b8a429bd7dbbfda29600c3f353bbef0249f0ff5fc","title":"Configuration","url":"/docs/getting-started/providers/anthropic#configuration","content":"Configuration","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Configuration","lvl3":""}},
|
|
4823
4823
|
{"objectID":"57cf0f7394ea15937bfa56393a1810810e6ac4f8b0ad606cd7884760e89b051d","title":"CLI Usage","url":"/docs/getting-started/providers/anthropic#cli-usage","content":"CLI Usage","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"CLI Usage","lvl3":""}},
|
|
4824
4824
|
{"objectID":"363647b336363b9f2e8dae713031aec7e297f0f0fa3799cec3280131890f6226","title":"Beta Features","url":"/docs/getting-started/providers/anthropic#beta-features","content":"The Anthropic provider supports beta features via the anthropic-beta header. The following beta headers are included by default when enableBetaFeatures is true:\nclaude-code-20250219 -- Claude Code specific features\ninterleaved-thinking-2025-05-14 -- Interleaved thinking mode\nfine-grained-tool-streaming-2025-05-14 -- Fine-grained tool streaming\n\nThese correspond to the AnthropicBetaFeature enum values in src/lib/constants/enums.ts:\n\nFor OAuth mode, the beta headers are different: oauth-2025-04-20 and interleaved-thinking-2025-05-14 are sent (the claude-code-20250219 header is only included if it was present in the original request headers, as it can trigger authorization errors with OAuth tokens).","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Beta Features","lvl3":""}},
|
|
4825
|
+
{"objectID":"e8a6ea83967bb6e1e6fe7208c5e1d1aa868e114173dca65e43938b6fddca5ae6","title":"Message threads (beta)","url":"/docs/getting-started/providers/anthropic#message-threads-beta","content":"A turn with tools makes several requests, and each one carries the whole conversation so far. With messageThreads: true the first request creates an Anthropic message thread. A later request sends only the messages since the last response, plus the previous response id, while nothing the thread fixes has changed; otherwise it sends the whole conversation as a new thread. It adds the message-threads-2026-08-12 beta header to those requests.\n\nWhat to know before turning it on:\nIt shrinks the request, it did not lower latency in a measurement. Against the Messages API, with prompt caching on in both modes, a tool turn's later requests went from about 79 KB to about 0.3 KB at 25k tokens of context, and from about 337 KB to about 0.3 KB at 110k tokens. Median time to first token was the same either way (672 vs 700 ms, and 739 vs 724 ms; one model, one network, no tools in the loop). The saving is bandwidth, not time.\nStreaming stream() turns on API-key auth only. generate(), other providers and OAuth (subscription) auth ignore the option.\nIt is best-effort and the conversation stays yours. The API keeps a thread in memory for a few minutes. If it cannot continue one (thread_not_found and similar), the same step is resent once in full as a new thread. If it cannot thread the request at all (thread_unsupported_request: HIPAA or inference-hook organisations, for example), that step and the rest of the turn go out unthreaded.\nAnything a thread fixes starts a new one. A change to the tools, the system prompt, the tool choice or the earlier messages (a context reclaim, for example) is sent as a new thread rather than a continue. A forced first-step tool choice therefore makes step 2 a new thread.\nA cut-off, refused or otherwise abnormal response is never continued from.\nRetention. Threads are not zero-data-retention eligible, there is no API to delete one, and each is deleted within an hour of its last use.","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Message threads (beta)","lvl3":""}},
|
|
4826
|
+
{"objectID":"34441eee0c40860138d19ffcfce73b82e33f0f9125ddee3f426680e1a095c687","title":"Across the calls of a session (messageThreads: \"session\")","url":"/docs/getting-started/providers/anthropic#across-the-calls-of-a-session-messagethreads-session","content":"\"session\" also keeps the thread for the session's next call, so that call sends only its new message instead of the whole history. The thread is found again by user (context.userId), session (context.sessionId), API key (hashed) and endpoint; it lives in memory on the NeuroLink instance for up to four minutes (the API drops an idle thread after five), and another process simply starts a new one. A call continues only if its model, tools, system prompt (without the \"you are continuing a conversation\" note NeuroLink appends once there is history) and tool choice are the same, and the history conversation memory rebuilt matches what the thread holds. Otherwise it is a new thread.\n\nThree things differ from the per-turn option, and the first two are the price of the feature:\nThe model sees more than the unthreaded path would. Conversation memory keeps only each turn's final text plus a one-line [called <tool> → ok] marker per call. The thread still holds the full tool calls and results from earlier turns, so after a tool turn a continued call has context a rebuilt-from-memory call does not. That is deliberate, and it is why this is a separate value rather than the default.\nThe thread outlives clearConversationSession(). NeuroLink forgets it, so the next call starts a new thread, but the server keeps the old one until it expires (up to an hour) and has no delete. It is not zero-data-retention eligible. There is no carve-out for the conversation-erasure write protocol: choose \"session\" only where that is acceptable.\nA continued call runs without the conversation note in its system prompt, since the thread already holds the history the note points at.","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Across the calls of a session (messageThreads: \"session\")","lvl3":""}},
|
|
4825
4827
|
{"objectID":"b11311c624dc33cf3ddb6888c5ff085a18e0ce089b0db5cdb15bd2ebe2b70bf7","title":"Multimodal Capabilities","url":"/docs/getting-started/providers/anthropic#multimodal-capabilities","content":"Claude models with vision support can analyze images.","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Multimodal Capabilities","lvl3":""}},
|
|
4826
4828
|
{"objectID":"b9d325e6a6e5e5934dc6e4662fa16de4b606dfc6e2184e7a41dc7e60d4d59fe8","title":"Image Analysis","url":"/docs/getting-started/providers/anthropic#image-analysis","content":"Image Analysis","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"Image Analysis","lvl3":""}},
|
|
4827
4829
|
{"objectID":"173aa07da1c648c3a005ea3cd6bcee2016d7a2fa4401ea8cdfe440615545abe3","title":"PDF Processing","url":"/docs/getting-started/providers/anthropic#pdf-processing","content":"PDF Processing","hierarchy":{"lvl0":"Getting Started","lvl1":"Anthropic Provider Guide","lvl2":"PDF Processing","lvl3":""}},
|