@parall/parel-channel 1.40.0 → 1.41.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/inbound.js CHANGED
@@ -1,7 +1,47 @@
1
- import { buildChannelPrompt, buildChatPrompt } from './channel-prompt.js';
2
- import { parallApiUrl, parallOrgId, requireAgk } from './connect.js';
3
- import { createChannelInputStep, createErrorStep, createInputStep, createTraceStep, ensureSession, invalidateSession, markDispatchReceived, patchSession, REQUEST_TIMEOUT_MS, TURN_ENVELOPE_KEY, } from './session.js';
4
- export async function handleParallFrame(frame, ctx) {
1
+ import { buildChatPrompt } from './channel-prompt.js';
2
+ import { parallApiUrl, parallOrgId, requireAgk, sandboxEnabled } from './connect.js';
3
+ import { effectsForChannelDispatch, PROVIDER_LOOKUP_TIMEOUT_MS } from './inbound-channel.js';
4
+ import { buildForkScopePrefix, bumpForkRetryAttempts, childConfirmed, childRefKnown, clearForkState, clearForkSubject, FORK_RETRY_DELAY_MS, FORK_RETRY_PREFIX, handleChildSpawnFailed, MAX_SPAWN_VERIFY_ATTEMPTS, noteMainTurnEvent, planForkDecision, recordSpawn, settleChildEvent, trackFollowUpAck, } from './fork.js';
5
+ import { asChildSpawnFailed, asConnectorEffects, } from './parel-sdk-compat.js';
6
+ import { ackByIdEffect, ackEffect, conversationKey, createErrorStep, fetchMainSessionFresh, createInputStep, createTraceStep, createTypedInputStep, ensureChildSession, ensureSession, invalidateChildSession, invalidateSession, markDispatchReceived, patchSession, reportingEnabled, SESSION_CACHE_KEY, TURN_ENVELOPE_KEY, } from './session.js';
7
+ import { isTypedEventType, planTypedDispatch } from './typed-dispatch.js';
8
+ /**
9
+ * Connection-local hook serialization. The parel ConnectorHost dispatches
10
+ * socket callbacks fire-and-forget (verified against connector-host.ts:
11
+ * `onMessage: (data) => { this.handleMessage(data).catch(…) }`), so two
12
+ * frames' async handling can interleave at await points inside one DO
13
+ * isolate. Every read-then-write protocol here — the turnEnvelope marker,
14
+ * fork planForkDecision→recordSpawn, pendingAck parking — assumes serial
15
+ * execution, so ALL hook bodies run through this one promise chain. Same
16
+ * connection ⇒ same DO isolate ⇒ same module instance, so a module-level
17
+ * chain is exactly connection-scoped TODAY — if parel ever pools multiple
18
+ * connections into one isolate, key this chain on ctx.connectionId before
19
+ * anything else (cross-connection head-of-line blocking would be silent).
20
+ * Failures don't break the chain.
21
+ */
22
+ let hookChain = Promise.resolve();
23
+ let chainConnectionId;
24
+ /** Surface a violated isolation assumption as a log line, not silent
25
+ * mis-serialization (see the chain doc above). */
26
+ export function assertChainConnection(ctx) {
27
+ if (chainConnectionId === undefined) {
28
+ chainConnectionId = ctx.connectionId;
29
+ }
30
+ else if (chainConnectionId !== ctx.connectionId) {
31
+ console.warn(`[parel-channel] hook chain saw a second connection (${chainConnectionId} → ${ctx.connectionId}) — the one-connection-per-isolate assumption broke; key the chain on connectionId`);
32
+ chainConnectionId = ctx.connectionId;
33
+ }
34
+ }
35
+ export function serialized(fn) {
36
+ const next = hookChain.then(fn, fn);
37
+ hookChain = next.then(() => undefined, () => undefined);
38
+ return next;
39
+ }
40
+ export function handleParallFrame(frame, ctx) {
41
+ assertChainConnection(ctx);
42
+ return serialized(() => handleParallFrameInner(frame, ctx));
43
+ }
44
+ async function handleParallFrameInner(frame, ctx) {
5
45
  let event;
6
46
  try {
7
47
  const raw = typeof frame.data === 'string' ? frame.data : new TextDecoder().decode(frame.data);
@@ -10,6 +50,23 @@ export async function handleParallFrame(frame, ctx) {
10
50
  catch {
11
51
  return [];
12
52
  }
53
+ if (event.type === 'agent.new_session') {
54
+ // New Session rotated the main conversation line (server-driven binding
55
+ // reset). Stale fork routing surviving it would deliver post-reset
56
+ // messages into pre-reset children (old context) or fork off a busy
57
+ // marker for a session that no longer exists — purge it all, and drop
58
+ // the cached fork ase_ rows so the next event resolves fresh ones.
59
+ try {
60
+ const refs = await clearForkState(ctx);
61
+ for (const ref of refs) {
62
+ await invalidateChildSession(ctx, ref);
63
+ }
64
+ }
65
+ catch (err) {
66
+ console.error('[parel-channel] new-session fork purge failed', err);
67
+ }
68
+ return [];
69
+ }
13
70
  if (event.type !== 'dispatch.new' || !event.data)
14
71
  return [];
15
72
  try {
@@ -22,21 +79,94 @@ export async function handleParallFrame(frame, ctx) {
22
79
  return [];
23
80
  }
24
81
  }
82
+ /**
83
+ * Fork retry timers (armed by child_spawn_failed): re-plan the stranded
84
+ * message through the normal dispatch pipeline. onTimer returns the FULL
85
+ * effect union (unlike onAgentEvent), so the re-plan can emit/spawn/ack.
86
+ * The parked row is cleared first — a re-plan that fails transiently leaves
87
+ * the WorkItem in `received` for the reconnect sweep, same as any dispatch.
88
+ */
89
+ export function handleParallTimer(timer, ctx) {
90
+ return serialized(() => handleParallTimerInner(timer, ctx));
91
+ }
92
+ async function handleParallTimerInner(timer, ctx) {
93
+ if (!timer.key.startsWith(FORK_RETRY_PREFIX))
94
+ return [];
95
+ const parked = (await ctx.store?.get(timer.key).catch(() => null));
96
+ if (!parked?.source_id)
97
+ return [];
98
+ // Re-planning is idempotent on every path — an already-acked opening hits
99
+ // the confirmed branch (ack re-send, harmless), an unconfirmed one bumps
100
+ // the bounded verification counter, deliverTo replays dedupe on envelope
101
+ // id — so the timer re-drives unconditionally.
102
+ try {
103
+ const effects = await effectsForDispatch(parked, ctx);
104
+ // The parked row's only live purpose is the attempts counter across
105
+ // verification rounds — signaled by the re-plan re-arming THIS key. Any
106
+ // other outcome (confirmed ack / deliverTo / main / give-up) resolved
107
+ // the message, and the row would otherwise leak forever (no TTL).
108
+ const rearmed = effects.some((e) => e.type === 'setTimer' && e.key === timer.key);
109
+ if (!rearmed)
110
+ await ctx.store?.delete(timer.key).catch(() => { });
111
+ return effects;
112
+ }
113
+ catch (err) {
114
+ console.error('[parel-channel] fork retry re-plan failed', err);
115
+ return [];
116
+ }
117
+ }
25
118
  /**
26
119
  * Sweep pending dispatches on (re)connect — the live WS push has no replay.
27
120
  * Paginates with the server cursor so a long outage's backlog is not silently
28
121
  * truncated (bounded to keep a pathological backlog from wedging onOpen; the
29
122
  * remainder is picked up on the next reconnect sweep).
30
123
  */
31
- export async function catchUpParall(ctx) {
124
+ export function catchUpParall(ctx) {
125
+ return serialized(() => catchUpParallInner(ctx));
126
+ }
127
+ async function catchUpParallInner(ctx) {
128
+ // New Session generation check (must run before any dispatch replay): the
129
+ // `agent.new_session` WS push is not replayed, so a reset that happened
130
+ // while this connection was down would leave stale fork routing behind —
131
+ // post-reset messages would land in pre-reset children. The main ase_ IS
132
+ // the generation: New Session closes it and the next get-or-create mints a
133
+ // fresh id, so compare the cached id against the server's current one and
134
+ // purge fork state on rotation. Every missed-event scenario passes through
135
+ // onOpen (a live socket delivers the event; a dead one reconnects here).
136
+ // The cached id is never dropped before the fresh (bypass-cache) read
137
+ // succeeds — it is the only generation token, and losing it to a transient
138
+ // /sessions failure would silently skip the purge until the fork TTLs
139
+ // expire.
140
+ try {
141
+ const cachedMain = (await ctx.store?.get(SESSION_CACHE_KEY).catch(() => null));
142
+ if (cachedMain) {
143
+ const freshMain = await fetchMainSessionFresh(ctx);
144
+ if (freshMain && freshMain !== cachedMain) {
145
+ const refs = await clearForkState(ctx);
146
+ for (const ref of refs) {
147
+ await invalidateChildSession(ctx, ref);
148
+ }
149
+ console.warn('[parel-channel] main session rotated while offline — fork state purged');
150
+ }
151
+ }
152
+ // Capability revalidation: a parked forkDisabled latch reflects the
153
+ // binding shape at failure time; the fleet sweep converges bindings
154
+ // without restarting the connection, so a reconnect is the natural
155
+ // revalidation point. If forking is truly still disabled, the first
156
+ // spawn attempt re-parks the latch at the cost of one failed effect.
157
+ await ctx.store?.delete('forkDisabled').catch(() => { });
158
+ }
159
+ catch (err) {
160
+ console.error('[parel-channel] new-session generation check failed', err);
161
+ }
32
162
  const effects = [];
33
163
  try {
34
164
  const apiUrl = parallApiUrl(ctx);
35
165
  const agk = requireAgk(ctx);
36
166
  const orgId = parallOrgId(ctx);
37
167
  let cursor = '';
38
- // Page bound is a wedge guard, not a coverage target. Non-message
39
- // dispatches stay pending (deliberately — see effectsForDispatch) and the
168
+ // Page bound is a wedge guard, not a coverage target. Unknown dispatch
169
+ // types stay pending (deliberately — see effectsForDispatch) and the
40
170
  // list is FIFO, so the bound must comfortably exceed any realistic
41
171
  // unsupported backlog or old rows could starve newer DMs out of the sweep.
42
172
  // 40 pages ≈ 2000 dispatches per sweep; log when we hit the ceiling so a
@@ -92,11 +222,30 @@ async function effectsForDispatch(data, ctx) {
92
222
  // lives on the provider, not in a Parall chat).
93
223
  return effectsForChannelDispatch(sourceId, dispatchId, ctx);
94
224
  }
95
- // Non-message dispatches (task_assign, schedule.fire, …) stay PENDING on
96
- // purpose: they are meaningful work a future connector version will handle,
97
- // and acking would silently drop it. Message dispatches that can NEVER
98
- // become processable are acked-and-dropped below instead, so the pending
99
- // queue (and the reconnect catch-up sweep) is bounded by real future work.
225
+ const eventType = String(data.event_type ?? '');
226
+ if (sourceId && isTypedEventType(eventType)) {
227
+ // Legacy configs without parallAgentId predate the whole reporting
228
+ // surface AND the typed handlers' stale guards (planTask compares the
229
+ // assignee against it) — emitting there would deliver reassigned tasks
230
+ // and record nothing. Keep typed work pending until the connection is
231
+ // redeployed on the current shape (same posture as unknown types).
232
+ if (!reportingEnabled(ctx)) {
233
+ return [];
234
+ }
235
+ // Conversational-only deployments (no sandbox → no `parall` CLI) cannot
236
+ // act on CLI-only typed work — emitting AND acking it would silently
237
+ // consume real work. Keep it pending (same posture as unknown types);
238
+ // approval_decided is exempt (it lives in a chat, replies auto-deliver).
239
+ if (!sandboxEnabled(ctx) && eventType !== 'approval_decided') {
240
+ return [];
241
+ }
242
+ return effectsForTypedDispatch(data, ctx);
243
+ }
244
+ // Unknown non-message dispatches stay PENDING on purpose: they are
245
+ // meaningful work a future connector version will handle, and acking would
246
+ // silently drop it. Message dispatches that can NEVER become processable
247
+ // are acked-and-dropped below instead, so the pending queue (and the
248
+ // reconnect catch-up sweep) is bounded by real future work.
100
249
  if (sourceType !== 'message' || !sourceId)
101
250
  return [];
102
251
  if (!chatId) {
@@ -123,22 +272,238 @@ async function effectsForDispatch(data, ctx) {
123
272
  const text = msg?.content?.text ?? '';
124
273
  // A thread reply anchors the agent's answer to the same thread.
125
274
  const threadRootId = msg?.thread_root_id || undefined;
126
- if (!text) {
127
- // Attachment-only / empty-text messages never grow text — MVP has no
128
- // attachment path, so ack-and-drop rather than let them pile up in the
129
- // pending queue forever.
275
+ // Attachments render as reference lines — the agent knows they exist and
276
+ // pulls the bytes itself via its sandbox CLI (standard-runtime contract).
277
+ const attachments = (msg?.attachments ?? [])
278
+ .filter((a) => typeof a?.id === 'string' && a.id)
279
+ .map((a) => ({
280
+ id: String(a.id),
281
+ fileName: String(a.file_name ?? ''),
282
+ fileSize: typeof a.file_size === 'number' ? a.file_size : 0,
283
+ mimeType: String(a.mime_type ?? ''),
284
+ }));
285
+ if (!text && attachments.length === 0) {
286
+ // Truly empty messages never grow content — ack-and-drop rather than let
287
+ // them pile up in the pending queue forever. (Attachment-only messages
288
+ // used to take this path; they now ride the attachment lines instead.)
130
289
  return [ackEffect(ctx, sourceType, sourceId)];
131
290
  }
132
- // Progress reporting (best-effort, parall-runtime-indicator-plan.md §3):
133
- // received lights the pending ring, the active+trigger patch arms the done
134
- // signal, the input step flips the ring to processing. received MUST settle
135
- // before this function returns — the ack effect below moves the dispatch
136
- // row out of 'pending', and MarkReceived only transitions pending rows.
137
- // It is deliberately NOT gated on the session resolving: it only touches
138
- // the dispatch row, and a transient session failure must not also cost the
139
- // pending ring (a later successful turn's idle clears agent-level pendings).
140
- const receivedSettled = markDispatchReceived(ctx, sourceType, sourceId);
291
+ // Frame the message with its chat of origin: all chats share the agent's
292
+ // one main session, so the model must see WHERE each message comes from or
293
+ // it answers chat B inside chat A's train of thought. The name is cosmetic
294
+ // garnish and must never block the emit/ack hot path (the catch-up sweep is
295
+ // fully serialized — one slow lookup would stall the whole backlog): only
296
+ // the cached name is used, and a miss kicks off a fire-and-forget prefetch
297
+ // so the NEXT message from this chat gets the name. The id alone already
298
+ // marks the context switch.
299
+ const chatName = await cachedChatName(ctx, chatId);
300
+ const senderId = msg?.sender_id ? String(msg.sender_id) : undefined;
301
+ const framedText = buildChatPrompt({
302
+ chatId,
303
+ chatName,
304
+ senderId,
305
+ threadRootId,
306
+ text,
307
+ attachments,
308
+ });
141
309
  const envelopeId = dispatchId || `${sourceType}:${sourceId}`;
310
+ // Input-step summary must never be empty (attachment-only messages).
311
+ const stepText = text || `[${attachments.length} attachment(s)]`;
312
+ // Thread-aware conversation identity: F2 grouping / F3 injection / fork
313
+ // routing all key on the subject, and a turn carries ONE reply route — a
314
+ // thread must never be absorbed into its sibling's turn (session.ts
315
+ // conversationKey doc).
316
+ const subject = conversationKey(chatId, threadRootId);
317
+ // Fork-on-busy scheduling (fork.ts): a live child owns its conversation;
318
+ // main mid-turn on ANOTHER conversation forks a new child; everything else
319
+ // rides main. Typed and channel_message dispatches always ride main.
320
+ const decision = await planForkDecision(ctx, subject, sourceId);
321
+ // Per-turn invocation context: parel snapshots this at turn start and
322
+ // consume-gated plugins receive it — sandbox-e2b flattens it into per-exec
323
+ // env, so `parall` CLI calls inside the sandbox land on the right chat.
324
+ const invocationContext = {
325
+ PRLL_CHAT_ID: chatId,
326
+ PRLL_TRIGGER_MESSAGE_ID: sourceId,
327
+ ...(threadRootId ? { PRLL_THREAD_ROOT_ID: threadRootId } : {}),
328
+ };
329
+ const envelope = {
330
+ id: envelopeId,
331
+ orgId,
332
+ connectionId: ctx.connectionId,
333
+ source: 'parall',
334
+ type: 'message',
335
+ // The binding's `main` routing sends every envelope to the agent's
336
+ // one session; subject still carries the conversation (chat, or
337
+ // chat~thread) so parel's turn input grouping (F2) and mid-turn
338
+ // injection (F3) never mix conversations in one turn, and agent
339
+ // events mirror it back for per-conversation correlation.
340
+ subject,
341
+ data: { text: framedText, chatId, messageId: sourceId, threadRootId },
342
+ // chat id + thread anchor ride replyRoute.data so deliver() knows
343
+ // where to post back (same shape channel-slack-socket uses for its
344
+ // channel id).
345
+ replyRoute: {
346
+ kind: 'provider_http',
347
+ connectionId: ctx.connectionId,
348
+ // envelopeId lets deliver() run the same staleness guard as
349
+ // onAgentEvent against the shared turnEnvelope marker.
350
+ data: { chatId, messageId: sourceId, threadRootId, envelopeId },
351
+ },
352
+ context: invocationContext,
353
+ };
354
+ if (decision.mode === 'deliverTo') {
355
+ // Follow-up for a conversation a live child owns: the envelope rides the
356
+ // full ingress contract but session resolution goes to the child (§18.2).
357
+ // Progress reporting lands on the CHILD's ase_ — its turn does the work,
358
+ // and the replyRoute carries childRef so deliver() links the reply to the
359
+ // child session (and idles IT, not main).
360
+ const receivedSettled = markDispatchReceived(ctx, sourceType, sourceId);
361
+ const childAse = await ensureChildSession(ctx, decision.childRef);
362
+ if (childAse) {
363
+ const results = await Promise.all([
364
+ patchSession(ctx, childAse, { status: 'active', trigger_message_id: sourceId }),
365
+ createInputStep(ctx, childAse, {
366
+ chatId,
367
+ messageId: sourceId,
368
+ senderId,
369
+ text: stepText,
370
+ }),
371
+ ]);
372
+ // A closed child ase_ (New Session closed the whole family) just drops
373
+ // the cache; the next event rebuilds it.
374
+ if (results.includes('stale'))
375
+ await invalidateChildSession(ctx, decision.childRef);
376
+ }
377
+ await receivedSettled;
378
+ const childEnvelope = {
379
+ ...envelope,
380
+ replyRoute: {
381
+ ...envelope.replyRoute,
382
+ data: { ...envelope.replyRoute.data, childRef: decision.childRef },
383
+ },
384
+ };
385
+ // Until the child's first observed event confirms provisioning, a
386
+ // deliverTo can still land in a spawn that fails terminally (the host
387
+ // ignores its queued events) — park the WorkItem ack on the bookkeeping
388
+ // row instead of consuming it on emit. Ingress dedupe (same envelope id)
389
+ // makes the eventual replay safe. A full parking list (cap) does NOT
390
+ // degrade to ack-on-emit — that would trade bounded storage for message
391
+ // loss; the overflow stays pending un-emitted and a later replay finds
392
+ // either a confirmed child (normal ack-on-emit) or a fresh decision.
393
+ if (decision.trackAck && dispatchId) {
394
+ const parked = await trackFollowUpAck(ctx, subject, decision.childRef, {
395
+ dispatchId,
396
+ sourceId,
397
+ });
398
+ if (!parked) {
399
+ // Parking cap hit: stay pending, but arm a local retry — a healthy
400
+ // long-lived socket never re-runs the reconnect sweep, so without a
401
+ // timer the overflow follow-up would strand until the next
402
+ // disconnect. By the retry the child is usually confirmed (normal
403
+ // ack-on-emit) or gone (fresh decision).
404
+ const retryKey = `${FORK_RETRY_PREFIX}${dispatchId}`;
405
+ await bumpForkRetryAttempts(ctx, retryKey, {
406
+ id: dispatchId,
407
+ source_type: sourceType,
408
+ source_id: sourceId,
409
+ chat_id: chatId,
410
+ });
411
+ return asConnectorEffects([
412
+ { type: 'setTimer', key: retryKey, at: ctx.now() + FORK_RETRY_DELAY_MS },
413
+ ]);
414
+ }
415
+ return asConnectorEffects([
416
+ { type: 'emitEvent', event: childEnvelope, deliverTo: { childRef: decision.childRef } },
417
+ ]);
418
+ }
419
+ return asConnectorEffects([
420
+ { type: 'emitEvent', event: childEnvelope, deliverTo: { childRef: decision.childRef } },
421
+ ackEffect(ctx, sourceType, sourceId),
422
+ ]);
423
+ }
424
+ if (decision.mode === 'spawn') {
425
+ // Main is mid-turn on another conversation — fork. The opening message
426
+ // IS the spawn input (one turn, no idle warm-up); its dispatch is NOT
427
+ // acked here: the pending ack (by WorkItem id) rides the fork bookkeeping
428
+ // and fires on the child's first observed event, so a spawn failure
429
+ // leaves the message recoverable instead of silently lost. A REPLAY of
430
+ // this same message re-enters here with the recorded childRef (fork.ts
431
+ // branch 1a): the platform spawn is idempotent on the ref, so re-issuing
432
+ // is both the transient-failure retry and the duplicate-processing guard.
433
+ // If the child is already CONFIRMED (events observed) the replay means
434
+ // only the ACK went missing — a re-spawn is a silent no-op that emits no
435
+ // new event, so ack directly instead of waiting for one.
436
+ const replayed = await childConfirmed(ctx, subject, decision.childRef);
437
+ if (replayed && dispatchId) {
438
+ return [ackByIdEffect(ctx, dispatchId)];
439
+ }
440
+ // Verification-cap check FIRST, before any side effect: onAgentEvent is
441
+ // best-effort — if every child event is lost, a replayed spawn is a
442
+ // silent idempotent no-op that never produces a new event, so each spawn
443
+ // pass bumps a bounded counter and re-arms a timer. Once the cap is
444
+ // exceeded the ref is a black hole: clear the fork bookkeeping and FALL
445
+ // THROUGH to the main path in THIS pass (emitting yet another spawn
446
+ // would leave the message stranded with no timer and no bookkeeping
447
+ // until a reconnect).
448
+ let spawnBlackHoled = false;
449
+ const timerEffects = [];
450
+ if (dispatchId) {
451
+ const retryKey = `${FORK_RETRY_PREFIX}${dispatchId}`;
452
+ const attempts = await bumpForkRetryAttempts(ctx, retryKey, {
453
+ id: dispatchId,
454
+ source_type: sourceType,
455
+ source_id: sourceId,
456
+ chat_id: chatId,
457
+ });
458
+ if (attempts <= MAX_SPAWN_VERIFY_ATTEMPTS) {
459
+ timerEffects.push({ type: 'setTimer', key: retryKey, at: ctx.now() + FORK_RETRY_DELAY_MS });
460
+ }
461
+ else {
462
+ spawnBlackHoled = true;
463
+ await clearForkSubject(ctx, subject, decision.childRef);
464
+ await ctx.store?.delete(retryKey).catch(() => { });
465
+ }
466
+ }
467
+ if (!spawnBlackHoled) {
468
+ const receivedSettled = markDispatchReceived(ctx, sourceType, sourceId);
469
+ const childAse = await ensureChildSession(ctx, decision.childRef);
470
+ if (childAse) {
471
+ const results = await Promise.all([
472
+ patchSession(ctx, childAse, { status: 'active', trigger_message_id: sourceId }),
473
+ createInputStep(ctx, childAse, {
474
+ chatId,
475
+ messageId: sourceId,
476
+ senderId,
477
+ text: stepText,
478
+ }),
479
+ ]);
480
+ if (results.includes('stale'))
481
+ await invalidateChildSession(ctx, decision.childRef);
482
+ }
483
+ await recordSpawn(ctx, subject, decision.childRef, { dispatchId, sourceId });
484
+ await receivedSettled;
485
+ return asConnectorEffects([
486
+ {
487
+ type: 'spawnChildSession',
488
+ childRef: decision.childRef,
489
+ input: buildForkScopePrefix(chatId, threadRootId) + framedText,
490
+ subject,
491
+ },
492
+ ...timerEffects,
493
+ ]);
494
+ }
495
+ // fall through: black-holed spawn rides main below.
496
+ }
497
+ // Main path. Progress reporting (best-effort,
498
+ // parall-runtime-indicator-plan.md §3): received lights the pending ring,
499
+ // the active+trigger patch arms the done signal, the input step flips the
500
+ // ring to processing. received MUST settle before this function returns —
501
+ // the ack effect below moves the dispatch row out of 'pending', and
502
+ // MarkReceived only transitions pending rows. It is deliberately NOT gated
503
+ // on the session resolving: it only touches the dispatch row, and a
504
+ // transient session failure must not also cost the pending ring (a later
505
+ // successful turn's idle clears agent-level pendings).
506
+ const receivedSettled = markDispatchReceived(ctx, sourceType, sourceId);
142
507
  let sessionId = await ensureSession(ctx);
143
508
  if (sessionId) {
144
509
  // The guard marker goes down BEFORE any session write: a stale
@@ -148,6 +513,7 @@ async function effectsForDispatch(data, ctx) {
148
513
  // envelope id and idle the session out from under this message. The
149
514
  // marker is agent-global: chats share the one main session, so a chat-A
150
515
  // done signal must not idle it while this (later) message is pending.
516
+ // Child turns never touch it — only main-bound envelopes arm it.
151
517
  // (Residual read-then-patch overlap is zero when the host runs a
152
518
  // connection's hooks serially, per the C3 contract / C3b confirm item.)
153
519
  await ctx.store?.set(TURN_ENVELOPE_KEY, envelopeId).catch(() => { });
@@ -156,8 +522,8 @@ async function effectsForDispatch(data, ctx) {
156
522
  createInputStep(ctx, sid, {
157
523
  chatId,
158
524
  messageId: sourceId,
159
- senderId: msg?.sender_id ? String(msg.sender_id) : undefined,
160
- text,
525
+ senderId,
526
+ text: stepText,
161
527
  }),
162
528
  ]);
163
529
  const results = await report(sessionId);
@@ -174,142 +540,50 @@ async function effectsForDispatch(data, ctx) {
174
540
  }
175
541
  }
176
542
  await receivedSettled;
177
- // Per-turn invocation context: parel snapshots this at turn start and
178
- // consume-gated plugins receive it — sandbox-e2b flattens it into per-exec
179
- // env, so `parall` CLI calls inside the sandbox land on the right chat.
180
- const invocationContext = {
181
- PRLL_CHAT_ID: chatId,
182
- PRLL_TRIGGER_MESSAGE_ID: sourceId,
183
- ...(threadRootId ? { PRLL_THREAD_ROOT_ID: threadRootId } : {}),
184
- };
185
- // Frame the message with its chat of origin: all chats share the agent's
186
- // one main session, so the model must see WHERE each message comes from or
187
- // it answers chat B inside chat A's train of thought. The name is cosmetic
188
- // garnish and must never block the emit/ack hot path (the catch-up sweep is
189
- // fully serialized — one slow lookup would stall the whole backlog): only
190
- // the cached name is used, and a miss kicks off a fire-and-forget prefetch
191
- // so the NEXT message from this chat gets the name. The id alone already
192
- // marks the context switch.
193
- const chatName = await cachedChatName(ctx, chatId);
194
- const framedText = buildChatPrompt({
195
- chatId,
196
- chatName,
197
- senderId: msg?.sender_id ? String(msg.sender_id) : undefined,
198
- threadRootId,
199
- text,
200
- });
201
- const effects = [
202
- {
203
- type: 'emitEvent',
204
- event: {
205
- id: envelopeId,
206
- orgId,
207
- connectionId: ctx.connectionId,
208
- source: 'parall',
209
- type: 'message',
210
- // The binding's `main` routing sends every envelope to the agent's
211
- // one session; subject still carries the chat so parel's turn input
212
- // grouping (F2) never mixes conversations in one turn and agent
213
- // events mirror it back for per-chat correlation.
214
- subject: chatId,
215
- data: { text: framedText, chatId, messageId: sourceId, threadRootId },
216
- // chat id + thread anchor ride replyRoute.data so deliver() knows
217
- // where to post back (same shape channel-slack-socket uses for its
218
- // channel id).
219
- replyRoute: {
220
- kind: 'provider_http',
221
- connectionId: ctx.connectionId,
222
- // envelopeId lets deliver() run the same staleness guard as
223
- // onAgentEvent against the shared turnEnvelope marker.
224
- data: { chatId, messageId: sourceId, threadRootId, envelopeId },
225
- },
226
- context: invocationContext,
227
- },
228
- },
229
- ackEffect(ctx, sourceType, sourceId),
230
- ];
231
- return effects;
543
+ return [{ type: 'emitEvent', event: envelope }, ackEffect(ctx, sourceType, sourceId)];
232
544
  }
233
545
  /**
234
- * channel_message dispatch → agent (external IM channel,
235
- * external-im-channel-design.md). Same pipeline shape as the message path,
236
- * with the ChannelConversation (chv_) standing in for the chat as the
237
- * routing subject: fetch the durable ChannelMessage + its conversation,
238
- * resolve the provider for prompt labeling (cached — the connection→provider
239
- * mapping is stable), frame the prompt for the EXTERNAL audience, report
240
- * progress against the conversation-keyed session, and ack by source.
546
+ * Typed (non-message) dispatch → main-session envelope. The heavy lifting
547
+ * (entity fetch + event-body rendering + stale/pending classification) lives
548
+ * in typed-dispatch.ts; this function owns the shared emit pipeline: session
549
+ * bookkeeping, the turnEnvelope marker, the envelope, and the ack.
241
550
  *
242
- * Error contract mirrors the message path (and agent-core's
243
- * fetchAndHandleChannelMessage): 404/403 on the source entities is
244
- * permanently unusable → ack-and-drop; a transient failure keeps the
245
- * dispatch pending for the catch-up sweep.
551
+ * Typed events always ride MAIN (never fork): nobody is watching a chat
552
+ * indicator for them, so head-of-line latency costs nothing, and keeping
553
+ * them on the orchestrator preserves task/schedule context continuity.
246
554
  */
247
- async function effectsForChannelDispatch(sourceId, dispatchId, ctx) {
248
- const apiUrl = parallApiUrl(ctx);
249
- const orgId = parallOrgId(ctx);
250
- const authHeaders = { Authorization: `Bearer ${requireAgk(ctx)}` };
251
- const get = (path, timeoutMs = REQUEST_TIMEOUT_MS) => fetch(`${apiUrl}/api/v1/orgs/${orgId}${path}`, {
252
- headers: authHeaders,
253
- signal: AbortSignal.timeout(timeoutMs),
254
- });
255
- const m = await get(`/channel-messages/${sourceId}`);
256
- if (!m.ok) {
257
- if (m.status === 404 || m.status === 403) {
258
- // Deleted / inaccessible (also the shape a disabled org feature flag
259
- // takes) — permanently unusable, drop it.
260
- return [ackEffect(ctx, 'channel_message', sourceId)];
261
- }
262
- return []; // transient: keep pending, the catch-up sweep retries
263
- }
264
- const msg = (await m.json().catch(() => null));
265
- const conversationId = msg?.conversation_id ? String(msg.conversation_id) : undefined;
266
- const text = msg?.text ?? '';
267
- if (!conversationId) {
268
- // No conversation → no session key and no reply target: unusable.
269
- return [ackEffect(ctx, 'channel_message', sourceId)];
270
- }
271
- if (!text) {
272
- // The ingress adapter only persists mechanically parsed text; a row with
273
- // none will never grow any (same reasoning as attachment-only chat
274
- // messages) — drop rather than let it pile up in the pending queue.
275
- return [ackEffect(ctx, 'channel_message', sourceId)];
276
- }
277
- const c = await get(`/channel-conversations/${conversationId}`);
278
- if (!c.ok) {
279
- if (c.status === 404 || c.status === 403) {
280
- return [ackEffect(ctx, 'channel_message', sourceId)];
281
- }
555
+ async function effectsForTypedDispatch(data, ctx) {
556
+ // No markDispatchReceived here ON PURPOSE: typed dispatches have no
557
+ // message-level activity indicator (DispatchResolvedData: "typed
558
+ // dispatches have no indicator"), so there is no pending ring to light —
559
+ // the typed input step below is the session panel's timeline entry.
560
+ const sourceType = String(data.source_type ?? '');
561
+ const sourceId = String(data.source_id ?? '');
562
+ const dispatchId = String(data.id ?? '');
563
+ // Typed WorkItems ack by id, never by source: sibling rows (a task
564
+ // mutation's task_assign + task_update) share (source_type, source_id),
565
+ // and the source ack would terminally resolve work that was never emitted.
566
+ const ack = () => dispatchId ? ackByIdEffect(ctx, dispatchId) : ackEffect(ctx, sourceType, sourceId);
567
+ const plan = await planTypedDispatch(data, ctx);
568
+ if (plan.outcome === 'pending')
282
569
  return [];
283
- }
284
- const conv = (await c.json().catch(() => null));
285
- // Provider (= clip alias) for prompt labeling + the reply hint.
286
- // Best-effort: an unresolved provider degrades the wording, never blocks.
287
- const connectionId = conv?.connection_id ? String(conv.connection_id) : undefined;
288
- const provider = connectionId ? await resolveChannelProvider(ctx, connectionId, get) : undefined;
289
- const senderName = msg?.external_user_name || msg?.external_user_id || 'external user';
290
- const externalConversationId = conv?.external_conversation_id
291
- ? String(conv.external_conversation_id)
292
- : undefined;
293
- const externalMessageId = msg?.external_message_id ? String(msg.external_message_id) : undefined;
294
- // Progress reporting — identical ordering contract to the message path
295
- // (see the comments there): received settles before the ack effect is
296
- // returned; the turnEnvelope marker goes down before any session write.
297
- const receivedSettled = markDispatchReceived(ctx, 'channel_message', sourceId);
298
- const envelopeId = dispatchId || `channel_message:${sourceId}`;
570
+ if (plan.outcome === 'stale')
571
+ return [ack()];
572
+ const envelopeId = dispatchId || `${sourceType}:${sourceId}`;
299
573
  let sessionId = await ensureSession(ctx);
300
574
  if (sessionId) {
575
+ // Same marker contract as the message path: a typed envelope is now the
576
+ // agent's latest emitted input, so older turns' done signals must not
577
+ // idle the session out from under it.
301
578
  await ctx.store?.set(TURN_ENVELOPE_KEY, envelopeId).catch(() => { });
302
579
  const report = (sid) => Promise.all([
303
- patchSession(ctx, sid, { status: 'active', trigger_message_id: sourceId }),
304
- createChannelInputStep(ctx, sid, {
305
- conversationId,
306
- channelMessageId: sourceId,
307
- provider,
308
- externalConversationId,
309
- senderId: msg?.external_user_id ? String(msg.external_user_id) : 'external',
310
- senderName,
311
- text,
312
- sentAt: msg?.received_at ? String(msg.received_at) : undefined,
580
+ patchSession(ctx, sid, { status: 'active' }),
581
+ createTypedInputStep(ctx, sid, {
582
+ target: plan.stepTarget,
583
+ triggerType: plan.triggerType,
584
+ dispatchId,
585
+ sourceId,
586
+ summary: plan.summary,
313
587
  }),
314
588
  ]);
315
589
  const results = await report(sessionId);
@@ -321,72 +595,44 @@ async function effectsForChannelDispatch(sourceId, dispatchId, ctx) {
321
595
  sessionId = fresh;
322
596
  }
323
597
  }
324
- // Record the durable chv_ ↔ ase_ mapping (ops drill-down from a
325
- // conversation into its session; last-write-wins on the server). Only on
326
- // change — the store remembers what was last pushed — and fully
327
- // fire-and-forget: pure bookkeeping must never add latency to the
328
- // emit/ack path (a lost attempt is retried on the next message because
329
- // the store memo only updates on success).
330
- void recordConversationSession(ctx, conversationId, sessionId).catch(() => { });
331
598
  }
332
- await receivedSettled;
333
599
  return [
334
600
  {
335
601
  type: 'emitEvent',
336
602
  event: {
337
603
  id: envelopeId,
338
- orgId,
604
+ orgId: parallOrgId(ctx),
339
605
  connectionId: ctx.connectionId,
340
606
  source: 'parall',
341
- // The host's message intake path turns data.text into the user
342
- // message — the external-audience framing rides inside it (parel has
343
- // no separate prompt channel), so 'message' is the right type here.
344
607
  type: 'message',
345
- // main routing sends this to the agent's one session too; subject
346
- // still carries the external conversation (chv_) for parel's turn
347
- // input grouping (F2) and per-conversation event correlation.
348
- subject: conversationId,
349
- data: {
350
- text: buildChannelPrompt({
351
- provider,
352
- conversationType: conv?.conversation_type ? String(conv.conversation_type) : undefined,
353
- externalConversationId,
354
- externalMessageId,
355
- senderName,
356
- text,
357
- }),
358
- conversationId,
359
- channelMessageId: sourceId,
360
- provider,
361
- externalConversationId,
362
- externalMessageId,
363
- },
364
- // No chatId on purpose: the reply goes out through the provider clip
365
- // (agent-invoked), NOT deliver() — deliver only runs the redundant
366
- // session idle for channel routes (see delivery.ts).
608
+ // Subject = the source entity (task/schedule/trigger/…): F2 groups
609
+ // consecutive events for one entity into one turn and never mixes
610
+ // them with chat conversations.
611
+ subject: plan.subject,
612
+ data: { text: plan.body, sourceType, sourceId },
367
613
  replyRoute: {
368
614
  kind: 'provider_http',
369
615
  connectionId: ctx.connectionId,
370
- data: { conversationId, envelopeId },
616
+ // approval_decided replies deliver to its chat; every other typed
617
+ // event has no delivery target (deliver() only runs the redundant
618
+ // idle off envelopeId) — the agent acts via its sandbox CLI.
619
+ data: plan.chatId
620
+ ? { chatId: plan.chatId, messageId: sourceId, envelopeId }
621
+ : { envelopeId },
371
622
  },
372
- // No invocation context: PRLL_CHAT_ID must not point CLI defaults at
373
- // a chat that doesn't exist, and the reply targets (external ids)
374
- // already ride the prompt verbatim.
623
+ ...(plan.chatId
624
+ ? {
625
+ context: {
626
+ PRLL_CHAT_ID: plan.chatId,
627
+ PRLL_TRIGGER_MESSAGE_ID: sourceId,
628
+ },
629
+ }
630
+ : {}),
375
631
  },
376
632
  },
377
- ackEffect(ctx, 'channel_message', sourceId),
633
+ ack(),
378
634
  ];
379
635
  }
380
- /**
381
- * connection id → provider alias, cached in the durable store (stable
382
- * mapping; avoids one connection fetch per inbound message). Cache hits are
383
- * a store read; the miss-path fetch is cosmetic (prompt labeling only), so
384
- * it gets a tight timeout — same 3s budget as deliver's front-of-reply
385
- * session lookup — rather than holding the message's emit/ack behind the
386
- * full REQUEST_TIMEOUT_MS. Any failure returns undefined — prompt wording
387
- * degrades to neutral rather than inventing a clip alias.
388
- */
389
- const PROVIDER_LOOKUP_TIMEOUT_MS = 3_000;
390
636
  /**
391
637
  * How long a cached chat name is served without revalidation. Chat renames
392
638
  * are rare and the frame is the model's cross-chat context anchor, so serve
@@ -445,51 +691,6 @@ async function prefetchChatName(ctx, chatId, cacheKey) {
445
691
  // Cosmetic prefetch — the next message from this chat retries.
446
692
  }
447
693
  }
448
- async function resolveChannelProvider(ctx, connectionId, get) {
449
- const cacheKey = `channelProvider:${connectionId}`;
450
- const cached = await ctx.store?.get(cacheKey).catch(() => null);
451
- if (typeof cached === 'string' && cached)
452
- return cached;
453
- try {
454
- const res = await get(`/channel-connections/${connectionId}`, PROVIDER_LOOKUP_TIMEOUT_MS);
455
- if (!res.ok)
456
- return undefined;
457
- const body = (await res.json().catch(() => null));
458
- const provider = body?.provider ? String(body.provider) : undefined;
459
- if (provider)
460
- await ctx.store?.set(cacheKey, provider).catch(() => { });
461
- return provider;
462
- }
463
- catch {
464
- return undefined;
465
- }
466
- }
467
- /** Push the chv_ → ase_ pointer when it changed; warn-only on failure. */
468
- async function recordConversationSession(ctx, conversationId, sessionId) {
469
- const mappedKey = `convSession:${conversationId}`;
470
- const mapped = await ctx.store?.get(mappedKey).catch(() => null);
471
- if (mapped === sessionId)
472
- return;
473
- try {
474
- const res = await fetch(`${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/channel-conversations/${conversationId}/session`, {
475
- method: 'PATCH',
476
- headers: {
477
- Authorization: `Bearer ${requireAgk(ctx)}`,
478
- 'Content-Type': 'application/json',
479
- },
480
- body: JSON.stringify({ agent_session_id: sessionId }),
481
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
482
- });
483
- if (!res.ok) {
484
- console.warn(`[parel-channel] conversation session mapping failed (${res.status})`);
485
- return;
486
- }
487
- await ctx.store?.set(mappedKey, sessionId).catch(() => { });
488
- }
489
- catch (err) {
490
- console.warn('[parel-channel] conversation session mapping failed', err);
491
- }
492
- }
493
694
  /**
494
695
  * Agent execution events (parel E1+E2, plugin-sdk 0.9.0, opt-in via the
495
696
  * channel declaration's `observe: [turn, steps]`).
@@ -507,18 +708,72 @@ async function recordConversationSession(ctx, conversationId, sessionId) {
507
708
  * done event just means the ring clears on the next turn's trigger change; a
508
709
  * missed trace step is a gap in the panel, nothing more.
509
710
  */
510
- export async function handleParallAgentEvent(event, ctx) {
711
+ export function handleParallAgentEvent(event, ctx) {
712
+ return serialized(() => handleParallAgentEventInner(event, ctx));
713
+ }
714
+ async function handleParallAgentEventInner(event, ctx) {
715
+ // spawnChildSession's asynchronous error channel — not turn-scoped, pushed
716
+ // regardless of observe scopes, and shaped outside the published AgentEvent
717
+ // union (see parel-sdk-compat). Handle it before anything subject-gated.
718
+ const spawnFailed = asChildSpawnFailed(event);
719
+ if (spawnFailed) {
720
+ const effects = [];
721
+ try {
722
+ const outcome = await handleChildSpawnFailed(ctx, spawnFailed);
723
+ if (outcome.cleared) {
724
+ // The spawn's ase_ was already created active with an input step; no
725
+ // child turn will ever emit a terminal event for it — settle it here
726
+ // or the session (and its processing indicator) stays active forever.
727
+ const orphanAse = await ensureChildSession(ctx, spawnFailed.childRef);
728
+ if (orphanAse)
729
+ await patchSession(ctx, orphanAse, { status: 'idle' });
730
+ await invalidateChildSession(ctx, spawnFailed.childRef);
731
+ }
732
+ // Re-drive the stranded messages WITHOUT waiting for a reconnect sweep
733
+ // (a healthy long-lived socket never re-runs onOpen): park their
734
+ // coordinates and arm a timer — onTimer re-plans them through the
735
+ // normal dispatch pipeline (transient failures re-enter branch 1a with
736
+ // the same ref; terminal ones re-plan from scratch).
737
+ if (outcome.subject && outcome.pendingAcks.length > 0) {
738
+ const chatId = outcome.subject.split('~')[0];
739
+ for (const ack of outcome.pendingAcks) {
740
+ const key = `${FORK_RETRY_PREFIX}${ack.dispatchId}`;
741
+ await bumpForkRetryAttempts(ctx, key, {
742
+ id: ack.dispatchId,
743
+ source_type: 'message',
744
+ source_id: ack.sourceId,
745
+ chat_id: chatId,
746
+ });
747
+ effects.push({ type: 'setTimer', key, at: ctx.now() + FORK_RETRY_DELAY_MS });
748
+ }
749
+ }
750
+ }
751
+ catch (err) {
752
+ console.error('[parel-channel] child spawn failure handling failed', err);
753
+ }
754
+ return effects;
755
+ }
756
+ const withChild = event;
757
+ if (withChild.childRef) {
758
+ return handleChildAgentEvent(withChild, ctx);
759
+ }
511
760
  const chatId = event.subject;
512
- if (!chatId)
513
- return [];
514
761
  try {
762
+ // Best-effort busy classifier for fork-on-busy: only MAIN turns feed it
763
+ // (child events took the branch above).
764
+ await noteMainTurnEvent(ctx, withChild).catch(() => { });
765
+ if (!chatId)
766
+ return [];
515
767
  if (event.type === 'turn_completed' || event.type === 'turn_failed') {
516
768
  // Staleness guard: only idle if this event's turn covers the AGENT'S
517
769
  // latest emitted envelope (the marker is agent-global — all chats share
518
770
  // the one main session, so a done signal for chat A's turn must not
519
771
  // clear the indicator while a later chat-B message is queued/running).
520
- // A late/retried event for a superseded turn is dropped. Fail-open
521
- // when the marker is unavailable (a stuck ring is worse than a blink).
772
+ // With injectInFlight (parel F3), an absorbed envelope has no turn of
773
+ // its own — its id is appended to the absorbing turn's envelopeIds, so
774
+ // this membership check settles it naturally. A late/retried event for
775
+ // a superseded turn is dropped. Fail-open when the marker is
776
+ // unavailable (a stuck ring is worse than a blink).
522
777
  const current = await ctx.store?.get(TURN_ENVELOPE_KEY).catch(() => null);
523
778
  if (typeof current === 'string' && current && !event.envelopeIds.includes(current)) {
524
779
  return [];
@@ -558,28 +813,73 @@ export async function handleParallAgentEvent(event, ctx) {
558
813
  }
559
814
  return [];
560
815
  }
561
- // turn_started (processing is input-step-driven) and execution_paused
562
- // (E3 — no resolve loop wired yet, HITL deliberately deferred) are
563
- // ignored; observe only requests [turn, steps].
816
+ // turn_started feeds only the busy classifier above (processing is
817
+ // input-step-driven); execution_paused (E3 — no resolve loop wired yet,
818
+ // HITL deliberately deferred) is ignored.
564
819
  }
565
820
  catch (err) {
566
821
  console.error('[parel-channel] agent event handling failed', err);
567
822
  }
568
823
  return [];
569
824
  }
570
- /** Ack a dispatch by source so it leaves the pending queue (idempotent). */
571
- function ackEffect(ctx, sourceType, sourceId) {
572
- return {
573
- type: 'fetch',
574
- request: {
575
- url: `${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/dispatch/ack`,
576
- method: 'POST',
577
- headers: {
578
- Authorization: `Bearer ${requireAgk(ctx)}`,
579
- 'Content-Type': 'application/json',
580
- },
581
- body: JSON.stringify({ source_type: sourceType, source_id: sourceId }),
582
- },
583
- idempotencyKey: `ack:${sourceType}:${sourceId}`,
584
- };
825
+ /**
826
+ * Agent events from a connector-spawned fork child (they carry childRef).
827
+ * Mirrors the main-session handling against the CHILD's ase_ instead:
828
+ * turn done → idle the child session (its indicator/panel), turn_failed →
829
+ * error step first, E2 → trace steps. Additionally settles the fork's
830
+ * pending spawn ack: the opening dispatch is acked on the child's first
831
+ * observed event (a spawn that never produces one leaves it pending for the
832
+ * catch-up sweep — see fork.ts). Child turns never touch the main session's
833
+ * turnEnvelope marker or the busy classifier.
834
+ */
835
+ async function handleChildAgentEvent(event, ctx) {
836
+ const childRef = event.childRef ?? '';
837
+ const effects = [];
838
+ try {
839
+ const settled = await settleChildEvent(ctx, event).catch(() => null);
840
+ for (const ack of settled?.pendingAcks ?? []) {
841
+ // Ack the fork's parked WorkItems (by id) — the child demonstrably
842
+ // exists and holds them. Re-sent on later events (bounded) because the
843
+ // fetch effect is fire-and-forget; the ack endpoint is idempotent.
844
+ effects.push(ackByIdEffect(ctx, ack.dispatchId));
845
+ }
846
+ const subject = event.subject || settled?.subject || '';
847
+ if (!subject)
848
+ return effects;
849
+ // A childRef outside live bookkeeping is a LATE callback (post-reset or
850
+ // post-give-up): resolving a session here would blind-recreate a fork
851
+ // ase_ under the new conversation line — drop the event instead.
852
+ if (!(await childRefKnown(ctx, childRef)))
853
+ return effects;
854
+ const sessionId = await ensureChildSession(ctx, childRef);
855
+ if (!sessionId)
856
+ return effects;
857
+ if (event.type === 'turn_completed' || event.type === 'turn_failed') {
858
+ let stale = false;
859
+ if (event.type === 'turn_failed') {
860
+ const stepResult = await createErrorStep(ctx, sessionId, {
861
+ subject,
862
+ turnId: event.turnId,
863
+ error: event.error,
864
+ });
865
+ stale = stepResult === 'stale';
866
+ }
867
+ const result = await patchSession(ctx, sessionId, { status: 'idle' });
868
+ if (stale || result === 'stale')
869
+ await invalidateChildSession(ctx, childRef);
870
+ return effects;
871
+ }
872
+ if (event.type === 'model_reasoning' ||
873
+ event.type === 'tool_call' ||
874
+ event.type === 'tool_result') {
875
+ const result = await createTraceStep(ctx, sessionId, subject, event);
876
+ if (result === 'stale')
877
+ await invalidateChildSession(ctx, childRef);
878
+ return effects;
879
+ }
880
+ }
881
+ catch (err) {
882
+ console.error('[parel-channel] child agent event handling failed', err);
883
+ }
884
+ return effects;
585
885
  }