@parall/agent-core 1.45.0 → 1.47.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.
Files changed (46) hide show
  1. package/dist/channel-capability.d.ts +2 -0
  2. package/dist/channel-capability.d.ts.map +1 -1
  3. package/dist/channel-capability.js +15 -0
  4. package/dist/dispatch-adapter.d.ts +9 -0
  5. package/dist/dispatch-adapter.d.ts.map +1 -1
  6. package/dist/event-format.d.ts.map +1 -1
  7. package/dist/event-format.js +27 -7
  8. package/dist/fork-session-finalizer.d.ts +65 -0
  9. package/dist/fork-session-finalizer.d.ts.map +1 -0
  10. package/dist/fork-session-finalizer.js +70 -0
  11. package/dist/gateway-base.d.ts +47 -0
  12. package/dist/gateway-base.d.ts.map +1 -1
  13. package/dist/gateway-base.js +457 -200
  14. package/dist/gateway-lane-flow.d.ts.map +1 -1
  15. package/dist/gateway-lane-flow.js +13 -7
  16. package/dist/http-keepalive.d.ts +4 -0
  17. package/dist/http-keepalive.d.ts.map +1 -0
  18. package/dist/http-keepalive.js +33 -0
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +6 -0
  22. package/dist/session-lifecycle.d.ts +198 -0
  23. package/dist/session-lifecycle.d.ts.map +1 -0
  24. package/dist/session-lifecycle.js +446 -0
  25. package/dist/skills/parall-clips.d.ts +1 -1
  26. package/dist/skills/parall-clips.d.ts.map +1 -1
  27. package/dist/skills/parall-clips.js +3 -0
  28. package/dist/step-persister.d.ts +66 -0
  29. package/dist/step-persister.d.ts.map +1 -0
  30. package/dist/step-persister.js +116 -0
  31. package/dist/step-retry-queue.d.ts +91 -0
  32. package/dist/step-retry-queue.d.ts.map +1 -0
  33. package/dist/step-retry-queue.js +259 -0
  34. package/package.json +3 -2
  35. package/src/channel-capability.ts +16 -0
  36. package/src/dispatch-adapter.ts +10 -0
  37. package/src/event-format.ts +27 -7
  38. package/src/fork-session-finalizer.ts +122 -0
  39. package/src/gateway-base.ts +487 -255
  40. package/src/gateway-lane-flow.ts +12 -7
  41. package/src/http-keepalive.ts +36 -0
  42. package/src/index.ts +6 -0
  43. package/src/session-lifecycle.ts +552 -0
  44. package/src/skills/parall-clips.ts +3 -0
  45. package/src/step-persister.ts +161 -0
  46. package/src/step-retry-queue.ts +296 -0
@@ -309,15 +309,21 @@ export async function settleDrainedTypedGroup(
309
309
  return;
310
310
  }
311
311
  // The legacy ack BY ID, never by source — task siblings share a source
312
- // pair, and a by-source ack would sweep the undispatched one. Awaited:
313
- // these rows are already pending (released at buffer time), so a failed
314
- // ack must free the local dedupe claim or the pending retry would be
315
- // self-rejected by this pod forever.
312
+ // pair, and a by-source ack would sweep the undispatched one. Awaited, and
313
+ // the dedupe claim is freed on EVERY outcome: a claim's lifetime is the
314
+ // buffer stay (#1149). On failure the row is still pending and its retry
315
+ // must not be self-rejected; on success the row is terminal — but a
316
+ // shared-key sibling WorkItem (task assign+update fetch the same
317
+ // `task:updated_at` pair) must not be rejected by a leftover claim either.
316
318
  const legacyAckFrom = async (start: number) => {
317
319
  for (const [j, id] of ids.slice(start).entries()) {
318
320
  try {
319
321
  await host.opts.client.ackDispatchByID(host.opts.config.org_id, id);
320
322
  } catch {
323
+ // Transient ack failure: the row stays live server-side and its
324
+ // re-drive re-converges — keep settling the REST of the group (a
325
+ // propagated error would strand every later id's retained claim).
326
+ } finally {
321
327
  clearTypedDedupeForEvent(host, events[start + j]);
322
328
  }
323
329
  }
@@ -338,9 +344,8 @@ export async function settleDrainedTypedGroup(
338
344
  await legacyAckFrom(i);
339
345
  return;
340
346
  }
341
- if (outcome !== 'ok') {
342
- clearTypedDedupeForEvent(host, events[i]);
343
- }
347
+ // Freed on every outcome see legacyAckFrom's contract note.
348
+ clearTypedDedupeForEvent(host, events[i]);
344
349
  }
