@aituber-onair/chat 0.21.0 → 0.21.1
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.ja.md +1 -1
- package/README.md +1 -1
- package/dist/cjs/constants/openai.d.ts +1 -1
- package/dist/cjs/constants/openai.d.ts.map +1 -1
- package/dist/cjs/constants/openai.js +5 -2
- package/dist/cjs/constants/openai.js.map +1 -1
- package/dist/esm/constants/openai.d.ts +1 -1
- package/dist/esm/constants/openai.d.ts.map +1 -1
- package/dist/esm/constants/openai.js +5 -2
- package/dist/esm/constants/openai.js.map +1 -1
- package/dist/umd/aituber-onair-chat.js +1 -1
- package/dist/umd/aituber-onair-chat.min.js +4 -4
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -187,7 +187,7 @@ const compatibleService = ChatServiceFactory.createChatService(
|
|
|
187
187
|
`reasoning_effort` の選択肢はモデルによって異なります。
|
|
188
188
|
- `gpt-5.4-pro`: `'medium' | 'high' | 'xhigh'`(Responses API 専用)
|
|
189
189
|
- `gpt-5.4`: `'none' | 'low' | 'medium' | 'high' | 'xhigh'`
|
|
190
|
-
- `gpt-5.4-mini` / `gpt-5.4-nano`: `'low' | 'medium' | 'high' | 'xhigh'`
|
|
190
|
+
- `gpt-5.4-mini` / `gpt-5.4-nano`: `'none' | 'low' | 'medium' | 'high' | 'xhigh'`
|
|
191
191
|
- `gpt-5.1`: `'none' | 'low' | 'medium' | 'high'`
|
|
192
192
|
- `gpt-5` / `gpt-5-mini` / `gpt-5-nano`: `'minimal' | 'low' | 'medium' | 'high'`
|
|
193
193
|
|
package/README.md
CHANGED
|
@@ -187,7 +187,7 @@ Notes:
|
|
|
187
187
|
`reasoning_effort` options differ per model:
|
|
188
188
|
- `gpt-5.4-pro`: `'medium' | 'high' | 'xhigh'` (Responses API only)
|
|
189
189
|
- `gpt-5.4`: `'none' | 'low' | 'medium' | 'high' | 'xhigh'`
|
|
190
|
-
- `gpt-5.4-mini` / `gpt-5.4-nano`: `'low' | 'medium' | 'high' | 'xhigh'`
|
|
190
|
+
- `gpt-5.4-mini` / `gpt-5.4-nano`: `'none' | 'low' | 'medium' | 'high' | 'xhigh'`
|
|
191
191
|
- `gpt-5.1`: `'none' | 'low' | 'medium' | 'high'`
|
|
192
192
|
- `gpt-5` / `gpt-5-mini` / `gpt-5-nano`: `'minimal' | 'low' | 'medium' | 'high'`
|
|
193
193
|
|
|
@@ -35,7 +35,7 @@ export declare function isResponsesOnlyGPT5Model(model: string): boolean;
|
|
|
35
35
|
export declare function allowsReasoningXHigh(model: string): boolean;
|
|
36
36
|
/**
|
|
37
37
|
* Check if the provided model allows the reasoning_effort 'none' shortcut
|
|
38
|
-
* Supported by GPT-5.1 and GPT-5.4
|
|
38
|
+
* Supported by GPT-5.1 and GPT-5.4 family models, except Pro
|
|
39
39
|
*/
|
|
40
40
|
export declare function allowsReasoningNone(model: string): boolean;
|
|
41
41
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oCAAoC,+CACH,CAAC;AAC/C,eAAO,MAAM,6BAA6B,wCACH,CAAC;AAGxC,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,WAAW,UAAU,CAAC;AACnC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,YAAY,WAAW,CAAC;AACrC,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,QAAQ,OAAO,CAAC;AAG7B,eAAO,MAAM,uBAAuB,UAgBnC,CAAC;AAGF,eAAO,MAAM,YAAY,UASxB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B,MAAM,GACN,SAAS,GACT,KAAK,GACL,QAAQ,GACR,MAAM,GACN,OAAO,CAAC;AAEZ;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO3D;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,
|
|
1
|
+
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oCAAoC,+CACH,CAAC;AAC/C,eAAO,MAAM,6BAA6B,wCACH,CAAC;AAGxC,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,WAAW,UAAU,CAAC;AACnC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,YAAY,WAAW,CAAC;AACrC,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,QAAQ,OAAO,CAAC;AAG7B,eAAO,MAAM,uBAAuB,UAgBnC,CAAC;AAGF,eAAO,MAAM,YAAY,UASxB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B,MAAM,GACN,SAAS,GACT,KAAK,GACL,QAAQ,GACR,MAAM,GACN,OAAO,CAAC;AAEZ;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO3D;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO1D;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM7D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED;;;;GAIG;AACH,wBAAgB,qCAAqC,CACnD,KAAK,EAAE,MAAM,GACZ,MAAM,GAAG,QAAQ,CAKnB"}
|
|
@@ -81,10 +81,13 @@ function allowsReasoningXHigh(model) {
|
|
|
81
81
|
}
|
|
82
82
|
/**
|
|
83
83
|
* Check if the provided model allows the reasoning_effort 'none' shortcut
|
|
84
|
-
* Supported by GPT-5.1 and GPT-5.4
|
|
84
|
+
* Supported by GPT-5.1 and GPT-5.4 family models, except Pro
|
|
85
85
|
*/
|
|
86
86
|
function allowsReasoningNone(model) {
|
|
87
|
-
return model === exports.MODEL_GPT_5_1 ||
|
|
87
|
+
return (model === exports.MODEL_GPT_5_1 ||
|
|
88
|
+
model === exports.MODEL_GPT_5_4 ||
|
|
89
|
+
model === exports.MODEL_GPT_5_4_MINI ||
|
|
90
|
+
model === exports.MODEL_GPT_5_4_NANO);
|
|
88
91
|
}
|
|
89
92
|
/**
|
|
90
93
|
* Check if the provided model allows the 'minimal' reasoning effort level
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.js","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":";;;AAsEA,kCAEC;AAKD,4DAEC;AAKD,oDAOC;AAMD,
|
|
1
|
+
{"version":3,"file":"openai.js","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":";;;AAsEA,kCAEC;AAKD,4DAEC;AAKD,oDAOC;AAMD,kDAOC;AAMD,wDAMC;AAMD,gDAEC;AAOD,sFAOC;AA1IY,QAAA,oCAAoC,GAC/C,4CAA4C,CAAC;AAClC,QAAA,6BAA6B,GACxC,qCAAqC,CAAC;AAExC,YAAY;AACC,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,WAAW,GAAG,OAAO,CAAC;AACtB,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,iBAAiB,GAAG,aAAa,CAAC;AAElC,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,kBAAkB,GAAG,cAAc,CAAC;AAEpC,QAAA,iBAAiB,GAAG,aAAa,CAAC;AAClC,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,aAAa,GAAG,SAAS,CAAC;AAE1B,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,QAAQ,GAAG,IAAI,CAAC;AAE7B,4BAA4B;AACf,QAAA,uBAAuB,GAAG;IACrC,wBAAgB;IAChB,wBAAgB;IAChB,mBAAW;IACX,qBAAa;IACb,qBAAa;IACb,0BAAkB;IAClB,0BAAkB;IAClB,yBAAiB;IACjB,qBAAa;IACb,0BAAkB;IAClB,0BAAkB;IAClB,yBAAiB;IACjB,oBAAY;IACZ,gBAAQ;IACR,gFAAgF;CACjF,CAAC;AAEF,oBAAoB;AACP,QAAA,YAAY,GAAG;IAC1B,wBAAgB;IAChB,wBAAgB;IAChB,mBAAW;IACX,qBAAa;IACb,qBAAa;IACb,0BAAkB;IAClB,0BAAkB;IAClB,yBAAiB;CAClB,CAAC;AAUF;;;;GAIG;AACH,SAAgB,WAAW,CAAC,KAAa;IACvC,OAAO,oBAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED;;GAEG;AACH,SAAgB,wBAAwB,CAAC,KAAa;IACpD,OAAO,KAAK,KAAK,yBAAiB,CAAC;AACrC,CAAC;AAED;;GAEG;AACH,SAAgB,oBAAoB,CAAC,KAAa;IAChD,OAAO,CACL,KAAK,KAAK,qBAAa;QACvB,KAAK,KAAK,0BAAkB;QAC5B,KAAK,KAAK,0BAAkB;QAC5B,KAAK,KAAK,yBAAiB,CAC5B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,mBAAmB,CAAC,KAAa;IAC/C,OAAO,CACL,KAAK,KAAK,qBAAa;QACvB,KAAK,KAAK,qBAAa;QACvB,KAAK,KAAK,0BAAkB;QAC5B,KAAK,KAAK,0BAAkB,CAC7B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,sBAAsB,CAAC,KAAa;IAClD,OAAO,CACL,KAAK,KAAK,wBAAgB;QAC1B,KAAK,KAAK,wBAAgB;QAC1B,KAAK,KAAK,mBAAW,CACtB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,KAAa;IAC9C,OAAO,KAAK,KAAK,yBAAiB,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH,SAAgB,qCAAqC,CACnD,KAAa;IAEb,IAAI,KAAK,KAAK,qBAAa,IAAI,KAAK,KAAK,qBAAa,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
|
@@ -35,7 +35,7 @@ export declare function isResponsesOnlyGPT5Model(model: string): boolean;
|
|
|
35
35
|
export declare function allowsReasoningXHigh(model: string): boolean;
|
|
36
36
|
/**
|
|
37
37
|
* Check if the provided model allows the reasoning_effort 'none' shortcut
|
|
38
|
-
* Supported by GPT-5.1 and GPT-5.4
|
|
38
|
+
* Supported by GPT-5.1 and GPT-5.4 family models, except Pro
|
|
39
39
|
*/
|
|
40
40
|
export declare function allowsReasoningNone(model: string): boolean;
|
|
41
41
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oCAAoC,+CACH,CAAC;AAC/C,eAAO,MAAM,6BAA6B,wCACH,CAAC;AAGxC,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,WAAW,UAAU,CAAC;AACnC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,YAAY,WAAW,CAAC;AACrC,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,QAAQ,OAAO,CAAC;AAG7B,eAAO,MAAM,uBAAuB,UAgBnC,CAAC;AAGF,eAAO,MAAM,YAAY,UASxB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B,MAAM,GACN,SAAS,GACT,KAAK,GACL,QAAQ,GACR,MAAM,GACN,OAAO,CAAC;AAEZ;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO3D;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,
|
|
1
|
+
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oCAAoC,+CACH,CAAC;AAC/C,eAAO,MAAM,6BAA6B,wCACH,CAAC;AAGxC,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAC7C,eAAO,MAAM,WAAW,UAAU,CAAC;AACnC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AACjD,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAEjD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,YAAY,WAAW,CAAC;AACrC,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,QAAQ,OAAO,CAAC;AAG7B,eAAO,MAAM,uBAAuB,UAgBnC,CAAC;AAGF,eAAO,MAAM,YAAY,UASxB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B,MAAM,GACN,SAAS,GACT,KAAK,GACL,QAAQ,GACR,MAAM,GACN,OAAO,CAAC;AAEZ;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO3D;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO1D;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM7D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED;;;;GAIG;AACH,wBAAgB,qCAAqC,CACnD,KAAK,EAAE,MAAM,GACZ,MAAM,GAAG,QAAQ,CAKnB"}
|
|
@@ -71,10 +71,13 @@ export function allowsReasoningXHigh(model) {
|
|
|
71
71
|
}
|
|
72
72
|
/**
|
|
73
73
|
* Check if the provided model allows the reasoning_effort 'none' shortcut
|
|
74
|
-
* Supported by GPT-5.1 and GPT-5.4
|
|
74
|
+
* Supported by GPT-5.1 and GPT-5.4 family models, except Pro
|
|
75
75
|
*/
|
|
76
76
|
export function allowsReasoningNone(model) {
|
|
77
|
-
return model === MODEL_GPT_5_1 ||
|
|
77
|
+
return (model === MODEL_GPT_5_1 ||
|
|
78
|
+
model === MODEL_GPT_5_4 ||
|
|
79
|
+
model === MODEL_GPT_5_4_MINI ||
|
|
80
|
+
model === MODEL_GPT_5_4_NANO);
|
|
78
81
|
}
|
|
79
82
|
/**
|
|
80
83
|
* Check if the provided model allows the 'minimal' reasoning effort level
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.js","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oCAAoC,GAC/C,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,6BAA6B,GACxC,qCAAqC,CAAC;AAExC,YAAY;AACZ,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAC;AAC7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAC;AAC7C,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AACnC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAE/C,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAEjD,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAC/C,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AACrC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAEvC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,CAAC;AAE7B,4BAA4B;AAC5B,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;IACX,aAAa;IACb,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;IACjB,YAAY;IACZ,QAAQ;IACR,gFAAgF;CACjF,CAAC;AAEF,oBAAoB;AACpB,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;IACX,aAAa;IACb,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;CAClB,CAAC;AAUF;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IACvC,OAAO,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACpD,OAAO,KAAK,KAAK,iBAAiB,CAAC;AACrC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,OAAO,CACL,KAAK,KAAK,aAAa;QACvB,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,iBAAiB,CAC5B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,KAAK,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"openai.js","sourceRoot":"","sources":["../../../src/constants/openai.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oCAAoC,GAC/C,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,6BAA6B,GACxC,qCAAqC,CAAC;AAExC,YAAY;AACZ,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAC;AAC7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAC;AAC7C,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AACnC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAE/C,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAEjD,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAC/C,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AACrC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAEvC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,CAAC;AAE7B,4BAA4B;AAC5B,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;IACX,aAAa;IACb,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;IACjB,YAAY;IACZ,QAAQ;IACR,gFAAgF;CACjF,CAAC;AAEF,oBAAoB;AACpB,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;IACX,aAAa;IACb,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;CAClB,CAAC;AAUF;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IACvC,OAAO,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACpD,OAAO,KAAK,KAAK,iBAAiB,CAAC;AACrC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,OAAO,CACL,KAAK,KAAK,aAAa;QACvB,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,iBAAiB,CAC5B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,CACL,KAAK,KAAK,aAAa;QACvB,KAAK,KAAK,aAAa;QACvB,KAAK,KAAK,kBAAkB;QAC5B,KAAK,KAAK,kBAAkB,CAC7B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAa;IAClD,OAAO,CACL,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,gBAAgB;QAC1B,KAAK,KAAK,WAAW,CACtB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,OAAO,KAAK,KAAK,iBAAiB,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,qCAAqC,CACnD,KAAa;IAEb,IAAI,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,aAAa,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
|
@@ -216,7 +216,7 @@ var AITuberOnAirChat = (() => {
|
|
|
216
216
|
return model === MODEL_GPT_5_4 || model === MODEL_GPT_5_4_MINI || model === MODEL_GPT_5_4_NANO || model === MODEL_GPT_5_4_PRO;
|
|
217
217
|
}
|
|
218
218
|
function allowsReasoningNone(model) {
|
|
219
|
-
return model === MODEL_GPT_5_1 || model === MODEL_GPT_5_4;
|
|
219
|
+
return model === MODEL_GPT_5_1 || model === MODEL_GPT_5_4 || model === MODEL_GPT_5_4_MINI || model === MODEL_GPT_5_4_NANO;
|
|
220
220
|
}
|
|
221
221
|
function allowsReasoningMinimal(model) {
|
|
222
222
|
return model === MODEL_GPT_5_NANO || model === MODEL_GPT_5_MINI || model === MODEL_GPT_5;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AITuberOnAirChat=(()=>{var ct=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Qt=Object.prototype.hasOwnProperty;var eo=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},to=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yt(e))!Qt.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(o=Xt(e,r))||o.enumerable});return i};var oo=i=>to(ct({},"__esModule",{value:!0}),i);var yo={};eo(yo,{CHAT_RESPONSE_LENGTH:()=>
|
|
1
|
+
"use strict";var AITuberOnAirChat=(()=>{var ct=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var Qt=Object.prototype.hasOwnProperty;var eo=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},to=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yt(e))!Qt.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(o=Xt(e,r))||o.enumerable});return i};var oo=i=>to(ct({},"__esModule",{value:!0}),i);var yo={};eo(yo,{CHAT_RESPONSE_LENGTH:()=>K,CLAUDE_VISION_SUPPORTED_MODELS:()=>ge,ChatServiceFactory:()=>me,ChatServiceHttpClient:()=>g,ClaudeChatService:()=>te,ClaudeChatServiceProvider:()=>oe,DEFAULT_MAX_TOKENS:()=>Dt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>ao,DEFAULT_VISION_PROMPT:()=>no,EMOTION_TAG_CLEANUP_REGEX:()=>wt,EMOTION_TAG_REGEX:()=>Wt,ENDPOINT_CLAUDE_API:()=>Ot,ENDPOINT_GEMINI_API:()=>Mt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>Y,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>$,ENDPOINT_OPENAI_RESPONSES_API:()=>y,ENDPOINT_OPENROUTER_API:()=>fe,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>ve,EmotionParser:()=>ee,GEMINI_VISION_SUPPORTED_MODELS:()=>_e,GPT5_PRESETS:()=>At,GPT_5_MODELS:()=>Vt,GeminiChatService:()=>re,GeminiChatServiceProvider:()=>se,HttpError:()=>w,KIMI_VISION_SUPPORTED_MODELS:()=>Ut,KimiChatService:()=>ie,KimiChatServiceProvider:()=>ne,MAX_TOKENS_BY_LENGTH:()=>Ht,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Et,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>Qe,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>et,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>Xe,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>Ye,MODEL_CLAUDE_3_5_HAIKU:()=>Ae,MODEL_CLAUDE_3_5_SONNET:()=>we,MODEL_CLAUDE_3_7_SONNET:()=>Ne,MODEL_CLAUDE_3_HAIKU:()=>T,MODEL_CLAUDE_4_5_HAIKU:()=>Fe,MODEL_CLAUDE_4_5_OPUS:()=>Ue,MODEL_CLAUDE_4_5_SONNET:()=>Ge,MODEL_CLAUDE_4_6_OPUS:()=>We,MODEL_CLAUDE_4_6_SONNET:()=>He,MODEL_CLAUDE_4_OPUS:()=>Ve,MODEL_CLAUDE_4_SONNET:()=>ke,MODEL_GEMINI_2_0_FLASH:()=>De,MODEL_GEMINI_2_0_FLASH_LITE:()=>D,MODEL_GEMINI_2_5_FLASH:()=>Le,MODEL_GEMINI_2_5_FLASH_LITE:()=>be,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>Re,MODEL_GEMINI_2_5_PRO:()=>Ie,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Se,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Te,MODEL_GEMINI_3_FLASH_PREVIEW:()=>xe,MODEL_GEMINI_3_PRO_PREVIEW:()=>Pe,MODEL_GLM_4_6:()=>bt,MODEL_GLM_4_6V:()=>it,MODEL_GLM_4_6V_FLASH:()=>B,MODEL_GLM_4_6V_FLASHX:()=>nt,MODEL_GLM_4_7:()=>Z,MODEL_GLM_4_7_FLASH:()=>Lt,MODEL_GLM_4_7_FLASHX:()=>It,MODEL_GLM_5:()=>Pt,MODEL_GLM_5_TURBO:()=>xt,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>ot,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>rt,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>tt,MODEL_GPT_4O:()=>ye,MODEL_GPT_4O_MINI:()=>U,MODEL_GPT_4_1:()=>Oe,MODEL_GPT_4_1_MINI:()=>Ee,MODEL_GPT_4_1_NANO:()=>Ce,MODEL_GPT_5:()=>z,MODEL_GPT_5_1:()=>V,MODEL_GPT_5_4:()=>b,MODEL_GPT_5_4_MINI:()=>G,MODEL_GPT_5_4_NANO:()=>F,MODEL_GPT_5_4_PRO:()=>R,MODEL_GPT_5_MINI:()=>j,MODEL_GPT_5_NANO:()=>k,MODEL_GPT_OSS_20B_FREE:()=>A,MODEL_KIMI_K2_5:()=>S,MODEL_MOONSHOTAI_KIMI_K2_5:()=>Be,MODEL_O1:()=>mt,MODEL_O1_MINI:()=>ut,MODEL_O3_MINI:()=>ht,MODEL_OPENAI_GPT_4O:()=>qe,MODEL_OPENAI_GPT_4_1_MINI:()=>Je,MODEL_OPENAI_GPT_4_1_NANO:()=>Ze,MODEL_OPENAI_GPT_5_1_CHAT:()=>Ke,MODEL_OPENAI_GPT_5_1_CODEX:()=>$e,MODEL_OPENAI_GPT_5_MINI:()=>je,MODEL_OPENAI_GPT_5_NANO:()=>ze,MODEL_ZAI_GLM_4_5_AIR:()=>yt,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>st,MODEL_ZAI_GLM_4_7_FLASH:()=>Ct,OPENROUTER_CREDITS_THRESHOLD:()=>io,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>so,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>ro,OPENROUTER_FREE_MODELS:()=>Tt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>St,OPENROUTER_VISION_SUPPORTED_MODELS:()=>Gt,OpenAIChatService:()=>N,OpenAIChatServiceProvider:()=>le,OpenAICompatibleChatServiceProvider:()=>ae,OpenRouterChatService:()=>pe,OpenRouterChatServiceProvider:()=>ce,StreamTextAccumulator:()=>f,VISION_SUPPORTED_MODELS:()=>de,ZAIChatService:()=>he,ZAIChatServiceProvider:()=>ue,ZAI_VISION_SUPPORTED_MODELS:()=>Ft,allowsReasoningLow:()=>vt,allowsReasoningMinimal:()=>ft,allowsReasoningNone:()=>gt,allowsReasoningXHigh:()=>_t,buildOpenAICompatibleTools:()=>L,getDefaultReasoningEffortForGPT5Model:()=>H,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>Jt,isGPT5Model:()=>q,isKimiVisionModel:()=>Q,isOpenRouterFreeModel:()=>W,isOpenRouterVisionModel:()=>J,isResponsesOnlyGPT5Model:()=>dt,isZaiToolStreamModel:()=>Rt,isZaiVisionModel:()=>X,parseOpenAICompatibleOneShot:()=>I,parseOpenAICompatibleTextStream:()=>P,parseOpenAICompatibleToolStream:()=>x,processChatWithOptionalTools:()=>v,refreshOpenRouterFreeModels:()=>Co,resolveVisionModel:()=>E,runOnceText:()=>ho,screenplayToText:()=>co,textToScreenplay:()=>Bt,textsToScreenplay:()=>po});var $="https://api.openai.com/v1/chat/completions",y="https://api.openai.com/v1/responses",k="gpt-5-nano",j="gpt-5-mini",z="gpt-5",V="gpt-5.1",b="gpt-5.4",G="gpt-5.4-mini",F="gpt-5.4-nano",R="gpt-5.4-pro",Oe="gpt-4.1",Ee="gpt-4.1-mini",Ce="gpt-4.1-nano",U="gpt-4o-mini",ye="gpt-4o",ht="o3-mini",ut="o1-mini",mt="o1",de=[k,j,z,V,b,G,F,R,Oe,Ee,Ce,U,ye,"o1"],Vt=[k,j,z,V,b,G,F,R];function q(i){return Vt.includes(i)}function dt(i){return i===R}function _t(i){return i===b||i===G||i===F||i===R}function gt(i){return i===V||i===b||i===G||i===F}function ft(i){return i===k||i===j||i===z}function vt(i){return i!==R}function H(i){return i===V||i===b?"none":"medium"}var Mt="https://generativelanguage.googleapis.com",Te="gemini-3.1-pro-preview",Se="gemini-3.1-flash-lite-preview",Pe="gemini-3-pro-preview",xe="gemini-3-flash-preview",Ie="gemini-2.5-pro",Le="gemini-2.5-flash",be="gemini-2.5-flash-lite",Re="gemini-2.5-flash-lite-preview-06-17",De="gemini-2.0-flash",D="gemini-2.0-flash-lite",_e=[Te,Se,Pe,xe,Ie,Le,be,Re,De,D];var Ot="https://api.anthropic.com/v1/messages",T="claude-3-haiku-20240307",Ae="claude-3-5-haiku-20241022",we="claude-3-5-sonnet-20241022",Ne="claude-3-7-sonnet-20250219",ke="claude-4-sonnet-20250514",Ve="claude-4-opus-20250514",Ge="claude-sonnet-4-5-20250929",Fe="claude-haiku-4-5-20251001",Ue="claude-opus-4-5-20251101",He="claude-sonnet-4-6",We="claude-opus-4-6",ge=[T,Ae,we,Ne,ke,Ve,Ge,Fe,Ue,He,We];var fe="https://openrouter.ai/api/v1/chat/completions",A="openai/gpt-oss-20b:free",Be="moonshotai/kimi-k2.5",Ke="openai/gpt-5.1-chat",$e="openai/gpt-5.1-codex",je="openai/gpt-5-mini",ze="openai/gpt-5-nano",qe="openai/gpt-4o",Je="openai/gpt-4.1-mini",Ze="openai/gpt-4.1-nano",Xe="anthropic/claude-opus-4",Ye="anthropic/claude-sonnet-4",Qe="anthropic/claude-3.7-sonnet",Et="anthropic/claude-3.5-sonnet",et="anthropic/claude-haiku-4.5",tt="google/gemini-2.5-pro",ot="google/gemini-2.5-flash",rt="google/gemini-2.5-flash-lite-preview-09-2025",Ct="z-ai/glm-4.7-flash",yt="z-ai/glm-4.5-air",st="z-ai/glm-4.5-air:free",Tt=[A,st],Gt=[Ke,$e,je,ze,qe,Je,Ze,Xe,Ye,Qe,et,tt,ot,rt,Be],St=20,ro=50,so=1e3,io=10;function W(i){return i.trim().endsWith(":free")}function J(i){return Gt.some(e=>i.includes(e))}var ve="https://api.z.ai/api/paas/v4/chat/completions",Pt="glm-5",xt="glm-5-turbo",Z="glm-4.7",It="glm-4.7-FlashX",Lt="glm-4.7-Flash",bt="glm-4.6",it="glm-4.6V",nt="glm-4.6V-FlashX",B="glm-4.6V-Flash",Ft=[it,nt,B];function X(i){return Ft.includes(i)}function Rt(i){return i.toLowerCase().startsWith("glm-4.6")}var Y="https://api.moonshot.ai/v1/chat/completions",S="kimi-k2.5",Ut=[S];function Q(i){return Ut.includes(i)}var K={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},Ht={[K.VERY_SHORT]:40,[K.SHORT]:100,[K.MEDIUM]:200,[K.LONG]:300,[K.VERY_LONG]:1e3,[K.DEEP]:5e3},Dt=5e3,At={casual:{reasoning_effort:"minimal",verbosity:"low",description:"Fast responses for casual chat, quick questions (GPT-4 like experience)"},balanced:{reasoning_effort:"medium",verbosity:"medium",description:"Balanced reasoning for business tasks, learning, general problem solving"},expert:{reasoning_effort:"high",verbosity:"high",description:"Deep reasoning for research, complex analysis, expert-level tasks"}};function O(i){return i?Ht[i]??Dt:Dt}var no="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",ao=`You are a skilled summarizing assistant.
|
|
2
2
|
Analyze the following conversation and produce a summary in the **same language** as the majority of the conversation:
|
|
3
3
|
- Summaries should highlight key points
|
|
4
4
|
- Stay concise (around {maxLength} characters if possible)
|
|
@@ -8,7 +8,7 @@ If the conversation is in Japanese, summarize in Japanese.
|
|
|
8
8
|
If it's in English, summarize in English.
|
|
9
9
|
If it's in another language, summarize in that language.
|
|
10
10
|
`;var w=class extends Error{constructor(t,o,r){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=r;this.name="HttpError"}},Me=class Me{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},r={}){let{timeout:s=3e4,retries:n=0,retryDelay:a=1e3}=r,c={...{"Content-Type":"application/json"},...o},u=null;for(let h=0;h<=n;h++)try{let m=typeof AbortController<"u",p=m?new AbortController:void 0,_=m?setTimeout(()=>p.abort(),s):void 0,M=await Me.fetchImpl(e,{method:"POST",headers:c,body:typeof t=="string"?t:JSON.stringify(t),...p?{signal:p.signal}:{}});if(_&&clearTimeout(_),!M.ok){let d=await M.text();throw new w(M.status,M.statusText,d)}return M}catch(m){if(u=m,m instanceof w&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError")throw new Error(`Request timeout after ${s}ms`);h<n&&await new Promise(p=>setTimeout(p,a*(h+1)))}throw u||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new w(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:r=3e4,retries:s=0,retryDelay:n=1e3}=o,a=null;for(let l=0;l<=s;l++)try{let c=typeof AbortController<"u",u=c?new AbortController:void 0,h=c?setTimeout(()=>u.abort(),r):void 0,m=await Me.fetchImpl(e,{method:"GET",headers:t,...u?{signal:u.signal}:{}});if(h&&clearTimeout(h),!m.ok){let p=await m.text();throw new w(m.status,m.statusText,p)}return m}catch(c){if(a=c,c instanceof w&&c.status>=400&&c.status<500)throw c;if(c instanceof Error&&c.name==="AbortError")throw new Error(`Request timeout after ${r}ms`);l<s&&await new Promise(u=>setTimeout(u,n*(l+1)))}throw a||new Error("Request failed")}};Me.fetchImpl=(e,t)=>fetch(e,t);var g=Me;var f=class{static append(e,t){if(!t)return;let o=e[e.length-1];o&&o.type==="text"?o.text+=t:e.push({type:"text",text:t})}static getFullText(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}static addTextBlock(e,t){t&&e.push({type:"text",text:t})}};var lo=["happy","sad","angry","surprised","neutral"],Wt=/\[([a-z]+)\]/i,wt=/\[[a-z]+\]\s*/gi,ee=class{static extractEmotion(e){let t=e.match(Wt);if(t){let o=t[1].toLowerCase(),r=e.replace(wt,"").trim();return{emotion:o,cleanText:r}}return{cleanText:e}}static isValidEmotion(e){return lo.includes(e)}static cleanEmotionTags(e){return e.replace(wt,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function Bt(i){let{emotion:e,cleanText:t}=ee.extractEmotion(i);return e?{emotion:e,text:t}:{text:t}}function po(i){return i.map(e=>Bt(e))}function co(i){return i.emotion?ee.addEmotionTag(i.emotion,i.text):i.text}async function ho(i,e){let{blocks:t}=await i.chatOnce(e,!1,()=>{});return f.getFullText(t)}var Kt=(i,e)=>{try{return JSON.parse(i)}catch(t){if(e){e(i,t);return}throw t}},$t=async(i,e)=>{let t=i.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,r="",s=!1;for(;!s;){let{done:n,value:a}=await t.read();if(n)break;r+=o.decode(a,{stream:!0});let l=r.split(`
|
|
11
|
-
`);r=l.pop()||"";for(let c of l){let u=c.trim();if(!u||u.startsWith(":")||!u.startsWith("data:"))continue;let h=u.slice(5).trim();if(h==="[DONE]"){s=!0;break}e(h)}}};async function P(i,e,t={}){let o="";return await $t(i,r=>{let s=Kt(r,t.onJsonError);if(!s)return;let n=s.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function x(i,e,t={}){let o=[],r=new Map,s=t.appendTextBlock??f.append;await $t(i,l=>{let c=Kt(l,t.onJsonError);if(!c)return;let u=c.choices?.[0]?.delta;u?.content&&(e(u.content),s(o,u.content)),u?.tool_calls&&u.tool_calls.forEach(h=>{let m=r.get(h.index)??{id:h.id,name:h.function?.name,args:""};m.args+=h.function?.arguments||"",r.set(h.index,m)})});let n=Array.from(r.entries()).sort((l,c)=>l[0]-c[0]).map(([l,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...n],stop_reason:n.length?"tool_use":"end"}}function I(i){let e=i?.choices?.[0],t=[];return e?.message?.tool_calls?.length?e.message.tool_calls.forEach(o=>t.push({type:"tool_use",id:o.id,name:o.function?.name,input:JSON.parse(o.function?.arguments||"{}")})):e?.message?.content&&t.push({type:"text",text:e.message.content}),{blocks:t,stop_reason:e?.finish_reason==="tool_calls"||t.some(o=>o.type==="tool_use")?"tool_use":"end"}}var L=(i,e="chat-completions")=>i.length===0?[]:e==="responses"?i.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):i.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function v(i){if(!i.hasTools){let t=await i.runWithoutTools();await i.onCompleteResponse(t);return}let e=await i.runWithTools();if(i.onToolBlocks&&i.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=f.getFullText(e.blocks);await i.onCompleteResponse(t);return}throw new Error(i.toolErrorMessage)}var E=i=>{let e=i.model??i.defaultModel,t=i.visionModel??(i.supportsVisionForModel(e)?e:i.defaultVisionModel);if(i.validate==="explicit"&&i.visionModel&&!i.supportsVisionForModel(i.visionModel))throw new Error(`Model ${i.visionModel} does not support vision capabilities.`);if(i.validate==="resolved"&&!i.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var uo="https://openrouter.ai/api/v1/models",mo=2,_o=12e3,go=1,fo=10;function Nt(i){return i instanceof Error?i.message:String(i)}function at(i,e){return typeof i!="number"||!Number.isFinite(i)?e:Math.max(1,Math.floor(i))}function vo(i){let e=new Set,t=[];for(let o of i){let r=o.trim();!r||e.has(r)||(e.add(r),t.push(r))}return t}async function jt(i,e,t){if(!(typeof AbortController<"u"))return fetch(i,e);let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(i,{...e,signal:r.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(s)}}async function zt(i){let e=`HTTP ${i.status} ${i.statusText}`.trim(),t="";try{t=await i.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Mo(i){if(!i||typeof i!="object")throw new Error("Invalid models response shape");let e=i,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(r=>r.id).filter(r=>typeof r=="string");return vo(o)}async function Oo({modelId:i,apiKey:e,endpoint:t,timeoutMs:o,appName:r,appUrl:s}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};r&&(n["X-Title"]=r),s&&(n["HTTP-Referer"]=s);try{let a=await jt(t,{method:"POST",headers:n,body:JSON.stringify({model:i,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:i,ok:!1,reason:await zt(a)};try{await a.json()}catch(l){return{id:i,ok:!1,reason:`JSON parse failed: ${Nt(l)}`}}return{id:i,ok:!0}}catch(a){return{id:i,ok:!1,reason:Nt(a)}}}async function Eo(i,e,t){if(i.length===0)return[];let o=new Array(i.length),r=0,s=Math.min(e,i.length);return await Promise.all(Array.from({length:s},async()=>{for(;r<i.length;){let n=r;r+=1,o[n]=await t(i[n])}})),o}async function Co(i){let e=i.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=i.modelsEndpoint||uo,o=i.endpoint||fe,r=at(i.timeoutMs,_o),s=at(i.concurrency,mo),n=at(i.maxCandidates,go),a=at(i.maxWorking,fo),l=await jt(t,{method:"GET"},r);if(!l.ok)throw new Error(await zt(l));let c;try{c=await l.json()}catch(_){throw new Error(`JSON parse failed: ${Nt(_)}`)}let u=Mo(c).filter(_=>
|
|
11
|
+
`);r=l.pop()||"";for(let c of l){let u=c.trim();if(!u||u.startsWith(":")||!u.startsWith("data:"))continue;let h=u.slice(5).trim();if(h==="[DONE]"){s=!0;break}e(h)}}};async function P(i,e,t={}){let o="";return await $t(i,r=>{let s=Kt(r,t.onJsonError);if(!s)return;let n=s.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function x(i,e,t={}){let o=[],r=new Map,s=t.appendTextBlock??f.append;await $t(i,l=>{let c=Kt(l,t.onJsonError);if(!c)return;let u=c.choices?.[0]?.delta;u?.content&&(e(u.content),s(o,u.content)),u?.tool_calls&&u.tool_calls.forEach(h=>{let m=r.get(h.index)??{id:h.id,name:h.function?.name,args:""};m.args+=h.function?.arguments||"",r.set(h.index,m)})});let n=Array.from(r.entries()).sort((l,c)=>l[0]-c[0]).map(([l,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...n],stop_reason:n.length?"tool_use":"end"}}function I(i){let e=i?.choices?.[0],t=[];return e?.message?.tool_calls?.length?e.message.tool_calls.forEach(o=>t.push({type:"tool_use",id:o.id,name:o.function?.name,input:JSON.parse(o.function?.arguments||"{}")})):e?.message?.content&&t.push({type:"text",text:e.message.content}),{blocks:t,stop_reason:e?.finish_reason==="tool_calls"||t.some(o=>o.type==="tool_use")?"tool_use":"end"}}var L=(i,e="chat-completions")=>i.length===0?[]:e==="responses"?i.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):i.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function v(i){if(!i.hasTools){let t=await i.runWithoutTools();await i.onCompleteResponse(t);return}let e=await i.runWithTools();if(i.onToolBlocks&&i.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=f.getFullText(e.blocks);await i.onCompleteResponse(t);return}throw new Error(i.toolErrorMessage)}var E=i=>{let e=i.model??i.defaultModel,t=i.visionModel??(i.supportsVisionForModel(e)?e:i.defaultVisionModel);if(i.validate==="explicit"&&i.visionModel&&!i.supportsVisionForModel(i.visionModel))throw new Error(`Model ${i.visionModel} does not support vision capabilities.`);if(i.validate==="resolved"&&!i.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var uo="https://openrouter.ai/api/v1/models",mo=2,_o=12e3,go=1,fo=10;function Nt(i){return i instanceof Error?i.message:String(i)}function at(i,e){return typeof i!="number"||!Number.isFinite(i)?e:Math.max(1,Math.floor(i))}function vo(i){let e=new Set,t=[];for(let o of i){let r=o.trim();!r||e.has(r)||(e.add(r),t.push(r))}return t}async function jt(i,e,t){if(!(typeof AbortController<"u"))return fetch(i,e);let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(i,{...e,signal:r.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(s)}}async function zt(i){let e=`HTTP ${i.status} ${i.statusText}`.trim(),t="";try{t=await i.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Mo(i){if(!i||typeof i!="object")throw new Error("Invalid models response shape");let e=i,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(r=>r.id).filter(r=>typeof r=="string");return vo(o)}async function Oo({modelId:i,apiKey:e,endpoint:t,timeoutMs:o,appName:r,appUrl:s}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};r&&(n["X-Title"]=r),s&&(n["HTTP-Referer"]=s);try{let a=await jt(t,{method:"POST",headers:n,body:JSON.stringify({model:i,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:i,ok:!1,reason:await zt(a)};try{await a.json()}catch(l){return{id:i,ok:!1,reason:`JSON parse failed: ${Nt(l)}`}}return{id:i,ok:!0}}catch(a){return{id:i,ok:!1,reason:Nt(a)}}}async function Eo(i,e,t){if(i.length===0)return[];let o=new Array(i.length),r=0,s=Math.min(e,i.length);return await Promise.all(Array.from({length:s},async()=>{for(;r<i.length;){let n=r;r+=1,o[n]=await t(i[n])}})),o}async function Co(i){let e=i.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=i.modelsEndpoint||uo,o=i.endpoint||fe,r=at(i.timeoutMs,_o),s=at(i.concurrency,mo),n=at(i.maxCandidates,go),a=at(i.maxWorking,fo),l=await jt(t,{method:"GET"},r);if(!l.ok)throw new Error(await zt(l));let c;try{c=await l.json()}catch(_){throw new Error(`JSON parse failed: ${Nt(_)}`)}let u=Mo(c).filter(_=>W(_)).slice(0,n),h=await Eo(u,s,_=>Oo({modelId:_,apiKey:e,endpoint:o,timeoutMs:r,appName:i.appName,appUrl:i.appUrl})),m=h.filter(_=>_.ok).map(_=>_.id).slice(0,a),p=h.filter(_=>!_.ok).map(_=>({id:_.id,reason:_.reason||"Unknown error"}));return{working:m,failed:p,fetchedAt:Date.now()}}var te=class{constructor(e,t=T,o=T,r=[],s=[],n){this.provider="claude";if(this.apiKey=e,this.model=t||T,this.visionModel=o||T,this.tools=r,this.mcpServers=s,this.responseLength=n,!ge.includes(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`)}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e)}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e)}hasMCPServers(){return this.mcpServers.length>0}async processChat(e,t,o){await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callClaude(e,this.model,!0);return this.parsePureStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(r,t)},runWithTools:()=>this.visionChatOnce(e),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}convertMessagesToClaudeFormat(e){return e.map(t=>({role:this.mapRoleToClaude(t.role),content:t.content}))}convertVisionMessagesToClaudeFormat(e){return e.map(t=>{if(typeof t.content=="string")return{role:this.mapRoleToClaude(t.role),content:[{type:"text",text:t.content}]};if(Array.isArray(t.content)){let o=t.content.map(r=>{if(r.type==="image_url"){if(r.image_url.url.startsWith("data:")){let s=r.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return s?{type:"image",source:{type:"base64",media_type:s[1],data:s[2]}}:null}return{type:"image",source:{type:"url",url:r.image_url.url,media_type:this.getMimeTypeFromUrl(r.image_url.url)}}}return r}).filter(r=>r);return{role:this.mapRoleToClaude(t.role),content:o}}return{role:this.mapRoleToClaude(t.role),content:[]}})}mapRoleToClaude(e){switch(e){case"system":return"system";case"user":return"user";case"assistant":return"assistant";default:return"user"}}getMimeTypeFromUrl(e){switch(e.split(".").pop()?.toLowerCase()){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";default:return"image/jpeg"}}async callClaude(e,t,o,r){let s=e.find(h=>h.role==="system")?.content??"",n=e.filter(h=>h.role!=="system"),a=n.some(h=>Array.isArray(h.content)&&h.content.some(m=>m.type==="image_url"||m.type==="image")),l={model:t,system:s,messages:a?this.convertVisionMessagesToClaudeFormat(n):this.convertMessagesToClaudeFormat(n),stream:o,max_tokens:r!==void 0?r:O(this.responseLength)};this.tools.length&&(l.tools=this.tools.map(h=>({name:h.name,description:h.description,input_schema:h.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let c={"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"};return this.mcpServers.length>0&&(c["anthropic-beta"]="mcp-client-2025-04-04"),await g.post(Ot,l,c)}async parseStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=new Map,a="";for(;;){let{done:l,value:c}=await o.read();if(l)break;a+=r.decode(c,{stream:!0});let u;for(;(u=a.indexOf(`
|
|
12
12
|
`))!==-1;){let h=a.slice(0,u).trim();if(a=a.slice(u+1),!h.startsWith("data:"))continue;let m=h.slice(5).trim();if(m==="[DONE]")break;let p=JSON.parse(m);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),s.push({type:"text",text:p.delta.text})),p.type==="content_block_start"&&p.content_block?.type==="tool_use"?n.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_use"?n.set(p.index,{id:p.content_block.id,name:p.content_block.name,args:"",server_name:p.content_block.server_name}):p.type==="content_block_start"&&p.content_block?.type==="tool_result"?s.push({type:"tool_result",tool_use_id:p.content_block.tool_use_id,content:p.content_block.content??""}):p.type==="content_block_start"&&p.content_block?.type==="mcp_tool_result"&&s.push({type:"mcp_tool_result",tool_use_id:p.content_block.tool_use_id,is_error:p.content_block.is_error??!1,content:p.content_block.content??[]}),p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"){let _=n.get(p.index);_&&(_.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&n.has(p.index)){let{id:_,name:M,args:d,server_name:C}=n.get(p.index);C?s.push({type:"mcp_tool_use",id:_,name:M,server_name:C,input:JSON.parse(d||"{}")}):s.push({type:"tool_use",id:_,name:M,input:JSON.parse(d||"{}")}),n.delete(p.index)}}}return{blocks:s,stop_reason:s.some(l=>l.type==="tool_use"||l.type==="mcp_tool_use")?"tool_use":"end"}}async parsePureStream(e,t){let{blocks:o}=await this.parseStream(e,t);return o.filter(r=>r.type==="text").map(r=>r.text).join("")}parseOneShot(e){let t=[];return(e.content??[]).forEach(o=>{o.type==="text"?t.push({type:"text",text:o.text}):o.type==="tool_use"?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input??{}}):o.type==="mcp_tool_use"?t.push({type:"mcp_tool_use",id:o.id,name:o.name,server_name:o.server_name,input:o.input??{}}):o.type==="tool_result"?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:o.content??""}):o.type==="mcp_tool_result"&&t.push({type:"mcp_tool_result",tool_use_id:o.tool_use_id,is_error:o.is_error??!1,content:o.content??[]})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use"||o.type==="mcp_tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callClaude(e,this.model,t,r),n=t?await this.parseStream(s,o):this.parseOneShot(await s.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callClaude(e,this.visionModel,t,r),n=t?await this.parseStream(s,o):this.parseOneShot(await s.json());return this.convertToStandardCompletion(n)}convertToStandardCompletion(e){return{blocks:e.blocks.filter(o=>o.type==="text"||o.type==="tool_use"||o.type==="tool_result"),stop_reason:e.stop_reason}}};var oe=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new te(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[T,Ae,we,Ne,ke,Ve,Ge,Fe,Ue,He,We]}getDefaultModel(){return T}supportsVision(){return!0}supportsVisionForModel(e){return ge.includes(e)}};var lt=class{static async fetchToolSchemas(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let r=await(await g.post(`${e.url}/tools`,{},t)).json();return Array.isArray(r.tools)?r.tools.map(s=>({name:`mcp_${e.name}_${s.name}`,description:s.description||`Tool from ${e.name} MCP server`,parameters:s.inputSchema||{type:"object",properties:{},required:[]}})):[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}catch(t){return console.warn(`Failed to fetch MCP schemas from ${e.name}:`,t),[{name:`mcp_${e.name}_search`,description:`Search using ${e.name} MCP server (schema fetch failed)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}]}}static async fetchAllToolSchemas(e){let t=[];for(let o of e)try{let r=await this.fetchToolSchemas(o);t.push(...r)}catch(r){console.error(`Failed to fetch schemas from ${o.name}:`,r)}return t}};var re=class{constructor(e,t=D,o=D,r=[],s=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!_e.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=r,this.mcpServers=s}safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}normalizeToolResult(e){return e===null?{content:null}:typeof e=="object"?e:{content:e}}adaptKeysForApi(e){let t={toolConfig:"tool_config",functionCallingConfig:"function_calling_config",functionDeclarations:"function_declarations",functionCall:"function_call",functionResponse:"function_response"};return Array.isArray(e)?e.map(o=>this.adaptKeysForApi(o)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,r])=>[t[o]??o,this.adaptKeysForApi(r)])):e}getModel(){return this.model}getVisionModel(){return this.visionModel}getMCPServers(){return this.mcpServers}addMCPServer(e){this.mcpServers.push(e),this.mcpSchemasInitialized=!1}removeMCPServer(e){this.mcpServers=this.mcpServers.filter(t=>t.name!==e),this.mcpSchemasInitialized=!1}hasMCPServers(){return this.mcpServers.length>0}async initializeMCPSchemas(){if(!(this.mcpSchemasInitialized||this.mcpServers.length===0))try{let e=new Promise((o,r)=>setTimeout(()=>r(new Error("MCP schema fetch timeout")),5e3)),t=lt.fetchAllToolSchemas(this.mcpServers);this.mcpToolSchemas=await Promise.race([t,e]),this.mcpSchemasInitialized=!0}catch(e){console.warn("Failed to initialize MCP schemas, using fallback:",e),this.mcpToolSchemas=this.mcpServers.map(t=>({name:`mcp_${t.name}_search`,description:`Search using ${t.name} MCP server (fallback)`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}})),this.mcpSchemasInitialized=!0}}async processChat(e,t,o){try{await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.model,!0),{blocks:s}=await this.parseStream(r,t);return f.getFullText(s)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processChat:",r),r}}async processVisionChat(e,t,o){try{await v({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let r=await this.callGemini(e,this.visionModel,!0),{blocks:s}=await this.parseStream(r,t);return f.getFullText(s)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:r=>{r.filter(s=>s.type==="text").forEach(s=>t(s.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}convertMessagesToGeminiFormat(e){let t=[],o=null,r=[],s=()=>{o&&r.length&&(t.push({role:o,parts:[...r]}),r=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){s();for(let l of n.tool_calls)this.callIdMap.set(l.id,l.function.name),t.push({role:"model",parts:[{functionCall:{name:l.function.name,args:JSON.parse(l.function.arguments||"{}")}}]});continue}if(n.role==="tool"){s();let l=n.name??this.callIdMap.get(n.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:l,response:this.normalizeToolResult(this.safeJsonParse(n.content))}}]});continue}a!==o&&s(),o=a,r.push({text:n.content})}return s(),t}async callGemini(e,t,o=!1,r){let a={contents:e.some(d=>Array.isArray(d.content)&&d.content.some(C=>C?.type==="image_url"||C?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:r!==void 0?r:O(this.responseLength)}},l=[];if(this.tools.length>0&&l.push(...this.tools.map(d=>({name:d.name,description:d.description,parameters:d.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l.push(...this.mcpToolSchemas.map(d=>({name:d.name,description:d.description,parameters:d.parameters})))}catch(d){console.warn("MCP initialization failed, skipping MCP tools:",d)}l.length>0&&(a.tools=[{functionDeclarations:l}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let c=async(d,C)=>{let pt=o?"streamGenerateContent":"generateContent",kt=o?"?alt=sse":"",Zt=`${Mt}/${d}/models/${t}:${pt}${kt}${kt?"&":"?"}key=${this.apiKey}`;return g.post(Zt,C)},u=/flash[-_]lite/.test(t),h=/gemini-2\.5/.test(t),m=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),p=u||h||m,_=p?"v1beta":"v1",M=async()=>{try{let d=_==="v1"?a:this.adaptKeysForApi(a);return await c(_,d)}catch(d){let C=/Unknown name|Cannot find field|404/.test(d?.message||"")||d?.status===404;if(!p&&C)return await c("v1beta",this.adaptKeysForApi(a));throw d}};try{return await M()}catch(d){throw d.body&&(console.error("Gemini API Error Details:",d.body),console.error("Request Body:",JSON.stringify(a,null,2))),d}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,r=[];for(let s of e){let n=this.mapRoleToGemini(s.role);if(s.tool_calls){for(let a of s.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(s.role==="tool"){let a=s.name??this.callIdMap.get(s.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(s.content))}}]});continue}if(n!==o&&r.length>0&&(t.push({role:o,parts:[...r]}),r=[]),o=n,typeof s.content=="string")r.push({text:s.content});else if(Array.isArray(s.content)){for(let a of s.content)if(a.type==="text")r.push({text:a.text});else if(a.type==="image_url")try{let c=await(await g.get(a.image_url.url)).blob(),u=await this.blobToBase64(c);r.push({inlineData:{mimeType:c.type||"image/jpeg",data:u.split(",")[1]}})}catch(l){throw console.error("Error processing image:",l),new Error(`Failed to process image: ${l.message}`)}}}return o&&r.length>0&&t.push({role:o,parts:[...r]}),t}blobToBase64(e){return new Promise((t,o)=>{let r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=o,r.readAsDataURL(e)})}mapRoleToGemini(e){switch(e){case"system":return"model";case"user":return"user";case"assistant":return"model";default:return"user"}}async parseStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=[],a="",l=u=>{if(!u||u==="[DONE]")return;let h;try{h=JSON.parse(u)}catch{return}for(let m of h.candidates??[])for(let p of m.content?.parts??[])p.text&&(t(p.text),f.addTextBlock(s,p.text)),p.functionCall&&n.push({type:"tool_use",id:this.genUUID(),name:p.functionCall.name,input:p.functionCall.args??{}}),p.functionResponse&&n.push({type:"tool_result",tool_use_id:p.functionResponse.name,content:JSON.stringify(p.functionResponse.response)})};for(;;){let{done:u,value:h}=await o.read();if(u)break;a+=r.decode(h,{stream:!0});let m;for(;(m=a.indexOf(`
|
|
13
|
-
`))!==-1;){let p=a.slice(0,m);if(a=a.slice(m+1),p.endsWith("\r")&&(p=p.slice(0,-1)),!p.trim()){l("");continue}p.startsWith("data:")&&(p=p.slice(5).trim()),p&&l(p)}}return a&&l(a),{blocks:[...s,...n],stop_reason:n.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let s of e.candidates??[])for(let n of s.content?.parts??[])n.text&&t.push({type:"text",text:n.text}),n.functionCall&&o.push({type:"tool_use",id:this.genUUID(),name:n.functionCall.name,input:n.functionCall.args??{}}),n.functionResponse&&o.push({type:"tool_result",tool_use_id:n.functionResponse.name,content:JSON.stringify(n.functionResponse.response)});return{blocks:[...t,...o],stop_reason:o.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callGemini(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callGemini(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var se=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new re(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Te,Se,Pe,xe,Ie,Le,be,Re,De,D]}getDefaultModel(){return D}supportsVision(){return!0}supportsVisionForModel(e){return _e.includes(e)}};var ie=class{constructor(e,t=S,o=S,r,s=Y,n,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.responseFormat=a,this.thinking=l??{type:"enabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callKimi(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callKimi(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(s.chat_template_kwargs={thinking:!1}):s.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(s.tools=l,s.tool_choice="auto"),s}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Y)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ne=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),r=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),s=e.tools,n=e.thinking??{type:"enabled"},a=s&&s.length>0?{type:"disabled"}:n;return new ie(e.apiKey,o,r,s,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[S]}getDefaultModel(){return S}getDefaultVisionModel(){return S}supportsVision(){return!0}supportsVisionForModel(e){return Q(e)}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Y}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var N=class{constructor(e,t=
|
|
14
|
-
`);a=_.pop()||"";for(let M=0;M<_.length;M++){let d=_[M].trim();if(d.startsWith("event:"))m=d.slice(6).trim();else if(d.startsWith("data:"))p=d.slice(5).trim();else if(d===""&&m&&p){try{let C=JSON.parse(p),pt=this.handleResponsesSSEEvent(m,C,t,s,n)}catch{console.warn("Failed to parse SSE data:",p)}m="",p=""}}}let l=Array.from(n.values()).map(u=>({type:"tool_use",id:u.id,name:u.name,input:u.input||{}}));return{blocks:[...s,...l],stop_reason:l.length?"tool_use":"end"}}handleResponsesSSEEvent(e,t,o,r,s){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(n=>{n.type==="output_text"&&n.text&&(o(n.text),f.append(r,n.text))}):t.item?.type==="function_call"&&s.set(t.item.id,{id:t.item.id,name:t.item.name,input:t.item.arguments?JSON.parse(t.item.arguments):{}});break;case"response.content_part.added":t.part?.type==="output_text"&&typeof t.part.text=="string"&&(o(t.part.text),f.append(r,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let n=typeof t.delta=="string"?t.delta:t.delta?.text??"";n&&(o(n),f.append(r,n))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(r=>{r.type==="output_text"&&r.text&&t.push({type:"text",text:r.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:o.arguments?JSON.parse(o.arguments):{}})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end"}}};var ae=class{createChatService(e){return this.validateRequiredOptions(e),new N(e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return!1}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var le=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),r=t.tools,s=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;s.length>0||dt(n)?a=!0:q(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?y:B);return new N(t.apiKey,n,o,r,l,s,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[k,K,$,V,b,j,z,R,Oe,Ee,Ce,G,ye,ht,ut,"o1"]}getDefaultModel(){return k}supportsVision(){return!0}supportsVisionForModel(e){return de.includes(e)}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!q(t))return e;let o={...e};if(e.gpt5Preset){let r=At[e.gpt5Preset];o.reasoning_effort=r.reasoning_effort,o.verbosity=r.verbosity}else e.reasoning_effort||(o.reasoning_effort=F(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!gt(e)?F(e):t==="minimal"&&!ft(e)?F(e):t==="low"&&!vt(e)?F(e):t==="xhigh"&&!_t(e)?F(e):t}};var pe=class{constructor(e,t=A,o=A,r,s=fe,n,a,l,c,u,h){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=c,this.includeReasoning=u,this.reasoningMaxTokens=h,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!U(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=St){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(r=>setTimeout(r,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){await this.applyRateLimiting();let s=await this.callOpenRouter(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){if(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let s=await this.callOpenRouter(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async callOpenRouter(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await g.post(this.endpoint,s,n)}buildRequestBody(e,t,o,r){let s={model:t,messages:e,stream:o};if((r!==void 0?r:O(this.responseLength))&&console.warn("OpenRouter: Token limits are not supported for gpt-oss-20b model due to known issues. Using unlimited tokens instead."),this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens){if(s.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;s.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(s.reasoning.exclude=!0),this.reasoningMaxTokens&&(s.reasoning.max_tokens=this.reasoningMaxTokens)}else s.reasoning={exclude:!0};return this.tools.length>0&&(s.tools=L(this.tools,"chat-completions"),s.tool_choice="auto"),s}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ce=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),o=e.tools,r=e.appName,s=e.appUrl;return new pe(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,r,s,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[A,st,Ke,$e,je,ze,qe,Je,Ze,Xe,Ye,Qe,Et,et,tt,ot,rt,Ct,yt,Be]}getDefaultModel(){return A}supportsVision(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))}supportsVisionForModel(e){return J(e)}getFreeModels(){return Tt}isModelFree(e){return U(e)}};var he=class{constructor(e,t=Z,o=H,r,s=ve,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.responseFormat=a,this.thinking=l??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callZAI(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callZAI(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat),this.thinking&&(s.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(s.tools=a,s.tool_choice="auto",o&&Rt(t)&&(s.tool_stream=!0)),s}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ue=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),r=e.tools,s=e.thinking??{type:"disabled"};return new he(e.apiKey,t,o,r,e.endpoint||ve,e.responseLength,e.responseFormat,s)}getProviderName(){return"zai"}getSupportedModels(){return[Pt,xt,Z,It,Lt,bt,it,nt,H]}getDefaultModel(){return Z}getDefaultVisionModel(){return H}supportsVision(){return!0}supportsVisionForModel(e){return X(e)}};var qt=[new le,new ae,new se,new oe,new ce,new ue,new ne];var me=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}};me.providers=new Map;qt.forEach(i=>me.registerProvider(i));function Jt(){g.setFetch(async(i,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,r={};if(Array.isArray(o))for(let[h,m]of o)r[h]=String(m);else if(o&&typeof o=="object")for(let[h,m]of Object.entries(o))r[h]=String(m);let s={method:t,headers:r,muteHttpExceptions:!0},n=e.body;typeof n=="string"?s.payload=n:n!=null&&(r["Content-Type"]||(r["Content-Type"]="application/json"),s.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(i,s),l=a.getResponseCode(),c=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return oo(yo);})();
|
|
13
|
+
`))!==-1;){let p=a.slice(0,m);if(a=a.slice(m+1),p.endsWith("\r")&&(p=p.slice(0,-1)),!p.trim()){l("");continue}p.startsWith("data:")&&(p=p.slice(5).trim()),p&&l(p)}}return a&&l(a),{blocks:[...s,...n],stop_reason:n.some(u=>u.type==="tool_use")?"tool_use":"end"}}parseOneShot(e){let t=[],o=[];for(let s of e.candidates??[])for(let n of s.content?.parts??[])n.text&&t.push({type:"text",text:n.text}),n.functionCall&&o.push({type:"tool_use",id:this.genUUID(),name:n.functionCall.name,input:n.functionCall.args??{}}),n.functionResponse&&o.push({type:"tool_result",tool_use_id:n.functionResponse.name,content:JSON.stringify(n.functionResponse.response)});return{blocks:[...t,...o],stop_reason:o.some(s=>s.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callGemini(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callGemini(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}genUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};var se=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:o=>this.supportsVisionForModel(o),validate:"resolved"});return new re(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Te,Se,Pe,xe,Ie,Le,be,Re,De,D]}getDefaultModel(){return D}supportsVision(){return!0}supportsVisionForModel(e){return _e.includes(e)}};var ie=class{constructor(e,t=S,o=S,r,s=Y,n,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.responseFormat=a,this.thinking=l??{type:"enabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callKimi(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callKimi(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!Q(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callKimi(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(s.chat_template_kwargs={thinking:!1}):s.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(s.tools=l,s.tool_choice="auto"),s}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(Y)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ne=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),r=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),s=e.tools,n=e.thinking??{type:"enabled"},a=s&&s.length>0?{type:"disabled"}:n;return new ie(e.apiKey,o,r,s,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[S]}getDefaultModel(){return S}getDefaultVisionModel(){return S}supportsVision(){return!0}supportsVisionForModel(e){return Q(e)}resolveEndpoint(e){if(e.endpoint)return this.normalizeEndpoint(e.endpoint);if(e.baseUrl){let t=this.normalizeEndpoint(e.baseUrl);return t.endsWith("/chat/completions")?t:`${t}/chat/completions`}return Y}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var N=class{constructor(e,t=U,o=U,r,s=$,n=[],a,l,c,u=!1,h="openai",m=!0){if(this.provider=h,this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.mcpServers=n,this.responseLength=a,this.verbosity=l,this.reasoning_effort=c,this.enableReasoningSummary=u,m&&!de.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.model,!0),s=this.endpoint===y;try{if(s){let n=await this.parseResponsesStream(r,t);return f.getFullText(n.blocks)}return this.handleStream(r,t)}catch(n){throw console.error("[processChat] Error in streaming/completion:",n),n}},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){try{await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenAI(e,this.visionModel,!0),s=this.endpoint===y;try{if(s){let n=await this.parseResponsesStream(r,t);return f.getFullText(n.blocks)}return this.handleStream(r,t)}catch(n){throw console.error("[processVisionChat] Error in streaming/completion:",n),n}},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callOpenAI(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){let s=await this.callOpenAI(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return this.endpoint===y?t?this.parseResponsesStream(e,o):this.parseResponsesOneShot(await e.json()):t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callOpenAI(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r),n={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(n.Authorization=`Bearer ${this.apiKey}`),await g.post(this.endpoint,s,n)}buildRequestBody(e,t,o,r){let s=this.endpoint===y;this.validateMCPCompatibility();let n={model:t,stream:o},a=r!==void 0?r:this.provider==="openai-compatible"?this.responseLength!==void 0?O(this.responseLength):void 0:O(this.responseLength);s?a!==void 0&&(n.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?n.max_tokens=a:n.max_completion_tokens=a),s?n.input=this.cleanMessagesForResponsesAPI(e):n.messages=e,q(t)&&(s?(this.reasoning_effort&&(n.reasoning={...n.reasoning,effort:this.reasoning_effort},this.enableReasoningSummary&&(n.reasoning.summary="auto")),this.verbosity&&(n.text={...n.text,format:{type:"text"},verbosity:this.verbosity})):(this.reasoning_effort&&(n.reasoning_effort=this.reasoning_effort),this.verbosity&&(n.verbosity=this.verbosity)));let l=this.buildToolsDefinition();return l.length>0&&(n.tools=l,s||(n.tool_choice="auto")),n}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===$)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${y}. MCP tools are only available in the Responses API endpoint.`)}cleanMessagesForResponsesAPI(e){return e.map(t=>{let r={role:t.role==="tool"?"user":t.role};return typeof t.content=="string"?r.content=t.content:Array.isArray(t.content)?r.content=t.content.map(s=>s.type==="text"?{type:"input_text",text:s.text}:s.type==="image_url"?{type:"input_image",image_url:s.image_url.url}:s):r.content=t.content,r})}buildToolsDefinition(){let e=this.endpoint===y,t=[];return this.tools.length>0&&t.push(...L(this.tools,e?"responses":"chat-completions")),this.mcpServers.length>0&&e&&t.push(...this.buildMCPToolsDefinition()),t}buildMCPToolsDefinition(){return this.mcpServers.map(e=>{let t={type:"mcp",server_label:e.name,server_url:e.url};return e.require_approval&&(t.require_approval=e.require_approval),e.tool_configuration?.allowed_tools&&(t.allowed_tools=e.tool_configuration.allowed_tools),e.authorization_token&&(t.headers={Authorization:`Bearer ${e.authorization_token}`}),t})}async handleStream(e,t){return P(e,t)}async parseStream(e,t){return x(e,t,{appendTextBlock:f.addTextBlock})}parseOneShot(e){return I(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),r=new TextDecoder,s=[],n=new Map,a="";for(;;){let{done:u,value:h}=await o.read();if(u)break;a+=r.decode(h,{stream:!0});let m="",p="",_=a.split(`
|
|
14
|
+
`);a=_.pop()||"";for(let M=0;M<_.length;M++){let d=_[M].trim();if(d.startsWith("event:"))m=d.slice(6).trim();else if(d.startsWith("data:"))p=d.slice(5).trim();else if(d===""&&m&&p){try{let C=JSON.parse(p),pt=this.handleResponsesSSEEvent(m,C,t,s,n)}catch{console.warn("Failed to parse SSE data:",p)}m="",p=""}}}let l=Array.from(n.values()).map(u=>({type:"tool_use",id:u.id,name:u.name,input:u.input||{}}));return{blocks:[...s,...l],stop_reason:l.length?"tool_use":"end"}}handleResponsesSSEEvent(e,t,o,r,s){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(n=>{n.type==="output_text"&&n.text&&(o(n.text),f.append(r,n.text))}):t.item?.type==="function_call"&&s.set(t.item.id,{id:t.item.id,name:t.item.name,input:t.item.arguments?JSON.parse(t.item.arguments):{}});break;case"response.content_part.added":t.part?.type==="output_text"&&typeof t.part.text=="string"&&(o(t.part.text),f.append(r,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let n=typeof t.delta=="string"?t.delta:t.delta?.text??"";n&&(o(n),f.append(r,n))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(r=>{r.type==="output_text"&&r.text&&t.push({type:"text",text:r.text})}),o.type==="function_call"&&t.push({type:"tool_use",id:o.id,name:o.name,input:o.arguments?JSON.parse(o.arguments):{}})}),{blocks:t,stop_reason:t.some(o=>o.type==="tool_use")?"tool_use":"end"}}};var ae=class{createChatService(e){return this.validateRequiredOptions(e),new N(e.apiKey?.trim()??"",e.model,e.visionModel??e.model,e.tools,e.endpoint,[],e.responseLength,e.verbosity,e.reasoning_effort,e.enableReasoningSummary,this.getProviderName(),!1)}getProviderName(){return"openai-compatible"}getSupportedModels(){return[]}supportsVision(){return!1}getDefaultModel(){return"local-model"}validateRequiredOptions(e){if(e.mcpServers!==void 0)throw new Error("openai-compatible provider does not support mcpServers.");let t=e.endpoint?.trim();if(!t)throw new Error("openai-compatible provider requires endpoint (full URL).");let o;try{o=new URL(t)}catch{throw new Error("openai-compatible provider requires endpoint to be a full URL.")}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("openai-compatible provider requires endpoint to be a full URL.");if(!e.model?.trim())throw new Error("openai-compatible provider requires model.")}};var le=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:c=>this.supportsVisionForModel(c),validate:"resolved"}),r=t.tools,s=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;s.length>0||dt(n)?a=!0:q(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?y:$);return new N(t.apiKey,n,o,r,l,s,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[k,j,z,V,b,G,F,R,Oe,Ee,Ce,U,ye,ht,ut,"o1"]}getDefaultModel(){return k}supportsVision(){return!0}supportsVisionForModel(e){return de.includes(e)}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!q(t))return e;let o={...e};if(e.gpt5Preset){let r=At[e.gpt5Preset];o.reasoning_effort=r.reasoning_effort,o.verbosity=r.verbosity}else e.reasoning_effort||(o.reasoning_effort=H(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!gt(e)?H(e):t==="minimal"&&!ft(e)?H(e):t==="low"&&!vt(e)?H(e):t==="xhigh"&&!_t(e)?H(e):t}};var pe=class{constructor(e,t=A,o=A,r,s=fe,n,a,l,c,u,h){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=c,this.includeReasoning=u,this.reasoningMaxTokens=h,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!W(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=St){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(r=>setTimeout(r,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(r){throw console.error("Error in processVisionChat:",r),r}}async chatOnce(e,t=!0,o=()=>{},r){await this.applyRateLimiting();let s=await this.callOpenRouter(e,this.model,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async visionChatOnce(e,t=!1,o=()=>{},r){if(!J(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let s=await this.callOpenRouter(e,this.visionModel,t,r);return t?this.parseStream(s,o):this.parseOneShot(await s.json())}async callOpenRouter(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await g.post(this.endpoint,s,n)}buildRequestBody(e,t,o,r){let s={model:t,messages:e,stream:o};if((r!==void 0?r:O(this.responseLength))&&console.warn("OpenRouter: Token limits are not supported for gpt-oss-20b model due to known issues. Using unlimited tokens instead."),this.reasoning_effort!==void 0||this.includeReasoning!==void 0||this.reasoningMaxTokens){if(s.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;s.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(s.reasoning.exclude=!0),this.reasoningMaxTokens&&(s.reasoning.max_tokens=this.reasoningMaxTokens)}else s.reasoning={exclude:!0};return this.tools.length>0&&(s.tools=L(this.tools,"chat-completions"),s.tool_choice="auto"),s}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ce=class{createChatService(e){let t=E({model:e.model,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:e.model||this.getDefaultModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),o=e.tools,r=e.appName,s=e.appUrl;return new pe(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,r,s,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[A,st,Ke,$e,je,ze,qe,Je,Ze,Xe,Ye,Qe,Et,et,tt,ot,rt,Ct,yt,Be]}getDefaultModel(){return A}supportsVision(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))}supportsVisionForModel(e){return J(e)}getFreeModels(){return Tt}isModelFree(e){return W(e)}};var he=class{constructor(e,t=Z,o=B,r,s=ve,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=r||[],this.endpoint=s,this.responseLength=n,this.responseFormat=a,this.thinking=l??{type:"disabled"},this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.model,!0);return this.handleStream(r,t)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processChat received tool_calls. ChatProcessor must use chatOnce() loop when tools are enabled."})}async processVisionChat(e,t,o){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await v({hasTools:this.tools.length>0,runWithoutTools:async()=>{let r=await this.callZAI(e,this.visionModel,!0);return this.handleStream(r,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}async chatOnce(e,t=!0,o=()=>{},r){let s=await this.callZAI(e,this.model,t,r);return this.parseResponse(s,t,o)}async visionChatOnce(e,t=!1,o=()=>{},r){if(!X(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let s=await this.callZAI(e,this.visionModel,t,r);return this.parseResponse(s,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,r){let s=this.buildRequestBody(e,t,o,r);return await g.post(this.endpoint,s,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,r){let s={model:t,stream:o,messages:e},n=r!==void 0?r:O(this.responseLength);n!==void 0&&(s.max_tokens=n),this.responseFormat&&(s.response_format=this.responseFormat),this.thinking&&(s.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(s.tools=a,s.tool_choice="auto",o&&Rt(t)&&(s.tool_stream=!0)),s}buildToolsDefinition(){return L(this.tools,"chat-completions")}async handleStream(e,t){return P(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return x(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return I(e)}};var ue=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:n=>this.supportsVisionForModel(n),validate:"explicit"}),r=e.tools,s=e.thinking??{type:"disabled"};return new he(e.apiKey,t,o,r,e.endpoint||ve,e.responseLength,e.responseFormat,s)}getProviderName(){return"zai"}getSupportedModels(){return[Pt,xt,Z,It,Lt,bt,it,nt,B]}getDefaultModel(){return Z}getDefaultVisionModel(){return B}supportsVision(){return!0}supportsVisionForModel(e){return X(e)}};var qt=[new le,new ae,new se,new oe,new ce,new ue,new ne];var me=class{static registerProvider(e){this.providers.set(e.getProviderName(),e)}static createChatService(e,t){let o=this.providers.get(e);if(!o)throw new Error(`Unknown chat provider: ${e}`);return o.createChatService(t)}static getProviders(){return this.providers}static getAvailableProviders(){return Array.from(this.providers.keys())}static getSupportedModels(e){let t=this.providers.get(e);return t?t.getSupportedModels():[]}};me.providers=new Map;qt.forEach(i=>me.registerProvider(i));function Jt(){g.setFetch(async(i,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,r={};if(Array.isArray(o))for(let[h,m]of o)r[h]=String(m);else if(o&&typeof o=="object")for(let[h,m]of Object.entries(o))r[h]=String(m);let s={method:t,headers:r,muteHttpExceptions:!0},n=e.body;typeof n=="string"?s.payload=n:n!=null&&(r["Content-Type"]||(r["Content-Type"]="application/json"),s.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(i,s),l=a.getResponseCode(),c=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>c,json:async()=>c?JSON.parse(c):null}})}return oo(yo);})();
|