@codelia/core 0.1.22 → 0.1.25
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/index.cjs +884 -23
- package/dist/index.d.cts +38 -1
- package/dist/index.d.ts +38 -1
- package/dist/index.js +884 -23
- package/package.json +4 -4
- package/prompts/system.md +2 -0
package/dist/index.cjs
CHANGED
|
@@ -2643,7 +2643,7 @@ function toResponsesToolChoice(choice) {
|
|
|
2643
2643
|
}
|
|
2644
2644
|
return { type: "function", name: choice };
|
|
2645
2645
|
}
|
|
2646
|
-
function toChatInvokeCompletion2(response) {
|
|
2646
|
+
function toChatInvokeCompletion2(response, meta) {
|
|
2647
2647
|
const usage = response.usage ? {
|
|
2648
2648
|
model: response.model,
|
|
2649
2649
|
input_tokens: response.usage.input_tokens,
|
|
@@ -2663,7 +2663,13 @@ function toChatInvokeCompletion2(response) {
|
|
|
2663
2663
|
usage,
|
|
2664
2664
|
stop_reason: response.incomplete_details?.reason ?? response.status ?? null,
|
|
2665
2665
|
provider_meta: {
|
|
2666
|
-
response_id: response.id
|
|
2666
|
+
response_id: response.id,
|
|
2667
|
+
...meta?.transport ? { transport: meta.transport } : {},
|
|
2668
|
+
...meta?.websocket_mode ? { websocket_mode: meta.websocket_mode } : {},
|
|
2669
|
+
...typeof meta?.fallback_used === "boolean" ? { fallback_used: meta.fallback_used } : {},
|
|
2670
|
+
...typeof meta?.chain_reset === "boolean" ? { chain_reset: meta.chain_reset } : {},
|
|
2671
|
+
...typeof meta?.ws_reconnect_count === "number" ? { ws_reconnect_count: meta.ws_reconnect_count } : {},
|
|
2672
|
+
...typeof meta?.ws_input_mode === "string" ? { ws_input_mode: meta.ws_input_mode } : {}
|
|
2667
2673
|
}
|
|
2668
2674
|
};
|
|
2669
2675
|
}
|
|
@@ -2735,6 +2741,545 @@ function toOpenAiHostedSearchTool(tool) {
|
|
|
2735
2741
|
};
|
|
2736
2742
|
}
|
|
2737
2743
|
|
|
2744
|
+
// src/llm/openai/http-transport.ts
|
|
2745
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader) => {
|
|
2746
|
+
const streamRequest = {
|
|
2747
|
+
...request,
|
|
2748
|
+
stream: true
|
|
2749
|
+
};
|
|
2750
|
+
return client.responses.stream(
|
|
2751
|
+
streamRequest,
|
|
2752
|
+
signal || sessionIdHeader ? {
|
|
2753
|
+
...signal ? { signal } : {},
|
|
2754
|
+
...sessionIdHeader ? {
|
|
2755
|
+
headers: {
|
|
2756
|
+
session_id: sessionIdHeader
|
|
2757
|
+
}
|
|
2758
|
+
} : {}
|
|
2759
|
+
} : void 0
|
|
2760
|
+
).finalResponse();
|
|
2761
|
+
};
|
|
2762
|
+
|
|
2763
|
+
// src/llm/openai/websocket-transport.ts
|
|
2764
|
+
var import_ws = require("openai/resources/responses/ws");
|
|
2765
|
+
var WS_RESPONSE_TIMEOUT_MS = 45e3;
|
|
2766
|
+
var WS_UNEXPECTED_RESPONSE_BODY_TIMEOUT_MS = 250;
|
|
2767
|
+
var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
2768
|
+
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
2769
|
+
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
2770
|
+
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
2771
|
+
var WsResponseError = class extends Error {
|
|
2772
|
+
constructor(message, code) {
|
|
2773
|
+
super(message);
|
|
2774
|
+
this.code = code;
|
|
2775
|
+
}
|
|
2776
|
+
};
|
|
2777
|
+
var OpenAiWsTransport = class {
|
|
2778
|
+
client;
|
|
2779
|
+
websocketApiVersion;
|
|
2780
|
+
createResponsesWs;
|
|
2781
|
+
constructor(options) {
|
|
2782
|
+
this.client = options.client;
|
|
2783
|
+
this.websocketApiVersion = options.websocketApiVersion;
|
|
2784
|
+
this.createResponsesWs = options.createResponsesWs;
|
|
2785
|
+
}
|
|
2786
|
+
async invoke(args) {
|
|
2787
|
+
await this.prepareClientForWsHandshake();
|
|
2788
|
+
const wsOptionsHeaders = {
|
|
2789
|
+
...this.getClientDefaultHeaders(),
|
|
2790
|
+
[OPENAI_BETA_HEADER]: this.websocketApiVersion === "v2" ? OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 : OPENAI_BETA_RESPONSES_WEBSOCKETS_V1
|
|
2791
|
+
};
|
|
2792
|
+
if (args.sessionIdHeader) {
|
|
2793
|
+
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
2794
|
+
}
|
|
2795
|
+
const wsOptions = { headers: wsOptionsHeaders };
|
|
2796
|
+
const ownsWs = !args.ws;
|
|
2797
|
+
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new import_ws.ResponsesWS(
|
|
2798
|
+
this.client,
|
|
2799
|
+
wsOptions
|
|
2800
|
+
));
|
|
2801
|
+
if (!args.ws) {
|
|
2802
|
+
ws.on("error", () => {
|
|
2803
|
+
});
|
|
2804
|
+
}
|
|
2805
|
+
try {
|
|
2806
|
+
await this.waitForWsOpen(ws, args.signal);
|
|
2807
|
+
let settled = false;
|
|
2808
|
+
let rejectResponsePromise;
|
|
2809
|
+
const closeWs = () => {
|
|
2810
|
+
this.closeWithoutMaskingPrimaryError(ws, "done");
|
|
2811
|
+
};
|
|
2812
|
+
const responsePromise = new Promise((resolve, reject) => {
|
|
2813
|
+
let onAbort;
|
|
2814
|
+
const nativeSocket = this.getNativeSocket(ws);
|
|
2815
|
+
let removeNativeClose;
|
|
2816
|
+
let removeNativeError;
|
|
2817
|
+
const timeout = setTimeout(() => {
|
|
2818
|
+
if (settled) return;
|
|
2819
|
+
settled = true;
|
|
2820
|
+
teardown();
|
|
2821
|
+
reject(new Error("openai websocket response timeout"));
|
|
2822
|
+
}, WS_RESPONSE_TIMEOUT_MS);
|
|
2823
|
+
const teardown = () => {
|
|
2824
|
+
if (ws.off) {
|
|
2825
|
+
ws.off("error", onError);
|
|
2826
|
+
ws.off("response.failed", onResponseFailed);
|
|
2827
|
+
ws.off("response.completed", onResponseCompleted);
|
|
2828
|
+
ws.off("close", onClose);
|
|
2829
|
+
}
|
|
2830
|
+
removeNativeClose?.();
|
|
2831
|
+
removeNativeError?.();
|
|
2832
|
+
if (args.signal && onAbort) {
|
|
2833
|
+
args.signal.removeEventListener("abort", onAbort);
|
|
2834
|
+
}
|
|
2835
|
+
};
|
|
2836
|
+
const resolveOnce = (response2) => {
|
|
2837
|
+
if (settled) return;
|
|
2838
|
+
settled = true;
|
|
2839
|
+
clearTimeout(timeout);
|
|
2840
|
+
teardown();
|
|
2841
|
+
resolve(response2);
|
|
2842
|
+
};
|
|
2843
|
+
const rejectOnce = (error) => {
|
|
2844
|
+
if (settled) return;
|
|
2845
|
+
settled = true;
|
|
2846
|
+
clearTimeout(timeout);
|
|
2847
|
+
teardown();
|
|
2848
|
+
reject(error);
|
|
2849
|
+
};
|
|
2850
|
+
rejectResponsePromise = rejectOnce;
|
|
2851
|
+
const onError = (error) => {
|
|
2852
|
+
rejectOnce(error);
|
|
2853
|
+
};
|
|
2854
|
+
const onResponseFailed = (event) => {
|
|
2855
|
+
const failed = event;
|
|
2856
|
+
const message = failed.response?.error?.message;
|
|
2857
|
+
const code = failed.response?.error?.code ?? void 0;
|
|
2858
|
+
rejectOnce(
|
|
2859
|
+
new WsResponseError(
|
|
2860
|
+
message || "openai websocket response failed",
|
|
2861
|
+
typeof code === "string" ? code : void 0
|
|
2862
|
+
)
|
|
2863
|
+
);
|
|
2864
|
+
};
|
|
2865
|
+
const onResponseCompleted = (event) => {
|
|
2866
|
+
const completed = event;
|
|
2867
|
+
resolveOnce(completed.response);
|
|
2868
|
+
};
|
|
2869
|
+
const onClose = (event) => {
|
|
2870
|
+
const closeCode = this.extractWsCloseCode(event);
|
|
2871
|
+
rejectOnce(
|
|
2872
|
+
new Error(
|
|
2873
|
+
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
2874
|
+
)
|
|
2875
|
+
);
|
|
2876
|
+
};
|
|
2877
|
+
ws.on("error", onError);
|
|
2878
|
+
ws.on("response.failed", onResponseFailed);
|
|
2879
|
+
ws.on("response.completed", onResponseCompleted);
|
|
2880
|
+
ws.on("close", onClose);
|
|
2881
|
+
removeNativeClose = this.addNativeSocketListener(
|
|
2882
|
+
nativeSocket,
|
|
2883
|
+
"close",
|
|
2884
|
+
(...events) => {
|
|
2885
|
+
onClose(events[0]);
|
|
2886
|
+
}
|
|
2887
|
+
);
|
|
2888
|
+
removeNativeError = this.addNativeSocketListener(
|
|
2889
|
+
nativeSocket,
|
|
2890
|
+
"error",
|
|
2891
|
+
(error) => {
|
|
2892
|
+
onError(error);
|
|
2893
|
+
}
|
|
2894
|
+
);
|
|
2895
|
+
if (args.signal) {
|
|
2896
|
+
onAbort = () => {
|
|
2897
|
+
rejectOnce(new Error("openai websocket request aborted"));
|
|
2898
|
+
closeWs();
|
|
2899
|
+
};
|
|
2900
|
+
args.signal.addEventListener("abort", onAbort, { once: true });
|
|
2901
|
+
if (args.signal.aborted) {
|
|
2902
|
+
onAbort();
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
});
|
|
2906
|
+
const responseCreateEvent = {
|
|
2907
|
+
type: "response.create",
|
|
2908
|
+
...args.request
|
|
2909
|
+
};
|
|
2910
|
+
if (!settled) {
|
|
2911
|
+
try {
|
|
2912
|
+
ws.send(responseCreateEvent);
|
|
2913
|
+
} catch (error) {
|
|
2914
|
+
rejectResponsePromise?.(error);
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
const response = await responsePromise;
|
|
2918
|
+
return { response, ws };
|
|
2919
|
+
} catch (error) {
|
|
2920
|
+
if (ownsWs) {
|
|
2921
|
+
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
2922
|
+
}
|
|
2923
|
+
throw error;
|
|
2924
|
+
}
|
|
2925
|
+
}
|
|
2926
|
+
closeSafely(ws, reason) {
|
|
2927
|
+
if (!ws) {
|
|
2928
|
+
return;
|
|
2929
|
+
}
|
|
2930
|
+
try {
|
|
2931
|
+
ws.close({ code: 1e3, reason });
|
|
2932
|
+
} catch (error) {
|
|
2933
|
+
if (this.isExpectedWsCloseError(error)) {
|
|
2934
|
+
console.error(
|
|
2935
|
+
`[openai.ws] close_expected_failure reason=${reason} error=${String(error)}`
|
|
2936
|
+
);
|
|
2937
|
+
return;
|
|
2938
|
+
}
|
|
2939
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
2940
|
+
}
|
|
2941
|
+
}
|
|
2942
|
+
closeWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
2943
|
+
try {
|
|
2944
|
+
this.closeSafely(ws, reason);
|
|
2945
|
+
} catch (closeError) {
|
|
2946
|
+
const suffix = primaryError ? ` primary_error=${String(primaryError)}` : "";
|
|
2947
|
+
console.error(
|
|
2948
|
+
`[openai.ws] close_unexpected_failure reason=${reason} error=${String(closeError)}${suffix}`
|
|
2949
|
+
);
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
isConnectionReusable(ws) {
|
|
2953
|
+
if (!ws) {
|
|
2954
|
+
return false;
|
|
2955
|
+
}
|
|
2956
|
+
const socket = this.getNativeSocket(ws);
|
|
2957
|
+
if (!socket) {
|
|
2958
|
+
return true;
|
|
2959
|
+
}
|
|
2960
|
+
if (typeof socket.readyState !== "number") {
|
|
2961
|
+
return true;
|
|
2962
|
+
}
|
|
2963
|
+
const openState = typeof socket.OPEN === "number" ? socket.OPEN : 1;
|
|
2964
|
+
const connectingState = typeof socket.CONNECTING === "number" ? socket.CONNECTING : 0;
|
|
2965
|
+
return socket.readyState === openState || socket.readyState === connectingState;
|
|
2966
|
+
}
|
|
2967
|
+
extractErrorCode(error) {
|
|
2968
|
+
if (error instanceof WsResponseError && typeof error.code === "string") {
|
|
2969
|
+
return error.code;
|
|
2970
|
+
}
|
|
2971
|
+
if (!error || typeof error !== "object") {
|
|
2972
|
+
return void 0;
|
|
2973
|
+
}
|
|
2974
|
+
const maybeError = error;
|
|
2975
|
+
if (typeof maybeError.code === "string") {
|
|
2976
|
+
return maybeError.code;
|
|
2977
|
+
}
|
|
2978
|
+
if (typeof maybeError.error?.code === "string") {
|
|
2979
|
+
return maybeError.error.code;
|
|
2980
|
+
}
|
|
2981
|
+
if (typeof maybeError.error?.error?.code === "string") {
|
|
2982
|
+
return maybeError.error.error.code;
|
|
2983
|
+
}
|
|
2984
|
+
return void 0;
|
|
2985
|
+
}
|
|
2986
|
+
async prepareClientForWsHandshake() {
|
|
2987
|
+
const maybeClient = this.client;
|
|
2988
|
+
if (typeof maybeClient.prepareOptions !== "function") {
|
|
2989
|
+
return;
|
|
2990
|
+
}
|
|
2991
|
+
await maybeClient.prepareOptions({});
|
|
2992
|
+
}
|
|
2993
|
+
getClientDefaultHeaders() {
|
|
2994
|
+
const headers = {};
|
|
2995
|
+
const source = this.client._options?.defaultHeaders;
|
|
2996
|
+
if (!source) {
|
|
2997
|
+
return headers;
|
|
2998
|
+
}
|
|
2999
|
+
const addHeader = (key, value) => {
|
|
3000
|
+
if (!key) return;
|
|
3001
|
+
if (value === void 0 || value === null) return;
|
|
3002
|
+
headers[key] = String(value);
|
|
3003
|
+
};
|
|
3004
|
+
if (source instanceof Headers) {
|
|
3005
|
+
for (const [key, value] of source.entries()) {
|
|
3006
|
+
addHeader(key, value);
|
|
3007
|
+
}
|
|
3008
|
+
return headers;
|
|
3009
|
+
}
|
|
3010
|
+
if (Array.isArray(source)) {
|
|
3011
|
+
for (const item of source) {
|
|
3012
|
+
if (!Array.isArray(item) || item.length < 2) continue;
|
|
3013
|
+
addHeader(String(item[0]), item[1]);
|
|
3014
|
+
}
|
|
3015
|
+
return headers;
|
|
3016
|
+
}
|
|
3017
|
+
if (typeof source === "object") {
|
|
3018
|
+
for (const [key, value] of Object.entries(source)) {
|
|
3019
|
+
addHeader(key, value);
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
return headers;
|
|
3023
|
+
}
|
|
3024
|
+
getNativeSocket(ws) {
|
|
3025
|
+
const maybeSocket = ws.socket;
|
|
3026
|
+
if (!maybeSocket || typeof maybeSocket !== "object") {
|
|
3027
|
+
return void 0;
|
|
3028
|
+
}
|
|
3029
|
+
return maybeSocket;
|
|
3030
|
+
}
|
|
3031
|
+
addNativeSocketListener(socket, event, listener) {
|
|
3032
|
+
if (!socket) {
|
|
3033
|
+
return void 0;
|
|
3034
|
+
}
|
|
3035
|
+
if (typeof socket.on === "function") {
|
|
3036
|
+
socket.on(event, listener);
|
|
3037
|
+
return () => {
|
|
3038
|
+
if (typeof socket.off === "function") {
|
|
3039
|
+
socket.off(event, listener);
|
|
3040
|
+
}
|
|
3041
|
+
};
|
|
3042
|
+
}
|
|
3043
|
+
if (typeof socket.addEventListener === "function") {
|
|
3044
|
+
socket.addEventListener(event, listener);
|
|
3045
|
+
return () => {
|
|
3046
|
+
if (typeof socket.removeEventListener === "function") {
|
|
3047
|
+
socket.removeEventListener(event, listener);
|
|
3048
|
+
}
|
|
3049
|
+
};
|
|
3050
|
+
}
|
|
3051
|
+
return void 0;
|
|
3052
|
+
}
|
|
3053
|
+
extractWsCloseCode(event) {
|
|
3054
|
+
if (typeof event === "number") {
|
|
3055
|
+
return event;
|
|
3056
|
+
}
|
|
3057
|
+
if (!event || typeof event !== "object") {
|
|
3058
|
+
return void 0;
|
|
3059
|
+
}
|
|
3060
|
+
const maybeEvent = event;
|
|
3061
|
+
return typeof maybeEvent.code === "number" ? maybeEvent.code : void 0;
|
|
3062
|
+
}
|
|
3063
|
+
isExpectedWsCloseError(error) {
|
|
3064
|
+
if (!error || typeof error !== "object") {
|
|
3065
|
+
return false;
|
|
3066
|
+
}
|
|
3067
|
+
const maybeError = error;
|
|
3068
|
+
if (typeof maybeError.code === "string") {
|
|
3069
|
+
if (maybeError.code === "ERR_SOCKET_CLOSED" || maybeError.code === "ERR_INVALID_STATE") {
|
|
3070
|
+
return true;
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
if (typeof maybeError.message !== "string") {
|
|
3074
|
+
return false;
|
|
3075
|
+
}
|
|
3076
|
+
const message = maybeError.message.toLowerCase();
|
|
3077
|
+
return message.includes("not open") || message.includes("already closed") || message.includes("was closed before") || message.includes("readystate") || message.includes("closing") || message.includes("closed");
|
|
3078
|
+
}
|
|
3079
|
+
formatUnexpectedResponseHeaders(headers) {
|
|
3080
|
+
if (!headers || typeof headers !== "object") {
|
|
3081
|
+
return void 0;
|
|
3082
|
+
}
|
|
3083
|
+
const entries = Object.entries(headers);
|
|
3084
|
+
if (entries.length === 0) {
|
|
3085
|
+
return void 0;
|
|
3086
|
+
}
|
|
3087
|
+
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
3088
|
+
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
3089
|
+
return `${key}:${text}`;
|
|
3090
|
+
});
|
|
3091
|
+
return limited.join(", ");
|
|
3092
|
+
}
|
|
3093
|
+
toUnexpectedResponseChunkText(chunk) {
|
|
3094
|
+
if (typeof chunk === "string") {
|
|
3095
|
+
return chunk;
|
|
3096
|
+
}
|
|
3097
|
+
if (chunk instanceof Uint8Array) {
|
|
3098
|
+
return Buffer.from(chunk).toString("utf8");
|
|
3099
|
+
}
|
|
3100
|
+
if (chunk instanceof ArrayBuffer) {
|
|
3101
|
+
return Buffer.from(chunk).toString("utf8");
|
|
3102
|
+
}
|
|
3103
|
+
if (ArrayBuffer.isView(chunk)) {
|
|
3104
|
+
return Buffer.from(
|
|
3105
|
+
chunk.buffer,
|
|
3106
|
+
chunk.byteOffset,
|
|
3107
|
+
chunk.byteLength
|
|
3108
|
+
).toString("utf8");
|
|
3109
|
+
}
|
|
3110
|
+
return "";
|
|
3111
|
+
}
|
|
3112
|
+
async readUnexpectedResponseBody(response) {
|
|
3113
|
+
if (typeof response.on !== "function") {
|
|
3114
|
+
return void 0;
|
|
3115
|
+
}
|
|
3116
|
+
return new Promise((resolve) => {
|
|
3117
|
+
let body = "";
|
|
3118
|
+
let settled = false;
|
|
3119
|
+
const listeners = [];
|
|
3120
|
+
const removeListeners = () => {
|
|
3121
|
+
if (typeof response.off !== "function") {
|
|
3122
|
+
return;
|
|
3123
|
+
}
|
|
3124
|
+
for (const entry of listeners) {
|
|
3125
|
+
response.off(entry.event, entry.listener);
|
|
3126
|
+
}
|
|
3127
|
+
};
|
|
3128
|
+
const settle = () => {
|
|
3129
|
+
if (settled) return;
|
|
3130
|
+
settled = true;
|
|
3131
|
+
clearTimeout(timeout);
|
|
3132
|
+
removeListeners();
|
|
3133
|
+
const normalized = body.trim();
|
|
3134
|
+
resolve(normalized.length > 0 ? normalized : void 0);
|
|
3135
|
+
};
|
|
3136
|
+
const addListener = (event, listener) => {
|
|
3137
|
+
response.on?.(event, listener);
|
|
3138
|
+
listeners.push({ event, listener });
|
|
3139
|
+
};
|
|
3140
|
+
const timeout = setTimeout(() => {
|
|
3141
|
+
settle();
|
|
3142
|
+
}, WS_UNEXPECTED_RESPONSE_BODY_TIMEOUT_MS);
|
|
3143
|
+
addListener("data", (chunk) => {
|
|
3144
|
+
if (body.length >= WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS) {
|
|
3145
|
+
return;
|
|
3146
|
+
}
|
|
3147
|
+
const text = this.toUnexpectedResponseChunkText(chunk);
|
|
3148
|
+
if (!text) {
|
|
3149
|
+
return;
|
|
3150
|
+
}
|
|
3151
|
+
const remaining = WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS - body.length;
|
|
3152
|
+
body += text.slice(0, remaining);
|
|
3153
|
+
});
|
|
3154
|
+
addListener("end", () => {
|
|
3155
|
+
settle();
|
|
3156
|
+
});
|
|
3157
|
+
addListener("error", () => {
|
|
3158
|
+
settle();
|
|
3159
|
+
});
|
|
3160
|
+
});
|
|
3161
|
+
}
|
|
3162
|
+
async createUnexpectedResponseError(responseLike) {
|
|
3163
|
+
const response = responseLike && typeof responseLike === "object" ? responseLike : void 0;
|
|
3164
|
+
if (!response) {
|
|
3165
|
+
return new Error("unexpected server response");
|
|
3166
|
+
}
|
|
3167
|
+
const status = typeof response.statusCode === "number" ? response.statusCode : void 0;
|
|
3168
|
+
const headers = this.formatUnexpectedResponseHeaders(response.headers);
|
|
3169
|
+
const body = await this.readUnexpectedResponseBody(response);
|
|
3170
|
+
const detailParts = [];
|
|
3171
|
+
if (headers) {
|
|
3172
|
+
detailParts.push(`headers=${headers}`);
|
|
3173
|
+
}
|
|
3174
|
+
if (body) {
|
|
3175
|
+
detailParts.push(`body=${body}`);
|
|
3176
|
+
}
|
|
3177
|
+
const suffix = detailParts.length > 0 ? ` (${detailParts.join(" ")})` : "";
|
|
3178
|
+
return new Error(
|
|
3179
|
+
`unexpected server response${status ? `: ${status}` : ""}${suffix}`
|
|
3180
|
+
);
|
|
3181
|
+
}
|
|
3182
|
+
async waitForWsOpen(ws, signal) {
|
|
3183
|
+
const maybeSocket = ws.socket;
|
|
3184
|
+
if (!maybeSocket || typeof maybeSocket !== "object") {
|
|
3185
|
+
return;
|
|
3186
|
+
}
|
|
3187
|
+
const socket = maybeSocket;
|
|
3188
|
+
const openState = typeof socket.OPEN === "number" ? socket.OPEN : 1;
|
|
3189
|
+
const connectingState = typeof socket.CONNECTING === "number" ? socket.CONNECTING : 0;
|
|
3190
|
+
if (socket.readyState === openState) {
|
|
3191
|
+
return;
|
|
3192
|
+
}
|
|
3193
|
+
if (socket.readyState !== connectingState) {
|
|
3194
|
+
throw new Error(
|
|
3195
|
+
`openai websocket is not open (readyState=${String(socket.readyState ?? "unknown")})`
|
|
3196
|
+
);
|
|
3197
|
+
}
|
|
3198
|
+
if (signal?.aborted) {
|
|
3199
|
+
throw new Error("openai websocket aborted before open");
|
|
3200
|
+
}
|
|
3201
|
+
await new Promise((resolve, reject) => {
|
|
3202
|
+
let settled = false;
|
|
3203
|
+
const removeFns = [];
|
|
3204
|
+
const teardown = () => {
|
|
3205
|
+
for (const remove of removeFns) {
|
|
3206
|
+
remove();
|
|
3207
|
+
}
|
|
3208
|
+
};
|
|
3209
|
+
const settleResolve = () => {
|
|
3210
|
+
if (settled) return;
|
|
3211
|
+
settled = true;
|
|
3212
|
+
clearTimeout(timeout);
|
|
3213
|
+
teardown();
|
|
3214
|
+
resolve();
|
|
3215
|
+
};
|
|
3216
|
+
const settleReject = (error) => {
|
|
3217
|
+
if (settled) return;
|
|
3218
|
+
settled = true;
|
|
3219
|
+
clearTimeout(timeout);
|
|
3220
|
+
teardown();
|
|
3221
|
+
reject(error);
|
|
3222
|
+
};
|
|
3223
|
+
const addSocketListener = (event, listener) => {
|
|
3224
|
+
if (typeof socket.on === "function") {
|
|
3225
|
+
socket.on(event, listener);
|
|
3226
|
+
removeFns.push(() => {
|
|
3227
|
+
if (typeof socket.off === "function") {
|
|
3228
|
+
socket.off(event, listener);
|
|
3229
|
+
}
|
|
3230
|
+
});
|
|
3231
|
+
return;
|
|
3232
|
+
}
|
|
3233
|
+
if (typeof socket.addEventListener === "function") {
|
|
3234
|
+
socket.addEventListener(event, listener);
|
|
3235
|
+
removeFns.push(() => {
|
|
3236
|
+
if (typeof socket.removeEventListener === "function") {
|
|
3237
|
+
socket.removeEventListener(event, listener);
|
|
3238
|
+
}
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
};
|
|
3242
|
+
const timeout = setTimeout(() => {
|
|
3243
|
+
settleReject(new Error("openai websocket connect timeout"));
|
|
3244
|
+
}, WS_RESPONSE_TIMEOUT_MS);
|
|
3245
|
+
addSocketListener("open", () => {
|
|
3246
|
+
settleResolve();
|
|
3247
|
+
});
|
|
3248
|
+
addSocketListener("error", (error) => {
|
|
3249
|
+
settleReject(error);
|
|
3250
|
+
});
|
|
3251
|
+
addSocketListener(
|
|
3252
|
+
"unexpected-response",
|
|
3253
|
+
(...args) => {
|
|
3254
|
+
void this.createUnexpectedResponseError(args[1]).then((error) => {
|
|
3255
|
+
settleReject(error);
|
|
3256
|
+
}).catch((error) => {
|
|
3257
|
+
settleReject(error);
|
|
3258
|
+
});
|
|
3259
|
+
}
|
|
3260
|
+
);
|
|
3261
|
+
addSocketListener("close", (code) => {
|
|
3262
|
+
const closeCode = typeof code === "number" ? ` code=${code}` : "";
|
|
3263
|
+
settleReject(
|
|
3264
|
+
new Error(`openai websocket closed before open${closeCode}`)
|
|
3265
|
+
);
|
|
3266
|
+
});
|
|
3267
|
+
if (signal) {
|
|
3268
|
+
const onAbort = () => {
|
|
3269
|
+
settleReject(new Error("openai websocket aborted before open"));
|
|
3270
|
+
};
|
|
3271
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
3272
|
+
removeFns.push(() => {
|
|
3273
|
+
signal.removeEventListener("abort", onAbort);
|
|
3274
|
+
});
|
|
3275
|
+
}
|
|
3276
|
+
if (socket.readyState === openState) {
|
|
3277
|
+
settleResolve();
|
|
3278
|
+
}
|
|
3279
|
+
});
|
|
3280
|
+
}
|
|
3281
|
+
};
|
|
3282
|
+
|
|
2738
3283
|
// src/llm/openai/chat.ts
|
|
2739
3284
|
var PROVIDER_NAME2 = "openai";
|
|
2740
3285
|
var DEFAULT_MODEL2 = OPENAI_DEFAULT_MODEL;
|
|
@@ -2743,19 +3288,35 @@ var DEFAULT_REASONING_SUMMARY = "auto";
|
|
|
2743
3288
|
var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
2744
3289
|
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
2745
3290
|
};
|
|
3291
|
+
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
3292
|
+
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
3293
|
+
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
2746
3294
|
var ChatOpenAI = class {
|
|
2747
3295
|
provider = PROVIDER_NAME2;
|
|
2748
3296
|
model;
|
|
2749
3297
|
client;
|
|
2750
3298
|
defaultReasoningEffort;
|
|
2751
3299
|
defaultTextVerbosity;
|
|
3300
|
+
websocketMode;
|
|
3301
|
+
websocketApiVersion;
|
|
3302
|
+
wsTransport;
|
|
2752
3303
|
debugInvokeSeq = 0;
|
|
2753
3304
|
lastDebugRequestPayload = null;
|
|
3305
|
+
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
3306
|
+
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
3307
|
+
wsReconnectCount = 0;
|
|
2754
3308
|
constructor(options = {}) {
|
|
2755
3309
|
this.client = options.client ?? new import_openai3.default(options.clientOptions);
|
|
2756
3310
|
this.model = options.model ?? DEFAULT_MODEL2;
|
|
2757
3311
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT;
|
|
2758
3312
|
this.defaultTextVerbosity = options.textVerbosity;
|
|
3313
|
+
this.websocketMode = options.websocketMode ?? "off";
|
|
3314
|
+
this.websocketApiVersion = options.websocketApiVersion ?? "v2";
|
|
3315
|
+
this.wsTransport = new OpenAiWsTransport({
|
|
3316
|
+
client: this.client,
|
|
3317
|
+
websocketApiVersion: this.websocketApiVersion,
|
|
3318
|
+
createResponsesWs: options.createResponsesWs
|
|
3319
|
+
});
|
|
2759
3320
|
}
|
|
2760
3321
|
async ainvoke(input, context) {
|
|
2761
3322
|
const {
|
|
@@ -2808,31 +3369,329 @@ var ChatOpenAI = class {
|
|
|
2808
3369
|
}
|
|
2809
3370
|
const sessionIdHeader = getSessionIdHeaderValue(request.prompt_cache_key);
|
|
2810
3371
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
3372
|
+
const requestMeta = {
|
|
3373
|
+
model: String(request.model ?? this.model),
|
|
3374
|
+
instructionsHash: (0, import_node_crypto2.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
3375
|
+
toolsHash: (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
2815
3376
|
};
|
|
2816
|
-
const
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
3377
|
+
const transportResult = await this.invokeWithTransport({
|
|
3378
|
+
request,
|
|
3379
|
+
sessionKey: context?.sessionKey,
|
|
3380
|
+
sessionIdHeader,
|
|
3381
|
+
signal,
|
|
3382
|
+
debugSeq,
|
|
3383
|
+
requestMeta
|
|
3384
|
+
});
|
|
3385
|
+
await this.debugResponseIfEnabled(
|
|
3386
|
+
transportResult.response,
|
|
3387
|
+
debugSeq,
|
|
3388
|
+
transportResult.transport
|
|
3389
|
+
);
|
|
3390
|
+
return toChatInvokeCompletion2(transportResult.response, {
|
|
3391
|
+
transport: transportResult.transport,
|
|
3392
|
+
websocket_mode: this.websocketMode,
|
|
3393
|
+
fallback_used: transportResult.fallbackUsed,
|
|
3394
|
+
chain_reset: transportResult.chainReset,
|
|
3395
|
+
ws_reconnect_count: this.wsReconnectCount,
|
|
3396
|
+
ws_input_mode: transportResult.wsInputMode
|
|
3397
|
+
});
|
|
3398
|
+
}
|
|
3399
|
+
async invokeWithTransport(args) {
|
|
3400
|
+
this.evictIdleWsSessionState();
|
|
3401
|
+
if (this.websocketMode === "off") {
|
|
3402
|
+
return this.invokeHttpTransportWithDebug({
|
|
3403
|
+
request: args.request,
|
|
3404
|
+
debugSeq: args.debugSeq,
|
|
3405
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3406
|
+
signal: args.signal,
|
|
3407
|
+
fallbackUsed: false,
|
|
3408
|
+
chainReset: false
|
|
3409
|
+
});
|
|
3410
|
+
}
|
|
3411
|
+
if (!args.sessionKey) {
|
|
3412
|
+
if (this.websocketMode === "on") {
|
|
3413
|
+
throw new Error(
|
|
3414
|
+
"openai websocket_mode=on requires a session key for stable chaining"
|
|
3415
|
+
);
|
|
3416
|
+
}
|
|
3417
|
+
return this.invokeHttpTransportWithDebug({
|
|
3418
|
+
request: args.request,
|
|
3419
|
+
debugSeq: args.debugSeq,
|
|
3420
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3421
|
+
signal: args.signal,
|
|
3422
|
+
fallbackUsed: false,
|
|
3423
|
+
chainReset: false
|
|
3424
|
+
});
|
|
3425
|
+
}
|
|
3426
|
+
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
3427
|
+
return this.invokeHttpTransportWithDebug({
|
|
3428
|
+
request: args.request,
|
|
3429
|
+
debugSeq: args.debugSeq,
|
|
3430
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3431
|
+
signal: args.signal,
|
|
3432
|
+
fallbackUsed: true,
|
|
3433
|
+
chainReset: true
|
|
3434
|
+
});
|
|
3435
|
+
}
|
|
3436
|
+
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
3437
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws) && !this.isWsConnectionReuseExpired(wsState.lastUsedAt);
|
|
3438
|
+
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
3439
|
+
const incrementalInput = this.getIncrementalInput(
|
|
3440
|
+
wsState.lastInput,
|
|
3441
|
+
args.request.input
|
|
3442
|
+
);
|
|
3443
|
+
const canUsePreviousResponseId = this.websocketApiVersion === "v2" && Boolean(wsState.previousResponseId) && !shouldResetChain && incrementalInput !== null;
|
|
3444
|
+
const chainReset = shouldResetChain || Boolean(wsState.previousResponseId) && !canUsePreviousResponseId;
|
|
3445
|
+
let wsInputMode = "full_no_previous";
|
|
3446
|
+
if (Boolean(wsState.previousResponseId)) {
|
|
3447
|
+
if (canUsePreviousResponseId) {
|
|
3448
|
+
if (Array.isArray(incrementalInput) && incrementalInput.length === 0) {
|
|
3449
|
+
wsInputMode = "empty";
|
|
3450
|
+
} else {
|
|
3451
|
+
wsInputMode = "incremental";
|
|
3452
|
+
}
|
|
3453
|
+
} else {
|
|
3454
|
+
wsInputMode = "full_regenerated";
|
|
3455
|
+
}
|
|
3456
|
+
}
|
|
3457
|
+
const fallbackAllowed = this.websocketMode === "auto";
|
|
3458
|
+
const wsExecutionPlan = {
|
|
3459
|
+
request: {
|
|
3460
|
+
...args.request,
|
|
3461
|
+
...canUsePreviousResponseId ? { previous_response_id: wsState.previousResponseId } : {},
|
|
3462
|
+
...canUsePreviousResponseId && incrementalInput !== void 0 ? { input: incrementalInput } : {}
|
|
3463
|
+
},
|
|
3464
|
+
chainReset,
|
|
3465
|
+
wsInputMode,
|
|
3466
|
+
requiresWsConnectionReset: Boolean(wsState.ws) && (!hasReusableWs || Boolean(wsState.previousResponseId) && !canUsePreviousResponseId),
|
|
3467
|
+
hasReusableWs
|
|
3468
|
+
};
|
|
3469
|
+
try {
|
|
3470
|
+
if (wsExecutionPlan.requiresWsConnectionReset) {
|
|
3471
|
+
this.closeWsSafely(
|
|
3472
|
+
wsState.ws,
|
|
3473
|
+
hasReusableWs ? "chain_reset" : "stale_connection"
|
|
3474
|
+
);
|
|
3475
|
+
}
|
|
3476
|
+
await this.debugRequestIfEnabled(
|
|
3477
|
+
wsExecutionPlan.request,
|
|
3478
|
+
args.debugSeq,
|
|
3479
|
+
args.sessionIdHeader,
|
|
3480
|
+
"ws_mode",
|
|
3481
|
+
false,
|
|
3482
|
+
wsExecutionPlan.chainReset,
|
|
3483
|
+
wsExecutionPlan.wsInputMode
|
|
3484
|
+
);
|
|
3485
|
+
const { response, ws } = await this.invokeViaWs({
|
|
3486
|
+
request: wsExecutionPlan.request,
|
|
3487
|
+
signal: args.signal,
|
|
3488
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3489
|
+
ws: wsExecutionPlan.requiresWsConnectionReset || !wsExecutionPlan.hasReusableWs ? void 0 : wsState.ws
|
|
3490
|
+
});
|
|
3491
|
+
this.persistWsSessionState({
|
|
3492
|
+
sessionKey: args.sessionKey,
|
|
3493
|
+
request: args.request,
|
|
3494
|
+
requestMeta: args.requestMeta,
|
|
3495
|
+
response,
|
|
3496
|
+
ws
|
|
3497
|
+
});
|
|
3498
|
+
return {
|
|
3499
|
+
response,
|
|
3500
|
+
transport: "ws_mode",
|
|
3501
|
+
fallbackUsed: false,
|
|
3502
|
+
chainReset: wsExecutionPlan.chainReset,
|
|
3503
|
+
wsInputMode: wsExecutionPlan.wsInputMode
|
|
3504
|
+
};
|
|
3505
|
+
} catch (error) {
|
|
3506
|
+
let failure = error;
|
|
3507
|
+
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
3508
|
+
const retryWsInputMode = Boolean(
|
|
3509
|
+
wsState.previousResponseId
|
|
3510
|
+
) ? "full_regenerated" : "full_no_previous";
|
|
3511
|
+
this.closeWsWithoutMaskingPrimaryError(wsState.ws, "retry_reset", failure);
|
|
3512
|
+
try {
|
|
3513
|
+
await this.debugRequestIfEnabled(
|
|
3514
|
+
args.request,
|
|
3515
|
+
args.debugSeq,
|
|
3516
|
+
args.sessionIdHeader,
|
|
3517
|
+
"ws_mode",
|
|
3518
|
+
false,
|
|
3519
|
+
true,
|
|
3520
|
+
retryWsInputMode
|
|
3521
|
+
);
|
|
3522
|
+
const { response, ws } = await this.invokeViaWs({
|
|
3523
|
+
request: args.request,
|
|
3524
|
+
signal: args.signal,
|
|
3525
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3526
|
+
ws: void 0
|
|
3527
|
+
});
|
|
3528
|
+
this.wsReconnectCount += 1;
|
|
3529
|
+
this.persistWsSessionState({
|
|
3530
|
+
sessionKey: args.sessionKey,
|
|
3531
|
+
request: args.request,
|
|
3532
|
+
requestMeta: args.requestMeta,
|
|
3533
|
+
response,
|
|
3534
|
+
ws
|
|
3535
|
+
});
|
|
3536
|
+
return {
|
|
3537
|
+
response,
|
|
3538
|
+
transport: "ws_mode",
|
|
3539
|
+
fallbackUsed: false,
|
|
3540
|
+
chainReset: true,
|
|
3541
|
+
wsInputMode: retryWsInputMode
|
|
3542
|
+
};
|
|
3543
|
+
} catch (retryError) {
|
|
3544
|
+
failure = retryError;
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
3548
|
+
const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
|
|
3549
|
+
const shouldDisableWsForSession = wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
3550
|
+
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
3551
|
+
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
3552
|
+
this.wsDisabledUntilBySessionKey.set(
|
|
3553
|
+
args.sessionKey,
|
|
3554
|
+
Date.now() + WS_SESSION_DISABLE_TTL_MS
|
|
3555
|
+
);
|
|
3556
|
+
}
|
|
3557
|
+
if (!fallbackAllowed) {
|
|
3558
|
+
throw failure;
|
|
3559
|
+
}
|
|
3560
|
+
this.wsReconnectCount += 1;
|
|
3561
|
+
return this.invokeHttpTransportWithDebug({
|
|
3562
|
+
request: args.request,
|
|
3563
|
+
debugSeq: args.debugSeq,
|
|
3564
|
+
sessionIdHeader: args.sessionIdHeader,
|
|
3565
|
+
signal: args.signal,
|
|
3566
|
+
fallbackUsed: true,
|
|
3567
|
+
chainReset: true,
|
|
3568
|
+
wsInputMode: wsExecutionPlan.wsInputMode
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
}
|
|
3572
|
+
async invokeHttpTransportWithDebug(args) {
|
|
3573
|
+
await this.debugRequestIfEnabled(
|
|
3574
|
+
args.request,
|
|
3575
|
+
args.debugSeq,
|
|
3576
|
+
args.sessionIdHeader,
|
|
3577
|
+
"http_stream",
|
|
3578
|
+
args.fallbackUsed,
|
|
3579
|
+
args.chainReset,
|
|
3580
|
+
args.wsInputMode
|
|
3581
|
+
);
|
|
3582
|
+
const response = await invokeOpenAiHttp(
|
|
3583
|
+
this.client,
|
|
3584
|
+
args.request,
|
|
3585
|
+
args.signal,
|
|
3586
|
+
args.sessionIdHeader
|
|
3587
|
+
);
|
|
3588
|
+
return {
|
|
3589
|
+
response,
|
|
3590
|
+
transport: "http_stream",
|
|
3591
|
+
fallbackUsed: args.fallbackUsed,
|
|
3592
|
+
chainReset: args.chainReset
|
|
3593
|
+
};
|
|
3594
|
+
}
|
|
3595
|
+
persistWsSessionState(args) {
|
|
3596
|
+
this.wsDisabledUntilBySessionKey.delete(args.sessionKey);
|
|
3597
|
+
this.wsStateBySessionKey.set(args.sessionKey, {
|
|
3598
|
+
previousResponseId: args.response.id,
|
|
3599
|
+
instructionsHash: args.requestMeta.instructionsHash,
|
|
3600
|
+
toolsHash: args.requestMeta.toolsHash,
|
|
3601
|
+
model: args.requestMeta.model,
|
|
3602
|
+
lastInput: args.request.input,
|
|
3603
|
+
ws: args.ws,
|
|
3604
|
+
lastUsedAt: Date.now()
|
|
3605
|
+
});
|
|
3606
|
+
}
|
|
3607
|
+
async invokeViaWs(args) {
|
|
3608
|
+
return this.wsTransport.invoke(args);
|
|
3609
|
+
}
|
|
3610
|
+
closeWsSafely(ws, reason) {
|
|
3611
|
+
this.wsTransport.closeSafely(ws, reason);
|
|
3612
|
+
}
|
|
3613
|
+
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
3614
|
+
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
3615
|
+
}
|
|
3616
|
+
isWsConnectionReuseExpired(lastUsedAt) {
|
|
3617
|
+
if (typeof lastUsedAt !== "number") {
|
|
3618
|
+
return false;
|
|
3619
|
+
}
|
|
3620
|
+
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
3621
|
+
}
|
|
3622
|
+
isWsReconnectRetryableError(error) {
|
|
3623
|
+
if (!(error instanceof Error)) {
|
|
3624
|
+
return false;
|
|
3625
|
+
}
|
|
3626
|
+
const message = error.message.toLowerCase();
|
|
3627
|
+
return message.includes("response timeout") || message.includes("closed before response") || message.includes("closed before open") || message.includes("connect timeout") || message.includes("could not send data") || message.includes("websocket is not open");
|
|
3628
|
+
}
|
|
3629
|
+
isWsConnectionReusable(ws) {
|
|
3630
|
+
return this.wsTransport.isConnectionReusable(ws);
|
|
3631
|
+
}
|
|
3632
|
+
extractWsErrorCode(error) {
|
|
3633
|
+
return this.wsTransport.extractErrorCode(error);
|
|
3634
|
+
}
|
|
3635
|
+
clearWsSessionState(sessionKey, reason, primaryError) {
|
|
3636
|
+
const state = this.wsStateBySessionKey.get(sessionKey);
|
|
3637
|
+
if (primaryError === void 0) {
|
|
3638
|
+
this.closeWsSafely(state?.ws, reason);
|
|
3639
|
+
} else {
|
|
3640
|
+
this.closeWsWithoutMaskingPrimaryError(state?.ws, reason, primaryError);
|
|
3641
|
+
}
|
|
3642
|
+
this.wsStateBySessionKey.delete(sessionKey);
|
|
3643
|
+
}
|
|
3644
|
+
evictIdleWsSessionState(now = Date.now()) {
|
|
3645
|
+
for (const [sessionKey, disabledUntil] of this.wsDisabledUntilBySessionKey) {
|
|
3646
|
+
if (disabledUntil <= now) {
|
|
3647
|
+
this.wsDisabledUntilBySessionKey.delete(sessionKey);
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
for (const [sessionKey, state] of this.wsStateBySessionKey) {
|
|
3651
|
+
if (typeof state.lastUsedAt === "number" && now - state.lastUsedAt <= WS_SESSION_IDLE_TTL_MS) {
|
|
3652
|
+
continue;
|
|
3653
|
+
}
|
|
3654
|
+
this.closeWsSafely(state.ws, "idle_evict");
|
|
3655
|
+
this.wsStateBySessionKey.delete(sessionKey);
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
isWsSessionDisabled(sessionKey, now = Date.now()) {
|
|
3659
|
+
const disabledUntil = this.wsDisabledUntilBySessionKey.get(sessionKey);
|
|
3660
|
+
if (disabledUntil === void 0) {
|
|
3661
|
+
return false;
|
|
3662
|
+
}
|
|
3663
|
+
if (disabledUntil <= now) {
|
|
3664
|
+
this.wsDisabledUntilBySessionKey.delete(sessionKey);
|
|
3665
|
+
return false;
|
|
3666
|
+
}
|
|
3667
|
+
return true;
|
|
3668
|
+
}
|
|
3669
|
+
getIncrementalInput(previousInput, currentInput) {
|
|
3670
|
+
if (previousInput === void 0) {
|
|
3671
|
+
return void 0;
|
|
3672
|
+
}
|
|
3673
|
+
if (!Array.isArray(previousInput) || !Array.isArray(currentInput)) {
|
|
3674
|
+
return safeJsonStringify(previousInput) === safeJsonStringify(currentInput) ? [] : null;
|
|
3675
|
+
}
|
|
3676
|
+
if (previousInput.length > currentInput.length) {
|
|
3677
|
+
return null;
|
|
3678
|
+
}
|
|
3679
|
+
for (let index = 0; index < previousInput.length; index += 1) {
|
|
3680
|
+
if (safeJsonStringify(previousInput[index]) !== safeJsonStringify(currentInput[index])) {
|
|
3681
|
+
return null;
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
if (previousInput.length === currentInput.length) {
|
|
3685
|
+
return [];
|
|
3686
|
+
}
|
|
3687
|
+
return currentInput.slice(previousInput.length);
|
|
2829
3688
|
}
|
|
2830
3689
|
nextDebugInvokeSeq() {
|
|
2831
3690
|
const seq = this.debugInvokeSeq + 1;
|
|
2832
3691
|
this.debugInvokeSeq = seq;
|
|
2833
3692
|
return seq;
|
|
2834
3693
|
}
|
|
2835
|
-
async debugRequestIfEnabled(request, seq, sessionIdHeader) {
|
|
3694
|
+
async debugRequestIfEnabled(request, seq, sessionIdHeader, transport = "http_stream", fallbackUsed = false, chainReset, wsInputMode) {
|
|
2836
3695
|
const settings = getProviderLogSettings();
|
|
2837
3696
|
if (!settings.enabled && !settings.dumpDir) {
|
|
2838
3697
|
return;
|
|
@@ -2846,8 +3705,10 @@ var ChatOpenAI = class {
|
|
|
2846
3705
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
2847
3706
|
if (settings.enabled) {
|
|
2848
3707
|
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto2.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
3708
|
+
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
3709
|
+
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
2849
3710
|
console.error(
|
|
2850
|
-
`[openai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
3711
|
+
`[openai.request] seq=${seq} transport=${transport} websocket_mode=${this.websocketMode} fallback_used=${fallbackUsed ? "true" : "false"} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${chainResetSuffix}${wsInputModeSuffix}${sessionHeaderSuffix}`
|
|
2851
3712
|
);
|
|
2852
3713
|
}
|
|
2853
3714
|
if (settings.dumpDir) {
|
|
@@ -2869,7 +3730,7 @@ var ChatOpenAI = class {
|
|
|
2869
3730
|
}
|
|
2870
3731
|
this.lastDebugRequestPayload = payload;
|
|
2871
3732
|
}
|
|
2872
|
-
async debugResponseIfEnabled(response, seq) {
|
|
3733
|
+
async debugResponseIfEnabled(response, seq, transport) {
|
|
2873
3734
|
const settings = getProviderLogSettings();
|
|
2874
3735
|
if (!settings.enabled && !settings.dumpDir) {
|
|
2875
3736
|
return;
|
|
@@ -2885,7 +3746,7 @@ var ChatOpenAI = class {
|
|
|
2885
3746
|
}
|
|
2886
3747
|
const usageIn = usage?.input_tokens ?? 0;
|
|
2887
3748
|
console.error(
|
|
2888
|
-
`[openai.response] seq=${seq} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
3749
|
+
`[openai.response] seq=${seq} transport=${transport} websocket_mode=${this.websocketMode} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
2889
3750
|
);
|
|
2890
3751
|
}
|
|
2891
3752
|
if (settings.dumpDir) {
|