effect-durable-agent 0.1.0-alpha.18 → 0.1.0-alpha.20

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 (120) hide show
  1. package/dist/{commands-p8venTWs.d.ts → commands-3OD-p8dD.d.ts} +7 -8
  2. package/dist/{compaction-Db6eoLce.js → compaction-GD1cTPTZ.js} +5 -7
  3. package/dist/compaction-GD1cTPTZ.js.map +1 -0
  4. package/dist/{context-projection-Dr_kA41k.d.ts → context-projection-D_uRtK3r.d.ts} +15 -16
  5. package/dist/{core-C-6xHzRx.d.ts → core-BcimKMIv.d.ts} +1 -2
  6. package/dist/domain/command-queues.d.ts +3 -4
  7. package/dist/domain/command-queues.js.map +1 -1
  8. package/dist/domain/context-projection.d.ts +1 -1
  9. package/dist/domain/context-projection.js +1 -1
  10. package/dist/domain/context-projection.js.map +1 -1
  11. package/dist/domain/message-transcript.d.ts +1 -1
  12. package/dist/domain/message-transcript.js +1 -1
  13. package/dist/domain/message-transcript.js.map +1 -1
  14. package/dist/domain/model-usage.d.ts +1 -1
  15. package/dist/domain/reduced-state-schema.d.ts +2 -2
  16. package/dist/domain/reduced-state-schema.js +2 -2
  17. package/dist/domain/reduced-state-schema.js.map +1 -1
  18. package/dist/domain/reduced-state.d.ts +2 -2
  19. package/dist/domain/reduced-state.js +1 -1
  20. package/dist/domain/run-scheduling.d.ts +1 -1
  21. package/dist/domain/run-scheduling.js.map +1 -1
  22. package/dist/{durable-DRY7AcsF.js → durable-CD__3ztN.js} +67 -4
  23. package/dist/durable-CD__3ztN.js.map +1 -0
  24. package/dist/{durable-DeQBR5wA.d.ts → durable-CKdCCqhw.d.ts} +1548 -1496
  25. package/dist/envelope-BCzKUq_z.js.map +1 -1
  26. package/dist/{envelope-VXFEC8zr.d.ts → envelope-Che6KatU.d.ts} +29 -30
  27. package/dist/{event-factory-CKuWhjS4.js → event-factory-VAci3NJb.js} +2 -2
  28. package/dist/{event-factory-CKuWhjS4.js.map → event-factory-VAci3NJb.js.map} +1 -1
  29. package/dist/{events-D3OAPXgS.d.ts → events-BWuvzVml.d.ts} +124 -122
  30. package/dist/{id-generator--x6itQZ2.d.ts → id-generator-BKGoKjt-.d.ts} +2 -3
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +1 -1
  33. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  34. package/dist/{model-resolver-ci5D5WQv.d.ts → model-resolver-BfM5YA6A.d.ts} +5 -5
  35. package/dist/{model-usage-CNcnhj72.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
  36. package/dist/{reduced-state-xY-tYuGo.d.ts → reduced-state-4FSWDdgT.d.ts} +8215 -8010
  37. package/dist/{reduced-state-DFIYylAq.js → reduced-state-Vuud6LCM.js} +2 -2
  38. package/dist/reduced-state-Vuud6LCM.js.map +1 -0
  39. package/dist/{reduced-state-schema-CgW0mzpS.d.ts → reduced-state-schema-jyZWJ0QS.d.ts} +170 -152
  40. package/dist/{reducer-registry-bRbc4COf.d.ts → reducer-registry-BIhncOHH.d.ts} +8 -7
  41. package/dist/{run-scheduling-wakeup-CY5hfgMR.d.ts → run-scheduling-wakeup-BH2pHE0U.d.ts} +2 -3
  42. package/dist/services/compaction.d.ts +1 -1
  43. package/dist/services/compaction.js +1 -1
  44. package/dist/services/id-generator.d.ts +1 -1
  45. package/dist/services/id-generator.js +2 -1
  46. package/dist/services/id-generator.js.map +1 -1
  47. package/dist/services/keep-alive.d.ts +1 -1
  48. package/dist/services/keep-alive.js.map +1 -1
  49. package/dist/services/model-resolver.d.ts +1 -1
  50. package/dist/services/model-resolver.js +1 -1
  51. package/dist/services/model-resolver.js.map +1 -1
  52. package/dist/services/prompt-projector.d.ts +1 -1
  53. package/dist/services/prompt-projector.js +1 -1
  54. package/dist/services/prompt-projector.js.map +1 -1
  55. package/dist/services/reducer-registry.d.ts +1 -1
  56. package/dist/services/reducer-registry.js.map +1 -1
  57. package/dist/services/run-scheduler.d.ts +1 -1
  58. package/dist/services/run-scheduler.js +1 -1
  59. package/dist/services/run-scheduler.js.map +1 -1
  60. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  61. package/dist/services/run-scheduling-wakeup.js.map +1 -1
  62. package/dist/services/runtime-layer.d.ts +14 -31
  63. package/dist/services/runtime-layer.js +6 -6
  64. package/dist/services/runtime-layer.js.map +1 -1
  65. package/dist/services/runtime.d.ts +1 -1
  66. package/dist/services/runtime.js +2 -2
  67. package/dist/services/runtime.js.map +1 -1
  68. package/dist/services/session-event-observer.d.ts +1 -1
  69. package/dist/services/session-event-observer.js.map +1 -1
  70. package/dist/services/session-query.d.ts +1 -1
  71. package/dist/services/session-query.js +6 -8
  72. package/dist/services/session-query.js.map +1 -1
  73. package/dist/services/session-state.d.ts +1 -1
  74. package/dist/services/session-state.js +1 -1
  75. package/dist/services/session-store.d.ts +1 -1
  76. package/dist/services/session-store.js +10 -8
  77. package/dist/services/session-store.js.map +1 -1
  78. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  79. package/dist/services/sink-checkpoint-store.js +2 -1
  80. package/dist/services/sink-checkpoint-store.js.map +1 -1
  81. package/dist/services/sink-registry.d.ts +1 -1
  82. package/dist/services/sink-registry.js +1 -1
  83. package/dist/services/tool-registry.d.ts +1 -1
  84. package/dist/services/tool-registry.js +2 -2
  85. package/dist/services/tool-registry.js.map +1 -1
  86. package/dist/services/tracing.d.ts +3 -3
  87. package/dist/services/tracing.js +1 -1
  88. package/dist/services/tracing.js.map +1 -1
  89. package/dist/{session-event-observer-BWppl2Fr.d.ts → session-event-observer-BdZltdrK.d.ts} +3 -3
  90. package/dist/{session-state-8PJZvuR3.js → session-state-BAzdzqV4.js} +92 -59
  91. package/dist/session-state-BAzdzqV4.js.map +1 -0
  92. package/dist/{session-store-CERvTeaV.d.ts → session-store-BpitF4Wg.d.ts} +9 -9
  93. package/dist/{sink-checkpoint-store-DTiswoqy.d.ts → sink-checkpoint-store-C-SY0cG2.d.ts} +3 -4
  94. package/dist/{sink-registry-B4yxTmlI.js → sink-registry-BnWfMABI.js} +5 -5
  95. package/dist/sink-registry-BnWfMABI.js.map +1 -0
  96. package/dist/testkit/layers.d.ts +15 -15
  97. package/dist/testkit/layers.js +9 -6
  98. package/dist/testkit/layers.js.map +1 -1
  99. package/dist/{tool-registry-D4ALie3K.d.ts → tool-registry-wPsHagF_.d.ts} +7 -7
  100. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  101. package/dist/types/commands.d.ts +1 -1
  102. package/dist/types/commands.js +1 -1
  103. package/dist/types/commands.js.map +1 -1
  104. package/dist/types/core.d.ts +1 -1
  105. package/dist/types/core.js.map +1 -1
  106. package/dist/types/events/durable.d.ts +1 -1
  107. package/dist/types/events/durable.js +1 -1
  108. package/dist/types/events.d.ts +4 -4
  109. package/dist/types/events.js +1 -1
  110. package/dist/types/tracing.d.ts +1 -1
  111. package/dist/types/tracing.js.map +1 -1
  112. package/dist/websocket.d.ts +204 -187
  113. package/dist/websocket.js +5 -4
  114. package/dist/websocket.js.map +1 -1
  115. package/package.json +12 -12
  116. package/dist/compaction-Db6eoLce.js.map +0 -1
  117. package/dist/durable-DRY7AcsF.js.map +0 -1
  118. package/dist/reduced-state-DFIYylAq.js.map +0 -1
  119. package/dist/session-state-8PJZvuR3.js.map +0 -1
  120. package/dist/sink-registry-B4yxTmlI.js.map +0 -1
@@ -6,29 +6,29 @@ 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-DRY7AcsF.js";
10
- import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-DFIYylAq.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";
10
+ import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-Vuud6LCM.js";
11
11
  import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
12
12
  import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
13
- import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-Db6eoLce.js";
13
+ import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-GD1cTPTZ.js";
14
14
  import { IdGenerator } from "./services/id-generator.js";
15
- import { n as SessionContext, t as EventFactory } from "./event-factory-CKuWhjS4.js";
15
+ import { n as SessionContext, t as EventFactory } from "./event-factory-VAci3NJb.js";
16
16
  import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
17
17
  import { EDAKeepAlive } from "./services/keep-alive.js";
18
18
  import { SessionEventObserver } from "./services/session-event-observer.js";
19
19
  import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
20
20
  import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
21
- import { n as EDASinkRegistry } from "./sink-registry-B4yxTmlI.js";
21
+ import { n as EDASinkRegistry } from "./sink-registry-BnWfMABI.js";
22
22
  import { EDAToolRegistry } from "./services/tool-registry.js";
23
23
  import * as Context from "effect/Context";
24
24
  import * as Effect from "effect/Effect";
25
25
  import * as Layer from "effect/Layer";
26
26
  import * as Schema from "effect/Schema";
27
27
  import * as Stream from "effect/Stream";
28
- import * as Prompt from "effect/unstable/ai/Prompt";
28
+ import * as Prompt from "effect/ai/Prompt";
29
+ import * as Exit from "effect/Exit";
29
30
  import * as Cause from "effect/Cause";
30
31
  import * as Clock from "effect/Clock";
31
- import * as Exit from "effect/Exit";
32
32
  import * as Fiber from "effect/Fiber";
33
33
  import * as Queue from "effect/Queue";
34
34
  import * as Ref from "effect/Ref";
@@ -36,7 +36,7 @@ import * as Scope from "effect/Scope";
36
36
  import * as Semaphore from "effect/Semaphore";
37
37
  import * as Option from "effect/Option";
38
38
  import * as PubSub from "effect/PubSub";
39
- import * as Response from "effect/unstable/ai/Response";
39
+ import * as Response from "effect/ai/Response";
40
40
  //#region src/domain/dispatch-policy.ts
41
41
  /** Durable/runtime evidence for active work blocking new queued commands. */
42
42
  const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
@@ -233,7 +233,7 @@ const planSessionRecovery = (state) => {
233
233
  const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
234
234
  const sourceMessageIds = continuationCommand?.command?._tag === "ResumePendingMessages" ? continuationCommand.command.messageIds.filter((messageId) => pendingMessageIds.has(messageId)) : continuationCommand === void 0 ? [] : [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].filter((message) => message.commandId === continuationCommand.commandId).map((message) => message.messageId);
235
235
  const eligibleSteerIds = continuationRun === void 0 ? [] : state.commandQueues.pendingSteers.filter((message) => message.targetRunId === void 0 || message.targetRunId === continuationRun.runId || continuationRun.commandIds.some((commandId) => state.runs.get(message.targetRunId)?.commandIds.includes(commandId) === true)).map((message) => message.messageId);
236
- const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
236
+ const continuationInputMessageIds = Array.from(/* @__PURE__ */ new Set([...sourceMessageIds, ...eligibleSteerIds]));
237
237
  const continuationInputIds = new Set(continuationInputMessageIds);
238
238
  const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !(state.runSchedulingRequest?.work._tag === "Recovery" && state.runSchedulingRequest.work.inputMessageIds.includes(message.messageId)) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
239
239
  return {
@@ -267,10 +267,13 @@ const activeTurnEphemeralReplayCapacity = 4096;
267
267
  /** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
268
268
  var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
269
269
  static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
270
- return makeLiveBus(yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown), yield* Ref.make({
270
+ const pubsub = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
271
+ const activeTurnReplay = yield* Ref.make({
271
272
  events: [],
272
273
  overflowed: false
273
- }), yield* SessionEventObserver);
274
+ });
275
+ const observer = yield* SessionEventObserver;
276
+ return makeLiveBus(pubsub, activeTurnReplay, observer);
274
277
  }));
275
278
  /** Live bus for hosts that do not install an append-driven observer. */
276
279
  static Noop = LiveEventBus.Live.pipe(Layer.provide(SessionEventObserver.Noop));
@@ -370,7 +373,7 @@ Schema.Union([
370
373
  ToolExecutionSkipped
371
374
  ]);
372
375
  /** Failure when tool execution receives a committed event that is not ToolCallCreated. */
373
- var ToolExecutionEventNotCreated = class extends Schema.TaggedErrorClass()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
376
+ var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
374
377
  /** Construct the live tool-executor implementation. */
375
378
  const makeLiveToolExecutor = Effect.gen(function* () {
376
379
  const events = yield* EventFactory;
@@ -473,6 +476,7 @@ const toolCompletedPromptPart = (created, result) => ({
473
476
  id: created.event.payload.promptPart.id,
474
477
  name: created.event.payload.promptPart.name,
475
478
  isFailure: false,
479
+ providerExecuted: false,
476
480
  result
477
481
  }),
478
482
  id: created.event.payload.promptPart.id,
@@ -484,6 +488,7 @@ const toolFailedPromptPart = (created, error) => ({
484
488
  id: created.event.payload.promptPart.id,
485
489
  name: created.event.payload.promptPart.name,
486
490
  isFailure: true,
491
+ providerExecuted: false,
487
492
  result: error
488
493
  }),
489
494
  id: created.event.payload.promptPart.id,
@@ -665,7 +670,8 @@ const recordToolParamsEnd = (state, input) => {
665
670
  };
666
671
  const recordToolCall = (state, input) => {
667
672
  const draft = state.drafts.get(input.providerPartId);
668
- const decision = makeToolCallDecision(state, input, draft?.toolCallId ?? input.toolCallId);
673
+ const toolCallId = draft?.toolCallId ?? input.toolCallId;
674
+ const decision = makeToolCallDecision(state, input, toolCallId);
669
675
  const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
670
676
  const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
671
677
  return {
@@ -782,6 +788,7 @@ const toolRejectedPromptPart = (decision) => ({
782
788
  id: decision.providerPartId,
783
789
  name: decision.toolName,
784
790
  isFailure: true,
791
+ providerExecuted: false,
785
792
  result: {
786
793
  message: decision.error.message,
787
794
  reason: decision.reason,
@@ -819,7 +826,7 @@ const InferenceRunResult = Schema.Struct({
819
826
  partsRecorded: NonNegativeInt,
820
827
  terminal: InferenceRunTerminal
821
828
  });
822
- Schema.TaggedErrorClass()("UnsupportedInferencePart", {
829
+ Schema.TaggedError()("UnsupportedInferencePart", {
823
830
  partType: Schema.String,
824
831
  reason: Schema.String
825
832
  });
@@ -1039,7 +1046,8 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
1039
1046
  type: "error",
1040
1047
  error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
1041
1048
  });
1042
- return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
1049
+ const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []);
1050
+ return yield* requireTerminal(terminal);
1043
1051
  });
1044
1052
  return { runInference: Effect.fn("agent.inference")(function* (input) {
1045
1053
  const languageModel = yield* models.resolve(input.modelSelection);
@@ -1451,6 +1459,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
1451
1459
  id: created.event.payload.promptPart.id,
1452
1460
  name: created.event.payload.promptPart.name,
1453
1461
  isFailure: true,
1462
+ providerExecuted: false,
1454
1463
  result
1455
1464
  }),
1456
1465
  id: created.event.payload.promptPart.id,
@@ -1511,7 +1520,7 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
1511
1520
  });
1512
1521
  /** Control result when command execution was started in an active child scope. */
1513
1522
  const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
1514
- var SessionCommandAdmissionConflict = class extends Schema.TaggedErrorClass()("SessionCommandAdmissionConflict", {
1523
+ var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
1515
1524
  code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
1516
1525
  message: Schema.String,
1517
1526
  pausedMessageIds: Schema.Array(MessageId)
@@ -1530,6 +1539,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
1530
1539
  id: decision.providerPartId,
1531
1540
  name: decision.toolName,
1532
1541
  isFailure: true,
1542
+ providerExecuted: false,
1533
1543
  result: error
1534
1544
  }),
1535
1545
  id: decision.providerPartId,
@@ -1704,10 +1714,11 @@ const makeLiveSessionState = Effect.gen(function* () {
1704
1714
  const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
1705
1715
  if (systemPrompt === void 0) return;
1706
1716
  if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
1707
- yield* appendDurable(yield* events.systemMessageCommitted({
1717
+ const event = yield* events.systemMessageCommitted({
1708
1718
  messageId: yield* ids.makeMessageId(),
1709
1719
  content: systemPrompt
1710
- }));
1720
+ });
1721
+ yield* appendDurable(event);
1711
1722
  });
1712
1723
  const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
1713
1724
  const current = yield* Ref.get(state);
@@ -1818,7 +1829,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1818
1829
  const committed = yield* withAppendGate(Effect.gen(function* () {
1819
1830
  const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
1820
1831
  const preparedByCommandId = /* @__PURE__ */ new Map();
1821
- return yield* commitDurableEntriesWithinGate((yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat().map((event) => ({ event })));
1832
+ const durableEvents = (yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat();
1833
+ return yield* commitDurableEntriesWithinGate(durableEvents.map((event) => ({ event })));
1822
1834
  }));
1823
1835
  yield* annotateEdaSpan(committedBatchAttributes(committed));
1824
1836
  if (commandCount > 0) yield* wakeAfterCommandAdmission();
@@ -1882,25 +1894,29 @@ const makeLiveSessionState = Effect.gen(function* () {
1882
1894
  return next;
1883
1895
  });
1884
1896
  const cancelCommand = (commandId, reason) => Effect.gen(function* () {
1885
- const committed = yield* appendDurable(yield* events.commandCancelled({
1897
+ const event = yield* events.commandCancelled({
1886
1898
  commandId,
1887
1899
  reason
1888
- }));
1900
+ });
1901
+ const committed = yield* appendDurable(event);
1889
1902
  return SessionCommandCancelled.make({ committed });
1890
1903
  });
1891
1904
  const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
1892
1905
  if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
1893
- return yield* appendDurable(yield* events.turnFailed({
1906
+ const event = yield* events.turnFailed({
1894
1907
  runId: active.runId,
1895
1908
  turnId: active.turnId,
1896
1909
  error: interruptionFailure("turn", reason, {
1897
1910
  runId: active.runId,
1898
1911
  turnId: active.turnId
1899
1912
  })
1900
- }));
1913
+ });
1914
+ return yield* appendDurable(event);
1901
1915
  });
1902
1916
  const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
1903
- const committed = yield* appendDurableBatch([yield* events.runCompleted({ runId }), yield* events.commandCompleted({ commandId })]);
1917
+ const runCompleted = yield* events.runCompleted({ runId });
1918
+ const commandCompleted = yield* events.commandCompleted({ commandId });
1919
+ const committed = yield* appendDurableBatch([runCompleted, commandCompleted]);
1904
1920
  return SessionCommandCompleted.make({ committed: committed.at(-1) });
1905
1921
  });
1906
1922
  const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
@@ -1912,7 +1928,8 @@ const makeLiveSessionState = Effect.gen(function* () {
1912
1928
  commandId,
1913
1929
  error
1914
1930
  });
1915
- const failurePlan = planRunFailure(yield* currentReduced());
1931
+ const current = yield* currentReduced();
1932
+ const failurePlan = planRunFailure(current);
1916
1933
  const resumeEvents = [];
1917
1934
  if (failurePlan.messageIdsToResume.length > 0) {
1918
1935
  const resumeCommandId = yield* ids.makeCommandId();
@@ -1930,23 +1947,27 @@ const makeLiveSessionState = Effect.gen(function* () {
1930
1947
  });
1931
1948
  const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
1932
1949
  if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
1933
- return yield* failRunAndCommandWithError(commandId, runId, (yield* requireTurnFailed(turn.outcome.committed)).event.payload.error);
1950
+ const failed = yield* requireTurnFailed(turn.outcome.committed);
1951
+ return yield* failRunAndCommandWithError(commandId, runId, failed.event.payload.error);
1934
1952
  });
1935
1953
  const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
1936
1954
  const failurePlan = planRunFailure(yield* currentReduced());
1955
+ const runFailed = yield* events.runFailed({
1956
+ runId: active.runId,
1957
+ error: interruptionFailure("run", reason, { runId: active.runId })
1958
+ });
1959
+ const commandCancelled = yield* events.commandCancelled({
1960
+ commandId: active.commandId,
1961
+ reason
1962
+ });
1963
+ const resume = failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
1964
+ commandId: yield* ids.makeCommandId(),
1965
+ messageIds: failurePlan.messageIdsToResume
1966
+ }) })];
1937
1967
  const committed = yield* appendDurableBatch([
1938
- yield* events.runFailed({
1939
- runId: active.runId,
1940
- error: interruptionFailure("run", reason, { runId: active.runId })
1941
- }),
1942
- yield* events.commandCancelled({
1943
- commandId: active.commandId,
1944
- reason
1945
- }),
1946
- ...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
1947
- commandId: yield* ids.makeCommandId(),
1948
- messageIds: failurePlan.messageIdsToResume
1949
- }) })]
1968
+ runFailed,
1969
+ commandCancelled,
1970
+ ...resume
1950
1971
  ]);
