@aituber-onair/chat 0.25.0 → 0.25.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/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.d.ts +2 -0
- package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.d.ts.map +1 -1
- package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js +28 -3
- package/dist/cjs/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -1
- package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.d.ts +2 -0
- package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.d.ts.map +1 -1
- package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js +28 -3
- package/dist/esm/services/providers/geminiNano/GeminiNanoChatService.js.map +1 -1
- package/dist/umd/aituber-onair-chat.js +23 -3
- package/dist/umd/aituber-onair-chat.min.js +11 -9
- package/package.json +1 -1
|
@@ -33,5 +33,7 @@ export declare class GeminiNanoChatService implements ChatService {
|
|
|
33
33
|
* Context history (excluding the last user message) is embedded in the system prompt.
|
|
34
34
|
*/
|
|
35
35
|
private createSession;
|
|
36
|
+
private buildSystemPrompt;
|
|
37
|
+
private getResponseLengthInstruction;
|
|
36
38
|
}
|
|
37
39
|
//# sourceMappingURL=GeminiNanoChatService.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeminiNanoChatService.d.ts","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"GeminiNanoChatService.d.ts","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts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AE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAe,EACrD,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,kBAAkB,CAAC;IAI9B;;OAEG;YACW,gBAAgB;IAqD9B;;;OAGG;YACW,aAAa;IA6B3B,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,4BAA4B;CAgBrC"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.GeminiNanoChatService = void 0;
|
|
4
4
|
const geminiNano_1 = require("../../../constants/geminiNano");
|
|
5
|
+
const chat_1 = require("../../../constants/chat");
|
|
5
6
|
/**
|
|
6
7
|
* Get the LanguageModel API from the global scope.
|
|
7
8
|
* Returns undefined in non-browser environments or unsupported browsers.
|
|
@@ -23,7 +24,6 @@ class GeminiNanoChatService {
|
|
|
23
24
|
this.expectedInputLanguages = options.expectedInputLanguages ?? ['ja'];
|
|
24
25
|
this.expectedOutputLanguages = options.expectedOutputLanguages ?? ['ja'];
|
|
25
26
|
this._responseLength = options.responseLength;
|
|
26
|
-
void this._responseLength;
|
|
27
27
|
}
|
|
28
28
|
getModel() {
|
|
29
29
|
return geminiNano_1.MODEL_GEMINI_NANO;
|
|
@@ -102,7 +102,7 @@ class GeminiNanoChatService {
|
|
|
102
102
|
* Context history (excluding the last user message) is embedded in the system prompt.
|
|
103
103
|
*/
|
|
104
104
|
async createSession(api, systemPrompt, contextHistory) {
|
|
105
|
-
let prompt = systemPrompt;
|
|
105
|
+
let prompt = this.buildSystemPrompt(systemPrompt);
|
|
106
106
|
// Embed conversation history into system prompt (exclude last user msg)
|
|
107
107
|
const historyMessages = contextHistory.slice(0, -1);
|
|
108
108
|
if (historyMessages.length > 0) {
|
|
@@ -110,7 +110,7 @@ class GeminiNanoChatService {
|
|
|
110
110
|
.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`)
|
|
111
111
|
.join('\n');
|
|
112
112
|
prompt +=
|
|
113
|
-
'\n\n
|
|
113
|
+
'\n\nThe following is the prior conversation history. Use it as context for your response:\n' +
|
|
114
114
|
history;
|
|
115
115
|
}
|
|
116
116
|
return api.create({
|
|
@@ -123,6 +123,31 @@ class GeminiNanoChatService {
|
|
|
123
123
|
],
|
|
124
124
|
});
|
|
125
125
|
}
|
|
126
|
+
buildSystemPrompt(systemPrompt) {
|
|
127
|
+
const promptParts = [];
|
|
128
|
+
if (systemPrompt) {
|
|
129
|
+
promptParts.push(systemPrompt);
|
|
130
|
+
}
|
|
131
|
+
const lengthInstruction = this.getResponseLengthInstruction();
|
|
132
|
+
if (lengthInstruction) {
|
|
133
|
+
promptParts.push(lengthInstruction);
|
|
134
|
+
}
|
|
135
|
+
return promptParts.join('\n\n');
|
|
136
|
+
}
|
|
137
|
+
getResponseLengthInstruction() {
|
|
138
|
+
if (!this._responseLength) {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
const maxTokens = chat_1.MAX_TOKENS_BY_LENGTH[this._responseLength];
|
|
142
|
+
if (!maxTokens) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
// Chrome LanguageModel API does not expose a max output length parameter,
|
|
146
|
+
// so we inject a soft output-length instruction into the prompt instead.
|
|
147
|
+
// We express the instruction in English so it is language-neutral across
|
|
148
|
+
// any value of expectedOutputLanguages.
|
|
149
|
+
return `Please keep your response concise, within approximately ${maxTokens} tokens.`;
|
|
150
|
+
}
|
|
126
151
|
}
|
|
127
152
|
exports.GeminiNanoChatService = GeminiNanoChatService;
|
|
128
153
|
//# sourceMappingURL=GeminiNanoChatService.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeminiNanoChatService.js","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":";;;AAGA,8DAGuC;
|
|
1
|
+
{"version":3,"file":"GeminiNanoChatService.js","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/Gemin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AAO,CAAC;QACZ,CAAC;QAED,OAAO,GAAG,CAAC,MAAM,CAAC;YAChB,YAAY,EAAE,MAAM;YACpB,cAAc,EAAE;gBACd,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,sBAAsB,EAAE;aACzD;YACD,eAAe,EAAE;gBACf,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,uBAAuB,EAAE;aAC1D;SACF,CAAC,CAAC;IACL,CAAC;IAEO,iBAAiB,CAAC,YAAqB;QAC7C,MAAM,WAAW,GAAa,EAAE,CAAC;QAEjC,IAAI,YAAY,EAAE,CAAC;YACjB,WAAW,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACjC,CAAC;QAED,MAAM,iBAAiB,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;QAC9D,IAAI,iBAAiB,EAAE,CAAC;YACtB,WAAW,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QACtC,CAAC;QAED,OAAO,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;IAEO,4BAA4B;QAClC,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YAC1B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,SAAS,GAAG,2BAAoB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC7D,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,0EAA0E;QAC1E,yEAAyE;QACzE,yEAAyE;QACzE,wCAAwC;QACxC,OAAO,2DAA2D,SAAS,UAAU,CAAC;IACxF,CAAC;CACF;AA5LD,sDA4LC"}
|
|
@@ -33,5 +33,7 @@ export declare class GeminiNanoChatService implements ChatService {
|
|
|
33
33
|
* Context history (excluding the last user message) is embedded in the system prompt.
|
|
34
34
|
*/
|
|
35
35
|
private createSession;
|
|
36
|
+
private buildSystemPrompt;
|
|
37
|
+
private getResponseLengthInstruction;
|
|
36
38
|
}
|
|
37
39
|
//# sourceMappingURL=GeminiNanoChatService.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeminiNanoChatService.d.ts","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"GeminiNanoChatService.d.ts","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAS7D,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AA2B3E;;;;GAIG;AACH,qBAAa,qBAAsB,YAAW,WAAW;IACvD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAiB;IAE1C,OAAO,CAAC,sBAAsB,CAAW;IACzC,OAAO,CAAC,uBAAuB,CAAW;IAC1C,OAAO,CAAC,eAAe,CAAC,CAAqB;gBAEjC,OAAO,GAAE,4BAAiC;IAMtD,QAAQ,IAAI,MAAM;IAIlB,cAAc,IAAI,MAAM;IAIxB;;;;OAIG;IACG,WAAW,CACf,QAAQ,EAAE,OAAO,EAAE,EACnB,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EACzC,kBAAkB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAClD,OAAO,CAAC,IAAI,CAAC;IAMV,iBAAiB,CACrB,SAAS,EAAE,iBAAiB,EAAE,EAC9B,kBAAkB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAC1C,mBAAmB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GACnD,OAAO,CAAC,IAAI,CAAC;IAIV,QAAQ,CACZ,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,GAAE,OAAe,EACxB,iBAAiB,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAe,EACpD,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,kBAAkB,CAAC;IAUxB,cAAc,CAClB,SAAS,EAAE,iBAAiB,EAAE,EAC9B,OAAO,GAAE,OAAe,EACxB,kBAAkB,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAe,EACrD,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,kBAAkB,CAAC;IAI9B;;OAEG;YACW,gBAAgB;IAqD9B;;;OAGG;YACW,aAAa;IA6B3B,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,4BAA4B;CAgBrC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MODEL_GEMINI_NANO, GEMINI_NANO_MAX_CONTEXT_MESSAGES, } from '../../../constants/geminiNano';
|
|
2
|
+
import { MAX_TOKENS_BY_LENGTH, } from '../../../constants/chat';
|
|
2
3
|
/**
|
|
3
4
|
* Get the LanguageModel API from the global scope.
|
|
4
5
|
* Returns undefined in non-browser environments or unsupported browsers.
|
|
@@ -20,7 +21,6 @@ export class GeminiNanoChatService {
|
|
|
20
21
|
this.expectedInputLanguages = options.expectedInputLanguages ?? ['ja'];
|
|
21
22
|
this.expectedOutputLanguages = options.expectedOutputLanguages ?? ['ja'];
|
|
22
23
|
this._responseLength = options.responseLength;
|
|
23
|
-
void this._responseLength;
|
|
24
24
|
}
|
|
25
25
|
getModel() {
|
|
26
26
|
return MODEL_GEMINI_NANO;
|
|
@@ -99,7 +99,7 @@ export class GeminiNanoChatService {
|
|
|
99
99
|
* Context history (excluding the last user message) is embedded in the system prompt.
|
|
100
100
|
*/
|
|
101
101
|
async createSession(api, systemPrompt, contextHistory) {
|
|
102
|
-
let prompt = systemPrompt;
|
|
102
|
+
let prompt = this.buildSystemPrompt(systemPrompt);
|
|
103
103
|
// Embed conversation history into system prompt (exclude last user msg)
|
|
104
104
|
const historyMessages = contextHistory.slice(0, -1);
|
|
105
105
|
if (historyMessages.length > 0) {
|
|
@@ -107,7 +107,7 @@ export class GeminiNanoChatService {
|
|
|
107
107
|
.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`)
|
|
108
108
|
.join('\n');
|
|
109
109
|
prompt +=
|
|
110
|
-
'\n\n
|
|
110
|
+
'\n\nThe following is the prior conversation history. Use it as context for your response:\n' +
|
|
111
111
|
history;
|
|
112
112
|
}
|
|
113
113
|
return api.create({
|
|
@@ -120,5 +120,30 @@ export class GeminiNanoChatService {
|
|
|
120
120
|
],
|
|
121
121
|
});
|
|
122
122
|
}
|
|
123
|
+
buildSystemPrompt(systemPrompt) {
|
|
124
|
+
const promptParts = [];
|
|
125
|
+
if (systemPrompt) {
|
|
126
|
+
promptParts.push(systemPrompt);
|
|
127
|
+
}
|
|
128
|
+
const lengthInstruction = this.getResponseLengthInstruction();
|
|
129
|
+
if (lengthInstruction) {
|
|
130
|
+
promptParts.push(lengthInstruction);
|
|
131
|
+
}
|
|
132
|
+
return promptParts.join('\n\n');
|
|
133
|
+
}
|
|
134
|
+
getResponseLengthInstruction() {
|
|
135
|
+
if (!this._responseLength) {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
const maxTokens = MAX_TOKENS_BY_LENGTH[this._responseLength];
|
|
139
|
+
if (!maxTokens) {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
// Chrome LanguageModel API does not expose a max output length parameter,
|
|
143
|
+
// so we inject a soft output-length instruction into the prompt instead.
|
|
144
|
+
// We express the instruction in English so it is language-neutral across
|
|
145
|
+
// any value of expectedOutputLanguages.
|
|
146
|
+
return `Please keep your response concise, within approximately ${maxTokens} tokens.`;
|
|
147
|
+
}
|
|
123
148
|
}
|
|
124
149
|
//# sourceMappingURL=GeminiNanoChatService.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeminiNanoChatService.js","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"GeminiNanoChatService.js","sourceRoot":"","sources":["../../../../../src/services/providers/geminiNano/GeminiNanoChatService.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;AAiBjC;;;GAGG;AACH,SAAS,mBAAmB;IAC1B,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,eAAe,IAAI,UAAU,EAAE,CAAC;QACvE,OAAQ,UAAkB,CAAC,aAAiC,CAAC;IAC/D,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IAOhC,YAAY,UAAwC,EAAE;QAN7C,aAAQ,GAAW,aAAa,CAAC;QAOxC,IAAI,CAAC,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,IAAI,CAAC,IAAI,CAAC,CAAC;QACvE,IAAI,CAAC,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,IAAI,CAAC,IAAI,CAAC,CAAC;QACzE,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAChD,CAAC;IAED,QAAQ;QACN,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED,cAAc;QACZ,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IAED;;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BAA4B;QAClC,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YAC1B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,SAAS,GAAG,oBAAoB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC7D,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,0EAA0E;QAC1E,yEAAyE;QACzE,yEAAyE;QACzE,wCAAwC;QACxC,OAAO,2DAA2D,SAAS,UAAU,CAAC;IACxF,CAAC;CACF"}
|
|
@@ -2426,7 +2426,6 @@ If it's in another language, summarize in that language.
|
|
|
2426
2426
|
this.expectedInputLanguages = options.expectedInputLanguages ?? ["ja"];
|
|
2427
2427
|
this.expectedOutputLanguages = options.expectedOutputLanguages ?? ["ja"];
|
|
2428
2428
|
this._responseLength = options.responseLength;
|
|
2429
|
-
void this._responseLength;
|
|
2430
2429
|
}
|
|
2431
2430
|
getModel() {
|
|
2432
2431
|
return MODEL_GEMINI_NANO;
|
|
@@ -2502,11 +2501,11 @@ If it's in another language, summarize in that language.
|
|
|
2502
2501
|
* Context history (excluding the last user message) is embedded in the system prompt.
|
|
2503
2502
|
*/
|
|
2504
2503
|
async createSession(api, systemPrompt, contextHistory) {
|
|
2505
|
-
let prompt = systemPrompt;
|
|
2504
|
+
let prompt = this.buildSystemPrompt(systemPrompt);
|
|
2506
2505
|
const historyMessages = contextHistory.slice(0, -1);
|
|
2507
2506
|
if (historyMessages.length > 0) {
|
|
2508
2507
|
const history = historyMessages.map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`).join("\n");
|
|
2509
|
-
prompt += "\n\
|
|
2508
|
+
prompt += "\n\nThe following is the prior conversation history. Use it as context for your response:\n" + history;
|
|
2510
2509
|
}
|
|
2511
2510
|
return api.create({
|
|
2512
2511
|
systemPrompt: prompt,
|
|
@@ -2518,6 +2517,27 @@ If it's in another language, summarize in that language.
|
|
|
2518
2517
|
]
|
|
2519
2518
|
});
|
|
2520
2519
|
}
|
|
2520
|
+
buildSystemPrompt(systemPrompt) {
|
|
2521
|
+
const promptParts = [];
|
|
2522
|
+
if (systemPrompt) {
|
|
2523
|
+
promptParts.push(systemPrompt);
|
|
2524
|
+
}
|
|
2525
|
+
const lengthInstruction = this.getResponseLengthInstruction();
|
|
2526
|
+
if (lengthInstruction) {
|
|
2527
|
+
promptParts.push(lengthInstruction);
|
|
2528
|
+
}
|
|
2529
|
+
return promptParts.join("\n\n");
|
|
2530
|
+
}
|
|
2531
|
+
getResponseLengthInstruction() {
|
|
2532
|
+
if (!this._responseLength) {
|
|
2533
|
+
return void 0;
|
|
2534
|
+
}
|
|
2535
|
+
const maxTokens = MAX_TOKENS_BY_LENGTH[this._responseLength];
|
|
2536
|
+
if (!maxTokens) {
|
|
2537
|
+
return void 0;
|
|
2538
|
+
}
|
|
2539
|
+
return `Please keep your response concise, within approximately ${maxTokens} tokens.`;
|
|
2540
|
+
}
|
|
2521
2541
|
};
|
|
2522
2542
|
|
|
2523
2543
|
// src/services/providers/geminiNano/GeminiNanoChatServiceProvider.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AITuberOnAirChat=(()=>{var
|
|
1
|
+
"use strict";var AITuberOnAirChat=(()=>{var xt=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var _o=Object.getOwnPropertyNames;var fo=Object.prototype.hasOwnProperty;var vo=(r,e)=>{for(var t in e)xt(r,t,{get:e[t],enumerable:!0})},Mo=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _o(e))!fo.call(r,s)&&s!==t&&xt(r,s,{get:()=>e[s],enumerable:!(o=go(e,s))||o.enumerable});return r};var Oo=r=>Mo(xt({},"__esModule",{value:!0}),r);var Bo={};vo(Bo,{CHAT_RESPONSE_LENGTH:()=>C,CLAUDE_VISION_SUPPORTED_MODELS:()=>Pe,ChatServiceFactory:()=>Se,ChatServiceHttpClient:()=>_,ClaudeChatService:()=>ae,ClaudeChatServiceProvider:()=>le,DEFAULT_MAX_TOKENS:()=>Jt,DEFAULT_SUMMARY_PROMPT_TEMPLATE:()=>To,DEFAULT_VISION_PROMPT:()=>yo,EMOTION_TAG_CLEANUP_REGEX:()=>Qt,EMOTION_TAG_REGEX:()=>no,ENDPOINT_CLAUDE_API:()=>Gt,ENDPOINT_GEMINI_API:()=>kt,ENDPOINT_KIMI_CHAT_COMPLETIONS_API:()=>ie,ENDPOINT_OPENAI_CHAT_COMPLETIONS_API:()=>Z,ENDPOINT_OPENAI_RESPONSES_API:()=>I,ENDPOINT_OPENROUTER_API:()=>xe,ENDPOINT_XAI_CHAT_COMPLETIONS_API:()=>be,ENDPOINT_ZAI_CHAT_COMPLETIONS_API:()=>Ie,EmotionParser:()=>ne,GEMINI_NANO_MAX_CONTEXT_MESSAGES:()=>Yt,GEMINI_VISION_SUPPORTED_MODELS:()=>Le,GPT5_PRESETS:()=>Zt,GPT_5_MODELS:()=>to,GeminiChatService:()=>pe,GeminiChatServiceProvider:()=>ce,GeminiNanoChatService:()=>ue,GeminiNanoChatServiceProvider:()=>he,HttpError:()=>G,KIMI_VISION_SUPPORTED_MODELS:()=>ro,KimiChatService:()=>de,KimiChatServiceProvider:()=>me,MAX_TOKENS_BY_LENGTH:()=>yt,MODEL_ANTHROPIC_CLAUDE_3_5_SONNET:()=>Ft,MODEL_ANTHROPIC_CLAUDE_3_7_SONNET:()=>dt,MODEL_ANTHROPIC_CLAUDE_4_5_HAIKU:()=>mt,MODEL_ANTHROPIC_CLAUDE_OPUS_4:()=>ut,MODEL_ANTHROPIC_CLAUDE_SONNET_4:()=>ht,MODEL_CLAUDE_3_5_HAIKU:()=>qe,MODEL_CLAUDE_3_5_SONNET:()=>ze,MODEL_CLAUDE_3_7_SONNET:()=>Xe,MODEL_CLAUDE_3_HAIKU:()=>b,MODEL_CLAUDE_4_5_HAIKU:()=>Qe,MODEL_CLAUDE_4_5_OPUS:()=>et,MODEL_CLAUDE_4_5_SONNET:()=>Ye,MODEL_CLAUDE_4_6_OPUS:()=>ot,MODEL_CLAUDE_4_6_SONNET:()=>tt,MODEL_CLAUDE_4_OPUS:()=>Ze,MODEL_CLAUDE_4_SONNET:()=>Je,MODEL_GEMINI_2_0_FLASH:()=>je,MODEL_GEMINI_2_0_FLASH_LITE:()=>V,MODEL_GEMINI_2_5_FLASH:()=>Be,MODEL_GEMINI_2_5_FLASH_LITE:()=>Ke,MODEL_GEMINI_2_5_FLASH_LITE_PREVIEW_06_17:()=>$e,MODEL_GEMINI_2_5_PRO:()=>We,MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW:()=>Fe,MODEL_GEMINI_3_1_PRO_PREVIEW:()=>Ge,MODEL_GEMINI_3_FLASH_PREVIEW:()=>He,MODEL_GEMINI_3_PRO_PREVIEW:()=>Ue,MODEL_GEMINI_NANO:()=>X,MODEL_GEMMA_4_26B_A4B_IT:()=>ke,MODEL_GEMMA_4_31B_IT:()=>Ve,MODEL_GLM_4_6:()=>zt,MODEL_GLM_4_6V:()=>Mt,MODEL_GLM_4_6V_FLASH:()=>z,MODEL_GLM_4_6V_FLASHX:()=>Ot,MODEL_GLM_4_7:()=>te,MODEL_GLM_4_7_FLASH:()=>qt,MODEL_GLM_4_7_FLASHX:()=>jt,MODEL_GLM_5:()=>Kt,MODEL_GLM_5_TURBO:()=>$t,MODEL_GOOGLE_GEMINI_2_5_FLASH:()=>_t,MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:()=>ft,MODEL_GOOGLE_GEMINI_2_5_PRO:()=>gt,MODEL_GPT_4O:()=>we,MODEL_GPT_4O_MINI:()=>$,MODEL_GPT_4_1:()=>Ae,MODEL_GPT_4_1_MINI:()=>De,MODEL_GPT_4_1_NANO:()=>Ne,MODEL_GPT_5:()=>Q,MODEL_GPT_5_1:()=>W,MODEL_GPT_5_4:()=>N,MODEL_GPT_5_4_MINI:()=>B,MODEL_GPT_5_4_NANO:()=>K,MODEL_GPT_5_4_PRO:()=>w,MODEL_GPT_5_MINI:()=>Y,MODEL_GPT_5_NANO:()=>H,MODEL_GPT_OSS_20B_FREE:()=>k,MODEL_GROK_4_1_FAST_NON_REASONING:()=>A,MODEL_GROK_4_1_FAST_REASONING:()=>St,MODEL_GROK_4_20_NON_REASONING:()=>Ct,MODEL_GROK_4_20_REASONING:()=>Et,MODEL_KIMI_K2_5:()=>D,MODEL_MOONSHOTAI_KIMI_K2_5:()=>st,MODEL_O1:()=>Rt,MODEL_O1_MINI:()=>bt,MODEL_O3_MINI:()=>It,MODEL_OPENAI_GPT_4O:()=>lt,MODEL_OPENAI_GPT_4_1_MINI:()=>pt,MODEL_OPENAI_GPT_4_1_NANO:()=>ct,MODEL_OPENAI_GPT_5_1_CHAT:()=>it,MODEL_OPENAI_GPT_5_1_CODEX:()=>rt,MODEL_OPENAI_GPT_5_MINI:()=>nt,MODEL_OPENAI_GPT_5_NANO:()=>at,MODEL_ZAI_GLM_4_5_AIR:()=>Ht,MODEL_ZAI_GLM_4_5_AIR_FREE:()=>vt,MODEL_ZAI_GLM_4_7_FLASH:()=>Ut,OPENROUTER_CREDITS_THRESHOLD:()=>So,OPENROUTER_FREE_DAILY_LIMIT_HIGH_CREDITS:()=>Co,OPENROUTER_FREE_DAILY_LIMIT_LOW_CREDITS:()=>Eo,OPENROUTER_FREE_MODELS:()=>Wt,OPENROUTER_FREE_RATE_LIMIT_PER_MINUTE:()=>Bt,OPENROUTER_VISION_SUPPORTED_MODELS:()=>oo,OpenAIChatService:()=>F,OpenAIChatServiceProvider:()=>_e,OpenAICompatibleChatServiceProvider:()=>ge,OpenRouterChatService:()=>fe,OpenRouterChatServiceProvider:()=>ve,StreamTextAccumulator:()=>v,VISION_SUPPORTED_MODELS:()=>Te,XAIChatService:()=>Me,XAIChatServiceProvider:()=>Oe,XAI_VISION_SUPPORTED_MODELS:()=>io,ZAIChatService:()=>Ee,ZAIChatServiceProvider:()=>Ce,ZAI_VISION_SUPPORTED_MODELS:()=>so,allowsReasoningLow:()=>Vt,allowsReasoningMinimal:()=>wt,allowsReasoningNone:()=>Nt,allowsReasoningXHigh:()=>Dt,buildOpenAICompatibleTools:()=>P,getDefaultReasoningEffortForGPT5Model:()=>R,getMaxTokensForResponseLength:()=>O,installGASFetch:()=>mo,isGPT5Model:()=>j,isKimiVisionModel:()=>re,isOpenRouterFreeModel:()=>q,isOpenRouterVisionModel:()=>ee,isResponsesOnlyGPT5Model:()=>At,isXaiVisionModel:()=>se,isZaiToolStreamModel:()=>Xt,isZaiVisionModel:()=>oe,parseOpenAICompatibleOneShot:()=>L,parseOpenAICompatibleTextStream:()=>y,parseOpenAICompatibleToolStream:()=>T,processChatWithOptionalTools:()=>f,refreshOpenRouterFreeModels:()=>Fo,resolveVisionModel:()=>E,runOnceText:()=>Io,screenplayToText:()=>xo,textToScreenplay:()=>ao,textsToScreenplay:()=>Po});var Z="https://api.openai.com/v1/chat/completions",I="https://api.openai.com/v1/responses",H="gpt-5-nano",Y="gpt-5-mini",Q="gpt-5",W="gpt-5.1",N="gpt-5.4",B="gpt-5.4-mini",K="gpt-5.4-nano",w="gpt-5.4-pro",Ae="gpt-4.1",De="gpt-4.1-mini",Ne="gpt-4.1-nano",$="gpt-4o-mini",we="gpt-4o",It="o3-mini",bt="o1-mini",Rt="o1",Te=[H,Y,Q,W,N,B,K,w,Ae,De,Ne,$,we,"o1"],to=[H,Y,Q,W,N,B,K,w];function j(r){return to.includes(r)}function At(r){return r===w}function Dt(r){return r===N||r===B||r===K||r===w}function Nt(r){return r===W||r===N||r===B||r===K}function wt(r){return r===H||r===Y||r===Q}function Vt(r){return r!==w}function R(r){return r===W||r===N?"none":"medium"}var kt="https://generativelanguage.googleapis.com",Ve="gemma-4-31b-it",ke="gemma-4-26b-a4b-it",Ge="gemini-3.1-pro-preview",Fe="gemini-3.1-flash-lite-preview",Ue="gemini-3-pro-preview",He="gemini-3-flash-preview",We="gemini-2.5-pro",Be="gemini-2.5-flash",Ke="gemini-2.5-flash-lite",$e="gemini-2.5-flash-lite-preview-06-17",je="gemini-2.0-flash",V="gemini-2.0-flash-lite",Le=[Ve,ke,Ge,Fe,Ue,He,We,Be,Ke,$e,je,V];var Gt="https://api.anthropic.com/v1/messages",b="claude-3-haiku-20240307",qe="claude-3-5-haiku-20241022",ze="claude-3-5-sonnet-20241022",Xe="claude-3-7-sonnet-20250219",Je="claude-4-sonnet-20250514",Ze="claude-4-opus-20250514",Ye="claude-sonnet-4-5-20250929",Qe="claude-haiku-4-5-20251001",et="claude-opus-4-5-20251101",tt="claude-sonnet-4-6",ot="claude-opus-4-6",Pe=[b,qe,ze,Xe,Je,Ze,Ye,Qe,et,tt,ot];var xe="https://openrouter.ai/api/v1/chat/completions",k="openai/gpt-oss-20b:free",st="moonshotai/kimi-k2.5",it="openai/gpt-5.1-chat",rt="openai/gpt-5.1-codex",nt="openai/gpt-5-mini",at="openai/gpt-5-nano",lt="openai/gpt-4o",pt="openai/gpt-4.1-mini",ct="openai/gpt-4.1-nano",ut="anthropic/claude-opus-4",ht="anthropic/claude-sonnet-4",dt="anthropic/claude-3.7-sonnet",Ft="anthropic/claude-3.5-sonnet",mt="anthropic/claude-haiku-4.5",gt="google/gemini-2.5-pro",_t="google/gemini-2.5-flash",ft="google/gemini-2.5-flash-lite-preview-09-2025",Ut="z-ai/glm-4.7-flash",Ht="z-ai/glm-4.5-air",vt="z-ai/glm-4.5-air:free",Wt=[k,vt],oo=[it,rt,nt,at,lt,pt,ct,ut,ht,dt,mt,gt,_t,ft,st],Bt=20,Eo=50,Co=1e3,So=10;function q(r){return r.trim().endsWith(":free")}function ee(r){return oo.some(e=>r.includes(e))}var Ie="https://api.z.ai/api/paas/v4/chat/completions",Kt="glm-5",$t="glm-5-turbo",te="glm-4.7",jt="glm-4.7-FlashX",qt="glm-4.7-Flash",zt="glm-4.6",Mt="glm-4.6V",Ot="glm-4.6V-FlashX",z="glm-4.6V-Flash",so=[Mt,Ot,z];function oe(r){return so.includes(r)}function Xt(r){return r.toLowerCase().startsWith("glm-4.6")}var be="https://api.x.ai/v1/chat/completions",Et="grok-4.20-0309-reasoning",Ct="grok-4.20-0309-non-reasoning",St="grok-4-1-fast-reasoning",A="grok-4-1-fast-non-reasoning",io=[Et,Ct,St,A];function se(r){return io.includes(r)}var ie="https://api.moonshot.ai/v1/chat/completions",D="kimi-k2.5",ro=[D];function re(r){return ro.includes(r)}var C={VERY_SHORT:"veryShort",SHORT:"short",MEDIUM:"medium",LONG:"long",VERY_LONG:"veryLong",DEEP:"deep"},yt={[C.VERY_SHORT]:40,[C.SHORT]:100,[C.MEDIUM]:200,[C.LONG]:300,[C.VERY_LONG]:1e3,[C.DEEP]:5e3},Jt=5e3,Zt={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(r){return r?yt[r]??Jt:Jt}var yo="You are a friendly AI avatar. Comment on the situation based on the broadcast screen.",To=`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)
|
|
@@ -7,13 +7,15 @@ Analyze the following conversation and produce a summary in the **same language*
|
|
|
7
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
|
-
`;var X="gemini-nano",
|
|
11
|
-
`);s=l.pop()||"";for(let u of l){let m=u.trim();if(!m||m.startsWith(":")||!m.startsWith("data:"))continue;let c=m.slice(5).trim();if(c==="[DONE]"){i=!0;break}e(c)}}};async function y(r,e,t={}){let o="";return await po(r,s=>{let i=lo(s,t.onJsonError);if(!i)return;let n=i.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function T(r,e,t={}){let o=[],s=new Map,i,n,a=t.appendTextBlock??v.append;await po(r,m=>{let c=lo(m,t.onJsonError);if(!c)return;let d=c.choices?.[0];typeof d?.finish_reason=="string"&&(i=d.finish_reason),c.usage&&(n=c.usage);let p=d?.delta;p?.content&&(e(p.content),a(o,p.content)),p?.tool_calls&&p.tool_calls.forEach(h=>{let M=s.get(h.index)??{id:h.id,name:h.function?.name,args:""};M.args+=h.function?.arguments||"",s.set(h.index,M)})});let l=Array.from(s.entries()).sort((m,c)=>m[0]-c[0]).map(([m,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...l],stop_reason:l.length?"tool_use":"end",truncated:i==="length",finish_reason:i,usage:n}}function L(r){let e=r?.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",truncated:e?.finish_reason==="length",finish_reason:e?.finish_reason,usage:r?.usage}}var P=(r,e="chat-completions")=>r.length===0?[]:e==="responses"?r.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function f(r){if(!r.hasTools){let t=await r.runWithoutTools();await r.onCompleteResponse(t);return}let e=await r.runWithTools();if(r.onToolBlocks&&r.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=v.getFullText(e.blocks);await r.onCompleteResponse(t);return}throw new Error(r.toolErrorMessage)}var E=r=>{let e=r.model??r.defaultModel,t=r.visionModel??(r.supportsVisionForModel(e)?e:r.defaultVisionModel);if(r.validate==="explicit"&&r.visionModel&&!r.supportsVisionForModel(r.visionModel))throw new Error(`Model ${r.visionModel} does not support vision capabilities.`);if(r.validate==="resolved"&&!r.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var bo="https://openrouter.ai/api/v1/models",Ro=2,Ao=12e3,Do=1,No=10;function
|
|
12
|
-
`))!==-1;){let c=a.slice(0,m).trim();if(a=a.slice(m+1),!c.startsWith("data:"))continue;let d=c.slice(5).trim();if(d==="[DONE]")break;let p=JSON.parse(d);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),i.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"?i.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"&&i.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 h=n.get(p.index);h&&(h.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&n.has(p.index)){let{id:h,name:M,args:S,server_name:g}=n.get(p.index);g?i.push({type:"mcp_tool_use",id:h,name:M,server_name:g,input:JSON.parse(S||"{}")}):i.push({type:"tool_use",id:h,name:M,input:JSON.parse(S||"{}")}),n.delete(p.index)}}}return{blocks:i,stop_reason:i.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(s=>s.type==="text").map(s=>s.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=()=>{},s){let i=await this.callClaude(e,this.model,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callClaude(e,this.visionModel,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.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 le=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 ae(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[b,qe,ze,Xe,Je,Ze,Ye,Qe,et,tt,ot]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Pe.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Tt=class{static async fetchToolSchemas(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let s=await(await _.post(`${e.url}/tools`,{},t)).json();return Array.isArray(s.tools)?s.tools.map(i=>({name:`mcp_${e.name}_${i.name}`,description:i.description||`Tool from ${e.name} MCP server`,parameters:i.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 s=await this.fetchToolSchemas(o);t.push(...s)}catch(s){console.error(`Failed to fetch schemas from ${o.name}:`,s)}return t}};var pe=class{constructor(e,t=V,o=V,s=[],i=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!Le.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=s,this.mcpServers=i}safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}normalizeToolResult(e){return e===null?{content:null}:typeof e=="object"?e:{content:e}}isGemma4Model(e){return/^gemma-4-/.test(e)}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}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,s])=>[t[o]??o,this.adaptKeysForApi(s)])):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,s)=>setTimeout(()=>s(new Error("MCP schema fetch timeout")),5e3)),t=Tt.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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.model,!0),{blocks:i}=await this.parseStream(s,t,this.model);return v.getFullText(i)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processChat:",s),s}}async processVisionChat(e,t,o){try{await f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.visionModel,!0),{blocks:i}=await this.parseStream(s,t,this.visionModel);return v.getFullText(i)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:s=>{s.filter(i=>i.type==="text").forEach(i=>t(i.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}convertMessagesToGeminiFormat(e){let t=[],o=null,s=[],i=()=>{o&&s.length&&(t.push({role:o,parts:[...s]}),s=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){i();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"){i();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&&i(),o=a,s.push({text:n.content})}return i(),t}async callGemini(e,t,o=!1,s){let a={contents:e.some(g=>Array.isArray(g.content)&&g.content.some(x=>x?.type==="image_url"||x?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:s!==void 0?s:O(this.responseLength)}};this.isGemma4Model(t)&&(a.generationConfig.thinkingConfig={includeThoughts:!1,thinkingLevel:"minimal"});let l=[];if(this.tools.length>0&&l.push(...this.tools.map(g=>({name:g.name,description:g.description,parameters:g.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l.push(...this.mcpToolSchemas.map(g=>({name:g.name,description:g.description,parameters:g.parameters})))}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}l.length>0&&(a.tools=[{functionDeclarations:l}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let u=async(g,x)=>{let U=o?"streamGenerateContent":"generateContent",ye=o?"?alt=sse":"",Lt=`${Vt}/${g}/models/${t}:${U}${ye}${ye?"&":"?"}key=${this.apiKey}`;return _.post(Lt,x)},m=/flash[-_]lite/.test(t),c=this.isGemma4Model(t),d=/gemini-2\.5/.test(t),p=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),h=m||c||d||p,M=h?"v1beta":"v1",S=async()=>{try{let g=M==="v1"?a:this.adaptKeysForApi(a);return await u(M,g)}catch(g){let x=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!h&&x)return await u("v1beta",this.adaptKeysForApi(a));throw g}};try{return await S()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,s=[];for(let i of e){let n=this.mapRoleToGemini(i.role);if(i.tool_calls){for(let a of i.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(i.role==="tool"){let a=i.name??this.callIdMap.get(i.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(i.content))}}]});continue}if(n!==o&&s.length>0&&(t.push({role:o,parts:[...s]}),s=[]),o=n,typeof i.content=="string")s.push({text:i.content});else if(Array.isArray(i.content)){for(let a of i.content)if(a.type==="text")s.push({text:a.text});else if(a.type==="image_url")try{let u=await(await _.get(a.image_url.url)).blob(),m=await this.blobToBase64(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(l){throw console.error("Error processing image:",l),new Error(`Failed to process image: ${l.message}`)}}}return o&&s.length>0&&t.push({role:o,parts:[...s]}),t}blobToBase64(e){return new Promise((t,o)=>{let s=new FileReader;s.onloadend=()=>t(s.result),s.onerror=o,s.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,o){let s=e.body.getReader(),i=new TextDecoder,n=[],a=[],l="",u=c=>{if(!c||c==="[DONE]")return;let d;try{d=JSON.parse(c)}catch{return}for(let p of d.candidates??[])for(let h of p.content?.parts??[])this.shouldExposeTextPart(h,o)&&(t(h.text),v.addTextBlock(n,h.text)),h.functionCall&&a.push({type:"tool_use",id:this.genUUID(),name:h.functionCall.name,input:h.functionCall.args??{}}),h.functionResponse&&a.push({type:"tool_result",tool_use_id:h.functionResponse.name,content:JSON.stringify(h.functionResponse.response)})};for(;;){let{done:c,value:d}=await s.read();if(c)break;l+=i.decode(d,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
13
|
-
`))!==-1;){let h=l.slice(0,p);if(l=l.slice(p+1),h.endsWith("\r")&&(h=h.slice(0,-1)),!h.trim()){u("");continue}h.startsWith("data:")&&(h=h.slice(5).trim()),h&&u(h)}}return l&&u(l),{blocks:[...n,...a],stop_reason:a.some(c=>c.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],s=[];for(let n of e.candidates??[])for(let a of n.content?.parts??[])this.shouldExposeTextPart(a,t)&&o.push({type:"text",text:a.text}),a.functionCall&&s.push({type:"tool_use",id:this.genUUID(),name:a.functionCall.name,input:a.functionCall.args??{}}),a.functionResponse&&s.push({type:"tool_result",tool_use_id:a.functionResponse.name,content:JSON.stringify(a.functionResponse.response)});return{blocks:[...o,...s],stop_reason:s.some(n=>n.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callGemini(e,this.model,t,s);return t?this.parseStream(i,o,this.model):this.parseOneShot(await i.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callGemini(e,this.visionModel,t,s);return t?this.parseStream(i,o,this.visionModel):this.parseOneShot(await i.json(),this.visionModel)}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 ce=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 pe(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Ve,ke,Ge,Fe,Ue,He,We,Be,Ke,$e,je,V]}getDefaultModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Le.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Uo(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var ue=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this._responseLength=e.responseLength
|
|
14
|
-
`),n=e.filter(u=>u.role!=="system").slice(-20),a=[...n].reverse().find(u=>u.role==="user");if(!a)throw new Error("No user message found in the provided messages.");let l=await this.createSession(t,i,n);try{return await l.prompt(a.content)}finally{try{l.destroy()}catch{}}}async createSession(e,t,o){let s=t,i=o.slice(0,-1);if(i.length>0){let n=i.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
10
|
+
`;var X="gemini-nano",Yt=20;var G=class extends Error{constructor(t,o,s){super(`HTTP ${t}: ${o}`);this.status=t;this.statusText=o;this.body=s;this.name="HttpError"}},Re=class Re{static setFetch(e){this.fetchImpl=e}static async post(e,t,o={},s={}){let{timeout:i=3e4,retries:n=0,retryDelay:a=1e3}=s,u={...{"Content-Type":"application/json"},...o},m=null;for(let c=0;c<=n;c++)try{let d=typeof AbortController<"u",p=d?new AbortController:void 0,h=d?setTimeout(()=>p.abort(),i):void 0,M=await Re.fetchImpl(e,{method:"POST",headers:u,body:typeof t=="string"?t:JSON.stringify(t),...p?{signal:p.signal}:{}});if(h&&clearTimeout(h),!M.ok){let S=await M.text();throw new G(M.status,M.statusText,S)}return M}catch(d){if(m=d,d instanceof G&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError")throw new Error(`Request timeout after ${i}ms`);c<n&&await new Promise(p=>setTimeout(p,a*(c+1)))}throw m||new Error("Request failed")}static async handleErrorResponse(e){let t=await e.text();throw new G(e.status,e.statusText,t)}static async get(e,t={},o={}){let{timeout:s=3e4,retries:i=0,retryDelay:n=1e3}=o,a=null;for(let l=0;l<=i;l++)try{let u=typeof AbortController<"u",m=u?new AbortController:void 0,c=u?setTimeout(()=>m.abort(),s):void 0,d=await Re.fetchImpl(e,{method:"GET",headers:t,...m?{signal:m.signal}:{}});if(c&&clearTimeout(c),!d.ok){let p=await d.text();throw new G(d.status,d.statusText,p)}return d}catch(u){if(a=u,u instanceof G&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError")throw new Error(`Request timeout after ${s}ms`);l<i&&await new Promise(m=>setTimeout(m,n*(l+1)))}throw a||new Error("Request failed")}};Re.fetchImpl=(e,t)=>fetch(e,t);var _=Re;var v=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"],no=/\[([a-z]+)\]/i,Qt=/\[[a-z]+\]\s*/gi,ne=class{static extractEmotion(e){let t=e.match(no);if(t){let o=t[1].toLowerCase(),s=e.replace(Qt,"").trim();return{emotion:o,cleanText:s}}return{cleanText:e}}static isValidEmotion(e){return Lo.includes(e)}static cleanEmotionTags(e){return e.replace(Qt,"").trim()}static addEmotionTag(e,t){return`[${e}] ${t}`}};function ao(r){let{emotion:e,cleanText:t}=ne.extractEmotion(r);return e?{emotion:e,text:t}:{text:t}}function Po(r){return r.map(e=>ao(e))}function xo(r){return r.emotion?ne.addEmotionTag(r.emotion,r.text):r.text}async function Io(r,e){let{blocks:t}=await r.chatOnce(e,!1,()=>{});return v.getFullText(t)}var lo=(r,e)=>{try{return JSON.parse(r)}catch(t){if(e){e(r,t);return}throw t}},po=async(r,e)=>{let t=r.body?.getReader();if(!t)throw new Error("Response body is null.");let o=new TextDecoder,s="",i=!1;for(;!i;){let{done:n,value:a}=await t.read();if(n)break;s+=o.decode(a,{stream:!0});let l=s.split(`
|
|
11
|
+
`);s=l.pop()||"";for(let u of l){let m=u.trim();if(!m||m.startsWith(":")||!m.startsWith("data:"))continue;let c=m.slice(5).trim();if(c==="[DONE]"){i=!0;break}e(c)}}};async function y(r,e,t={}){let o="";return await po(r,s=>{let i=lo(s,t.onJsonError);if(!i)return;let n=i.choices?.[0]?.delta?.content||"";n&&(e(n),o+=n)}),o}async function T(r,e,t={}){let o=[],s=new Map,i,n,a=t.appendTextBlock??v.append;await po(r,m=>{let c=lo(m,t.onJsonError);if(!c)return;let d=c.choices?.[0];typeof d?.finish_reason=="string"&&(i=d.finish_reason),c.usage&&(n=c.usage);let p=d?.delta;p?.content&&(e(p.content),a(o,p.content)),p?.tool_calls&&p.tool_calls.forEach(h=>{let M=s.get(h.index)??{id:h.id,name:h.function?.name,args:""};M.args+=h.function?.arguments||"",s.set(h.index,M)})});let l=Array.from(s.entries()).sort((m,c)=>m[0]-c[0]).map(([m,c])=>({type:"tool_use",id:c.id,name:c.name,input:JSON.parse(c.args||"{}")}));return{blocks:[...o,...l],stop_reason:l.length?"tool_use":"end",truncated:i==="length",finish_reason:i,usage:n}}function L(r){let e=r?.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",truncated:e?.finish_reason==="length",finish_reason:e?.finish_reason,usage:r?.usage}}var P=(r,e="chat-completions")=>r.length===0?[]:e==="responses"?r.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters})):r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}));async function f(r){if(!r.hasTools){let t=await r.runWithoutTools();await r.onCompleteResponse(t);return}let e=await r.runWithTools();if(r.onToolBlocks&&r.onToolBlocks(e.blocks),e.stop_reason==="end"){let t=v.getFullText(e.blocks);await r.onCompleteResponse(t);return}throw new Error(r.toolErrorMessage)}var E=r=>{let e=r.model??r.defaultModel,t=r.visionModel??(r.supportsVisionForModel(e)?e:r.defaultVisionModel);if(r.validate==="explicit"&&r.visionModel&&!r.supportsVisionForModel(r.visionModel))throw new Error(`Model ${r.visionModel} does not support vision capabilities.`);if(r.validate==="resolved"&&!r.supportsVisionForModel(t))throw new Error(`Model ${t} does not support vision capabilities.`);return t};var bo="https://openrouter.ai/api/v1/models",Ro=2,Ao=12e3,Do=1,No=10;function eo(r){return r instanceof Error?r.message:String(r)}function Tt(r,e){return typeof r!="number"||!Number.isFinite(r)?e:Math.max(1,Math.floor(r))}function wo(r){let e=new Set,t=[];for(let o of r){let s=o.trim();!s||e.has(s)||(e.add(s),t.push(s))}return t}async function co(r,e,t){if(!(typeof AbortController<"u"))return fetch(r,e);let s=new AbortController,i=setTimeout(()=>s.abort(),t);try{return await fetch(r,{...e,signal:s.signal})}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Timeout after ${t}ms`):n}finally{clearTimeout(i)}}async function uo(r){let e=`HTTP ${r.status} ${r.statusText}`.trim(),t="";try{t=await r.text()}catch{return e}let o=t.replace(/\s+/g," ").trim().slice(0,200);return o?`${e}: ${o}`:e}function Vo(r){if(!r||typeof r!="object")throw new Error("Invalid models response shape");let e=r,t=Array.isArray(e.data)?e.data:Array.isArray(e.models)?e.models:[];if(t.length===0)return[];let o=t.map(s=>s.id).filter(s=>typeof s=="string");return wo(o)}async function ko({modelId:r,apiKey:e,endpoint:t,timeoutMs:o,appName:s,appUrl:i}){let n={Authorization:`Bearer ${e}`,"Content-Type":"application/json"};s&&(n["X-Title"]=s),i&&(n["HTTP-Referer"]=i);try{let a=await co(t,{method:"POST",headers:n,body:JSON.stringify({model:r,messages:[{role:"user",content:"Reply only with OK."}],stream:!1})},o);if(!a.ok)return{id:r,ok:!1,reason:await uo(a)};try{await a.json()}catch(l){return{id:r,ok:!1,reason:`JSON parse failed: ${eo(l)}`}}return{id:r,ok:!0}}catch(a){return{id:r,ok:!1,reason:eo(a)}}}async function Go(r,e,t){if(r.length===0)return[];let o=new Array(r.length),s=0,i=Math.min(e,r.length);return await Promise.all(Array.from({length:i},async()=>{for(;s<r.length;){let n=s;s+=1,o[n]=await t(r[n])}})),o}async function Fo(r){let e=r.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");let t=r.modelsEndpoint||bo,o=r.endpoint||xe,s=Tt(r.timeoutMs,Ao),i=Tt(r.concurrency,Ro),n=Tt(r.maxCandidates,Do),a=Tt(r.maxWorking,No),l=await co(t,{method:"GET"},s);if(!l.ok)throw new Error(await uo(l));let u;try{u=await l.json()}catch(h){throw new Error(`JSON parse failed: ${eo(h)}`)}let m=Vo(u).filter(h=>q(h)).slice(0,n),c=await Go(m,i,h=>ko({modelId:h,apiKey:e,endpoint:o,timeoutMs:s,appName:r.appName,appUrl:r.appUrl})),d=c.filter(h=>h.ok).map(h=>h.id).slice(0,a),p=c.filter(h=>!h.ok).map(h=>({id:h.id,reason:h.reason||"Unknown error"}));return{working:d,failed:p,fetchedAt:Date.now()}}var ae=class{constructor(e,t=b,o=b,s=[],i=[],n){this.provider="claude";if(this.apiKey=e,this.model=t||b,this.visionModel=o||b,this.tools=s,this.mcpServers=i,this.responseLength=n,!Pe.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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callClaude(e,this.model,!0);return this.parsePureStream(s,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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callClaude(e,this.visionModel,!0);return this.parsePureStream(s,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(s=>{if(s.type==="image_url"){if(s.image_url.url.startsWith("data:")){let i=s.image_url.url.match(/^data:([^;]+);base64,(.+)$/);return i?{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}:null}return{type:"image",source:{type:"url",url:s.image_url.url,media_type:this.getMimeTypeFromUrl(s.image_url.url)}}}return s}).filter(s=>s);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,s){let i=e.find(c=>c.role==="system")?.content??"",n=e.filter(c=>c.role!=="system"),a=n.some(c=>Array.isArray(c.content)&&c.content.some(d=>d.type==="image_url"||d.type==="image")),l={model:t,system:i,messages:a?this.convertVisionMessagesToClaudeFormat(n):this.convertMessagesToClaudeFormat(n),stream:o,max_tokens:s!==void 0?s:O(this.responseLength)};this.tools.length&&(l.tools=this.tools.map(c=>({name:c.name,description:c.description,input_schema:c.parameters})),l.tool_choice={type:"auto"}),this.mcpServers.length>0&&(l.mcp_servers=this.mcpServers);let u={"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&&(u["anthropic-beta"]="mcp-client-2025-04-04"),await _.post(Gt,l,u)}async parseStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a="";for(;;){let{done:l,value:u}=await o.read();if(l)break;a+=s.decode(u,{stream:!0});let m;for(;(m=a.indexOf(`
|
|
12
|
+
`))!==-1;){let c=a.slice(0,m).trim();if(a=a.slice(m+1),!c.startsWith("data:"))continue;let d=c.slice(5).trim();if(d==="[DONE]")break;let p=JSON.parse(d);if(p.type==="content_block_delta"&&p.delta?.text&&(t(p.delta.text),i.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"?i.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"&&i.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 h=n.get(p.index);h&&(h.args+=p.delta.partial_json||"")}if(p.type==="content_block_stop"&&n.has(p.index)){let{id:h,name:M,args:S,server_name:g}=n.get(p.index);g?i.push({type:"mcp_tool_use",id:h,name:M,server_name:g,input:JSON.parse(S||"{}")}):i.push({type:"tool_use",id:h,name:M,input:JSON.parse(S||"{}")}),n.delete(p.index)}}}return{blocks:i,stop_reason:i.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(s=>s.type==="text").map(s=>s.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=()=>{},s){let i=await this.callClaude(e,this.model,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.json());return this.convertToStandardCompletion(n)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callClaude(e,this.visionModel,t,s),n=t?await this.parseStream(i,o):this.parseOneShot(await i.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 le=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 ae(e.apiKey,e.model||this.getDefaultModel(),t,e.tools??[],e.mcpServers??[],e.responseLength)}getProviderName(){return"claude"}getSupportedModels(){return[b,qe,ze,Xe,Je,Ze,Ye,Qe,et,tt,ot]}getDefaultModel(){return b}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Pe.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Lt=class{static async fetchToolSchemas(e){try{let t={"Content-Type":"application/json"};e.authorization_token&&(t.Authorization=`Bearer ${e.authorization_token}`);let s=await(await _.post(`${e.url}/tools`,{},t)).json();return Array.isArray(s.tools)?s.tools.map(i=>({name:`mcp_${e.name}_${i.name}`,description:i.description||`Tool from ${e.name} MCP server`,parameters:i.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 s=await this.fetchToolSchemas(o);t.push(...s)}catch(s){console.error(`Failed to fetch schemas from ${o.name}:`,s)}return t}};var pe=class{constructor(e,t=V,o=V,s=[],i=[],n){this.provider="gemini";this.mcpToolSchemas=[];this.mcpSchemasInitialized=!1;this.callIdMap=new Map;if(this.apiKey=e,this.model=t,this.responseLength=n,!Le.includes(o))throw new Error(`Model ${o} does not support vision capabilities.`);this.visionModel=o,this.tools=s,this.mcpServers=i}safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}normalizeToolResult(e){return e===null?{content:null}:typeof e=="object"?e:{content:e}}isGemma4Model(e){return/^gemma-4-/.test(e)}shouldExposeTextPart(e,t){return!(!e.text||this.isGemma4Model(t)&&e.thought===!0)}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,s])=>[t[o]??o,this.adaptKeysForApi(s)])):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,s)=>setTimeout(()=>s(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 f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.model,!0),{blocks:i}=await this.parseStream(s,t,this.model);return v.getFullText(i)},runWithTools:()=>this.chatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use chatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processChat:",s),s}}async processVisionChat(e,t,o){try{await f({hasTools:this.tools.length>0||this.mcpServers.length>0,runWithoutTools:async()=>{let s=await this.callGemini(e,this.visionModel,!0),{blocks:i}=await this.parseStream(s,t,this.visionModel);return v.getFullText(i)},runWithTools:()=>this.visionChatOnce(e),onToolBlocks:s=>{s.filter(i=>i.type==="text").forEach(i=>t(i.text))},onCompleteResponse:o,toolErrorMessage:"Received functionCall. Use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}convertMessagesToGeminiFormat(e){let t=[],o=null,s=[],i=()=>{o&&s.length&&(t.push({role:o,parts:[...s]}),s=[])};for(let n of e){let a=this.mapRoleToGemini(n.role);if(n.tool_calls){i();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"){i();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&&i(),o=a,s.push({text:n.content})}return i(),t}async callGemini(e,t,o=!1,s){let a={contents:e.some(g=>Array.isArray(g.content)&&g.content.some(x=>x?.type==="image_url"||x?.inlineData))?await this.convertVisionMessagesToGeminiFormat(e):this.convertMessagesToGeminiFormat(e),generationConfig:{maxOutputTokens:s!==void 0?s:O(this.responseLength)}};this.isGemma4Model(t)&&(a.generationConfig.thinkingConfig={includeThoughts:!1,thinkingLevel:"minimal"});let l=[];if(this.tools.length>0&&l.push(...this.tools.map(g=>({name:g.name,description:g.description,parameters:g.parameters}))),this.mcpServers.length>0)try{await this.initializeMCPSchemas(),l.push(...this.mcpToolSchemas.map(g=>({name:g.name,description:g.description,parameters:g.parameters})))}catch(g){console.warn("MCP initialization failed, skipping MCP tools:",g)}l.length>0&&(a.tools=[{functionDeclarations:l}],a.toolConfig={functionCallingConfig:{mode:"AUTO"}});let u=async(g,x)=>{let U=o?"streamGenerateContent":"generateContent",ye=o?"?alt=sse":"",Pt=`${kt}/${g}/models/${t}:${U}${ye}${ye?"&":"?"}key=${this.apiKey}`;return _.post(Pt,x)},m=/flash[-_]lite/.test(t),c=this.isGemma4Model(t),d=/gemini-2\.5/.test(t),p=/^gemini-3(?:\.[0-9]+)?-.*preview/.test(t),h=m||c||d||p,M=h?"v1beta":"v1",S=async()=>{try{let g=M==="v1"?a:this.adaptKeysForApi(a);return await u(M,g)}catch(g){let x=/Unknown name|Cannot find field|404/.test(g?.message||"")||g?.status===404;if(!h&&x)return await u("v1beta",this.adaptKeysForApi(a));throw g}};try{return await S()}catch(g){throw g.body&&(console.error("Gemini API Error Details:",g.body),console.error("Request Body:",JSON.stringify(a,null,2))),g}}async convertVisionMessagesToGeminiFormat(e){let t=[],o=null,s=[];for(let i of e){let n=this.mapRoleToGemini(i.role);if(i.tool_calls){for(let a of i.tool_calls)t.push({role:"model",parts:[{functionCall:{name:a.function.name,args:JSON.parse(a.function.arguments||"{}")}}]});continue}if(i.role==="tool"){let a=i.name??this.callIdMap.get(i.tool_call_id)??"result";t.push({role:"user",parts:[{functionResponse:{name:a,response:this.normalizeToolResult(this.safeJsonParse(i.content))}}]});continue}if(n!==o&&s.length>0&&(t.push({role:o,parts:[...s]}),s=[]),o=n,typeof i.content=="string")s.push({text:i.content});else if(Array.isArray(i.content)){for(let a of i.content)if(a.type==="text")s.push({text:a.text});else if(a.type==="image_url")try{let u=await(await _.get(a.image_url.url)).blob(),m=await this.blobToBase64(u);s.push({inlineData:{mimeType:u.type||"image/jpeg",data:m.split(",")[1]}})}catch(l){throw console.error("Error processing image:",l),new Error(`Failed to process image: ${l.message}`)}}}return o&&s.length>0&&t.push({role:o,parts:[...s]}),t}blobToBase64(e){return new Promise((t,o)=>{let s=new FileReader;s.onloadend=()=>t(s.result),s.onerror=o,s.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,o){let s=e.body.getReader(),i=new TextDecoder,n=[],a=[],l="",u=c=>{if(!c||c==="[DONE]")return;let d;try{d=JSON.parse(c)}catch{return}for(let p of d.candidates??[])for(let h of p.content?.parts??[])this.shouldExposeTextPart(h,o)&&(t(h.text),v.addTextBlock(n,h.text)),h.functionCall&&a.push({type:"tool_use",id:this.genUUID(),name:h.functionCall.name,input:h.functionCall.args??{}}),h.functionResponse&&a.push({type:"tool_result",tool_use_id:h.functionResponse.name,content:JSON.stringify(h.functionResponse.response)})};for(;;){let{done:c,value:d}=await s.read();if(c)break;l+=i.decode(d,{stream:!0});let p;for(;(p=l.indexOf(`
|
|
13
|
+
`))!==-1;){let h=l.slice(0,p);if(l=l.slice(p+1),h.endsWith("\r")&&(h=h.slice(0,-1)),!h.trim()){u("");continue}h.startsWith("data:")&&(h=h.slice(5).trim()),h&&u(h)}}return l&&u(l),{blocks:[...n,...a],stop_reason:a.some(c=>c.type==="tool_use")?"tool_use":"end"}}parseOneShot(e,t){let o=[],s=[];for(let n of e.candidates??[])for(let a of n.content?.parts??[])this.shouldExposeTextPart(a,t)&&o.push({type:"text",text:a.text}),a.functionCall&&s.push({type:"tool_use",id:this.genUUID(),name:a.functionCall.name,input:a.functionCall.args??{}}),a.functionResponse&&s.push({type:"tool_result",tool_use_id:a.functionResponse.name,content:JSON.stringify(a.functionResponse.response)});return{blocks:[...o,...s],stop_reason:s.some(n=>n.type==="tool_use")?"tool_use":"end"}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callGemini(e,this.model,t,s);return t?this.parseStream(i,o,this.model):this.parseOneShot(await i.json(),this.model)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callGemini(e,this.visionModel,t,s);return t?this.parseStream(i,o,this.visionModel):this.parseOneShot(await i.json(),this.visionModel)}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 ce=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 pe(e.apiKey,e.model||this.getDefaultModel(),t,e.tools||[],e.mcpServers||[],e.responseLength)}getProviderName(){return"gemini"}getSupportedModels(){return[Ve,ke,Ge,Fe,Ue,He,We,Be,Ke,$e,je,V]}getDefaultModel(){return V}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Le.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};function Uo(){if(typeof globalThis<"u"&&"LanguageModel"in globalThis)return globalThis.LanguageModel}var ue=class{constructor(e={}){this.provider="gemini-nano";this.expectedInputLanguages=e.expectedInputLanguages??["ja"],this.expectedOutputLanguages=e.expectedOutputLanguages??["ja"],this._responseLength=e.responseLength}getModel(){return X}getVisionModel(){return X}async processChat(e,t,o){let s=await this.generateResponse(e);t(s),await o(s)}async processVisionChat(e,t,o){throw new Error("Gemini Nano does not support vision capabilities.")}async chatOnce(e,t=!1,o=()=>{},s){let i=await this.generateResponse(e);return o(i),{blocks:[{type:"text",text:i}],stop_reason:"end"}}async visionChatOnce(e,t=!1,o=()=>{},s){throw new Error("Gemini Nano does not support vision capabilities.")}async generateResponse(e){let t=Uo();if(!t)throw new Error("Gemini Nano is not available in this environment. Chrome 138+ with Prompt API enabled is required.");let o=await t.availability();if(o!=="available"&&o!=="downloadable")throw new Error(`Gemini Nano Prompt API is not ready in this environment. LanguageModel.availability() returned "${o}". Expected "available" or "downloadable".`);let i=e.filter(u=>u.role==="system").map(u=>u.content).join(`
|
|
14
|
+
`),n=e.filter(u=>u.role!=="system").slice(-20),a=[...n].reverse().find(u=>u.role==="user");if(!a)throw new Error("No user message found in the provided messages.");let l=await this.createSession(t,i,n);try{return await l.prompt(a.content)}finally{try{l.destroy()}catch{}}}async createSession(e,t,o){let s=this.buildSystemPrompt(t),i=o.slice(0,-1);if(i.length>0){let n=i.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
15
15
|
`);s+=`
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
`+n}return e.create({systemPrompt:s,expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]})}
|
|
19
|
-
`);m=g.pop()||"";for(let x=0;x<g.length;x++){let U=g[x].trim();if(U.startsWith("event:"))M=U.slice(6).trim();else if(U.startsWith("data:"))S=U.slice(5).trim();else if(U===""&&M&&S){try{let ye=JSON.parse(S),Lt=this.handleResponsesSSEEvent(M,ye,t,i,n,J=>{J.responseStatus!==void 0&&(a=J.responseStatus),J.incompleteDetails!==void 0&&(l=J.incompleteDetails),J.usage!==void 0&&(u=J.usage)})}catch{console.warn("Failed to parse SSE data:",S)}M="",S=""}}}let c=Array.from(n.values()).map(p=>({type:"tool_use",id:p.id,name:p.name,input:p.input||{}}));return{blocks:[...i,...c],stop_reason:c.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:l,usage:u}}handleResponsesSSEEvent(e,t,o,s,i,n){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(o(a.text),v.append(s,a.text))}):t.item?.type==="function_call"&&i.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),v.append(s,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let a=typeof t.delta=="string"?t.delta:t.delta?.text??"";a&&(o(a),v.append(s,a))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return n(this.extractResponsesMetadata(t,"completed")),"completed";case"response.incomplete":return n(this.extractResponsesMetadata(t,"incomplete")),"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}extractResponsesMetadata(e,t){let o=e?.response??e;return{responseStatus:o?.status??t,incompleteDetails:o?.incomplete_details??null,usage:o?.usage}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(s=>{s.type==="output_text"&&s.text&&t.push({type:"text",text:s.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",truncated:e?.status==="incomplete",response_status:e?.status,incomplete_details:e?.incomplete_details??null,usage:e?.usage}}};var ge=class{createChatService(e){return this.validateRequiredOptions(e),new F(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 this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}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 _e=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:u=>this.supportsVisionForModel(u),validate:"resolved"}),s=t.tools,i=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;i.length>0||Rt(n)?a=!0:j(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?I:Z);return new F(t.apiKey,n,o,s,l,i,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[H,Y,Q,W,N,B,K,w,Ae,De,Ne,$,we,xt,It,"o1"]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Te.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!j(t))return e;let o={...e};if(e.gpt5Preset){let s=Jt[e.gpt5Preset];o.reasoning_effort=s.reasoning_effort,o.verbosity=s.verbosity}else e.reasoning_effort||(o.reasoning_effort=R(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Dt(e)?R(e):t==="minimal"&&!Nt(e)?R(e):t==="low"&&!wt(e)?R(e):t==="xhigh"&&!At(e)?R(e):t}};var fe=class{constructor(e,t=k,o=k,s,i=xe,n,a,l,u,m,c){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=u,this.includeReasoning=m,this.reasoningMaxTokens=c,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!q(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Wt){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(s=>setTimeout(s,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.model,!0);return this.handleStream(s,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(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(s,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){if(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async callOpenRouter(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await _.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i={model:t,messages:e,stream:o};if((s!==void 0?s: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(i.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;i.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(i.reasoning.exclude=!0),this.reasoningMaxTokens&&(i.reasoning.max_tokens=this.reasoningMaxTokens)}else i.reasoning={exclude:!0};return this.tools.length>0&&(i.tools=P(this.tools,"chat-completions"),i.tool_choice="auto"),i}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var ve=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,s=e.appName,i=e.appUrl;return new fe(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,s,i,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[k,vt,it,rt,nt,at,lt,pt,ct,ut,ht,dt,Gt,mt,gt,_t,ft,Ft,Ut,st]}getDefaultModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return ee(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Ht}isModelFree(e){return q(e)}};var Me=class{constructor(e,t=A,o=A,s,i=be,n){this.provider="xai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(e,this.model,!0);return this.handleStream(s,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(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let i=await this.callXAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callXAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto"),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Oe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),s=e.tools;return new Me(e.apiKey,t,o,s,e.endpoint||be,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[Et,Ct,St,A]}getDefaultModel(){return A}getDefaultVisionModel(){return A}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Ee=class{constructor(e,t=te,o=z,s,i=Ie,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.model,!0);return this.handleStream(s,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(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let i=await this.callZAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callZAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat),this.thinking&&(i.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto",o&&zt(t)&&(i.tool_stream=!0)),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Ce=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"}),s=e.tools,i=e.thinking??{type:"disabled"};return new Ee(e.apiKey,t,o,s,e.endpoint||Ie,e.responseLength,e.responseFormat,i)}getProviderName(){return"zai"}getSupportedModels(){return[Bt,Kt,te,$t,jt,qt,Mt,Ot,z]}getDefaultModel(){return te}getDefaultVisionModel(){return z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return oe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var ho=[new _e,new ge,new ce,new he,new le,new ve,new Ce,new Oe,new me];var Se=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():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Se.providers=new Map;ho.forEach(r=>Se.registerProvider(r));function mo(){_.setFetch(async(r,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,s={};if(Array.isArray(o))for(let[c,d]of o)s[c]=String(d);else if(o&&typeof o=="object")for(let[c,d]of Object.entries(o))s[c]=String(d);let i={method:t,headers:s,muteHttpExceptions:!0},n=e.body;typeof n=="string"?i.payload=n:n!=null&&(s["Content-Type"]||(s["Content-Type"]="application/json"),i.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(r,i),l=a.getResponseCode(),u=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>u,json:async()=>u?JSON.parse(u):null}})}return Oo(Bo);})();
|
|
17
|
+
The following is the prior conversation history. Use it as context for your response:
|
|
18
|
+
`+n}return e.create({systemPrompt:s,expectedInputs:[{type:"text",languages:this.expectedInputLanguages}],expectedOutputs:[{type:"text",languages:this.expectedOutputLanguages}]})}buildSystemPrompt(e){let t=[];e&&t.push(e);let o=this.getResponseLengthInstruction();return o&&t.push(o),t.join(`
|
|
19
|
+
|
|
20
|
+
`)}getResponseLengthInstruction(){if(!this._responseLength)return;let e=yt[this._responseLength];if(e)return`Please keep your response concise, within approximately ${e} tokens.`}};var he=class{createChatService(e){return new ue({expectedInputLanguages:e.expectedInputLanguages,expectedOutputLanguages:e.expectedOutputLanguages,responseLength:e.responseLength})}getProviderName(){return"gemini-nano"}getSupportedModels(){return[X]}getDefaultModel(){return X}supportsVision(){return!1}getVisionSupportLevel(){return"unsupported"}};var de=class{constructor(e,t=D,o=D,s,i=ie,n,a,l){this.provider="kimi";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callKimi(e,this.model,!0);return this.handleStream(s,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(!re(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callKimi(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let i=await this.callKimi(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!re(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callKimi(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callKimi(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat);let a=this.tools.length>0?{type:"disabled"}:this.thinking;a&&(this.isSelfHostedEndpoint()?a.type==="disabled"&&(i.chat_template_kwargs={thinking:!1}):i.thinking=a);let l=this.buildToolsDefinition();return l.length>0&&(i.tools=l,i.tool_choice="auto"),i}isSelfHostedEndpoint(){return this.normalizeEndpoint(this.endpoint)!==this.normalizeEndpoint(ie)}normalizeEndpoint(e){return e.replace(/\/+$/,"")}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var me=class{createChatService(e){let t=this.resolveEndpoint(e),o=e.model||this.getDefaultModel(),s=E({model:o,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:l=>this.supportsVisionForModel(l),validate:"explicit"}),i=e.tools,n=e.thinking??{type:"enabled"},a=i&&i.length>0?{type:"disabled"}:n;return new de(e.apiKey,o,s,i,t,e.responseLength,e.responseFormat,a)}getProviderName(){return"kimi"}getSupportedModels(){return[D]}getDefaultModel(){return D}getDefaultVisionModel(){return D}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return re(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}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 ie}normalizeEndpoint(e){return e.replace(/\/+$/,"")}};var Ho={[C.VERY_SHORT]:800,[C.SHORT]:1200,[C.MEDIUM]:2e3,[C.LONG]:3e3,[C.VERY_LONG]:8e3,[C.DEEP]:25e3},Wo={none:1200,minimal:1600,low:2500,medium:4e3,high:8e3,xhigh:12e3},F=class{constructor(e,t=$,o=$,s,i=Z,n=[],a,l,u,m=!1,c="openai",d=!0){if(this.provider=c,this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.mcpServers=n,this.responseLength=a,this.verbosity=l,this.reasoning_effort=u,this.enableReasoningSummary=m,d&&!Te.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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.model,!0),i=this.endpoint===I;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenAI(e,this.visionModel,!0),i=this.endpoint===I;try{if(i){let n=await this.parseResponsesStream(s,t);return v.getFullText(n.blocks)}return this.handleStream(s,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(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){let i=await this.callOpenAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){let i=await this.callOpenAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return this.endpoint===I?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,s){let i=this.buildRequestBody(e,t,o,s),n={};return(this.provider!=="openai-compatible"||this.apiKey.trim()!=="")&&(n.Authorization=`Bearer ${this.apiKey}`),await _.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i=this.endpoint===I;this.validateMCPCompatibility();let n={model:t,stream:o},a=this.resolveTokenLimit(t,s);i?a!==void 0&&(n.max_output_tokens=a):a!==void 0&&(this.provider==="openai-compatible"?n.max_tokens=a:n.max_completion_tokens=a),i?n.input=this.cleanMessagesForResponsesAPI(e):n.messages=e,j(t)&&(i?(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,i||(n.tool_choice="auto")),n}resolveTokenLimit(e,t){if(t!==void 0)return t;let o=this.provider==="openai-compatible"?this.responseLength!==void 0?O(this.responseLength):void 0:O(this.responseLength);if(this.provider!=="openai"||!j(e)||this.responseLength===void 0)return o;let s=this.reasoning_effort??R(e);return Math.max(o??0,Ho[this.responseLength],Wo[s])}validateMCPCompatibility(){if(this.mcpServers.length>0&&this.endpoint===Z)throw new Error(`MCP servers are not supported with Chat Completions API. Current endpoint: ${this.endpoint}. Please use OpenAI Responses API endpoint: ${I}. MCP tools are only available in the Responses API endpoint.`)}cleanMessagesForResponsesAPI(e){return e.map(t=>{let s={role:t.role==="tool"?"user":t.role};return typeof t.content=="string"?s.content=t.content:Array.isArray(t.content)?s.content=t.content.map(i=>i.type==="text"?{type:"input_text",text:i.text}:i.type==="image_url"?{type:"input_image",image_url:i.image_url.url}:i):s.content=t.content,s})}buildToolsDefinition(){let e=this.endpoint===I,t=[];return this.tools.length>0&&t.push(...P(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 y(e,t)}async parseStream(e,t){return T(e,t,{appendTextBlock:v.addTextBlock})}parseOneShot(e){return L(e)}async parseResponsesStream(e,t){let o=e.body.getReader(),s=new TextDecoder,i=[],n=new Map,a,l,u,m="";for(;;){let{done:p,value:h}=await o.read();if(p)break;m+=s.decode(h,{stream:!0});let M="",S="",g=m.split(`
|
|
21
|
+
`);m=g.pop()||"";for(let x=0;x<g.length;x++){let U=g[x].trim();if(U.startsWith("event:"))M=U.slice(6).trim();else if(U.startsWith("data:"))S=U.slice(5).trim();else if(U===""&&M&&S){try{let ye=JSON.parse(S),Pt=this.handleResponsesSSEEvent(M,ye,t,i,n,J=>{J.responseStatus!==void 0&&(a=J.responseStatus),J.incompleteDetails!==void 0&&(l=J.incompleteDetails),J.usage!==void 0&&(u=J.usage)})}catch{console.warn("Failed to parse SSE data:",S)}M="",S=""}}}let c=Array.from(n.values()).map(p=>({type:"tool_use",id:p.id,name:p.name,input:p.input||{}}));return{blocks:[...i,...c],stop_reason:c.length?"tool_use":"end",truncated:a==="incomplete",response_status:a,incomplete_details:l,usage:u}}handleResponsesSSEEvent(e,t,o,s,i,n){switch(e){case"response.output_item.added":t.item?.type==="message"&&Array.isArray(t.item.content)?t.item.content.forEach(a=>{a.type==="output_text"&&a.text&&(o(a.text),v.append(s,a.text))}):t.item?.type==="function_call"&&i.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),v.append(s,t.part.text));break;case"response.output_text.delta":case"response.content_part.delta":{let a=typeof t.delta=="string"?t.delta:t.delta?.text??"";a&&(o(a),v.append(s,a))}break;case"response.output_text.done":case"response.content_part.done":break;case"response.completed":return n(this.extractResponsesMetadata(t,"completed")),"completed";case"response.incomplete":return n(this.extractResponsesMetadata(t,"incomplete")),"completed";case"response.reasoning.started":case"response.reasoning.delta":case"response.reasoning.done":break;default:break}}extractResponsesMetadata(e,t){let o=e?.response??e;return{responseStatus:o?.status??t,incompleteDetails:o?.incomplete_details??null,usage:o?.usage}}parseResponsesOneShot(e){let t=[];return e.output&&Array.isArray(e.output)&&e.output.forEach(o=>{o.type==="message"&&o.content&&o.content.forEach(s=>{s.type==="output_text"&&s.text&&t.push({type:"text",text:s.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",truncated:e?.status==="incomplete",response_status:e?.status,incomplete_details:e?.incomplete_details??null,usage:e?.usage}}};var ge=class{createChatService(e){return this.validateRequiredOptions(e),new F(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 this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"unknown"}supportsVisionForModel(e){return!0}getVisionSupportLevelForModel(e){return"unknown"}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 _e=class{createChatService(e){let t=this.optimizeGPT5Options(e),o=E({model:t.model,visionModel:t.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultModel(),supportsVisionForModel:u=>this.supportsVisionForModel(u),validate:"resolved"}),s=t.tools,i=t.mcpServers??[],n=t.model||this.getDefaultModel(),a=!1;i.length>0||At(n)?a=!0:j(n)&&(a=(t.gpt5EndpointPreference||"chat")==="responses");let l=t.endpoint||(a?I:Z);return new F(t.apiKey,n,o,s,l,i,t.responseLength,t.verbosity,t.reasoning_effort,t.enableReasoningSummary,this.getProviderName())}getProviderName(){return"openai"}getSupportedModels(){return[H,Y,Q,W,N,B,K,w,Ae,De,Ne,$,we,It,bt,"o1"]}getDefaultModel(){return H}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return Te.includes(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}optimizeGPT5Options(e){let t=e.model||this.getDefaultModel();if(!j(t))return e;let o={...e};if(e.gpt5Preset){let s=Zt[e.gpt5Preset];o.reasoning_effort=s.reasoning_effort,o.verbosity=s.verbosity}else e.reasoning_effort||(o.reasoning_effort=R(t));return o.reasoning_effort=this.normalizeReasoningEffort(t,o.reasoning_effort),o}normalizeReasoningEffort(e,t){if(t)return t==="none"&&!Nt(e)?R(e):t==="minimal"&&!wt(e)?R(e):t==="low"&&!Vt(e)?R(e):t==="xhigh"&&!Dt(e)?R(e):t}};var fe=class{constructor(e,t=k,o=k,s,i=xe,n,a,l,u,m,c){this.provider="openrouter";this.lastRequestTime=0;this.requestCount=0;this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.appName=a,this.appUrl=l,this.reasoning_effort=u,this.includeReasoning=m,this.reasoningMaxTokens=c,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async applyRateLimiting(){if(!q(this.model))return;let e=Date.now(),t=e-this.lastRequestTime;if(t>6e4&&(this.requestCount=0),this.requestCount>=Bt){let o=6e4-t;o>0&&(console.log(`Rate limit reached for free tier. Waiting ${o}ms...`),await new Promise(s=>setTimeout(s,o)),this.requestCount=0)}this.lastRequestTime=e,this.requestCount++}async processChat(e,t,o){await this.applyRateLimiting(),await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.model,!0);return this.handleStream(s,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(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();try{await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callOpenRouter(e,this.visionModel,!0);return this.handleStream(s,t)},runWithTools:()=>this.visionChatOnce(e,!0,t),onCompleteResponse:o,toolErrorMessage:"processVisionChat received tool_calls. ChatProcessor must use visionChatOnce() loop when tools are enabled."})}catch(s){throw console.error("Error in processVisionChat:",s),s}}async chatOnce(e,t=!0,o=()=>{},s){await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.model,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async visionChatOnce(e,t=!1,o=()=>{},s){if(!ee(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await this.applyRateLimiting();let i=await this.callOpenRouter(e,this.visionModel,t,s);return t?this.parseStream(i,o):this.parseOneShot(await i.json())}async callOpenRouter(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s),n={Authorization:`Bearer ${this.apiKey}`};return this.appUrl&&(n["HTTP-Referer"]=this.appUrl),this.appName&&(n["X-Title"]=this.appName),await _.post(this.endpoint,i,n)}buildRequestBody(e,t,o,s){let i={model:t,messages:e,stream:o};if((s!==void 0?s: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(i.reasoning={},this.reasoning_effort&&this.reasoning_effort!=="none"){let a=this.reasoning_effort==="minimal"?"low":this.reasoning_effort;i.reasoning.effort=a}(this.reasoning_effort==="none"||this.includeReasoning!==!0)&&(i.reasoning.exclude=!0),this.reasoningMaxTokens&&(i.reasoning.max_tokens=this.reasoningMaxTokens)}else i.reasoning={exclude:!0};return this.tools.length>0&&(i.tools=P(this.tools,"chat-completions"),i.tool_choice="auto"),i}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var ve=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,s=e.appName,i=e.appUrl;return new fe(e.apiKey,e.model||this.getDefaultModel(),t,o,e.endpoint,e.responseLength,s,i,e.reasoning_effort,e.includeReasoning,e.reasoningMaxTokens)}getProviderName(){return"openrouter"}getSupportedModels(){return[k,vt,it,rt,nt,at,lt,pt,ct,ut,ht,dt,Ft,mt,gt,_t,ft,Ut,Ht,st]}getDefaultModel(){return k}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return this.getSupportedModels().some(e=>this.supportsVisionForModel(e))?"supported":"unsupported"}supportsVisionForModel(e){return ee(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}getFreeModels(){return Wt}isModelFree(e){return q(e)}};var Me=class{constructor(e,t=A,o=A,s,i=be,n){this.provider="xai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,this.responseLength=n,this.visionModel=o}getModel(){return this.model}getVisionModel(){return this.visionModel}async processChat(e,t,o){await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(e,this.model,!0);return this.handleStream(s,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(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callXAI(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let i=await this.callXAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!se(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callXAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callXAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto"),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Oe=class{createChatService(e){let t=e.model||this.getDefaultModel(),o=E({model:t,visionModel:e.visionModel,defaultModel:this.getDefaultModel(),defaultVisionModel:this.getDefaultVisionModel(),supportsVisionForModel:i=>this.supportsVisionForModel(i),validate:"explicit"}),s=e.tools;return new Me(e.apiKey,t,o,s,e.endpoint||be,e.responseLength)}getProviderName(){return"xai"}getSupportedModels(){return[Et,Ct,St,A]}getDefaultModel(){return A}getDefaultVisionModel(){return A}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return se(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var Ee=class{constructor(e,t=te,o=z,s,i=Ie,n,a,l){this.provider="zai";this.apiKey=e,this.model=t,this.tools=s||[],this.endpoint=i,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 f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.model,!0);return this.handleStream(s,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(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);await f({hasTools:this.tools.length>0,runWithoutTools:async()=>{let s=await this.callZAI(e,this.visionModel,!0);return this.handleStream(s,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=()=>{},s){let i=await this.callZAI(e,this.model,t,s);return this.parseResponse(i,t,o)}async visionChatOnce(e,t=!1,o=()=>{},s){if(!oe(this.visionModel))throw new Error(`Model ${this.visionModel} does not support vision capabilities.`);let i=await this.callZAI(e,this.visionModel,t,s);return this.parseResponse(i,t,o)}async parseResponse(e,t,o){return t?this.parseStream(e,o):this.parseOneShot(await e.json())}async callZAI(e,t,o=!1,s){let i=this.buildRequestBody(e,t,o,s);return await _.post(this.endpoint,i,{Authorization:`Bearer ${this.apiKey}`})}buildRequestBody(e,t,o,s){let i={model:t,stream:o,messages:e},n=s!==void 0?s:O(this.responseLength);n!==void 0&&(i.max_tokens=n),this.responseFormat&&(i.response_format=this.responseFormat),this.thinking&&(i.thinking=this.thinking);let a=this.buildToolsDefinition();return a.length>0&&(i.tools=a,i.tool_choice="auto",o&&Xt(t)&&(i.tool_stream=!0)),i}buildToolsDefinition(){return P(this.tools,"chat-completions")}async handleStream(e,t){return y(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}async parseStream(e,t){return T(e,t,{onJsonError:o=>console.debug("Failed to parse SSE data:",o)})}parseOneShot(e){return L(e)}};var Ce=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"}),s=e.tools,i=e.thinking??{type:"disabled"};return new Ee(e.apiKey,t,o,s,e.endpoint||Ie,e.responseLength,e.responseFormat,i)}getProviderName(){return"zai"}getSupportedModels(){return[Kt,$t,te,jt,qt,zt,Mt,Ot,z]}getDefaultModel(){return te}getDefaultVisionModel(){return z}supportsVision(){return this.getVisionSupportLevel()!=="unsupported"}getVisionSupportLevel(){return"supported"}supportsVisionForModel(e){return oe(e)}getVisionSupportLevelForModel(e){return this.supportsVisionForModel(e)?"supported":"unsupported"}};var ho=[new _e,new ge,new ce,new he,new le,new ve,new Ce,new Oe,new me];var Se=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():[]}static getVisionSupportLevel(e){let t=this.providers.get(e);return t?t.getVisionSupportLevel():"unsupported"}static getVisionSupportLevelForModel(e,t){let o=this.providers.get(e);return o?o.getVisionSupportLevelForModel?o.getVisionSupportLevelForModel(t):o.supportsVisionForModel?o.supportsVisionForModel(t)?"supported":"unsupported":o.getVisionSupportLevel():"unsupported"}};Se.providers=new Map;ho.forEach(r=>Se.registerProvider(r));function mo(){_.setFetch(async(r,e={})=>{let t=(e.method||"GET").toString().toUpperCase(),o=e.headers,s={};if(Array.isArray(o))for(let[c,d]of o)s[c]=String(d);else if(o&&typeof o=="object")for(let[c,d]of Object.entries(o))s[c]=String(d);let i={method:t,headers:s,muteHttpExceptions:!0},n=e.body;typeof n=="string"?i.payload=n:n!=null&&(s["Content-Type"]||(s["Content-Type"]="application/json"),i.payload=JSON.stringify(n));let a=UrlFetchApp.fetch(r,i),l=a.getResponseCode(),u=a.getContentText();return{ok:l>=200&&l<300,status:l,statusText:String(l),text:async()=>u,json:async()=>u?JSON.parse(u):null}})}return Oo(Bo);})();
|