opc-agent 1.1.1 → 1.1.3

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.
Files changed (142) hide show
  1. package/CHANGELOG.md +51 -51
  2. package/CONTRIBUTING.md +75 -75
  3. package/README.md +222 -126
  4. package/README.zh-CN.md +129 -80
  5. package/dist/channels/web.js +256 -256
  6. package/dist/deploy/hermes.js +22 -22
  7. package/dist/deploy/openclaw.js +31 -31
  8. package/dist/providers/index.d.ts +1 -1
  9. package/dist/providers/index.js +148 -13
  10. package/dist/schema/oad.d.ts +3 -3
  11. package/dist/templates/code-reviewer.js +5 -5
  12. package/dist/templates/customer-service.js +2 -2
  13. package/dist/templates/data-analyst.js +5 -5
  14. package/dist/templates/knowledge-base.js +2 -2
  15. package/dist/templates/sales-assistant.js +4 -4
  16. package/dist/templates/teacher.js +6 -6
  17. package/docs/.vitepress/config.ts +103 -103
  18. package/docs/api/cli.md +48 -48
  19. package/docs/api/oad-schema.md +64 -64
  20. package/docs/api/sdk.md +80 -80
  21. package/docs/guide/concepts.md +51 -51
  22. package/docs/guide/configuration.md +79 -79
  23. package/docs/guide/deployment.md +42 -42
  24. package/docs/guide/getting-started.md +44 -44
  25. package/docs/guide/templates.md +28 -28
  26. package/docs/guide/testing.md +84 -84
  27. package/docs/index.md +27 -27
  28. package/docs/zh/api/cli.md +54 -54
  29. package/docs/zh/api/oad-schema.md +87 -87
  30. package/docs/zh/api/sdk.md +102 -102
  31. package/docs/zh/guide/concepts.md +104 -104
  32. package/docs/zh/guide/configuration.md +135 -135
  33. package/docs/zh/guide/deployment.md +81 -81
  34. package/docs/zh/guide/getting-started.md +82 -82
  35. package/docs/zh/guide/templates.md +84 -84
  36. package/docs/zh/guide/testing.md +88 -88
  37. package/docs/zh/index.md +27 -27
  38. package/examples/customer-service-demo/README.md +90 -90
  39. package/examples/customer-service-demo/oad.yaml +107 -107
  40. package/package.json +1 -1
  41. package/src/analytics/index.ts +66 -66
  42. package/src/channels/discord.ts +192 -192
  43. package/src/channels/email.ts +177 -177
  44. package/src/channels/feishu.ts +236 -236
  45. package/src/channels/index.ts +15 -15
  46. package/src/channels/slack.ts +160 -160
  47. package/src/channels/telegram.ts +90 -90
  48. package/src/channels/voice.ts +106 -106
  49. package/src/channels/web.ts +596 -596
  50. package/src/channels/webhook.ts +199 -199
  51. package/src/channels/websocket.ts +87 -87
  52. package/src/channels/wechat.ts +149 -149
  53. package/src/core/a2a.ts +143 -143
  54. package/src/core/agent.ts +152 -152
  55. package/src/core/analytics-engine.ts +186 -186
  56. package/src/core/auth.ts +57 -57
  57. package/src/core/cache.ts +141 -141
  58. package/src/core/compose.ts +77 -77
  59. package/src/core/config.ts +14 -14
  60. package/src/core/errors.ts +148 -148
  61. package/src/core/hitl.ts +138 -138
  62. package/src/core/knowledge.ts +210 -210
  63. package/src/core/logger.ts +57 -57
  64. package/src/core/orchestrator.ts +215 -215
  65. package/src/core/performance.ts +187 -187
  66. package/src/core/rate-limiter.ts +128 -128
  67. package/src/core/room.ts +109 -109
  68. package/src/core/runtime.ts +152 -152
  69. package/src/core/sandbox.ts +101 -101
  70. package/src/core/security.ts +171 -171
  71. package/src/core/types.ts +68 -68
  72. package/src/core/versioning.ts +106 -106
  73. package/src/core/watch.ts +178 -178
  74. package/src/core/workflow.ts +235 -235
  75. package/src/deploy/hermes.ts +156 -156
  76. package/src/deploy/openclaw.ts +200 -200
  77. package/src/dtv/data.ts +29 -29
  78. package/src/dtv/trust.ts +43 -43
  79. package/src/dtv/value.ts +47 -47
  80. package/src/i18n/index.ts +216 -216
  81. package/src/index.ts +110 -110
  82. package/src/marketplace/index.ts +223 -223
  83. package/src/memory/deepbrain.ts +108 -108
  84. package/src/memory/index.ts +34 -34
  85. package/src/plugins/index.ts +208 -208
  86. package/src/providers/index.ts +322 -183
  87. package/src/schema/oad.ts +155 -155
  88. package/src/skills/base.ts +16 -16
  89. package/src/skills/document.ts +100 -100
  90. package/src/skills/http.ts +35 -35
  91. package/src/skills/index.ts +27 -27
  92. package/src/skills/scheduler.ts +80 -80
  93. package/src/skills/webhook-trigger.ts +59 -59
  94. package/src/templates/code-reviewer.ts +34 -34
  95. package/src/templates/customer-service.ts +80 -80
  96. package/src/templates/data-analyst.ts +70 -70
  97. package/src/templates/executive-assistant.ts +71 -71
  98. package/src/templates/financial-advisor.ts +60 -60
  99. package/src/templates/knowledge-base.ts +31 -31
  100. package/src/templates/legal-assistant.ts +71 -71
  101. package/src/templates/sales-assistant.ts +79 -79
  102. package/src/templates/teacher.ts +79 -79
  103. package/src/testing/index.ts +181 -181
  104. package/src/tools/calculator.ts +73 -73
  105. package/src/tools/datetime.ts +149 -149
  106. package/src/tools/json-transform.ts +187 -187
  107. package/src/tools/mcp.ts +76 -76
  108. package/src/tools/text-analysis.ts +116 -116
  109. package/templates/Dockerfile +15 -15
  110. package/templates/code-reviewer/README.md +27 -27
  111. package/templates/code-reviewer/oad.yaml +41 -41
  112. package/templates/customer-service/README.md +22 -22
  113. package/templates/customer-service/oad.yaml +36 -36
  114. package/templates/docker-compose.yml +21 -21
  115. package/templates/knowledge-base/README.md +28 -28
  116. package/templates/knowledge-base/oad.yaml +38 -38
  117. package/templates/sales-assistant/README.md +26 -26
  118. package/templates/sales-assistant/oad.yaml +43 -43
  119. package/tests/a2a.test.ts +66 -66
  120. package/tests/agent.test.ts +72 -72
  121. package/tests/analytics.test.ts +50 -50
  122. package/tests/channel.test.ts +39 -39
  123. package/tests/e2e.test.ts +134 -134
  124. package/tests/errors.test.ts +83 -83
  125. package/tests/hitl.test.ts +71 -71
  126. package/tests/i18n.test.ts +41 -41
  127. package/tests/mcp.test.ts +54 -54
  128. package/tests/oad.test.ts +68 -68
  129. package/tests/performance.test.ts +115 -115
  130. package/tests/plugin.test.ts +74 -74
  131. package/tests/room.test.ts +106 -106
  132. package/tests/runtime.test.ts +42 -42
  133. package/tests/sandbox.test.ts +46 -46
  134. package/tests/security.test.ts +60 -60
  135. package/tests/templates.test.ts +77 -77
  136. package/tests/v070.test.ts +76 -76
  137. package/tests/versioning.test.ts +75 -75
  138. package/tests/voice.test.ts +61 -61
  139. package/tests/webhook.test.ts +29 -29
  140. package/tests/workflow.test.ts +143 -143
  141. package/tsconfig.json +19 -19
  142. package/vitest.config.ts +9 -9
