@librechat/agents 4.0.5 → 4.1.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/dist/cjs/agents/AgentContext.cjs +6 -4
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/decisions/breaker.cjs +59 -0
- package/dist/cjs/decisions/breaker.cjs.map +1 -0
- package/dist/cjs/decisions/core.cjs +44 -0
- package/dist/cjs/decisions/dialect.cjs +65 -12
- package/dist/cjs/decisions/dialect.cjs.map +1 -1
- package/dist/cjs/decisions/hook.cjs +19 -0
- package/dist/cjs/decisions/hook.cjs.map +1 -0
- package/dist/cjs/decisions/http.cjs +2 -1
- package/dist/cjs/decisions/http.cjs.map +1 -1
- package/dist/cjs/decisions/index.cjs +6 -0
- package/dist/cjs/decisions/node.cjs +315 -0
- package/dist/cjs/decisions/node.cjs.map +1 -0
- package/dist/cjs/decisions/probe.cjs +56 -0
- package/dist/cjs/decisions/probe.cjs.map +1 -0
- package/dist/cjs/decisions/redact.cjs +109 -0
- package/dist/cjs/decisions/redact.cjs.map +1 -0
- package/dist/cjs/decisions/structuredChat.cjs +2 -3
- package/dist/cjs/decisions/structuredChat.cjs.map +1 -1
- package/dist/cjs/decisions/transport.cjs +56 -23
- package/dist/cjs/decisions/transport.cjs.map +1 -1
- package/dist/cjs/decisions/types.cjs +2 -0
- package/dist/cjs/decisions/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +7 -6
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
- package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +8 -5
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +8 -2
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/main.cjs +45 -0
- package/dist/cjs/rerank/bm25.cjs +110 -0
- package/dist/cjs/rerank/bm25.cjs.map +1 -0
- package/dist/cjs/rerank/cache.cjs +50 -0
- package/dist/cjs/rerank/cache.cjs.map +1 -0
- package/dist/cjs/rerank/core.cjs +29 -0
- package/dist/cjs/rerank/crossEncoder.cjs +172 -0
- package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
- package/dist/cjs/rerank/fallback.cjs +280 -0
- package/dist/cjs/rerank/fallback.cjs.map +1 -0
- package/dist/cjs/rerank/index.cjs +8 -0
- package/dist/cjs/rerank/outcome.cjs +382 -0
- package/dist/cjs/rerank/outcome.cjs.map +1 -0
- package/dist/cjs/rerank/pin.cjs +74 -0
- package/dist/cjs/rerank/pin.cjs.map +1 -0
- package/dist/cjs/rerank/semaphore.cjs +38 -0
- package/dist/cjs/rerank/semaphore.cjs.map +1 -0
- package/dist/cjs/rerank/systemone.cjs +476 -50
- package/dist/cjs/rerank/systemone.cjs.map +1 -1
- package/dist/cjs/session/AgentSession.cjs +1 -1
- package/dist/cjs/session/AgentSession.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
- package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
- package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
- package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
- package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
- package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
- package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +7 -5
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/decisions/breaker.mjs +56 -0
- package/dist/esm/decisions/breaker.mjs.map +1 -0
- package/dist/esm/decisions/core.mjs +11 -0
- package/dist/esm/decisions/dialect.mjs +65 -12
- package/dist/esm/decisions/dialect.mjs.map +1 -1
- package/dist/esm/decisions/hook.mjs +19 -0
- package/dist/esm/decisions/hook.mjs.map +1 -0
- package/dist/esm/decisions/http.mjs +2 -1
- package/dist/esm/decisions/http.mjs.map +1 -1
- package/dist/esm/decisions/index.mjs +6 -0
- package/dist/esm/decisions/node.mjs +313 -0
- package/dist/esm/decisions/node.mjs.map +1 -0
- package/dist/esm/decisions/probe.mjs +54 -0
- package/dist/esm/decisions/probe.mjs.map +1 -0
- package/dist/esm/decisions/redact.mjs +108 -0
- package/dist/esm/decisions/redact.mjs.map +1 -0
- package/dist/esm/decisions/structuredChat.mjs +2 -3
- package/dist/esm/decisions/structuredChat.mjs.map +1 -1
- package/dist/esm/decisions/transport.mjs +56 -23
- package/dist/esm/decisions/transport.mjs.map +1 -1
- package/dist/esm/decisions/types.mjs +2 -0
- package/dist/esm/decisions/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +7 -7
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
- package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +7 -4
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +2 -2
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +8 -3
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/main.mjs +15 -3
- package/dist/esm/rerank/bm25.mjs +108 -0
- package/dist/esm/rerank/bm25.mjs.map +1 -0
- package/dist/esm/rerank/cache.mjs +50 -0
- package/dist/esm/rerank/cache.mjs.map +1 -0
- package/dist/esm/rerank/core.mjs +9 -0
- package/dist/esm/rerank/crossEncoder.mjs +172 -0
- package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
- package/dist/esm/rerank/fallback.mjs +278 -0
- package/dist/esm/rerank/fallback.mjs.map +1 -0
- package/dist/esm/rerank/index.mjs +8 -0
- package/dist/esm/rerank/outcome.mjs +360 -0
- package/dist/esm/rerank/outcome.mjs.map +1 -0
- package/dist/esm/rerank/pin.mjs +73 -0
- package/dist/esm/rerank/pin.mjs.map +1 -0
- package/dist/esm/rerank/semaphore.mjs +38 -0
- package/dist/esm/rerank/semaphore.mjs.map +1 -0
- package/dist/esm/rerank/systemone.mjs +476 -50
- package/dist/esm/rerank/systemone.mjs.map +1 -1
- package/dist/esm/session/AgentSession.mjs +1 -1
- package/dist/esm/session/AgentSession.mjs.map +1 -1
- package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
- package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
- package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
- package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
- package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
- package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
- package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
- package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
- package/dist/types/decisions/breaker.d.ts +37 -0
- package/dist/types/decisions/core.d.ts +19 -0
- package/dist/types/decisions/hook.d.ts +9 -0
- package/dist/types/decisions/index.d.ts +3 -8
- package/dist/types/decisions/node.d.ts +90 -0
- package/dist/types/decisions/probe.d.ts +37 -0
- package/dist/types/decisions/redact.d.ts +22 -0
- package/dist/types/decisions/structuredChat.d.ts +1 -0
- package/dist/types/decisions/transport.d.ts +16 -3
- package/dist/types/decisions/types.d.ts +43 -4
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
- package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
- package/dist/types/llm/bedrock/index.d.ts +2 -1
- package/dist/types/llm/google/index.d.ts +1 -0
- package/dist/types/llm/google/utils/common.d.ts +2 -0
- package/dist/types/rerank/bm25.d.ts +46 -0
- package/dist/types/rerank/cache.d.ts +40 -0
- package/dist/types/rerank/core.d.ts +24 -0
- package/dist/types/rerank/crossEncoder.d.ts +48 -0
- package/dist/types/rerank/fallback.d.ts +67 -0
- package/dist/types/rerank/index.d.ts +1 -3
- package/dist/types/rerank/outcome.d.ts +144 -0
- package/dist/types/rerank/pin.d.ts +48 -0
- package/dist/types/rerank/semaphore.d.ts +9 -0
- package/dist/types/rerank/systemone.d.ts +51 -5
- package/dist/types/rerank/types.d.ts +116 -1
- package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
- package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
- package/dist/types/types/tools.d.ts +16 -0
- package/package.json +26 -1
- package/src/agents/AgentContext.ts +33 -4
- package/src/decisions/breaker.ts +110 -0
- package/src/decisions/core.ts +23 -0
- package/src/decisions/dialect.ts +134 -20
- package/src/decisions/hook.ts +32 -0
- package/src/decisions/http.ts +4 -1
- package/src/decisions/index.ts +3 -12
- package/src/decisions/node.ts +671 -0
- package/src/decisions/probe.ts +114 -0
- package/src/decisions/redact.ts +222 -0
- package/src/decisions/structuredChat.ts +6 -8
- package/src/decisions/transport.ts +104 -22
- package/src/decisions/types.ts +46 -5
- package/src/llm/anthropic/utils/message_inputs.ts +16 -16
- package/src/llm/bedrock/cachePoints.ts +47 -0
- package/src/llm/bedrock/index.ts +35 -13
- package/src/llm/google/index.ts +5 -3
- package/src/llm/google/utils/common.ts +19 -5
- package/src/rerank/bm25.ts +190 -0
- package/src/rerank/cache.ts +103 -0
- package/src/rerank/core.ts +47 -0
- package/src/rerank/crossEncoder.ts +289 -0
- package/src/rerank/fallback.ts +625 -0
- package/src/rerank/index.ts +1 -3
- package/src/rerank/outcome.ts +767 -0
- package/src/rerank/pin.ts +157 -0
- package/src/rerank/semaphore.ts +47 -0
- package/src/rerank/systemone.ts +914 -88
- package/src/rerank/types.ts +143 -1
- package/src/session/AgentSession.ts +3 -1
- package/src/tools/local/LocalCodingTools.ts +139 -19
- package/src/tools/local/LocalExecutionTools.ts +21 -1
- package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
- package/src/tools/local/toolResultCaps.ts +60 -0
- package/src/types/tools.ts +16 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { DecisionModel, DecisionFailure, DecisionRequest } from './types';
|
|
2
|
+
import { withDecisionDeadline } from './deadline';
|
|
3
|
+
import { booleanQuestion } from './questions';
|
|
4
|
+
import { redactExcerpt } from './redact';
|
|
5
|
+
import { DecisionError } from './types';
|
|
6
|
+
|
|
7
|
+
const DETAIL_LIMIT = 200;
|
|
8
|
+
const PROBE_FAILED = 'decision model probe failed';
|
|
9
|
+
/** How long a probe without `timeoutMs` waits for a model that never settles. */
|
|
10
|
+
export const PROBE_MAX_WAIT_MS = 60_000;
|
|
11
|
+
|
|
12
|
+
export type DecisionProbe =
|
|
13
|
+
| { ok: true; model: string }
|
|
14
|
+
| {
|
|
15
|
+
ok: false;
|
|
16
|
+
failure: DecisionFailure;
|
|
17
|
+
status?: number;
|
|
18
|
+
circuitOpen: boolean;
|
|
19
|
+
/** Redacted, whitespace-collapsed, and truncated; safe for a log line or a status row. */
|
|
20
|
+
detail: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface DecisionProbeOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Passed to the model and enforced around its call, so a model that ignores
|
|
26
|
+
* it still settles; allow for a slow first token mint. Without it the model
|
|
27
|
+
* keeps its own timeout and the wait is bounded at `PROBE_MAX_WAIT_MS`.
|
|
28
|
+
*/
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
/** Credentials the failure detail must never contain. */
|
|
32
|
+
secrets?: ReadonlyArray<string | null | undefined>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type DecisionProbeRequest = Pick<
|
|
36
|
+
DecisionRequest,
|
|
37
|
+
'state' | 'questions' | 'label'
|
|
38
|
+
>;
|
|
39
|
+
|
|
40
|
+
/** One yes/no question a host answers in a few tokens; the answer itself is irrelevant. */
|
|
41
|
+
export function probeRequest(): DecisionProbeRequest {
|
|
42
|
+
return {
|
|
43
|
+
state: 'decision model readiness probe',
|
|
44
|
+
questions: { ok: booleanQuestion('Is this text a readiness probe?') },
|
|
45
|
+
label: 'probe',
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Can this model answer right now? Asks one tiny boolean question and never
|
|
51
|
+
* throws, and settles by its deadline or the caller's abort even when the
|
|
52
|
+
* model ignores both: any reply is `ok`, and any failure, including a non-SDK
|
|
53
|
+
* exception (read as `network`), is returned with a redacted detail. Through
|
|
54
|
+
* `withBreaker`, a fatal failure trips the breaker and an open breaker answers
|
|
55
|
+
* without a request.
|
|
56
|
+
*/
|
|
57
|
+
export async function probe(
|
|
58
|
+
model: DecisionModel,
|
|
59
|
+
options: DecisionProbeOptions = {}
|
|
60
|
+
): Promise<DecisionProbe> {
|
|
61
|
+
try {
|
|
62
|
+
const { timeoutMs } = options;
|
|
63
|
+
const result = await withDecisionDeadline(
|
|
64
|
+
model.id,
|
|
65
|
+
timeoutMs ?? PROBE_MAX_WAIT_MS,
|
|
66
|
+
options.signal,
|
|
67
|
+
(signal, waitFor) =>
|
|
68
|
+
waitFor(
|
|
69
|
+
Promise.resolve().then(() =>
|
|
70
|
+
model.decide({
|
|
71
|
+
...probeRequest(),
|
|
72
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
73
|
+
signal,
|
|
74
|
+
})
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
);
|
|
78
|
+
return { ok: true, model: result.model };
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (!(error instanceof DecisionError)) {
|
|
81
|
+
return {
|
|
82
|
+
ok: false,
|
|
83
|
+
failure: 'network',
|
|
84
|
+
circuitOpen: false,
|
|
85
|
+
detail: PROBE_FAILED,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
failure: error.failure,
|
|
91
|
+
...(error.status !== undefined ? { status: error.status } : {}),
|
|
92
|
+
circuitOpen: error.circuitOpen,
|
|
93
|
+
detail: safeDetail(error.message, options),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The redacted start of the message, or a fixed detail when `secrets` cannot
|
|
100
|
+
* be read: never the raw message, never a throw. Only the start is read, so a
|
|
101
|
+
* host model's oversized error message cannot make the probe slow or large.
|
|
102
|
+
*/
|
|
103
|
+
function safeDetail(message: string, options: DecisionProbeOptions): string {
|
|
104
|
+
try {
|
|
105
|
+
const { secrets } = options;
|
|
106
|
+
return redactExcerpt(
|
|
107
|
+
message,
|
|
108
|
+
secrets === undefined ? [] : secrets,
|
|
109
|
+
DETAIL_LIMIT
|
|
110
|
+
);
|
|
111
|
+
} catch {
|
|
112
|
+
return PROBE_FAILED;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
const REDACTED = '[REDACTED]';
|
|
2
|
+
const BEARER = /\b(bearer\s+)([^\s"',;]+)/gi;
|
|
3
|
+
/** Where a JWT can start; its three segments are measured by `jwtSpans`. */
|
|
4
|
+
const JWT_START = /\beyJ/g;
|
|
5
|
+
/** A character of one JWT segment. */
|
|
6
|
+
const SEGMENT_CHAR = /[\w-]/;
|
|
7
|
+
/** The shortest segment a JWT is recognized with. */
|
|
8
|
+
const SEGMENT_MIN = 8;
|
|
9
|
+
/** Long opaque runs (API keys, session tokens); also catches 40-hex digests, which is acceptable in a log line. */
|
|
10
|
+
const OPAQUE = /[A-Za-z0-9_-]{40,}/g;
|
|
11
|
+
/** A character of a token-shaped run (opaque, JWT, dotted) a cut at the end of an excerpt window may split. */
|
|
12
|
+
const TOKEN_CHAR = /[\w.-]/;
|
|
13
|
+
/** How much of the text an excerpt reads, so its cost does not grow with the text. */
|
|
14
|
+
const EXCERPT_WINDOW = 4096;
|
|
15
|
+
/** How much raw text an excerpt collapses to fill its window; whitespace past it is never scanned. */
|
|
16
|
+
const RAW_WINDOW = EXCERPT_WINDOW * 4;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Coverage of `source` as a difference array: `depth[i]` adds one where a
|
|
20
|
+
* span starts and subtracts one where it ends, so memory stays one slot per
|
|
21
|
+
* character however many matches there are.
|
|
22
|
+
*/
|
|
23
|
+
type Coverage = { depth: Int32Array; marked: boolean };
|
|
24
|
+
|
|
25
|
+
function mark(coverage: Coverage, start: number, end: number): void {
|
|
26
|
+
coverage.depth[start] += 1;
|
|
27
|
+
coverage.depth[end] -= 1;
|
|
28
|
+
coverage.marked = true;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Every occurrence of `secret`, overlapping ones included, merged into runs as they are found. */
|
|
32
|
+
function literalSpans(
|
|
33
|
+
source: string,
|
|
34
|
+
secret: string,
|
|
35
|
+
coverage: Coverage
|
|
36
|
+
): void {
|
|
37
|
+
let start = -1;
|
|
38
|
+
let end = -1;
|
|
39
|
+
for (
|
|
40
|
+
let at = source.indexOf(secret);
|
|
41
|
+
at !== -1;
|
|
42
|
+
at = source.indexOf(secret, at + 1)
|
|
43
|
+
) {
|
|
44
|
+
if (at > end) {
|
|
45
|
+
if (start !== -1) {
|
|
46
|
+
mark(coverage, start, end);
|
|
47
|
+
}
|
|
48
|
+
start = at;
|
|
49
|
+
}
|
|
50
|
+
end = at + secret.length;
|
|
51
|
+
}
|
|
52
|
+
if (start !== -1) {
|
|
53
|
+
mark(coverage, start, end);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function patternSpans(
|
|
58
|
+
source: string,
|
|
59
|
+
pattern: RegExp,
|
|
60
|
+
coverage: Coverage,
|
|
61
|
+
keepGroup = 0
|
|
62
|
+
): void {
|
|
63
|
+
for (const match of source.matchAll(pattern)) {
|
|
64
|
+
const kept = keepGroup > 0 ? match[keepGroup].length : 0;
|
|
65
|
+
mark(coverage, match.index + kept, match.index + match[0].length);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Where the run of segment characters starting at `from` ends. */
|
|
70
|
+
function segmentEnd(source: string, from: number): number {
|
|
71
|
+
let at = from;
|
|
72
|
+
while (at < source.length && SEGMENT_CHAR.test(source[at])) {
|
|
73
|
+
at += 1;
|
|
74
|
+
}
|
|
75
|
+
return at;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Every JWT shape (`eyJ` and three dot-separated segments of at least
|
|
80
|
+
* `SEGMENT_MIN` characters each) in one pass. A segment cannot contain the
|
|
81
|
+
* dot that ends it, so each segment's end is fixed by where its run of
|
|
82
|
+
* segment characters stops, and a start that fails fails for every later
|
|
83
|
+
* start inside its first segment too: the scan resumes past that segment
|
|
84
|
+
* instead of rescanning the run from each word boundary, which a
|
|
85
|
+
* backtracking pattern does in quadratic time.
|
|
86
|
+
*/
|
|
87
|
+
function jwtSpans(source: string, coverage: Coverage): void {
|
|
88
|
+
JWT_START.lastIndex = 0;
|
|
89
|
+
for (
|
|
90
|
+
let match = JWT_START.exec(source);
|
|
91
|
+
match !== null;
|
|
92
|
+
match = JWT_START.exec(source)
|
|
93
|
+
) {
|
|
94
|
+
const start = match.index;
|
|
95
|
+
const firstEnd = segmentEnd(source, start + 3);
|
|
96
|
+
let from = start + 3;
|
|
97
|
+
let stop = firstEnd;
|
|
98
|
+
let segments = 0;
|
|
99
|
+
while (
|
|
100
|
+
stop - from >= SEGMENT_MIN &&
|
|
101
|
+
++segments < 3 &&
|
|
102
|
+
source[stop] === '.'
|
|
103
|
+
) {
|
|
104
|
+
from = stop + 1;
|
|
105
|
+
stop = segmentEnd(source, from);
|
|
106
|
+
}
|
|
107
|
+
if (segments === 3) {
|
|
108
|
+
mark(coverage, start, stop);
|
|
109
|
+
}
|
|
110
|
+
JWT_START.lastIndex = Math.max(segments === 3 ? stop : firstEnd, start + 1);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The distinct listed secrets, each normalized by `normalize`; iterates
|
|
116
|
+
* `secrets` with `for...of`, so an unreadable list throws instead of
|
|
117
|
+
* silently redacting nothing.
|
|
118
|
+
*/
|
|
119
|
+
function listed(
|
|
120
|
+
secrets: ReadonlyArray<string | null | undefined>,
|
|
121
|
+
normalize: (secret: string) => string
|
|
122
|
+
): Set<string> {
|
|
123
|
+
const distinct = new Set<string>();
|
|
124
|
+
for (const secret of secrets) {
|
|
125
|
+
const value = typeof secret === 'string' ? normalize(secret) : '';
|
|
126
|
+
if (value !== '') {
|
|
127
|
+
distinct.add(value);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return distinct;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Marks every recognizer's matches, then replaces each covered run with one marker. */
|
|
134
|
+
function cover(source: string, secrets: Set<string>, cutAt?: number): string {
|
|
135
|
+
const coverage: Coverage = {
|
|
136
|
+
depth: new Int32Array(source.length + 1),
|
|
137
|
+
marked: false,
|
|
138
|
+
};
|
|
139
|
+
for (const secret of secrets) {
|
|
140
|
+
literalSpans(source, secret, coverage);
|
|
141
|
+
}
|
|
142
|
+
patternSpans(source, BEARER, coverage, 1);
|
|
143
|
+
jwtSpans(source, coverage);
|
|
144
|
+
patternSpans(source, OPAQUE, coverage);
|
|
145
|
+
if (cutAt !== undefined && cutAt < source.length) {
|
|
146
|
+
mark(coverage, cutAt, source.length);
|
|
147
|
+
}
|
|
148
|
+
if (!coverage.marked) {
|
|
149
|
+
return source;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let result = '';
|
|
153
|
+
let cursor = 0;
|
|
154
|
+
let depth = 0;
|
|
155
|
+
for (let at = 0; at <= source.length; at++) {
|
|
156
|
+
const covered = depth > 0;
|
|
157
|
+
depth += coverage.depth[at];
|
|
158
|
+
if (!covered && depth > 0) {
|
|
159
|
+
result += source.slice(cursor, at) + REDACTED;
|
|
160
|
+
} else if (covered && depth === 0) {
|
|
161
|
+
cursor = at;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return result + source.slice(cursor);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Removes credentials from text bound for a log line or a status row: every
|
|
169
|
+
* listed secret verbatim, plus anything shaped like a bearer value, a JWT, or
|
|
170
|
+
* a long opaque token. Every recognizer reads the original text and the
|
|
171
|
+
* union of their matches is replaced at once, so a listed secret that
|
|
172
|
+
* overlaps a `Bearer` keyword or splits a long token cannot hide a credential
|
|
173
|
+
* from the shape checks. Unlisted short secrets are not recognizable by
|
|
174
|
+
* shape, so pass every credential the text could contain. Memory stays
|
|
175
|
+
* proportional to the text however often a secret repeats in it; time grows
|
|
176
|
+
* with the text times the number of distinct secrets.
|
|
177
|
+
*/
|
|
178
|
+
export function redact(
|
|
179
|
+
text: string,
|
|
180
|
+
secrets: ReadonlyArray<string | null | undefined> = []
|
|
181
|
+
): string {
|
|
182
|
+
return cover(
|
|
183
|
+
String(text),
|
|
184
|
+
listed(secrets, (secret) => secret.trim())
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const collapse = (text: string): string => text.replace(/\s+/g, ' ').trim();
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The first `limit` characters of `text` redacted, with whitespace
|
|
192
|
+
* collapsed. Only the first 4096 characters after collapsing, drawn from at
|
|
193
|
+
* most the first 16384 of the text, are read, so the cost stays bounded
|
|
194
|
+
* however long the text and however many secrets there are. When the text runs past that window, its tail is redacted as far
|
|
195
|
+
* back as the longest listed secret could reach and through any token-shaped
|
|
196
|
+
* run the cut splits, so a credential the window cuts off cannot show its
|
|
197
|
+
* first characters.
|
|
198
|
+
*/
|
|
199
|
+
export function redactExcerpt(
|
|
200
|
+
text: string,
|
|
201
|
+
secrets: ReadonlyArray<string | null | undefined>,
|
|
202
|
+
limit: number
|
|
203
|
+
): string {
|
|
204
|
+
const raw = String(text);
|
|
205
|
+
const head = raw.slice(0, RAW_WINDOW);
|
|
206
|
+
const whole = collapse(head);
|
|
207
|
+
const source = whole.slice(0, EXCERPT_WINDOW);
|
|
208
|
+
const distinct = listed(secrets, collapse);
|
|
209
|
+
let cutAt: number | undefined;
|
|
210
|
+
if (raw.length > head.length || whole.length > source.length) {
|
|
211
|
+
let longest = 0;
|
|
212
|
+
for (const secret of distinct) {
|
|
213
|
+
longest = Math.max(longest, secret.length);
|
|
214
|
+
}
|
|
215
|
+
let run = source.length;
|
|
216
|
+
while (run > 0 && TOKEN_CHAR.test(source[run - 1])) {
|
|
217
|
+
run -= 1;
|
|
218
|
+
}
|
|
219
|
+
cutAt = Math.max(0, Math.min(source.length - longest + 1, run));
|
|
220
|
+
}
|
|
221
|
+
return cover(source, distinct, cutAt).slice(0, limit);
|
|
222
|
+
}
|
|
@@ -13,6 +13,7 @@ import { failureForStatus, retryAfterMs } from './transport';
|
|
|
13
13
|
import { validateDecisionQuestions } from './questions';
|
|
14
14
|
import { DECISION_PROMPT_PREFIX } from './traceMarker';
|
|
15
15
|
import { withDecisionDeadline } from './deadline';
|
|
16
|
+
import { callHook } from './hook';
|
|
16
17
|
|
|
17
18
|
const MAX_QUESTIONS = 32;
|
|
18
19
|
const MAX_CHOICE_OPTIONS = 128;
|
|
@@ -92,6 +93,7 @@ export interface StructuredChatDecisionModelOptions {
|
|
|
92
93
|
method: DecisionOutputMethod;
|
|
93
94
|
timeoutMs?: number;
|
|
94
95
|
maxQuestions?: number;
|
|
96
|
+
/** Called after a valid decision. Not awaited; a throw or a rejected promise is ignored. */
|
|
95
97
|
onAnswered?: (label: string, ms: number) => void;
|
|
96
98
|
}
|
|
97
99
|
|
|
@@ -342,14 +344,10 @@ export function createStructuredChatDecisionModel(
|
|
|
342
344
|
usage: readChatUsage(output.raw),
|
|
343
345
|
};
|
|
344
346
|
await waitFor(Promise.resolve());
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
);
|
|
350
|
-
} catch {
|
|
351
|
-
// A callback error must not make a valid decision fail.
|
|
352
|
-
}
|
|
347
|
+
// A callback error, sync or async, must not make a valid decision fail.
|
|
348
|
+
callHook(() =>
|
|
349
|
+
onAnswered?.(request.label ?? 'decide', performance.now() - started)
|
|
350
|
+
);
|
|
353
351
|
return result;
|
|
354
352
|
}
|
|
355
353
|
);
|
|
@@ -2,6 +2,7 @@ import type { AwaitWithinDeadline } from './deadline';
|
|
|
2
2
|
import type { DecisionCredential } from './types';
|
|
3
3
|
import { withDecisionDeadline } from './deadline';
|
|
4
4
|
import { DecisionError } from './types';
|
|
5
|
+
import { callHook } from './hook';
|
|
5
6
|
|
|
6
7
|
const DEFAULT_TIMEOUT_MS = 4_000;
|
|
7
8
|
const DEFAULT_MAX_RETRIES = 2;
|
|
@@ -30,23 +31,41 @@ export interface TransportOptions {
|
|
|
30
31
|
maxRetries?: number;
|
|
31
32
|
fetch?: DecisionFetch;
|
|
32
33
|
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
33
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Called only after the response parses, with no state, answers, or
|
|
36
|
+
* credentials. Not awaited; a throw or a rejected promise is ignored.
|
|
37
|
+
*/
|
|
34
38
|
onAnswered?: (label: string, ms: number) => void;
|
|
35
39
|
}
|
|
36
40
|
|
|
41
|
+
/**
|
|
42
|
+
* `onRequest` is called once per HTTP request, just before it is sent:
|
|
43
|
+
* retries and every re-send after a 401 included. `onResponse` is called once
|
|
44
|
+
* per such request that ended before the deadline or the caller's abort, with
|
|
45
|
+
* its HTTP status (after a successful body is read in full) or `null` when the
|
|
46
|
+
* fetch failed or a successful body could not be read, and a reply's
|
|
47
|
+
* `Retry-After` in milliseconds when it was not OK and sent one; a request
|
|
48
|
+
* interrupted in flight gets none. Neither is awaited; a throw or a rejected
|
|
49
|
+
* promise is ignored.
|
|
50
|
+
*/
|
|
37
51
|
export type Transport = <T>(
|
|
38
52
|
prepare: () => { payload: string; parse: (body: string) => T },
|
|
39
53
|
signal: AbortSignal | undefined,
|
|
40
54
|
label: string,
|
|
41
|
-
timeoutOverrideMs?: number
|
|
55
|
+
timeoutOverrideMs?: number,
|
|
56
|
+
onRequest?: () => void,
|
|
57
|
+
onResponse?: (status: number | null, retryAfterMs?: number) => void
|
|
42
58
|
) => Promise<T>;
|
|
43
59
|
|
|
44
60
|
export function failureForStatus(
|
|
45
61
|
status: number
|
|
46
|
-
): 'unauthorized' | 'rate_limited' | 'server_error' | 'bad_request' {
|
|
62
|
+
): 'unauthorized' | 'quota' | 'rate_limited' | 'server_error' | 'bad_request' {
|
|
47
63
|
if (status === 401 || status === 403) {
|
|
48
64
|
return 'unauthorized';
|
|
49
65
|
}
|
|
66
|
+
if (status === 402) {
|
|
67
|
+
return 'quota';
|
|
68
|
+
}
|
|
50
69
|
if (status === 429) {
|
|
51
70
|
return 'rate_limited';
|
|
52
71
|
}
|
|
@@ -176,7 +195,7 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
176
195
|
}
|
|
177
196
|
|
|
178
197
|
async function resolveKey(
|
|
179
|
-
|
|
198
|
+
refused: string | undefined,
|
|
180
199
|
signal: AbortSignal
|
|
181
200
|
): Promise<string | null> {
|
|
182
201
|
if (typeof credential === 'string') {
|
|
@@ -185,7 +204,11 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
185
204
|
if (!credential) {
|
|
186
205
|
return null;
|
|
187
206
|
}
|
|
188
|
-
const minted: string = await credential(
|
|
207
|
+
const minted: string = await credential(
|
|
208
|
+
refused === undefined
|
|
209
|
+
? { refresh: false, signal }
|
|
210
|
+
: { refresh: true, refused, signal }
|
|
211
|
+
);
|
|
189
212
|
const token = typeof minted === 'string' ? minted.trim() : '';
|
|
190
213
|
if (!token) {
|
|
191
214
|
throw new DecisionError(
|
|
@@ -199,7 +222,14 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
199
222
|
return token;
|
|
200
223
|
}
|
|
201
224
|
|
|
202
|
-
return async function send(
|
|
225
|
+
return async function send(
|
|
226
|
+
prepare,
|
|
227
|
+
callerSignal,
|
|
228
|
+
label,
|
|
229
|
+
timeoutOverrideMs,
|
|
230
|
+
onRequest,
|
|
231
|
+
onResponse
|
|
232
|
+
) {
|
|
203
233
|
const started = performance.now();
|
|
204
234
|
return withDecisionDeadline(
|
|
205
235
|
providerId,
|
|
@@ -230,7 +260,14 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
230
260
|
'decision model request interrupted',
|
|
231
261
|
{ provider: providerId }
|
|
232
262
|
);
|
|
233
|
-
|
|
263
|
+
/**
|
|
264
|
+
* Keys 401s refused in this call. The first earns a refresh; a second
|
|
265
|
+
* earns one recheck with `refresh: false`, since another call may have
|
|
266
|
+
* replaced the key while this request was in flight, and the call
|
|
267
|
+
* re-sends only a key it has not had refused.
|
|
268
|
+
*/
|
|
269
|
+
const refused: string[] = [];
|
|
270
|
+
let refusal: DecisionError | undefined;
|
|
234
271
|
let key: string | null | undefined;
|
|
235
272
|
let lastError: DecisionError | undefined;
|
|
236
273
|
for (let attemptNo = 0; attemptNo <= maxRetries; attemptNo++) {
|
|
@@ -239,10 +276,39 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
239
276
|
}
|
|
240
277
|
try {
|
|
241
278
|
if (key === undefined) {
|
|
242
|
-
key = await waitFor(
|
|
279
|
+
key = await waitFor(
|
|
280
|
+
resolveKey(
|
|
281
|
+
refused.length === 1 ? refused[0] : undefined,
|
|
282
|
+
signal
|
|
283
|
+
)
|
|
284
|
+
);
|
|
285
|
+
if (
|
|
286
|
+
refusal !== undefined &&
|
|
287
|
+
typeof key === 'string' &&
|
|
288
|
+
refused.includes(key)
|
|
289
|
+
) {
|
|
290
|
+
/** The minter has nothing newer than a key this call had refused: that refusal stands. */
|
|
291
|
+
throw refusal;
|
|
292
|
+
}
|
|
243
293
|
}
|
|
244
|
-
|
|
245
|
-
|
|
294
|
+
if (onRequest !== undefined) {
|
|
295
|
+
callHook(() => onRequest());
|
|
296
|
+
}
|
|
297
|
+
/** Reports the request's end once, unless the deadline or the caller's abort interrupted it. */
|
|
298
|
+
let open = true;
|
|
299
|
+
const ended = (
|
|
300
|
+
status: number | null,
|
|
301
|
+
retryAfter?: number
|
|
302
|
+
): void => {
|
|
303
|
+
if (open && !wasAborted() && onResponse !== undefined) {
|
|
304
|
+
callHook(() => onResponse(status, retryAfter));
|
|
305
|
+
}
|
|
306
|
+
open = false;
|
|
307
|
+
};
|
|
308
|
+
let response: Awaited<ReturnType<DecisionFetch>>;
|
|
309
|
+
let pending: ReturnType<DecisionFetch> | undefined;
|
|
310
|
+
try {
|
|
311
|
+
pending = fetchImpl(endpoint, {
|
|
246
312
|
method: 'POST',
|
|
247
313
|
headers: {
|
|
248
314
|
...(key !== null ? { Authorization: `Bearer ${key}` } : {}),
|
|
@@ -251,27 +317,40 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
251
317
|
body: payload,
|
|
252
318
|
signal,
|
|
253
319
|
redirect: 'error',
|
|
254
|
-
})
|
|
255
|
-
|
|
320
|
+
});
|
|
321
|
+
response = await waitFor(pending);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
// A fetch that ignores abort still owns a body when it eventually resolves.
|
|
324
|
+
void pending?.then((late) => late.body?.cancel()).catch(() => {});
|
|
325
|
+
ended(null);
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
256
328
|
if (!response.ok) {
|
|
329
|
+
const retryAfter = retryAfterMs(
|
|
330
|
+
response.headers.get('retry-after')
|
|
331
|
+
);
|
|
332
|
+
ended(response.status, retryAfter);
|
|
257
333
|
void response.body?.cancel().catch(() => {});
|
|
258
334
|
const error = new DecisionError(
|
|
259
335
|
failureForStatus(response.status),
|
|
260
336
|
`decision model returned HTTP ${response.status}`,
|
|
261
337
|
{ provider: providerId, status: response.status }
|
|
262
338
|
);
|
|
263
|
-
error.retryAfterMs =
|
|
264
|
-
response.headers.get('retry-after')
|
|
265
|
-
);
|
|
339
|
+
error.retryAfterMs = retryAfter;
|
|
266
340
|
throw error;
|
|
267
341
|
}
|
|
268
|
-
|
|
269
|
-
const result = await waitFor(Promise.resolve(parse(body)));
|
|
342
|
+
let body: string;
|
|
270
343
|
try {
|
|
271
|
-
|
|
272
|
-
} catch {
|
|
273
|
-
//
|
|
344
|
+
body = await readResponse(response.body, waitFor, providerId);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
// A body that broke off or overflowed is no reply: the request may be retried.
|
|
347
|
+
ended(null);
|
|
348
|
+
throw error;
|
|
274
349
|
}
|
|
350
|
+
ended(response.status);
|
|
351
|
+
const result = await waitFor(Promise.resolve(parse(body)));
|
|
352
|
+
// Observability, sync or async, must not turn a valid answer into a retried request.
|
|
353
|
+
callHook(() => onAnswered?.(label, performance.now() - started));
|
|
275
354
|
return result;
|
|
276
355
|
} catch (error) {
|
|
277
356
|
if (wasAborted()) {
|
|
@@ -289,9 +368,12 @@ export function createTransport(options: TransportOptions): Transport {
|
|
|
289
368
|
if (
|
|
290
369
|
lastError.status === 401 &&
|
|
291
370
|
typeof credential === 'function' &&
|
|
292
|
-
|
|
371
|
+
typeof key === 'string' &&
|
|
372
|
+
refused.length < 2 &&
|
|
373
|
+
!refused.includes(key)
|
|
293
374
|
) {
|
|
294
|
-
|
|
375
|
+
refused.push(key);
|
|
376
|
+
refusal = lastError;
|
|
295
377
|
key = undefined;
|
|
296
378
|
attemptNo -= 1;
|
|
297
379
|
continue;
|
package/src/decisions/types.ts
CHANGED
|
@@ -80,6 +80,25 @@ export interface DecisionRequest {
|
|
|
80
80
|
label?: string;
|
|
81
81
|
/** Overrides the provider's timeout for this request alone. */
|
|
82
82
|
timeoutMs?: number;
|
|
83
|
+
/**
|
|
84
|
+
* Called once per request the model sends, just before it goes out, so a
|
|
85
|
+
* caller can count retries and every re-send after a 401. The HTTP
|
|
86
|
+
* decision model calls it; a model that does not report requests leaves the
|
|
87
|
+
* caller to count one per `decide()`. Not awaited; a throw is ignored.
|
|
88
|
+
*/
|
|
89
|
+
onRequest?: () => void;
|
|
90
|
+
/**
|
|
91
|
+
* Called once per request `onRequest` announced that ended before the
|
|
92
|
+
* deadline or the caller's abort: with the HTTP status once the host
|
|
93
|
+
* replied (a successful reply's body read in full), or `null` when the
|
|
94
|
+
* request failed without a reply or a successful reply's body could not be
|
|
95
|
+
* read, and for a reply that was not OK its
|
|
96
|
+
* `Retry-After` in milliseconds when it sent one. A request still in
|
|
97
|
+
* flight when the call is interrupted gets none, so the announced requests
|
|
98
|
+
* without one are the ones the host may still be working on. Not awaited;
|
|
99
|
+
* a throw is ignored.
|
|
100
|
+
*/
|
|
101
|
+
onResponse?: (status: number | null, retryAfterMs?: number) => void;
|
|
83
102
|
}
|
|
84
103
|
|
|
85
104
|
export interface DecisionResult {
|
|
@@ -92,15 +111,32 @@ export interface DecisionResult {
|
|
|
92
111
|
export interface DecisionModel {
|
|
93
112
|
readonly id: string;
|
|
94
113
|
readonly model: string;
|
|
114
|
+
/**
|
|
115
|
+
* True when `decide` reports every request it sends through `onRequest`
|
|
116
|
+
* and every one that ends through `onResponse`, as the HTTP decision model
|
|
117
|
+
* does, so a caller can count what was really sent: a `decide` that fails
|
|
118
|
+
* before its first `onRequest` sent nothing.
|
|
119
|
+
*/
|
|
120
|
+
readonly reportsRequests?: boolean;
|
|
95
121
|
decide(request: DecisionRequest): Promise<DecisionResult>;
|
|
96
122
|
}
|
|
97
123
|
|
|
98
124
|
export type DecisionDialect = 'port' | 'systemone';
|
|
99
125
|
|
|
100
|
-
/**
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Mints a bearer token; `refresh` asks for a new one after a 401. On a
|
|
128
|
+
* refresh, `refused` is the token the 401 refused (as sent, trimmed), so a
|
|
129
|
+
* caching minter can hand out a token minted since then instead of
|
|
130
|
+
* discarding it.
|
|
131
|
+
*/
|
|
132
|
+
export type DecisionTokenMinter = (options: {
|
|
133
|
+
refresh: boolean;
|
|
134
|
+
refused?: string;
|
|
135
|
+
signal?: AbortSignal;
|
|
136
|
+
}) => Promise<string>;
|
|
137
|
+
|
|
138
|
+
/** A bearer key, or a per-request token minter; a 401 requests one fresh token for that call, and a second 401 one recheck (`refresh: false`) for a token minted since. */
|
|
139
|
+
export type DecisionCredential = string | DecisionTokenMinter;
|
|
104
140
|
|
|
105
141
|
export interface DecisionProviderSettings {
|
|
106
142
|
/** Full URL of the decision endpoint, not a base path. */
|
|
@@ -121,6 +157,8 @@ export type DecisionFailure =
|
|
|
121
157
|
| 'aborted'
|
|
122
158
|
| 'rate_limited'
|
|
123
159
|
| 'unauthorized'
|
|
160
|
+
/** HTTP 402: the credential is out of credits; never retried. */
|
|
161
|
+
| 'quota'
|
|
124
162
|
| 'bad_request'
|
|
125
163
|
| 'server_error'
|
|
126
164
|
| 'network'
|
|
@@ -133,17 +171,20 @@ export class DecisionError extends Error {
|
|
|
133
171
|
readonly provider: string;
|
|
134
172
|
readonly status?: number;
|
|
135
173
|
retryAfterMs?: number;
|
|
174
|
+
/** True when a breaker refused the call without a request; see `withBreaker`. */
|
|
175
|
+
readonly circuitOpen: boolean;
|
|
136
176
|
|
|
137
177
|
constructor(
|
|
138
178
|
failure: DecisionFailure,
|
|
139
179
|
message: string,
|
|
140
|
-
options?: { provider?: string; status?: number }
|
|
180
|
+
options?: { provider?: string; status?: number; circuitOpen?: boolean }
|
|
141
181
|
) {
|
|
142
182
|
super(message);
|
|
143
183
|
this.name = 'DecisionError';
|
|
144
184
|
this.failure = failure;
|
|
145
185
|
this.provider = options?.provider ?? 'unknown';
|
|
146
186
|
this.status = options?.status;
|
|
187
|
+
this.circuitOpen = options?.circuitOpen ?? false;
|
|
147
188
|
}
|
|
148
189
|
}
|
|
149
190
|
|