opc-agent 3.0.1 → 4.0.0

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 (151) hide show
  1. package/README.md +30 -24
  2. package/dist/channels/dingtalk.d.ts +17 -0
  3. package/dist/channels/dingtalk.js +38 -0
  4. package/dist/channels/googlechat.d.ts +14 -0
  5. package/dist/channels/googlechat.js +37 -0
  6. package/dist/channels/imessage.d.ts +13 -0
  7. package/dist/channels/imessage.js +28 -0
  8. package/dist/channels/irc.d.ts +20 -0
  9. package/dist/channels/irc.js +71 -0
  10. package/dist/channels/line.d.ts +14 -0
  11. package/dist/channels/line.js +28 -0
  12. package/dist/channels/matrix.d.ts +15 -0
  13. package/dist/channels/matrix.js +28 -0
  14. package/dist/channels/mattermost.d.ts +18 -0
  15. package/dist/channels/mattermost.js +49 -0
  16. package/dist/channels/msteams.d.ts +14 -0
  17. package/dist/channels/msteams.js +28 -0
  18. package/dist/channels/nostr.d.ts +14 -0
  19. package/dist/channels/nostr.js +28 -0
  20. package/dist/channels/qq.d.ts +15 -0
  21. package/dist/channels/qq.js +28 -0
  22. package/dist/channels/signal.d.ts +14 -0
  23. package/dist/channels/signal.js +28 -0
  24. package/dist/channels/sms.d.ts +15 -0
  25. package/dist/channels/sms.js +28 -0
  26. package/dist/channels/twitch.d.ts +17 -0
  27. package/dist/channels/twitch.js +59 -0
  28. package/dist/channels/voice-call.d.ts +27 -0
  29. package/dist/channels/voice-call.js +82 -0
  30. package/dist/channels/whatsapp.d.ts +14 -0
  31. package/dist/channels/whatsapp.js +28 -0
  32. package/dist/cli.js +36 -0
  33. package/dist/core/api-server.d.ts +25 -0
  34. package/dist/core/api-server.js +286 -0
  35. package/dist/core/audio.d.ts +50 -0
  36. package/dist/core/audio.js +68 -0
  37. package/dist/core/context-discovery.d.ts +16 -0
  38. package/dist/core/context-discovery.js +107 -0
  39. package/dist/core/context-refs.d.ts +29 -0
  40. package/dist/core/context-refs.js +162 -0
  41. package/dist/core/gateway.d.ts +53 -0
  42. package/dist/core/gateway.js +80 -0
  43. package/dist/core/heartbeat.d.ts +19 -0
  44. package/dist/core/heartbeat.js +50 -0
  45. package/dist/core/hooks.d.ts +28 -0
  46. package/dist/core/hooks.js +82 -0
  47. package/dist/core/ide-bridge.d.ts +53 -0
  48. package/dist/core/ide-bridge.js +97 -0
  49. package/dist/core/node-network.d.ts +23 -0
  50. package/dist/core/node-network.js +77 -0
  51. package/dist/core/profiles.d.ts +27 -0
  52. package/dist/core/profiles.js +131 -0
  53. package/dist/core/sandbox.d.ts +25 -0
  54. package/dist/core/sandbox.js +84 -1
  55. package/dist/core/session-manager.d.ts +33 -0
  56. package/dist/core/session-manager.js +157 -0
  57. package/dist/core/vision.d.ts +45 -0
  58. package/dist/core/vision.js +177 -0
  59. package/dist/index.d.ts +64 -1
  60. package/dist/index.js +86 -3
  61. package/dist/memory/context-compressor.d.ts +43 -0
  62. package/dist/memory/context-compressor.js +167 -0
  63. package/dist/memory/index.d.ts +4 -0
  64. package/dist/memory/index.js +5 -1
  65. package/dist/memory/user-profiler.d.ts +50 -0
  66. package/dist/memory/user-profiler.js +201 -0
  67. package/dist/schema/oad.d.ts +12 -12
  68. package/dist/security/approvals.d.ts +53 -0
  69. package/dist/security/approvals.js +115 -0
  70. package/dist/security/elevated.d.ts +41 -0
  71. package/dist/security/elevated.js +89 -0
  72. package/dist/security/index.d.ts +6 -0
  73. package/dist/security/index.js +7 -1
  74. package/dist/security/secrets.d.ts +34 -0
  75. package/dist/security/secrets.js +115 -0
  76. package/dist/tools/builtin/browser.d.ts +47 -0
  77. package/dist/tools/builtin/browser.js +284 -0
  78. package/dist/tools/builtin/home-assistant.d.ts +12 -0
  79. package/dist/tools/builtin/home-assistant.js +126 -0
  80. package/dist/tools/builtin/index.d.ts +6 -1
  81. package/dist/tools/builtin/index.js +18 -2
  82. package/dist/tools/builtin/rl-tools.d.ts +13 -0
  83. package/dist/tools/builtin/rl-tools.js +228 -0
  84. package/dist/tools/builtin/vision.d.ts +6 -0
  85. package/dist/tools/builtin/vision.js +61 -0
  86. package/package.json +2 -2
  87. package/src/channels/dingtalk.ts +46 -0
  88. package/src/channels/googlechat.ts +42 -0
  89. package/src/channels/imessage.ts +32 -0
  90. package/src/channels/irc.ts +82 -0
  91. package/src/channels/line.ts +33 -0
  92. package/src/channels/matrix.ts +34 -0
  93. package/src/channels/mattermost.ts +57 -0
  94. package/src/channels/msteams.ts +33 -0
  95. package/src/channels/nostr.ts +33 -0
  96. package/src/channels/qq.ts +34 -0
  97. package/src/channels/signal.ts +33 -0
  98. package/src/channels/sms.ts +34 -0
  99. package/src/channels/twitch.ts +65 -0
  100. package/src/channels/voice-call.ts +100 -0
  101. package/src/channels/whatsapp.ts +33 -0
  102. package/src/cli.ts +40 -0
  103. package/src/core/api-server.ts +277 -0
  104. package/src/core/audio.ts +98 -0
  105. package/src/core/context-discovery.ts +85 -0
  106. package/src/core/context-refs.ts +140 -0
  107. package/src/core/gateway.ts +106 -0
  108. package/src/core/heartbeat.ts +51 -0
  109. package/src/core/hooks.ts +105 -0
  110. package/src/core/ide-bridge.ts +133 -0
  111. package/src/core/node-network.ts +86 -0
  112. package/src/core/profiles.ts +122 -0
  113. package/src/core/sandbox.ts +100 -0
  114. package/src/core/session-manager.ts +137 -0
  115. package/src/core/vision.ts +180 -0
  116. package/src/index.ts +84 -1
  117. package/src/memory/context-compressor.ts +189 -0
  118. package/src/memory/index.ts +4 -0
  119. package/src/memory/user-profiler.ts +215 -0
  120. package/src/security/approvals.ts +143 -0
  121. package/src/security/elevated.ts +105 -0
  122. package/src/security/index.ts +6 -0
  123. package/src/security/secrets.ts +129 -0
  124. package/src/tools/builtin/browser.ts +299 -0
  125. package/src/tools/builtin/home-assistant.ts +116 -0
  126. package/src/tools/builtin/index.ts +9 -2
  127. package/src/tools/builtin/rl-tools.ts +243 -0
  128. package/src/tools/builtin/vision.ts +64 -0
  129. package/tests/api-server.test.ts +148 -0
  130. package/tests/approvals.test.ts +89 -0
  131. package/tests/audio.test.ts +40 -0
  132. package/tests/browser.test.ts +179 -0
  133. package/tests/builtin-tools.test.ts +83 -83
  134. package/tests/channels-extra.test.ts +45 -0
  135. package/tests/context-compressor.test.ts +172 -0
  136. package/tests/context-refs.test.ts +121 -0
  137. package/tests/elevated.test.ts +69 -0
  138. package/tests/gateway.test.ts +63 -71
  139. package/tests/home-assistant.test.ts +40 -0
  140. package/tests/hooks.test.ts +79 -0
  141. package/tests/ide-bridge.test.ts +38 -0
  142. package/tests/node-network.test.ts +74 -0
  143. package/tests/profiles.test.ts +61 -0
  144. package/tests/rl-tools.test.ts +93 -0
  145. package/tests/sandbox-manager.test.ts +46 -0
  146. package/tests/secrets.test.ts +107 -0
  147. package/tests/tools/builtin-extended.test.ts +138 -138
  148. package/tests/user-profiler.test.ts +169 -0
  149. package/tests/v090-features.test.ts +254 -0
  150. package/tests/vision.test.ts +61 -0
  151. package/tests/voice-call.test.ts +47 -0