@@ -1,183 +1,322 @@
1
- import type { Message } from '../core/types';
2
- import * as https from 'https';
3
- import * as http from 'http';
4
-
5
- export interface LLMProvider {
6
- name: string;
7
- chat(messages: Message[], systemPrompt?: string): Promise<string>;
8
- chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string>;
9
- }
10
-
11
- interface OpenAIMessage {
12
- role: 'system' | 'user' | 'assistant';
13
- content: string;
14
- }
15
-
16
- function getApiKey(): string {
17
- return process.env.OPC_LLM_API_KEY || process.env.OPENAI_API_KEY || '';
18
- }
19
-
20
- function getBaseUrl(): string {
21
- return process.env.OPC_LLM_BASE_URL || 'https://api.openai.com/v1';
22
- }
23
-
24
- class OpenAICompatibleProvider implements LLMProvider {
25
- name: string;
26
- private model: string;
27
- private baseUrl: string;
28
- private apiKey: string;
29
-
30
- constructor(name: string, model: string, baseUrl?: string, apiKey?: string) {
31
- this.name = name;
32
- this.model = model;
33
- this.baseUrl = baseUrl || getBaseUrl();
34
- this.apiKey = apiKey || getApiKey();
35
- }
36
-
37
- private formatMessages(messages: Message[], systemPrompt?: string): OpenAIMessage[] {
38
- const formatted: OpenAIMessage[] = [];
39
- if (systemPrompt) {
40
- formatted.push({ role: 'system', content: systemPrompt });
41
- }
42
- for (const m of messages) {
43
- formatted.push({ role: m.role as 'user' | 'assistant', content: m.content });
44
- }
45
- return formatted;
46
- }
47
-
48
- private async request(body: any): Promise<any> {
49
- if (!this.apiKey) {
50
- throw new Error('No API key configured. Set OPC_LLM_API_KEY or OPENAI_API_KEY environment variable.');
51
- }
52
-
53
- const url = new URL(`${this.baseUrl}/chat/completions`);
54
- const isHttps = url.protocol === 'https:';
55
- const lib = isHttps ? https : http;
56
-
57
- const postData = JSON.stringify(body);
58
-
59
- return new Promise((resolve, reject) => {
60
- const req = lib.request(
61
- {
62
- hostname: url.hostname,
63
- port: url.port || (isHttps ? 443 : 80),
64
- path: url.pathname,
65
- method: 'POST',
66
- headers: {
67
- 'Content-Type': 'application/json',
68
- Authorization: `Bearer ${this.apiKey}`,
69
- 'Content-Length': Buffer.byteLength(postData),
70
- },
71
- },
72
- (res) => {
73
- let data = '';
74
- res.on('data', (chunk: Buffer) => (data += chunk.toString()));
75
- res.on('end', () => {
76
- if (res.statusCode && res.statusCode >= 400) {
77
- reject(new Error(`LLM API error ${res.statusCode}: ${data}`));
78
- return;
79
- }
80
- try {
81
- resolve(JSON.parse(data));
82
- } catch {
83
- reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
84
- }
85
- });
86
- },
87
- );
88
- req.on('error', reject);
89
- req.write(postData);
90
- req.end();
91
- });
92
- }
93
-
94
- async chat(messages: Message[], systemPrompt?: string): Promise<string> {
95
- if (!this.apiKey) {
96
- // Stub mode when no API key
97
- const last = messages[messages.length - 1];
98
- return `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
99
- }
100
- const formatted = this.formatMessages(messages, systemPrompt);
101
- const result = await this.request({
102
- model: this.model,
103
- messages: formatted,
104
- temperature: 0.7,
105
- max_tokens: 2048,
106
- });
107
- return result.choices?.[0]?.message?.content ?? '';
108
- }
109
-
110
- async *chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string> {
111
- if (!this.apiKey) {
112
- const last = messages[messages.length - 1];
113
- yield `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
114
- return;
115
- }
116
-
117
- const formatted = this.formatMessages(messages, systemPrompt);
118
- const url = new URL(`${this.baseUrl}/chat/completions`);
119
- const isHttps = url.protocol === 'https:';
120
- const lib = isHttps ? https : http;
121
- const postData = JSON.stringify({
122
- model: this.model,
123
- messages: formatted,
124
- temperature: 0.7,
125
- max_tokens: 2048,
126
- stream: true,
127
- });
128
-
129
- const response = await new Promise<http.IncomingMessage>((resolve, reject) => {
130
- const req = lib.request(
131
- {
132
- hostname: url.hostname,
133
- port: url.port || (isHttps ? 443 : 80),
134
- path: url.pathname,
135
- method: 'POST',
136
- headers: {
137
- 'Content-Type': 'application/json',
138
- Authorization: `Bearer ${this.apiKey}`,
139
- 'Content-Length': Buffer.byteLength(postData),
140
- },
141
- },
142
- resolve,
143
- );
144
- req.on('error', reject);
145
- req.write(postData);
146
- req.end();
147
- });
148
-
149
- if (response.statusCode && response.statusCode >= 400) {
150
- let data = '';
151
- for await (const chunk of response) data += chunk.toString();
152
- throw new Error(`LLM API error ${response.statusCode}: ${data}`);
153
- }
154
-
155
- let buffer = '';
156
- for await (const chunk of response) {
157
- buffer += chunk.toString();
158
- const lines = buffer.split('\n');
159
- buffer = lines.pop() ?? '';
160
-
161
- for (const line of lines) {
162
- const trimmed = line.trim();
163
- if (!trimmed || !trimmed.startsWith('data: ')) continue;
164
- const data = trimmed.slice(6);
165
- if (data === '[DONE]') return;
166
- try {
167
- const parsed = JSON.parse(data);
168
- const content = parsed.choices?.[0]?.delta?.content;
169
- if (content) yield content;
170
- } catch {
171
- // skip malformed lines
172
- }
173
- }
174
- }
175
- }
176
- }
177
-
178
- export function createProvider(name: string = 'openai', model?: string, baseUrl?: string, apiKey?: string): LLMProvider {
179
- const finalModel = model || process.env.OPC_LLM_MODEL || 'gpt-4o-mini';
180
- return new OpenAICompatibleProvider(name, finalModel, baseUrl, apiKey);
181
- }
182
-
183
- export const SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen'] as const;
1
+ import type { Message } from '../core/types';
2
+ import * as https from 'https';
3
+ import * as http from 'http';
4
+
5
+ export interface LLMProvider {
6
+ name: string;
7
+ chat(messages: Message[], systemPrompt?: string): Promise<string>;
8
+ chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string>;
9
+ }
10
+
11
+ interface OpenAIMessage {
12
+ role: 'system' | 'user' | 'assistant';
13
+ content: string;
14
+ }
15
+
16
+ function getApiKey(): string {
17
+ return process.env.OPC_LLM_API_KEY || process.env.OPENAI_API_KEY || '';
18
+ }
19
+
20
+ function getBaseUrl(): string {
21
+ return process.env.OPC_LLM_BASE_URL || 'https://api.openai.com/v1';
22
+ }
23
+
24
+ class OpenAICompatibleProvider implements LLMProvider {
25
+ name: string;
26
+ private model: string;
27
+ private baseUrl: string;
28
+ private apiKey: string;
29
+
30
+ constructor(name: string, model: string, baseUrl?: string, apiKey?: string) {
31
+ this.name = name;
32
+ this.model = model;
33
+ this.baseUrl = baseUrl || getBaseUrl();
34
+ this.apiKey = apiKey || getApiKey();
35
+ }
36
+
37
+ private formatMessages(messages: Message[], systemPrompt?: string): OpenAIMessage[] {
38
+ const formatted: OpenAIMessage[] = [];
39
+ if (systemPrompt) {
40
+ formatted.push({ role: 'system', content: systemPrompt });
41
+ }
42
+ for (const m of messages) {
43
+ formatted.push({ role: m.role as 'user' | 'assistant', content: m.content });
44
+ }
45
+ return formatted;
46
+ }
47
+
48
+ private async request(body: any): Promise<any> {
49
+ if (!this.apiKey) {
50
+ throw new Error('No API key configured. Set OPC_LLM_API_KEY or OPENAI_API_KEY environment variable.');
51
+ }
52
+
53
+ const url = new URL(`${this.baseUrl}/chat/completions`);
54
+ const isGemini = url.hostname.includes('googleapis.com');
55
+ if (isGemini) {
56
+ url.searchParams.set('key', this.apiKey);
57
+ }
58
+ const isHttps = url.protocol === 'https:';
59
+ const lib = isHttps ? https : http;
60
+
61
+ const postData = JSON.stringify(body);
62
+
63
+ const headers: Record<string, string> = {
64
+ 'Content-Type': 'application/json',
65
+ 'Content-Length': String(Buffer.byteLength(postData)),
66
+ };
67
+ if (!isGemini) {
68
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
69
+ }
70
+
71
+ return new Promise((resolve, reject) => {
72
+ const req = lib.request(
73
+ {
74
+ hostname: url.hostname,
75
+ port: url.port || (isHttps ? 443 : 80),
76
+ path: url.pathname + url.search,
77
+ method: 'POST',
78
+ headers,
79
+ },
80
+ (res) => {
81
+ let data = '';
82
+ res.on('data', (chunk: Buffer) => (data += chunk.toString()));
83
+ res.on('end', () => {
84
+ if (res.statusCode && res.statusCode >= 400) {
85
+ reject(new Error(`LLM API error ${res.statusCode}: ${data}`));
86
+ return;
87
+ }
88
+ try {
89
+ resolve(JSON.parse(data));
90
+ } catch {
91
+ reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
92
+ }
93
+ });
94
+ },
95
+ );
96
+ req.on('error', reject);
97
+ req.write(postData);
98
+ req.end();
99
+ });
100
+ }
101
+
102
+ async chat(messages: Message[], systemPrompt?: string): Promise<string> {
103
+ if (!this.apiKey) {
104
+ // Stub mode when no API key
105
+ const last = messages[messages.length - 1];
106
+ return `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
107
+ }
108
+ const formatted = this.formatMessages(messages, systemPrompt);
109
+ const result = await this.request({
110
+ model: this.model,
111
+ messages: formatted,
112
+ temperature: 0.7,
113
+ max_tokens: 2048,
114
+ });
115
+ return result.choices?.[0]?.message?.content ?? '';
116
+ }
117
+
118
+ async *chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string> {
119
+ if (!this.apiKey) {
120
+ const last = messages[messages.length - 1];
121
+ yield `[${this.name}/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
122
+ return;
123
+ }
124
+
125
+ const formatted = this.formatMessages(messages, systemPrompt);
126
+ const url = new URL(`${this.baseUrl}/chat/completions`);
127
+ const isGemini = url.hostname.includes('googleapis.com');
128
+ if (isGemini) {
129
+ url.searchParams.set('key', this.apiKey);
130
+ }
131
+ const isHttps = url.protocol === 'https:';
132
+ const lib = isHttps ? https : http;
133
+ const postData = JSON.stringify({
134
+ model: this.model,
135
+ messages: formatted,
136
+ temperature: 0.7,
137
+ max_tokens: 2048,
138
+ stream: true,
139
+ });
140
+
141
+ const streamHeaders: Record<string, string> = {
142
+ 'Content-Type': 'application/json',
143
+ 'Content-Length': String(Buffer.byteLength(postData)),
144
+ };
145
+ if (!isGemini) {
146
+ streamHeaders['Authorization'] = `Bearer ${this.apiKey}`;
147
+ }
148
+
149
+ const response = await new Promise<http.IncomingMessage>((resolve, reject) => {
150
+ const req = lib.request(
151
+ {
152
+ hostname: url.hostname,
153
+ port: url.port || (isHttps ? 443 : 80),
154
+ path: url.pathname + url.search,
155
+ method: 'POST',
156
+ headers: streamHeaders,
157
+ },
158
+ resolve,
159
+ );
160
+ req.on('error', reject);
161
+ req.write(postData);
162
+ req.end();
163
+ });
164
+
165
+ if (response.statusCode && response.statusCode >= 400) {
166
+ let data = '';
167
+ for await (const chunk of response) data += chunk.toString();
168
+ throw new Error(`LLM API error ${response.statusCode}: ${data}`);
169
+ }
170
+
171
+ let buffer = '';
172
+ for await (const chunk of response) {
173
+ buffer += chunk.toString();
174
+ const lines = buffer.split('\n');
175
+ buffer = lines.pop() ?? '';
176
+
177
+ for (const line of lines) {
178
+ const trimmed = line.trim();
179
+ if (!trimmed || !trimmed.startsWith('data: ')) continue;
180
+ const data = trimmed.slice(6);
181
+ if (data === '[DONE]') return;
182
+ try {
183
+ const parsed = JSON.parse(data);
184
+ const content = parsed.choices?.[0]?.delta?.content;
185
+ if (content) yield content;
186
+ } catch {
187
+ // skip malformed lines
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+
194
+ class GeminiNativeProvider implements LLMProvider {
195
+ name = 'gemini';
196
+ private model: string;
197
+ private apiKey: string;
198
+
199
+ constructor(model: string, apiKey?: string) {
200
+ this.model = model;
201
+ this.apiKey = apiKey || getApiKey();
202
+ }
203
+
204
+ private buildUrl(stream: boolean): string {
205
+ const action = stream ? 'streamGenerateContent?alt=sse&' : 'generateContent?';
206
+ return `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:${action}key=${this.apiKey}`;
207
+ }
208
+
209
+ private formatContents(messages: Message[], systemPrompt?: string): { contents: any[]; systemInstruction?: any } {
210
+ const contents: any[] = [];
211
+ for (const m of messages) {
212
+ contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] });
213
+ }
214
+ const result: any = { contents };
215
+ if (systemPrompt) {
216
+ result.systemInstruction = { parts: [{ text: systemPrompt }] };
217
+ }
218
+ return result;
219
+ }
220
+
221
+ async chat(messages: Message[], systemPrompt?: string): Promise<string> {
222
+ if (!this.apiKey) {
223
+ const last = messages[messages.length - 1];
224
+ return `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
225
+ }
226
+ const body = this.formatContents(messages, systemPrompt);
227
+ const url = this.buildUrl(false);
228
+ const postData = JSON.stringify(body);
229
+
230
+ return new Promise((resolve, reject) => {
231
+ const parsedUrl = new URL(url);
232
+ const req = https.request({
233
+ hostname: parsedUrl.hostname,
234
+ path: parsedUrl.pathname + parsedUrl.search,
235
+ method: 'POST',
236
+ headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
237
+ }, (res) => {
238
+ let data = '';
239
+ res.on('data', (chunk: Buffer) => (data += chunk.toString()));
240
+ res.on('end', () => {
241
+ if (res.statusCode && res.statusCode >= 400) { reject(new Error(`Gemini API error ${res.statusCode}: ${data}`)); return; }
242
+ try {
243
+ const parsed = JSON.parse(data);
244
+ resolve(parsed.candidates?.[0]?.content?.parts?.[0]?.text ?? '');
245
+ } catch { reject(new Error(`Invalid Gemini response: ${data.slice(0, 200)}`)); }
246
+ });
247
+ });
248
+ req.on('error', reject);
249
+ req.write(postData);
250
+ req.end();
251
+ });
252
+ }
253
+
254
+ async *chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string> {
255
+ if (!this.apiKey) {
256
+ const last = messages[messages.length - 1];
257
+ yield `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
258
+ return;
259
+ }
260
+ const body = this.formatContents(messages, systemPrompt);
261
+ const url = this.buildUrl(true);
262
+ const postData = JSON.stringify(body);
263
+ const parsedUrl = new URL(url);
264
+
265
+ const response = await new Promise<http.IncomingMessage>((resolve, reject) => {
266
+ const req = https.request({
267
+ hostname: parsedUrl.hostname,
268
+ path: parsedUrl.pathname + parsedUrl.search,
269
+ method: 'POST',
270
+ headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
271
+ }, resolve);
272
+ req.on('error', reject);
273
+ req.write(postData);
274
+ req.end();
275
+ });
276
+
277
+ if (response.statusCode && response.statusCode >= 400) {
278
+ let data = '';
279
+ for await (const chunk of response) data += chunk.toString();
280
+ throw new Error(`Gemini API error ${response.statusCode}: ${data}`);
281
+ }
282
+
283
+ let buffer = '';
284
+ for await (const chunk of response) {
285
+ buffer += chunk.toString();
286
+ const lines = buffer.split('\n');
287
+ buffer = lines.pop() ?? '';
288
+ for (const line of lines) {
289
+ const trimmed = line.trim();
290
+ if (!trimmed.startsWith('data: ')) continue;
291
+ const data = trimmed.slice(6);
292
+ if (data === '[DONE]') return;
293
+ try {
294
+ const parsed = JSON.parse(data);
295
+ const text = parsed.candidates?.[0]?.content?.parts?.[0]?.text;
296
+ if (text) yield text;
297
+ } catch {}
298
+ }
299
+ }
300
+ }
301
+ }
302
+
303
+ function isGeminiNative(): boolean {
304
+ const baseUrl = process.env.OPC_LLM_BASE_URL || '';
305
+ const key = getApiKey();
306
+ // Use native Gemini API when: key starts with AQ. (new format) OR base URL points to googleapis
307
+ return key.startsWith('AQ.') || (baseUrl.includes('googleapis.com') && !baseUrl.includes('/openai'));
308
+ }
309
+
310
+ export function createProvider(name: string = 'openai', model?: string, baseUrl?: string, apiKey?: string): LLMProvider {
311
+ const finalModel = model || process.env.OPC_LLM_MODEL || 'gpt-4o-mini';
312
+ const finalKey = apiKey || getApiKey();
313
+
314
+ // Auto-detect Gemini native when key is new format
315
+ if (finalKey.startsWith('AQ.') || isGeminiNative()) {
316
+ return new GeminiNativeProvider(finalModel, finalKey);
317
+ }
318
+
319
+ return new OpenAICompatibleProvider(name, finalModel, baseUrl, apiKey);
320
+ }
321
+
322
+ export const SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen', 'gemini'] as const;