@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/channel-prompt.d.ts +9 -1
- package/dist/channel-prompt.d.ts.map +1 -1
- package/dist/channel-prompt.js +17 -0
- package/dist/connect.d.ts +7 -0
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +9 -0
- package/dist/delivery.d.ts.map +1 -1
- package/dist/delivery.js +38 -10
- package/dist/fork.d.ts +145 -0
- package/dist/fork.d.ts.map +1 -0
- package/dist/fork.js +320 -0
- package/dist/inbound-channel.d.ts +29 -0
- package/dist/inbound-channel.d.ts.map +1 -0
- package/dist/inbound-channel.js +213 -0
- package/dist/inbound.d.ts +14 -0
- package/dist/inbound.d.ts.map +1 -1
- package/dist/inbound.js +571 -271
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/parel-sdk-compat.d.ts +63 -0
- package/dist/parel-sdk-compat.d.ts.map +1 -0
- package/dist/parel-sdk-compat.js +16 -0
- package/dist/session.d.ts +88 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +225 -11
- package/dist/typed-dispatch.d.ts +76 -0
- package/dist/typed-dispatch.d.ts.map +1 -0
- package/dist/typed-dispatch.js +345 -0
- package/package.json +1 -1
- package/src/channel-prompt.ts +28 -1
- package/src/connect.ts +10 -0
- package/src/delivery.ts +38 -9
- package/src/fork.ts +432 -0
- package/src/inbound-channel.ts +256 -0
- package/src/inbound.ts +634 -303
- package/src/index.ts +7 -1
- package/src/parel-sdk-compat.ts +77 -0
- package/src/session.ts +247 -12
- package/src/typed-dispatch.ts +521 -0
package/src/fork.ts
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import type { ConnectorContext } from '@parel/plugin-sdk';
|
|
2
|
+
import type { AgentEventWithChild, ChildSpawnFailedEvent } from './parel-sdk-compat.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Fork-on-busy scheduling (the parall-side half of parel F4, parel-mono #140;
|
|
6
|
+
* strategy ownership per parel-session-alignment-plan.md §6 — the platform
|
|
7
|
+
* provides the spawnChildSession primitive, WHEN to fork is connector code).
|
|
8
|
+
*
|
|
9
|
+
* Model, mirroring the standard runtimes' fork-on-busy:
|
|
10
|
+
* - The main session is the single orchestrator. While it is mid-turn, a
|
|
11
|
+
* message for a DIFFERENT conversation would head-of-line block behind it.
|
|
12
|
+
* - Instead, the connector spawns a fork child session (inherits main's
|
|
13
|
+
* transcript at the last turn boundary — platform-guaranteed) keyed by an
|
|
14
|
+
* opaque childRef, and routes that conversation's follow-ups to the child
|
|
15
|
+
* via emitEvent deliverTo.
|
|
16
|
+
* - The child replies through the normal turn-end deliver (its envelopes
|
|
17
|
+
* carry the same replyRoute shape), and its summary flows back to main via
|
|
18
|
+
* the platform's async child notification. Same-conversation messages keep
|
|
19
|
+
* riding main (steer/inject handles mid-turn arrival there).
|
|
20
|
+
*
|
|
21
|
+
* Busy tracking is BEST-EFFORT on the E1 turn stream (turn_started /
|
|
22
|
+
* turn_completed / turn_failed): a missed event mis-classifies busy vs idle,
|
|
23
|
+
* which costs a fork too many or a queued message too long — never
|
|
24
|
+
* correctness (F2 subject grouping guarantees turns don't mix conversations
|
|
25
|
+
* either way). Stale entries expire by TTL so a lost done event cannot wedge
|
|
26
|
+
* the classifier.
|
|
27
|
+
*
|
|
28
|
+
* Ack discipline: the spawn opening message — and any follow-up routed to
|
|
29
|
+
* the child before provisioning is confirmed — is NOT acked on emit; spawn
|
|
30
|
+
* failures come back asynchronously (child_spawn_failed) and an
|
|
31
|
+
* acked-but-never-processed message would be silently lost. Parked acks ride
|
|
32
|
+
* the child bookkeeping row and fire (by WorkItem id, re-sent a bounded
|
|
33
|
+
* number of times) on the child's observed events. On spawn failure the
|
|
34
|
+
* inbound layer arms an onTimer re-drive (FORK_RETRY_DELAY_MS) so the
|
|
35
|
+
* messages are re-planned promptly on a healthy long-lived connection —
|
|
36
|
+
* transient failures re-issue the SAME spawn ref (branch 1a), terminal ones
|
|
37
|
+
* re-plan from scratch (fresh ref or main).
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** Main-session turn considered over after this long without a done event. */
|
|
41
|
+
const MAIN_TURN_TTL_MS = 15 * 60 * 1000;
|
|
42
|
+
|
|
43
|
+
/** A child with no observed activity for this long is considered gone. */
|
|
44
|
+
const CHILD_TTL_MS = 10 * 60 * 1000;
|
|
45
|
+
|
|
46
|
+
/** After a disabled/unsupported spawn failure, stop trying to fork for a while. */
|
|
47
|
+
const FORK_DISABLED_TTL_MS = 60 * 60 * 1000;
|
|
48
|
+
|
|
49
|
+
/** Delay before a failed spawn's messages are re-driven through onTimer. */
|
|
50
|
+
export const FORK_RETRY_DELAY_MS = 15_000;
|
|
51
|
+
|
|
52
|
+
/** Cap on un-acked follow-ups parked on an unconfirmed child. */
|
|
53
|
+
const MAX_PENDING_FOLLOWUPS = 20;
|
|
54
|
+
|
|
55
|
+
/** Stop re-sending acks after this many settle rounds. */
|
|
56
|
+
const MAX_ACK_ATTEMPTS = 3;
|
|
57
|
+
|
|
58
|
+
const MAIN_TURN_KEY = 'forkMainTurn';
|
|
59
|
+
export const FORK_RETRY_PREFIX = 'forkRetry:';
|
|
60
|
+
const FORK_DISABLED_KEY = 'forkDisabled';
|
|
61
|
+
const childKey = (subject: string) => `forkChild:${subject}`;
|
|
62
|
+
const childSubjectKey = (childRef: string) => `forkChildSubject:${childRef}`;
|
|
63
|
+
|
|
64
|
+
interface MainTurnRow {
|
|
65
|
+
turnId: string;
|
|
66
|
+
subject?: string;
|
|
67
|
+
at: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface PendingAck {
|
|
71
|
+
dispatchId: string;
|
|
72
|
+
sourceId: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ChildRow {
|
|
76
|
+
childRef: string;
|
|
77
|
+
at: number;
|
|
78
|
+
/**
|
|
79
|
+
* The opening message's replay identity — set at spawn and NEVER cleared
|
|
80
|
+
* while the row lives. pendingAcks can be dropped after MAX_ACK_ATTEMPTS,
|
|
81
|
+
* but a replay of the opening source must still match branch 1a (its input
|
|
82
|
+
* was a spawn payload, not an envelope — a deliverTo replay would bypass
|
|
83
|
+
* ingress dedupe and inject the user's first message twice).
|
|
84
|
+
*/
|
|
85
|
+
openingSourceId?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Un-acked WorkItems this child holds: the spawn opening dispatch plus any
|
|
88
|
+
* follow-ups routed to the child BEFORE its provisioning was confirmed (a
|
|
89
|
+
* deliverTo into a spawn that then fails terminally is ignored by the host
|
|
90
|
+
* — acking those up front would lose them). Acked (by WorkItem id) on the
|
|
91
|
+
* child's observed events; sourceIds double as replay identities (a swept
|
|
92
|
+
* dispatch whose sourceId appears here is one of these very messages).
|
|
93
|
+
* pendingAcks[0] is always the opening message.
|
|
94
|
+
*/
|
|
95
|
+
pendingAcks?: PendingAck[];
|
|
96
|
+
/** Set on the child's first observed event — provisioning demonstrably done. */
|
|
97
|
+
confirmed?: boolean;
|
|
98
|
+
/** Ack re-send counter: acks are re-issued on later events until this hits
|
|
99
|
+
* MAX_ACK_ATTEMPTS (fetch effects are fire-and-forget; one lost ack must
|
|
100
|
+
* not orphan the WorkItem forever). */
|
|
101
|
+
ackAttempts?: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export type ForkDecision =
|
|
105
|
+
| { mode: 'main' }
|
|
106
|
+
/** trackAck: the child is not yet confirmed — the caller must park the
|
|
107
|
+
* WorkItem ack on the bookkeeping row instead of acking on emit. */
|
|
108
|
+
| { mode: 'deliverTo'; childRef: string; trackAck: boolean }
|
|
109
|
+
| { mode: 'spawn'; childRef: string };
|
|
110
|
+
|
|
111
|
+
function isLive(at: unknown, ttl: number, now: number): boolean {
|
|
112
|
+
return typeof at === 'number' && now - at < ttl;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Decide how to route one inbound chat message. Called on the message hot
|
|
117
|
+
* path — store reads only, never a fetch.
|
|
118
|
+
*
|
|
119
|
+
* Concurrency: the decision-then-record sequence is NOT internally locked —
|
|
120
|
+
* it relies on the parel host executing one connection's hooks serially (the
|
|
121
|
+
* C3 contract; the same guarantee the turnEnvelope marker's read-then-patch
|
|
122
|
+
* ordering already leans on). Two same-chat dispatches therefore cannot both
|
|
123
|
+
* observe "no child" — the second runs after the first's recordSpawn.
|
|
124
|
+
*/
|
|
125
|
+
export async function planForkDecision(
|
|
126
|
+
ctx: ConnectorContext,
|
|
127
|
+
subject: string,
|
|
128
|
+
sourceId: string,
|
|
129
|
+
): Promise<ForkDecision> {
|
|
130
|
+
const now = ctx.now();
|
|
131
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
132
|
+
if (child?.childRef && isLive(child.at, CHILD_TTL_MS, now)) {
|
|
133
|
+
// 1a. A replay of the fork's own opening message: re-issue the spawn
|
|
134
|
+
// with the SAME childRef. The platform spawn is idempotent (same ref
|
|
135
|
+
// → same child, duplicate input suppressed, transient
|
|
136
|
+
// concurrency_limit failures retry through) — this is both the retry
|
|
137
|
+
// path for transient spawn failures and the duplicate-processing
|
|
138
|
+
// guard (a deliverTo here would bypass ingress dedupe, the opening
|
|
139
|
+
// input never was an envelope). Matched on the row-lifetime
|
|
140
|
+
// openingSourceId, not pendingAcks — the acks list can be dropped
|
|
141
|
+
// after bounded re-sends while replays must keep matching.
|
|
142
|
+
if (child.openingSourceId === sourceId) {
|
|
143
|
+
return { mode: 'spawn', childRef: child.childRef };
|
|
144
|
+
}
|
|
145
|
+
// 1b. An existing live child owns its conversation's follow-ups. Until
|
|
146
|
+
// the child's first observed event confirms provisioning, follow-up
|
|
147
|
+
// acks are parked on the row (a deliverTo into a terminally-failed
|
|
148
|
+
// spawn is host-ignored — acking up front would lose the message).
|
|
149
|
+
return { mode: 'deliverTo', childRef: child.childRef, trackAck: child.confirmed !== true };
|
|
150
|
+
}
|
|
151
|
+
// 2. Forking disabled (binding opt-out observed) — everything rides main.
|
|
152
|
+
const disabled = (await ctx.store?.get(FORK_DISABLED_KEY).catch(() => null)) as {
|
|
153
|
+
at?: number;
|
|
154
|
+
} | null;
|
|
155
|
+
if (disabled && isLive(disabled.at, FORK_DISABLED_TTL_MS, now)) {
|
|
156
|
+
return { mode: 'main' };
|
|
157
|
+
}
|
|
158
|
+
// 3. Main mid-turn on a DIFFERENT conversation → fork. Same conversation
|
|
159
|
+
// stays on main (inject-in-flight absorbs it there).
|
|
160
|
+
const turn = (await ctx.store?.get(MAIN_TURN_KEY).catch(() => null)) as MainTurnRow | null;
|
|
161
|
+
if (turn?.turnId && isLive(turn.at, MAIN_TURN_TTL_MS, now) && turn.subject !== subject) {
|
|
162
|
+
// now() suffix: a childRef is burned once its spawn fails terminally
|
|
163
|
+
// (platform mapping row is three-state), so a re-plan after a terminal
|
|
164
|
+
// failure must mint a fresh ref; retries of a still-pending spawn go
|
|
165
|
+
// through branch 1a with the recorded ref instead.
|
|
166
|
+
return { mode: 'spawn', childRef: `fk-${now.toString(36)}-${subject}` };
|
|
167
|
+
}
|
|
168
|
+
return { mode: 'main' };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Record a just-issued spawn so follow-ups route to the child. Idempotent
|
|
172
|
+
* for the 1a replay path: an existing row for the same ref keeps its parked
|
|
173
|
+
* follow-up acks and confirmation state, only refreshing liveness. */
|
|
174
|
+
export async function recordSpawn(
|
|
175
|
+
ctx: ConnectorContext,
|
|
176
|
+
subject: string,
|
|
177
|
+
childRef: string,
|
|
178
|
+
opening: PendingAck,
|
|
179
|
+
): Promise<void> {
|
|
180
|
+
const existing = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
181
|
+
const row: ChildRow =
|
|
182
|
+
existing?.childRef === childRef
|
|
183
|
+
? { ...existing, at: ctx.now() }
|
|
184
|
+
: { childRef, at: ctx.now(), pendingAcks: [opening], openingSourceId: opening.sourceId };
|
|
185
|
+
await ctx.store?.set(childKey(subject), row).catch(() => {});
|
|
186
|
+
await ctx.store?.set(childSubjectKey(childRef), subject).catch(() => {});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Park a follow-up's WorkItem ack on an unconfirmed child. Returns false when
|
|
191
|
+
* the row is gone or the cap is hit — the caller then acks on emit (the cap
|
|
192
|
+
* bounds the loss window of a pathological never-confirming child; beyond it
|
|
193
|
+
* we prefer at-most-once for the tail over unbounded growth).
|
|
194
|
+
*/
|
|
195
|
+
export async function trackFollowUpAck(
|
|
196
|
+
ctx: ConnectorContext,
|
|
197
|
+
subject: string,
|
|
198
|
+
childRef: string,
|
|
199
|
+
ack: PendingAck,
|
|
200
|
+
): Promise<boolean> {
|
|
201
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
202
|
+
if (!child || child.childRef !== childRef) return false;
|
|
203
|
+
const acks = child.pendingAcks ?? [];
|
|
204
|
+
if (acks.some((a) => a.dispatchId === ack.dispatchId)) return true; // replay — already parked
|
|
205
|
+
if (acks.length >= MAX_PENDING_FOLLOWUPS) return false;
|
|
206
|
+
const row: ChildRow = { ...child, at: ctx.now(), pendingAcks: [...acks, ack] };
|
|
207
|
+
await ctx.store?.set(childKey(subject), row).catch(() => {});
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Whether a childRef is still part of live fork bookkeeping. Late child
|
|
212
|
+
* callbacks after a New Session purge (or after give-up) must NOT recreate
|
|
213
|
+
* fork ase_ rows via the blind get-or-create — a pre-reset child's delayed
|
|
214
|
+
* trace/reply would attach a fresh session under the NEW conversation line. */
|
|
215
|
+
export async function childRefKnown(ctx: ConnectorContext, childRef: string): Promise<boolean> {
|
|
216
|
+
const subject = (await ctx.store?.get(childSubjectKey(childRef)).catch(() => null)) as
|
|
217
|
+
| string
|
|
218
|
+
| null;
|
|
219
|
+
if (!subject) return false;
|
|
220
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
221
|
+
return child?.childRef === childRef;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether a subject's live child has ever produced an observed event. */
|
|
225
|
+
export async function childConfirmed(
|
|
226
|
+
ctx: ConnectorContext,
|
|
227
|
+
subject: string,
|
|
228
|
+
childRef: string,
|
|
229
|
+
): Promise<boolean> {
|
|
230
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
231
|
+
return child?.childRef === childRef && child.confirmed === true;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Drop one subject's fork routing (give-up path: message re-plans fresh). */
|
|
235
|
+
export async function clearForkSubject(
|
|
236
|
+
ctx: ConnectorContext,
|
|
237
|
+
subject: string,
|
|
238
|
+
childRef: string,
|
|
239
|
+
): Promise<void> {
|
|
240
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
241
|
+
if (child?.childRef === childRef) {
|
|
242
|
+
await ctx.store?.delete(childKey(subject)).catch(() => {});
|
|
243
|
+
}
|
|
244
|
+
await ctx.store?.delete(childSubjectKey(childRef)).catch(() => {});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Bump-and-park a fork retry ledger row (also the spawn-verification
|
|
249
|
+
* coordinate onTimer re-plans). Returns the attempt count INCLUDING this one.
|
|
250
|
+
*/
|
|
251
|
+
export async function bumpForkRetryAttempts(
|
|
252
|
+
ctx: ConnectorContext,
|
|
253
|
+
retryKey: string,
|
|
254
|
+
data: Record<string, unknown>,
|
|
255
|
+
): Promise<number> {
|
|
256
|
+
const prior = (await ctx.store?.get(retryKey).catch(() => null)) as {
|
|
257
|
+
attempts?: number;
|
|
258
|
+
} | null;
|
|
259
|
+
const attempts = (prior?.attempts ?? 0) + 1;
|
|
260
|
+
await ctx.store?.set(retryKey, { ...data, attempts }).catch(() => {});
|
|
261
|
+
return attempts;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Give up re-verifying a spawn after this many timer rounds. */
|
|
265
|
+
export const MAX_SPAWN_VERIFY_ATTEMPTS = 3;
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Purge ALL fork routing state — called on `agent.new_session`. The binding
|
|
269
|
+
* reset rotates main's conversation line; stale child routing surviving it
|
|
270
|
+
* would deliver post-reset messages into pre-reset forks (old context), and
|
|
271
|
+
* a stale busy marker would fork off a session that no longer exists.
|
|
272
|
+
* Returns the childRefs that were live so the caller can also invalidate
|
|
273
|
+
* their cached ase_ rows.
|
|
274
|
+
*/
|
|
275
|
+
export async function clearForkState(ctx: ConnectorContext): Promise<string[]> {
|
|
276
|
+
const refs: string[] = [];
|
|
277
|
+
try {
|
|
278
|
+
// EVERY fork-scoped key deliberately shares the `fork` prefix
|
|
279
|
+
// (forkChild / forkChildSubject / forkMainTurn / forkDisabled /
|
|
280
|
+
// forkRetry) so this one list-and-delete purges the whole family — a
|
|
281
|
+
// surviving disabled latch would suppress F4 for an hour after a reset,
|
|
282
|
+
// and a surviving retry row would re-drive a pre-reset message into the
|
|
283
|
+
// fresh session. Keep new fork keys on the prefix.
|
|
284
|
+
const keys = (await ctx.store?.list('fork').catch(() => [])) ?? [];
|
|
285
|
+
for (const key of keys) {
|
|
286
|
+
if (key.startsWith('forkChildSubject:')) {
|
|
287
|
+
refs.push(key.slice('forkChildSubject:'.length));
|
|
288
|
+
}
|
|
289
|
+
await ctx.store?.delete(key).catch(() => {});
|
|
290
|
+
}
|
|
291
|
+
} catch {
|
|
292
|
+
// Best-effort: leftover rows expire by TTL anyway.
|
|
293
|
+
}
|
|
294
|
+
return refs;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Track main-session busyness from the E1 turn stream. Child events (they
|
|
299
|
+
* carry childRef) must NOT feed this — only the main session's turns do.
|
|
300
|
+
*/
|
|
301
|
+
export async function noteMainTurnEvent(
|
|
302
|
+
ctx: ConnectorContext,
|
|
303
|
+
event: AgentEventWithChild,
|
|
304
|
+
): Promise<void> {
|
|
305
|
+
if (event.type === 'turn_started') {
|
|
306
|
+
const row: MainTurnRow = { turnId: event.turnId, subject: event.subject, at: ctx.now() };
|
|
307
|
+
await ctx.store?.set(MAIN_TURN_KEY, row).catch(() => {});
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (event.type === 'turn_completed' || event.type === 'turn_failed') {
|
|
311
|
+
const turn = (await ctx.store?.get(MAIN_TURN_KEY).catch(() => null)) as MainTurnRow | null;
|
|
312
|
+
// Clear only the turn this done event belongs to — a stale done for a
|
|
313
|
+
// superseded turn must not mark a newer running turn idle.
|
|
314
|
+
if (!turn || turn.turnId === event.turnId) {
|
|
315
|
+
await ctx.store?.delete(MAIN_TURN_KEY).catch(() => {});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Resolve a child event's bookkeeping row (by its subject mirror) and fire
|
|
322
|
+
* the pending spawn ack exactly once. Returns the ack request when due.
|
|
323
|
+
*/
|
|
324
|
+
export async function settleChildEvent(
|
|
325
|
+
ctx: ConnectorContext,
|
|
326
|
+
event: AgentEventWithChild,
|
|
327
|
+
): Promise<{ subject: string; pendingAcks: PendingAck[] } | null> {
|
|
328
|
+
const childRef = event.childRef;
|
|
329
|
+
if (!childRef) return null;
|
|
330
|
+
const subject =
|
|
331
|
+
event.subject ||
|
|
332
|
+
((await ctx.store?.get(childSubjectKey(childRef)).catch(() => null)) as string | null) ||
|
|
333
|
+
'';
|
|
334
|
+
if (!subject) return null;
|
|
335
|
+
const child = (await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null;
|
|
336
|
+
if (!child || child.childRef !== childRef) {
|
|
337
|
+
// Unknown/superseded child — refresh nothing, ack nothing.
|
|
338
|
+
return { subject, pendingAcks: [] };
|
|
339
|
+
}
|
|
340
|
+
// Acks are re-issued on subsequent events (bounded) rather than cleared on
|
|
341
|
+
// first send: the ack rides a fire-and-forget fetch effect, and clearing
|
|
342
|
+
// eagerly would let one lost request orphan the WorkItem in `received`
|
|
343
|
+
// forever (its replay would then re-enter the child as a duplicate).
|
|
344
|
+
const acks = child.pendingAcks ?? [];
|
|
345
|
+
const attempts = (child.ackAttempts ?? 0) + 1;
|
|
346
|
+
const done = attempts >= MAX_ACK_ATTEMPTS;
|
|
347
|
+
const refreshed: ChildRow = {
|
|
348
|
+
childRef,
|
|
349
|
+
at: ctx.now(),
|
|
350
|
+
confirmed: true,
|
|
351
|
+
// openingSourceId survives the ack-list drop — replay identity is
|
|
352
|
+
// row-lifetime (see the field doc).
|
|
353
|
+
...(child.openingSourceId ? { openingSourceId: child.openingSourceId } : {}),
|
|
354
|
+
...(done ? {} : { pendingAcks: acks, ackAttempts: attempts }),
|
|
355
|
+
};
|
|
356
|
+
await ctx.store?.set(childKey(subject), refreshed).catch(() => {});
|
|
357
|
+
return { subject, pendingAcks: acks };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* A spawn failed before the child ran. NEVER acks the opening dispatch — it
|
|
362
|
+
* stays received and the catch-up sweep re-plans it. Failure codes split
|
|
363
|
+
* three ways (parel §18.2 three-state mapping semantics):
|
|
364
|
+
* - `concurrency_limit` is TRANSIENT: the platform keeps the mapping in
|
|
365
|
+
* `provisioning` and the same childRef can retry — keep the bookkeeping so
|
|
366
|
+
* the sweep's replay re-issues the same spawn key (branch 1a) instead of
|
|
367
|
+
* abandoning one provisioning row per attempt.
|
|
368
|
+
* - `disabled` / `unsupported_routing` are configuration-shaped: clear the
|
|
369
|
+
* bookkeeping AND park a no-fork flag so the connector stops re-trying a
|
|
370
|
+
* fork the binding will never allow.
|
|
371
|
+
* - Everything else is terminal for this childRef (the ref is burned): clear
|
|
372
|
+
* the bookkeeping so the sweep's re-plan mints a fresh ref.
|
|
373
|
+
* Returns true when the bookkeeping was cleared (the caller then settles the
|
|
374
|
+
* orphaned child ase_).
|
|
375
|
+
*/
|
|
376
|
+
export async function handleChildSpawnFailed(
|
|
377
|
+
ctx: ConnectorContext,
|
|
378
|
+
event: ChildSpawnFailedEvent,
|
|
379
|
+
): Promise<{ cleared: boolean; subject: string; pendingAcks: PendingAck[] }> {
|
|
380
|
+
console.error(
|
|
381
|
+
`[parel-channel] child spawn failed (${event.code}): ${event.error} (ref ${event.childRef})`,
|
|
382
|
+
);
|
|
383
|
+
const subject =
|
|
384
|
+
((await ctx.store?.get(childSubjectKey(event.childRef)).catch(() => null)) as string | null) ??
|
|
385
|
+
'';
|
|
386
|
+
const child = subject
|
|
387
|
+
? ((await ctx.store?.get(childKey(subject)).catch(() => null)) as ChildRow | null)
|
|
388
|
+
: null;
|
|
389
|
+
const pendingAcks = child?.childRef === event.childRef ? (child.pendingAcks ?? []) : [];
|
|
390
|
+
if (event.code === 'concurrency_limit') {
|
|
391
|
+
// Transient: the platform keeps the mapping in `provisioning` and the
|
|
392
|
+
// SAME childRef can retry — keep the bookkeeping; the caller's retry
|
|
393
|
+
// timer re-drives the opening message through branch 1a.
|
|
394
|
+
return { cleared: false, subject, pendingAcks };
|
|
395
|
+
}
|
|
396
|
+
if (subject) {
|
|
397
|
+
if (child?.childRef === event.childRef) {
|
|
398
|
+
await ctx.store?.delete(childKey(subject)).catch(() => {});
|
|
399
|
+
}
|
|
400
|
+
await ctx.store?.delete(childSubjectKey(event.childRef)).catch(() => {});
|
|
401
|
+
}
|
|
402
|
+
if (event.code === 'disabled' || event.code === 'unsupported_routing') {
|
|
403
|
+
await ctx.store?.set(FORK_DISABLED_KEY, { at: ctx.now() }).catch(() => {});
|
|
404
|
+
}
|
|
405
|
+
return { cleared: true, subject, pendingAcks };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Scope guard prepended to a fork child's opening input — the behavioral
|
|
410
|
+
* fallback agent-core applies to every forked dispatch (buildForkScopePrefix
|
|
411
|
+
* equivalent; the platform already excludes in-flight output from the seed,
|
|
412
|
+
* this line keeps the child from "finishing" main's visible work).
|
|
413
|
+
*
|
|
414
|
+
* The opening turn has no envelope (it starts from the spawn input), so its
|
|
415
|
+
* turn-end text is NOT auto-delivered anywhere (parel §18.3: outward replies
|
|
416
|
+
* from a child are the agent's own job) — the prefix therefore spells out
|
|
417
|
+
* the CLI reply command for THIS message; follow-ups arrive as deliverTo
|
|
418
|
+
* envelopes whose replies auto-deliver like any chat message.
|
|
419
|
+
*/
|
|
420
|
+
export function buildForkScopePrefix(subject: string, threadRootId?: string): string {
|
|
421
|
+
// Quoted-heredoc input form (mirrors agent-core's send hint): plain
|
|
422
|
+
// `--text "…"` lets the sandbox shell expand $, backticks and eat quotes —
|
|
423
|
+
// and this is the opening turn's ONLY delivery path.
|
|
424
|
+
const send = threadRootId
|
|
425
|
+
? `parall messages send ${subject} --thread-root-id ${threadRootId} --text-file - <<'EOF'`
|
|
426
|
+
: `parall messages send ${subject} --text-file - <<'EOF'`;
|
|
427
|
+
return (
|
|
428
|
+
`[Fork scope: you are a parallel branch of your main session, handling ONE conversation (${subject}) only. ` +
|
|
429
|
+
`Act only on this conversation's request. Do not continue, complete, or produce output for other work visible in your inherited history — the main session owns it.]\n` +
|
|
430
|
+
`<system-reminder>Reply to THIS message with your sandbox CLI: \`${send}\` … \`EOF\` — the quoted heredoc keeps \`$\`, backticks and apostrophes literal. For this opening message your plain text output is NOT auto-delivered; later messages in this conversation deliver replies automatically.</system-reminder>\n\n`
|
|
431
|
+
);
|
|
432
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
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
|
+
patchSession,
|
|
11
|
+
REQUEST_TIMEOUT_MS,
|
|
12
|
+
TURN_ENVELOPE_KEY,
|
|
13
|
+
} from './session.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* External IM inbound (channel_message dispatches — Feishu/Slack via the
|
|
17
|
+
* platform-mediated channel, external-im-channel-design.md). Split from
|
|
18
|
+
* inbound.ts as a pure move; the pipeline contract lives there.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Miss-path lookups here are cosmetic (prompt labeling only), so they get a
|
|
23
|
+
* tight timeout — same 3s budget as deliver's front-of-reply session lookup —
|
|
24
|
+
* rather than holding the message's emit/ack behind the full
|
|
25
|
+
* REQUEST_TIMEOUT_MS. Also reused by inbound.ts's chat-name prefetch.
|
|
26
|
+
*/
|
|
27
|
+
export const PROVIDER_LOOKUP_TIMEOUT_MS = 3_000;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* channel_message dispatch → agent (external IM channel,
|
|
31
|
+
* external-im-channel-design.md). Same pipeline shape as the message path,
|
|
32
|
+
* with the ChannelConversation (chv_) standing in for the chat as the
|
|
33
|
+
* routing subject: fetch the durable ChannelMessage + its conversation,
|
|
34
|
+
* resolve the provider for prompt labeling (cached — the connection→provider
|
|
35
|
+
* mapping is stable), frame the prompt for the EXTERNAL audience, report
|
|
36
|
+
* progress against the conversation-keyed session, and ack by source.
|
|
37
|
+
*
|
|
38
|
+
* Error contract mirrors the message path (and agent-core's
|
|
39
|
+
* fetchAndHandleChannelMessage): 404/403 on the source entities is
|
|
40
|
+
* permanently unusable → ack-and-drop; a transient failure keeps the
|
|
41
|
+
* dispatch pending for the catch-up sweep.
|
|
42
|
+
*/
|
|
43
|
+
export async function effectsForChannelDispatch(
|
|
44
|
+
sourceId: string,
|
|
45
|
+
dispatchId: string,
|
|
46
|
+
ctx: ConnectorContext,
|
|
47
|
+
): Promise<ConnectorEffect[]> {
|
|
48
|
+
const apiUrl = parallApiUrl(ctx);
|
|
49
|
+
const orgId = parallOrgId(ctx);
|
|
50
|
+
const authHeaders = { Authorization: `Bearer ${requireAgk(ctx)}` };
|
|
51
|
+
const get = (path: string, timeoutMs: number = REQUEST_TIMEOUT_MS) =>
|
|
52
|
+
fetch(`${apiUrl}/api/v1/orgs/${orgId}${path}`, {
|
|
53
|
+
headers: authHeaders,
|
|
54
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const m = await get(`/channel-messages/${sourceId}`);
|
|
58
|
+
if (!m.ok) {
|
|
59
|
+
if (m.status === 404 || m.status === 403) {
|
|
60
|
+
// Deleted / inaccessible (also the shape a disabled org feature flag
|
|
61
|
+
// takes) — permanently unusable, drop it.
|
|
62
|
+
return [ackEffect(ctx, 'channel_message', sourceId)];
|
|
63
|
+
}
|
|
64
|
+
return []; // transient: keep pending, the catch-up sweep retries
|
|
65
|
+
}
|
|
66
|
+
const msg = (await m.json().catch(() => null)) as {
|
|
67
|
+
conversation_id?: string;
|
|
68
|
+
external_message_id?: string;
|
|
69
|
+
text?: string;
|
|
70
|
+
external_user_id?: string;
|
|
71
|
+
external_user_name?: string;
|
|
72
|
+
received_at?: string;
|
|
73
|
+
} | null;
|
|
74
|
+
const conversationId = msg?.conversation_id ? String(msg.conversation_id) : undefined;
|
|
75
|
+
const text = msg?.text ?? '';
|
|
76
|
+
if (!conversationId) {
|
|
77
|
+
// No conversation → no session key and no reply target: unusable.
|
|
78
|
+
return [ackEffect(ctx, 'channel_message', sourceId)];
|
|
79
|
+
}
|
|
80
|
+
if (!text) {
|
|
81
|
+
// The ingress adapter only persists mechanically parsed text; a row with
|
|
82
|
+
// none will never grow any (same reasoning as attachment-only chat
|
|
83
|
+
// messages) — drop rather than let it pile up in the pending queue.
|
|
84
|
+
return [ackEffect(ctx, 'channel_message', sourceId)];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const c = await get(`/channel-conversations/${conversationId}`);
|
|
88
|
+
if (!c.ok) {
|
|
89
|
+
if (c.status === 404 || c.status === 403) {
|
|
90
|
+
return [ackEffect(ctx, 'channel_message', sourceId)];
|
|
91
|
+
}
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
const conv = (await c.json().catch(() => null)) as {
|
|
95
|
+
connection_id?: string;
|
|
96
|
+
external_conversation_id?: string;
|
|
97
|
+
conversation_type?: string;
|
|
98
|
+
} | null;
|
|
99
|
+
|
|
100
|
+
// Provider (= clip alias) for prompt labeling + the reply hint.
|
|
101
|
+
// Best-effort: an unresolved provider degrades the wording, never blocks.
|
|
102
|
+
const connectionId = conv?.connection_id ? String(conv.connection_id) : undefined;
|
|
103
|
+
const provider = connectionId ? await resolveChannelProvider(ctx, connectionId, get) : undefined;
|
|
104
|
+
|
|
105
|
+
const senderName = msg?.external_user_name || msg?.external_user_id || 'external user';
|
|
106
|
+
const externalConversationId = conv?.external_conversation_id
|
|
107
|
+
? String(conv.external_conversation_id)
|
|
108
|
+
: undefined;
|
|
109
|
+
const externalMessageId = msg?.external_message_id ? String(msg.external_message_id) : undefined;
|
|
110
|
+
|
|
111
|
+
// Progress reporting — identical ordering contract to the message path
|
|
112
|
+
// (see the comments there): received settles before the ack effect is
|
|
113
|
+
// returned; the turnEnvelope marker goes down before any session write.
|
|
114
|
+
const receivedSettled = markDispatchReceived(ctx, 'channel_message', sourceId);
|
|
115
|
+
const envelopeId = dispatchId || `channel_message:${sourceId}`;
|
|
116
|
+
let sessionId = await ensureSession(ctx);
|
|
117
|
+
if (sessionId) {
|
|
118
|
+
await ctx.store?.set(TURN_ENVELOPE_KEY, envelopeId).catch(() => {});
|
|
119
|
+
const report = (sid: string) =>
|
|
120
|
+
Promise.all([
|
|
121
|
+
patchSession(ctx, sid, { status: 'active', trigger_message_id: sourceId }),
|
|
122
|
+
createChannelInputStep(ctx, sid, {
|
|
123
|
+
conversationId,
|
|
124
|
+
channelMessageId: sourceId,
|
|
125
|
+
provider,
|
|
126
|
+
externalConversationId,
|
|
127
|
+
senderId: msg?.external_user_id ? String(msg.external_user_id) : 'external',
|
|
128
|
+
senderName,
|
|
129
|
+
text,
|
|
130
|
+
sentAt: msg?.received_at ? String(msg.received_at) : undefined,
|
|
131
|
+
}),
|
|
132
|
+
]);
|
|
133
|
+
const results = await report(sessionId);
|
|
134
|
+
if (results.includes('stale')) {
|
|
135
|
+
await invalidateSession(ctx);
|
|
136
|
+
const fresh = await ensureSession(ctx);
|
|
137
|
+
if (fresh && fresh !== sessionId) {
|
|
138
|
+
await report(fresh);
|
|
139
|
+
sessionId = fresh;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// Record the durable chv_ ↔ ase_ mapping (ops drill-down from a
|
|
143
|
+
// conversation into its session; last-write-wins on the server). Only on
|
|
144
|
+
// change — the store remembers what was last pushed — and fully
|
|
145
|
+
// fire-and-forget: pure bookkeeping must never add latency to the
|
|
146
|
+
// emit/ack path (a lost attempt is retried on the next message because
|
|
147
|
+
// the store memo only updates on success).
|
|
148
|
+
void recordConversationSession(ctx, conversationId, sessionId).catch(() => {});
|
|
149
|
+
}
|
|
150
|
+
await receivedSettled;
|
|
151
|
+
|
|
152
|
+
return [
|
|
153
|
+
{
|
|
154
|
+
type: 'emitEvent',
|
|
155
|
+
event: {
|
|
156
|
+
id: envelopeId,
|
|
157
|
+
orgId,
|
|
158
|
+
connectionId: ctx.connectionId,
|
|
159
|
+
source: 'parall',
|
|
160
|
+
// The host's message intake path turns data.text into the user
|
|
161
|
+
// message — the external-audience framing rides inside it (parel has
|
|
162
|
+
// no separate prompt channel), so 'message' is the right type here.
|
|
163
|
+
type: 'message',
|
|
164
|
+
// main routing sends this to the agent's one session too; subject
|
|
165
|
+
// still carries the external conversation (chv_) for parel's turn
|
|
166
|
+
// input grouping (F2) and per-conversation event correlation.
|
|
167
|
+
subject: conversationId,
|
|
168
|
+
data: {
|
|
169
|
+
text: buildChannelPrompt({
|
|
170
|
+
provider,
|
|
171
|
+
conversationType: conv?.conversation_type ? String(conv.conversation_type) : undefined,
|
|
172
|
+
externalConversationId,
|
|
173
|
+
externalMessageId,
|
|
174
|
+
senderName,
|
|
175
|
+
text,
|
|
176
|
+
}),
|
|
177
|
+
conversationId,
|
|
178
|
+
channelMessageId: sourceId,
|
|
179
|
+
provider,
|
|
180
|
+
externalConversationId,
|
|
181
|
+
externalMessageId,
|
|
182
|
+
},
|
|
183
|
+
// No chatId on purpose: the reply goes out through the provider clip
|
|
184
|
+
// (agent-invoked), NOT deliver() — deliver only runs the redundant
|
|
185
|
+
// session idle for channel routes (see delivery.ts).
|
|
186
|
+
replyRoute: {
|
|
187
|
+
kind: 'provider_http',
|
|
188
|
+
connectionId: ctx.connectionId,
|
|
189
|
+
data: { conversationId, envelopeId },
|
|
190
|
+
},
|
|
191
|
+
// No invocation context: PRLL_CHAT_ID must not point CLI defaults at
|
|
192
|
+
// a chat that doesn't exist, and the reply targets (external ids)
|
|
193
|
+
// already ride the prompt verbatim.
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
ackEffect(ctx, 'channel_message', sourceId),
|
|
197
|
+
];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* connection id → provider alias, cached in the durable store (stable
|
|
202
|
+
* mapping; avoids one connection fetch per inbound message). Cache hits are
|
|
203
|
+
* a store read; any failure returns undefined — prompt wording degrades to
|
|
204
|
+
* neutral rather than inventing a clip alias.
|
|
205
|
+
*/
|
|
206
|
+
async function resolveChannelProvider(
|
|
207
|
+
ctx: ConnectorContext,
|
|
208
|
+
connectionId: string,
|
|
209
|
+
get: (path: string, timeoutMs?: number) => Promise<Response>,
|
|
210
|
+
): Promise<string | undefined> {
|
|
211
|
+
const cacheKey = `channelProvider:${connectionId}`;
|
|
212
|
+
const cached = await ctx.store?.get(cacheKey).catch(() => null);
|
|
213
|
+
if (typeof cached === 'string' && cached) return cached;
|
|
214
|
+
try {
|
|
215
|
+
const res = await get(`/channel-connections/${connectionId}`, PROVIDER_LOOKUP_TIMEOUT_MS);
|
|
216
|
+
if (!res.ok) return undefined;
|
|
217
|
+
const body = (await res.json().catch(() => null)) as { provider?: string } | null;
|
|
218
|
+
const provider = body?.provider ? String(body.provider) : undefined;
|
|
219
|
+
if (provider) await ctx.store?.set(cacheKey, provider).catch(() => {});
|
|
220
|
+
return provider;
|
|
221
|
+
} catch {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Push the chv_ → ase_ pointer when it changed; warn-only on failure. */
|
|
227
|
+
async function recordConversationSession(
|
|
228
|
+
ctx: ConnectorContext,
|
|
229
|
+
conversationId: string,
|
|
230
|
+
sessionId: string,
|
|
231
|
+
): Promise<void> {
|
|
232
|
+
const mappedKey = `convSession:${conversationId}`;
|
|
233
|
+
const mapped = await ctx.store?.get(mappedKey).catch(() => null);
|
|
234
|
+
if (mapped === sessionId) return;
|
|
235
|
+
try {
|
|
236
|
+
const res = await fetch(
|
|
237
|
+
`${parallApiUrl(ctx)}/api/v1/orgs/${parallOrgId(ctx)}/channel-conversations/${conversationId}/session`,
|
|
238
|
+
{
|
|
239
|
+
method: 'PATCH',
|
|
240
|
+
headers: {
|
|
241
|
+
Authorization: `Bearer ${requireAgk(ctx)}`,
|
|
242
|
+
'Content-Type': 'application/json',
|
|
243
|
+
},
|
|
244
|
+
body: JSON.stringify({ agent_session_id: sessionId }),
|
|
245
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
246
|
+
},
|
|
247
|
+
);
|
|
248
|
+
if (!res.ok) {
|
|
249
|
+
console.warn(`[parel-channel] conversation session mapping failed (${res.status})`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
await ctx.store?.set(mappedKey, sessionId).catch(() => {});
|
|
253
|
+
} catch (err) {
|
|
254
|
+
console.warn('[parel-channel] conversation session mapping failed', err);
|
|
255
|
+
}
|
|
256
|
+
}
|