@@ -0,0 +1,33 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface NostrChannelConfig {
5
+ privateKey?: string;
6
+ relays?: string[];
7
+ }
8
+
9
+ export class NostrChannel extends BaseChannel {
10
+ readonly type = 'nostr';
11
+ private config: NostrChannelConfig;
12
+
13
+ constructor(config: NostrChannelConfig = {}) {
14
+ super();
15
+ this.config = config;
16
+ }
17
+
18
+ async start(): Promise<void> {
19
+ try {
20
+ require('nostr-tools');
21
+ } catch {
22
+ throw new Error('Install nostr-tools to use the NostrChannel. Run: npm install nostr-tools');
23
+ }
24
+ }
25
+
26
+ async stop(): Promise<void> {
27
+ // cleanup
28
+ }
29
+
30
+ async send(chatId: string, text: string): Promise<void> {
31
+ throw new Error('NostrChannel: not yet connected. Call start() first.');
32
+ }
33
+ }
@@ -0,0 +1,34 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface QQChannelConfig {
5
+ appId?: string;
6
+ token?: string;
7
+ sandbox?: boolean;
8
+ }
9
+
10
+ export class QQChannel extends BaseChannel {
11
+ readonly type = 'qq';
12
+ private config: QQChannelConfig;
13
+
14
+ constructor(config: QQChannelConfig = {}) {
15
+ super();
16
+ this.config = config;
17
+ }
18
+
19
+ async start(): Promise<void> {
20
+ try {
21
+ require('qq-bot-sdk');
22
+ } catch {
23
+ throw new Error('Install qq-bot-sdk to use the QQChannel. Run: npm install qq-bot-sdk');
24
+ }
25
+ }
26
+
27
+ async stop(): Promise<void> {
28
+ // cleanup
29
+ }
30
+
31
+ async send(chatId: string, text: string): Promise<void> {
32
+ throw new Error('QQChannel: not yet connected. Call start() first.');
33
+ }
34
+ }
@@ -0,0 +1,33 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface SignalChannelConfig {
5
+ signalCliPath?: string;
6
+ phoneNumber?: string;
7
+ }
8
+
9
+ export class SignalChannel extends BaseChannel {
10
+ readonly type = 'signal';
11
+ private config: SignalChannelConfig;
12
+
13
+ constructor(config: SignalChannelConfig = {}) {
14
+ super();
15
+ this.config = config;
16
+ }
17
+
18
+ async start(): Promise<void> {
19
+ try {
20
+ require('signal-cli');
21
+ } catch {
22
+ throw new Error('Install signal-cli to use the SignalChannel. Run: npm install signal-cli');
23
+ }
24
+ }
25
+
26
+ async stop(): Promise<void> {
27
+ // cleanup
28
+ }
29
+
30
+ async send(chatId: string, text: string): Promise<void> {
31
+ throw new Error('SignalChannel: not yet connected. Call start() first.');
32
+ }
33
+ }
@@ -0,0 +1,34 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface SMSChannelConfig {
5
+ accountSid?: string;
6
+ authToken?: string;
7
+ fromNumber?: string;
8
+ }
9
+
10
+ export class SMSChannel extends BaseChannel {
11
+ readonly type = 'sms';
12
+ private config: SMSChannelConfig;
13
+
14
+ constructor(config: SMSChannelConfig = {}) {
15
+ super();
16
+ this.config = config;
17
+ }
18
+
19
+ async start(): Promise<void> {
20
+ try {
21
+ require('twilio');
22
+ } catch {
23
+ throw new Error('Install twilio to use the SMSChannel. Run: npm install twilio');
24
+ }
25
+ }
26
+
27
+ async stop(): Promise<void> {
28
+ // cleanup
29
+ }
30
+
31
+ async send(chatId: string, text: string): Promise<void> {
32
+ throw new Error('SMSChannel: not yet connected. Call start() first.');
33
+ }
34
+ }
@@ -0,0 +1,65 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface TwitchChannelConfig {
5
+ username: string;
6
+ oauthToken: string;
7
+ channels: string[];
8
+ }
9
+
10
+ export class TwitchChannel extends BaseChannel {
11
+ readonly type = 'twitch';
12
+ private config: TwitchChannelConfig;
13
+ private client: any = null;
14
+ private running = false;
15
+
16
+ constructor(config: TwitchChannelConfig) {
17
+ super();
18
+ if (!config.username || !config.oauthToken || !config.channels?.length) {
19
+ throw new Error('TwitchChannel requires username, oauthToken, and channels in config');
20
+ }
21
+ this.config = config;
22
+ }
23
+
24
+ async start(): Promise<void> {
25
+ let tmi: any;
26
+ try {
27
+ tmi = require('tmi.js');
28
+ } catch {
29
+ throw new Error('Install tmi.js to use the TwitchChannel. Run: npm install tmi.js');
30
+ }
31
+ this.client = new tmi.Client({
32
+ identity: { username: this.config.username, password: this.config.oauthToken },
33
+ channels: this.config.channels,
34
+ });
35
+ await this.client.connect();
36
+ this.running = true;
37
+
38
+ this.client.on('message', async (channel: string, tags: any, message: string, self: boolean) => {
39
+ if (self || !this.handler) return;
40
+ const msg: Message = {
41
+ id: tags.id || Date.now().toString(),
42
+ role: 'user',
43
+ content: message,
44
+ timestamp: Date.now(),
45
+ metadata: { channel, username: tags.username, tags },
46
+ };
47
+ await this.handler(msg);
48
+ });
49
+ }
50
+
51
+ async stop(): Promise<void> {
52
+ if (this.client) {
53
+ await this.client.disconnect();
54
+ this.client = null;
55
+ }
56
+ this.running = false;
57
+ }
58
+
59
+ async send(channel: string, text: string): Promise<void> {
60
+ if (!this.running || !this.client) {
61
+ throw new Error('TwitchChannel: not started. Call start() first.');
62
+ }
63
+ await this.client.say(channel, text);
64
+ }
65
+ }
@@ -0,0 +1,100 @@
1
+ import { EventEmitter } from 'events';
2
+ import { randomUUID } from 'crypto';
3
+
4
+ export interface VoiceCallConfig {
5
+ provider: 'twilio' | 'vonage' | 'webrtc' | 'sip';
6
+ credentials?: Record<string, string>;
7
+ sttProvider?: string;
8
+ ttsProvider?: string;
9
+ }
10
+
11
+ interface ActiveCall {
12
+ callId: string;
13
+ from: string;
14
+ to: string;
15
+ status: 'ringing' | 'active' | 'ended';
16
+ startedAt: number;
17
+ }
18
+
19
+ export class VoiceCallManager extends EventEmitter {
20
+ private config: VoiceCallConfig;
21
+ private calls = new Map<string, ActiveCall>();
22
+ private audioListeners = new Map<string, ((audio: Buffer) => void)[]>();
23
+
24
+ constructor(config: VoiceCallConfig) {
25
+ super();
26
+ this.config = config;
27
+ }
28
+
29
+ private ensureCredentials(): void {
30
+ if (!this.config.credentials || Object.keys(this.config.credentials).length === 0) {
31
+ throw new Error(
32
+ `Voice call provider "${this.config.provider}" requires credentials. ` +
33
+ `Please configure credentials for ${this.config.provider} in your VoiceCallConfig.`
34
+ );
35
+ }
36
+ }
37
+
38
+ async startCall(to: string): Promise<string> {
39
+ this.ensureCredentials();
40
+ const callId = randomUUID();
41
+ const call: ActiveCall = {
42
+ callId,
43
+ from: 'self',
44
+ to,
45
+ status: 'ringing',
46
+ startedAt: Date.now(),
47
+ };
48
+ this.calls.set(callId, call);
49
+ // Simulate connection
50
+ setTimeout(() => {
51
+ const c = this.calls.get(callId);
52
+ if (c && c.status === 'ringing') c.status = 'active';
53
+ }, 100);
54
+ return callId;
55
+ }
56
+
57
+ async endCall(callId: string): Promise<void> {
58
+ const call = this.calls.get(callId);
59
+ if (!call) throw new Error(`Call ${callId} not found`);
60
+ call.status = 'ended';
61
+ this.audioListeners.delete(callId);
62
+ }
63
+
64
+ onIncoming(callback: (callId: string, from: string) => void): void {
65
+ this.on('incoming', callback);
66
+ }
67
+
68
+ simulateIncoming(from: string): string {
69
+ const callId = randomUUID();
70
+ const call: ActiveCall = { callId, from, to: 'self', status: 'ringing', startedAt: Date.now() };
71
+ this.calls.set(callId, call);
72
+ this.emit('incoming', callId, from);
73
+ return callId;
74
+ }
75
+
76
+ async sendAudio(callId: string, audio: Buffer): Promise<void> {
77
+ const call = this.calls.get(callId);
78
+ if (!call) throw new Error(`Call ${callId} not found`);
79
+ if (call.status !== 'active') throw new Error(`Call ${callId} is not active`);
80
+ // Stub: would send audio to provider
81
+ }
82
+
83
+ onAudio(callId: string, callback: (audio: Buffer) => void): void {
84
+ const listeners = this.audioListeners.get(callId) || [];
85
+ listeners.push(callback);
86
+ this.audioListeners.set(callId, listeners);
87
+ }
88
+
89
+ getCallStatus(callId: string): 'ringing' | 'active' | 'ended' {
90
+ const call = this.calls.get(callId);
91
+ if (!call) throw new Error(`Call ${callId} not found`);
92
+ return call.status;
93
+ }
94
+
95
+ listActiveCalls(): Array<{ callId: string; from: string; startedAt: number }> {
96
+ return Array.from(this.calls.values())
97
+ .filter(c => c.status !== 'ended')
98
+ .map(({ callId, from, startedAt }) => ({ callId, from, startedAt }));
99
+ }
100
+ }
@@ -0,0 +1,33 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ export interface WhatsAppChannelConfig {
5
+ phoneNumber?: string;
6
+ authDir?: string;
7
+ }
8
+
9
+ export class WhatsAppChannel extends BaseChannel {
10
+ readonly type = 'whatsapp';
11
+ private config: WhatsAppChannelConfig;
12
+
13
+ constructor(config: WhatsAppChannelConfig = {}) {
14
+ super();
15
+ this.config = config;
16
+ }
17
+
18
+ async start(): Promise<void> {
19
+ try {
20
+ require('@whiskeysockets/baileys');
21
+ } catch {
22
+ throw new Error('Install @whiskeysockets/baileys to use the WhatsAppChannel. Run: npm install @whiskeysockets/baileys');
23
+ }
24
+ }
25
+
26
+ async stop(): Promise<void> {
27
+ // cleanup
28
+ }
29
+
30
+ async send(chatId: string, text: string): Promise<void> {
31
+ throw new Error('WhatsAppChannel: not yet connected. Call start() first.');
32
+ }
33
+ }
package/src/cli.ts CHANGED
@@ -901,6 +901,46 @@ program
901
901
  console.log(`\n ${color.dim('Press Ctrl+C to stop.')}\n`);
