effect-durable-agent 0.1.0-alpha.29 → 0.1.0-alpha.30

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 (93) hide show
  1. package/dist/{compaction-ajHZ5l7f.js → compaction-63iEDHHl.js} +2 -2
  2. package/dist/{compaction-ajHZ5l7f.js.map → compaction-63iEDHHl.js.map} +1 -1
  3. package/dist/{delivery-Bb7pkQ9o.js → delivery-2ZILvoRD.js} +2 -2
  4. package/dist/{delivery-Bb7pkQ9o.js.map → delivery-2ZILvoRD.js.map} +1 -1
  5. package/dist/{delivery-C0aN3Oza.d.ts → delivery-RjM1_NAE.d.ts} +4 -3
  6. package/dist/domain/command-queues.d.ts +1 -1
  7. package/dist/domain/message-transcript.d.ts +1 -1
  8. package/dist/domain/reduced-state-schema.d.ts +1 -1
  9. package/dist/domain/reduced-state-schema.js +2 -1
  10. package/dist/domain/reduced-state-schema.js.map +1 -1
  11. package/dist/domain/reduced-state.d.ts +1 -1
  12. package/dist/domain/reduced-state.js +13 -4
  13. package/dist/domain/reduced-state.js.map +1 -1
  14. package/dist/domain/run-scheduling.d.ts +1 -1
  15. package/dist/{durable-CKdCCqhw.d.ts → durable-Cqv5ZRFA.d.ts} +14 -2
  16. package/dist/{durable-CD__3ztN.js → durable-D13w1Qr3.js} +11 -3
  17. package/dist/{durable-CD__3ztN.js.map → durable-D13w1Qr3.js.map} +1 -1
  18. package/dist/{event-factory-VAci3NJb.js → event-factory-_vF1bIJ7.js} +2 -2
  19. package/dist/{event-factory-VAci3NJb.js.map → event-factory-_vF1bIJ7.js.map} +1 -1
  20. package/dist/{events-BWuvzVml.d.ts → events-Dg0o5wWs.d.ts} +2 -2
  21. package/dist/{in-memory-IgxnTbGb.js → in-memory-CeODnZhE.js} +3 -3
  22. package/dist/{in-memory-IgxnTbGb.js.map → in-memory-CeODnZhE.js.map} +1 -1
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/{interpreter-BdRoYrfL.js → interpreter-DKGJ1sSx.js} +4 -4
  26. package/dist/{interpreter-BdRoYrfL.js.map → interpreter-DKGJ1sSx.js.map} +1 -1
  27. package/dist/{model-resolver-DUms5p6X.d.ts → model-resolver-D0vcDZsU.d.ts} +2 -2
  28. package/dist/{records-DWKEjuqb.js → records--54mZEBx.js} +2 -2
  29. package/dist/{records-DWKEjuqb.js.map → records--54mZEBx.js.map} +1 -1
  30. package/dist/{reduced-state-D50SR0qM.d.ts → reduced-state-DU2ECOUp.d.ts} +1600 -1561
  31. package/dist/{reduced-state-schema-jyZWJ0QS.d.ts → reduced-state-schema-B2t3cobf.d.ts} +3 -1
  32. package/dist/{reducer-registry-CPObI3cs.d.ts → reducer-registry-JLU1yptN.d.ts} +4 -4
  33. package/dist/{run-scheduling-wakeup-B19JTeyq.d.ts → run-scheduling-wakeup-D_bGdicf.d.ts} +2 -2
  34. package/dist/services/compaction.d.ts +1 -1
  35. package/dist/services/compaction.js +1 -1
  36. package/dist/services/model-call.d.ts +1 -1
  37. package/dist/services/model-resolver.d.ts +1 -1
  38. package/dist/services/prompt-projector.d.ts +1 -1
  39. package/dist/services/reducer-registry.d.ts +1 -1
  40. package/dist/services/run-scheduler.d.ts +1 -1
  41. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  42. package/dist/services/runtime-layer.d.ts +8 -8
  43. package/dist/services/runtime-layer.js +4 -4
  44. package/dist/services/runtime.d.ts +1 -1
  45. package/dist/services/runtime.js +2 -2
  46. package/dist/services/session-event-observer.d.ts +1 -1
  47. package/dist/services/session-query.d.ts +1 -1
  48. package/dist/services/session-query.js +2 -2
  49. package/dist/services/session-state.d.ts +1 -1
  50. package/dist/services/session-state.js +1 -1
  51. package/dist/services/session-store.d.ts +1 -1
  52. package/dist/services/session-store.js +5 -5
  53. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  54. package/dist/services/sink-registry.d.ts +1 -1
  55. package/dist/services/sink-registry.js +1 -1
  56. package/dist/services/span-names.d.ts +1 -1
  57. package/dist/services/span-names.js +1 -0
  58. package/dist/services/span-names.js.map +1 -1
  59. package/dist/services/tool-registry.d.ts +2 -2
  60. package/dist/services/tool-registry.js +10 -1
  61. package/dist/services/tool-registry.js.map +1 -1
  62. package/dist/services/tracing.d.ts +1 -1
  63. package/dist/{session-event-observer-BdZltdrK.d.ts → session-event-observer-HvrRckbC.d.ts} +2 -2
  64. package/dist/{session-state-BW0l2aNk.js → session-state-BQYsuBqi.js} +154 -59
  65. package/dist/session-state-BQYsuBqi.js.map +1 -0
  66. package/dist/{session-store-CWYZ29CV.d.ts → session-store-CQxg9U82.d.ts} +3 -3
  67. package/dist/{sink-checkpoint-store-B8Ky5nfW.d.ts → sink-checkpoint-store-DWGifxp0.d.ts} +2 -2
  68. package/dist/{sink-registry-D0MetcNq.js → sink-registry-DskRcyOS.js} +2 -2
  69. package/dist/{sink-registry-D0MetcNq.js.map → sink-registry-DskRcyOS.js.map} +1 -1
  70. package/dist/{subscription-hkD4M3xp.js → subscription-DmO3BcdT.js} +2 -2
  71. package/dist/{subscription-hkD4M3xp.js.map → subscription-DmO3BcdT.js.map} +1 -1
  72. package/dist/{subscription-DelB8L87.d.ts → subscription-rC35dAWn.d.ts} +2 -2
  73. package/dist/testkit/layers.d.ts +11 -9
  74. package/dist/testkit/layers.js +5 -5
  75. package/dist/testkit/layers.js.map +1 -1
  76. package/dist/testkit/transcript.d.ts +2 -2
  77. package/dist/testkit/transcript.js +4 -4
  78. package/dist/{tool-registry-B_WE2ZwK.d.ts → tool-registry-BzlMhwzj.d.ts} +35 -6
  79. package/dist/transcript.d.ts +4 -4
  80. package/dist/transcript.js +5 -5
  81. package/dist/types/events/durable.d.ts +1 -1
  82. package/dist/types/events/durable.js +1 -1
  83. package/dist/types/events.d.ts +2 -2
  84. package/dist/types/events.js +1 -1
  85. package/dist/websocket/events.d.ts +1 -1
  86. package/dist/websocket/events.js +1 -1
  87. package/dist/websocket.d.ts +3 -3
  88. package/dist/websocket.js +3 -3
  89. package/dist/{window-read-BG8lxMVB.d.ts → window-read-CBZEJ84M.d.ts} +2 -2
  90. package/dist/{window-read-C8anZVdl.js → window-read-DPFAA1hM.js} +2 -2
  91. package/dist/{window-read-C8anZVdl.js.map → window-read-DPFAA1hM.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/dist/session-state-BW0l2aNk.js.map +0 -1
@@ -6,21 +6,21 @@ import { ModelResolver } from "./services/model-resolver.js";
6
6
  import { makeEDARunTrace } from "./types/tracing.js";
7
7
  import { d as PositionedEvent, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
8
8
  import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
9
- import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-CD__3ztN.js";
9
+ import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-D13w1Qr3.js";
10
10
  import { n as assertNeverError, t as assertNever } from "./assert-never-CoyUpoRB.js";
11
11
  import { activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, initialReducedState, reducedStateCheckpointEventSeqs } from "./domain/reduced-state.js";
12
12
  import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
13
13
  import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
14
- import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-ajHZ5l7f.js";
14
+ import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-63iEDHHl.js";
15
15
  import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
16
- import { n as SessionContext, t as EventFactory } from "./event-factory-VAci3NJb.js";
17
- import { EDAToolRegistry } from "./services/tool-registry.js";
16
+ import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
17
+ import { EDAToolRegistry, toolRecoveryPolicy } from "./services/tool-registry.js";
18
18
  import { IdGenerator } from "./services/id-generator.js";
19
19
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
20
20
  import { EDAKeepAlive } from "./services/keep-alive.js";
21
21
  import { SessionEventObserver } from "./services/session-event-observer.js";
22
22
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
23
- import { n as EDASinkRegistry } from "./sink-registry-D0MetcNq.js";
23
+ import { n as EDASinkRegistry } from "./sink-registry-DskRcyOS.js";
24
24
  import * as Context from "effect/Context";
25
25
  import * as Effect from "effect/Effect";
26
26
  import * as Layer from "effect/Layer";
@@ -396,7 +396,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
396
396
  yield* annotateEdaSpan({
397
397
  "eda.tool_call.id": created.event.payload.toolCallId,
398
398
  "eda.tool.name": created.event.payload.promptPart.name,
399
- "eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted
399
+ "eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted,
400
+ ...input.resume === void 0 ? {} : { "eda.tool.attempt": input.resume.attempt }
400
401
  });
401
402
  if (created.event.payload.promptPart.providerExecuted) {
402
403
  const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
@@ -407,7 +408,10 @@ const makeLiveToolExecutor = Effect.gen(function* () {
407
408
  };
408
409
  }
409
410
  const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
410
- start: events.toolCallStarted({ toolCallId: created.event.payload.toolCallId }),
411
+ start: events.toolCallStarted({
412
+ toolCallId: created.event.payload.toolCallId,
413
+ ...input.resume === void 0 ? {} : { attempt: input.resume.attempt }
414
+ }),
411
415
  body: () => Effect.gen(function* () {
412
416
  const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
413
417
  toolCallId: created.event.payload.toolCallId,
@@ -416,7 +420,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
416
420
  queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
417
421
  sessionId: session.sessionId,
418
422
  makeEventId: ids.makeEventId,
419
- emitDurable: input.eventSink.appendDurable
423
+ emitDurable: input.eventSink.appendDurable,
424
+ ...input.resume === void 0 ? {} : { recovery: input.resume }
420
425
  }).pipe(Effect.map((result) => ({
421
426
  _tag: "Succeeded",
422
427
  result
@@ -1279,6 +1284,7 @@ const makeLiveTurnRunner = Effect.gen(function* () {
1279
1284
  const events = yield* EventFactory;
1280
1285
  const inferenceRunner = yield* InferenceRunner;
1281
1286
  const toolExecutor = yield* ToolExecutor;
1287
+ const toolRegistry = yield* EDAToolRegistry;
1282
1288
  const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
1283
1289
  const usage = inferenceCompleted.event.payload.usage;
1284
1290
  const turnCompleted = yield* events.turnCompleted({
@@ -1397,55 +1403,66 @@ const makeLiveTurnRunner = Effect.gen(function* () {
1397
1403
  return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
1398
1404
  });
1399
1405
  });
1400
- return { runTurn: Effect.fn("agent.turn")(function* (input) {
1401
- const turnIdentity = {
1402
- runId: input.runId,
1403
- turnId: input.turnId
1404
- };
1405
- const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
1406
- yield* annotateEdaSpan({
1407
- "eda.run.id": input.runId,
1408
- "eda.turn.id": input.turnId,
1409
- "eda.model.provider": input.modelSelection?.provider,
1410
- "eda.model.id": input.modelSelection?.modelId,
1411
- "eda.tool.max_calls_per_run": maxToolCallsPerRun
1412
- });
1413
- const inferencesStarted = yield* Ref.make(0);
1414
- return yield* Effect.gen(function* () {
1415
- const inferenceId = yield* ids.makeInferenceId();
1416
- yield* Ref.update(inferencesStarted, (count) => count + 1);
1417
- const inference = yield* inferenceRunner.runInference({
1418
- ...turnIdentity,
1419
- inferenceId,
1420
- prompt: input.prompt,
1421
- eventSink: input.eventSink,
1422
- modelSelection: input.modelSelection
1423
- });
1424
- const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
1425
- return TurnRunResult.make({
1426
- started: input.started,
1427
- inference,
1428
- outcome
1429
- });
1430
- }).pipe(Effect.tap((result) => Effect.gen(function* () {
1406
+ return {
1407
+ toolRecoveryPolicy: (toolName) => toolRegistry.getModelToolkit().pipe(Effect.map((toolkit) => toolRecoveryPolicy(toolkit, toolName))),
1408
+ resumeToolCalls: ({ calls, eventSink }) => Effect.forEach(calls, ({ created, resume }) => toolExecutor.executeCreated({
1409
+ created,
1410
+ eventSink,
1411
+ resume
1412
+ }), {
1413
+ concurrency: maxToolExecutionConcurrency,
1414
+ discard: true
1415
+ }),
1416
+ runTurn: Effect.fn("agent.turn")(function* (input) {
1417
+ const turnIdentity = {
1418
+ runId: input.runId,
1419
+ turnId: input.turnId
1420
+ };
1421
+ const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
1431
1422
  yield* annotateEdaSpan({
1432
- "eda.turn.outcome": result.outcome._tag,
1433
- "eda.inference.started_count": yield* Ref.get(inferencesStarted),
1434
- "eda.provider.parts_recorded": result.inference.partsRecorded,
1435
- ...turnUsageAttributes(result)
1423
+ "eda.run.id": input.runId,
1424
+ "eda.turn.id": input.turnId,
1425
+ "eda.model.provider": input.modelSelection?.provider,
1426
+ "eda.model.id": input.modelSelection?.modelId,
1427
+ "eda.tool.max_calls_per_run": maxToolCallsPerRun
1436
1428
  });
1437
- })), Effect.catchCause((cause) => {
1438
- if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
1439
- return Effect.uninterruptible(Effect.gen(function* () {
1440
- const terminal = yield* events.turnFailed({
1429
+ const inferencesStarted = yield* Ref.make(0);
1430
+ return yield* Effect.gen(function* () {
1431
+ const inferenceId = yield* ids.makeInferenceId();
1432
+ yield* Ref.update(inferencesStarted, (count) => count + 1);
1433
+ const inference = yield* inferenceRunner.runInference({
1441
1434
  ...turnIdentity,
1442
- error: failurePayloadFromCause(cause)
1435
+ inferenceId,
1436
+ prompt: input.prompt,
1437
+ eventSink: input.eventSink,
1438
+ modelSelection: input.modelSelection
1439
+ });
1440
+ const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
1441
+ return TurnRunResult.make({
1442
+ started: input.started,
1443
+ inference,
1444
+ outcome
1443
1445
  });
1444
- yield* input.eventSink.appendDurable(terminal);
1445
- return yield* Effect.failCause(cause);
1446
+ }).pipe(Effect.tap((result) => Effect.gen(function* () {
1447
+ yield* annotateEdaSpan({
1448
+ "eda.turn.outcome": result.outcome._tag,
1449
+ "eda.inference.started_count": yield* Ref.get(inferencesStarted),
1450
+ "eda.provider.parts_recorded": result.inference.partsRecorded,
1451
+ ...turnUsageAttributes(result)
1452
+ });
1453
+ })), Effect.catchCause((cause) => {
1454
+ if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
1455
+ return Effect.uninterruptible(Effect.gen(function* () {
1456
+ const terminal = yield* events.turnFailed({
1457
+ ...turnIdentity,
1458
+ error: failurePayloadFromCause(cause)
1459
+ });
1460
+ yield* input.eventSink.appendDurable(terminal);
1461
+ return yield* Effect.failCause(cause);
1462
+ }));
1446
1463
  }));
1447
- }));
1448
- }) };
1464
+ })
1465
+ };
1449
1466
  });
1450
1467
  /** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
1451
1468
  var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
@@ -1638,6 +1655,14 @@ const makeLiveSessionState = Effect.gen(function* () {
1638
1655
  });
1639
1656
  const gate = yield* Semaphore.make(1);
1640
1657
  const controlGate = yield* Semaphore.make(1);
1658
+ /**
1659
+ * Admission versus startup repair: recovery plans its repair batch from a snapshot and then
1660
+ * checks the result reached a fixed point, so no command may be admitted in between. Recovery
1661
+ * that finishes in the background (re-invoked tools) would otherwise race live admission.
1662
+ */
1663
+ const admissionGate = yield* Semaphore.make(1);
1664
+ /** Set while startup recovery finishes in the background holding the control gate. */
1665
+ const recoveringInBackground = yield* Ref.make(false);
1641
1666
  const deliveryGate = yield* Semaphore.make(1);
1642
1667
  const ingressSignals = yield* Queue.sliding(1);
1643
1668
  const reducerCheckpointSnapshots = yield* Queue.sliding(1);
@@ -1847,7 +1872,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1847
1872
  submitted
1848
1873
  ];
1849
1874
  });
1850
- const submitBatch = Effect.fn(function* (input) {
1875
+ const submitBatch = (input) => admissionGate.withPermits(1)(submitBatchAdmitted(input));
1876
+ const submitBatchAdmitted = Effect.fn(function* (input) {
1851
1877
  const commandCount = input.filter(isEDACommand).length;
1852
1878
  yield* annotateEdaSpan({
1853
1879
  "eda.command.submittable_count": input.length,
@@ -2119,6 +2145,7 @@ const makeLiveSessionState = Effect.gen(function* () {
2119
2145
  yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
2120
2146
  });
2121
2147
  const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
2148
+ if (yield* Ref.get(recoveringInBackground)) return;
2122
2149
  yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
2123
2150
  const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
2124
2151
  const current = (yield* currentReduced()).runSchedulingRequest;
@@ -2448,6 +2475,47 @@ const makeLiveSessionState = Effect.gen(function* () {
2448
2475
  turn: exit.value
2449
2476
  };
2450
2477
  });
2478
+ /**
2479
+ * Before failing what the dead runtime left open, re-invoke each started tool call whose tool
2480
+ * declares `ToolRecovery: "reinvoke"` and still has attempts left. Each commits its next start
2481
+ * before running, so a runtime that dies again mid-reinvocation spends that attempt. Calls that
2482
+ * finish here are terminal by the time recovery plans its batch; the rest are failed as before.
2483
+ */
2484
+ const plannedReinvocations = Effect.fnUntraced(function* (reduced) {
2485
+ const calls = [];
2486
+ for (const tool of planSessionRecovery(reduced).openToolCalls) {
2487
+ const decision = tool.decision;
2488
+ if (decision?._tag !== "Created" || decision.providerExecuted) continue;
2489
+ if (tool.startedSeq === void 0 || tool.startedAtMs === void 0) continue;
2490
+ const attempt = (tool.attempt ?? 1) + 1;
2491
+ if (attempt > 3) continue;
2492
+ if ((yield* turnRunner.toolRecoveryPolicy(decision.toolName)) !== "reinvoke") continue;
2493
+ calls.push({
2494
+ seq: decision.seq,
2495
+ resume: {
2496
+ attempt,
2497
+ firstStartedAtMs: tool.startedAtMs,
2498
+ firstStartedSeq: tool.startedSeq
2499
+ }
2500
+ });
2501
+ }
2502
+ return calls;
2503
+ });
2504
+ const resumeInterruptedToolCalls = Effect.fnUntraced(function* (calls) {
2505
+ yield* annotateEdaSpan({ "eda.recovery.reinvoked_tool_calls": calls.length });
2506
+ if (calls.length === 0) return;
2507
+ const created = yield* store.loadCommittedEventsBySeq(calls.map((call) => call.seq));
2508
+ yield* turnRunner.resumeToolCalls({
2509
+ calls: calls.flatMap((call) => {
2510
+ const event = created.find((entry) => entry.position.seq === call.seq);
2511
+ return event === void 0 ? [] : [{
2512
+ created: event,
2513
+ resume: call.resume
2514
+ }];
2515
+ }),
2516
+ eventSink: sessionApi
2517
+ }).pipe(Effect.catchTag("ToolExecutionEventNotCreated", (error) => Effect.die(error)));
2518
+ });
2451
2519
  const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
2452
2520
  const plan = planSessionRecovery(reduced);
2453
2521
  input = {
@@ -3080,12 +3148,20 @@ const makeLiveSessionState = Effect.gen(function* () {
3080
3148
  "eda.model.id": input.modelSelection.modelId
3081
3149
  });
3082
3150
  yield* failIfFatal;
3083
- const initial = yield* currentReduced();
3151
+ const { initial, recovery } = yield* admissionGate.withPermits(1)(Effect.gen(function* () {
3152
+ const initial = yield* currentReduced();
3153
+ return {
3154
+ initial,
3155
+ recovery: yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, {
3156
+ ...input,
3157
+ modelSelection: initial.modelSelection ?? input.modelSelection
3158
+ }))
3159
+ };
3160
+ }));
3084
3161
  input = {
3085
3162
  ...input,
3086
3163
  modelSelection: initial.modelSelection ?? input.modelSelection
3087
3164
  };
3088
- const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
3089
3165
  yield* requestStartupRecoveryCheckpointIfNeeded();
3090
3166
  if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
3091
3167
  });
@@ -3122,9 +3198,28 @@ const makeLiveSessionState = Effect.gen(function* () {
3122
3198
  }
3123
3199
  });
3124
3200
  const start = Effect.fn(function* (input) {
3125
- yield* runStartupRecovery(input);
3126
- yield* forkSchedulingDelivery();
3127
- yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
3201
+ const reinvocations = yield* plannedReinvocations(yield* currentReduced());
3202
+ if (reinvocations.length === 0) {
3203
+ yield* runStartupRecovery(input);
3204
+ yield* forkSchedulingDelivery();
3205
+ yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
3206
+ return;
3207
+ }
3208
+ yield* controlGate.take(1);
3209
+ yield* Ref.set(recoveringInBackground, true);
3210
+ yield* Effect.gen(function* () {
3211
+ yield* annotateRunInput(input);
3212
+ yield* initialize(input);
3213
+ yield* keepAlive.withActiveWork("session-recovery", Effect.gen(function* () {
3214
+ yield* withFatalRecording(resumeInterruptedToolCalls(reinvocations));
3215
+ yield* runStartupRecoveryPass(input);
3216
+ }));
3217
+ }).pipe(Effect.ensuring(Ref.set(recoveringInBackground, false).pipe(Effect.andThen(controlGate.release(1)))), Effect.andThen(forkSchedulingDelivery()), Effect.andThen(runLiveControlLoop(input)), Effect.catchCause((cause) => Effect.gen(function* () {
3218
+ const message = `EDA background startup recovery failed: ${Cause.pretty(cause)}`;
3219
+ yield* markFatalIfDurable(cause);
3220
+ yield* Ref.update(fatalInvariantViolation, (current) => current ?? message);
3221
+ yield* Effect.logError(message);
3222
+ })), Effect.withSpan("agent.session.recover.tools"), Effect.forkIn(runtimeScope));
3128
3223
  });
3129
3224
  yield* sinkRegistry.startSinkRunners({
3130
3225
  appendDurableBatch,
@@ -3230,4 +3325,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
3230
3325
  //#endregion
3231
3326
  export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, LiveEventBus as m, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
3232
3327
 
3233
- //# sourceMappingURL=session-state-BW0l2aNk.js.map
3328
+ //# sourceMappingURL=session-state-BQYsuBqi.js.map