@umituz/web-ai 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -3
- package/dist/{cancellation-error-_39nYWwz.d.cts → cancellation-error-BWb59Wkj.d.cts} +1 -1
- package/dist/{cancellation-error-hYcE9AS9.d.ts → cancellation-error-D9LETLCD.d.ts} +1 -1
- package/dist/chat/index.cjs +1 -0
- package/dist/chat/index.cjs.map +1 -1
- package/dist/chat/index.js +1 -0
- package/dist/chat/index.js.map +1 -1
- package/dist/content/index.cjs +622 -8
- package/dist/content/index.cjs.map +1 -1
- package/dist/content/index.d.cts +2 -2
- package/dist/content/index.d.ts +2 -2
- package/dist/content/index.js +622 -8
- package/dist/content/index.js.map +1 -1
- package/dist/context-manager-CuZz0vnC.d.cts +104 -0
- package/dist/context-manager-CuZz0vnC.d.ts +104 -0
- package/dist/core/index.cjs +147 -10
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +91 -73
- package/dist/core/index.d.ts +91 -73
- package/dist/core/index.js +141 -11
- package/dist/core/index.js.map +1 -1
- package/dist/{create-ai-D-oEWzf9.d.ts → create-ai-Cq3HkJxd.d.ts} +61 -1
- package/dist/{create-ai-DRysRImc.d.cts → create-ai-DDyTVzef.d.cts} +61 -1
- package/dist/hooks/index.cjs +747 -15
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +57 -4
- package/dist/hooks/index.d.ts +57 -4
- package/dist/hooks/index.js +746 -16
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +1180 -242
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -6
- package/dist/index.d.ts +7 -6
- package/dist/index.js +1140 -243
- package/dist/index.js.map +1 -1
- package/dist/providers/index.cjs +1212 -362
- package/dist/providers/index.cjs.map +1 -1
- package/dist/providers/index.d.cts +422 -10
- package/dist/providers/index.d.ts +422 -10
- package/dist/providers/index.js +1179 -363
- package/dist/providers/index.js.map +1 -1
- package/dist/remote-chat-client-LrNlew4n.d.cts +70 -0
- package/dist/remote-chat-client-LrNlew4n.d.ts +70 -0
- package/dist/{requestQueue-D89wx91Q.d.cts → requestQueue--h2uZ-Q3.d.cts} +1 -1
- package/dist/{requestQueue-AP6n_bRH.d.ts → requestQueue-BGeCy4Fd.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/tool-call-accumulator-C7KhaXZA.d.cts +0 -69
- package/dist/tool-call-accumulator-C7KhaXZA.d.ts +0 -69
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
type AiErrorCode = 'invalid_key' | 'missing_key' | 'rate_limited' | 'capacity' | 'timeout' | 'invalid_request' | 'model_unavailable' | 'upstream_error' | 'network' | 'cancelled';
|
|
2
|
+
declare const STATUS_TO_CODE: Readonly<Record<number, AiErrorCode>>;
|
|
3
|
+
declare const CODE_MESSAGES: Readonly<Record<AiErrorCode, string>>;
|
|
4
|
+
declare class AiError extends Error {
|
|
5
|
+
readonly code: AiErrorCode;
|
|
6
|
+
constructor(code: AiErrorCode, message?: string);
|
|
7
|
+
get userMessage(): string;
|
|
8
|
+
}
|
|
9
|
+
declare function aiErrorMessage(code: AiErrorCode): string;
|
|
10
|
+
interface ProviderErrorShape {
|
|
11
|
+
readonly type?: string;
|
|
12
|
+
readonly code?: string;
|
|
13
|
+
}
|
|
14
|
+
declare function errorFromStatus(status: number, detail?: string, provider?: ProviderErrorShape): AiError;
|
|
15
|
+
declare function errorFromUnknown(err: unknown): AiError;
|
|
16
|
+
|
|
17
|
+
interface RetryOptions {
|
|
18
|
+
readonly maxAttempts?: number;
|
|
19
|
+
readonly initialDelay?: number;
|
|
20
|
+
readonly maxDelay?: number;
|
|
21
|
+
readonly backoffMultiplier?: number;
|
|
22
|
+
readonly jitterFactor?: number;
|
|
23
|
+
readonly shouldRetry?: (error: Error) => boolean;
|
|
24
|
+
}
|
|
25
|
+
declare class RetryManager {
|
|
26
|
+
private readonly defaults;
|
|
27
|
+
constructor();
|
|
28
|
+
execute<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
29
|
+
private shouldRetry;
|
|
30
|
+
private delay;
|
|
31
|
+
}
|
|
32
|
+
declare const retryManager: RetryManager;
|
|
33
|
+
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
34
|
+
|
|
35
|
+
interface QueueOptions {
|
|
36
|
+
readonly maxConcurrent?: number;
|
|
37
|
+
readonly defaultPriority?: number;
|
|
38
|
+
readonly requestTimeout?: number;
|
|
39
|
+
}
|
|
40
|
+
declare class RequestQueue {
|
|
41
|
+
private queue;
|
|
42
|
+
private readonly activeRequests;
|
|
43
|
+
private readonly maxConcurrent;
|
|
44
|
+
private readonly defaultPriority;
|
|
45
|
+
private readonly requestTimeout;
|
|
46
|
+
private requestIdCounter;
|
|
47
|
+
constructor(options?: QueueOptions);
|
|
48
|
+
add<T>(requestFn: () => Promise<T>, priority?: number): Promise<T>;
|
|
49
|
+
cancelAll(): void;
|
|
50
|
+
private sortQueue;
|
|
51
|
+
private process;
|
|
52
|
+
private executeRequest;
|
|
53
|
+
}
|
|
54
|
+
declare const requestQueue: RequestQueue;
|
|
55
|
+
|
|
56
|
+
declare class RequestDeduplicator {
|
|
57
|
+
private readonly pendingRequests;
|
|
58
|
+
private readonly ttl;
|
|
59
|
+
constructor(ttl?: number);
|
|
60
|
+
execute<T>(key: string, requestFn: () => Promise<T>): Promise<T>;
|
|
61
|
+
cancelAll(): void;
|
|
62
|
+
private cleanup;
|
|
63
|
+
}
|
|
64
|
+
declare const requestDeduplicator: RequestDeduplicator;
|
|
65
|
+
|
|
66
|
+
interface WireToolCallDelta {
|
|
67
|
+
readonly index?: number;
|
|
68
|
+
readonly id?: string;
|
|
69
|
+
readonly function?: {
|
|
70
|
+
readonly name?: string;
|
|
71
|
+
readonly arguments?: string;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
interface AssistantToolCall {
|
|
75
|
+
readonly id: string;
|
|
76
|
+
readonly name: string;
|
|
77
|
+
readonly arguments: string;
|
|
78
|
+
}
|
|
79
|
+
declare class ToolCallAccumulator {
|
|
80
|
+
private readonly slots;
|
|
81
|
+
push(delta: WireToolCallDelta): void;
|
|
82
|
+
finish(): AssistantToolCall[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type ContextRole = 'system' | 'user' | 'assistant' | 'tool';
|
|
86
|
+
interface ContextMessage {
|
|
87
|
+
readonly role: ContextRole;
|
|
88
|
+
readonly content: string;
|
|
89
|
+
readonly toolCalls?: ReadonlyArray<{
|
|
90
|
+
id: string;
|
|
91
|
+
name: string;
|
|
92
|
+
arguments: string;
|
|
93
|
+
}>;
|
|
94
|
+
readonly toolCallId?: string;
|
|
95
|
+
}
|
|
96
|
+
interface ContextBudget {
|
|
97
|
+
readonly contextWindow: number;
|
|
98
|
+
readonly maxOutputTokens: number;
|
|
99
|
+
}
|
|
100
|
+
declare function estimateTokens(text: string): number;
|
|
101
|
+
declare function estimateMessageTokens(message: ContextMessage): number;
|
|
102
|
+
declare function buildContext<T extends ContextMessage = ContextMessage>(history: ReadonlyArray<T>, systemPrompt: string, budget: ContextBudget): T[];
|
|
103
|
+
|
|
104
|
+
export { AiError as A, CODE_MESSAGES as C, type ProviderErrorShape as P, type QueueOptions as Q, RequestDeduplicator as R, STATUS_TO_CODE as S, ToolCallAccumulator as T, type WireToolCallDelta as W, type AiErrorCode as a, type AssistantToolCall as b, type ContextBudget as c, type ContextMessage as d, type ContextRole as e, RequestQueue as f, RetryManager as g, type RetryOptions as h, aiErrorMessage as i, buildContext as j, errorFromStatus as k, errorFromUnknown as l, estimateMessageTokens as m, estimateTokens as n, requestQueue as o, retryManager as p, requestDeduplicator as r, withRetry as w };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
type AiErrorCode = 'invalid_key' | 'missing_key' | 'rate_limited' | 'capacity' | 'timeout' | 'invalid_request' | 'model_unavailable' | 'upstream_error' | 'network' | 'cancelled';
|
|
2
|
+
declare const STATUS_TO_CODE: Readonly<Record<number, AiErrorCode>>;
|
|
3
|
+
declare const CODE_MESSAGES: Readonly<Record<AiErrorCode, string>>;
|
|
4
|
+
declare class AiError extends Error {
|
|
5
|
+
readonly code: AiErrorCode;
|
|
6
|
+
constructor(code: AiErrorCode, message?: string);
|
|
7
|
+
get userMessage(): string;
|
|
8
|
+
}
|
|
9
|
+
declare function aiErrorMessage(code: AiErrorCode): string;
|
|
10
|
+
interface ProviderErrorShape {
|
|
11
|
+
readonly type?: string;
|
|
12
|
+
readonly code?: string;
|
|
13
|
+
}
|
|
14
|
+
declare function errorFromStatus(status: number, detail?: string, provider?: ProviderErrorShape): AiError;
|
|
15
|
+
declare function errorFromUnknown(err: unknown): AiError;
|
|
16
|
+
|
|
17
|
+
interface RetryOptions {
|
|
18
|
+
readonly maxAttempts?: number;
|
|
19
|
+
readonly initialDelay?: number;
|
|
20
|
+
readonly maxDelay?: number;
|
|
21
|
+
readonly backoffMultiplier?: number;
|
|
22
|
+
readonly jitterFactor?: number;
|
|
23
|
+
readonly shouldRetry?: (error: Error) => boolean;
|
|
24
|
+
}
|
|
25
|
+
declare class RetryManager {
|
|
26
|
+
private readonly defaults;
|
|
27
|
+
constructor();
|
|
28
|
+
execute<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
29
|
+
private shouldRetry;
|
|
30
|
+
private delay;
|
|
31
|
+
}
|
|
32
|
+
declare const retryManager: RetryManager;
|
|
33
|
+
declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
34
|
+
|
|
35
|
+
interface QueueOptions {
|
|
36
|
+
readonly maxConcurrent?: number;
|
|
37
|
+
readonly defaultPriority?: number;
|
|
38
|
+
readonly requestTimeout?: number;
|
|
39
|
+
}
|
|
40
|
+
declare class RequestQueue {
|
|
41
|
+
private queue;
|
|
42
|
+
private readonly activeRequests;
|
|
43
|
+
private readonly maxConcurrent;
|
|
44
|
+
private readonly defaultPriority;
|
|
45
|
+
private readonly requestTimeout;
|
|
46
|
+
private requestIdCounter;
|
|
47
|
+
constructor(options?: QueueOptions);
|
|
48
|
+
add<T>(requestFn: () => Promise<T>, priority?: number): Promise<T>;
|
|
49
|
+
cancelAll(): void;
|
|
50
|
+
private sortQueue;
|
|
51
|
+
private process;
|
|
52
|
+
private executeRequest;
|
|
53
|
+
}
|
|
54
|
+
declare const requestQueue: RequestQueue;
|
|
55
|
+
|
|
56
|
+
declare class RequestDeduplicator {
|
|
57
|
+
private readonly pendingRequests;
|
|
58
|
+
private readonly ttl;
|
|
59
|
+
constructor(ttl?: number);
|
|
60
|
+
execute<T>(key: string, requestFn: () => Promise<T>): Promise<T>;
|
|
61
|
+
cancelAll(): void;
|
|
62
|
+
private cleanup;
|
|
63
|
+
}
|
|
64
|
+
declare const requestDeduplicator: RequestDeduplicator;
|
|
65
|
+
|
|
66
|
+
interface WireToolCallDelta {
|
|
67
|
+
readonly index?: number;
|
|
68
|
+
readonly id?: string;
|
|
69
|
+
readonly function?: {
|
|
70
|
+
readonly name?: string;
|
|
71
|
+
readonly arguments?: string;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
interface AssistantToolCall {
|
|
75
|
+
readonly id: string;
|
|
76
|
+
readonly name: string;
|
|
77
|
+
readonly arguments: string;
|
|
78
|
+
}
|
|
79
|
+
declare class ToolCallAccumulator {
|
|
80
|
+
private readonly slots;
|
|
81
|
+
push(delta: WireToolCallDelta): void;
|
|
82
|
+
finish(): AssistantToolCall[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type ContextRole = 'system' | 'user' | 'assistant' | 'tool';
|
|
86
|
+
interface ContextMessage {
|
|
87
|
+
readonly role: ContextRole;
|
|
88
|
+
readonly content: string;
|
|
89
|
+
readonly toolCalls?: ReadonlyArray<{
|
|
90
|
+
id: string;
|
|
91
|
+
name: string;
|
|
92
|
+
arguments: string;
|
|
93
|
+
}>;
|
|
94
|
+
readonly toolCallId?: string;
|
|
95
|
+
}
|
|
96
|
+
interface ContextBudget {
|
|
97
|
+
readonly contextWindow: number;
|
|
98
|
+
readonly maxOutputTokens: number;
|
|
99
|
+
}
|
|
100
|
+
declare function estimateTokens(text: string): number;
|
|
101
|
+
declare function estimateMessageTokens(message: ContextMessage): number;
|
|
102
|
+
declare function buildContext<T extends ContextMessage = ContextMessage>(history: ReadonlyArray<T>, systemPrompt: string, budget: ContextBudget): T[];
|
|
103
|
+
|
|
104
|
+
export { AiError as A, CODE_MESSAGES as C, type ProviderErrorShape as P, type QueueOptions as Q, RequestDeduplicator as R, STATUS_TO_CODE as S, ToolCallAccumulator as T, type WireToolCallDelta as W, type AiErrorCode as a, type AssistantToolCall as b, type ContextBudget as c, type ContextMessage as d, type ContextRole as e, RequestQueue as f, RetryManager as g, type RetryOptions as h, aiErrorMessage as i, buildContext as j, errorFromStatus as k, errorFromUnknown as l, estimateMessageTokens as m, estimateTokens as n, requestQueue as o, retryManager as p, requestDeduplicator as r, withRetry as w };
|
package/dist/core/index.cjs
CHANGED
|
@@ -305,6 +305,23 @@ function errorFromUnknown(err) {
|
|
|
305
305
|
return new AiError("upstream_error");
|
|
306
306
|
}
|
|
307
307
|
|
|
308
|
+
// src/core/errors/error-status.ts
|
|
309
|
+
var AI_ERROR_STATUS = {
|
|
310
|
+
invalid_key: 502,
|
|
311
|
+
missing_key: 503,
|
|
312
|
+
rate_limited: 429,
|
|
313
|
+
capacity: 503,
|
|
314
|
+
timeout: 504,
|
|
315
|
+
invalid_request: 400,
|
|
316
|
+
model_unavailable: 503,
|
|
317
|
+
upstream_error: 502,
|
|
318
|
+
network: 502,
|
|
319
|
+
cancelled: 400
|
|
320
|
+
};
|
|
321
|
+
function aiErrorStatus(code) {
|
|
322
|
+
return AI_ERROR_STATUS[code];
|
|
323
|
+
}
|
|
324
|
+
|
|
308
325
|
// src/core/executor/retry-executor.strategy.ts
|
|
309
326
|
var RetryExecutor = class {
|
|
310
327
|
constructor(retryManager2, options) {
|
|
@@ -1421,13 +1438,14 @@ function buildContext(history, systemPrompt, budget) {
|
|
|
1421
1438
|
const selected = [];
|
|
1422
1439
|
for (let i = history.length - 1; i >= 0; i -= 1) {
|
|
1423
1440
|
const message = history[i];
|
|
1441
|
+
if (!message) continue;
|
|
1424
1442
|
const cost = estimateMessageTokens(message);
|
|
1425
1443
|
if (used + cost > available && selected.length > 0) break;
|
|
1426
1444
|
used += cost;
|
|
1427
1445
|
selected.push(message);
|
|
1428
1446
|
}
|
|
1429
1447
|
selected.reverse();
|
|
1430
|
-
while (selected.length > 1 && (selected[0]
|
|
1448
|
+
while (selected.length > 1 && (selected[0]?.role === "assistant" || selected[0]?.role === "tool")) {
|
|
1431
1449
|
selected.shift();
|
|
1432
1450
|
}
|
|
1433
1451
|
return [{ role: "system", content: systemPrompt }, ...selected];
|
|
@@ -1630,7 +1648,10 @@ function diffLines(before, after) {
|
|
|
1630
1648
|
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
|
1631
1649
|
for (let i2 = m - 1; i2 >= 0; i2 -= 1) {
|
|
1632
1650
|
for (let j2 = n - 1; j2 >= 0; j2 -= 1) {
|
|
1633
|
-
|
|
1651
|
+
const row = dp[i2];
|
|
1652
|
+
if (row) {
|
|
1653
|
+
row[j2] = a[i2] === b[j2] ? (dp[i2 + 1]?.[j2 + 1] ?? 0) + 1 : Math.max(dp[i2 + 1]?.[j2] ?? 0, row[j2 + 1] ?? 0);
|
|
1654
|
+
}
|
|
1634
1655
|
}
|
|
1635
1656
|
}
|
|
1636
1657
|
const out = [];
|
|
@@ -1638,23 +1659,23 @@ function diffLines(before, after) {
|
|
|
1638
1659
|
let j = 0;
|
|
1639
1660
|
while (i < m && j < n) {
|
|
1640
1661
|
if (a[i] === b[j]) {
|
|
1641
|
-
out.push({ type: "same", text: a[i] });
|
|
1662
|
+
out.push({ type: "same", text: a[i] ?? "" });
|
|
1642
1663
|
i += 1;
|
|
1643
1664
|
j += 1;
|
|
1644
|
-
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
|
1645
|
-
out.push({ type: "remove", text: a[i] });
|
|
1665
|
+
} else if ((dp[i + 1]?.[j] ?? 0) >= (dp[i]?.[j + 1] ?? 0)) {
|
|
1666
|
+
out.push({ type: "remove", text: a[i] ?? "" });
|
|
1646
1667
|
i += 1;
|
|
1647
1668
|
} else {
|
|
1648
|
-
out.push({ type: "add", text: b[j] });
|
|
1669
|
+
out.push({ type: "add", text: b[j] ?? "" });
|
|
1649
1670
|
j += 1;
|
|
1650
1671
|
}
|
|
1651
1672
|
}
|
|
1652
1673
|
while (i < m) {
|
|
1653
|
-
out.push({ type: "remove", text: a[i] });
|
|
1674
|
+
out.push({ type: "remove", text: a[i] ?? "" });
|
|
1654
1675
|
i += 1;
|
|
1655
1676
|
}
|
|
1656
1677
|
while (j < n) {
|
|
1657
|
-
out.push({ type: "add", text: b[j] });
|
|
1678
|
+
out.push({ type: "add", text: b[j] ?? "" });
|
|
1658
1679
|
j += 1;
|
|
1659
1680
|
}
|
|
1660
1681
|
return out;
|
|
@@ -1769,14 +1790,14 @@ function dotProduct(a, b) {
|
|
|
1769
1790
|
const length = Math.min(a.length, b.length);
|
|
1770
1791
|
let sum = 0;
|
|
1771
1792
|
for (let i = 0; i < length; i += 1) {
|
|
1772
|
-
sum += a[i] * b[i];
|
|
1793
|
+
sum += (a[i] ?? 0) * (b[i] ?? 0);
|
|
1773
1794
|
}
|
|
1774
1795
|
return sum;
|
|
1775
1796
|
}
|
|
1776
1797
|
function magnitude(v) {
|
|
1777
1798
|
let sum = 0;
|
|
1778
1799
|
for (let i = 0; i < v.length; i += 1) {
|
|
1779
|
-
sum += v[i] * v[i];
|
|
1800
|
+
sum += (v[i] ?? 0) * (v[i] ?? 0);
|
|
1780
1801
|
}
|
|
1781
1802
|
return Math.sqrt(sum);
|
|
1782
1803
|
}
|
|
@@ -1921,8 +1942,118 @@ function validateToolArgs(toolKey, args, schemas) {
|
|
|
1921
1942
|
return { ok: false, error: `Invalid schema definition for tool: ${toolKey}` };
|
|
1922
1943
|
}
|
|
1923
1944
|
|
|
1945
|
+
// src/core/analytics/usage-series.ts
|
|
1946
|
+
function num(value) {
|
|
1947
|
+
const parsed = typeof value === "number" ? value : Number(value ?? 0);
|
|
1948
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
1949
|
+
}
|
|
1950
|
+
function utcDateKey(base, offsetDays) {
|
|
1951
|
+
const shifted = new Date(base.getTime() - offsetDays * 864e5);
|
|
1952
|
+
return shifted.toISOString().slice(0, 10);
|
|
1953
|
+
}
|
|
1954
|
+
function buildUsageDailySeries(days, usageRows, messageRows, today = /* @__PURE__ */ new Date()) {
|
|
1955
|
+
const usageByDate = new Map(usageRows.map((row) => [row.date, row]));
|
|
1956
|
+
const messageByDate = new Map(messageRows.map((row) => [row.date, row]));
|
|
1957
|
+
const series = [];
|
|
1958
|
+
for (let offset = days - 1; offset >= 0; offset -= 1) {
|
|
1959
|
+
const date = utcDateKey(today, offset);
|
|
1960
|
+
const usage = usageByDate.get(date);
|
|
1961
|
+
const message = messageByDate.get(date);
|
|
1962
|
+
series.push({
|
|
1963
|
+
date,
|
|
1964
|
+
requests: num(usage?.requests),
|
|
1965
|
+
attempts: num(message?.attempts),
|
|
1966
|
+
errors: num(message?.errors),
|
|
1967
|
+
inputTokens: num(usage?.inputTokens),
|
|
1968
|
+
outputTokens: num(usage?.outputTokens),
|
|
1969
|
+
reasoningTokens: num(usage?.reasoningTokens),
|
|
1970
|
+
costMicros: num(usage?.costMicros)
|
|
1971
|
+
});
|
|
1972
|
+
}
|
|
1973
|
+
return series;
|
|
1974
|
+
}
|
|
1975
|
+
function usageWindowTotals(series, from, to) {
|
|
1976
|
+
const slice = series.slice(from, to);
|
|
1977
|
+
return slice.reduce(
|
|
1978
|
+
(acc, day) => ({
|
|
1979
|
+
requests: acc.requests + day.requests,
|
|
1980
|
+
attempts: acc.attempts + day.attempts,
|
|
1981
|
+
errors: acc.errors + day.errors,
|
|
1982
|
+
inputTokens: acc.inputTokens + day.inputTokens,
|
|
1983
|
+
outputTokens: acc.outputTokens + day.outputTokens,
|
|
1984
|
+
costMicros: acc.costMicros + day.costMicros
|
|
1985
|
+
}),
|
|
1986
|
+
{ requests: 0, attempts: 0, errors: 0, inputTokens: 0, outputTokens: 0, costMicros: 0 }
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
function usageTrendOf(current, previous) {
|
|
1990
|
+
return {
|
|
1991
|
+
current,
|
|
1992
|
+
previous,
|
|
1993
|
+
deltaPct: previous > 0 ? (current - previous) / previous * 100 : null
|
|
1994
|
+
};
|
|
1995
|
+
}
|
|
1996
|
+
function errorRatePct(errors, attempts) {
|
|
1997
|
+
if (attempts <= 0) return 0;
|
|
1998
|
+
return errors / attempts * 100;
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
// src/core/remote/remote-chat-client.ts
|
|
2002
|
+
async function surfaceHttpError(response, callbacks) {
|
|
2003
|
+
const payload = await response.json().catch(() => null);
|
|
2004
|
+
callbacks.onError?.(payload?.code ?? "request_failed", payload?.error ?? "Request failed");
|
|
2005
|
+
}
|
|
2006
|
+
function createRemoteChatClient(options) {
|
|
2007
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
2008
|
+
const { urls } = options;
|
|
2009
|
+
return {
|
|
2010
|
+
streamChat(conversationId, body, callbacks) {
|
|
2011
|
+
const controller = new AbortController();
|
|
2012
|
+
const promise = (async () => {
|
|
2013
|
+
const response = await doFetch(urls.stream(conversationId), {
|
|
2014
|
+
method: "POST",
|
|
2015
|
+
headers: { "content-type": "application/json" },
|
|
2016
|
+
body: JSON.stringify(body),
|
|
2017
|
+
signal: controller.signal
|
|
2018
|
+
});
|
|
2019
|
+
if (!response.ok) {
|
|
2020
|
+
await surfaceHttpError(response, callbacks);
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
if (!response.body) {
|
|
2024
|
+
callbacks.onError?.("request_failed", "The server returned an empty stream.");
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
await readSseResponse(response, callbacks);
|
|
2028
|
+
})();
|
|
2029
|
+
return {
|
|
2030
|
+
promise,
|
|
2031
|
+
abort: () => controller.abort()
|
|
2032
|
+
};
|
|
2033
|
+
},
|
|
2034
|
+
async resolveToolCall(conversationId, toolCallId, approved, callbacks) {
|
|
2035
|
+
const response = await doFetch(urls.resolveToolCall(conversationId, toolCallId), {
|
|
2036
|
+
method: "POST",
|
|
2037
|
+
headers: { "content-type": "application/json" },
|
|
2038
|
+
body: JSON.stringify({ approved })
|
|
2039
|
+
});
|
|
2040
|
+
if (!response.ok) {
|
|
2041
|
+
await surfaceHttpError(response, callbacks);
|
|
2042
|
+
return false;
|
|
2043
|
+
}
|
|
2044
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
2045
|
+
if (!contentType.includes("text/event-stream") || !response.body) {
|
|
2046
|
+
return false;
|
|
2047
|
+
}
|
|
2048
|
+
await readSseResponse(response, callbacks);
|
|
2049
|
+
return true;
|
|
2050
|
+
}
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
|
|
1924
2054
|
exports.AIError = AIError;
|
|
1925
2055
|
exports.AIErrorType = AIErrorType;
|
|
2056
|
+
exports.AI_ERROR_STATUS = AI_ERROR_STATUS;
|
|
1926
2057
|
exports.AiError = AiError;
|
|
1927
2058
|
exports.CHUNK_MAX_CHARS = CHUNK_MAX_CHARS;
|
|
1928
2059
|
exports.CHUNK_OVERLAP_CHARS = CHUNK_OVERLAP_CHARS;
|
|
@@ -1981,6 +2112,7 @@ exports.ToolCallAccumulator = ToolCallAccumulator;
|
|
|
1981
2112
|
exports.USER_FRIENDLY_ERROR_MESSAGES = USER_FRIENDLY_ERROR_MESSAGES;
|
|
1982
2113
|
exports.accumulateReport = accumulateReport;
|
|
1983
2114
|
exports.aiErrorMessage = aiErrorMessage;
|
|
2115
|
+
exports.aiErrorStatus = aiErrorStatus;
|
|
1984
2116
|
exports.asObjectArray = asObjectArray;
|
|
1985
2117
|
exports.asRecord = asRecord;
|
|
1986
2118
|
exports.asStringArray = asStringArray;
|
|
@@ -1991,6 +2123,7 @@ exports.buildContext = buildContext;
|
|
|
1991
2123
|
exports.buildHttpStatusFallback = buildHttpStatusFallback;
|
|
1992
2124
|
exports.buildResearchMessages = buildResearchMessages;
|
|
1993
2125
|
exports.buildSystemPrompt = buildSystemPrompt;
|
|
2126
|
+
exports.buildUsageDailySeries = buildUsageDailySeries;
|
|
1994
2127
|
exports.buildUsageData = buildUsageData;
|
|
1995
2128
|
exports.cacheManager = cacheManager;
|
|
1996
2129
|
exports.calculateCacheHitRate = calculateCacheHitRate;
|
|
@@ -2005,6 +2138,7 @@ exports.classifyHttpStatus = classifyHttpStatus;
|
|
|
2005
2138
|
exports.computeCostMicros = computeCostMicros;
|
|
2006
2139
|
exports.cosineSimilarity = cosineSimilarity;
|
|
2007
2140
|
exports.countChanges = countChanges;
|
|
2141
|
+
exports.createRemoteChatClient = createRemoteChatClient;
|
|
2008
2142
|
exports.createSseResponse = createSseResponse;
|
|
2009
2143
|
exports.debounce = debounce;
|
|
2010
2144
|
exports.debounceManager = debounceManager;
|
|
@@ -2015,6 +2149,7 @@ exports.diffLines = diffLines;
|
|
|
2015
2149
|
exports.dotProduct = dotProduct;
|
|
2016
2150
|
exports.errorFromStatus = errorFromStatus;
|
|
2017
2151
|
exports.errorFromUnknown = errorFromUnknown;
|
|
2152
|
+
exports.errorRatePct = errorRatePct;
|
|
2018
2153
|
exports.estimateMessageTokens = estimateMessageTokens;
|
|
2019
2154
|
exports.estimateTokens = estimateTokens;
|
|
2020
2155
|
exports.extractErrorMessageFromJsonBody = extractErrorMessageFromJsonBody;
|
|
@@ -2067,6 +2202,8 @@ exports.splitSseLines = splitSseLines;
|
|
|
2067
2202
|
exports.sseStreamResponse = sseStreamResponse;
|
|
2068
2203
|
exports.throttle = throttle;
|
|
2069
2204
|
exports.throttleManager = throttleManager;
|
|
2205
|
+
exports.usageTrendOf = usageTrendOf;
|
|
2206
|
+
exports.usageWindowTotals = usageWindowTotals;
|
|
2070
2207
|
exports.validateApiKey = validateApiKey;
|
|
2071
2208
|
exports.validateToolArgs = validateToolArgs;
|
|
2072
2209
|
exports.withRetry = withRetry;
|