opc-agent 0.7.0 → 0.8.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.
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TextAnalysisTool = void 0;
4
+ /**
5
+ * Text Analysis Tool — v0.8.0
6
+ * Summarize, translate (stub), sentiment analysis as an LLM function tool.
7
+ * Note: For production, connect to actual LLM/NLP APIs. This provides basic built-in analysis.
8
+ */
9
+ exports.TextAnalysisTool = {
10
+ name: 'text_analysis',
11
+ description: 'Analyze text: word count, character count, reading time, keyword extraction, basic sentiment, and language detection.',
12
+ inputSchema: {
13
+ type: 'object',
14
+ properties: {
15
+ operation: {
16
+ type: 'string',
17
+ enum: ['stats', 'keywords', 'sentiment', 'detect_language', 'truncate', 'split_sentences'],
18
+ description: 'Analysis operation to perform',
19
+ },
20
+ text: {
21
+ type: 'string',
22
+ description: 'Text to analyze',
23
+ },
24
+ maxLength: {
25
+ type: 'number',
26
+ description: 'Max length for truncate operation',
27
+ },
28
+ topN: {
29
+ type: 'number',
30
+ description: 'Number of top keywords to extract (default: 10)',
31
+ },
32
+ },
33
+ required: ['operation', 'text'],
34
+ },
35
+ async execute(input) {
36
+ try {
37
+ const op = String(input.operation);
38
+ const text = String(input.text ?? '');
39
+ switch (op) {
40
+ case 'stats': {
41
+ const words = text.split(/\s+/).filter(Boolean);
42
+ const sentences = text.split(/[.!?。!?]+/).filter(Boolean);
43
+ const readingTimeMin = Math.ceil(words.length / 200);
44
+ return {
45
+ content: JSON.stringify({
46
+ characters: text.length,
47
+ words: words.length,
48
+ sentences: sentences.length,
49
+ paragraphs: text.split(/\n\s*\n/).filter(Boolean).length,
50
+ readingTimeMinutes: readingTimeMin,
51
+ }, null, 2),
52
+ };
53
+ }
54
+ case 'keywords': {
55
+ const topN = Number(input.topN ?? 10);
56
+ const words = text.toLowerCase().replace(/[^\w\s\u4e00-\u9fff]/g, '').split(/\s+/).filter(Boolean);
57
+ const stopWords = new Set(['the', 'a', 'an', 'is', 'are', 'was', 'were', 'in', 'on', 'at', 'to', 'for', 'of', 'and', 'or', 'but', 'not', 'with', 'this', 'that', 'it', 'be', 'has', 'have', 'had', 'do', 'does', 'did', 'will', 'would', 'can', 'could', 'should', 'may', 'might', 'from', 'by', 'as', 'if', 'so', 'than']);
58
+ const freq = {};
59
+ for (const w of words) {
60
+ if (w.length < 2 || stopWords.has(w))
61
+ continue;
62
+ freq[w] = (freq[w] ?? 0) + 1;
63
+ }
64
+ const sorted = Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, topN);
65
+ return { content: JSON.stringify(sorted.map(([word, count]) => ({ word, count })), null, 2) };
66
+ }
67
+ case 'sentiment': {
68
+ // Basic lexicon-based sentiment
69
+ const positiveWords = new Set(['good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'love', 'happy', 'best', 'awesome', 'perfect', 'brilliant', 'outstanding', 'superb', 'beautiful', 'nice', 'enjoy', 'like', 'positive', 'success']);
70
+ const negativeWords = new Set(['bad', 'terrible', 'awful', 'horrible', 'hate', 'worst', 'poor', 'ugly', 'fail', 'wrong', 'sad', 'angry', 'frustrating', 'disappointing', 'negative', 'annoying', 'broken', 'useless', 'boring', 'painful']);
71
+ const words = text.toLowerCase().split(/\s+/);
72
+ let pos = 0, neg = 0;
73
+ for (const w of words) {
74
+ if (positiveWords.has(w))
75
+ pos++;
76
+ if (negativeWords.has(w))
77
+ neg++;
78
+ }
79
+ const total = pos + neg || 1;
80
+ const score = (pos - neg) / total; // -1 to 1
81
+ const label = score > 0.1 ? 'positive' : score < -0.1 ? 'negative' : 'neutral';
82
+ return {
83
+ content: JSON.stringify({ score: Math.round(score * 100) / 100, label, positive: pos, negative: neg }, null, 2),
84
+ };
85
+ }
86
+ case 'detect_language': {
87
+ // Simple heuristic
88
+ const hasChinese = /[\u4e00-\u9fff]/.test(text);
89
+ const hasJapanese = /[\u3040-\u309f\u30a0-\u30ff]/.test(text);
90
+ const hasKorean = /[\uac00-\ud7af]/.test(text);
91
+ const hasArabic = /[\u0600-\u06ff]/.test(text);
92
+ const lang = hasChinese ? 'zh' : hasJapanese ? 'ja' : hasKorean ? 'ko' : hasArabic ? 'ar' : 'en';
93
+ return { content: JSON.stringify({ detected: lang, confidence: 'heuristic' }) };
94
+ }
95
+ case 'truncate': {
96
+ const maxLen = Number(input.maxLength ?? 100);
97
+ const truncated = text.length > maxLen ? text.slice(0, maxLen) + '...' : text;
98
+ return { content: truncated };
99
+ }
100
+ case 'split_sentences': {
101
+ const sentences = text.match(/[^.!?。!?]+[.!?。!?]+/g) ?? [text];
102
+ return { content: JSON.stringify(sentences.map((s) => s.trim()), null, 2) };
103
+ }
104
+ default:
105
+ return { content: `Unknown operation: ${op}`, isError: true };
106
+ }
107
+ }
108
+ catch (err) {
109
+ return { content: `Error: ${err.message}`, isError: true };
110
+ }
111
+ },
112
+ };
113
+ //# sourceMappingURL=text-analysis.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opc-agent",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,177 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * Email Channel — v0.8.0
6
+ * IMAP polling for incoming emails, SMTP for sending replies.
7
+ * Parses email threads as conversations.
8
+ */
9
+
10
+ export interface EmailChannelConfig {
11
+ imap: {
12
+ host: string;
13
+ port: number;
14
+ user: string;
15
+ password: string;
16
+ tls?: boolean;
17
+ /** Mailbox to monitor (default: INBOX) */
18
+ mailbox?: string;
19
+ /** Poll interval in ms (default: 30000) */
20
+ pollInterval?: number;
21
+ };
22
+ smtp: {
23
+ host: string;
24
+ port: number;
25
+ user: string;
26
+ password: string;
27
+ tls?: boolean;
28
+ from: string;
29
+ };
30
+ /** Filter: only process emails matching these patterns */
31
+ filters?: {
32
+ from?: string[];
33
+ subject?: string[];
34
+ };
35
+ }
36
+
37
+ export interface EmailMessage {
38
+ messageId: string;
39
+ from: string;
40
+ to: string[];
41
+ cc?: string[];
42
+ subject: string;
43
+ body: string;
44
+ html?: string;
45
+ date: Date;
46
+ inReplyTo?: string;
47
+ references?: string[];
48
+ threadId?: string;
49
+ }
50
+
51
+ export class EmailChannel extends BaseChannel {
52
+ type = 'email';
53
+ private config: EmailChannelConfig;
54
+ private pollTimer: ReturnType<typeof setInterval> | null = null;
55
+ private running = false;
56
+ private processedIds: Set<string> = new Set();
57
+
58
+ constructor(config: EmailChannelConfig) {
59
+ super();
60
+ this.config = config;
61
+ }
62
+
63
+ async start(): Promise<void> {
64
+ this.running = true;
65
+ const interval = this.config.imap.pollInterval ?? 30000;
66
+
67
+ // Initial poll
68
+ await this.poll();
69
+
70
+ // Set up recurring poll
71
+ this.pollTimer = setInterval(() => {
72
+ if (this.running) this.poll().catch(console.error);
73
+ }, interval);
74
+ }
75
+
76
+ async stop(): Promise<void> {
77
+ this.running = false;
78
+ if (this.pollTimer) {
79
+ clearInterval(this.pollTimer);
80
+ this.pollTimer = null;
81
+ }
82
+ }
83
+
84
+ /** Poll IMAP for new emails */
85
+ private async poll(): Promise<void> {
86
+ // In production, use a library like `imapflow` or `imap-simple`
87
+ // This is the integration point — actual IMAP connection logic goes here
88
+ const emails = await this.fetchEmails();
89
+
90
+ for (const email of emails) {
91
+ if (this.processedIds.has(email.messageId)) continue;
92
+ this.processedIds.add(email.messageId);
93
+
94
+ if (!this.matchesFilters(email)) continue;
95
+
96
+ const message = this.emailToMessage(email);
97
+ if (this.handler) {
98
+ const reply = await this.handler(message);
99
+ await this.sendReply(email, reply);
100
+ }
101
+ }
102
+ }
103
+
104
+ /** Convert email to Message format */
105
+ private emailToMessage(email: EmailMessage): Message {
106
+ return {
107
+ id: email.messageId,
108
+ role: 'user',
109
+ content: email.body,
110
+ timestamp: email.date.getTime(),
111
+ metadata: {
112
+ channel: 'email',
113
+ from: email.from,
114
+ to: email.to,
115
+ subject: email.subject,
116
+ threadId: email.threadId ?? email.messageId,
117
+ inReplyTo: email.inReplyTo,
118
+ },
119
+ };
120
+ }
121
+
122
+ /** Check if email matches configured filters */
123
+ private matchesFilters(email: EmailMessage): boolean {
124
+ if (!this.config.filters) return true;
125
+
126
+ if (this.config.filters.from?.length) {
127
+ const fromMatch = this.config.filters.from.some((f) =>
128
+ email.from.toLowerCase().includes(f.toLowerCase())
129
+ );
130
+ if (!fromMatch) return false;
131
+ }
132
+
133
+ if (this.config.filters.subject?.length) {
134
+ const subjectMatch = this.config.filters.subject.some((s) =>
135
+ email.subject.toLowerCase().includes(s.toLowerCase())
136
+ );
137
+ if (!subjectMatch) return false;
138
+ }
139
+
140
+ return true;
141
+ }
142
+
143
+ /** Fetch emails via IMAP — stub for actual implementation */
144
+ private async fetchEmails(): Promise<EmailMessage[]> {
145
+ // TODO: Implement with imapflow or similar library
146
+ // const { ImapFlow } = await import('imapflow');
147
+ // const client = new ImapFlow({ ...this.config.imap });
148
+ // await client.connect();
149
+ // ...
150
+ return [];
151
+ }
152
+
153
+ /** Send reply via SMTP — stub for actual implementation */
154
+ async sendReply(originalEmail: EmailMessage, reply: Message): Promise<void> {
155
+ // TODO: Implement with nodemailer or similar library
156
+ // const nodemailer = await import('nodemailer');
157
+ // const transport = nodemailer.createTransport({ ...this.config.smtp });
158
+ // await transport.sendMail({
159
+ // from: this.config.smtp.from,
160
+ // to: originalEmail.from,
161
+ // subject: `Re: ${originalEmail.subject}`,
162
+ // text: reply.content,
163
+ // inReplyTo: originalEmail.messageId,
164
+ // references: [originalEmail.messageId],
165
+ // });
166
+ void originalEmail;
167
+ void reply;
168
+ }
169
+
170
+ /** Send a standalone email */
171
+ async send(to: string, subject: string, body: string): Promise<void> {
172
+ void to;
173
+ void subject;
174
+ void body;
175
+ // TODO: Implement with nodemailer
176
+ }
177
+ }
@@ -0,0 +1,160 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * Slack Channel — v0.8.0
6
+ * Slack Bot with Socket Mode / Events API support, threads, and slash commands.
7
+ */
8
+
9
+ export interface SlackChannelConfig {
10
+ /** Bot token (xoxb-...) */
11
+ botToken: string;
12
+ /** App-level token for Socket Mode (xapp-...) */
13
+ appToken?: string;
14
+ /** Signing secret for Events API verification */
15
+ signingSecret?: string;
16
+ /** Use Socket Mode (true) or Events API (false) */
17
+ socketMode?: boolean;
18
+ /** Port for Events API webhook server (default: 3001) */
19
+ port?: number;
20
+ /** Slash commands to register */
21
+ slashCommands?: SlashCommandConfig[];
22
+ }
23
+
24
+ export interface SlashCommandConfig {
25
+ command: string;
26
+ description: string;
27
+ handler?: (payload: SlashCommandPayload) => Promise<string>;
28
+ }
29
+
30
+ export interface SlashCommandPayload {
31
+ command: string;
32
+ text: string;
33
+ userId: string;
34
+ channelId: string;
35
+ triggerId: string;
36
+ }
37
+
38
+ export interface SlackMessageEvent {
39
+ type: string;
40
+ channel: string;
41
+ user: string;
42
+ text: string;
43
+ ts: string;
44
+ threadTs?: string;
45
+ botId?: string;
46
+ }
47
+
48
+ export class SlackChannel extends BaseChannel {
49
+ type = 'slack';
50
+ private config: SlackChannelConfig;
51
+ private running = false;
52
+ private slashHandlers: Map<string, SlashCommandConfig> = new Map();
53
+
54
+ constructor(config: SlackChannelConfig) {
55
+ super();
56
+ this.config = config;
57
+
58
+ for (const cmd of config.slashCommands ?? []) {
59
+ this.slashHandlers.set(cmd.command, cmd);
60
+ }
61
+ }
62
+
63
+ async start(): Promise<void> {
64
+ this.running = true;
65
+
66
+ if (this.config.socketMode && this.config.appToken) {
67
+ await this.startSocketMode();
68
+ } else {
69
+ await this.startEventsAPI();
70
+ }
71
+ }
72
+
73
+ async stop(): Promise<void> {
74
+ this.running = false;
75
+ // Cleanup connections
76
+ }
77
+
78
+ /** Start Socket Mode connection */
79
+ private async startSocketMode(): Promise<void> {
80
+ // TODO: Implement with @slack/socket-mode
81
+ // const { SocketModeClient } = await import('@slack/socket-mode');
82
+ // const client = new SocketModeClient({ appToken: this.config.appToken! });
83
+ // client.on('message', (event) => this.handleMessage(event));
84
+ // await client.start();
85
+ }
86
+
87
+ /** Start Events API HTTP server */
88
+ private async startEventsAPI(): Promise<void> {
89
+ // TODO: Implement with express or http
90
+ // const port = this.config.port ?? 3001;
91
+ // Listen for POST /slack/events and /slack/commands
92
+ }
93
+
94
+ /** Handle incoming Slack message */
95
+ async handleMessage(event: SlackMessageEvent): Promise<void> {
96
+ // Ignore bot messages
97
+ if (event.botId) return;
98
+
99
+ const message = this.slackToMessage(event);
100
+ if (this.handler) {
101
+ const reply = await this.handler(message);
102
+ await this.sendMessage(event.channel, reply.content, event.threadTs ?? event.ts);
103
+ }
104
+ }
105
+
106
+ /** Handle slash command */
107
+ async handleSlashCommand(payload: SlashCommandPayload): Promise<string> {
108
+ const cmd = this.slashHandlers.get(payload.command);
109
+ if (cmd?.handler) {
110
+ return cmd.handler(payload);
111
+ }
112
+
113
+ // Default: pass to message handler
114
+ const message: Message = {
115
+ id: `slack-cmd-${Date.now()}`,
116
+ role: 'user',
117
+ content: `${payload.command} ${payload.text}`.trim(),
118
+ timestamp: Date.now(),
119
+ metadata: {
120
+ channel: 'slack',
121
+ channelId: payload.channelId,
122
+ userId: payload.userId,
123
+ isSlashCommand: true,
124
+ },
125
+ };
126
+
127
+ if (this.handler) {
128
+ const reply = await this.handler(message);
129
+ return reply.content;
130
+ }
131
+ return 'Command received.';
132
+ }
133
+
134
+ /** Convert Slack event to Message */
135
+ private slackToMessage(event: SlackMessageEvent): Message {
136
+ return {
137
+ id: event.ts,
138
+ role: 'user',
139
+ content: event.text,
140
+ timestamp: parseFloat(event.ts) * 1000,
141
+ metadata: {
142
+ channel: 'slack',
143
+ channelId: event.channel,
144
+ userId: event.user,
145
+ threadTs: event.threadTs,
146
+ },
147
+ };
148
+ }
149
+
150
+ /** Send a message to a Slack channel */
151
+ async sendMessage(channel: string, text: string, threadTs?: string): Promise<void> {
152
+ // TODO: Implement with @slack/web-api
153
+ // const { WebClient } = await import('@slack/web-api');
154
+ // const client = new WebClient(this.config.botToken);
155
+ // await client.chat.postMessage({ channel, text, thread_ts: threadTs });
156
+ void channel;
157
+ void text;
158
+ void threadTs;
159
+ }
160
+ }
@@ -0,0 +1,149 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * WeChat Channel (Stub) — v0.8.0
6
+ * WeChat Official Account message handling, template messages, QR code login.
7
+ */
8
+
9
+ export interface WeChatChannelConfig {
10
+ /** WeChat Official Account AppID */
11
+ appId: string;
12
+ /** WeChat Official Account AppSecret */
13
+ appSecret: string;
14
+ /** Verification token for message validation */
15
+ token: string;
16
+ /** AES encoding key for encrypted messages */
17
+ encodingAESKey?: string;
18
+ /** HTTP server port (default: 3002) */
19
+ port?: number;
20
+ }
21
+
22
+ export interface WeChatMessage {
23
+ toUserName: string;
24
+ fromUserName: string;
25
+ createTime: number;
26
+ msgType: 'text' | 'image' | 'voice' | 'video' | 'event';
27
+ content?: string;
28
+ msgId?: string;
29
+ event?: string;
30
+ eventKey?: string;
31
+ }
32
+
33
+ export interface TemplateMessageData {
34
+ toUser: string;
35
+ templateId: string;
36
+ url?: string;
37
+ data: Record<string, { value: string; color?: string }>;
38
+ }
39
+
40
+ export class WeChatChannel extends BaseChannel {
41
+ type = 'wechat';
42
+ private config: WeChatChannelConfig;
43
+ private accessToken: string | null = null;
44
+ private tokenExpiry = 0;
45
+
46
+ constructor(config: WeChatChannelConfig) {
47
+ super();
48
+ this.config = config;
49
+ }
50
+
51
+ async start(): Promise<void> {
52
+ // TODO: Start HTTP server to receive WeChat push messages
53
+ // 1. Verify signature on GET requests
54
+ // 2. Parse XML messages on POST requests
55
+ // 3. Route to handler and reply with XML
56
+ }
57
+
58
+ async stop(): Promise<void> {
59
+ // TODO: Stop HTTP server
60
+ }
61
+
62
+ /** Get or refresh access token */
63
+ async getAccessToken(): Promise<string> {
64
+ if (this.accessToken && Date.now() < this.tokenExpiry) {
65
+ return this.accessToken;
66
+ }
67
+
68
+ // TODO: Implement token refresh
69
+ // const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
70
+ // const res = await fetch(url);
71
+ // const data = await res.json();
72
+ // this.accessToken = data.access_token;
73
+ // this.tokenExpiry = Date.now() + (data.expires_in - 300) * 1000;
74
+
75
+ return this.accessToken ?? '';
76
+ }
77
+
78
+ /** Handle incoming WeChat message */
79
+ async handleMessage(wxMsg: WeChatMessage): Promise<string> {
80
+ if (wxMsg.msgType === 'event') {
81
+ return this.handleEvent(wxMsg);
82
+ }
83
+
84
+ const message = this.wechatToMessage(wxMsg);
85
+ if (this.handler) {
86
+ const reply = await this.handler(message);
87
+ return reply.content;
88
+ }
89
+ return '';
90
+ }
91
+
92
+ /** Handle WeChat events (subscribe, scan, etc.) */
93
+ private handleEvent(wxMsg: WeChatMessage): string {
94
+ switch (wxMsg.event) {
95
+ case 'subscribe':
96
+ return 'Welcome! How can I help you?';
97
+ case 'SCAN':
98
+ return `QR code scanned: ${wxMsg.eventKey}`;
99
+ default:
100
+ return '';
101
+ }
102
+ }
103
+
104
+ /** Convert WeChat message to internal Message */
105
+ private wechatToMessage(wxMsg: WeChatMessage): Message {
106
+ return {
107
+ id: wxMsg.msgId ?? `wx-${wxMsg.createTime}`,
108
+ role: 'user',
109
+ content: wxMsg.content ?? '',
110
+ timestamp: wxMsg.createTime * 1000,
111
+ metadata: {
112
+ channel: 'wechat',
113
+ fromUser: wxMsg.fromUserName,
114
+ toUser: wxMsg.toUserName,
115
+ msgType: wxMsg.msgType,
116
+ },
117
+ };
118
+ }
119
+
120
+ /** Send template message */
121
+ async sendTemplateMessage(data: TemplateMessageData): Promise<boolean> {
122
+ // TODO: Implement
123
+ // const token = await this.getAccessToken();
124
+ // const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
125
+ // const res = await fetch(url, {
126
+ // method: 'POST',
127
+ // body: JSON.stringify({
128
+ // touser: data.toUser,
129
+ // template_id: data.templateId,
130
+ // url: data.url,
131
+ // data: data.data,
132
+ // }),
133
+ // });
134
+ void data;
135
+ return true;
136
+ }
137
+
138
+ /** Generate QR code for login (stub) */
139
+ async generateLoginQR(): Promise<{ ticket: string; url: string; expireSeconds: number }> {
140
+ // TODO: Implement with WeChat QR code API
141
+ // const token = await this.getAccessToken();
142
+ // POST to https://api.weixin.qq.com/cgi-bin/qrcode/create
143
+ return {
144
+ ticket: 'stub-ticket',
145
+ url: 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=stub-ticket',
146
+ expireSeconds: 300,
147
+ };
148
+ }
149
+ }
@@ -0,0 +1,77 @@
1
+ import type { AgentContext, Message } from './types';
2
+
3
+ /**
4
+ * Agent Composition — v0.8.0
5
+ * Combine multiple agents into a pipeline: Agent A output → Agent B input.
6
+ * Configurable in OAD: `compose: [agent-a, agent-b]`
7
+ */
8
+
9
+ export type AgentHandler = (context: AgentContext, message: Message) => Promise<Message>;
10
+
11
+ export interface ComposableAgent {
12
+ id: string;
13
+ name: string;
14
+ handler: AgentHandler;
15
+ }
16
+
17
+ export interface ComposeOptions {
18
+ /** Stop pipeline if any agent returns empty content */
19
+ stopOnEmpty?: boolean;
20
+ /** Transform output between agents */
21
+ transform?: (output: Message, nextAgentId: string) => Message;
22
+ /** Timeout per agent in ms */
23
+ timeoutMs?: number;
24
+ }
25
+
26
+ export class AgentPipeline {
27
+ private agents: ComposableAgent[] = [];
28
+ private options: ComposeOptions;
29
+
30
+ constructor(agents: ComposableAgent[], options: ComposeOptions = {}) {
31
+ this.agents = agents;
32
+ this.options = options;
33
+ }
34
+
35
+ /** Run the pipeline sequentially: each agent's output becomes the next agent's input */
36
+ async execute(context: AgentContext, initialMessage: Message): Promise<Message> {
37
+ let currentMessage = initialMessage;
38
+
39
+ for (const agent of this.agents) {
40
+ if (this.options.stopOnEmpty && !currentMessage.content.trim()) {
41
+ break;
42
+ }
43
+
44
+ // Apply transform if provided
45
+ if (this.options.transform) {
46
+ currentMessage = this.options.transform(currentMessage, agent.id);
47
+ }
48
+
49
+ if (this.options.timeoutMs) {
50
+ const result = await Promise.race([
51
+ agent.handler(context, currentMessage),
52
+ new Promise<never>((_, reject) =>
53
+ setTimeout(() => reject(new Error(`Agent ${agent.id} timed out`)), this.options.timeoutMs)
54
+ ),
55
+ ]);
56
+ currentMessage = result;
57
+ } else {
58
+ currentMessage = await agent.handler(context, currentMessage);
59
+ }
60
+ }
61
+
62
+ return currentMessage;
63
+ }
64
+
65
+ /** Get the pipeline agent IDs in order */
66
+ getAgentIds(): string[] {
67
+ return this.agents.map((a) => a.id);
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Create a pipeline from an array of composable agents.
73
+ * Usage in OAD: `compose: [agent-a, agent-b, agent-c]`
74
+ */
75
+ export function compose(agents: ComposableAgent[], options?: ComposeOptions): AgentPipeline {
76
+ return new AgentPipeline(agents, options);
77
+ }