effect-durable-agent 0.1.0-alpha.3 → 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.
- package/README.md +43 -41
- package/dist/assert-never-CoyUpoRB.js +18 -0
- package/dist/assert-never-CoyUpoRB.js.map +1 -0
- package/dist/{commands-Ce1ec6kH.d.ts → commands-3OD-p8dD.d.ts} +16 -9
- package/dist/compaction-63iEDHHl.js +523 -0
- package/dist/compaction-63iEDHHl.js.map +1 -0
- package/dist/context-projection-D_uRtK3r.d.ts +139 -0
- package/dist/{core-Hv3cFydL.d.ts → core-BcimKMIv.d.ts} +6 -4
- package/dist/delivery-2ZILvoRD.js +507 -0
- package/dist/delivery-2ZILvoRD.js.map +1 -0
- package/dist/{websocket-wire-D3tLrhe2.d.ts → delivery-RjM1_NAE.d.ts} +1019 -200
- package/dist/domain/command-queues.d.ts +81 -2
- package/dist/domain/command-queues.js +1 -1
- package/dist/domain/command-queues.js.map +1 -1
- package/dist/domain/context-projection.d.ts +2 -0
- package/dist/domain/context-projection.js +32 -0
- package/dist/domain/context-projection.js.map +1 -0
- package/dist/domain/message-transcript.d.ts +36 -2
- package/dist/domain/message-transcript.js +10 -2
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/model-usage.d.ts +2 -0
- package/dist/domain/model-usage.js +59 -0
- package/dist/domain/model-usage.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +3 -996
- package/dist/domain/reduced-state-schema.js +121 -12
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +3 -2
- package/dist/domain/reduced-state.js +937 -2
- package/dist/domain/reduced-state.js.map +1 -0
- package/dist/domain/run-scheduling.d.ts +2 -0
- package/dist/domain/run-scheduling.js +127 -0
- package/dist/domain/run-scheduling.js.map +1 -0
- package/dist/{durable-DlScwmCy.d.ts → durable-Cqv5ZRFA.d.ts} +8505 -2497
- package/dist/{durable-C3Rz7kg3.js → durable-D13w1Qr3.js} +253 -91
- package/dist/durable-D13w1Qr3.js.map +1 -0
- package/dist/envelope-BCzKUq_z.js +91 -0
- package/dist/envelope-BCzKUq_z.js.map +1 -0
- package/dist/envelope-Che6KatU.d.ts +254 -0
- package/dist/{keep-alive-p8dIcSVy.js → event-factory-_vF1bIJ7.js} +8 -10
- package/dist/event-factory-_vF1bIJ7.js.map +1 -0
- package/dist/{events-Bb9-Cu-7.d.ts → events-Dg0o5wWs.d.ts} +140 -324
- package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
- package/dist/in-memory-CeODnZhE.js +150 -0
- package/dist/in-memory-CeODnZhE.js.map +1 -0
- package/dist/index.d.ts +8 -7
- package/dist/index.js +6 -5
- package/dist/interpreter-DKGJ1sSx.js +1452 -0
- package/dist/interpreter-DKGJ1sSx.js.map +1 -0
- package/dist/keep-alive-_zFCUvt3.d.ts +28 -0
- package/dist/model-resolver-D0vcDZsU.d.ts +24 -0
- package/dist/model-usage-0GeHwaaU.d.ts +54 -0
- package/dist/records--54mZEBx.js +675 -0
- package/dist/records--54mZEBx.js.map +1 -0
- package/dist/reduced-state-DU2ECOUp.d.ts +47821 -0
- package/dist/reduced-state-schema-B2t3cobf.d.ts +2187 -0
- package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-JLU1yptN.d.ts} +24 -8
- package/dist/run-scheduling-wakeup-D_bGdicf.d.ts +24 -0
- package/dist/services/compaction.d.ts +2 -2
- package/dist/services/compaction.js +2 -426
- package/dist/services/id-generator.d.ts +1 -1
- package/dist/services/id-generator.js +4 -2
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/keep-alive.d.ts +2 -0
- package/dist/services/keep-alive.js +13 -0
- package/dist/services/keep-alive.js.map +1 -0
- package/dist/services/model-call.d.ts +15 -0
- package/dist/services/model-call.js +15 -0
- package/dist/services/model-call.js.map +1 -0
- package/dist/services/model-resolver.d.ts +2 -0
- package/dist/services/model-resolver.js +17 -0
- package/dist/services/model-resolver.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +2 -2
- package/dist/services/prompt-projector.js +49 -5
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +2 -2
- package/dist/services/reducer-registry.js +21 -4
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/run-scheduler.d.ts +2 -0
- package/dist/services/run-scheduler.js +25 -0
- package/dist/services/run-scheduler.js.map +1 -0
- package/dist/services/run-scheduling-wakeup.d.ts +2 -0
- package/dist/services/run-scheduling-wakeup.js +13 -0
- package/dist/services/run-scheduling-wakeup.js.map +1 -0
- package/dist/services/runtime-layer.d.ts +48 -0
- package/dist/services/runtime-layer.js +51 -0
- package/dist/services/runtime-layer.js.map +1 -0
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +34 -20
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +2 -0
- package/dist/services/session-event-observer.js +13 -0
- package/dist/services/session-event-observer.js.map +1 -0
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +141 -2
- package/dist/services/session-query.js.map +1 -0
- package/dist/services/session-state.d.ts +2 -0
- package/dist/services/session-state.js +2 -0
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +272 -2
- package/dist/services/session-store.js.map +1 -0
- package/dist/services/sink-checkpoint-store.d.ts +2 -0
- package/dist/services/sink-checkpoint-store.js +50 -0
- package/dist/services/sink-checkpoint-store.js.map +1 -0
- package/dist/services/sink-registry.d.ts +2 -2
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/span-names.d.ts +1 -1
- package/dist/services/span-names.js +7 -1
- package/dist/services/span-names.js.map +1 -1
- package/dist/services/tool-registry.d.ts +2 -2
- package/dist/services/tool-registry.js +12 -3
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +3 -3
- package/dist/services/tracing.js +25 -4
- package/dist/services/tracing.js.map +1 -1
- package/dist/session-event-observer-HvrRckbC.d.ts +24 -0
- package/dist/{session-query-Cbf-e0rG.js → session-state-BQYsuBqi.js} +693 -251
- package/dist/session-state-BQYsuBqi.js.map +1 -0
- package/dist/session-store-CQxg9U82.d.ts +3302 -0
- package/dist/sink-checkpoint-store-DWGifxp0.d.ts +39 -0
- package/dist/sink-registry-DskRcyOS.js +345 -0
- package/dist/sink-registry-DskRcyOS.js.map +1 -0
- package/dist/subscription-DmO3BcdT.js +505 -0
- package/dist/subscription-DmO3BcdT.js.map +1 -0
- package/dist/subscription-rC35dAWn.d.ts +958 -0
- package/dist/testkit/layers.d.ts +34 -19
- package/dist/testkit/layers.js +30 -16
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.d.ts +226 -0
- package/dist/testkit/transcript.js +1475 -0
- package/dist/testkit/transcript.js.map +1 -0
- package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BzlMhwzj.d.ts} +44 -8
- package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
- package/dist/transcript.d.ts +101 -0
- package/dist/transcript.js +107 -0
- package/dist/transcript.js.map +1 -0
- package/dist/types/commands.d.ts +2 -2
- package/dist/types/commands.js +8 -3
- package/dist/types/commands.js.map +1 -1
- package/dist/types/core.d.ts +2 -2
- package/dist/types/core.js +4 -2
- package/dist/types/core.js.map +1 -1
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +5 -4
- package/dist/types/events.js +3 -2
- package/dist/types/events.js.map +1 -1
- package/dist/types/tracing.d.ts +1 -1
- package/dist/types/tracing.js.map +1 -1
- package/dist/websocket/events.d.ts +2 -0
- package/dist/websocket/events.js +2 -0
- package/dist/websocket.d.ts +2201 -0
- package/dist/websocket.js +684 -0
- package/dist/websocket.js.map +1 -0
- package/dist/window-read-CBZEJ84M.d.ts +113 -0
- package/dist/window-read-DPFAA1hM.js +264 -0
- package/dist/window-read-DPFAA1hM.js.map +1 -0
- package/package.json +87 -46
- package/testing/offline-trace/README.md +2 -1
- package/CHANGELOG.md +0 -25
- package/CONTRIBUTING.md +0 -26
- package/SECURITY.md +0 -7
- package/dist/command-queues-CQ9cwRP7.d.ts +0 -468
- package/dist/compaction-1LSZR944.d.ts +0 -144
- package/dist/durable-C3Rz7kg3.js.map +0 -1
- package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
- package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
- package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
- package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
- package/dist/host/durable-object-runtime.d.ts +0 -2
- package/dist/host/durable-object-runtime.js +0 -2
- package/dist/host/durable-object-storage.d.ts +0 -2
- package/dist/host/durable-object-storage.js +0 -0
- package/dist/host/durable-object.d.ts +0 -83
- package/dist/host/durable-object.js +0 -191
- package/dist/host/durable-object.js.map +0 -1
- package/dist/host/websocket-wire.d.ts +0 -2
- package/dist/host/websocket-wire.js +0 -105
- package/dist/host/websocket-wire.js.map +0 -1
- package/dist/index-BVVgDSdq.d.ts +0 -1
- package/dist/keep-alive-DYDsH6qN.d.ts +0 -111
- package/dist/keep-alive-p8dIcSVy.js.map +0 -1
- package/dist/message-transcript-BCHdHAe2.d.ts +0 -32
- package/dist/prompt-projector-DimXJPOJ.d.ts +0 -39
- package/dist/reduced-state-C4nVVzz9.js +0 -910
- package/dist/reduced-state-C4nVVzz9.js.map +0 -1
- package/dist/runtime-DcdPOEuE.d.ts +0 -60
- package/dist/services/compaction.js.map +0 -1
- package/dist/session-query-Cbf-e0rG.js.map +0 -1
- package/dist/session-query-hxfujxUH.d.ts +0 -769
- package/dist/session-store-D2Ore1QC.d.ts +0 -295
- package/dist/session-store-pYxQW9qh.js +0 -214
- package/dist/session-store-pYxQW9qh.js.map +0 -1
- package/dist/sink-registry-BziFpxoE.d.ts +0 -158
- package/dist/sink-registry-CFC6xjsN.js +0 -312
- package/dist/sink-registry-CFC6xjsN.js.map +0 -1
- package/docs/assets/architecture.svg +0 -216
- package/docs/assets/event-sequence.svg +0 -133
- package/docs/assets/gcp-trace.png +0 -0
- package/docs/assets/hero.svg +0 -33
- package/docs/message-steering.md +0 -831
- package/docs/releasing.md +0 -96
- package/docs/spec.md +0 -777
- package/docs/subagents.md +0 -725
- package/docs/testing.md +0 -64
- package/docs/ui-projection.md +0 -742
- package/docs/websocket-protocol.md +0 -639
- package/examples/001-no-tools/README.md +0 -65
- package/examples/001-no-tools/worker.ts +0 -79
- package/examples/002-slack-bridge/README.md +0 -134
- package/examples/002-slack-bridge/events.ts +0 -115
- package/examples/002-slack-bridge/reducer.ts +0 -216
- package/examples/002-slack-bridge/scenario.test.ts +0 -223
- package/examples/002-slack-bridge/sinks.ts +0 -109
- package/examples/002-slack-bridge/worker.ts +0 -140
- package/examples/003-sandbox-lifecycle/README.md +0 -78
- package/examples/003-sandbox-lifecycle/events.ts +0 -203
- package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
- package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
- package/examples/_shared/event-id.ts +0 -12
- package/examples/_shared/http.ts +0 -27
- package/examples/_shared/openai.ts +0 -33
|
@@ -1,36 +1,43 @@
|
|
|
1
|
+
import { RunSchedulingWakeup } from "./services/run-scheduling-wakeup.js";
|
|
1
2
|
import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
|
|
2
|
-
import {
|
|
3
|
+
import { canGrantRun, planRunSchedulingCancellation, planWaitingRunInterruption, runSchedulingInputMessageIds, waitingRunControl } from "./domain/run-scheduling.js";
|
|
4
|
+
import { RunScheduler } from "./services/run-scheduler.js";
|
|
5
|
+
import { ModelResolver } from "./services/model-resolver.js";
|
|
3
6
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
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
|
+
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-D13w1Qr3.js";
|
|
10
|
+
import { n as assertNeverError, t as assertNever } from "./assert-never-CoyUpoRB.js";
|
|
11
|
+
import { activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, initialReducedState, reducedStateCheckpointEventSeqs } from "./domain/reduced-state.js";
|
|
12
|
+
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
13
|
+
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
|
|
14
|
+
import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-63iEDHHl.js";
|
|
15
|
+
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
16
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
|
|
17
|
+
import { EDAToolRegistry, toolRecoveryPolicy } from "./services/tool-registry.js";
|
|
8
18
|
import { IdGenerator } from "./services/id-generator.js";
|
|
9
|
-
import { n as EventFactory, r as SessionContext, t as EDAKeepAlive } from "./keep-alive-p8dIcSVy.js";
|
|
10
19
|
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
20
|
+
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
21
|
+
import { SessionEventObserver } from "./services/session-event-observer.js";
|
|
14
22
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
15
|
-
import {
|
|
23
|
+
import { n as EDASinkRegistry } from "./sink-registry-DskRcyOS.js";
|
|
16
24
|
import * as Context from "effect/Context";
|
|
17
25
|
import * as Effect from "effect/Effect";
|
|
18
26
|
import * as Layer from "effect/Layer";
|
|
19
27
|
import * as Schema from "effect/Schema";
|
|
20
28
|
import * as Stream from "effect/Stream";
|
|
21
|
-
import * as Prompt from "effect/
|
|
29
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
30
|
+
import * as Exit from "effect/Exit";
|
|
22
31
|
import * as Cause from "effect/Cause";
|
|
23
32
|
import * as Clock from "effect/Clock";
|
|
24
|
-
import * as Exit from "effect/Exit";
|
|
25
33
|
import * as Fiber from "effect/Fiber";
|
|
26
34
|
import * as Queue from "effect/Queue";
|
|
27
35
|
import * as Ref from "effect/Ref";
|
|
28
36
|
import * as Scope from "effect/Scope";
|
|
29
37
|
import * as Semaphore from "effect/Semaphore";
|
|
30
|
-
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
31
38
|
import * as Option from "effect/Option";
|
|
32
39
|
import * as PubSub from "effect/PubSub";
|
|
33
|
-
import * as Response from "effect/
|
|
40
|
+
import * as Response from "effect/ai/Response";
|
|
34
41
|
//#region src/domain/dispatch-policy.ts
|
|
35
42
|
/** Durable/runtime evidence for active work blocking new queued commands. */
|
|
36
43
|
const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
|
|
@@ -108,6 +115,15 @@ const decideDispatch = (state) => {
|
|
|
108
115
|
command: toCandidate(next)
|
|
109
116
|
};
|
|
110
117
|
};
|
|
118
|
+
/** Promotion must retain a live or pending execution owner when the original command is terminal. */
|
|
119
|
+
const promotionNeedsResumeCommand = (state, messageId) => {
|
|
120
|
+
if (state.commandQueues.active?.runId !== void 0) return false;
|
|
121
|
+
const target = state.messages.get(messageId);
|
|
122
|
+
if (target?._tag !== "User" && target?._tag !== "Steering") return false;
|
|
123
|
+
const waiting = state.runSchedulingRequest?.work;
|
|
124
|
+
if (waiting?._tag === "Recovery" && waiting.inputMessageIds.includes(messageId)) return false;
|
|
125
|
+
return !state.commandQueues.pendingCommands.some((pending) => pending.commandId === target.commandId || pending.command._tag === "ResumePendingMessages" && pending.command.messageIds.includes(messageId));
|
|
126
|
+
};
|
|
111
127
|
const nextIdleCommand = (state) => {
|
|
112
128
|
const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
|
|
113
129
|
for (const message of state.commandQueues.pendingSteers) {
|
|
@@ -218,9 +234,9 @@ const planSessionRecovery = (state) => {
|
|
|
218
234
|
const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
|
|
219
235
|
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);
|
|
220
236
|
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);
|
|
221
|
-
const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
237
|
+
const continuationInputMessageIds = Array.from(/* @__PURE__ */ new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
222
238
|
const continuationInputIds = new Set(continuationInputMessageIds);
|
|
223
|
-
const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
|
|
239
|
+
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);
|
|
224
240
|
return {
|
|
225
241
|
activeCommands: recoverable.activeCommands,
|
|
226
242
|
activeRuns: recoverable.activeRuns,
|
|
@@ -246,6 +262,60 @@ const planRunFailure = (state) => ({ messageIdsToResume: state.commandQueues.pen
|
|
|
246
262
|
/** Normal explicit Stop/Interrupt policy. This is not startup recovery. */
|
|
247
263
|
const planUserInterruption = (state) => ({ messageIdsToPause: [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) });
|
|
248
264
|
//#endregion
|
|
265
|
+
//#region src/services/live-event-bus.ts
|
|
266
|
+
/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
|
|
267
|
+
const activeTurnEphemeralReplayCapacity = 4096;
|
|
268
|
+
/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
|
|
269
|
+
var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
|
|
270
|
+
static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
|
|
271
|
+
const pubsub = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
|
|
272
|
+
const activeTurnReplay = yield* Ref.make({
|
|
273
|
+
events: [],
|
|
274
|
+
overflowed: false
|
|
275
|
+
});
|
|
276
|
+
const observer = yield* SessionEventObserver;
|
|
277
|
+
return makeLiveBus(pubsub, activeTurnReplay, observer);
|
|
278
|
+
}));
|
|
279
|
+
/** Live bus for hosts that do not install an append-driven observer. */
|
|
280
|
+
static Noop = LiveEventBus.Live.pipe(Layer.provide(SessionEventObserver.Noop));
|
|
281
|
+
};
|
|
282
|
+
const makeLiveBus = (pubsub, activeTurnReplay, observer) => ({
|
|
283
|
+
publish: (event) => Effect.gen(function* () {
|
|
284
|
+
yield* updateActiveTurnReplay(activeTurnReplay, event);
|
|
285
|
+
yield* observer.onEvent(event);
|
|
286
|
+
return yield* PubSub.publish(pubsub, event);
|
|
287
|
+
}),
|
|
288
|
+
subscribeQueue: () => PubSub.subscribe(pubsub),
|
|
289
|
+
subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
|
|
290
|
+
activeTurnReplay: () => Ref.get(activeTurnReplay)
|
|
291
|
+
});
|
|
292
|
+
const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
|
|
293
|
+
const nextActiveTurnReplay = (state, event) => {
|
|
294
|
+
if (Schema.is(TurnStartedEvent)(event.event)) return {
|
|
295
|
+
turnId: event.event.payload.turnId,
|
|
296
|
+
events: [],
|
|
297
|
+
overflowed: false
|
|
298
|
+
};
|
|
299
|
+
if (Schema.is(TurnCompletedEvent)(event.event) || Schema.is(TurnFailedEvent)(event.event) || Schema.is(TurnStoppedEvent)(event.event)) {
|
|
300
|
+
const turnId = event.event.payload.turnId;
|
|
301
|
+
return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
|
|
302
|
+
events: [],
|
|
303
|
+
overflowed: false
|
|
304
|
+
} : state;
|
|
305
|
+
}
|
|
306
|
+
if (event.event.durability !== "ephemeral" || state.turnId === void 0) return state;
|
|
307
|
+
const events = [...state.events, event];
|
|
308
|
+
if (events.length <= 4096) return {
|
|
309
|
+
...state,
|
|
310
|
+
events
|
|
311
|
+
};
|
|
312
|
+
return {
|
|
313
|
+
...state,
|
|
314
|
+
events: events.slice(events.length - activeTurnEphemeralReplayCapacity),
|
|
315
|
+
overflowed: true
|
|
316
|
+
};
|
|
317
|
+
};
|
|
318
|
+
//#endregion
|
|
249
319
|
//#region src/services/started-boundary-guard.ts
|
|
250
320
|
/** Build a guard bound to the session's durable append boundary. */
|
|
251
321
|
const makeStartedBoundaryGuard = (state) => (spec) => {
|
|
@@ -304,13 +374,14 @@ Schema.Union([
|
|
|
304
374
|
ToolExecutionSkipped
|
|
305
375
|
]);
|
|
306
376
|
/** Failure when tool execution receives a committed event that is not ToolCallCreated. */
|
|
307
|
-
var ToolExecutionEventNotCreated = class extends Schema.
|
|
377
|
+
var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
|
|
308
378
|
/** Construct the live tool-executor implementation. */
|
|
309
379
|
const makeLiveToolExecutor = Effect.gen(function* () {
|
|
310
380
|
const events = yield* EventFactory;
|
|
311
381
|
const ids = yield* IdGenerator;
|
|
312
382
|
const registry = yield* EDAToolRegistry;
|
|
313
383
|
const session = yield* SessionContext;
|
|
384
|
+
const store = yield* EDASessionStore;
|
|
314
385
|
const failToolCall = (input, created, error) => Effect.gen(function* () {
|
|
315
386
|
const event = yield* events.toolCallFailed({
|
|
316
387
|
toolCallId: created.event.payload.toolCallId,
|
|
@@ -325,7 +396,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
325
396
|
yield* annotateEdaSpan({
|
|
326
397
|
"eda.tool_call.id": created.event.payload.toolCallId,
|
|
327
398
|
"eda.tool.name": created.event.payload.promptPart.name,
|
|
328
|
-
"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 }
|
|
329
401
|
});
|
|
330
402
|
if (created.event.payload.promptPart.providerExecuted) {
|
|
331
403
|
const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
|
|
@@ -336,13 +408,20 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
336
408
|
};
|
|
337
409
|
}
|
|
338
410
|
const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
|
|
339
|
-
start: events.toolCallStarted({
|
|
411
|
+
start: events.toolCallStarted({
|
|
412
|
+
toolCallId: created.event.payload.toolCallId,
|
|
413
|
+
...input.resume === void 0 ? {} : { attempt: input.resume.attempt }
|
|
414
|
+
}),
|
|
340
415
|
body: () => Effect.gen(function* () {
|
|
341
416
|
const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
|
|
342
417
|
toolCallId: created.event.payload.toolCallId,
|
|
418
|
+
runId: created.event.payload.runId,
|
|
419
|
+
turnId: created.event.payload.turnId,
|
|
420
|
+
queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
|
|
343
421
|
sessionId: session.sessionId,
|
|
344
422
|
makeEventId: ids.makeEventId,
|
|
345
|
-
emitDurable: input.eventSink.appendDurable
|
|
423
|
+
emitDurable: input.eventSink.appendDurable,
|
|
424
|
+
...input.resume === void 0 ? {} : { recovery: input.resume }
|
|
346
425
|
}).pipe(Effect.map((result) => ({
|
|
347
426
|
_tag: "Succeeded",
|
|
348
427
|
result
|
|
@@ -403,6 +482,7 @@ const toolCompletedPromptPart = (created, result) => ({
|
|
|
403
482
|
id: created.event.payload.promptPart.id,
|
|
404
483
|
name: created.event.payload.promptPart.name,
|
|
405
484
|
isFailure: false,
|
|
485
|
+
providerExecuted: false,
|
|
406
486
|
result
|
|
407
487
|
}),
|
|
408
488
|
id: created.event.payload.promptPart.id,
|
|
@@ -414,6 +494,7 @@ const toolFailedPromptPart = (created, error) => ({
|
|
|
414
494
|
id: created.event.payload.promptPart.id,
|
|
415
495
|
name: created.event.payload.promptPart.name,
|
|
416
496
|
isFailure: true,
|
|
497
|
+
providerExecuted: false,
|
|
417
498
|
result: error
|
|
418
499
|
}),
|
|
419
500
|
id: created.event.payload.promptPart.id,
|
|
@@ -595,7 +676,8 @@ const recordToolParamsEnd = (state, input) => {
|
|
|
595
676
|
};
|
|
596
677
|
const recordToolCall = (state, input) => {
|
|
597
678
|
const draft = state.drafts.get(input.providerPartId);
|
|
598
|
-
const
|
|
679
|
+
const toolCallId = draft?.toolCallId ?? input.toolCallId;
|
|
680
|
+
const decision = makeToolCallDecision(state, input, toolCallId);
|
|
599
681
|
const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
|
|
600
682
|
const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
|
|
601
683
|
return {
|
|
@@ -712,6 +794,7 @@ const toolRejectedPromptPart = (decision) => ({
|
|
|
712
794
|
id: decision.providerPartId,
|
|
713
795
|
name: decision.toolName,
|
|
714
796
|
isFailure: true,
|
|
797
|
+
providerExecuted: false,
|
|
715
798
|
result: {
|
|
716
799
|
message: decision.error.message,
|
|
717
800
|
reason: decision.reason,
|
|
@@ -749,7 +832,7 @@ const InferenceRunResult = Schema.Struct({
|
|
|
749
832
|
partsRecorded: NonNegativeInt,
|
|
750
833
|
terminal: InferenceRunTerminal
|
|
751
834
|
});
|
|
752
|
-
Schema.
|
|
835
|
+
Schema.TaggedError()("UnsupportedInferencePart", {
|
|
753
836
|
partType: Schema.String,
|
|
754
837
|
reason: Schema.String
|
|
755
838
|
});
|
|
@@ -757,7 +840,7 @@ Schema.TaggedErrorClass()("UnsupportedInferencePart", {
|
|
|
757
840
|
const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
758
841
|
const ids = yield* IdGenerator;
|
|
759
842
|
const events = yield* EventFactory;
|
|
760
|
-
const
|
|
843
|
+
const models = yield* ModelResolver;
|
|
761
844
|
const toolRegistry = yield* EDAToolRegistry;
|
|
762
845
|
const recordPart = (eventSink, state, part, setLatestState) => Effect.gen(function* () {
|
|
763
846
|
if (state.inference.phase === "sealed") {
|
|
@@ -969,9 +1052,11 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
969
1052
|
type: "error",
|
|
970
1053
|
error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
|
|
971
1054
|
});
|
|
972
|
-
|
|
1055
|
+
const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []);
|
|
1056
|
+
return yield* requireTerminal(terminal);
|
|
973
1057
|
});
|
|
974
1058
|
return { runInference: Effect.fn("agent.inference")(function* (input) {
|
|
1059
|
+
const languageModel = yield* models.resolve(input.modelSelection);
|
|
975
1060
|
const inferenceIdentity = {
|
|
976
1061
|
runId: input.runId,
|
|
977
1062
|
turnId: input.turnId,
|
|
@@ -992,8 +1077,9 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
992
1077
|
});
|
|
993
1078
|
const body = (started) => Effect.gen(function* () {
|
|
994
1079
|
const toolkit = yield* toolRegistry.getModelToolkit();
|
|
1080
|
+
const prompt = models.preparePrompt?.(input.modelSelection, Prompt.make(input.prompt));
|
|
995
1081
|
const state = yield* languageModel.streamText({
|
|
996
|
-
prompt: input.prompt,
|
|
1082
|
+
prompt: prompt ?? input.prompt,
|
|
997
1083
|
disableToolCallResolution: true,
|
|
998
1084
|
...toolkit === void 0 ? {} : { toolkit }
|
|
999
1085
|
}).pipe(Stream.map((part) => part)).pipe(Stream.catchIf(isProviderStreamFailure, (error) => Stream.make(makeProviderErrorPart(error))), Stream.runFoldEffect(() => initialState, (current, part) => recordPart(input.eventSink, current, part, (next) => Ref.set(stateRef, next)).pipe(Effect.tap((next) => Ref.set(stateRef, next)))));
|
|
@@ -1040,7 +1126,8 @@ var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-d
|
|
|
1040
1126
|
};
|
|
1041
1127
|
const inferenceUsageAttributes = (terminal) => {
|
|
1042
1128
|
if (terminal._tag !== "InferenceRunFinished") return {};
|
|
1043
|
-
|
|
1129
|
+
const completed = terminal.committed.find((entry) => entry.event.type === "InferenceCompleted");
|
|
1130
|
+
return usageAttributes(completed?.event.type === "InferenceCompleted" ? completed.event.payload.usage : void 0);
|
|
1044
1131
|
};
|
|
1045
1132
|
const initialRunInferenceState = (identity) => ({
|
|
1046
1133
|
inference: initialInferenceState(identity),
|
|
@@ -1050,12 +1137,12 @@ const initialRunInferenceState = (identity) => ({
|
|
|
1050
1137
|
});
|
|
1051
1138
|
const recordResponseContext = (entries, part) => {
|
|
1052
1139
|
switch (part.type) {
|
|
1053
|
-
case "text-start":
|
|
1054
|
-
case "text-
|
|
1055
|
-
case "text-
|
|
1056
|
-
case "reasoning-start":
|
|
1057
|
-
case "reasoning-
|
|
1058
|
-
case "reasoning-
|
|
1140
|
+
case "text-start":
|
|
1141
|
+
case "text-end": return upsertTextualResponseEntry(entries, "Text", part.id, "", part.metadata);
|
|
1142
|
+
case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta, part.metadata);
|
|
1143
|
+
case "reasoning-start":
|
|
1144
|
+
case "reasoning-end": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "", part.metadata);
|
|
1145
|
+
case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta, part.metadata);
|
|
1059
1146
|
case "tool-call": return part.providerExecuted ? entries : [...entries, {
|
|
1060
1147
|
_tag: "ResponsePart",
|
|
1061
1148
|
part
|
|
@@ -1073,24 +1160,50 @@ const recordResponseContext = (entries, part) => {
|
|
|
1073
1160
|
default: throw assertNeverError(part, "response context part");
|
|
1074
1161
|
}
|
|
1075
1162
|
};
|
|
1076
|
-
|
|
1163
|
+
/**
|
|
1164
|
+
* Folds one textual stream part into its entry. Provider metadata from start, delta and end parts
|
|
1165
|
+
* is merged per provider so replay keeps signatures, item ids and encrypted reasoning.
|
|
1166
|
+
*/
|
|
1167
|
+
const upsertTextualResponseEntry = (entries, tag, providerPartId, delta, metadata) => {
|
|
1077
1168
|
const index = entries.findIndex((entry) => (entry._tag === "Text" || entry._tag === "Reasoning") && entry._tag === tag && entry.providerPartId === providerPartId);
|
|
1078
1169
|
if (index === -1) return [...entries, {
|
|
1079
1170
|
_tag: tag,
|
|
1080
1171
|
providerPartId,
|
|
1081
|
-
text: delta
|
|
1172
|
+
text: delta,
|
|
1173
|
+
metadata: metadata ?? {}
|
|
1082
1174
|
}];
|
|
1083
1175
|
const current = entries[index];
|
|
1084
1176
|
if (current._tag !== tag) return entries;
|
|
1085
1177
|
return entries.map((entry, entryIndex) => entryIndex === index ? {
|
|
1086
1178
|
...current,
|
|
1087
|
-
text: `${current.text}${delta}
|
|
1179
|
+
text: `${current.text}${delta}`,
|
|
1180
|
+
metadata: mergeProviderMetadata(current.metadata, metadata)
|
|
1088
1181
|
} : entry);
|
|
1089
1182
|
};
|
|
1183
|
+
const mergeProviderMetadata = (left, right) => {
|
|
1184
|
+
if (right === void 0) return left;
|
|
1185
|
+
const merged = { ...left };
|
|
1186
|
+
for (const [provider, value] of Object.entries(right)) {
|
|
1187
|
+
const previous = merged[provider];
|
|
1188
|
+
merged[provider] = isMetadataRecord(previous) && isMetadataRecord(value) ? {
|
|
1189
|
+
...previous,
|
|
1190
|
+
...value
|
|
1191
|
+
} : value;
|
|
1192
|
+
}
|
|
1193
|
+
return merged;
|
|
1194
|
+
};
|
|
1195
|
+
const isMetadataRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1196
|
+
const hasProviderMetadata = (metadata) => Object.keys(metadata).length > 0;
|
|
1090
1197
|
const responseContextToParts = (entries) => entries.flatMap((entry) => {
|
|
1091
1198
|
switch (entry._tag) {
|
|
1092
|
-
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1093
|
-
|
|
1199
|
+
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1200
|
+
text: entry.text,
|
|
1201
|
+
metadata: entry.metadata
|
|
1202
|
+
})];
|
|
1203
|
+
case "Reasoning": return entry.text.length === 0 && !hasProviderMetadata(entry.metadata) ? [] : [Response.makePart("reasoning", {
|
|
1204
|
+
text: entry.text,
|
|
1205
|
+
metadata: entry.metadata
|
|
1206
|
+
})];
|
|
1094
1207
|
case "ResponsePart": return [entry.part];
|
|
1095
1208
|
default: throw assertNeverError(entry, "response context entry");
|
|
1096
1209
|
}
|
|
@@ -1146,31 +1259,6 @@ const makeFinishMetadata = (part) => ({
|
|
|
1146
1259
|
response: part.response,
|
|
1147
1260
|
metadata: part.metadata
|
|
1148
1261
|
});
|
|
1149
|
-
const makeUsagePayload = (usage) => {
|
|
1150
|
-
const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
|
|
1151
|
-
const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
|
|
1152
|
-
const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
|
|
1153
|
-
const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
|
|
1154
|
-
uncachedInputTokens,
|
|
1155
|
-
cachedInputTokens,
|
|
1156
|
-
cacheWriteInputTokens
|
|
1157
|
-
]);
|
|
1158
|
-
const textTokens = nonNegativeInt(usage.outputTokens.text);
|
|
1159
|
-
const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
|
|
1160
|
-
const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
|
|
1161
|
-
return UsagePayload.make({
|
|
1162
|
-
...inputTokens === void 0 ? {} : { inputTokens },
|
|
1163
|
-
...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
|
|
1164
|
-
...outputTokens === void 0 ? {} : { outputTokens },
|
|
1165
|
-
...textTokens === void 0 ? {} : { textTokens },
|
|
1166
|
-
...reasoningTokens === void 0 ? {} : { reasoningTokens }
|
|
1167
|
-
});
|
|
1168
|
-
};
|
|
1169
|
-
const sumDefined = (values) => {
|
|
1170
|
-
const present = values.filter((value) => value !== void 0);
|
|
1171
|
-
return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
|
|
1172
|
-
};
|
|
1173
|
-
const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
|
|
1174
1262
|
Schema.Struct({
|
|
1175
1263
|
runId: RunId,
|
|
1176
1264
|
turnId: TurnId
|
|
@@ -1196,6 +1284,7 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1196
1284
|
const events = yield* EventFactory;
|
|
1197
1285
|
const inferenceRunner = yield* InferenceRunner;
|
|
1198
1286
|
const toolExecutor = yield* ToolExecutor;
|
|
1287
|
+
const toolRegistry = yield* EDAToolRegistry;
|
|
1199
1288
|
const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
|
|
1200
1289
|
const usage = inferenceCompleted.event.payload.usage;
|
|
1201
1290
|
const turnCompleted = yield* events.turnCompleted({
|
|
@@ -1314,55 +1403,66 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1314
1403
|
return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
|
|
1315
1404
|
});
|
|
1316
1405
|
});
|
|
1317
|
-
return {
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
const
|
|
1333
|
-
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1334
|
-
const inference = yield* inferenceRunner.runInference({
|
|
1335
|
-
...turnIdentity,
|
|
1336
|
-
inferenceId,
|
|
1337
|
-
prompt: input.prompt,
|
|
1338
|
-
eventSink: input.eventSink,
|
|
1339
|
-
modelSelection: input.modelSelection
|
|
1340
|
-
});
|
|
1341
|
-
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1342
|
-
return TurnRunResult.make({
|
|
1343
|
-
started: input.started,
|
|
1344
|
-
inference,
|
|
1345
|
-
outcome
|
|
1346
|
-
});
|
|
1347
|
-
}).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;
|
|
1348
1422
|
yield* annotateEdaSpan({
|
|
1349
|
-
"eda.
|
|
1350
|
-
"eda.
|
|
1351
|
-
"eda.provider
|
|
1352
|
-
|
|
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
|
|
1353
1428
|
});
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
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({
|
|
1358
1434
|
...turnIdentity,
|
|
1359
|
-
|
|
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
|
|
1360
1445
|
});
|
|
1361
|
-
|
|
1362
|
-
|
|
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
|
+
}));
|
|
1363
1463
|
}));
|
|
1364
|
-
})
|
|
1365
|
-
}
|
|
1464
|
+
})
|
|
1465
|
+
};
|
|
1366
1466
|
});
|
|
1367
1467
|
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
1368
1468
|
var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
|
|
@@ -1404,6 +1504,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
|
|
|
1404
1504
|
id: created.event.payload.promptPart.id,
|
|
1405
1505
|
name: created.event.payload.promptPart.name,
|
|
1406
1506
|
isFailure: true,
|
|
1507
|
+
providerExecuted: false,
|
|
1407
1508
|
result
|
|
1408
1509
|
}),
|
|
1409
1510
|
id: created.event.payload.promptPart.id,
|
|
@@ -1417,11 +1518,11 @@ const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
|
|
|
1417
1518
|
if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
|
|
1418
1519
|
return created;
|
|
1419
1520
|
});
|
|
1420
|
-
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
|
|
1421
|
-
const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
|
|
1422
|
-
const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
|
|
1423
|
-
const isToolCallCreated = (committed) => committed.event.
|
|
1424
|
-
const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
|
|
1521
|
+
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.type === "TurnCompleted" ? result.outcome.committed.event.payload.usage : void 0) : {};
|
|
1522
|
+
const isInferenceCompleted = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceCompletedEventType;
|
|
1523
|
+
const isInferenceFailed = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceFailedEventType;
|
|
1524
|
+
const isToolCallCreated = (committed) => committed.event.namespace === "effect-durable-agent" && Schema.is(ToolCallCreatedEvent)(committed.event);
|
|
1525
|
+
const isToolCallRejected = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === toolCallRejectedEventType;
|
|
1425
1526
|
const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
|
|
1426
1527
|
const requireInferenceCompleted = (committed) => {
|
|
1427
1528
|
const completed = committed.find(isInferenceCompleted);
|
|
@@ -1431,7 +1532,10 @@ const requireInferenceFailed = (committed) => {
|
|
|
1431
1532
|
const failed = committed.find(isInferenceFailed);
|
|
1432
1533
|
return failed === void 0 ? Effect.die(/* @__PURE__ */ new Error("InferenceRunFailed did not include InferenceFailed")) : Effect.succeed(failed);
|
|
1433
1534
|
};
|
|
1434
|
-
|
|
1535
|
+
//#endregion
|
|
1536
|
+
//#region src/services/session-state.ts
|
|
1537
|
+
/** Input for one session control pass or long-lived control process. */
|
|
1538
|
+
const SessionRunInput = Schema.Struct({
|
|
1435
1539
|
modelSelection: ModelSelectionPayload,
|
|
1436
1540
|
maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),
|
|
1437
1541
|
systemPrompt: Schema.optionalKey(SystemPromptText)
|
|
@@ -1442,13 +1546,18 @@ const SessionCommandCompleted = Schema.TaggedStruct("SessionCommandCompleted", {
|
|
|
1442
1546
|
const SessionCommandFailed = Schema.TaggedStruct("SessionCommandFailed", { committed: CommittedDurableEvent });
|
|
1443
1547
|
/** Command outcome when command work was cancelled by stop, interrupt, or recovery. */
|
|
1444
1548
|
const SessionCommandCancelled = Schema.TaggedStruct("SessionCommandCancelled", { committed: CommittedDurableEvent });
|
|
1445
|
-
|
|
1549
|
+
/** Terminal command-processing variants returned from one control action. */
|
|
1550
|
+
const SessionCommandOutcome = Schema.Union([
|
|
1446
1551
|
SessionCommandCompleted,
|
|
1447
1552
|
SessionCommandFailed,
|
|
1448
1553
|
SessionCommandCancelled
|
|
1449
1554
|
]);
|
|
1450
1555
|
/** Why a control drain stopped without starting more command work. */
|
|
1451
|
-
const SessionNoRunnableReason = Schema.Literals([
|
|
1556
|
+
const SessionNoRunnableReason = Schema.Literals([
|
|
1557
|
+
"active-command",
|
|
1558
|
+
"no-pending-command",
|
|
1559
|
+
"awaiting-run-authorization"
|
|
1560
|
+
]);
|
|
1452
1561
|
/** Session control result when no admitted command is runnable. */
|
|
1453
1562
|
const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
|
|
1454
1563
|
reason: SessionNoRunnableReason,
|
|
@@ -1456,7 +1565,7 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
|
|
|
1456
1565
|
});
|
|
1457
1566
|
/** Control result when command execution was started in an active child scope. */
|
|
1458
1567
|
const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
|
|
1459
|
-
var SessionCommandAdmissionConflict = class extends Schema.
|
|
1568
|
+
var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
|
|
1460
1569
|
code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
|
|
1461
1570
|
message: Schema.String,
|
|
1462
1571
|
pausedMessageIds: Schema.Array(MessageId)
|
|
@@ -1475,6 +1584,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
|
|
|
1475
1584
|
id: decision.providerPartId,
|
|
1476
1585
|
name: decision.toolName,
|
|
1477
1586
|
isFailure: true,
|
|
1587
|
+
providerExecuted: false,
|
|
1478
1588
|
result: error
|
|
1479
1589
|
}),
|
|
1480
1590
|
id: decision.providerPartId,
|
|
@@ -1512,10 +1622,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1512
1622
|
const compactionRunner = yield* CompactionRunner;
|
|
1513
1623
|
const promptProjector = yield* EDAPromptProjector;
|
|
1514
1624
|
const sessionContext = yield* SessionContext;
|
|
1625
|
+
const runScheduler = yield* RunScheduler;
|
|
1626
|
+
const schedulingWakeup = yield* RunSchedulingWakeup;
|
|
1515
1627
|
const reducerRegistry = yield* EDAReducerRegistry;
|
|
1516
1628
|
const sinkRegistry = yield* EDASinkRegistry;
|
|
1517
|
-
const hydrated = yield*
|
|
1518
|
-
|
|
1629
|
+
const { hydrated, hydratedReducerStates } = yield* Effect.gen(function* () {
|
|
1630
|
+
const hydrated = yield* hydrateFrameworkReducedState(store);
|
|
1631
|
+
const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
|
|
1632
|
+
yield* Effect.annotateCurrentSpan({
|
|
1633
|
+
"eda.seq.head": hydrated.state.lastSeq,
|
|
1634
|
+
"eda.checkpoint.framework_seq": hydrated.checkpointSeq,
|
|
1635
|
+
...hydratedReducerStates.checkpointSeq === void 0 ? {} : { "eda.checkpoint.app_min_seq": hydratedReducerStates.checkpointSeq }
|
|
1636
|
+
});
|
|
1637
|
+
return {
|
|
1638
|
+
hydrated,
|
|
1639
|
+
hydratedReducerStates
|
|
1640
|
+
};
|
|
1641
|
+
}).pipe(Effect.withSpan("agent.session.hydrate", { attributes: {
|
|
1642
|
+
sessionId: sessionContext.sessionId,
|
|
1643
|
+
"eda.session.id": sessionContext.sessionId,
|
|
1644
|
+
"eda.reducers.count": reducerRegistry.reducers.length
|
|
1645
|
+
} }));
|
|
1646
|
+
yield* schedulingWakeup.setPending(hydrated.state.runSchedulingRequest !== void 0 && hydrated.state.runSchedulingRequest.deliveredSeq === void 0);
|
|
1519
1647
|
const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
|
|
1520
1648
|
const state = yield* Ref.make({
|
|
1521
1649
|
reduced: hydrated.state,
|
|
@@ -1526,6 +1654,16 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1526
1654
|
}
|
|
1527
1655
|
});
|
|
1528
1656
|
const gate = yield* Semaphore.make(1);
|
|
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);
|
|
1666
|
+
const deliveryGate = yield* Semaphore.make(1);
|
|
1529
1667
|
const ingressSignals = yield* Queue.sliding(1);
|
|
1530
1668
|
const reducerCheckpointSnapshots = yield* Queue.sliding(1);
|
|
1531
1669
|
const executionState = yield* Ref.make({ _tag: "Idle" });
|
|
@@ -1553,7 +1691,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1553
1691
|
}));
|
|
1554
1692
|
const buildReducerCheckpointSnapshot = (snapshot) => [{
|
|
1555
1693
|
name: frameworkReducedStateReducerName,
|
|
1556
|
-
schemaVersion:
|
|
1694
|
+
schemaVersion: 7,
|
|
1557
1695
|
throughSeq: snapshot.reduced.lastSeq,
|
|
1558
1696
|
payload: encodeReducedStateCheckpoint(snapshot.reduced),
|
|
1559
1697
|
updatedAtMs: snapshot.updatedAtMs
|
|
@@ -1594,7 +1732,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1594
1732
|
reducerStates: nextReducerStates,
|
|
1595
1733
|
ephemeral: current.ephemeral
|
|
1596
1734
|
});
|
|
1597
|
-
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(
|
|
1735
|
+
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make({
|
|
1736
|
+
position: entry.position,
|
|
1737
|
+
event: durableEventEnvelope(entry.event)
|
|
1738
|
+
}));
|
|
1598
1739
|
return { head: nextReduced.lastSeq };
|
|
1599
1740
|
});
|
|
1600
1741
|
const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
@@ -1626,10 +1767,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1626
1767
|
const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
|
|
1627
1768
|
if (systemPrompt === void 0) return;
|
|
1628
1769
|
if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
|
|
1629
|
-
|
|
1770
|
+
const event = yield* events.systemMessageCommitted({
|
|
1630
1771
|
messageId: yield* ids.makeMessageId(),
|
|
1631
1772
|
content: systemPrompt
|
|
1632
|
-
})
|
|
1773
|
+
});
|
|
1774
|
+
yield* appendDurable(event);
|
|
1633
1775
|
});
|
|
1634
1776
|
const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
|
|
1635
1777
|
const current = yield* Ref.get(state);
|
|
@@ -1651,13 +1793,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1651
1793
|
}
|
|
1652
1794
|
});
|
|
1653
1795
|
yield* liveBus.publish(positioned);
|
|
1796
|
+
yield* sinkRegistry.publishEphemeralToSinks(positioned);
|
|
1654
1797
|
return positioned;
|
|
1655
1798
|
}));
|
|
1656
|
-
const publishEphemeral =
|
|
1657
|
-
const positioned = yield* publishEphemeralCore(event);
|
|
1658
|
-
yield* sinkRegistry.publishEphemeralToSinks(positioned, publishEphemeralCore);
|
|
1659
|
-
return positioned;
|
|
1660
|
-
});
|
|
1799
|
+
const publishEphemeral = publishEphemeralCore;
|
|
1661
1800
|
const wakeAfterCommandAdmission = () => Queue.offer(ingressSignals, void 0);
|
|
1662
1801
|
/** Use indexed store lookup for command idempotency instead of genesis replay. */
|
|
1663
1802
|
const findExistingCommandAdmission = (command) => Effect.gen(function* () {
|
|
@@ -1678,8 +1817,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1678
1817
|
}
|
|
1679
1818
|
const existing = yield* findExistingCommandAdmission(command);
|
|
1680
1819
|
if (existing !== void 0) {
|
|
1681
|
-
rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1682
|
-
return [existing.event];
|
|
1820
|
+
rememberPreparedCommand(durableEventEnvelope(existing.event), preparedByIdempotencyKey, preparedByCommandId);
|
|
1821
|
+
return [durableEventEnvelope(existing.event)];
|
|
1683
1822
|
}
|
|
1684
1823
|
const commandId = command.commandId ?? (yield* ids.makeCommandId());
|
|
1685
1824
|
const admitted = commandWithId(command, commandId);
|
|
@@ -1733,7 +1872,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1733
1872
|
submitted
|
|
1734
1873
|
];
|
|
1735
1874
|
});
|
|
1736
|
-
const submitBatch =
|
|
1875
|
+
const submitBatch = (input) => admissionGate.withPermits(1)(submitBatchAdmitted(input));
|
|
1876
|
+
const submitBatchAdmitted = Effect.fn(function* (input) {
|
|
1737
1877
|
const commandCount = input.filter(isEDACommand).length;
|
|
1738
1878
|
yield* annotateEdaSpan({
|
|
1739
1879
|
"eda.command.submittable_count": input.length,
|
|
@@ -1743,7 +1883,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1743
1883
|
const committed = yield* withAppendGate(Effect.gen(function* () {
|
|
1744
1884
|
const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1745
1885
|
const preparedByCommandId = /* @__PURE__ */ new Map();
|
|
1746
|
-
|
|
1886
|
+
const durableEvents = (yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat();
|
|
1887
|
+
return yield* commitDurableEntriesWithinGate(durableEvents.map((event) => ({ event })));
|
|
1747
1888
|
}));
|
|
1748
1889
|
yield* annotateEdaSpan(committedBatchAttributes(committed));
|
|
1749
1890
|
if (commandCount > 0) yield* wakeAfterCommandAdmission();
|
|
@@ -1754,6 +1895,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1754
1895
|
});
|
|
1755
1896
|
const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
|
|
1756
1897
|
const sessionApi = {
|
|
1898
|
+
grantRun: (command, input) => grantRun(command, input),
|
|
1899
|
+
retryRunSchedulingDelivery: () => retryRunSchedulingDelivery(),
|
|
1757
1900
|
initialize,
|
|
1758
1901
|
submitBatch,
|
|
1759
1902
|
admitCommand,
|
|
@@ -1795,9 +1938,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1795
1938
|
yield* requestCurrentReducerCheckpointSnapshot("startup-recovery-complete");
|
|
1796
1939
|
});
|
|
1797
1940
|
const maybeCompactAtBoundary = () => Effect.gen(function* () {
|
|
1798
|
-
const
|
|
1941
|
+
const data = yield* currentData();
|
|
1942
|
+
const current = data.reduced;
|
|
1799
1943
|
const next = (yield* compactionRunner.maybeCompact({
|
|
1800
1944
|
state: current,
|
|
1945
|
+
reducerStates: data.reducerStates,
|
|
1801
1946
|
context: yield* contextProjectionFor(current),
|
|
1802
1947
|
appendDurableEntries
|
|
1803
1948
|
})).length === 0 ? current : yield* currentReduced();
|
|
@@ -1805,25 +1950,29 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1805
1950
|
return next;
|
|
1806
1951
|
});
|
|
1807
1952
|
const cancelCommand = (commandId, reason) => Effect.gen(function* () {
|
|
1808
|
-
const
|
|
1953
|
+
const event = yield* events.commandCancelled({
|
|
1809
1954
|
commandId,
|
|
1810
1955
|
reason
|
|
1811
|
-
})
|
|
1956
|
+
});
|
|
1957
|
+
const committed = yield* appendDurable(event);
|
|
1812
1958
|
return SessionCommandCancelled.make({ committed });
|
|
1813
1959
|
});
|
|
1814
1960
|
const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
|
|
1815
1961
|
if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
|
|
1816
|
-
|
|
1962
|
+
const event = yield* events.turnFailed({
|
|
1817
1963
|
runId: active.runId,
|
|
1818
1964
|
turnId: active.turnId,
|
|
1819
1965
|
error: interruptionFailure("turn", reason, {
|
|
1820
1966
|
runId: active.runId,
|
|
1821
1967
|
turnId: active.turnId
|
|
1822
1968
|
})
|
|
1823
|
-
})
|
|
1969
|
+
});
|
|
1970
|
+
return yield* appendDurable(event);
|
|
1824
1971
|
});
|
|
1825
1972
|
const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
|
|
1826
|
-
const
|
|
1973
|
+
const runCompleted = yield* events.runCompleted({ runId });
|
|
1974
|
+
const commandCompleted = yield* events.commandCompleted({ commandId });
|
|
1975
|
+
const committed = yield* appendDurableBatch([runCompleted, commandCompleted]);
|
|
1827
1976
|
return SessionCommandCompleted.make({ committed: committed.at(-1) });
|
|
1828
1977
|
});
|
|
1829
1978
|
const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
|
|
@@ -1835,7 +1984,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1835
1984
|
commandId,
|
|
1836
1985
|
error
|
|
1837
1986
|
});
|
|
1838
|
-
const
|
|
1987
|
+
const current = yield* currentReduced();
|
|
1988
|
+
const failurePlan = planRunFailure(current);
|
|
1839
1989
|
const resumeEvents = [];
|
|
1840
1990
|
if (failurePlan.messageIdsToResume.length > 0) {
|
|
1841
1991
|
const resumeCommandId = yield* ids.makeCommandId();
|
|
@@ -1853,23 +2003,27 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1853
2003
|
});
|
|
1854
2004
|
const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
|
|
1855
2005
|
if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
|
|
1856
|
-
|
|
2006
|
+
const failed = yield* requireTurnFailed(turn.outcome.committed);
|
|
2007
|
+
return yield* failRunAndCommandWithError(commandId, runId, failed.event.payload.error);
|
|
1857
2008
|
});
|
|
1858
2009
|
const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
|
|
1859
2010
|
const failurePlan = planRunFailure(yield* currentReduced());
|
|
2011
|
+
const runFailed = yield* events.runFailed({
|
|
2012
|
+
runId: active.runId,
|
|
2013
|
+
error: interruptionFailure("run", reason, { runId: active.runId })
|
|
2014
|
+
});
|
|
2015
|
+
const commandCancelled = yield* events.commandCancelled({
|
|
2016
|
+
commandId: active.commandId,
|
|
2017
|
+
reason
|
|
2018
|
+
});
|
|
2019
|
+
const resume = failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2020
|
+
commandId: yield* ids.makeCommandId(),
|
|
2021
|
+
messageIds: failurePlan.messageIdsToResume
|
|
2022
|
+
}) })];
|
|
1860
2023
|
const committed = yield* appendDurableBatch([
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
}),
|
|
1865
|
-
yield* events.commandCancelled({
|
|
1866
|
-
commandId: active.commandId,
|
|
1867
|
-
reason
|
|
1868
|
-
}),
|
|
1869
|
-
...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
1870
|
-
commandId: yield* ids.makeCommandId(),
|
|
1871
|
-
messageIds: failurePlan.messageIdsToResume
|
|
1872
|
-
}) })]
|
|
2024
|
+
runFailed,
|
|
2025
|
+
commandCancelled,
|
|
2026
|
+
...resume
|
|
1873
2027
|
]);
|
|
1874
2028
|
return SessionCommandCancelled.make({ committed: committed.at(-1) });
|
|
1875
2029
|
});
|
|
@@ -1986,10 +2140,69 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1986
2140
|
});
|
|
1987
2141
|
return SessionForkedCommand.make({ commandId: input.commandId });
|
|
1988
2142
|
});
|
|
2143
|
+
const reconcileSchedulingWakeup = Effect.fnUntraced(function* () {
|
|
2144
|
+
const request = (yield* currentReduced()).runSchedulingRequest;
|
|
2145
|
+
yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
|
|
2146
|
+
});
|
|
2147
|
+
const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
|
|
2148
|
+
if (yield* Ref.get(recoveringInBackground)) return;
|
|
2149
|
+
yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
|
|
2150
|
+
const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2151
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2152
|
+
yield* reconcileSchedulingWakeup();
|
|
2153
|
+
return current?.deliveredSeq === void 0 ? current : void 0;
|
|
2154
|
+
}));
|
|
2155
|
+
if (request === void 0) return;
|
|
2156
|
+
const delivered = yield* Effect.exit(keepAlive.withActiveWork("run-scheduling-delivery", runScheduler.deliver({
|
|
2157
|
+
sessionId: sessionContext.sessionId,
|
|
2158
|
+
request: {
|
|
2159
|
+
requestId: request.requestId,
|
|
2160
|
+
work: request.work
|
|
2161
|
+
}
|
|
2162
|
+
}).pipe(Effect.timeout("10 seconds"))));
|
|
2163
|
+
if (Exit.isFailure(delivered)) {
|
|
2164
|
+
if (Cause.hasInterruptsOnly(delivered.cause)) return yield* Effect.interrupt;
|
|
2165
|
+
yield* controlGate.withPermits(1)(reconcileSchedulingWakeup());
|
|
2166
|
+
yield* Effect.logWarning("Run authorization delivery will retry on the durable host wakeup", {
|
|
2167
|
+
requestId: request.requestId,
|
|
2168
|
+
cause: Cause.pretty(delivered.cause)
|
|
2169
|
+
});
|
|
2170
|
+
return;
|
|
2171
|
+
}
|
|
2172
|
+
yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2173
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2174
|
+
if (current?.requestId === request.requestId && current.deliveredSeq === void 0) yield* appendDurable(yield* events.runSchedulingDelivered({ requestId: request.requestId }));
|
|
2175
|
+
yield* reconcileSchedulingWakeup();
|
|
2176
|
+
}));
|
|
2177
|
+
}));
|
|
2178
|
+
});
|
|
2179
|
+
const forkSchedulingDelivery = () => retryRunSchedulingDelivery().pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2180
|
+
yield* markFatalIfDurable(cause);
|
|
2181
|
+
yield* Effect.logError("Run authorization delivery worker failed", { cause: Cause.pretty(cause) });
|
|
2182
|
+
})), Effect.forkIn(runtimeScope), Effect.asVoid);
|
|
2183
|
+
const prepareRunSchedulingRequest = Effect.fnUntraced(function* (work) {
|
|
2184
|
+
yield* schedulingWakeup.setPending(true);
|
|
2185
|
+
return yield* events.runSchedulingRequested({
|
|
2186
|
+
requestId: yield* ids.makeRunRequestId(),
|
|
2187
|
+
work
|
|
2188
|
+
});
|
|
2189
|
+
});
|
|
2190
|
+
const deferRun = Effect.fnUntraced(function* (work) {
|
|
2191
|
+
yield* appendDurable(yield* prepareRunSchedulingRequest(work));
|
|
2192
|
+
yield* forkSchedulingDelivery();
|
|
2193
|
+
return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
2194
|
+
});
|
|
1989
2195
|
const startSubmitCommand = Effect.fn(function* (command, input) {
|
|
1990
2196
|
if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
|
|
1991
2197
|
const submit = command.command;
|
|
1992
2198
|
const commandId = command.commandId;
|
|
2199
|
+
if ((yield* runScheduler.resolve({
|
|
2200
|
+
sessionId: sessionContext.sessionId,
|
|
2201
|
+
commandId
|
|
2202
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2203
|
+
_tag: "Command",
|
|
2204
|
+
commandId
|
|
2205
|
+
});
|
|
1993
2206
|
yield* annotateEdaSpan({
|
|
1994
2207
|
"eda.command.id": commandId,
|
|
1995
2208
|
"eda.command.disposition": submit.disposition,
|
|
@@ -2019,13 +2232,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2019
2232
|
modelSelection: input.modelSelection,
|
|
2020
2233
|
trace: activeRunTrace.runTrace
|
|
2021
2234
|
});
|
|
2235
|
+
const startedEvents = yield* appendDurableBatch([
|
|
2236
|
+
commandStarted,
|
|
2237
|
+
...userMessage === void 0 ? [] : [userMessage],
|
|
2238
|
+
runStarted
|
|
2239
|
+
]);
|
|
2022
2240
|
return yield* startTurn({
|
|
2023
2241
|
commandId,
|
|
2024
|
-
commandStarted:
|
|
2025
|
-
commandStarted,
|
|
2026
|
-
...userMessage === void 0 ? [] : [userMessage],
|
|
2027
|
-
runStarted
|
|
2028
|
-
]))[0],
|
|
2242
|
+
commandStarted: startedEvents[0],
|
|
2029
2243
|
inputMessageIds: [messageId],
|
|
2030
2244
|
runId,
|
|
2031
2245
|
modelSelection: input.modelSelection,
|
|
@@ -2043,6 +2257,13 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2043
2257
|
return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
|
|
2044
2258
|
});
|
|
2045
2259
|
if (pending.length === 0) return yield* processInactiveStopCommand(command);
|
|
2260
|
+
if ((yield* runScheduler.resolve({
|
|
2261
|
+
sessionId: sessionContext.sessionId,
|
|
2262
|
+
commandId: command.commandId
|
|
2263
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2264
|
+
_tag: "Command",
|
|
2265
|
+
commandId: command.commandId
|
|
2266
|
+
});
|
|
2046
2267
|
const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
|
|
2047
2268
|
const runId = yield* ids.makeRunId();
|
|
2048
2269
|
const activeRunTrace = yield* startRunTrace({
|
|
@@ -2052,12 +2273,13 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2052
2273
|
runId
|
|
2053
2274
|
});
|
|
2054
2275
|
return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
|
|
2055
|
-
const
|
|
2276
|
+
const runStarted = yield* events.runStarted({
|
|
2056
2277
|
runId,
|
|
2057
2278
|
commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
|
|
2058
2279
|
modelSelection: input.modelSelection,
|
|
2059
2280
|
trace: activeRunTrace.runTrace
|
|
2060
|
-
})
|
|
2281
|
+
});
|
|
2282
|
+
const started = yield* appendDurableBatch([commandStarted, runStarted]);
|
|
2061
2283
|
return yield* startTurn({
|
|
2062
2284
|
commandId: command.commandId,
|
|
2063
2285
|
commandStarted: started[0],
|
|
@@ -2070,6 +2292,108 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2070
2292
|
});
|
|
2071
2293
|
}));
|
|
2072
2294
|
});
|
|
2295
|
+
const grantRun = Effect.fn("agent.run.grant")(function* (grant, input) {
|
|
2296
|
+
yield* annotateEdaSpan({
|
|
2297
|
+
"eda.session.id": sessionContext.sessionId,
|
|
2298
|
+
"eda.run_request.id": grant.requestId
|
|
2299
|
+
});
|
|
2300
|
+
return yield* controlGate.withPermits(1)(keepAlive.withActiveWork("run-authorization-grant", Effect.gen(function* () {
|
|
2301
|
+
yield* failIfFatal;
|
|
2302
|
+
const initial = yield* currentReduced();
|
|
2303
|
+
if (!canGrantRun(initial, grant.requestId)) return { _tag: "Stale" };
|
|
2304
|
+
const request = initial.runSchedulingRequest;
|
|
2305
|
+
if (request === void 0) return { _tag: "Stale" };
|
|
2306
|
+
const command = initial.commands.get(request.work.commandId);
|
|
2307
|
+
if (command?.command === void 0) return { _tag: "Stale" };
|
|
2308
|
+
const admitted = command.command;
|
|
2309
|
+
const predecessor = request.work._tag === "Recovery" ? initial.runs.get(request.work.interruptedRunId) : void 0;
|
|
2310
|
+
const modelSelection = predecessor?.modelSelection ?? initial.modelSelection ?? input.modelSelection;
|
|
2311
|
+
const runId = yield* ids.makeRunId();
|
|
2312
|
+
const trace = yield* startRunTrace({
|
|
2313
|
+
commandId: command.commandId,
|
|
2314
|
+
admissionTrace: command.admissionTrace,
|
|
2315
|
+
modelSelection,
|
|
2316
|
+
runId
|
|
2317
|
+
});
|
|
2318
|
+
return yield* closeRunTraceOnFailure(trace, Effect.gen(function* () {
|
|
2319
|
+
const started = yield* withAppendGate(Effect.gen(function* () {
|
|
2320
|
+
const current = yield* currentReduced();
|
|
2321
|
+
if (!canGrantRun(current, grant.requestId)) return void 0;
|
|
2322
|
+
const inputMessageIds = [...runSchedulingInputMessageIds(current, request.work)];
|
|
2323
|
+
const batch = [];
|
|
2324
|
+
let commandStarted;
|
|
2325
|
+
if (request.work._tag === "Recovery") {
|
|
2326
|
+
if (command.startedSeq === void 0 || predecessor === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization requires its started command and predecessor"));
|
|
2327
|
+
[commandStarted] = yield* store.loadCommittedEventsBySeq([command.startedSeq]);
|
|
2328
|
+
if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization is missing CommandStarted"));
|
|
2329
|
+
} else {
|
|
2330
|
+
batch.push(yield* events.commandStarted({ commandId: command.commandId }));
|
|
2331
|
+
if (admitted._tag === "SubmitMessage" && inputMessageIds.length === 0) {
|
|
2332
|
+
const messageId = yield* ids.makeMessageId();
|
|
2333
|
+
batch.push(yield* events.userMessageCommitted({
|
|
2334
|
+
commandId: command.commandId,
|
|
2335
|
+
messageId,
|
|
2336
|
+
content: admitted.content
|
|
2337
|
+
}));
|
|
2338
|
+
inputMessageIds.push(messageId);
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
batch.push(yield* events.runSchedulingGranted({
|
|
2342
|
+
requestId: request.requestId,
|
|
2343
|
+
runId
|
|
2344
|
+
}));
|
|
2345
|
+
const commandIds = predecessor?.commandIds ?? [command.commandId, ...admitted._tag === "ResumePendingMessages" ? inputMessageIds.flatMap((messageId) => {
|
|
2346
|
+
const message = current.messages.get(messageId);
|
|
2347
|
+
return message?._tag === "User" || message?._tag === "Steering" ? [message.commandId] : [];
|
|
2348
|
+
}) : []];
|
|
2349
|
+
batch.push(yield* events.runStarted({
|
|
2350
|
+
runId,
|
|
2351
|
+
commandIds,
|
|
2352
|
+
modelSelection,
|
|
2353
|
+
trace: trace.runTrace
|
|
2354
|
+
}));
|
|
2355
|
+
if (request.work._tag === "Recovery") batch.push(yield* events.recoveryCompleted({
|
|
2356
|
+
trigger: "runtime-restart",
|
|
2357
|
+
continuation: {
|
|
2358
|
+
commandId: command.commandId,
|
|
2359
|
+
interruptedRunId: request.work.interruptedRunId,
|
|
2360
|
+
replacementRunId: runId
|
|
2361
|
+
}
|
|
2362
|
+
}));
|
|
2363
|
+
const committed = yield* commitDurableEntriesWithinGate(batch.map((event) => ({ event })));
|
|
2364
|
+
commandStarted ??= committed[0];
|
|
2365
|
+
if (commandStarted === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Granted run must have CommandStarted"));
|
|
2366
|
+
return {
|
|
2367
|
+
commandStarted,
|
|
2368
|
+
inputMessageIds
|
|
2369
|
+
};
|
|
2370
|
+
}));
|
|
2371
|
+
if (started === void 0) {
|
|
2372
|
+
yield* Scope.close(trace.runScope, Exit.void);
|
|
2373
|
+
return { _tag: "Stale" };
|
|
2374
|
+
}
|
|
2375
|
+
yield* reconcileSchedulingWakeup();
|
|
2376
|
+
yield* startTurn({
|
|
2377
|
+
commandId: command.commandId,
|
|
2378
|
+
commandStarted: started.commandStarted,
|
|
2379
|
+
inputMessageIds: started.inputMessageIds,
|
|
2380
|
+
runId,
|
|
2381
|
+
modelSelection,
|
|
2382
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2383
|
+
runScope: trace.runScope,
|
|
2384
|
+
runSpan: trace.runSpan
|
|
2385
|
+
});
|
|
2386
|
+
yield* wakeAfterCommandAdmission();
|
|
2387
|
+
return {
|
|
2388
|
+
_tag: "Granted",
|
|
2389
|
+
runId
|
|
2390
|
+
};
|
|
2391
|
+
}));
|
|
2392
|
+
})).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2393
|
+
yield* markFatalIfDurable(cause);
|
|
2394
|
+
return yield* Effect.failCause(cause);
|
|
2395
|
+
}))));
|
|
2396
|
+
});
|
|
2073
2397
|
const processInactiveStopCommand = Effect.fn(function* (command) {
|
|
2074
2398
|
const commandId = command.commandId;
|
|
2075
2399
|
return (yield* startedBoundaryGuard({
|
|
@@ -2151,8 +2475,53 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2151
2475
|
turn: exit.value
|
|
2152
2476
|
};
|
|
2153
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
|
+
});
|
|
2154
2519
|
const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
|
|
2155
2520
|
const plan = planSessionRecovery(reduced);
|
|
2521
|
+
input = {
|
|
2522
|
+
...input,
|
|
2523
|
+
modelSelection: plan.continuation?.run.modelSelection ?? input.modelSelection
|
|
2524
|
+
};
|
|
2156
2525
|
yield* annotateEdaSpan({
|
|
2157
2526
|
"eda.recovery.reason": reason,
|
|
2158
2527
|
"eda.recovery.open_tool_calls": plan.openToolCalls.length,
|
|
@@ -2234,7 +2603,17 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2234
2603
|
commandId: yield* ids.makeCommandId(),
|
|
2235
2604
|
messageIds: plan.messageIdsToResume
|
|
2236
2605
|
}) }));
|
|
2237
|
-
const
|
|
2606
|
+
const resolution = plan.continuation === void 0 ? void 0 : yield* runScheduler.resolve({
|
|
2607
|
+
sessionId: sessionContext.sessionId,
|
|
2608
|
+
commandId: plan.continuation.command.commandId
|
|
2609
|
+
});
|
|
2610
|
+
if (plan.continuation !== void 0 && resolution?._tag === "Deferred") recoveryEvents.push(yield* prepareRunSchedulingRequest({
|
|
2611
|
+
_tag: "Recovery",
|
|
2612
|
+
commandId: plan.continuation.command.commandId,
|
|
2613
|
+
interruptedRunId: plan.continuation.run.runId,
|
|
2614
|
+
inputMessageIds: plan.continuation.inputMessageIds
|
|
2615
|
+
}));
|
|
2616
|
+
const continuationRunId = plan.continuation === void 0 || resolution?._tag === "Deferred" ? void 0 : yield* ids.makeRunId();
|
|
2238
2617
|
const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
|
|
2239
2618
|
admissionTrace: plan.continuation.command.admissionTrace,
|
|
2240
2619
|
commandId: plan.continuation.command.commandId,
|
|
@@ -2257,6 +2636,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2257
2636
|
} }
|
|
2258
2637
|
}));
|
|
2259
2638
|
const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
|
|
2639
|
+
if (resolution?._tag === "Deferred") yield* forkSchedulingDelivery();
|
|
2260
2640
|
const nextPlan = planSessionRecovery(yield* currentReduced());
|
|
2261
2641
|
if (!(plan.continuation === void 0 || continuationRunId === void 0 ? isSessionRecoveryPlanEmpty(nextPlan) : nextPlan.activeCommands.length === 1 && nextPlan.activeCommands[0]?.commandId === plan.continuation.command.commandId && nextPlan.activeRuns.length === 1 && nextPlan.activeRuns[0]?.runId === continuationRunId && nextPlan.activeTurns.length === 0 && nextPlan.activeInferences.length === 0 && nextPlan.openToolCalls.length === 0 && nextPlan.pendingStopRequests.length === 0 && nextPlan.openCompactions.length === 0 && nextPlan.messageIdsToPause.length === 0 && nextPlan.messageIdsToResume.length === 0 && nextPlan.continuation?.inputMessageIds.length === plan.continuation.inputMessageIds.length && nextPlan.continuation.inputMessageIds.every((messageId) => plan.continuation?.inputMessageIds.includes(messageId)))) return yield* Effect.die(/* @__PURE__ */ new Error("Startup recovery did not reach a fixed point before live execution"));
|
|
2262
2642
|
return {
|
|
@@ -2264,6 +2644,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2264
2644
|
continuation: plan.continuation === void 0 || continuationRunId === void 0 || continuationRunTrace === void 0 ? void 0 : {
|
|
2265
2645
|
command: plan.continuation.command,
|
|
2266
2646
|
runId: continuationRunId,
|
|
2647
|
+
modelSelection: input.modelSelection,
|
|
2267
2648
|
inputMessageIds: plan.continuation.inputMessageIds,
|
|
2268
2649
|
runScope: continuationRunTrace.runScope,
|
|
2269
2650
|
runSpan: continuationRunTrace.runSpan
|
|
@@ -2286,7 +2667,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2286
2667
|
commandStarted,
|
|
2287
2668
|
inputMessageIds: pendingInputs.map((message) => message.messageId),
|
|
2288
2669
|
runId: continuation.runId,
|
|
2289
|
-
modelSelection:
|
|
2670
|
+
modelSelection: continuation.modelSelection,
|
|
2290
2671
|
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2291
2672
|
runScope: continuation.runScope,
|
|
2292
2673
|
runSpan: continuation.runSpan
|
|
@@ -2317,7 +2698,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2317
2698
|
return (yield* startedBoundaryGuard({
|
|
2318
2699
|
start: events.commandStarted({ commandId }),
|
|
2319
2700
|
body: (started) => Effect.gen(function* () {
|
|
2320
|
-
const
|
|
2701
|
+
const completed = yield* events.commandCompleted({ commandId });
|
|
2702
|
+
const committed = yield* appendDurableBatch([completed]);
|
|
2321
2703
|
return {
|
|
2322
2704
|
started,
|
|
2323
2705
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2334,13 +2716,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2334
2716
|
})).value;
|
|
2335
2717
|
});
|
|
2336
2718
|
const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
|
|
2337
|
-
const
|
|
2719
|
+
const failed = yield* events.commandFailed({
|
|
2338
2720
|
commandId,
|
|
2339
2721
|
error: FailurePayload.make({
|
|
2340
2722
|
code,
|
|
2341
2723
|
message
|
|
2342
2724
|
})
|
|
2343
|
-
})
|
|
2725
|
+
});
|
|
2726
|
+
const committed = yield* appendDurable(failed);
|
|
2344
2727
|
return SessionCommandFailed.make({ committed });
|
|
2345
2728
|
});
|
|
2346
2729
|
const cancelPendingMessage = Effect.fn(function* (command) {
|
|
@@ -2366,12 +2749,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2366
2749
|
commandId: target.commandId,
|
|
2367
2750
|
reason: "pending message cancelled"
|
|
2368
2751
|
})] : [];
|
|
2752
|
+
const schedulingPlan = planRunSchedulingCancellation(current, target.messageId);
|
|
2753
|
+
const schedulingEvents = [];
|
|
2754
|
+
if (schedulingPlan !== void 0) {
|
|
2755
|
+
schedulingEvents.push(yield* events.runSchedulingInvalidated({
|
|
2756
|
+
requestId: schedulingPlan.requestId,
|
|
2757
|
+
reason: "message-cancelled"
|
|
2758
|
+
}));
|
|
2759
|
+
if (schedulingPlan.cancelCommandId !== void 0) schedulingEvents.push(yield* events.commandCancelled({
|
|
2760
|
+
commandId: schedulingPlan.cancelCommandId,
|
|
2761
|
+
reason: "pending recovery inputs cancelled"
|
|
2762
|
+
}));
|
|
2763
|
+
if (schedulingPlan.replacementWork !== void 0) schedulingEvents.push(yield* prepareRunSchedulingRequest(schedulingPlan.replacementWork));
|
|
2764
|
+
}
|
|
2369
2765
|
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2370
2766
|
const committed = yield* appendDurableBatch([
|
|
2371
2767
|
cancelled,
|
|
2372
2768
|
...originCancelled,
|
|
2769
|
+
...schedulingEvents,
|
|
2373
2770
|
completed
|
|
2374
2771
|
]);
|
|
2772
|
+
if (schedulingEvents.length > 0) {
|
|
2773
|
+
yield* reconcileSchedulingWakeup();
|
|
2774
|
+
yield* forkSchedulingDelivery();
|
|
2775
|
+
}
|
|
2375
2776
|
return {
|
|
2376
2777
|
started,
|
|
2377
2778
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2394,17 +2795,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2394
2795
|
return (yield* startedBoundaryGuard({
|
|
2395
2796
|
start: events.commandStarted({ commandId: controlCommandId }),
|
|
2396
2797
|
body: (started) => Effect.gen(function* () {
|
|
2397
|
-
const
|
|
2798
|
+
const current = yield* currentReduced();
|
|
2799
|
+
const target = current.messages.get(promotion.messageId);
|
|
2398
2800
|
if (target?._tag !== "User" && target?._tag !== "Steering" || (target._tag === "User" ? target.disposition !== "queue" : target.pausedByCommandId === void 0) || target.consumedSeq !== void 0 || target.cancelledSeq !== void 0) return {
|
|
2399
2801
|
started,
|
|
2400
2802
|
outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
|
|
2401
2803
|
};
|
|
2402
|
-
const
|
|
2804
|
+
const promoted = yield* events.userMessagePromoted({
|
|
2403
2805
|
commandId: controlCommandId,
|
|
2404
2806
|
messageId: target.messageId,
|
|
2405
2807
|
from: "queue",
|
|
2406
2808
|
to: "steer"
|
|
2407
|
-
})
|
|
2809
|
+
});
|
|
2810
|
+
const resumed = promotionNeedsResumeCommand(current, target.messageId) ? [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2811
|
+
commandId: yield* ids.makeCommandId(),
|
|
2812
|
+
messageIds: [target.messageId]
|
|
2813
|
+
}) })] : [];
|
|
2814
|
+
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2815
|
+
const committed = yield* appendDurableBatch([
|
|
2816
|
+
promoted,
|
|
2817
|
+
...resumed,
|
|
2818
|
+
completed
|
|
2819
|
+
]);
|
|
2408
2820
|
return {
|
|
2409
2821
|
started,
|
|
2410
2822
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2431,25 +2843,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2431
2843
|
return (yield* startedBoundaryGuard({
|
|
2432
2844
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2433
2845
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2434
|
-
const
|
|
2435
|
-
|
|
2846
|
+
const beforeStop = yield* currentReduced();
|
|
2847
|
+
const requested = activeTurnIdentityForCommand(beforeStop, active.commandId);
|
|
2848
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2436
2849
|
commandId: stopCommandId,
|
|
2437
2850
|
...requested === void 0 ? {} : {
|
|
2438
2851
|
runId: requested.runId,
|
|
2439
2852
|
turnId: requested.turnId
|
|
2440
2853
|
}
|
|
2441
|
-
})
|
|
2854
|
+
});
|
|
2855
|
+
yield* appendDurable(requestedEvent);
|
|
2442
2856
|
yield* Scope.close(active.turnScope, Exit.interrupt());
|
|
2443
2857
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2444
2858
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2445
2859
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2446
|
-
const
|
|
2447
|
-
const
|
|
2860
|
+
const afterStop = yield* currentReduced();
|
|
2861
|
+
const applied = activeTurnIdentityForCommand(afterStop, active.commandId);
|
|
2862
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2448
2863
|
commandId: stopCommandId,
|
|
2449
2864
|
runId: active.runId,
|
|
2450
2865
|
turnId: active.turnId,
|
|
2451
2866
|
...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
|
|
2452
|
-
})
|
|
2867
|
+
});
|
|
2868
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
2869
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2453
2870
|
return {
|
|
2454
2871
|
started,
|
|
2455
2872
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2476,19 +2893,22 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2476
2893
|
return (yield* startedBoundaryGuard({
|
|
2477
2894
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2478
2895
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2479
|
-
|
|
2896
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2480
2897
|
commandId: stopCommandId,
|
|
2481
2898
|
runId: active.runId,
|
|
2482
2899
|
turnId: active.turnId
|
|
2483
|
-
})
|
|
2900
|
+
});
|
|
2901
|
+
yield* appendDurable(requestedEvent);
|
|
2484
2902
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2485
2903
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2486
2904
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2487
|
-
const
|
|
2905
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2488
2906
|
commandId: stopCommandId,
|
|
2489
2907
|
runId: active.runId,
|
|
2490
2908
|
turnId: active.turnId
|
|
2491
|
-
})
|
|
2909
|
+
});
|
|
2910
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
2911
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2492
2912
|
return {
|
|
2493
2913
|
started,
|
|
2494
2914
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2570,9 +2990,39 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2570
2990
|
default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
|
|
2571
2991
|
}
|
|
2572
2992
|
});
|
|
2993
|
+
const interruptWaitingRun = Effect.fnUntraced(function* (control, reason) {
|
|
2994
|
+
const plan = planWaitingRunInterruption(yield* currentReduced(), control.commandId);
|
|
2995
|
+
if (plan === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Waiting interruption requires a current reservation"));
|
|
2996
|
+
const isStop = control.command._tag === "StopTurn";
|
|
2997
|
+
const batch = [];
|
|
2998
|
+
if (isStop) batch.push(yield* events.commandStarted({ commandId: control.commandId }));
|
|
2999
|
+
batch.push(yield* events.runSchedulingInvalidated({
|
|
3000
|
+
requestId: plan.requestId,
|
|
3001
|
+
reason
|
|
3002
|
+
}));
|
|
3003
|
+
const [firstMessageId, ...restMessageIds] = plan.messageIds;
|
|
3004
|
+
if (firstMessageId !== void 0) batch.push(yield* events.pendingMessagesPaused({
|
|
3005
|
+
interruptionCommandId: control.commandId,
|
|
3006
|
+
runRequestId: plan.requestId,
|
|
3007
|
+
messageIds: [firstMessageId, ...restMessageIds],
|
|
3008
|
+
reason: "user-interrupted"
|
|
3009
|
+
}));
|
|
3010
|
+
if (plan.cancelCommandId !== void 0) batch.push(yield* events.commandCancelled({
|
|
3011
|
+
commandId: plan.cancelCommandId,
|
|
3012
|
+
reason
|
|
3013
|
+
}));
|
|
3014
|
+
if (isStop) batch.push(yield* events.commandCompleted({ commandId: control.commandId }));
|
|
3015
|
+
const committed = yield* appendDurableBatch(batch);
|
|
3016
|
+
yield* reconcileSchedulingWakeup();
|
|
3017
|
+
return committed;
|
|
3018
|
+
});
|
|
2573
3019
|
const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
|
|
2574
3020
|
const execution = yield* inspectExecutionState();
|
|
2575
3021
|
const current = yield* currentReduced();
|
|
3022
|
+
input = {
|
|
3023
|
+
...input,
|
|
3024
|
+
modelSelection: current.modelSelection ?? input.modelSelection
|
|
3025
|
+
};
|
|
2576
3026
|
if (execution?._tag === "FailedTurn") return execution.result;
|
|
2577
3027
|
if (execution?._tag === "CompletedTurn") {
|
|
2578
3028
|
const decision = decideDispatch(current);
|
|
@@ -2625,6 +3075,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2625
3075
|
});
|
|
2626
3076
|
}
|
|
2627
3077
|
}
|
|
3078
|
+
if (current.runSchedulingRequest !== void 0) {
|
|
3079
|
+
const control = waitingRunControl(current);
|
|
3080
|
+
if (control === void 0) return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3081
|
+
switch (control.command._tag) {
|
|
3082
|
+
case "CancelPendingMessage": return yield* cancelPendingMessage(control);
|
|
3083
|
+
case "PromotePendingMessage": return yield* promotePendingMessage(control);
|
|
3084
|
+
case "StopTurn": {
|
|
3085
|
+
const committed = yield* interruptWaitingRun(control, "stopped");
|
|
3086
|
+
const started = committed[0];
|
|
3087
|
+
const completed = committed.at(-1);
|
|
3088
|
+
if (started === void 0 || completed === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Stopping a waiting request must commit its control lifecycle"));
|
|
3089
|
+
return {
|
|
3090
|
+
started,
|
|
3091
|
+
outcome: SessionCommandCompleted.make({ committed: completed })
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
case "SubmitMessage":
|
|
3095
|
+
yield* interruptWaitingRun(control, "interrupted");
|
|
3096
|
+
return yield* startSubmitCommand(control, input);
|
|
3097
|
+
default: return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3098
|
+
}
|
|
3099
|
+
}
|
|
2628
3100
|
const decision = decideDispatch(current);
|
|
2629
3101
|
switch (decision._tag) {
|
|
2630
3102
|
case "DispatchBlockedByActiveCommand":
|
|
@@ -2654,7 +3126,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2654
3126
|
yield* failIfFatal;
|
|
2655
3127
|
const processed = [];
|
|
2656
3128
|
while (true) {
|
|
2657
|
-
const result = yield* withFatalRecording(drainOneReadyCommand(input));
|
|
3129
|
+
const result = yield* controlGate.withPermits(1)(withFatalRecording(drainOneReadyCommand(input)));
|
|
2658
3130
|
if (isSessionNoRunnableCommand(result)) {
|
|
2659
3131
|
yield* annotateEdaSpan({
|
|
2660
3132
|
"eda.command.processed_count": processed.length,
|
|
@@ -2676,7 +3148,20 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2676
3148
|
"eda.model.id": input.modelSelection.modelId
|
|
2677
3149
|
});
|
|
2678
3150
|
yield* failIfFatal;
|
|
2679
|
-
const recovery = yield*
|
|
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
|
+
}));
|
|
3161
|
+
input = {
|
|
3162
|
+
...input,
|
|
3163
|
+
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
3164
|
+
};
|
|
2680
3165
|
yield* requestStartupRecoveryCheckpointIfNeeded();
|
|
2681
3166
|
if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
|
|
2682
3167
|
});
|
|
@@ -2713,12 +3198,32 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2713
3198
|
}
|
|
2714
3199
|
});
|
|
2715
3200
|
const start = Effect.fn(function* (input) {
|
|
2716
|
-
yield*
|
|
2717
|
-
|
|
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));
|
|
2718
3223
|
});
|
|
2719
3224
|
yield* sinkRegistry.startSinkRunners({
|
|
2720
3225
|
appendDurableBatch,
|
|
2721
|
-
|
|
3226
|
+
initialProjection: yield* Ref.get(state),
|
|
2722
3227
|
publishEphemeral: publishEphemeralCore,
|
|
2723
3228
|
scope: runtimeScope
|
|
2724
3229
|
});
|
|
@@ -2735,10 +3240,10 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
|
|
|
2735
3240
|
});
|
|
2736
3241
|
const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
|
|
2737
3242
|
const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
|
|
2738
|
-
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
2739
|
-
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
3243
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
|
|
3244
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2740
3245
|
return {
|
|
2741
|
-
state:
|
|
3246
|
+
state: yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, foldReducedState)),
|
|
2742
3247
|
checkpointSeq
|
|
2743
3248
|
};
|
|
2744
3249
|
});
|
|
@@ -2748,10 +3253,10 @@ const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
|
|
|
2748
3253
|
const schemaVersion = reducerSchemaVersion(reducer);
|
|
2749
3254
|
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? reducer.initial : decodeReducerState(reducer, checkpoint.payload);
|
|
2750
3255
|
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2751
|
-
const
|
|
3256
|
+
const state = yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, (current, page) => page.reduce(reducer.reduce, current)));
|
|
2752
3257
|
return [
|
|
2753
3258
|
reducer.name,
|
|
2754
|
-
|
|
3259
|
+
state,
|
|
2755
3260
|
checkpointSeq
|
|
2756
3261
|
];
|
|
2757
3262
|
}));
|
|
@@ -2795,7 +3300,7 @@ const commandWithId = (command, commandId) => {
|
|
|
2795
3300
|
}
|
|
2796
3301
|
};
|
|
2797
3302
|
const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
|
|
2798
|
-
if (
|
|
3303
|
+
if (!Schema.is(CommandAdmittedEvent)(event)) return;
|
|
2799
3304
|
const command = event.payload.command;
|
|
2800
3305
|
if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
|
|
2801
3306
|
if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
|
|
@@ -2818,69 +3323,6 @@ const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succee
|
|
|
2818
3323
|
const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
|
|
2819
3324
|
const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
|
|
2820
3325
|
//#endregion
|
|
2821
|
-
|
|
2822
|
-
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
2823
|
-
var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
|
|
2824
|
-
static Live = Layer.effect(EDASessionQuery, Effect.gen(function* () {
|
|
2825
|
-
const store = yield* EDASessionStore;
|
|
2826
|
-
const liveBus = yield* LiveEventBus;
|
|
2827
|
-
const sessionState = yield* SessionState;
|
|
2828
|
-
const snapshot = Effect.gen(function* () {
|
|
2829
|
-
const data = yield* sessionState.snapshotData();
|
|
2830
|
-
return {
|
|
2831
|
-
state: data.reduced,
|
|
2832
|
-
reducerStates: data.reducerStates,
|
|
2833
|
-
messages: durableMessageTranscript(data.reduced)
|
|
2834
|
-
};
|
|
2835
|
-
});
|
|
2836
|
-
return {
|
|
2837
|
-
snapshot: () => snapshot,
|
|
2838
|
-
messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),
|
|
2839
|
-
eventsAfter: (afterSeq) => Effect.gen(function* () {
|
|
2840
|
-
const live = yield* liveBus.subscribeQueue();
|
|
2841
|
-
const replayHead = (yield* sessionState.snapshot()).lastSeq;
|
|
2842
|
-
const replay = yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= replayHead), Stream.map((entry) => PositionedEvent.make({
|
|
2843
|
-
position: entry.position,
|
|
2844
|
-
event: entry.event
|
|
2845
|
-
})), Stream.runCollect, Effect.map((events) => Array.from(events)));
|
|
2846
|
-
const activeTurnReplay = yield* liveBus.activeTurnReplay();
|
|
2847
|
-
const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter((event) => shouldEmitLiveEvent(event, replayHead));
|
|
2848
|
-
const reconnectPrefix = Array.from(uniquePositionedEvents([
|
|
2849
|
-
...replay,
|
|
2850
|
-
...activeTurnReplay.events,
|
|
2851
|
-
...pendingLive
|
|
2852
|
-
])).sort(comparePositionedEvents);
|
|
2853
|
-
yield* annotateEdaSpan({
|
|
2854
|
-
"eda.seq.after": afterSeq,
|
|
2855
|
-
"eda.seq.head": replayHead,
|
|
2856
|
-
"eda.replay.events": replay.length,
|
|
2857
|
-
"eda.live.active_turn_events": activeTurnReplay.events.length,
|
|
2858
|
-
"eda.live.active_turn_overflowed": activeTurnReplay.overflowed,
|
|
2859
|
-
"eda.live.buffered_events": pendingLive.length
|
|
2860
|
-
});
|
|
2861
|
-
const follow = Stream.fromEffectRepeat(PubSub.take(live)).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));
|
|
2862
|
-
return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));
|
|
2863
|
-
}).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } }))
|
|
2864
|
-
};
|
|
2865
|
-
}));
|
|
2866
|
-
};
|
|
2867
|
-
const shouldEmitLiveEvent = (event, replayHead) => event.event.durability === "ephemeral" || event.position.seq > replayHead;
|
|
2868
|
-
const comparePositionedEvents = (left, right) => {
|
|
2869
|
-
const seq = left.position.seq - right.position.seq;
|
|
2870
|
-
return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;
|
|
2871
|
-
};
|
|
2872
|
-
const uniquePositionedEvents = (events) => {
|
|
2873
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2874
|
-
const output = [];
|
|
2875
|
-
for (const event of events) {
|
|
2876
|
-
const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;
|
|
2877
|
-
if (seen.has(key)) continue;
|
|
2878
|
-
seen.add(key);
|
|
2879
|
-
output.push(event);
|
|
2880
|
-
}
|
|
2881
|
-
return output;
|
|
2882
|
-
};
|
|
2883
|
-
//#endregion
|
|
2884
|
-
export { ToolExecutor as a, InferenceRunner as i, SessionState as n, TurnRunner as r, EDASessionQuery as t };
|
|
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 };
|
|
2885
3327
|
|
|
2886
|
-
//# sourceMappingURL=session-
|
|
3328
|
+
//# sourceMappingURL=session-state-BQYsuBqi.js.map
|