opc-agent 0.2.0 → 0.4.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.
- package/dist/analytics/index.d.ts +31 -0
- package/dist/analytics/index.js +52 -0
- package/dist/channels/voice.d.ts +43 -0
- package/dist/channels/voice.js +67 -0
- package/dist/channels/webhook.d.ts +40 -0
- package/dist/channels/webhook.js +193 -0
- package/dist/cli.js +157 -13
- package/dist/core/a2a.d.ts +46 -0
- package/dist/core/a2a.js +99 -0
- package/dist/core/hitl.d.ts +41 -0
- package/dist/core/hitl.js +100 -0
- package/dist/core/performance.d.ts +50 -0
- package/dist/core/performance.js +148 -0
- package/dist/core/room.d.ts +24 -0
- package/dist/core/room.js +97 -0
- package/dist/core/sandbox.d.ts +28 -0
- package/dist/core/sandbox.js +118 -0
- package/dist/core/versioning.d.ts +29 -0
- package/dist/core/versioning.js +114 -0
- package/dist/core/workflow.d.ts +59 -0
- package/dist/core/workflow.js +174 -0
- package/dist/i18n/index.d.ts +13 -0
- package/dist/i18n/index.js +73 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +36 -1
- package/dist/plugins/index.d.ts +47 -0
- package/dist/plugins/index.js +59 -0
- package/dist/schema/oad.d.ts +483 -15
- package/dist/schema/oad.js +53 -2
- package/dist/templates/content-writer.d.ts +36 -0
- package/dist/templates/content-writer.js +52 -0
- package/dist/templates/executive-assistant.d.ts +20 -0
- package/dist/templates/executive-assistant.js +70 -0
- package/dist/templates/financial-advisor.d.ts +15 -0
- package/dist/templates/financial-advisor.js +60 -0
- package/dist/templates/hr-recruiter.d.ts +36 -0
- package/dist/templates/hr-recruiter.js +52 -0
- package/dist/templates/legal-assistant.d.ts +15 -0
- package/dist/templates/legal-assistant.js +70 -0
- package/dist/templates/project-manager.d.ts +36 -0
- package/dist/templates/project-manager.js +52 -0
- package/dist/tools/mcp.d.ts +32 -0
- package/dist/tools/mcp.js +49 -0
- package/package.json +46 -46
- package/src/analytics/index.ts +66 -0
- package/src/channels/voice.ts +106 -0
- package/src/channels/webhook.ts +199 -0
- package/src/cli.ts +173 -16
- package/src/core/a2a.ts +143 -0
- package/src/core/hitl.ts +138 -0
- package/src/core/performance.ts +187 -0
- package/src/core/room.ts +109 -0
- package/src/core/sandbox.ts +101 -0
- package/src/core/versioning.ts +106 -0
- package/src/core/workflow.ts +235 -0
- package/src/i18n/index.ts +79 -0
- package/src/index.ts +29 -0
- package/src/plugins/index.ts +87 -0
- package/src/schema/oad.ts +59 -1
- package/src/templates/content-writer.ts +58 -0
- package/src/templates/executive-assistant.ts +71 -0
- package/src/templates/financial-advisor.ts +60 -0
- package/src/templates/hr-recruiter.ts +58 -0
- package/src/templates/legal-assistant.ts +71 -0
- package/src/templates/project-manager.ts +58 -0
- package/src/tools/mcp.ts +76 -0
- package/tests/a2a.test.ts +66 -0
- package/tests/analytics.test.ts +50 -0
- package/tests/hitl.test.ts +71 -0
- package/tests/i18n.test.ts +41 -0
- package/tests/mcp.test.ts +54 -0
- package/tests/performance.test.ts +115 -0
- package/tests/plugin.test.ts +74 -0
- package/tests/room.test.ts +106 -0
- package/tests/sandbox.test.ts +46 -0
- package/tests/templates.test.ts +77 -0
- package/tests/versioning.test.ts +75 -0
- package/tests/voice.test.ts +61 -0
- package/tests/webhook.test.ts +29 -0
- package/tests/workflow.test.ts +143 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MCPToolRegistry = void 0;
|
|
4
|
+
exports.createMCPTool = createMCPTool;
|
|
5
|
+
class MCPToolRegistry {
|
|
6
|
+
tools = new Map();
|
|
7
|
+
register(tool) {
|
|
8
|
+
this.tools.set(tool.name, tool);
|
|
9
|
+
}
|
|
10
|
+
unregister(name) {
|
|
11
|
+
this.tools.delete(name);
|
|
12
|
+
}
|
|
13
|
+
get(name) {
|
|
14
|
+
return this.tools.get(name);
|
|
15
|
+
}
|
|
16
|
+
list() {
|
|
17
|
+
return Array.from(this.tools.values()).map(({ name, description, inputSchema }) => ({
|
|
18
|
+
name,
|
|
19
|
+
description,
|
|
20
|
+
inputSchema,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
has(name) {
|
|
24
|
+
return this.tools.has(name);
|
|
25
|
+
}
|
|
26
|
+
async execute(name, input, context) {
|
|
27
|
+
const tool = this.tools.get(name);
|
|
28
|
+
if (!tool) {
|
|
29
|
+
return { content: `Tool '${name}' not found`, isError: true };
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
return await tool.execute(input, context);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
return {
|
|
36
|
+
content: `Tool execution error: ${err instanceof Error ? err.message : String(err)}`,
|
|
37
|
+
isError: true,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.MCPToolRegistry = MCPToolRegistry;
|
|
43
|
+
/**
|
|
44
|
+
* Create an MCP tool from a simple function.
|
|
45
|
+
*/
|
|
46
|
+
function createMCPTool(name, description, inputSchema, executeFn) {
|
|
47
|
+
return { name, description, inputSchema, execute: executeFn };
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=mcp.js.map
|
package/package.json
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "opc-agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
|
|
5
|
-
"main": "dist/index.js",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
7
|
-
"bin": {
|
|
8
|
-
"opc": "dist/cli.js"
|
|
9
|
-
},
|
|
10
|
-
"scripts": {
|
|
11
|
-
"build": "tsc",
|
|
12
|
-
"test": "vitest run",
|
|
13
|
-
"dev": "tsc --watch",
|
|
14
|
-
"lint": "tsc --noEmit"
|
|
15
|
-
},
|
|
16
|
-
"keywords": [
|
|
17
|
-
"agent",
|
|
18
|
-
"ai",
|
|
19
|
-
"llm",
|
|
20
|
-
"framework",
|
|
21
|
-
"typescript",
|
|
22
|
-
"agent-framework"
|
|
23
|
-
],
|
|
24
|
-
"author": "Deepleaper",
|
|
25
|
-
"license": "Apache-2.0",
|
|
26
|
-
"repository": {
|
|
27
|
-
"type": "git",
|
|
28
|
-
"url": "https://github.com/Deepleaper/opc-agent.git"
|
|
29
|
-
},
|
|
30
|
-
"dependencies": {
|
|
31
|
-
"agentkits": "^0.1.0",
|
|
32
|
-
"commander": "^12.0.0",
|
|
33
|
-
"express": "^4.21.0",
|
|
34
|
-
"js-yaml": "^4.1.0",
|
|
35
|
-
"ws": "^8.20.0",
|
|
36
|
-
"zod": "^3.23.0"
|
|
37
|
-
},
|
|
38
|
-
"devDependencies": {
|
|
39
|
-
"@types/express": "^4.17.21",
|
|
40
|
-
"@types/js-yaml": "^4.0.9",
|
|
41
|
-
"@types/node": "^20.11.0",
|
|
42
|
-
"@types/ws": "^8.18.1",
|
|
43
|
-
"typescript": "^5.5.0",
|
|
44
|
-
"vitest": "^2.0.0"
|
|
45
|
-
}
|
|
46
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "opc-agent",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"opc": "dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"test": "vitest run",
|
|
13
|
+
"dev": "tsc --watch",
|
|
14
|
+
"lint": "tsc --noEmit"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"agent",
|
|
18
|
+
"ai",
|
|
19
|
+
"llm",
|
|
20
|
+
"framework",
|
|
21
|
+
"typescript",
|
|
22
|
+
"agent-framework"
|
|
23
|
+
],
|
|
24
|
+
"author": "Deepleaper",
|
|
25
|
+
"license": "Apache-2.0",
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "https://github.com/Deepleaper/opc-agent.git"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"agentkits": "^0.1.0",
|
|
32
|
+
"commander": "^12.0.0",
|
|
33
|
+
"express": "^4.21.0",
|
|
34
|
+
"js-yaml": "^4.1.0",
|
|
35
|
+
"ws": "^8.20.0",
|
|
36
|
+
"zod": "^3.23.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/express": "^4.17.21",
|
|
40
|
+
"@types/js-yaml": "^4.0.9",
|
|
41
|
+
"@types/node": "^20.11.0",
|
|
42
|
+
"@types/ws": "^8.18.1",
|
|
43
|
+
"typescript": "^5.5.0",
|
|
44
|
+
"vitest": "^2.0.0"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Analytics — track messages, response times, skill usage, errors, tokens.
|
|
3
|
+
*/
|
|
4
|
+
export interface AnalyticsSnapshot {
|
|
5
|
+
messagesProcessed: number;
|
|
6
|
+
avgResponseTimeMs: number;
|
|
7
|
+
skillUsage: Record<string, number>;
|
|
8
|
+
errorCount: number;
|
|
9
|
+
tokenUsage: { input: number; output: number; total: number };
|
|
10
|
+
uptime: number;
|
|
11
|
+
startedAt: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class Analytics {
|
|
15
|
+
private messagesProcessed = 0;
|
|
16
|
+
private totalResponseTimeMs = 0;
|
|
17
|
+
private skillUsage: Record<string, number> = {};
|
|
18
|
+
private errorCount = 0;
|
|
19
|
+
private tokenUsage = { input: 0, output: 0 };
|
|
20
|
+
private startedAt = Date.now();
|
|
21
|
+
|
|
22
|
+
recordMessage(responseTimeMs: number): void {
|
|
23
|
+
this.messagesProcessed++;
|
|
24
|
+
this.totalResponseTimeMs += responseTimeMs;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
recordSkillUsage(skillName: string): void {
|
|
28
|
+
this.skillUsage[skillName] = (this.skillUsage[skillName] ?? 0) + 1;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
recordError(): void {
|
|
32
|
+
this.errorCount++;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
recordTokens(input: number, output: number): void {
|
|
36
|
+
this.tokenUsage.input += input;
|
|
37
|
+
this.tokenUsage.output += output;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
getSnapshot(): AnalyticsSnapshot {
|
|
41
|
+
return {
|
|
42
|
+
messagesProcessed: this.messagesProcessed,
|
|
43
|
+
avgResponseTimeMs: this.messagesProcessed > 0
|
|
44
|
+
? Math.round(this.totalResponseTimeMs / this.messagesProcessed)
|
|
45
|
+
: 0,
|
|
46
|
+
skillUsage: { ...this.skillUsage },
|
|
47
|
+
errorCount: this.errorCount,
|
|
48
|
+
tokenUsage: {
|
|
49
|
+
input: this.tokenUsage.input,
|
|
50
|
+
output: this.tokenUsage.output,
|
|
51
|
+
total: this.tokenUsage.input + this.tokenUsage.output,
|
|
52
|
+
},
|
|
53
|
+
uptime: Date.now() - this.startedAt,
|
|
54
|
+
startedAt: this.startedAt,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
reset(): void {
|
|
59
|
+
this.messagesProcessed = 0;
|
|
60
|
+
this.totalResponseTimeMs = 0;
|
|
61
|
+
this.skillUsage = {};
|
|
62
|
+
this.errorCount = 0;
|
|
63
|
+
this.tokenUsage = { input: 0, output: 0 };
|
|
64
|
+
this.startedAt = Date.now();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { BaseChannel } from './index';
|
|
2
|
+
import type { Message } from '../core/types';
|
|
3
|
+
import { Logger } from '../core/logger';
|
|
4
|
+
|
|
5
|
+
// ── Voice Channel Types ─────────────────────────────────────
|
|
6
|
+
|
|
7
|
+
export interface STTProvider {
|
|
8
|
+
name: string;
|
|
9
|
+
transcribe(audio: Buffer, options?: STTOptions): Promise<string>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface TTSProvider {
|
|
13
|
+
name: string;
|
|
14
|
+
synthesize(text: string, options?: TTSOptions): Promise<Buffer>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface STTOptions {
|
|
18
|
+
language?: string;
|
|
19
|
+
model?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface TTSOptions {
|
|
23
|
+
voice?: string;
|
|
24
|
+
speed?: number;
|
|
25
|
+
language?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface VoiceChannelConfig {
|
|
29
|
+
sttProvider?: STTProvider;
|
|
30
|
+
ttsProvider?: TTSProvider;
|
|
31
|
+
sampleRate?: number;
|
|
32
|
+
language?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ── Voice Channel ───────────────────────────────────────────
|
|
36
|
+
|
|
37
|
+
export class VoiceChannel extends BaseChannel {
|
|
38
|
+
type = 'voice';
|
|
39
|
+
private config: VoiceChannelConfig;
|
|
40
|
+
private logger = new Logger('voice-channel');
|
|
41
|
+
private running = false;
|
|
42
|
+
|
|
43
|
+
constructor(config?: VoiceChannelConfig) {
|
|
44
|
+
super();
|
|
45
|
+
this.config = config ?? {};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async start(): Promise<void> {
|
|
49
|
+
this.running = true;
|
|
50
|
+
this.logger.info('Voice channel started', {
|
|
51
|
+
stt: this.config.sttProvider?.name ?? 'none',
|
|
52
|
+
tts: this.config.ttsProvider?.name ?? 'none',
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async stop(): Promise<void> {
|
|
57
|
+
this.running = false;
|
|
58
|
+
this.logger.info('Voice channel stopped');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
isRunning(): boolean {
|
|
62
|
+
return this.running;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Process audio input: STT → Agent → TTS */
|
|
66
|
+
async processAudio(audio: Buffer): Promise<{ text: string; response: string; audioResponse?: Buffer }> {
|
|
67
|
+
if (!this.handler) throw new Error('No message handler set');
|
|
68
|
+
|
|
69
|
+
// STT
|
|
70
|
+
let text: string;
|
|
71
|
+
if (this.config.sttProvider) {
|
|
72
|
+
text = await this.config.sttProvider.transcribe(audio, { language: this.config.language });
|
|
73
|
+
} else {
|
|
74
|
+
text = audio.toString('utf-8'); // Fallback: treat as text
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
this.logger.debug('STT result', { text });
|
|
78
|
+
|
|
79
|
+
// Create message and send to agent
|
|
80
|
+
const message: Message = {
|
|
81
|
+
id: `voice_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
82
|
+
role: 'user',
|
|
83
|
+
content: text,
|
|
84
|
+
timestamp: Date.now(),
|
|
85
|
+
metadata: { channel: 'voice' },
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const response = await this.handler(message);
|
|
89
|
+
|
|
90
|
+
// TTS
|
|
91
|
+
let audioResponse: Buffer | undefined;
|
|
92
|
+
if (this.config.ttsProvider) {
|
|
93
|
+
audioResponse = await this.config.ttsProvider.synthesize(response.content, { language: this.config.language });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { text, response: response.content, audioResponse };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
setSTTProvider(provider: STTProvider): void {
|
|
100
|
+
this.config.sttProvider = provider;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
setTTSProvider(provider: TTSProvider): void {
|
|
104
|
+
this.config.ttsProvider = provider;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { BaseChannel } from './index';
|
|
2
|
+
import type { Message } from '../core/types';
|
|
3
|
+
import { Logger } from '../core/logger';
|
|
4
|
+
import * as http from 'http';
|
|
5
|
+
import * as crypto from 'crypto';
|
|
6
|
+
|
|
7
|
+
// ── Webhook Types ───────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
export interface WebhookConfig {
|
|
10
|
+
port?: number;
|
|
11
|
+
path?: string;
|
|
12
|
+
secret?: string;
|
|
13
|
+
retryAttempts?: number;
|
|
14
|
+
retryDelayMs?: number;
|
|
15
|
+
outgoing?: WebhookOutgoing[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface WebhookOutgoing {
|
|
19
|
+
name: string;
|
|
20
|
+
url: string;
|
|
21
|
+
secret?: string;
|
|
22
|
+
events: string[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface WebhookPayload {
|
|
26
|
+
event: string;
|
|
27
|
+
data: unknown;
|
|
28
|
+
timestamp: number;
|
|
29
|
+
id: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ── Webhook Channel ─────────────────────────────────────────
|
|
33
|
+
|
|
34
|
+
export class WebhookChannel extends BaseChannel {
|
|
35
|
+
type = 'webhook';
|
|
36
|
+
private config: WebhookConfig;
|
|
37
|
+
private server: http.Server | null = null;
|
|
38
|
+
private logger = new Logger('webhook-channel');
|
|
39
|
+
private outgoing: WebhookOutgoing[] = [];
|
|
40
|
+
|
|
41
|
+
constructor(config?: WebhookConfig) {
|
|
42
|
+
super();
|
|
43
|
+
this.config = config ?? {};
|
|
44
|
+
this.outgoing = config?.outgoing ?? [];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async start(): Promise<void> {
|
|
48
|
+
const port = this.config.port ?? 3100;
|
|
49
|
+
const path = this.config.path ?? '/webhook';
|
|
50
|
+
|
|
51
|
+
this.server = http.createServer(async (req, res) => {
|
|
52
|
+
if (req.url !== path || req.method !== 'POST') {
|
|
53
|
+
res.writeHead(404);
|
|
54
|
+
res.end('Not found');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const body = await this.readBody(req);
|
|
60
|
+
|
|
61
|
+
// Verify signature if secret configured
|
|
62
|
+
if (this.config.secret) {
|
|
63
|
+
const signature = req.headers['x-webhook-signature'] as string;
|
|
64
|
+
if (!this.verifySignature(body, signature, this.config.secret)) {
|
|
65
|
+
res.writeHead(401);
|
|
66
|
+
res.end('Invalid signature');
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const payload: WebhookPayload = JSON.parse(body);
|
|
72
|
+
const message: Message = {
|
|
73
|
+
id: payload.id ?? `wh_${Date.now()}`,
|
|
74
|
+
role: 'user',
|
|
75
|
+
content: typeof payload.data === 'string' ? payload.data : JSON.stringify(payload.data),
|
|
76
|
+
timestamp: payload.timestamp ?? Date.now(),
|
|
77
|
+
metadata: { channel: 'webhook', event: payload.event },
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
if (this.handler) {
|
|
81
|
+
const response = await this.handler(message);
|
|
82
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
83
|
+
res.end(JSON.stringify({ status: 'ok', response: response.content }));
|
|
84
|
+
} else {
|
|
85
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
86
|
+
res.end(JSON.stringify({ status: 'ok' }));
|
|
87
|
+
}
|
|
88
|
+
} catch (err) {
|
|
89
|
+
this.logger.error('Webhook error', { error: (err as Error).message });
|
|
90
|
+
res.writeHead(500);
|
|
91
|
+
res.end('Internal error');
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
return new Promise((resolve) => {
|
|
96
|
+
this.server!.listen(port, () => {
|
|
97
|
+
this.logger.info('Webhook channel started', { port, path });
|
|
98
|
+
resolve();
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async stop(): Promise<void> {
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
if (this.server) {
|
|
106
|
+
this.server.close(() => {
|
|
107
|
+
this.logger.info('Webhook channel stopped');
|
|
108
|
+
resolve();
|
|
109
|
+
});
|
|
110
|
+
} else {
|
|
111
|
+
resolve();
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Send a webhook to outgoing endpoints */
|
|
117
|
+
async send(event: string, data: unknown): Promise<void> {
|
|
118
|
+
const targets = this.outgoing.filter(o => o.events.includes(event) || o.events.includes('*'));
|
|
119
|
+
|
|
120
|
+
for (const target of targets) {
|
|
121
|
+
const payload: WebhookPayload = {
|
|
122
|
+
event,
|
|
123
|
+
data,
|
|
124
|
+
timestamp: Date.now(),
|
|
125
|
+
id: `wh_out_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
await this.sendWithRetry(target, payload);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async sendWithRetry(target: WebhookOutgoing, payload: WebhookPayload): Promise<void> {
|
|
133
|
+
const maxRetries = this.config.retryAttempts ?? 3;
|
|
134
|
+
const retryDelay = this.config.retryDelayMs ?? 1000;
|
|
135
|
+
const body = JSON.stringify(payload);
|
|
136
|
+
|
|
137
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
138
|
+
try {
|
|
139
|
+
await this.httpPost(target.url, body, target.secret);
|
|
140
|
+
return;
|
|
141
|
+
} catch (err) {
|
|
142
|
+
if (attempt === maxRetries) {
|
|
143
|
+
this.logger.error('Webhook delivery failed', { target: target.name, error: (err as Error).message });
|
|
144
|
+
throw err;
|
|
145
|
+
}
|
|
146
|
+
await new Promise(r => setTimeout(r, retryDelay * Math.pow(2, attempt)));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private httpPost(url: string, body: string, secret?: string): Promise<void> {
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const urlObj = new URL(url);
|
|
154
|
+
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
|
155
|
+
if (secret) {
|
|
156
|
+
headers['x-webhook-signature'] = this.createSignature(body, secret);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const req = http.request(
|
|
160
|
+
{ hostname: urlObj.hostname, port: urlObj.port, path: urlObj.pathname, method: 'POST', headers },
|
|
161
|
+
(res) => {
|
|
162
|
+
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
|
163
|
+
resolve();
|
|
164
|
+
} else {
|
|
165
|
+
reject(new Error(`HTTP ${res.statusCode}`));
|
|
166
|
+
}
|
|
167
|
+
res.resume();
|
|
168
|
+
},
|
|
169
|
+
);
|
|
170
|
+
req.on('error', reject);
|
|
171
|
+
req.write(body);
|
|
172
|
+
req.end();
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private readBody(req: http.IncomingMessage): Promise<string> {
|
|
177
|
+
return new Promise((resolve, reject) => {
|
|
178
|
+
const chunks: Buffer[] = [];
|
|
179
|
+
req.on('data', (c: Buffer) => chunks.push(c));
|
|
180
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString()));
|
|
181
|
+
req.on('error', reject);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
verifySignature(body: string, signature: string, secret: string): boolean {
|
|
186
|
+
if (!signature) return false;
|
|
187
|
+
const expected = this.createSignature(body, secret);
|
|
188
|
+
if (signature.length !== expected.length) return false;
|
|
189
|
+
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
createSignature(body: string, secret: string): string {
|
|
193
|
+
return crypto.createHmac('sha256', secret).update(body).digest('hex');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
addOutgoing(outgoing: WebhookOutgoing): void {
|
|
197
|
+
this.outgoing.push(outgoing);
|
|
198
|
+
}
|
|
199
|
+
}
|