effect-durable-agent 0.1.0-alpha.1
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/CHANGELOG.md +10 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +21 -0
- package/README.md +305 -0
- package/SECURITY.md +8 -0
- package/dist/command-queues-CQ9cwRP7.d.ts +468 -0
- package/dist/commands-Ce1ec6kH.d.ts +104 -0
- package/dist/compaction-YayFKo_1.d.ts +144 -0
- package/dist/core-Hv3cFydL.d.ts +81 -0
- package/dist/domain/command-queues.d.ts +2 -0
- package/dist/domain/command-queues.js +97 -0
- package/dist/domain/command-queues.js.map +1 -0
- package/dist/domain/message-transcript.d.ts +2 -0
- package/dist/domain/message-transcript.js +111 -0
- package/dist/domain/message-transcript.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +996 -0
- package/dist/domain/reduced-state-schema.js +286 -0
- package/dist/domain/reduced-state-schema.js.map +1 -0
- package/dist/domain/reduced-state.d.ts +2 -0
- package/dist/domain/reduced-state.js +2 -0
- package/dist/durable-C3Rz7kg3.js +625 -0
- package/dist/durable-C3Rz7kg3.js.map +1 -0
- package/dist/durable-DlScwmCy.d.ts +7424 -0
- package/dist/durable-object-runtime-B7jwBY2R.js +1494 -0
- package/dist/durable-object-runtime-B7jwBY2R.js.map +1 -0
- package/dist/durable-object-runtime-pWv0ohlz.d.ts +257 -0
- package/dist/durable-object-storage-Czy7IPrh.d.ts +41 -0
- package/dist/events-Bb9-Cu-7.d.ts +918 -0
- package/dist/host/durable-object-runtime.d.ts +2 -0
- package/dist/host/durable-object-runtime.js +2 -0
- package/dist/host/durable-object-storage.d.ts +2 -0
- package/dist/host/durable-object-storage.js +0 -0
- package/dist/host/durable-object.d.ts +83 -0
- package/dist/host/durable-object.js +191 -0
- package/dist/host/durable-object.js.map +1 -0
- package/dist/host/websocket-wire.d.ts +2 -0
- package/dist/host/websocket-wire.js +88 -0
- package/dist/host/websocket-wire.js.map +1 -0
- package/dist/id-generator-C2Q15uZM.d.ts +33 -0
- package/dist/index-BVVgDSdq.d.ts +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/keep-alive-DYDsH6qN.d.ts +111 -0
- package/dist/keep-alive-p8dIcSVy.js +109 -0
- package/dist/keep-alive-p8dIcSVy.js.map +1 -0
- package/dist/message-transcript-BCHdHAe2.d.ts +32 -0
- package/dist/prompt-projector-9_02lk5-.d.ts +40 -0
- package/dist/reduced-state-C4nVVzz9.js +910 -0
- package/dist/reduced-state-C4nVVzz9.js.map +1 -0
- package/dist/reducer-registry-C0svUa63.d.ts +69 -0
- package/dist/runtime-C56FQxiL.d.ts +60 -0
- package/dist/services/compaction.d.ts +2 -0
- package/dist/services/compaction.js +426 -0
- package/dist/services/compaction.js.map +1 -0
- package/dist/services/id-generator.d.ts +2 -0
- package/dist/services/id-generator.js +56 -0
- package/dist/services/id-generator.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +2 -0
- package/dist/services/prompt-projector.js +27 -0
- package/dist/services/prompt-projector.js.map +1 -0
- package/dist/services/reducer-registry.d.ts +2 -0
- package/dist/services/reducer-registry.js +71 -0
- package/dist/services/reducer-registry.js.map +1 -0
- package/dist/services/runtime.d.ts +2 -0
- package/dist/services/runtime.js +84 -0
- package/dist/services/runtime.js.map +1 -0
- package/dist/services/session-query.d.ts +2 -0
- package/dist/services/session-query.js +2 -0
- package/dist/services/session-store.d.ts +2 -0
- package/dist/services/session-store.js +2 -0
- package/dist/services/sink-registry.d.ts +2 -0
- package/dist/services/sink-registry.js +2 -0
- package/dist/services/span-names.d.ts +28 -0
- package/dist/services/span-names.js +42 -0
- package/dist/services/span-names.js.map +1 -0
- package/dist/services/tool-registry.d.ts +2 -0
- package/dist/services/tool-registry.js +46 -0
- package/dist/services/tool-registry.js.map +1 -0
- package/dist/services/tracing.d.ts +76 -0
- package/dist/services/tracing.js +116 -0
- package/dist/services/tracing.js.map +1 -0
- package/dist/session-query-DOc1KanA.js +2930 -0
- package/dist/session-query-DOc1KanA.js.map +1 -0
- package/dist/session-query-DlRo5Ufc.d.ts +769 -0
- package/dist/session-store-D2Ore1QC.d.ts +295 -0
- package/dist/session-store-pYxQW9qh.js +214 -0
- package/dist/session-store-pYxQW9qh.js.map +1 -0
- package/dist/sink-registry-CFC6xjsN.js +312 -0
- package/dist/sink-registry-CFC6xjsN.js.map +1 -0
- package/dist/sink-registry-CIU0LD3m.d.ts +158 -0
- package/dist/testkit/layers.d.ts +101 -0
- package/dist/testkit/layers.js +108 -0
- package/dist/testkit/layers.js.map +1 -0
- package/dist/tool-registry-CcnkAAQK.d.ts +51 -0
- package/dist/tracing-BXHAkxkx.d.ts +111 -0
- package/dist/types/commands.d.ts +2 -0
- package/dist/types/commands.js +60 -0
- package/dist/types/commands.js.map +1 -0
- package/dist/types/core.d.ts +2 -0
- package/dist/types/core.js +68 -0
- package/dist/types/core.js.map +1 -0
- package/dist/types/events/durable.d.ts +2 -0
- package/dist/types/events/durable.js +2 -0
- package/dist/types/events.d.ts +4 -0
- package/dist/types/events.js +90 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/tracing.d.ts +2 -0
- package/dist/types/tracing.js +99 -0
- package/dist/types/tracing.js.map +1 -0
- package/dist/websocket-wire-DvOu_6BJ.d.ts +16773 -0
- package/docs/assets/architecture.svg +106 -0
- package/docs/assets/event-sequence.svg +143 -0
- package/docs/assets/gcp-trace.png +0 -0
- package/docs/message-steering.md +831 -0
- package/docs/releasing.md +57 -0
- package/docs/spec.md +774 -0
- package/docs/subagents.md +725 -0
- package/docs/testing.md +64 -0
- package/docs/ui-projection.md +742 -0
- package/docs/websocket-protocol.md +613 -0
- package/examples/001-no-tools/README.md +65 -0
- package/examples/001-no-tools/worker.ts +79 -0
- package/examples/002-slack-bridge/README.md +134 -0
- package/examples/002-slack-bridge/events.ts +115 -0
- package/examples/002-slack-bridge/reducer.ts +216 -0
- package/examples/002-slack-bridge/scenario.test.ts +223 -0
- package/examples/002-slack-bridge/sinks.ts +109 -0
- package/examples/002-slack-bridge/worker.ts +140 -0
- package/examples/003-sandbox-lifecycle/README.md +78 -0
- package/examples/003-sandbox-lifecycle/events.ts +203 -0
- package/examples/003-sandbox-lifecycle/reducer.ts +305 -0
- package/examples/003-sandbox-lifecycle/scenario.test.ts +202 -0
- package/examples/_shared/event-id.ts +12 -0
- package/examples/_shared/http.ts +27 -0
- package/examples/_shared/openai.ts +33 -0
- package/package.json +181 -0
- package/testing/offline-trace/README.md +63 -0
- package/tooling/oxlint/index.mjs +15 -0
- package/tooling/oxlint/rules/effect-span-from-catalog.mjs +152 -0
- package/tooling/oxlint/rules/span-catalog-format.mjs +74 -0
|
@@ -0,0 +1,2930 @@
|
|
|
1
|
+
import { CommandId, InferenceId, MessageId, Position, RunId, SequenceNumber, SubSequenceNumber, TurnId } from "./types/core.js";
|
|
2
|
+
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand, UserMessageContent } from "./types/commands.js";
|
|
3
|
+
import { makeEDARunTrace } from "./types/tracing.js";
|
|
4
|
+
import { Dn as inferenceFailedEventType, En as inferenceCompletedEventType, Gn as toolCallRejectedEventType, Jn as turnFailedEventType, Un as toolCallCreatedEventType, _r as UsagePayload, cr as FailurePayload, dr as PositionedEvent, fr as ProviderPartId, hr as ToolName, lr as ModelSelectionPayload, mr as SystemPromptText, pn as commandAdmittedEventType, ur as NonNegativeInt } from "./durable-C3Rz7kg3.js";
|
|
5
|
+
import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-C4nVVzz9.js";
|
|
6
|
+
import { a as EDASessionStoreError, c as hasEDASessionStoreError, f as ContextProjection, i as EDASessionStore, p as emptyContextProjection, t as CommittedDurableEvent } from "./session-store-pYxQW9qh.js";
|
|
7
|
+
import { durableMessageTranscript } from "./domain/message-transcript.js";
|
|
8
|
+
import { IdGenerator } from "./services/id-generator.js";
|
|
9
|
+
import { n as EventFactory, r as SessionContext, t as EDAKeepAlive } from "./keep-alive-p8dIcSVy.js";
|
|
10
|
+
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
11
|
+
import { CompactionRunner } from "./services/compaction.js";
|
|
12
|
+
import { i as LiveEventBus, n as EDASinkRegistry } from "./sink-registry-CFC6xjsN.js";
|
|
13
|
+
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
14
|
+
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
15
|
+
import { EDAToolRegistry } from "./services/tool-registry.js";
|
|
16
|
+
import * as Context from "effect/Context";
|
|
17
|
+
import * as Effect from "effect/Effect";
|
|
18
|
+
import * as Layer from "effect/Layer";
|
|
19
|
+
import * as Schema from "effect/Schema";
|
|
20
|
+
import * as Stream from "effect/Stream";
|
|
21
|
+
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
22
|
+
import * as Cause from "effect/Cause";
|
|
23
|
+
import * as Clock from "effect/Clock";
|
|
24
|
+
import * as Exit from "effect/Exit";
|
|
25
|
+
import * as Fiber from "effect/Fiber";
|
|
26
|
+
import * as Queue from "effect/Queue";
|
|
27
|
+
import * as Ref from "effect/Ref";
|
|
28
|
+
import * as Scope from "effect/Scope";
|
|
29
|
+
import * as Semaphore from "effect/Semaphore";
|
|
30
|
+
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
31
|
+
import * as Option from "effect/Option";
|
|
32
|
+
import * as PubSub from "effect/PubSub";
|
|
33
|
+
import * as Response from "effect/unstable/ai/Response";
|
|
34
|
+
//#region src/domain/dispatch-policy.ts
|
|
35
|
+
/** Durable/runtime evidence for active work blocking new queued commands. */
|
|
36
|
+
const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
|
|
37
|
+
commandId: CommandId,
|
|
38
|
+
runId: Schema.optionalKey(RunId)
|
|
39
|
+
});
|
|
40
|
+
/** Decide the next dispatch action from the canonical reduced replay state. */
|
|
41
|
+
const decideDispatch = (state) => {
|
|
42
|
+
const active = state.commandQueues.active;
|
|
43
|
+
if (active !== void 0) {
|
|
44
|
+
const activeDispatch = DispatchActiveCommand.make({
|
|
45
|
+
commandId: active.commandId,
|
|
46
|
+
...active.runId === void 0 ? {} : { runId: active.runId }
|
|
47
|
+
});
|
|
48
|
+
const control = pendingActiveControlCommand(state);
|
|
49
|
+
if (control === void 0) return {
|
|
50
|
+
_tag: "DispatchBlockedByActiveCommand",
|
|
51
|
+
active: activeDispatch
|
|
52
|
+
};
|
|
53
|
+
const candidate = toCandidate(control);
|
|
54
|
+
if (control.command._tag === "StopTurn") return {
|
|
55
|
+
_tag: "DispatchStopCommand",
|
|
56
|
+
command: candidate,
|
|
57
|
+
active: activeDispatch
|
|
58
|
+
};
|
|
59
|
+
if (control.command._tag === "CancelPendingMessage") return {
|
|
60
|
+
_tag: "DispatchCancelPendingMessage",
|
|
61
|
+
command: candidate,
|
|
62
|
+
active: activeDispatch
|
|
63
|
+
};
|
|
64
|
+
if (control.command._tag === "PromotePendingMessage") return {
|
|
65
|
+
_tag: "DispatchPromotePendingMessage",
|
|
66
|
+
command: candidate,
|
|
67
|
+
active: activeDispatch
|
|
68
|
+
};
|
|
69
|
+
if (control.command._tag !== "SubmitMessage") return {
|
|
70
|
+
_tag: "DispatchBlockedByActiveCommand",
|
|
71
|
+
active: activeDispatch
|
|
72
|
+
};
|
|
73
|
+
if (control.command.disposition === "interrupt") return {
|
|
74
|
+
_tag: "DispatchInterruptCommand",
|
|
75
|
+
command: candidate,
|
|
76
|
+
active: activeDispatch
|
|
77
|
+
};
|
|
78
|
+
return activeDispatch.runId === void 0 ? {
|
|
79
|
+
_tag: "DispatchBlockedByActiveCommand",
|
|
80
|
+
active: activeDispatch
|
|
81
|
+
} : {
|
|
82
|
+
_tag: "DispatchSteerCommand",
|
|
83
|
+
command: candidate,
|
|
84
|
+
active: activeDispatch
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const control = pendingActiveControlCommand(state);
|
|
88
|
+
if (control?.command._tag === "CancelPendingMessage") return {
|
|
89
|
+
_tag: "DispatchCancelPendingMessage",
|
|
90
|
+
command: toCandidate(control)
|
|
91
|
+
};
|
|
92
|
+
if (control?.command._tag === "PromotePendingMessage") return {
|
|
93
|
+
_tag: "DispatchPromotePendingMessage",
|
|
94
|
+
command: toCandidate(control)
|
|
95
|
+
};
|
|
96
|
+
const stop = control?.command._tag === "StopTurn" ? control : void 0;
|
|
97
|
+
if (stop !== void 0) return {
|
|
98
|
+
_tag: "DispatchStartCommand",
|
|
99
|
+
command: toCandidate(stop)
|
|
100
|
+
};
|
|
101
|
+
const next = nextIdleCommand(state);
|
|
102
|
+
if (next === "orphan-pending-messages") return {
|
|
103
|
+
_tag: "DispatchInvariantViolation",
|
|
104
|
+
messageIds: state.commandQueues.pendingSteers.map((message) => message.messageId)
|
|
105
|
+
};
|
|
106
|
+
return next === void 0 ? { _tag: "DispatchNoPendingCommand" } : {
|
|
107
|
+
_tag: "DispatchStartCommand",
|
|
108
|
+
command: toCandidate(next)
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
const nextIdleCommand = (state) => {
|
|
112
|
+
const pendingById = new Map(state.commandQueues.pendingCommands.map((command) => [command.commandId, command]));
|
|
113
|
+
for (const message of state.commandQueues.pendingSteers) {
|
|
114
|
+
const origin = pendingById.get(message.commandId);
|
|
115
|
+
if (origin !== void 0) return origin;
|
|
116
|
+
const resume = state.commandQueues.pendingCommands.find((command) => command.command._tag === "ResumePendingMessages" && command.command.messageIds.includes(message.messageId));
|
|
117
|
+
if (resume !== void 0) return resume;
|
|
118
|
+
}
|
|
119
|
+
if (state.commandQueues.pendingSteers.length > 0) return "orphan-pending-messages";
|
|
120
|
+
const interrupt = state.commandQueues.pendingCommands.find((command) => command.command._tag === "SubmitMessage" && command.command.disposition === "interrupt");
|
|
121
|
+
if (interrupt !== void 0) return interrupt;
|
|
122
|
+
for (const message of state.commandQueues.pendingQueue) {
|
|
123
|
+
const origin = pendingById.get(message.commandId);
|
|
124
|
+
if (origin !== void 0) return origin;
|
|
125
|
+
}
|
|
126
|
+
return state.commandQueues.pendingCommands.find((command) => command.command._tag === "ResumePendingMessages" || command.command._tag === "SubmitMessage" && !state.commandQueues.pausedQueue.some((message) => message.commandId === command.commandId));
|
|
127
|
+
};
|
|
128
|
+
const pendingActiveControlCommand = (state) => [...state.commandQueues.activeControlCommands].sort((left, right) => controlPriority(left.command) - controlPriority(right.command) || left.admittedSeq - right.admittedSeq)[0];
|
|
129
|
+
const controlPriority = (command) => {
|
|
130
|
+
switch (command._tag) {
|
|
131
|
+
case "StopTurn": return 0;
|
|
132
|
+
case "CancelPendingMessage": return 1;
|
|
133
|
+
case "PromotePendingMessage": return 2;
|
|
134
|
+
case "SubmitMessage": return 3;
|
|
135
|
+
case "ResumePendingMessages": return 4;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const toCandidate = (pending) => ({
|
|
139
|
+
commandId: pending.commandId,
|
|
140
|
+
command: pending.command,
|
|
141
|
+
...pending.admissionTrace === void 0 ? {} : { admissionTrace: pending.admissionTrace }
|
|
142
|
+
});
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region src/domain/run-continuation-policy.ts
|
|
145
|
+
/**
|
|
146
|
+
* Decide whether a completed turn should continue its run before run terminalization.
|
|
147
|
+
*
|
|
148
|
+
* All eligible steering messages are selected together at the boundary.
|
|
149
|
+
*/
|
|
150
|
+
const decideRunContinuation = (input) => {
|
|
151
|
+
const currentTurnTools = toolCallsForTurn(input.state, input.runId, input.turnId);
|
|
152
|
+
const created = currentTurnTools.filter((tool) => tool.decision?._tag === "Created");
|
|
153
|
+
const rejected = currentTurnTools.filter((tool) => tool.decision?._tag === "Rejected");
|
|
154
|
+
const providerExecuted = created.find((tool) => tool.decision?._tag === "Created" && tool.decision.providerExecuted);
|
|
155
|
+
if (providerExecuted !== void 0) return {
|
|
156
|
+
_tag: "FailRun",
|
|
157
|
+
error: FailurePayload.make({
|
|
158
|
+
message: `Provider-executed tool calls are unsupported: ${providerExecuted.decision?.toolName}`,
|
|
159
|
+
code: "tool.unsupported_provider_executed",
|
|
160
|
+
details: { toolCallId: providerExecuted.toolCallId }
|
|
161
|
+
})
|
|
162
|
+
};
|
|
163
|
+
if (rejected.length > 0) {
|
|
164
|
+
const correctionLimit = input.maxToolRejectionCorrections ?? 1;
|
|
165
|
+
if (countRejectedTurns(input.state, input.runId) > correctionLimit) return {
|
|
166
|
+
_tag: "FailRun",
|
|
167
|
+
error: FailurePayload.make({
|
|
168
|
+
message: "tool rejection correction exhausted",
|
|
169
|
+
code: "tool.rejection_correction_exhausted",
|
|
170
|
+
details: {
|
|
171
|
+
limit: correctionLimit,
|
|
172
|
+
rejectedToolCallIds: rejected.map((tool) => tool.toolCallId)
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
if (rejected.length > 0 || created.some((tool) => tool.decision?._tag === "Created" && tool.terminal !== void 0)) {
|
|
178
|
+
const steerings = pendingSteerings(input.state, input.runId);
|
|
179
|
+
return steerings.length === 0 ? { _tag: "ContinueWithToolFeedback" } : {
|
|
180
|
+
_tag: "ContinueWithSteering",
|
|
181
|
+
steerings
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const steerings = pendingSteerings(input.state, input.runId);
|
|
185
|
+
return steerings.length === 0 ? { _tag: "CompleteRun" } : {
|
|
186
|
+
_tag: "ContinueWithSteering",
|
|
187
|
+
steerings
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
const pendingSteerings = (state, runId) => {
|
|
191
|
+
const current = state.commandQueues.pendingSteers.filter((message) => message.targetRunId === void 0 || message.targetRunId === runId);
|
|
192
|
+
const currentIds = new Set(current.map((message) => message.messageId));
|
|
193
|
+
const legacy = (state.commandQueues.steeringByRun.get(runId) ?? []).filter((message) => !currentIds.has(message.messageId));
|
|
194
|
+
return [...current, ...legacy].sort((left, right) => ("effectiveSeq" in left ? left.effectiveSeq : left.queuedSeq) - ("effectiveSeq" in right ? right.effectiveSeq : right.queuedSeq));
|
|
195
|
+
};
|
|
196
|
+
const toolCallsForTurn = (state, runId, turnId) => Array.from(state.toolCalls.values()).filter((tool) => tool.decision?.runId === runId && tool.decision.turnId === turnId);
|
|
197
|
+
const countRejectedTurns = (state, runId) => {
|
|
198
|
+
const turnIds = /* @__PURE__ */ new Set();
|
|
199
|
+
for (const tool of state.toolCalls.values()) if (tool.decision?._tag === "Rejected" && tool.decision.runId === runId) turnIds.add(tool.decision.turnId);
|
|
200
|
+
return turnIds.size;
|
|
201
|
+
};
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/domain/recovery-policy.ts
|
|
204
|
+
/** Pure startup-recovery policy over one canonical durable snapshot. */
|
|
205
|
+
const planSessionRecovery = (state) => {
|
|
206
|
+
const recoverable = classifyRecoverableWork(state);
|
|
207
|
+
const pendingCommandsById = new Set(state.commandQueues.pendingCommands.map((command) => command.commandId));
|
|
208
|
+
const resumeOwnedMessageIds = new Set([...Array.from(state.commands.values()), ...state.commandQueues.pendingCommands].flatMap((command) => ("terminal" in command ? command.terminal === void 0 : true) && command.command?._tag === "ResumePendingMessages" ? command.command.messageIds : []));
|
|
209
|
+
const hasApplicableStop = recoverable.pendingStopRequests.some((request) => request.requestedRunId !== void 0 && request.requestedTurnId !== void 0);
|
|
210
|
+
const messageIdsToPause = hasApplicableStop ? [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) : [];
|
|
211
|
+
const pausedMessageIds = new Set(messageIdsToPause);
|
|
212
|
+
const stoppedRunIds = new Set(recoverable.pendingStopRequests.flatMap((request) => request.requestedRunId === void 0 ? [] : [request.requestedRunId]));
|
|
213
|
+
const continuationCommand = hasApplicableStop ? void 0 : recoverable.activeCommands.find((command) => {
|
|
214
|
+
const tag = command.command?._tag;
|
|
215
|
+
return (tag === "SubmitMessage" || tag === "ResumePendingMessages") && recoverable.activeRuns.some((run) => !stoppedRunIds.has(run.runId) && run.commandIds.includes(command.commandId));
|
|
216
|
+
});
|
|
217
|
+
const continuationRun = recoverable.activeRuns.find((run) => continuationCommand !== void 0 && !stoppedRunIds.has(run.runId) && run.commandIds.includes(continuationCommand.commandId));
|
|
218
|
+
const pendingMessageIds = new Set([...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId));
|
|
219
|
+
const sourceMessageIds = continuationCommand?.command?._tag === "ResumePendingMessages" ? continuationCommand.command.messageIds.filter((messageId) => pendingMessageIds.has(messageId)) : continuationCommand === void 0 ? [] : [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].filter((message) => message.commandId === continuationCommand.commandId).map((message) => message.messageId);
|
|
220
|
+
const eligibleSteerIds = continuationRun === void 0 ? [] : state.commandQueues.pendingSteers.filter((message) => message.targetRunId === void 0 || message.targetRunId === continuationRun.runId || continuationRun.commandIds.some((commandId) => state.runs.get(message.targetRunId)?.commandIds.includes(commandId) === true)).map((message) => message.messageId);
|
|
221
|
+
const continuationInputMessageIds = Array.from(new Set([...sourceMessageIds, ...eligibleSteerIds]));
|
|
222
|
+
const continuationInputIds = new Set(continuationInputMessageIds);
|
|
223
|
+
const messageIdsToResume = state.commandQueues.pendingSteers.filter((message) => !pausedMessageIds.has(message.messageId) && !continuationInputIds.has(message.messageId) && !pendingCommandsById.has(message.commandId) && !resumeOwnedMessageIds.has(message.messageId)).map((message) => message.messageId);
|
|
224
|
+
return {
|
|
225
|
+
activeCommands: recoverable.activeCommands,
|
|
226
|
+
activeRuns: recoverable.activeRuns,
|
|
227
|
+
activeTurns: recoverable.activeTurns,
|
|
228
|
+
activeInferences: recoverable.activeInferences,
|
|
229
|
+
openToolCalls: recoverable.openToolCalls,
|
|
230
|
+
pendingStopRequests: recoverable.pendingStopRequests,
|
|
231
|
+
openCompactions: recoverable.openCompactions,
|
|
232
|
+
messageIdsToPause,
|
|
233
|
+
messageIdsToResume,
|
|
234
|
+
...continuationCommand === void 0 || continuationRun === void 0 ? {} : { continuation: {
|
|
235
|
+
command: continuationCommand,
|
|
236
|
+
run: continuationRun,
|
|
237
|
+
inputMessageIds: continuationInputMessageIds
|
|
238
|
+
} }
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
const isSessionRecoveryPlanEmpty = (plan) => plan.activeCommands.length === 0 && plan.activeRuns.length === 0 && plan.activeTurns.length === 0 && plan.activeInferences.length === 0 && plan.openToolCalls.length === 0 && plan.pendingStopRequests.length === 0 && plan.openCompactions.length === 0 && plan.messageIdsToPause.length === 0 && plan.messageIdsToResume.length === 0 && plan.continuation === void 0;
|
|
242
|
+
//#endregion
|
|
243
|
+
//#region src/domain/run-terminal-policy.ts
|
|
244
|
+
/** Normal live-run failure policy. This is not startup recovery. */
|
|
245
|
+
const planRunFailure = (state) => ({ messageIdsToResume: state.commandQueues.pendingSteers.map((message) => message.messageId) });
|
|
246
|
+
/** Normal explicit Stop/Interrupt policy. This is not startup recovery. */
|
|
247
|
+
const planUserInterruption = (state) => ({ messageIdsToPause: [...state.commandQueues.pendingQueue, ...state.commandQueues.pendingSteers].map((message) => message.messageId) });
|
|
248
|
+
//#endregion
|
|
249
|
+
//#region src/services/started-boundary-guard.ts
|
|
250
|
+
/** Build a guard bound to the session's durable append boundary. */
|
|
251
|
+
const makeStartedBoundaryGuard = (state) => (spec) => {
|
|
252
|
+
const start = Effect.gen(function* () {
|
|
253
|
+
const startedEvent = yield* spec.start;
|
|
254
|
+
return yield* state.appendDurable(startedEvent);
|
|
255
|
+
});
|
|
256
|
+
const body = (started) => Effect.gen(function* () {
|
|
257
|
+
return {
|
|
258
|
+
started,
|
|
259
|
+
value: yield* spec.body(started)
|
|
260
|
+
};
|
|
261
|
+
});
|
|
262
|
+
const release = (_started, exit) => {
|
|
263
|
+
if (Exit.isSuccess(exit)) return Effect.void;
|
|
264
|
+
if (hasEDASessionStoreError(exit.cause)) return Effect.failCause(exit.cause);
|
|
265
|
+
const terminal = Cause.hasInterruptsOnly(exit.cause) ? spec.onInterrupt : spec.onFailure(failurePayloadFromCause(exit.cause));
|
|
266
|
+
return Effect.gen(function* () {
|
|
267
|
+
const terminalEvent = yield* terminal;
|
|
268
|
+
yield* state.appendDurable(terminalEvent);
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
return Effect.acquireUseRelease(start, body, release);
|
|
272
|
+
};
|
|
273
|
+
/** Flatten an unknown thrown/streamed error into the durable failure payload. */
|
|
274
|
+
const failurePayloadFromUnknown = (error) => {
|
|
275
|
+
if (error instanceof Error) return FailurePayload.make({
|
|
276
|
+
message: error.message !== "" ? error.message : error.name,
|
|
277
|
+
details: {
|
|
278
|
+
name: error.name,
|
|
279
|
+
stack: error.stack
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
if (typeof error === "string") return FailurePayload.make({ message: error });
|
|
283
|
+
return FailurePayload.make({
|
|
284
|
+
message: "Unknown error",
|
|
285
|
+
details: error
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
/** Flatten a started-boundary exit cause into the durable failure payload. */
|
|
289
|
+
const failurePayloadFromCause = (cause) => failurePayloadFromUnknown(Cause.squash(cause));
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/services/tool-executor.ts
|
|
292
|
+
/** Tool execution outcome after committing ToolCallCompleted. */
|
|
293
|
+
const ToolExecutionCompleted = Schema.TaggedStruct("ToolExecutionCompleted", {
|
|
294
|
+
committed: CommittedDurableEvent,
|
|
295
|
+
result: Schema.Unknown
|
|
296
|
+
});
|
|
297
|
+
/** Tool execution outcome after committing ToolCallFailed or cancellation-as-failure. */
|
|
298
|
+
const ToolExecutionFailed = Schema.TaggedStruct("ToolExecutionFailed", { committed: CommittedDurableEvent });
|
|
299
|
+
/** Outcome for tool calls the provider already executed and EDA must not rerun. */
|
|
300
|
+
const ToolExecutionSkipped = Schema.TaggedStruct("ToolExecutionSkipped", { reason: Schema.Literal("provider-executed") });
|
|
301
|
+
Schema.Union([
|
|
302
|
+
ToolExecutionCompleted,
|
|
303
|
+
ToolExecutionFailed,
|
|
304
|
+
ToolExecutionSkipped
|
|
305
|
+
]);
|
|
306
|
+
/** Failure when tool execution receives a committed event that is not ToolCallCreated. */
|
|
307
|
+
var ToolExecutionEventNotCreated = class extends Schema.TaggedErrorClass()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
|
|
308
|
+
/** Construct the live tool-executor implementation. */
|
|
309
|
+
const makeLiveToolExecutor = Effect.gen(function* () {
|
|
310
|
+
const events = yield* EventFactory;
|
|
311
|
+
const ids = yield* IdGenerator;
|
|
312
|
+
const registry = yield* EDAToolRegistry;
|
|
313
|
+
const session = yield* SessionContext;
|
|
314
|
+
const failToolCall = (input, created, error) => Effect.gen(function* () {
|
|
315
|
+
const event = yield* events.toolCallFailed({
|
|
316
|
+
toolCallId: created.event.payload.toolCallId,
|
|
317
|
+
error,
|
|
318
|
+
promptPart: toolFailedPromptPart(created, error)
|
|
319
|
+
});
|
|
320
|
+
const committed = yield* input.eventSink.appendDurable(event);
|
|
321
|
+
return ToolExecutionFailed.make({ committed });
|
|
322
|
+
});
|
|
323
|
+
return { executeCreated: Effect.fn("agent.tool")(function* (input) {
|
|
324
|
+
const created = yield* requireToolCallCreated(input.created);
|
|
325
|
+
yield* annotateEdaSpan({
|
|
326
|
+
"eda.tool_call.id": created.event.payload.toolCallId,
|
|
327
|
+
"eda.tool.name": created.event.payload.promptPart.name,
|
|
328
|
+
"eda.tool.provider_executed": created.event.payload.promptPart.providerExecuted
|
|
329
|
+
});
|
|
330
|
+
if (created.event.payload.promptPart.providerExecuted) {
|
|
331
|
+
const outcome = ToolExecutionSkipped.make({ reason: "provider-executed" });
|
|
332
|
+
yield* annotateEdaSpan({ "eda.tool.outcome": outcome._tag });
|
|
333
|
+
return {
|
|
334
|
+
created,
|
|
335
|
+
outcome
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
const guarded = yield* makeStartedBoundaryGuard(input.eventSink)({
|
|
339
|
+
start: events.toolCallStarted({ toolCallId: created.event.payload.toolCallId }),
|
|
340
|
+
body: () => Effect.gen(function* () {
|
|
341
|
+
const handled = yield* registry.execute(created.event.payload.promptPart.name, created.event.payload.promptPart.params, {
|
|
342
|
+
toolCallId: created.event.payload.toolCallId,
|
|
343
|
+
sessionId: session.sessionId,
|
|
344
|
+
makeEventId: ids.makeEventId,
|
|
345
|
+
emitDurable: input.eventSink.appendDurable
|
|
346
|
+
}).pipe(Effect.map((result) => ({
|
|
347
|
+
_tag: "Succeeded",
|
|
348
|
+
result
|
|
349
|
+
})), Effect.catchCause((cause) => hasEDASessionStoreError(cause) ? Effect.failCause(cause) : Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.succeed({
|
|
350
|
+
_tag: "Failed",
|
|
351
|
+
error: failurePayloadFromCause(cause)
|
|
352
|
+
})));
|
|
353
|
+
switch (handled._tag) {
|
|
354
|
+
case "Succeeded": {
|
|
355
|
+
const event = yield* events.toolCallCompleted({
|
|
356
|
+
toolCallId: created.event.payload.toolCallId,
|
|
357
|
+
promptPart: toolCompletedPromptPart(created, handled.result)
|
|
358
|
+
});
|
|
359
|
+
const committed = yield* input.eventSink.appendDurable(event);
|
|
360
|
+
return ToolExecutionCompleted.make({
|
|
361
|
+
committed,
|
|
362
|
+
result: handled.result
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
case "Failed": return yield* failToolCall(input, created, handled.error);
|
|
366
|
+
default: return yield* Effect.die(assertNeverError(handled, "tool handler outcome"));
|
|
367
|
+
}
|
|
368
|
+
}),
|
|
369
|
+
onFailure: (error) => events.toolCallFailed({
|
|
370
|
+
toolCallId: created.event.payload.toolCallId,
|
|
371
|
+
error,
|
|
372
|
+
promptPart: toolFailedPromptPart(created, error)
|
|
373
|
+
}),
|
|
374
|
+
onInterrupt: Effect.gen(function* () {
|
|
375
|
+
const error = FailurePayload.make({
|
|
376
|
+
message: "tool call interrupted: interrupted",
|
|
377
|
+
code: "tool.interrupted",
|
|
378
|
+
details: {
|
|
379
|
+
reason: "interrupted",
|
|
380
|
+
toolCallId: created.event.payload.toolCallId
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
return yield* events.toolCallFailed({
|
|
384
|
+
toolCallId: created.event.payload.toolCallId,
|
|
385
|
+
error,
|
|
386
|
+
promptPart: toolFailedPromptPart(created, error)
|
|
387
|
+
});
|
|
388
|
+
})
|
|
389
|
+
});
|
|
390
|
+
yield* annotateEdaSpan({ "eda.tool.outcome": guarded.value._tag });
|
|
391
|
+
return {
|
|
392
|
+
created,
|
|
393
|
+
outcome: guarded.value
|
|
394
|
+
};
|
|
395
|
+
}) };
|
|
396
|
+
});
|
|
397
|
+
/** Executes sealed framework-owned tool calls and commits tool lifecycle boundaries. */
|
|
398
|
+
var ToolExecutor = class ToolExecutor extends Context.Service()("@effect-durable-agent/ToolExecutor") {
|
|
399
|
+
static Live = Layer.effect(ToolExecutor, makeLiveToolExecutor);
|
|
400
|
+
};
|
|
401
|
+
const toolCompletedPromptPart = (created, result) => ({
|
|
402
|
+
...Prompt.toolResultPart({
|
|
403
|
+
id: created.event.payload.promptPart.id,
|
|
404
|
+
name: created.event.payload.promptPart.name,
|
|
405
|
+
isFailure: false,
|
|
406
|
+
result
|
|
407
|
+
}),
|
|
408
|
+
id: created.event.payload.promptPart.id,
|
|
409
|
+
name: created.event.payload.promptPart.name,
|
|
410
|
+
isFailure: false
|
|
411
|
+
});
|
|
412
|
+
const toolFailedPromptPart = (created, error) => ({
|
|
413
|
+
...Prompt.toolResultPart({
|
|
414
|
+
id: created.event.payload.promptPart.id,
|
|
415
|
+
name: created.event.payload.promptPart.name,
|
|
416
|
+
isFailure: true,
|
|
417
|
+
result: error
|
|
418
|
+
}),
|
|
419
|
+
id: created.event.payload.promptPart.id,
|
|
420
|
+
name: created.event.payload.promptPart.name,
|
|
421
|
+
isFailure: true,
|
|
422
|
+
result: error
|
|
423
|
+
});
|
|
424
|
+
const isToolCallCreated$1 = (committed) => committed.event.type === toolCallCreatedEventType;
|
|
425
|
+
const requireToolCallCreated = (committed) => isToolCallCreated$1(committed) ? Effect.succeed(committed) : new ToolExecutionEventNotCreated({ eventType: committed.event.type });
|
|
426
|
+
//#endregion
|
|
427
|
+
//#region src/domain/inference-state.ts
|
|
428
|
+
/** Initial empty fold state for a newly committed inference. */
|
|
429
|
+
const initialInferenceState = (identity) => ({
|
|
430
|
+
...identity,
|
|
431
|
+
phase: "streaming",
|
|
432
|
+
assistantText: "",
|
|
433
|
+
reasoningText: "",
|
|
434
|
+
responseMetadata: Option.none(),
|
|
435
|
+
drafts: /* @__PURE__ */ new Map(),
|
|
436
|
+
decisions: []
|
|
437
|
+
});
|
|
438
|
+
/** Pure transition for one provider stream part. */
|
|
439
|
+
const step = (state, input) => {
|
|
440
|
+
if (state.phase === "sealed") return {
|
|
441
|
+
next: state,
|
|
442
|
+
emissions: []
|
|
443
|
+
};
|
|
444
|
+
switch (input.type) {
|
|
445
|
+
case "text-start":
|
|
446
|
+
case "text-end":
|
|
447
|
+
case "reasoning-start":
|
|
448
|
+
case "reasoning-end": return {
|
|
449
|
+
next: state,
|
|
450
|
+
emissions: []
|
|
451
|
+
};
|
|
452
|
+
case "text-delta": return recordTextDelta(state, input);
|
|
453
|
+
case "reasoning-delta": return recordReasoningDelta(state, input);
|
|
454
|
+
case "tool-params-start": return recordToolParamsStart(state, input);
|
|
455
|
+
case "tool-params-delta": return recordToolParamsDelta(state, input);
|
|
456
|
+
case "tool-params-end": return recordToolParamsEnd(state, input);
|
|
457
|
+
case "tool-call": return recordToolCall(state, input);
|
|
458
|
+
case "response-metadata": return {
|
|
459
|
+
next: {
|
|
460
|
+
...state,
|
|
461
|
+
responseMetadata: Option.some(input.responseMetadata)
|
|
462
|
+
},
|
|
463
|
+
emissions: []
|
|
464
|
+
};
|
|
465
|
+
case "finish": return finalizeInference(state, input);
|
|
466
|
+
case "error": return failInference(state, input.error);
|
|
467
|
+
default: return assertNever(input, "inference step input");
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
const recordTextDelta = (state, input) => {
|
|
471
|
+
return {
|
|
472
|
+
next: {
|
|
473
|
+
...state,
|
|
474
|
+
assistantText: `${state.assistantText}${input.delta}`
|
|
475
|
+
},
|
|
476
|
+
emissions: [{
|
|
477
|
+
kind: "ephemeral",
|
|
478
|
+
event: {
|
|
479
|
+
type: "TextDelta",
|
|
480
|
+
payload: {
|
|
481
|
+
providerPartId: input.providerPartId,
|
|
482
|
+
delta: input.delta
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}]
|
|
486
|
+
};
|
|
487
|
+
};
|
|
488
|
+
const recordReasoningDelta = (state, input) => {
|
|
489
|
+
return {
|
|
490
|
+
next: {
|
|
491
|
+
...state,
|
|
492
|
+
reasoningText: `${state.reasoningText}${input.delta}`
|
|
493
|
+
},
|
|
494
|
+
emissions: [{
|
|
495
|
+
kind: "ephemeral",
|
|
496
|
+
event: {
|
|
497
|
+
type: "ReasoningDelta",
|
|
498
|
+
payload: {
|
|
499
|
+
providerPartId: input.providerPartId,
|
|
500
|
+
delta: input.delta
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}]
|
|
504
|
+
};
|
|
505
|
+
};
|
|
506
|
+
const recordToolParamsStart = (state, input) => {
|
|
507
|
+
if (state.drafts.has(input.providerPartId)) return {
|
|
508
|
+
next: state,
|
|
509
|
+
emissions: []
|
|
510
|
+
};
|
|
511
|
+
const draft = {
|
|
512
|
+
runId: state.runId,
|
|
513
|
+
turnId: state.turnId,
|
|
514
|
+
inferenceId: state.inferenceId,
|
|
515
|
+
providerPartId: input.providerPartId,
|
|
516
|
+
toolCallId: input.toolCallId,
|
|
517
|
+
toolName: input.toolName,
|
|
518
|
+
providerExecuted: input.providerExecuted,
|
|
519
|
+
paramsText: "",
|
|
520
|
+
status: "streaming"
|
|
521
|
+
};
|
|
522
|
+
return {
|
|
523
|
+
next: {
|
|
524
|
+
...state,
|
|
525
|
+
drafts: new Map(state.drafts).set(input.providerPartId, draft)
|
|
526
|
+
},
|
|
527
|
+
emissions: [{
|
|
528
|
+
kind: "ephemeral",
|
|
529
|
+
event: {
|
|
530
|
+
type: "ToolParamsStart",
|
|
531
|
+
payload: {
|
|
532
|
+
providerPartId: input.providerPartId,
|
|
533
|
+
toolCallId: input.toolCallId,
|
|
534
|
+
toolName: input.toolName,
|
|
535
|
+
providerExecuted: input.providerExecuted
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}]
|
|
539
|
+
};
|
|
540
|
+
};
|
|
541
|
+
const recordToolParamsDelta = (state, input) => {
|
|
542
|
+
const draft = state.drafts.get(input.providerPartId);
|
|
543
|
+
if (draft === void 0 || draft.status !== "streaming") return {
|
|
544
|
+
next: state,
|
|
545
|
+
emissions: []
|
|
546
|
+
};
|
|
547
|
+
const nextDraft = {
|
|
548
|
+
...draft,
|
|
549
|
+
paramsText: `${draft.paramsText}${input.delta}`
|
|
550
|
+
};
|
|
551
|
+
return {
|
|
552
|
+
next: {
|
|
553
|
+
...state,
|
|
554
|
+
drafts: new Map(state.drafts).set(input.providerPartId, nextDraft)
|
|
555
|
+
},
|
|
556
|
+
emissions: [{
|
|
557
|
+
kind: "ephemeral",
|
|
558
|
+
event: {
|
|
559
|
+
type: "ToolParamsDelta",
|
|
560
|
+
payload: {
|
|
561
|
+
providerPartId: input.providerPartId,
|
|
562
|
+
toolCallId: draft.toolCallId,
|
|
563
|
+
delta: input.delta
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}]
|
|
567
|
+
};
|
|
568
|
+
};
|
|
569
|
+
const recordToolParamsEnd = (state, input) => {
|
|
570
|
+
const draft = state.drafts.get(input.providerPartId);
|
|
571
|
+
if (draft === void 0 || draft.status !== "streaming") return {
|
|
572
|
+
next: state,
|
|
573
|
+
emissions: []
|
|
574
|
+
};
|
|
575
|
+
const nextDraft = {
|
|
576
|
+
...draft,
|
|
577
|
+
status: "ended"
|
|
578
|
+
};
|
|
579
|
+
return {
|
|
580
|
+
next: {
|
|
581
|
+
...state,
|
|
582
|
+
drafts: new Map(state.drafts).set(input.providerPartId, nextDraft)
|
|
583
|
+
},
|
|
584
|
+
emissions: [{
|
|
585
|
+
kind: "ephemeral",
|
|
586
|
+
event: {
|
|
587
|
+
type: "ToolParamsEnd",
|
|
588
|
+
payload: {
|
|
589
|
+
providerPartId: input.providerPartId,
|
|
590
|
+
toolCallId: draft.toolCallId
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}]
|
|
594
|
+
};
|
|
595
|
+
};
|
|
596
|
+
const recordToolCall = (state, input) => {
|
|
597
|
+
const draft = state.drafts.get(input.providerPartId);
|
|
598
|
+
const decision = makeToolCallDecision(state, input, draft?.toolCallId ?? input.toolCallId);
|
|
599
|
+
const nextDraft = draft === void 0 ? void 0 : markDraft(draft, decision);
|
|
600
|
+
const nextDrafts = nextDraft === void 0 ? state.drafts : new Map(state.drafts).set(input.providerPartId, nextDraft);
|
|
601
|
+
return {
|
|
602
|
+
next: {
|
|
603
|
+
...state,
|
|
604
|
+
drafts: nextDrafts,
|
|
605
|
+
decisions: upsertDecision(state.decisions, decision)
|
|
606
|
+
},
|
|
607
|
+
emissions: []
|
|
608
|
+
};
|
|
609
|
+
};
|
|
610
|
+
const makeToolCallDecision = (state, input, toolCallId) => {
|
|
611
|
+
const fields = {
|
|
612
|
+
runId: state.runId,
|
|
613
|
+
turnId: state.turnId,
|
|
614
|
+
inferenceId: state.inferenceId,
|
|
615
|
+
providerPartId: input.providerPartId,
|
|
616
|
+
toolCallId,
|
|
617
|
+
toolName: input.toolName,
|
|
618
|
+
params: input.params,
|
|
619
|
+
providerExecuted: input.providerExecuted
|
|
620
|
+
};
|
|
621
|
+
switch (input.validation._tag) {
|
|
622
|
+
case "ValidToolParams": return {
|
|
623
|
+
...fields,
|
|
624
|
+
_tag: "ToolCallCreatedDecision",
|
|
625
|
+
params: input.validation.params
|
|
626
|
+
};
|
|
627
|
+
case "UnknownTool": return rejectToolCall(fields, "unknown-tool", `Unknown tool: ${input.toolName}`);
|
|
628
|
+
case "InvalidToolParams": return rejectToolCall(fields, "invalid-params", input.validation.message);
|
|
629
|
+
default: return assertNever(input.validation, "tool validation");
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
const rejectToolCall = (fields, reason, message) => ({
|
|
633
|
+
...fields,
|
|
634
|
+
_tag: "ToolCallRejectedDecision",
|
|
635
|
+
reason,
|
|
636
|
+
error: { message },
|
|
637
|
+
modelFeedback: `Tool ${fields.toolName} arguments were rejected: ${message}`
|
|
638
|
+
});
|
|
639
|
+
const markDraft = (draft, decision) => ({
|
|
640
|
+
...draft,
|
|
641
|
+
status: decision._tag === "ToolCallCreatedDecision" ? "staged-created" : "staged-rejected"
|
|
642
|
+
});
|
|
643
|
+
const upsertDecision = (decisions, decision) => [...decisions.filter((existing) => existing.providerPartId !== decision.providerPartId), decision];
|
|
644
|
+
const finalizeInference = (state, input) => ({
|
|
645
|
+
next: {
|
|
646
|
+
...state,
|
|
647
|
+
phase: "sealed"
|
|
648
|
+
},
|
|
649
|
+
emissions: [{
|
|
650
|
+
kind: "finalize",
|
|
651
|
+
events: [...state.decisions.flatMap(decisionToPayloads), {
|
|
652
|
+
type: "InferenceCompleted",
|
|
653
|
+
payload: {
|
|
654
|
+
runId: state.runId,
|
|
655
|
+
turnId: state.turnId,
|
|
656
|
+
inferenceId: state.inferenceId,
|
|
657
|
+
...input.finishReason === void 0 ? {} : { finishReason: input.finishReason },
|
|
658
|
+
...input.usage === void 0 ? {} : { usage: input.usage },
|
|
659
|
+
...Option.isNone(state.responseMetadata) ? {} : { responseMetadata: state.responseMetadata.value },
|
|
660
|
+
...input.finishMetadata === void 0 ? {} : { finishMetadata: input.finishMetadata }
|
|
661
|
+
}
|
|
662
|
+
}]
|
|
663
|
+
}]
|
|
664
|
+
});
|
|
665
|
+
const failInference = (state, error) => ({
|
|
666
|
+
next: {
|
|
667
|
+
...state,
|
|
668
|
+
phase: "sealed"
|
|
669
|
+
},
|
|
670
|
+
emissions: [{
|
|
671
|
+
kind: "fail",
|
|
672
|
+
payload: {
|
|
673
|
+
runId: state.runId,
|
|
674
|
+
turnId: state.turnId,
|
|
675
|
+
inferenceId: state.inferenceId,
|
|
676
|
+
error
|
|
677
|
+
}
|
|
678
|
+
}]
|
|
679
|
+
});
|
|
680
|
+
const decisionToPayloads = (decision) => {
|
|
681
|
+
const payload = {
|
|
682
|
+
runId: decision.runId,
|
|
683
|
+
turnId: decision.turnId,
|
|
684
|
+
inferenceId: decision.inferenceId,
|
|
685
|
+
toolCallId: decision.toolCallId,
|
|
686
|
+
promptPart: toolCallPromptPart(decision)
|
|
687
|
+
};
|
|
688
|
+
if (decision._tag === "ToolCallRejectedDecision") return [{
|
|
689
|
+
type: "ToolCallRejected",
|
|
690
|
+
payload: {
|
|
691
|
+
...payload,
|
|
692
|
+
promptPart: toolRejectedPromptPart(decision)
|
|
693
|
+
}
|
|
694
|
+
}];
|
|
695
|
+
return [{
|
|
696
|
+
type: "ToolCallCreated",
|
|
697
|
+
payload
|
|
698
|
+
}];
|
|
699
|
+
};
|
|
700
|
+
const toolCallPromptPart = (decision) => ({
|
|
701
|
+
...Prompt.toolCallPart({
|
|
702
|
+
id: decision.providerPartId,
|
|
703
|
+
name: decision.toolName,
|
|
704
|
+
params: decision.params,
|
|
705
|
+
providerExecuted: decision.providerExecuted
|
|
706
|
+
}),
|
|
707
|
+
id: decision.providerPartId,
|
|
708
|
+
name: decision.toolName
|
|
709
|
+
});
|
|
710
|
+
const toolRejectedPromptPart = (decision) => ({
|
|
711
|
+
...Prompt.toolResultPart({
|
|
712
|
+
id: decision.providerPartId,
|
|
713
|
+
name: decision.toolName,
|
|
714
|
+
isFailure: true,
|
|
715
|
+
result: {
|
|
716
|
+
message: decision.error.message,
|
|
717
|
+
reason: decision.reason,
|
|
718
|
+
modelFeedback: decision.modelFeedback
|
|
719
|
+
}
|
|
720
|
+
}),
|
|
721
|
+
id: decision.providerPartId,
|
|
722
|
+
name: decision.toolName,
|
|
723
|
+
isFailure: true,
|
|
724
|
+
result: {
|
|
725
|
+
message: decision.error.message,
|
|
726
|
+
reason: decision.reason,
|
|
727
|
+
modelFeedback: decision.modelFeedback
|
|
728
|
+
}
|
|
729
|
+
});
|
|
730
|
+
Schema.Struct({
|
|
731
|
+
runId: RunId,
|
|
732
|
+
turnId: TurnId,
|
|
733
|
+
inferenceId: InferenceId
|
|
734
|
+
});
|
|
735
|
+
/** Terminal result when the inference stream reached a provider finish part. */
|
|
736
|
+
const InferenceRunFinished = Schema.TaggedStruct("InferenceRunFinished", {
|
|
737
|
+
committed: Schema.Array(CommittedDurableEvent),
|
|
738
|
+
assistantText: Schema.String,
|
|
739
|
+
reasoningText: Schema.String,
|
|
740
|
+
responseParts: Schema.Array(Schema.Any)
|
|
741
|
+
});
|
|
742
|
+
/** Terminal result when the inference stream reached or synthesized an error part. */
|
|
743
|
+
const InferenceRunFailed = Schema.TaggedStruct("InferenceRunFailed", { committed: Schema.Array(CommittedDurableEvent) });
|
|
744
|
+
/** Terminal variants for a consumed provider inference stream. */
|
|
745
|
+
const InferenceRunTerminal = Schema.Union([InferenceRunFinished, InferenceRunFailed]);
|
|
746
|
+
/** Summary returned after one provider inference stream is consumed. */
|
|
747
|
+
const InferenceRunResult = Schema.Struct({
|
|
748
|
+
started: CommittedDurableEvent,
|
|
749
|
+
partsRecorded: NonNegativeInt,
|
|
750
|
+
terminal: InferenceRunTerminal
|
|
751
|
+
});
|
|
752
|
+
Schema.TaggedErrorClass()("UnsupportedInferencePart", {
|
|
753
|
+
partType: Schema.String,
|
|
754
|
+
reason: Schema.String
|
|
755
|
+
});
|
|
756
|
+
/** Construct the live inference-runner implementation. */
|
|
757
|
+
const makeLiveInferenceRunner = Effect.gen(function* () {
|
|
758
|
+
const ids = yield* IdGenerator;
|
|
759
|
+
const events = yield* EventFactory;
|
|
760
|
+
const languageModel = yield* LanguageModel.LanguageModel;
|
|
761
|
+
const toolRegistry = yield* EDAToolRegistry;
|
|
762
|
+
const recordPart = (eventSink, state, part, setLatestState) => Effect.gen(function* () {
|
|
763
|
+
if (state.inference.phase === "sealed") {
|
|
764
|
+
yield* Effect.logWarning("dropping provider part after terminal inference boundary", {
|
|
765
|
+
inferenceId: state.inference.inferenceId,
|
|
766
|
+
partType: part.type
|
|
767
|
+
});
|
|
768
|
+
return state;
|
|
769
|
+
}
|
|
770
|
+
if (isProviderSidebandPart(part) || isIgnoredToolResultPart(part)) {
|
|
771
|
+
yield* Effect.logDebug("dropping provider sideband response part", {
|
|
772
|
+
inferenceId: state.inference.inferenceId,
|
|
773
|
+
partType: part.type
|
|
774
|
+
});
|
|
775
|
+
return {
|
|
776
|
+
...state,
|
|
777
|
+
partsRecorded: state.partsRecorded + 1
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
const input = yield* makeStepInput(state.inference, part);
|
|
781
|
+
const stepped = step(state.inference, input);
|
|
782
|
+
const responseContext = recordResponseContext(state.responseContext, part);
|
|
783
|
+
const nextBeforeEmissions = {
|
|
784
|
+
inference: stepped.next,
|
|
785
|
+
partsRecorded: state.partsRecorded + 1,
|
|
786
|
+
terminal: state.terminal,
|
|
787
|
+
responseContext
|
|
788
|
+
};
|
|
789
|
+
yield* setLatestState(nextBeforeEmissions);
|
|
790
|
+
const terminal = yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, responseContextToParts(responseContext));
|
|
791
|
+
return {
|
|
792
|
+
...nextBeforeEmissions,
|
|
793
|
+
terminal: terminal ?? state.terminal
|
|
794
|
+
};
|
|
795
|
+
});
|
|
796
|
+
const makeStepInput = (state, part) => Effect.gen(function* () {
|
|
797
|
+
switch (part.type) {
|
|
798
|
+
case "text-start":
|
|
799
|
+
case "text-end":
|
|
800
|
+
case "reasoning-start":
|
|
801
|
+
case "reasoning-end": return {
|
|
802
|
+
type: part.type,
|
|
803
|
+
providerPartId: ProviderPartId.make(part.id)
|
|
804
|
+
};
|
|
805
|
+
case "text-delta":
|
|
806
|
+
case "reasoning-delta": return {
|
|
807
|
+
type: part.type,
|
|
808
|
+
providerPartId: ProviderPartId.make(part.id),
|
|
809
|
+
delta: part.delta
|
|
810
|
+
};
|
|
811
|
+
case "tool-params-start": {
|
|
812
|
+
if (part.providerExecuted) return unsupportedProviderExecutedTool(part.name, part.id);
|
|
813
|
+
const providerPartId = ProviderPartId.make(part.id);
|
|
814
|
+
return {
|
|
815
|
+
type: "tool-params-start",
|
|
816
|
+
providerPartId,
|
|
817
|
+
toolCallId: state.drafts.get(providerPartId)?.toolCallId ?? (yield* ids.makeToolCallId()),
|
|
818
|
+
toolName: ToolName.make(part.name),
|
|
819
|
+
providerExecuted: part.providerExecuted
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
case "tool-params-delta": return {
|
|
823
|
+
type: "tool-params-delta",
|
|
824
|
+
providerPartId: ProviderPartId.make(part.id),
|
|
825
|
+
delta: part.delta
|
|
826
|
+
};
|
|
827
|
+
case "tool-params-end": return {
|
|
828
|
+
type: "tool-params-end",
|
|
829
|
+
providerPartId: ProviderPartId.make(part.id)
|
|
830
|
+
};
|
|
831
|
+
case "tool-call": {
|
|
832
|
+
if (part.providerExecuted) return unsupportedProviderExecutedTool(part.name, part.id);
|
|
833
|
+
const providerPartId = ProviderPartId.make(part.id);
|
|
834
|
+
return {
|
|
835
|
+
type: "tool-call",
|
|
836
|
+
providerPartId,
|
|
837
|
+
toolCallId: state.drafts.get(providerPartId)?.toolCallId ?? (yield* ids.makeToolCallId()),
|
|
838
|
+
toolName: ToolName.make(part.name),
|
|
839
|
+
params: part.params,
|
|
840
|
+
providerExecuted: part.providerExecuted,
|
|
841
|
+
validation: yield* validateToolCall(part.name, part.params)
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
case "tool-result": return unsupportedProviderExecutedTool(part.name, part.id);
|
|
845
|
+
case "response-metadata": return {
|
|
846
|
+
type: "response-metadata",
|
|
847
|
+
responseMetadata: makeResponseMetadata(part)
|
|
848
|
+
};
|
|
849
|
+
case "finish": return {
|
|
850
|
+
type: "finish",
|
|
851
|
+
finishReason: part.reason,
|
|
852
|
+
usage: makeUsagePayload(part.usage),
|
|
853
|
+
finishMetadata: makeFinishMetadata(part)
|
|
854
|
+
};
|
|
855
|
+
case "error": return {
|
|
856
|
+
type: "error",
|
|
857
|
+
error: failurePayloadFromUnknown(part.error)
|
|
858
|
+
};
|
|
859
|
+
case "tool-approval-request":
|
|
860
|
+
case "file":
|
|
861
|
+
case "source": return yield* Effect.die(/* @__PURE__ */ new Error(`Provider sideband part escaped no-op handling: ${part.type}`));
|
|
862
|
+
default: return yield* Effect.die(assertNeverError(part, "inference stream part"));
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
const validateToolCall = (toolName, params) => Effect.gen(function* () {
|
|
866
|
+
const schema = yield* toolRegistry.getParamsSchema(ToolName.make(toolName));
|
|
867
|
+
if (schema === void 0) return { _tag: "UnknownTool" };
|
|
868
|
+
return validateParams(schema, params);
|
|
869
|
+
});
|
|
870
|
+
const interpretEmissions = (eventSink, emissions, state, responseParts) => Effect.gen(function* () {
|
|
871
|
+
let terminal;
|
|
872
|
+
for (const emission of emissions) switch (emission.kind) {
|
|
873
|
+
case "ephemeral":
|
|
874
|
+
yield* publishEphemeral(eventSink, emission.event);
|
|
875
|
+
break;
|
|
876
|
+
case "finalize":
|
|
877
|
+
terminal = yield* commitFinalize(eventSink, emission.events, state, responseParts);
|
|
878
|
+
break;
|
|
879
|
+
case "fail":
|
|
880
|
+
terminal = yield* commitFailure(eventSink, emission.payload, state, responseParts);
|
|
881
|
+
break;
|
|
882
|
+
default: return yield* Effect.die(assertNeverError(emission, "inference emission"));
|
|
883
|
+
}
|
|
884
|
+
return terminal;
|
|
885
|
+
});
|
|
886
|
+
const publishEphemeral = (eventSink, emission) => Effect.gen(function* () {
|
|
887
|
+
switch (emission.type) {
|
|
888
|
+
case "TextDelta": {
|
|
889
|
+
const event = yield* events.textDelta(emission.payload);
|
|
890
|
+
yield* eventSink.publishEphemeral(event);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
case "ReasoningDelta": {
|
|
894
|
+
const event = yield* events.reasoningDelta(emission.payload);
|
|
895
|
+
yield* eventSink.publishEphemeral(event);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
case "ToolParamsStart": {
|
|
899
|
+
const event = yield* events.toolParamsStart(emission.payload);
|
|
900
|
+
yield* eventSink.publishEphemeral(event);
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
case "ToolParamsDelta": {
|
|
904
|
+
const event = yield* events.toolParamsDelta(emission.payload);
|
|
905
|
+
yield* eventSink.publishEphemeral(event);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
case "ToolParamsEnd": {
|
|
909
|
+
const event = yield* events.toolParamsEnd(emission.payload);
|
|
910
|
+
yield* eventSink.publishEphemeral(event);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
default: return yield* Effect.die(assertNeverError(emission, "ephemeral emission"));
|
|
914
|
+
}
|
|
915
|
+
});
|
|
916
|
+
const commitFinalize = (eventSink, payloads, state, responseParts) => Effect.gen(function* () {
|
|
917
|
+
const durableEvents = [];
|
|
918
|
+
const assistant = yield* assistantMessageEvent(state, responseParts);
|
|
919
|
+
if (assistant !== void 0) durableEvents.push(assistant);
|
|
920
|
+
for (const payload of payloads) durableEvents.push(yield* makeFinalizeEvent(payload));
|
|
921
|
+
const committed = yield* eventSink.appendDurableBatch(durableEvents);
|
|
922
|
+
return InferenceRunFinished.make({
|
|
923
|
+
committed,
|
|
924
|
+
assistantText: state.assistantText,
|
|
925
|
+
reasoningText: state.reasoningText,
|
|
926
|
+
responseParts
|
|
927
|
+
});
|
|
928
|
+
});
|
|
929
|
+
const assistantMessageEvent = (state, responseParts) => Effect.gen(function* () {
|
|
930
|
+
const promptParts = nonEmptyAssistantPromptParts(assistantPromptPartsFromResponseParts(responseParts));
|
|
931
|
+
if (promptParts === void 0 && !hasAssistantContent(state)) return;
|
|
932
|
+
const messageId = yield* ids.makeMessageId();
|
|
933
|
+
return yield* events.assistantMessageCommitted({
|
|
934
|
+
messageId,
|
|
935
|
+
runId: state.runId,
|
|
936
|
+
turnId: state.turnId,
|
|
937
|
+
inferenceId: state.inferenceId,
|
|
938
|
+
promptParts: promptParts ?? legacyAssistantPromptParts(state)
|
|
939
|
+
});
|
|
940
|
+
});
|
|
941
|
+
const assistantPartialEvent = (state, reason, responseParts) => Effect.gen(function* () {
|
|
942
|
+
if (!hasAssistantContent(state)) return;
|
|
943
|
+
const messageId = yield* ids.makeMessageId();
|
|
944
|
+
return yield* events.assistantPartialCommitted({
|
|
945
|
+
messageId,
|
|
946
|
+
runId: state.runId,
|
|
947
|
+
turnId: state.turnId,
|
|
948
|
+
inferenceId: state.inferenceId,
|
|
949
|
+
promptParts: nonEmptyAssistantPromptParts(partialAssistantPromptPartsFromResponseParts(responseParts)) ?? legacyAssistantPromptParts(state),
|
|
950
|
+
reason
|
|
951
|
+
});
|
|
952
|
+
});
|
|
953
|
+
const commitFailure = (eventSink, payload, state, responseParts) => Effect.gen(function* () {
|
|
954
|
+
const partial = yield* assistantPartialEvent(state, "inference failed before completion", responseParts);
|
|
955
|
+
const event = yield* events.inferenceFailed(payload);
|
|
956
|
+
const committed = yield* eventSink.appendDurableBatch(partial === void 0 ? [event] : [partial, event]);
|
|
957
|
+
return InferenceRunFailed.make({ committed });
|
|
958
|
+
});
|
|
959
|
+
const makeFinalizeEvent = (payload) => {
|
|
960
|
+
switch (payload.type) {
|
|
961
|
+
case "InferenceCompleted": return events.inferenceCompleted(payload.payload);
|
|
962
|
+
case "ToolCallCreated": return events.toolCallCreated(payload.payload);
|
|
963
|
+
case "ToolCallRejected": return events.toolCallRejected(payload.payload);
|
|
964
|
+
default: return Effect.die(assertNeverError(payload, "finalize payload"));
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
const recordMissingFinish = (eventSink, state) => Effect.gen(function* () {
|
|
968
|
+
const stepped = step(state, {
|
|
969
|
+
type: "error",
|
|
970
|
+
error: failurePayloadFromUnknown(/* @__PURE__ */ new Error("Provider stream ended without a finish part"))
|
|
971
|
+
});
|
|
972
|
+
return yield* requireTerminal(yield* interpretEmissions(eventSink, stepped.emissions, stepped.next, []));
|
|
973
|
+
});
|
|
974
|
+
return { runInference: Effect.fn("agent.inference")(function* (input) {
|
|
975
|
+
const inferenceIdentity = {
|
|
976
|
+
runId: input.runId,
|
|
977
|
+
turnId: input.turnId,
|
|
978
|
+
inferenceId: input.inferenceId
|
|
979
|
+
};
|
|
980
|
+
yield* annotateEdaSpan({
|
|
981
|
+
"eda.run.id": input.runId,
|
|
982
|
+
"eda.turn.id": input.turnId,
|
|
983
|
+
"eda.inference.id": input.inferenceId,
|
|
984
|
+
"eda.model.provider": input.modelSelection?.provider,
|
|
985
|
+
"eda.model.id": input.modelSelection?.modelId
|
|
986
|
+
});
|
|
987
|
+
const initialState = initialRunInferenceState(inferenceIdentity);
|
|
988
|
+
const stateRef = yield* Ref.make(initialState);
|
|
989
|
+
const start = Effect.gen(function* () {
|
|
990
|
+
const startedEvent = yield* events.inferenceStarted(inferenceIdentity);
|
|
991
|
+
return yield* input.eventSink.appendDurable(startedEvent);
|
|
992
|
+
});
|
|
993
|
+
const body = (started) => Effect.gen(function* () {
|
|
994
|
+
const toolkit = yield* toolRegistry.getModelToolkit();
|
|
995
|
+
const state = yield* languageModel.streamText({
|
|
996
|
+
prompt: input.prompt,
|
|
997
|
+
disableToolCallResolution: true,
|
|
998
|
+
...toolkit === void 0 ? {} : { toolkit }
|
|
999
|
+
}).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)))));
|
|
1000
|
+
const terminal = state.terminal ?? (yield* recordMissingFinish(input.eventSink, state.inference));
|
|
1001
|
+
return {
|
|
1002
|
+
started,
|
|
1003
|
+
value: InferenceRunResult.make({
|
|
1004
|
+
started,
|
|
1005
|
+
partsRecorded: NonNegativeInt.make(state.partsRecorded),
|
|
1006
|
+
terminal
|
|
1007
|
+
})
|
|
1008
|
+
};
|
|
1009
|
+
});
|
|
1010
|
+
const release = (_started, exit) => {
|
|
1011
|
+
if (Exit.isSuccess(exit)) return Effect.void;
|
|
1012
|
+
if (hasEDASessionStoreError(exit.cause)) return Effect.failCause(exit.cause);
|
|
1013
|
+
return Effect.uninterruptible(Effect.gen(function* () {
|
|
1014
|
+
const latest = yield* Ref.get(stateRef);
|
|
1015
|
+
const partial = yield* assistantPartialEvent(latest.inference, Cause.hasInterruptsOnly(exit.cause) ? "inference interrupted before completion" : "inference failed before completion", responseContextToParts(latest.responseContext));
|
|
1016
|
+
const terminal = yield* events.inferenceFailed({
|
|
1017
|
+
...inferenceIdentity,
|
|
1018
|
+
error: Cause.hasInterruptsOnly(exit.cause) ? FailurePayload.make({
|
|
1019
|
+
message: "inference interrupted",
|
|
1020
|
+
code: "inference.interrupted",
|
|
1021
|
+
details: { reason: "interrupted" }
|
|
1022
|
+
}) : failurePayloadFromCause(exit.cause)
|
|
1023
|
+
});
|
|
1024
|
+
yield* input.eventSink.appendDurableBatch(partial === void 0 ? [terminal] : [partial, terminal]);
|
|
1025
|
+
}));
|
|
1026
|
+
};
|
|
1027
|
+
const guarded = yield* Effect.acquireUseRelease(start, body, release);
|
|
1028
|
+
yield* annotateEdaSpan({
|
|
1029
|
+
"eda.provider.parts_recorded": guarded.value.partsRecorded,
|
|
1030
|
+
"eda.inference.terminal": guarded.value.terminal._tag,
|
|
1031
|
+
...inferenceUsageAttributes(guarded.value.terminal),
|
|
1032
|
+
...committedBatchAttributes(guarded.value.terminal.committed)
|
|
1033
|
+
});
|
|
1034
|
+
return guarded.value;
|
|
1035
|
+
}) };
|
|
1036
|
+
});
|
|
1037
|
+
/** Owns provider inference streams and routes them into durable/live inference emissions. */
|
|
1038
|
+
var InferenceRunner = class InferenceRunner extends Context.Service()("@effect-durable-agent/InferenceRunner") {
|
|
1039
|
+
static Live = Layer.effect(InferenceRunner, makeLiveInferenceRunner);
|
|
1040
|
+
};
|
|
1041
|
+
const inferenceUsageAttributes = (terminal) => {
|
|
1042
|
+
if (terminal._tag !== "InferenceRunFinished") return {};
|
|
1043
|
+
return usageAttributes((terminal.committed.find((entry) => entry.event.type === "InferenceCompleted")?.event.payload)?.usage);
|
|
1044
|
+
};
|
|
1045
|
+
const initialRunInferenceState = (identity) => ({
|
|
1046
|
+
inference: initialInferenceState(identity),
|
|
1047
|
+
partsRecorded: 0,
|
|
1048
|
+
terminal: void 0,
|
|
1049
|
+
responseContext: []
|
|
1050
|
+
});
|
|
1051
|
+
const recordResponseContext = (entries, part) => {
|
|
1052
|
+
switch (part.type) {
|
|
1053
|
+
case "text-start": return upsertTextualResponseEntry(entries, "Text", part.id, "");
|
|
1054
|
+
case "text-delta": return upsertTextualResponseEntry(entries, "Text", part.id, part.delta);
|
|
1055
|
+
case "text-end": return entries;
|
|
1056
|
+
case "reasoning-start": return upsertTextualResponseEntry(entries, "Reasoning", part.id, "");
|
|
1057
|
+
case "reasoning-delta": return upsertTextualResponseEntry(entries, "Reasoning", part.id, part.delta);
|
|
1058
|
+
case "reasoning-end": return entries;
|
|
1059
|
+
case "tool-call": return part.providerExecuted ? entries : [...entries, {
|
|
1060
|
+
_tag: "ResponsePart",
|
|
1061
|
+
part
|
|
1062
|
+
}];
|
|
1063
|
+
case "tool-result": return entries;
|
|
1064
|
+
case "tool-params-start":
|
|
1065
|
+
case "tool-params-delta":
|
|
1066
|
+
case "tool-params-end":
|
|
1067
|
+
case "response-metadata":
|
|
1068
|
+
case "finish":
|
|
1069
|
+
case "error":
|
|
1070
|
+
case "tool-approval-request":
|
|
1071
|
+
case "file":
|
|
1072
|
+
case "source": return entries;
|
|
1073
|
+
default: throw assertNeverError(part, "response context part");
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
const upsertTextualResponseEntry = (entries, tag, providerPartId, delta) => {
|
|
1077
|
+
const index = entries.findIndex((entry) => (entry._tag === "Text" || entry._tag === "Reasoning") && entry._tag === tag && entry.providerPartId === providerPartId);
|
|
1078
|
+
if (index === -1) return [...entries, {
|
|
1079
|
+
_tag: tag,
|
|
1080
|
+
providerPartId,
|
|
1081
|
+
text: delta
|
|
1082
|
+
}];
|
|
1083
|
+
const current = entries[index];
|
|
1084
|
+
if (current._tag !== tag) return entries;
|
|
1085
|
+
return entries.map((entry, entryIndex) => entryIndex === index ? {
|
|
1086
|
+
...current,
|
|
1087
|
+
text: `${current.text}${delta}`
|
|
1088
|
+
} : entry);
|
|
1089
|
+
};
|
|
1090
|
+
const responseContextToParts = (entries) => entries.flatMap((entry) => {
|
|
1091
|
+
switch (entry._tag) {
|
|
1092
|
+
case "Text": return entry.text.length === 0 ? [] : [Response.makePart("text", { text: entry.text })];
|
|
1093
|
+
case "Reasoning": return entry.text.length === 0 ? [] : [Response.makePart("reasoning", { text: entry.text })];
|
|
1094
|
+
case "ResponsePart": return [entry.part];
|
|
1095
|
+
default: throw assertNeverError(entry, "response context entry");
|
|
1096
|
+
}
|
|
1097
|
+
});
|
|
1098
|
+
const assistantPromptPartsFromResponseParts = (responseParts) => {
|
|
1099
|
+
return Prompt.fromResponseParts(responseParts).content.find((message) => message.role === "assistant")?.content ?? [];
|
|
1100
|
+
};
|
|
1101
|
+
const partialAssistantPromptPartsFromResponseParts = (responseParts) => assistantPromptPartsFromResponseParts(responseParts).filter((part) => part.type !== "tool-call");
|
|
1102
|
+
const nonEmptyAssistantPromptParts = (parts) => parts.length === 0 ? void 0 : parts;
|
|
1103
|
+
const legacyAssistantPromptParts = (state) => nonEmptyAssistantPromptParts([...state.reasoningText.length === 0 ? [] : [Prompt.reasoningPart({ text: state.reasoningText })], ...state.assistantText.length === 0 ? [] : [Prompt.textPart({ text: state.assistantText })]]) ?? [Prompt.textPart({ text: "" })];
|
|
1104
|
+
const isProviderStreamFailure = (_error) => true;
|
|
1105
|
+
const makeProviderErrorPart = (error) => Response.makePart("error", { error });
|
|
1106
|
+
const unsupportedProviderExecutedTool = (toolName, providerPartId) => ({
|
|
1107
|
+
type: "error",
|
|
1108
|
+
error: FailurePayload.make({
|
|
1109
|
+
message: `Provider-executed tool calls are unsupported: ${toolName}`,
|
|
1110
|
+
code: "tool.unsupported_provider_executed",
|
|
1111
|
+
details: {
|
|
1112
|
+
providerPartId,
|
|
1113
|
+
toolName
|
|
1114
|
+
}
|
|
1115
|
+
})
|
|
1116
|
+
});
|
|
1117
|
+
const isProviderSidebandPart = (part) => part.type === "tool-approval-request" || part.type === "file" || part.type === "source";
|
|
1118
|
+
const isIgnoredToolResultPart = (part) => part.type === "tool-result" && (part.providerExecuted !== true || part.preliminary === true);
|
|
1119
|
+
const hasAssistantContent = (state) => state.assistantText.length > 0 || state.reasoningText.length > 0;
|
|
1120
|
+
const validateParams = (schema, params) => {
|
|
1121
|
+
try {
|
|
1122
|
+
return {
|
|
1123
|
+
_tag: "ValidToolParams",
|
|
1124
|
+
params: Schema.decodeUnknownSync(schema)(params)
|
|
1125
|
+
};
|
|
1126
|
+
} catch (error) {
|
|
1127
|
+
return {
|
|
1128
|
+
_tag: "InvalidToolParams",
|
|
1129
|
+
message: formatSchemaError(error)
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
const formatSchemaError = (error) => {
|
|
1134
|
+
if (error instanceof Error) return error.message;
|
|
1135
|
+
return String(error);
|
|
1136
|
+
};
|
|
1137
|
+
const requireTerminal = (terminal) => terminal === void 0 ? Effect.die(/* @__PURE__ */ new Error("Expected terminal inference result")) : Effect.succeed(terminal);
|
|
1138
|
+
const makeResponseMetadata = (part) => ({
|
|
1139
|
+
id: part.id,
|
|
1140
|
+
modelId: part.modelId,
|
|
1141
|
+
timestamp: part.timestamp,
|
|
1142
|
+
request: part.request,
|
|
1143
|
+
metadata: part.metadata
|
|
1144
|
+
});
|
|
1145
|
+
const makeFinishMetadata = (part) => ({
|
|
1146
|
+
response: part.response,
|
|
1147
|
+
metadata: part.metadata
|
|
1148
|
+
});
|
|
1149
|
+
const makeUsagePayload = (usage) => {
|
|
1150
|
+
const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
|
|
1151
|
+
const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
|
|
1152
|
+
const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
|
|
1153
|
+
const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
|
|
1154
|
+
uncachedInputTokens,
|
|
1155
|
+
cachedInputTokens,
|
|
1156
|
+
cacheWriteInputTokens
|
|
1157
|
+
]);
|
|
1158
|
+
const textTokens = nonNegativeInt(usage.outputTokens.text);
|
|
1159
|
+
const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
|
|
1160
|
+
const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
|
|
1161
|
+
return UsagePayload.make({
|
|
1162
|
+
...inputTokens === void 0 ? {} : { inputTokens },
|
|
1163
|
+
...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
|
|
1164
|
+
...outputTokens === void 0 ? {} : { outputTokens },
|
|
1165
|
+
...textTokens === void 0 ? {} : { textTokens },
|
|
1166
|
+
...reasoningTokens === void 0 ? {} : { reasoningTokens }
|
|
1167
|
+
});
|
|
1168
|
+
};
|
|
1169
|
+
const sumDefined = (values) => {
|
|
1170
|
+
const present = values.filter((value) => value !== void 0);
|
|
1171
|
+
return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
|
|
1172
|
+
};
|
|
1173
|
+
const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
|
|
1174
|
+
Schema.Struct({
|
|
1175
|
+
runId: RunId,
|
|
1176
|
+
turnId: TurnId
|
|
1177
|
+
});
|
|
1178
|
+
/** Turn outcome when the inference completed and no tools need handling. */
|
|
1179
|
+
const TurnRunCompleted = Schema.TaggedStruct("TurnRunCompleted", { committed: CommittedDurableEvent });
|
|
1180
|
+
/** Turn outcome when the inference failed and the turn failure was persisted. */
|
|
1181
|
+
const TurnRunFailed = Schema.TaggedStruct("TurnRunFailed", { committed: CommittedDurableEvent });
|
|
1182
|
+
/** Terminal outcome variants for one turn body. */
|
|
1183
|
+
const TurnRunOutcome = Schema.Union([TurnRunCompleted, TurnRunFailed]);
|
|
1184
|
+
/** Summary returned after the turn runner processes one inference stream. */
|
|
1185
|
+
const TurnRunResult = Schema.Struct({
|
|
1186
|
+
started: CommittedDurableEvent,
|
|
1187
|
+
inference: InferenceRunResult,
|
|
1188
|
+
outcome: TurnRunOutcome
|
|
1189
|
+
});
|
|
1190
|
+
const defaultMaxToolRejectionCorrections = NonNegativeInt.make(1);
|
|
1191
|
+
const defaultMaxToolCallsPerRun$1 = NonNegativeInt.make(20);
|
|
1192
|
+
const maxToolExecutionConcurrency = 10;
|
|
1193
|
+
/** Construct the live turn-runner implementation. */
|
|
1194
|
+
const makeLiveTurnRunner = Effect.gen(function* () {
|
|
1195
|
+
const ids = yield* IdGenerator;
|
|
1196
|
+
const events = yield* EventFactory;
|
|
1197
|
+
const inferenceRunner = yield* InferenceRunner;
|
|
1198
|
+
const toolExecutor = yield* ToolExecutor;
|
|
1199
|
+
const commitCompletedTurn = (input, inferenceCompleted) => Effect.gen(function* () {
|
|
1200
|
+
const usage = inferenceCompleted.event.payload.usage;
|
|
1201
|
+
const turnCompleted = yield* events.turnCompleted({
|
|
1202
|
+
runId: input.runId,
|
|
1203
|
+
turnId: input.turnId,
|
|
1204
|
+
...usage === void 0 ? {} : { usage }
|
|
1205
|
+
});
|
|
1206
|
+
return yield* input.eventSink.appendDurable(turnCompleted);
|
|
1207
|
+
});
|
|
1208
|
+
const finishTurnAfterInference = (input, inference, remainingToolCalls) => Effect.gen(function* () {
|
|
1209
|
+
switch (inference.terminal._tag) {
|
|
1210
|
+
case "InferenceRunFinished": {
|
|
1211
|
+
const toolEvents = inference.terminal.committed.filter(isToolDecisionBoundary);
|
|
1212
|
+
const created = toolEvents.filter(isToolCallCreated);
|
|
1213
|
+
const rejected = toolEvents.filter(isToolCallRejected);
|
|
1214
|
+
const frameworkCreated = yield* requireFrameworkCreatedToolCalls(created);
|
|
1215
|
+
if (created.length > 0) {
|
|
1216
|
+
if (frameworkCreated.length > remainingToolCalls) {
|
|
1217
|
+
yield* failUnexecutedToolCalls(input.eventSink, events, frameworkCreated, FailurePayload.make({
|
|
1218
|
+
message: `maxToolCallsPerRun exceeded: requested ${frameworkCreated.length} tool call(s) with ${remainingToolCalls} remaining`,
|
|
1219
|
+
code: "tool.budget_exceeded",
|
|
1220
|
+
details: {
|
|
1221
|
+
requested: frameworkCreated.length,
|
|
1222
|
+
remaining: remainingToolCalls,
|
|
1223
|
+
maxToolCallsPerRun: input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1
|
|
1224
|
+
}
|
|
1225
|
+
}));
|
|
1226
|
+
const committed = yield* failTurnForToolCallBudget({
|
|
1227
|
+
eventSink: input.eventSink,
|
|
1228
|
+
events,
|
|
1229
|
+
requested: frameworkCreated.length,
|
|
1230
|
+
remaining: remainingToolCalls,
|
|
1231
|
+
turnIdentity: {
|
|
1232
|
+
runId: input.runId,
|
|
1233
|
+
turnId: input.turnId
|
|
1234
|
+
},
|
|
1235
|
+
maxToolCallsPerRun: input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1
|
|
1236
|
+
});
|
|
1237
|
+
return TurnRunFailed.make({ committed });
|
|
1238
|
+
}
|
|
1239
|
+
yield* executeFrameworkToolCalls(input.eventSink, events, frameworkCreated);
|
|
1240
|
+
}
|
|
1241
|
+
const completed = yield* requireInferenceCompleted(inference.terminal.committed);
|
|
1242
|
+
if (rejected.length > 0 && rejectedToolCorrectionExhausted(input)) {
|
|
1243
|
+
const committed = yield* failTurnForRejectedToolCorrectionExhaustion({
|
|
1244
|
+
eventSink: input.eventSink,
|
|
1245
|
+
events,
|
|
1246
|
+
rejected,
|
|
1247
|
+
turnIdentity: {
|
|
1248
|
+
runId: input.runId,
|
|
1249
|
+
turnId: input.turnId
|
|
1250
|
+
},
|
|
1251
|
+
maxToolRejectionCorrections: input.maxToolRejectionCorrections ?? defaultMaxToolRejectionCorrections
|
|
1252
|
+
});
|
|
1253
|
+
return TurnRunFailed.make({ committed });
|
|
1254
|
+
}
|
|
1255
|
+
const committed = yield* commitCompletedTurn(input, completed);
|
|
1256
|
+
return TurnRunCompleted.make({ committed });
|
|
1257
|
+
}
|
|
1258
|
+
case "InferenceRunFailed": {
|
|
1259
|
+
const failed = yield* requireInferenceFailed(inference.terminal.committed);
|
|
1260
|
+
const event = yield* events.turnFailed({
|
|
1261
|
+
runId: input.runId,
|
|
1262
|
+
turnId: input.turnId,
|
|
1263
|
+
error: failed.event.payload.error
|
|
1264
|
+
});
|
|
1265
|
+
const committed = yield* input.eventSink.appendDurable(event);
|
|
1266
|
+
return TurnRunFailed.make({ committed });
|
|
1267
|
+
}
|
|
1268
|
+
default: return yield* Effect.die(assertNeverError(inference.terminal, "inference terminal"));
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
const failUnexecutedToolCalls = (eventSink, events, created, error) => Effect.gen(function* () {
|
|
1272
|
+
if (created.length === 0) return;
|
|
1273
|
+
const failed = yield* Effect.forEach(created, (entry) => events.toolCallFailed({
|
|
1274
|
+
toolCallId: entry.event.payload.toolCallId,
|
|
1275
|
+
error,
|
|
1276
|
+
promptPart: toolFailurePromptPartFromCreated(entry, error)
|
|
1277
|
+
}));
|
|
1278
|
+
yield* eventSink.appendDurableBatch(failed);
|
|
1279
|
+
});
|
|
1280
|
+
const executeFrameworkToolCalls = (eventSink, events, created) => Effect.gen(function* () {
|
|
1281
|
+
const open = yield* Ref.make(new Map(created.map((entry) => [entry.event.payload.toolCallId, entry])));
|
|
1282
|
+
const removeOpen = (entry) => Ref.update(open, (current) => {
|
|
1283
|
+
const next = new Map(current);
|
|
1284
|
+
next.delete(entry.event.payload.toolCallId);
|
|
1285
|
+
return next;
|
|
1286
|
+
});
|
|
1287
|
+
const failRemainingOpen = (reason) => Effect.gen(function* () {
|
|
1288
|
+
const remaining = Array.from((yield* Ref.get(open)).values());
|
|
1289
|
+
if (remaining.length === 0) return;
|
|
1290
|
+
const failed = yield* Effect.forEach(remaining, (entry) => Effect.gen(function* () {
|
|
1291
|
+
const error = FailurePayload.make({
|
|
1292
|
+
message: `tool call interrupted: ${reason}`,
|
|
1293
|
+
code: "tool.interrupted",
|
|
1294
|
+
details: {
|
|
1295
|
+
reason,
|
|
1296
|
+
toolCallId: entry.event.payload.toolCallId
|
|
1297
|
+
}
|
|
1298
|
+
});
|
|
1299
|
+
return yield* events.toolCallFailed({
|
|
1300
|
+
toolCallId: entry.event.payload.toolCallId,
|
|
1301
|
+
error,
|
|
1302
|
+
promptPart: toolFailurePromptPartFromCreated(entry, error)
|
|
1303
|
+
});
|
|
1304
|
+
}));
|
|
1305
|
+
yield* eventSink.appendDurableBatch(failed);
|
|
1306
|
+
});
|
|
1307
|
+
const run = Effect.forEach(created, (entry) => toolExecutor.executeCreated({
|
|
1308
|
+
created: entry,
|
|
1309
|
+
eventSink
|
|
1310
|
+
}).pipe(Effect.ensuring(removeOpen(entry))), { concurrency: maxToolExecutionConcurrency });
|
|
1311
|
+
return yield* Effect.acquireUseRelease(Effect.succeed(open), () => run, (_open, exit) => {
|
|
1312
|
+
if (Exit.isSuccess(exit)) return Effect.void;
|
|
1313
|
+
if (hasEDASessionStoreError(exit.cause)) return Effect.failCause(exit.cause);
|
|
1314
|
+
return Cause.hasInterruptsOnly(exit.cause) ? failRemainingOpen("interrupted") : Effect.void;
|
|
1315
|
+
});
|
|
1316
|
+
});
|
|
1317
|
+
return { runTurn: Effect.fn("agent.turn")(function* (input) {
|
|
1318
|
+
const turnIdentity = {
|
|
1319
|
+
runId: input.runId,
|
|
1320
|
+
turnId: input.turnId
|
|
1321
|
+
};
|
|
1322
|
+
const maxToolCallsPerRun = input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun$1;
|
|
1323
|
+
yield* annotateEdaSpan({
|
|
1324
|
+
"eda.run.id": input.runId,
|
|
1325
|
+
"eda.turn.id": input.turnId,
|
|
1326
|
+
"eda.model.provider": input.modelSelection?.provider,
|
|
1327
|
+
"eda.model.id": input.modelSelection?.modelId,
|
|
1328
|
+
"eda.tool.max_calls_per_run": maxToolCallsPerRun
|
|
1329
|
+
});
|
|
1330
|
+
const inferencesStarted = yield* Ref.make(0);
|
|
1331
|
+
return yield* Effect.gen(function* () {
|
|
1332
|
+
const inferenceId = yield* ids.makeInferenceId();
|
|
1333
|
+
yield* Ref.update(inferencesStarted, (count) => count + 1);
|
|
1334
|
+
const inference = yield* inferenceRunner.runInference({
|
|
1335
|
+
...turnIdentity,
|
|
1336
|
+
inferenceId,
|
|
1337
|
+
prompt: input.prompt,
|
|
1338
|
+
eventSink: input.eventSink,
|
|
1339
|
+
modelSelection: input.modelSelection
|
|
1340
|
+
});
|
|
1341
|
+
const outcome = yield* finishTurnAfterInference(input, inference, maxToolCallsPerRun);
|
|
1342
|
+
return TurnRunResult.make({
|
|
1343
|
+
started: input.started,
|
|
1344
|
+
inference,
|
|
1345
|
+
outcome
|
|
1346
|
+
});
|
|
1347
|
+
}).pipe(Effect.tap((result) => Effect.gen(function* () {
|
|
1348
|
+
yield* annotateEdaSpan({
|
|
1349
|
+
"eda.turn.outcome": result.outcome._tag,
|
|
1350
|
+
"eda.inference.started_count": yield* Ref.get(inferencesStarted),
|
|
1351
|
+
"eda.provider.parts_recorded": result.inference.partsRecorded,
|
|
1352
|
+
...turnUsageAttributes(result)
|
|
1353
|
+
});
|
|
1354
|
+
})), Effect.catchCause((cause) => {
|
|
1355
|
+
if (hasEDASessionStoreError(cause) || Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
|
|
1356
|
+
return Effect.uninterruptible(Effect.gen(function* () {
|
|
1357
|
+
const terminal = yield* events.turnFailed({
|
|
1358
|
+
...turnIdentity,
|
|
1359
|
+
error: failurePayloadFromCause(cause)
|
|
1360
|
+
});
|
|
1361
|
+
yield* input.eventSink.appendDurable(terminal);
|
|
1362
|
+
return yield* Effect.failCause(cause);
|
|
1363
|
+
}));
|
|
1364
|
+
}));
|
|
1365
|
+
}) };
|
|
1366
|
+
});
|
|
1367
|
+
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
1368
|
+
var TurnRunner = class TurnRunner extends Context.Service()("@effect-durable-agent/TurnRunner") {
|
|
1369
|
+
static Live = Layer.effect(TurnRunner, makeLiveTurnRunner);
|
|
1370
|
+
};
|
|
1371
|
+
const failTurnForToolCallBudget = (input) => Effect.gen(function* () {
|
|
1372
|
+
const event = yield* input.events.turnFailed({
|
|
1373
|
+
...input.turnIdentity,
|
|
1374
|
+
error: FailurePayload.make({
|
|
1375
|
+
message: `maxToolCallsPerRun exceeded: requested ${input.requested} tool call(s) with ${input.remaining} remaining out of ${input.maxToolCallsPerRun}`,
|
|
1376
|
+
code: "tool.budget_exceeded",
|
|
1377
|
+
details: {
|
|
1378
|
+
requested: input.requested,
|
|
1379
|
+
remaining: input.remaining,
|
|
1380
|
+
maxToolCallsPerRun: input.maxToolCallsPerRun
|
|
1381
|
+
}
|
|
1382
|
+
})
|
|
1383
|
+
});
|
|
1384
|
+
return yield* input.eventSink.appendDurable(event);
|
|
1385
|
+
});
|
|
1386
|
+
const failTurnForRejectedToolCorrectionExhaustion = (input) => Effect.gen(function* () {
|
|
1387
|
+
const event = yield* input.events.turnFailed({
|
|
1388
|
+
...input.turnIdentity,
|
|
1389
|
+
error: FailurePayload.make({
|
|
1390
|
+
message: "tool rejection correction exhausted",
|
|
1391
|
+
code: "tool.rejection_correction_exhausted",
|
|
1392
|
+
details: {
|
|
1393
|
+
limit: input.maxToolRejectionCorrections,
|
|
1394
|
+
rejectedToolCallIds: input.rejected.map((entry) => entry.event.payload.toolCallId)
|
|
1395
|
+
}
|
|
1396
|
+
})
|
|
1397
|
+
});
|
|
1398
|
+
return yield* input.eventSink.appendDurable(event);
|
|
1399
|
+
});
|
|
1400
|
+
const rejectedToolCorrectionExhausted = (input) => (input.remainingToolRejectionCorrections ?? defaultMaxToolRejectionCorrections) <= 0;
|
|
1401
|
+
const toolFailurePromptPartFromCreated = (created, result) => {
|
|
1402
|
+
return {
|
|
1403
|
+
...Prompt.toolResultPart({
|
|
1404
|
+
id: created.event.payload.promptPart.id,
|
|
1405
|
+
name: created.event.payload.promptPart.name,
|
|
1406
|
+
isFailure: true,
|
|
1407
|
+
result
|
|
1408
|
+
}),
|
|
1409
|
+
id: created.event.payload.promptPart.id,
|
|
1410
|
+
name: created.event.payload.promptPart.name,
|
|
1411
|
+
isFailure: true,
|
|
1412
|
+
result
|
|
1413
|
+
};
|
|
1414
|
+
};
|
|
1415
|
+
const requireFrameworkCreatedToolCalls = (created) => Effect.gen(function* () {
|
|
1416
|
+
const unsupported = created.find((entry) => entry.event.payload.promptPart.providerExecuted);
|
|
1417
|
+
if (unsupported !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Provider-executed tool calls are unsupported: ${unsupported.event.payload.promptPart.name}`));
|
|
1418
|
+
return created;
|
|
1419
|
+
});
|
|
1420
|
+
const turnUsageAttributes = (result) => result.outcome._tag === "TurnRunCompleted" ? usageAttributes(result.outcome.committed.event.payload.usage) : {};
|
|
1421
|
+
const isInferenceCompleted = (committed) => committed.event.type === inferenceCompletedEventType;
|
|
1422
|
+
const isInferenceFailed = (committed) => committed.event.type === inferenceFailedEventType;
|
|
1423
|
+
const isToolCallCreated = (committed) => committed.event.type === toolCallCreatedEventType;
|
|
1424
|
+
const isToolCallRejected = (committed) => committed.event.type === toolCallRejectedEventType;
|
|
1425
|
+
const isToolDecisionBoundary = (committed) => isToolCallCreated(committed) || isToolCallRejected(committed);
|
|
1426
|
+
const requireInferenceCompleted = (committed) => {
|
|
1427
|
+
const completed = committed.find(isInferenceCompleted);
|
|
1428
|
+
return completed === void 0 ? Effect.die(/* @__PURE__ */ new Error("InferenceRunFinished did not include InferenceCompleted")) : Effect.succeed(completed);
|
|
1429
|
+
};
|
|
1430
|
+
const requireInferenceFailed = (committed) => {
|
|
1431
|
+
const failed = committed.find(isInferenceFailed);
|
|
1432
|
+
return failed === void 0 ? Effect.die(/* @__PURE__ */ new Error("InferenceRunFailed did not include InferenceFailed")) : Effect.succeed(failed);
|
|
1433
|
+
};
|
|
1434
|
+
Schema.Struct({
|
|
1435
|
+
modelSelection: ModelSelectionPayload,
|
|
1436
|
+
maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),
|
|
1437
|
+
systemPrompt: Schema.optionalKey(SystemPromptText)
|
|
1438
|
+
});
|
|
1439
|
+
/** Command outcome when the command's run completed and the command was completed. */
|
|
1440
|
+
const SessionCommandCompleted = Schema.TaggedStruct("SessionCommandCompleted", { committed: CommittedDurableEvent });
|
|
1441
|
+
/** Command outcome when the command's run failed and the command was failed. */
|
|
1442
|
+
const SessionCommandFailed = Schema.TaggedStruct("SessionCommandFailed", { committed: CommittedDurableEvent });
|
|
1443
|
+
/** Command outcome when command work was cancelled by stop, interrupt, or recovery. */
|
|
1444
|
+
const SessionCommandCancelled = Schema.TaggedStruct("SessionCommandCancelled", { committed: CommittedDurableEvent });
|
|
1445
|
+
Schema.Union([
|
|
1446
|
+
SessionCommandCompleted,
|
|
1447
|
+
SessionCommandFailed,
|
|
1448
|
+
SessionCommandCancelled
|
|
1449
|
+
]);
|
|
1450
|
+
/** Why a control drain stopped without starting more command work. */
|
|
1451
|
+
const SessionNoRunnableReason = Schema.Literals(["active-command", "no-pending-command"]);
|
|
1452
|
+
/** Session control result when no admitted command is runnable. */
|
|
1453
|
+
const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand", {
|
|
1454
|
+
reason: SessionNoRunnableReason,
|
|
1455
|
+
active: Schema.optionalKey(DispatchActiveCommand)
|
|
1456
|
+
});
|
|
1457
|
+
/** Control result when command execution was started in an active child scope. */
|
|
1458
|
+
const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
|
|
1459
|
+
var SessionCommandAdmissionConflict = class extends Schema.TaggedErrorClass()("SessionCommandAdmissionConflict", {
|
|
1460
|
+
code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
|
|
1461
|
+
message: Schema.String,
|
|
1462
|
+
pausedMessageIds: Schema.Array(MessageId)
|
|
1463
|
+
}) {};
|
|
1464
|
+
/** Internal authoritative live state and root control loop for one session. */
|
|
1465
|
+
var SessionState = class SessionState extends Context.Service()("@effect-durable-agent/SessionState") {
|
|
1466
|
+
static Live = Layer.effect(SessionState, Effect.suspend(() => makeLiveSessionState));
|
|
1467
|
+
};
|
|
1468
|
+
const defaultMaxToolCallsPerRun = NonNegativeInt.make(20);
|
|
1469
|
+
const maxToolRejectionCorrections = 1;
|
|
1470
|
+
const toolCancelledPromptPartFromRecord = (tool, error) => {
|
|
1471
|
+
const decision = tool.decision;
|
|
1472
|
+
if (decision?._tag !== "Created") throw new Error("Cannot build cancellation failure prompt part without a created tool decision");
|
|
1473
|
+
return {
|
|
1474
|
+
...Prompt.toolResultPart({
|
|
1475
|
+
id: decision.providerPartId,
|
|
1476
|
+
name: decision.toolName,
|
|
1477
|
+
isFailure: true,
|
|
1478
|
+
result: error
|
|
1479
|
+
}),
|
|
1480
|
+
id: decision.providerPartId,
|
|
1481
|
+
name: decision.toolName,
|
|
1482
|
+
isFailure: true,
|
|
1483
|
+
result: error
|
|
1484
|
+
};
|
|
1485
|
+
};
|
|
1486
|
+
const toolCancelledFailureFromRecord = (tool, reason) => FailurePayload.make({
|
|
1487
|
+
message: `tool call interrupted: ${reason}`,
|
|
1488
|
+
code: "tool.interrupted",
|
|
1489
|
+
details: {
|
|
1490
|
+
reason,
|
|
1491
|
+
toolCallId: tool.toolCallId
|
|
1492
|
+
}
|
|
1493
|
+
});
|
|
1494
|
+
/** Build the canonical failed-terminal payload for an interrupted lifecycle. */
|
|
1495
|
+
const interruptionFailure = (lifecycle, reason, details, recoverable = reason === startupRecoveryReason) => FailurePayload.make({
|
|
1496
|
+
message: `${lifecycle} interrupted: ${reason}`,
|
|
1497
|
+
code: `${lifecycle}.interrupted`,
|
|
1498
|
+
details: {
|
|
1499
|
+
...details,
|
|
1500
|
+
reason,
|
|
1501
|
+
recoverable
|
|
1502
|
+
}
|
|
1503
|
+
});
|
|
1504
|
+
const startupRecoveryReason = "runtime restarted before lifecycle completed";
|
|
1505
|
+
const makeLiveSessionState = Effect.gen(function* () {
|
|
1506
|
+
const store = yield* EDASessionStore;
|
|
1507
|
+
const liveBus = yield* LiveEventBus;
|
|
1508
|
+
const keepAlive = yield* EDAKeepAlive;
|
|
1509
|
+
const ids = yield* IdGenerator;
|
|
1510
|
+
const events = yield* EventFactory;
|
|
1511
|
+
const turnRunner = yield* TurnRunner;
|
|
1512
|
+
const compactionRunner = yield* CompactionRunner;
|
|
1513
|
+
const promptProjector = yield* EDAPromptProjector;
|
|
1514
|
+
const sessionContext = yield* SessionContext;
|
|
1515
|
+
const reducerRegistry = yield* EDAReducerRegistry;
|
|
1516
|
+
const sinkRegistry = yield* EDASinkRegistry;
|
|
1517
|
+
const hydrated = yield* hydrateFrameworkReducedState(store);
|
|
1518
|
+
const hydratedReducerStates = yield* hydrateAppReducerStates(store, reducerRegistry.reducers);
|
|
1519
|
+
const startupRecoveryCheckpointSeq = hydratedReducerStates.checkpointSeq === void 0 ? hydrated.checkpointSeq : SequenceNumber.make(Math.min(hydrated.checkpointSeq, hydratedReducerStates.checkpointSeq));
|
|
1520
|
+
const state = yield* Ref.make({
|
|
1521
|
+
reduced: hydrated.state,
|
|
1522
|
+
reducerStates: hydratedReducerStates.states,
|
|
1523
|
+
ephemeral: {
|
|
1524
|
+
anchorSeq: SequenceNumber.make(0),
|
|
1525
|
+
lastSubSeq: SubSequenceNumber.make(0)
|
|
1526
|
+
}
|
|
1527
|
+
});
|
|
1528
|
+
const gate = yield* Semaphore.make(1);
|
|
1529
|
+
const ingressSignals = yield* Queue.sliding(1);
|
|
1530
|
+
const reducerCheckpointSnapshots = yield* Queue.sliding(1);
|
|
1531
|
+
const executionState = yield* Ref.make({ _tag: "Idle" });
|
|
1532
|
+
const startupRecoveryCheckpointRequested = yield* Ref.make(false);
|
|
1533
|
+
const fatalCause = yield* Ref.make(void 0);
|
|
1534
|
+
const fatalInvariantViolation = yield* Ref.make(void 0);
|
|
1535
|
+
const runtimeScope = yield* Effect.acquireRelease(Scope.make("sequential"), (scope) => Scope.close(scope, Exit.void));
|
|
1536
|
+
const failIfFatal = Effect.gen(function* () {
|
|
1537
|
+
const invariantViolation = yield* Ref.get(fatalInvariantViolation);
|
|
1538
|
+
if (invariantViolation !== void 0) return yield* Effect.die(invariantViolation);
|
|
1539
|
+
const cause = yield* Ref.get(fatalCause);
|
|
1540
|
+
if (cause !== void 0) return yield* Effect.failCause(cause);
|
|
1541
|
+
});
|
|
1542
|
+
const markFatalIfDurable = (cause) => hasEDASessionStoreError(cause) ? Ref.set(fatalCause, cause) : Effect.void;
|
|
1543
|
+
const withAppendGate = (effect) => gate.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
|
|
1544
|
+
yield* failIfFatal;
|
|
1545
|
+
return yield* effect;
|
|
1546
|
+
}).pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
1547
|
+
yield* markFatalIfDurable(cause);
|
|
1548
|
+
return yield* Effect.failCause(cause);
|
|
1549
|
+
})))));
|
|
1550
|
+
const withFatalRecording = (effect) => Effect.catchCause(effect, (cause) => Effect.gen(function* () {
|
|
1551
|
+
yield* markFatalIfDurable(cause);
|
|
1552
|
+
return yield* Effect.failCause(cause);
|
|
1553
|
+
}));
|
|
1554
|
+
const buildReducerCheckpointSnapshot = (snapshot) => [{
|
|
1555
|
+
name: frameworkReducedStateReducerName,
|
|
1556
|
+
schemaVersion: 4,
|
|
1557
|
+
throughSeq: snapshot.reduced.lastSeq,
|
|
1558
|
+
payload: encodeReducedStateCheckpoint(snapshot.reduced),
|
|
1559
|
+
updatedAtMs: snapshot.updatedAtMs
|
|
1560
|
+
}, ...reducerRegistry.reducers.map((reducer) => ({
|
|
1561
|
+
name: reducer.name,
|
|
1562
|
+
schemaVersion: reducerSchemaVersion(reducer),
|
|
1563
|
+
throughSeq: snapshot.reduced.lastSeq,
|
|
1564
|
+
payload: encodeReducerState(reducer, snapshot.reducerStates.get(reducer.name) ?? reducer.initial),
|
|
1565
|
+
updatedAtMs: snapshot.updatedAtMs
|
|
1566
|
+
}))];
|
|
1567
|
+
const writeReducerCheckpointSnapshot = Effect.fnUntraced(function* (snapshot) {
|
|
1568
|
+
const checkpoints = yield* Effect.sync(() => buildReducerCheckpointSnapshot(snapshot));
|
|
1569
|
+
yield* store.saveReducerCheckpoints(checkpoints).pipe(Effect.catchCause((cause) => Effect.logError("EDA reducer checkpoint snapshot skipped", {
|
|
1570
|
+
cause: Cause.pretty(cause),
|
|
1571
|
+
reducerNames: checkpoints.map((checkpoint) => checkpoint.name),
|
|
1572
|
+
reason: snapshot.reason,
|
|
1573
|
+
throughSeq: snapshot.reduced.lastSeq
|
|
1574
|
+
})));
|
|
1575
|
+
});
|
|
1576
|
+
yield* Effect.forever(Effect.gen(function* () {
|
|
1577
|
+
const snapshot = yield* Queue.take(reducerCheckpointSnapshots);
|
|
1578
|
+
yield* Effect.yieldNow;
|
|
1579
|
+
yield* writeReducerCheckpointSnapshot(snapshot).pipe(Effect.catchCause((cause) => Effect.logError("EDA reducer checkpoint snapshot worker recovered from defect", {
|
|
1580
|
+
cause: Cause.pretty(cause),
|
|
1581
|
+
reason: snapshot.reason,
|
|
1582
|
+
throughSeq: snapshot.reduced.lastSeq
|
|
1583
|
+
})));
|
|
1584
|
+
})).pipe(Effect.forkIn(runtimeScope), Effect.asVoid);
|
|
1585
|
+
const requestReducerCheckpointSnapshot = (snapshot) => Queue.offer(reducerCheckpointSnapshots, snapshot).pipe(Effect.asVoid);
|
|
1586
|
+
const publishFreshDurables = (committed) => Effect.gen(function* () {
|
|
1587
|
+
const current = yield* Ref.get(state);
|
|
1588
|
+
const fresh = Array.from(committed.filter((entry) => entry.position.seq > current.reduced.lastSeq)).sort((a, b) => a.position.seq - b.position.seq);
|
|
1589
|
+
if (fresh.length === 0) return;
|
|
1590
|
+
const nextReduced = foldReducedState(current.reduced, fresh);
|
|
1591
|
+
const nextReducerStates = reducerRegistry.reduce(current.reducerStates, fresh);
|
|
1592
|
+
yield* Ref.set(state, {
|
|
1593
|
+
reduced: nextReduced,
|
|
1594
|
+
reducerStates: nextReducerStates,
|
|
1595
|
+
ephemeral: current.ephemeral
|
|
1596
|
+
});
|
|
1597
|
+
for (const entry of fresh) yield* liveBus.publish(PositionedEvent.make(entry));
|
|
1598
|
+
return { head: nextReduced.lastSeq };
|
|
1599
|
+
});
|
|
1600
|
+
const snapshot = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
1601
|
+
const snapshotData = () => Ref.get(state).pipe(Effect.map((state) => ({
|
|
1602
|
+
reduced: state.reduced,
|
|
1603
|
+
reducerStates: state.reducerStates
|
|
1604
|
+
})));
|
|
1605
|
+
/**
|
|
1606
|
+
* Append, fold, and publish one durable batch under the session append gate.
|
|
1607
|
+
*
|
|
1608
|
+
* `EDASessionStore` owns durable atomicity; `SessionState` deliberately owns
|
|
1609
|
+
* the post-commit fold/live-publish step so storage never depends on the live
|
|
1610
|
+
* bus and a crash after commit can be recovered by replay.
|
|
1611
|
+
*/
|
|
1612
|
+
const commitDurableEntriesWithinGate = Effect.fn(function* (entries) {
|
|
1613
|
+
if (entries.length === 0) return [];
|
|
1614
|
+
yield* annotateEdaSpan(eventBatchAttributes(entries.map((entry) => entry.event)));
|
|
1615
|
+
const committed = yield* store.append({ entries });
|
|
1616
|
+
yield* annotateEdaSpan(committedBatchAttributes(committed));
|
|
1617
|
+
const published = yield* publishFreshDurables(committed);
|
|
1618
|
+
if (published !== void 0) yield* sinkRegistry.notifyDurableHeadAdvanced(published.head);
|
|
1619
|
+
return committed;
|
|
1620
|
+
});
|
|
1621
|
+
const appendDurableEntries = (entries) => withAppendGate(commitDurableEntriesWithinGate(entries));
|
|
1622
|
+
const appendDurableBatch = (durableEvents) => appendDurableEntries(durableEvents.map((event) => ({ event })));
|
|
1623
|
+
const appendDurable = (event) => Effect.gen(function* () {
|
|
1624
|
+
return (yield* appendDurableBatch([event]))[0];
|
|
1625
|
+
});
|
|
1626
|
+
const commitInitialSystemPrompt = (systemPrompt) => Effect.gen(function* () {
|
|
1627
|
+
if (systemPrompt === void 0) return;
|
|
1628
|
+
if ((yield* Ref.get(state)).reduced.lastSeq > SequenceNumber.make(0)) return;
|
|
1629
|
+
yield* appendDurable(yield* events.systemMessageCommitted({
|
|
1630
|
+
messageId: yield* ids.makeMessageId(),
|
|
1631
|
+
content: systemPrompt
|
|
1632
|
+
}));
|
|
1633
|
+
});
|
|
1634
|
+
const publishEphemeralCore = (event) => withAppendGate(Effect.gen(function* () {
|
|
1635
|
+
const current = yield* Ref.get(state);
|
|
1636
|
+
const head = current.reduced.lastSeq;
|
|
1637
|
+
const nextSubSeq = SubSequenceNumber.make(current.ephemeral.anchorSeq === head ? current.ephemeral.lastSubSeq + 1 : 1);
|
|
1638
|
+
const positioned = PositionedEvent.make({
|
|
1639
|
+
position: Position.make({
|
|
1640
|
+
seq: head,
|
|
1641
|
+
subSeq: nextSubSeq
|
|
1642
|
+
}),
|
|
1643
|
+
event
|
|
1644
|
+
});
|
|
1645
|
+
yield* Ref.set(state, {
|
|
1646
|
+
reduced: current.reduced,
|
|
1647
|
+
reducerStates: current.reducerStates,
|
|
1648
|
+
ephemeral: {
|
|
1649
|
+
anchorSeq: head,
|
|
1650
|
+
lastSubSeq: nextSubSeq
|
|
1651
|
+
}
|
|
1652
|
+
});
|
|
1653
|
+
yield* liveBus.publish(positioned);
|
|
1654
|
+
return positioned;
|
|
1655
|
+
}));
|
|
1656
|
+
const publishEphemeral = (event) => Effect.gen(function* () {
|
|
1657
|
+
const positioned = yield* publishEphemeralCore(event);
|
|
1658
|
+
yield* sinkRegistry.publishEphemeralToSinks(positioned, publishEphemeralCore);
|
|
1659
|
+
return positioned;
|
|
1660
|
+
});
|
|
1661
|
+
const wakeAfterCommandAdmission = () => Queue.offer(ingressSignals, void 0);
|
|
1662
|
+
/** Use indexed store lookup for command idempotency instead of genesis replay. */
|
|
1663
|
+
const findExistingCommandAdmission = (command) => Effect.gen(function* () {
|
|
1664
|
+
if (command.idempotencyKey === void 0 && command.commandId === void 0) return;
|
|
1665
|
+
return yield* store.findCommandAdmission({
|
|
1666
|
+
...command.commandId === void 0 ? {} : { commandId: command.commandId },
|
|
1667
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey }
|
|
1668
|
+
});
|
|
1669
|
+
});
|
|
1670
|
+
const prepareCommandAdmission = (command, preparedByIdempotencyKey, preparedByCommandId) => Effect.gen(function* () {
|
|
1671
|
+
if (command.idempotencyKey !== void 0) {
|
|
1672
|
+
const prepared = preparedByIdempotencyKey.get(command.idempotencyKey);
|
|
1673
|
+
if (prepared !== void 0) return [prepared];
|
|
1674
|
+
}
|
|
1675
|
+
if (command.commandId !== void 0) {
|
|
1676
|
+
const prepared = preparedByCommandId.get(command.commandId);
|
|
1677
|
+
if (prepared !== void 0) return [prepared];
|
|
1678
|
+
}
|
|
1679
|
+
const existing = yield* findExistingCommandAdmission(command);
|
|
1680
|
+
if (existing !== void 0) {
|
|
1681
|
+
rememberPreparedCommand(existing.event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1682
|
+
return [existing.event];
|
|
1683
|
+
}
|
|
1684
|
+
const commandId = command.commandId ?? (yield* ids.makeCommandId());
|
|
1685
|
+
const admitted = commandWithId(command, commandId);
|
|
1686
|
+
const event = yield* events.commandAdmitted({ command: admitted });
|
|
1687
|
+
rememberPreparedCommand(event, preparedByIdempotencyKey, preparedByCommandId);
|
|
1688
|
+
if (admitted._tag !== "SubmitMessage" || admitted.disposition === "interrupt") return [event];
|
|
1689
|
+
const current = yield* Ref.get(state);
|
|
1690
|
+
const pausedMessageIds = current.reduced.commandQueues.pausedQueue.map((message) => message.messageId);
|
|
1691
|
+
const requestedClear = admitted.expectedPausedMessageIdsToCancel;
|
|
1692
|
+
if (admitted.disposition === "queue" && pausedMessageIds.length > 0) {
|
|
1693
|
+
if (requestedClear === void 0) return yield* new SessionCommandAdmissionConflict({
|
|
1694
|
+
code: "queue_paused",
|
|
1695
|
+
message: "Queue paused because you interrupted",
|
|
1696
|
+
pausedMessageIds
|
|
1697
|
+
});
|
|
1698
|
+
if (!sameMessageIdSet(requestedClear, pausedMessageIds)) return yield* new SessionCommandAdmissionConflict({
|
|
1699
|
+
code: "paused_queue_changed",
|
|
1700
|
+
message: "Paused queue changed; confirm the current messages before clearing",
|
|
1701
|
+
pausedMessageIds
|
|
1702
|
+
});
|
|
1703
|
+
} else if (requestedClear !== void 0 && !sameMessageIdSet(requestedClear, pausedMessageIds)) return yield* new SessionCommandAdmissionConflict({
|
|
1704
|
+
code: "paused_queue_changed",
|
|
1705
|
+
message: "Paused queue changed; confirm the current messages before clearing",
|
|
1706
|
+
pausedMessageIds
|
|
1707
|
+
});
|
|
1708
|
+
const messageId = yield* ids.makeMessageId();
|
|
1709
|
+
const submitted = yield* events.userMessageSubmitted({
|
|
1710
|
+
commandId,
|
|
1711
|
+
messageId,
|
|
1712
|
+
disposition: admitted.disposition,
|
|
1713
|
+
content: admitted.content
|
|
1714
|
+
});
|
|
1715
|
+
const clearEvents = [];
|
|
1716
|
+
if (requestedClear !== void 0) for (const pausedMessageId of requestedClear) {
|
|
1717
|
+
const pausedMessage = current.reduced.messages.get(pausedMessageId);
|
|
1718
|
+
if (pausedMessage?._tag !== "User" && pausedMessage?._tag !== "Steering") continue;
|
|
1719
|
+
clearEvents.push(yield* events.userMessageCancelled({
|
|
1720
|
+
commandId,
|
|
1721
|
+
messageId: pausedMessageId,
|
|
1722
|
+
reason: "clear-paused-queue"
|
|
1723
|
+
}));
|
|
1724
|
+
const origin = current.reduced.commands.get(pausedMessage.commandId);
|
|
1725
|
+
if (origin !== void 0 && origin.startedSeq === void 0 && origin.terminal === void 0) clearEvents.push(yield* events.commandCancelled({
|
|
1726
|
+
commandId: origin.commandId,
|
|
1727
|
+
reason: "paused queue cleared by replacement message"
|
|
1728
|
+
}));
|
|
1729
|
+
}
|
|
1730
|
+
return [
|
|
1731
|
+
event,
|
|
1732
|
+
...clearEvents,
|
|
1733
|
+
submitted
|
|
1734
|
+
];
|
|
1735
|
+
});
|
|
1736
|
+
const submitBatch = Effect.fn(function* (input) {
|
|
1737
|
+
const commandCount = input.filter(isEDACommand).length;
|
|
1738
|
+
yield* annotateEdaSpan({
|
|
1739
|
+
"eda.command.submittable_count": input.length,
|
|
1740
|
+
"eda.command.count": commandCount,
|
|
1741
|
+
"eda.event.app_owned_count": input.length - commandCount
|
|
1742
|
+
});
|
|
1743
|
+
const committed = yield* withAppendGate(Effect.gen(function* () {
|
|
1744
|
+
const preparedByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1745
|
+
const preparedByCommandId = /* @__PURE__ */ new Map();
|
|
1746
|
+
return yield* commitDurableEntriesWithinGate((yield* Effect.forEach(input, (item) => isEDACommand(item) ? prepareCommandAdmission(item, preparedByIdempotencyKey, preparedByCommandId) : Effect.succeed([item]))).flat().map((event) => ({ event })));
|
|
1747
|
+
}));
|
|
1748
|
+
yield* annotateEdaSpan(committedBatchAttributes(committed));
|
|
1749
|
+
if (commandCount > 0) yield* wakeAfterCommandAdmission();
|
|
1750
|
+
return committed;
|
|
1751
|
+
});
|
|
1752
|
+
const admitCommand = (command) => Effect.gen(function* () {
|
|
1753
|
+
return (yield* submitBatch([command]))[0];
|
|
1754
|
+
});
|
|
1755
|
+
const initialize = (input) => commitInitialSystemPrompt(input.systemPrompt);
|
|
1756
|
+
const sessionApi = {
|
|
1757
|
+
initialize,
|
|
1758
|
+
submitBatch,
|
|
1759
|
+
admitCommand,
|
|
1760
|
+
snapshot,
|
|
1761
|
+
snapshotData,
|
|
1762
|
+
appendDurable,
|
|
1763
|
+
appendDurableBatch,
|
|
1764
|
+
publishEphemeral,
|
|
1765
|
+
drainReadyWork: (input) => drainReadyWork(input),
|
|
1766
|
+
start: (input) => start(input)
|
|
1767
|
+
};
|
|
1768
|
+
const startedBoundaryGuard = makeStartedBoundaryGuard(sessionApi);
|
|
1769
|
+
const currentReduced = () => Ref.get(state).pipe(Effect.map((state) => state.reduced));
|
|
1770
|
+
const currentData = () => Ref.get(state);
|
|
1771
|
+
const contextProjectionFor = (reduced) => Effect.gen(function* () {
|
|
1772
|
+
const summaryId = reduced.context.currentSummaryId;
|
|
1773
|
+
if (summaryId === void 0) return emptyContextProjection;
|
|
1774
|
+
const summary = yield* store.loadSummaryArtifact(summaryId);
|
|
1775
|
+
if (summary === void 0) return yield* new EDASessionStoreError({ message: `ReducedState references missing summary ${summaryId}` });
|
|
1776
|
+
return ContextProjection.make({
|
|
1777
|
+
contextVersion: reduced.context.version,
|
|
1778
|
+
currentSummary: summary
|
|
1779
|
+
});
|
|
1780
|
+
});
|
|
1781
|
+
const requestCurrentReducerCheckpointSnapshot = (reason) => Effect.gen(function* () {
|
|
1782
|
+
const current = yield* currentData();
|
|
1783
|
+
if (current.reduced.lastSeq <= SequenceNumber.make(0)) return;
|
|
1784
|
+
yield* requestReducerCheckpointSnapshot({
|
|
1785
|
+
reason,
|
|
1786
|
+
reduced: current.reduced,
|
|
1787
|
+
reducerStates: current.reducerStates,
|
|
1788
|
+
updatedAtMs: yield* Clock.currentTimeMillis
|
|
1789
|
+
});
|
|
1790
|
+
});
|
|
1791
|
+
const requestStartupRecoveryCheckpointIfNeeded = () => Effect.gen(function* () {
|
|
1792
|
+
if (yield* Ref.get(startupRecoveryCheckpointRequested)) return;
|
|
1793
|
+
if ((yield* currentData()).reduced.lastSeq <= startupRecoveryCheckpointSeq) return;
|
|
1794
|
+
yield* Ref.set(startupRecoveryCheckpointRequested, true);
|
|
1795
|
+
yield* requestCurrentReducerCheckpointSnapshot("startup-recovery-complete");
|
|
1796
|
+
});
|
|
1797
|
+
const maybeCompactAtBoundary = () => Effect.gen(function* () {
|
|
1798
|
+
const current = yield* currentReduced();
|
|
1799
|
+
const next = (yield* compactionRunner.maybeCompact({
|
|
1800
|
+
state: current,
|
|
1801
|
+
context: yield* contextProjectionFor(current),
|
|
1802
|
+
appendDurableEntries
|
|
1803
|
+
})).length === 0 ? current : yield* currentReduced();
|
|
1804
|
+
yield* requestCurrentReducerCheckpointSnapshot("turn-boundary");
|
|
1805
|
+
return next;
|
|
1806
|
+
});
|
|
1807
|
+
const cancelCommand = (commandId, reason) => Effect.gen(function* () {
|
|
1808
|
+
const committed = yield* appendDurable(yield* events.commandCancelled({
|
|
1809
|
+
commandId,
|
|
1810
|
+
reason
|
|
1811
|
+
}));
|
|
1812
|
+
return SessionCommandCancelled.make({ committed });
|
|
1813
|
+
});
|
|
1814
|
+
const failInterruptedTurnIfOpen = (active, reason) => Effect.gen(function* () {
|
|
1815
|
+
if ((yield* currentReduced()).turns.get(active.turnId)?.terminal !== void 0) return;
|
|
1816
|
+
return yield* appendDurable(yield* events.turnFailed({
|
|
1817
|
+
runId: active.runId,
|
|
1818
|
+
turnId: active.turnId,
|
|
1819
|
+
error: interruptionFailure("turn", reason, {
|
|
1820
|
+
runId: active.runId,
|
|
1821
|
+
turnId: active.turnId
|
|
1822
|
+
})
|
|
1823
|
+
}));
|
|
1824
|
+
});
|
|
1825
|
+
const completeRunAndCommand = (commandId, runId) => Effect.gen(function* () {
|
|
1826
|
+
const committed = yield* appendDurableBatch([yield* events.runCompleted({ runId }), yield* events.commandCompleted({ commandId })]);
|
|
1827
|
+
return SessionCommandCompleted.make({ committed: committed.at(-1) });
|
|
1828
|
+
});
|
|
1829
|
+
const failRunAndCommandWithError = (commandId, runId, error) => Effect.gen(function* () {
|
|
1830
|
+
const runFailed = yield* events.runFailed({
|
|
1831
|
+
runId,
|
|
1832
|
+
error
|
|
1833
|
+
});
|
|
1834
|
+
const commandFailed = yield* events.commandFailed({
|
|
1835
|
+
commandId,
|
|
1836
|
+
error
|
|
1837
|
+
});
|
|
1838
|
+
const failurePlan = planRunFailure(yield* currentReduced());
|
|
1839
|
+
const resumeEvents = [];
|
|
1840
|
+
if (failurePlan.messageIdsToResume.length > 0) {
|
|
1841
|
+
const resumeCommandId = yield* ids.makeCommandId();
|
|
1842
|
+
resumeEvents.push(yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
1843
|
+
commandId: resumeCommandId,
|
|
1844
|
+
messageIds: failurePlan.messageIdsToResume
|
|
1845
|
+
}) }));
|
|
1846
|
+
}
|
|
1847
|
+
const committed = yield* appendDurableBatch([
|
|
1848
|
+
runFailed,
|
|
1849
|
+
commandFailed,
|
|
1850
|
+
...resumeEvents
|
|
1851
|
+
]);
|
|
1852
|
+
return SessionCommandFailed.make({ committed: committed.at(-1) });
|
|
1853
|
+
});
|
|
1854
|
+
const failRunAndCommand = (commandId, runId, turn) => Effect.gen(function* () {
|
|
1855
|
+
if (turn.outcome._tag !== "TurnRunFailed") return yield* Effect.die(/* @__PURE__ */ new Error("Cannot fail run from a completed turn"));
|
|
1856
|
+
return yield* failRunAndCommandWithError(commandId, runId, (yield* requireTurnFailed(turn.outcome.committed)).event.payload.error);
|
|
1857
|
+
});
|
|
1858
|
+
const interruptRunAndCommand = (active, reason) => Effect.gen(function* () {
|
|
1859
|
+
const failurePlan = planRunFailure(yield* currentReduced());
|
|
1860
|
+
const committed = yield* appendDurableBatch([
|
|
1861
|
+
yield* events.runFailed({
|
|
1862
|
+
runId: active.runId,
|
|
1863
|
+
error: interruptionFailure("run", reason, { runId: active.runId })
|
|
1864
|
+
}),
|
|
1865
|
+
yield* events.commandCancelled({
|
|
1866
|
+
commandId: active.commandId,
|
|
1867
|
+
reason
|
|
1868
|
+
}),
|
|
1869
|
+
...failurePlan.messageIdsToResume.length === 0 ? [] : [yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
1870
|
+
commandId: yield* ids.makeCommandId(),
|
|
1871
|
+
messageIds: failurePlan.messageIdsToResume
|
|
1872
|
+
}) })]
|
|
1873
|
+
]);
|
|
1874
|
+
return SessionCommandCancelled.make({ committed: committed.at(-1) });
|
|
1875
|
+
});
|
|
1876
|
+
const userInterruptionEvents = (active, interruptionCommandId, reason) => Effect.gen(function* () {
|
|
1877
|
+
const current = yield* currentReduced();
|
|
1878
|
+
const plan = planUserInterruption(current);
|
|
1879
|
+
const turn = current.turns.get(active.turnId);
|
|
1880
|
+
const terminalEvents = [];
|
|
1881
|
+
if (turn?.terminal === void 0) terminalEvents.push(yield* events.turnFailed({
|
|
1882
|
+
runId: active.runId,
|
|
1883
|
+
turnId: active.turnId,
|
|
1884
|
+
error: interruptionFailure("turn", reason, {
|
|
1885
|
+
runId: active.runId,
|
|
1886
|
+
turnId: active.turnId
|
|
1887
|
+
})
|
|
1888
|
+
}));
|
|
1889
|
+
terminalEvents.push(yield* events.runFailed({
|
|
1890
|
+
runId: active.runId,
|
|
1891
|
+
error: interruptionFailure("run", reason, { runId: active.runId })
|
|
1892
|
+
}), yield* events.commandCancelled({
|
|
1893
|
+
commandId: active.commandId,
|
|
1894
|
+
reason
|
|
1895
|
+
}));
|
|
1896
|
+
if (plan.messageIdsToPause.length > 0) terminalEvents.push(yield* events.pendingMessagesPaused({
|
|
1897
|
+
interruptionCommandId,
|
|
1898
|
+
runId: active.runId,
|
|
1899
|
+
messageIds: plan.messageIdsToPause,
|
|
1900
|
+
reason: "user-interrupted"
|
|
1901
|
+
}));
|
|
1902
|
+
return terminalEvents;
|
|
1903
|
+
});
|
|
1904
|
+
const appendUserInterruption = (active, interruptionCommandId, reason) => Effect.gen(function* () {
|
|
1905
|
+
yield* appendDurableBatch(yield* userInterruptionEvents(active, interruptionCommandId, reason));
|
|
1906
|
+
});
|
|
1907
|
+
const startRunTrace = Effect.fn(function* (input) {
|
|
1908
|
+
const runScope = yield* Scope.fork(runtimeScope, "sequential");
|
|
1909
|
+
return yield* Effect.gen(function* () {
|
|
1910
|
+
const links = input.admissionTrace === void 0 ? [] : [{
|
|
1911
|
+
context: input.admissionTrace.span,
|
|
1912
|
+
attributes: {
|
|
1913
|
+
"eda.trace.link_type": "command_admission",
|
|
1914
|
+
"eda.command.id": input.commandId
|
|
1915
|
+
}
|
|
1916
|
+
}];
|
|
1917
|
+
const runSpan = yield* Effect.makeSpanScoped("agent.run", {
|
|
1918
|
+
root: true,
|
|
1919
|
+
attributes: {
|
|
1920
|
+
"eda.session.id": sessionContext.sessionId,
|
|
1921
|
+
"eda.command.id": input.commandId,
|
|
1922
|
+
"eda.run.id": input.runId,
|
|
1923
|
+
"eda.model.provider": input.modelSelection.provider,
|
|
1924
|
+
"eda.model.id": input.modelSelection.modelId
|
|
1925
|
+
},
|
|
1926
|
+
links: links.map((link) => ({
|
|
1927
|
+
span: toEdaExternalSpan(link.context),
|
|
1928
|
+
attributes: link.attributes
|
|
1929
|
+
}))
|
|
1930
|
+
}).pipe(Scope.provide(runScope));
|
|
1931
|
+
return {
|
|
1932
|
+
runScope,
|
|
1933
|
+
runSpan,
|
|
1934
|
+
runTrace: makeEDARunTrace(edaTraceContextFromSpan(runSpan), links)
|
|
1935
|
+
};
|
|
1936
|
+
}).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(runScope, exit) : Effect.void));
|
|
1937
|
+
});
|
|
1938
|
+
const closeRunTraceOnFailure = (trace, effect) => effect.pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(trace.runScope, exit) : Effect.void));
|
|
1939
|
+
const startTurn = Effect.fn(function* (input) {
|
|
1940
|
+
const inputMessageIds = input.promptInput.selectedUserMessages.map((message) => message.messageId);
|
|
1941
|
+
const prompt = yield* buildEDAPrompt(promptProjector, input.promptInput);
|
|
1942
|
+
const turnId = yield* ids.makeTurnId();
|
|
1943
|
+
const current = yield* currentReduced();
|
|
1944
|
+
const remainingToolCalls = remainingToolCallsForRun(current, input.runId, input.maxToolCallsPerRun ?? defaultMaxToolCallsPerRun);
|
|
1945
|
+
const remainingToolRejectionCorrections = remainingToolRejectionCorrectionsForRun(current, input.runId, NonNegativeInt.make(maxToolRejectionCorrections));
|
|
1946
|
+
yield* annotateEdaSpan({
|
|
1947
|
+
"eda.command.id": input.commandId,
|
|
1948
|
+
"eda.run.id": input.runId,
|
|
1949
|
+
"eda.turn.id": turnId,
|
|
1950
|
+
"eda.message.input_count": inputMessageIds.length
|
|
1951
|
+
});
|
|
1952
|
+
const started = yield* appendDurable(yield* events.turnStarted({
|
|
1953
|
+
runId: input.runId,
|
|
1954
|
+
turnId,
|
|
1955
|
+
...inputMessageIds.length === 0 ? {} : { inputMessageIds }
|
|
1956
|
+
}));
|
|
1957
|
+
const turnScope = yield* Scope.fork(input.runScope, "sequential");
|
|
1958
|
+
const fiber = yield* keepAlive.withActiveWork(`turn:${turnId}`, turnRunner.runTurn({
|
|
1959
|
+
runId: input.runId,
|
|
1960
|
+
turnId,
|
|
1961
|
+
prompt,
|
|
1962
|
+
eventSink: sessionApi,
|
|
1963
|
+
started,
|
|
1964
|
+
modelSelection: input.modelSelection,
|
|
1965
|
+
maxToolCallsPerRun: remainingToolCalls,
|
|
1966
|
+
remainingToolRejectionCorrections,
|
|
1967
|
+
maxToolRejectionCorrections: NonNegativeInt.make(maxToolRejectionCorrections)
|
|
1968
|
+
})).pipe(Effect.withParentSpan(input.runSpan), Effect.forkIn(turnScope));
|
|
1969
|
+
yield* Ref.set(executionState, {
|
|
1970
|
+
_tag: "Running",
|
|
1971
|
+
commandId: input.commandId,
|
|
1972
|
+
commandStarted: input.commandStarted,
|
|
1973
|
+
runId: input.runId,
|
|
1974
|
+
turnId,
|
|
1975
|
+
modelSelection: input.modelSelection,
|
|
1976
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
1977
|
+
runScope: input.runScope,
|
|
1978
|
+
runSpan: input.runSpan,
|
|
1979
|
+
turnScope,
|
|
1980
|
+
fiber
|
|
1981
|
+
});
|
|
1982
|
+
return SessionForkedCommand.make({ commandId: input.commandId });
|
|
1983
|
+
});
|
|
1984
|
+
const startSubmitCommand = Effect.fn(function* (command, input) {
|
|
1985
|
+
if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("startSubmitCommand requires SubmitMessage"));
|
|
1986
|
+
const submit = command.command;
|
|
1987
|
+
const commandId = command.commandId;
|
|
1988
|
+
yield* annotateEdaSpan({
|
|
1989
|
+
"eda.command.id": commandId,
|
|
1990
|
+
"eda.command.disposition": submit.disposition,
|
|
1991
|
+
"eda.model.provider": input.modelSelection.provider,
|
|
1992
|
+
"eda.model.id": input.modelSelection.modelId
|
|
1993
|
+
});
|
|
1994
|
+
const commandStarted = yield* events.commandStarted({ commandId });
|
|
1995
|
+
const beforeStart = yield* currentReduced();
|
|
1996
|
+
const submittedMessage = Array.from(beforeStart.messages.values()).find((message) => message._tag === "User" && message.commandId === commandId);
|
|
1997
|
+
const messageId = submittedMessage?.messageId ?? (yield* ids.makeMessageId());
|
|
1998
|
+
const userMessage = submittedMessage === void 0 ? yield* events.userMessageCommitted({
|
|
1999
|
+
commandId,
|
|
2000
|
+
messageId,
|
|
2001
|
+
content: submit.content
|
|
2002
|
+
}) : void 0;
|
|
2003
|
+
const runId = yield* ids.makeRunId();
|
|
2004
|
+
const activeRunTrace = yield* startRunTrace({
|
|
2005
|
+
admissionTrace: command.admissionTrace,
|
|
2006
|
+
commandId,
|
|
2007
|
+
modelSelection: input.modelSelection,
|
|
2008
|
+
runId
|
|
2009
|
+
});
|
|
2010
|
+
return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
|
|
2011
|
+
const runStarted = yield* events.runStarted({
|
|
2012
|
+
runId,
|
|
2013
|
+
commandIds: [commandId],
|
|
2014
|
+
modelSelection: input.modelSelection,
|
|
2015
|
+
trace: activeRunTrace.runTrace
|
|
2016
|
+
});
|
|
2017
|
+
const startedEvents = yield* appendDurableBatch([
|
|
2018
|
+
commandStarted,
|
|
2019
|
+
...userMessage === void 0 ? [] : [userMessage],
|
|
2020
|
+
runStarted
|
|
2021
|
+
]);
|
|
2022
|
+
const selectedUserContent = submittedMessage === void 0 ? submit.content : Schema.decodeUnknownSync(UserMessageContent)(submittedMessage.content);
|
|
2023
|
+
const promptState = yield* currentData();
|
|
2024
|
+
return yield* startTurn({
|
|
2025
|
+
commandId,
|
|
2026
|
+
commandStarted: startedEvents[0],
|
|
2027
|
+
runId,
|
|
2028
|
+
modelSelection: input.modelSelection,
|
|
2029
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2030
|
+
promptInput: {
|
|
2031
|
+
sessionId: sessionContext.sessionId,
|
|
2032
|
+
state: promptState.reduced,
|
|
2033
|
+
reducerStates: promptState.reducerStates,
|
|
2034
|
+
context: yield* contextProjectionFor(promptState.reduced),
|
|
2035
|
+
selectedUserMessages: [{
|
|
2036
|
+
commandId,
|
|
2037
|
+
content: selectedUserContent,
|
|
2038
|
+
messageId
|
|
2039
|
+
}]
|
|
2040
|
+
},
|
|
2041
|
+
runScope: activeRunTrace.runScope,
|
|
2042
|
+
runSpan: activeRunTrace.runSpan
|
|
2043
|
+
});
|
|
2044
|
+
}));
|
|
2045
|
+
});
|
|
2046
|
+
const startResumePendingMessages = Effect.fn(function* (command, input) {
|
|
2047
|
+
if (command.command._tag !== "ResumePendingMessages") return yield* Effect.die(/* @__PURE__ */ new Error("Resume dispatch requires ResumePendingMessages"));
|
|
2048
|
+
const current = yield* currentData();
|
|
2049
|
+
const pending = command.command.messageIds.flatMap((messageId) => {
|
|
2050
|
+
const message = current.reduced.messages.get(messageId);
|
|
2051
|
+
return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
|
|
2052
|
+
});
|
|
2053
|
+
if (pending.length === 0) return yield* processInactiveStopCommand(command);
|
|
2054
|
+
const commandStarted = yield* events.commandStarted({ commandId: command.commandId });
|
|
2055
|
+
const runId = yield* ids.makeRunId();
|
|
2056
|
+
const activeRunTrace = yield* startRunTrace({
|
|
2057
|
+
admissionTrace: command.admissionTrace,
|
|
2058
|
+
commandId: command.commandId,
|
|
2059
|
+
modelSelection: input.modelSelection,
|
|
2060
|
+
runId
|
|
2061
|
+
});
|
|
2062
|
+
return yield* closeRunTraceOnFailure(activeRunTrace, Effect.gen(function* () {
|
|
2063
|
+
const started = yield* appendDurableBatch([commandStarted, yield* events.runStarted({
|
|
2064
|
+
runId,
|
|
2065
|
+
commandIds: [command.commandId, ...pending.map((message) => message.commandId)],
|
|
2066
|
+
modelSelection: input.modelSelection,
|
|
2067
|
+
trace: activeRunTrace.runTrace
|
|
2068
|
+
})]);
|
|
2069
|
+
return yield* startTurn({
|
|
2070
|
+
commandId: command.commandId,
|
|
2071
|
+
commandStarted: started[0],
|
|
2072
|
+
runId,
|
|
2073
|
+
modelSelection: input.modelSelection,
|
|
2074
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2075
|
+
promptInput: {
|
|
2076
|
+
sessionId: sessionContext.sessionId,
|
|
2077
|
+
state: current.reduced,
|
|
2078
|
+
reducerStates: current.reducerStates,
|
|
2079
|
+
context: yield* contextProjectionFor(current.reduced),
|
|
2080
|
+
selectedUserMessages: pending.map((message) => ({
|
|
2081
|
+
commandId: message.commandId,
|
|
2082
|
+
content: message.content,
|
|
2083
|
+
messageId: message.messageId
|
|
2084
|
+
}))
|
|
2085
|
+
},
|
|
2086
|
+
runScope: activeRunTrace.runScope,
|
|
2087
|
+
runSpan: activeRunTrace.runSpan
|
|
2088
|
+
});
|
|
2089
|
+
}));
|
|
2090
|
+
});
|
|
2091
|
+
const processInactiveStopCommand = Effect.fn(function* (command) {
|
|
2092
|
+
const commandId = command.commandId;
|
|
2093
|
+
return (yield* startedBoundaryGuard({
|
|
2094
|
+
start: events.commandStarted({ commandId }),
|
|
2095
|
+
body: (started) => Effect.gen(function* () {
|
|
2096
|
+
return {
|
|
2097
|
+
started,
|
|
2098
|
+
outcome: yield* cancelCommand(commandId, "no active turn")
|
|
2099
|
+
};
|
|
2100
|
+
}),
|
|
2101
|
+
onFailure: (error) => events.commandFailed({
|
|
2102
|
+
commandId,
|
|
2103
|
+
error
|
|
2104
|
+
}),
|
|
2105
|
+
onInterrupt: events.commandCancelled({
|
|
2106
|
+
commandId,
|
|
2107
|
+
reason: "interrupted"
|
|
2108
|
+
})
|
|
2109
|
+
})).value;
|
|
2110
|
+
});
|
|
2111
|
+
const inspectExecutionState = () => Effect.gen(function* () {
|
|
2112
|
+
const current = yield* Ref.get(executionState);
|
|
2113
|
+
if (current._tag === "Idle") return;
|
|
2114
|
+
if (current._tag === "Completed") return {
|
|
2115
|
+
_tag: "CompletedTurn",
|
|
2116
|
+
active: current,
|
|
2117
|
+
turn: current.turn
|
|
2118
|
+
};
|
|
2119
|
+
const exit = current.fiber.pollUnsafe();
|
|
2120
|
+
if (exit === void 0) return {
|
|
2121
|
+
_tag: "RunningTurn",
|
|
2122
|
+
active: current
|
|
2123
|
+
};
|
|
2124
|
+
yield* Scope.close(current.turnScope, exit);
|
|
2125
|
+
if (Exit.isFailure(exit)) {
|
|
2126
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2127
|
+
if (hasEDASessionStoreError(exit.cause)) {
|
|
2128
|
+
yield* Scope.close(current.runScope, exit);
|
|
2129
|
+
return yield* Effect.failCause(exit.cause);
|
|
2130
|
+
}
|
|
2131
|
+
if (Cause.hasInterruptsOnly(exit.cause)) {
|
|
2132
|
+
yield* failInterruptedTurnIfOpen(current, "interrupted");
|
|
2133
|
+
const outcome = yield* interruptRunAndCommand(current, "interrupted");
|
|
2134
|
+
yield* Scope.close(current.runScope, exit);
|
|
2135
|
+
return {
|
|
2136
|
+
_tag: "FailedTurn",
|
|
2137
|
+
result: {
|
|
2138
|
+
started: current.commandStarted,
|
|
2139
|
+
outcome
|
|
2140
|
+
}
|
|
2141
|
+
};
|
|
2142
|
+
}
|
|
2143
|
+
const outcome = yield* failRunAndCommandWithError(current.commandId, current.runId, failurePayloadFromCause(exit.cause));
|
|
2144
|
+
yield* Scope.close(current.runScope, exit);
|
|
2145
|
+
return {
|
|
2146
|
+
_tag: "FailedTurn",
|
|
2147
|
+
result: {
|
|
2148
|
+
started: current.commandStarted,
|
|
2149
|
+
outcome
|
|
2150
|
+
}
|
|
2151
|
+
};
|
|
2152
|
+
}
|
|
2153
|
+
const completed = {
|
|
2154
|
+
_tag: "Completed",
|
|
2155
|
+
commandId: current.commandId,
|
|
2156
|
+
commandStarted: current.commandStarted,
|
|
2157
|
+
runId: current.runId,
|
|
2158
|
+
turnId: current.turnId,
|
|
2159
|
+
modelSelection: current.modelSelection,
|
|
2160
|
+
...current.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: current.maxToolCallsPerRun },
|
|
2161
|
+
runScope: current.runScope,
|
|
2162
|
+
runSpan: current.runSpan,
|
|
2163
|
+
turn: exit.value
|
|
2164
|
+
};
|
|
2165
|
+
yield* Ref.set(executionState, completed);
|
|
2166
|
+
return {
|
|
2167
|
+
_tag: "CompletedTurn",
|
|
2168
|
+
active: completed,
|
|
2169
|
+
turn: exit.value
|
|
2170
|
+
};
|
|
2171
|
+
});
|
|
2172
|
+
const recoverSession = Effect.fnUntraced(function* (reduced, reason, input) {
|
|
2173
|
+
const plan = planSessionRecovery(reduced);
|
|
2174
|
+
yield* annotateEdaSpan({
|
|
2175
|
+
"eda.recovery.reason": reason,
|
|
2176
|
+
"eda.recovery.open_tool_calls": plan.openToolCalls.length,
|
|
2177
|
+
"eda.recovery.active_inferences": plan.activeInferences.length,
|
|
2178
|
+
"eda.recovery.active_turns": plan.activeTurns.length,
|
|
2179
|
+
"eda.recovery.active_runs": plan.activeRuns.length,
|
|
2180
|
+
"eda.recovery.active_commands": plan.activeCommands.length,
|
|
2181
|
+
"eda.recovery.pending_stop_requests": plan.pendingStopRequests.length,
|
|
2182
|
+
"eda.recovery.open_compactions": plan.openCompactions.length,
|
|
2183
|
+
"eda.recovery.messages_to_pause": plan.messageIdsToPause.length,
|
|
2184
|
+
"eda.recovery.messages_to_resume": plan.messageIdsToResume.length
|
|
2185
|
+
});
|
|
2186
|
+
const recoveryEvents = [];
|
|
2187
|
+
for (const tool of plan.openToolCalls) {
|
|
2188
|
+
const error = toolCancelledFailureFromRecord(tool, reason);
|
|
2189
|
+
recoveryEvents.push(yield* events.toolCallFailed({
|
|
2190
|
+
toolCallId: tool.toolCallId,
|
|
2191
|
+
error,
|
|
2192
|
+
promptPart: toolCancelledPromptPartFromRecord(tool, error)
|
|
2193
|
+
}));
|
|
2194
|
+
}
|
|
2195
|
+
for (const inference of plan.activeInferences) recoveryEvents.push(yield* events.inferenceFailed({
|
|
2196
|
+
runId: inference.runId,
|
|
2197
|
+
turnId: inference.turnId,
|
|
2198
|
+
inferenceId: inference.inferenceId,
|
|
2199
|
+
error: FailurePayload.make({
|
|
2200
|
+
message: `inference interrupted: ${reason}`,
|
|
2201
|
+
code: "inference.interrupted",
|
|
2202
|
+
details: { reason }
|
|
2203
|
+
})
|
|
2204
|
+
}));
|
|
2205
|
+
const stoppedRunIds = new Set(plan.pendingStopRequests.flatMap((request) => request.requestedRunId === void 0 ? [] : [request.requestedRunId]));
|
|
2206
|
+
for (const turn of plan.activeTurns) recoveryEvents.push(yield* events.turnFailed({
|
|
2207
|
+
runId: turn.runId,
|
|
2208
|
+
turnId: turn.turnId,
|
|
2209
|
+
error: interruptionFailure("turn", reason, {
|
|
2210
|
+
runId: turn.runId,
|
|
2211
|
+
turnId: turn.turnId
|
|
2212
|
+
}, !stoppedRunIds.has(turn.runId))
|
|
2213
|
+
}));
|
|
2214
|
+
for (const run of plan.activeRuns) recoveryEvents.push(yield* events.runFailed({
|
|
2215
|
+
runId: run.runId,
|
|
2216
|
+
error: interruptionFailure("run", reason, { runId: run.runId }, !stoppedRunIds.has(run.runId))
|
|
2217
|
+
}));
|
|
2218
|
+
const completedStopCommandIds = /* @__PURE__ */ new Set();
|
|
2219
|
+
for (const request of plan.pendingStopRequests) {
|
|
2220
|
+
if (request.requestedRunId === void 0 || request.requestedTurnId === void 0) continue;
|
|
2221
|
+
completedStopCommandIds.add(request.commandId);
|
|
2222
|
+
}
|
|
2223
|
+
for (const command of plan.activeCommands) {
|
|
2224
|
+
if (completedStopCommandIds.has(command.commandId)) continue;
|
|
2225
|
+
if (command.commandId === plan.continuation?.command.commandId) continue;
|
|
2226
|
+
recoveryEvents.push(yield* events.commandCancelled({
|
|
2227
|
+
commandId: command.commandId,
|
|
2228
|
+
reason
|
|
2229
|
+
}));
|
|
2230
|
+
}
|
|
2231
|
+
for (const request of plan.pendingStopRequests) {
|
|
2232
|
+
if (request.requestedRunId === void 0 || request.requestedTurnId === void 0) continue;
|
|
2233
|
+
recoveryEvents.push(yield* events.stopTurnApplied({
|
|
2234
|
+
commandId: request.commandId,
|
|
2235
|
+
runId: request.requestedRunId,
|
|
2236
|
+
turnId: request.requestedTurnId
|
|
2237
|
+
}));
|
|
2238
|
+
recoveryEvents.push(yield* events.commandCompleted({ commandId: request.commandId }));
|
|
2239
|
+
}
|
|
2240
|
+
const applicableStop = plan.pendingStopRequests.find((request) => request.requestedRunId !== void 0 && request.requestedTurnId !== void 0);
|
|
2241
|
+
if (applicableStop !== void 0 && plan.messageIdsToPause.length > 0) recoveryEvents.push(yield* events.pendingMessagesPaused({
|
|
2242
|
+
interruptionCommandId: applicableStop.commandId,
|
|
2243
|
+
runId: applicableStop.requestedRunId,
|
|
2244
|
+
messageIds: plan.messageIdsToPause,
|
|
2245
|
+
reason: "user-interrupted"
|
|
2246
|
+
}));
|
|
2247
|
+
for (const compaction of plan.openCompactions) recoveryEvents.push(compaction.rebasedSeq === void 0 ? yield* events.compactionFailed({
|
|
2248
|
+
compactionId: compaction.compactionId,
|
|
2249
|
+
error: FailurePayload.make({ message: "runtime restarted before compaction completed" })
|
|
2250
|
+
}) : yield* events.compactionCompleted({ compactionId: compaction.compactionId }));
|
|
2251
|
+
if (plan.messageIdsToResume.length > 0) recoveryEvents.push(yield* events.commandAdmitted({ command: new ResumePendingMessagesCommand({
|
|
2252
|
+
commandId: yield* ids.makeCommandId(),
|
|
2253
|
+
messageIds: plan.messageIdsToResume
|
|
2254
|
+
}) }));
|
|
2255
|
+
const continuationRunId = plan.continuation === void 0 ? void 0 : yield* ids.makeRunId();
|
|
2256
|
+
const continuationRunTrace = plan.continuation === void 0 || continuationRunId === void 0 ? void 0 : yield* startRunTrace({
|
|
2257
|
+
admissionTrace: plan.continuation.command.admissionTrace,
|
|
2258
|
+
commandId: plan.continuation.command.commandId,
|
|
2259
|
+
modelSelection: input.modelSelection,
|
|
2260
|
+
runId: continuationRunId
|
|
2261
|
+
});
|
|
2262
|
+
const completeRecovery = Effect.gen(function* () {
|
|
2263
|
+
if (plan.continuation !== void 0 && continuationRunId !== void 0 && continuationRunTrace !== void 0) recoveryEvents.push(yield* events.runStarted({
|
|
2264
|
+
runId: continuationRunId,
|
|
2265
|
+
commandIds: plan.continuation.run.commandIds,
|
|
2266
|
+
modelSelection: input.modelSelection,
|
|
2267
|
+
trace: continuationRunTrace.runTrace
|
|
2268
|
+
}));
|
|
2269
|
+
if (recoveryEvents.length > 0) recoveryEvents.push(yield* events.recoveryCompleted({
|
|
2270
|
+
trigger: "runtime-restart",
|
|
2271
|
+
...plan.continuation === void 0 || continuationRunId === void 0 ? {} : { continuation: {
|
|
2272
|
+
commandId: plan.continuation.command.commandId,
|
|
2273
|
+
interruptedRunId: plan.continuation.run.runId,
|
|
2274
|
+
replacementRunId: continuationRunId
|
|
2275
|
+
} }
|
|
2276
|
+
}));
|
|
2277
|
+
const committed = recoveryEvents.length === 0 ? [] : yield* appendDurableBatch(recoveryEvents);
|
|
2278
|
+
const nextPlan = planSessionRecovery(yield* currentReduced());
|
|
2279
|
+
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"));
|
|
2280
|
+
return {
|
|
2281
|
+
committed,
|
|
2282
|
+
continuation: plan.continuation === void 0 || continuationRunId === void 0 || continuationRunTrace === void 0 ? void 0 : {
|
|
2283
|
+
command: plan.continuation.command,
|
|
2284
|
+
runId: continuationRunId,
|
|
2285
|
+
inputMessageIds: plan.continuation.inputMessageIds,
|
|
2286
|
+
runScope: continuationRunTrace.runScope,
|
|
2287
|
+
runSpan: continuationRunTrace.runSpan
|
|
2288
|
+
}
|
|
2289
|
+
};
|
|
2290
|
+
});
|
|
2291
|
+
return continuationRunTrace === void 0 ? yield* completeRecovery : yield* closeRunTraceOnFailure(continuationRunTrace, completeRecovery);
|
|
2292
|
+
});
|
|
2293
|
+
/** Launch the turn for a replacement run already scheduled atomically by startup recovery. */
|
|
2294
|
+
const resumeRecoveredCommand = Effect.fnUntraced(function* (continuation, input) {
|
|
2295
|
+
const [commandStarted] = yield* store.loadCommittedEventsBySeq([continuation.command.startedSeq]);
|
|
2296
|
+
if (commandStarted?.event.type !== "CommandStarted") return yield* Effect.die(/* @__PURE__ */ new Error(`Recovered command ${continuation.command.commandId} is missing its CommandStarted event`));
|
|
2297
|
+
const promptState = yield* currentData();
|
|
2298
|
+
const pendingInputs = continuation.inputMessageIds.flatMap((messageId) => {
|
|
2299
|
+
const message = promptState.reduced.messages.get(messageId);
|
|
2300
|
+
return (message?._tag === "User" || message?._tag === "Steering") && message.consumedSeq === void 0 && message.cancelledSeq === void 0 ? [message] : [];
|
|
2301
|
+
});
|
|
2302
|
+
yield* startTurn({
|
|
2303
|
+
commandId: continuation.command.commandId,
|
|
2304
|
+
commandStarted,
|
|
2305
|
+
runId: continuation.runId,
|
|
2306
|
+
modelSelection: input.modelSelection,
|
|
2307
|
+
...input.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: input.maxToolCallsPerRun },
|
|
2308
|
+
promptInput: {
|
|
2309
|
+
sessionId: sessionContext.sessionId,
|
|
2310
|
+
state: promptState.reduced,
|
|
2311
|
+
reducerStates: promptState.reducerStates,
|
|
2312
|
+
context: yield* contextProjectionFor(promptState.reduced),
|
|
2313
|
+
selectedUserMessages: pendingInputs.map((message) => ({
|
|
2314
|
+
commandId: message.commandId,
|
|
2315
|
+
content: message.content,
|
|
2316
|
+
messageId: message.messageId
|
|
2317
|
+
}))
|
|
2318
|
+
},
|
|
2319
|
+
runScope: continuation.runScope,
|
|
2320
|
+
runSpan: continuation.runSpan
|
|
2321
|
+
});
|
|
2322
|
+
});
|
|
2323
|
+
const dieLiveInvariantViolation = (reduced, active) => Effect.gen(function* () {
|
|
2324
|
+
const recoverable = classifyRecoverableWork(reduced);
|
|
2325
|
+
const message = "SessionState live invariant violated: durable replay has active work but no in-memory execution owner.";
|
|
2326
|
+
yield* Effect.logFatal(message, {
|
|
2327
|
+
"eda.command.id": active.commandId,
|
|
2328
|
+
"eda.recovery.active_inferences": recoverable.activeInferences.length,
|
|
2329
|
+
"eda.recovery.active_runs": recoverable.activeRuns.length,
|
|
2330
|
+
"eda.recovery.active_turns": recoverable.activeTurns.length,
|
|
2331
|
+
"eda.recovery.open_tool_calls": recoverable.openToolCalls.length,
|
|
2332
|
+
"eda.recovery.pending_stop_requests": recoverable.pendingStopRequests.length,
|
|
2333
|
+
...active.runId === void 0 ? {} : { "eda.run.id": active.runId }
|
|
2334
|
+
});
|
|
2335
|
+
yield* Ref.set(fatalInvariantViolation, message);
|
|
2336
|
+
return yield* Effect.die(message);
|
|
2337
|
+
});
|
|
2338
|
+
const steerActiveCommand = Effect.fn(function* (command, runId) {
|
|
2339
|
+
yield* annotateEdaSpan({
|
|
2340
|
+
"eda.command.id": command.commandId,
|
|
2341
|
+
"eda.run.id": runId
|
|
2342
|
+
});
|
|
2343
|
+
if (command.command._tag !== "SubmitMessage") return yield* Effect.die(/* @__PURE__ */ new Error("DispatchSteerCommand must contain SubmitMessage"));
|
|
2344
|
+
const commandId = command.commandId;
|
|
2345
|
+
return (yield* startedBoundaryGuard({
|
|
2346
|
+
start: events.commandStarted({ commandId }),
|
|
2347
|
+
body: (started) => Effect.gen(function* () {
|
|
2348
|
+
const committed = yield* appendDurableBatch([yield* events.commandCompleted({ commandId })]);
|
|
2349
|
+
return {
|
|
2350
|
+
started,
|
|
2351
|
+
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
2352
|
+
};
|
|
2353
|
+
}),
|
|
2354
|
+
onFailure: (error) => events.commandFailed({
|
|
2355
|
+
commandId,
|
|
2356
|
+
error
|
|
2357
|
+
}),
|
|
2358
|
+
onInterrupt: events.commandCancelled({
|
|
2359
|
+
commandId,
|
|
2360
|
+
reason: "interrupted"
|
|
2361
|
+
})
|
|
2362
|
+
})).value;
|
|
2363
|
+
});
|
|
2364
|
+
const failControlCommand = (commandId, code, message) => Effect.gen(function* () {
|
|
2365
|
+
const committed = yield* appendDurable(yield* events.commandFailed({
|
|
2366
|
+
commandId,
|
|
2367
|
+
error: FailurePayload.make({
|
|
2368
|
+
code,
|
|
2369
|
+
message
|
|
2370
|
+
})
|
|
2371
|
+
}));
|
|
2372
|
+
return SessionCommandFailed.make({ committed });
|
|
2373
|
+
});
|
|
2374
|
+
const cancelPendingMessage = Effect.fn(function* (command) {
|
|
2375
|
+
if (command.command._tag !== "CancelPendingMessage") return yield* Effect.die(/* @__PURE__ */ new Error("CancelPendingMessage dispatch requires matching command"));
|
|
2376
|
+
const cancel = command.command;
|
|
2377
|
+
const controlCommandId = command.commandId;
|
|
2378
|
+
return (yield* startedBoundaryGuard({
|
|
2379
|
+
start: events.commandStarted({ commandId: controlCommandId }),
|
|
2380
|
+
body: (started) => Effect.gen(function* () {
|
|
2381
|
+
const current = yield* currentReduced();
|
|
2382
|
+
const target = current.messages.get(cancel.messageId);
|
|
2383
|
+
if (target?._tag !== "User" && target?._tag !== "Steering" || target._tag === "User" && target.disposition === void 0 || target.consumedSeq !== void 0 || target.cancelledSeq !== void 0) return {
|
|
2384
|
+
started,
|
|
2385
|
+
outcome: yield* failControlCommand(controlCommandId, "message_not_pending", "Message is no longer pending")
|
|
2386
|
+
};
|
|
2387
|
+
const cancelled = yield* events.userMessageCancelled({
|
|
2388
|
+
commandId: controlCommandId,
|
|
2389
|
+
messageId: target.messageId,
|
|
2390
|
+
reason: cancel.reason
|
|
2391
|
+
});
|
|
2392
|
+
const origin = current.commands.get(target.commandId);
|
|
2393
|
+
const originCancelled = origin !== void 0 && origin.terminal === void 0 && origin.startedSeq === void 0 ? [yield* events.commandCancelled({
|
|
2394
|
+
commandId: target.commandId,
|
|
2395
|
+
reason: "pending message cancelled"
|
|
2396
|
+
})] : [];
|
|
2397
|
+
const completed = yield* events.commandCompleted({ commandId: controlCommandId });
|
|
2398
|
+
const committed = yield* appendDurableBatch([
|
|
2399
|
+
cancelled,
|
|
2400
|
+
...originCancelled,
|
|
2401
|
+
completed
|
|
2402
|
+
]);
|
|
2403
|
+
return {
|
|
2404
|
+
started,
|
|
2405
|
+
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
2406
|
+
};
|
|
2407
|
+
}),
|
|
2408
|
+
onFailure: (error) => events.commandFailed({
|
|
2409
|
+
commandId: controlCommandId,
|
|
2410
|
+
error
|
|
2411
|
+
}),
|
|
2412
|
+
onInterrupt: events.commandCancelled({
|
|
2413
|
+
commandId: controlCommandId,
|
|
2414
|
+
reason: "interrupted"
|
|
2415
|
+
})
|
|
2416
|
+
})).value;
|
|
2417
|
+
});
|
|
2418
|
+
const promotePendingMessage = Effect.fn(function* (command) {
|
|
2419
|
+
if (command.command._tag !== "PromotePendingMessage") return yield* Effect.die(/* @__PURE__ */ new Error("PromotePendingMessage dispatch requires matching command"));
|
|
2420
|
+
const promotion = command.command;
|
|
2421
|
+
const controlCommandId = command.commandId;
|
|
2422
|
+
return (yield* startedBoundaryGuard({
|
|
2423
|
+
start: events.commandStarted({ commandId: controlCommandId }),
|
|
2424
|
+
body: (started) => Effect.gen(function* () {
|
|
2425
|
+
const target = (yield* currentReduced()).messages.get(promotion.messageId);
|
|
2426
|
+
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 {
|
|
2427
|
+
started,
|
|
2428
|
+
outcome: yield* failControlCommand(controlCommandId, "message_not_queue", "Message is no longer a pending queue message")
|
|
2429
|
+
};
|
|
2430
|
+
const committed = yield* appendDurableBatch([yield* events.userMessagePromoted({
|
|
2431
|
+
commandId: controlCommandId,
|
|
2432
|
+
messageId: target.messageId,
|
|
2433
|
+
from: "queue",
|
|
2434
|
+
to: "steer"
|
|
2435
|
+
}), yield* events.commandCompleted({ commandId: controlCommandId })]);
|
|
2436
|
+
return {
|
|
2437
|
+
started,
|
|
2438
|
+
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
2439
|
+
};
|
|
2440
|
+
}),
|
|
2441
|
+
onFailure: (error) => events.commandFailed({
|
|
2442
|
+
commandId: controlCommandId,
|
|
2443
|
+
error
|
|
2444
|
+
}),
|
|
2445
|
+
onInterrupt: events.commandCancelled({
|
|
2446
|
+
commandId: controlCommandId,
|
|
2447
|
+
reason: "interrupted"
|
|
2448
|
+
})
|
|
2449
|
+
})).value;
|
|
2450
|
+
});
|
|
2451
|
+
const stopActiveCommand = Effect.fn(function* (command, active) {
|
|
2452
|
+
const stopCommandId = command.commandId;
|
|
2453
|
+
yield* annotateEdaSpan({
|
|
2454
|
+
"eda.command.id": active.commandId,
|
|
2455
|
+
"eda.control_command.id": stopCommandId,
|
|
2456
|
+
"eda.run.id": active.runId,
|
|
2457
|
+
"eda.turn.id": active.turnId
|
|
2458
|
+
});
|
|
2459
|
+
return (yield* startedBoundaryGuard({
|
|
2460
|
+
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2461
|
+
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2462
|
+
const requested = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
|
|
2463
|
+
yield* appendDurable(yield* events.stopTurnRequested({
|
|
2464
|
+
commandId: stopCommandId,
|
|
2465
|
+
...requested === void 0 ? {} : {
|
|
2466
|
+
runId: requested.runId,
|
|
2467
|
+
turnId: requested.turnId
|
|
2468
|
+
}
|
|
2469
|
+
}));
|
|
2470
|
+
yield* Scope.close(active.turnScope, Exit.interrupt());
|
|
2471
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2472
|
+
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2473
|
+
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2474
|
+
const applied = activeTurnIdentityForCommand(yield* currentReduced(), active.commandId);
|
|
2475
|
+
const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
|
|
2476
|
+
commandId: stopCommandId,
|
|
2477
|
+
runId: active.runId,
|
|
2478
|
+
turnId: active.turnId,
|
|
2479
|
+
...applied?.turnId === active.turnId && applied.inferenceId !== void 0 ? { inferenceId: applied.inferenceId } : {}
|
|
2480
|
+
}), yield* events.commandCompleted({ commandId: stopCommandId })]);
|
|
2481
|
+
return {
|
|
2482
|
+
started,
|
|
2483
|
+
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
2484
|
+
};
|
|
2485
|
+
})),
|
|
2486
|
+
onFailure: (error) => events.commandFailed({
|
|
2487
|
+
commandId: stopCommandId,
|
|
2488
|
+
error
|
|
2489
|
+
}),
|
|
2490
|
+
onInterrupt: events.commandCancelled({
|
|
2491
|
+
commandId: stopCommandId,
|
|
2492
|
+
reason: "interrupted"
|
|
2493
|
+
})
|
|
2494
|
+
})).value;
|
|
2495
|
+
});
|
|
2496
|
+
const stopCompletedCommand = Effect.fn(function* (command, active) {
|
|
2497
|
+
const stopCommandId = command.commandId;
|
|
2498
|
+
yield* annotateEdaSpan({
|
|
2499
|
+
"eda.command.id": active.commandId,
|
|
2500
|
+
"eda.control_command.id": stopCommandId,
|
|
2501
|
+
"eda.run.id": active.runId,
|
|
2502
|
+
"eda.turn.id": active.turnId
|
|
2503
|
+
});
|
|
2504
|
+
return (yield* startedBoundaryGuard({
|
|
2505
|
+
start: events.commandStarted({ commandId: stopCommandId }),
|
|
2506
|
+
body: (started) => Effect.uninterruptible(Effect.gen(function* () {
|
|
2507
|
+
yield* appendDurable(yield* events.stopTurnRequested({
|
|
2508
|
+
commandId: stopCommandId,
|
|
2509
|
+
runId: active.runId,
|
|
2510
|
+
turnId: active.turnId
|
|
2511
|
+
}));
|
|
2512
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2513
|
+
yield* appendUserInterruption(active, stopCommandId, "interrupted");
|
|
2514
|
+
yield* Scope.close(active.runScope, Exit.interrupt());
|
|
2515
|
+
const committed = yield* appendDurableBatch([yield* events.stopTurnApplied({
|
|
2516
|
+
commandId: stopCommandId,
|
|
2517
|
+
runId: active.runId,
|
|
2518
|
+
turnId: active.turnId
|
|
2519
|
+
}), yield* events.commandCompleted({ commandId: stopCommandId })]);
|
|
2520
|
+
return {
|
|
2521
|
+
started,
|
|
2522
|
+
outcome: SessionCommandCompleted.make({ committed: committed.at(-1) })
|
|
2523
|
+
};
|
|
2524
|
+
})),
|
|
2525
|
+
onFailure: (error) => events.commandFailed({
|
|
2526
|
+
commandId: stopCommandId,
|
|
2527
|
+
error
|
|
2528
|
+
}),
|
|
2529
|
+
onInterrupt: events.commandCancelled({
|
|
2530
|
+
commandId: stopCommandId,
|
|
2531
|
+
reason: "interrupted"
|
|
2532
|
+
})
|
|
2533
|
+
})).value;
|
|
2534
|
+
});
|
|
2535
|
+
const continueOrFinishRunAfterTurn = Effect.fnUntraced(function* (active, turn) {
|
|
2536
|
+
switch (turn.outcome._tag) {
|
|
2537
|
+
case "TurnRunFailed": {
|
|
2538
|
+
const outcome = yield* failRunAndCommand(active.commandId, active.runId, turn);
|
|
2539
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2540
|
+
yield* maybeCompactAtBoundary();
|
|
2541
|
+
yield* Scope.close(active.runScope, Exit.fail(/* @__PURE__ */ new Error("agent turn failed")));
|
|
2542
|
+
return {
|
|
2543
|
+
started: active.commandStarted,
|
|
2544
|
+
outcome
|
|
2545
|
+
};
|
|
2546
|
+
}
|
|
2547
|
+
case "TurnRunCompleted": {
|
|
2548
|
+
const current = yield* currentReduced();
|
|
2549
|
+
const continuation = decideRunContinuation({
|
|
2550
|
+
runId: active.runId,
|
|
2551
|
+
turnId: active.turnId,
|
|
2552
|
+
state: current,
|
|
2553
|
+
maxToolRejectionCorrections
|
|
2554
|
+
});
|
|
2555
|
+
switch (continuation._tag) {
|
|
2556
|
+
case "ContinueWithSteering": return yield* startTurn({
|
|
2557
|
+
commandId: active.commandId,
|
|
2558
|
+
commandStarted: active.commandStarted,
|
|
2559
|
+
runId: active.runId,
|
|
2560
|
+
modelSelection: active.modelSelection,
|
|
2561
|
+
...active.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: active.maxToolCallsPerRun },
|
|
2562
|
+
promptInput: {
|
|
2563
|
+
sessionId: sessionContext.sessionId,
|
|
2564
|
+
state: current,
|
|
2565
|
+
reducerStates: (yield* currentData()).reducerStates,
|
|
2566
|
+
context: yield* contextProjectionFor(current),
|
|
2567
|
+
selectedUserMessages: continuation.steerings.map((steering) => ({
|
|
2568
|
+
commandId: steering.commandId,
|
|
2569
|
+
content: steering.content,
|
|
2570
|
+
messageId: steering.messageId
|
|
2571
|
+
}))
|
|
2572
|
+
},
|
|
2573
|
+
runScope: active.runScope,
|
|
2574
|
+
runSpan: active.runSpan
|
|
2575
|
+
});
|
|
2576
|
+
case "ContinueWithToolFeedback": return yield* startTurn({
|
|
2577
|
+
commandId: active.commandId,
|
|
2578
|
+
commandStarted: active.commandStarted,
|
|
2579
|
+
runId: active.runId,
|
|
2580
|
+
modelSelection: active.modelSelection,
|
|
2581
|
+
...active.maxToolCallsPerRun === void 0 ? {} : { maxToolCallsPerRun: active.maxToolCallsPerRun },
|
|
2582
|
+
promptInput: {
|
|
2583
|
+
sessionId: sessionContext.sessionId,
|
|
2584
|
+
state: current,
|
|
2585
|
+
reducerStates: (yield* currentData()).reducerStates,
|
|
2586
|
+
context: yield* contextProjectionFor(current),
|
|
2587
|
+
selectedUserMessages: []
|
|
2588
|
+
},
|
|
2589
|
+
runScope: active.runScope,
|
|
2590
|
+
runSpan: active.runSpan
|
|
2591
|
+
});
|
|
2592
|
+
case "FailRun": {
|
|
2593
|
+
const outcome = yield* failRunAndCommandWithError(active.commandId, active.runId, continuation.error);
|
|
2594
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2595
|
+
yield* maybeCompactAtBoundary();
|
|
2596
|
+
yield* Scope.close(active.runScope, Exit.fail(new Error(continuation.error.message)));
|
|
2597
|
+
return {
|
|
2598
|
+
started: active.commandStarted,
|
|
2599
|
+
outcome
|
|
2600
|
+
};
|
|
2601
|
+
}
|
|
2602
|
+
case "CompleteRun": break;
|
|
2603
|
+
default: return yield* Effect.die(assertNeverError(continuation, "run continuation decision"));
|
|
2604
|
+
}
|
|
2605
|
+
yield* maybeCompactAtBoundary();
|
|
2606
|
+
const outcome = yield* completeRunAndCommand(active.commandId, active.runId);
|
|
2607
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2608
|
+
yield* Scope.close(active.runScope, Exit.void);
|
|
2609
|
+
return {
|
|
2610
|
+
started: active.commandStarted,
|
|
2611
|
+
outcome
|
|
2612
|
+
};
|
|
2613
|
+
}
|
|
2614
|
+
default: return yield* Effect.die(assertNeverError(turn.outcome, "turn outcome"));
|
|
2615
|
+
}
|
|
2616
|
+
});
|
|
2617
|
+
const drainOneReadyCommand = Effect.fnUntraced(function* (input) {
|
|
2618
|
+
const execution = yield* inspectExecutionState();
|
|
2619
|
+
const current = yield* currentReduced();
|
|
2620
|
+
if (execution?._tag === "FailedTurn") return execution.result;
|
|
2621
|
+
if (execution?._tag === "CompletedTurn") {
|
|
2622
|
+
const decision = decideDispatch(current);
|
|
2623
|
+
switch (decision._tag) {
|
|
2624
|
+
case "DispatchCancelPendingMessage": return yield* cancelPendingMessage(decision.command);
|
|
2625
|
+
case "DispatchPromotePendingMessage": return yield* promotePendingMessage(decision.command);
|
|
2626
|
+
case "DispatchStopCommand": {
|
|
2627
|
+
const result = yield* stopCompletedCommand(decision.command, execution.active);
|
|
2628
|
+
yield* maybeCompactAtBoundary();
|
|
2629
|
+
return result;
|
|
2630
|
+
}
|
|
2631
|
+
case "DispatchSteerCommand": {
|
|
2632
|
+
const result = yield* steerActiveCommand(decision.command, decision.active.runId);
|
|
2633
|
+
yield* maybeCompactAtBoundary();
|
|
2634
|
+
return result;
|
|
2635
|
+
}
|
|
2636
|
+
case "DispatchInterruptCommand":
|
|
2637
|
+
yield* appendUserInterruption(execution.active, decision.command.commandId, "interrupted");
|
|
2638
|
+
yield* Scope.close(execution.active.runScope, Exit.interrupt());
|
|
2639
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2640
|
+
yield* maybeCompactAtBoundary();
|
|
2641
|
+
return yield* startSubmitCommand(decision.command, input);
|
|
2642
|
+
default: return yield* continueOrFinishRunAfterTurn(execution.active, execution.turn);
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
if (execution?._tag === "RunningTurn") {
|
|
2646
|
+
const decision = decideDispatch(current);
|
|
2647
|
+
switch (decision._tag) {
|
|
2648
|
+
case "DispatchCancelPendingMessage": return yield* cancelPendingMessage(decision.command);
|
|
2649
|
+
case "DispatchPromotePendingMessage": return yield* promotePendingMessage(decision.command);
|
|
2650
|
+
case "DispatchStopCommand": {
|
|
2651
|
+
const result = yield* stopActiveCommand(decision.command, execution.active);
|
|
2652
|
+
yield* maybeCompactAtBoundary();
|
|
2653
|
+
return result;
|
|
2654
|
+
}
|
|
2655
|
+
case "DispatchSteerCommand": return yield* steerActiveCommand(decision.command, decision.active.runId);
|
|
2656
|
+
case "DispatchInterruptCommand":
|
|
2657
|
+
yield* Scope.close(execution.active.turnScope, Exit.interrupt());
|
|
2658
|
+
yield* Ref.set(executionState, { _tag: "Idle" });
|
|
2659
|
+
yield* appendUserInterruption(execution.active, decision.command.commandId, "interrupted");
|
|
2660
|
+
yield* Scope.close(execution.active.runScope, Exit.interrupt());
|
|
2661
|
+
yield* maybeCompactAtBoundary();
|
|
2662
|
+
return yield* startSubmitCommand(decision.command, input);
|
|
2663
|
+
default: return SessionNoRunnableCommand.make({
|
|
2664
|
+
reason: "active-command",
|
|
2665
|
+
active: DispatchActiveCommand.make({
|
|
2666
|
+
commandId: execution.active.commandId,
|
|
2667
|
+
runId: execution.active.runId
|
|
2668
|
+
})
|
|
2669
|
+
});
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
const decision = decideDispatch(current);
|
|
2673
|
+
switch (decision._tag) {
|
|
2674
|
+
case "DispatchBlockedByActiveCommand":
|
|
2675
|
+
case "DispatchStopCommand":
|
|
2676
|
+
case "DispatchSteerCommand":
|
|
2677
|
+
case "DispatchInterruptCommand": return yield* dieLiveInvariantViolation(current, decision.active);
|
|
2678
|
+
case "DispatchCancelPendingMessage": return yield* cancelPendingMessage(decision.command);
|
|
2679
|
+
case "DispatchPromotePendingMessage": return yield* promotePendingMessage(decision.command);
|
|
2680
|
+
case "DispatchNoPendingCommand": return SessionNoRunnableCommand.make({ reason: "no-pending-command" });
|
|
2681
|
+
case "DispatchInvariantViolation": return yield* Effect.die(/* @__PURE__ */ new Error(`SessionState live invariant violated: pending messages have no execution owner (${decision.messageIds.join(", ")})`));
|
|
2682
|
+
case "DispatchStartCommand": switch (decision.command.command._tag) {
|
|
2683
|
+
case "StopTurn": return yield* processInactiveStopCommand(decision.command);
|
|
2684
|
+
case "ResumePendingMessages": return yield* startResumePendingMessages(decision.command, input);
|
|
2685
|
+
case "SubmitMessage": return yield* startSubmitCommand(decision.command, input);
|
|
2686
|
+
case "CancelPendingMessage": return yield* cancelPendingMessage(decision.command);
|
|
2687
|
+
case "PromotePendingMessage": return yield* promotePendingMessage(decision.command);
|
|
2688
|
+
default: return yield* Effect.die(assertNeverError(decision.command.command, "start dispatch command"));
|
|
2689
|
+
}
|
|
2690
|
+
default: return yield* Effect.die(assertNeverError(decision, "dispatch decision"));
|
|
2691
|
+
}
|
|
2692
|
+
});
|
|
2693
|
+
const drainReadyWorkPostRecovery = Effect.fnUntraced(function* (input) {
|
|
2694
|
+
yield* annotateEdaSpan({
|
|
2695
|
+
"eda.model.provider": input.modelSelection.provider,
|
|
2696
|
+
"eda.model.id": input.modelSelection.modelId
|
|
2697
|
+
});
|
|
2698
|
+
yield* failIfFatal;
|
|
2699
|
+
const processed = [];
|
|
2700
|
+
while (true) {
|
|
2701
|
+
const result = yield* withFatalRecording(drainOneReadyCommand(input));
|
|
2702
|
+
if (isSessionNoRunnableCommand(result)) {
|
|
2703
|
+
yield* annotateEdaSpan({
|
|
2704
|
+
"eda.command.processed_count": processed.length,
|
|
2705
|
+
"eda.dispatch.stop_reason": result.reason
|
|
2706
|
+
});
|
|
2707
|
+
return {
|
|
2708
|
+
_tag: "SessionDrainResult",
|
|
2709
|
+
processed,
|
|
2710
|
+
stop: result
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
processed.push(result);
|
|
2714
|
+
}
|
|
2715
|
+
});
|
|
2716
|
+
const runStartupRecoveryPass = Effect.fnUntraced(function* (input) {
|
|
2717
|
+
yield* annotateEdaSpan({
|
|
2718
|
+
"eda.recovery.reason": startupRecoveryReason,
|
|
2719
|
+
"eda.model.provider": input.modelSelection.provider,
|
|
2720
|
+
"eda.model.id": input.modelSelection.modelId
|
|
2721
|
+
});
|
|
2722
|
+
yield* failIfFatal;
|
|
2723
|
+
const recovery = yield* withFatalRecording(recoverSession(yield* currentReduced(), startupRecoveryReason, input));
|
|
2724
|
+
yield* requestStartupRecoveryCheckpointIfNeeded();
|
|
2725
|
+
if (recovery.continuation !== void 0) yield* closeRunTraceOnFailure(recovery.continuation, withFatalRecording(resumeRecoveredCommand(recovery.continuation, input)));
|
|
2726
|
+
});
|
|
2727
|
+
const drainReadyWork = (input) => drainReadyWorkPostRecovery(input);
|
|
2728
|
+
const drainAndLog = (input) => keepAlive.withActiveWork("session-control", drainReadyWorkPostRecovery(input).pipe(Effect.asVoid, Effect.catchCause((cause) => Effect.gen(function* () {
|
|
2729
|
+
yield* markFatalIfDurable(cause);
|
|
2730
|
+
yield* Effect.logError("session control drain pass failed", { cause: Cause.pretty(cause) });
|
|
2731
|
+
return yield* Effect.failCause(cause);
|
|
2732
|
+
}))));
|
|
2733
|
+
const waitForIngressSignal = () => Stream.fromQueue(ingressSignals).pipe(Stream.take(1), Stream.runDrain);
|
|
2734
|
+
const waitForNextSignal = () => Effect.gen(function* () {
|
|
2735
|
+
const current = yield* Ref.get(executionState);
|
|
2736
|
+
if (current._tag === "Running") {
|
|
2737
|
+
yield* Effect.raceFirst(waitForIngressSignal(), Fiber.await(current.fiber).pipe(Effect.asVoid));
|
|
2738
|
+
return;
|
|
2739
|
+
}
|
|
2740
|
+
if (current._tag === "Completed") return;
|
|
2741
|
+
yield* waitForIngressSignal();
|
|
2742
|
+
});
|
|
2743
|
+
const annotateRunInput = (input) => annotateEdaSpan({
|
|
2744
|
+
"eda.model.provider": input.modelSelection.provider,
|
|
2745
|
+
"eda.model.id": input.modelSelection.modelId
|
|
2746
|
+
});
|
|
2747
|
+
const runStartupRecovery = Effect.fnUntraced(function* (input) {
|
|
2748
|
+
yield* annotateRunInput(input);
|
|
2749
|
+
yield* initialize(input);
|
|
2750
|
+
yield* keepAlive.withActiveWork("session-recovery", runStartupRecoveryPass(input));
|
|
2751
|
+
});
|
|
2752
|
+
const runLiveControlLoop = Effect.fn(function* (input) {
|
|
2753
|
+
yield* annotateRunInput(input);
|
|
2754
|
+
while (true) {
|
|
2755
|
+
yield* drainAndLog(input);
|
|
2756
|
+
yield* waitForNextSignal();
|
|
2757
|
+
}
|
|
2758
|
+
});
|
|
2759
|
+
const start = Effect.fn(function* (input) {
|
|
2760
|
+
yield* runStartupRecovery(input);
|
|
2761
|
+
yield* runLiveControlLoop(input).pipe(Effect.forkIn(runtimeScope));
|
|
2762
|
+
});
|
|
2763
|
+
yield* sinkRegistry.startSinkRunners({
|
|
2764
|
+
appendDurableBatch,
|
|
2765
|
+
initialHead: (yield* Ref.get(state)).reduced.lastSeq,
|
|
2766
|
+
publishEphemeral: publishEphemeralCore,
|
|
2767
|
+
scope: runtimeScope
|
|
2768
|
+
});
|
|
2769
|
+
return sessionApi;
|
|
2770
|
+
});
|
|
2771
|
+
const hydrateReducedStateCheckpoint = (store, checkpoint) => Effect.gen(function* () {
|
|
2772
|
+
const referencedEvents = yield* store.loadCommittedEventsBySeq(reducedStateCheckpointEventSeqs(checkpoint.payload));
|
|
2773
|
+
const state = yield* Effect.try({
|
|
2774
|
+
try: () => decodeReducedStateCheckpoint(checkpoint.payload, referencedEvents),
|
|
2775
|
+
catch: (error) => new EDASessionStoreError({ message: `hydrating framework reducer checkpoint: ${String(error)}` })
|
|
2776
|
+
});
|
|
2777
|
+
if (state.lastSeq !== checkpoint.throughSeq) return yield* new EDASessionStoreError({ message: `hydrating framework reducer checkpoint: payload lastSeq ${state.lastSeq} does not match row throughSeq ${checkpoint.throughSeq}` });
|
|
2778
|
+
return state;
|
|
2779
|
+
});
|
|
2780
|
+
const hydrateFrameworkReducedState = (store) => Effect.gen(function* () {
|
|
2781
|
+
const checkpoint = yield* store.loadReducerCheckpoint(frameworkReducedStateReducerName);
|
|
2782
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== 4 ? initialReducedState : yield* hydrateReducedStateCheckpoint(store, checkpoint);
|
|
2783
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== 4 ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2784
|
+
return {
|
|
2785
|
+
state: foldReducedState(checkpointState, yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)))),
|
|
2786
|
+
checkpointSeq
|
|
2787
|
+
};
|
|
2788
|
+
});
|
|
2789
|
+
const hydrateAppReducerStates = (store, reducers) => Effect.gen(function* () {
|
|
2790
|
+
const entries = yield* Effect.forEach(reducers, (reducer) => Effect.gen(function* () {
|
|
2791
|
+
const checkpoint = yield* store.loadReducerCheckpoint(reducer.name);
|
|
2792
|
+
const schemaVersion = reducerSchemaVersion(reducer);
|
|
2793
|
+
const checkpointState = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? reducer.initial : decodeReducerState(reducer, checkpoint.payload);
|
|
2794
|
+
const checkpointSeq = checkpoint === void 0 || checkpoint.schemaVersion !== schemaVersion ? SequenceNumber.make(0) : checkpoint.throughSeq;
|
|
2795
|
+
const tail = yield* store.eventsAfter(checkpointSeq).pipe(Stream.runCollect, Effect.map((events) => Array.from(events)));
|
|
2796
|
+
return [
|
|
2797
|
+
reducer.name,
|
|
2798
|
+
tail.reduce(reducer.reduce, checkpointState),
|
|
2799
|
+
checkpointSeq
|
|
2800
|
+
];
|
|
2801
|
+
}));
|
|
2802
|
+
const checkpointSeq = entries.reduce((min, [, , seq]) => min === void 0 || seq < min ? seq : min, void 0);
|
|
2803
|
+
return {
|
|
2804
|
+
states: new Map(entries.map(([name, state]) => [name, state])),
|
|
2805
|
+
...checkpointSeq === void 0 ? {} : { checkpointSeq }
|
|
2806
|
+
};
|
|
2807
|
+
});
|
|
2808
|
+
const isEDACommand = (input) => "_tag" in input;
|
|
2809
|
+
const commandWithId = (command, commandId) => {
|
|
2810
|
+
switch (command._tag) {
|
|
2811
|
+
case "SubmitMessage": return new SubmitMessageCommand({
|
|
2812
|
+
commandId,
|
|
2813
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey },
|
|
2814
|
+
disposition: command.disposition,
|
|
2815
|
+
content: command.content,
|
|
2816
|
+
...command.expectedPausedMessageIdsToCancel === void 0 ? {} : { expectedPausedMessageIdsToCancel: command.expectedPausedMessageIdsToCancel }
|
|
2817
|
+
});
|
|
2818
|
+
case "StopTurn": return new StopTurnCommand({
|
|
2819
|
+
commandId,
|
|
2820
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey }
|
|
2821
|
+
});
|
|
2822
|
+
case "CancelPendingMessage": return new CancelPendingMessageCommand({
|
|
2823
|
+
commandId,
|
|
2824
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey },
|
|
2825
|
+
messageId: command.messageId,
|
|
2826
|
+
reason: command.reason
|
|
2827
|
+
});
|
|
2828
|
+
case "PromotePendingMessage": return new PromotePendingMessageCommand({
|
|
2829
|
+
commandId,
|
|
2830
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey },
|
|
2831
|
+
messageId: command.messageId
|
|
2832
|
+
});
|
|
2833
|
+
case "ResumePendingMessages": return new ResumePendingMessagesCommand({
|
|
2834
|
+
commandId,
|
|
2835
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey },
|
|
2836
|
+
messageIds: command.messageIds
|
|
2837
|
+
});
|
|
2838
|
+
default: throw assertNeverError(command, "EDA command");
|
|
2839
|
+
}
|
|
2840
|
+
};
|
|
2841
|
+
const rememberPreparedCommand = (event, preparedByIdempotencyKey, preparedByCommandId) => {
|
|
2842
|
+
if (event.type !== commandAdmittedEventType) return;
|
|
2843
|
+
const command = event.payload.command;
|
|
2844
|
+
if (command?.idempotencyKey !== void 0) preparedByIdempotencyKey.set(command.idempotencyKey, event);
|
|
2845
|
+
if (command?.commandId !== void 0) preparedByCommandId.set(command.commandId, event);
|
|
2846
|
+
};
|
|
2847
|
+
const sameMessageIdSet = (left, right) => {
|
|
2848
|
+
if (left.length !== right.length) return false;
|
|
2849
|
+
const rightIds = new Set(right);
|
|
2850
|
+
return left.every((messageId) => rightIds.has(messageId));
|
|
2851
|
+
};
|
|
2852
|
+
const remainingToolCallsForRun = (state, runId, maxToolCallsPerRun) => {
|
|
2853
|
+
const used = Array.from(state.toolCalls.values()).filter((tool) => tool.decision?._tag === "Created" && tool.decision.runId === runId && !tool.decision.providerExecuted).length;
|
|
2854
|
+
return NonNegativeInt.make(Math.max(0, maxToolCallsPerRun - used));
|
|
2855
|
+
};
|
|
2856
|
+
const remainingToolRejectionCorrectionsForRun = (state, runId, limit) => {
|
|
2857
|
+
const rejectedTurnIds = /* @__PURE__ */ new Set();
|
|
2858
|
+
for (const tool of state.toolCalls.values()) if (tool.decision?._tag === "Rejected" && tool.decision.runId === runId) rejectedTurnIds.add(tool.decision.turnId);
|
|
2859
|
+
return NonNegativeInt.make(Math.max(0, limit - rejectedTurnIds.size));
|
|
2860
|
+
};
|
|
2861
|
+
const requireTurnFailed = (committed) => isTurnFailed(committed) ? Effect.succeed(committed) : Effect.die(/* @__PURE__ */ new Error("TurnRunFailed did not include TurnFailed"));
|
|
2862
|
+
const isTurnFailed = (committed) => committed.event.type === turnFailedEventType;
|
|
2863
|
+
const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag === "SessionNoRunnableCommand";
|
|
2864
|
+
//#endregion
|
|
2865
|
+
//#region src/services/session-query.ts
|
|
2866
|
+
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
2867
|
+
var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
|
|
2868
|
+
static Live = Layer.effect(EDASessionQuery, Effect.gen(function* () {
|
|
2869
|
+
const store = yield* EDASessionStore;
|
|
2870
|
+
const liveBus = yield* LiveEventBus;
|
|
2871
|
+
const sessionState = yield* SessionState;
|
|
2872
|
+
const snapshot = Effect.gen(function* () {
|
|
2873
|
+
const data = yield* sessionState.snapshotData();
|
|
2874
|
+
return {
|
|
2875
|
+
state: data.reduced,
|
|
2876
|
+
reducerStates: data.reducerStates,
|
|
2877
|
+
messages: durableMessageTranscript(data.reduced)
|
|
2878
|
+
};
|
|
2879
|
+
});
|
|
2880
|
+
return {
|
|
2881
|
+
snapshot: () => snapshot,
|
|
2882
|
+
messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),
|
|
2883
|
+
eventsAfter: (afterSeq) => Effect.gen(function* () {
|
|
2884
|
+
const live = yield* liveBus.subscribeQueue();
|
|
2885
|
+
const replayHead = (yield* sessionState.snapshot()).lastSeq;
|
|
2886
|
+
const replay = yield* store.eventsAfter(afterSeq).pipe(Stream.filter((entry) => entry.position.seq <= replayHead), Stream.map((entry) => PositionedEvent.make({
|
|
2887
|
+
position: entry.position,
|
|
2888
|
+
event: entry.event
|
|
2889
|
+
})), Stream.runCollect, Effect.map((events) => Array.from(events)));
|
|
2890
|
+
const activeTurnReplay = yield* liveBus.activeTurnReplay();
|
|
2891
|
+
const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter((event) => shouldEmitLiveEvent(event, replayHead));
|
|
2892
|
+
const reconnectPrefix = Array.from(uniquePositionedEvents([
|
|
2893
|
+
...replay,
|
|
2894
|
+
...activeTurnReplay.events,
|
|
2895
|
+
...pendingLive
|
|
2896
|
+
])).sort(comparePositionedEvents);
|
|
2897
|
+
yield* annotateEdaSpan({
|
|
2898
|
+
"eda.seq.after": afterSeq,
|
|
2899
|
+
"eda.seq.head": replayHead,
|
|
2900
|
+
"eda.replay.events": replay.length,
|
|
2901
|
+
"eda.live.active_turn_events": activeTurnReplay.events.length,
|
|
2902
|
+
"eda.live.active_turn_overflowed": activeTurnReplay.overflowed,
|
|
2903
|
+
"eda.live.buffered_events": pendingLive.length
|
|
2904
|
+
});
|
|
2905
|
+
const follow = Stream.fromEffectRepeat(PubSub.take(live)).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));
|
|
2906
|
+
return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));
|
|
2907
|
+
}).pipe(Effect.withSpan("agent.events.follow", { attributes: { "eda.seq.after": afterSeq } }))
|
|
2908
|
+
};
|
|
2909
|
+
}));
|
|
2910
|
+
};
|
|
2911
|
+
const shouldEmitLiveEvent = (event, replayHead) => event.event.durability === "ephemeral" || event.position.seq > replayHead;
|
|
2912
|
+
const comparePositionedEvents = (left, right) => {
|
|
2913
|
+
const seq = left.position.seq - right.position.seq;
|
|
2914
|
+
return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;
|
|
2915
|
+
};
|
|
2916
|
+
const uniquePositionedEvents = (events) => {
|
|
2917
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2918
|
+
const output = [];
|
|
2919
|
+
for (const event of events) {
|
|
2920
|
+
const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;
|
|
2921
|
+
if (seen.has(key)) continue;
|
|
2922
|
+
seen.add(key);
|
|
2923
|
+
output.push(event);
|
|
2924
|
+
}
|
|
2925
|
+
return output;
|
|
2926
|
+
};
|
|
2927
|
+
//#endregion
|
|
2928
|
+
export { ToolExecutor as a, InferenceRunner as i, SessionState as n, TurnRunner as r, EDASessionQuery as t };
|
|
2929
|
+
|
|
2930
|
+
//# sourceMappingURL=session-query-DOc1KanA.js.map
|