opc-agent 1.1.3 → 1.2.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.
Files changed (156) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/CONTRIBUTING.md +75 -75
  3. package/README.md +429 -429
  4. package/README.zh-CN.md +415 -415
  5. package/dist/channels/web.js +256 -256
  6. package/dist/core/streaming.d.ts +56 -0
  7. package/dist/core/streaming.js +160 -0
  8. package/dist/deploy/hermes.js +22 -22
  9. package/dist/deploy/openclaw.js +31 -31
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.js +7 -1
  12. package/dist/providers/index.d.ts +1 -1
  13. package/dist/providers/index.js +13 -148
  14. package/dist/schema/oad.d.ts +3 -3
  15. package/dist/templates/code-reviewer.js +5 -5
  16. package/dist/templates/customer-service.js +2 -2
  17. package/dist/templates/data-analyst.js +5 -5
  18. package/dist/templates/knowledge-base.js +2 -2
  19. package/dist/templates/sales-assistant.js +4 -4
  20. package/dist/templates/teacher.js +6 -6
  21. package/dist/tools/gateway.d.ts +28 -0
  22. package/dist/tools/gateway.js +177 -0
  23. package/docs/.vitepress/config.ts +103 -103
  24. package/docs/api/cli.md +48 -48
  25. package/docs/api/oad-schema.md +64 -64
  26. package/docs/api/sdk.md +80 -80
  27. package/docs/guide/concepts.md +51 -51
  28. package/docs/guide/configuration.md +79 -79
  29. package/docs/guide/deployment.md +42 -42
  30. package/docs/guide/getting-started.md +44 -44
  31. package/docs/guide/templates.md +28 -28
  32. package/docs/guide/testing.md +84 -84
  33. package/docs/index.md +27 -27
  34. package/docs/zh/api/cli.md +54 -54
  35. package/docs/zh/api/oad-schema.md +87 -87
  36. package/docs/zh/api/sdk.md +102 -102
  37. package/docs/zh/guide/concepts.md +104 -104
  38. package/docs/zh/guide/configuration.md +135 -135
  39. package/docs/zh/guide/deployment.md +81 -81
  40. package/docs/zh/guide/getting-started.md +82 -82
  41. package/docs/zh/guide/templates.md +84 -84
  42. package/docs/zh/guide/testing.md +88 -88
  43. package/docs/zh/index.md +27 -27
  44. package/examples/customer-service-demo/README.md +90 -90
  45. package/examples/customer-service-demo/oad.yaml +107 -107
  46. package/package.json +1 -1
  47. package/src/analytics/index.ts +66 -66
  48. package/src/channels/discord.ts +192 -192
  49. package/src/channels/email.ts +177 -177
  50. package/src/channels/feishu.ts +236 -236
  51. package/src/channels/index.ts +15 -15
  52. package/src/channels/slack.ts +160 -160
  53. package/src/channels/telegram.ts +90 -90
  54. package/src/channels/voice.ts +106 -106
  55. package/src/channels/web.ts +17 -17
  56. package/src/channels/webhook.ts +199 -199
  57. package/src/channels/websocket.ts +87 -87
  58. package/src/channels/wechat.ts +149 -149
  59. package/src/core/a2a.ts +143 -143
  60. package/src/core/agent.ts +152 -152
  61. package/src/core/analytics-engine.ts +186 -186
  62. package/src/core/auth.ts +57 -57
  63. package/src/core/cache.ts +141 -141
  64. package/src/core/compose.ts +77 -77
  65. package/src/core/config.ts +14 -14
  66. package/src/core/errors.ts +148 -148
  67. package/src/core/hitl.ts +138 -138
  68. package/src/core/knowledge.ts +49 -4
  69. package/src/core/logger.ts +57 -57
  70. package/src/core/orchestrator.ts +215 -215
  71. package/src/core/performance.ts +187 -187
  72. package/src/core/rate-limiter.ts +128 -128
  73. package/src/core/room.ts +109 -109
  74. package/src/core/runtime.ts +152 -152
  75. package/src/core/sandbox.ts +101 -101
  76. package/src/core/security.ts +171 -171
  77. package/src/core/streaming.ts +195 -0
  78. package/src/core/types.ts +68 -68
  79. package/src/core/versioning.ts +106 -106
  80. package/src/core/watch.ts +178 -178
  81. package/src/core/workflow.ts +235 -235
  82. package/src/deploy/hermes.ts +156 -156
  83. package/src/deploy/openclaw.ts +200 -200
  84. package/src/dtv/data.ts +29 -29
  85. package/src/dtv/trust.ts +43 -43
  86. package/src/dtv/value.ts +47 -47
  87. package/src/i18n/index.ts +216 -216
  88. package/src/index.ts +6 -0
  89. package/src/marketplace/index.ts +223 -223
  90. package/src/memory/deepbrain.ts +108 -108
  91. package/src/memory/index.ts +34 -34
  92. package/src/plugins/index.ts +208 -208
  93. package/src/providers/index.ts +12 -3
  94. package/src/schema/oad.ts +155 -155
  95. package/src/skills/base.ts +16 -16
  96. package/src/skills/document.ts +100 -100
  97. package/src/skills/http.ts +35 -35
  98. package/src/skills/index.ts +27 -27
  99. package/src/skills/scheduler.ts +80 -80
  100. package/src/skills/webhook-trigger.ts +59 -59
  101. package/src/templates/code-reviewer.ts +34 -34
  102. package/src/templates/customer-service.ts +80 -80
  103. package/src/templates/data-analyst.ts +70 -70
  104. package/src/templates/executive-assistant.ts +71 -71
  105. package/src/templates/financial-advisor.ts +60 -60
  106. package/src/templates/knowledge-base.ts +31 -31
  107. package/src/templates/legal-assistant.ts +71 -71
  108. package/src/templates/sales-assistant.ts +79 -79
  109. package/src/templates/teacher.ts +79 -79
  110. package/src/testing/index.ts +181 -181
  111. package/src/tools/calculator.ts +73 -73
  112. package/src/tools/datetime.ts +149 -149
  113. package/src/tools/gateway.ts +220 -0
  114. package/src/tools/json-transform.ts +187 -187
  115. package/src/tools/mcp.ts +76 -76
  116. package/src/tools/text-analysis.ts +116 -116
  117. package/templates/Dockerfile +15 -15
  118. package/templates/code-reviewer/README.md +27 -27
  119. package/templates/code-reviewer/oad.yaml +41 -41
  120. package/templates/customer-service/README.md +22 -22
  121. package/templates/customer-service/oad.yaml +36 -36
  122. package/templates/docker-compose.yml +21 -21
  123. package/templates/ecommerce-assistant/README.md +45 -0
  124. package/templates/ecommerce-assistant/oad.yaml +47 -0
  125. package/templates/knowledge-base/README.md +28 -28
  126. package/templates/knowledge-base/oad.yaml +38 -38
  127. package/templates/sales-assistant/README.md +26 -26
  128. package/templates/sales-assistant/oad.yaml +43 -43
  129. package/templates/tech-support/README.md +43 -0
  130. package/templates/tech-support/oad.yaml +45 -0
  131. package/tests/a2a.test.ts +66 -66
  132. package/tests/agent.test.ts +72 -72
  133. package/tests/analytics.test.ts +50 -50
  134. package/tests/channel.test.ts +39 -39
  135. package/tests/e2e.test.ts +134 -134
  136. package/tests/errors.test.ts +83 -83
  137. package/tests/gateway.test.ts +71 -0
  138. package/tests/hitl.test.ts +71 -71
  139. package/tests/i18n.test.ts +41 -41
  140. package/tests/mcp.test.ts +54 -54
  141. package/tests/oad.test.ts +68 -68
  142. package/tests/performance.test.ts +115 -115
  143. package/tests/plugin.test.ts +74 -74
  144. package/tests/room.test.ts +106 -106
  145. package/tests/runtime.test.ts +42 -42
  146. package/tests/sandbox.test.ts +46 -46
  147. package/tests/security.test.ts +60 -60
  148. package/tests/streaming.test.ts +109 -0
  149. package/tests/templates.test.ts +77 -77
  150. package/tests/v070.test.ts +76 -76
  151. package/tests/versioning.test.ts +75 -75
  152. package/tests/voice.test.ts +61 -61
  153. package/tests/webhook.test.ts +29 -29
  154. package/tests/workflow.test.ts +143 -143
  155. package/tsconfig.json +19 -19
  156. package/vitest.config.ts +9 -9
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamingManager = exports.StreamableResponse = void 0;
4
+ const events_1 = require("events");
5
+ // ─── StreamableResponse ──────────────────────────────────────
6
+ class StreamableResponse extends events_1.EventEmitter {
7
+ id;
8
+ chunks = [];
9
+ ended = false;
10
+ paused = false;
11
+ buffer = [];
12
+ highWaterMark;
13
+ constructor(id, options) {
14
+ super();
15
+ this.id = id;
16
+ this.highWaterMark = options?.highWaterMark ?? 64;
17
+ }
18
+ /** Push a chunk. Returns false if backpressure threshold reached. */
19
+ push(chunk) {
20
+ if (this.ended)
21
+ return false;
22
+ this.chunks.push(chunk);
23
+ if (this.paused) {
24
+ this.buffer.push(chunk);
25
+ return this.buffer.length < this.highWaterMark;
26
+ }
27
+ this.emit('chunk', chunk);
28
+ if (this.chunks.length >= this.highWaterMark) {
29
+ this.paused = true;
30
+ this.emit('backpressure');
31
+ return false;
32
+ }
33
+ return true;
34
+ }
35
+ /** Resume after backpressure — flush buffered chunks. */
36
+ resume() {
37
+ if (!this.paused)
38
+ return;
39
+ this.paused = false;
40
+ const buffered = this.buffer.splice(0);
41
+ for (const chunk of buffered) {
42
+ this.emit('chunk', chunk);
43
+ }
44
+ this.emit('drain');
45
+ }
46
+ end() {
47
+ if (this.ended)
48
+ return;
49
+ this.ended = true;
50
+ if (this.paused)
51
+ this.resume();
52
+ this.emit('end');
53
+ }
54
+ getChunks() {
55
+ return [...this.chunks];
56
+ }
57
+ /** Collect all text chunks into a single string. */
58
+ getText() {
59
+ return this.chunks
60
+ .filter((c) => c.type === 'text')
61
+ .map((c) => c.data)
62
+ .join('');
63
+ }
64
+ get isEnded() {
65
+ return this.ended;
66
+ }
67
+ get isPaused() {
68
+ return this.paused;
69
+ }
70
+ get length() {
71
+ return this.chunks.length;
72
+ }
73
+ }
74
+ exports.StreamableResponse = StreamableResponse;
75
+ // ─── StreamingManager ────────────────────────────────────────
76
+ class StreamingManager {
77
+ streams = new Map();
78
+ counter = 0;
79
+ /** Create a new stream. */
80
+ createStream(options) {
81
+ const id = `stream_${++this.counter}_${Date.now()}`;
82
+ const stream = new StreamableResponse(id, options);
83
+ this.streams.set(id, stream);
84
+ stream.on('end', () => {
85
+ // Keep ended streams for a bit for late consumers, then clean up
86
+ setTimeout(() => this.streams.delete(id), 30_000);
87
+ });
88
+ return stream;
89
+ }
90
+ /** Write a text chunk to a stream. */
91
+ writeChunk(streamId, data, metadata) {
92
+ const stream = this.streams.get(streamId);
93
+ if (!stream)
94
+ return false;
95
+ return stream.push({
96
+ id: `chunk_${stream.length}`,
97
+ type: 'text',
98
+ data,
99
+ timestamp: Date.now(),
100
+ metadata,
101
+ });
102
+ }
103
+ /** End a stream. */
104
+ endStream(streamId) {
105
+ const stream = this.streams.get(streamId);
106
+ if (!stream)
107
+ return;
108
+ stream.push({
109
+ id: `chunk_${stream.length}`,
110
+ type: 'done',
111
+ data: '',
112
+ timestamp: Date.now(),
113
+ });
114
+ stream.end();
115
+ }
116
+ /** Get an existing stream. */
117
+ getStream(streamId) {
118
+ return this.streams.get(streamId);
119
+ }
120
+ /** Format a chunk as an SSE event string. */
121
+ static formatSSE(chunk) {
122
+ const lines = [];
123
+ lines.push(`event: ${chunk.type}`);
124
+ lines.push(`id: ${chunk.id}`);
125
+ const payload = JSON.stringify({ data: chunk.data, metadata: chunk.metadata });
126
+ lines.push(`data: ${payload}`);
127
+ lines.push('');
128
+ return lines.join('\n') + '\n';
129
+ }
130
+ /** Pipe a stream to an SSE-compatible HTTP response (Express-style). */
131
+ static pipeSSE(stream, res, options) {
132
+ res.setHeader?.('Content-Type', 'text/event-stream');
133
+ res.setHeader?.('Cache-Control', 'no-cache');
134
+ res.setHeader?.('Connection', 'keep-alive');
135
+ const heartbeatMs = options?.heartbeatInterval ?? 15_000;
136
+ const heartbeat = setInterval(() => {
137
+ res.write(': heartbeat\n\n');
138
+ }, heartbeatMs);
139
+ stream.on('chunk', (chunk) => {
140
+ const ok = res.write(StreamingManager.formatSSE(chunk));
141
+ if (!ok && stream.isPaused === false) {
142
+ // Downstream can't keep up — will resume on drain from stream
143
+ }
144
+ });
145
+ stream.on('end', () => {
146
+ clearInterval(heartbeat);
147
+ res.end();
148
+ });
149
+ }
150
+ get activeCount() {
151
+ let count = 0;
152
+ for (const s of this.streams.values()) {
153
+ if (!s.isEnded)
154
+ count++;
155
+ }
156
+ return count;
157
+ }
158
+ }
159
+ exports.StreamingManager = StreamingManager;
160
+ //# sourceMappingURL=streaming.js.map
@@ -113,32 +113,32 @@ function deployToHermes(options) {
113
113
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf-8');
114
114
  files.push('settings.json');
115
115
  // .env template
116
- const envContent = `# Hermes Agent Environment
117
- HERMES_CHARACTER=${oad.metadata.name}
118
- HERMES_MODEL=${oad.spec.model}
119
- HERMES_PROVIDER=${oad.spec.provider?.default ?? 'openai'}
120
- # Add your API keys below:
121
- # OPENAI_API_KEY=
122
- # DEEPSEEK_API_KEY=
116
+ const envContent = `# Hermes Agent Environment
117
+ HERMES_CHARACTER=${oad.metadata.name}
118
+ HERMES_MODEL=${oad.spec.model}
119
+ HERMES_PROVIDER=${oad.spec.provider?.default ?? 'openai'}
120
+ # Add your API keys below:
121
+ # OPENAI_API_KEY=
122
+ # DEEPSEEK_API_KEY=
123
123
  `;
124
124
  fs.writeFileSync(path.join(outputDir, '.env.hermes'), envContent, 'utf-8');
125
125
  files.push('.env.hermes');
126
126
  // README
127
- const readme = `# ${oad.metadata.name} - Hermes Agent
128
-
129
- Converted from OAD format using \`opc deploy --target hermes\`.
130
-
131
- ## Usage
132
-
133
- 1. Copy \`character.json\` to your Hermes agents directory
134
- 2. Configure \`.env.hermes\` with your API keys
135
- 3. Start Hermes with this character
136
-
137
- ## Files
138
-
139
- - \`character.json\` - Agent character definition
140
- - \`settings.json\` - Runtime settings
141
- - \`.env.hermes\` - Environment template
127
+ const readme = `# ${oad.metadata.name} - Hermes Agent
128
+
129
+ Converted from OAD format using \`opc deploy --target hermes\`.
130
+
131
+ ## Usage
132
+
133
+ 1. Copy \`character.json\` to your Hermes agents directory
134
+ 2. Configure \`.env.hermes\` with your API keys
135
+ 3. Start Hermes with this character
136
+
137
+ ## Files
138
+
139
+ - \`character.json\` - Agent character definition
140
+ - \`settings.json\` - Runtime settings
141
+ - \`.env.hermes\` - Environment template
142
142
  `;
143
143
  fs.writeFileSync(path.join(outputDir, 'README.md'), readme, 'utf-8');
144
144
  files.push('README.md');
@@ -41,27 +41,27 @@ const fs = __importStar(require("fs"));
41
41
  const path = __importStar(require("path"));
42
42
  function generateIdentityMd(oad) {
43
43
  const m = oad.metadata;
44
- return `# IDENTITY.md
45
-
46
- - **Name:** ${m.name}
47
- - **Version:** ${m.version}
48
- - **Description:** ${m.description ?? 'An AI agent'}
49
- - **Author:** ${m.author ?? 'Unknown'}
50
- - **License:** ${m.license}
44
+ return `# IDENTITY.md
45
+
46
+ - **Name:** ${m.name}
47
+ - **Version:** ${m.version}
48
+ - **Description:** ${m.description ?? 'An AI agent'}
49
+ - **Author:** ${m.author ?? 'Unknown'}
50
+ - **License:** ${m.license}
51
51
  `;
52
52
  }
53
53
  function generateSoulMd(oad) {
54
54
  const prompt = oad.spec.systemPrompt ?? 'You are a helpful AI assistant.';
55
- return `# SOUL.md - ${oad.metadata.name}
56
-
57
- ## System Prompt
58
-
59
- ${prompt}
60
-
61
- ## Model Configuration
62
-
63
- - **Model:** ${oad.spec.model}
64
- - **Provider:** ${oad.spec.provider?.default ?? 'deepseek'}
55
+ return `# SOUL.md - ${oad.metadata.name}
56
+
57
+ ## System Prompt
58
+
59
+ ${prompt}
60
+
61
+ ## Model Configuration
62
+
63
+ - **Model:** ${oad.spec.model}
64
+ - **Provider:** ${oad.spec.provider?.default ?? 'deepseek'}
65
65
  `;
66
66
  }
67
67
  function generateAgentsMd(oad) {
@@ -112,23 +112,23 @@ function generateAgentsMd(oad) {
112
112
  return md;
113
113
  }
114
114
  function generateUserMd(oad) {
115
- return `# USER.md
116
-
117
- - **Name:** (your name)
118
- - **Role:** User
119
- - **Notes:** Configure this file with your preferences for ${oad.metadata.name}.
115
+ return `# USER.md
116
+
117
+ - **Name:** (your name)
118
+ - **Role:** User
119
+ - **Notes:** Configure this file with your preferences for ${oad.metadata.name}.
120
120
  `;
121
121
  }
122
122
  function generateMemoryMd(oad) {
123
- return `# MEMORY.md - ${oad.metadata.name}
124
-
125
- ## Persistent Knowledge
126
-
127
- (Agent will store learned information here)
128
-
129
- ## User Preferences
130
-
131
- (Discovered user preferences will be noted here)
123
+ return `# MEMORY.md - ${oad.metadata.name}
124
+
125
+ ## Persistent Knowledge
126
+
127
+ (Agent will store learned information here)
128
+
129
+ ## User Preferences
130
+
131
+ (Discovered user preferences will be noted here)
132
132
  `;
133
133
  }
134
134
  function generateOpenClawConfig(oad, agentDir) {
package/dist/index.d.ts CHANGED
@@ -91,4 +91,8 @@ export { DiscordChannel } from './channels/discord';
91
91
  export type { DiscordChannelConfig } from './channels/discord';
92
92
  export { ProcessWatcher } from './core/watch';
93
93
  export type { WatchPattern, WatchMatch, WatchOptions } from './core/watch';
94
+ export { ToolGateway } from './tools/gateway';
95
+ export type { ToolGatewayConfig, GatewayToolName } from './tools/gateway';
96
+ export { StreamingManager, StreamableResponse } from './core/streaming';
97
+ export type { StreamChunk, StreamOptions } from './core/streaming';
94
98
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EmailChannel = exports.compose = exports.AgentPipeline = exports.Orchestrator = exports.getActiveSessions = exports.createAuthMiddleware = exports.installAgent = exports.publishAgent = exports.deployToHermes = exports.KnowledgeBase = exports.addMessages = exports.detectLocale = exports.getLocale = exports.setLocale = exports.t = exports.LazyLoader = exports.RequestBatcher = exports.ConnectionPool = exports.VersionManager = exports.WebhookChannel = exports.VoiceChannel = exports.HITLManager = exports.AgentRegistry = exports.WorkflowEngine = exports.Analytics = exports.Sandbox = exports.PluginManager = exports.createMCPTool = exports.MCPToolRegistry = exports.Room = exports.SUPPORTED_PROVIDERS = exports.createProvider = exports.MRGConfigReader = exports.ValueTracker = exports.TrustManager = exports.DeepBrainMemoryStore = exports.InMemoryStore = exports.SkillRegistry = exports.BaseSkill = exports.WebSocketChannel = exports.TelegramChannel = exports.WebChannel = exports.BaseChannel = exports.OADSchema = exports.validateOAD = exports.loadOAD = exports.Logger = exports.truncateOutput = exports.AgentRuntime = exports.BaseAgent = void 0;
4
- exports.ProcessWatcher = exports.DiscordChannel = exports.FeishuChannel = exports.createRateLimitPlugin = exports.createAnalyticsPlugin = exports.createLoggingPlugin = exports.inputValidation = exports.APIKeyManager = exports.corsMiddleware = exports.securityHeaders = exports.detectInjection = exports.sanitizeInput = exports.formatErrorForUser = exports.wrapError = exports.TimeoutError = exports.SecurityError = exports.RateLimitError = exports.PluginError = exports.ChannelError = exports.ConfigError = exports.ValidationError = exports.ProviderError = exports.OPCError = exports.createTeacherConfig = exports.createDataAnalystConfig = exports.getSupportedLocales = exports.LLMCache = exports.RateLimiter = exports.AnalyticsEngine = exports.formatReport = exports.loadTestCases = exports.runTests = exports.DocumentSkill = exports.SchedulerSkill = exports.WebhookTriggerSkill = exports.HttpSkill = exports.TextAnalysisTool = exports.JsonTransformTool = exports.DateTimeTool = exports.CalculatorTool = exports.WeChatChannel = exports.SlackChannel = void 0;
4
+ exports.StreamableResponse = exports.StreamingManager = exports.ToolGateway = exports.ProcessWatcher = exports.DiscordChannel = exports.FeishuChannel = exports.createRateLimitPlugin = exports.createAnalyticsPlugin = exports.createLoggingPlugin = exports.inputValidation = exports.APIKeyManager = exports.corsMiddleware = exports.securityHeaders = exports.detectInjection = exports.sanitizeInput = exports.formatErrorForUser = exports.wrapError = exports.TimeoutError = exports.SecurityError = exports.RateLimitError = exports.PluginError = exports.ChannelError = exports.ConfigError = exports.ValidationError = exports.ProviderError = exports.OPCError = exports.createTeacherConfig = exports.createDataAnalystConfig = exports.getSupportedLocales = exports.LLMCache = exports.RateLimiter = exports.AnalyticsEngine = exports.formatReport = exports.loadTestCases = exports.runTests = exports.DocumentSkill = exports.SchedulerSkill = exports.WebhookTriggerSkill = exports.HttpSkill = exports.TextAnalysisTool = exports.JsonTransformTool = exports.DateTimeTool = exports.CalculatorTool = exports.WeChatChannel = exports.SlackChannel = void 0;
5
5
  // OPC Agent — Open Agent Framework
6
6
  var agent_1 = require("./core/agent");
7
7
  Object.defineProperty(exports, "BaseAgent", { enumerable: true, get: function () { return agent_1.BaseAgent; } });
@@ -163,4 +163,10 @@ var discord_1 = require("./channels/discord");
163
163
  Object.defineProperty(exports, "DiscordChannel", { enumerable: true, get: function () { return discord_1.DiscordChannel; } });
164
164
  var watch_1 = require("./core/watch");
165
165
  Object.defineProperty(exports, "ProcessWatcher", { enumerable: true, get: function () { return watch_1.ProcessWatcher; } });
166
+ // v1.2.0 modules
167
+ var gateway_1 = require("./tools/gateway");
168
+ Object.defineProperty(exports, "ToolGateway", { enumerable: true, get: function () { return gateway_1.ToolGateway; } });
169
+ var streaming_1 = require("./core/streaming");
170
+ Object.defineProperty(exports, "StreamingManager", { enumerable: true, get: function () { return streaming_1.StreamingManager; } });
171
+ Object.defineProperty(exports, "StreamableResponse", { enumerable: true, get: function () { return streaming_1.StreamableResponse; } });
166
172
  //# sourceMappingURL=index.js.map
@@ -5,5 +5,5 @@ export interface LLMProvider {
5
5
  chatStream(messages: Message[], systemPrompt?: string): AsyncIterable<string>;
6
6
  }
7
7
  export declare function createProvider(name?: string, model?: string, baseUrl?: string, apiKey?: string): LLMProvider;
8
- export declare const SUPPORTED_PROVIDERS: readonly ["openai", "deepseek", "qwen", "gemini"];
8
+ export declare const SUPPORTED_PROVIDERS: readonly ["openai", "deepseek", "qwen"];
9
9
  //# sourceMappingURL=index.d.ts.map
@@ -69,27 +69,20 @@ class OpenAICompatibleProvider {
69
69
  throw new Error('No API key configured. Set OPC_LLM_API_KEY or OPENAI_API_KEY environment variable.');
70
70
  }
71
71
  const url = new URL(`${this.baseUrl}/chat/completions`);
72
- const isGemini = url.hostname.includes('googleapis.com');
73
- if (isGemini) {
74
- url.searchParams.set('key', this.apiKey);
75
- }
76
72
  const isHttps = url.protocol === 'https:';
77
73
  const lib = isHttps ? https : http;
78
74
  const postData = JSON.stringify(body);
79
- const headers = {
80
- 'Content-Type': 'application/json',
81
- 'Content-Length': String(Buffer.byteLength(postData)),
82
- };
83
- if (!isGemini) {
84
- headers['Authorization'] = `Bearer ${this.apiKey}`;
85
- }
86
75
  return new Promise((resolve, reject) => {
87
76
  const req = lib.request({
88
77
  hostname: url.hostname,
89
78
  port: url.port || (isHttps ? 443 : 80),
90
- path: url.pathname + url.search,
79
+ path: url.pathname,
91
80
  method: 'POST',
92
- headers,
81
+ headers: {
82
+ 'Content-Type': 'application/json',
83
+ Authorization: `Bearer ${this.apiKey}`,
84
+ 'Content-Length': Buffer.byteLength(postData),
85
+ },
93
86
  }, (res) => {
94
87
  let data = '';
95
88
  res.on('data', (chunk) => (data += chunk.toString()));
@@ -134,10 +127,6 @@ class OpenAICompatibleProvider {
134
127
  }
135
128
  const formatted = this.formatMessages(messages, systemPrompt);
136
129
  const url = new URL(`${this.baseUrl}/chat/completions`);
137
- const isGemini = url.hostname.includes('googleapis.com');
138
- if (isGemini) {
139
- url.searchParams.set('key', this.apiKey);
140
- }
141
130
  const isHttps = url.protocol === 'https:';
142
131
  const lib = isHttps ? https : http;
143
132
  const postData = JSON.stringify({
@@ -147,20 +136,17 @@ class OpenAICompatibleProvider {
147
136
  max_tokens: 2048,
148
137
  stream: true,
149
138
  });
150
- const streamHeaders = {
151
- 'Content-Type': 'application/json',
152
- 'Content-Length': String(Buffer.byteLength(postData)),
153
- };
154
- if (!isGemini) {
155
- streamHeaders['Authorization'] = `Bearer ${this.apiKey}`;
156
- }
157
139
  const response = await new Promise((resolve, reject) => {
158
140
  const req = lib.request({
159
141
  hostname: url.hostname,
160
142
  port: url.port || (isHttps ? 443 : 80),
161
- path: url.pathname + url.search,
143
+ path: url.pathname,
162
144
  method: 'POST',
163
- headers: streamHeaders,
145
+ headers: {
146
+ 'Content-Type': 'application/json',
147
+ Authorization: `Bearer ${this.apiKey}`,
148
+ 'Content-Length': Buffer.byteLength(postData),
149
+ },
164
150
  }, resolve);
165
151
  req.on('error', reject);
166
152
  req.write(postData);
@@ -197,130 +183,9 @@ class OpenAICompatibleProvider {
197
183
  }
198
184
  }
199
185
  }
200
- class GeminiNativeProvider {
201
- name = 'gemini';
202
- model;
203
- apiKey;
204
- constructor(model, apiKey) {
205
- this.model = model;
206
- this.apiKey = apiKey || getApiKey();
207
- }
208
- buildUrl(stream) {
209
- const action = stream ? 'streamGenerateContent?alt=sse&' : 'generateContent?';
210
- return `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:${action}key=${this.apiKey}`;
211
- }
212
- formatContents(messages, systemPrompt) {
213
- const contents = [];
214
- for (const m of messages) {
215
- contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] });
216
- }
217
- const result = { contents };
218
- if (systemPrompt) {
219
- result.systemInstruction = { parts: [{ text: systemPrompt }] };
220
- }
221
- return result;
222
- }
223
- async chat(messages, systemPrompt) {
224
- if (!this.apiKey) {
225
- const last = messages[messages.length - 1];
226
- return `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
227
- }
228
- const body = this.formatContents(messages, systemPrompt);
229
- const url = this.buildUrl(false);
230
- const postData = JSON.stringify(body);
231
- return new Promise((resolve, reject) => {
232
- const parsedUrl = new URL(url);
233
- const req = https.request({
234
- hostname: parsedUrl.hostname,
235
- path: parsedUrl.pathname + parsedUrl.search,
236
- method: 'POST',
237
- headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
238
- }, (res) => {
239
- let data = '';
240
- res.on('data', (chunk) => (data += chunk.toString()));
241
- res.on('end', () => {
242
- if (res.statusCode && res.statusCode >= 400) {
243
- reject(new Error(`Gemini API error ${res.statusCode}: ${data}`));
244
- return;
245
- }
246
- try {
247
- const parsed = JSON.parse(data);
248
- resolve(parsed.candidates?.[0]?.content?.parts?.[0]?.text ?? '');
249
- }
250
- catch {
251
- reject(new Error(`Invalid Gemini response: ${data.slice(0, 200)}`));
252
- }
253
- });
254
- });
255
- req.on('error', reject);
256
- req.write(postData);
257
- req.end();
258
- });
259
- }
260
- async *chatStream(messages, systemPrompt) {
261
- if (!this.apiKey) {
262
- const last = messages[messages.length - 1];
263
- yield `[gemini/${this.model} - no API key] Echo: ${last?.content ?? ''}`;
264
- return;
265
- }
266
- const body = this.formatContents(messages, systemPrompt);
267
- const url = this.buildUrl(true);
268
- const postData = JSON.stringify(body);
269
- const parsedUrl = new URL(url);
270
- const response = await new Promise((resolve, reject) => {
271
- const req = https.request({
272
- hostname: parsedUrl.hostname,
273
- path: parsedUrl.pathname + parsedUrl.search,
274
- method: 'POST',
275
- headers: { 'Content-Type': 'application/json', 'Content-Length': String(Buffer.byteLength(postData)) },
276
- }, resolve);
277
- req.on('error', reject);
278
- req.write(postData);
279
- req.end();
280
- });
281
- if (response.statusCode && response.statusCode >= 400) {
282
- let data = '';
283
- for await (const chunk of response)
284
- data += chunk.toString();
285
- throw new Error(`Gemini API error ${response.statusCode}: ${data}`);
286
- }
287
- let buffer = '';
288
- for await (const chunk of response) {
289
- buffer += chunk.toString();
290
- const lines = buffer.split('\n');
291
- buffer = lines.pop() ?? '';
292
- for (const line of lines) {
293
- const trimmed = line.trim();
294
- if (!trimmed.startsWith('data: '))
295
- continue;
296
- const data = trimmed.slice(6);
297
- if (data === '[DONE]')
298
- return;
299
- try {
300
- const parsed = JSON.parse(data);
301
- const text = parsed.candidates?.[0]?.content?.parts?.[0]?.text;
302
- if (text)
303
- yield text;
304
- }
305
- catch { }
306
- }
307
- }
308
- }
309
- }
310
- function isGeminiNative() {
311
- const baseUrl = process.env.OPC_LLM_BASE_URL || '';
312
- const key = getApiKey();
313
- // Use native Gemini API when: key starts with AQ. (new format) OR base URL points to googleapis
314
- return key.startsWith('AQ.') || (baseUrl.includes('googleapis.com') && !baseUrl.includes('/openai'));
315
- }
316
186
  function createProvider(name = 'openai', model, baseUrl, apiKey) {
317
187
  const finalModel = model || process.env.OPC_LLM_MODEL || 'gpt-4o-mini';
318
- const finalKey = apiKey || getApiKey();
319
- // Auto-detect Gemini native when key is new format
320
- if (finalKey.startsWith('AQ.') || isGeminiNative()) {
321
- return new GeminiNativeProvider(finalModel, finalKey);
322
- }
323
188
  return new OpenAICompatibleProvider(name, finalModel, baseUrl, apiKey);
324
189
  }
325
- exports.SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen', 'gemini'];
190
+ exports.SUPPORTED_PROVIDERS = ['openai', 'deepseek', 'qwen'];
326
191
  //# sourceMappingURL=index.js.map
@@ -577,7 +577,6 @@ export declare const SpecSchema: z.ZodObject<{
577
577
  config?: Record<string, unknown> | undefined;
578
578
  }[] | undefined;
579
579
  }, {
580
- model?: string | undefined;
581
580
  auth?: {
582
581
  enabled?: boolean | undefined;
583
582
  apiKeys?: string[] | undefined;
@@ -598,6 +597,7 @@ export declare const SpecSchema: z.ZodObject<{
598
597
  default?: string | undefined;
599
598
  allowed?: string[] | undefined;
600
599
  } | undefined;
600
+ model?: string | undefined;
601
601
  systemPrompt?: string | undefined;
602
602
  skills?: {
603
603
  name: string;
@@ -995,7 +995,6 @@ export declare const OADSchema: z.ZodObject<{
995
995
  config?: Record<string, unknown> | undefined;
996
996
  }[] | undefined;
997
997
  }, {
998
- model?: string | undefined;
999
998
  auth?: {
1000
999
  enabled?: boolean | undefined;
1001
1000
  apiKeys?: string[] | undefined;
@@ -1016,6 +1015,7 @@ export declare const OADSchema: z.ZodObject<{
1016
1015
  default?: string | undefined;
1017
1016
  allowed?: string[] | undefined;
1018
1017
  } | undefined;
1018
+ model?: string | undefined;
1019
1019
  systemPrompt?: string | undefined;
1020
1020
  skills?: {
1021
1021
  name: string;
@@ -1183,7 +1183,6 @@ export declare const OADSchema: z.ZodObject<{
1183
1183
  } | undefined;
1184
1184
  };
1185
1185
  spec: {
1186
- model?: string | undefined;
1187
1186
  auth?: {
1188
1187
  enabled?: boolean | undefined;
1189
1188
  apiKeys?: string[] | undefined;
@@ -1204,6 +1203,7 @@ export declare const OADSchema: z.ZodObject<{
1204
1203
  default?: string | undefined;
1205
1204
  allowed?: string[] | undefined;
1206
1205
  } | undefined;
1206
+ model?: string | undefined;
1207
1207
  systemPrompt?: string | undefined;
1208
1208
  skills?: {
1209
1209
  name: string;
@@ -2,11 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CODE_REVIEWER_SYSTEM_PROMPT = void 0;
4
4
  exports.createCodeReviewerConfig = createCodeReviewerConfig;
5
- exports.CODE_REVIEWER_SYSTEM_PROMPT = `You are an expert code reviewer. When given code:
6
- 1. Check for bugs, security issues, and performance problems
7
- 2. Suggest improvements for readability and maintainability
8
- 3. Follow language-specific best practices
9
- 4. Be constructive and explain your reasoning
5
+ exports.CODE_REVIEWER_SYSTEM_PROMPT = `You are an expert code reviewer. When given code:
6
+ 1. Check for bugs, security issues, and performance problems
7
+ 2. Suggest improvements for readability and maintainability
8
+ 3. Follow language-specific best practices
9
+ 4. Be constructive and explain your reasoning
10
10
  Rate severity: 🔴 Critical | 🟡 Warning | 🔵 Info`;
11
11
  function createCodeReviewerConfig() {
12
12
  return {
@@ -41,8 +41,8 @@ class HandoffSkill extends base_1.BaseSkill {
41
41
  }
42
42
  }
43
43
  exports.HandoffSkill = HandoffSkill;
44
- exports.CUSTOMER_SERVICE_SYSTEM_PROMPT = `You are a friendly and professional customer service agent.
45
- You help customers with their questions about products, orders, shipping, and returns.
44
+ exports.CUSTOMER_SERVICE_SYSTEM_PROMPT = `You are a friendly and professional customer service agent.
45
+ You help customers with their questions about products, orders, shipping, and returns.
46
46
  Be concise, helpful, and empathetic. If you're unsure, offer to connect them with a human agent.`;
47
47
  function createCustomerServiceConfig() {
48
48
  return {
@@ -33,11 +33,11 @@ class InsightSkill extends base_1.BaseSkill {
33
33
  }
34
34
  }
35
35
  exports.InsightSkill = InsightSkill;
36
- exports.DATA_ANALYST_SYSTEM_PROMPT = `You are a professional data analyst assistant. Your goals:
37
- 1. Help users query, transform, and analyze data
38
- 2. Create clear visualizations and summaries
39
- 3. Identify trends, patterns, and anomalies
40
- 4. Explain findings in plain language
36
+ exports.DATA_ANALYST_SYSTEM_PROMPT = `You are a professional data analyst assistant. Your goals:
37
+ 1. Help users query, transform, and analyze data
38
+ 2. Create clear visualizations and summaries
39
+ 3. Identify trends, patterns, and anomalies
40
+ 4. Explain findings in plain language
41
41
  Be precise with numbers, always cite your data source, and suggest next steps for deeper analysis.`;
42
42
  function createDataAnalystConfig() {
43
43
  return {
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KNOWLEDGE_BASE_SYSTEM_PROMPT = void 0;
4
4
  exports.createKnowledgeBaseConfig = createKnowledgeBaseConfig;
5
- exports.KNOWLEDGE_BASE_SYSTEM_PROMPT = `You are a knowledge base assistant. Answer questions using the company documents
6
- and knowledge provided to you. If you don't have enough information, say so honestly.
5
+ exports.KNOWLEDGE_BASE_SYSTEM_PROMPT = `You are a knowledge base assistant. Answer questions using the company documents
6
+ and knowledge provided to you. If you don't have enough information, say so honestly.
7
7
  Always cite sources when possible. Be accurate and concise.`;
8
8
  function createKnowledgeBaseConfig() {
9
9
  return {
@@ -43,10 +43,10 @@ class LeadCaptureSkill extends base_1.BaseSkill {
43
43
  }
44
44
  }
45
45
  exports.LeadCaptureSkill = LeadCaptureSkill;
46
- exports.SALES_ASSISTANT_SYSTEM_PROMPT = `You are a professional sales assistant. Your goals:
47
- 1. Answer product questions accurately and enthusiastically
48
- 2. Capture leads by collecting name, email, and company info
49
- 3. Book appointments when prospects are ready
46
+ exports.SALES_ASSISTANT_SYSTEM_PROMPT = `You are a professional sales assistant. Your goals:
47
+ 1. Answer product questions accurately and enthusiastically
48
+ 2. Capture leads by collecting name, email, and company info
49
+ 3. Book appointments when prospects are ready
50
50
  Be friendly, persuasive but not pushy. Always provide value first.`;
51
51
  function createSalesAssistantConfig() {
52
52
  return {