effect-durable-agent 0.1.0-alpha.8 → 0.1.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-63iEDHHl.js} +63 -13
- package/dist/compaction-63iEDHHl.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-2ZILvoRD.js +507 -0
- package/dist/delivery-2ZILvoRD.js.map +1 -0
- package/dist/delivery-D3MxW4wg.d.ts +3026 -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 +936 -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-168Womqp.d.ts} +8535 -2859
- package/dist/{durable-BGFvX7Mh.js → durable-D13w1Qr3.js} +229 -15
- package/dist/durable-D13w1Qr3.js.map +1 -0
- package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
- package/dist/envelope-BCzKUq_z.js.map +1 -0
- package/dist/{envelope-DkZyMIgp.d.ts → envelope-Che6KatU.d.ts} +70 -7
- package/dist/{event-factory-DTFdy0Cb.js → event-factory-_vF1bIJ7.js} +7 -3
- package/dist/event-factory-_vF1bIJ7.js.map +1 -0
- package/dist/{events-LZFNoESe.d.ts → events-DwTARLMv.d.ts} +139 -137
- package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
- package/dist/in-memory-CeODnZhE.js +150 -0
- package/dist/in-memory-CeODnZhE.js.map +1 -0
- package/dist/index.d.ts +8 -8
- package/dist/index.js +6 -6
- package/dist/interpreter-DKGJ1sSx.js +1452 -0
- package/dist/interpreter-DKGJ1sSx.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-DeBDK8XO.d.ts} +11 -5
- package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
- package/dist/records--54mZEBx.js +675 -0
- package/dist/records--54mZEBx.js.map +1 -0
- package/dist/reduced-state-B1cvy8N_.d.ts +51110 -0
- package/dist/reduced-state-schema-B98exWxQ.d.ts +2338 -0
- package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-DhGVzHBV.d.ts} +12 -6
- package/dist/run-scheduling-wakeup-Mjic4tb_.d.ts +24 -0
- package/dist/services/compaction.d.ts +2 -2
- package/dist/services/compaction.js +2 -2
- 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 -0
- package/dist/services/run-scheduler.js +25 -0
- package/dist/services/run-scheduler.js.map +1 -0
- package/dist/services/run-scheduling-wakeup.d.ts +2 -0
- package/dist/services/run-scheduling-wakeup.js +13 -0
- package/dist/services/run-scheduling-wakeup.js.map +1 -0
- package/dist/services/runtime-layer.d.ts +18 -31
- package/dist/services/runtime-layer.js +19 -13
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +31 -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 +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +127 -37
- 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 +6 -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-event-observer-DaFMKKNc.d.ts → session-event-observer-DlP9ITB2.d.ts} +3 -3
- package/dist/{session-state-aIqe9CLa.js → session-state-BehvUVyq.js} +669 -160
- package/dist/session-state-BehvUVyq.js.map +1 -0
- package/dist/session-store-BL6sfrnn.d.ts +3326 -0
- package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-DvuHwvx_.d.ts} +3 -4
- package/dist/sink-registry-DskRcyOS.js +345 -0
- package/dist/sink-registry-DskRcyOS.js.map +1 -0
- package/dist/subscription-DZNWFDTV.d.ts +966 -0
- package/dist/subscription-DmO3BcdT.js +505 -0
- package/dist/subscription-DmO3BcdT.js.map +1 -0
- package/dist/testkit/layers.d.ts +31 -22
- package/dist/testkit/layers.js +23 -14
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.d.ts +226 -0
- package/dist/testkit/transcript.js +1475 -0
- package/dist/testkit/transcript.js.map +1 -0
- package/dist/{tool-registry-BJaVNtw4.d.ts → tool-registry-CHHUU9BN.d.ts} +44 -8
- package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
- package/dist/transcript.d.ts +101 -0
- package/dist/transcript.js +107 -0
- package/dist/transcript.js.map +1 -0
- package/dist/types/commands.d.ts +2 -2
- package/dist/types/commands.js +8 -3
- package/dist/types/commands.js.map +1 -1
- package/dist/types/core.d.ts +2 -2
- package/dist/types/core.js +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-Brov9VdQ.d.ts +113 -0
- package/dist/window-read-DPFAA1hM.js +264 -0
- package/dist/window-read-DPFAA1hM.js.map +1 -0
- package/package.json +42 -14
- package/dist/command-queues-DdDB_aYM.d.ts +0 -462
- package/dist/compaction-BEor3jKv.d.ts +0 -165
- package/dist/compaction-BgDr5VJy.js.map +0 -1
- 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-pFzsPlDs.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/runtime-DbTCb32-.d.ts +0 -63
- package/dist/session-query-l8xpJYp8.d.ts +0 -45
- package/dist/session-state-YHFzOGDf.d.ts +0 -861
- package/dist/session-state-aIqe9CLa.js.map +0 -1
- package/dist/session-store-Cpi_NwTR.d.ts +0 -206
- package/dist/sink-registry-NDgeyzO0.js +0 -272
- package/dist/sink-registry-NDgeyzO0.js.map +0 -1
- package/dist/sink-registry-T1wOUuzq.d.ts +0 -133
|
@@ -1,37 +1,43 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RunSchedulingWakeup } from "./services/run-scheduling-wakeup.js";
|
|
2
2
|
import { CommandId, InferenceId, MessageId, 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";
|
|
5
|
+
import { ModelResolver } from "./services/model-resolver.js";
|
|
3
6
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
4
|
-
import {
|
|
7
|
+
import { d as PositionedEvent, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
|
|
5
8
|
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
9
|
+
import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-D13w1Qr3.js";
|
|
10
|
+
import { n as assertNeverError, t as assertNever } from "./assert-never-CoyUpoRB.js";
|
|
11
|
+
import { activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, initialReducedState, reducedStateCheckpointEventSeqs } from "./domain/reduced-state.js";
|
|
8
12
|
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
9
|
-
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError } from "./services/session-store.js";
|
|
10
|
-
import {
|
|
13
|
+
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
|
|
14
|
+
import { o as CompactionRunner, p as makeUsagePayload } from "./compaction-63iEDHHl.js";
|
|
15
|
+
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
16
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
|
|
17
|
+
import { EDAToolRegistry, toolRecoveryPolicy } from "./services/tool-registry.js";
|
|
11
18
|
import { IdGenerator } from "./services/id-generator.js";
|
|
12
|
-
import { n as SessionContext, t as EventFactory } from "./event-factory-DTFdy0Cb.js";
|
|
13
19
|
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
14
20
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
15
|
-
import {
|
|
16
|
-
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
21
|
+
import { SessionEventObserver } from "./services/session-event-observer.js";
|
|
17
22
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
18
|
-
import {
|
|
23
|
+
import { n as EDASinkRegistry } from "./sink-registry-DskRcyOS.js";
|
|
19
24
|
import * as Context from "effect/Context";
|
|
20
25
|
import * as Effect from "effect/Effect";
|
|
21
26
|
import * as Layer from "effect/Layer";
|
|
22
27
|
import * as Schema from "effect/Schema";
|
|
23
28
|
import * as Stream from "effect/Stream";
|
|
24
|
-
import * as Prompt from "effect/
|
|
29
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
30
|
+
import * as Exit from "effect/Exit";
|
|
25
31
|
import * as Cause from "effect/Cause";
|
|
26
32
|
import * as Clock from "effect/Clock";
|
|
27
|
-
import * as Exit from "effect/Exit";
|
|
28
33
|
import * as Fiber from "effect/Fiber";
|
|
29
34
|
import * as Queue from "effect/Queue";
|
|
30
35
|
import * as Ref from "effect/Ref";
|
|
31
36
|
import * as Scope from "effect/Scope";
|
|
32
37
|
import * as Semaphore from "effect/Semaphore";
|
|
33
38
|
import * as Option from "effect/Option";
|
|
34
|
-
import * as
|
|
39
|
+
import * as PubSub from "effect/PubSub";
|
|
40
|
+
import * as Response from "effect/ai/Response";
|
|
35
41
|
//#region src/domain/dispatch-policy.ts
|
|
36
42
|
/** Durable/runtime evidence for active work blocking new queued commands. */
|
|
37
43
|
const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
|
|
@@ -109,6 +115,15 @@ const decideDispatch = (state) => {
|
|
|
109
115
|
command: toCandidate(next)
|
|
110
116
|
};
|
|
111
117
|
};
|
|
118
|
+
/** Promotion must retain a live or pending execution owner when the original command is terminal. */
|
|
119
|
+
const promotionNeedsResumeCommand = (state, messageId) => {
|
|
120
|
+
if (state.commandQueues.active?.runId !== void 0) return false;
|
|
121
|
+
const target = state.messages.get(messageId);
|
|
122
|
+
if (target?._tag !== "User" && target?._tag !== "Steering") return false;
|
|
123
|
+
const waiting = state.runSchedulingRequest?.work;
|
|
124
|
+
if (waiting?._tag === "Recovery" && waiting.inputMessageIds.includes(messageId)) return false;
|
|
125
|
+
return !state.commandQueues.pendingCommands.some((pending) => pending.commandId === target.commandId || pending.command._tag === "ResumePendingMessages" && pending.command.messageIds.includes(messageId));
|
|
126
|
+
};
|
|
112
127
|
const nextIdleCommand = (state) => {
|
|
113
128
|
const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
|
|
114
129
|
for (const message of state.commandQueues.pendingSteers) {
|
|
@@ -219,9 +234,9 @@ const planSessionRecovery = (state) => {
|
|
|
219
234
|
const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
|
|
220
235
|
const sourceMessageIds = continuationCommand?.command?._tag === "ResumePendingMessages" ? continuationCommand.command.messageIds.filter((messageId) => pendingMessageIds.has(messageId)) : continuationCommand === void 0 ? [] : [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].filter((message) => message.commandId === continuationCommand.commandId).map((message) => message.messageId);
|
|
221
236
|
const eligibleSteerIds = continuationRun === void 0 ? [] : state.commandQueues.pendingSteers.filter((message) => message.targetRunId === void 0 || message.targetRunId === continuationRun.runId || continuationRun.commandIds.some((commandId) => state.runs.get(message.targetRunId)?.commandIds.includes(commandId) === true)).map((message) => message.messageId);
|
|
222
|
-
const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
237
|
+
const continuationInputMessageIds = Array.from(/* @__PURE__ */ new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
223
238
|
const continuationInputIds = new Set(continuationInputMessageIds);
|
|
224
|
-
const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
|
|
239
|
+
const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !(state.runSchedulingRequest?.work._tag === "Recovery" && state.runSchedulingRequest.work.inputMessageIds.includes(message.messageId)) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
|
|
225
240
|
return {
|
|
226
241
|
activeCommands: recoverable.activeCommands,
|
|
227
242
|
activeRuns: recoverable.activeRuns,
|
|
@@ -247,6 +262,60 @@ const planRunFailure = (state) => ({ messageIdsToResume: state.commandQueues.pen
|
|
|
247
262
|
/** Normal explicit Stop/Interrupt policy. This is not startup recovery. */
|
|
248
263
|
const planUserInterruption = (state) => ({ messageIdsToPause: [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) });
|
|
249
264
|
//#endregion
|
|
265
|
+
//#region src/services/live-event-bus.ts
|
|
266
|
+
/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
|
|
267
|
+
const activeTurnEphemeralReplayCapacity = 4096;
|
|
268
|
+
/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
|
|
269
|
+
var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
|
|
270
|
+
static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
|
|
271
|
+
const pubsub = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
|
|
272
|
+
const activeTurnReplay = yield* Ref.make({
|
|
273
|
+
events: [],
|
|
274
|
+
overflowed: false
|
|
275
|
+
});
|
|
276
|
+
const observer = yield* SessionEventObserver;
|
|
277
|
+
return makeLiveBus(pubsub, activeTurnReplay, observer);
|
|
278
|
+
}));
|
|
279
|
+
/** Live bus for hosts that do not install an append-driven observer. */
|
|
280
|
+
static Noop = LiveEventBus.Live.pipe(Layer.provide(SessionEventObserver.Noop));
|
|
281
|
+
};
|
|
282
|
+
const makeLiveBus = (pubsub, activeTurnReplay, observer) => ({
|
|
283
|
+
publish: (event) => Effect.gen(function* () {
|
|
284
|
+
yield* updateActiveTurnReplay(activeTurnReplay, event);
|
|
285
|
+
yield* observer.onEvent(event);
|
|
286
|
+
return yield* PubSub.publish(pubsub, event);
|
|
287
|
+
}),
|
|
288
|
+
subscribeQueue: () => PubSub.subscribe(pubsub),
|
|
289
|
+
subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
|
|
290
|
+
activeTurnReplay: () => Ref.get(activeTurnReplay)
|
|
291
|
+
});
|
|
292
|
+
const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
|
|
293
|
+
const nextActiveTurnReplay = (state, event) => {
|
|
294
|
+
if (Schema.is(TurnStartedEvent)(event.event)) return {
|
|
295
|
+
turnId: event.event.payload.turnId,
|
|
296
|
+
events: [],
|
|
297
|
+
overflowed: false
|
|
298
|
+
};
|
|
299
|
+
if (Schema.is(TurnCompletedEvent)(event.event) || Schema.is(TurnFailedEvent)(event.event) || Schema.is(TurnStoppedEvent)(event.event)) {
|
|
300
|
+
const turnId = event.event.payload.turnId;
|
|
301
|
+
return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
|
|
302
|
+
events: [],
|
|
303
|
+
overflowed: false
|
|
304
|
+
} : state;
|
|
305
|
+
}
|
|
306
|
+
if (event.event.durability !== "ephemeral" || state.turnId === void 0) return state;
|
|
307
|
+
const events = [...state.events, event];
|
|
308
|
+
if (events.length <= 4096) return {
|
|
309
|
+
...state,
|
|
310
|
+
events
|
|
311
|
+
};
|
|
312
|
+
return {
|
|
313
|
+
...state,
|
|
314
|
+
events: events.slice(events.length - activeTurnEphemeralReplayCapacity),
|
|
315
|
+
overflowed: true
|
|
316
|
+
};
|
|
317
|
+
};
|
|
318
|
+
//#endregion
|
|
250
319
|
//#region src/services/started-boundary-guard.ts
|
|
251
320
|
/** Build a guard bound to the session's durable append boundary. */
|
|
252
321
|
const makeStartedBoundaryGuard = (state) => (spec) => {
|
|
@@ -305,13 +374,14 @@ Schema.Union([
|
|
|
305
374
|
ToolExecutionSkipped
|
|
306
375
|
]);
|
|
307
376
|
/** Failure when tool execution receives a committed event that is not ToolCallCreated. */
|
|
308
|
-
var ToolExecutionEventNotCreated = class extends Schema.
|
|
377
|
+
var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
|
|
309
378
|
/** Construct the live tool-executor implementation. */
|
|
310
379
|
const makeLiveToolExecutor = Effect.gen(function* () {
|
|
311
380
|
const events = yield* EventFactory;
|
|
312
381
|
const ids = yield* IdGenerator;
|
|
313
382
|
const registry = yield* EDAToolRegistry;
|
|
314
383
|
const session = yield* SessionContext;
|
|
384
|
+
const store = yield* EDASessionStore;
|
|
315
385
|
const failToolCall = (input, created, error) => Effect.gen(function* () {
|
|
316
386
|
const event = yield* events.toolCallFailed({
|
|
317
387
|
toolCallId: created.event.payload.toolCallId,
|
|
@@ -326,7 +396,8 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
326
396
|
yield* annotateEdaSpan({
|
|
327
397
|
"eda.tool_call.id": created.event.payload.toolCallId,
|
|
328
398
|
"eda.tool.name": created.event.payload.promptPart.name,
|
|
329
|
-
"eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted
|
|
399
|
+
"eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted,
|
|
400
|
+
...input.resume === void 0 ? {} : { "eda.tool.attempt": input.resume.attempt }
|
|
330
401
|
});
|
|
331
402
|
if (created.event.payload.promptPart.providerExecuted) {
|
|
332
403
|
const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
|
|
@@ -337,13 +408,20 @@ const makeLiveToolExecutor = Effect.gen(function* () {
|
|
|
337
408
|
};
|
|
338
409
|
}
|
|
339
410
|
const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
|
|
340
|
-
start: events.toolCallStarted({
|
|
411
|
+
start: events.toolCallStarted({
|
|
412
|
+
toolCallId: created.event.payload.toolCallId,
|
|
413
|
+
...input.resume === void 0 ? {} : { attempt: input.resume.attempt }
|
|
414
|
+
}),
|
|
341
415
|
body: () => Effect.gen(function* () {
|
|
342
416
|
const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
|
|
343
417
|
toolCallId: created.event.payload.toolCallId,
|
|
418
|
+
runId: created.event.payload.runId,
|
|
419
|
+
turnId: created.event.payload.turnId,
|
|
420
|
+
queryEvents: (schema, options) => queryCommittedEvents(store, schema, options),
|
|
344
421
|
sessionId: session.sessionId,
|
|
345
422
|
makeEventId: ids.makeEventId,
|
|
346
|
-
emitDurable: input.eventSink.appendDurable
|
|
423
|
+
emitDurable: input.eventSink.appendDurable,
|
|
424
|
+
...input.resume === void 0 ? {} : { recovery: input.resume }
|
|
347
425
|
}).pipe(Effect.map((result) => ({
|
|
348
426
|
_tag: "Succeeded",
|
|
349
427
|
result
|
|
@@ -404,6 +482,7 @@ const toolCompletedPromptPart = (created, result) => ({
|
|
|
404
482
|
id: created.event.payload.promptPart.id,
|
|
405
483
|
name: created.event.payload.promptPart.name,
|
|
406
484
|
isFailure: false,
|
|
485
|
+
providerExecuted: false,
|
|
407
486
|
result
|
|
408
487
|
}),
|
|
409
488
|
id: created.event.payload.promptPart.id,
|
|
@@ -415,6 +494,7 @@ const toolFailedPromptPart = (created, error) => ({
|
|
|
415
494
|
id: created.event.payload.promptPart.id,
|
|
416
495
|
name: created.event.payload.promptPart.name,
|
|
417
496
|
isFailure: true,
|
|
497
|
+
providerExecuted: false,
|
|
418
498
|
result: error
|
|
419
499
|
}),
|
|
420
500
|
id: created.event.payload.promptPart.id,
|
|
@@ -596,7 +676,8 @@ const recordToolParamsEnd = (state, input) => {
|
|
|
596
676
|
};
|
|
597
677
|
const recordToolCall = (state, input) => {
|
|
598
678
|
const draft = state.drafts.get(input.providerPartId);
|
|
599
|
-
const
|
|
679
|
+
const toolCallId = draft?.toolCallId ?? input.toolCallId;
|
|
680
|
+
const decision = makeToolCallDecision(state, input, toolCallId);
|
|
600
681
|
const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
|
|
601
682
|
const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
|
|
602
683
|
return {
|
|
@@ -713,6 +794,7 @@ const toolRejectedPromptPart = (decision) => ({
|
|
|
713
794
|
id: decision.providerPartId,
|
|
714
795
|
name: decision.toolName,
|
|
715
796
|
isFailure: true,
|
|
797
|
+
providerExecuted: false,
|
|
716
798
|
result: {
|
|
717
799
|
message: decision.error.message,
|
|
718
800
|
reason: decision.reason,
|
|
@@ -750,7 +832,7 @@ const InferenceRunResult = Schema.Struct({
|
|
|
750
832
|
partsRecorded: NonNegativeInt,
|
|
751
833
|
terminal: InferenceRunTerminal
|
|
752
834
|
});
|
|
753
|
-
Schema.
|
|
835
|
+
Schema.TaggedError()("UnsupportedInferencePart", {
|
|
754
836
|
partType: Schema.String,
|
|
755
837
|
reason: Schema.String
|
|
756
838
|
});
|
|
@@ -970,7 +1052,8 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
970
1052
|
type: "error",
|
|
971
1053
|
error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
|
|
972
1054
|
});
|
|
973
|
-
|
|
1055
|
+
const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []);
|
|
1056
|
+
return yield* requireTerminal(terminal);
|
|
974
1057
|
});
|
|
975
1058
|
return { runInference: Effect.fn("agent.inference")(function* (input) {
|
|
976
1059
|
const languageModel = yield* models.resolve(input.modelSelection);
|
|
@@ -994,8 +1077,9 @@ const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
|
994
1077
|
});
|
|
995
1078
|
const body = (started) => Effect.gen(function* () {
|
|
996
1079
|
const toolkit = yield* toolRegistry.getModelToolkit();
|
|
1080
|
+
const prompt = models.preparePrompt?.(input.modelSelection, Prompt.make(input.prompt));
|
|
997
1081
|
const state = yield* languageModel.streamText({
|
|
998
|
-
prompt: input.prompt,
|
|
1082
|
+
prompt: prompt ?? input.prompt,
|
|
999
1083
|
disableToolCallResolution: true,
|
|
1000
1084
|
...toolkit === void 0 ? {} : { toolkit }
|
|
1001
1085
|
}).pipe(Stream.map((part) => part)).pipe(Stream.catchIf(isProviderStreamFailure, (error) => Stream.make(makeProviderErrorPart(error))), Stream.runFoldEffect(() => initialState, (current, part) => recordPart(input.eventSink, current, part, (next) => Ref.set(stateRef, next)).pipe(Effect.tap((next) => Ref.set(stateRef, next)))));
|
|
@@ -1042,7 +1126,8 @@ var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-d
|
|
|
1042
1126
|
};
|
|
1043
1127
|
const inferenceUsageAttributes = (terminal) => {
|
|
1044
1128
|
if (terminal._tag !== "InferenceRunFinished") return {};
|
|
1045
|
-
|
|
1129
|
+
const completed = terminal.committed.find((entry) => entry.event.type === "InferenceCompleted");
|
|
1130
|
+
return usageAttributes(completed?.event.type === "InferenceCompleted" ? completed.event.payload.usage : void 0);
|
|
1046
1131
|
};
|
|
1047
1132
|
const initialRunInferenceState = (identity) => ({
|
|
1048
1133
|
inference: initialInferenceState(identity),
|
|
@@ -1052,12 +1137,12 @@ const initialRunInferenceState = (identity) => ({
|
|
|
1052
1137
|
});
|
|
1053
1138
|
const recordResponseContext = (entries, part) => {
|
|
1054
1139
|
switch (part.type) {
|
|
1055
|
-
case "text-start":
|
|
1056
|
-
case "text-
|
|
1057
|
-
case "text-
|
|
1058
|
-
case "reasoning-start":
|
|
1059
|
-
case "reasoning-
|
|
1060
|
-
case "reasoning-
|
|
1140
|
+
case "text-start":
|
|
1141
|
+
case "text-end": return upsertTextualResponseEntry(entries, "Text", part.id, "", part.metadata);
|
|
1142
|
+
case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta, part.metadata);
|
|
1143
|
+
case "reasoning-start":
|
|
1144
|
+
case "reasoning-end": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "", part.metadata);
|
|
1145
|
+
case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta, part.metadata);
|
|
1061
1146
|
case "tool-call": return part.providerExecuted ? entries : [...entries, {
|
|
1062
1147
|
_tag: "ResponsePart",
|
|
1063
1148
|
part
|
|
@@ -1075,24 +1160,50 @@ const recordResponseContext = (entries, part) => {
|
|
|
1075
1160
|
default: throw assertNeverError(part, "response context part");
|
|
1076
1161
|
}
|
|
1077
1162
|
};
|
|
1078
|
-
|
|
1163
|
+
/**
|
|
1164
|
+
* Folds one textual stream part into its entry. Provider metadata from start, delta and end parts
|
|
1165
|
+
* is merged per provider so replay keeps signatures, item ids and encrypted reasoning.
|
|
1166
|
+
*/
|
|
1167
|
+
const upsertTextualResponseEntry = (entries, tag, providerPartId, delta, metadata) => {
|
|
1079
1168
|
const index = entries.findIndex((entry) => (entry._tag === "Text" || entry._tag === "Reasoning") && entry._tag === tag && entry.providerPartId === providerPartId);
|
|
1080
1169
|
if (index === -1) return [...entries, {
|
|
1081
1170
|
_tag: tag,
|
|
1082
1171
|
providerPartId,
|
|
1083
|
-
text: delta
|
|
1172
|
+
text: delta,
|
|
1173
|
+
metadata: metadata ?? {}
|
|
1084
1174
|
}];
|
|
1085
1175
|
const current = entries[index];
|
|
1086
1176
|
if (current._tag !== tag) return entries;
|
|
1087
1177
|
return entries.map((entry, entryIndex) => entryIndex === index ? {
|
|
1088
1178
|
...current,
|
|
1089
|
-
text: `${current.text}${delta}
|
|
1179
|
+
text: `${current.text}${delta}`,
|
|
1180
|
+
metadata: mergeProviderMetadata(current.metadata, metadata)
|
|
1090
1181
|
} : entry);
|
|
1091
1182
|
};
|
|
1183
|
+
const mergeProviderMetadata = (left, right) => {
|
|
1184
|
+
if (right === void 0) return left;
|
|
1185
|
+
const merged = { ...left };
|
|
1186
|
+
for (const [provider, value] of Object.entries(right)) {
|
|
1187
|
+
const previous = merged[provider];
|
|
1188
|
+
merged[provider] = isMetadataRecord(previous) && isMetadataRecord(value) ? {
|
|
1189
|
+
...previous,
|
|
1190
|
+
...value
|
|
1191
|
+
} : value;
|
|
1192
|
+
}
|
|
1193
|
+
return merged;
|
|
1194
|
+
};
|
|
1195
|
+
const isMetadataRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1196
|
+
const hasProviderMetadata = (metadata) => Object.keys(metadata).length > 0;
|
|
1092
1197
|
const responseContextToParts = (entries) => entries.flatMap((entry) => {
|
|
1093
1198
|
switch (entry._tag) {
|
|
1094
|
-
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1095
|
-
|
|
1199
|
+
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", {
|
|
1200
|
+
text: entry.text,
|
|
1201
|
+
metadata: entry.metadata
|
|
1202
|
+
})];
|
|
1203
|
+
case "Reasoning": return entry.text.length === 0 && !hasProviderMetadata(entry.metadata) ? [] : [Response.makePart("reasoning", {
|
|
1204
|
+
text: entry.text,
|
|
1205
|
+
metadata: entry.metadata
|
|
1206
|
+
})];
|
|
1096
1207
|
case "ResponsePart": return [entry.part];
|
|
1097
1208
|
default: throw assertNeverError(entry, "response context entry");
|
|
1098
1209
|
}
|
|
@@ -1141,7 +1252,6 @@ const makeResponseMetadata = (part) => ({
|
|
|
1141
1252
|
id: part.id,
|
|
1142
1253
|
modelId: part.modelId,
|
|
1143
1254
|
timestamp: part.timestamp,
|
|
1144
|
-
request: part.request,
|
|
1145
1255
|
metadata: part.metadata
|
|
1146
1256
|
});
|
|
1147
1257
|
const makeFinishMetadata = (part) => ({
|
|
@@ -1173,6 +1283,7 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1173
1283
|
const events = yield* EventFactory;
|
|
1174
1284
|
const inferenceRunner = yield* InferenceRunner;
|
|
1175
1285
|
const toolExecutor = yield* ToolExecutor;
|
|
1286
|
+
const toolRegistry = yield* EDAToolRegistry;
|
|
1176
1287
|
const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
|
|
1177
1288
|
const usage = inferenceCompleted.event.payload.usage;
|
|
1178
1289
|
const turnCompleted = yield* events.turnCompleted({
|
|
@@ -1291,55 +1402,66 @@ const makeLiveTurnRunner = Effect.gen(function* () {
|
|
|
1291
1402
|
return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
|
|
1292
1403
|
});
|
|
1293
1404
|
});
|
|
1294
|
-
return {
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
const
|
|
1310
|
-
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1311
|
-
const inference = yield* inferenceRunner.runInference({
|
|
1312
|
-
...turnIdentity,
|
|
1313
|
-
inferenceId,
|
|
1314
|
-
prompt: input.prompt,
|
|
1315
|
-
eventSink: input.eventSink,
|
|
1316
|
-
modelSelection: input.modelSelection
|
|
1317
|
-
});
|
|
1318
|
-
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1319
|
-
return TurnRunResult.make({
|
|
1320
|
-
started: input.started,
|
|
1321
|
-
inference,
|
|
1322
|
-
outcome
|
|
1323
|
-
});
|
|
1324
|
-
}).pipe(Effect.tap((result) => Effect.gen(function* () {
|
|
1405
|
+
return {
|
|
1406
|
+
toolRecoveryPolicy: (toolName) => toolRegistry.getModelToolkit().pipe(Effect.map((toolkit) => toolRecoveryPolicy(toolkit, toolName))),
|
|
1407
|
+
resumeToolCalls: ({ calls, eventSink }) => Effect.forEach(calls, ({ created, resume }) => toolExecutor.executeCreated({
|
|
1408
|
+
created,
|
|
1409
|
+
eventSink,
|
|
1410
|
+
resume
|
|
1411
|
+
}), {
|
|
1412
|
+
concurrency: maxToolExecutionConcurrency,
|
|
1413
|
+
discard: true
|
|
1414
|
+
}),
|
|
1415
|
+
runTurn: Effect.fn("agent.turn")(function* (input) {
|
|
1416
|
+
const turnIdentity = {
|
|
1417
|
+
runId: input.runId,
|
|
1418
|
+
turnId: input.turnId
|
|
1419
|
+
};
|
|
1420
|
+
const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
|
|
1325
1421
|
yield* annotateEdaSpan({
|
|
1326
|
-
"eda.
|
|
1327
|
-
"eda.
|
|
1328
|
-
"eda.provider
|
|
1329
|
-
|
|
1422
|
+
"eda.run.id": input.runId,
|
|
1423
|
+
"eda.turn.id": input.turnId,
|
|
1424
|
+
"eda.model.provider": input.modelSelection?.provider,
|
|
1425
|
+
"eda.model.id": input.modelSelection?.modelId,
|
|
1426
|
+
"eda.tool.max_calls_per_run": maxToolCallsPerRun
|
|
1330
1427
|
});
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1428
|
+
const inferencesStarted = yield* Ref.make(0);
|
|
1429
|
+
return yield* Effect.gen(function* () {
|
|
1430
|
+
const inferenceId = yield* ids.makeInferenceId();
|
|
1431
|
+
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1432
|
+
const inference = yield* inferenceRunner.runInference({
|
|
1335
1433
|
...turnIdentity,
|
|
1336
|
-
|
|
1434
|
+
inferenceId,
|
|
1435
|
+
prompt: input.prompt,
|
|
1436
|
+
eventSink: input.eventSink,
|
|
1437
|
+
modelSelection: input.modelSelection
|
|
1337
1438
|
});
|
|
1338
|
-
yield* input
|
|
1339
|
-
return
|
|
1439
|
+
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1440
|
+
return TurnRunResult.make({
|
|
1441
|
+
started: input.started,
|
|
1442
|
+
inference,
|
|
1443
|
+
outcome
|
|
1444
|
+
});
|
|
1445
|
+
}).pipe(Effect.tap((result) => Effect.gen(function* () {
|
|
1446
|
+
yield* annotateEdaSpan({
|
|
1447
|
+
"eda.turn.outcome": result.outcome._tag,
|
|
1448
|
+
"eda.inference.started_count": yield* Ref.get(inferencesStarted),
|
|
1449
|
+
"eda.provider.parts_recorded": result.inference.partsRecorded,
|
|
1450
|
+
...turnUsageAttributes(result)
|
|
1451
|
+
});
|
|
1452
|
+
})), Effect.catchCause((cause) => {
|
|
1453
|
+
if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
|
|
1454
|
+
return Effect.uninterruptible(Effect.gen(function* () {
|
|
1455
|
+
const terminal = yield* events.turnFailed({
|
|
1456
|
+
...turnIdentity,
|
|
1457
|
+
error: failurePayloadFromCause(cause)
|
|
1458
|
+
});
|
|
1459
|
+
yield* input.eventSink.appendDurable(terminal);
|
|
1460
|
+
return yield* Effect.failCause(cause);
|
|
1461
|
+
}));
|
|
1340
1462
|
}));
|
|
1341
|
-
})
|
|
1342
|
-
}
|
|
1463
|
+
})
|
|
1464
|
+
};
|
|
1343
1465
|
});
|
|
1344
1466
|
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
1345
1467
|
var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
|
|
@@ -1381,6 +1503,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
|
|
|
1381
1503
|
id: created.event.payload.promptPart.id,
|
|
1382
1504
|
name: created.event.payload.promptPart.name,
|
|
1383
1505
|
isFailure: true,
|
|
1506
|
+
providerExecuted: false,
|
|
1384
1507
|
result
|
|
1385
1508
|
}),
|
|
1386
1509
|
id: created.event.payload.promptPart.id,
|
|
@@ -1394,11 +1517,11 @@ const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
|
|
|
1394
1517
|
if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
|
|
1395
1518
|
return created;
|
|
1396
1519
|
});
|
|
1397
|
-
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
|
|
1398
|
-
const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
|
|
1399
|
-
const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
|
|
1400
|
-
const isToolCallCreated = (committed) => committed.event.
|
|
1401
|
-
const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
|
|
1520
|
+
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.type === "TurnCompleted" ? result.outcome.committed.event.payload.usage : void 0) : {};
|
|
1521
|
+
const isInferenceCompleted = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceCompletedEventType;
|
|
1522
|
+
const isInferenceFailed = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === inferenceFailedEventType;
|
|
1523
|
+
const isToolCallCreated = (committed) => committed.event.namespace === "effect-durable-agent" && Schema.is(ToolCallCreatedEvent)(committed.event);
|
|
1524
|
+
const isToolCallRejected = (committed) => committed.event.namespace === "effect-durable-agent" && committed.event.type === toolCallRejectedEventType;
|
|
1402
1525
|
const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
|
|
1403
1526
|
const requireInferenceCompleted = (committed) => {
|
|
1404
1527
|
const completed = committed.find(isInferenceCompleted);
|
|
@@ -1429,7 +1552,11 @@ const SessionCommandOutcome = Schema.Union([
|
|
|
1429
1552
|
SessionCommandCancelled
|
|
1430
1553
|
]);
|
|
1431
1554
|
/** Why a control drain stopped without starting more command work. */
|
|
1432
|
-
const SessionNoRunnableReason = Schema.Literals([
|
|
1555
|
+
const SessionNoRunnableReason = Schema.Literals([
|
|
1556
|
+
"active-command",
|
|
1557
|
+
"no-pending-command",
|
|
1558
|
+
"awaiting-run-authorization"
|
|
1559
|
+
]);
|
|
1433
1560
|
/** Session control result when no admitted command is runnable. */
|
|
1434
1561
|
const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
|
|
1435
1562
|
reason: SessionNoRunnableReason,
|
|
@@ -1437,7 +1564,7 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
|
|
|
1437
1564
|
});
|
|
1438
1565
|
/** Control result when command execution was started in an active child scope. */
|
|
1439
1566
|
const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
|
|
1440
|
-
var SessionCommandAdmissionConflict = class extends Schema.
|
|
1567
|
+
var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
|
|
1441
1568
|
code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
|
|
1442
1569
|
message: Schema.String,
|
|
1443
1570
|
pausedMessageIds: Schema.Array(MessageId)
|
|
@@ -1456,6 +1583,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
|
|
|
1456
1583
|
id: decision.providerPartId,
|
|
1457
1584
|
name: decision.toolName,
|
|
1458
1585
|
isFailure: true,
|
|
1586
|
+
providerExecuted: false,
|
|
1459
1587
|
result: error
|
|
1460
1588
|
}),
|
|
1461
1589
|
id: decision.providerPartId,
|
|
@@ -1493,10 +1621,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1493
1621
|
const compactionRunner = yield* CompactionRunner;
|
|
1494
1622
|
const promptProjector = yield* EDAPromptProjector;
|
|
1495
1623
|
const sessionContext = yield* SessionContext;
|
|
1624
|
+
const runScheduler = yield* RunScheduler;
|
|
1625
|
+
const schedulingWakeup = yield* RunSchedulingWakeup;
|
|
1496
1626
|
const reducerRegistry = yield* EDAReducerRegistry;
|
|
1497
1627
|
const sinkRegistry = yield* EDASinkRegistry;
|
|
1498
|
-
const hydrated = yield*
|
|
1499
|
-
|
|
1628
|
+
const { hydrated, hydratedReducerStates } = yield* Effect.gen(function* () {
|
|
1629
|
+
const hydrated = yield* hydrateFrameworkReducedState(store);
|
|
1630
|
+
const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
|
|
1631
|
+
yield* Effect.annotateCurrentSpan({
|
|
1632
|
+
"eda.seq.head": hydrated.state.lastSeq,
|
|
1633
|
+
"eda.checkpoint.framework_seq": hydrated.checkpointSeq,
|
|
1634
|
+
...hydratedReducerStates.checkpointSeq === void 0 ? {} : { "eda.checkpoint.app_min_seq": hydratedReducerStates.checkpointSeq }
|
|
1635
|
+
});
|
|
1636
|
+
return {
|
|
1637
|
+
hydrated,
|
|
1638
|
+
hydratedReducerStates
|
|
1639
|
+
};
|
|
1640
|
+
}).pipe(Effect.withSpan("agent.session.hydrate", { attributes: {
|
|
1641
|
+
sessionId: sessionContext.sessionId,
|
|
1642
|
+
"eda.session.id": sessionContext.sessionId,
|
|
1643
|
+
"eda.reducers.count": reducerRegistry.reducers.length
|
|
1644
|
+
} }));
|
|
1645
|
+
yield* schedulingWakeup.setPending(hydrated.state.runSchedulingRequest !== void 0 && hydrated.state.runSchedulingRequest.deliveredSeq === void 0);
|
|
1500
1646
|
const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
|
|
1501
1647
|
const state = yield* Ref.make({
|
|
1502
1648
|
reduced: hydrated.state,
|
|
@@ -1507,6 +1653,16 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1507
1653
|
}
|
|
1508
1654
|
});
|
|
1509
1655
|
const gate = yield* Semaphore.make(1);
|
|
1656
|
+
const controlGate = yield* Semaphore.make(1);
|
|
1657
|
+
/**
|
|
1658
|
+
* Admission versus startup repair: recovery plans its repair batch from a snapshot and then
|
|
1659
|
+
* checks the result reached a fixed point, so no command may be admitted in between. Recovery
|
|
1660
|
+
* that finishes in the background (re-invoked tools) would otherwise race live admission.
|
|
1661
|
+
*/
|
|
1662
|
+
const admissionGate = yield* Semaphore.make(1);
|
|
1663
|
+
/** Set while startup recovery finishes in the background holding the control gate. */
|
|
1664
|
+
const recoveringInBackground = yield* Ref.make(false);
|
|
1665
|
+
const deliveryGate = yield* Semaphore.make(1);
|
|
1510
1666
|
const ingressSignals = yield* Queue.sliding(1);
|
|
1511
1667
|
const reducerCheckpointSnapshots = yield* Queue.sliding(1);
|
|
1512
1668
|
const executionState = yield* Ref.make({ _tag: "Idle" });
|
|
@@ -1534,7 +1690,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1534
1690
|
}));
|
|
1535
1691
|
const buildReducerCheckpointSnapshot = (snapshot) => [{
|
|
1536
1692
|
name: frameworkReducedStateReducerName,
|
|
1537
|
-
schemaVersion:
|
|
1693
|
+
schemaVersion: 7,
|
|
1538
1694
|
throughSeq: snapshot.reduced.lastSeq,
|
|
1539
1695
|
payload: encodeReducedStateCheckpoint(snapshot.reduced),
|
|
1540
1696
|
updatedAtMs: snapshot.updatedAtMs
|
|
@@ -1575,7 +1731,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1575
1731
|
reducerStates: nextReducerStates,
|
|
1576
1732
|
ephemeral: current.ephemeral
|
|
1577
1733
|
});
|
|
1578
|
-
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(
|
|
1734
|
+
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make({
|
|
1735
|
+
position: entry.position,
|
|
1736
|
+
event: durableEventEnvelope(entry.event)
|
|
1737
|
+
}));
|
|
1579
1738
|
return { head: nextReduced.lastSeq };
|
|
1580
1739
|
});
|
|
1581
1740
|
const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
@@ -1607,10 +1766,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1607
1766
|
const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
|
|
1608
1767
|
if (systemPrompt === void 0) return;
|
|
1609
1768
|
if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
|
|
1610
|
-
|
|
1769
|
+
const event = yield* events.systemMessageCommitted({
|
|
1611
1770
|
messageId: yield* ids.makeMessageId(),
|
|
1612
1771
|
content: systemPrompt
|
|
1613
|
-
})
|
|
1772
|
+
});
|
|
1773
|
+
yield* appendDurable(event);
|
|
1614
1774
|
});
|
|
1615
1775
|
const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
|
|
1616
1776
|
const current = yield* Ref.get(state);
|
|
@@ -1632,13 +1792,10 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1632
1792
|
}
|
|
1633
1793
|
});
|
|
1634
1794
|
yield* liveBus.publish(positioned);
|
|
1795
|
+
yield* sinkRegistry.publishEphemeralToSinks(positioned);
|
|
1635
1796
|
return positioned;
|
|
1636
1797
|
}));
|
|
1637
|
-
const publishEphemeral =
|
|
1638
|
-
const positioned = yield* publishEphemeralCore(event);
|
|
1639
|
-
yield* sinkRegistry.publishEphemeralToSinks(positioned, publishEphemeralCore);
|
|
1640
|
-
return positioned;
|
|
1641
|
-
});
|
|
1798
|
+
const publishEphemeral = publishEphemeralCore;
|
|
1642
1799
|
const wakeAfterCommandAdmission = () => Queue.offer(ingressSignals, void 0);
|
|
1643
1800
|
/** Use indexed store lookup for command idempotency instead of genesis replay. */
|
|
1644
1801
|
const findExistingCommandAdmission = (command) => Effect.gen(function* () {
|
|
@@ -1659,8 +1816,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1659
1816
|
}
|
|
1660
1817
|
const existing = yield* findExistingCommandAdmission(command);
|
|
1661
1818
|
if (existing !== void 0) {
|
|
1662
|
-
rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1663
|
-
return [existing.event];
|
|
1819
|
+
rememberPreparedCommand(durableEventEnvelope(existing.event), preparedByIdempotencyKey, preparedByCommandId);
|
|
1820
|
+
return [durableEventEnvelope(existing.event)];
|
|
1664
1821
|
}
|
|
1665
1822
|
const commandId = command.commandId ?? (yield* ids.makeCommandId());
|
|
1666
1823
|
const admitted = commandWithId(command, commandId);
|
|
@@ -1714,7 +1871,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1714
1871
|
submitted
|
|
1715
1872
|
];
|
|
1716
1873
|
});
|
|
1717
|
-
const submitBatch =
|
|
1874
|
+
const submitBatch = (input) => admissionGate.withPermits(1)(submitBatchAdmitted(input));
|
|
1875
|
+
const submitBatchAdmitted = Effect.fn(function* (input) {
|
|
1718
1876
|
const commandCount = input.filter(isEDACommand).length;
|
|
1719
1877
|
yield* annotateEdaSpan({
|
|
1720
1878
|
"eda.command.submittable_count": input.length,
|
|
@@ -1724,7 +1882,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1724
1882
|
const committed = yield* withAppendGate(Effect.gen(function* () {
|
|
1725
1883
|
const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1726
1884
|
const preparedByCommandId = /* @__PURE__ */ new Map();
|
|
1727
|
-
|
|
1885
|
+
const durableEvents = (yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat();
|
|
1886
|
+
return yield* commitDurableEntriesWithinGate(durableEvents.map((event) => ({ event })));
|
|
1728
1887
|
}));
|
|
1729
1888
|
yield* annotateEdaSpan(committedBatchAttributes(committed));
|
|
1730
1889
|
if (commandCount > 0) yield* wakeAfterCommandAdmission();
|
|
@@ -1735,6 +1894,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1735
1894
|
});
|
|
1736
1895
|
const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
|
|
1737
1896
|
const sessionApi = {
|
|
1897
|
+
grantRun: (command, input) => grantRun(command, input),
|
|
1898
|
+
retryRunSchedulingDelivery: () => retryRunSchedulingDelivery(),
|
|
1738
1899
|
initialize,
|
|
1739
1900
|
submitBatch,
|
|
1740
1901
|
admitCommand,
|
|
@@ -1776,9 +1937,11 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1776
1937
|
yield* requestCurrentReducerCheckpointSnapshot("startup-recovery-complete");
|
|
1777
1938
|
});
|
|
1778
1939
|
const maybeCompactAtBoundary = () => Effect.gen(function* () {
|
|
1779
|
-
const
|
|
1940
|
+
const data = yield* currentData();
|
|
1941
|
+
const current = data.reduced;
|
|
1780
1942
|
const next = (yield* compactionRunner.maybeCompact({
|
|
1781
1943
|
state: current,
|
|
1944
|
+
reducerStates: data.reducerStates,
|
|
1782
1945
|
context: yield* contextProjectionFor(current),
|
|
1783
1946
|
appendDurableEntries
|
|
1784
1947
|
})).length === 0 ? current : yield* currentReduced();
|
|
@@ -1786,25 +1949,29 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1786
1949
|
return next;
|
|
1787
1950
|
});
|
|
1788
1951
|
const cancelCommand = (commandId, reason) => Effect.gen(function* () {
|
|
1789
|
-
const
|
|
1952
|
+
const event = yield* events.commandCancelled({
|
|
1790
1953
|
commandId,
|
|
1791
1954
|
reason
|
|
1792
|
-
})
|
|
1955
|
+
});
|
|
1956
|
+
const committed = yield* appendDurable(event);
|
|
1793
1957
|
return SessionCommandCancelled.make({ committed });
|
|
1794
1958
|
});
|
|
1795
1959
|
const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
|
|
1796
1960
|
if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
|
|
1797
|
-
|
|
1961
|
+
const event = yield* events.turnFailed({
|
|
1798
1962
|
runId: active.runId,
|
|
1799
1963
|
turnId: active.turnId,
|
|
1800
1964
|
error: interruptionFailure("turn", reason, {
|
|
1801
1965
|
runId: active.runId,
|
|
1802
1966
|
turnId: active.turnId
|
|
1803
1967
|
})
|
|
1804
|
-
})
|
|
1968
|
+
});
|
|
1969
|
+
return yield* appendDurable(event);
|
|
1805
1970
|
});
|
|
1806
1971
|
const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
|
|
1807
|
-
const
|
|
1972
|
+
const runCompleted = yield* events.runCompleted({ runId });
|
|
1973
|
+
const commandCompleted = yield* events.commandCompleted({ commandId });
|
|
1974
|
+
const committed = yield* appendDurableBatch([runCompleted, commandCompleted]);
|
|
1808
1975
|
return SessionCommandCompleted.make({ committed: committed.at(-1) });
|
|
1809
1976
|
});
|
|
1810
1977
|
const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
|
|
@@ -1816,7 +1983,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1816
1983
|
commandId,
|
|
1817
1984
|
error
|
|
1818
1985
|
});
|
|
1819
|
-
const
|
|
1986
|
+
const current = yield* currentReduced();
|
|
1987
|
+
const failurePlan = planRunFailure(current);
|
|
1820
1988
|
const resumeEvents = [];
|
|
1821
1989
|
if (failurePlan.messageIdsToResume.length > 0) {
|
|
1822
1990
|
const resumeCommandId = yield* ids.makeCommandId();
|
|
@@ -1834,23 +2002,27 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1834
2002
|
});
|
|
1835
2003
|
const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
|
|
1836
2004
|
if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
|
|
1837
|
-
|
|
2005
|
+
const failed = yield* requireTurnFailed(turn.outcome.committed);
|
|
2006
|
+
return yield* failRunAndCommandWithError(commandId, runId, failed.event.payload.error);
|
|
1838
2007
|
});
|
|
1839
2008
|
const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
|
|
1840
2009
|
const failurePlan = planRunFailure(yield* currentReduced());
|
|
2010
|
+
const runFailed = yield* events.runFailed({
|
|
2011
|
+
runId: active.runId,
|
|
2012
|
+
error: interruptionFailure("run", reason, { runId: active.runId })
|
|
2013
|
+
});
|
|
2014
|
+
const commandCancelled = yield* events.commandCancelled({
|
|
2015
|
+
commandId: active.commandId,
|
|
2016
|
+
reason
|
|
2017
|
+
});
|
|
2018
|
+
const resume = failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2019
|
+
commandId: yield* ids.makeCommandId(),
|
|
2020
|
+
messageIds: failurePlan.messageIdsToResume
|
|
2021
|
+
}) })];
|
|
1841
2022
|
const committed = yield* appendDurableBatch([
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
}),
|
|
1846
|
-
yield* events.commandCancelled({
|
|
1847
|
-
commandId: active.commandId,
|
|
1848
|
-
reason
|
|
1849
|
-
}),
|
|
1850
|
-
...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
1851
|
-
commandId: yield* ids.makeCommandId(),
|
|
1852
|
-
messageIds: failurePlan.messageIdsToResume
|
|
1853
|
-
}) })]
|
|
2023
|
+
runFailed,
|
|
2024
|
+
commandCancelled,
|
|
2025
|
+
...resume
|
|
1854
2026
|
]);
|
|
1855
2027
|
return SessionCommandCancelled.make({ committed: committed.at(-1) });
|
|
1856
2028
|
});
|
|
@@ -1967,10 +2139,69 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
1967
2139
|
});
|
|
1968
2140
|
return SessionForkedCommand.make({ commandId: input.commandId });
|
|
1969
2141
|
});
|
|
2142
|
+
const reconcileSchedulingWakeup = Effect.fnUntraced(function* () {
|
|
2143
|
+
const request = (yield* currentReduced()).runSchedulingRequest;
|
|
2144
|
+
yield* schedulingWakeup.setPending(request !== void 0 && request.deliveredSeq === void 0);
|
|
2145
|
+
});
|
|
2146
|
+
const retryRunSchedulingDelivery = Effect.fnUntraced(function* () {
|
|
2147
|
+
if (yield* Ref.get(recoveringInBackground)) return;
|
|
2148
|
+
yield* deliveryGate.withPermitsIfAvailable(1)(Effect.gen(function* () {
|
|
2149
|
+
const request = yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2150
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2151
|
+
yield* reconcileSchedulingWakeup();
|
|
2152
|
+
return current?.deliveredSeq === void 0 ? current : void 0;
|
|
2153
|
+
}));
|
|
2154
|
+
if (request === void 0) return;
|
|
2155
|
+
const delivered = yield* Effect.exit(keepAlive.withActiveWork("run-scheduling-delivery", runScheduler.deliver({
|
|
2156
|
+
sessionId: sessionContext.sessionId,
|
|
2157
|
+
request: {
|
|
2158
|
+
requestId: request.requestId,
|
|
2159
|
+
work: request.work
|
|
2160
|
+
}
|
|
2161
|
+
}).pipe(Effect.timeout("10 seconds"))));
|
|
2162
|
+
if (Exit.isFailure(delivered)) {
|
|
2163
|
+
if (Cause.hasInterruptsOnly(delivered.cause)) return yield* Effect.interrupt;
|
|
2164
|
+
yield* controlGate.withPermits(1)(reconcileSchedulingWakeup());
|
|
2165
|
+
yield* Effect.logWarning("Run authorization delivery will retry on the durable host wakeup", {
|
|
2166
|
+
requestId: request.requestId,
|
|
2167
|
+
cause: Cause.pretty(delivered.cause)
|
|
2168
|
+
});
|
|
2169
|
+
return;
|
|
2170
|
+
}
|
|
2171
|
+
yield* controlGate.withPermits(1)(Effect.gen(function* () {
|
|
2172
|
+
const current = (yield* currentReduced()).runSchedulingRequest;
|
|
2173
|
+
if (current?.requestId === request.requestId && current.deliveredSeq === void 0) yield* appendDurable(yield* events.runSchedulingDelivered({ requestId: request.requestId }));
|
|
2174
|
+
yield* reconcileSchedulingWakeup();
|
|
2175
|
+
}));
|
|
2176
|
+
}));
|
|
2177
|
+
});
|
|
2178
|
+
const forkSchedulingDelivery = () => retryRunSchedulingDelivery().pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2179
|
+
yield* markFatalIfDurable(cause);
|
|
2180
|
+
yield* Effect.logError("Run authorization delivery worker failed", { cause: Cause.pretty(cause) });
|
|
2181
|
+
})), Effect.forkIn(runtimeScope), Effect.asVoid);
|
|
2182
|
+
const prepareRunSchedulingRequest = Effect.fnUntraced(function* (work) {
|
|
2183
|
+
yield* schedulingWakeup.setPending(true);
|
|
2184
|
+
return yield* events.runSchedulingRequested({
|
|
2185
|
+
requestId: yield* ids.makeRunRequestId(),
|
|
2186
|
+
work
|
|
2187
|
+
});
|
|
2188
|
+
});
|
|
2189
|
+
const deferRun = Effect.fnUntraced(function* (work) {
|
|
2190
|
+
yield* appendDurable(yield* prepareRunSchedulingRequest(work));
|
|
2191
|
+
yield* forkSchedulingDelivery();
|
|
2192
|
+
return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
2193
|
+
});
|
|
1970
2194
|
const startSubmitCommand = Effect.fn(function* (command, input) {
|
|
1971
2195
|
if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
|
|
1972
2196
|
const submit = command.command;
|
|
1973
2197
|
const commandId = command.commandId;
|
|
2198
|
+
if ((yield* runScheduler.resolve({
|
|
2199
|
+
sessionId: sessionContext.sessionId,
|
|
2200
|
+
commandId
|
|
2201
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2202
|
+
_tag: "Command",
|
|
2203
|
+
commandId
|
|
2204
|
+
});
|
|
1974
2205
|
yield* annotateEdaSpan({
|
|
1975
2206
|
"eda.command.id": commandId,
|
|
1976
2207
|
"eda.command.disposition": submit.disposition,
|
|
@@ -2000,13 +2231,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2000
2231
|
modelSelection: input.modelSelection,
|
|
2001
2232
|
trace: activeRunTrace.runTrace
|
|
2002
2233
|
});
|
|
2234
|
+
const startedEvents = yield* appendDurableBatch([
|
|
2235
|
+
commandStarted,
|
|
2236
|
+
...userMessage === void 0 ? [] : [userMessage],
|
|
2237
|
+
runStarted
|
|
2238
|
+
]);
|
|
2003
2239
|
return yield* startTurn({
|
|
2004
2240
|
commandId,
|
|
2005
|
-
commandStarted:
|
|
2006
|
-
commandStarted,
|
|
2007
|
-
...userMessage === void 0 ? [] : [userMessage],
|
|
2008
|
-
runStarted
|
|
2009
|
-
]))[0],
|
|
2241
|
+
commandStarted: startedEvents[0],
|
|
2010
2242
|
inputMessageIds: [messageId],
|
|
2011
2243
|
runId,
|
|
2012
2244
|
modelSelection: input.modelSelection,
|
|
@@ -2024,6 +2256,13 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2024
2256
|
return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
|
|
2025
2257
|
});
|
|
2026
2258
|
if (pending.length === 0) return yield* processInactiveStopCommand(command);
|
|
2259
|
+
if ((yield* runScheduler.resolve({
|
|
2260
|
+
sessionId: sessionContext.sessionId,
|
|
2261
|
+
commandId: command.commandId
|
|
2262
|
+
}))._tag === "Deferred") return yield* deferRun({
|
|
2263
|
+
_tag: "Command",
|
|
2264
|
+
commandId: command.commandId
|
|
2265
|
+
});
|
|
2027
2266
|
const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
|
|
2028
2267
|
const runId = yield* ids.makeRunId();
|
|
2029
2268
|
const activeRunTrace = yield* startRunTrace({
|
|
@@ -2033,12 +2272,13 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2033
2272
|
runId
|
|
2034
2273
|
});
|
|
2035
2274
|
return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
|
|
2036
|
-
const
|
|
2275
|
+
const runStarted = yield* events.runStarted({
|
|
2037
2276
|
runId,
|
|
2038
2277
|
commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
|
|
2039
2278
|
modelSelection: input.modelSelection,
|
|
2040
2279
|
trace: activeRunTrace.runTrace
|
|
2041
|
-
})
|
|
2280
|
+
});
|
|
2281
|
+
const started = yield* appendDurableBatch([commandStarted, runStarted]);
|
|
2042
2282
|
return yield* startTurn({
|
|
2043
2283
|
commandId: command.commandId,
|
|
2044
2284
|
commandStarted: started[0],
|
|
@@ -2051,6 +2291,108 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2051
2291
|
});
|
|
2052
2292
|
}));
|
|
2053
2293
|
});
|
|
2294
|
+
const grantRun = Effect.fn("agent.run.grant")(function* (grant, input) {
|
|
2295
|
+
yield* annotateEdaSpan({
|
|
2296
|
+
"eda.session.id": sessionContext.sessionId,
|
|
2297
|
+
"eda.run_request.id": grant.requestId
|
|
2298
|
+
});
|
|
2299
|
+
return yield* controlGate.withPermits(1)(keepAlive.withActiveWork("run-authorization-grant", Effect.gen(function* () {
|
|
2300
|
+
yield* failIfFatal;
|
|
2301
|
+
const initial = yield* currentReduced();
|
|
2302
|
+
if (!canGrantRun(initial, grant.requestId)) return { _tag: "Stale" };
|
|
2303
|
+
const request = initial.runSchedulingRequest;
|
|
2304
|
+
if (request === void 0) return { _tag: "Stale" };
|
|
2305
|
+
const command = initial.commands.get(request.work.commandId);
|
|
2306
|
+
if (command?.command === void 0) return { _tag: "Stale" };
|
|
2307
|
+
const admitted = command.command;
|
|
2308
|
+
const predecessor = request.work._tag === "Recovery" ? initial.runs.get(request.work.interruptedRunId) : void 0;
|
|
2309
|
+
const modelSelection = predecessor?.modelSelection ?? initial.modelSelection ?? input.modelSelection;
|
|
2310
|
+
const runId = yield* ids.makeRunId();
|
|
2311
|
+
const trace = yield* startRunTrace({
|
|
2312
|
+
commandId: command.commandId,
|
|
2313
|
+
admissionTrace: command.admissionTrace,
|
|
2314
|
+
modelSelection,
|
|
2315
|
+
runId
|
|
2316
|
+
});
|
|
2317
|
+
return yield* closeRunTraceOnFailure(trace, Effect.gen(function* () {
|
|
2318
|
+
const started = yield* withAppendGate(Effect.gen(function* () {
|
|
2319
|
+
const current = yield* currentReduced();
|
|
2320
|
+
if (!canGrantRun(current, grant.requestId)) return void 0;
|
|
2321
|
+
const inputMessageIds = [...runSchedulingInputMessageIds(current, request.work)];
|
|
2322
|
+
const batch = [];
|
|
2323
|
+
let commandStarted;
|
|
2324
|
+
if (request.work._tag === "Recovery") {
|
|
2325
|
+
if (command.startedSeq === void 0 || predecessor === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization requires its started command and predecessor"));
|
|
2326
|
+
[commandStarted] = yield* store.loadCommittedEventsBySeq([command.startedSeq]);
|
|
2327
|
+
if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error("Recovery authorization is missing CommandStarted"));
|
|
2328
|
+
} else {
|
|
2329
|
+
batch.push(yield* events.commandStarted({ commandId: command.commandId }));
|
|
2330
|
+
if (admitted._tag === "SubmitMessage" && inputMessageIds.length === 0) {
|
|
2331
|
+
const messageId = yield* ids.makeMessageId();
|
|
2332
|
+
batch.push(yield* events.userMessageCommitted({
|
|
2333
|
+
commandId: command.commandId,
|
|
2334
|
+
messageId,
|
|
2335
|
+
content: admitted.content
|
|
2336
|
+
}));
|
|
2337
|
+
inputMessageIds.push(messageId);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
batch.push(yield* events.runSchedulingGranted({
|
|
2341
|
+
requestId: request.requestId,
|
|
2342
|
+
runId
|
|
2343
|
+
}));
|
|
2344
|
+
const commandIds = predecessor?.commandIds ?? [command.commandId, ...admitted._tag === "ResumePendingMessages" ? inputMessageIds.flatMap((messageId) => {
|
|
2345
|
+
const message = current.messages.get(messageId);
|
|
2346
|
+
return message?._tag === "User" || message?._tag === "Steering" ? [message.commandId] : [];
|
|
2347
|
+
}) : []];
|
|
2348
|
+
batch.push(yield* events.runStarted({
|
|
2349
|
+
runId,
|
|
2350
|
+
commandIds,
|
|
2351
|
+
modelSelection,
|
|
2352
|
+
trace: trace.runTrace
|
|
2353
|
+
}));
|
|
2354
|
+
if (request.work._tag === "Recovery") batch.push(yield* events.recoveryCompleted({
|
|
2355
|
+
trigger: "runtime-restart",
|
|
2356
|
+
continuation: {
|
|
2357
|
+
commandId: command.commandId,
|
|
2358
|
+
interruptedRunId: request.work.interruptedRunId,
|
|
2359
|
+
replacementRunId: runId
|
|
2360
|
+
}
|
|
2361
|
+
}));
|
|
2362
|
+
const committed = yield* commitDurableEntriesWithinGate(batch.map((event) => ({ event })));
|
|
2363
|
+
commandStarted ??= committed[0];
|
|
2364
|
+
if (commandStarted === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Granted run must have CommandStarted"));
|
|
2365
|
+
return {
|
|
2366
|
+
commandStarted,
|
|
2367
|
+
inputMessageIds
|
|
2368
|
+
};
|
|
2369
|
+
}));
|
|
2370
|
+
if (started === void 0) {
|
|
2371
|
+
yield* Scope.close(trace.runScope, Exit.void);
|
|
2372
|
+
return { _tag: "Stale" };
|
|
2373
|
+
}
|
|
2374
|
+
yield* reconcileSchedulingWakeup();
|
|
2375
|
+
yield* startTurn({
|
|
2376
|
+
commandId: command.commandId,
|
|
2377
|
+
commandStarted: started.commandStarted,
|
|
2378
|
+
inputMessageIds: started.inputMessageIds,
|
|
2379
|
+
runId,
|
|
2380
|
+
modelSelection,
|
|
2381
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2382
|
+
runScope: trace.runScope,
|
|
2383
|
+
runSpan: trace.runSpan
|
|
2384
|
+
});
|
|
2385
|
+
yield* wakeAfterCommandAdmission();
|
|
2386
|
+
return {
|
|
2387
|
+
_tag: "Granted",
|
|
2388
|
+
runId
|
|
2389
|
+
};
|
|
2390
|
+
}));
|
|
2391
|
+
})).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2392
|
+
yield* markFatalIfDurable(cause);
|
|
2393
|
+
return yield* Effect.failCause(cause);
|
|
2394
|
+
}))));
|
|
2395
|
+
});
|
|
2054
2396
|
const processInactiveStopCommand = Effect.fn(function* (command) {
|
|
2055
2397
|
const commandId = command.commandId;
|
|
2056
2398
|
return (yield* startedBoundaryGuard({
|
|
@@ -2132,6 +2474,47 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2132
2474
|
turn: exit.value
|
|
2133
2475
|
};
|
|
2134
2476
|
});
|
|
2477
|
+
/**
|
|
2478
|
+
* Before failing what the dead runtime left open, re-invoke each started tool call whose tool
|
|
2479
|
+
* declares `ToolRecovery: "reinvoke"` and still has attempts left. Each commits its next start
|
|
2480
|
+
* before running, so a runtime that dies again mid-reinvocation spends that attempt. Calls that
|
|
2481
|
+
* finish here are terminal by the time recovery plans its batch; the rest are failed as before.
|
|
2482
|
+
*/
|
|
2483
|
+
const plannedReinvocations = Effect.fnUntraced(function* (reduced) {
|
|
2484
|
+
const calls = [];
|
|
2485
|
+
for (const tool of planSessionRecovery(reduced).openToolCalls) {
|
|
2486
|
+
const decision = tool.decision;
|
|
2487
|
+
if (decision?._tag !== "Created" || decision.providerExecuted) continue;
|
|
2488
|
+
if (tool.startedSeq === void 0 || tool.startedAtMs === void 0) continue;
|
|
2489
|
+
const attempt = (tool.attempt ?? 1) + 1;
|
|
2490
|
+
if (attempt > 3) continue;
|
|
2491
|
+
if ((yield* turnRunner.toolRecoveryPolicy(decision.toolName)) !== "reinvoke") continue;
|
|
2492
|
+
calls.push({
|
|
2493
|
+
seq: decision.seq,
|
|
2494
|
+
resume: {
|
|
2495
|
+
attempt,
|
|
2496
|
+
firstStartedAtMs: tool.startedAtMs,
|
|
2497
|
+
firstStartedSeq: tool.startedSeq
|
|
2498
|
+
}
|
|
2499
|
+
});
|
|
2500
|
+
}
|
|
2501
|
+
return calls;
|
|
2502
|
+
});
|
|
2503
|
+
const resumeInterruptedToolCalls = Effect.fnUntraced(function* (calls) {
|
|
2504
|
+
yield* annotateEdaSpan({ "eda.recovery.reinvoked_tool_calls": calls.length });
|
|
2505
|
+
if (calls.length === 0) return;
|
|
2506
|
+
const created = yield* store.loadCommittedEventsBySeq(calls.map((call) => call.seq));
|
|
2507
|
+
yield* turnRunner.resumeToolCalls({
|
|
2508
|
+
calls: calls.flatMap((call) => {
|
|
2509
|
+
const event = created.find((entry) => entry.position.seq === call.seq);
|
|
2510
|
+
return event === void 0 ? [] : [{
|
|
2511
|
+
created: event,
|
|
2512
|
+
resume: call.resume
|
|
2513
|
+
}];
|
|
2514
|
+
}),
|
|
2515
|
+
eventSink: sessionApi
|
|
2516
|
+
}).pipe(Effect.catchTag("ToolExecutionEventNotCreated", (error) => Effect.die(error)));
|
|
2517
|
+
});
|
|
2135
2518
|
const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
|
|
2136
2519
|
const plan = planSessionRecovery(reduced);
|
|
2137
2520
|
input = {
|
|
@@ -2219,7 +2602,17 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2219
2602
|
commandId: yield* ids.makeCommandId(),
|
|
2220
2603
|
messageIds: plan.messageIdsToResume
|
|
2221
2604
|
}) }));
|
|
2222
|
-
const
|
|
2605
|
+
const resolution = plan.continuation === void 0 ? void 0 : yield* runScheduler.resolve({
|
|
2606
|
+
sessionId: sessionContext.sessionId,
|
|
2607
|
+
commandId: plan.continuation.command.commandId
|
|
2608
|
+
});
|
|
2609
|
+
if (plan.continuation !== void 0 && resolution?._tag === "Deferred") recoveryEvents.push(yield* prepareRunSchedulingRequest({
|
|
2610
|
+
_tag: "Recovery",
|
|
2611
|
+
commandId: plan.continuation.command.commandId,
|
|
2612
|
+
interruptedRunId: plan.continuation.run.runId,
|
|
2613
|
+
inputMessageIds: plan.continuation.inputMessageIds
|
|
2614
|
+
}));
|
|
2615
|
+
const continuationRunId = plan.continuation === void 0 || resolution?._tag === "Deferred" ? void 0 : yield* ids.makeRunId();
|
|
2223
2616
|
const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
|
|
2224
2617
|
admissionTrace: plan.continuation.command.admissionTrace,
|
|
2225
2618
|
commandId: plan.continuation.command.commandId,
|
|
@@ -2242,6 +2635,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2242
2635
|
} }
|
|
2243
2636
|
}));
|
|
2244
2637
|
const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
|
|
2638
|
+
if (resolution?._tag === "Deferred") yield* forkSchedulingDelivery();
|
|
2245
2639
|
const nextPlan = planSessionRecovery(yield* currentReduced());
|
|
2246
2640
|
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"));
|
|
2247
2641
|
return {
|
|
@@ -2303,7 +2697,8 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2303
2697
|
return (yield* startedBoundaryGuard({
|
|
2304
2698
|
start: events.commandStarted({ commandId }),
|
|
2305
2699
|
body: (started) => Effect.gen(function* () {
|
|
2306
|
-
const
|
|
2700
|
+
const completed = yield* events.commandCompleted({ commandId });
|
|
2701
|
+
const committed = yield* appendDurableBatch([completed]);
|
|
2307
2702
|
return {
|
|
2308
2703
|
started,
|
|
2309
2704
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2320,13 +2715,14 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2320
2715
|
})).value;
|
|
2321
2716
|
});
|
|
2322
2717
|
const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
|
|
2323
|
-
const
|
|
2718
|
+
const failed = yield* events.commandFailed({
|
|
2324
2719
|
commandId,
|
|
2325
2720
|
error: FailurePayload.make({
|
|
2326
2721
|
code,
|
|
2327
2722
|
message
|
|
2328
2723
|
})
|
|
2329
|
-
})
|
|
2724
|
+
});
|
|
2725
|
+
const committed = yield* appendDurable(failed);
|
|
2330
2726
|
return SessionCommandFailed.make({ committed });
|
|
2331
2727
|
});
|
|
2332
2728
|
const cancelPendingMessage = Effect.fn(function* (command) {
|
|
@@ -2352,12 +2748,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2352
2748
|
commandId: target.commandId,
|
|
2353
2749
|
reason: "pending message cancelled"
|
|
2354
2750
|
})] : [];
|
|
2751
|
+
const schedulingPlan = planRunSchedulingCancellation(current, target.messageId);
|
|
2752
|
+
const schedulingEvents = [];
|
|
2753
|
+
if (schedulingPlan !== void 0) {
|
|
2754
|
+
schedulingEvents.push(yield* events.runSchedulingInvalidated({
|
|
2755
|
+
requestId: schedulingPlan.requestId,
|
|
2756
|
+
reason: "message-cancelled"
|
|
2757
|
+
}));
|
|
2758
|
+
if (schedulingPlan.cancelCommandId !== void 0) schedulingEvents.push(yield* events.commandCancelled({
|
|
2759
|
+
commandId: schedulingPlan.cancelCommandId,
|
|
2760
|
+
reason: "pending recovery inputs cancelled"
|
|
2761
|
+
}));
|
|
2762
|
+
if (schedulingPlan.replacementWork !== void 0) schedulingEvents.push(yield* prepareRunSchedulingRequest(schedulingPlan.replacementWork));
|
|
2763
|
+
}
|
|
2355
2764
|
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2356
2765
|
const committed = yield* appendDurableBatch([
|
|
2357
2766
|
cancelled,
|
|
2358
2767
|
...originCancelled,
|
|
2768
|
+
...schedulingEvents,
|
|
2359
2769
|
completed
|
|
2360
2770
|
]);
|
|
2771
|
+
if (schedulingEvents.length > 0) {
|
|
2772
|
+
yield* reconcileSchedulingWakeup();
|
|
2773
|
+
yield* forkSchedulingDelivery();
|
|
2774
|
+
}
|
|
2361
2775
|
return {
|
|
2362
2776
|
started,
|
|
2363
2777
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2380,17 +2794,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2380
2794
|
return (yield* startedBoundaryGuard({
|
|
2381
2795
|
start: events.commandStarted({ commandId: controlCommandId }),
|
|
2382
2796
|
body: (started) => Effect.gen(function* () {
|
|
2383
|
-
const
|
|
2797
|
+
const current = yield* currentReduced();
|
|
2798
|
+
const target = current.messages.get(promotion.messageId);
|
|
2384
2799
|
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 {
|
|
2385
2800
|
started,
|
|
2386
2801
|
outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
|
|
2387
2802
|
};
|
|
2388
|
-
const
|
|
2803
|
+
const promoted = yield* events.userMessagePromoted({
|
|
2389
2804
|
commandId: controlCommandId,
|
|
2390
2805
|
messageId: target.messageId,
|
|
2391
2806
|
from: "queue",
|
|
2392
2807
|
to: "steer"
|
|
2393
|
-
})
|
|
2808
|
+
});
|
|
2809
|
+
const resumed = promotionNeedsResumeCommand(current, target.messageId) ? [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2810
|
+
commandId: yield* ids.makeCommandId(),
|
|
2811
|
+
messageIds: [target.messageId]
|
|
2812
|
+
}) })] : [];
|
|
2813
|
+
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2814
|
+
const committed = yield* appendDurableBatch([
|
|
2815
|
+
promoted,
|
|
2816
|
+
...resumed,
|
|
2817
|
+
completed
|
|
2818
|
+
]);
|
|
2394
2819
|
return {
|
|
2395
2820
|
started,
|
|
2396
2821
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2417,25 +2842,30 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2417
2842
|
return (yield* startedBoundaryGuard({
|
|
2418
2843
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2419
2844
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2420
|
-
const
|
|
2421
|
-
|
|
2845
|
+
const beforeStop = yield* currentReduced();
|
|
2846
|
+
const requested = activeTurnIdentityForCommand(beforeStop, active.commandId);
|
|
2847
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2422
2848
|
commandId: stopCommandId,
|
|
2423
2849
|
...requested === void 0 ? {} : {
|
|
2424
2850
|
runId: requested.runId,
|
|
2425
2851
|
turnId: requested.turnId
|
|
2426
2852
|
}
|
|
2427
|
-
})
|
|
2853
|
+
});
|
|
2854
|
+
yield* appendDurable(requestedEvent);
|
|
2428
2855
|
yield* Scope.close(active.turnScope, Exit.interrupt());
|
|
2429
2856
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2430
2857
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2431
2858
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2432
|
-
const
|
|
2433
|
-
const
|
|
2859
|
+
const afterStop = yield* currentReduced();
|
|
2860
|
+
const applied = activeTurnIdentityForCommand(afterStop, active.commandId);
|
|
2861
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2434
2862
|
commandId: stopCommandId,
|
|
2435
2863
|
runId: active.runId,
|
|
2436
2864
|
turnId: active.turnId,
|
|
2437
2865
|
...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
|
|
2438
|
-
})
|
|
2866
|
+
});
|
|
2867
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
2868
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2439
2869
|
return {
|
|
2440
2870
|
started,
|
|
2441
2871
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2462,19 +2892,22 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2462
2892
|
return (yield* startedBoundaryGuard({
|
|
2463
2893
|
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2464
2894
|
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2465
|
-
|
|
2895
|
+
const requestedEvent = yield* events.stopTurnRequested({
|
|
2466
2896
|
commandId: stopCommandId,
|
|
2467
2897
|
runId: active.runId,
|
|
2468
2898
|
turnId: active.turnId
|
|
2469
|
-
})
|
|
2899
|
+
});
|
|
2900
|
+
yield* appendDurable(requestedEvent);
|
|
2470
2901
|
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2471
2902
|
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2472
2903
|
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2473
|
-
const
|
|
2904
|
+
const appliedEvent = yield* events.stopTurnApplied({
|
|
2474
2905
|
commandId: stopCommandId,
|
|
2475
2906
|
runId: active.runId,
|
|
2476
2907
|
turnId: active.turnId
|
|
2477
|
-
})
|
|
2908
|
+
});
|
|
2909
|
+
const completedEvent = yield* events.commandCompleted({ commandId: stopCommandId });
|
|
2910
|
+
const committed = yield* appendDurableBatch([appliedEvent, completedEvent]);
|
|
2478
2911
|
return {
|
|
2479
2912
|
started,
|
|
2480
2913
|
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
@@ -2556,6 +2989,32 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2556
2989
|
default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
|
|
2557
2990
|
}
|
|
2558
2991
|
});
|
|
2992
|
+
const interruptWaitingRun = Effect.fnUntraced(function* (control, reason) {
|
|
2993
|
+
const plan = planWaitingRunInterruption(yield* currentReduced(), control.commandId);
|
|
2994
|
+
if (plan === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Waiting interruption requires a current reservation"));
|
|
2995
|
+
const isStop = control.command._tag === "StopTurn";
|
|
2996
|
+
const batch = [];
|
|
2997
|
+
if (isStop) batch.push(yield* events.commandStarted({ commandId: control.commandId }));
|
|
2998
|
+
batch.push(yield* events.runSchedulingInvalidated({
|
|
2999
|
+
requestId: plan.requestId,
|
|
3000
|
+
reason
|
|
3001
|
+
}));
|
|
3002
|
+
const [firstMessageId, ...restMessageIds] = plan.messageIds;
|
|
3003
|
+
if (firstMessageId !== void 0) batch.push(yield* events.pendingMessagesPaused({
|
|
3004
|
+
interruptionCommandId: control.commandId,
|
|
3005
|
+
runRequestId: plan.requestId,
|
|
3006
|
+
messageIds: [firstMessageId, ...restMessageIds],
|
|
3007
|
+
reason: "user-interrupted"
|
|
3008
|
+
}));
|
|
3009
|
+
if (plan.cancelCommandId !== void 0) batch.push(yield* events.commandCancelled({
|
|
3010
|
+
commandId: plan.cancelCommandId,
|
|
3011
|
+
reason
|
|
3012
|
+
}));
|
|
3013
|
+
if (isStop) batch.push(yield* events.commandCompleted({ commandId: control.commandId }));
|
|
3014
|
+
const committed = yield* appendDurableBatch(batch);
|
|
3015
|
+
yield* reconcileSchedulingWakeup();
|
|
3016
|
+
return committed;
|
|
3017
|
+
});
|
|
2559
3018
|
const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
|
|
2560
3019
|
const execution = yield* inspectExecutionState();
|
|
2561
3020
|
const current = yield* currentReduced();
|
|
@@ -2615,6 +3074,28 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2615
3074
|
});
|
|
2616
3075
|
}
|
|
2617
3076
|
}
|
|
3077
|
+
if (current.runSchedulingRequest !== void 0) {
|
|
3078
|
+
const control = waitingRunControl(current);
|
|
3079
|
+
if (control === void 0) return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3080
|
+
switch (control.command._tag) {
|
|
3081
|
+
case "CancelPendingMessage": return yield* cancelPendingMessage(control);
|
|
3082
|
+
case "PromotePendingMessage": return yield* promotePendingMessage(control);
|
|
3083
|
+
case "StopTurn": {
|
|
3084
|
+
const committed = yield* interruptWaitingRun(control, "stopped");
|
|
3085
|
+
const started = committed[0];
|
|
3086
|
+
const completed = committed.at(-1);
|
|
3087
|
+
if (started === void 0 || completed === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Stopping a waiting request must commit its control lifecycle"));
|
|
3088
|
+
return {
|
|
3089
|
+
started,
|
|
3090
|
+
outcome: SessionCommandCompleted.make({ committed: completed })
|
|
3091
|
+
};
|
|
3092
|
+
}
|
|
3093
|
+
case "SubmitMessage":
|
|
3094
|
+
yield* interruptWaitingRun(control, "interrupted");
|
|
3095
|
+
return yield* startSubmitCommand(control, input);
|
|
3096
|
+
default: return SessionNoRunnableCommand.make({ reason: "awaiting-run-authorization" });
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
2618
3099
|
const decision = decideDispatch(current);
|
|
2619
3100
|
switch (decision._tag) {
|
|
2620
3101
|
case "DispatchBlockedByActiveCommand":
|
|
@@ -2644,7 +3125,7 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2644
3125
|
yield* failIfFatal;
|
|
2645
3126
|
const processed = [];
|
|
2646
3127
|
while (true) {
|
|
2647
|
-
const result = yield* withFatalRecording(drainOneReadyCommand(input));
|
|
3128
|
+
const result = yield* controlGate.withPermits(1)(withFatalRecording(drainOneReadyCommand(input)));
|
|
2648
3129
|
if (isSessionNoRunnableCommand(result)) {
|
|
2649
3130
|
yield* annotateEdaSpan({
|
|
2650
3131
|
"eda.command.processed_count": processed.length,
|
|
@@ -2666,12 +3147,20 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2666
3147
|
"eda.model.id": input.modelSelection.modelId
|
|
2667
3148
|
});
|
|
2668
3149
|
yield* failIfFatal;
|
|
2669
|
-
const initial = yield*
|
|
3150
|
+
const { initial, recovery } = yield* admissionGate.withPermits(1)(Effect.gen(function* () {
|
|
3151
|
+
const initial = yield* currentReduced();
|
|
3152
|
+
return {
|
|
3153
|
+
initial,
|
|
3154
|
+
recovery: yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, {
|
|
3155
|
+
...input,
|
|
3156
|
+
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
3157
|
+
}))
|
|
3158
|
+
};
|
|
3159
|
+
}));
|
|
2670
3160
|
input = {
|
|
2671
3161
|
...input,
|
|
2672
3162
|
modelSelection: initial.modelSelection ?? input.modelSelection
|
|
2673
3163
|
};
|
|
2674
|
-
const recovery = yield* withFatalRecording(recoverSession(initial, startupRecoveryReason, input));
|
|
2675
3164
|
yield* requestStartupRecoveryCheckpointIfNeeded();
|
|
2676
3165
|
if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
|
|
2677
3166
|
});
|
|
@@ -2708,12 +3197,32 @@ const makeLiveSessionState = Effect.gen(function* () {
|
|
|
2708
3197
|
}
|
|
2709
3198
|
});
|
|
2710
3199
|
const start = Effect.fn(function* (input) {
|
|
2711
|
-
yield*
|
|
2712
|
-
|
|
3200
|
+
const reinvocations = yield* plannedReinvocations(yield* currentReduced());
|
|
3201
|
+
if (reinvocations.length === 0) {
|
|
3202
|
+
yield* runStartupRecovery(input);
|
|
3203
|
+
yield* forkSchedulingDelivery();
|
|
3204
|
+
yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
|
|
3205
|
+
return;
|
|
3206
|
+
}
|
|
3207
|
+
yield* controlGate.take(1);
|
|
3208
|
+
yield* Ref.set(recoveringInBackground, true);
|
|
3209
|
+
yield* Effect.gen(function* () {
|
|
3210
|
+
yield* annotateRunInput(input);
|
|
3211
|
+
yield* initialize(input);
|
|
3212
|
+
yield* keepAlive.withActiveWork("session-recovery", Effect.gen(function* () {
|
|
3213
|
+
yield* withFatalRecording(resumeInterruptedToolCalls(reinvocations));
|
|
3214
|
+
yield* runStartupRecoveryPass(input);
|
|
3215
|
+
}));
|
|
3216
|
+
}).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* () {
|
|
3217
|
+
const message = `EDA background startup recovery failed: ${Cause.pretty(cause)}`;
|
|
3218
|
+
yield* markFatalIfDurable(cause);
|
|
3219
|
+
yield* Ref.update(fatalInvariantViolation, (current) => current ?? message);
|
|
3220
|
+
yield* Effect.logError(message);
|
|
3221
|
+
})), Effect.withSpan("agent.session.recover.tools"), Effect.forkIn(runtimeScope));
|
|
2713
3222
|
});
|
|
2714
3223
|
yield* sinkRegistry.startSinkRunners({
|
|
2715
3224
|
appendDurableBatch,
|
|
2716
|
-
|
|
3225
|
+
initialProjection: yield* Ref.get(state),
|
|
2717
3226
|
publishEphemeral: publishEphemeralCore,
|
|
2718
3227
|
scope: runtimeScope
|
|
2719
3228
|
});
|
|
@@ -2730,10 +3239,10 @@ const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function
|
|
|
2730
3239
|
});
|
|
2731
3240
|
const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
|
|
2732
3241
|
const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
|
|
2733
|
-
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
2734
|
-
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !==
|
|
3242
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
|
|
3243
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 7 ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2735
3244
|
return {
|
|
2736
|
-
state:
|
|
3245
|
+
state: yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, foldReducedState)),
|
|
2737
3246
|
checkpointSeq
|
|
2738
3247
|
};
|
|
2739
3248
|
});
|
|
@@ -2743,10 +3252,10 @@ const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
|
|
|
2743
3252
|
const schemaVersion = reducerSchemaVersion(reducer);
|
|
2744
3253
|
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? reducer.initial : decodeReducerState(reducer, checkpoint.payload);
|
|
2745
3254
|
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2746
|
-
const
|
|
3255
|
+
const state = yield* store.eventsAfter(checkpointSeq).pipe(Stream.chunks, Stream.runFold(() => checkpointState, (current, page) => page.reduce(reducer.reduce, current)));
|
|
2747
3256
|
return [
|
|
2748
3257
|
reducer.name,
|
|
2749
|
-
|
|
3258
|
+
state,
|
|
2750
3259
|
checkpointSeq
|
|
2751
3260
|
];
|
|
2752
3261
|
}));
|
|
@@ -2790,7 +3299,7 @@ const commandWithId = (command, commandId) => {
|
|
|
2790
3299
|
}
|
|
2791
3300
|
};
|
|
2792
3301
|
const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
|
|
2793
|
-
if (
|
|
3302
|
+
if (!Schema.is(CommandAdmittedEvent)(event)) return;
|
|
2794
3303
|
const command = event.payload.command;
|
|
2795
3304
|
if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
|
|
2796
3305
|
if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
|
|
@@ -2813,6 +3322,6 @@ const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succee
|
|
|
2813
3322
|
const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
|
|
2814
3323
|
const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
|
|
2815
3324
|
//#endregion
|
|
2816
|
-
export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
|
|
3325
|
+
export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, LiveEventBus as m, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
|
|
2817
3326
|
|
|
2818
|
-
//# sourceMappingURL=session-state-
|
|
3327
|
+
//# sourceMappingURL=session-state-BehvUVyq.js.map
|