@parall/parel-channel 1.40.0 → 1.42.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,264 @@
1
+ import type { ConnectorContext, ConnectorEffect } from '@parel/plugin-sdk';
2
+ import { buildChannelPrompt } from './channel-prompt.js';
3
+ import { parallApiUrl, parallOrgId, requireAgk } from './connect.js';
4
+ import {
5
+ ackEffect,
6
+ createChannelInputStep,
7
+ ensureSession,
8
+ invalidateSession,
9
+ markDispatchReceived,
10
+ nextEnvelopeId,
11
+ patchSession,
12
+ readActiveEmit,
13
+ REQUEST_TIMEOUT_MS,
14
+ TURN_ENVELOPE_KEY,
15
+ writeActiveEmit,
16
+ } from './session.js';
17
+
18
+ /**
19
+ * External IM inbound (channel_message dispatches — Feishu/Slack via the
20
+ * platform-mediated channel, external-im-channel-design.md). Split from
21
+ * inbound.ts as a pure move; the pipeline contract lives there.
22
+ */
23
+
24
+ /**
25
+ * Miss-path lookups here are cosmetic (prompt labeling only), so they get a
26
+ * tight timeout — same 3s budget as deliver's front-of-reply session lookup —
27
+ * rather than holding the message's emit/ack behind the full
28
+ * REQUEST_TIMEOUT_MS. Also reused by inbound.ts's chat-name prefetch.
29
+ */
30
+ export const PROVIDER_LOOKUP_TIMEOUT_MS = 3_000;
31
+
32
+ /**
33
+ * channel_message dispatch → agent (external IM channel,
34
+ * external-im-channel-design.md). Same pipeline shape as the message path,
35
+ * with the ChannelConversation (chv_) standing in for the chat as the
36
+ * routing subject: fetch the durable ChannelMessage + its conversation,
37
+ * resolve the provider for prompt labeling (cached — the connection→provider
38
+ * mapping is stable), frame the prompt for the EXTERNAL audience, report
39
+ * progress against the conversation-keyed session, and ack by source.
40
+ *
41
+ * Error contract mirrors the message path (and agent-core's
42
+ * fetchAndHandleChannelMessage): 404/403 on the source entities is
43
+ * permanently unusable → ack-and-drop; a transient failure keeps the
44
+ * dispatch pending for the catch-up sweep.
45
+ */
46
+ export async function effectsForChannelDispatch(
47
+ sourceId: string,
48
+ ctx: ConnectorContext,
49
+ ): Promise<ConnectorEffect[]> {
50
+ const apiUrl = parallApiUrl(ctx);
51
+ const orgId = parallOrgId(ctx);
52
+ const authHeaders = { Authorization: `Bearer ${requireAgk(ctx)}` };
53
+ const get = (path: string, timeoutMs: number = REQUEST_TIMEOUT_MS) =>
54
+ fetch(`${apiUrl}/api/v1/orgs/${orgId}${path}`, {
55
+ headers: authHeaders,
56
+ signal: AbortSignal.timeout(timeoutMs),
57
+ });
58
+
59
+ const m = await get(`/channel-messages/${sourceId}`);
60
+ if (!m.ok) {
61
+ if (m.status === 404 || m.status === 403) {
62
+ // Deleted / inaccessible (also the shape a disabled org feature flag
63
+ // takes) — permanently unusable, drop it.
64
+ return [ackEffect(ctx, 'channel_message', sourceId)];
65
+ }
66
+ return []; // transient: keep pending, the catch-up sweep retries
67
+ }
68
+ const msg = (await m.json().catch(() => null)) as {
69
+ conversation_id?: string;
70
+ external_message_id?: string;
71
+ text?: string;
72
+ external_user_id?: string;
73
+ external_user_name?: string;
74
+ received_at?: string;
75
+ } | null;
76
+ const conversationId = msg?.conversation_id ? String(msg.conversation_id) : undefined;
77
+ const text = msg?.text ?? '';
78
+ if (!conversationId) {
79
+ // No conversation → no session key and no reply target: unusable.
80
+ return [ackEffect(ctx, 'channel_message', sourceId)];
81
+ }
82
+ if (!text) {
83
+ // The ingress adapter only persists mechanically parsed text; a row with
84
+ // none will never grow any (same reasoning as attachment-only chat
85
+ // messages) — drop rather than let it pile up in the pending queue.
86
+ return [ackEffect(ctx, 'channel_message', sourceId)];
87
+ }
88
+
89
+ const c = await get(`/channel-conversations/${conversationId}`);
90
+ if (!c.ok) {
91
+ if (c.status === 404 || c.status === 403) {
92
+ return [ackEffect(ctx, 'channel_message', sourceId)];
93
+ }
94
+ return [];
95
+ }
96
+ const conv = (await c.json().catch(() => null)) as {
97
+ connection_id?: string;
98
+ external_conversation_id?: string;
99
+ conversation_type?: string;
100
+ } | null;
101
+
102
+ // Provider (= clip alias) for prompt labeling + the reply hint.
103
+ // Best-effort: an unresolved provider degrades the wording, never blocks.
104
+ const connectionId = conv?.connection_id ? String(conv.connection_id) : undefined;
105
+ const provider = connectionId ? await resolveChannelProvider(ctx, connectionId, get) : undefined;
106
+
107
+ const senderName = msg?.external_user_name || msg?.external_user_id || 'external user';
108
+ const externalConversationId = conv?.external_conversation_id
109
+ ? String(conv.external_conversation_id)
110
+ : undefined;
111
+ const externalMessageId = msg?.external_message_id ? String(msg.external_message_id) : undefined;
112
+
113
+ // Progress reporting — identical ordering contract to the message path
114
+ // (see the comments there): received settles before this function returns;
115
+ // the turnEnvelope marker goes down before any session write; the row
116
+ // stays 'received' until the turn event's complete-sources.
117
+ const receivedSettled = markDispatchReceived(ctx, 'channel_message', sourceId);
118
+ const priorEmit = await readActiveEmit(ctx, 'channel_message', sourceId);
119
+ const envelopeId = nextEnvelopeId('channel_message', sourceId, priorEmit);
120
+ let sessionId = await ensureSession(ctx);
121
+ if (sessionId) {
122
+ await ctx.store?.set(TURN_ENVELOPE_KEY, envelopeId).catch(() => {});
123
+ const report = (sid: string) =>
124
+ Promise.all([
125
+ patchSession(ctx, sid, { status: 'active', trigger_message_id: sourceId }),
126
+ createChannelInputStep(ctx, sid, {
127
+ conversationId,
128
+ channelMessageId: sourceId,
129
+ provider,
130
+ externalConversationId,
131
+ senderId: msg?.external_user_id ? String(msg.external_user_id) : 'external',
132
+ senderName,
133
+ text,
134
+ sentAt: msg?.received_at ? String(msg.received_at) : undefined,
135
+ }),
136
+ ]);
137
+ const results = await report(sessionId);
138
+ if (results.includes('stale')) {
139
+ await invalidateSession(ctx);
140
+ const fresh = await ensureSession(ctx);
141
+ if (fresh && fresh !== sessionId) {
142
+ await report(fresh);
143
+ sessionId = fresh;
144
+ }
145
+ }
146
+ // Record the durable chv_ ↔ ase_ mapping (ops drill-down from a
147
+ // conversation into its session; last-write-wins on the server). Only on
148
+ // change — the store remembers what was last pushed — and fully
149
+ // fire-and-forget: pure bookkeeping must never add latency to the
150
+ // emit/ack path (a lost attempt is retried on the next message because
151
+ // the store memo only updates on success).
152
+ void recordConversationSession(ctx, conversationId, sessionId).catch(() => {});
153
+ }
154
+ await receivedSettled;
155
+ await writeActiveEmit(ctx, 'channel_message', sourceId, envelopeId);
156
+
157
+ return [
158
+ {
159
+ type: 'emitEvent',
160
+ event: {
161
+ id: envelopeId,
162
+ orgId,
163
+ connectionId: ctx.connectionId,
164
+ source: 'parall',
165
+ // The host's message intake path turns data.text into the user
166
+ // message — the external-audience framing rides inside it (parel has
167
+ // no separate prompt channel), so 'message' is the right type here.
168
+ type: 'message',
169
+ // main routing sends this to the agent's one session too; subject
170
+ // still carries the external conversation (chv_) for parel's turn
171
+ // input grouping (F2) and per-conversation event correlation.
172
+ subject: conversationId,
173
+ data: {
174
+ text: buildChannelPrompt({
175
+ provider,
176
+ conversationType: conv?.conversation_type ? String(conv.conversation_type) : undefined,
177
+ externalConversationId,
178
+ externalMessageId,
179
+ senderName,
180
+ text,
181
+ }),
182
+ conversationId,
183
+ channelMessageId: sourceId,
184
+ provider,
185
+ externalConversationId,
186
+ externalMessageId,
187
+ },
188
+ // No chatId on purpose: the reply goes out through the provider clip
189
+ // (agent-invoked), NOT deliver() — deliver only runs the redundant
190
+ // session idle for channel routes (see delivery.ts).
191
+ replyRoute: {
192
+ kind: 'provider_http',
193
+ connectionId: ctx.connectionId,
194
+ data: { conversationId, envelopeId },
195
+ },
196
+ // No invocation context: PRLL_CHAT_ID must not point CLI defaults at
197
+ // a chat that doesn't exist, and the reply targets (external ids)
198
+ // already ride the prompt verbatim. (So no PRLL_DISPATCH_SOURCE_*
199
+ // either — the external reply goes out through the provider clip,
200
+ // and this row's ledger close is the turn event's complete-sources.)
201
+ },
202
+ },
203
+ // No ack effect — see the message path (inbound.ts): the row stays
204
+ // received until complete-sources closes it.
205
+ ];
206
+ }
207
+
208
+ /**
209
+ * connection id → provider alias, cached in the durable store (stable
210
+ * mapping; avoids one connection fetch per inbound message). Cache hits are
211
+ * a store read; any failure returns undefined — prompt wording degrades to
212
+ * neutral rather than inventing a clip alias.
213
+ */
214
+ async function resolveChannelProvider(
215
+ ctx: ConnectorContext,
216
+ connectionId: string,
217
+ get: (path: string, timeoutMs?: number) => Promise<Response>,
218
+ ): Promise<string | undefined> {
219
+ const cacheKey = `channelProvider:${connectionId}`;
220
+ const cached = await ctx.store?.get(cacheKey).catch(() => null);
221
+ if (typeof cached === 'string' && cached) return cached;
222
+ try {
223
+ const res = await get(`/channel-connections/${connectionId}`, PROVIDER_LOOKUP_TIMEOUT_MS);
224
+ if (!res.ok) return undefined;
225
+ const body = (await res.json().catch(() => null)) as { provider?: string } | null;
226
+ const provider = body?.provider ? String(body.provider) : undefined;
227
+ if (provider) await ctx.store?.set(cacheKey, provider).catch(() => {});
228
+ return provider;
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ /** Push the chv_ → ase_ pointer when it changed; warn-only on failure. */
235
+ async function recordConversationSession(
236
+ ctx: ConnectorContext,
237
+ conversationId: string,
238
+ sessionId: string,
239
+ ): Promise<void> {
240
+ const mappedKey = `convSession:${conversationId}`;
241
+ const mapped = await ctx.store?.get(mappedKey).catch(() => null);
242
+ if (mapped === sessionId) return;
243
+ try {
244
+ const res = await fetch(
245
+ `${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/channel-conversations/${conversationId}/session`,
246
+ {
247
+ method: 'PATCH',
248
+ headers: {
249
+ Authorization: `Bearer ${requireAgk(ctx)}`,
250
+ 'Content-Type': 'application/json',
251
+ },
252
+ body: JSON.stringify({ agent_session_id: sessionId }),
253
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
254
+ },
255
+ );
256
+ if (!res.ok) {
257
+ console.warn(`[parel-channel] conversation session mapping failed (${res.status})`);
258
+ return;
259
+ }
260
+ await ctx.store?.set(mappedKey, sessionId).catch(() => {});
261
+ } catch (err) {
262
+ console.warn('[parel-channel] conversation session mapping failed', err);
263
+ }
264
+ }