effect-durable-agent 0.1.0-alpha.9 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/assert-never-CoyUpoRB.js +18 -0
- package/dist/assert-never-CoyUpoRB.js.map +1 -0
- package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
- package/dist/{compaction-BgDr5VJy.js → compaction-D7WJa899.js} +63 -13
- package/dist/compaction-D7WJa899.js.map +1 -0
- package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
- package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
- package/dist/delivery-B_LDTuIB.d.ts +3169 -0
- package/dist/delivery-BoF-NZbZ.js +507 -0
- package/dist/delivery-BoF-NZbZ.js.map +1 -0
- 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 +1 -1
- package/dist/domain/context-projection.js +1 -1
- package/dist/domain/context-projection.js.map +1 -1
- 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 +1 -1
- package/dist/domain/model-usage.js +1 -1
- package/dist/domain/reduced-state-schema.d.ts +3 -992
- package/dist/domain/reduced-state-schema.js +126 -7
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +2 -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-br2C1bWK.d.ts → durable-BXqwM70o.d.ts} +8983 -2800
- package/dist/{durable-BGFvX7Mh.js → durable-Da57Rcml.js} +243 -15
- package/dist/durable-Da57Rcml.js.map +1 -0
- package/dist/{envelope-DxQzo5rN.js → envelope-BSI_Xh-f.js} +31 -6
- package/dist/envelope-BSI_Xh-f.js.map +1 -0
- package/dist/{envelope-DkZyMIgp.d.ts → envelope-CJnPfbjC.d.ts} +121 -11
- package/dist/{event-factory-DTFdy0Cb.js → event-factory-BUoBwqAy.js} +7 -3
- package/dist/event-factory-BUoBwqAy.js.map +1 -0
- package/dist/{events-LZFNoESe.d.ts → events-AIIwZ6dS.d.ts} +139 -137
- package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
- package/dist/in-memory-E497WhtS.js +150 -0
- package/dist/in-memory-E497WhtS.js.map +1 -0
- package/dist/index.d.ts +8 -8
- package/dist/index.js +6 -6
- package/dist/interpreter-BwYN2PCC.js +1453 -0
- package/dist/interpreter-BwYN2PCC.js.map +1 -0
- package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
- package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-O8Kn27GH.d.ts} +11 -5
- package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-mttrPN0j.d.ts} +2 -3
- package/dist/records-D0ZIAOzd.js +675 -0
- package/dist/records-D0ZIAOzd.js.map +1 -0
- package/dist/reduced-state-YbjpihEf.d.ts +52933 -0
- package/dist/reduced-state-schema-B9TYxkP9.d.ts +2338 -0
- package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-Bqn5B4JO.d.ts} +12 -6
- package/dist/run-scheduling-wakeup-DX2zRAxd.d.ts +24 -0
- package/dist/services/compaction.d.ts +2 -2
- package/dist/services/compaction.js +2 -2
- package/dist/services/decider.d.ts +2 -0
- package/dist/services/decider.js +97 -0
- package/dist/services/decider.js.map +1 -0
- package/dist/services/id-generator.d.ts +1 -1
- package/dist/services/id-generator.js +6 -12
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/keep-alive.d.ts +1 -1
- package/dist/services/keep-alive.js.map +1 -1
- 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 +1 -1
- package/dist/services/model-resolver.js +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- 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 +1 -1
- package/dist/services/reducer-registry.js +19 -6
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/run-scheduler.d.ts +2 -2
- package/dist/services/run-scheduler.js +25 -2
- 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 +21 -33
- package/dist/services/runtime-layer.js +24 -16
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +32 -20
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-event-observer.js.map +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +57 -10
- package/dist/services/session-query.js.map +1 -1
- package/dist/services/session-state.d.ts +2 -2
- package/dist/services/session-state.js +2 -1
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +143 -38
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-checkpoint-store.js +2 -1
- package/dist/services/sink-checkpoint-store.js.map +1 -1
- 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 +2 -2
- package/dist/services/tracing.js.map +1 -1
- package/dist/session-admission-WE8J_0z9.js +138 -0
- package/dist/session-admission-WE8J_0z9.js.map +1 -0
- package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-BWQUJTcN.d.ts} +3 -3
- package/dist/{session-state-Bkc6u-Wr.js → session-state-D02LCVcC.js} +815 -170
- package/dist/session-state-D02LCVcC.js.map +1 -0
- package/dist/session-store-DaSHeg8Q.d.ts +3343 -0
- package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-CUvIVvlZ.d.ts} +3 -4
- package/dist/sink-registry-AOjX5_A1.js +369 -0
- package/dist/sink-registry-AOjX5_A1.js.map +1 -0
- package/dist/subscription-BhwUmsl4.d.ts +966 -0
- package/dist/subscription-D7U4Tziv.js +505 -0
- package/dist/subscription-D7U4Tziv.js.map +1 -0
- package/dist/testkit/layers.d.ts +33 -23
- package/dist/testkit/layers.js +34 -19
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.d.ts +232 -0
- package/dist/testkit/transcript.js +1526 -0
- package/dist/testkit/transcript.js.map +1 -0
- 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 +3 -1
- 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 -5
- package/dist/types/events.js +3 -3
- 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 +2123 -2552
- package/dist/websocket.js +628 -442
- package/dist/websocket.js.map +1 -1
- package/dist/window-read-BELSkO-r.d.ts +113 -0
- package/dist/window-read-FJTCDaSq.js +264 -0
- package/dist/window-read-FJTCDaSq.js.map +1 -0
- package/package.json +41 -13
- package/dist/command-queues-DdDB_aYM.d.ts +0 -462
- package/dist/compaction-BgDr5VJy.js.map +0 -1
- package/dist/compaction-ch8z6G9x.d.ts +0 -165
- package/dist/durable-BGFvX7Mh.js.map +0 -1
- package/dist/envelope-DxQzo5rN.js.map +0 -1
- package/dist/event-factory-DTFdy0Cb.js.map +0 -1
- package/dist/event-factory-Di1jwQvm.d.ts +0 -87
- package/dist/index-BVVgDSdq.d.ts +0 -1
- package/dist/message-transcript-DQNlzxle.d.ts +0 -32
- package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
- package/dist/reduced-state-DF0-6mbR.js +0 -921
- package/dist/reduced-state-DF0-6mbR.js.map +0 -1
- package/dist/run-scheduler-CAt7dF6C.js +0 -21
- package/dist/run-scheduler-CAt7dF6C.js.map +0 -1
- package/dist/run-scheduler-xkhZyto5.d.ts +0 -44
- package/dist/runtime-DDSYP9jS.d.ts +0 -63
- package/dist/session-query-B72HY_0L.d.ts +0 -45
- package/dist/session-state-Bkc6u-Wr.js.map +0 -1
- package/dist/session-state-C9YLSAso.d.ts +0 -862
- package/dist/session-store-Cpi_NwTR.d.ts +0 -206
- package/dist/sink-registry-Bl-vQES6.d.ts +0 -133
- package/dist/sink-registry-NDgeyzO0.js +0 -272
- package/dist/sink-registry-NDgeyzO0.js.map +0 -1
- package/dist/tool-registry-BJaVNtw4.d.ts +0 -51
|
@@ -1,38 +1,46 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RunSchedulingWakeup } from "./services/run-scheduling-wakeup.js";
|
|
2
|
+
import { CommandId, InferenceId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
|
|
3
|
+
import { canGrantRun, planRunSchedulingCancellation, planWaitingRunInterruption, runSchedulingInputMessageIds, waitingRunControl } from "./domain/run-scheduling.js";
|
|
4
|
+
import { RunScheduler } from "./services/run-scheduler.js";
|
|
2
5
|
import { ModelResolver } from "./services/model-resolver.js";
|
|
3
|
-
import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
|
|
4
6
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
5
|
-
import { c as
|
|
7
|
+
import { S as schemaV1, _ as UnixEpochMillis, c as FailurePayload, d as NonNegativeInt, f as PositionedEvent, g as ToolName, h as SystemPromptText, p as ProviderPartId, r as EventDedupeKey, t as DurableEventEnvelope, u as ModelSelectionPayload, y as effectDurableAgentNamespace } from "./envelope-BSI_Xh-f.js";
|
|
6
8
|
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
+
import { H as DeciderAcceptedEvent, Jt as ToolCallCreatedEvent, Kn as deciderAcceptedEventType, Qn as inferenceFailedEventType, Sr as toolCallRejectedEventType, Tr as turnFailedEventType, Xn as durableEventEnvelope, Zn as inferenceCompletedEventType, _ as CommandAdmittedEvent, _n as TurnStoppedEvent, br as toolCallCreatedEventType, hn as TurnStartedEvent, pn as TurnFailedEvent, un as TurnCompletedEvent } from "./durable-Da57Rcml.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";
|
|
9
12
|
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
13
|
+
import { a as jsonBytes, n as SessionCommandAdmissionConflict, o as makeAppEventAdmission, r as appEventConflict, t as RegisteredAppEvents } from "./session-admission-WE8J_0z9.js";
|
|
14
|
+
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
|
|
15
|
+
import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-D7WJa899.js";
|
|
16
|
+
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
17
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-BUoBwqAy.js";
|
|
18
|
+
import { EDAToolRegistry, toolRecoveryPolicy } from "./services/tool-registry.js";
|
|
12
19
|
import { IdGenerator } from "./services/id-generator.js";
|
|
13
|
-
import {
|
|
14
|
-
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
20
|
+
import { annotateEdaSpan, committedBatchAttributes, currentOrRootEDAEventTrace, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
15
21
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
16
|
-
import {
|
|
17
|
-
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
22
|
+
import { SessionEventObserver } from "./services/session-event-observer.js";
|
|
18
23
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
19
|
-
import {
|
|
24
|
+
import { n as EDASinkRegistry } from "./sink-registry-AOjX5_A1.js";
|
|
25
|
+
import { EDADeciderError, EDADeciderRegistry, deciderIdempotencyKeyViolation, deciderMarkerDedupeKey, encodeDeciderJson, maxDeciderResultBytes } from "./services/decider.js";
|
|
20
26
|
import * as Context from "effect/Context";
|
|
21
27
|
import * as Effect from "effect/Effect";
|
|
22
28
|
import * as Layer from "effect/Layer";
|
|
23
29
|
import * as Schema from "effect/Schema";
|
|
24
30
|
import * as Stream from "effect/Stream";
|
|
25
|
-
import * as Prompt from "effect/
|
|
31
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
32
|
+
import * as Exit from "effect/Exit";
|
|
26
33
|
import * as Cause from "effect/Cause";
|
|
27
34
|
import * as Clock from "effect/Clock";
|
|
28
|
-
import * as Exit from "effect/Exit";
|
|
29
35
|
import * as Fiber from "effect/Fiber";
|
|
30
36
|
import * as Queue from "effect/Queue";
|
|
31
37
|
import * as Ref from "effect/Ref";
|
|
38
|
+
import * as Result from "effect/Result";
|
|
32
39
|
import * as Scope from "effect/Scope";
|
|
33
40
|
import * as Semaphore from "effect/Semaphore";
|
|
34
41
|
import * as Option from "effect/Option";
|
|
35
|
-
import * as
|
|
42
|
+
import * as PubSub from "effect/PubSub";
|
|
43
|
+
import * as Response from "effect/ai/Response";
|
|
36
44
|
//#region src/domain/dispatch-policy.ts
|
|
37
45
|
/** Durable/runtime evidence for active work blocking new queued commands. */
|
|
38
46
|
const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
|
|
@@ -110,6 +118,15 @@ const decideDispatch = (state) => {
|
|
|
110
118
|
command: toCandidate(next)
|
|
111
119
|
};
|
|
112
120
|
};
|
|
121
|
+
/** Promotion must retain a live or pending execution owner when the original command is terminal. */
|
|
122
|
+
const promotionNeedsResumeCommand = (state, messageId) => {
|
|
123
|
+
if (state.commandQueues.active?.runId !== void 0) return false;
|
|
124
|
+
const target = state.messages.get(messageId);
|
|
125
|
+
if (target?._tag !== "User" && target?._tag !== "Steering") return false;
|
|
126
|
+
const waiting = state.runSchedulingRequest?.work;
|
|
127
|
+
if (waiting?._tag === "Recovery" && waiting.inputMessageIds.includes(messageId)) return false;
|
|
128
|
+
return !state.commandQueues.pendingCommands.some((pending) => pending.commandId === target.commandId || pending.command._tag === "ResumePendingMessages" && pending.command.messageIds.includes(messageId));
|
|
129
|
+
};
|
|
113
130
|
const nextIdleCommand = (state) => {
|
|
114
131
|
const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
|
|
115
132
|
for (const message of state.commandQueues.pendingSteers) {
|
|
@@ -220,9 +237,9 @@ const planSessionRecovery = (state) => {
|
|
|
220
237
|
const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
|
|
221
238
|
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);
|
|
222
239
|
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);
|
|
223
|
-
const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
240
|
+
const continuationInputMessageIds = Array.from(/* @__PURE__ */ new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
224
241
|
const continuationInputIds = new Set(continuationInputMessageIds);
|
|
225
|
-
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);
|
|
242
|
+
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);
|
|
226
243
|
return {
|
|
227
244
|
activeCommands: recoverable.activeCommands,
|
|
228
245
|
activeRuns: recoverable.activeRuns,
|
|
@@ -248,6 +265,60 @@ const planRunFailure = (state) => ({ messageIdsToResume: state.commandQueues.pen
|
|
|
248
265
|
/** Normal explicit Stop/Interrupt policy. This is not startup recovery. */
|
|
249
266
|
const planUserInterruption = (state) => ({ messageIdsToPause: [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) });
|
|
250
267
|
//#endregion
|
|
268
|
+
//#region src/services/live-event-bus.ts
|
|
269
|
+
/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
|
|
270
|
+
const activeTurnEphemeralReplayCapacity = 4096;
|
|
271
|
+
/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
|
|
272
|
+
var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
|
|
273
|
+
static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
|
|
274
|
+
const pubsub = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
|
|
275
|
+
const activeTurnReplay = yield* Ref.make({
|
|
276
|
+
events: [],
|
|
277
|
+
overflowed: false
|
|
278
|
+
});
|
|
279
|
+
const observer = yield* SessionEventObserver;
|
|
280
|
+
return makeLiveBus(pubsub, activeTurnReplay, observer);
|
|
281
|
+
}));
|
|
282
|
+
/** Live bus for hosts that do not install an append-driven observer. */
|
|
283
|
+
static Noop = LiveEventBus.Live.pipe(Layer.provide(SessionEventObserver.Noop));
|
|
284
|
+
};
|
|
285
|
+
const makeLiveBus = (pubsub, activeTurnReplay, observer) => ({
|
|
286
|
+
publish: (event) => Effect.gen(function* () {
|
|
287
|
+
yield* updateActiveTurnReplay(activeTurnReplay, event);
|
|
288
|
+
yield* observer.onEvent(event);
|
|
289
|
+
return yield* PubSub.publish(pubsub, event);
|
|
290
|
+
}),
|
|
291
|
+
subscribeQueue: () => PubSub.subscribe(pubsub),
|
|
292
|
+
subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
|
|
293
|
+
activeTurnReplay: () => Ref.get(activeTurnReplay)
|
|
294
|
+
});
|
|
295
|
+
const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
|
|
296
|
+
const nextActiveTurnReplay = (state, event) => {
|
|
297
|
+
if (Schema.is(TurnStartedEvent)(event.event)) return {
|
|
298
|
+
turnId: event.event.payload.turnId,
|
|
299
|
+
events: [],
|
|
300
|
+
overflowed: false
|
|
301
|
+
};
|
|
302
|
+
if (Schema.is(TurnCompletedEvent)(event.event) || Schema.is(TurnFailedEvent)(event.event) || Schema.is(TurnStoppedEvent)(event.event)) {
|
|
303
|
+
const turnId = event.event.payload.turnId;
|
|
304
|
+
return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
|
|
305
|
+
events: [],
|
|
306
|
+
overflowed: false
|
|
307
|
+
} : state;
|
|
308
|
+
}
|
|
309
|
+
if (event.event.durability !== "ephemeral" || state.turnId === void 0) return state;
|
|
310
|
+
const events = [...state.events, event];
|
|
311
|
+
if (events.length <= 4096) return {
|
|
312
|
+
...state,
|
|
313
|
+
events
|
|
314
|
+
};
|
|
315
|
+
return {
|
|
316
|
+
...state,
|
|
317
|
+
events: events.slice(events.length - activeTurnEphemeralReplayCapacity),
|
|
318
|
+
overflowed: true
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
//#endregion
|
|
251
322
|
//#region src/services/started-boundary-guard.ts
|
|
252
323
|
/** Build a guard bound to the session's durable append boundary. */
|
|
253
324
|
const makeStartedBoundaryGuard = (state) => (spec) => {
|
|
@@ -306,13 +377,14 @@ Schema.Union([
|
|
|
306
377
|
ToolExecutionSkipped
|
|
307
378
|
]);
|
|
308
379
|
/** Failure when tool execution receives a committed event that is not ToolCallCreated. */
|
|
309
|
-
var ToolExecutionEventNotCreated = class extends Schema.
|
|
380
|
+
var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
|
|
310
381
|
/** Construct the live tool-executor implementation. */
|
|
311
382
|
const makeLiveToolExecutor = Effect.gen(function* () {
|
|
312
383
|
const events = yield* EventFactory;
|
|
313
384
|
const ids = yield* IdGenerator;
|
|
314
385
|
const registry = yield* EDAToolRegistry;
|
|
315
386
|
const session = yield* SessionContext;
|
|
387
|
+
const store = yield* EDASessionStore;
|
|
316
388
|
const failToolCall = (input, created, error) => Effect.gen(function* () {
|
|
317
389
|
const event = yield* events.toolCallFailed({
|
|
318
390
|
toolCallId: created.event.payload.toolCallId,
|
|
@@ -327,7 +399,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
327
399
|
yield* annotateEdaSpan({
|
|
328
400
|
"eda.tool_call.id": created.event.payload.toolCallId,
|
|
329
401
|
"eda.tool.name": created.event.payload.promptPart.name,
|
|
330
|
-
"eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted
|
|
402
|
+
"eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted,
|
|
403
|
+
...input.resume === void 0 ? {} : { "eda.tool.attempt": input.resume.attempt }
|
|
331
404
|
});
|
|
332
405
|
if (created.event.payload.promptPart.providerExecuted) {
|
|
333
406
|
const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
|
|
@@ -338,13 +411,25 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
338
411
|
};
|
|
339
412
|
}
|
|
340
413
|
const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
|
|
341
|
-
start: events.toolCallStarted({
|
|
414
|
+
start: events.toolCallStarted({
|
|
415
|
+
toolCallId: created.event.payload.toolCallId,
|
|
416
|
+
...input.resume === void 0 ? {} : { attempt: input.resume.attempt }
|
|
417
|
+
}),
|
|
342
418
|
body: () => Effect.gen(function* () {
|
|
343
419
|
const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
|
|
344
420
|
toolCallId: created.event.payload.toolCallId,
|
|
421
|
+
runId: created.event.payload.runId,
|
|
422
|
+
turnId: created.event.payload.turnId,
|
|
423
|
+
queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
|
|
345
424
|
sessionId: session.sessionId,
|
|
346
425
|
makeEventId: ids.makeEventId,
|
|
347
|
-
emitDurable: input.eventSink.
|
|
426
|
+
emitDurable: input.eventSink.appendAppDurable,
|
|
427
|
+
decide: input.eventSink.decide,
|
|
428
|
+
snapshot: () => input.eventSink.snapshotData().pipe(Effect.map((data) => ({
|
|
429
|
+
state: data.reduced,
|
|
430
|
+
reducerStates: data.reducerStates
|
|
431
|
+
}))),
|
|
432
|
+
...input.resume === void 0 ? {} : { recovery: input.resume }
|
|
348
433
|
}).pipe(Effect.map((result) => ({
|
|
349
434
|
_tag: "Succeeded",
|
|
350
435
|
result
|
|
@@ -405,6 +490,7 @@ const toolCompletedPromptPart = (created, result) => ({
|
|
|
405
490
|
id: created.event.payload.promptPart.id,
|
|
406
491
|
name: created.event.payload.promptPart.name,
|
|
407
492
|
isFailure: false,
|
|
493
|
+
providerExecuted: false,
|
|
408
494
|
result
|
|
409
495
|
}),
|
|
410
496
|
id: created.event.payload.promptPart.id,
|
|
@@ -416,6 +502,7 @@ const toolFailedPromptPart = (created, error) => ({
|
|
|
416
502
|
id: created.event.payload.promptPart.id,
|
|
417
503
|
name: created.event.payload.promptPart.name,
|
|
418
504
|
isFailure: true,
|
|
505
|
+
providerExecuted: false,
|
|
419
506
|
result: error
|
|
420
507
|
}),
|
|
421
508
|
id: created.event.payload.promptPart.id,
|
|
@@ -597,7 +684,8 @@ const recordToolParamsEnd = (state, input) => {
|
|
|
597
684
|
};
|
|
598
685
|
const recordToolCall = (state, input) => {
|
|
599
686
|
const draft = state.drafts.get(input.providerPartId);
|
|
600
|
-
const
|
|
687
|
+
const toolCallId = draft?.toolCallId ?? input.toolCallId;
|
|
688
|
+
const decision = makeToolCallDecision(state, input, toolCallId);
|
|
601
689
|
const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
|
|
602
690
|
const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
|
|
603
691
|
return {
|
|
@@ -714,6 +802,7 @@ const toolRejectedPromptPart = (decision) => ({
|
|
|
714
802
|
id: decision.providerPartId,
|
|
715
803
|
name: decision.toolName,
|
|
716
804
|
isFailure: true,
|
|
805
|
+
providerExecuted: false,
|
|
717
806
|
result: {
|
|
718
807
|
message: decision.error.message,
|
|
719
808
|
reason: decision.reason,
|
|
@@ -751,7 +840,7 @@ const InferenceRunResult = Schema.Struct({
|
|
|
751
840
|
partsRecorded: NonNegativeInt,
|
|
752
841
|
terminal: InferenceRunTerminal
|
|
753
842
|
});
|
|
754
|
-
Schema.
|
|
843
|
+
Schema.TaggedError()("UnsupportedInferencePart", {
|
|
755
844
|
partType: Schema.String,
|
|
756
845
|
reason: Schema.String
|
|
757
846
|
});
|
|
@@ -971,7 +1060,8 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
971
1060
|
type: "error",
|
|
972
1061
|
error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
|
|
973
1062
|
});
|
|
974
|
-
|
|
1063
|
+
const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []);
|
|
1064
|
+
return yield* requireTerminal(terminal);
|
|
975
1065
|
});
|
|
976
1066
|
return { runInference: Effect.fn("agent.inference")(function* (input) {
|
|
977
1067
|
const languageModel = yield* models.resolve(input.modelSelection);
|
|
@@ -995,8 +1085,9 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
995
1085
|
});
|
|
996
1086
|
const body = (started) => Effect.gen(function* () {
|
|
997
1087
|
const toolkit = yield* toolRegistry.getModelToolkit();
|
|
1088
|
+
const prompt = models.preparePrompt?.(input.modelSelection, Prompt.make(input.prompt));
|
|
998
1089
|
const state = yield* languageModel.streamText({
|
|
999
|
-
prompt: input.prompt,
|
|
1090
|
+
prompt: prompt ?? input.prompt,
|
|
1000
1091
|
disableToolCallResolution: true,
|
|
1001
1092
|
...toolkit === void 0 ? {} : { toolkit }
|
|
1002
1093
|
}).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)))));
|
|
@@ -1043,7 +1134,8 @@ var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-d
|
|
|
1043
1134
|
};
|
|
1044
1135
|
const inferenceUsageAttributes = (terminal) => {
|
|
1045
1136
|
if (terminal._tag !== "InferenceRunFinished") return {};
|
|
1046
|
-
|
|
1137
|
+
const completed = terminal.committed.find((entry) => entry.event.type === "InferenceCompleted");
|
|
1138
|
+
return usageAttributes(completed?.event.type === "InferenceCompleted" ? completed.event.payload.usage : void 0);
|
|
1047
1139
|
};
|
|
1048
1140
|
const initialRunInferenceState = (identity) => ({
|
|
1049
1141
|
inference: initialInferenceState(identity),
|
|
@@ -1053,12 +1145,12 @@ const initialRunInferenceState = (identity) => ({
|
|
|
1053
1145
|
});
|
|
1054
1146
|
const recordResponseContext = (entries, part) => {
|
|
1055
1147
|
switch (part.type) {
|
|
1056
|
-
case "text-start":
|
|
1057
|
-
case "text-
|
|
1058
|
-
case "text-
|
|
1059
|
-
case "reasoning-start":
|
|
1060
|
-
case "reasoning-
|
|
1061
|
-
case "reasoning-
|
|
1148
|
+
case "text-start":
|
|
1149
|
+
case "text-end": return upsertTextualResponseEntry(entries, "Text", part.id, "", part.metadata);
|
|
1150
|
+
case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta, part.metadata);
|
|
1151
|
+
case "reasoning-start":
|
|
1152
|
+
case "reasoning-end": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "", part.metadata);
|
|
1153
|
+
case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta, part.metadata);
|
|
1062
1154
|
case "tool-call": return part.providerExecuted ? entries : [...entries, {
|
|
1063
1155
|
_tag: "ResponsePart",
|
|
1064
1156
|
part
|
|
@@ -1076,24 +1168,50 @@ const recordResponseContext = (entries, part) => {
|
|
|
1076
1168
|
default: throw assertNeverError(part, "response context part");
|
|
1077
1169
|
}
|
|
1078
1170
|
};
|
|
1079
|
-
|
|
1171
|
+
/**
|
|
1172
|
+
* Folds one textual stream part into its entry. Provider metadata from start, delta and end parts
|
|
1173
|
+
* is merged per provider so replay keeps signatures, item ids and encrypted reasoning.
|
|
1174
|
+
*/
|
|
1175
|
+
const upsertTextualResponseEntry = (entries, tag, providerPartId, delta, metadata) => {
|
|
1080
1176
|
const index = entries.findIndex((entry) => (entry._tag === "Text" || entry._tag === "Reasoning") && entry._tag === tag && entry.providerPartId === providerPartId);
|
|
1081
1177
|
if (index === -1) return [...entries, {
|
|
1082
1178
|
_tag: tag,
|
|
1083
1179
|
providerPartId,
|
|
1084
|
-
text: delta
|
|
1180
|
+
text: delta,
|
|
1181
|
+
metadata: metadata ?? {}
|
|
1085
1182
|
}];
|
|
1086
1183
|
const current = entries[index];
|
|
1087
1184
|
if (current._tag !== tag) return entries;
|
|
1088
1185
|
return entries.map((entry, entryIndex) => entryIndex === index ? {
|
|
1089
1186
|
...current,
|
|
1090
|
-
text: `${current.text}${delta}
|
|
1187
|
+
text: `${current.text}${delta}`,
|
|
1188
|
+
metadata: mergeProviderMetadata(current.metadata, metadata)
|
|
1091
1189
|
} : entry);
|
|
1092
1190
|
};
|
|
1191
|
+
const mergeProviderMetadata = (left, right) => {
|
|
1192
|
+
if (right === void 0) return left;
|
|
1193
|
+
const merged = { ...left };
|
|
1194
|
+
for (const [provider, value] of Object.entries(right)) {
|
|
1195
|
+
const previous = merged[provider];
|
|
1196
|
+
merged[provider] = isMetadataRecord(previous) && isMetadataRecord(value) ? {
|
|
1197
|
+
...previous,
|
|
1198
|
+
...value
|
|
1199
|
+
} : value;
|
|
1200
|
+
}
|
|
1201
|
+
return merged;
|
|
1202
|
+
};
|
|
1203
|
+
const isMetadataRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1204
|
+
const hasProviderMetadata = (metadata) => Object.keys(metadata).length > 0;
|
|
1093
1205
|
const responseContextToParts = (entries) => entries.flatMap((entry) => {
|
|
1094
1206
|
switch (entry._tag) {
|
|
1095
|
-
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1096
|
-
|
|
1207
|
+
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1208
|
+
text: entry.text,
|
|
1209
|
+
metadata: entry.metadata
|
|
1210
|
+
})];
|
|
1211
|
+
case "Reasoning": return entry.text.length === 0 && !hasProviderMetadata(entry.metadata) ? [] : [Response.makePart("reasoning", {
|
|
1212
|
+
text: entry.text,
|
|
1213
|
+
metadata: entry.metadata
|
|
1214
|
+
})];
|
|
1097
1215
|
case "ResponsePart": return [entry.part];
|
|
1098
1216
|
default: throw assertNeverError(entry, "response context entry");
|
|
1099
1217
|
}
|
|
@@ -1142,7 +1260,6 @@ const makeResponseMetadata = (part) => ({
|
|
|
1142
1260
|
id: part.id,
|
|
1143
1261
|
modelId: part.modelId,
|
|
1144
1262
|
timestamp: part.timestamp,
|
|
1145
|
-
request: part.request,
|
|
1146
1263
|
metadata: part.metadata
|
|
1147
1264
|
});
|
|
1148
1265
|
const makeFinishMetadata = (part) => ({
|
|
@@ -1174,6 +1291,7 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1174
1291
|
const events = yield* EventFactory;
|
|
1175
1292
|
const inferenceRunner = yield* InferenceRunner;
|
|
1176
1293
|
const toolExecutor = yield* ToolExecutor;
|
|
1294
|
+
const toolRegistry = yield* EDAToolRegistry;
|
|
1177
1295
|
const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
|
|
1178
1296
|
const usage = inferenceCompleted.event.payload.usage;
|
|
1179
1297
|
const turnCompleted = yield* events.turnCompleted({
|
|
@@ -1292,55 +1410,66 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1292
1410
|
return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
|
|
1293
1411
|
});
|
|
1294
1412
|
});
|
|
1295
|
-
return {
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
const
|
|
1311
|
-
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1312
|
-
const inference = yield* inferenceRunner.runInference({
|
|
1313
|
-
...turnIdentity,
|
|
1314
|
-
inferenceId,
|
|
1315
|
-
prompt: input.prompt,
|
|
1316
|
-
eventSink: input.eventSink,
|
|
1317
|
-
modelSelection: input.modelSelection
|
|
1318
|
-
});
|
|
1319
|
-
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1320
|
-
return TurnRunResult.make({
|
|
1321
|
-
started: input.started,
|
|
1322
|
-
inference,
|
|
1323
|
-
outcome
|
|
1324
|
-
});
|
|
1325
|
-
}).pipe(Effect.tap((result) => Effect.gen(function* () {
|
|
1413
|
+
return {
|
|
1414
|
+
toolRecoveryPolicy: (toolName) => toolRegistry.getModelToolkit().pipe(Effect.map((toolkit) => toolRecoveryPolicy(toolkit, toolName))),
|
|
1415
|
+
resumeToolCalls: ({ calls, eventSink }) => Effect.forEach(calls, ({ created, resume }) => toolExecutor.executeCreated({
|
|
1416
|
+
created,
|
|
1417
|
+
eventSink,
|
|
1418
|
+
resume
|
|
1419
|
+
}), {
|
|
1420
|
+
concurrency: maxToolExecutionConcurrency,
|
|
1421
|
+
discard: true
|
|
1422
|
+
}),
|
|
1423
|
+
runTurn: Effect.fn("agent.turn")(function* (input) {
|
|
1424
|
+
const turnIdentity = {
|
|
1425
|
+
runId: input.runId,
|
|
1426
|
+
turnId: input.turnId
|
|
1427
|
+
};
|
|
1428
|
+
const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
|
|
1326
1429
|
yield* annotateEdaSpan({
|
|
1327
|
-
"eda.
|
|
1328
|
-
"eda.
|
|
1329
|
-
"eda.provider
|
|
1330
|
-
|
|
1430
|
+
"eda.run.id": input.runId,
|
|
1431
|
+
"eda.turn.id": input.turnId,
|
|
1432
|
+
"eda.model.provider": input.modelSelection?.provider,
|
|
1433
|
+
"eda.model.id": input.modelSelection?.modelId,
|
|
1434
|
+
"eda.tool.max_calls_per_run": maxToolCallsPerRun
|
|
1331
1435
|
});
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1436
|
+
const inferencesStarted = yield* Ref.make(0);
|
|
1437
|
+
return yield* Effect.gen(function* () {
|
|
1438
|
+
const inferenceId = yield* ids.makeInferenceId();
|
|
1439
|
+
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1440
|
+
const inference = yield* inferenceRunner.runInference({
|
|
1336
1441
|
...turnIdentity,
|
|
1337
|
-
|
|
1442
|
+
inferenceId,
|
|
1443
|
+
prompt: input.prompt,
|
|
1444
|
+
eventSink: input.eventSink,
|
|
1445
|
+
modelSelection: input.modelSelection
|
|
1446
|
+
});
|
|
1447
|
+
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1448
|
+
return TurnRunResult.make({
|
|
1449
|
+
started: input.started,
|
|
1450
|
+
inference,
|
|
1451
|
+
outcome
|
|
1452
|
+
});
|
|
1453
|
+
}).pipe(Effect.tap((result) => Effect.gen(function* () {
|
|
1454
|
+
yield* annotateEdaSpan({
|
|
1455
|
+
"eda.turn.outcome": result.outcome._tag,
|
|
1456
|
+
"eda.inference.started_count": yield* Ref.get(inferencesStarted),
|
|
1457
|
+
"eda.provider.parts_recorded": result.inference.partsRecorded,
|
|
1458
|
+
...turnUsageAttributes(result)
|
|
1338
1459
|
});
|
|
1339
|
-
|
|
1340
|
-
return
|
|
1460
|
+
})), Effect.catchCause((cause) => {
|
|
1461
|
+
if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
|
|
1462
|
+
return Effect.uninterruptible(Effect.gen(function* () {
|
|
1463
|
+
const terminal = yield* events.turnFailed({
|
|
1464
|
+
...turnIdentity,
|
|
1465
|
+
error: failurePayloadFromCause(cause)
|
|
1466
|
+
});
|
|
1467
|
+
yield* input.eventSink.appendDurable(terminal);
|
|
1468
|
+
return yield* Effect.failCause(cause);
|
|
1469
|
+
}));
|
|
1341
1470
|
}));
|
|
1342
|
-
})
|
|
1343
|
-
}
|
|
1471
|
+
})
|
|
1472
|
+
};
|
|
1344
1473
|
});
|
|
1345
1474
|
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
1346
1475
|
var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
|
|
@@ -1382,6 +1511,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
|
|
|
1382
1511
|
id: created.event.payload.promptPart.id,
|
|
1383
1512
|
name: created.event.payload.promptPart.name,
|
|
1384
1513
|
isFailure: true,
|
|
1514
|
+
providerExecuted: false,
|
|
1385
1515
|
result
|
|
1386
1516
|
}),
|
|
1387
1517
|
id: created.event.payload.promptPart.id,
|
|
@@ -1395,11 +1525,11 @@ const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
|
|
|
1395
1525
|
if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
|
|
1396
1526
|
return created;
|
|
1397
1527
|
});
|
|
1398
|
-
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
|
|
1399
|
-
const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
|
|
1400
|
-
const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
|
|
1401
|
-
const isToolCallCreated = (committed) => committed.event.
|
|
1402
|
-
const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
|
|
1528
|
+
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.type === "TurnCompleted" ? result.outcome.committed.event.payload.usage : void 0) : {};
|
|
1529
|
+
const isInferenceCompleted = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceCompletedEventType;
|
|
1530
|
+
const isInferenceFailed = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceFailedEventType;
|
|
1531
|
+
const isToolCallCreated = (committed) => committed.event.namespace === "effect-durable-agent" && Schema.is(ToolCallCreatedEvent)(committed.event);
|
|
1532
|
+
const isToolCallRejected = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === toolCallRejectedEventType;
|
|
1403
1533
|
const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
|
|
1404
1534
|
const requireInferenceCompleted = (committed) => {
|
|
1405
1535
|
const completed = committed.find(isInferenceCompleted);
|
|
@@ -1430,7 +1560,11 @@ const SessionCommandOutcome = Schema.Union([
|
|
|
1430
1560
|
SessionCommandCancelled
|
|
1431
1561
|
]);
|
|
1432
1562
|
/** Why a control drain stopped without starting more command work. */
|
|
1433
|
-
const SessionNoRunnableReason = Schema.Literals([
|
|
1563
|
+
const SessionNoRunnableReason = Schema.Literals([
|
|
1564
|
+
"active-command",
|
|
1565
|
+
"no-pending-command",
|
|
1566
|
+
"awaiting-run-authorization"
|
|
1567
|
+
]);
|
|
1434
1568
|
/** Session control result when no admitted command is runnable. */
|
|
1435
1569
|
const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
|
|
1436
1570
|
reason: SessionNoRunnableReason,
|
|
@@ -1438,11 +1572,6 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
|
|
|
1438
1572
|
});
|
|
1439
1573
|
/** Control result when command execution was started in an active child scope. */
|
|
1440
1574
|
const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
|
|
1441
|
-
var SessionCommandAdmissionConflict = class extends Schema.TaggedErrorClass()("SessionCommandAdmissionConflict", {
|
|
1442
|
-
code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
|
|
1443
|
-
message: Schema.String,
|
|
1444
|
-
pausedMessageIds: Schema.Array(MessageId)
|
|
1445
|
-
}) {};
|
|
1446
1575
|
/** Internal authoritative live state and root control loop for one session. */
|
|
1447
1576
|
var SessionState = class SessionState extends Context.Service()("@effect-durable-agent/SessionState") {
|
|
1448
1577
|
static Live = Layer.effect(SessionState, Effect.suspend(() => makeLiveSessionState));
|
|
@@ -1457,6 +1586,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
|
|
|
1457
1586
|
id: decision.providerPartId,
|
|
1458
1587
|
name: decision.toolName,
|
|
1459
1588
|
isFailure: true,
|
|
1589
|
+
providerExecuted: false,
|
|
1460
1590
|
result: error
|
|
1461
1591
|
}),
|
|
1462
1592
|
id: decision.providerPartId,
|
|
@@ -1495,10 +1625,29 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1495
1625
|
const promptProjector = yield* EDAPromptProjector;
|
|
1496
1626
|
const sessionContext = yield* SessionContext;
|
|
1497
1627
|
const runScheduler = yield* RunScheduler;
|
|
1628
|
+
const schedulingWakeup = yield* RunSchedulingWakeup;
|
|
1498
1629
|
const reducerRegistry = yield* EDAReducerRegistry;
|
|
1499
1630
|
const sinkRegistry = yield* EDASinkRegistry;
|
|
1500
|
-
const
|
|
1501
|
-
const
|
|
1631
|
+
const appEventAdmission = makeAppEventAdmission(yield* RegisteredAppEvents);
|
|
1632
|
+
const deciders = yield* EDADeciderRegistry;
|
|
1633
|
+
const { hydrated, hydratedReducerStates } = yield* Effect.gen(function* () {
|
|
1634
|
+
const hydrated = yield* hydrateFrameworkReducedState(store);
|
|
1635
|
+
const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
|
|
1636
|
+
yield* Effect.annotateCurrentSpan({
|
|
1637
|
+
"eda.seq.head": hydrated.state.lastSeq,
|
|
1638
|
+
"eda.checkpoint.framework_seq": hydrated.checkpointSeq,
|
|
1639
|
+
...hydratedReducerStates.checkpointSeq === void 0 ? {} : { "eda.checkpoint.app_min_seq": hydratedReducerStates.checkpointSeq }
|
|
1640
|
+
});
|
|
1641
|
+
return {
|
|
1642
|
+
hydrated,
|
|
1643
|
+
hydratedReducerStates
|
|
1644
|
+
};
|
|
1645
|
+
}).pipe(Effect.withSpan("agent.session.hydrate", { attributes: {
|
|
1646
|
+
sessionId: sessionContext.sessionId,
|
|
1647
|
+
"eda.session.id": sessionContext.sessionId,
|
|
1648
|
+
"eda.reducers.count": reducerRegistry.reducers.length
|
|
1649
|
+
} }));
|
|
1650
|
+
yield* schedulingWakeup.setPending(hydrated.state.runSchedulingRequest !== void 0 && hydrated.state.runSchedulingRequest.deliveredSeq === void 0);
|
|
1502
1651
|
const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
|
|
1503
1652
|
const state = yield* Ref.make({
|
|
1504
1653
|
reduced: hydrated.state,
|
|
@@ -1509,6 +1658,16 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1509
1658
|
}
|
|
1510
1659
|
});
|
|
1511
1660
|
const gate = yield* Semaphore.make(1);
|
|
1661
|
+
const controlGate = yield* Semaphore.make(1);
|
|
1662
|
+
/**
|
|
1663
|
+
* Admission versus startup repair: recovery plans its repair batch from a snapshot and then
|
|
1664
|
+
* checks the result reached a fixed point, so no command may be admitted in between. Recovery
|
|
1665
|
+
* that finishes in the background (re-invoked tools) would otherwise race live admission.
|
|
1666
|
+
*/
|
|
1667
|
+
const admissionGate = yield* Semaphore.make(1);
|
|
1668
|
+
/** Set while startup recovery finishes in the background holding the control gate. */
|
|
1669
|
+
const recoveringInBackground = yield* Ref.make(false);
|
|
1670
|
+
const deliveryGate = yield* Semaphore.make(1);
|
|
1512
1671
|
const ingressSignals = yield* Queue.sliding(1);
|
|
1513
1672
|
const reducerCheckpointSnapshots = yield* Queue.sliding(1);
|
|
1514
1673
|
const executionState = yield* Ref.make({ _tag: "Idle" });
|
|
@@ -1536,7 +1695,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1536
1695
|
}));
|
|
1537
1696
|
const buildReducerCheckpointSnapshot = (snapshot) => [{
|
|
1538
1697
|
name: frameworkReducedStateReducerName,
|
|
1539
|
-
schemaVersion:
|
|
1698
|
+
schemaVersion: 7,
|
|
1540
1699
|
throughSeq: snapshot.reduced.lastSeq,
|
|
1541
1700
|
payload: encodeReducedStateCheckpoint(snapshot.reduced),
|
|
1542
1701
|
updatedAtMs: snapshot.updatedAtMs
|
|
@@ -1568,7 +1727,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1568
1727
|
const requestReducerCheckpointSnapshot = (snapshot) => Queue.offer(reducerCheckpointSnapshots, snapshot).pipe(Effect.asVoid);
|
|
1569
1728
|
const publishFreshDurables = (committed) => Effect.gen(function* () {
|
|
1570
1729
|
const current = yield* Ref.get(state);
|
|
1571
|
-
const fresh = Array.from(committed.filter((entry) => entry.position.seq > current.reduced.lastSeq)).sort((a, b) => a.position.seq - b.position.seq);
|
|
1730
|
+
const fresh = Array.from(new Map(committed.filter((entry) => entry.position.seq > current.reduced.lastSeq).map((entry) => [entry.position.seq, entry])).values()).sort((a, b) => a.position.seq - b.position.seq);
|
|
1572
1731
|
if (fresh.length === 0) return;
|
|
1573
1732
|
const nextReduced = foldReducedState(current.reduced, fresh);
|
|
1574
1733
|
const nextReducerStates = reducerRegistry.reduce(current.reducerStates, fresh);
|
|
@@ -1577,7 +1736,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1577
1736
|
reducerStates: nextReducerStates,
|
|
1578
1737
|
ephemeral: current.ephemeral
|
|
1579
1738
|
});
|
|
1580
|
-
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(
|
|
1739
|
+
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make({
|
|
1740
|
+
position: entry.position,
|
|
1741
|
+
event: durableEventEnvelope(entry.event)
|
|
1742
|
+
}));
|
|
1581
1743
|
return { head: nextReduced.lastSeq };
|
|
1582
1744
|
});
|
|
1583
1745
|
const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
@@ -1609,10 +1771,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1609
1771
|
const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
|
|
1610
1772
|
if (systemPrompt === void 0) return;
|
|
1611
1773
|
if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
|
|
1612
|
-
|
|
1774
|
+
const event = yield* events.systemMessageCommitted({
|
|
1613
1775
|
messageId: yield* ids.makeMessageId(),
|
|
1614
1776
|
content: systemPrompt
|
|
1615
|
-
})
|
|
1777
|
+
});
|
|
1778
|
+
yield* appendDurable(event);
|
|
1616
1779
|
});
|
|
1617
1780
|
const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
|
|
1618
1781
|
const current = yield* Ref.get(state);
|
|
@@ -1634,13 +1797,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1634
1797
|
}
|
|
1635
1798
|
});
|
|
1636
1799
|
yield* liveBus.publish(positioned);
|
|
1800
|
+
yield* sinkRegistry.publishEphemeralToSinks(positioned);
|
|
1637
1801
|
return positioned;
|
|
1638
1802
|
}));
|
|
1639
|
-
const publishEphemeral =
|
|
1640
|
-
const positioned = yield* publishEphemeralCore(event);
|
|
1641
|
-
yield* sinkRegistry.publishEphemeralToSinks(positioned, publishEphemeralCore);
|
|
1642
|
-
return positioned;
|
|
1643
|
-
});
|
|
1803
|
+
const publishEphemeral = publishEphemeralCore;
|
|
1644
1804
|
const wakeAfterCommandAdmission = () => Queue.offer(ingressSignals, void 0);
|
|
1645
1805
|
/** Use indexed store lookup for command idempotency instead of genesis replay. */
|
|
1646
1806
|
const findExistingCommandAdmission = (command) => Effect.gen(function* () {
|
|
@@ -1661,8 +1821,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1661
1821
|
}
|
|
1662
1822
|
const existing = yield* findExistingCommandAdmission(command);
|
|
1663
1823
|
if (existing !== void 0) {
|
|
1664
|
-
rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1665
|
-
return [existing.event];
|
|
1824
|
+
rememberPreparedCommand(durableEventEnvelope(existing.event), preparedByIdempotencyKey, preparedByCommandId);
|
|
1825
|
+
return [durableEventEnvelope(existing.event)];
|
|
1666
1826
|
}
|
|
1667
1827
|
const commandId = command.commandId ?? (yield* ids.makeCommandId());
|
|
1668
1828
|
const admitted = commandWithId(command, commandId);
|
|
@@ -1716,17 +1876,29 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1716
1876
|
submitted
|
|
1717
1877
|
];
|
|
1718
1878
|
});
|
|
1719
|
-
const submitBatch =
|
|
1879
|
+
const submitBatch = (input) => admissionGate.withPermits(1)(submitBatchAdmitted(input));
|
|
1880
|
+
const submitBatchAdmitted = Effect.fn(function* (input) {
|
|
1720
1881
|
const commandCount = input.filter(isEDACommand).length;
|
|
1721
1882
|
yield* annotateEdaSpan({
|
|
1722
1883
|
"eda.command.submittable_count": input.length,
|
|
1723
1884
|
"eda.command.count": commandCount,
|
|
1724
1885
|
"eda.event.app_owned_count": input.length - commandCount
|
|
1725
1886
|
});
|
|
1887
|
+
const admitted = [];
|
|
1888
|
+
for (const item of input) {
|
|
1889
|
+
if (isEDACommand(item)) {
|
|
1890
|
+
admitted.push(item);
|
|
1891
|
+
continue;
|
|
1892
|
+
}
|
|
1893
|
+
const event = appEventAdmission.admit(item);
|
|
1894
|
+
if (Result.isFailure(event)) return yield* appEventConflict(event.failure);
|
|
1895
|
+
admitted.push(event.success);
|
|
1896
|
+
}
|
|
1726
1897
|
const committed = yield* withAppendGate(Effect.gen(function* () {
|
|
1727
1898
|
const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1728
1899
|
const preparedByCommandId = /* @__PURE__ */ new Map();
|
|
1729
|
-
|
|
1900
|
+
const durableEvents = (yield* Effect.forEach(admitted, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat();
|
|
1901
|
+
return yield* commitDurableEntriesWithinGate(durableEvents.map((event) => ({ event })));
|
|
1730
1902
|
}));
|
|
1731
1903
|
yield* annotateEdaSpan(committedBatchAttributes(committed));
|
|
1732
1904
|
if (commandCount > 0) yield* wakeAfterCommandAdmission();
|
|
@@ -1735,14 +1907,149 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1735
1907
|
const admitCommand = (command) => Effect.gen(function* () {
|
|
1736
1908
|
return (yield* submitBatch([command]))[0];
|
|
1737
1909
|
});
|
|
1910
|
+
/** A tool's app fact: the same admission rules as `submit`, then the framework path. */
|
|
1911
|
+
const appendAppDurable = (event) => Effect.gen(function* () {
|
|
1912
|
+
const admitted = appEventAdmission.admit(event);
|
|
1913
|
+
if (Result.isFailure(admitted)) return yield* appEventConflict(admitted.failure);
|
|
1914
|
+
return yield* appendDurable(admitted.success);
|
|
1915
|
+
});
|
|
1916
|
+
/**
|
|
1917
|
+
* Run a registered decider: read the committed fold and append its marker and items as one
|
|
1918
|
+
* batch under the admission and append gates `submitBatch` takes, so nothing interleaves
|
|
1919
|
+
* between the read and the write. A retry with the same key finds the marker and returns the
|
|
1920
|
+
* stored result without deciding again. No decider error is a store error, so none is fatal.
|
|
1921
|
+
*/
|
|
1922
|
+
const decide = (decider, input) => Effect.gen(function* () {
|
|
1923
|
+
const fail = (reason, message) => new EDADeciderError({
|
|
1924
|
+
decider: decider.name,
|
|
1925
|
+
reason,
|
|
1926
|
+
message
|
|
1927
|
+
});
|
|
1928
|
+
if (deciders.get(decider.name) !== decider) return yield* fail("unknown_decider", `EDA decider ${decider.name} is not registered`);
|
|
1929
|
+
const idempotencyKey = yield* Effect.try({
|
|
1930
|
+
try: () => decider.idempotencyKey(input),
|
|
1931
|
+
catch: (cause) => fail("invalid_input", `idempotencyKey threw: ${String(cause)}`)
|
|
1932
|
+
});
|
|
1933
|
+
const keyViolation = deciderIdempotencyKeyViolation(idempotencyKey);
|
|
1934
|
+
if (keyViolation !== void 0) return yield* fail("invalid_input", keyViolation);
|
|
1935
|
+
const markerKey = EventDedupeKey.make(deciderMarkerDedupeKey(decider.name, idempotencyKey));
|
|
1936
|
+
yield* annotateEdaSpan({ "eda.decider.name": decider.name });
|
|
1937
|
+
const decided = yield* admissionGate.withPermits(1)(withAppendGate(Effect.gen(function* () {
|
|
1938
|
+
const accepted = yield* store.findEventByDedupeKey({
|
|
1939
|
+
namespace: effectDurableAgentNamespace,
|
|
1940
|
+
type: deciderAcceptedEventType,
|
|
1941
|
+
dedupeKey: markerKey
|
|
1942
|
+
});
|
|
1943
|
+
if (accepted !== void 0) {
|
|
1944
|
+
const marker = durableEventEnvelope(accepted.event);
|
|
1945
|
+
const stored = Schema.is(DeciderAcceptedEvent)(marker) ? marker.payload.result : void 0;
|
|
1946
|
+
return {
|
|
1947
|
+
outcome: {
|
|
1948
|
+
_tag: "Accepted",
|
|
1949
|
+
result: yield* Schema.decodeUnknownEffect(decider.result)(stored).pipe(Effect.mapError((cause) => fail("invalid_output", `stored result does not decode: ${cause.message}`))),
|
|
1950
|
+
acceptedSeq: accepted.position.seq,
|
|
1951
|
+
replayed: true
|
|
1952
|
+
},
|
|
1953
|
+
wake: false
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
const current = yield* Ref.get(state);
|
|
1957
|
+
const nowMs = yield* Clock.currentTimeMillis;
|
|
1958
|
+
const view = {
|
|
1959
|
+
sessionId: sessionContext.sessionId,
|
|
1960
|
+
nowMs,
|
|
1961
|
+
state: current.reduced,
|
|
1962
|
+
reducerStates: current.reducerStates
|
|
1963
|
+
};
|
|
1964
|
+
const decision = yield* Effect.try({
|
|
1965
|
+
try: () => decider.decide(view, input),
|
|
1966
|
+
catch: (cause) => fail("decide_threw", `decide threw: ${String(cause)}`)
|
|
1967
|
+
});
|
|
1968
|
+
if (decision._tag === "Reject") return {
|
|
1969
|
+
outcome: {
|
|
1970
|
+
_tag: "Rejected",
|
|
1971
|
+
rejection: decision.rejection
|
|
1972
|
+
},
|
|
1973
|
+
wake: false
|
|
1974
|
+
};
|
|
1975
|
+
const storedResult = encodeDeciderJson(decider.result, decision.result);
|
|
1976
|
+
if (Result.isFailure(storedResult)) return yield* fail("invalid_output", `result ${storedResult.failure}`);
|
|
1977
|
+
const resultBytes = jsonBytes(storedResult.success);
|
|
1978
|
+
if (resultBytes > 16384) return yield* fail("invalid_output", `encoded result is ${resultBytes} bytes; the limit is ${maxDeciderResultBytes} bytes`);
|
|
1979
|
+
const result = yield* Schema.decodeUnknownEffect(decider.result)(storedResult.success).pipe(Effect.mapError((cause) => fail("invalid_output", `result does not decode from its stored JSON: ${cause.message}`)));
|
|
1980
|
+
const wireResult = encodeDeciderJson(decider.result, result);
|
|
1981
|
+
if (Result.isFailure(wireResult)) return yield* fail("invalid_output", `result decoded from its stored JSON ${wireResult.failure}`);
|
|
1982
|
+
const trace = yield* currentOrRootEDAEventTrace;
|
|
1983
|
+
const createdAtMs = UnixEpochMillis.make(nowMs);
|
|
1984
|
+
const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1985
|
+
const preparedByCommandId = /* @__PURE__ */ new Map();
|
|
1986
|
+
const items = [];
|
|
1987
|
+
let hasCommand = false;
|
|
1988
|
+
for (const [index, item] of decision.items.entries()) {
|
|
1989
|
+
if (isDecidedCommand(item)) {
|
|
1990
|
+
hasCommand = true;
|
|
1991
|
+
items.push(...yield* prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId));
|
|
1992
|
+
continue;
|
|
1993
|
+
}
|
|
1994
|
+
const eventId = "eventId" in item && typeof item.eventId === "string" ? item.eventId : yield* ids.makeEventId();
|
|
1995
|
+
const event = yield* Effect.try({
|
|
1996
|
+
try: () => Schema.decodeUnknownSync(DurableEventEnvelope)(decider.encodeEvent({
|
|
1997
|
+
...item,
|
|
1998
|
+
eventId,
|
|
1999
|
+
sessionId: sessionContext.sessionId,
|
|
2000
|
+
createdAtMs,
|
|
2001
|
+
trace,
|
|
2002
|
+
durability: "durable"
|
|
2003
|
+
})),
|
|
2004
|
+
catch: (cause) => fail("invalid_output", `item ${index} is not an event of the decider's events schema: ${String(cause)}`)
|
|
2005
|
+
});
|
|
2006
|
+
const admitted = appEventAdmission.admit(event);
|
|
2007
|
+
if (Result.isFailure(admitted)) return yield* fail("invalid_output", `item ${index}: ${admitted.failure.message}`);
|
|
2008
|
+
items.push(admitted.success);
|
|
2009
|
+
}
|
|
2010
|
+
const marker = yield* Schema.decodeUnknownEffect(DeciderAcceptedEvent)({
|
|
2011
|
+
namespace: effectDurableAgentNamespace,
|
|
2012
|
+
type: deciderAcceptedEventType,
|
|
2013
|
+
schemaVersion: schemaV1,
|
|
2014
|
+
durability: "durable",
|
|
2015
|
+
eventId: yield* ids.makeEventId(),
|
|
2016
|
+
sessionId: sessionContext.sessionId,
|
|
2017
|
+
createdAtMs,
|
|
2018
|
+
trace,
|
|
2019
|
+
dedupeKey: markerKey,
|
|
2020
|
+
payload: {
|
|
2021
|
+
decider: decider.name,
|
|
2022
|
+
idempotencyKey,
|
|
2023
|
+
result: storedResult.success
|
|
2024
|
+
}
|
|
2025
|
+
}).pipe(Effect.mapError((cause) => fail("invalid_output", `encoded result is not JSON: ${cause.message}`)));
|
|
2026
|
+
const acceptedSeq = (yield* commitDurableEntriesWithinGate([marker, ...items].map((event) => ({ event }))))[0]?.position.seq;
|
|
2027
|
+
if (acceptedSeq === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("decider marker was not committed"));
|
|
2028
|
+
return {
|
|
2029
|
+
outcome: {
|
|
2030
|
+
_tag: "Accepted",
|
|
2031
|
+
result,
|
|
2032
|
+
acceptedSeq,
|
|
2033
|
+
replayed: false
|
|
2034
|
+
},
|
|
2035
|
+
wake: hasCommand
|
|
2036
|
+
};
|
|
2037
|
+
})));
|
|
2038
|
+
if (decided.wake) yield* wakeAfterCommandAdmission();
|
|
2039
|
+
return decided.outcome;
|
|
2040
|
+
});
|
|
1738
2041
|
const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
|
|
1739
2042
|
const sessionApi = {
|
|
2043
|
+
grantRun: (command, input) => grantRun(command, input),
|
|
2044
|
+
retryRunSchedulingDelivery: () => retryRunSchedulingDelivery(),
|
|
1740
2045
|
initialize,
|
|
1741
2046
|
submitBatch,
|
|
2047
|
+
decide,
|
|
1742
2048
|
admitCommand,
|
|
1743
2049
|
snapshot,
|
|
1744
2050
|
snapshotData,
|
|
1745
2051
|
appendDurable,
|
|
2052
|
+
appendAppDurable,
|
|
1746
2053
|
appendDurableBatch,
|
|
1747
2054
|
publishEphemeral,
|
|
1748
2055
|
drainReadyWork: (input) => drainReadyWork(input),
|
|
@@ -1778,9 +2085,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1778
2085
|
yield* requestCurrentReducerCheckpointSnapshot("startup-recovery-complete");
|
|
1779
2086
|
});
|
|
1780
2087
|
const maybeCompactAtBoundary = () => Effect.gen(function* () {
|
|
1781
|
-
const
|
|
2088
|
+
const data = yield* currentData();
|
|
2089
|
+
const current = data.reduced;
|
|
1782
2090
|
const next = (yield* compactionRunner.maybeCompact({
|
|
1783
2091
|
state: current,
|
|
2092
|
+
reducerStates: data.reducerStates,
|
|
1784
2093
|
context: yield* contextProjectionFor(current),
|
|
1785
2094
|
appendDurableEntries
|
|
1786
2095
|
})).length === 0 ? current : yield* currentReduced();
|
|
@@ -1788,25 +2097,29 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1788
2097
|
return next;
|
|
1789
2098
|
});
|
|
1790
2099
|
const cancelCommand = (commandId, reason) => Effect.gen(function* () {
|
|
1791
|
-
const
|
|
2100
|
+
const event = yield* events.commandCancelled({
|
|
1792
2101
|
commandId,
|
|
1793
2102
|
reason
|
|
1794
|
-
})
|
|
2103
|
+
});
|
|
2104
|
+
const committed = yield* appendDurable(event);
|
|
1795
2105
|
return SessionCommandCancelled.make({ committed });
|
|
1796
2106
|
});
|
|
1797
2107
|
const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
|
|
1798
2108
|
if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
|
|
1799
|
-
|
|
2109
|
+
const event = yield* events.turnFailed({
|
|
1800
2110
|
runId: active.runId,
|
|
1801
2111
|
turnId: active.turnId,
|
|
1802
2112
|
error: interruptionFailure("turn", reason, {
|
|
1803
2113
|
runId: active.runId,
|
|
1804
2114
|
turnId: active.turnId
|
|
1805
2115
|
})
|
|
1806
|
-
})
|
|
2116
|
+
});
|
|
2117
|
+
return yield* appendDurable(event);
|
|
1807
2118
|
});
|
|
1808
2119
|
const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
|
|
1809
|
-
const
|
|
2120
|
+
const runCompleted = yield* events.runCompleted({ runId });
|
|
2121
|
+
const commandCompleted = yield* events.commandCompleted({ commandId });
|
|
2122
|
+
const committed = yield* appendDurableBatch([runCompleted, commandCompleted]);
|
|
1810
2123
|
return SessionCommandCompleted.make({ committed: committed.at(-1) });
|
|
1811
2124
|
});
|
|
1812
2125
|
const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
|
|
@@ -1818,7 +2131,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1818
2131
|
commandId,
|
|
1819
2132
|
error
|
|
1820
2133
|
});
|
|
1821
|
-
const
|
|
2134
|
+
const current = yield* currentReduced();
|
|
2135
|
+
const failurePlan = planRunFailure(current);
|
|
1822
2136
|
const resumeEvents = [];
|
|
1823
2137
|
if (failurePlan.messageIdsToResume.length > 0) {
|
|
1824
2138
|
const resumeCommandId = yield* ids.makeCommandId();
|
|
@@ -1836,23 +2150,27 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1836
2150
|
});
|
|
1837
2151
|
const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
|
|
1838
2152
|
if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
|
|
1839
|
-
|
|
2153
|
+
const failed = yield* requireTurnFailed(turn.outcome.committed);
|
|
2154
|
+
return yield* failRunAndCommandWithError(commandId, runId, failed.event.payload.error);
|
|
1840
2155
|
});
|
|
1841
2156
|
const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
|
|
1842
2157
|
const failurePlan = planRunFailure(yield* currentReduced());
|
|
2158
|
+
const runFailed = yield* events.runFailed({
|
|
2159
|
+
runId: active.runId,
|
|
2160
|
+
error: interruptionFailure("run", reason, { runId: active.runId })
|
|
2161
|
+
});
|
|
2162
|
+
const commandCancelled = yield* events.commandCancelled({
|
|
2163
|
+
commandId: active.commandId,
|
|
2164
|
+
reason
|
|
2165
|
+
});
|
|
2166
|
+
const resume = failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2167
|
+
commandId: yield* ids.makeCommandId(),
|
|
2168
|
+
messageIds: failurePlan.messageIdsToResume
|
|
2169
|
+
}) })];
|
|
1843
2170
|
const committed = yield* appendDurableBatch([
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
}),
|
|
1848
|
-
yield* events.commandCancelled({
|
|
1849
|
-
commandId: active.commandId,
|
|
1850
|
-
reason
|
|
1851
|
-
}),
|
|
1852
|
-
...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
1853
|
-
commandId: yield* ids.makeCommandId(),
|
|
1854
|
-
messageIds: failurePlan.messageIdsToResume
|
|
1855
|
-
}) })]
|
|
2171
|
+
runFailed,
|
|
2172
|
+
commandCancelled,
|
|
2173
|
+
...resume
|
|
1856
2174
|
]);
|
|
1857
2175
|
return SessionCommandCancelled.make({ committed: committed.at(-1) });
|
|
1858
2176
|
});
|
|
@@ -1969,13 +2287,68 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1969
2287
|
});
|
|
1970
2288
|
return SessionForkedCommand.make({ commandId: input.commandId });
|
|
1971
2289
|
});
|
|
2290
|
+
const reconcileSchedulingWakeup = Effect.fnUntraced(function* () {
|
|
2291
|
+
const request = (yield* currentReduced()).runSchedulingRequest;
|
|
2292
|
+
yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
|
|
2293
|
+
});
|
|
2294
|
+
const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
|
|
2295
|
+
if (yield* Ref.get(recoveringInBackground)) return;
|
|
2296
|
+
yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
|
|
2297
|
+
const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2298
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2299
|
+
yield* reconcileSchedulingWakeup();
|
|
2300
|
+
return current?.deliveredSeq === void 0 ? current : void 0;
|
|
2301
|
+
}));
|
|
2302
|
+
if (request === void 0) return;
|
|
2303
|
+
const delivered = yield* Effect.exit(keepAlive.withActiveWork("run-scheduling-delivery", runScheduler.deliver({
|
|
2304
|
+
sessionId: sessionContext.sessionId,
|
|
2305
|
+
request: {
|
|
2306
|
+
requestId: request.requestId,
|
|
2307
|
+
work: request.work
|
|
2308
|
+
}
|
|
2309
|
+
}).pipe(Effect.timeout("10 seconds"))));
|
|
2310
|
+
if (Exit.isFailure(delivered)) {
|
|
2311
|
+
if (Cause.hasInterruptsOnly(delivered.cause)) return yield* Effect.interrupt;
|
|
2312
|
+
yield* controlGate.withPermits(1)(reconcileSchedulingWakeup());
|
|
2313
|
+
yield* Effect.logWarning("Run authorization delivery will retry on the durable host wakeup", {
|
|
2314
|
+
requestId: request.requestId,
|
|
2315
|
+
cause: Cause.pretty(delivered.cause)
|
|
2316
|
+
});
|
|
2317
|
+
return;
|
|
2318
|
+
}
|
|
2319
|
+
yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2320
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2321
|
+
if (current?.requestId === request.requestId && current.deliveredSeq === void 0) yield* appendDurable(yield* events.runSchedulingDelivered({ requestId: request.requestId }));
|
|
2322
|
+
yield* reconcileSchedulingWakeup();
|
|
2323
|
+
}));
|
|
2324
|
+
}));
|
|
2325
|
+
});
|
|
2326
|
+
const forkSchedulingDelivery = () => retryRunSchedulingDelivery().pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2327
|
+
yield* markFatalIfDurable(cause);
|
|
2328
|
+
yield* Effect.logError("Run authorization delivery worker failed", { cause: Cause.pretty(cause) });
|
|
2329
|
+
})), Effect.forkIn(runtimeScope), Effect.asVoid);
|
|
2330
|
+
const prepareRunSchedulingRequest = Effect.fnUntraced(function* (work) {
|
|
2331
|
+
yield* schedulingWakeup.setPending(true);
|
|
2332
|
+
return yield* events.runSchedulingRequested({
|
|
2333
|
+
requestId: yield* ids.makeRunRequestId(),
|
|
2334
|
+
work
|
|
2335
|
+
});
|
|
2336
|
+
});
|
|
2337
|
+
const deferRun = Effect.fnUntraced(function* (work) {
|
|
2338
|
+
yield* appendDurable(yield* prepareRunSchedulingRequest(work));
|
|
2339
|
+
yield* forkSchedulingDelivery();
|
|
2340
|
+
return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
2341
|
+
});
|
|
1972
2342
|
const startSubmitCommand = Effect.fn(function* (command, input) {
|
|
1973
2343
|
if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
|
|
1974
2344
|
const submit = command.command;
|
|
1975
2345
|
const commandId = command.commandId;
|
|
1976
|
-
yield* runScheduler.resolve({
|
|
2346
|
+
if ((yield* runScheduler.resolve({
|
|
1977
2347
|
sessionId: sessionContext.sessionId,
|
|
1978
2348
|
commandId
|
|
2349
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2350
|
+
_tag: "Command",
|
|
2351
|
+
commandId
|
|
1979
2352
|
});
|
|
1980
2353
|
yield* annotateEdaSpan({
|
|
1981
2354
|
"eda.command.id": commandId,
|
|
@@ -2006,13 +2379,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2006
2379
|
modelSelection: input.modelSelection,
|
|
2007
2380
|
trace: activeRunTrace.runTrace
|
|
2008
2381
|
});
|
|
2382
|
+
const startedEvents = yield* appendDurableBatch([
|
|
2383
|
+
commandStarted,
|
|
2384
|
+
...userMessage === void 0 ? [] : [userMessage],
|
|
2385
|
+
runStarted
|
|
2386
|
+
]);
|
|
2009
2387
|
return yield* startTurn({
|
|
2010
2388
|
commandId,
|
|
2011
|
-
commandStarted:
|
|
2012
|
-
commandStarted,
|
|
2013
|
-
...userMessage === void 0 ? [] : [userMessage],
|
|
2014
|
-
runStarted
|
|
2015
|
-
]))[0],
|
|
2389
|
+
commandStarted: startedEvents[0],
|
|
2016
2390
|
inputMessageIds: [messageId],
|
|
2017
2391
|
runId,
|
|
2018
2392
|
modelSelection: input.modelSelection,
|
|
@@ -2030,9 +2404,12 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2030
2404
|
return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
|
|
2031
2405
|
});
|
|
2032
2406
|
if (pending.length === 0) return yield* processInactiveStopCommand(command);
|
|
2033
|
-
yield* runScheduler.resolve({
|
|
2407
|
+
if ((yield* runScheduler.resolve({
|
|
2034
2408
|
sessionId: sessionContext.sessionId,
|
|
2035
2409
|
commandId: command.commandId
|
|
2410
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2411
|
+
_tag: "Command",
|
|
2412
|
+
commandId: command.commandId
|
|
2036
2413
|
});
|
|
2037
2414
|
const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
|
|
2038
2415
|
const runId = yield* ids.makeRunId();
|
|
@@ -2043,12 +2420,13 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2043
2420
|
runId
|
|
2044
2421
|
});
|
|
2045
2422
|
return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
|
|
2046
|
-
const
|
|
2423
|
+
const runStarted = yield* events.runStarted({
|
|
2047
2424
|
runId,
|
|
2048
2425
|
commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
|
|
2049
2426
|
modelSelection: input.modelSelection,
|
|
2050
2427
|
trace: activeRunTrace.runTrace
|
|
2051
|
-
})
|
|
2428
|
+
});
|
|
2429
|
+
const started = yield* appendDurableBatch([commandStarted, runStarted]);
|
|
2052
2430
|
return yield* startTurn({
|
|
2053
2431
|
commandId: command.commandId,
|
|
2054
2432
|
commandStarted: started[0],
|
|
@@ -2061,6 +2439,108 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2061
2439
|
});
|
|
2062
2440
|
}));
|
|
2063
2441
|
});
|
|
2442
|
+
const grantRun = Effect.fn("agent.run.grant")(function* (grant, input) {
|
|
2443
|
+
yield* annotateEdaSpan({
|
|
2444
|
+
"eda.session.id": sessionContext.sessionId,
|
|
2445
|
+
"eda.run_request.id": grant.requestId
|
|
2446
|
+
});
|
|
2447
|
+
return yield* controlGate.withPermits(1)(keepAlive.withActiveWork("run-authorization-grant", Effect.gen(function* () {
|
|
2448
|
+
yield* failIfFatal;
|
|
2449
|
+
const initial = yield* currentReduced();
|
|
2450
|
+
if (!canGrantRun(initial, grant.requestId)) return { _tag: "Stale" };
|
|
2451
|
+
const request = initial.runSchedulingRequest;
|
|
2452
|
+
if (request === void 0) return { _tag: "Stale" };
|
|
2453
|
+
const command = initial.commands.get(request.work.commandId);
|
|
2454
|
+
if (command?.command === void 0) return { _tag: "Stale" };
|
|
2455
|
+
const admitted = command.command;
|
|
2456
|
+
const predecessor = request.work._tag === "Recovery" ? initial.runs.get(request.work.interruptedRunId) : void 0;
|
|
2457
|
+
const modelSelection = predecessor?.modelSelection ?? initial.modelSelection ?? input.modelSelection;
|
|
2458
|
+
const runId = yield* ids.makeRunId();
|
|
2459
|
+
const trace = yield* startRunTrace({
|
|
2460
|
+
commandId: command.commandId,
|
|
2461
|
+
admissionTrace: command.admissionTrace,
|
|
2462
|
+
modelSelection,
|
|
2463
|
+
runId
|
|
2464
|
+
});
|
|
2465
|
+
return yield* closeRunTraceOnFailure(trace, Effect.gen(function* () {
|
|
2466
|
+
const started = yield* withAppendGate(Effect.gen(function* () {
|
|
2467
|
+
const current = yield* currentReduced();
|
|
2468
|
+
if (!canGrantRun(current, grant.requestId)) return void 0;
|
|
2469
|
+
const inputMessageIds = [...runSchedulingInputMessageIds(current, request.work)];
|
|
2470
|
+
const batch = [];
|
|
2471
|
+
let commandStarted;
|
|
2472
|
+
if (request.work._tag === "Recovery") {
|
|
2473
|
+
if (command.startedSeq === void 0 || predecessor === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization requires its started command and predecessor"));
|
|
2474
|
+
[commandStarted] = yield* store.loadCommittedEventsBySeq([command.startedSeq]);
|
|
2475
|
+
if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization is missing CommandStarted"));
|
|
2476
|
+
} else {
|
|
2477
|
+
batch.push(yield* events.commandStarted({ commandId: command.commandId }));
|
|
2478
|
+
if (admitted._tag === "SubmitMessage" && inputMessageIds.length === 0) {
|
|
2479
|
+
const messageId = yield* ids.makeMessageId();
|
|
2480
|
+
batch.push(yield* events.userMessageCommitted({
|
|
2481
|
+
commandId: command.commandId,
|
|
2482
|
+
messageId,
|
|
2483
|
+
content: admitted.content
|
|
2484
|
+
}));
|
|
2485
|
+
inputMessageIds.push(messageId);
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
batch.push(yield* events.runSchedulingGranted({
|
|
2489
|
+
requestId: request.requestId,
|
|
2490
|
+
runId
|
|
2491
|
+
}));
|
|
2492
|
+
const commandIds = predecessor?.commandIds ?? [command.commandId, ...admitted._tag === "ResumePendingMessages" ? inputMessageIds.flatMap((messageId) => {
|
|
2493
|
+
const message = current.messages.get(messageId);
|
|
2494
|
+
return message?._tag === "User" || message?._tag === "Steering" ? [message.commandId] : [];
|
|
2495
|
+
}) : []];
|
|
2496
|
+
batch.push(yield* events.runStarted({
|
|
2497
|
+
runId,
|
|
2498
|
+
commandIds,
|
|
2499
|
+
modelSelection,
|
|
2500
|
+
trace: trace.runTrace
|
|
2501
|
+
}));
|
|
2502
|
+
if (request.work._tag === "Recovery") batch.push(yield* events.recoveryCompleted({
|
|
2503
|
+
trigger: "runtime-restart",
|
|
2504
|
+
continuation: {
|
|
2505
|
+
commandId: command.commandId,
|
|
2506
|
+
interruptedRunId: request.work.interruptedRunId,
|
|
2507
|
+
replacementRunId: runId
|
|
2508
|
+
}
|
|
2509
|
+
}));
|
|
2510
|
+
const committed = yield* commitDurableEntriesWithinGate(batch.map((event) => ({ event })));
|
|
2511
|
+
commandStarted ??= committed[0];
|
|
2512
|
+
if (commandStarted === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Granted run must have CommandStarted"));
|
|
2513
|
+
return {
|
|
2514
|
+
commandStarted,
|
|
2515
|
+
inputMessageIds
|
|
2516
|
+
};
|
|
2517
|
+
}));
|
|
2518
|
+
if (started === void 0) {
|
|
2519
|
+
yield* Scope.close(trace.runScope, Exit.void);
|
|
2520
|
+
return { _tag: "Stale" };
|
|
2521
|
+
}
|
|
2522
|
+
yield* reconcileSchedulingWakeup();
|
|
2523
|
+
yield* startTurn({
|
|
2524
|
+
commandId: command.commandId,
|
|
2525
|
+
commandStarted: started.commandStarted,
|
|
2526
|
+
inputMessageIds: started.inputMessageIds,
|
|
2527
|
+
runId,
|
|
2528
|
+
modelSelection,
|
|
2529
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2530
|
+
runScope: trace.runScope,
|
|
2531
|
+
runSpan: trace.runSpan
|
|
2532
|
+
});
|
|
2533
|
+
yield* wakeAfterCommandAdmission();
|
|
2534
|
+
return {
|
|
2535
|
+
_tag: "Granted",
|
|
2536
|
+
runId
|
|
2537
|
+
};
|
|
2538
|
+
}));
|
|
2539
|
+
})).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2540
|
+
yield* markFatalIfDurable(cause);
|
|
2541
|
+
return yield* Effect.failCause(cause);
|
|
2542
|
+
}))));
|
|
2543
|
+
});
|
|
2064
2544
|
const processInactiveStopCommand = Effect.fn(function* (command) {
|
|
2065
2545
|
const commandId = command.commandId;
|
|
2066
2546
|
return (yield* startedBoundaryGuard({
|
|
@@ -2142,6 +2622,47 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2142
2622
|
turn: exit.value
|
|
2143
2623
|
};
|
|
2144
2624
|
});
|
|
2625
|
+
/**
|
|
2626
|
+
* Before failing what the dead runtime left open, re-invoke each started tool call whose tool
|
|
2627
|
+
* declares `ToolRecovery: "reinvoke"` and still has attempts left. Each commits its next start
|
|
2628
|
+
* before running, so a runtime that dies again mid-reinvocation spends that attempt. Calls that
|
|
2629
|
+
* finish here are terminal by the time recovery plans its batch; the rest are failed as before.
|
|
2630
|
+
*/
|
|
2631
|
+
const plannedReinvocations = Effect.fnUntraced(function* (reduced) {
|
|
2632
|
+
const calls = [];
|
|
2633
|
+
for (const tool of planSessionRecovery(reduced).openToolCalls) {
|
|
2634
|
+
const decision = tool.decision;
|
|
2635
|
+
if (decision?._tag !== "Created" || decision.providerExecuted) continue;
|
|
2636
|
+
if (tool.startedSeq === void 0 || tool.startedAtMs === void 0) continue;
|
|
2637
|
+
const attempt = (tool.attempt ?? 1) + 1;
|
|
2638
|
+
if (attempt > 3) continue;
|
|
2639
|
+
if ((yield* turnRunner.toolRecoveryPolicy(decision.toolName)) !== "reinvoke") continue;
|
|
2640
|
+
calls.push({
|
|
2641
|
+
seq: decision.seq,
|
|
2642
|
+
resume: {
|
|
2643
|
+
attempt,
|
|
2644
|
+
firstStartedAtMs: tool.startedAtMs,
|
|
2645
|
+
firstStartedSeq: tool.startedSeq
|
|
2646
|
+
}
|
|
2647
|
+
});
|
|
2648
|
+
}
|
|
2649
|
+
return calls;
|
|
2650
|
+
});
|
|
2651
|
+
const resumeInterruptedToolCalls = Effect.fnUntraced(function* (calls) {
|
|
2652
|
+
yield* annotateEdaSpan({ "eda.recovery.reinvoked_tool_calls": calls.length });
|
|
2653
|
+
if (calls.length === 0) return;
|
|
2654
|
+
const created = yield* store.loadCommittedEventsBySeq(calls.map((call) => call.seq));
|
|
2655
|
+
yield* turnRunner.resumeToolCalls({
|
|
2656
|
+
calls: calls.flatMap((call) => {
|
|
2657
|
+
const event = created.find((entry) => entry.position.seq === call.seq);
|
|
2658
|
+
return event === void 0 ? [] : [{
|
|
2659
|
+
created: event,
|
|
2660
|
+
resume: call.resume
|
|
2661
|
+
}];
|
|
2662
|
+
}),
|
|
2663
|
+
eventSink: sessionApi
|
|
2664
|
+
}).pipe(Effect.catchTag("ToolExecutionEventNotCreated", (error) => Effect.die(error)));
|
|
2665
|
+
});
|
|
2145
2666
|
const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
|
|
2146
2667
|
const plan = planSessionRecovery(reduced);
|
|
2147
2668
|
input = {
|
|
@@ -2229,11 +2750,17 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2229
2750
|
commandId: yield* ids.makeCommandId(),
|
|
2230
2751
|
messageIds: plan.messageIdsToResume
|
|
2231
2752
|
}) }));
|
|
2232
|
-
|
|
2753
|
+
const resolution = plan.continuation === void 0 ? void 0 : yield* runScheduler.resolve({
|
|
2233
2754
|
sessionId: sessionContext.sessionId,
|
|
2234
2755
|
commandId: plan.continuation.command.commandId
|
|
2235
2756
|
});
|
|
2236
|
-
|
|
2757
|
+
if (plan.continuation !== void 0 && resolution?._tag === "Deferred") recoveryEvents.push(yield* prepareRunSchedulingRequest({
|
|
2758
|
+
_tag: "Recovery",
|
|
2759
|
+
commandId: plan.continuation.command.commandId,
|
|
2760
|
+
interruptedRunId: plan.continuation.run.runId,
|
|
2761
|
+
inputMessageIds: plan.continuation.inputMessageIds
|
|
2762
|
+
}));
|
|
2763
|
+
const continuationRunId = plan.continuation === void 0 || resolution?._tag === "Deferred" ? void 0 : yield* ids.makeRunId();
|
|
2237
2764
|
const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
|
|
2238
2765
|
admissionTrace: plan.continuation.command.admissionTrace,
|
|
2239
2766
|
commandId: plan.continuation.command.commandId,
|
|
@@ -2256,6 +2783,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2256
2783
|
} }
|
|
2257
2784
|
}));
|
|
2258
2785
|
const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
|
|
2786
|
+
if (resolution?._tag === "Deferred") yield* forkSchedulingDelivery();
|
|
2259
2787
|
const nextPlan = planSessionRecovery(yield* currentReduced());
|
|
2260
2788
|
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"));
|
|
2261
2789
|
return {
|
|
@@ -2317,7 +2845,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2317
2845
|
return (yield* startedBoundaryGuard({
|
|
2318
2846
|
start: events.commandStarted({ commandId }),
|
|
2319
2847
|
body: (started) => Effect.gen(function* () {
|
|
2320
|
-
const
|
|
2848
|
+
const completed = yield* events.commandCompleted({ commandId });
|
|
2849
|
+
const committed = yield* appendDurableBatch([completed]);
|
|
2321
2850
|
return {
|
|
2322
2851
|
started,
|
|
2323
2852
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2334,13 +2863,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2334
2863
|
})).value;
|
|
2335
2864
|
});
|
|
2336
2865
|
const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
|
|
2337
|
-
const
|
|
2866
|
+
const failed = yield* events.commandFailed({
|
|
2338
2867
|
commandId,
|
|
2339
2868
|
error: FailurePayload.make({
|
|
2340
2869
|
code,
|
|
2341
2870
|
message
|
|
2342
2871
|
})
|
|
2343
|
-
})
|
|
2872
|
+
});
|
|
2873
|
+
const committed = yield* appendDurable(failed);
|
|
2344
2874
|
return SessionCommandFailed.make({ committed });
|
|
2345
2875
|
});
|
|
2346
2876
|
const cancelPendingMessage = Effect.fn(function* (command) {
|
|
@@ -2366,12 +2896,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2366
2896
|
commandId: target.commandId,
|
|
2367
2897
|
reason: "pending message cancelled"
|
|
2368
2898
|
})] : [];
|
|
2899
|
+
const schedulingPlan = planRunSchedulingCancellation(current, target.messageId);
|
|
2900
|
+
const schedulingEvents = [];
|
|
2901
|
+
if (schedulingPlan !== void 0) {
|
|
2902
|
+
schedulingEvents.push(yield* events.runSchedulingInvalidated({
|
|
2903
|
+
requestId: schedulingPlan.requestId,
|
|
2904
|
+
reason: "message-cancelled"
|
|
2905
|
+
}));
|
|
2906
|
+
if (schedulingPlan.cancelCommandId !== void 0) schedulingEvents.push(yield* events.commandCancelled({
|
|
2907
|
+
commandId: schedulingPlan.cancelCommandId,
|
|
2908
|
+
reason: "pending recovery inputs cancelled"
|
|
2909
|
+
}));
|
|
2910
|
+
if (schedulingPlan.replacementWork !== void 0) schedulingEvents.push(yield* prepareRunSchedulingRequest(schedulingPlan.replacementWork));
|
|
2911
|
+
}
|
|
2369
2912
|
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2370
2913
|
const committed = yield* appendDurableBatch([
|
|
2371
2914
|
cancelled,
|
|
2372
2915
|
...originCancelled,
|
|
2916
|
+
...schedulingEvents,
|
|
2373
2917
|
completed
|
|
2374
2918
|
]);
|
|
2919
|
+
if (schedulingEvents.length > 0) {
|
|
2920
|
+
yield* reconcileSchedulingWakeup();
|
|
2921
|
+
yield* forkSchedulingDelivery();
|
|
2922
|
+
}
|
|
2375
2923
|
return {
|
|
2376
2924
|
started,
|
|
2377
2925
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2394,17 +2942,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2394
2942
|
return (yield* startedBoundaryGuard({
|
|
2395
2943
|
start: events.commandStarted({ commandId: controlCommandId }),
|
|
2396
2944
|
body: (started) => Effect.gen(function* () {
|
|
2397
|
-
const
|
|
2945
|
+
const current = yield* currentReduced();
|
|
2946
|
+
const target = current.messages.get(promotion.messageId);
|
|
2398
2947
|
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
2948
|
started,
|
|
2400
2949
|
outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
|
|
2401
2950
|
};
|
|
2402
|
-
const
|
|
2951
|
+
const promoted = yield* events.userMessagePromoted({
|
|
2403
2952
|
commandId: controlCommandId,
|
|
2404
2953
|
messageId: target.messageId,
|
|
2405
2954
|
from: "queue",
|
|
2406
2955
|
to: "steer"
|
|
2407
|
-
})
|
|
2956
|
+
});
|
|
2957
|
+
const resumed = promotionNeedsResumeCommand(current, target.messageId) ? [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2958
|
+
commandId: yield* ids.makeCommandId(),
|
|
2959
|
+
messageIds: [target.messageId]
|
|
2960
|
+
}) })] : [];
|
|
2961
|
+
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2962
|
+
const committed = yield* appendDurableBatch([
|
|
2963
|
+
promoted,
|
|
2964
|
+
...resumed,
|
|
2965
|
+
completed
|
|
2966
|
+
]);
|
|
2408
2967
|
return {
|
|
2409
2968
|
started,
|
|
2410
2969
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2431,25 +2990,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2431
2990
|
return (yield* startedBoundaryGuard({
|
|
2432
2991
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2433
2992
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2434
|
-
const
|
|
2435
|
-
|
|
2993
|
+
const beforeStop = yield* currentReduced();
|
|
2994
|
+
const requested = activeTurnIdentityForCommand(beforeStop, active.commandId);
|
|
2995
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2436
2996
|
commandId: stopCommandId,
|
|
2437
2997
|
...requested === void 0 ? {} : {
|
|
2438
2998
|
runId: requested.runId,
|
|
2439
2999
|
turnId: requested.turnId
|
|
2440
3000
|
}
|
|
2441
|
-
})
|
|
3001
|
+
});
|
|
3002
|
+
yield* appendDurable(requestedEvent);
|
|
2442
3003
|
yield* Scope.close(active.turnScope, Exit.interrupt());
|
|
2443
3004
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2444
3005
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2445
3006
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2446
|
-
const
|
|
2447
|
-
const
|
|
3007
|
+
const afterStop = yield* currentReduced();
|
|
3008
|
+
const applied = activeTurnIdentityForCommand(afterStop, active.commandId);
|
|
3009
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2448
3010
|
commandId: stopCommandId,
|
|
2449
3011
|
runId: active.runId,
|
|
2450
3012
|
turnId: active.turnId,
|
|
2451
3013
|
...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
|
|
2452
|
-
})
|
|
3014
|
+
});
|
|
3015
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
3016
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2453
3017
|
return {
|
|
2454
3018
|
started,
|
|
2455
3019
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2476,19 +3040,22 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2476
3040
|
return (yield* startedBoundaryGuard({
|
|
2477
3041
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2478
3042
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2479
|
-
|
|
3043
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2480
3044
|
commandId: stopCommandId,
|
|
2481
3045
|
runId: active.runId,
|
|
2482
3046
|
turnId: active.turnId
|
|
2483
|
-
})
|
|
3047
|
+
});
|
|
3048
|
+
yield* appendDurable(requestedEvent);
|
|
2484
3049
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2485
3050
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2486
3051
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2487
|
-
const
|
|
3052
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2488
3053
|
commandId: stopCommandId,
|
|
2489
3054
|
runId: active.runId,
|
|
2490
3055
|
turnId: active.turnId
|
|
2491
|
-
})
|
|
3056
|
+
});
|
|
3057
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
3058
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2492
3059
|
return {
|
|
2493
3060
|
started,
|
|
2494
3061
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2570,6 +3137,32 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2570
3137
|
default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
|
|
2571
3138
|
}
|
|
2572
3139
|
});
|
|
3140
|
+
const interruptWaitingRun = Effect.fnUntraced(function* (control, reason) {
|
|
3141
|
+
const plan = planWaitingRunInterruption(yield* currentReduced(), control.commandId);
|
|
3142
|
+
if (plan === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Waiting interruption requires a current reservation"));
|
|
3143
|
+
const isStop = control.command._tag === "StopTurn";
|
|
3144
|
+
const batch = [];
|
|
3145
|
+
if (isStop) batch.push(yield* events.commandStarted({ commandId: control.commandId }));
|
|
3146
|
+
batch.push(yield* events.runSchedulingInvalidated({
|
|
3147
|
+
requestId: plan.requestId,
|
|
3148
|
+
reason
|
|
3149
|
+
}));
|
|
3150
|
+
const [firstMessageId, ...restMessageIds] = plan.messageIds;
|
|
3151
|
+
if (firstMessageId !== void 0) batch.push(yield* events.pendingMessagesPaused({
|
|
3152
|
+
interruptionCommandId: control.commandId,
|
|
3153
|
+
runRequestId: plan.requestId,
|
|
3154
|
+
messageIds: [firstMessageId, ...restMessageIds],
|
|
3155
|
+
reason: "user-interrupted"
|
|
3156
|
+
}));
|
|
3157
|
+
if (plan.cancelCommandId !== void 0) batch.push(yield* events.commandCancelled({
|
|
3158
|
+
commandId: plan.cancelCommandId,
|
|
3159
|
+
reason
|
|
3160
|
+
}));
|
|
3161
|
+
if (isStop) batch.push(yield* events.commandCompleted({ commandId: control.commandId }));
|
|
3162
|
+
const committed = yield* appendDurableBatch(batch);
|
|
3163
|
+
yield* reconcileSchedulingWakeup();
|
|
3164
|
+
return committed;
|
|
3165
|
+
});
|
|
2573
3166
|
const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
|
|
2574
3167
|
const execution = yield* inspectExecutionState();
|
|
2575
3168
|
const current = yield* currentReduced();
|
|
@@ -2629,6 +3222,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2629
3222
|
});
|
|
2630
3223
|
}
|
|
2631
3224
|
}
|
|
3225
|
+
if (current.runSchedulingRequest !== void 0) {
|
|
3226
|
+
const control = waitingRunControl(current);
|
|
3227
|
+
if (control === void 0) return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3228
|
+
switch (control.command._tag) {
|
|
3229
|
+
case "CancelPendingMessage": return yield* cancelPendingMessage(control);
|
|
3230
|
+
case "PromotePendingMessage": return yield* promotePendingMessage(control);
|
|
3231
|
+
case "StopTurn": {
|
|
3232
|
+
const committed = yield* interruptWaitingRun(control, "stopped");
|
|
3233
|
+
const started = committed[0];
|
|
3234
|
+
const completed = committed.at(-1);
|
|
3235
|
+
if (started === void 0 || completed === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Stopping a waiting request must commit its control lifecycle"));
|
|
3236
|
+
return {
|
|
3237
|
+
started,
|
|
3238
|
+
outcome: SessionCommandCompleted.make({ committed: completed })
|
|
3239
|
+
};
|
|
3240
|
+
}
|
|
3241
|
+
case "SubmitMessage":
|
|
3242
|
+
yield* interruptWaitingRun(control, "interrupted");
|
|
3243
|
+
return yield* startSubmitCommand(control, input);
|
|
3244
|
+
default: return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3245
|
+
}
|
|
3246
|
+
}
|
|
2632
3247
|
const decision = decideDispatch(current);
|
|
2633
3248
|
switch (decision._tag) {
|
|
2634
3249
|
case "DispatchBlockedByActiveCommand":
|
|
@@ -2658,7 +3273,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2658
3273
|
yield* failIfFatal;
|
|
2659
3274
|
const processed = [];
|
|
2660
3275
|
while (true) {
|
|
2661
|
-
const result = yield* withFatalRecording(drainOneReadyCommand(input));
|
|
3276
|
+
const result = yield* controlGate.withPermits(1)(withFatalRecording(drainOneReadyCommand(input)));
|
|
2662
3277
|
if (isSessionNoRunnableCommand(result)) {
|
|
2663
3278
|
yield* annotateEdaSpan({
|
|
2664
3279
|
"eda.command.processed_count": processed.length,
|
|
@@ -2680,12 +3295,20 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2680
3295
|
"eda.model.id": input.modelSelection.modelId
|
|
2681
3296
|
});
|
|
2682
3297
|
yield* failIfFatal;
|
|
2683
|
-
const initial = yield*
|
|
3298
|
+
const { initial, recovery } = yield* admissionGate.withPermits(1)(Effect.gen(function* () {
|
|
3299
|
+
const initial = yield* currentReduced();
|
|
3300
|
+
return {
|
|
3301
|
+
initial,
|
|
3302
|
+
recovery: yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, {
|
|
3303
|
+
...input,
|
|
3304
|
+
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
3305
|
+
}))
|
|
3306
|
+
};
|
|
3307
|
+
}));
|
|
2684
3308
|
input = {
|
|
2685
3309
|
...input,
|
|
2686
3310
|
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
2687
3311
|
};
|
|
2688
|
-
const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
|
|
2689
3312
|
yield* requestStartupRecoveryCheckpointIfNeeded();
|
|
2690
3313
|
if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
|
|
2691
3314
|
});
|
|
@@ -2722,12 +3345,32 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2722
3345
|
}
|
|
2723
3346
|
});
|
|
2724
3347
|
const start = Effect.fn(function* (input) {
|
|
2725
|
-
yield*
|
|
2726
|
-
|
|
3348
|
+
const reinvocations = yield* plannedReinvocations(yield* currentReduced());
|
|
3349
|
+
if (reinvocations.length === 0) {
|
|
3350
|
+
yield* runStartupRecovery(input);
|
|
3351
|
+
yield* forkSchedulingDelivery();
|
|
3352
|
+
yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
|
|
3353
|
+
return;
|
|
3354
|
+
}
|
|
3355
|
+
yield* controlGate.take(1);
|
|
3356
|
+
yield* Ref.set(recoveringInBackground, true);
|
|
3357
|
+
yield* Effect.gen(function* () {
|
|
3358
|
+
yield* annotateRunInput(input);
|
|
3359
|
+
yield* initialize(input);
|
|
3360
|
+
yield* keepAlive.withActiveWork("session-recovery", Effect.gen(function* () {
|
|
3361
|
+
yield* withFatalRecording(resumeInterruptedToolCalls(reinvocations));
|
|
3362
|
+
yield* runStartupRecoveryPass(input);
|
|
3363
|
+
}));
|
|
3364
|
+
}).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* () {
|
|
3365
|
+
const message = `EDA background startup recovery failed: ${Cause.pretty(cause)}`;
|
|
3366
|
+
yield* markFatalIfDurable(cause);
|
|
3367
|
+
yield* Ref.update(fatalInvariantViolation, (current) => current ?? message);
|
|
3368
|
+
yield* Effect.logError(message);
|
|
3369
|
+
})), Effect.withSpan("agent.session.recover.tools"), Effect.forkIn(runtimeScope));
|
|
2727
3370
|
});
|
|
2728
3371
|
yield* sinkRegistry.startSinkRunners({
|
|
2729
3372
|
appendDurableBatch,
|
|
2730
|
-
|
|
3373
|
+
initialProjection: yield* Ref.get(state),
|
|
2731
3374
|
publishEphemeral: publishEphemeralCore,
|
|
2732
3375
|
scope: runtimeScope
|
|
2733
3376
|
});
|
|
@@ -2744,10 +3387,10 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
|
|
|
2744
3387
|
});
|
|
2745
3388
|
const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
|
|
2746
3389
|
const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
|
|
2747
|
-
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
2748
|
-
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
3390
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
|
|
3391
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2749
3392
|
return {
|
|
2750
|
-
state:
|
|
3393
|
+
state: yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, foldReducedState)),
|
|
2751
3394
|
checkpointSeq
|
|
2752
3395
|
};
|
|
2753
3396
|
});
|
|
@@ -2757,10 +3400,10 @@ const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
|
|
|
2757
3400
|
const schemaVersion = reducerSchemaVersion(reducer);
|
|
2758
3401
|
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? reducer.initial : decodeReducerState(reducer, checkpoint.payload);
|
|
2759
3402
|
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2760
|
-
const
|
|
3403
|
+
const state = yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, (current, page) => page.reduce(reducer.reduce, current)));
|
|
2761
3404
|
return [
|
|
2762
3405
|
reducer.name,
|
|
2763
|
-
|
|
3406
|
+
state,
|
|
2764
3407
|
checkpointSeq
|
|
2765
3408
|
];
|
|
2766
3409
|
}));
|
|
@@ -2771,6 +3414,8 @@ const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
|
|
|
2771
3414
|
};
|
|
2772
3415
|
});
|
|
2773
3416
|
const isEDACommand = (input) => "_tag" in input;
|
|
3417
|
+
/** Decider items are commands (tagged classes) or untagged event drafts. */
|
|
3418
|
+
const isDecidedCommand = (item) => "_tag" in item;
|
|
2774
3419
|
const commandWithId = (command, commandId) => {
|
|
2775
3420
|
switch (command._tag) {
|
|
2776
3421
|
case "SubmitMessage": return new SubmitMessageCommand({
|
|
@@ -2804,7 +3449,7 @@ const commandWithId = (command, commandId) => {
|
|
|
2804
3449
|
}
|
|
2805
3450
|
};
|
|
2806
3451
|
const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
|
|
2807
|
-
if (
|
|
3452
|
+
if (!Schema.is(CommandAdmittedEvent)(event)) return;
|
|
2808
3453
|
const command = event.payload.command;
|
|
2809
3454
|
if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
|
|
2810
3455
|
if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
|
|
@@ -2827,6 +3472,6 @@ const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succee
|
|
|
2827
3472
|
const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
|
|
2828
3473
|
const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
|
|
2829
3474
|
//#endregion
|
|
2830
|
-
export {
|
|
3475
|
+
export { SessionForkedCommand as a, SessionRunInput as c, InferenceRunner as d, ToolExecutor as f, SessionCommandOutcome as i, SessionState as l, SessionCommandCompleted as n, SessionNoRunnableCommand as o, LiveEventBus as p, SessionCommandFailed as r, SessionNoRunnableReason as s, SessionCommandCancelled as t, TurnRunner as u };
|
|
2831
3476
|
|
|
2832
|
-
//# sourceMappingURL=session-state-
|
|
3477
|
+
//# sourceMappingURL=session-state-D02LCVcC.js.map
|