effect-durable-agent 0.1.0-alpha.19 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compaction-Bell28K8.js → compaction-GD1cTPTZ.js} +4 -4
- package/dist/compaction-GD1cTPTZ.js.map +1 -0
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.js +1 -1
- package/dist/domain/context-projection.js.map +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/message-transcript.js +1 -1
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/reduced-state-schema.d.ts +1 -1
- package/dist/domain/reduced-state-schema.js +2 -2
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/reduced-state.js +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/{durable-DRY7AcsF.js → durable-CD__3ztN.js} +67 -4
- package/dist/durable-CD__3ztN.js.map +1 -0
- package/dist/{durable-DoG_e4iL.d.ts → durable-CKdCCqhw.d.ts} +54 -1
- package/dist/{event-factory-CKuWhjS4.js → event-factory-VAci3NJb.js} +2 -2
- package/dist/{event-factory-CKuWhjS4.js.map → event-factory-VAci3NJb.js.map} +1 -1
- package/dist/{events-sxIzJY26.d.ts → events-BWuvzVml.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{model-resolver-BHYVHsam.d.ts → model-resolver-BfM5YA6A.d.ts} +4 -4
- package/dist/{reduced-state-DrSHn_47.d.ts → reduced-state-4FSWDdgT.d.ts} +654 -453
- package/dist/{reduced-state-DFIYylAq.js → reduced-state-Vuud6LCM.js} +2 -2
- package/dist/reduced-state-Vuud6LCM.js.map +1 -0
- package/dist/{reduced-state-schema-CPEmuHLY.d.ts → reduced-state-schema-jyZWJ0QS.d.ts} +19 -1
- package/dist/{reducer-registry-C3ZidOI1.d.ts → reducer-registry-BIhncOHH.d.ts} +4 -4
- package/dist/{run-scheduling-wakeup-COUj3r_B.d.ts → run-scheduling-wakeup-BH2pHE0U.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/id-generator.js +1 -1
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/model-resolver.js +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/prompt-projector.js +1 -1
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/run-scheduler.js +1 -1
- package/dist/services/run-scheduler.js.map +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +12 -9
- package/dist/services/runtime-layer.js +6 -6
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +2 -2
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +5 -5
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tool-registry.js +2 -2
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +1 -1
- package/dist/services/tracing.js +1 -1
- package/dist/{session-event-observer-BDwja1jX.d.ts → session-event-observer-BdZltdrK.d.ts} +2 -2
- package/dist/{session-state-BBzzJrDC.js → session-state-BAzdzqV4.js} +17 -12
- package/dist/session-state-BAzdzqV4.js.map +1 -0
- package/dist/{session-store-B_vh581h.d.ts → session-store-BpitF4Wg.d.ts} +3 -3
- package/dist/{sink-checkpoint-store-2SxoNMbI.d.ts → sink-checkpoint-store-C-SY0cG2.d.ts} +2 -2
- package/dist/{sink-registry-ogHu2Sw7.js → sink-registry-BnWfMABI.js} +4 -4
- package/dist/sink-registry-BnWfMABI.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -10
- package/dist/testkit/layers.js +9 -6
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-DDxbmMpY.d.ts → tool-registry-wPsHagF_.d.ts} +5 -5
- package/dist/types/commands.js +1 -1
- package/dist/types/commands.js.map +1 -1
- package/dist/types/events/durable.d.ts +1 -1
- package/dist/types/events/durable.js +1 -1
- package/dist/types/events.d.ts +2 -2
- package/dist/types/events.js +1 -1
- package/dist/websocket.d.ts +9 -2
- package/dist/websocket.js +1 -1
- package/package.json +8 -8
- package/dist/compaction-Bell28K8.js.map +0 -1
- package/dist/durable-DRY7AcsF.js.map +0 -1
- package/dist/reduced-state-DFIYylAq.js.map +0 -1
- package/dist/session-state-BBzzJrDC.js.map +0 -1
- package/dist/sink-registry-ogHu2Sw7.js.map +0 -1
package/dist/websocket.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { c as StopTurnCommand, l as SubmitMessageCommand, o as PromotePendingMessageCommand, s as ResumePendingMessagesCommand, t as CancelPendingMessageCommand } from "./commands-3OD-p8dD.js";
|
|
2
2
|
import { h as SequenceNumber } from "./core-BcimKMIv.js";
|
|
3
3
|
import { f as PositionedEvent, i as EventEnvelope } from "./envelope-Che6KatU.js";
|
|
4
|
-
import "./events-
|
|
5
|
-
import "./reduced-state-
|
|
4
|
+
import "./events-BWuvzVml.js";
|
|
5
|
+
import "./reduced-state-4FSWDdgT.js";
|
|
6
6
|
import * as Effect from "effect/Effect";
|
|
7
7
|
import * as Schema from "effect/Schema";
|
|
8
8
|
//#region src/websocket/protocol.d.ts
|
|
@@ -229,6 +229,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
229
229
|
readonly name: Schema.String;
|
|
230
230
|
readonly isFailure: Schema.Boolean;
|
|
231
231
|
readonly result: Schema.Unknown;
|
|
232
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
232
233
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
233
234
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
234
235
|
}>, Schema.Struct<{
|
|
@@ -990,6 +991,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
990
991
|
readonly name: Schema.String;
|
|
991
992
|
readonly isFailure: Schema.Boolean;
|
|
992
993
|
readonly result: Schema.Unknown;
|
|
994
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
993
995
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
994
996
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
995
997
|
}>, Schema.Struct<{
|
|
@@ -1062,6 +1064,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
1062
1064
|
readonly name: Schema.String;
|
|
1063
1065
|
readonly isFailure: Schema.Boolean;
|
|
1064
1066
|
readonly result: Schema.Unknown;
|
|
1067
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
1065
1068
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
1066
1069
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
1067
1070
|
}>, Schema.Struct<{
|
|
@@ -1134,6 +1137,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
1134
1137
|
readonly name: Schema.String;
|
|
1135
1138
|
readonly isFailure: Schema.Boolean;
|
|
1136
1139
|
readonly result: Schema.Unknown;
|
|
1140
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
1137
1141
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
1138
1142
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
1139
1143
|
}>, Schema.Struct<{
|
|
@@ -1642,6 +1646,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
1642
1646
|
readonly toolCallId: Schema.brand<Schema.String, "ToolCallId">;
|
|
1643
1647
|
readonly promptPart: Schema.Struct<{
|
|
1644
1648
|
readonly type: Schema.Literal<"tool-result">;
|
|
1649
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
1645
1650
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
1646
1651
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
1647
1652
|
readonly id: Schema.brand<Schema.NonEmptyString, "ProviderPartId">;
|
|
@@ -1713,6 +1718,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
1713
1718
|
readonly toolCallId: Schema.brand<Schema.String, "ToolCallId">;
|
|
1714
1719
|
readonly promptPart: Schema.Struct<{
|
|
1715
1720
|
readonly type: Schema.Literal<"tool-result">;
|
|
1721
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
1716
1722
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
1717
1723
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
1718
1724
|
readonly id: Schema.brand<Schema.NonEmptyString, "ProviderPartId">;
|
|
@@ -1756,6 +1762,7 @@ declare const EDAFrameworkWebSocketEvent: Schema.Union<readonly [Schema.Union<re
|
|
|
1756
1762
|
}>>;
|
|
1757
1763
|
readonly promptPart: Schema.Struct<{
|
|
1758
1764
|
readonly type: Schema.Literal<"tool-result">;
|
|
1765
|
+
readonly providerExecuted: Schema.withDecodingDefault<Schema.Boolean>;
|
|
1759
1766
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
1760
1767
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
1761
1768
|
readonly id: Schema.brand<Schema.NonEmptyString, "ProviderPartId">;
|
package/dist/websocket.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Position, SequenceNumber } from "./types/core.js";
|
|
2
2
|
import { d as PositionedEvent, g as UnixEpochMillis, i as EventEnvelope } from "./envelope-BCzKUq_z.js";
|
|
3
|
-
import { U as EDADurableEvent } from "./durable-
|
|
3
|
+
import { U as EDADurableEvent } from "./durable-CD__3ztN.js";
|
|
4
4
|
import { EDAEphemeralEvent } from "./types/events.js";
|
|
5
5
|
import * as Effect from "effect/Effect";
|
|
6
6
|
import * as Schema from "effect/Schema";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effect-durable-agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.20",
|
|
4
4
|
"description": "A host-independent, event-sourced durable state-management and execution layer for agentic applications.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -175,19 +175,19 @@
|
|
|
175
175
|
"tag": "alpha"
|
|
176
176
|
},
|
|
177
177
|
"peerDependencies": {
|
|
178
|
-
"effect": "4.0.
|
|
178
|
+
"effect": "4.0.3"
|
|
179
179
|
},
|
|
180
180
|
"devDependencies": {
|
|
181
181
|
"@cloudflare/workers-types": "5.20260813.1",
|
|
182
|
-
"@effect/ai-openai": "4.0.
|
|
183
|
-
"@effect/tsgo": "0.
|
|
184
|
-
"@effect/vitest": "4.0.
|
|
182
|
+
"@effect/ai-openai": "4.0.3",
|
|
183
|
+
"@effect/tsgo": "0.51.1",
|
|
184
|
+
"@effect/vitest": "4.0.3",
|
|
185
185
|
"@types/node": "^25.7.0",
|
|
186
|
-
"effect": "4.0.
|
|
186
|
+
"effect": "4.0.3",
|
|
187
187
|
"esbuild": "^0.28.1",
|
|
188
188
|
"fast-check": "^4.8.0",
|
|
189
|
-
"oxlint": "1.
|
|
190
|
-
"oxlint-tsgolint": "7.0.
|
|
189
|
+
"oxlint": "1.87.0",
|
|
190
|
+
"oxlint-tsgolint": "7.0.2003",
|
|
191
191
|
"publint": "^0.3.22",
|
|
192
192
|
"tsx": "4.21.0",
|
|
193
193
|
"typescript": "7.0.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-Bell28K8.js","names":[],"sources":["../src/services/provider-usage.ts","../src/services/compaction.ts"],"sourcesContent":["import type * as Response from \"effect/unstable/ai/Response\";\nimport { UsagePayload } from \"../types/events\";\n\n/** Normalizes provider usage for both conversation and compaction calls. */\nexport const makeUsagePayload = (usage: Response.Usage) => {\n const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);\n const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);\n const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);\n const inputTokens =\n nonNegativeInt(usage.inputTokens.total) ??\n sumDefined([uncachedInputTokens, cachedInputTokens, cacheWriteInputTokens]);\n const textTokens = nonNegativeInt(usage.outputTokens.text);\n const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);\n const outputTokens =\n nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);\n\n return UsagePayload.make({\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),\n ...(cacheWriteInputTokens === undefined ? {} : { cacheWriteInputTokens }),\n ...(outputTokens === undefined ? {} : { outputTokens }),\n ...(textTokens === undefined ? {} : { textTokens }),\n ...(reasoningTokens === undefined ? {} : { reasoningTokens }),\n });\n};\n\nconst sumDefined = (values: ReadonlyArray<number | undefined>) => {\n const present = values.filter((value): value is number => value !== undefined);\n return present.length === 0 ? undefined : present.reduce((sum, value) => sum + value, 0);\n};\n\nconst nonNegativeInt = (value: number | undefined) =>\n value === undefined || !Number.isFinite(value) ? undefined : Math.max(0, Math.trunc(value));\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Prompt from \"effect/unstable/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\nimport type * as LanguageModel from \"effect/unstable/ai/LanguageModel\";\nimport { ModelResolver } from \"./model-resolver\";\nimport { makeUsagePayload } from \"./provider-usage\";\n\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport {\n durableMessageTranscript,\n type DurableTranscriptMessage,\n} from \"../domain/message-transcript\";\nimport {\n CompactionExecutorId,\n CompactionPolicyId,\n CompactionSummaryArtifact,\n} from \"../domain/context-projection\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport { InferenceId, ContextVersion, SequenceNumber } from \"../types/core\";\nimport { FailurePayload, UsagePayload, type AssistantMessageContent } from \"../types/events\";\nimport { CommittedDurableEvent, DurableAppendEntry, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\n\n/** Candidate durable range and retained cursor selected by compaction policy. */\nexport const CompactionPlan = Schema.Struct({\n policyId: CompactionPolicyId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n retainedFromContextSeq: SequenceNumber,\n});\nexport type CompactionPlan = typeof CompactionPlan.Type;\n\n/** Rough token heuristic used by the built-in compaction presets. */\nexport const defaultCompactionCharsPerToken = 4;\n\n/** Production-oriented context threshold for the built-in approximate-token policy. */\nexport const defaultCompactionThresholdTokens = 220_000;\n\n/** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */\nexport const defaultCompactionRetainTailTokens = 40_000;\n\n/** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */\nexport const defaultCompactionMinSummarizableTokens = 10_000;\n\n/** Approximate-token policy options for common production compaction. */\nexport interface ApproximateTokenThresholdCompactionPolicyOptions {\n /** Stable policy id stored on summary artifacts. */\n readonly policyId?: string;\n /** Context-size threshold that triggers compaction. Defaults to 220k tokens. */\n readonly thresholdTokens?: number;\n /** Recent tail retained verbatim after compaction. Defaults to 40k tokens. */\n readonly retainTailTokens?: number;\n /** Smallest prefix worth summarizing. Defaults to 10k tokens. */\n readonly minSummarizableTokens?: number;\n /** Character-to-token divisor for the approximate estimator. Defaults to 4. */\n readonly charsPerToken?: number;\n}\n\n/** LanguageModel-backed summary executor options. */\nexport interface LanguageModelSummaryCompactionExecutorOptions {\n /** Stable executor id stored on summary artifacts. */\n readonly executorId?: string;\n /** Prefix used for the synthetic prompt message inserted into future context. */\n readonly summaryMessagePrefix?: string;\n}\n\n/** Input visible to policy decisions. */\nexport interface CompactionPolicyInput {\n readonly state: ReducedState;\n readonly context: ContextProjection;\n}\n\n/** Result produced by the summary executor before the framework commits it. */\nexport const CompactionOutput = Schema.Struct({\n text: Schema.NonEmptyString,\n promptMessage: Prompt.UserMessage,\n executorId: Schema.optionalKey(CompactionExecutorId),\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type CompactionOutput = typeof CompactionOutput.Type;\n\n/** Executor input with framework-minted lifecycle identities. */\nexport interface CompactionExecutorInput extends CompactionPolicyInput {\n readonly plan: CompactionPlan;\n /** Provider service resolved from the same durable selection used for accounting. */\n readonly model: LanguageModel.Service;\n}\n\n/** Typed failure from policy planning or summary generation. */\nexport class CompactionError extends Schema.TaggedErrorClass<CompactionError>()(\"CompactionError\", {\n message: Schema.String,\n usage: Schema.optionalKey(UsagePayload),\n}) {}\n\n/** Service contract for deciding whether the current context should be compacted. */\nexport interface CompactionPolicyShape {\n readonly id: CompactionPolicyId;\n readonly plan: (\n input: CompactionPolicyInput,\n ) => Effect.Effect<CompactionPlan | undefined, CompactionError>;\n}\n\n/** Decides whether a safe prompt-context rebase should be attempted. */\nexport class CompactionPolicy extends Context.Service<CompactionPolicy, CompactionPolicyShape>()(\n \"@effect-durable-agent/CompactionPolicy\",\n) {\n /** Default policy: compaction is disabled and commits no skip events. */\n static readonly Disabled = Layer.succeed(CompactionPolicy, {\n id: CompactionPolicyId.make(\"disabled\"),\n plan: () => Effect.succeed(undefined),\n } satisfies CompactionPolicyShape);\n\n /** Test/app hook for replacing the policy with a concrete planner. */\n static readonly FromFunction = (\n id: string,\n plan: CompactionPolicyShape[\"plan\"],\n ): Layer.Layer<CompactionPolicy> =>\n Layer.succeed(CompactionPolicy, {\n id: CompactionPolicyId.make(id),\n plan,\n });\n\n /**\n * Common production policy: compact when approximate prompt context exceeds a token threshold.\n *\n * The policy keeps a recent tail verbatim, summarizes the older prefix, and advances from the\n * current summary cursor so repeated compactions behave like the first one.\n */\n static readonly ApproximateTokenThreshold = (\n options: ApproximateTokenThresholdCompactionPolicyOptions = {},\n ): Layer.Layer<CompactionPolicy> => {\n const normalized = normalizeApproximateTokenPolicyOptions(options);\n return Layer.succeed(CompactionPolicy, {\n id: normalized.policyId,\n plan: ({ state, context }) =>\n Effect.sync(() => planApproximateTokenCompaction(state, context, normalized)),\n });\n };\n}\n\n/** Service contract for turning a selected compaction range into a summary artifact. */\nexport interface CompactionExecutorShape {\n readonly id: CompactionExecutorId;\n readonly execute: (\n input: CompactionExecutorInput,\n ) => Effect.Effect<CompactionOutput, CompactionError>;\n}\n\n/** Produces a cumulative summary artifact for a selected compaction plan. */\nexport class CompactionExecutor extends Context.Service<\n CompactionExecutor,\n CompactionExecutorShape\n>()(\"@effect-durable-agent/CompactionExecutor\") {\n /** Placeholder executor for the disabled default policy. It should never be called. */\n static readonly Disabled = Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(\"disabled\"),\n execute: () => Effect.die(new Error(\"CompactionExecutor.Disabled was called\")),\n } satisfies CompactionExecutorShape);\n\n /** Test/app hook for replacing summary generation. */\n static readonly FromFunction = (\n id: string,\n execute: CompactionExecutorShape[\"execute\"],\n ): Layer.Layer<CompactionExecutor> =>\n Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(id),\n execute,\n });\n\n /** Summary executor backed by the configured Effect AI LanguageModel. */\n static readonly LanguageModelSummary = (\n options: LanguageModelSummaryCompactionExecutorOptions = {},\n ): Layer.Layer<CompactionExecutor> =>\n Layer.effect(\n CompactionExecutor,\n Effect.sync(() => {\n const executorId = CompactionExecutorId.make(\n options.executorId ?? \"language-model-summary\",\n );\n const summaryMessagePrefix = options.summaryMessagePrefix ?? \"Conversation summary:\";\n return {\n id: executorId,\n execute: Effect.fn(\"agent.compaction\")(function* (input) {\n yield* annotateEdaSpan({\n \"eda.compaction.policy_id\": input.plan.policyId,\n \"eda.compaction.source_from_seq\": input.plan.sourceFromSeq,\n \"eda.compaction.source_to_seq\": input.plan.sourceToSeq,\n \"eda.compaction.retained_from_context_seq\": input.plan.retainedFromContextSeq,\n \"eda.compaction.executor_id\": executorId,\n });\n const promptText = buildSummaryPrompt(input);\n if (promptText === undefined) {\n return yield* new CompactionError({\n message: \"compaction plan selected no source messages\",\n });\n }\n const response = yield* input.model\n .generateText({\n prompt: Prompt.fromMessages([\n Prompt.makeMessage(\"system\", { content: summarizationSystemPrompt }),\n Prompt.makeMessage(\"user\", {\n content: [Prompt.textPart({ text: promptText })],\n }),\n ]),\n toolChoice: \"none\",\n })\n .pipe(\n Effect.mapError(\n (error) =>\n new CompactionError({\n message: `summary model failed: ${formatUnknownError(error)}`,\n }),\n ),\n );\n const text = response.text.trim();\n if (text.length === 0) {\n return yield* new CompactionError({\n message: \"summary model returned no text\",\n usage: makeUsagePayload(response.usage),\n });\n }\n return CompactionOutput.make({\n usage: makeUsagePayload(response.usage),\n text,\n promptMessage: Prompt.makeMessage(\"user\", {\n content: [Prompt.textPart({ text: `${summaryMessagePrefix}\\n\\n${text}` })],\n }),\n executorId,\n });\n }),\n } satisfies CompactionExecutorShape;\n }),\n );\n}\n\n/** Inputs needed by the framework-owned compaction lifecycle runner. */\nexport interface CompactionRunnerInput {\n readonly state: ReducedState;\n readonly context: ContextProjection;\n readonly appendDurableEntries: (\n entries: ReadonlyArray<DurableAppendEntry>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Runtime service that executes framework-owned compaction lifecycles. */\nexport interface CompactionRunnerShape {\n /** Evaluate policy and run one compaction if a plan is selected. */\n readonly maybeCompact: (\n input: CompactionRunnerInput,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Framework-owned compaction lifecycle runner. */\nexport class CompactionRunner extends Context.Service<CompactionRunner, CompactionRunnerShape>()(\n \"@effect-durable-agent/CompactionRunner\",\n) {\n static readonly Live = Layer.effect(\n CompactionRunner,\n Effect.suspend(() => makeLiveCompactionRunner),\n );\n}\n\ninterface NormalizedApproximateTokenPolicyOptions {\n readonly policyId: CompactionPolicyId;\n readonly thresholdTokens: number;\n readonly retainTailTokens: number;\n readonly minSummarizableTokens: number;\n readonly charsPerToken: number;\n}\n\ninterface EstimatedContextMessage {\n readonly chars: number;\n readonly message: DurableTranscriptMessage;\n readonly seq: SequenceNumber;\n}\n\nconst makeLiveCompactionRunner = Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const events = yield* EventFactory;\n const policy = yield* CompactionPolicy;\n const executor = yield* CompactionExecutor;\n const keepAlive = yield* EDAKeepAlive;\n const models = yield* ModelResolver;\n\n const maybeCompact = Effect.fnUntraced(function* (input: CompactionRunnerInput) {\n const plan = yield* policy\n .plan({ state: input.state, context: input.context })\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.logError(\"compaction policy failed\", { error }).pipe(Effect.as(undefined)),\n ),\n );\n if (plan === undefined) {\n yield* annotateEdaSpan({ \"eda.compaction.selected\": false });\n return [];\n }\n yield* annotateEdaSpan({\n \"eda.compaction.selected\": true,\n \"eda.compaction.policy_id\": plan.policyId,\n \"eda.compaction.source_from_seq\": plan.sourceFromSeq,\n \"eda.compaction.source_to_seq\": plan.sourceToSeq,\n \"eda.compaction.retained_from_context_seq\": plan.retainedFromContextSeq,\n });\n const invalidPlan = validatePlan(plan, input.state, input.context);\n if (invalidPlan !== undefined) {\n yield* Effect.logError(\"compaction policy returned invalid plan\", { reason: invalidPlan });\n return [];\n }\n\n const compactionId = yield* ids.makeCompactionId();\n const summaryId = yield* ids.makeSummaryId();\n yield* annotateEdaSpan({\n \"eda.compaction.id\": compactionId,\n \"eda.summary.id\": summaryId,\n });\n const requested = yield* events.compactionRequested({\n compactionId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n });\n const started = yield* events.compactionStarted({ compactionId });\n const startedEvents = yield* input.appendDurableEntries([\n { event: requested },\n { event: started },\n ]);\n\n const model = yield* models.resolve(input.state.modelSelection);\n const output = yield* keepAlive\n .withActiveWork(\n `compaction:${compactionId}`,\n executor.execute({ plan, state: input.state, context: input.context, model }),\n )\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.gen(function* () {\n const failed = yield* events.compactionFailed({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(error.usage === undefined ? {} : { usage: error.usage }),\n error: FailurePayload.make({ message: error.message }),\n });\n const committed = yield* input.appendDurableEntries([{ event: failed }]);\n return { _tag: \"Failed\" as const, committed };\n }),\n ),\n Effect.map((result) =>\n \"_tag\" in result ? result : { _tag: \"Output\" as const, output: result },\n ),\n );\n\n if (output._tag === \"Failed\") {\n return [...startedEvents, ...output.committed];\n }\n\n const artifact = CompactionSummaryArtifact.make({\n compactionId,\n summaryId,\n ...(input.context.currentSummary === undefined\n ? {}\n : { previousSummaryId: input.context.currentSummary.summaryId }),\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n retainedFromContextSeq: plan.retainedFromContextSeq,\n text: output.output.text,\n promptMessage: output.output.promptMessage,\n policyId: plan.policyId,\n ...(output.output.executorId === undefined ? {} : { executorId: output.output.executorId }),\n });\n const summaryCreated = yield* events.summaryCreated({\n compactionId,\n summaryId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n summary: artifact,\n });\n const contextRebased = yield* events.contextRebased({\n compactionId,\n summaryId,\n contextVersion: ContextVersion.make(input.context.contextVersion + 1),\n retainedFromContextSeq: plan.retainedFromContextSeq,\n });\n const completed = yield* events.compactionCompleted({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(output.output.usage === undefined ? {} : { usage: output.output.usage }),\n });\n const committed = yield* input.appendDurableEntries([\n { event: summaryCreated },\n { event: contextRebased },\n { event: completed },\n ]);\n yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));\n return [...startedEvents, ...committed];\n });\n\n return { maybeCompact } satisfies CompactionRunnerShape;\n});\n\nconst validatePlan = (\n plan: CompactionPlan,\n state: ReducedState,\n context: ContextProjection,\n): string | undefined => {\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n if (plan.retainedFromContextSeq <= currentRetainedFromSeq) {\n return \"retainedFromContextSeq must advance beyond the current summary cursor\";\n }\n if (plan.sourceToSeq > state.lastSeq) {\n return \"sourceToSeq must not exceed the current durable head\";\n }\n if (plan.retainedFromContextSeq > state.lastSeq + 1) {\n return \"retainedFromContextSeq must not skip unsummarized future context\";\n }\n if (plan.sourceFromSeq > plan.sourceToSeq) {\n return \"sourceFromSeq must be less than or equal to sourceToSeq\";\n }\n if (plan.retainedFromContextSeq <= plan.sourceToSeq) {\n return \"retainedFromContextSeq must start after the summarized source range\";\n }\n return undefined;\n};\n\nconst normalizeApproximateTokenPolicyOptions = (\n options: ApproximateTokenThresholdCompactionPolicyOptions,\n): NormalizedApproximateTokenPolicyOptions => ({\n policyId: CompactionPolicyId.make(options.policyId ?? \"approximate-token-threshold\"),\n thresholdTokens: positiveNumber(\n options.thresholdTokens ?? defaultCompactionThresholdTokens,\n \"thresholdTokens\",\n ),\n retainTailTokens: nonNegativeNumber(\n options.retainTailTokens ?? defaultCompactionRetainTailTokens,\n \"retainTailTokens\",\n ),\n minSummarizableTokens: nonNegativeNumber(\n options.minSummarizableTokens ?? defaultCompactionMinSummarizableTokens,\n \"minSummarizableTokens\",\n ),\n charsPerToken: positiveNumber(\n options.charsPerToken ?? defaultCompactionCharsPerToken,\n \"charsPerToken\",\n ),\n});\n\nconst positiveNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`${name} must be a positive finite number`);\n }\n return value;\n};\n\nconst nonNegativeNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a non-negative finite number`);\n }\n return value;\n};\n\n/** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */\nconst planApproximateTokenCompaction = (\n state: ReducedState,\n context: ContextProjection,\n options: NormalizedApproximateTokenPolicyOptions,\n): CompactionPlan | undefined => {\n const messages = estimatedContextMessages(state);\n const totalChars = estimateCurrentPromptChars(state, context, messages);\n if (totalChars <= options.thresholdTokens * options.charsPerToken) {\n return undefined;\n }\n\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);\n if (retainedFromSeq <= currentRetainedFromSeq) {\n return undefined;\n }\n\n const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);\n if (sourceMessages.length === 0) {\n return undefined;\n }\n\n const summarizableTokens = charsToTokens(\n sourceMessages.reduce((sum, message) => sum + message.chars, 0),\n options.charsPerToken,\n );\n if (summarizableTokens < options.minSummarizableTokens) {\n return undefined;\n }\n\n const sourceFromSeq =\n currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0]!.seq;\n const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);\n if (sourceFromSeq > sourceToSeq) {\n return undefined;\n }\n\n return CompactionPlan.make({\n policyId: options.policyId,\n sourceFromSeq,\n sourceToSeq,\n retainedFromContextSeq: retainedFromSeq,\n });\n};\n\nconst selectRetainedFromSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n lastSeq: SequenceNumber,\n options: NormalizedApproximateTokenPolicyOptions,\n): SequenceNumber => {\n if (options.retainTailTokens === 0) {\n return SequenceNumber.make(lastSeq + 1);\n }\n\n const retainTailChars = options.retainTailTokens * options.charsPerToken;\n let tailChars = 0;\n let retainedIndex = messages.length;\n for (let index = messages.length - 1; index >= 0; index--) {\n tailChars += messages[index]!.chars;\n retainedIndex = index;\n if (tailChars >= retainTailChars) {\n break;\n }\n }\n return retainedIndex >= messages.length\n ? SequenceNumber.make(lastSeq + 1)\n : messages[retainedIndex]!.seq;\n};\n\nconst estimateCurrentPromptChars = (\n state: ReducedState,\n context: ContextProjection,\n messages: ReadonlyArray<EstimatedContextMessage>,\n): number => {\n const systemChars = Array.from(state.messages.values()).reduce(\n (sum, message) => (message._tag === \"System\" ? sum + message.content.length : sum),\n 0,\n );\n const summaryChars =\n context.currentSummary === undefined\n ? 0\n : estimatePromptMessageChars(context.currentSummary.promptMessage);\n const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);\n return systemChars + summaryChars + messageChars;\n};\n\nconst estimatedContextMessages = (state: ReducedState): ReadonlyArray<EstimatedContextMessage> =>\n durableMessageTranscript(state).map((message) => ({\n message,\n seq: messageSeq(message),\n chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state),\n }));\n\nconst estimateDurableMessageChars = (message: DurableTranscriptMessage): number => {\n switch (message._tag) {\n case \"User\":\n case \"Steering\":\n return estimateUserContentChars(message.content);\n case \"Assistant\":\n case \"AssistantPartial\":\n return estimateAssistantPromptChars(message.promptParts, message.content);\n }\n};\n\nconst estimateAssociatedToolChars = (\n message: DurableTranscriptMessage,\n state: ReducedState,\n): number => {\n if (message._tag !== \"Assistant\" && message._tag !== \"AssistantPartial\") {\n return 0;\n }\n return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n};\n\nconst messageSeq = (message: DurableTranscriptMessage): SequenceNumber =>\n message._tag === \"Steering\" ? message.consumedSeq : message.seq;\n\nconst charsToTokens = (chars: number, charsPerToken: number): number =>\n Math.ceil(chars / charsPerToken);\n\nconst buildSummaryPrompt = (input: CompactionExecutorInput): string | undefined => {\n const sourceText = serializeCompactionSource(input);\n if (sourceText.trim().length === 0) {\n return undefined;\n }\n\n const previousSummary =\n input.context.currentSummary === undefined\n ? \"\"\n : `<previous-summary>\\n${input.context.currentSummary.text}\\n</previous-summary>\\n\\n`;\n return `${previousSummary}<conversation>\\n${sourceText}\\n</conversation>\\n\\n${summaryPromptText}`;\n};\n\nconst serializeCompactionSource = (input: CompactionExecutorInput): string => {\n const lines: Array<string> = [];\n for (const message of durableMessageTranscript(input.state)) {\n const seq = messageSeq(message);\n if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) {\n continue;\n }\n lines.push(serializeDurableMessage(message));\n if (message._tag === \"Assistant\" || message._tag === \"AssistantPartial\") {\n for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) {\n lines.push(serializeToolResultPart(part));\n }\n }\n }\n return lines.filter((line) => line.trim().length > 0).join(\"\\n\\n\");\n};\n\nconst serializeDurableMessage = (message: DurableTranscriptMessage): string => {\n switch (message._tag) {\n case \"User\":\n return `[User]: ${userContentText(message.content)}`;\n case \"Steering\":\n return `[User steering]: ${userContentText(message.content)}`;\n case \"Assistant\":\n case \"AssistantPartial\":\n return serializeAssistantMessage(message.promptParts, message.content);\n }\n};\n\nconst serializeAssistantMessage = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): string => {\n const parts = promptParts ?? assistantContentToPromptParts(content);\n const text: Array<string> = [];\n const reasoning: Array<string> = [];\n const toolCalls: Array<string> = [];\n const sideband: Array<string> = [];\n for (const part of parts) {\n switch (part.type) {\n case \"text\":\n text.push(part.text);\n break;\n case \"reasoning\":\n reasoning.push(part.text);\n break;\n case \"tool-call\":\n toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);\n break;\n case \"file\":\n sideband.push(`file(${part.fileName ?? \"unnamed\"}, ${part.mediaType})`);\n break;\n case \"tool-result\":\n sideband.push(\n `tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`,\n );\n break;\n case \"tool-approval-request\":\n sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);\n break;\n }\n }\n return [\n reasoning.length === 0 ? \"\" : `[Assistant reasoning]: ${reasoning.join(\"\\n\")}`,\n text.length === 0 ? \"\" : `[Assistant]: ${text.join(\"\\n\")}`,\n toolCalls.length === 0 ? \"\" : `[Assistant tool calls]: ${toolCalls.join(\"; \")}`,\n sideband.length === 0 ? \"\" : `[Assistant context]: ${sideband.join(\"; \")}`,\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\");\n};\n\nconst serializeToolResultPart = (part: Prompt.ToolResultPart): string =>\n `[Tool result ${part.name}${part.isFailure ? \" failed\" : \"\"}]: ${truncateForSummary(\n safeJsonStringify(part.result),\n )}`;\n\nconst toolPromptPartsForInference = (\n inferenceId: InferenceId,\n toolCalls: ReducedState[\"toolCalls\"],\n): ReadonlyArray<Prompt.ToolResultPart> =>\n Array.from(toolCalls.values()).flatMap((tool): ReadonlyArray<Prompt.ToolResultPart> => {\n const { decision } = tool;\n if (decision === undefined || decision.inferenceId !== inferenceId) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined ? [] : [decision.promptPart];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [terminal.promptPart];\n });\n\nconst assistantContentToPromptParts = (\n content: AssistantMessageContent,\n): ReadonlyArray<Prompt.AssistantMessagePart> => [\n ...(content.reasoning === undefined ? [] : [Prompt.reasoningPart({ text: content.reasoning })]),\n ...(content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]),\n];\n\nconst estimateAssistantPromptChars = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): number =>\n (promptParts ?? assistantContentToPromptParts(content)).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n\nconst estimateUserContentChars = (\n content: string | ReadonlyArray<Prompt.UserMessagePart>,\n): number =>\n typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n\nconst estimatePromptMessageChars = (message: Prompt.Message): number => {\n if (!(\"content\" in message)) {\n return 0;\n }\n const { content } = message;\n return typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n};\n\ntype PromptContentPart =\n | Prompt.UserMessagePart\n | Prompt.AssistantMessagePart\n | Prompt.ToolMessagePart;\n\nconst estimatePromptPartChars = (part: PromptContentPart): number => {\n switch (part.type) {\n case \"text\":\n return part.text.length;\n case \"reasoning\":\n return part.text.length;\n case \"file\":\n return (\n part.mediaType.length +\n (part.fileName?.length ?? 0) +\n (typeof part.data === \"string\"\n ? part.data.length\n : part.data instanceof URL\n ? part.data.toString().length\n : estimatedBinaryFileChars)\n );\n case \"tool-call\":\n return part.name.length + safeJsonStringify(part.params).length;\n case \"tool-result\":\n return part.name.length + safeJsonStringify(part.result).length;\n case \"tool-approval-response\":\n return part.approvalId.length + (part.reason?.length ?? 0) + 8;\n case \"tool-approval-request\":\n return part.approvalId.length + part.toolCallId.length;\n default:\n return safeJsonStringify(part).length;\n }\n};\n\nconst userContentText = (content: string | ReadonlyArray<Prompt.UserMessagePart>): string =>\n typeof content === \"string\"\n ? content\n : content\n .map((part) => {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"file\":\n return `[file ${part.fileName ?? \"unnamed\"} ${part.mediaType}]`;\n }\n })\n .join(\"\\n\");\n\nconst safeJsonStringify = (value: unknown): string => {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst truncateForSummary = (text: string, maxChars = 2_000): string => {\n if (text.length <= maxChars) {\n return text;\n }\n return `${text.slice(0, maxChars)}\\n\\n[... ${text.length - maxChars} more characters truncated]`;\n};\n\nconst formatUnknownError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst estimatedBinaryFileChars = 4_800;\n\nconst summarizationSystemPrompt =\n \"You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.\";\n\nconst summaryPromptText = `The messages above are conversation history selected for compaction. Create a cumulative context checkpoint summary that another LLM will use to continue the work.\n\nUse this exact structure:\n\n## Goal\n[What the user is trying to accomplish]\n\n## Constraints & Preferences\n- [Requirements, constraints, and preferences]\n\n## Progress\n### Done\n- [x] [Completed work]\n\n### In Progress\n- [ ] [Current unfinished work]\n\n### Blocked\n- [Current blockers, or \"(none)\"]\n\n## Key Decisions\n- **[Decision]**: [Rationale]\n\n## Next Steps\n1. [Concrete next step]\n\n## Critical Context\n- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]\n\nRules:\n- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.\n- Keep the summary concise but sufficient to replace the compacted history.\n- Preserve exact file paths, tool names, identifiers, and error messages.\n- Do not answer questions from the conversation.`;\n"],"mappings":";;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoB,UAA0B;CACzD,MAAM,sBAAsB,eAAe,MAAM,YAAY,QAAQ;CACrE,MAAM,oBAAoB,eAAe,MAAM,YAAY,SAAS;CACpE,MAAM,wBAAwB,eAAe,MAAM,YAAY,UAAU;CACzE,MAAM,cACJ,eAAe,MAAM,YAAY,KAAK,KACtC,WAAW;EAAC;EAAqB;EAAmB;CAAqB,CAAC;CAC5E,MAAM,aAAa,eAAe,MAAM,aAAa,IAAI;CACzD,MAAM,kBAAkB,eAAe,MAAM,aAAa,SAAS;CACnE,MAAM,eACJ,eAAe,MAAM,aAAa,KAAK,KAAK,WAAW,CAAC,YAAY,eAAe,CAAC;CAEtF,OAAO,aAAa,KAAK;EACvB,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,sBAAsB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB;EAC/D,GAAI,0BAA0B,KAAA,IAAY,CAAC,IAAI,EAAE,sBAAsB;EACvE,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;EACrD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB;CAC7D,CAAC;AACH;AAEA,MAAM,cAAc,WAA8C;CAChE,MAAM,UAAU,OAAO,QAAQ,UAA2B,UAAU,KAAA,CAAS;CAC7E,OAAO,QAAQ,WAAW,IAAI,KAAA,IAAY,QAAQ,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC;AACzF;AAEA,MAAM,kBAAkB,UACtB,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;;;;ACH5F,MAAa,iBAAiB,OAAO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AAS,kBAAkB,KAAK,MAAM,CAAC,CAAC;EAC3D,KAAK,eACH,OAAO,KAAK,KAAK,SAAS,kBAAkB,KAAK,MAAM,CAAC,CAAC;EAC3D,KAAK,0BACH,OAAO,KAAK,WAAW,UAAU,KAAK,QAAQ,UAAU,KAAK;EAC/D,KAAK,yBACH,OAAO,KAAK,WAAW,SAAS,KAAK,WAAW;EAClD,SACE,OAAO,kBAAkB,IAAI,CAAC,CAAC;CACnC;AACF;AAEA,MAAM,mBAAmB,YACvB,OAAO,YAAY,WACf,UACA,QACG,KAAK,SAAS;CACb,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO,KAAK;EACd,KAAK,QACH,OAAO,SAAS,KAAK,YAAY,UAAU,GAAG,KAAK,UAAU;CACjE;AACF,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,MAAM,qBAAqB,UAA2B;CACpD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,MAAM,sBAAsB,MAAc,WAAW,QAAkB;CACrE,IAAI,KAAK,UAAU,UACjB,OAAO;CAET,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,EAAE,WAAW,KAAK,SAAS,SAAS;AACtE;AAEA,MAAM,sBAAsB,UAC1B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,2BAA2B;AAEjC,MAAM,4BACJ;AAEF,MAAM,oBAAoB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"durable-DRY7AcsF.js","names":[],"sources":["../src/types/events/internal.ts","../src/types/events/durable.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n EventType,\n effectDurableAgentNamespace,\n schemaV1,\n} from \"./envelope\";\n\n/** Build a built-in durable event schema from its fixed event type and payload schema. */\nexport const durableEventSchema = <const Type extends EventType, Payload extends Schema.Top>(\n type: Type,\n payload: Payload,\n) =>\n Schema.Struct({\n ...DurableEventEnvelope.fields,\n namespace: Schema.Literal(effectDurableAgentNamespace),\n type: Schema.Literal(type),\n schemaVersion: Schema.Literal(schemaV1),\n payload,\n });\n\n/** Build a built-in ephemeral event schema from its fixed event type and payload schema. */\nexport const ephemeralEventSchema = <const Type extends EventType, Payload extends Schema.Top>(\n type: Type,\n payload: Payload,\n) =>\n Schema.Struct({\n ...EphemeralEventEnvelope.fields,\n namespace: Schema.Literal(effectDurableAgentNamespace),\n type: Schema.Literal(type),\n schemaVersion: Schema.Literal(schemaV1),\n payload,\n });\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as Prompt from \"effect/unstable/ai/Prompt\";\n\nimport { EDACommand, UserMessageContent } from \"../commands\";\nimport {\n BaseStateId,\n CommandId,\n CompactionId,\n ContextVersion,\n InferenceId,\n MessageId,\n RunId,\n RunRequestId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../core\";\nimport {\n DurableEventEnvelope,\n ForeignDurableEvent,\n FailurePayload,\n ModelSelectionPayload,\n ProviderPartId,\n SystemPromptText,\n ToolName,\n UsagePayload,\n effectDurableAgentNamespace,\n makeEventType,\n schemaV1,\n} from \"./envelope\";\nimport { RunSchedulingRequest } from \"../../domain/run-scheduling\";\nimport { durableEventSchema } from \"./internal\";\nimport { EDARunTrace, makeEDARunTrace } from \"../tracing\";\n\n/** Establishes a session's execution policy before its first run; not a model-switch operation. */\nexport const sessionConfiguredEventType = makeEventType(\"SessionConfigured\");\nexport const SessionConfiguredEvent = durableEventSchema(\n sessionConfiguredEventType,\n Schema.Struct({ modelSelection: ModelSelectionPayload }),\n);\nexport type SessionConfiguredEvent = typeof SessionConfiguredEvent.Type;\n\n/** Event type values for durable command lifecycle events. */\nexport const commandAdmittedEventType = makeEventType(\"CommandAdmitted\");\nexport const commandStartedEventType = makeEventType(\"CommandStarted\");\nexport const commandCompletedEventType = makeEventType(\"CommandCompleted\");\nexport const commandFailedEventType = makeEventType(\"CommandFailed\");\nexport const commandCancelledEventType = makeEventType(\"CommandCancelled\");\n\n/** Payload recorded when a command enters the durable session log. */\nexport const CommandAdmittedPayload = Schema.Struct({ command: EDACommand });\nexport type CommandAdmittedPayload = typeof CommandAdmittedPayload.Type;\nexport const CommandAdmittedEvent = durableEventSchema(\n commandAdmittedEventType,\n CommandAdmittedPayload,\n);\nexport type CommandAdmittedEvent = typeof CommandAdmittedEvent.Type;\n\n/** Payload recorded when command execution starts. */\nexport const CommandStartedPayload = Schema.Struct({ commandId: CommandId });\nexport type CommandStartedPayload = typeof CommandStartedPayload.Type;\nexport const CommandStartedEvent = durableEventSchema(\n commandStartedEventType,\n CommandStartedPayload,\n);\nexport type CommandStartedEvent = typeof CommandStartedEvent.Type;\n\n/** Payload recorded when command execution completes normally. */\nexport const CommandCompletedPayload = Schema.Struct({ commandId: CommandId });\nexport type CommandCompletedPayload = typeof CommandCompletedPayload.Type;\nexport const CommandCompletedEvent = durableEventSchema(\n commandCompletedEventType,\n CommandCompletedPayload,\n);\nexport type CommandCompletedEvent = typeof CommandCompletedEvent.Type;\n\n/** Payload recorded when command execution fails. */\nexport const CommandFailedPayload = Schema.Struct({ commandId: CommandId, error: FailurePayload });\nexport type CommandFailedPayload = typeof CommandFailedPayload.Type;\nexport const CommandFailedEvent = durableEventSchema(commandFailedEventType, CommandFailedPayload);\nexport type CommandFailedEvent = typeof CommandFailedEvent.Type;\n\n/** Payload recorded when a command is cancelled before completion. */\nexport const CommandCancelledPayload = Schema.Struct({\n commandId: CommandId,\n reason: Schema.String,\n});\nexport type CommandCancelledPayload = typeof CommandCancelledPayload.Type;\nexport const CommandCancelledEvent = durableEventSchema(\n commandCancelledEventType,\n CommandCancelledPayload,\n);\nexport type CommandCancelledEvent = typeof CommandCancelledEvent.Type;\n\n/** Durable event union for the command lifecycle. */\nexport const CommandEvent = Schema.Union([\n CommandAdmittedEvent,\n CommandStartedEvent,\n CommandCompletedEvent,\n CommandFailedEvent,\n CommandCancelledEvent,\n]);\nexport type CommandEvent = typeof CommandEvent.Type;\n\n/** Durable reservation for the next run slot, committed before outbound delivery. */\nexport const runSchedulingRequestedEventType = makeEventType(\"RunSchedulingRequested\");\nexport const RunSchedulingRequestedPayload = RunSchedulingRequest;\nexport type RunSchedulingRequestedPayload = typeof RunSchedulingRequestedPayload.Type;\nexport const RunSchedulingRequestedEvent = durableEventSchema(\n runSchedulingRequestedEventType,\n RunSchedulingRequestedPayload,\n);\nexport type RunSchedulingRequestedEvent = typeof RunSchedulingRequestedEvent.Type;\n\n/** Acknowledgment that the external authorizer durably accepted this request. */\nexport const runSchedulingDeliveredEventType = makeEventType(\"RunSchedulingDelivered\");\nexport const RunSchedulingDeliveredPayload = Schema.Struct({ requestId: RunRequestId });\nexport type RunSchedulingDeliveredPayload = typeof RunSchedulingDeliveredPayload.Type;\nexport const RunSchedulingDeliveredEvent = durableEventSchema(\n runSchedulingDeliveredEventType,\n RunSchedulingDeliveredPayload,\n);\nexport type RunSchedulingDeliveredEvent = typeof RunSchedulingDeliveredEvent.Type;\n\n/** Revocation of a reservation whose work was cancelled, stopped, or superseded. */\nexport const runSchedulingInvalidatedEventType = makeEventType(\"RunSchedulingInvalidated\");\nexport const RunSchedulingInvalidatedPayload = Schema.Struct({\n requestId: RunRequestId,\n reason: Schema.Literals([\"stopped\", \"interrupted\", \"message-cancelled\", \"ineligible\"]),\n});\nexport type RunSchedulingInvalidatedPayload = typeof RunSchedulingInvalidatedPayload.Type;\nexport const RunSchedulingInvalidatedEvent = durableEventSchema(\n runSchedulingInvalidatedEventType,\n RunSchedulingInvalidatedPayload,\n);\nexport type RunSchedulingInvalidatedEvent = typeof RunSchedulingInvalidatedEvent.Type;\n\n/** Permission consumed atomically with RunStarted; never a standalone authorization. */\nexport const runSchedulingGrantedEventType = makeEventType(\"RunSchedulingGranted\");\nexport const RunSchedulingGrantedPayload = Schema.Struct({ requestId: RunRequestId, runId: RunId });\nexport type RunSchedulingGrantedPayload = typeof RunSchedulingGrantedPayload.Type;\nexport const RunSchedulingGrantedEvent = durableEventSchema(\n runSchedulingGrantedEventType,\n RunSchedulingGrantedPayload,\n);\nexport type RunSchedulingGrantedEvent = typeof RunSchedulingGrantedEvent.Type;\n\n/** Framework facts for durable run authorization and its strict delivery acknowledgment. */\nexport const RunSchedulingEvent = Schema.Union([\n RunSchedulingRequestedEvent,\n RunSchedulingDeliveredEvent,\n RunSchedulingInvalidatedEvent,\n RunSchedulingGrantedEvent,\n]);\nexport type RunSchedulingEvent = typeof RunSchedulingEvent.Type;\n\n/** Event type values for durable message lifecycle events. */\nexport const systemMessageCommittedEventType = makeEventType(\"SystemMessageCommitted\");\nexport const userMessageCommittedEventType = makeEventType(\"UserMessageCommitted\");\nexport const steeringMessageQueuedEventType = makeEventType(\"SteeringMessageQueued\");\nexport const steeringMessageCancelledEventType = makeEventType(\"SteeringMessageCancelled\");\nexport const userMessageSubmittedEventType = makeEventType(\"UserMessageSubmitted\");\nexport const userMessagePromotedEventType = makeEventType(\"UserMessagePromoted\");\nexport const userMessageCancelledEventType = makeEventType(\"UserMessageCancelled\");\nexport const messageQueuePausedEventType = makeEventType(\"MessageQueuePaused\");\nexport const pendingMessagesPausedEventType = makeEventType(\"PendingMessagesPaused\");\nexport const assistantMessageCommittedEventType = makeEventType(\"AssistantMessageCommitted\");\nexport const assistantMessageImportedEventType = makeEventType(\"AssistantMessageImported\");\nexport const assistantPartialCommittedEventType = makeEventType(\"AssistantPartialCommitted\");\n\n/** Semantic assistant content derived from canonical prompt parts for query convenience. */\nexport const AssistantMessageContent = Schema.Struct({\n text: Schema.String,\n reasoning: Schema.optionalKey(Schema.String),\n});\nexport type AssistantMessageContent = typeof AssistantMessageContent.Type;\n\n/** Exact assistant-role prompt parts sent to the model for cache-faithful replay. */\nexport const AssistantPromptPart = Schema.Union([\n Prompt.TextPart,\n Prompt.FilePart,\n Prompt.ReasoningPart,\n Prompt.ToolCallPart,\n Prompt.ToolResultPart,\n Prompt.ToolApprovalRequestPart,\n]);\nexport type AssistantPromptPart = typeof AssistantPromptPart.Type;\n\n/** Exact non-empty assistant-role prompt content sent to the model. */\nexport const AssistantPromptParts = Schema.NonEmptyArray(AssistantPromptPart);\nexport type AssistantPromptParts = typeof AssistantPromptParts.Type;\n\n/** Exact assistant tool-call prompt part with EDA-branded provider identity. */\nexport const ToolCallPromptPart = Schema.Struct({\n ...Prompt.ToolCallPart.fields,\n id: ProviderPartId,\n name: ToolName,\n});\nexport type ToolCallPromptPart = typeof ToolCallPromptPart.Type;\n\n/** Exact tool-role prompt part sent to the model with EDA-branded provider identity. */\nexport const ToolPromptPart = Schema.Struct({\n ...Prompt.ToolResultPart.fields,\n id: ProviderPartId,\n name: ToolName,\n});\nexport type ToolPromptPart = typeof ToolPromptPart.Type;\n\n/** Payload recorded when app instructions become durable system-message context. */\nexport const SystemMessageCommittedPayload = Schema.Struct({\n messageId: MessageId,\n content: SystemPromptText,\n});\nexport type SystemMessageCommittedPayload = typeof SystemMessageCommittedPayload.Type;\nexport const SystemMessageCommittedEvent = durableEventSchema(\n systemMessageCommittedEventType,\n SystemMessageCommittedPayload,\n);\nexport type SystemMessageCommittedEvent = typeof SystemMessageCommittedEvent.Type;\n\n/** Payload recorded when a user message becomes durable session context. */\nexport const UserMessageCommittedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n content: UserMessageContent,\n});\nexport type UserMessageCommittedPayload = typeof UserMessageCommittedPayload.Type;\nexport const UserMessageCommittedEvent = durableEventSchema(\n userMessageCommittedEventType,\n UserMessageCommittedPayload,\n);\nexport type UserMessageCommittedEvent = typeof UserMessageCommittedEvent.Type;\n\n/** Payload recorded when steering context is queued for a future turn. */\nexport const SteeringMessageQueuedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n runId: RunId,\n content: UserMessageContent,\n});\nexport type SteeringMessageQueuedPayload = typeof SteeringMessageQueuedPayload.Type;\nexport const SteeringMessageQueuedEvent = durableEventSchema(\n steeringMessageQueuedEventType,\n SteeringMessageQueuedPayload,\n);\nexport type SteeringMessageQueuedEvent = typeof SteeringMessageQueuedEvent.Type;\n\n/** Payload recorded when queued steering will never be consumed by its target run. */\nexport const SteeringMessageCancelledPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n reason: Schema.String,\n});\nexport type SteeringMessageCancelledPayload = typeof SteeringMessageCancelledPayload.Type;\nexport const SteeringMessageCancelledEvent = durableEventSchema(\n steeringMessageCancelledEventType,\n SteeringMessageCancelledPayload,\n);\nexport type SteeringMessageCancelledEvent = typeof SteeringMessageCancelledEvent.Type;\n\nexport const UserMessageDisposition = Schema.Literals([\"queue\", \"steer\"]);\nexport type UserMessageDisposition = typeof UserMessageDisposition.Type;\n\nexport const UserMessageSubmittedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n disposition: UserMessageDisposition,\n content: UserMessageContent,\n});\nexport type UserMessageSubmittedPayload = typeof UserMessageSubmittedPayload.Type;\nexport const UserMessageSubmittedEvent = durableEventSchema(\n userMessageSubmittedEventType,\n UserMessageSubmittedPayload,\n);\nexport type UserMessageSubmittedEvent = typeof UserMessageSubmittedEvent.Type;\n\nexport const UserMessagePromotedPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n from: Schema.Literal(\"queue\"),\n to: Schema.Literal(\"steer\"),\n});\nexport type UserMessagePromotedPayload = typeof UserMessagePromotedPayload.Type;\nexport const UserMessagePromotedEvent = durableEventSchema(\n userMessagePromotedEventType,\n UserMessagePromotedPayload,\n);\nexport type UserMessagePromotedEvent = typeof UserMessagePromotedEvent.Type;\n\nexport const UserMessageCancellationReason = Schema.Literals([\n \"edit\",\n \"user-cancel\",\n \"clear-paused-queue\",\n]);\nexport type UserMessageCancellationReason = typeof UserMessageCancellationReason.Type;\nexport const UserMessageCancelledPayload = Schema.Struct({\n commandId: CommandId,\n messageId: MessageId,\n reason: UserMessageCancellationReason,\n});\nexport type UserMessageCancelledPayload = typeof UserMessageCancelledPayload.Type;\nexport const UserMessageCancelledEvent = durableEventSchema(\n userMessageCancelledEventType,\n UserMessageCancelledPayload,\n);\nexport type UserMessageCancelledEvent = typeof UserMessageCancelledEvent.Type;\n\n/** Legacy V1 pause fact retained for replay compatibility. */\nexport const MessageQueuePausedPayload = Schema.Struct({\n stopCommandId: CommandId,\n runId: RunId,\n messageIds: Schema.Array(MessageId),\n reason: Schema.Literal(\"user-interrupted\"),\n});\nexport type MessageQueuePausedPayload = typeof MessageQueuePausedPayload.Type;\nexport const MessageQueuePausedEvent = durableEventSchema(\n messageQueuePausedEventType,\n MessageQueuePausedPayload,\n);\nexport type MessageQueuePausedEvent = typeof MessageQueuePausedEvent.Type;\n\nconst PendingMessagesPausedFields = {\n interruptionCommandId: CommandId,\n messageIds: Schema.NonEmptyArray(MessageId),\n reason: Schema.Literal(\"user-interrupted\"),\n};\n/** A pause refers to the running lifecycle or to permission still waiting before a run. */\nexport const PendingMessagesPausedPayload = Schema.Union([\n Schema.Struct({ ...PendingMessagesPausedFields, runId: RunId }),\n Schema.Struct({ ...PendingMessagesPausedFields, runRequestId: RunRequestId }),\n]);\nexport type PendingMessagesPausedPayload = typeof PendingMessagesPausedPayload.Type;\nexport const PendingMessagesPausedEvent = durableEventSchema(\n pendingMessagesPausedEventType,\n PendingMessagesPausedPayload,\n);\nexport type PendingMessagesPausedEvent = typeof PendingMessagesPausedEvent.Type;\n\n/** Payload recorded when an assistant message is durably finalized. */\nexport const AssistantMessageCommittedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n});\nexport type AssistantMessageCommittedPayload = typeof AssistantMessageCommittedPayload.Type;\nexport const AssistantMessageCommittedEvent = durableEventSchema(\n assistantMessageCommittedEventType,\n AssistantMessageCommittedPayload,\n);\nexport type AssistantMessageCommittedEvent = typeof AssistantMessageCommittedEvent.Type;\n\n/** Payload recorded when pre-existing assistant context is imported from an external transport. */\nexport const AssistantMessageImportedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n});\nexport type AssistantMessageImportedPayload = typeof AssistantMessageImportedPayload.Type;\nexport const AssistantMessageImportedEvent = durableEventSchema(\n assistantMessageImportedEventType,\n AssistantMessageImportedPayload,\n);\nexport type AssistantMessageImportedEvent = typeof AssistantMessageImportedEvent.Type;\n\n/** Payload recorded when a partial assistant message is preserved durably. */\nexport const AssistantPartialCommittedPayload = Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n promptParts: AssistantPromptParts,\n reason: Schema.String,\n});\nexport type AssistantPartialCommittedPayload = typeof AssistantPartialCommittedPayload.Type;\nexport const AssistantPartialCommittedEvent = durableEventSchema(\n assistantPartialCommittedEventType,\n AssistantPartialCommittedPayload,\n);\nexport type AssistantPartialCommittedEvent = typeof AssistantPartialCommittedEvent.Type;\n\n/** Durable event union for message commit/queue boundaries. */\nexport const MessageEvent = Schema.Union([\n SystemMessageCommittedEvent,\n UserMessageCommittedEvent,\n SteeringMessageQueuedEvent,\n SteeringMessageCancelledEvent,\n UserMessageSubmittedEvent,\n UserMessagePromotedEvent,\n UserMessageCancelledEvent,\n MessageQueuePausedEvent,\n PendingMessagesPausedEvent,\n AssistantMessageCommittedEvent,\n AssistantMessageImportedEvent,\n AssistantPartialCommittedEvent,\n]);\nexport type MessageEvent = typeof MessageEvent.Type;\n\n/** Event type values for durable run lifecycle events. */\nexport const runStartedEventType = makeEventType(\"RunStarted\");\nexport const runCompletedEventType = makeEventType(\"RunCompleted\");\nexport const runFailedEventType = makeEventType(\"RunFailed\");\n/** @deprecated Legacy terminal retained for durable replay. Emit `RunFailed` with an interruption-coded `FailurePayload` instead. */\nexport const runInterruptedEventType = makeEventType(\"RunInterrupted\");\n\n/** Payload recorded when a run starts with its intended model selection. */\nexport const RunStartedPayload = Schema.Struct({\n runId: RunId,\n commandIds: Schema.Array(CommandId),\n modelSelection: ModelSelectionPayload,\n trace: EDARunTrace.pipe(Schema.withConstructorDefault(Effect.sync(() => makeEDARunTrace()))),\n});\nexport type RunStartedPayload = typeof RunStartedPayload.Type;\nexport const RunStartedEvent = durableEventSchema(runStartedEventType, RunStartedPayload);\nexport type RunStartedEvent = typeof RunStartedEvent.Type;\n\n/** Payload recorded when a run completes. */\nexport const RunCompletedPayload = Schema.Struct({ runId: RunId });\nexport type RunCompletedPayload = typeof RunCompletedPayload.Type;\nexport const RunCompletedEvent = durableEventSchema(runCompletedEventType, RunCompletedPayload);\nexport type RunCompletedEvent = typeof RunCompletedEvent.Type;\n\n/** Payload recorded when a run fails. */\nexport const RunFailedPayload = Schema.Struct({ runId: RunId, error: FailurePayload });\nexport type RunFailedPayload = typeof RunFailedPayload.Type;\nexport const RunFailedEvent = durableEventSchema(runFailedEventType, RunFailedPayload);\nexport type RunFailedEvent = typeof RunFailedEvent.Type;\n\n/** @deprecated Legacy payload retained for durable replay. New interruptions use `RunFailedPayload` with `error.code = \"run.interrupted\"`. */\nexport const RunInterruptedPayload = Schema.Struct({ runId: RunId, reason: Schema.String });\n/** @deprecated Use `RunFailedPayload` with interruption metadata. */\nexport type RunInterruptedPayload = typeof RunInterruptedPayload.Type;\n/** @deprecated Legacy event schema retained for durable replay; new producers emit `RunFailedEvent`. */\nexport const RunInterruptedEvent = durableEventSchema(\n runInterruptedEventType,\n RunInterruptedPayload,\n);\n/** @deprecated Use `RunFailedEvent` with interruption metadata. */\nexport type RunInterruptedEvent = typeof RunInterruptedEvent.Type;\n\n/** Durable event union for run lifecycle boundaries. */\nexport const RunEvent = Schema.Union([\n RunStartedEvent,\n RunCompletedEvent,\n RunFailedEvent,\n RunInterruptedEvent,\n]);\nexport type RunEvent = typeof RunEvent.Type;\n\n/** Event type value for the durable barrier written after real startup recovery work. */\nexport const recoveryCompletedEventType = makeEventType(\"RecoveryCompleted\");\n\n/** Explicit relationship between an interrupted run and its startup-recovery replacement. */\nexport const RecoveryContinuation = Schema.Struct({\n commandId: CommandId,\n interruptedRunId: RunId,\n replacementRunId: RunId,\n});\nexport type RecoveryContinuation = typeof RecoveryContinuation.Type;\n\n/**\n * Durable completion barrier for a startup recovery transaction that repaired\n * unfinished state. Idle runtime construction does not emit this event.\n */\nexport const RecoveryCompletedPayload = Schema.Struct({\n trigger: Schema.Literal(\"runtime-restart\"),\n continuation: Schema.optionalKey(RecoveryContinuation),\n});\nexport type RecoveryCompletedPayload = typeof RecoveryCompletedPayload.Type;\nexport const RecoveryCompletedEvent = durableEventSchema(\n recoveryCompletedEventType,\n RecoveryCompletedPayload,\n);\nexport type RecoveryCompletedEvent = typeof RecoveryCompletedEvent.Type;\n\n/** Durable facts written only by the framework startup-recovery transaction. */\nexport const RecoveryEvent = RecoveryCompletedEvent;\nexport type RecoveryEvent = typeof RecoveryEvent.Type;\n\n/** Event type values for durable turn lifecycle events. */\nexport const turnStartedEventType = makeEventType(\"TurnStarted\");\nexport const turnCompletedEventType = makeEventType(\"TurnCompleted\");\nexport const turnFailedEventType = makeEventType(\"TurnFailed\");\n/** @deprecated Legacy terminal retained for durable replay. Emit `TurnFailed` with an interruption-coded `FailurePayload` instead. */\nexport const turnStoppedEventType = makeEventType(\"TurnStopped\");\n\n/** Payload recorded when one turn starts inside a run. */\nexport const TurnStartedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inputMessageIds: Schema.optionalKey(Schema.Array(MessageId)),\n});\nexport type TurnStartedPayload = typeof TurnStartedPayload.Type;\nexport const TurnStartedEvent = durableEventSchema(turnStartedEventType, TurnStartedPayload);\nexport type TurnStartedEvent = typeof TurnStartedEvent.Type;\n\n/** Payload recorded when one turn completes. */\nexport const TurnCompletedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type TurnCompletedPayload = typeof TurnCompletedPayload.Type;\nexport const TurnCompletedEvent = durableEventSchema(turnCompletedEventType, TurnCompletedPayload);\nexport type TurnCompletedEvent = typeof TurnCompletedEvent.Type;\n\n/** Payload recorded when one turn fails. */\nexport const TurnFailedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n error: FailurePayload,\n});\nexport type TurnFailedPayload = typeof TurnFailedPayload.Type;\nexport const TurnFailedEvent = durableEventSchema(turnFailedEventType, TurnFailedPayload);\nexport type TurnFailedEvent = typeof TurnFailedEvent.Type;\n\n/** @deprecated Legacy payload retained for durable replay. New stops use `TurnFailedPayload` with `error.code = \"turn.interrupted\"`. */\nexport const TurnStoppedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n reason: Schema.String,\n});\n/** @deprecated Use `TurnFailedPayload` with interruption metadata. */\nexport type TurnStoppedPayload = typeof TurnStoppedPayload.Type;\n/** @deprecated Legacy event schema retained for durable replay; new producers emit `TurnFailedEvent`. */\nexport const TurnStoppedEvent = durableEventSchema(turnStoppedEventType, TurnStoppedPayload);\n/** @deprecated Use `TurnFailedEvent` with interruption metadata. */\nexport type TurnStoppedEvent = typeof TurnStoppedEvent.Type;\n\n/** Durable event union for turn lifecycle boundaries. */\nexport const TurnEvent = Schema.Union([\n TurnStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnStoppedEvent,\n]);\nexport type TurnEvent = typeof TurnEvent.Type;\n\n/** Event type values for durable model-inference lifecycle events. */\nexport const inferenceStartedEventType = makeEventType(\"InferenceStarted\");\nexport const inferenceCompletedEventType = makeEventType(\"InferenceCompleted\");\nexport const inferenceFailedEventType = makeEventType(\"InferenceFailed\");\n\n/** Payload recorded when one model inference starts for a turn. */\nexport const InferenceStartedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n});\nexport type InferenceStartedPayload = typeof InferenceStartedPayload.Type;\nexport const InferenceStartedEvent = durableEventSchema(\n inferenceStartedEventType,\n InferenceStartedPayload,\n);\nexport type InferenceStartedEvent = typeof InferenceStartedEvent.Type;\n\n/** Payload recorded when one model inference completes. */\nexport const InferenceCompletedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n finishReason: Schema.optionalKey(Schema.String),\n usage: Schema.optionalKey(UsagePayload),\n responseMetadata: Schema.optionalKey(Schema.Unknown),\n finishMetadata: Schema.optionalKey(Schema.Unknown),\n});\nexport type InferenceCompletedPayload = typeof InferenceCompletedPayload.Type;\nexport const InferenceCompletedEvent = durableEventSchema(\n inferenceCompletedEventType,\n InferenceCompletedPayload,\n);\nexport type InferenceCompletedEvent = typeof InferenceCompletedEvent.Type;\n\n/** Payload recorded when one model inference fails or is interrupted. */\nexport const InferenceFailedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n error: FailurePayload,\n});\nexport type InferenceFailedPayload = typeof InferenceFailedPayload.Type;\nexport const InferenceFailedEvent = durableEventSchema(\n inferenceFailedEventType,\n InferenceFailedPayload,\n);\nexport type InferenceFailedEvent = typeof InferenceFailedEvent.Type;\n\n/** Durable event union for canonical model-inference lifecycle boundaries. */\nexport const InferenceEvent = Schema.Union([\n InferenceStartedEvent,\n InferenceCompletedEvent,\n InferenceFailedEvent,\n]);\nexport type InferenceEvent = typeof InferenceEvent.Type;\n\n/** Event type values for durable tool lifecycle events. */\nexport const toolCallCreatedEventType = makeEventType(\"ToolCallCreated\");\nexport const toolCallRejectedEventType = makeEventType(\"ToolCallRejected\");\nexport const toolCallStartedEventType = makeEventType(\"ToolCallStarted\");\nexport const toolCallCompletedEventType = makeEventType(\"ToolCallCompleted\");\nexport const toolCallFailedEventType = makeEventType(\"ToolCallFailed\");\n\n/** Reason a model-requested tool call was rejected before execution. */\nexport const ToolCallRejectionReason = Schema.Literals([\"unknown-tool\", \"invalid-params\"]);\nexport type ToolCallRejectionReason = typeof ToolCallRejectionReason.Type;\n\n/** Exact synthetic tool-result feedback for a rejected model-requested tool call. */\nexport const ToolCallRejectionFeedback = Schema.Struct({\n message: Schema.String,\n reason: ToolCallRejectionReason,\n modelFeedback: Schema.NonEmptyString,\n});\nexport type ToolCallRejectionFeedback = typeof ToolCallRejectionFeedback.Type;\n\n/** Exact prompt part for a rejected model-requested tool call. */\nexport const ToolRejectionPromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(true),\n result: ToolCallRejectionFeedback,\n});\nexport type ToolRejectionPromptPart = typeof ToolRejectionPromptPart.Type;\n\n/** Exact prompt part for a successful framework-owned tool result. */\nexport const ToolSuccessPromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(false),\n result: Schema.Unknown,\n});\nexport type ToolSuccessPromptPart = typeof ToolSuccessPromptPart.Type;\n\n/** Exact prompt part for a failed framework-owned tool result. */\nexport const ToolFailurePromptPart = Schema.Struct({\n ...ToolPromptPart.fields,\n isFailure: Schema.Literal(true),\n result: FailurePayload,\n});\nexport type ToolFailurePromptPart = typeof ToolFailurePromptPart.Type;\n\n/** Payload recorded once streamed tool parameters validate and become executable. */\nexport const ToolCallCreatedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n toolCallId: ToolCallId,\n promptPart: ToolCallPromptPart,\n});\nexport type ToolCallCreatedPayload = typeof ToolCallCreatedPayload.Type;\nexport const ToolCallCreatedEvent = durableEventSchema(\n toolCallCreatedEventType,\n ToolCallCreatedPayload,\n);\nexport type ToolCallCreatedEvent = typeof ToolCallCreatedEvent.Type;\n\n/** Payload recorded when a model-requested tool call is not executable. */\nexport const ToolCallRejectedPayload = Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n inferenceId: InferenceId,\n toolCallId: ToolCallId,\n promptPart: ToolRejectionPromptPart,\n});\nexport type ToolCallRejectedPayload = typeof ToolCallRejectedPayload.Type;\nexport const ToolCallRejectedEvent = durableEventSchema(\n toolCallRejectedEventType,\n ToolCallRejectedPayload,\n);\nexport type ToolCallRejectedEvent = typeof ToolCallRejectedEvent.Type;\n\n/** Payload recorded when framework-owned tool execution starts. */\nexport const ToolCallStartedPayload = Schema.Struct({ toolCallId: ToolCallId });\nexport type ToolCallStartedPayload = typeof ToolCallStartedPayload.Type;\nexport const ToolCallStartedEvent = durableEventSchema(\n toolCallStartedEventType,\n ToolCallStartedPayload,\n);\nexport type ToolCallStartedEvent = typeof ToolCallStartedEvent.Type;\n\n/** Payload recorded when a tool call completes with a result. */\nexport const ToolCallCompletedPayload = Schema.Struct({\n toolCallId: ToolCallId,\n promptPart: ToolSuccessPromptPart,\n});\nexport type ToolCallCompletedPayload = typeof ToolCallCompletedPayload.Type;\nexport const ToolCallCompletedEvent = durableEventSchema(\n toolCallCompletedEventType,\n ToolCallCompletedPayload,\n);\nexport type ToolCallCompletedEvent = typeof ToolCallCompletedEvent.Type;\n\n/** Payload recorded when a tool call fails. */\nexport const ToolCallFailedPayload = Schema.Struct({\n toolCallId: ToolCallId,\n error: Schema.optionalKey(FailurePayload),\n promptPart: ToolFailurePromptPart,\n});\nexport type ToolCallFailedPayload = typeof ToolCallFailedPayload.Type;\nexport const ToolCallFailedEvent = durableEventSchema(\n toolCallFailedEventType,\n ToolCallFailedPayload,\n);\nexport type ToolCallFailedEvent = typeof ToolCallFailedEvent.Type;\n\n/** Durable event union for tool lifecycle boundaries. */\nexport const ToolCallEvent = Schema.Union([\n ToolCallCreatedEvent,\n ToolCallRejectedEvent,\n ToolCallStartedEvent,\n ToolCallCompletedEvent,\n ToolCallFailedEvent,\n]);\nexport type ToolCallEvent = typeof ToolCallEvent.Type;\n\n/** Event type values for durable stop-control events. */\nexport const stopTurnRequestedEventType = makeEventType(\"StopTurnRequested\");\nexport const stopTurnAppliedEventType = makeEventType(\"StopTurnApplied\");\n\n/** Payload recorded when a stop command targets active or future turn work. */\nexport const StopTurnRequestedPayload = Schema.Struct({\n commandId: CommandId,\n runId: Schema.optionalKey(RunId),\n turnId: Schema.optionalKey(TurnId),\n});\nexport type StopTurnRequestedPayload = typeof StopTurnRequestedPayload.Type;\nexport const StopTurnRequestedEvent = durableEventSchema(\n stopTurnRequestedEventType,\n StopTurnRequestedPayload,\n);\nexport type StopTurnRequestedEvent = typeof StopTurnRequestedEvent.Type;\n\n/** Payload recorded when a stop request has affected runtime work. */\nexport const StopTurnAppliedPayload = Schema.Struct({\n commandId: CommandId,\n runId: RunId,\n turnId: TurnId,\n inferenceId: Schema.optionalKey(InferenceId),\n});\nexport type StopTurnAppliedPayload = typeof StopTurnAppliedPayload.Type;\nexport const StopTurnAppliedEvent = durableEventSchema(\n stopTurnAppliedEventType,\n StopTurnAppliedPayload,\n);\nexport type StopTurnAppliedEvent = typeof StopTurnAppliedEvent.Type;\n\n/** Durable event union for stop-request lifecycle boundaries. */\nexport const StopControlEvent = Schema.Union([StopTurnRequestedEvent, StopTurnAppliedEvent]);\nexport type StopControlEvent = typeof StopControlEvent.Type;\n\n/** Event type values for durable context and compaction events. */\nexport const contextProjectedEventType = makeEventType(\"ContextProjected\");\nexport const compactionRequestedEventType = makeEventType(\"CompactionRequested\");\nexport const compactionStartedEventType = makeEventType(\"CompactionStarted\");\nexport const summaryCreatedEventType = makeEventType(\"SummaryCreated\");\nexport const compactionCompletedEventType = makeEventType(\"CompactionCompleted\");\nexport const contextRebasedEventType = makeEventType(\"ContextRebased\");\nexport const compactionFailedEventType = makeEventType(\"CompactionFailed\");\n\n/** Payload recorded when the prompt context projection advances. */\nexport const ContextProjectedPayload = Schema.Struct({\n contextVersion: ContextVersion,\n throughSeq: SequenceNumber,\n});\nexport type ContextProjectedPayload = typeof ContextProjectedPayload.Type;\nexport const ContextProjectedEvent = durableEventSchema(\n contextProjectedEventType,\n ContextProjectedPayload,\n);\nexport type ContextProjectedEvent = typeof ContextProjectedEvent.Type;\n\n/** Payload recorded when compaction is requested for a durable range. */\nexport const CompactionRequestedPayload = Schema.Struct({\n compactionId: CompactionId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n});\nexport type CompactionRequestedPayload = typeof CompactionRequestedPayload.Type;\nexport const CompactionRequestedEvent = durableEventSchema(\n compactionRequestedEventType,\n CompactionRequestedPayload,\n);\nexport type CompactionRequestedEvent = typeof CompactionRequestedEvent.Type;\n\n/** Payload recorded when compaction starts. */\nexport const CompactionStartedPayload = Schema.Struct({ compactionId: CompactionId });\nexport type CompactionStartedPayload = typeof CompactionStartedPayload.Type;\nexport const CompactionStartedEvent = durableEventSchema(\n compactionStartedEventType,\n CompactionStartedPayload,\n);\nexport type CompactionStartedEvent = typeof CompactionStartedEvent.Type;\n\n/** Payload recorded when a summary artifact is created. */\nexport const SummaryCreatedPayload = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n summary: Schema.Unknown,\n});\nexport type SummaryCreatedPayload = typeof SummaryCreatedPayload.Type;\nexport const SummaryCreatedEvent = durableEventSchema(\n summaryCreatedEventType,\n SummaryCreatedPayload,\n);\nexport type SummaryCreatedEvent = typeof SummaryCreatedEvent.Type;\n\n/** Payload recorded when compaction completes. */\nexport const CompactionCompletedPayload = Schema.Struct({\n compactionId: CompactionId,\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type CompactionCompletedPayload = typeof CompactionCompletedPayload.Type;\nexport const CompactionCompletedEvent = durableEventSchema(\n compactionCompletedEventType,\n CompactionCompletedPayload,\n);\nexport type CompactionCompletedEvent = typeof CompactionCompletedEvent.Type;\n\n/** Payload recorded when durable context is rebased onto a summary. */\nexport const ContextRebasedPayload = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n contextVersion: ContextVersion,\n retainedFromContextSeq: SequenceNumber,\n});\nexport type ContextRebasedPayload = typeof ContextRebasedPayload.Type;\nexport const ContextRebasedEvent = durableEventSchema(\n contextRebasedEventType,\n ContextRebasedPayload,\n);\nexport type ContextRebasedEvent = typeof ContextRebasedEvent.Type;\n\n/** Payload recorded when compaction fails. */\nexport const CompactionFailedPayload = Schema.Struct({\n compactionId: CompactionId,\n error: FailurePayload,\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type CompactionFailedPayload = typeof CompactionFailedPayload.Type;\nexport const CompactionFailedEvent = durableEventSchema(\n compactionFailedEventType,\n CompactionFailedPayload,\n);\nexport type CompactionFailedEvent = typeof CompactionFailedEvent.Type;\n\n/** Durable event union for context projection and compaction boundaries. */\nexport const ContextAndCompactionEvent = Schema.Union([\n ContextProjectedEvent,\n CompactionRequestedEvent,\n CompactionStartedEvent,\n SummaryCreatedEvent,\n CompactionCompletedEvent,\n ContextRebasedEvent,\n CompactionFailedEvent,\n]);\nexport type ContextAndCompactionEvent = typeof ContextAndCompactionEvent.Type;\n\n/** Event type values for durable BaseState lifecycle events. */\nexport const baseStateRequestedEventType = makeEventType(\"BaseStateRequested\");\nexport const baseStateCreatedEventType = makeEventType(\"BaseStateCreated\");\nexport const baseStateFailedEventType = makeEventType(\"BaseStateFailed\");\n\n/** Payload recorded when durable BaseState generation is requested. */\nexport const BaseStateRequestedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n requestedThroughSeq: SequenceNumber,\n});\nexport type BaseStateRequestedPayload = typeof BaseStateRequestedPayload.Type;\nexport const BaseStateRequestedEvent = durableEventSchema(\n baseStateRequestedEventType,\n BaseStateRequestedPayload,\n);\nexport type BaseStateRequestedEvent = typeof BaseStateRequestedEvent.Type;\n\n/** Payload recorded when a BaseState snapshot is created. */\nexport const BaseStateCreatedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n coversThroughSeq: SequenceNumber,\n});\nexport type BaseStateCreatedPayload = typeof BaseStateCreatedPayload.Type;\nexport const BaseStateCreatedEvent = durableEventSchema(\n baseStateCreatedEventType,\n BaseStateCreatedPayload,\n);\nexport type BaseStateCreatedEvent = typeof BaseStateCreatedEvent.Type;\n\n/** Payload recorded when BaseState generation fails. */\nexport const BaseStateFailedPayload = Schema.Struct({\n baseStateId: BaseStateId,\n error: FailurePayload,\n});\nexport type BaseStateFailedPayload = typeof BaseStateFailedPayload.Type;\nexport const BaseStateFailedEvent = durableEventSchema(\n baseStateFailedEventType,\n BaseStateFailedPayload,\n);\nexport type BaseStateFailedEvent = typeof BaseStateFailedEvent.Type;\n\n/** Durable event union for BaseState lifecycle boundaries. */\nexport const BaseStateEvent = Schema.Union([\n BaseStateRequestedEvent,\n BaseStateCreatedEvent,\n BaseStateFailedEvent,\n]);\nexport type BaseStateEvent = typeof BaseStateEvent.Type;\n\n/** Retained pre-inference lifecycle facts. Attempt identities remain unchanged in storage and on wire. */\nexport const LegacyTurnAttemptStartedEvent = durableEventSchema(\n makeEventType(\"TurnAttemptStarted\"),\n Schema.Struct({ runId: RunId, turnId: TurnId, attemptId: InferenceId }),\n);\n\n/** A successful historical provider request; multiple attempts can belong to one historical turn. */\nexport const LegacyTurnAttemptCompletedEvent = durableEventSchema(\n makeEventType(\"TurnAttemptCompleted\"),\n Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n attemptId: InferenceId,\n finishReason: Schema.optionalKey(Schema.String),\n usage: Schema.optionalKey(UsagePayload),\n responseMetadata: Schema.optionalKey(Schema.Unknown),\n finishMetadata: Schema.optionalKey(Schema.Unknown),\n }),\n);\n\n/** Historical assistant content links to the original attempt rather than a renamed event. */\nexport const LegacyAssistantMessageCommittedEvent = durableEventSchema(\n assistantMessageCommittedEventType,\n Schema.Struct({\n messageId: MessageId,\n runId: RunId,\n turnId: TurnId,\n attemptId: InferenceId,\n promptParts: AssistantPromptParts,\n }),\n);\n\n/** Historical tool decisions retain their attempt and turn references during replay. */\nexport const LegacyToolCallCreatedEvent = durableEventSchema(\n toolCallCreatedEventType,\n Schema.Struct({\n runId: RunId,\n turnId: TurnId,\n attemptId: InferenceId,\n toolCallId: ToolCallId,\n promptPart: ToolCallPromptPart,\n }),\n);\n\n/** Explicitly supported historical shapes; unknown event types and versions remain errors. */\nexport const LegacyAttemptEvent = Schema.Union([\n LegacyTurnAttemptStartedEvent,\n LegacyTurnAttemptCompletedEvent,\n LegacyAssistantMessageCommittedEvent,\n LegacyToolCallCreatedEvent,\n]);\n\n/**\n * Interprets retained attempt references solely for domain folding. It never changes the stored\n * envelope, stream position, or wire event. Historical turns retain all of their attempts;\n * this deliberately does not split turns or manufacture lifecycle events.\n */\nexport const interpretLegacyAttemptForReduction = (\n event: EDADurableEvent,\n): CurrentEDADurableEvent => {\n if (event.type === \"TurnAttemptStarted\") {\n return {\n ...event,\n type: inferenceStartedEventType,\n payload: { ...event.payload, inferenceId: event.payload.attemptId },\n };\n }\n if (event.type === \"TurnAttemptCompleted\") {\n return {\n ...event,\n type: inferenceCompletedEventType,\n payload: { ...event.payload, inferenceId: event.payload.attemptId },\n };\n }\n if (Schema.is(AssistantMessageCommittedEvent)(event) || Schema.is(ToolCallCreatedEvent)(event)) {\n return event;\n }\n if (isLegacyAssistant(event)) {\n return { ...event, payload: { ...event.payload, inferenceId: event.payload.attemptId } };\n }\n if (isLegacyToolCall(event)) {\n return { ...event, payload: { ...event.payload, inferenceId: event.payload.attemptId } };\n }\n return event;\n};\n\nconst isLegacyAssistant = (\n event: EDADurableEvent,\n): event is typeof LegacyAssistantMessageCommittedEvent.Type =>\n event.type === assistantMessageCommittedEventType && \"attemptId\" in event.payload;\nconst isLegacyToolCall = (\n event: EDADurableEvent,\n): event is typeof LegacyToolCallCreatedEvent.Type =>\n event.type === toolCallCreatedEventType && \"attemptId\" in event.payload;\n\n/** Built-in durable event union for framework-owned session facts, including retained historical schemas. */\nexport const CurrentEDADurableEvent = Schema.Union([\n SessionConfiguredEvent,\n RunSchedulingEvent,\n CommandEvent,\n MessageEvent,\n RunEvent,\n RecoveryEvent,\n TurnEvent,\n InferenceEvent,\n ToolCallEvent,\n StopControlEvent,\n ContextAndCompactionEvent,\n BaseStateEvent,\n]);\nexport type CurrentEDADurableEvent = typeof CurrentEDADurableEvent.Type;\n/** Retained historical facts remain readable without rewriting the event journal. */\nexport const EDADurableEvent = Schema.Union([LegacyAttemptEvent, CurrentEDADurableEvent]);\nexport type EDADurableEvent = typeof EDADurableEvent.Type;\n\n/** Current V1 framework durable event schema. Future versions route beside this alias. */\nexport const EDADurableEventV1 = EDADurableEvent;\nexport type EDADurableEventV1 = typeof EDADurableEventV1.Type;\n\n/** Decode one framework-owned durable event through the namespace/type/version router. */\nexport const decodeUnknownEDADurableEventSync = (input: unknown): EDADurableEvent => {\n return decodeFrameworkEnvelope(Schema.decodeUnknownSync(DurableEventEnvelope)(input));\n};\n\nconst decodeFrameworkEnvelope = (envelope: DurableEventEnvelope): EDADurableEvent => {\n if (envelope.namespace !== effectDurableAgentNamespace) {\n throw new Error(\n `EDADurableEvent decoder only accepts namespace ${effectDurableAgentNamespace}; received ${envelope.namespace}`,\n );\n }\n\n switch (envelope.schemaVersion) {\n case schemaV1:\n return Schema.decodeUnknownSync(EDADurableEventV1)(envelope, {\n onExcessProperty: \"preserve\",\n });\n default:\n throw new Error(\n `Unsupported EDA durable event schemaVersion ${envelope.schemaVersion} for ${envelope.type}`,\n );\n }\n};\n\n/** Effectful V1+ router for untrusted framework-owned durable event boundaries. */\nexport const decodeUnknownEDADurableEvent = (\n input: unknown,\n): Effect.Effect<EDADurableEvent, unknown> =>\n Effect.try({\n try: () => decodeUnknownEDADurableEventSync(input),\n catch: (error) => error,\n });\n\n/** Decoded internal facts distinguish framework events from explicitly opaque foreign envelopes. */\nexport const DecodedDurableEvent = Schema.Union([EDADurableEvent, ForeignDurableEvent]);\nexport type DecodedDurableEvent = typeof DecodedDurableEvent.Type;\n\n/** Restore the original envelope at persistence and protocol boundaries. */\nexport const durableEventEnvelope = (\n event: DecodedDurableEvent | DurableEventEnvelope,\n): DurableEventEnvelope =>\n \"envelope\" in event && Schema.is(ForeignDurableEvent)(event) ? event.envelope : event;\n\n/** Decode a durable envelope once at the store boundary, preserving foreign namespaces opaquely. */\nexport const decodeDurableEventSync = (input: unknown): DecodedDurableEvent => {\n const envelope = Schema.decodeUnknownSync(DurableEventEnvelope)(input);\n if (envelope.namespace === effectDurableAgentNamespace) return decodeFrameworkEnvelope(envelope);\n return { ...envelope, namespace: \"__foreign\", type: \"Foreign\", _tag: \"Foreign\", envelope };\n};\n"],"mappings":";;;;;;;;;;AAWA,MAAa,sBACX,MACA,YAEA,OAAO,OAAO;CACZ,GAAG,qBAAqB;CACxB,WAAW,OAAO,QAAQ,2BAA2B;CACrD,MAAM,OAAO,QAAQ,IAAI;CACzB,eAAe,OAAO,QAAQ,QAAQ;CACtC;AACF,CAAC;;AAGH,MAAa,wBACX,MACA,YAEA,OAAO,OAAO;CACZ,GAAG,uBAAuB;CAC1B,WAAW,OAAO,QAAQ,2BAA2B;CACrD,MAAM,OAAO,QAAQ,IAAI;CACzB,eAAe,OAAO,QAAQ,QAAQ;CACtC;AACF,CAAC;;;;ACGH,MAAa,6BAA6B,cAAc,mBAAmB;AAC3E,MAAa,yBAAyB,mBACpC,4BACA,OAAO,OAAO,EAAE,gBAAgB,sBAAsB,CAAC,CACzD;;AAIA,MAAa,2BAA2B,cAAc,iBAAiB;AACvE,MAAa,0BAA0B,cAAc,gBAAgB;AACrE,MAAa,4BAA4B,cAAc,kBAAkB;AACzE,MAAa,yBAAyB,cAAc,eAAe;AACnE,MAAa,4BAA4B,cAAc,kBAAkB;;AAGzE,MAAa,yBAAyB,OAAO,OAAO,EAAE,SAAS,WAAW,CAAC;AAE3E,MAAa,uBAAuB,mBAClC,0BACA,sBACF;;AAIA,MAAa,wBAAwB,OAAO,OAAO,EAAE,WAAW,UAAU,CAAC;AAE3E,MAAa,sBAAsB,mBACjC,yBACA,qBACF;;AAIA,MAAa,0BAA0B,OAAO,OAAO,EAAE,WAAW,UAAU,CAAC;AAE7E,MAAa,wBAAwB,mBACnC,2BACA,uBACF;;AAIA,MAAa,uBAAuB,OAAO,OAAO;CAAE,WAAW;CAAW,OAAO;AAAe,CAAC;AAEjG,MAAa,qBAAqB,mBAAmB,wBAAwB,oBAAoB;;AAIjG,MAAa,0BAA0B,OAAO,OAAO;CACnD,WA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js","names":[],"sources":["../src/domain/assert-never.ts","../src/domain/reduced-state.ts"],"sourcesContent":["const formatNeverValue = (value: never): string => {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\n/** Build the defect used when an exhaustive switch receives an impossible value. */\nexport const assertNeverError = (value: never, context: string) =>\n new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);\n\n/** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */\nexport const assertNever = (value: never, context: string): never => {\n throw assertNeverError(value, context);\n};\n","import { ReducedStateSchema } from \"./reduced-state-schema\";\nimport { RunSchedulingRequest, RunSchedulingRequestRecord } from \"./run-scheduling\";\nimport { interpretLegacyAttemptForReduction } from \"../types/events/durable\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Prompt from \"effect/unstable/ai/Prompt\";\nimport { addModelUsage, TokenConsumptionState } from \"./model-usage\";\nexport { type TokenUsageTotals, TokenConsumptionState } from \"./model-usage\";\n\nimport { assertNever } from \"./assert-never\";\nimport { deriveCommandQueues, emptyCommandQueues } from \"./command-queues\";\nimport {\n InferenceId,\n CommandId,\n CompactionId,\n ContextVersion,\n MessageId,\n RunId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n assistantMessageCommittedEventType,\n assistantMessageImportedEventType,\n assistantPartialCommittedEventType,\n baseStateCreatedEventType,\n baseStateFailedEventType,\n baseStateRequestedEventType,\n commandAdmittedEventType,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n commandStartedEventType,\n compactionCompletedEventType,\n compactionFailedEventType,\n compactionRequestedEventType,\n compactionStartedEventType,\n contextProjectedEventType,\n effectDurableAgentNamespace,\n contextRebasedEventType,\n inferenceCompletedEventType,\n inferenceFailedEventType,\n inferenceStartedEventType,\n runCompletedEventType,\n runFailedEventType,\n runInterruptedEventType,\n runStartedEventType,\n runSchedulingRequestedEventType,\n runSchedulingDeliveredEventType,\n runSchedulingInvalidatedEventType,\n runSchedulingGrantedEventType,\n sessionConfiguredEventType,\n stopTurnAppliedEventType,\n stopTurnRequestedEventType,\n steeringMessageCancelledEventType,\n steeringMessageQueuedEventType,\n userMessageSubmittedEventType,\n userMessagePromotedEventType,\n userMessageCancelledEventType,\n messageQueuePausedEventType,\n pendingMessagesPausedEventType,\n recoveryCompletedEventType,\n summaryCreatedEventType,\n systemMessageCommittedEventType,\n toolCallCompletedEventType,\n toolCallCreatedEventType,\n toolCallFailedEventType,\n toolCallRejectedEventType,\n toolCallStartedEventType,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n userMessageCommittedEventType,\n} from \"../types/events\";\nimport { type EDACommand as EDACommandValue, type UserMessageContent } from \"../types/commands\";\nimport type {\n AssistantMessageContent,\n EDAEventTrace,\n EDARunTrace,\n FailurePayload,\n ProviderPartId,\n RecoveryContinuation,\n SystemPromptText,\n ToolName,\n UsagePayload,\n ModelSelectionPayload,\n} from \"../types/events\";\nimport type { CommittedDurableEvent } from \"../services/session-store\";\n\n/** Failure payload paired with the durable sequence that recorded it. */\nexport type LifecycleFailure = {\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n};\n\n/** Terminal command state folded from command lifecycle events. */\nexport type CommandTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Cancelled\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable command lifecycle projection used for scheduling and recovery. */\nexport interface CommandRecord {\n readonly commandId: CommandId;\n readonly command?: EDACommandValue;\n readonly admittedSeq?: SequenceNumber;\n readonly admissionTrace?: EDAEventTrace;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: CommandTerminal;\n}\n\n/** Terminal run state folded from run lifecycle events. */\nexport type RunTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Interrupted\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Common wall-clock lifecycle timing folded from durable event envelopes. */\nexport interface LifecycleTiming {\n readonly startedAtMs?: number;\n readonly terminalAtMs?: number;\n readonly durationMs?: number;\n}\n\n/** Durable run lifecycle projection tying one run to its owning command ids. */\nexport interface RunRecord extends LifecycleTiming {\n readonly modelSelection?: ModelSelectionPayload;\n readonly runId: RunId;\n readonly commandIds: ReadonlyArray<CommandId>;\n readonly startedSeq: SequenceNumber;\n readonly trace: EDARunTrace;\n readonly terminal?: RunTerminal;\n}\n\n/** Terminal turn state folded from turn lifecycle events. */\nexport type TurnTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload }\n | { readonly _tag: \"Stopped\"; readonly seq: SequenceNumber; readonly reason: string };\n\n/** Durable turn lifecycle projection nested under a run. */\nexport interface TurnRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: TurnTerminal;\n}\n\n/** Terminal inference state folded from inference lifecycle events. */\nexport type InferenceTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber; readonly usage?: UsagePayload }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable model-inference lifecycle projection nested under a turn. */\nexport interface InferenceRecord extends LifecycleTiming {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly startedSeq: SequenceNumber;\n readonly terminal?: InferenceTerminal;\n}\n\n/** Durable decision produced after a model inference seals final tool calls. */\nexport type ToolDecision =\n | {\n readonly _tag: \"Created\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly params: unknown;\n readonly providerExecuted: boolean;\n readonly promptPart?: Prompt.ToolCallPart;\n }\n | {\n readonly _tag: \"Rejected\";\n readonly seq: SequenceNumber;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly providerPartId: ProviderPartId;\n readonly toolName: ToolName;\n readonly reason: \"unknown-tool\" | \"invalid-params\";\n readonly modelFeedback: string;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Terminal framework-owned tool-call execution state. */\nexport type ToolTerminal =\n | {\n readonly _tag: \"Completed\";\n readonly seq: SequenceNumber;\n readonly result: unknown;\n readonly promptPart?: Prompt.ToolResultPart;\n }\n | {\n readonly _tag: \"Failed\";\n readonly seq: SequenceNumber;\n readonly error: FailurePayload;\n readonly promptPart?: Prompt.ToolResultPart;\n };\n\n/** Durable tool-call projection from decision through execution terminal. */\nexport interface ToolCallRecord extends LifecycleTiming {\n readonly toolCallId: ToolCallId;\n readonly decision?: ToolDecision;\n readonly startedSeq?: SequenceNumber;\n readonly terminal?: ToolTerminal;\n}\n\n/** Durable message-like facts folded from the event log. */\nexport type MessageRecord =\n | {\n readonly _tag: \"System\";\n readonly messageId: MessageId;\n readonly content: SystemPromptText;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"User\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n /** Present for admission-time message entities; absent on legacy committed users. */\n readonly requestedDisposition?: \"queue\" | \"steer\";\n readonly disposition?: \"queue\" | \"steer\";\n readonly promotedSeq?: SequenceNumber;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n }\n | {\n readonly _tag: \"Steering\";\n readonly messageId: MessageId;\n readonly commandId: CommandId;\n readonly runId: RunId;\n readonly content: UserMessageContent;\n readonly createdAtMs?: number;\n readonly seq: SequenceNumber;\n readonly promotedSeq?: SequenceNumber;\n readonly consumedSeq?: SequenceNumber;\n readonly consumedTurnId?: TurnId;\n readonly cancelledSeq?: SequenceNumber;\n readonly cancelledByCommandId?: CommandId;\n readonly cancellationReason?: string;\n readonly pausedSeq?: SequenceNumber;\n readonly pausedByCommandId?: CommandId;\n }\n | {\n readonly _tag: \"Assistant\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n /** True when the assistant message originated outside this EDA session. */\n readonly imported?: true;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly seq: SequenceNumber;\n }\n | {\n readonly _tag: \"AssistantPartial\";\n readonly messageId: MessageId;\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId: InferenceId;\n readonly content: AssistantMessageContent;\n readonly createdAtMs?: number;\n readonly promptParts?: ReadonlyArray<Prompt.AssistantMessagePart>;\n readonly reason: string;\n readonly seq: SequenceNumber;\n };\n\n/** Terminal compaction state folded from compaction lifecycle events. */\nexport type CompactionTerminal =\n | { readonly _tag: \"Completed\"; readonly seq: SequenceNumber }\n | { readonly _tag: \"Failed\"; readonly seq: SequenceNumber; readonly error: FailurePayload };\n\n/** Durable compaction lifecycle projection and its produced summary cursor. */\nexport interface CompactionRecord {\n readonly compactionId: CompactionId;\n readonly requestedSeq?: SequenceNumber;\n readonly startedSeq?: SequenceNumber;\n readonly summaryCreatedSeq?: SequenceNumber;\n readonly summaryId?: SummaryId;\n readonly sourceFromSeq?: SequenceNumber;\n readonly sourceToSeq?: SequenceNumber;\n readonly rebasedSeq?: SequenceNumber;\n readonly contextVersion?: ContextVersion;\n readonly terminal?: CompactionTerminal;\n}\n\n/** Current model-context version and summary selected by compaction. */\nexport interface ContextRecord {\n readonly version: ContextVersion;\n readonly currentSummaryId?: SummaryId;\n}\n\n/** Durable StopTurn request and the lifecycle boundary it eventually applied to. */\nexport interface StopRequestRecord {\n readonly commandId: CommandId;\n readonly requestedSeq: SequenceNumber;\n readonly requestedRunId?: RunId;\n readonly requestedTurnId?: TurnId;\n readonly appliedSeq?: SequenceNumber;\n readonly appliedRunId?: RunId;\n readonly appliedTurnId?: TurnId;\n readonly appliedInferenceId?: InferenceId;\n}\n\n/** Admitted command that has not yet crossed the `CommandStarted` boundary. */\nexport interface PendingCommand {\n /** Lifecycle ID for the admitted command. */\n readonly commandId: CommandId;\n /** Typed command payload admitted durably. */\n readonly command: EDACommandValue;\n /** Admission sequence used for deterministic FIFO/control ordering. */\n readonly admittedSeq: SequenceNumber;\n /** Trace context captured at the durable command admission boundary. */\n readonly admissionTrace?: EDAEventTrace;\n}\n\n/** Started command without a terminal command boundary, optionally tied to an open run. */\nexport interface ActiveCommandEvidence {\n readonly commandId: CommandId;\n readonly runId?: RunId;\n}\n\n/** Active run/turn/inference identity derived from unfinished lifecycle records. */\nexport type ActiveTurnIdentity = {\n readonly runId: RunId;\n readonly turnId: TurnId;\n readonly inferenceId?: InferenceId;\n};\n\n/** Canonical durable replay product used by queries, recovery, and scheduling. */\nexport type ReducedState = typeof ReducedStateSchema.Type;\n\n/** Durable recovery continuation plus the sequence of its completion barrier. */\nexport interface RecoveryContinuationRecord extends RecoveryContinuation {\n readonly seq: SequenceNumber;\n}\n\n/** Unfinished lifecycle records requiring deterministic startup recovery. */\nexport interface RecoverableWork {\n readonly activeCommands: ReadonlyArray<CommandRecord>;\n readonly activeRuns: ReadonlyArray<RunRecord>;\n readonly activeTurns: ReadonlyArray<TurnRecord>;\n readonly activeInferences: ReadonlyArray<InferenceRecord>;\n readonly openToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly runningToolCalls: ReadonlyArray<ToolCallRecord>;\n readonly pendingStopRequests: ReadonlyArray<StopRequestRecord>;\n readonly openCompactions: ReadonlyArray<CompactionRecord>;\n}\n\nconst emptyTokenConsumptionState: TokenConsumptionState = {\n byModel: [],\n};\n\n/** Empty durable replay state before any session event has committed. */\nexport const initialReducedState: ReducedState = {\n lastSeq: SequenceNumber.make(0),\n commands: new Map(),\n runs: new Map(),\n recoveryContinuations: new Map(),\n turns: new Map(),\n inferences: new Map(),\n toolCalls: new Map(),\n messages: new Map(),\n stopRequests: new Map(),\n compactions: new Map(),\n context: { version: ContextVersion.make(0) },\n tokenConsumption: emptyTokenConsumptionState,\n commandQueues: emptyCommandQueues,\n};\n\n/** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */\nexport const frameworkReducedStateReducerName = \"_eda.framework.reduced-state\";\n\n/** Schema version for the framework-owned `ReducedState` checkpoint payload. */\nexport const frameworkReducedStateReducerSchemaVersion = 7;\n\n/** JSON payload stored for the framework-owned reduced-state reducer checkpoint. */\nexport type ReducedStateCheckpointCommandRecord = Omit<CommandRecord, \"command\">;\n\ntype SystemMessageRecord = Extract<MessageRecord, { readonly _tag: \"System\" }>;\ntype UserMessageRecord = Extract<MessageRecord, { readonly _tag: \"User\" }>;\ntype SteeringMessageRecord = Extract<MessageRecord, { readonly _tag: \"Steering\" }>;\ntype AssistantMessageRecord = Extract<MessageRecord, { readonly _tag: \"Assistant\" }>;\ntype AssistantPartialMessageRecord = Extract<MessageRecord, { readonly _tag: \"AssistantPartial\" }>;\n\nexport type ReducedStateCheckpointMessageRecord =\n | Omit<SystemMessageRecord, \"content\">\n | Omit<UserMessageRecord, \"content\">\n | Omit<SteeringMessageRecord, \"content\">\n | Omit<AssistantMessageRecord, \"content\" | \"promptParts\">\n | Omit<AssistantPartialMessageRecord, \"content\" | \"promptParts\">;\n\ntype CreatedToolDecision = Extract<ToolDecision, { readonly _tag: \"Created\" }>;\ntype RejectedToolDecision = Extract<ToolDecision, { readonly _tag: \"Rejected\" }>;\ntype CompletedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Completed\" }>;\ntype FailedToolTerminal = Extract<ToolTerminal, { readonly _tag: \"Failed\" }>;\n\nexport type ReducedStateCheckpointToolDecision =\n | Omit<CreatedToolDecision, \"params\" | \"promptPart\">\n | Omit<RejectedToolDecision, \"promptPart\">;\n\nexport type ReducedStateCheckpointToolTerminal =\n | Omit<CompletedToolTerminal, \"result\" | \"promptPart\">\n | Omit<FailedToolTerminal, \"error\" | \"promptPart\">;\n\nexport interface ReducedStateCheckpointToolCallRecord extends Omit<\n ToolCallRecord,\n \"decision\" | \"terminal\"\n> {\n readonly decision?: ReducedStateCheckpointToolDecision;\n readonly terminal?: ReducedStateCheckpointToolTerminal;\n}\n\nexport interface ReducedStateCheckpointPayload {\n readonly runSchedulingRequest?: RunSchedulingRequestRecord;\n readonly modelSelection?: ModelSelectionPayload;\n readonly lastSeq: SequenceNumber;\n readonly commands: ReadonlyArray<readonly [CommandId, ReducedStateCheckpointCommandRecord]>;\n readonly runs: ReadonlyArray<readonly [RunId, RunRecord]>;\n readonly recoveryContinuations?: ReadonlyArray<readonly [RunId, RecoveryContinuationRecord]>;\n readonly turns: ReadonlyArray<readonly [TurnId, TurnRecord]>;\n readonly inferences: ReadonlyArray<readonly [InferenceId, InferenceRecord]>;\n readonly toolCalls: ReadonlyArray<readonly [ToolCallId, ReducedStateCheckpointToolCallRecord]>;\n readonly messages: ReadonlyArray<readonly [MessageId, ReducedStateCheckpointMessageRecord]>;\n readonly stopRequests: ReadonlyArray<readonly [CommandId, StopRequestRecord]>;\n readonly compactions: ReadonlyArray<readonly [CompactionId, CompactionRecord]>;\n readonly context: ContextRecord;\n readonly tokenConsumption?: TokenConsumptionState;\n}\n\n/** Encode the framework reducer state into a pointer-based JSON-safe checkpoint payload. */\nexport const encodeReducedStateCheckpoint = (\n state: ReducedState,\n): ReducedStateCheckpointPayload => ({\n lastSeq: state.lastSeq,\n ...(state.runSchedulingRequest === undefined\n ? {}\n : { runSchedulingRequest: state.runSchedulingRequest }),\n ...(state.modelSelection === undefined ? {} : { modelSelection: state.modelSelection }),\n commands: Array.from(state.commands.entries()).map(([commandId, record]) => [\n commandId,\n encodeCheckpointCommandRecord(record),\n ]),\n runs: Array.from(state.runs.entries()),\n recoveryContinuations: Array.from(state.recoveryContinuations.entries()),\n turns: Array.from(state.turns.entries()),\n inferences: Array.from(state.inferences.entries()),\n toolCalls: Array.from(state.toolCalls.entries()).map(([toolCallId, record]) => [\n toolCallId,\n encodeCheckpointToolCallRecord(record),\n ]),\n messages: Array.from(state.messages.entries()).map(([messageId, record]) => [\n messageId,\n encodeCheckpointMessageRecord(record),\n ]),\n stopRequests: Array.from(state.stopRequests.entries()),\n compactions: Array.from(state.compactions.entries()),\n context: state.context,\n tokenConsumption: state.tokenConsumption,\n});\n\n/** Event-log positions required to hydrate a pointer-based framework checkpoint. */\nexport const reducedStateCheckpointEventSeqs = (\n payload: unknown,\n): ReadonlyArray<SequenceNumber> => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const seqs: Array<SequenceNumber> = [];\n for (const [, record] of checkpoint.commands ?? []) {\n if (record.admittedSeq !== undefined) {\n seqs.push(record.admittedSeq);\n }\n }\n for (const [, record] of checkpoint.messages ?? []) {\n seqs.push(record.seq);\n }\n for (const [, record] of checkpoint.toolCalls ?? []) {\n if (record.decision !== undefined) {\n seqs.push(record.decision.seq);\n }\n if (\n record.terminal !== undefined &&\n (record.terminal._tag === \"Completed\" || record.terminal._tag === \"Failed\")\n ) {\n seqs.push(record.terminal.seq);\n }\n }\n return uniqueSequenceNumbers(seqs);\n};\n\n/** Decode the framework reducer checkpoint and rebuild derived scheduler queues. */\nexport const decodeReducedStateCheckpoint = (\n payload: unknown,\n referencedEvents: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n const checkpoint = payload as ReducedStateCheckpointPayload;\n const eventsBySeq = committedEventMapBySeq(referencedEvents);\n const commands = decodeCheckpointCommandRecords(checkpoint.commands ?? [], eventsBySeq);\n const runs = new Map(checkpoint.runs ?? []);\n const messages = decodeCheckpointMessageRecords(checkpoint.messages ?? [], eventsBySeq);\n return {\n lastSeq: SequenceNumber.make(Number(checkpoint.lastSeq ?? 0)),\n ...(checkpoint.runSchedulingRequest === undefined\n ? {}\n : {\n runSchedulingRequest: Schema.decodeUnknownSync(RunSchedulingRequestRecord)(\n checkpoint.runSchedulingRequest,\n ),\n }),\n ...(checkpoint.modelSelection === undefined\n ? {}\n : { modelSelection: checkpoint.modelSelection }),\n commands,\n runs,\n recoveryContinuations: new Map(checkpoint.recoveryContinuations ?? []),\n turns: new Map(checkpoint.turns ?? []),\n inferences: new Map(checkpoint.inferences ?? []),\n toolCalls: decodeCheckpointToolCallRecords(checkpoint.toolCalls ?? [], eventsBySeq),\n messages,\n stopRequests: new Map(checkpoint.stopRequests ?? []),\n compactions: new Map(checkpoint.compactions ?? []),\n context: checkpoint.context ?? { version: ContextVersion.make(0) },\n tokenConsumption: decodeTokenConsumptionState(checkpoint.tokenConsumption),\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\nconst encodeCheckpointCommandRecord = (\n record: CommandRecord,\n): ReducedStateCheckpointCommandRecord => {\n const { command: _command, ...checkpoint } = record;\n return checkpoint;\n};\n\nconst encodeCheckpointMessageRecord = (\n record: MessageRecord,\n): ReducedStateCheckpointMessageRecord => {\n switch (record._tag) {\n case \"System\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"User\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Steering\": {\n const { content: _content, ...checkpoint } = record;\n return checkpoint;\n }\n case \"Assistant\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n case \"AssistantPartial\": {\n const { content: _content, promptParts: _promptParts, ...checkpoint } = record;\n return checkpoint;\n }\n default:\n return assertNever(record, \"checkpoint message record\");\n }\n};\n\nconst encodeCheckpointToolCallRecord = (\n record: ToolCallRecord,\n): ReducedStateCheckpointToolCallRecord => ({\n toolCallId: record.toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: encodeCheckpointToolDecision(record.decision) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: encodeCheckpointToolTerminal(record.terminal) }),\n});\n\nconst encodeCheckpointToolDecision = (\n decision: ToolDecision,\n): ReducedStateCheckpointToolDecision => {\n switch (decision._tag) {\n case \"Created\": {\n const { params: _params, promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n case \"Rejected\": {\n const { promptPart: _promptPart, ...checkpoint } = decision;\n return checkpoint;\n }\n default:\n return assertNever(decision, \"checkpoint tool decision\");\n }\n};\n\nconst encodeCheckpointToolTerminal = (\n terminal: ToolTerminal,\n): ReducedStateCheckpointToolTerminal => {\n switch (terminal._tag) {\n case \"Completed\": {\n const { result: _result, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n case \"Failed\": {\n const { error: _error, promptPart: _promptPart, ...checkpoint } = terminal;\n return checkpoint;\n }\n default:\n return assertNever(terminal, \"checkpoint tool terminal\");\n }\n};\n\nconst decodeCheckpointCommandRecords = (\n records: ReducedStateCheckpointPayload[\"commands\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<CommandId, CommandRecord> =>\n new Map(\n records.map(([commandId, record]) => {\n if (record.admittedSeq === undefined) {\n return [commandId, record];\n }\n const admitted = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.admittedSeq,\n commandAdmittedEventType,\n ).commands.get(commandId);\n if (admitted?.command === undefined) {\n throw new Error(`Checkpoint command ${commandId} missing admission payload`);\n }\n return [commandId, { ...record, command: admitted.command }];\n }),\n );\n\nconst decodeCheckpointMessageRecords = (\n records: ReducedStateCheckpointPayload[\"messages\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<MessageId, MessageRecord> =>\n new Map(\n records.map(([messageId, record]) => {\n const message = reduceSingleCheckpointEvent(\n eventsBySeq,\n record.seq,\n checkpointMessageEventType(record),\n ).messages.get(messageId);\n if (message === undefined) {\n throw new Error(`Checkpoint message ${messageId} missing message payload`);\n }\n return [messageId, { ...message, ...record } as MessageRecord];\n }),\n );\n\nconst decodeCheckpointToolCallRecords = (\n records: ReducedStateCheckpointPayload[\"toolCalls\"],\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ReadonlyMap<ToolCallId, ToolCallRecord> =>\n new Map(\n records.map(([toolCallId, record]) => [\n toolCallId,\n {\n toolCallId,\n ...(record.decision === undefined\n ? {}\n : { decision: decodeCheckpointToolDecision(toolCallId, record.decision, eventsBySeq) }),\n ...(record.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n ...(record.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record.startedSeq === undefined ? {} : { startedSeq: record.startedSeq }),\n ...(record.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record.terminal === undefined\n ? {}\n : { terminal: decodeCheckpointToolTerminal(toolCallId, record.terminal, eventsBySeq) }),\n },\n ]),\n );\n\nconst decodeCheckpointToolDecision = (\n toolCallId: ToolCallId,\n decision: ReducedStateCheckpointToolDecision,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolDecision => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n decision.seq,\n decision._tag === \"Created\" ? toolCallCreatedEventType : toolCallRejectedEventType,\n ).toolCalls.get(toolCallId)?.decision;\n if (hydrated === undefined || hydrated._tag !== decision._tag) {\n throw new Error(`Checkpoint tool decision ${toolCallId} missing ${decision._tag} payload`);\n }\n return hydrated;\n};\n\nconst decodeCheckpointToolTerminal = (\n toolCallId: ToolCallId,\n terminal: ReducedStateCheckpointToolTerminal,\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n): ToolTerminal => {\n const hydrated = reduceSingleCheckpointEvent(\n eventsBySeq,\n terminal.seq,\n terminal._tag === \"Completed\" ? toolCallCompletedEventType : toolCallFailedEventType,\n ).toolCalls.get(toolCallId)?.terminal;\n if (hydrated === undefined || hydrated._tag !== terminal._tag) {\n throw new Error(`Checkpoint tool terminal ${toolCallId} missing ${terminal._tag} payload`);\n }\n return hydrated;\n};\n\nconst checkpointMessageEventType = (record: ReducedStateCheckpointMessageRecord) => {\n switch (record._tag) {\n case \"System\":\n return systemMessageCommittedEventType;\n case \"User\":\n return record.requestedDisposition === undefined\n ? userMessageCommittedEventType\n : userMessageSubmittedEventType;\n case \"Steering\":\n return steeringMessageQueuedEventType;\n case \"Assistant\":\n return record.imported === true\n ? assistantMessageImportedEventType\n : assistantMessageCommittedEventType;\n case \"AssistantPartial\":\n return assistantPartialCommittedEventType;\n default:\n return assertNever(record, \"checkpoint message type\");\n }\n};\n\nconst reduceSingleCheckpointEvent = (\n eventsBySeq: ReadonlyMap<number, CommittedDurableEvent>,\n seq: SequenceNumber,\n expectedType: string,\n): ReducedState => {\n const event = eventsBySeq.get(Number(seq));\n if (event === undefined) {\n throw new Error(`Checkpoint reference seq ${seq} is missing`);\n }\n if (event.event.type !== expectedType) {\n throw new Error(\n `Checkpoint reference seq ${seq} expected ${expectedType}; got ${event.event.type}`,\n );\n }\n return foldReducedState(initialReducedState, [event]);\n};\n\nconst committedEventMapBySeq = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<number, CommittedDurableEvent> =>\n new Map(events.map((event) => [Number(event.position.seq), event]));\n\nconst uniqueSequenceNumbers = (\n seqs: ReadonlyArray<SequenceNumber>,\n): ReadonlyArray<SequenceNumber> =>\n Array.from(new Set(seqs.map((seq) => Number(seq))))\n .sort((left, right) => left - right)\n .map((seq) => SequenceNumber.make(seq));\n\nconst decodeTokenConsumptionState = (\n value: TokenConsumptionState | undefined,\n): TokenConsumptionState => value ?? emptyTokenConsumptionState;\n\n/** Fold newly committed durable events into the canonical replay state. */\nexport const foldReducedState = (\n state: ReducedState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): ReducedState => {\n let lastSeq = state.lastSeq;\n let runSchedulingRequest = state.runSchedulingRequest;\n let modelSelection = state.modelSelection;\n const commands = new Map(state.commands);\n const runs = new Map(state.runs);\n const recoveryContinuations = new Map(state.recoveryContinuations);\n const turns = new Map(state.turns);\n const inferences = new Map(state.inferences);\n const toolCalls = new Map(state.toolCalls);\n const messages = new Map(state.messages);\n const stopRequests = new Map(state.stopRequests);\n const compactions = new Map(state.compactions);\n let context = state.context;\n let tokenConsumption = state.tokenConsumption;\n\n for (const entry of committed) {\n lastSeq = entry.position.seq;\n if (entry.event.namespace !== effectDurableAgentNamespace) {\n continue;\n }\n\n const event = interpretLegacyAttemptForReduction(entry.event);\n const seq = entry.position.seq;\n const eventCreatedAtMs = Number(event.createdAtMs);\n\n switch (event.type) {\n case runSchedulingRequestedEventType:\n runSchedulingRequest = Schema.decodeUnknownSync(RunSchedulingRequestRecord)({\n ...Schema.decodeUnknownSync(RunSchedulingRequest)(event.payload),\n requestedSeq: seq,\n });\n break;\n case runSchedulingDeliveredEventType:\n if (\n runSchedulingRequest !== undefined &&\n runSchedulingRequest.requestId === event.payload.requestId\n ) {\n runSchedulingRequest = { ...runSchedulingRequest, deliveredSeq: seq };\n }\n break;\n case runSchedulingInvalidatedEventType:\n case runSchedulingGrantedEventType:\n if (runSchedulingRequest?.requestId === event.payload.requestId)\n runSchedulingRequest = undefined;\n break;\n case commandAdmittedEventType: {\n const { command } = event.payload;\n const commandId = requireAdmittedCommandId(command);\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n admittedSeq: seq,\n admissionTrace: event.trace,\n command,\n }));\n break;\n }\n case commandStartedEventType: {\n const { commandId } = event.payload;\n upsert(commands, commandId, { commandId }, (record) => ({ ...record, startedSeq: seq }));\n break;\n }\n case commandCompletedEventType: {\n const { commandId } = event.payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CommandTerminal,\n }));\n break;\n }\n case commandFailedEventType: {\n const { commandId, error } = event.payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CommandTerminal,\n }));\n break;\n }\n case commandCancelledEventType: {\n const { commandId, reason } = event.payload;\n upsert(commands, commandId, { commandId }, (record) => ({\n ...record,\n terminal: { _tag: \"Cancelled\", seq, reason } as CommandTerminal,\n }));\n break;\n }\n case runStartedEventType: {\n const { runId, commandIds, trace } = event.payload;\n modelSelection ??= event.payload.modelSelection;\n const terminal = runs.get(runId)?.terminal;\n runs.set(runId, {\n runId,\n commandIds,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n trace,\n modelSelection: event.payload.modelSelection,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case runCompletedEventType: {\n const { runId } = event.payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Completed\", seq } as RunTerminal,\n }));\n break;\n }\n case runFailedEventType: {\n const { runId, error } = event.payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as RunTerminal,\n }));\n break;\n }\n case runInterruptedEventType: {\n const { runId, reason } = event.payload;\n updateExisting(runs, runId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Interrupted\", seq, reason } as RunTerminal,\n }));\n break;\n }\n case turnStartedEventType: {\n const { runId, turnId, inputMessageIds } = event.payload;\n const terminal = turns.get(turnId)?.terminal;\n turns.set(turnId, {\n runId,\n turnId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n for (const messageId of inputMessageIds ?? []) {\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\" || message?._tag === \"User\") {\n messages.set(messageId, { ...message, consumedSeq: seq, consumedTurnId: turnId });\n }\n }\n break;\n }\n case turnCompletedEventType: {\n const { turnId, usage } = event.payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as TurnTerminal,\n }));\n break;\n }\n case turnFailedEventType: {\n const { turnId, error } = event.payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as TurnTerminal,\n }));\n break;\n }\n case turnStoppedEventType: {\n const { turnId, reason } = event.payload;\n updateExisting(turns, turnId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Stopped\", seq, reason } as TurnTerminal,\n }));\n break;\n }\n case inferenceStartedEventType: {\n const { runId, turnId, inferenceId } = event.payload;\n const terminal = inferences.get(inferenceId)?.terminal;\n inferences.set(inferenceId, {\n runId,\n turnId,\n inferenceId: inferenceId,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n ...(terminal === undefined ? {} : { terminal }),\n });\n break;\n }\n case inferenceCompletedEventType: {\n const { inferenceId, usage } = event.payload;\n const previouslyCompleted = inferences.get(inferenceId)?.terminal?._tag === \"Completed\";\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n ...(usage === undefined ? {} : { usage }),\n } as InferenceTerminal,\n }));\n if (!previouslyCompleted && inferences.get(inferenceId)?.terminal?._tag === \"Completed\") {\n const model = runs.get(event.payload.runId)?.modelSelection;\n if (model !== undefined) tokenConsumption = addModelUsage(tokenConsumption, model, usage);\n }\n break;\n }\n case inferenceFailedEventType: {\n const { inferenceId, error } = event.payload;\n updateExisting(inferences, inferenceId, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: { _tag: \"Failed\", seq, error } as InferenceTerminal,\n }));\n break;\n }\n case toolCallCreatedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = event.payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Created\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n params: promptPart.params,\n providerExecuted: promptPart.providerExecuted,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallRejectedEventType: {\n const { runId, turnId, inferenceId, toolCallId, promptPart } = event.payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n decision: {\n _tag: \"Rejected\",\n seq,\n runId,\n turnId,\n inferenceId: inferenceId,\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n reason: promptPart.result.reason,\n modelFeedback: promptPart.result.modelFeedback,\n promptPart,\n } as ToolDecision,\n }));\n break;\n }\n case toolCallStartedEventType: {\n const { toolCallId } = event.payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n startedAtMs: eventCreatedAtMs,\n startedSeq: seq,\n }));\n break;\n }\n case toolCallCompletedEventType: {\n const { toolCallId, promptPart } = event.payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Completed\",\n seq,\n result: promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case toolCallFailedEventType: {\n const { toolCallId, promptPart, error } = event.payload;\n upsert(toolCalls, toolCallId, { toolCallId }, (record) => ({\n ...record,\n ...terminalTiming(record, eventCreatedAtMs),\n terminal: {\n _tag: \"Failed\",\n seq,\n error: error ?? promptPart.result,\n promptPart,\n } as ToolTerminal,\n }));\n break;\n }\n case systemMessageCommittedEventType: {\n const { messageId, content } = event.payload;\n messages.set(messageId, {\n _tag: \"System\",\n messageId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageCommittedEventType: {\n const { commandId, messageId, content } = event.payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessageSubmittedEventType: {\n const { commandId, messageId, disposition: requestedDisposition, content } = event.payload;\n messages.set(messageId, {\n _tag: \"User\",\n messageId,\n commandId,\n content,\n requestedDisposition,\n disposition: requestedDisposition,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case userMessagePromotedEventType: {\n const { messageId } = event.payload;\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" && message.disposition === \"queue\") ||\n (message?._tag === \"Steering\" && message.pausedByCommandId !== undefined)\n ) {\n const {\n pausedByCommandId: _pausedByCommandId,\n pausedSeq: _pausedSeq,\n ...unpausedMessage\n } = message;\n messages.set(messageId, {\n ...unpausedMessage,\n ...(message._tag === \"User\" ? { disposition: \"steer\" as const } : {}),\n promotedSeq: seq,\n });\n }\n break;\n }\n case userMessageCancelledEventType: {\n const { commandId, messageId, reason } = event.payload;\n const message = messages.get(messageId);\n if (message?._tag === \"User\" || message?._tag === \"Steering\") {\n messages.set(messageId, {\n ...message,\n cancelledSeq: seq,\n cancelledByCommandId: commandId,\n cancellationReason: reason,\n });\n }\n break;\n }\n case messageQueuePausedEventType:\n case pendingMessagesPausedEventType: {\n const messageIds = event.payload.messageIds;\n const interruptionCommandId =\n event.type === messageQueuePausedEventType\n ? event.payload.stopCommandId\n : event.payload.interruptionCommandId;\n for (const messageId of messageIds) {\n const message = messages.get(messageId);\n if (\n (message?._tag === \"User\" || message?._tag === \"Steering\") &&\n message.consumedSeq === undefined &&\n message.cancelledSeq === undefined\n ) {\n messages.set(messageId, {\n ...message,\n ...(message._tag === \"User\" ? { disposition: \"queue\" as const } : {}),\n pausedSeq: seq,\n pausedByCommandId: interruptionCommandId,\n });\n }\n }\n break;\n }\n case steeringMessageQueuedEventType: {\n const { commandId, messageId, runId, content } = event.payload;\n messages.set(messageId, {\n _tag: \"Steering\",\n messageId,\n commandId,\n runId,\n content,\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n seq,\n });\n break;\n }\n case steeringMessageCancelledEventType: {\n const { messageId, reason } = event.payload;\n const message = messages.get(messageId);\n if (message?._tag === \"Steering\") {\n messages.set(messageId, { ...message, cancelledSeq: seq, cancellationReason: reason });\n }\n break;\n }\n case assistantMessageCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantMessageImportedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;\n messages.set(messageId, {\n _tag: \"Assistant\",\n messageId,\n runId,\n turnId,\n inferenceId,\n imported: true,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n seq,\n });\n break;\n }\n case assistantPartialCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts, reason } = event.payload;\n messages.set(messageId, {\n _tag: \"AssistantPartial\",\n messageId,\n runId,\n turnId,\n inferenceId: inferenceId,\n content: assistantContentFromPromptParts(promptParts),\n ...(Number.isFinite(eventCreatedAtMs) ? { createdAtMs: eventCreatedAtMs } : {}),\n promptParts,\n reason,\n seq,\n });\n break;\n }\n case stopTurnRequestedEventType: {\n const { commandId, runId, turnId } = event.payload;\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: seq,\n ...(runId === undefined ? {} : { requestedRunId: runId }),\n ...(turnId === undefined ? {} : { requestedTurnId: turnId }),\n ...appliedFields(stopRequests.get(commandId)),\n });\n break;\n }\n case stopTurnAppliedEventType: {\n const { commandId, runId, turnId, inferenceId } = event.payload;\n const existing = stopRequests.get(commandId);\n stopRequests.set(commandId, {\n commandId,\n requestedSeq: existing?.requestedSeq ?? seq,\n ...(existing?.requestedRunId === undefined\n ? {}\n : { requestedRunId: existing.requestedRunId }),\n ...(existing?.requestedTurnId === undefined\n ? {}\n : { requestedTurnId: existing.requestedTurnId }),\n appliedSeq: seq,\n appliedRunId: runId,\n appliedTurnId: turnId,\n ...(inferenceId === undefined ? {} : { appliedInferenceId: inferenceId }),\n });\n break;\n }\n case contextProjectedEventType: {\n const { contextVersion } = event.payload;\n context = { ...context, version: contextVersion };\n break;\n }\n case compactionRequestedEventType: {\n const { compactionId, sourceFromSeq, sourceToSeq } = event.payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n requestedSeq: seq,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case compactionStartedEventType: {\n const { compactionId } = event.payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n startedSeq: seq,\n }));\n break;\n }\n case summaryCreatedEventType: {\n const { compactionId, summaryId, sourceFromSeq, sourceToSeq } = event.payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryCreatedSeq: seq,\n summaryId,\n sourceFromSeq,\n sourceToSeq,\n }));\n break;\n }\n case contextRebasedEventType: {\n const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = event.payload;\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n summaryId,\n rebasedSeq: seq,\n contextVersion,\n }));\n pruneForContextRebase(\n {\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n },\n retainedFromContextSeq,\n summaryId,\n );\n context = {\n version: contextVersion,\n currentSummaryId: summaryId,\n };\n break;\n }\n case compactionCompletedEventType: {\n const { compactionId } = event.payload;\n if (\n compactions.get(compactionId)?.terminal?._tag !== \"Completed\" &&\n event.payload.modelSelection !== undefined\n ) {\n tokenConsumption = addModelUsage(\n tokenConsumption,\n event.payload.modelSelection,\n event.payload.usage,\n );\n }\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Completed\", seq } as CompactionTerminal,\n }));\n break;\n }\n case compactionFailedEventType: {\n const { compactionId, error } = event.payload;\n if (event.payload.modelSelection !== undefined) {\n tokenConsumption = addModelUsage(\n tokenConsumption,\n event.payload.modelSelection,\n event.payload.usage,\n );\n }\n upsert(compactions, compactionId, { compactionId }, (record) => ({\n ...record,\n terminal: { _tag: \"Failed\", seq, error } as CompactionTerminal,\n }));\n const failed = compactions.get(compactionId);\n if (failed?.summaryId === undefined || failed.summaryId !== context.currentSummaryId) {\n compactions.delete(compactionId);\n }\n break;\n }\n case recoveryCompletedEventType: {\n const { continuation } = event.payload;\n if (continuation !== undefined) {\n recoveryContinuations.set(continuation.replacementRunId, { ...continuation, seq });\n }\n break;\n }\n case sessionConfiguredEventType:\n modelSelection ??= event.payload.modelSelection;\n break;\n case baseStateRequestedEventType:\n case baseStateCreatedEventType:\n case baseStateFailedEventType:\n break;\n default:\n assertNever(event, \"reduced-state durable event\");\n }\n }\n\n return {\n lastSeq,\n ...(runSchedulingRequest === undefined ? {} : { runSchedulingRequest }),\n ...(modelSelection === undefined ? {} : { modelSelection }),\n commands,\n runs,\n recoveryContinuations,\n turns,\n inferences,\n toolCalls,\n messages,\n stopRequests,\n compactions,\n context,\n tokenConsumption,\n commandQueues: deriveCommandQueues({ commands, runs, messages }),\n };\n};\n\n/** Fold committed events from genesis into a fresh `ReducedState`. */\nexport const reduceCommittedEvents = (committed: ReadonlyArray<CommittedDurableEvent>) =>\n foldReducedState(initialReducedState, committed);\n\ninterface MutableReplayMaps {\n readonly commands: Map<CommandId, CommandRecord>;\n readonly runs: Map<RunId, RunRecord>;\n readonly recoveryContinuations: Map<RunId, RecoveryContinuationRecord>;\n readonly turns: Map<TurnId, TurnRecord>;\n readonly inferences: Map<InferenceId, InferenceRecord>;\n readonly toolCalls: Map<ToolCallId, ToolCallRecord>;\n readonly messages: Map<MessageId, MessageRecord>;\n readonly stopRequests: Map<CommandId, StopRequestRecord>;\n readonly compactions: Map<CompactionId, CompactionRecord>;\n}\n\n/** Drop runtime state made model-invisible by a context rebase; storage remains append-only. */\nconst pruneForContextRebase = (\n maps: MutableReplayMaps,\n retainedFromContextSeq: SequenceNumber,\n currentSummaryId: SummaryId,\n): void => {\n for (const [messageId, message] of maps.messages) {\n if (message._tag !== \"System\" && messagePruneSeq(message) < retainedFromContextSeq) {\n maps.messages.delete(messageId);\n }\n }\n\n for (const [toolCallId, tool] of maps.toolCalls) {\n const terminalSeq = tool.terminal?.seq;\n if (terminalSeq !== undefined && terminalSeq < retainedFromContextSeq) {\n maps.toolCalls.delete(toolCallId);\n }\n }\n\n for (const [inferenceId, inference] of maps.inferences) {\n if (inference.terminal !== undefined && inference.terminal.seq < retainedFromContextSeq) {\n maps.inferences.delete(inferenceId);\n }\n }\n\n for (const [turnId, turn] of maps.turns) {\n if (turn.terminal !== undefined && turn.terminal.seq < retainedFromContextSeq) {\n maps.turns.delete(turnId);\n }\n }\n\n for (const [runId, run] of maps.runs) {\n if (run.terminal !== undefined && run.terminal.seq < retainedFromContextSeq) {\n maps.runs.delete(runId);\n }\n }\n\n for (const replacementRunId of maps.recoveryContinuations.keys()) {\n if (!maps.runs.has(replacementRunId)) {\n maps.recoveryContinuations.delete(replacementRunId);\n }\n }\n\n for (const [commandId, command] of maps.commands) {\n if (command.terminal !== undefined && command.terminal.seq < retainedFromContextSeq) {\n maps.commands.delete(commandId);\n }\n }\n\n for (const [commandId, request] of maps.stopRequests) {\n if (request.appliedSeq !== undefined && request.appliedSeq < retainedFromContextSeq) {\n maps.stopRequests.delete(commandId);\n }\n }\n\n for (const [compactionId, compaction] of maps.compactions) {\n if (compaction.terminal !== undefined && compaction.summaryId !== currentSummaryId) {\n maps.compactions.delete(compactionId);\n }\n }\n};\n\nconst messagePruneSeq = (message: Exclude<MessageRecord, { readonly _tag: \"System\" }>): number => {\n if (message._tag === \"Steering\") {\n return message.consumedSeq ?? message.cancelledSeq ?? Number.POSITIVE_INFINITY;\n }\n return message.seq;\n};\n\n/** Pending admitted commands in deterministic scheduler order. */\nexport const pendingCommands = (state: ReducedState): ReadonlyArray<PendingCommand> =>\n state.commandQueues.pendingCommands;\n\n/** First pending StopTurn control command, when one is waiting. */\nexport const pendingStopCommand = (state: ReducedState): PendingCommand | undefined =>\n state.commandQueues.activeControlCommands.find((command) => command.command._tag === \"StopTurn\");\n\n/** Currently active command evidence, if any unfinished command is blocking FIFO work. */\nexport const activeCommand = (state: ReducedState): ActiveCommandEvidence | undefined =>\n state.commandQueues.active;\n\n/** Active run/turn/inference identity owned by a specific active command. */\nexport const activeTurnIdentityForCommand = (\n state: ReducedState,\n commandId: CommandId,\n): ActiveTurnIdentity | undefined => {\n const run = findLast(Array.from(state.runs.values()), (candidate): candidate is RunRecord =>\n candidate.commandIds.includes(commandId),\n );\n if (run === undefined) {\n return undefined;\n }\n\n const turn = findLast(\n Array.from(state.turns.values()),\n (candidate): candidate is TurnRecord => candidate.runId === run.runId,\n );\n if (turn === undefined) {\n return undefined;\n }\n\n const inference = findLast(\n Array.from(state.inferences.values()),\n (candidate): candidate is InferenceRecord =>\n candidate.runId === run.runId && candidate.turnId === turn.turnId,\n );\n\n return {\n runId: run.runId,\n turnId: turn.turnId,\n ...(inference === undefined ? {} : { inferenceId: inference.inferenceId }),\n };\n};\n\n/** Classify unfinished durable lifecycles that recovery may need to repair. */\nexport const classifyRecoverableWork = (state: ReducedState): RecoverableWork => {\n const activeCommands = Array.from(state.commands.values()).filter(\n (command) =>\n command.startedSeq !== undefined &&\n command.terminal === undefined &&\n command.commandId !== state.runSchedulingRequest?.work.commandId,\n );\n const activeRuns = Array.from(state.runs.values()).filter((run) => run.terminal === undefined);\n const activeTurns = Array.from(state.turns.values()).filter(\n (turn) => turn.terminal === undefined,\n );\n const activeInferences = Array.from(state.inferences.values()).filter(\n (inference) => inference.terminal === undefined,\n );\n const openToolCalls = Array.from(state.toolCalls.values()).filter(\n (tool) =>\n tool.decision?._tag === \"Created\" &&\n !tool.decision.providerExecuted &&\n tool.terminal === undefined,\n );\n const runningToolCalls = openToolCalls.filter((tool) => tool.startedSeq !== undefined);\n const pendingStopRequests = Array.from(state.stopRequests.values()).filter(\n (request) =>\n request.appliedSeq === undefined &&\n state.commands.get(request.commandId)?.terminal === undefined,\n );\n const openCompactions = Array.from(state.compactions.values()).filter(\n (compaction) => compaction.terminal === undefined,\n );\n\n return {\n activeCommands,\n activeRuns,\n activeTurns,\n activeInferences,\n openToolCalls,\n runningToolCalls,\n pendingStopRequests,\n openCompactions,\n };\n};\n\nconst assistantContentFromPromptParts = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart>,\n): AssistantMessageContent => {\n const text = promptParts\n .filter((part): part is Prompt.TextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n const reasoning = promptParts\n .filter((part): part is Prompt.ReasoningPart => part.type === \"reasoning\")\n .map((part) => part.text)\n .join(\"\");\n return {\n text,\n ...(reasoning.length === 0 ? {} : { reasoning }),\n };\n};\n\nconst findLast = <A, B extends A>(\n items: ReadonlyArray<A>,\n predicate: (item: A) => item is B,\n): B | undefined => {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n const item = items[index] as A;\n if (predicate(item)) {\n return item;\n }\n }\n return undefined;\n};\n\nconst requireAdmittedCommandId = (command: EDACommandValue): CommandId => {\n if (command.commandId !== undefined) {\n return command.commandId;\n }\n throw new Error(\"CommandAdmitted command is missing a framework commandId\");\n};\n\nconst terminalTiming = (\n record: Pick<LifecycleTiming, \"startedAtMs\">,\n terminalAtMs: number,\n): LifecycleTiming => ({\n terminalAtMs,\n ...(record.startedAtMs === undefined\n ? {}\n : { durationMs: Math.max(0, terminalAtMs - record.startedAtMs) }),\n});\n\nconst upsert = <K, V>(map: Map<K, V>, key: K, fallback: V, update: (record: V) => V) => {\n map.set(key, update(map.get(key) ?? fallback));\n};\n\nconst updateExisting = <K, V>(map: Map<K, V>, key: K, update: (record: V) => V) => {\n const record = map.get(key);\n if (record !== undefined) {\n map.set(key, update(record));\n }\n};\n\nconst appliedFields = (record: StopRequestRecord | undefined) =>\n record?.appliedSeq === undefined\n ? {}\n : {\n appliedSeq: record.appliedSeq,\n appliedRunId: record.appliedRunId,\n appliedTurnId: record.appliedTurnId,\n ...(record.appliedInferenceId === undefined\n ? {}\n : { appliedInferenceId: record.appliedInferenceId }),\n };\n"],"mappings":";;;;;;;;AAAA,MAAM,oBAAoB,UAAyB;CACjD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;AAGA,MAAa,oBAAoB,OAAc,4BAC7C,IAAI,MAAM,aAAa,QAAQ,IAAI,iBAAiB,KAAK,GAAG;;AAG9D,MAAa,eAAe,OAAc,YAA2B;CACnE,MAAM,iBAAiB,OAAO,OAAO;AACvC;;;ACgWA,MAAM,6BAAoD,EACxD,SAAS,CAAC,EACZ;;AAGA,MAAa,sBAAoC;CAC/C,SAAS,eAAe,KAAK,CAAC;CAC9B,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;CACd,uCAAuB,IAAI,IAAI;CAC/B,uBAAO,IAAI,IAAI;CACf,4BAAY,IAAI,IAAI;CACpB,2BAAW,IAAI,IAAI;CACnB,0BAAU,IAAI,IAAI;CAClB,8BAAc,IAAI,IAAI;CACtB,6BAAa,IAAI,IAAI;CACrB,SAAS,EAAE,SAAS,eAAe,KAAK,CAAC,EAAE;CAC3C,kBAAkB;CAClB,eAAe;AACjB;;AAGA,MAAa,mCAAmC;;AAGhD,MAAa,4CAA4C;;AAyDzD,MAAa,gCACX,WACmC;CACnC,SAAS,MAAM;CACf,GAAI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