effect-durable-agent 0.1.0-alpha.1 → 0.1.0-alpha.10

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.
Files changed (183) hide show
  1. package/README.md +140 -136
  2. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CQi4Xc7u.d.ts} +109 -21
  3. package/dist/{commands-Ce1ec6kH.d.ts → commands-p8venTWs.d.ts} +10 -2
  4. package/dist/compaction-0k8zCJgB.js +473 -0
  5. package/dist/compaction-0k8zCJgB.js.map +1 -0
  6. package/dist/{compaction-YayFKo_1.d.ts → compaction-BhLSSXJ-.d.ts} +28 -7
  7. package/dist/context-projection-mCuvcO2W.d.ts +140 -0
  8. package/dist/{core-Hv3cFydL.d.ts → core-C-6xHzRx.d.ts} +6 -3
  9. package/dist/domain/command-queues.d.ts +1 -1
  10. package/dist/domain/command-queues.js +1 -1
  11. package/dist/domain/command-queues.js.map +1 -1
  12. package/dist/domain/context-projection.d.ts +2 -0
  13. package/dist/domain/context-projection.js +32 -0
  14. package/dist/domain/context-projection.js.map +1 -0
  15. package/dist/domain/message-transcript.d.ts +1 -1
  16. package/dist/domain/model-usage.d.ts +2 -0
  17. package/dist/domain/model-usage.js +59 -0
  18. package/dist/domain/model-usage.js.map +1 -0
  19. package/dist/domain/reduced-state-schema.d.ts +14 -18
  20. package/dist/domain/reduced-state-schema.js +7 -11
  21. package/dist/domain/reduced-state-schema.js.map +1 -1
  22. package/dist/domain/reduced-state.d.ts +3 -2
  23. package/dist/domain/reduced-state.js +3 -2
  24. package/dist/domain/run-scheduling.d.ts +2 -0
  25. package/dist/domain/run-scheduling.js +127 -0
  26. package/dist/domain/run-scheduling.js.map +1 -0
  27. package/dist/{durable-C3Rz7kg3.js → durable-BPHVFVvV.js} +74 -83
  28. package/dist/durable-BPHVFVvV.js.map +1 -0
  29. package/dist/{durable-DlScwmCy.d.ts → durable-DeLCAvbw.d.ts} +1256 -104
  30. package/dist/envelope-DkZyMIgp.d.ts +191 -0
  31. package/dist/envelope-DxQzo5rN.js +82 -0
  32. package/dist/envelope-DxQzo5rN.js.map +1 -0
  33. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-KaeDSfeP.d.ts} +11 -31
  34. package/dist/{keep-alive-p8dIcSVy.js → event-factory-QuC_UvyP.js} +8 -10
  35. package/dist/event-factory-QuC_UvyP.js.map +1 -0
  36. package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
  37. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator--x6itQZ2.d.ts} +3 -2
  38. package/dist/index.d.ts +7 -6
  39. package/dist/index.js +5 -4
  40. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  41. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-6PEzaEGn.d.ts} +4 -4
  42. package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
  43. package/dist/model-usage-CdBEkTwU.d.ts +55 -0
  44. package/dist/{prompt-projector-9_02lk5-.d.ts → prompt-projector-CNhqUsEr.d.ts} +15 -16
  45. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-Bz68V2H8.js} +65 -32
  46. package/dist/reduced-state-Bz68V2H8.js.map +1 -0
  47. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CCSzc4h8.d.ts} +16 -6
  48. package/dist/run-scheduler-DcS_okUH.d.ts +43 -0
  49. package/dist/run-scheduling-wakeup-CeHrvXie.d.ts +25 -0
  50. package/dist/{runtime-C56FQxiL.d.ts → runtime-WL_gKqxn.d.ts} +16 -7
  51. package/dist/services/compaction.d.ts +1 -1
  52. package/dist/services/compaction.js +1 -425
  53. package/dist/services/id-generator.d.ts +1 -1
  54. package/dist/services/id-generator.js +2 -1
  55. package/dist/services/id-generator.js.map +1 -1
  56. package/dist/services/keep-alive.d.ts +2 -0
  57. package/dist/services/keep-alive.js +13 -0
  58. package/dist/services/keep-alive.js.map +1 -0
  59. package/dist/services/model-resolver.d.ts +2 -0
  60. package/dist/services/model-resolver.js +17 -0
  61. package/dist/services/model-resolver.js.map +1 -0
  62. package/dist/services/prompt-projector.d.ts +2 -2
  63. package/dist/services/prompt-projector.js +20 -10
  64. package/dist/services/prompt-projector.js.map +1 -1
  65. package/dist/services/reducer-registry.d.ts +2 -2
  66. package/dist/services/reducer-registry.js +7 -3
  67. package/dist/services/reducer-registry.js.map +1 -1
  68. package/dist/services/run-scheduler.d.ts +3 -0
  69. package/dist/services/run-scheduler.js +25 -0
  70. package/dist/services/run-scheduler.js.map +1 -0
  71. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  72. package/dist/services/run-scheduling-wakeup.js +13 -0
  73. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  74. package/dist/services/runtime-layer.d.ts +67 -0
  75. package/dist/services/runtime-layer.js +47 -0
  76. package/dist/services/runtime-layer.js.map +1 -0
  77. package/dist/services/runtime.d.ts +1 -1
  78. package/dist/services/runtime.js +21 -14
  79. package/dist/services/runtime.js.map +1 -1
  80. package/dist/services/session-event-observer.d.ts +2 -0
  81. package/dist/services/session-event-observer.js +13 -0
  82. package/dist/services/session-event-observer.js.map +1 -0
  83. package/dist/services/session-query.d.ts +2 -2
  84. package/dist/services/session-query.js +140 -1
  85. package/dist/services/session-query.js.map +1 -0
  86. package/dist/services/session-state.d.ts +2 -0
  87. package/dist/services/session-state.js +2 -0
  88. package/dist/services/session-store.d.ts +2 -2
  89. package/dist/services/session-store.js +182 -2
  90. package/dist/services/session-store.js.map +1 -0
  91. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  92. package/dist/services/sink-checkpoint-store.js +49 -0
  93. package/dist/services/sink-checkpoint-store.js.map +1 -0
  94. package/dist/services/sink-registry.d.ts +1 -1
  95. package/dist/services/sink-registry.js +1 -1
  96. package/dist/services/span-names.d.ts +1 -1
  97. package/dist/services/span-names.js +3 -0
  98. package/dist/services/span-names.js.map +1 -1
  99. package/dist/services/tool-registry.d.ts +1 -1
  100. package/dist/services/tracing.d.ts +1 -1
  101. package/dist/services/tracing.js +23 -2
  102. package/dist/services/tracing.js.map +1 -1
  103. package/dist/session-event-observer-DaFMKKNc.d.ts +24 -0
  104. package/dist/session-query-DfW_4KC0.d.ts +47 -0
  105. package/dist/{session-query-DOc1KanA.js → session-state-BIZ2SYaP.js} +350 -183
  106. package/dist/session-state-BIZ2SYaP.js.map +1 -0
  107. package/dist/{session-query-DlRo5Ufc.d.ts → session-state-BeR2rZRR.d.ts} +144 -46
  108. package/dist/{session-store-D2Ore1QC.d.ts → session-store-J_Un45kW.d.ts} +7 -96
  109. package/dist/sink-checkpoint-store-C9hUxfH0.d.ts +40 -0
  110. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-Bbqhtdnx.js} +27 -67
  111. package/dist/sink-registry-Bbqhtdnx.js.map +1 -0
  112. package/dist/{sink-registry-CIU0LD3m.d.ts → sink-registry-DuDkNXjZ.d.ts} +24 -49
  113. package/dist/testkit/layers.d.ts +24 -14
  114. package/dist/testkit/layers.js +18 -11
  115. package/dist/testkit/layers.js.map +1 -1
  116. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-BDmJe_Wr.d.ts} +4 -4
  117. package/dist/types/commands.d.ts +2 -2
  118. package/dist/types/commands.js +7 -2
  119. package/dist/types/commands.js.map +1 -1
  120. package/dist/types/core.d.ts +2 -2
  121. package/dist/types/core.js +4 -2
  122. package/dist/types/core.js.map +1 -1
  123. package/dist/types/events/durable.d.ts +2 -2
  124. package/dist/types/events/durable.js +2 -2
  125. package/dist/types/events.d.ts +4 -3
  126. package/dist/types/events.js +3 -2
  127. package/dist/types/events.js.map +1 -1
  128. package/dist/websocket.d.ts +2776 -0
  129. package/dist/websocket.js +498 -0
  130. package/dist/websocket.js.map +1 -0
  131. package/package.json +68 -43
  132. package/testing/offline-trace/README.md +2 -1
  133. package/CHANGELOG.md +0 -10
  134. package/CONTRIBUTING.md +0 -26
  135. package/SECURITY.md +0 -8
  136. package/dist/durable-C3Rz7kg3.js.map +0 -1
  137. package/dist/durable-object-runtime-B7jwBY2R.js +0 -1494
  138. package/dist/durable-object-runtime-B7jwBY2R.js.map +0 -1
  139. package/dist/durable-object-runtime-pWv0ohlz.d.ts +0 -257
  140. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  141. package/dist/host/durable-object-runtime.d.ts +0 -2
  142. package/dist/host/durable-object-runtime.js +0 -2
  143. package/dist/host/durable-object-storage.d.ts +0 -2
  144. package/dist/host/durable-object-storage.js +0 -0
  145. package/dist/host/durable-object.d.ts +0 -83
  146. package/dist/host/durable-object.js +0 -191
  147. package/dist/host/durable-object.js.map +0 -1
  148. package/dist/host/websocket-wire.d.ts +0 -2
  149. package/dist/host/websocket-wire.js +0 -88
  150. package/dist/host/websocket-wire.js.map +0 -1
  151. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  152. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  153. package/dist/services/compaction.js.map +0 -1
  154. package/dist/session-query-DOc1KanA.js.map +0 -1
  155. package/dist/session-store-pYxQW9qh.js +0 -214
  156. package/dist/session-store-pYxQW9qh.js.map +0 -1
  157. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  158. package/dist/websocket-wire-DvOu_6BJ.d.ts +0 -16773
  159. package/docs/assets/architecture.svg +0 -106
  160. package/docs/assets/event-sequence.svg +0 -143
  161. package/docs/assets/gcp-trace.png +0 -0
  162. package/docs/message-steering.md +0 -831
  163. package/docs/releasing.md +0 -57
  164. package/docs/spec.md +0 -774
  165. package/docs/subagents.md +0 -725
  166. package/docs/testing.md +0 -64
  167. package/docs/ui-projection.md +0 -742
  168. package/docs/websocket-protocol.md +0 -613
  169. package/examples/001-no-tools/README.md +0 -65
  170. package/examples/001-no-tools/worker.ts +0 -79
  171. package/examples/002-slack-bridge/README.md +0 -134
  172. package/examples/002-slack-bridge/events.ts +0 -115
  173. package/examples/002-slack-bridge/reducer.ts +0 -216
  174. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  175. package/examples/002-slack-bridge/sinks.ts +0 -109
  176. package/examples/002-slack-bridge/worker.ts +0 -140
  177. package/examples/003-sandbox-lifecycle/README.md +0 -78
  178. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  179. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  180. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  181. package/examples/_shared/event-id.ts +0 -12
  182. package/examples/_shared/http.ts +0 -27
  183. package/examples/_shared/openai.ts +0 -33
