@juspay/neurolink 13.10.5 → 13.11.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 +7 -2
- package/dist/agent/agent.js +7 -6
- package/dist/browser/neurolink.min.js +429 -429
- package/dist/core/nativeGenerateLoop.js +241 -3
- package/dist/providers/anthropic/client.d.ts +8 -0
- package/dist/providers/anthropic/client.js +20 -0
- package/dist/providers/anthropic/loopAdapter.js +86 -41
- package/dist/providers/anthropic/threads.d.ts +43 -0
- package/dist/providers/anthropic/threads.js +200 -0
- package/dist/server/routes/claudeProxyRoutes.js +19 -1
- package/dist/types/generate.d.ts +10 -0
- package/dist/types/loopEngine.d.ts +41 -0
- package/dist/types/stream.d.ts +16 -0
- package/docs-site/static/search-index.json +1 -0
- package/package.json +8 -6
|
@@ -369,6 +369,219 @@ function declaredInputSchema(name, tool) {
|
|
|
369
369
|
return empty;
|
|
370
370
|
}
|
|
371
371
|
}
|
|
372
|
+
/**
|
|
373
|
+
* A copy of `input` where each value Zod rejected as "expected date" and that
|
|
374
|
+
* is an ISO-8601 date or date-time string has become a `Date`; undefined when
|
|
375
|
+
* there is nothing to convert. The input itself is never mutated.
|
|
376
|
+
*/
|
|
377
|
+
const ISO_DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;
|
|
378
|
+
/** The Date for an ISO-8601 date or date-time string; undefined for anything else, including 2026-02-31. */
|
|
379
|
+
const parseIsoDate = (value) => {
|
|
380
|
+
if (typeof value !== "string") {
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
383
|
+
const match = ISO_DATE_STRING.exec(value);
|
|
384
|
+
if (match === null) {
|
|
385
|
+
return undefined;
|
|
386
|
+
}
|
|
387
|
+
// Date.parse rolls an impossible day over (2026-02-31 becomes March 3), which
|
|
388
|
+
// would hand the tool a date the model never named. Check the calendar day.
|
|
389
|
+
const [, year, month, day] = match;
|
|
390
|
+
// setUTCFullYear, not Date.UTC: Date.UTC reads years 0-99 as 1900-1999.
|
|
391
|
+
const probe = new Date(0);
|
|
392
|
+
probe.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
|
|
393
|
+
if (probe.getUTCFullYear() !== Number(year) ||
|
|
394
|
+
probe.getUTCMonth() !== Number(month) - 1 ||
|
|
395
|
+
probe.getUTCDate() !== Number(day)) {
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
const time = Date.parse(value);
|
|
399
|
+
return Number.isNaN(time) ? undefined : new Date(time);
|
|
400
|
+
};
|
|
401
|
+
/**
|
|
402
|
+
* The ways to read a failed validation as "these strings were meant as dates".
|
|
403
|
+
* Each candidate is a set of positions to convert together. Positions outside
|
|
404
|
+
* any union are in every candidate; a union contributes one alternative per
|
|
405
|
+
* branch, so a branch that wants a date in one field is tried without the dates
|
|
406
|
+
* the other branches wanted elsewhere.
|
|
407
|
+
*
|
|
408
|
+
* A union failure is one issue with each branch's issues nested. Zod 4 puts
|
|
409
|
+
* them in `errors` with paths relative to the union's; Zod 3 puts them in
|
|
410
|
+
* `unionErrors[].issues` with absolute paths.
|
|
411
|
+
*/
|
|
412
|
+
const valueAt = (input, path) => {
|
|
413
|
+
let cursor = input;
|
|
414
|
+
for (const key of path) {
|
|
415
|
+
cursor = cursor?.[key];
|
|
416
|
+
}
|
|
417
|
+
return cursor;
|
|
418
|
+
};
|
|
419
|
+
const dateCandidates = (issues, base, input) => {
|
|
420
|
+
let candidates = [[]];
|
|
421
|
+
if (!Array.isArray(issues)) {
|
|
422
|
+
return candidates;
|
|
423
|
+
}
|
|
424
|
+
for (const issue of issues) {
|
|
425
|
+
if (!Array.isArray(issue.path)) {
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
const path = [...base, ...issue.path];
|
|
429
|
+
let alternatives;
|
|
430
|
+
if (issue.code === "invalid_type" && issue.expected === "date") {
|
|
431
|
+
// A position that holds nothing convertible is left to fail as it did.
|
|
432
|
+
const value = valueAt(input, path);
|
|
433
|
+
if (Array.isArray(value)) {
|
|
434
|
+
// A set reached through a preprocess is reported at the field with the
|
|
435
|
+
// array as its value: convert its date strings member by member. The
|
|
436
|
+
// reading that converts every one is tried first; then, for up to
|
|
437
|
+
// eight members, one that leaves a member as the string it was, since
|
|
438
|
+
// the schema may accept a literal that merely looks like a date.
|
|
439
|
+
const members = value
|
|
440
|
+
.map((v, i) => (parseIsoDate(v) !== undefined ? i : -1))
|
|
441
|
+
.filter((i) => i >= 0);
|
|
442
|
+
if (members.length > 0) {
|
|
443
|
+
// The reading that converts every member comes first. Then, over the
|
|
444
|
+
// first six members, every smaller subset (largest first), so any
|
|
445
|
+
// number of date-shaped literals can be left as the strings they
|
|
446
|
+
// were: the schema may accept a literal that merely looks like a date.
|
|
447
|
+
const head = members.slice(0, 6);
|
|
448
|
+
const subsets = [];
|
|
449
|
+
for (let mask = (1 << head.length) - 2; mask > 0; mask--) {
|
|
450
|
+
subsets.push(head.filter((_, bit) => (mask >> bit) & 1));
|
|
451
|
+
}
|
|
452
|
+
subsets.sort((x, y) => y.length - x.length);
|
|
453
|
+
alternatives = [
|
|
454
|
+
members.map((i) => [...path, i]),
|
|
455
|
+
...subsets.map((subset) => [...subset, ...members.slice(6)].map((i) => [...path, i])),
|
|
456
|
+
];
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
else if (parseIsoDate(value) !== undefined) {
|
|
460
|
+
alternatives = [[path]];
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
else if (issue.code === "invalid_union") {
|
|
464
|
+
const branches = [];
|
|
465
|
+
if (Array.isArray(issue.errors)) {
|
|
466
|
+
for (const branch of issue.errors) {
|
|
467
|
+
branches.push(dateCandidates(branch, path, input));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
if (Array.isArray(issue.unionErrors)) {
|
|
471
|
+
for (const e of issue.unionErrors) {
|
|
472
|
+
branches.push(dateCandidates(e?.issues, [], input));
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
// Alternatives are the branches' own candidates, those that convert
|
|
476
|
+
// something; a union with none contributes nothing.
|
|
477
|
+
const useful = branches
|
|
478
|
+
.flat()
|
|
479
|
+
.filter((candidate) => candidate.length > 0);
|
|
480
|
+
if (useful.length > 0) {
|
|
481
|
+
alternatives = useful;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (alternatives !== undefined) {
|
|
485
|
+
const next = [];
|
|
486
|
+
for (const have of candidates) {
|
|
487
|
+
for (const add of alternatives) {
|
|
488
|
+
next.push([...have, ...add]);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
// Bounded: a schema with many unions must not multiply without limit.
|
|
492
|
+
// Only alternatives that can apply to this input got here, so the cap
|
|
493
|
+
// never drops the one conversion that would have worked.
|
|
494
|
+
candidates = next.slice(0, 512);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return candidates;
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* A copy of `input` with the string at each position converted, or undefined
|
|
501
|
+
* if any position holds something that is not a date string. Only the
|
|
502
|
+
* containers on the way to a converted value are copied: everything else is
|
|
503
|
+
* shared with `input`, so a class instance elsewhere in it keeps its prototype
|
|
504
|
+
* and nothing uncloneable is ever cloned.
|
|
505
|
+
*/
|
|
506
|
+
const applyDateConversions = (input, positions) => {
|
|
507
|
+
const rewrite = (node, rest) => {
|
|
508
|
+
// Positions that end here are converted; the others descend by their key.
|
|
509
|
+
const here = rest.find((path) => path.length === 0);
|
|
510
|
+
if (here !== undefined) {
|
|
511
|
+
return parseIsoDate(node);
|
|
512
|
+
}
|
|
513
|
+
if (node === null || typeof node !== "object") {
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
const byKey = new Map();
|
|
517
|
+
for (const path of rest) {
|
|
518
|
+
const [key, ...tail] = path;
|
|
519
|
+
byKey.set(key, [...(byKey.get(key) ?? []), tail]);
|
|
520
|
+
}
|
|
521
|
+
const replacements = new Map();
|
|
522
|
+
for (const [key, tails] of byKey) {
|
|
523
|
+
const replaced = rewrite(node[key], tails);
|
|
524
|
+
if (replaced === undefined) {
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
replacements.set(key, replaced);
|
|
528
|
+
}
|
|
529
|
+
if (Array.isArray(node)) {
|
|
530
|
+
const copy = Array.prototype.slice.call(node);
|
|
531
|
+
for (const [key, value] of replacements) {
|
|
532
|
+
copy[key] = value;
|
|
533
|
+
}
|
|
534
|
+
return copy;
|
|
535
|
+
}
|
|
536
|
+
// Own property descriptors, not Object.assign: assigning would run every
|
|
537
|
+
// getter on the object, including ones outside the schema that throw. The
|
|
538
|
+
// converted properties are written into the descriptors before anything is
|
|
539
|
+
// defined, so a frozen or non-writable original is never redefined.
|
|
540
|
+
const descriptors = Object.getOwnPropertyDescriptors(node);
|
|
541
|
+
for (const [key, value] of replacements) {
|
|
542
|
+
descriptors[key] = {
|
|
543
|
+
value,
|
|
544
|
+
writable: true,
|
|
545
|
+
enumerable: true,
|
|
546
|
+
configurable: true,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
const proto = Object.getPrototypeOf(node);
|
|
550
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
551
|
+
// A class instance may keep state in private fields, which a copy made
|
|
552
|
+
// with Object.create would not have. A proxy keeps the original as the
|
|
553
|
+
// receiver for everything except the converted properties.
|
|
554
|
+
return new Proxy(node, {
|
|
555
|
+
get: (target, key) => {
|
|
556
|
+
if (replacements.has(key)) {
|
|
557
|
+
return replacements.get(key);
|
|
558
|
+
}
|
|
559
|
+
const value = Reflect.get(target, key, target);
|
|
560
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
561
|
+
},
|
|
562
|
+
has: (target, key) => replacements.has(key) || Reflect.has(target, key),
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
return Object.defineProperties(Object.create(Object.getPrototypeOf(node)), descriptors);
|
|
566
|
+
};
|
|
567
|
+
return positions.length === 0 ? undefined : rewrite(input, positions);
|
|
568
|
+
};
|
|
569
|
+
/**
|
|
570
|
+
* The inputs worth validating again after a failure: for each way of reading
|
|
571
|
+
* the issues as dates, the input with those strings converted. Empty when no
|
|
572
|
+
* reading applies.
|
|
573
|
+
*/
|
|
574
|
+
const reviveDateStrings = (input, error) => {
|
|
575
|
+
const issues = error?.issues;
|
|
576
|
+
const out = [];
|
|
577
|
+
for (const positions of dateCandidates(issues, [], input)) {
|
|
578
|
+
const revived = applyDateConversions(input, positions);
|
|
579
|
+
if (revived !== undefined) {
|
|
580
|
+
out.push(revived);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return out;
|
|
584
|
+
};
|
|
372
585
|
/**
|
|
373
586
|
* Validate parsed input against the tool's own schema when it exposes one.
|
|
374
587
|
*
|
|
@@ -390,9 +603,34 @@ export const validateToolInput = async (tool, input) => {
|
|
|
390
603
|
typeof schema.safeParse !== "function") {
|
|
391
604
|
return { input };
|
|
392
605
|
}
|
|
393
|
-
const
|
|
394
|
-
? await schema.safeParseAsync(
|
|
395
|
-
: schema.safeParse(
|
|
606
|
+
const parse = async (value) => "safeParseAsync" in schema && typeof schema.safeParseAsync === "function"
|
|
607
|
+
? await schema.safeParseAsync(value)
|
|
608
|
+
: schema.safeParse(value);
|
|
609
|
+
let result = await parse(input);
|
|
610
|
+
if (!result.success) {
|
|
611
|
+
// The wire schema describes z.date() as a date-time string (JSON has no
|
|
612
|
+
// Date), so a model sends a string and a plain z.date() rejects it. Turn
|
|
613
|
+
// exactly the strings Zod named as "expected date" into Dates and
|
|
614
|
+
// validate again; every other mismatch is left to fail as before.
|
|
615
|
+
// Each reading of the failure is tried; the first that validates wins.
|
|
616
|
+
// When none does, the last retry's error is reported, so a date that
|
|
617
|
+
// parses but breaks `.min()` says so rather than repeating "expected
|
|
618
|
+
// date" and inviting the same value again.
|
|
619
|
+
for (const revived of reviveDateStrings(input, result.error)) {
|
|
620
|
+
try {
|
|
621
|
+
const retry = await parse(revived);
|
|
622
|
+
result = retry;
|
|
623
|
+
if (retry.success) {
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
// A branch that cannot take this reading (a refinement that throws
|
|
629
|
+
// on a Date) must not stop the readings that follow it.
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
396
634
|
if (result.success) {
|
|
397
635
|
return { input: result.data };
|
|
398
636
|
}
|
|
@@ -36,6 +36,14 @@ export declare class AnthropicProvider extends BaseProvider {
|
|
|
36
36
|
oauthToken?: string;
|
|
37
37
|
baseURL?: string;
|
|
38
38
|
});
|
|
39
|
+
/**
|
|
40
|
+
* The thread state for this turn, or undefined when message threads (beta)
|
|
41
|
+
* were not asked for. Opt-in per call (`StreamOptions.messageThreads`) and
|
|
42
|
+
* limited to API-key auth, because the subscription (OAuth) path rewrites
|
|
43
|
+
* beta headers in its own fetch wrapper, which has not been checked against
|
|
44
|
+
* the thread beta.
|
|
45
|
+
*/
|
|
46
|
+
private createMessageThreadSession;
|
|
39
47
|
/**
|
|
40
48
|
* Get authentication headers based on current auth method and configuration.
|
|
41
49
|
*
|
|
@@ -23,6 +23,7 @@ import { redactUrlCredentials } from "../../utils/logSanitize.js";
|
|
|
23
23
|
import { ANTHROPIC_MAX_CACHE_BREAKPOINTS, applyAnthropicHistoryCacheBreakpoints, countAnthropicCacheMarkers, } from "../../utils/anthropicCacheBreakpoints.js";
|
|
24
24
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
25
25
|
import { createAnthropicLoopAdapter } from "./loopAdapter.js";
|
|
26
|
+
import { createAnthropicThreadSession } from "./threads.js";
|
|
26
27
|
import { DEFAULT_BEFORE_STEP_TIMEOUT_MS } from "../../utils/parameterValidation.js";
|
|
27
28
|
import { runAgenticLoop } from "../../core/loopEngine.js";
|
|
28
29
|
import { hasNativeDoGenerate, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, } from "../../core/nativeGenerateLoop.js";
|
|
@@ -700,6 +701,23 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
700
701
|
: "disabled",
|
|
701
702
|
});
|
|
702
703
|
}
|
|
704
|
+
/**
|
|
705
|
+
* The thread state for this turn, or undefined when message threads (beta)
|
|
706
|
+
* were not asked for. Opt-in per call (`StreamOptions.messageThreads`) and
|
|
707
|
+
* limited to API-key auth, because the subscription (OAuth) path rewrites
|
|
708
|
+
* beta headers in its own fetch wrapper, which has not been checked against
|
|
709
|
+
* the thread beta.
|
|
710
|
+
*/
|
|
711
|
+
createMessageThreadSession(options) {
|
|
712
|
+
if (options.messageThreads !== true) {
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
if (this.authMethod !== "api_key") {
|
|
716
|
+
logger.debug("[anthropic] messageThreads requested but not used: it needs API-key auth", { authMethod: this.authMethod });
|
|
717
|
+
return undefined;
|
|
718
|
+
}
|
|
719
|
+
return createAnthropicThreadSession(this.getAuthHeaders()["anthropic-beta"]);
|
|
720
|
+
}
|
|
703
721
|
/**
|
|
704
722
|
* Get authentication headers based on current auth method and configuration.
|
|
705
723
|
*
|
|
@@ -2029,10 +2047,12 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2029
2047
|
...(thinking ? { thinking } : {}),
|
|
2030
2048
|
};
|
|
2031
2049
|
};
|
|
2050
|
+
const messageThreads = this.createMessageThreadSession(options);
|
|
2032
2051
|
const baseAdapter = createAnthropicLoopAdapter({
|
|
2033
2052
|
client,
|
|
2034
2053
|
provider: this.providerName,
|
|
2035
2054
|
maxSteps,
|
|
2055
|
+
...(messageThreads ? { threads: messageThreads } : {}),
|
|
2036
2056
|
toolsRecord,
|
|
2037
2057
|
buildParams,
|
|
2038
2058
|
planReclaim,
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
import { resolveDeferredTool } from "../../tools/toolDiscovery.js";
|
|
25
25
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
26
26
|
import { stringifyFinalResultInput } from "./structuredOutput.js";
|
|
27
|
+
import { settleThread, threadRecovery } from "./threads.js";
|
|
27
28
|
import { composeAbortSignalsScoped, createTimeoutController, } from "../../utils/timeout.js";
|
|
28
29
|
import { sanitizeAnthropicMessagesForTrace } from "../../utils/anthropicTraceSanitizer.js";
|
|
29
30
|
import { NeuroLinkError } from "../../utils/errorHandling.js";
|
|
@@ -49,7 +50,7 @@ function mapAnthropicFinishReason(rawStopReason, hadToolCallsAtCap) {
|
|
|
49
50
|
* `executeStep` above it is now only the per-request deadline wiring, which is
|
|
50
51
|
* the part a reader looking for "what bounds this request" needs to find.
|
|
51
52
|
*/
|
|
52
|
-
async function readAnthropicStep({ params, client, channel, stepSignal, requestTimeoutSignal, noteObservedPromptTokens, finalResultToolName, onTerminalResult, requireTerminalEvent, }) {
|
|
53
|
+
async function readAnthropicStep({ params, client, channel, stepSignal, requestTimeoutSignal, noteObservedPromptTokens, finalResultToolName, onTerminalResult, requireTerminalEvent, threads, requestHeaders, }) {
|
|
53
54
|
// Single assertion, not a double: `messages.create` returns a union of
|
|
54
55
|
// Message and Stream, and Stream<RawMessageStreamEvent> already IS an
|
|
55
56
|
// AsyncIterable of that event, so the two types overlap and the
|
|
@@ -59,7 +60,10 @@ async function readAnthropicStep({ params, client, channel, stepSignal, requestT
|
|
|
59
60
|
// runAgenticLoop already derives the engine signal from the caller's
|
|
60
61
|
// abortSignal, so preferring config's would ignore engine-initiated
|
|
61
62
|
// cancellation entirely.
|
|
62
|
-
{
|
|
63
|
+
{
|
|
64
|
+
signal: stepSignal,
|
|
65
|
+
...(requestHeaders ? { headers: requestHeaders } : {}),
|
|
66
|
+
}));
|
|
63
67
|
const textByIndex = new Map();
|
|
64
68
|
const toolByIndex = new Map();
|
|
65
69
|
const thinkingByIndex = new Map();
|
|
@@ -88,6 +92,7 @@ async function readAnthropicStep({ params, client, channel, stepSignal, requestT
|
|
|
88
92
|
// content blocks that DID arrive are syntactically complete.
|
|
89
93
|
let sawTerminalEvent = false;
|
|
90
94
|
let responseModel;
|
|
95
|
+
let messageId;
|
|
91
96
|
for await (const rawEvent of events) {
|
|
92
97
|
if (stepSignal.aborted) {
|
|
93
98
|
break;
|
|
@@ -98,6 +103,7 @@ async function readAnthropicStep({ params, client, channel, stepSignal, requestT
|
|
|
98
103
|
// asserted.
|
|
99
104
|
const event = rawEvent;
|
|
100
105
|
if (event.type === "message_start") {
|
|
106
|
+
messageId = event.message?.id ?? messageId;
|
|
101
107
|
responseModel = event.message?.model ?? responseModel;
|
|
102
108
|
const usage = event.message?.usage;
|
|
103
109
|
inputTokens += usage?.input_tokens ?? 0;
|
|
@@ -232,6 +238,13 @@ async function readAnthropicStep({ params, client, channel, stepSignal, requestT
|
|
|
232
238
|
context: { provider: "anthropic", rawStopReason },
|
|
233
239
|
});
|
|
234
240
|
}
|
|
241
|
+
if (threads) {
|
|
242
|
+
settleThread(threads, {
|
|
243
|
+
sawTerminalEvent,
|
|
244
|
+
messageId,
|
|
245
|
+
stopReason: rawStopReason,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
235
248
|
// JSON.parse happily yields null, an array or a primitive, and an
|
|
236
249
|
// assertion converts none of them. Both `tool_use.input` and
|
|
237
250
|
// AgenticLoopToolCall.args require an object, so anything else becomes
|
|
@@ -414,46 +427,78 @@ export function createAnthropicLoopAdapter(config) {
|
|
|
414
427
|
},
|
|
415
428
|
async executeStep(request, channel, signal) {
|
|
416
429
|
const params = request.raw;
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
:
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
430
|
+
const runStep = async (stepParams, threadPlan) => {
|
|
431
|
+
// Per-REQUEST deadline, armed fresh for this step and disposed the moment
|
|
432
|
+
// it settles. Being armed per step is what makes it unresettable from a
|
|
433
|
+
// step boundary: the boundary runs between two steps, when no request
|
|
434
|
+
// deadline is running at all.
|
|
435
|
+
//
|
|
436
|
+
// Scoped composition rather than AbortSignal.any: the engine signal lives
|
|
437
|
+
// for the whole turn, and `any` keeps its registration on that signal
|
|
438
|
+
// until the derived one is collected, so composing per step accumulates
|
|
439
|
+
// listeners for the turn's whole length.
|
|
440
|
+
const requestTimeout = config.requestTimeoutMs
|
|
441
|
+
? createTimeoutController(config.requestTimeoutMs, "anthropic", "stream")
|
|
442
|
+
: null;
|
|
443
|
+
const composed = composeAbortSignalsScoped(signal, requestTimeout?.controller.signal);
|
|
444
|
+
try {
|
|
445
|
+
return await readAnthropicStep({
|
|
446
|
+
params: stepParams,
|
|
447
|
+
...(threadPlan
|
|
448
|
+
? { threads: config.threads, requestHeaders: threadPlan.headers }
|
|
449
|
+
: {}),
|
|
450
|
+
client: config.client,
|
|
451
|
+
channel,
|
|
452
|
+
// The engine's signal, not config's: runAgenticLoop already derives
|
|
453
|
+
// it from the caller's abortSignal, so preferring config's would
|
|
454
|
+
// ignore engine-initiated cancellation entirely.
|
|
455
|
+
stepSignal: composed.signal ?? signal,
|
|
456
|
+
requestTimeoutSignal: requestTimeout?.controller.signal,
|
|
457
|
+
...(config.noteObservedPromptTokens
|
|
458
|
+
? { noteObservedPromptTokens: config.noteObservedPromptTokens }
|
|
459
|
+
: {}),
|
|
460
|
+
...(config.finalResultToolName
|
|
461
|
+
? { finalResultToolName: config.finalResultToolName }
|
|
462
|
+
: {}),
|
|
463
|
+
...(config.onTerminalResult
|
|
464
|
+
? { onTerminalResult: config.onTerminalResult }
|
|
465
|
+
: {}),
|
|
466
|
+
...(config.requireTerminalEvent
|
|
467
|
+
? { requireTerminalEvent: config.requireTerminalEvent }
|
|
468
|
+
: {}),
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
finally {
|
|
472
|
+
composed.dispose();
|
|
473
|
+
requestTimeout?.cleanup();
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
const threads = config.threads;
|
|
477
|
+
if (!threads?.enabled) {
|
|
478
|
+
return runStep(params);
|
|
453
479
|
}
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
480
|
+
// A thread step goes out as a create or a continue. When the API cannot
|
|
481
|
+
// continue it, or cannot thread the request at all, the same step is
|
|
482
|
+
// sent once more in full; any other failure just ends the thread, so the
|
|
483
|
+
// next step starts a new one.
|
|
484
|
+
let plan = threads.plan(params);
|
|
485
|
+
for (let attempt = 0;; attempt++) {
|
|
486
|
+
try {
|
|
487
|
+
return await runStep(plan.params, plan);
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
threads.reset();
|
|
491
|
+
const recovery = attempt === 0 ? threadRecovery(error) : undefined;
|
|
492
|
+
if (recovery === "recreate") {
|
|
493
|
+
plan = threads.plan(params);
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
if (recovery === "unthreaded") {
|
|
497
|
+
threads.disable();
|
|
498
|
+
return runStep(params);
|
|
499
|
+
}
|
|
500
|
+
throw error;
|
|
501
|
+
}
|
|
457
502
|
}
|
|
458
503
|
},
|
|
459
504
|
appendPlanningNudge(conversation, text) {
|
|
@@ -0,0 +1,43 @@
|
|
|
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 type { AnthropicThreadSession } from "../../types/index.js";
|
|
19
|
+
export declare const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
20
|
+
/**
|
|
21
|
+
* Record how a step's response ended. The API stores a thread turn only when
|
|
22
|
+
* the response ended normally; a refusal, a cut-off or an early end is resent
|
|
23
|
+
* in full by the next step.
|
|
24
|
+
*/
|
|
25
|
+
export declare function settleThread(session: AnthropicThreadSession, response: {
|
|
26
|
+
sawTerminalEvent: boolean;
|
|
27
|
+
messageId: string | undefined;
|
|
28
|
+
stopReason: string | undefined;
|
|
29
|
+
}): void;
|
|
30
|
+
/**
|
|
31
|
+
* Start the thread state for one turn.
|
|
32
|
+
*
|
|
33
|
+
* @param betaHeader the `anthropic-beta` value the client already sends; the
|
|
34
|
+
* thread beta is added to it, identically on every request of the thread.
|
|
35
|
+
*/
|
|
36
|
+
export declare function createAnthropicThreadSession(betaHeader: string | undefined): AnthropicThreadSession;
|
|
37
|
+
/** The API's `error.details.error_code` for a thread request that was refused, if there is one. */
|
|
38
|
+
export declare function threadErrorCode(error: unknown): string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* What to do after a thread request fails: send everything again as a new
|
|
41
|
+
* thread, send it without a thread at all, or neither (an ordinary error).
|
|
42
|
+
*/
|
|
43
|
+
export declare function threadRecovery(error: unknown): "recreate" | "unthreaded" | undefined;
|