1951
1972
  return SessionCommandCancelled.make({ committed: committed.at(-1) });
1952
1973
  });
@@ -2154,13 +2175,14 @@ const makeLiveSessionState = Effect.gen(function* () {
2154
2175
  modelSelection: input.modelSelection,
2155
2176
  trace: activeRunTrace.runTrace
2156
2177
  });
2178
+ const startedEvents = yield* appendDurableBatch([
2179
+ commandStarted,
2180
+ ...userMessage === void 0 ? [] : [userMessage],
2181
+ runStarted
2182
+ ]);
2157
2183
  return yield* startTurn({
2158
2184
  commandId,
2159
- commandStarted: (yield* appendDurableBatch([
2160
- commandStarted,
2161
- ...userMessage === void 0 ? [] : [userMessage],
2162
- runStarted
2163
- ]))[0],
2185
+ commandStarted: startedEvents[0],
2164
2186
  inputMessageIds: [messageId],
2165
2187
  runId,
2166
2188
  modelSelection: input.modelSelection,
@@ -2194,12 +2216,13 @@ const makeLiveSessionState = Effect.gen(function* () {
2194
2216
  runId
2195
2217
  });
2196
2218
  return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
2197
- const started = yield* appendDurableBatch([commandStarted, yield* events.runStarted({
2219
+ const runStarted = yield* events.runStarted({
2198
2220
  runId,
2199
2221
  commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
2200
2222
  modelSelection: input.modelSelection,
2201
2223
  trace: activeRunTrace.runTrace
2202
- })]);
2224
+ });
2225
+ const started = yield* appendDurableBatch([commandStarted, runStarted]);
2203
2226
  return yield* startTurn({
2204
2227
  commandId: command.commandId,
2205
2228
  commandStarted: started[0],
@@ -2577,7 +2600,8 @@ const makeLiveSessionState = Effect.gen(function* () {
2577
2600
  return (yield* startedBoundaryGuard({
2578
2601
  start: events.commandStarted({ commandId }),
2579
2602
  body: (started) => Effect.gen(function* () {
2580
- const committed = yield* appendDurableBatch([yield* events.commandCompleted({ commandId })]);
2603
+ const completed = yield* events.commandCompleted({ commandId });
2604
+ const committed = yield* appendDurableBatch([completed]);
2581
2605
  return {
2582
2606
  started,
2583
2607
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2594,13 +2618,14 @@ const makeLiveSessionState = Effect.gen(function* () {
2594
2618
  })).value;
2595
2619
  });
2596
2620
  const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
2597
- const committed = yield* appendDurable(yield* events.commandFailed({
2621
+ const failed = yield* events.commandFailed({
2598
2622
  commandId,
2599
2623
  error: FailurePayload.make({
2600
2624
  code,
2601
2625
  message
2602
2626
  })
2603
- }));
2627
+ });
2628
+ const committed = yield* appendDurable(failed);
2604
2629
  return SessionCommandFailed.make({ committed });
2605
2630
  });
2606
2631
  const cancelPendingMessage = Effect.fn(function* (command) {
@@ -2720,25 +2745,30 @@ const makeLiveSessionState = Effect.gen(function* () {
2720
2745
  return (yield* startedBoundaryGuard({
2721
2746
  start: events.commandStarted({ commandId: stopCommandId }),
2722
2747
  body: (started) => Effect.uninterruptible(Effect.gen(function* () {
2723
- const requested = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
2724
- yield* appendDurable(yield* events.stopTurnRequested({
2748
+ const beforeStop = yield* currentReduced();
2749
+ const requested = activeTurnIdentityForCommand(beforeStop, active.commandId);
2750
+ const requestedEvent = yield* events.stopTurnRequested({
2725
2751
  commandId: stopCommandId,
2726
2752
  ...requested === void 0 ? {} : {
2727
2753
  runId: requested.runId,
2728
2754
  turnId: requested.turnId
2729
2755
  }
2730
- }));
2756
+ });
2757
+ yield* appendDurable(requestedEvent);
2731
2758
  yield* Scope.close(active.turnScope, Exit.interrupt());
2732
2759
  yield* Ref.set(executionState, { _tag: "Idle" });
2733
2760
  yield* appendUserInterruption(active, stopCommandId, "interrupted");
2734
2761
  yield* Scope.close(active.runScope, Exit.interrupt());
2735
- const applied = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
2736
- const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
2762
+ const afterStop = yield* currentReduced();
2763
+ const applied = activeTurnIdentityForCommand(afterStop, active.commandId);
2764
+ const appliedEvent = yield* events.stopTurnApplied({
2737
2765
  commandId: stopCommandId,
2738
2766
  runId: active.runId,
2739
2767
  turnId: active.turnId,
2740
2768
  ...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
2741
- }), yield* events.commandCompleted({ commandId: stopCommandId })]);
2769
+ });
2770
+ const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
2771
+ const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
2742
2772
  return {
2743
2773
  started,
2744
2774
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -2765,19 +2795,22 @@ const makeLiveSessionState = Effect.gen(function* () {
2765
2795
  return (yield* startedBoundaryGuard({
2766
2796
  start: events.commandStarted({ commandId: stopCommandId }),
2767
2797
  body: (started) => Effect.uninterruptible(Effect.gen(function* () {
2768
- yield* appendDurable(yield* events.stopTurnRequested({
2798
+ const requestedEvent = yield* events.stopTurnRequested({
2769
2799
  commandId: stopCommandId,
2770
2800
  runId: active.runId,
2771
2801
  turnId: active.turnId
2772
- }));
2802
+ });
2803
+ yield* appendDurable(requestedEvent);
2773
2804
  yield* Ref.set(executionState, { _tag: "Idle" });
2774
2805
  yield* appendUserInterruption(active, stopCommandId, "interrupted");
2775
2806
  yield* Scope.close(active.runScope, Exit.interrupt());
2776
- const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
2807
+ const appliedEvent = yield* events.stopTurnApplied({
2777
2808
  commandId: stopCommandId,
2778
2809
  runId: active.runId,
2779
2810
  turnId: active.turnId
2780
- }), yield* events.commandCompleted({ commandId: stopCommandId })]);
2811
+ });
2812
+ const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
2813
+ const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
2781
2814
  return {
2782
2815
  started,
2783
2816
  outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
@@ -3167,4 +3200,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
3167
3200
  //#endregion
3168
3201
  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 };
3169
3202
 
3170
- //# sourceMappingURL=session-state-8PJZvuR3.js.map
3203
+ //# sourceMappingURL=session-state-BAzdzqV4.js.map