@@ -0,0 +1,473 @@
1
+ import { ContextVersion, SequenceNumber } from "./types/core.js";
2
+ import { ModelResolver } from "./services/model-resolver.js";
3
+ import { g as UsagePayload, s as FailurePayload } from "./envelope-DxQzo5rN.js";
4
+ import { CompactionExecutorId, CompactionPolicyId, CompactionSummaryArtifact } from "./domain/context-projection.js";
5
+ import { durableMessageTranscript } from "./domain/message-transcript.js";
6
+ import { IdGenerator } from "./services/id-generator.js";
7
+ import { t as EventFactory } from "./event-factory-QuC_UvyP.js";
8
+ import { annotateEdaSpan, committedBatchAttributes } from "./services/tracing.js";
9
+ import { EDAKeepAlive } from "./services/keep-alive.js";
10
+ import * as Context from "effect/Context";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Schema from "effect/Schema";
14
+ import * as Prompt from "effect/unstable/ai/Prompt";
15
+ //#region src/services/provider-usage.ts
16
+ /** Normalizes provider usage for both conversation and compaction calls. */
17
+ const makeUsagePayload = (usage) => {
18
+ const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
19
+ const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
20
+ const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
21
+ const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
22
+ uncachedInputTokens,
23
+ cachedInputTokens,
24
+ cacheWriteInputTokens
25
+ ]);
26
+ const textTokens = nonNegativeInt(usage.outputTokens.text);
27
+ const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
28
+ const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
29
+ return UsagePayload.make({
30
+ ...inputTokens === void 0 ? {} : { inputTokens },
31
+ ...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
32
+ ...cacheWriteInputTokens === void 0 ? {} : { cacheWriteInputTokens },
33
+ ...outputTokens === void 0 ? {} : { outputTokens },
34
+ ...textTokens === void 0 ? {} : { textTokens },
35
+ ...reasoningTokens === void 0 ? {} : { reasoningTokens }
36
+ });
37
+ };
38
+ const sumDefined = (values) => {
39
+ const present = values.filter((value) => value !== void 0);
40
+ return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
41
+ };
42
+ const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
43
+ //#endregion
44
+ //#region src/services/compaction.ts
45
+ /** Candidate durable range and retained cursor selected by compaction policy. */
46
+ const CompactionPlan = Schema.Struct({
47
+ policyId: CompactionPolicyId,
48
+ sourceFromSeq: SequenceNumber,
49
+ sourceToSeq: SequenceNumber,
50
+ retainedFromContextSeq: SequenceNumber
51
+ });
52
+ /** Rough token heuristic used by the built-in compaction presets. */
53
+ const defaultCompactionCharsPerToken = 4;
54
+ /** Production-oriented context threshold for the built-in approximate-token policy. */
55
+ const defaultCompactionThresholdTokens = 22e4;
56
+ /** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */
57
+ const defaultCompactionRetainTailTokens = 4e4;
58
+ /** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */
59
+ const defaultCompactionMinSummarizableTokens = 1e4;
60
+ /** Result produced by the summary executor before the framework commits it. */
61
+ const CompactionOutput = Schema.Struct({
62
+ text: Schema.NonEmptyString,
63
+ promptMessage: Prompt.UserMessage,
64
+ executorId: Schema.optionalKey(CompactionExecutorId),
65
+ usage: Schema.optionalKey(UsagePayload)
66
+ });
67
+ /** Typed failure from policy planning or summary generation. */
68
+ var CompactionError = class extends Schema.TaggedErrorClass()("CompactionError", {
69
+ message: Schema.String,
70
+ usage: Schema.optionalKey(UsagePayload)
71
+ }) {};
72
+ /** Decides whether a safe prompt-context rebase should be attempted. */
73
+ var CompactionPolicy = class CompactionPolicy extends Context.Service()("@effect-durable-agent/CompactionPolicy") {
74
+ /** Default policy: compaction is disabled and commits no skip events. */
75
+ static Disabled = Layer.succeed(CompactionPolicy, {
76
+ id: CompactionPolicyId.make("disabled"),
77
+ plan: () => Effect.succeed(void 0)
78
+ });
79
+ /** Test/app hook for replacing the policy with a concrete planner. */
80
+ static FromFunction = (id, plan) => Layer.succeed(CompactionPolicy, {
81
+ id: CompactionPolicyId.make(id),
82
+ plan
83
+ });
84
+ /**
85
+ * Common production policy: compact when approximate prompt context exceeds a token threshold.
86
+ *
87
+ * The policy keeps a recent tail verbatim, summarizes the older prefix, and advances from the
88
+ * current summary cursor so repeated compactions behave like the first one.
89
+ */
90
+ static ApproximateTokenThreshold = (options = {}) => {
91
+ const normalized = normalizeApproximateTokenPolicyOptions(options);
92
+ return Layer.succeed(CompactionPolicy, {
93
+ id: normalized.policyId,
94
+ plan: ({ state, context }) => Effect.sync(() => planApproximateTokenCompaction(state, context, normalized))
95
+ });
96
+ };
97
+ };
98
+ /** Produces a cumulative summary artifact for a selected compaction plan. */
99
+ var CompactionExecutor = class CompactionExecutor extends Context.Service()("@effect-durable-agent/CompactionExecutor") {
100
+ /** Placeholder executor for the disabled default policy. It should never be called. */
101
+ static Disabled = Layer.succeed(CompactionExecutor, {
102
+ id: CompactionExecutorId.make("disabled"),
103
+ execute: () => Effect.die(/* @__PURE__ */ new Error("CompactionExecutor.Disabled was called"))
104
+ });
105
+ /** Test/app hook for replacing summary generation. */
106
+ static FromFunction = (id, execute) => Layer.succeed(CompactionExecutor, {
107
+ id: CompactionExecutorId.make(id),
108
+ execute
109
+ });
110
+ /** Summary executor backed by the configured Effect AI LanguageModel. */
111
+ static LanguageModelSummary = (options = {}) => Layer.effect(CompactionExecutor, Effect.sync(() => {
112
+ const executorId = CompactionExecutorId.make(options.executorId ?? "language-model-summary");
113
+ const summaryMessagePrefix = options.summaryMessagePrefix ?? "Conversation summary:";
114
+ return {
115
+ id: executorId,
116
+ execute: Effect.fn("agent.compaction")(function* (input) {
117
+ yield* annotateEdaSpan({
118
+ "eda.compaction.policy_id": input.plan.policyId,
119
+ "eda.compaction.source_from_seq": input.plan.sourceFromSeq,
120
+ "eda.compaction.source_to_seq": input.plan.sourceToSeq,
121
+ "eda.compaction.retained_from_context_seq": input.plan.retainedFromContextSeq,
122
+ "eda.compaction.executor_id": executorId
123
+ });
124
+ const promptText = buildSummaryPrompt(input);
125
+ if (promptText === void 0) return yield* new CompactionError({ message: "compaction plan selected no source messages" });
126
+ const response = yield* input.model.generateText({
127
+ prompt: Prompt.fromMessages([Prompt.makeMessage("system", { content: summarizationSystemPrompt }), Prompt.makeMessage("user", { content: [Prompt.textPart({ text: promptText })] })]),
128
+ toolChoice: "none"
129
+ }).pipe(Effect.mapError((error) => new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` })));
130
+ const text = response.text.trim();
131
+ if (text.length === 0) return yield* new CompactionError({
132
+ message: "summary model returned no text",
133
+ usage: makeUsagePayload(response.usage)
134
+ });
135
+ return CompactionOutput.make({
136
+ usage: makeUsagePayload(response.usage),
137
+ text,
138
+ promptMessage: Prompt.makeMessage("user", { content: [Prompt.textPart({ text: `${summaryMessagePrefix}\n\n${text}` })] }),
139
+ executorId
140
+ });
141
+ })
142
+ };
143
+ }));
144
+ };
145
+ /** Framework-owned compaction lifecycle runner. */
146
+ var CompactionRunner = class CompactionRunner extends Context.Service()("@effect-durable-agent/CompactionRunner") {
147
+ static Live = Layer.effect(CompactionRunner, Effect.suspend(() => makeLiveCompactionRunner));
148
+ };
149
+ const makeLiveCompactionRunner = Effect.gen(function* () {
150
+ const ids = yield* IdGenerator;
151
+ const events = yield* EventFactory;
152
+ const policy = yield* CompactionPolicy;
153
+ const executor = yield* CompactionExecutor;
154
+ const keepAlive = yield* EDAKeepAlive;
155
+ const models = yield* ModelResolver;
156
+ return { maybeCompact: Effect.fnUntraced(function* (input) {
157
+ const plan = yield* policy.plan({
158
+ state: input.state,
159
+ context: input.context
160
+ }).pipe(Effect.catchTag("CompactionError", (error) => Effect.logError("compaction policy failed", { error }).pipe(Effect.as(void 0))));
161
+ if (plan === void 0) {
162
+ yield* annotateEdaSpan({ "eda.compaction.selected": false });
163
+ return [];
164
+ }
165
+ yield* annotateEdaSpan({
166
+ "eda.compaction.selected": true,
167
+ "eda.compaction.policy_id": plan.policyId,
168
+ "eda.compaction.source_from_seq": plan.sourceFromSeq,
169
+ "eda.compaction.source_to_seq": plan.sourceToSeq,
170
+ "eda.compaction.retained_from_context_seq": plan.retainedFromContextSeq
171
+ });
172
+ const invalidPlan = validatePlan(plan, input.state, input.context);
173
+ if (invalidPlan !== void 0) {
174
+ yield* Effect.logError("compaction policy returned invalid plan", { reason: invalidPlan });
175
+ return [];
176
+ }
177
+ const compactionId = yield* ids.makeCompactionId();
178
+ const summaryId = yield* ids.makeSummaryId();
179
+ yield* annotateEdaSpan({
180
+ "eda.compaction.id": compactionId,
181
+ "eda.summary.id": summaryId
182
+ });
183
+ const requested = yield* events.compactionRequested({
184
+ compactionId,
185
+ sourceFromSeq: plan.sourceFromSeq,
186
+ sourceToSeq: plan.sourceToSeq
187
+ });
188
+ const started = yield* events.compactionStarted({ compactionId });
189
+ const startedEvents = yield* input.appendDurableEntries([{ event: requested }, { event: started }]);
190
+ const model = yield* models.resolve(input.state.modelSelection);
191
+ const output = yield* keepAlive.withActiveWork(`compaction:${compactionId}`, executor.execute({
192
+ plan,
193
+ state: input.state,
194
+ context: input.context,
195
+ model
196
+ })).pipe(Effect.catchTag("CompactionError", (error) => Effect.gen(function* () {
197
+ const failed = yield* events.compactionFailed({
198
+ compactionId,
199
+ ...input.state.modelSelection === void 0 ? {} : { modelSelection: input.state.modelSelection },
200
+ ...error.usage === void 0 ? {} : { usage: error.usage },
201
+ error: FailurePayload.make({ message: error.message })
202
+ });
203
+ return {
204
+ _tag: "Failed",
205
+ committed: yield* input.appendDurableEntries([{ event: failed }])
206
+ };
207
+ })), Effect.map((result) => "_tag" in result ? result : {
208
+ _tag: "Output",
209
+ output: result
210
+ }));
211
+ if (output._tag === "Failed") return [...startedEvents, ...output.committed];
212
+ const artifact = CompactionSummaryArtifact.make({
213
+ compactionId,
214
+ summaryId,
215
+ ...input.context.currentSummary === void 0 ? {} : { previousSummaryId: input.context.currentSummary.summaryId },
216
+ sourceFromSeq: plan.sourceFromSeq,
217
+ sourceToSeq: plan.sourceToSeq,
218
+ retainedFromContextSeq: plan.retainedFromContextSeq,
219
+ text: output.output.text,
220
+ promptMessage: output.output.promptMessage,
221
+ policyId: plan.policyId,
222
+ ...output.output.executorId === void 0 ? {} : { executorId: output.output.executorId }
223
+ });
224
+ const summaryCreated = yield* events.summaryCreated({
225
+ compactionId,
226
+ summaryId,
227
+ sourceFromSeq: plan.sourceFromSeq,
228
+ sourceToSeq: plan.sourceToSeq,
229
+ summary: artifact
230
+ });
231
+ const contextRebased = yield* events.contextRebased({
232
+ compactionId,
233
+ summaryId,
234
+ contextVersion: ContextVersion.make(input.context.contextVersion + 1),
235
+ retainedFromContextSeq: plan.retainedFromContextSeq
236
+ });
237
+ const completed = yield* events.compactionCompleted({
238
+ compactionId,
239
+ ...input.state.modelSelection === void 0 ? {} : { modelSelection: input.state.modelSelection },
240
+ ...output.output.usage === void 0 ? {} : { usage: output.output.usage }
241
+ });
242
+ const committed = yield* input.appendDurableEntries([
243
+ { event: summaryCreated },
244
+ { event: contextRebased },
245
+ { event: completed }
246
+ ]);
247
+ yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));
248
+ return [...startedEvents, ...committed];
249
+ }) };
250
+ });
251
+ const validatePlan = (plan, state, context) => {
252
+ const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
253
+ if (plan.retainedFromContextSeq <= currentRetainedFromSeq) return "retainedFromContextSeq must advance beyond the current summary cursor";
254
+ if (plan.sourceToSeq > state.lastSeq) return "sourceToSeq must not exceed the current durable head";
255
+ if (plan.retainedFromContextSeq > state.lastSeq + 1) return "retainedFromContextSeq must not skip unsummarized future context";
256
+ if (plan.sourceFromSeq > plan.sourceToSeq) return "sourceFromSeq must be less than or equal to sourceToSeq";
257
+ if (plan.retainedFromContextSeq <= plan.sourceToSeq) return "retainedFromContextSeq must start after the summarized source range";
258
+ };
259
+ const normalizeApproximateTokenPolicyOptions = (options) => ({
260
+ policyId: CompactionPolicyId.make(options.policyId ?? "approximate-token-threshold"),
261
+ thresholdTokens: positiveNumber(options.thresholdTokens ?? 22e4, "thresholdTokens"),
262
+ retainTailTokens: nonNegativeNumber(options.retainTailTokens ?? 4e4, "retainTailTokens"),
263
+ minSummarizableTokens: nonNegativeNumber(options.minSummarizableTokens ?? 1e4, "minSummarizableTokens"),
264
+ charsPerToken: positiveNumber(options.charsPerToken ?? 4, "charsPerToken")
265
+ });
266
+ const positiveNumber = (value, name) => {
267
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive finite number`);
268
+ return value;
269
+ };
270
+ const nonNegativeNumber = (value, name) => {
271
+ if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative finite number`);
272
+ return value;
273
+ };
274
+ /** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */
275
+ const planApproximateTokenCompaction = (state, context, options) => {
276
+ const messages = estimatedContextMessages(state);
277
+ if (estimateCurrentPromptChars(state, context, messages) <= options.thresholdTokens * options.charsPerToken) return;
278
+ const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
279
+ const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);
280
+ if (retainedFromSeq <= currentRetainedFromSeq) return;
281
+ const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);
282
+ if (sourceMessages.length === 0) return;
283
+ if (charsToTokens(sourceMessages.reduce((sum, message) => sum + message.chars, 0), options.charsPerToken) < options.minSummarizableTokens) return;
284
+ const sourceFromSeq = currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0].seq;
285
+ const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);
286
+ if (sourceFromSeq > sourceToSeq) return;
287
+ return CompactionPlan.make({
288
+ policyId: options.policyId,
289
+ sourceFromSeq,
290
+ sourceToSeq,
291
+ retainedFromContextSeq: retainedFromSeq
292
+ });
293
+ };
294
+ const selectRetainedFromSeq = (messages, lastSeq, options) => {
295
+ if (options.retainTailTokens === 0) return SequenceNumber.make(lastSeq + 1);
296
+ const retainTailChars = options.retainTailTokens * options.charsPerToken;
297
+ let tailChars = 0;
298
+ let retainedIndex = messages.length;
299
+ for (let index = messages.length - 1; index >= 0; index--) {
300
+ tailChars += messages[index].chars;
301
+ retainedIndex = index;
302
+ if (tailChars >= retainTailChars) break;
303
+ }
304
+ return retainedIndex >= messages.length ? SequenceNumber.make(lastSeq + 1) : messages[retainedIndex].seq;
305
+ };
306
+ const estimateCurrentPromptChars = (state, context, messages) => {
307
+ const systemChars = Array.from(state.messages.values()).reduce((sum, message) => message._tag === "System" ? sum + message.content.length : sum, 0);
308
+ const summaryChars = context.currentSummary === void 0 ? 0 : estimatePromptMessageChars(context.currentSummary.promptMessage);
309
+ const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);
310
+ return systemChars + summaryChars + messageChars;
311
+ };
312
+ const estimatedContextMessages = (state) => durableMessageTranscript(state).map((message) => ({
313
+ message,
314
+ seq: messageSeq(message),
315
+ chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state)
316
+ }));
317
+ const estimateDurableMessageChars = (message) => {
318
+ switch (message._tag) {
319
+ case "User":
320
+ case "Steering": return estimateUserContentChars(message.content);
321
+ case "Assistant":
322
+ case "AssistantPartial": return estimateAssistantPromptChars(message.promptParts, message.content);
323
+ }
324
+ };
325
+ const estimateAssociatedToolChars = (message, state) => {
326
+ if (message._tag !== "Assistant" && message._tag !== "AssistantPartial") return 0;
327
+ return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
328
+ };
329
+ const messageSeq = (message) => message._tag === "Steering" ? message.consumedSeq : message.seq;
330
+ const charsToTokens = (chars, charsPerToken) => Math.ceil(chars / charsPerToken);
331
+ const buildSummaryPrompt = (input) => {
332
+ const sourceText = serializeCompactionSource(input);
333
+ if (sourceText.trim().length === 0) return;
334
+ return `${input.context.currentSummary === void 0 ? "" : `<previous-summary>\n${input.context.currentSummary.text}\n</previous-summary>\n\n`}<conversation>\n${sourceText}\n</conversation>\n\n${summaryPromptText}`;
335
+ };
336
+ const serializeCompactionSource = (input) => {
337
+ const lines = [];
338
+ for (const message of durableMessageTranscript(input.state)) {
339
+ const seq = messageSeq(message);
340
+ if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) continue;
341
+ lines.push(serializeDurableMessage(message));
342
+ if (message._tag === "Assistant" || message._tag === "AssistantPartial") for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) lines.push(serializeToolResultPart(part));
343
+ }
344
+ return lines.filter((line) => line.trim().length > 0).join("\n\n");
345
+ };
346
+ const serializeDurableMessage = (message) => {
347
+ switch (message._tag) {
348
+ case "User": return `[User]: ${userContentText(message.content)}`;
349
+ case "Steering": return `[User steering]: ${userContentText(message.content)}`;
350
+ case "Assistant":
351
+ case "AssistantPartial": return serializeAssistantMessage(message.promptParts, message.content);
352
+ }
353
+ };
354
+ const serializeAssistantMessage = (promptParts, content) => {
355
+ const parts = promptParts ?? assistantContentToPromptParts(content);
356
+ const text = [];
357
+ const reasoning = [];
358
+ const toolCalls = [];
359
+ const sideband = [];
360
+ for (const part of parts) switch (part.type) {
361
+ case "text":
362
+ text.push(part.text);
363
+ break;
364
+ case "reasoning":
365
+ reasoning.push(part.text);
366
+ break;
367
+ case "tool-call":
368
+ toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);
369
+ break;
370
+ case "file":
371
+ sideband.push(`file(${part.fileName ?? "unnamed"}, ${part.mediaType})`);
372
+ break;
373
+ case "tool-result":
374
+ sideband.push(`tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`);
375
+ break;
376
+ case "tool-approval-request":
377
+ sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);
378
+ break;
379
+ }
380
+ return [
381
+ reasoning.length === 0 ? "" : `[Assistant reasoning]: ${reasoning.join("\n")}`,
382
+ text.length === 0 ? "" : `[Assistant]: ${text.join("\n")}`,
383
+ toolCalls.length === 0 ? "" : `[Assistant tool calls]: ${toolCalls.join("; ")}`,
384
+ sideband.length === 0 ? "" : `[Assistant context]: ${sideband.join("; ")}`
385
+ ].filter((line) => line.length > 0).join("\n");
386
+ };
387
+ const serializeToolResultPart = (part) => `[Tool result ${part.name}${part.isFailure ? " failed" : ""}]: ${truncateForSummary(safeJsonStringify(part.result))}`;
388
+ const toolPromptPartsForInference = (inferenceId, toolCalls) => Array.from(toolCalls.values()).flatMap((tool) => {
389
+ const { decision } = tool;
390
+ if (decision === void 0 || decision.inferenceId !== inferenceId) return [];
391
+ if (decision._tag === "Rejected") return decision.promptPart === void 0 ? [] : [decision.promptPart];
392
+ const terminal = tool.terminal;
393
+ if (terminal === void 0 || terminal.promptPart === void 0) return [];
394
+ return [terminal.promptPart];
395
+ });
396
+ const assistantContentToPromptParts = (content) => [...content.reasoning === void 0 ? [] : [Prompt.reasoningPart({ text: content.reasoning })], ...content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]];
397
+ const estimateAssistantPromptChars = (promptParts, content) => (promptParts ?? assistantContentToPromptParts(content)).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
398
+ const estimateUserContentChars = (content) => typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
399
+ const estimatePromptMessageChars = (message) => {
400
+ if (!("content" in message)) return 0;
401
+ const { content } = message;
402
+ return typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
403
+ };
404
+ const estimatePromptPartChars = (part) => {
405
+ switch (part.type) {
406
+ case "text": return part.text.length;
407
+ case "reasoning": return part.text.length;
408
+ case "file": return part.mediaType.length + (part.fileName?.length ?? 0) + (typeof part.data === "string" ? part.data.length : part.data instanceof URL ? part.data.toString().length : estimatedBinaryFileChars);
409
+ case "tool-call": return part.name.length + safeJsonStringify(part.params).length;
410
+ case "tool-result": return part.name.length + safeJsonStringify(part.result).length;
411
+ case "tool-approval-response": return part.approvalId.length + (part.reason?.length ?? 0) + 8;
412
+ case "tool-approval-request": return part.approvalId.length + part.toolCallId.length;
413
+ default: return safeJsonStringify(part).length;
414
+ }
415
+ };
416
+ const userContentText = (content) => typeof content === "string" ? content : content.map((part) => {
417
+ switch (part.type) {
418
+ case "text": return part.text;
419
+ case "file": return `[file ${part.fileName ?? "unnamed"} ${part.mediaType}]`;
420
+ }
421
+ }).join("\n");
422
+ const safeJsonStringify = (value) => {
423
+ try {
424
+ return JSON.stringify(value) ?? String(value);
425
+ } catch {
426
+ return String(value);
427
+ }
428
+ };
429
+ const truncateForSummary = (text, maxChars = 2e3) => {
430
+ if (text.length <= maxChars) return text;
431
+ return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} more characters truncated]`;
432
+ };
433
+ const formatUnknownError = (error) => error instanceof Error ? error.message : String(error);
434
+ const estimatedBinaryFileChars = 4800;
435
+ const summarizationSystemPrompt = "You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.";
436
+ const 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.
437
+
438
+ Use this exact structure:
439
+
440
+ ## Goal
441
+ [What the user is trying to accomplish]
442
+
443
+ ## Constraints & Preferences
444
+ - [Requirements, constraints, and preferences]
445
+
446
+ ## Progress
447
+ ### Done
448
+ - [x] [Completed work]
449
+
450
+ ### In Progress
451
+ - [ ] [Current unfinished work]
452
+
453
+ ### Blocked
454
+ - [Current blockers, or "(none)"]
455
+
456
+ ## Key Decisions
457
+ - **[Decision]**: [Rationale]
458
+
459
+ ## Next Steps
460
+ 1. [Concrete next step]
461
+
462
+ ## Critical Context
463
+ - [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]
464
+
465
+ Rules:
466
+ - If <previous-summary> is present, preserve important existing facts and update it with the new conversation.
467
+ - Keep the summary concise but sufficient to replace the compacted history.
468
+ - Preserve exact file paths, tool names, identifiers, and error messages.
469
+ - Do not answer questions from the conversation.`;
470
+ //#endregion
471
+ export { CompactionPolicy as a, defaultCompactionMinSummarizableTokens as c, makeUsagePayload as d, CompactionPlan as i, defaultCompactionRetainTailTokens as l, CompactionExecutor as n, CompactionRunner as o, CompactionOutput as r, defaultCompactionCharsPerToken as s, CompactionError as t, defaultCompactionThresholdTokens as u };
472
+
473
+ //# sourceMappingURL=compaction-0k8zCJgB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction-0k8zCJgB.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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,OAAO,KAAK;EACd,KAAK,QACH,OAAO,SAAS,KAAK,YAAY,UAAU,GAAG,KAAK,UAAU;CACjE;AACF,CAAC,EACA,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,7 +1,10 @@
1
- import { f as CompactionExecutorId, m as ContextProjection, o as EDASessionStoreError, p as CompactionPolicyId, r as DurableAppendEntry, t as CommittedDurableEvent } from "./session-store-D2Ore1QC.js";
2
- import { S as ReducedState } from "./command-queues-CQ9cwRP7.js";
3
- import { t as IdGenerator } from "./id-generator-C2Q15uZM.js";
4
- import { n as EventFactory, t as EDAKeepAlive } from "./keep-alive-DYDsH6qN.js";
1
+ import { S as ReducedState } from "./command-queues-CQi4Xc7u.js";
2
+ import { i as ContextProjection, n as CompactionPolicyId, t as CompactionExecutorId } from "./context-projection-mCuvcO2W.js";
3
+ import { o as EDASessionStoreError, r as DurableAppendEntry, t as CommittedDurableEvent } from "./session-store-J_Un45kW.js";
4
+ import { t as ModelResolver } from "./model-resolver-BPPJAsuh.js";
5
+ import { t as IdGenerator } from "./id-generator--x6itQZ2.js";
6
+ import { t as EventFactory } from "./event-factory-KaeDSfeP.js";
7
+ import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
5
8
  import * as Context from "effect/Context";
6
9
  import * as Effect from "effect/Effect";
7
10
  import * as Layer from "effect/Layer";
@@ -77,14 +80,32 @@ declare const CompactionOutput: Schema.Struct<{
77
80
  readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
78
81
  }>;
79
82
  readonly executorId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CompactionExecutorId">>;
83
+ readonly usage: Schema.optionalKey<Schema.Struct<{
84
+ readonly inputTokens: Schema.optionalKey<Schema.Int>;
85
+ readonly cachedInputTokens: Schema.optionalKey<Schema.Int>;
86
+ readonly cacheWriteInputTokens: Schema.optionalKey<Schema.Int>;
87
+ readonly outputTokens: Schema.optionalKey<Schema.Int>;
88
+ readonly textTokens: Schema.optionalKey<Schema.Int>;
89
+ readonly reasoningTokens: Schema.optionalKey<Schema.Int>;
90
+ }>>;
80
91
  }>;
81
92
  type CompactionOutput = typeof CompactionOutput.Type;
82
93
  /** Executor input with framework-minted lifecycle identities. */
83
94
  interface CompactionExecutorInput extends CompactionPolicyInput {
84
95
  readonly plan: CompactionPlan;
96
+ /** Provider service resolved from the same durable selection used for accounting. */
97
+ readonly model: LanguageModel.Service;
85
98
  }
86
99
  declare const CompactionError_base: Schema.Class<CompactionError, Schema.TaggedStruct<"CompactionError", {
87
100
  readonly message: Schema.String;
101
+ readonly usage: Schema.optionalKey<Schema.Struct<{
102
+ readonly inputTokens: Schema.optionalKey<Schema.Int>;
103
+ readonly cachedInputTokens: Schema.optionalKey<Schema.Int>;
104
+ readonly cacheWriteInputTokens: Schema.optionalKey<Schema.Int>;
105
+ readonly outputTokens: Schema.optionalKey<Schema.Int>;
106
+ readonly textTokens: Schema.optionalKey<Schema.Int>;
107
+ readonly reasoningTokens: Schema.optionalKey<Schema.Int>;
108
+ }>>;
88
109
  }>, import("effect/Cause").YieldableError>;
89
110
  /** Typed failure from policy planning or summary generation. */
90
111
  declare class CompactionError extends CompactionError_base {}
@@ -121,7 +142,7 @@ declare class CompactionExecutor extends CompactionExecutor_base {
121
142
  /** Test/app hook for replacing summary generation. */
122
143
  static readonly FromFunction: (id: string, execute: CompactionExecutorShape["execute"]) => Layer.Layer<CompactionExecutor>;
123
144
  /** Summary executor backed by the configured Effect AI LanguageModel. */
124
- static readonly LanguageModelSummary: (options?: LanguageModelSummaryCompactionExecutorOptions) => Layer.Layer<CompactionExecutor, never, LanguageModel.LanguageModel>;
145
+ static readonly LanguageModelSummary: (options?: LanguageModelSummaryCompactionExecutorOptions) => Layer.Layer<CompactionExecutor>;
125
146
  }
126
147
  /** Inputs needed by the framework-owned compaction lifecycle runner. */
127
148
  interface CompactionRunnerInput {
@@ -137,8 +158,8 @@ interface CompactionRunnerShape {
137
158
  declare const CompactionRunner_base: Context.ServiceClass<CompactionRunner, "@effect-durable-agent/CompactionRunner", CompactionRunnerShape>;
138
159
  /** Framework-owned compaction lifecycle runner. */
139
160
  declare class CompactionRunner extends CompactionRunner_base {
140
- static readonly Live: Layer.Layer<CompactionRunner, never, IdGenerator | CompactionPolicy | CompactionExecutor | EventFactory | EDAKeepAlive>;
161
+ static readonly Live: Layer.Layer<CompactionRunner, never, ModelResolver | EDAKeepAlive | EventFactory | IdGenerator | CompactionPolicy | CompactionExecutor>;
141
162
  }
142
163
  //#endregion
143
164
  export { defaultCompactionRetainTailTokens as _, CompactionExecutorShape as a, CompactionPolicy as c, CompactionRunner as d, CompactionRunnerInput as f, defaultCompactionMinSummarizableTokens as g, defaultCompactionCharsPerToken as h, CompactionExecutorInput as i, CompactionPolicyInput as l, LanguageModelSummaryCompactionExecutorOptions as m, CompactionError as n, CompactionOutput as o, CompactionRunnerShape as p, CompactionExecutor as r, CompactionPlan as s, ApproximateTokenThresholdCompactionPolicyOptions as t, CompactionPolicyShape as u, defaultCompactionThresholdTokens as v };
144
- //# sourceMappingURL=compaction-YayFKo_1.d.ts.map
165
+ //# sourceMappingURL=compaction-BhLSSXJ-.d.ts.map