effect-durable-agent 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +21 -0
- package/README.md +305 -0
- package/SECURITY.md +8 -0
- package/dist/command-queues-CQ9cwRP7.d.ts +468 -0
- package/dist/commands-Ce1ec6kH.d.ts +104 -0
- package/dist/compaction-YayFKo_1.d.ts +144 -0
- package/dist/core-Hv3cFydL.d.ts +81 -0
- package/dist/domain/command-queues.d.ts +2 -0
- package/dist/domain/command-queues.js +97 -0
- package/dist/domain/command-queues.js.map +1 -0
- package/dist/domain/message-transcript.d.ts +2 -0
- package/dist/domain/message-transcript.js +111 -0
- package/dist/domain/message-transcript.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +996 -0
- package/dist/domain/reduced-state-schema.js +286 -0
- package/dist/domain/reduced-state-schema.js.map +1 -0
- package/dist/domain/reduced-state.d.ts +2 -0
- package/dist/domain/reduced-state.js +2 -0
- package/dist/durable-C3Rz7kg3.js +625 -0
- package/dist/durable-C3Rz7kg3.js.map +1 -0
- package/dist/durable-DlScwmCy.d.ts +7424 -0
- package/dist/durable-object-runtime-B7jwBY2R.js +1494 -0
- package/dist/durable-object-runtime-B7jwBY2R.js.map +1 -0
- package/dist/durable-object-runtime-pWv0ohlz.d.ts +257 -0
- package/dist/durable-object-storage-Czy7IPrh.d.ts +41 -0
- package/dist/events-Bb9-Cu-7.d.ts +918 -0
- package/dist/host/durable-object-runtime.d.ts +2 -0
- package/dist/host/durable-object-runtime.js +2 -0
- package/dist/host/durable-object-storage.d.ts +2 -0
- package/dist/host/durable-object-storage.js +0 -0
- package/dist/host/durable-object.d.ts +83 -0
- package/dist/host/durable-object.js +191 -0
- package/dist/host/durable-object.js.map +1 -0
- package/dist/host/websocket-wire.d.ts +2 -0
- package/dist/host/websocket-wire.js +88 -0
- package/dist/host/websocket-wire.js.map +1 -0
- package/dist/id-generator-C2Q15uZM.d.ts +33 -0
- package/dist/index-BVVgDSdq.d.ts +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/keep-alive-DYDsH6qN.d.ts +111 -0
- package/dist/keep-alive-p8dIcSVy.js +109 -0
- package/dist/keep-alive-p8dIcSVy.js.map +1 -0
- package/dist/message-transcript-BCHdHAe2.d.ts +32 -0
- package/dist/prompt-projector-9_02lk5-.d.ts +40 -0
- package/dist/reduced-state-C4nVVzz9.js +910 -0
- package/dist/reduced-state-C4nVVzz9.js.map +1 -0
- package/dist/reducer-registry-C0svUa63.d.ts +69 -0
- package/dist/runtime-C56FQxiL.d.ts +60 -0
- package/dist/services/compaction.d.ts +2 -0
- package/dist/services/compaction.js +426 -0
- package/dist/services/compaction.js.map +1 -0
- package/dist/services/id-generator.d.ts +2 -0
- package/dist/services/id-generator.js +56 -0
- package/dist/services/id-generator.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +2 -0
- package/dist/services/prompt-projector.js +27 -0
- package/dist/services/prompt-projector.js.map +1 -0
- package/dist/services/reducer-registry.d.ts +2 -0
- package/dist/services/reducer-registry.js +71 -0
- package/dist/services/reducer-registry.js.map +1 -0
- package/dist/services/runtime.d.ts +2 -0
- package/dist/services/runtime.js +84 -0
- package/dist/services/runtime.js.map +1 -0
- package/dist/services/session-query.d.ts +2 -0
- package/dist/services/session-query.js +2 -0
- package/dist/services/session-store.d.ts +2 -0
- package/dist/services/session-store.js +2 -0
- package/dist/services/sink-registry.d.ts +2 -0
- package/dist/services/sink-registry.js +2 -0
- package/dist/services/span-names.d.ts +28 -0
- package/dist/services/span-names.js +42 -0
- package/dist/services/span-names.js.map +1 -0
- package/dist/services/tool-registry.d.ts +2 -0
- package/dist/services/tool-registry.js +46 -0
- package/dist/services/tool-registry.js.map +1 -0
- package/dist/services/tracing.d.ts +76 -0
- package/dist/services/tracing.js +116 -0
- package/dist/services/tracing.js.map +1 -0
- package/dist/session-query-DOc1KanA.js +2930 -0
- package/dist/session-query-DOc1KanA.js.map +1 -0
- package/dist/session-query-DlRo5Ufc.d.ts +769 -0
- package/dist/session-store-D2Ore1QC.d.ts +295 -0
- package/dist/session-store-pYxQW9qh.js +214 -0
- package/dist/session-store-pYxQW9qh.js.map +1 -0
- package/dist/sink-registry-CFC6xjsN.js +312 -0
- package/dist/sink-registry-CFC6xjsN.js.map +1 -0
- package/dist/sink-registry-CIU0LD3m.d.ts +158 -0
- package/dist/testkit/layers.d.ts +101 -0
- package/dist/testkit/layers.js +108 -0
- package/dist/testkit/layers.js.map +1 -0
- package/dist/tool-registry-CcnkAAQK.d.ts +51 -0
- package/dist/tracing-BXHAkxkx.d.ts +111 -0
- package/dist/types/commands.d.ts +2 -0
- package/dist/types/commands.js +60 -0
- package/dist/types/commands.js.map +1 -0
- package/dist/types/core.d.ts +2 -0
- package/dist/types/core.js +68 -0
- package/dist/types/core.js.map +1 -0
- package/dist/types/events/durable.d.ts +2 -0
- package/dist/types/events/durable.js +2 -0
- package/dist/types/events.d.ts +4 -0
- package/dist/types/events.js +90 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/tracing.d.ts +2 -0
- package/dist/types/tracing.js +99 -0
- package/dist/types/tracing.js.map +1 -0
- package/dist/websocket-wire-DvOu_6BJ.d.ts +16773 -0
- package/docs/assets/architecture.svg +106 -0
- package/docs/assets/event-sequence.svg +143 -0
- package/docs/assets/gcp-trace.png +0 -0
- package/docs/message-steering.md +831 -0
- package/docs/releasing.md +57 -0
- package/docs/spec.md +774 -0
- package/docs/subagents.md +725 -0
- package/docs/testing.md +64 -0
- package/docs/ui-projection.md +742 -0
- package/docs/websocket-protocol.md +613 -0
- package/examples/001-no-tools/README.md +65 -0
- package/examples/001-no-tools/worker.ts +79 -0
- package/examples/002-slack-bridge/README.md +134 -0
- package/examples/002-slack-bridge/events.ts +115 -0
- package/examples/002-slack-bridge/reducer.ts +216 -0
- package/examples/002-slack-bridge/scenario.test.ts +223 -0
- package/examples/002-slack-bridge/sinks.ts +109 -0
- package/examples/002-slack-bridge/worker.ts +140 -0
- package/examples/003-sandbox-lifecycle/README.md +78 -0
- package/examples/003-sandbox-lifecycle/events.ts +203 -0
- package/examples/003-sandbox-lifecycle/reducer.ts +305 -0
- package/examples/003-sandbox-lifecycle/scenario.test.ts +202 -0
- package/examples/_shared/event-id.ts +12 -0
- package/examples/_shared/http.ts +27 -0
- package/examples/_shared/openai.ts +33 -0
- package/package.json +181 -0
- package/testing/offline-trace/README.md +63 -0
- package/tooling/oxlint/index.mjs +15 -0
- package/tooling/oxlint/rules/effect-span-from-catalog.mjs +152 -0
- package/tooling/oxlint/rules/span-catalog-format.mjs +74 -0
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import { ContextVersion, SequenceNumber } from "../types/core.js";
|
|
2
|
+
import { cr as FailurePayload } from "../durable-C3Rz7kg3.js";
|
|
3
|
+
import { d as CompactionSummaryArtifact, l as CompactionExecutorId, u as CompactionPolicyId } from "../session-store-pYxQW9qh.js";
|
|
4
|
+
import { durableMessageTranscript } from "../domain/message-transcript.js";
|
|
5
|
+
import { IdGenerator } from "./id-generator.js";
|
|
6
|
+
import { n as EventFactory, t as EDAKeepAlive } from "../keep-alive-p8dIcSVy.js";
|
|
7
|
+
import { annotateEdaSpan, committedBatchAttributes } from "./tracing.js";
|
|
8
|
+
import * as Context from "effect/Context";
|
|
9
|
+
import * as Effect from "effect/Effect";
|
|
10
|
+
import * as Layer from "effect/Layer";
|
|
11
|
+
import * as Schema from "effect/Schema";
|
|
12
|
+
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
13
|
+
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
14
|
+
//#region src/services/compaction.ts
|
|
15
|
+
/** Candidate durable range and retained cursor selected by compaction policy. */
|
|
16
|
+
const CompactionPlan = Schema.Struct({
|
|
17
|
+
policyId: CompactionPolicyId,
|
|
18
|
+
sourceFromSeq: SequenceNumber,
|
|
19
|
+
sourceToSeq: SequenceNumber,
|
|
20
|
+
retainedFromContextSeq: SequenceNumber
|
|
21
|
+
});
|
|
22
|
+
/** Rough token heuristic used by the built-in compaction presets. */
|
|
23
|
+
const defaultCompactionCharsPerToken = 4;
|
|
24
|
+
/** Production-oriented context threshold for the built-in approximate-token policy. */
|
|
25
|
+
const defaultCompactionThresholdTokens = 22e4;
|
|
26
|
+
/** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */
|
|
27
|
+
const defaultCompactionRetainTailTokens = 4e4;
|
|
28
|
+
/** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */
|
|
29
|
+
const defaultCompactionMinSummarizableTokens = 1e4;
|
|
30
|
+
/** Result produced by the summary executor before the framework commits it. */
|
|
31
|
+
const CompactionOutput = Schema.Struct({
|
|
32
|
+
text: Schema.NonEmptyString,
|
|
33
|
+
promptMessage: Prompt.UserMessage,
|
|
34
|
+
executorId: Schema.optionalKey(CompactionExecutorId)
|
|
35
|
+
});
|
|
36
|
+
/** Typed failure from policy planning or summary generation. */
|
|
37
|
+
var CompactionError = class extends Schema.TaggedErrorClass()("CompactionError", { message: Schema.String }) {};
|
|
38
|
+
/** Decides whether a safe prompt-context rebase should be attempted. */
|
|
39
|
+
var CompactionPolicy = class CompactionPolicy extends Context.Service()("@effect-durable-agent/CompactionPolicy") {
|
|
40
|
+
/** Default policy: compaction is disabled and commits no skip events. */
|
|
41
|
+
static Disabled = Layer.succeed(CompactionPolicy, {
|
|
42
|
+
id: CompactionPolicyId.make("disabled"),
|
|
43
|
+
plan: () => Effect.succeed(void 0)
|
|
44
|
+
});
|
|
45
|
+
/** Test/app hook for replacing the policy with a concrete planner. */
|
|
46
|
+
static FromFunction = (id, plan) => Layer.succeed(CompactionPolicy, {
|
|
47
|
+
id: CompactionPolicyId.make(id),
|
|
48
|
+
plan
|
|
49
|
+
});
|
|
50
|
+
/**
|
|
51
|
+
* Common production policy: compact when approximate prompt context exceeds a token threshold.
|
|
52
|
+
*
|
|
53
|
+
* The policy keeps a recent tail verbatim, summarizes the older prefix, and advances from the
|
|
54
|
+
* current summary cursor so repeated compactions behave like the first one.
|
|
55
|
+
*/
|
|
56
|
+
static ApproximateTokenThreshold = (options = {}) => {
|
|
57
|
+
const normalized = normalizeApproximateTokenPolicyOptions(options);
|
|
58
|
+
return Layer.succeed(CompactionPolicy, {
|
|
59
|
+
id: normalized.policyId,
|
|
60
|
+
plan: ({ state, context }) => Effect.sync(() => planApproximateTokenCompaction(state, context, normalized))
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
/** Produces a cumulative summary artifact for a selected compaction plan. */
|
|
65
|
+
var CompactionExecutor = class CompactionExecutor extends Context.Service()("@effect-durable-agent/CompactionExecutor") {
|
|
66
|
+
/** Placeholder executor for the disabled default policy. It should never be called. */
|
|
67
|
+
static Disabled = Layer.succeed(CompactionExecutor, {
|
|
68
|
+
id: CompactionExecutorId.make("disabled"),
|
|
69
|
+
execute: () => Effect.die(/* @__PURE__ */ new Error("CompactionExecutor.Disabled was called"))
|
|
70
|
+
});
|
|
71
|
+
/** Test/app hook for replacing summary generation. */
|
|
72
|
+
static FromFunction = (id, execute) => Layer.succeed(CompactionExecutor, {
|
|
73
|
+
id: CompactionExecutorId.make(id),
|
|
74
|
+
execute
|
|
75
|
+
});
|
|
76
|
+
/** Summary executor backed by the configured Effect AI LanguageModel. */
|
|
77
|
+
static LanguageModelSummary = (options = {}) => Layer.effect(CompactionExecutor, Effect.gen(function* () {
|
|
78
|
+
const languageModel = yield* LanguageModel.LanguageModel;
|
|
79
|
+
const executorId = CompactionExecutorId.make(options.executorId ?? "language-model-summary");
|
|
80
|
+
const summaryMessagePrefix = options.summaryMessagePrefix ?? "Conversation summary:";
|
|
81
|
+
return {
|
|
82
|
+
id: executorId,
|
|
83
|
+
execute: Effect.fn("agent.compaction")(function* (input) {
|
|
84
|
+
yield* annotateEdaSpan({
|
|
85
|
+
"eda.compaction.policy_id": input.plan.policyId,
|
|
86
|
+
"eda.compaction.source_from_seq": input.plan.sourceFromSeq,
|
|
87
|
+
"eda.compaction.source_to_seq": input.plan.sourceToSeq,
|
|
88
|
+
"eda.compaction.retained_from_context_seq": input.plan.retainedFromContextSeq,
|
|
89
|
+
"eda.compaction.executor_id": executorId
|
|
90
|
+
});
|
|
91
|
+
const promptText = buildSummaryPrompt(input);
|
|
92
|
+
if (promptText === void 0) return yield* new CompactionError({ message: "compaction plan selected no source messages" });
|
|
93
|
+
const text = (yield* languageModel.generateText({
|
|
94
|
+
prompt: Prompt.fromMessages([Prompt.makeMessage("system", { content: summarizationSystemPrompt }), Prompt.makeMessage("user", { content: [Prompt.textPart({ text: promptText })] })]),
|
|
95
|
+
toolChoice: "none"
|
|
96
|
+
}).pipe(Effect.mapError((error) => new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` })))).text.trim();
|
|
97
|
+
if (text.length === 0) return yield* new CompactionError({ message: "summary model returned no text" });
|
|
98
|
+
return CompactionOutput.make({
|
|
99
|
+
text,
|
|
100
|
+
promptMessage: Prompt.makeMessage("user", { content: [Prompt.textPart({ text: `${summaryMessagePrefix}\n\n${text}` })] }),
|
|
101
|
+
executorId
|
|
102
|
+
});
|
|
103
|
+
})
|
|
104
|
+
};
|
|
105
|
+
}));
|
|
106
|
+
};
|
|
107
|
+
/** Framework-owned compaction lifecycle runner. */
|
|
108
|
+
var CompactionRunner = class CompactionRunner extends Context.Service()("@effect-durable-agent/CompactionRunner") {
|
|
109
|
+
static Live = Layer.effect(CompactionRunner, Effect.suspend(() => makeLiveCompactionRunner));
|
|
110
|
+
};
|
|
111
|
+
const makeLiveCompactionRunner = Effect.gen(function* () {
|
|
112
|
+
const ids = yield* IdGenerator;
|
|
113
|
+
const events = yield* EventFactory;
|
|
114
|
+
const policy = yield* CompactionPolicy;
|
|
115
|
+
const executor = yield* CompactionExecutor;
|
|
116
|
+
const keepAlive = yield* EDAKeepAlive;
|
|
117
|
+
return { maybeCompact: Effect.fnUntraced(function* (input) {
|
|
118
|
+
const plan = yield* policy.plan({
|
|
119
|
+
state: input.state,
|
|
120
|
+
context: input.context
|
|
121
|
+
}).pipe(Effect.catchTag("CompactionError", (error) => Effect.logError("compaction policy failed", { error }).pipe(Effect.as(void 0))));
|
|
122
|
+
if (plan === void 0) {
|
|
123
|
+
yield* annotateEdaSpan({ "eda.compaction.selected": false });
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
yield* annotateEdaSpan({
|
|
127
|
+
"eda.compaction.selected": true,
|
|
128
|
+
"eda.compaction.policy_id": plan.policyId,
|
|
129
|
+
"eda.compaction.source_from_seq": plan.sourceFromSeq,
|
|
130
|
+
"eda.compaction.source_to_seq": plan.sourceToSeq,
|
|
131
|
+
"eda.compaction.retained_from_context_seq": plan.retainedFromContextSeq
|
|
132
|
+
});
|
|
133
|
+
const invalidPlan = validatePlan(plan, input.state, input.context);
|
|
134
|
+
if (invalidPlan !== void 0) {
|
|
135
|
+
yield* Effect.logError("compaction policy returned invalid plan", { reason: invalidPlan });
|
|
136
|
+
return [];
|
|
137
|
+
}
|
|
138
|
+
const compactionId = yield* ids.makeCompactionId();
|
|
139
|
+
const summaryId = yield* ids.makeSummaryId();
|
|
140
|
+
yield* annotateEdaSpan({
|
|
141
|
+
"eda.compaction.id": compactionId,
|
|
142
|
+
"eda.summary.id": summaryId
|
|
143
|
+
});
|
|
144
|
+
const requested = yield* events.compactionRequested({
|
|
145
|
+
compactionId,
|
|
146
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
147
|
+
sourceToSeq: plan.sourceToSeq
|
|
148
|
+
});
|
|
149
|
+
const started = yield* events.compactionStarted({ compactionId });
|
|
150
|
+
const startedEvents = yield* input.appendDurableEntries([{ event: requested }, { event: started }]);
|
|
151
|
+
const output = yield* keepAlive.withActiveWork(`compaction:${compactionId}`, executor.execute({
|
|
152
|
+
plan,
|
|
153
|
+
state: input.state,
|
|
154
|
+
context: input.context
|
|
155
|
+
})).pipe(Effect.catchTag("CompactionError", (error) => Effect.gen(function* () {
|
|
156
|
+
const failed = yield* events.compactionFailed({
|
|
157
|
+
compactionId,
|
|
158
|
+
error: FailurePayload.make({ message: error.message })
|
|
159
|
+
});
|
|
160
|
+
return {
|
|
161
|
+
_tag: "Failed",
|
|
162
|
+
committed: yield* input.appendDurableEntries([{ event: failed }])
|
|
163
|
+
};
|
|
164
|
+
})), Effect.map((result) => "_tag" in result ? result : {
|
|
165
|
+
_tag: "Output",
|
|
166
|
+
output: result
|
|
167
|
+
}));
|
|
168
|
+
if (output._tag === "Failed") return [...startedEvents, ...output.committed];
|
|
169
|
+
const artifact = CompactionSummaryArtifact.make({
|
|
170
|
+
compactionId,
|
|
171
|
+
summaryId,
|
|
172
|
+
...input.context.currentSummary === void 0 ? {} : { previousSummaryId: input.context.currentSummary.summaryId },
|
|
173
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
174
|
+
sourceToSeq: plan.sourceToSeq,
|
|
175
|
+
retainedFromContextSeq: plan.retainedFromContextSeq,
|
|
176
|
+
text: output.output.text,
|
|
177
|
+
promptMessage: output.output.promptMessage,
|
|
178
|
+
policyId: plan.policyId,
|
|
179
|
+
...output.output.executorId === void 0 ? {} : { executorId: output.output.executorId }
|
|
180
|
+
});
|
|
181
|
+
const summaryCreated = yield* events.summaryCreated({
|
|
182
|
+
compactionId,
|
|
183
|
+
summaryId,
|
|
184
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
185
|
+
sourceToSeq: plan.sourceToSeq,
|
|
186
|
+
summary: artifact
|
|
187
|
+
});
|
|
188
|
+
const contextRebased = yield* events.contextRebased({
|
|
189
|
+
compactionId,
|
|
190
|
+
summaryId,
|
|
191
|
+
contextVersion: ContextVersion.make(input.context.contextVersion + 1),
|
|
192
|
+
retainedFromContextSeq: plan.retainedFromContextSeq
|
|
193
|
+
});
|
|
194
|
+
const completed = yield* events.compactionCompleted({ compactionId });
|
|
195
|
+
const committed = yield* input.appendDurableEntries([
|
|
196
|
+
{ event: summaryCreated },
|
|
197
|
+
{ event: contextRebased },
|
|
198
|
+
{ event: completed }
|
|
199
|
+
]);
|
|
200
|
+
yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));
|
|
201
|
+
return [...startedEvents, ...committed];
|
|
202
|
+
}) };
|
|
203
|
+
});
|
|
204
|
+
const validatePlan = (plan, state, context) => {
|
|
205
|
+
const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
|
|
206
|
+
if (plan.retainedFromContextSeq <= currentRetainedFromSeq) return "retainedFromContextSeq must advance beyond the current summary cursor";
|
|
207
|
+
if (plan.sourceToSeq > state.lastSeq) return "sourceToSeq must not exceed the current durable head";
|
|
208
|
+
if (plan.retainedFromContextSeq > state.lastSeq + 1) return "retainedFromContextSeq must not skip unsummarized future context";
|
|
209
|
+
if (plan.sourceFromSeq > plan.sourceToSeq) return "sourceFromSeq must be less than or equal to sourceToSeq";
|
|
210
|
+
if (plan.retainedFromContextSeq <= plan.sourceToSeq) return "retainedFromContextSeq must start after the summarized source range";
|
|
211
|
+
};
|
|
212
|
+
const normalizeApproximateTokenPolicyOptions = (options) => ({
|
|
213
|
+
policyId: CompactionPolicyId.make(options.policyId ?? "approximate-token-threshold"),
|
|
214
|
+
thresholdTokens: positiveNumber(options.thresholdTokens ?? 22e4, "thresholdTokens"),
|
|
215
|
+
retainTailTokens: nonNegativeNumber(options.retainTailTokens ?? 4e4, "retainTailTokens"),
|
|
216
|
+
minSummarizableTokens: nonNegativeNumber(options.minSummarizableTokens ?? 1e4, "minSummarizableTokens"),
|
|
217
|
+
charsPerToken: positiveNumber(options.charsPerToken ?? 4, "charsPerToken")
|
|
218
|
+
});
|
|
219
|
+
const positiveNumber = (value, name) => {
|
|
220
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive finite number`);
|
|
221
|
+
return value;
|
|
222
|
+
};
|
|
223
|
+
const nonNegativeNumber = (value, name) => {
|
|
224
|
+
if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative finite number`);
|
|
225
|
+
return value;
|
|
226
|
+
};
|
|
227
|
+
/** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */
|
|
228
|
+
const planApproximateTokenCompaction = (state, context, options) => {
|
|
229
|
+
const messages = estimatedContextMessages(state);
|
|
230
|
+
if (estimateCurrentPromptChars(state, context, messages) <= options.thresholdTokens * options.charsPerToken) return;
|
|
231
|
+
const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
|
|
232
|
+
const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);
|
|
233
|
+
if (retainedFromSeq <= currentRetainedFromSeq) return;
|
|
234
|
+
const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);
|
|
235
|
+
if (sourceMessages.length === 0) return;
|
|
236
|
+
if (charsToTokens(sourceMessages.reduce((sum, message) => sum + message.chars, 0), options.charsPerToken) < options.minSummarizableTokens) return;
|
|
237
|
+
const sourceFromSeq = currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0].seq;
|
|
238
|
+
const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);
|
|
239
|
+
if (sourceFromSeq > sourceToSeq) return;
|
|
240
|
+
return CompactionPlan.make({
|
|
241
|
+
policyId: options.policyId,
|
|
242
|
+
sourceFromSeq,
|
|
243
|
+
sourceToSeq,
|
|
244
|
+
retainedFromContextSeq: retainedFromSeq
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
const selectRetainedFromSeq = (messages, lastSeq, options) => {
|
|
248
|
+
if (options.retainTailTokens === 0) return SequenceNumber.make(lastSeq + 1);
|
|
249
|
+
const retainTailChars = options.retainTailTokens * options.charsPerToken;
|
|
250
|
+
let tailChars = 0;
|
|
251
|
+
let retainedIndex = messages.length;
|
|
252
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
253
|
+
tailChars += messages[index].chars;
|
|
254
|
+
retainedIndex = index;
|
|
255
|
+
if (tailChars >= retainTailChars) break;
|
|
256
|
+
}
|
|
257
|
+
return retainedIndex >= messages.length ? SequenceNumber.make(lastSeq + 1) : messages[retainedIndex].seq;
|
|
258
|
+
};
|
|
259
|
+
const estimateCurrentPromptChars = (state, context, messages) => {
|
|
260
|
+
const systemChars = Array.from(state.messages.values()).reduce((sum, message) => message._tag === "System" ? sum + message.content.length : sum, 0);
|
|
261
|
+
const summaryChars = context.currentSummary === void 0 ? 0 : estimatePromptMessageChars(context.currentSummary.promptMessage);
|
|
262
|
+
const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);
|
|
263
|
+
return systemChars + summaryChars + messageChars;
|
|
264
|
+
};
|
|
265
|
+
const estimatedContextMessages = (state) => durableMessageTranscript(state).map((message) => ({
|
|
266
|
+
message,
|
|
267
|
+
seq: messageSeq(message),
|
|
268
|
+
chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state)
|
|
269
|
+
}));
|
|
270
|
+
const estimateDurableMessageChars = (message) => {
|
|
271
|
+
switch (message._tag) {
|
|
272
|
+
case "User":
|
|
273
|
+
case "Steering": return estimateUserContentChars(message.content);
|
|
274
|
+
case "Assistant":
|
|
275
|
+
case "AssistantPartial": return estimateAssistantPromptChars(message.promptParts, message.content);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
const estimateAssociatedToolChars = (message, state) => {
|
|
279
|
+
if (message._tag !== "Assistant" && message._tag !== "AssistantPartial") return 0;
|
|
280
|
+
return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
281
|
+
};
|
|
282
|
+
const messageSeq = (message) => message._tag === "Steering" ? message.consumedSeq : message.seq;
|
|
283
|
+
const charsToTokens = (chars, charsPerToken) => Math.ceil(chars / charsPerToken);
|
|
284
|
+
const buildSummaryPrompt = (input) => {
|
|
285
|
+
const sourceText = serializeCompactionSource(input);
|
|
286
|
+
if (sourceText.trim().length === 0) return;
|
|
287
|
+
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}`;
|
|
288
|
+
};
|
|
289
|
+
const serializeCompactionSource = (input) => {
|
|
290
|
+
const lines = [];
|
|
291
|
+
for (const message of durableMessageTranscript(input.state)) {
|
|
292
|
+
const seq = messageSeq(message);
|
|
293
|
+
if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) continue;
|
|
294
|
+
lines.push(serializeDurableMessage(message));
|
|
295
|
+
if (message._tag === "Assistant" || message._tag === "AssistantPartial") for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) lines.push(serializeToolResultPart(part));
|
|
296
|
+
}
|
|
297
|
+
return lines.filter((line) => line.trim().length > 0).join("\n\n");
|
|
298
|
+
};
|
|
299
|
+
const serializeDurableMessage = (message) => {
|
|
300
|
+
switch (message._tag) {
|
|
301
|
+
case "User": return `[User]: ${userContentText(message.content)}`;
|
|
302
|
+
case "Steering": return `[User steering]: ${userContentText(message.content)}`;
|
|
303
|
+
case "Assistant":
|
|
304
|
+
case "AssistantPartial": return serializeAssistantMessage(message.promptParts, message.content);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
const serializeAssistantMessage = (promptParts, content) => {
|
|
308
|
+
const parts = promptParts ?? assistantContentToPromptParts(content);
|
|
309
|
+
const text = [];
|
|
310
|
+
const reasoning = [];
|
|
311
|
+
const toolCalls = [];
|
|
312
|
+
const sideband = [];
|
|
313
|
+
for (const part of parts) switch (part.type) {
|
|
314
|
+
case "text":
|
|
315
|
+
text.push(part.text);
|
|
316
|
+
break;
|
|
317
|
+
case "reasoning":
|
|
318
|
+
reasoning.push(part.text);
|
|
319
|
+
break;
|
|
320
|
+
case "tool-call":
|
|
321
|
+
toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);
|
|
322
|
+
break;
|
|
323
|
+
case "file":
|
|
324
|
+
sideband.push(`file(${part.fileName ?? "unnamed"}, ${part.mediaType})`);
|
|
325
|
+
break;
|
|
326
|
+
case "tool-result":
|
|
327
|
+
sideband.push(`tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`);
|
|
328
|
+
break;
|
|
329
|
+
case "tool-approval-request":
|
|
330
|
+
sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
return [
|
|
334
|
+
reasoning.length === 0 ? "" : `[Assistant reasoning]: ${reasoning.join("\n")}`,
|
|
335
|
+
text.length === 0 ? "" : `[Assistant]: ${text.join("\n")}`,
|
|
336
|
+
toolCalls.length === 0 ? "" : `[Assistant tool calls]: ${toolCalls.join("; ")}`,
|
|
337
|
+
sideband.length === 0 ? "" : `[Assistant context]: ${sideband.join("; ")}`
|
|
338
|
+
].filter((line) => line.length > 0).join("\n");
|
|
339
|
+
};
|
|
340
|
+
const serializeToolResultPart = (part) => `[Tool result ${part.name}${part.isFailure ? " failed" : ""}]: ${truncateForSummary(safeJsonStringify(part.result))}`;
|
|
341
|
+
const toolPromptPartsForInference = (inferenceId, toolCalls) => Array.from(toolCalls.values()).flatMap((tool) => {
|
|
342
|
+
const { decision } = tool;
|
|
343
|
+
if (decision === void 0 || decision.inferenceId !== inferenceId) return [];
|
|
344
|
+
if (decision._tag === "Rejected") return decision.promptPart === void 0 ? [] : [decision.promptPart];
|
|
345
|
+
const terminal = tool.terminal;
|
|
346
|
+
if (terminal === void 0 || terminal.promptPart === void 0) return [];
|
|
347
|
+
return [terminal.promptPart];
|
|
348
|
+
});
|
|
349
|
+
const assistantContentToPromptParts = (content) => [...content.reasoning === void 0 ? [] : [Prompt.reasoningPart({ text: content.reasoning })], ...content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]];
|
|
350
|
+
const estimateAssistantPromptChars = (promptParts, content) => (promptParts ?? assistantContentToPromptParts(content)).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
351
|
+
const estimateUserContentChars = (content) => typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
352
|
+
const estimatePromptMessageChars = (message) => {
|
|
353
|
+
if (!("content" in message)) return 0;
|
|
354
|
+
const { content } = message;
|
|
355
|
+
return typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
356
|
+
};
|
|
357
|
+
const estimatePromptPartChars = (part) => {
|
|
358
|
+
switch (part.type) {
|
|
359
|
+
case "text": return part.text.length;
|
|
360
|
+
case "reasoning": return part.text.length;
|
|
361
|
+
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);
|
|
362
|
+
case "tool-call": return part.name.length + safeJsonStringify(part.params).length;
|
|
363
|
+
case "tool-result": return part.name.length + safeJsonStringify(part.result).length;
|
|
364
|
+
case "tool-approval-response": return part.approvalId.length + (part.reason?.length ?? 0) + 8;
|
|
365
|
+
case "tool-approval-request": return part.approvalId.length + part.toolCallId.length;
|
|
366
|
+
default: return safeJsonStringify(part).length;
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
const userContentText = (content) => typeof content === "string" ? content : content.map((part) => {
|
|
370
|
+
switch (part.type) {
|
|
371
|
+
case "text": return part.text;
|
|
372
|
+
case "file": return `[file ${part.fileName ?? "unnamed"} ${part.mediaType}]`;
|
|
373
|
+
}
|
|
374
|
+
}).join("\n");
|
|
375
|
+
const safeJsonStringify = (value) => {
|
|
376
|
+
try {
|
|
377
|
+
return JSON.stringify(value) ?? String(value);
|
|
378
|
+
} catch {
|
|
379
|
+
return String(value);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
const truncateForSummary = (text, maxChars = 2e3) => {
|
|
383
|
+
if (text.length <= maxChars) return text;
|
|
384
|
+
return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} more characters truncated]`;
|
|
385
|
+
};
|
|
386
|
+
const formatUnknownError = (error) => error instanceof Error ? error.message : String(error);
|
|
387
|
+
const estimatedBinaryFileChars = 4800;
|
|
388
|
+
const summarizationSystemPrompt = "You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.";
|
|
389
|
+
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.
|
|
390
|
+
|
|
391
|
+
Use this exact structure:
|
|
392
|
+
|
|
393
|
+
## Goal
|
|
394
|
+
[What the user is trying to accomplish]
|
|
395
|
+
|
|
396
|
+
## Constraints & Preferences
|
|
397
|
+
- [Requirements, constraints, and preferences]
|
|
398
|
+
|
|
399
|
+
## Progress
|
|
400
|
+
### Done
|
|
401
|
+
- [x] [Completed work]
|
|
402
|
+
|
|
403
|
+
### In Progress
|
|
404
|
+
- [ ] [Current unfinished work]
|
|
405
|
+
|
|
406
|
+
### Blocked
|
|
407
|
+
- [Current blockers, or "(none)"]
|
|
408
|
+
|
|
409
|
+
## Key Decisions
|
|
410
|
+
- **[Decision]**: [Rationale]
|
|
411
|
+
|
|
412
|
+
## Next Steps
|
|
413
|
+
1. [Concrete next step]
|
|
414
|
+
|
|
415
|
+
## Critical Context
|
|
416
|
+
- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]
|
|
417
|
+
|
|
418
|
+
Rules:
|
|
419
|
+
- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.
|
|
420
|
+
- Keep the summary concise but sufficient to replace the compacted history.
|
|
421
|
+
- Preserve exact file paths, tool names, identifiers, and error messages.
|
|
422
|
+
- Do not answer questions from the conversation.`;
|
|
423
|
+
//#endregion
|
|
424
|
+
export { CompactionError, CompactionExecutor, CompactionOutput, CompactionPlan, CompactionPolicy, CompactionRunner, defaultCompactionCharsPerToken, defaultCompactionMinSummarizableTokens, defaultCompactionRetainTailTokens, defaultCompactionThresholdTokens };
|
|
425
|
+
|
|
426
|
+
//# sourceMappingURL=compaction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compaction.js","names":[],"sources":["../../src/services/compaction.ts"],"sourcesContent":["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 * as LanguageModel from \"effect/unstable/ai/LanguageModel\";\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, 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});\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}\n\n/** Typed failure from policy planning or summary generation. */\nexport class CompactionError extends Schema.TaggedErrorClass<CompactionError>()(\"CompactionError\", {\n message: Schema.String,\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, never, LanguageModel.LanguageModel> =>\n Layer.effect(\n CompactionExecutor,\n Effect.gen(function* () {\n const languageModel = yield* LanguageModel.LanguageModel;\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* languageModel\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({ message: \"summary model returned no text\" });\n }\n return CompactionOutput.make({\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\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 output = yield* keepAlive\n .withActiveWork(\n `compaction:${compactionId}`,\n executor.execute({ plan, state: input.state, context: input.context }),\n )\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.gen(function* () {\n const failed = yield* events.compactionFailed({\n compactionId,\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({ compactionId });\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":";;;;;;;;;;;;;;;AA2BA,MAAa,iBAAiB,OAAO,OAAO;CAC1C,UAAU;CACV,eAAe;CACf,aAAa;CACb,wBAAwB;AAC1B,CAAC;;AAID,MAAa,iCAAiC;;AAG9C,MAAa,mCAAmC;;AAGhD,MAAa,oCAAoC;;AAGjD,MAAa,yCAAyC;;AA+BtD,MAAa,mBAAmB,OAAO,OAAO;CAC5C,MAAM,OAAO;CACb,eAAe,OAAO;CACtB,YAAY,OAAO,YAAY,oBAAoB;AACrD,CAAC;;AASD,IAAa,kBAAb,cAAqC,OAAO,iBAAkC,EAAE,mBAAmB,EACjG,SAAS,OAAO,OAClB,CAAC,EAAE,CAAC;;AAWJ,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAAiD,EAC7F,wCACF,EAAE;;CAEA,OAAgB,WAAW,MAAM,QAAQ,kBAAkB;EACzD,IAAI,mBAAmB,KAAK,UAAU;EACtC,YAAY,OAAO,QAAQ,KAAA,CAAS;CACtC,CAAiC;;CAGjC,OAAgB,gBACd,IACA,SAEA,MAAM,QAAQ,kBAAkB;EAC9B,IAAI,mBAAmB,KAAK,EAAE;EAC9B;CACF,CAAC;;;;;;;CAQH,OAAgB,6BACd,UAA4D,CAAC,MAC3B;EAClC,MAAM,aAAa,uCAAuC,OAAO;EACjE,OAAO,MAAM,QAAQ,kBAAkB;GACrC,IAAI,WAAW;GACf,OAAO,EAAE,OAAO,cACd,OAAO,W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AmB,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,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"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { CommandId, CompactionId, CorrelationId, EventId, InferenceId, MessageId, RunId, SessionId, SummaryId, ToolCallId, TurnId } from "../types/core.js";
|
|
2
|
+
import * as Context from "effect/Context";
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Layer from "effect/Layer";
|
|
5
|
+
import * as Crypto from "effect/Crypto";
|
|
6
|
+
//#region src/services/id-generator.ts
|
|
7
|
+
const WebCryptoLive = Layer.succeed(Crypto.Crypto, Crypto.make({
|
|
8
|
+
randomBytes: (size) => {
|
|
9
|
+
const bytes = new Uint8Array(size);
|
|
10
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
11
|
+
return bytes;
|
|
12
|
+
},
|
|
13
|
+
digest: () => Effect.die(/* @__PURE__ */ new Error("IdGenerator does not use Crypto.digest"))
|
|
14
|
+
}));
|
|
15
|
+
/** Mints framework-owned UUIDv7 lifecycle IDs for effect-durable-agent. */
|
|
16
|
+
var IdGenerator = class IdGenerator extends Context.Service()("@effect-durable-agent/IdGenerator") {
|
|
17
|
+
static Live = Layer.effect(IdGenerator, Effect.gen(function* () {
|
|
18
|
+
return makeIdGenerator((yield* Crypto.Crypto).randomUUIDv7.pipe(Effect.orDie));
|
|
19
|
+
})).pipe(Layer.provide(WebCryptoLive));
|
|
20
|
+
static Deterministic = (ids) => Layer.sync(IdGenerator, () => {
|
|
21
|
+
let index = 0;
|
|
22
|
+
return makeIdGenerator(Effect.sync(() => {
|
|
23
|
+
const next = ids[index];
|
|
24
|
+
if (next === void 0) throw new Error("deterministic IdGenerator exhausted");
|
|
25
|
+
index += 1;
|
|
26
|
+
return next;
|
|
27
|
+
}));
|
|
28
|
+
});
|
|
29
|
+
/** Counter-based deterministic IDs; the nth minted ID is `sequentialUuidV7(n)`. */
|
|
30
|
+
static Sequential = Layer.sync(IdGenerator, () => {
|
|
31
|
+
let counter = 0;
|
|
32
|
+
return makeIdGenerator(Effect.sync(() => {
|
|
33
|
+
counter += 1;
|
|
34
|
+
return sequentialUuidV7(counter);
|
|
35
|
+
}));
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
/** The UUIDv7-shaped value minted by `IdGenerator.Sequential` for counter `n` (1-based). */
|
|
39
|
+
const sequentialUuidV7 = (n) => `00000000-0000-7000-8000-${n.toString(16).padStart(12, "0")}`;
|
|
40
|
+
const makeIdGenerator = (nextUuidV7) => ({
|
|
41
|
+
makeSessionId: () => nextUuidV7.pipe(Effect.map((id) => SessionId.make(id))),
|
|
42
|
+
makeEventId: () => nextUuidV7.pipe(Effect.map((id) => EventId.make(id))),
|
|
43
|
+
makeCommandId: () => nextUuidV7.pipe(Effect.map((id) => CommandId.make(id))),
|
|
44
|
+
makeRunId: () => nextUuidV7.pipe(Effect.map((id) => RunId.make(id))),
|
|
45
|
+
makeTurnId: () => nextUuidV7.pipe(Effect.map((id) => TurnId.make(id))),
|
|
46
|
+
makeInferenceId: () => nextUuidV7.pipe(Effect.map((id) => InferenceId.make(id))),
|
|
47
|
+
makeToolCallId: () => nextUuidV7.pipe(Effect.map((id) => ToolCallId.make(id))),
|
|
48
|
+
makeMessageId: () => nextUuidV7.pipe(Effect.map((id) => MessageId.make(id))),
|
|
49
|
+
makeCompactionId: () => nextUuidV7.pipe(Effect.map((id) => CompactionId.make(id))),
|
|
50
|
+
makeSummaryId: () => nextUuidV7.pipe(Effect.map((id) => SummaryId.make(id))),
|
|
51
|
+
makeCorrelationId: () => nextUuidV7.pipe(Effect.map((id) => CorrelationId.make(id)))
|
|
52
|
+
});
|
|
53
|
+
//#endregion
|
|
54
|
+
export { IdGenerator, sequentialUuidV7 };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=id-generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"id-generator.js","names":[],"sources":["../../src/services/id-generator.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport {\n InferenceId,\n CommandId,\n CompactionId,\n CorrelationId,\n EventId,\n MessageId,\n RunId,\n SessionId,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\n\n/** UUIDv7 minting capability for all framework-owned lifecycle identities. */\nexport interface IdGeneratorShape {\n readonly makeSessionId: () => Effect.Effect<SessionId>;\n readonly makeEventId: () => Effect.Effect<EventId>;\n readonly makeCommandId: () => Effect.Effect<CommandId>;\n readonly makeRunId: () => Effect.Effect<RunId>;\n readonly makeTurnId: () => Effect.Effect<TurnId>;\n readonly makeInferenceId: () => Effect.Effect<InferenceId>;\n readonly makeToolCallId: () => Effect.Effect<ToolCallId>;\n readonly makeMessageId: () => Effect.Effect<MessageId>;\n readonly makeCompactionId: () => Effect.Effect<CompactionId>;\n readonly makeSummaryId: () => Effect.Effect<SummaryId>;\n readonly makeCorrelationId: () => Effect.Effect<CorrelationId>;\n}\n\nconst WebCryptoLive = Layer.succeed(\n Crypto.Crypto,\n Crypto.make({\n randomBytes: (size) => {\n const bytes = new Uint8Array(size);\n globalThis.crypto.getRandomValues(bytes);\n return bytes;\n },\n digest: () => Effect.die(new Error(\"IdGenerator does not use Crypto.digest\")),\n }),\n);\n\n/** Mints framework-owned UUIDv7 lifecycle IDs for effect-durable-agent. */\nexport class IdGenerator extends Context.Service<IdGenerator, IdGeneratorShape>()(\n \"@effect-durable-agent/IdGenerator\",\n) {\n static readonly Live = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const crypto = yield* Crypto.Crypto;\n return makeIdGenerator(crypto.randomUUIDv7.pipe(Effect.orDie));\n }),\n ).pipe(Layer.provide(WebCryptoLive));\n\n static readonly Deterministic = (ids: ReadonlyArray<string>) =>\n Layer.sync(IdGenerator, () => {\n let index = 0;\n return makeIdGenerator(\n Effect.sync(() => {\n const next = ids[index];\n if (next === undefined) {\n throw new Error(\"deterministic IdGenerator exhausted\");\n }\n index += 1;\n return next;\n }),\n );\n });\n\n /** Counter-based deterministic IDs; the nth minted ID is `sequentialUuidV7(n)`. */\n static readonly Sequential = Layer.sync(IdGenerator, () => {\n let counter = 0;\n return makeIdGenerator(\n Effect.sync(() => {\n counter += 1;\n return sequentialUuidV7(counter);\n }),\n );\n });\n}\n\n/** The UUIDv7-shaped value minted by `IdGenerator.Sequential` for counter `n` (1-based). */\nexport const sequentialUuidV7 = (n: number): string =>\n `00000000-0000-7000-8000-${n.toString(16).padStart(12, \"0\")}`;\n\nconst makeIdGenerator = (nextUuidV7: Effect.Effect<string>): IdGeneratorShape => ({\n makeSessionId: () => nextUuidV7.pipe(Effect.map((id) => SessionId.make(id))),\n makeEventId: () => nextUuidV7.pipe(Effect.map((id) => EventId.make(id))),\n makeCommandId: () => nextUuidV7.pipe(Effect.map((id) => CommandId.make(id))),\n makeRunId: () => nextUuidV7.pipe(Effect.map((id) => RunId.make(id))),\n makeTurnId: () => nextUuidV7.pipe(Effect.map((id) => TurnId.make(id))),\n makeInferenceId: () => nextUuidV7.pipe(Effect.map((id) => InferenceId.make(id))),\n makeToolCallId: () => nextUuidV7.pipe(Effect.map((id) => ToolCallId.make(id))),\n makeMessageId: () => nextUuidV7.pipe(Effect.map((id) => MessageId.make(id))),\n makeCompactionId: () => nextUuidV7.pipe(Effect.map((id) => CompactionId.make(id))),\n makeSummaryId: () => nextUuidV7.pipe(Effect.map((id) => SummaryId.make(id))),\n makeCorrelationId: () => nextUuidV7.pipe(Effect.map((id) => CorrelationId.make(id))),\n});\n"],"mappings":";;;;;;AAkCA,MAAM,gBAAgB,MAAM,QAC1B,OAAO,QACP,OAAO,KAAK;CACV,cAAc,SAAS;EACrB,MAAM,QAAQ,IAAI,WAAW,IAAI;EACjC,WAAW,OAAO,gBAAgB,KAAK;EACvC,OAAO;CACT;CACA,cAAc,OAAO,oBAAI,IAAI,MAAM,wCAAwC,CAAC;AAC9E,CAAC,CACH;;AAGA,IAAa,cAAb,MAAa,oBAAoB,QAAQ,QAAuC,EAC9E,mCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,aACA,OAAO,IAAI,aAAa;EAEtB,OAAO,iBAAgB,OADD,OAAO,QACC,aAAa,KAAK,OAAO,KAAK,CAAC;CAC/D,CAAC,CACH,EAAE,KAAK,MAAM,QAAQ,aAAa,CAAC;CAEnC,OAAgB,iBAAiB,QAC/B,MAAM,KAAK,mBAAmB;EAC5B,IAAI,QAAQ;EACZ,OAAO,gBACL,OAAO,WAAW;GAChB,MAAM,OAAO,IAAI;GACjB,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,qCAAqC;GAEvD,SAAS;GACT,OAAO;EACT,CAAC,CACH;CACF,CAAC;;CAGH,OAAgB,aAAa,MAAM,KAAK,mBAAmB;EACzD,IAAI,UAAU;EACd,OAAO,gBACL,OAAO,WAAW;GAChB,WAAW;GACX,OAAO,iBAAiB,OAAO;EACjC,CAAC,CACH;CACF,CAAC;AACH;;AAGA,MAAa,oBAAoB,MAC/B,2BAA2B,EAAE,SAAS,EAAE,EAAE,SAAS,IAAI,GAAG;AAE5D,MAAM,mBAAmB,gBAAyD;CAChF,qBAAqB,WAAW,KAAK,OAAO,KAAK,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC;CAC3E,mBAAmB,WAAW,KAAK,OAAO,KAAK,OAAO,QAAQ,KAAK,EAAE,CAAC,CAAC;CACvE,qBAAqB,WAAW,KAAK,OAAO,KAAK,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC;CAC3E,iBAAiB,WAAW,KAAK,OAAO,KAAK,OAAO,MAAM,KAAK,EAAE,CAAC,CAAC;CACnE,kBAAkB,WAAW,KAAK,OAAO,KAAK,OAAO,OAAO,KAAK,EAAE,CAAC,CAAC;CACrE,uBAAuB,WAAW,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,EAAE,CAAC,CAAC;CAC/E,sBAAsB,WAAW,KAAK,OAAO,KAAK,OAAO,WAAW,KAAK,EAAE,CAAC,CAAC;CAC7E,qBAAqB,WAAW,KAAK,OAAO,KAAK,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC;CAC3E,wBAAwB,WAAW,KAAK,OAAO,KAAK,OAAO,aAAa,KAAK,EAAE,CAAC,CAAC;CACjF,qBAAqB,WAAW,KAAK,OAAO,KAAK,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC;CAC3E,yBAAyB,WAAW,KAAK,OAAO,KAAK,OAAO,cAAc,KAAK,EAAE,CAAC,CAAC;AACrF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as buildEDAPrompt, i as SelectedPromptUserMessage, n as EDAPromptProjector, r as EDAPromptProjectorShape, t as EDAPromptProjectionInput } from "../prompt-projector-9_02lk5-.js";
|
|
2
|
+
export { EDAPromptProjectionInput, EDAPromptProjector, EDAPromptProjectorShape, SelectedPromptUserMessage, buildEDAPrompt };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { contextProjectionPromptWithUserContents } from "../domain/message-transcript.js";
|
|
2
|
+
import * as Context from "effect/Context";
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Layer from "effect/Layer";
|
|
5
|
+
//#region src/services/prompt-projector.ts
|
|
6
|
+
/** Build a provider prompt while preserving framework-owned selected-message cardinality/order. */
|
|
7
|
+
const buildEDAPrompt = (projector, input) => Effect.gen(function* () {
|
|
8
|
+
const state = yield* projector.projectState(input);
|
|
9
|
+
const contents = yield* Effect.forEach(input.selectedUserMessages.filter((message) => !isAlreadyProjectedFromState(input, message)), (message) => projector.projectUserMessageContent(input, message));
|
|
10
|
+
return contextProjectionPromptWithUserContents(state, input.context, contents);
|
|
11
|
+
});
|
|
12
|
+
/** Legacy committed user messages are already visible in the durable transcript projection. */
|
|
13
|
+
const isAlreadyProjectedFromState = (input, message) => {
|
|
14
|
+
const durable = input.state.messages.get(message.messageId);
|
|
15
|
+
return durable?._tag === "User" && durable.requestedDisposition === void 0;
|
|
16
|
+
};
|
|
17
|
+
/** Service that lets apps derive LLM context independently from UI projections. */
|
|
18
|
+
var EDAPromptProjector = class EDAPromptProjector extends Context.Service()("@effect-durable-agent/EDAPromptProjector") {
|
|
19
|
+
static Default = Layer.succeed(EDAPromptProjector, {
|
|
20
|
+
projectState: (input) => Effect.succeed(input.state),
|
|
21
|
+
projectUserMessageContent: (_input, message) => Effect.succeed(message.content)
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { EDAPromptProjector, buildEDAPrompt };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=prompt-projector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-projector.js","names":[],"sources":["../../src/services/prompt-projector.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport type * as Prompt from \"effect/unstable/ai/Prompt\";\n\nimport { contextProjectionPromptWithUserContents } from \"../domain/message-transcript\";\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { UserMessageContent } from \"../types/commands\";\nimport type { CommandId, MessageId, SessionId } from \"../types/core\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\n\n/** User content selected for a turn before its consuming TurnStarted event commits. */\nexport interface SelectedPromptUserMessage {\n readonly commandId: CommandId;\n readonly content: UserMessageContent;\n readonly messageId: MessageId;\n}\n\n/** Input for app-extensible state-to-LLM prompt projection. */\nexport interface EDAPromptProjectionInput {\n readonly sessionId: SessionId;\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly context?: ContextProjection;\n readonly selectedUserMessages: ReadonlyArray<SelectedPromptUserMessage>;\n}\n\n/** Host-extensible projection from durable state into provider prompt context. */\nexport interface EDAPromptProjectorShape {\n readonly projectState: (input: EDAPromptProjectionInput) => Effect.Effect<ReducedState>;\n readonly projectUserMessageContent: (\n input: EDAPromptProjectionInput,\n message: SelectedPromptUserMessage,\n ) => Effect.Effect<UserMessageContent>;\n}\n\n/** Build a provider prompt while preserving framework-owned selected-message cardinality/order. */\nexport const buildEDAPrompt = (\n projector: EDAPromptProjectorShape,\n input: EDAPromptProjectionInput,\n): Effect.Effect<Prompt.Prompt> =>\n Effect.gen(function* () {\n const state = yield* projector.projectState(input);\n const contents = yield* Effect.forEach(\n input.selectedUserMessages.filter((message) => !isAlreadyProjectedFromState(input, message)),\n (message) => projector.projectUserMessageContent(input, message),\n );\n return contextProjectionPromptWithUserContents(state, input.context, contents);\n });\n\n/** Legacy committed user messages are already visible in the durable transcript projection. */\nconst isAlreadyProjectedFromState = (\n input: EDAPromptProjectionInput,\n message: SelectedPromptUserMessage,\n): boolean => {\n const durable = input.state.messages.get(message.messageId);\n return durable?._tag === \"User\" && durable.requestedDisposition === undefined;\n};\n\n/** Service that lets apps derive LLM context independently from UI projections. */\nexport class EDAPromptProjector extends Context.Service<\n EDAPromptProjector,\n EDAPromptProjectorShape\n>()(\"@effect-durable-agent/EDAPromptProjector\") {\n static readonly Default = Layer.succeed(EDAPromptProjector, {\n projectState: (input) => Effect.succeed(input.state),\n projectUserMessageContent: (_input, message) => Effect.succeed(message.content),\n } satisfies EDAPromptProjectorShape);\n}\n"],"mappings":";;;;;;AAsCA,MAAa,kBACX,WACA,UAEA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,UAAU,aAAa,KAAK;CACjD,MAAM,WAAW,OAAO,OAAO,QAC7B,MAAM,qBAAqB,QAAQ,YAAY,CAAC,4BAA4B,OAAO,OAAO,CAAC,IAC1F,YAAY,UAAU,0BAA0B,OAAO,OAAO,CACjE;CACA,OAAO,wCAAwC,OAAO,MAAM,SAAS,QAAQ;AAC/E,CAAC;;AAGH,MAAM,+BACJ,OACA,YACY;CACZ,MAAM,UAAU,MAAM,MAAM,SAAS,IAAI,QAAQ,SAAS;CAC1D,OAAO,SAAS,SAAS,UAAU,QAAQ,yBAAyB,KAAA;AACtE;;AAGA,IAAa,qBAAb,MAAa,2BAA2B,QAAQ,QAG9C,EAAE,0CAA0C,EAAE;CAC9C,OAAgB,UAAU,MAAM,QAAQ,oBAAoB;EAC1D,eAAe,UAAU,OAAO,QAAQ,MAAM,KAAK;EACnD,4BAA4B,QAAQ,YAAY,OAAO,QAAQ,QAAQ,OAAO;CAChF,CAAmC;AACrC"}
|