902
902
  });
903
903
 
904
+ // ── Serve command (OpenAI-compatible API) ────────────────────
905
+
906
+ program
907
+ .command('serve')
908
+ .description('Start OpenAI-compatible API server')
909
+ .option('-f, --file <file>', 'OAD file', 'oad.yaml')
910
+ .option('-p, --port <port>', 'Port', '8080')
911
+ .option('-H, --host <host>', 'Host', '0.0.0.0')
912
+ .option('-k, --api-key <key>', 'API key for auth')
913
+ .action(async (opts: { file: string; port: string; host: string; apiKey?: string }) => {
914
+ loadDotEnv();
915
+ const { APIServer } = require('./core/api-server');
916
+ const runtime = new AgentRuntime();
917
+ await runtime.loadConfig(opts.file);
918
+ await runtime.initialize();
919
+ await runtime.start();
920
+ const agent = runtime.getAgent();
921
+
922
+ const server = new APIServer({
923
+ port: parseInt(opts.port) || 8080,
924
+ host: opts.host,
925
+ apiKey: opts.apiKey ?? process.env.OPC_API_KEY,
926
+ agent,
927
+ });
928
+ await server.start();
929
+
930
+ const name = agent?.name ?? 'unknown';
931
+ console.log(`\n${icon.rocket} OpenAI-compatible API server running`);
932
+ console.log(` Agent: ${color.bold(name)}`);
933
+ console.log(` URL: ${color.cyan(`http://${opts.host}:${opts.port}`)}`);
934
+ console.log(` Auth: ${opts.apiKey ? color.green('enabled') : color.yellow('disabled')}`);
935
+ console.log(`\n Endpoints:`);
936
+ console.log(` POST /v1/chat/completions`);
937
+ console.log(` GET /v1/models`);
938
+ console.log(` POST /v1/embeddings`);
939
+ console.log(` GET /health`);
940
+ console.log(` GET /v1/agent/status`);
941
+ console.log(`\n ${color.dim('Press Ctrl+C to stop.')}\n`);
942
+ });
943
+
904
944
  // ── Info command ─────────────────────────────────────────────
905
945
 
906
946
  program
@@ -0,0 +1,277 @@
1
+ import * as http from 'http';
2
+ import { randomUUID } from 'crypto';
3
+
4
+ export interface APIServerConfig {
5
+ port: number;
6
+ host: string;
7
+ apiKey?: string;
8
+ agent: any;
9
+ }
10
+
11
+ interface OpenAIError {
12
+ error: { message: string; type: string; code: string | number };
13
+ }
14
+
15
+ function jsonError(message: string, type: string, code: string | number): OpenAIError {
16
+ return { error: { message, type, code } };
17
+ }
18
+
19
+ function corsHeaders(): Record<string, string> {
20
+ return {
21
+ 'Access-Control-Allow-Origin': '*',
22
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
23
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
24
+ };
25
+ }
26
+
27
+ function parseBody(req: http.IncomingMessage): Promise<string> {
28
+ return new Promise((resolve, reject) => {
29
+ const chunks: Buffer[] = [];
30
+ req.on('data', (c) => chunks.push(c));
31
+ req.on('end', () => resolve(Buffer.concat(chunks).toString()));
32
+ req.on('error', reject);
33
+ });
34
+ }
35
+
36
+ function sendJSON(res: http.ServerResponse, status: number, data: unknown): void {
37
+ const body = JSON.stringify(data);
38
+ res.writeHead(status, { ...corsHeaders(), 'Content-Type': 'application/json' });
39
+ res.end(body);
40
+ }
41
+
42
+ export class APIServer {
43
+ private server: http.Server | null = null;
44
+ private config: APIServerConfig;
45
+
46
+ constructor(config: Partial<APIServerConfig> & { agent: any }) {
47
+ this.config = {
48
+ port: config.port ?? 8080,
49
+ host: config.host ?? '0.0.0.0',
50
+ apiKey: config.apiKey,
51
+ agent: config.agent,
52
+ };
53
+ }
54
+
55
+ private authenticate(req: http.IncomingMessage): boolean {
56
+ if (!this.config.apiKey) return true;
57
+ const auth = req.headers['authorization'] ?? '';
58
+ return auth === `Bearer ${this.config.apiKey}`;
59
+ }
60
+
61
+ async start(): Promise<void> {
62
+ return new Promise((resolve) => {
63
+ this.server = http.createServer((req, res) => this.handleRequest(req, res));
64
+ this.server.listen(this.config.port, this.config.host, () => resolve());
65
+ });
66
+ }
67
+
68
+ async stop(): Promise<void> {
69
+ return new Promise((resolve) => {
70
+ if (this.server) this.server.close(() => resolve());
71
+ else resolve();
72
+ });
73
+ }
74
+
75
+ getPort(): number { return this.config.port; }
76
+ getHost(): string { return this.config.host; }
77
+
78
+ private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
79
+ const url = req.url ?? '/';
80
+ const method = req.method ?? 'GET';
81
+
82
+ // CORS preflight
83
+ if (method === 'OPTIONS') {
84
+ res.writeHead(204, corsHeaders());
85
+ res.end();
86
+ return;
87
+ }
88
+
89
+ // Health check (no auth)
90
+ if (method === 'GET' && url === '/health') {
91
+ sendJSON(res, 200, { status: 'ok', timestamp: new Date().toISOString() });
92
+ return;
93
+ }
94
+
95
+ // Auth check for all other endpoints
96
+ if (!this.authenticate(req)) {
97
+ sendJSON(res, 401, jsonError('Invalid API key', 'authentication_error', 401));
98
+ return;
99
+ }
100
+
101
+ try {
102
+ if (method === 'GET' && url === '/v1/models') {
103
+ return this.handleModels(res);
104
+ }
105
+ if (method === 'GET' && url === '/v1/agent/status') {
106
+ return this.handleAgentStatus(res);
107
+ }
108
+ if (method === 'POST' && url === '/v1/chat/completions') {
109
+ return await this.handleChatCompletions(req, res);
110
+ }
111
+ if (method === 'POST' && url === '/v1/embeddings') {
112
+ return await this.handleEmbeddings(req, res);
113
+ }
114
+
115
+ sendJSON(res, 404, jsonError('Not found', 'not_found', 404));
116
+ } catch (err) {
117
+ const msg = err instanceof Error ? err.message : String(err);
118
+ sendJSON(res, 500, jsonError(msg, 'internal_error', 500));
119
+ }
120
+ }
121
+
122
+ private handleModels(res: http.ServerResponse): void {
123
+ const agent = this.config.agent;
124
+ const modelId = agent?.config?.model ?? agent?.model ?? 'default';
125
+ sendJSON(res, 200, {
126
+ object: 'list',
127
+ data: [{ id: modelId, object: 'model', created: Math.floor(Date.now() / 1000), owned_by: 'opc-agent' }],
128
+ });
129
+ }
130
+
131
+ private handleAgentStatus(res: http.ServerResponse): void {
132
+ const agent = this.config.agent;
133
+ sendJSON(res, 200, {
134
+ name: agent?.name ?? agent?.config?.name ?? 'unknown',
135
+ state: agent?.state ?? 'unknown',
136
+ uptime: process.uptime(),
137
+ });
138
+ }
139
+
140
+ private async handleChatCompletions(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
141
+ let body: any;
142
+ try {
143
+ body = JSON.parse(await parseBody(req));
144
+ } catch {
145
+ sendJSON(res, 400, jsonError('Invalid JSON body', 'invalid_request_error', 400));
146
+ return;
147
+ }
148
+
149
+ const { model, messages, temperature, max_tokens, stream, tools } = body;
150
+ if (!messages || !Array.isArray(messages)) {
151
+ sendJSON(res, 400, jsonError('messages is required and must be an array', 'invalid_request_error', 400));
152
+ return;
153
+ }
154
+
155
+ const agent = this.config.agent;
156
+ const requestId = `chatcmpl-${randomUUID().replace(/-/g, '').slice(0, 24)}`;
157
+ const modelId = model ?? agent?.config?.model ?? agent?.model ?? 'default';
158
+
159
+ if (stream) {
160
+ // SSE streaming
161
+ res.writeHead(200, {
162
+ ...corsHeaders(),
163
+ 'Content-Type': 'text/event-stream',
164
+ 'Cache-Control': 'no-cache',
165
+ 'Connection': 'keep-alive',
166
+ });
167
+
168
+ try {
169
+ const responseText = await this.getAgentResponse(agent, messages, { temperature, max_tokens, tools });
170
+ // Stream in chunks
171
+ const chunkSize = 10;
172
+ for (let i = 0; i < responseText.length; i += chunkSize) {
173
+ const delta = responseText.slice(i, i + chunkSize);
174
+ const chunk = {
175
+ id: requestId,
176
+ object: 'chat.completion.chunk',
177
+ created: Math.floor(Date.now() / 1000),
178
+ model: modelId,
179
+ choices: [{ index: 0, delta: { content: delta }, finish_reason: null }],
180
+ };
181
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
182
+ }
183
+ // Final chunk
184
+ const finalChunk = {
185
+ id: requestId,
186
+ object: 'chat.completion.chunk',
187
+ created: Math.floor(Date.now() / 1000),
188
+ model: modelId,
189
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
190
+ };
191
+ res.write(`data: ${JSON.stringify(finalChunk)}\n\n`);
192
+ res.write('data: [DONE]\n\n');
193
+ } catch (err) {
194
+ const errMsg = err instanceof Error ? err.message : String(err);
195
+ res.write(`data: ${JSON.stringify({ error: { message: errMsg } })}\n\n`);
196
+ }
197
+ res.end();
198
+ } else {
199
+ // Non-streaming
200
+ const responseText = await this.getAgentResponse(agent, messages, { temperature, max_tokens, tools });
201
+ sendJSON(res, 200, {
202
+ id: requestId,
203
+ object: 'chat.completion',
204
+ created: Math.floor(Date.now() / 1000),
205
+ model: modelId,
206
+ choices: [{
207
+ index: 0,
208
+ message: { role: 'assistant', content: responseText },
209
+ finish_reason: 'stop',
210
+ }],
211
+ usage: {
212
+ prompt_tokens: messages.reduce((a: number, m: any) => a + (m.content?.length ?? 0), 0),
213
+ completion_tokens: responseText.length,
214
+ total_tokens: messages.reduce((a: number, m: any) => a + (m.content?.length ?? 0), 0) + responseText.length,
215
+ },
216
+ });
217
+ }
218
+ }
219
+
220
+ private async getAgentResponse(agent: any, messages: any[], options: any): Promise<string> {
221
+ // Try various agent interfaces
222
+ if (agent?.chat) {
223
+ const lastUserMsg = [...messages].reverse().find((m: any) => m.role === 'user');
224
+ return await agent.chat(lastUserMsg?.content ?? '', options);
225
+ }
226
+ if (agent?.processMessage) {
227
+ const lastUserMsg = [...messages].reverse().find((m: any) => m.role === 'user');
228
+ const result = await agent.processMessage({ id: 'api', role: 'user', content: lastUserMsg?.content ?? '', timestamp: Date.now() });
229
+ return result?.response ?? result?.content ?? String(result);
230
+ }
231
+ if (agent?.provider?.chat) {
232
+ const formatted = messages.map((m: any) => ({ id: 'x', role: m.role, content: m.content, timestamp: Date.now() }));
233
+ return await agent.provider.chat(formatted, agent.systemPrompt ?? '');
234
+ }
235
+ return 'Agent does not support chat interface';
236
+ }
237
+
238
+ private async handleEmbeddings(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
239
+ let body: any;
240
+ try {
241
+ body = JSON.parse(await parseBody(req));
242
+ } catch {
243
+ sendJSON(res, 400, jsonError('Invalid JSON body', 'invalid_request_error', 400));
244
+ return;
245
+ }
246
+
247
+ const { input, model } = body;
248
+ if (!input) {
249
+ sendJSON(res, 400, jsonError('input is required', 'invalid_request_error', 400));
250
+ return;
251
+ }
252
+
253
+ const agent = this.config.agent;
254
+ const inputs = Array.isArray(input) ? input : [input];
255
+
256
+ try {
257
+ if (agent?.embed || agent?.provider?.embed) {
258
+ const embedFn = agent.embed?.bind(agent) ?? agent.provider.embed.bind(agent.provider);
259
+ const data = await Promise.all(inputs.map(async (text: string, i: number) => {
260
+ const embedding = await embedFn(text);
261
+ return { object: 'embedding', embedding, index: i };
262
+ }));
263
+ sendJSON(res, 200, {
264
+ object: 'list',
265
+ data,
266
+ model: model ?? 'default',
267
+ usage: { prompt_tokens: inputs.join('').length, total_tokens: inputs.join('').length },
268
+ });
269
+ } else {
270
+ sendJSON(res, 501, jsonError('Embedding provider not configured', 'not_implemented', 501));
271
+ }
272
+ } catch (err) {
273
+ const msg = err instanceof Error ? err.message : String(err);
274
+ sendJSON(res, 500, jsonError(msg, 'internal_error', 500));
275
+ }
276
+ }
277
+ }