-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelivery.ts
More file actions
231 lines (198 loc) · 7.29 KB
/
Copy pathdelivery.ts
File metadata and controls
231 lines (198 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { slackClient, telegramClient } from '@relayfile/relay-helpers';
import type { SlackClient, TelegramClient } from '@relayfile/relay-helpers';
import type { WorkforceCtx } from '@agentworkforce/runtime';
import {
resolveDeliveryTargets,
slackChannel,
telegramChat,
type DeliveryClient,
type DeliveryOptions,
type DeliveryResult,
type DeliveryTransports,
type SlackRef,
type TelegramRef
} from './types.js';
const WRITEBACK_TIMEOUT_MS = 15_000;
/**
* Create a delivery client that auto-discovers configured transports from
* the persona context and sends to all of them.
*
* Blocking mode (the default):
* const heads = await delivery.send(header);
* await delivery.send(body, { replyTo: heads });
*
* Non-blocking parentRef mode (zero receipt round-trips):
* const heads = await delivery.publish(header);
* await delivery.send(body, { replyTo: heads, nonBlocking: true });
*/
export function createDelivery(
ctx: WorkforceCtx,
transports?: DeliveryTransports
): DeliveryClient {
const targets = resolveDeliveryTargets(ctx);
// Two sets of clients: blocking (waits for receipt) and non-blocking
// (0ms timeout, returns draft refs immediately for parentRef threading).
const slackBlocking = transports?.slack ?? (targets.includes('slack')
? slackClient({ writebackTimeoutMs: WRITEBACK_TIMEOUT_MS })
: undefined);
const slackNonBlocking = targets.includes('slack')
? slackClient({ writebackTimeoutMs: 0 })
: undefined;
const telegramBlocking = transports?.telegram ?? (targets.includes('telegram')
? telegramClient({ writebackTimeoutMs: WRITEBACK_TIMEOUT_MS })
: undefined);
const telegramNonBlocking = targets.includes('telegram')
? telegramClient({ writebackTimeoutMs: 0 })
: undefined;
return new DeliveryClientImpl(ctx, targets, {
slackBlocking,
slackNonBlocking,
telegramBlocking,
telegramNonBlocking
});
}
interface DeliveryTransportsInternal {
slackBlocking?: SlackClient;
slackNonBlocking?: SlackClient;
telegramBlocking?: TelegramClient;
telegramNonBlocking?: TelegramClient;
}
class DeliveryClientImpl implements DeliveryClient {
readonly targets: ReadonlyArray<'slack' | 'telegram'>;
private ctx: WorkforceCtx;
private t: DeliveryTransportsInternal;
constructor(
ctx: WorkforceCtx,
targets: Array<'slack' | 'telegram'>,
transports: DeliveryTransportsInternal
) {
this.ctx = ctx;
this.targets = targets;
this.t = transports;
}
async send(text: string, opts?: DeliveryOptions): Promise<DeliveryResult> {
const nonBlocking = opts?.nonBlocking === true;
const refs: Array<SlackRef | TelegramRef> = [];
const errors: string[] = [];
const tasks: Promise<void>[] = [];
for (const target of this.targets) {
const parentRef = opts?.replyTo?.refs.find((r) => r.provider === target);
if (target === 'slack') {
tasks.push(
this.sendSlack(text, parentRef as SlackRef | undefined, nonBlocking)
.then((ref) => { if (ref) refs.push(ref); })
.catch((err) => { errors.push(`slack: ${String(err)}`); })
);
}
if (target === 'telegram') {
tasks.push(
this.sendTelegram(text, parentRef as TelegramRef | undefined, nonBlocking)
.then((ref) => { if (ref) refs.push(ref); })
.catch((err) => { errors.push(`telegram: ${String(err)}`); })
);
}
}
await Promise.all(tasks);
// In non-blocking mode, draft refs always succeed (no receipt wait to fail).
// Treat any ref as success.
const ok = nonBlocking
? refs.length > 0
: errors.length === 0 && refs.length === this.targets.length;
if (!ok && errors.length > 0) {
this.ctx.log?.('warn', 'delivery.partial-failure', { errors, nonBlocking });
}
if (!ok && refs.length === 0) {
throw new Error(`Delivery failed to all targets: ${errors.join('; ')}`);
}
return { ok, refs };
}
async publish(text: string): Promise<DeliveryResult> {
return this.send(text, { nonBlocking: true });
}
// ── Slack ──────────────────────────────────────────────────────────────
private async sendSlack(
text: string,
parentRef: SlackRef | undefined,
nonBlocking: boolean
): Promise<SlackRef | null> {
const channel = slackChannel(this.ctx);
if (!channel) return null;
if (nonBlocking) {
return this.sendSlackNonBlocking(channel, text, parentRef);
}
return this.sendSlackBlocking(channel, text, parentRef);
}
private async sendSlackBlocking(
channel: string,
text: string,
parentRef?: SlackRef
): Promise<SlackRef | null> {
const client = this.t.slackBlocking;
if (!client) return null;
const result = parentRef?.draftRef
? await client.post(channel, text, { replyTo: parentRef.draftRef })
: await client.post(channel, text);
if (!result.ts) {
this.ctx.log?.('warn', 'delivery.slack.no-receipt', { channel });
return null;
}
return {
provider: 'slack',
channel: result.channel,
ts: result.ts,
draftRef: result.ref
};
}
/**
* Non-blocking Slack: uses messages.write() directly with writebackTimeoutMs:0.
* The parentRef is embedded in the message body so the cloud orders the message
* under the parent server-side — zero receipt round-trips. The returned draftRef
* is the relay path, usable as a parent for subsequent threaded sends.
*
* Mirrors the x-reply-radar parentRef threading pattern (internal-agents).
*/
private async sendSlackNonBlocking(
channel: string,
text: string,
parentRef?: SlackRef
): Promise<SlackRef | null> {
const client = this.t.slackNonBlocking;
if (!client) return null;
const body: Record<string, unknown> = { text };
if (parentRef?.draftRef) {
// Embed parentRef in the body — the cloud lifts it from the streamed head
// and orders this message under the parent once the parent delivers.
body.parentRef = parentRef.draftRef;
}
const result = await client.messages.write({ channelId: channel }, body);
return {
provider: 'slack',
channel,
ts: '', // Not available yet (non-blocking)
draftRef: result.path
};
}
// ── Telegram ───────────────────────────────────────────────────────────
private async sendTelegram(
text: string,
parentRef: TelegramRef | undefined,
nonBlocking: boolean
): Promise<TelegramRef | null> {
const chatId = telegramChat(this.ctx);
if (!chatId) return null;
const client = nonBlocking ? this.t.telegramNonBlocking : this.t.telegramBlocking;
if (!client) return null;
const result = parentRef?.messageId
? await client.sendMessage(chatId, text, { replyToMessageId: Number(parentRef.messageId) || undefined })
: await client.sendMessage(chatId, text);
if (!nonBlocking && !result.ok) {
this.ctx.log?.('warn', 'delivery.telegram.no-receipt', { chatId });
return null;
}
return {
provider: 'telegram',
chatId: String(result.chatId),
messageId: result.ok ? result.messageId : ''
};
}
}