345
350
  }
346
351
 
@@ -0,0 +1,36 @@
1
+ import { Agent, setGlobalDispatcher } from 'undici';
2
+
3
+ /**
4
+ * Keep bridge→api HTTP connections long-lived.
5
+ *
6
+ * Node's built-in fetch closes idle pooled connections after ~4s when the
7
+ * server sends no Keep-Alive hint (our NLB+Envoy edge sends none), so any two
8
+ * bridge API calls spaced more than a few seconds apart pay a fresh TCP+TLS
9
+ * handshake. On a degraded long-haul link that handshake is exactly what
10
+ * fails — established connections (the WS, the runtime's own model stream)
11
+ * ride through such windows while every bridge call times out (2026-07-10:
12
+ * step creation losses). A 2-minute idle timeout keeps one warm connection
13
+ * across an active turn's step cadence, comfortably below the NLB's 350s
14
+ * idle cutoff.
15
+ *
16
+ * Uses undici's global-dispatcher registry, which Node's built-in fetch
17
+ * shares (verified on Node 22 / undici 7) — so this covers every fetch in
18
+ * the process: ParallClient, lane-ledger heartbeats, OTLP export.
19
+ * Node-only; call once from a bridge/daemon entrypoint before any fetch.
20
+ */
21
+ let installed = false;
22
+
23
+ export function configureHttpKeepAlive(opts?: { keepAliveTimeoutMs?: number }): void {
24
+ // Idempotent: a second call (e.g. a process hosting several bridge
25
+ // entrypoints) must not replace — and leak — the already-installed Agent.
26
+ if (installed) return;
27
+ installed = true;
28
+ const keepAliveTimeout = opts?.keepAliveTimeoutMs ?? 120_000;
29
+ setGlobalDispatcher(
30
+ new Agent({
31
+ keepAliveTimeout,
32
+ // Also cap the server-hinted value: never idle past the edge's cutoff.
33
+ keepAliveMaxTimeout: keepAliveTimeout,
34
+ }),
35
+ );
36
+ }
package/src/index.ts CHANGED
@@ -11,6 +11,12 @@ export * from './bridge-workspace.js';
11
11
  export * from './dispatch-adapter.js';
12
12
  export { createLogger, childLogger } from './logger.js';
13
13
  export * from './gateway-base.js';
14
+ export { configureHttpKeepAlive } from './http-keepalive.js';
15
+ // StepPersister / StepRetryQueue / SessionLifecycleCoordinator /
16
+ // ForkSessionFinalizer are internal gateway collaborators — deliberately NOT
17
+ // re-exported from the package root (no external consumer; a root export
18
+ // would become an accidental long-term compat promise). Tests import their
19
+ // built modules directly (e.g. `../dist/step-retry-queue.js`).
14
20
  export * from './platform-config.js';
15
21
  export * from './channel-capability.js';
16
22
  export * from './channel-token.js';
