@parall/parel-channel 1.37.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/src/inbound.ts ADDED
@@ -0,0 +1,623 @@
1
+ import type {
2
+ AgentEvent,
3
+ AgentEventEffect,
4
+ ConnectorContext,
5
+ ConnectorEffect,
6
+ WebSocketFrame,
7
+ } from '@parel/plugin-sdk';
8
+ import { buildChannelPrompt } from './channel-prompt.js';
9
+ import { parallApiUrl, parallOrgId, requireAgk } from './connect.js';
10
+ import {
11
+ createChannelInputStep,
12
+ createInputStep,
13
+ createTraceStep,
14
+ ensureSession,
15
+ invalidateSession,
16
+ markDispatchReceived,
17
+ patchSession,
18
+ REQUEST_TIMEOUT_MS,
19
+ turnEnvelopeKey,
20
+ } from './session.js';
21
+
22
+ /**
23
+ * Inbound path: Parall dispatches → agent.
24
+ *
25
+ * The Parall gateway pushes `dispatch.new` signals on the agent's WS; the
26
+ * dispatch is a pointer (source_type/source_id), not the payload. For each
27
+ * message dispatch we pull the source message text, emit it to the agent as a
28
+ * ChannelEnvelope, and ack the dispatch by source so it isn't redelivered.
29
+ * On (re)connect, onOpen sweeps `GET /dispatch` so dispatches that arrived
30
+ * while the socket was down are not lost — the WS push has no replay.
31
+ *
32
+ * Contract (confirmed against parel #102–#107): raw WS frames are handed to
33
+ * onMessage verbatim; the binding created by the agent.yaml `channels:` block
34
+ * routes emitted envelopes to this agent, keyed by `subject` under
35
+ * `routing: {mode: per_subject}`; ack-on-emit matches channel-slack-socket.
36
+ *
37
+ * Scope: `source_type === "message"` dispatches (DMs and mentions) and
38
+ * `source_type === "channel_message"` dispatches (external IM — Feishu/Slack
39
+ * via the platform-mediated channel, keyed by their ChannelConversation) are
40
+ * emitted. Task/schedule/trigger dispatches stay pending rather than being
41
+ * acked-and-dropped.
42
+ */
43
+
44
+ interface DispatchData {
45
+ id?: unknown;
46
+ source_type?: unknown;
47
+ source_id?: unknown;
48
+ chat_id?: unknown;
49
+ }
50
+
51
+ export async function handleParallFrame(
52
+ frame: WebSocketFrame,
53
+ ctx: ConnectorContext,
54
+ ): Promise<ConnectorEffect[]> {
55
+ let event: { type?: string; data?: DispatchData };
56
+ try {
57
+ const raw = typeof frame.data === 'string' ? frame.data : new TextDecoder().decode(frame.data);
58
+ event = JSON.parse(raw);
59
+ } catch {
60
+ return [];
61
+ }
62
+ if (event.type !== 'dispatch.new' || !event.data) return [];
63
+ try {
64
+ return await effectsForDispatch(event.data, ctx);
65
+ } catch (err) {
66
+ // A transient fetch failure on one frame must not fail the frame handler —
67
+ // the dispatch stays pending and the onOpen sweep replays it on reconnect.
68
+ console.error('[parel-channel] dispatch handling failed', err);
69
+ return [];
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Sweep pending dispatches on (re)connect — the live WS push has no replay.
75
+ * Paginates with the server cursor so a long outage's backlog is not silently
76
+ * truncated (bounded to keep a pathological backlog from wedging onOpen; the
77
+ * remainder is picked up on the next reconnect sweep).
78
+ */
79
+ export async function catchUpParall(ctx: ConnectorContext): Promise<ConnectorEffect[]> {
80
+ const effects: ConnectorEffect[] = [];
81
+ try {
82
+ const apiUrl = parallApiUrl(ctx);
83
+ const agk = requireAgk(ctx);
84
+ const orgId = parallOrgId(ctx);
85
+ let cursor = '';
86
+ // Page bound is a wedge guard, not a coverage target. Non-message
87
+ // dispatches stay pending (deliberately — see effectsForDispatch) and the
88
+ // list is FIFO, so the bound must comfortably exceed any realistic
89
+ // unsupported backlog or old rows could starve newer DMs out of the sweep.
90
+ // 40 pages ≈ 2000 dispatches per sweep; log when we hit the ceiling so a
91
+ // pathological backlog is visible instead of silent.
92
+ const maxPages = 40;
93
+ let page = 0;
94
+ for (; page < maxPages; page++) {
95
+ const url = `${apiUrl}/api/v1/orgs/${orgId}/dispatch?limit=50${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`;
96
+ const res = await fetch(url, {
97
+ headers: { Authorization: `Bearer ${agk}` },
98
+ signal: AbortSignal.timeout(10_000),
99
+ });
100
+ if (!res.ok) break;
101
+ const body = (await res.json().catch(() => null)) as {
102
+ data?: DispatchData[];
103
+ next_cursor?: string;
104
+ } | null;
105
+ // Same-chat dispatches run SEQUENTIALLY (session reporting PATCHes one
106
+ // shared session per chat — concurrent replay would let an older
107
+ // dispatch overwrite trigger_message_id after a newer one and reorder
108
+ // input steps); different chats still run concurrently. Page order is
109
+ // FIFO, so per-chat envelope order is preserved. A failed dispatch
110
+ // resolves to [] and stays pending for the next sweep.
111
+ //
112
+ // channel_message dispatches carry no chat_id and their conversation
113
+ // (the session key) is only known after fetching the message — so they
114
+ // all share ONE sequential chain: per-conversation order is preserved
115
+ // at the cost of serializing across conversations, which is fine for
116
+ // the small external-IM backlogs a reconnect sweep sees.
117
+ const byChat = new Map<string, DispatchData[]>();
118
+ const unkeyed: DispatchData[] = [];
119
+ for (const d of body?.data ?? []) {
120
+ const cid =
121
+ String(d.source_type ?? '') === 'channel_message'
122
+ ? CHANNEL_SWEEP_CHAIN
123
+ : d.chat_id
124
+ ? String(d.chat_id)
125
+ : '';
126
+ if (!cid) {
127
+ unkeyed.push(d);
128
+ continue;
129
+ }
130
+ const group = byChat.get(cid);
131
+ if (group) group.push(d);
132
+ else byChat.set(cid, [d]);
133
+ }
134
+ const runOne = (d: DispatchData) =>
135
+ effectsForDispatch(d, ctx).catch((err) => {
136
+ console.error('[parel-channel] catch-up dispatch failed', err);
137
+ return [] as ConnectorEffect[];
138
+ });
139
+ const chains = [...byChat.values()].map(async (group) => {
140
+ const out: ConnectorEffect[] = [];
141
+ for (const d of group) out.push(...(await runOne(d)));
142
+ return out;
143
+ });
144
+ const pageEffects = await Promise.all([...chains, ...unkeyed.map(runOne)]);
145
+ effects.push(...pageEffects.flat());
146
+ if (!body?.next_cursor) break;
147
+ cursor = body.next_cursor;
148
+ }
149
+ if (page === maxPages) {
150
+ console.warn(
151
+ '[parel-channel] catch-up hit the page ceiling; remainder deferred to the next reconnect sweep',
152
+ );
153
+ }
154
+ } catch (err) {
155
+ // Catch-up is best-effort: keep whatever pages completed and never fail
156
+ // the connection open over it.
157
+ console.error('[parel-channel] dispatch catch-up failed', err);
158
+ }
159
+ return effects;
160
+ }
161
+
162
+ /**
163
+ * Synthetic sweep group key for channel_message dispatches (no chat_id).
164
+ * Chat ids are cht_-prefixed nanoids, so this cannot collide with one.
165
+ */
166
+ const CHANNEL_SWEEP_CHAIN = 'sweep:channel_message';
167
+
168
+ async function effectsForDispatch(
169
+ data: DispatchData,
170
+ ctx: ConnectorContext,
171
+ ): Promise<ConnectorEffect[]> {
172
+ const sourceType = String(data.source_type ?? '');
173
+ const sourceId = data.source_id ? String(data.source_id) : undefined;
174
+ const chatId = data.chat_id ? String(data.chat_id) : undefined;
175
+ const dispatchId = String(data.id ?? '');
176
+ if (sourceType === 'channel_message' && sourceId) {
177
+ // External IM message (chat_id is NULL by design — the conversation
178
+ // lives on the provider, not in a Parall chat).
179
+ return effectsForChannelDispatch(sourceId, dispatchId, ctx);
180
+ }
181
+ // Non-message dispatches (task_assign, schedule.fire, …) stay PENDING on
182
+ // purpose: they are meaningful work a future connector version will handle,
183
+ // and acking would silently drop it. Message dispatches that can NEVER
184
+ // become processable are acked-and-dropped below instead, so the pending
185
+ // queue (and the reconnect catch-up sweep) is bounded by real future work.
186
+ if (sourceType !== 'message' || !sourceId) return [];
187
+ if (!chatId) {
188
+ // A message dispatch with no chat can never be routed or replied to.
189
+ return [ackEffect(ctx, sourceType, sourceId)];
190
+ }
191
+
192
+ const apiUrl = parallApiUrl(ctx);
193
+ const agk = requireAgk(ctx);
194
+ const orgId = parallOrgId(ctx);
195
+
196
+ // Pull the source message text (global by-id read; ACL = chat membership).
197
+ const m = await fetch(`${apiUrl}/api/v1/messages/${sourceId}`, {
198
+ headers: { Authorization: `Bearer ${agk}` },
199
+ signal: AbortSignal.timeout(10_000),
200
+ });
201
+ if (!m.ok) {
202
+ if (m.status === 404 || m.status === 403) {
203
+ // Deleted message / lost chat access — permanently unusable, drop it.
204
+ return [ackEffect(ctx, sourceType, sourceId)];
205
+ }
206
+ // Transient failure: keep pending, the catch-up sweep retries.
207
+ return [];
208
+ }
209
+ const msg = (await m.json().catch(() => null)) as {
210
+ content?: { text?: string };
211
+ thread_root_id?: string;
212
+ sender_id?: string;
213
+ } | null;
214
+ const text = msg?.content?.text ?? '';
215
+ // A thread reply anchors the agent's answer to the same thread.
216
+ const threadRootId = msg?.thread_root_id || undefined;
217
+ if (!text) {
218
+ // Attachment-only / empty-text messages never grow text — MVP has no
219
+ // attachment path, so ack-and-drop rather than let them pile up in the
220
+ // pending queue forever.
221
+ return [ackEffect(ctx, sourceType, sourceId)];
222
+ }
223
+
224
+ // Progress reporting (best-effort, parall-runtime-indicator-plan.md §3):
225
+ // received lights the pending ring, the active+trigger patch arms the done
226
+ // signal, the input step flips the ring to processing. received MUST settle
227
+ // before this function returns — the ack effect below moves the dispatch
228
+ // row out of 'pending', and MarkReceived only transitions pending rows.
229
+ // It is deliberately NOT gated on the session resolving: it only touches
230
+ // the dispatch row, and a transient session failure must not also cost the
231
+ // pending ring (a later successful turn's idle clears agent-level pendings).
232
+ const receivedSettled = markDispatchReceived(ctx, sourceType, sourceId);
233
+ const envelopeId = dispatchId || `${sourceType}:${sourceId}`;
234
+ let sessionId = await ensureSession(ctx, chatId);
235
+ if (sessionId) {
236
+ // The guard marker goes down BEFORE any session write: a stale
237
+ // turn_completed for the PREVIOUS turn (outbox retry, late event) checks
238
+ // turnEnvelope to decide whether its idle is still safe — if the active
239
+ // patch below could land first, that event would still see the old
240
+ // envelope id and idle the session out from under this message.
241
+ // (Residual read-then-patch overlap is zero when the host runs a
242
+ // connection's hooks serially, per the C3 contract / C3b confirm item.)
243
+ await ctx.store?.set(turnEnvelopeKey(chatId), envelopeId).catch(() => {});
244
+ const report = (sid: string) =>
245
+ Promise.all([
246
+ patchSession(ctx, sid, { status: 'active', trigger_message_id: sourceId }),
247
+ createInputStep(ctx, sid, {
248
+ chatId,
249
+ messageId: sourceId,
250
+ senderId: msg?.sender_id ? String(msg.sender_id) : undefined,
251
+ text,
252
+ }),
253
+ ]);
254
+ const results = await report(sessionId);
255
+ if (results.includes('stale')) {
256
+ // The cached session was closed under us (e.g. New Session). The
257
+ // get-or-create falls through terminal rows, so one rebuild + retry
258
+ // repairs reporting for this and every later dispatch.
259
+ await invalidateSession(ctx, chatId);
260
+ const fresh = await ensureSession(ctx, chatId);
261
+ if (fresh && fresh !== sessionId) {
262
+ await report(fresh);
263
+ sessionId = fresh;
264
+ }
265
+ }
266
+ }
267
+ await receivedSettled;
268
+
269
+ // Per-turn invocation context: parel snapshots this at turn start and
270
+ // consume-gated plugins receive it — sandbox-e2b flattens it into per-exec
271
+ // env, so `parall` CLI calls inside the sandbox land on the right chat.
272
+ const invocationContext: Record<string, string> = {
273
+ PRLL_CHAT_ID: chatId,
274
+ PRLL_TRIGGER_MESSAGE_ID: sourceId,
275
+ ...(threadRootId ? { PRLL_THREAD_ROOT_ID: threadRootId } : {}),
276
+ };
277
+
278
+ const effects: ConnectorEffect[] = [
279
+ {
280
+ type: 'emitEvent',
281
+ event: {
282
+ id: envelopeId,
283
+ orgId,
284
+ connectionId: ctx.connectionId,
285
+ source: 'parall',
286
+ type: 'message',
287
+ // per_subject routing keys the parel session by subject → one parel
288
+ // session per Parall chat (mirrors Parall's chat-scoped conversations).
289
+ subject: chatId,
290
+ data: { text, chatId, messageId: sourceId, threadRootId },
291
+ // chat id + thread anchor ride replyRoute.data so deliver() knows
292
+ // where to post back (same shape channel-slack-socket uses for its
293
+ // channel id).
294
+ replyRoute: {
295
+ kind: 'provider_http',
296
+ connectionId: ctx.connectionId,
297
+ // envelopeId lets deliver() run the same staleness guard as
298
+ // onAgentEvent against the shared turnEnvelope marker.
299
+ data: { chatId, messageId: sourceId, threadRootId, envelopeId },
300
+ },
301
+ context: invocationContext,
302
+ },
303
+ },
304
+ ackEffect(ctx, sourceType, sourceId),
305
+ ];
306
+ return effects;
307
+ }
308
+
309
+ /**
310
+ * channel_message dispatch → agent (external IM channel,
311
+ * external-im-channel-design.md). Same pipeline shape as the message path,
312
+ * with the ChannelConversation (chv_) standing in for the chat as the
313
+ * routing subject: fetch the durable ChannelMessage + its conversation,
314
+ * resolve the provider for prompt labeling (cached — the connection→provider
315
+ * mapping is stable), frame the prompt for the EXTERNAL audience, report
316
+ * progress against the conversation-keyed session, and ack by source.
317
+ *
318
+ * Error contract mirrors the message path (and agent-core's
319
+ * fetchAndHandleChannelMessage): 404/403 on the source entities is
320
+ * permanently unusable → ack-and-drop; a transient failure keeps the
321
+ * dispatch pending for the catch-up sweep.
322
+ */
323
+ async function effectsForChannelDispatch(
324
+ sourceId: string,
325
+ dispatchId: string,
326
+ ctx: ConnectorContext,
327
+ ): Promise<ConnectorEffect[]> {
328
+ const apiUrl = parallApiUrl(ctx);
329
+ const orgId = parallOrgId(ctx);
330
+ const authHeaders = { Authorization: `Bearer ${requireAgk(ctx)}` };
331
+ const get = (path: string, timeoutMs: number = REQUEST_TIMEOUT_MS) =>
332
+ fetch(`${apiUrl}/api/v1/orgs/${orgId}${path}`, {
333
+ headers: authHeaders,
334
+ signal: AbortSignal.timeout(timeoutMs),
335
+ });
336
+
337
+ const m = await get(`/channel-messages/${sourceId}`);
338
+ if (!m.ok) {
339
+ if (m.status === 404 || m.status === 403) {
340
+ // Deleted / inaccessible (also the shape a disabled org feature flag
341
+ // takes) — permanently unusable, drop it.
342
+ return [ackEffect(ctx, 'channel_message', sourceId)];
343
+ }
344
+ return []; // transient: keep pending, the catch-up sweep retries
345
+ }
346
+ const msg = (await m.json().catch(() => null)) as {
347
+ conversation_id?: string;
348
+ external_message_id?: string;
349
+ text?: string;
350
+ external_user_id?: string;
351
+ external_user_name?: string;
352
+ received_at?: string;
353
+ } | null;
354
+ const conversationId = msg?.conversation_id ? String(msg.conversation_id) : undefined;
355
+ const text = msg?.text ?? '';
356
+ if (!conversationId) {
357
+ // No conversation → no session key and no reply target: unusable.
358
+ return [ackEffect(ctx, 'channel_message', sourceId)];
359
+ }
360
+ if (!text) {
361
+ // The ingress adapter only persists mechanically parsed text; a row with
362
+ // none will never grow any (same reasoning as attachment-only chat
363
+ // messages) — drop rather than let it pile up in the pending queue.
364
+ return [ackEffect(ctx, 'channel_message', sourceId)];
365
+ }
366
+
367
+ const c = await get(`/channel-conversations/${conversationId}`);
368
+ if (!c.ok) {
369
+ if (c.status === 404 || c.status === 403) {
370
+ return [ackEffect(ctx, 'channel_message', sourceId)];
371
+ }
372
+ return [];
373
+ }
374
+ const conv = (await c.json().catch(() => null)) as {
375
+ connection_id?: string;
376
+ external_conversation_id?: string;
377
+ conversation_type?: string;
378
+ } | null;
379
+
380
+ // Provider (= clip alias) for prompt labeling + the reply hint.
381
+ // Best-effort: an unresolved provider degrades the wording, never blocks.
382
+ const connectionId = conv?.connection_id ? String(conv.connection_id) : undefined;
383
+ const provider = connectionId ? await resolveChannelProvider(ctx, connectionId, get) : undefined;
384
+
385
+ const senderName = msg?.external_user_name || msg?.external_user_id || 'external user';
386
+ const externalConversationId = conv?.external_conversation_id
387
+ ? String(conv.external_conversation_id)
388
+ : undefined;
389
+ const externalMessageId = msg?.external_message_id ? String(msg.external_message_id) : undefined;
390
+
391
+ // Progress reporting — identical ordering contract to the message path
392
+ // (see the comments there): received settles before the ack effect is
393
+ // returned; the turnEnvelope marker goes down before any session write.
394
+ const receivedSettled = markDispatchReceived(ctx, 'channel_message', sourceId);
395
+ const envelopeId = dispatchId || `channel_message:${sourceId}`;
396
+ let sessionId = await ensureSession(ctx, conversationId);
397
+ if (sessionId) {
398
+ await ctx.store?.set(turnEnvelopeKey(conversationId), envelopeId).catch(() => {});
399
+ const report = (sid: string) =>
400
+ Promise.all([
401
+ patchSession(ctx, sid, { status: 'active', trigger_message_id: sourceId }),
402
+ createChannelInputStep(ctx, sid, {
403
+ conversationId,
404
+ channelMessageId: sourceId,
405
+ provider,
406
+ externalConversationId,
407
+ senderId: msg?.external_user_id ? String(msg.external_user_id) : 'external',
408
+ senderName,
409
+ text,
410
+ sentAt: msg?.received_at ? String(msg.received_at) : undefined,
411
+ }),
412
+ ]);
413
+ const results = await report(sessionId);
414
+ if (results.includes('stale')) {
415
+ await invalidateSession(ctx, conversationId);
416
+ const fresh = await ensureSession(ctx, conversationId);
417
+ if (fresh && fresh !== sessionId) {
418
+ await report(fresh);
419
+ sessionId = fresh;
420
+ }
421
+ }
422
+ // Record the durable chv_ ↔ ase_ mapping (ops drill-down from a
423
+ // conversation into its session; last-write-wins on the server). Only on
424
+ // change — the store remembers what was last pushed — and fully
425
+ // fire-and-forget: pure bookkeeping must never add latency to the
426
+ // emit/ack path (a lost attempt is retried on the next message because
427
+ // the store memo only updates on success).
428
+ void recordConversationSession(ctx, conversationId, sessionId).catch(() => {});
429
+ }
430
+ await receivedSettled;
431
+
432
+ return [
433
+ {
434
+ type: 'emitEvent',
435
+ event: {
436
+ id: envelopeId,
437
+ orgId,
438
+ connectionId: ctx.connectionId,
439
+ source: 'parall',
440
+ // The host's message intake path turns data.text into the user
441
+ // message — the external-audience framing rides inside it (parel has
442
+ // no separate prompt channel), so 'message' is the right type here.
443
+ type: 'message',
444
+ // per_subject routing keys the parel session by subject → one parel
445
+ // session per external conversation (mirrors chv_ ↔ session 1:1 in
446
+ // the design).
447
+ subject: conversationId,
448
+ data: {
449
+ text: buildChannelPrompt({
450
+ provider,
451
+ conversationType: conv?.conversation_type ? String(conv.conversation_type) : undefined,
452
+ externalConversationId,
453
+ externalMessageId,
454
+ senderName,
455
+ text,
456
+ }),
457
+ conversationId,
458
+ channelMessageId: sourceId,
459
+ provider,
460
+ externalConversationId,
461
+ externalMessageId,
462
+ },
463
+ // No chatId on purpose: the reply goes out through the provider clip
464
+ // (agent-invoked), NOT deliver() — deliver only runs the redundant
465
+ // session idle for channel routes (see delivery.ts).
466
+ replyRoute: {
467
+ kind: 'provider_http',
468
+ connectionId: ctx.connectionId,
469
+ data: { conversationId, envelopeId },
470
+ },
471
+ // No invocation context: PRLL_CHAT_ID must not point CLI defaults at
472
+ // a chat that doesn't exist, and the reply targets (external ids)
473
+ // already ride the prompt verbatim.
474
+ },
475
+ },
476
+ ackEffect(ctx, 'channel_message', sourceId),
477
+ ];
478
+ }
479
+
480
+ /**
481
+ * connection id → provider alias, cached in the durable store (stable
482
+ * mapping; avoids one connection fetch per inbound message). Cache hits are
483
+ * a store read; the miss-path fetch is cosmetic (prompt labeling only), so
484
+ * it gets a tight timeout — same 3s budget as deliver's front-of-reply
485
+ * session lookup — rather than holding the message's emit/ack behind the
486
+ * full REQUEST_TIMEOUT_MS. Any failure returns undefined — prompt wording
487
+ * degrades to neutral rather than inventing a clip alias.
488
+ */
489
+ const PROVIDER_LOOKUP_TIMEOUT_MS = 3_000;
490
+
491
+ async function resolveChannelProvider(
492
+ ctx: ConnectorContext,
493
+ connectionId: string,
494
+ get: (path: string, timeoutMs?: number) => Promise<Response>,
495
+ ): Promise<string | undefined> {
496
+ const cacheKey = `channelProvider:${connectionId}`;
497
+ const cached = await ctx.store?.get(cacheKey).catch(() => null);
498
+ if (typeof cached === 'string' && cached) return cached;
499
+ try {
500
+ const res = await get(`/channel-connections/${connectionId}`, PROVIDER_LOOKUP_TIMEOUT_MS);
501
+ if (!res.ok) return undefined;
502
+ const body = (await res.json().catch(() => null)) as { provider?: string } | null;
503
+ const provider = body?.provider ? String(body.provider) : undefined;
504
+ if (provider) await ctx.store?.set(cacheKey, provider).catch(() => {});
505
+ return provider;
506
+ } catch {
507
+ return undefined;
508
+ }
509
+ }
510
+
511
+ /** Push the chv_ → ase_ pointer when it changed; warn-only on failure. */
512
+ async function recordConversationSession(
513
+ ctx: ConnectorContext,
514
+ conversationId: string,
515
+ sessionId: string,
516
+ ): Promise<void> {
517
+ const mappedKey = `convSession:${conversationId}`;
518
+ const mapped = await ctx.store?.get(mappedKey).catch(() => null);
519
+ if (mapped === sessionId) return;
520
+ try {
521
+ const res = await fetch(
522
+ `${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/channel-conversations/${conversationId}/session`,
523
+ {
524
+ method: 'PATCH',
525
+ headers: {
526
+ Authorization: `Bearer ${requireAgk(ctx)}`,
527
+ 'Content-Type': 'application/json',
528
+ },
529
+ body: JSON.stringify({ agent_session_id: sessionId }),
530
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
531
+ },
532
+ );
533
+ if (!res.ok) {
534
+ console.warn(`[parel-channel] conversation session mapping failed (${res.status})`);
535
+ return;
536
+ }
537
+ await ctx.store?.set(mappedKey, sessionId).catch(() => {});
538
+ } catch (err) {
539
+ console.warn('[parel-channel] conversation session mapping failed', err);
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Agent execution events (parel E1+E2, plugin-sdk 0.9.0, opt-in via the
545
+ * channel declaration's `observe: [turn, steps]`).
546
+ *
547
+ * E1 (turn lifecycle): turn_completed fires unconditionally on every cleanly
548
+ * finished turn — INCLUDING no-reply turns (hadOutput: false), the reliable
549
+ * "processing ended" signal that used to need a 30min turnwatch timer.
550
+ * turn_failed closes the turn the same way.
551
+ *
552
+ * E2 (step trace): model_reasoning / tool_call / tool_result become parall
553
+ * AgentSteps — the session panel gets the same live execution feed CC agents
554
+ * have (reasoning is aggregated host-side; tool output is a bounded preview).
555
+ *
556
+ * Events are best-effort (display feed, never data-correctness): a missed
557
+ * done event just means the ring clears on the next turn's trigger change; a
558
+ * missed trace step is a gap in the panel, nothing more.
559
+ */
560
+ export async function handleParallAgentEvent(
561
+ event: AgentEvent,
562
+ ctx: ConnectorContext,
563
+ ): Promise<AgentEventEffect[]> {
564
+ const chatId = event.subject;
565
+ if (!chatId) return [];
566
+ try {
567
+ if (event.type === 'turn_completed' || event.type === 'turn_failed') {
568
+ // Staleness guard: only idle if this event's turn is still the chat's
569
+ // latest emitted envelope — a late/retried completed event for a
570
+ // superseded turn must not clear the newer turn's indicator. Fail-open
571
+ // when the marker is unavailable (a stuck ring is worse than a blink).
572
+ const current = await ctx.store?.get(turnEnvelopeKey(chatId)).catch(() => null);
573
+ if (typeof current === 'string' && current && !event.envelopeIds.includes(current)) {
574
+ return [];
575
+ }
576
+ const sessionId = await ensureSession(ctx, chatId);
577
+ if (sessionId) {
578
+ const result = await patchSession(ctx, sessionId, { status: 'idle' });
579
+ // A closed session is already terminal (frontend shows done) — just
580
+ // drop the cache so the next dispatch resolves a fresh one.
581
+ if (result === 'stale') await invalidateSession(ctx, chatId);
582
+ }
583
+ return [];
584
+ }
585
+ if (
586
+ event.type === 'model_reasoning' ||
587
+ event.type === 'tool_call' ||
588
+ event.type === 'tool_result'
589
+ ) {
590
+ const sessionId = await ensureSession(ctx, chatId);
591
+ if (sessionId) {
592
+ const result = await createTraceStep(ctx, sessionId, chatId, event);
593
+ // Dropped step is fine (display feed); uncache so the NEXT event
594
+ // resolves a live session instead of failing forever.
595
+ if (result === 'stale') await invalidateSession(ctx, chatId);
596
+ }
597
+ return [];
598
+ }
599
+ // turn_started (processing is input-step-driven) and execution_paused
600
+ // (E3 — no resolve loop wired yet, HITL deliberately deferred) are
601
+ // ignored; observe only requests [turn, steps].
602
+ } catch (err) {
603
+ console.error('[parel-channel] agent event handling failed', err);
604
+ }
605
+ return [];
606
+ }
607
+
608
+ /** Ack a dispatch by source so it leaves the pending queue (idempotent). */
609
+ function ackEffect(ctx: ConnectorContext, sourceType: string, sourceId: string): ConnectorEffect {
610
+ return {
611
+ type: 'fetch',
612
+ request: {
613
+ url: `${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/dispatch/ack`,
614
+ method: 'POST',
615
+ headers: {
616
+ Authorization: `Bearer ${requireAgk(ctx)}`,
617
+ 'Content-Type': 'application/json',
618
+ },
619
+ body: JSON.stringify({ source_type: sourceType, source_id: sourceId }),
620
+ },
621
+ idempotencyKey: `ack:${sourceType}:${sourceId}`,
622
+ };
623
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { ChannelConnector } from '@parel/plugin-sdk';
2
+ import { connectParall } from './connect.js';
3
+ import { buildParallDelivery } from './delivery.js';
4
+ import { catchUpParall, handleParallAgentEvent, handleParallFrame } from './inbound.js';
5
+
6
+ /**
7
+ * Parall channel plugin for the parel runtime.
8
+ *
9
+ * Lets a parel agent treat Parall as a `managed_ws` channel — mirroring what
10
+ * channel-slack-socket does for Slack. The parel runtime owns the connection
11
+ * lifecycle + agent routing; this connector just supplies the three hooks:
12
+ *
13
+ * connect() → the Parall gateway WS url (authenticated by the agent's agk_)
14
+ * onMessage() → translate a Parall dispatch frame into a ChannelEnvelope
15
+ * deliver() → post the agent's reply back to the Parall chat via the API
16
+ *
17
+ * This is why Parall needs NO server-side worker/bridge: the integration lives
18
+ * here, runs inside parel, and is service-to-service from parel's side.
19
+ */
20
+ const connector: ChannelConnector = {
21
+ connect: connectParall,
22
+ onOpen: catchUpParall,
23
+ onMessage: handleParallFrame,
24
+ onAgentEvent: handleParallAgentEvent,
25
+ deliver: buildParallDelivery,
26
+ };
27
+
28
+ export default connector;