@@ -0,0 +1,552 @@
1
+ /**
2
+ * SessionLifecycleCoordinator — the single entry point for session status
3
+ * writes (active / idle / closed).
4
+ *
5
+ * SCOPE — this is a **process-local mitigation**, not a distributed fence.
6
+ * It serializes and orders the lifecycle writes THIS process issues. It does
7
+ * NOT order across processes, and it cannot fix a write that times out
8
+ * client-side but lands server-side later, nor an old turn's step retry
9
+ * landing during a new turn. The structural fix is a server-side turn fence
10
+ * (design tracked in #1879 — durable step outbox + turn fence); until that
11
+ * ships, this closes the in-process interleavings that produced the
12
+ * 2026-07-13 repro.
13
+ *
14
+ * The gateway used to fire active and idle PATCHes independently
15
+ * (fire-and-forget + detached retries). Two independent HTTP requests have
16
+ * no ordering: turn 1's in-flight idle could land AFTER turn 2's active and
17
+ * demote a running session — an epoch check on retry TIMERS cannot cancel a
18
+ * request already on the wire. The coordinator closes that class by being a
19
+ * serialized desired-state reconciler:
20
+ *
21
+ * - Per session it stores only the LATEST desired state plus a monotonic
22
+ * generation (bumped by beginTurn and closeSession).
23
+ * - At most ONE lifecycle write is in flight per session; when it settles
24
+ * the loop re-reads the latest desired state and reconciles — so a
25
+ * begin(turn N+1), or a closeSession, that arrives while an earlier write
26
+ * is in flight simply waits for it to settle and is written AFTER it.
27
+ * - finishTurn carries the TurnHandle from its beginTurn; a stale handle
28
+ * (generation superseded) is ignored outright.
29
+ * - Retries re-run the reconcile loop against the LATEST desired state —
30
+ * they never replay a captured command, so a pending idle retry is
31
+ * naturally superseded by a new turn.
32
+ * - Errors are CLASSIFIED (ports, defaults are conservative): transient →
33
+ * bounded backoff; permanent (4xx) → warn + abandon that desired state (a
34
+ * later turn retries with a fresh generation); session-stale (the server
35
+ * considers the session terminal) → drop the session, never write again.
36
+ * - beginTurn / closeSession resolve once one write attempt covering their
37
+ * generation has SETTLED (success or failure — bounded by the write's own
38
+ * timeout, plus at most one in-flight predecessor). The gateway awaits
39
+ * beginTurn before persisting the turn's first AgentStep, so a reused idle
40
+ * session is reconciled to active before steps arrive and the server's
41
+ * presence guard cannot swallow the turn's activity. A failed active write
42
+ * warns and lets the step flow continue.
43
+ * - closeSession's first settle carries a STRUCTURED outcome (`closed` /
44
+ * `stale` / `retrying` / `permanent_failure` / `disposed`) plus a
45
+ * `terminal` promise that resolves when the close reaches a terminal fate
46
+ * — a caller holding cleanup behind the close (ForkSessionFinalizer) can
47
+ * keep ownership through `retrying` instead of mistaking "one attempt
48
+ * settled" for "close completed".
49
+ * - Entries are RECLAIMED (no unbounded Map growth on long-lived daemons):
50
+ * dropSession removes the entry immediately when idle, or at the end of an
51
+ * in-flight write; a `closed` that landed OR failed permanently reclaims
52
+ * too — the permanent failure is not hidden by the reclaim, it is reported
53
+ * through the close's outcome/terminal before the entry goes away.
54
+ * - dispose() is absorbing: every later public command is a no-op that never
55
+ * re-creates an entry, issues a write, or arms a timer.
56
+ *
57
+ * The write port is infrastructure (ParallClient.updateAgentSession);
58
+ * retries, generations, error classification and the state machine live here.
59
+ */
60
+
61
+ export type SessionStatusPayload =
62
+ | { status: 'active'; trigger_message_id?: string }
63
+ | { status: 'idle' }
64
+ | { status: 'closed' };
65
+
66
+ export type TurnHandle = { sessionId: string; generation: number };
67
+
68
+ /**
69
+ * Terminal fate of a closeSession: `closed` — the write landed; `stale` —
70
+ * the server already considers the session terminal (equivalent outcome for
71
+ * the caller); `permanent_failure` — a 4xx or retry exhaustion; the close
72
+ * will never be written and the server-side session may be left non-closed;
73
+ * `disposed` — the coordinator shut down before the close settled.
74
+ */
75
+ export type SessionCloseOutcome = 'closed' | 'stale' | 'permanent_failure' | 'disposed';
76
+
77
+ /** First-settle view: `retrying` means a transient failure settled the first
78
+ * bounded attempt and background reconciliation continues — await `terminal`
79
+ * for the eventual fate. */
80
+ export type SessionCloseSettle = SessionCloseOutcome | 'retrying';
81
+
82
+ export type SessionCloseResult = {
83
+ /** Outcome of the first bounded settle (one write attempt covering the close). */
84
+ outcome: SessionCloseSettle;
85
+ /**
86
+ * Resolves when the close reaches a terminal state. Already resolved (to
87
+ * `outcome`) unless `outcome === 'retrying'`.
88
+ */
89
+ terminal: Promise<SessionCloseOutcome>;
90
+ };
91
+
92
+ /** How one write attempt settled — the value first-settle waiters receive. */
93
+ type WriteSettle = 'ok' | 'retry' | 'permanent' | 'stale' | 'dropped' | 'disposed';
94
+
95
+ export type SessionLifecycleScheduler = {
96
+ setTimeout(fn: () => void, ms: number): unknown;
97
+ clearTimeout(timer: unknown): void;
98
+ };
99
+
100
+ export type SessionLifecycleOpts = {
101
+ write: (sessionId: string, payload: SessionStatusPayload) => Promise<void>;
102
+ /**
103
+ * Transient failure worth retrying (timeout / network / 5xx). Anything
104
+ * else is treated as permanent: warn + abandon (no retry loop against a
105
+ * 400/401/403/404). Default: nothing is retryable — callers that want
106
+ * retries must classify.
107
+ */
108
+ isRetryable?: (err: unknown) => boolean;
109
+ /**
110
+ * The server considers this session terminal (409 SESSION_NOT_LIVE /
111
+ * INVALID_TRANSITION). The session is dropped — no further lifecycle
112
+ * writes, ever. Default: never stale.
113
+ */
114
+ isSessionStale?: (err: unknown) => boolean;
115
+ log?: { warn: (msg: string) => void };
116
+ /** Test port; default wraps global timers and unrefs them. */
117
+ scheduler?: SessionLifecycleScheduler;
118
+ /** Reconcile retry backoff. Default 5s→15s→45s→135s→405s (~10 min). */
119
+ retryDelaysMs?: number[];
120
+ };
121
+
122
+ type DesiredState = 'active' | 'idle' | 'closed';
123
+
124
+ type StateStamp = { state: DesiredState; generation: number };
125
+
126
+ type Entry = {
127
+ desired: DesiredState;
128
+ generation: number;
129
+ triggerMessageId?: string;
130
+ writing: boolean;
131
+ /** Last successfully written state. */
132
+ written?: StateStamp;
133
+ /** Permanently failed state — not retried until the desired state moves. */
134
+ abandoned?: StateStamp;
135
+ retryTimer?: unknown;
136
+ retryAttempt: number;
137
+ waiters: Array<{ generation: number; resolve: (settle: WriteSettle) => void }>;
138
+ /** closeSession terminal-outcome waiters — resolved exactly once each. */
139
+ closeWaiters: Array<{ generation: number; resolve: (outcome: SessionCloseOutcome) => void }>;
140
+ dropped: boolean;
141
+ };
142
+
143
+ const DEFAULT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 135_000, 405_000];
144
+
145
+ const defaultScheduler: SessionLifecycleScheduler = {
146
+ setTimeout(fn, ms) {
147
+ const timer = setTimeout(fn, ms);
148
+ (timer as NodeJS.Timeout).unref?.();
149
+ return timer;
150
+ },
151
+ clearTimeout(timer) {
152
+ clearTimeout(timer as NodeJS.Timeout);
153
+ },
154
+ };
155
+
156
+ export class SessionLifecycleCoordinator {
157
+ private readonly sessions = new Map<string, Entry>();
158
+ private readonly scheduler: SessionLifecycleScheduler;
159
+ private readonly retryDelays: number[];
160
+ // Generations are coordinator-global and strictly increasing, so a handle
161
+ // from before an entry was reclaimed can never match a REBUILT entry for
162
+ // the same session id (per-entry counters restart at 1 — an ABA hazard
163
+ // where a stale finish would demote a fresh turn).
164
+ private nextGeneration = 0;
165
+ private disposed = false;
166
+
167
+ constructor(private readonly opts: SessionLifecycleOpts) {
168
+ this.scheduler = opts.scheduler ?? defaultScheduler;
169
+ this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS;
170
+ }
171
+
172
+ /** Sessions currently tracked — reclaimed entries are gone (leak probe). */
173
+ trackedSessions(): number {
174
+ return this.sessions.size;
175
+ }
176
+
177
+ /**
178
+ * Declare a new turn. Resolves once one write attempt covering this turn's
179
+ * generation has settled (bounded: at most one in-flight predecessor plus
180
+ * one active write, each bounded by the write port's own timeout). Always
181
+ * resolves — a failed active write is warned and reconciled in the
182
+ * background, never blocks the caller.
183
+ */
184
+ async beginTurn(sessionId: string, triggerMessageId?: string): Promise<TurnHandle> {
185
+ // Dispose is absorbing: never touch the map (an upsert here would
186
+ // re-create an entry nothing will ever reclaim), never write.
187
+ // Generation 0 can't match any live entry, so the handle is inert.
188
+ if (this.disposed) return { sessionId, generation: 0 };
189
+ const entry = this.upsert(sessionId);
190
+ entry.desired = 'active';
191
+ entry.triggerMessageId = triggerMessageId;
192
+ const generation = entry.generation;
193
+ const settled = this.waitFor(entry, generation);
194
+ this.pump(sessionId);
195
+ await settled;
196
+ return { sessionId, generation };
197
+ }
198
+
199
+ /**
200
+ * Declare the turn finished. A stale handle (a newer turn — or a close —
201
+ * has bumped this session's generation) is ignored: finish(turn N) can
202
+ * never override begin(turn N+1). Reconciliation runs detached.
203
+ */
204
+ finishTurn(handle: TurnHandle): void {
205
+ if (this.disposed) return;
206
+ const entry = this.sessions.get(handle.sessionId);
207
+ if (!entry || entry.dropped || entry.generation !== handle.generation) return;
208
+ if (entry.desired === 'closed') return;
209
+ entry.desired = 'idle';
210
+ entry.retryAttempt = 0;
211
+ this.cancelRetry(entry);
212
+ this.pump(handle.sessionId);
213
+ }
214
+
215
+ /**
216
+ * Terminal transition (fork teardown). Serialized behind any in-flight
217
+ * write — a `closed` can never race the turn's idle — and reclaimed once
218
+ * settled. Resolves after one bounded settle with a STRUCTURED outcome:
219
+ * `closed` / `stale` / `permanent_failure` are terminal; `retrying` means
220
+ * background reconciliation continues — the caller keeps ownership of the
221
+ * session until `terminal` resolves. A close is never silently "done":
222
+ * every fate is observable.
223
+ */
224
+ async closeSession(sessionId: string): Promise<SessionCloseResult> {
225
+ if (this.disposed) {
226
+ return { outcome: 'disposed', terminal: Promise.resolve('disposed') };
227
+ }
228
+ const entry = this.upsert(sessionId);
229
+ entry.desired = 'closed';
230
+ entry.triggerMessageId = undefined;
231
+ const generation = entry.generation;
232
+ const terminal = new Promise<SessionCloseOutcome>((resolve) => {
233
+ entry.closeWaiters.push({ generation, resolve });
234
+ });
235
+ const settled = this.waitFor(entry, generation);
236
+ this.pump(sessionId);
237
+ const settle = await settled;
238
+ return { outcome: closeSettleFor(settle), terminal };
239
+ }
240
+
241
+ /**
242
+ * Session is dead (stale / superseded) — no further lifecycle writes, and
243
+ * the entry is reclaimed (immediately when idle; at the end of an in-flight
244
+ * write otherwise, unless a new turn revives it in the meantime).
245
+ */
246
+ dropSession(sessionId: string): void {
247
+ const entry = this.sessions.get(sessionId);
248
+ if (!entry) return;
249
+ entry.dropped = true;
250
+ this.cancelRetry(entry);
251
+ this.resolveWaiters(entry, Number.POSITIVE_INFINITY, 'dropped');
252
+ this.reclaim(sessionId, entry);
253
+ }
254
+
255
+ /** Every tracked session is dead (server closed them all — new_session). */
256
+ dropAllSessions(): void {
257
+ for (const sessionId of [...this.sessions.keys()]) this.dropSession(sessionId);
258
+ }
259
+
260
+ /**
261
+ * One best-effort reconcile pass over unsettled sessions within a hard
262
+ * deadline (shutdown). Returns the number still unsettled.
263
+ */
264
+ async flush(deadlineMs: number): Promise<number> {
265
+ const deadline = Date.now() + deadlineMs;
266
+ for (const [sessionId, entry] of [...this.sessions.entries()]) {
267
+ if (this.disposed) break;
268
+ if (entry.dropped || this.isSettled(entry)) continue;
269
+ this.cancelRetry(entry);
270
+ entry.retryAttempt = 0;
271
+ const timeLeft = deadline - Date.now();
272
+ if (timeLeft <= 0) break;
273
+ const settled = this.waitFor(entry, entry.generation);
274
+ this.pump(sessionId);
275
+ await raceWithDeadline(settled, timeLeft);
276
+ }
277
+ let remaining = 0;
278
+ for (const entry of this.sessions.values()) {
279
+ if (!entry.dropped && !this.isSettled(entry)) remaining += 1;
280
+ }
281
+ return remaining;
282
+ }
283
+
284
+ dispose(): void {
285
+ this.disposed = true;
286
+ for (const entry of this.sessions.values()) {
287
+ this.cancelRetry(entry);
288
+ this.resolveWaiters(entry, Number.POSITIVE_INFINITY, 'disposed');
289
+ this.settleCloseTerminal(entry, 'disposed');
290
+ }
291
+ this.sessions.clear();
292
+ }
293
+
294
+ // --- internals ----------------------------------------------------------
295
+
296
+ /**
297
+ * Get-or-create the entry and take the next generation. A dropped entry is
298
+ * REUSED (not replaced): its `writing` flag keeps the single-writer chain
299
+ * intact if a pre-drop write is still on the wire, and the generation stays
300
+ * monotonic across the drop boundary.
301
+ */
302
+ private upsert(sessionId: string): Entry {
303
+ let entry = this.sessions.get(sessionId);
304
+ if (!entry) {
305
+ entry = {
306
+ desired: 'active',
307
+ generation: 0,
308
+ writing: false,
309
+ retryAttempt: 0,
310
+ waiters: [],
311
+ closeWaiters: [],
312
+ dropped: false,
313
+ };
314
+ this.sessions.set(sessionId, entry);
315
+ }
316
+ entry.dropped = false;
317
+ this.nextGeneration += 1;
318
+ entry.generation = this.nextGeneration;
319
+ entry.retryAttempt = 0;
320
+ this.cancelRetry(entry);
321
+ return entry;
322
+ }
323
+
324
+ private waitFor(entry: Entry, generation: number): Promise<WriteSettle> {
325
+ return new Promise<WriteSettle>((resolve) => {
326
+ entry.waiters.push({ generation, resolve });
327
+ });
328
+ }
329
+
330
+ private isReconciled(entry: Entry): boolean {
331
+ return (
332
+ entry.written !== undefined &&
333
+ entry.written.state === entry.desired &&
334
+ entry.written.generation === entry.generation
335
+ );
336
+ }
337
+
338
+ private isAbandoned(entry: Entry): boolean {
339
+ return (
340
+ entry.abandoned !== undefined &&
341
+ entry.abandoned.state === entry.desired &&
342
+ entry.abandoned.generation === entry.generation
343
+ );
344
+ }
345
+
346
+ /** Nothing more to do for the current desired state (written or given up). */
347
+ private isSettled(entry: Entry): boolean {
348
+ return this.isReconciled(entry) || this.isAbandoned(entry);
349
+ }
350
+
351
+ private pump(sessionId: string): void {
352
+ const entry = this.sessions.get(sessionId);
353
+ if (!entry || entry.writing || entry.dropped || this.disposed) return;
354
+ if (this.isSettled(entry)) {
355
+ this.resolveWaiters(entry, entry.generation, this.isReconciled(entry) ? 'ok' : 'permanent');
356
+ this.reclaim(sessionId, entry);
357
+ return;
358
+ }
359
+ entry.writing = true;
360
+ void this.writeLoop(sessionId, entry);
361
+ }
362
+
363
+ private async writeLoop(sessionId: string, entry: Entry): Promise<void> {
364
+ try {
365
+ while (!entry.dropped && !this.disposed && !this.isSettled(entry)) {
366
+ const snapshot: StateStamp & { trigger?: string } = {
367
+ state: entry.desired,
368
+ generation: entry.generation,
369
+ trigger: entry.triggerMessageId,
370
+ };
371
+ let outcome: 'ok' | 'retry' | 'permanent' | 'stale' = 'ok';
372
+ try {
373
+ await this.opts.write(sessionId, payloadFor(snapshot));
374
+ entry.written = { state: snapshot.state, generation: snapshot.generation };
375
+ entry.retryAttempt = 0;
376
+ if (snapshot.state === 'closed') {
377
+ this.settleCloseTerminal(entry, 'closed', snapshot.generation);
378
+ }
379
+ } catch (err) {
380
+ outcome = this.classify(err);
381
+ this.opts.log?.warn(
382
+ `session ${sessionId} ${snapshot.state} write failed (${outcome}, gen ${snapshot.generation}): ${String(err)}`,
383
+ );
384
+ }
385
+ // A settle — success or failure — resolves every waiter this
386
+ // snapshot covers (the bounded beginTurn / closeSession contract).
387
+ this.resolveWaiters(entry, snapshot.generation, outcome);
388
+
389
+ if (outcome === 'stale') {
390
+ // Terminal server-side: never write to this session again.
391
+ entry.dropped = true;
392
+ this.cancelRetry(entry);
393
+ this.settleCloseTerminal(entry, 'stale');
394
+ this.resolveWaiters(entry, Number.POSITIVE_INFINITY, 'stale');
395
+ return;
396
+ }
397
+ const desiredUnchanged =
398
+ snapshot.generation === entry.generation && snapshot.state === entry.desired;
399
+ if (outcome === 'permanent' && desiredUnchanged) {
400
+ // No retry loop against a 4xx — a later turn (fresh generation)
401
+ // un-abandons this session automatically.
402
+ entry.abandoned = { state: snapshot.state, generation: snapshot.generation };
403
+ if (snapshot.state === 'closed') {
404
+ this.settleCloseTerminal(entry, 'permanent_failure', snapshot.generation);
405
+ }
406
+ return;
407
+ }
408
+ if (outcome === 'retry' && desiredUnchanged && !entry.dropped && !this.disposed) {
409
+ // The retry re-enters pump and replays the LATEST desired state,
410
+ // never this snapshot.
411
+ this.scheduleRetry(sessionId, entry);
412
+ return;
413
+ }
414
+ // Success, or the desired state advanced while writing: loop and
415
+ // reconcile the fresh state immediately.
416
+ }
417
+ } finally {
418
+ entry.writing = false;
419
+ this.reclaim(sessionId, entry);
420
+ }
421
+ }
422
+
423
+ private classify(err: unknown): 'retry' | 'permanent' | 'stale' {
424
+ if (this.opts.isSessionStale?.(err)) return 'stale';
425
+ if (this.opts.isRetryable?.(err)) return 'retry';
426
+ return 'permanent';
427
+ }
428
+
429
+ /**
430
+ * Drop the entry when it can never write again: dropped (and no write on
431
+ * the wire), a terminal `closed` that landed, or a `closed` that failed
432
+ * permanently (its fate has been reported via closeSession's outcome — an
433
+ * entry kept around would be an unowned leak, not a recovery path). Called
434
+ * after every write settles and from dropSession — this is what keeps the
435
+ * Map bounded on a long-lived daemon churning fork sessions.
436
+ */
437
+ private reclaim(sessionId: string, entry: Entry): void {
438
+ if (this.sessions.get(sessionId) !== entry) return;
439
+ if (entry.writing) return; // the write's finally will re-run this
440
+ const closedLanded =
441
+ entry.desired === 'closed' &&
442
+ entry.written?.state === 'closed' &&
443
+ entry.written.generation === entry.generation;
444
+ const closedAbandoned =
445
+ entry.desired === 'closed' &&
446
+ entry.abandoned?.state === 'closed' &&
447
+ entry.abandoned.generation === entry.generation;
448
+ if (!entry.dropped && !closedLanded && !closedAbandoned) return;
449
+ this.cancelRetry(entry);
450
+ this.settleCloseTerminal(
451
+ entry,
452
+ closedLanded ? 'closed' : entry.dropped ? 'stale' : 'permanent_failure',
453
+ );
454
+ this.resolveWaiters(
455
+ entry,
456
+ Number.POSITIVE_INFINITY,
457
+ closedLanded ? 'ok' : entry.dropped ? 'dropped' : 'permanent',
458
+ );
459
+ this.sessions.delete(sessionId);
460
+ }
461
+
462
+ private scheduleRetry(sessionId: string, entry: Entry): void {
463
+ if (entry.retryTimer !== undefined) return;
464
+ if (entry.retryAttempt >= this.retryDelays.length) {
465
+ this.opts.log?.warn(
466
+ `session ${sessionId} lifecycle reconcile giving up after ${entry.retryAttempt} retries (desired=${entry.desired})`,
467
+ );
468
+ entry.abandoned = { state: entry.desired, generation: entry.generation };
469
+ if (entry.desired === 'closed') {
470
+ this.settleCloseTerminal(entry, 'permanent_failure');
471
+ }
472
+ return;
473
+ }
474
+ const delay = this.retryDelays[entry.retryAttempt] ?? 5_000;
475
+ entry.retryAttempt += 1;
476
+ entry.retryTimer = this.scheduler.setTimeout(() => {
477
+ entry.retryTimer = undefined;
478
+ this.pump(sessionId);
479
+ }, delay);
480
+ }
481
+
482
+ private cancelRetry(entry: Entry): void {
483
+ if (entry.retryTimer !== undefined) {
484
+ this.scheduler.clearTimeout(entry.retryTimer);
485
+ entry.retryTimer = undefined;
486
+ }
487
+ }
488
+
489
+ private resolveWaiters(entry: Entry, upToGeneration: number, settle: WriteSettle): void {
490
+ if (entry.waiters.length === 0) return;
491
+ const remaining: Entry['waiters'] = [];
492
+ for (const waiter of entry.waiters) {
493
+ if (waiter.generation <= upToGeneration) waiter.resolve(settle);
494
+ else remaining.push(waiter);
495
+ }
496
+ entry.waiters = remaining;
497
+ }
498
+
499
+ /** Resolve closeSession terminal waiters covered by this settle, once. */
500
+ private settleCloseTerminal(
501
+ entry: Entry,
502
+ outcome: SessionCloseOutcome,
503
+ upToGeneration = Number.POSITIVE_INFINITY,
504
+ ): void {
505
+ if (entry.closeWaiters.length === 0) return;
506
+ const remaining: Entry['closeWaiters'] = [];
507
+ for (const waiter of entry.closeWaiters) {
508
+ if (waiter.generation <= upToGeneration) waiter.resolve(outcome);
509
+ else remaining.push(waiter);
510
+ }
511
+ entry.closeWaiters = remaining;
512
+ }
513
+ }
514
+
515
+ /** Map a first-settle write outcome onto the closeSession vocabulary. */
516
+ function closeSettleFor(settle: WriteSettle): SessionCloseSettle {
517
+ switch (settle) {
518
+ case 'ok':
519
+ return 'closed';
520
+ case 'retry':
521
+ return 'retrying';
522
+ case 'stale':
523
+ case 'dropped':
524
+ return 'stale';
525
+ case 'disposed':
526
+ return 'disposed';
527
+ default:
528
+ return 'permanent_failure';
529
+ }
530
+ }
531
+
532
+ function payloadFor(snapshot: StateStamp & { trigger?: string }): SessionStatusPayload {
533
+ if (snapshot.state === 'active') {
534
+ return {
535
+ status: 'active',
536
+ ...(snapshot.trigger ? { trigger_message_id: snapshot.trigger } : {}),
537
+ };
538
+ }
539
+ return snapshot.state === 'idle' ? { status: 'idle' } : { status: 'closed' };
540
+ }
541
+
542
+ async function raceWithDeadline<T>(work: Promise<T>, ms: number): Promise<T | 'timeout'> {
543
+ let timer: NodeJS.Timeout | undefined;
544
+ const timeout = new Promise<'timeout'>((resolve) => {
545
+ timer = setTimeout(() => resolve('timeout'), Math.max(0, ms));
546
+ });
547
+ try {
548
+ return await Promise.race([work, timeout]);
549
+ } finally {
550
+ clearTimeout(timer);
551
+ }
552
+ }
@@ -26,6 +26,9 @@ Results are JSON on stdout; failures print an error.
26
26
  clip's owner or an admin to bind it — do not retry or work around it.
27
27
  - If the executing runtime is offline or the call times out, report that
28
28
  plainly; do not queue, and never fabricate a result for a run that errored.
29
+ - Hosted browser activation is handled by the CLI: it waits (bounded) while a
30
+ cold hosted browser starts, so if the invoke still fails, report the error —
31
+ do not blind-retry in a loop.
29
32
  - A clip may act through a person's real logged-in account — outward,
30
33
  irreversible, or spending actions (post, order, delete, pay) get the same
31
34
  caution as any shared-state change: confirm when intent isn't explicit.