effect-durable-agent 0.1.0-alpha.9 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/assert-never-CoyUpoRB.js +18 -0
- package/dist/assert-never-CoyUpoRB.js.map +1 -0
- package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
- package/dist/{compaction-BgDr5VJy.js → compaction-63iEDHHl.js} +63 -13
- package/dist/compaction-63iEDHHl.js.map +1 -0
- package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
- package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
- package/dist/delivery-2ZILvoRD.js +507 -0
- package/dist/delivery-2ZILvoRD.js.map +1 -0
- package/dist/delivery-D3MxW4wg.d.ts +3026 -0
- package/dist/domain/command-queues.d.ts +81 -2
- package/dist/domain/command-queues.js +1 -1
- package/dist/domain/command-queues.js.map +1 -1
- package/dist/domain/context-projection.d.ts +1 -1
- package/dist/domain/context-projection.js +1 -1
- package/dist/domain/context-projection.js.map +1 -1
- package/dist/domain/message-transcript.d.ts +36 -2
- package/dist/domain/message-transcript.js +10 -2
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/model-usage.d.ts +1 -1
- package/dist/domain/model-usage.js +1 -1
- package/dist/domain/reduced-state-schema.d.ts +3 -992
- package/dist/domain/reduced-state-schema.js +126 -7
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +2 -2
- package/dist/domain/reduced-state.js +936 -2
- package/dist/domain/reduced-state.js.map +1 -0
- package/dist/domain/run-scheduling.d.ts +2 -0
- package/dist/domain/run-scheduling.js +127 -0
- package/dist/domain/run-scheduling.js.map +1 -0
- package/dist/{durable-br2C1bWK.d.ts → durable-168Womqp.d.ts} +8535 -2859
- package/dist/{durable-BGFvX7Mh.js → durable-D13w1Qr3.js} +229 -15
- package/dist/durable-D13w1Qr3.js.map +1 -0
- package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
- package/dist/envelope-BCzKUq_z.js.map +1 -0
- package/dist/{envelope-DkZyMIgp.d.ts → envelope-Che6KatU.d.ts} +70 -7
- package/dist/{event-factory-DTFdy0Cb.js → event-factory-_vF1bIJ7.js} +7 -3
- package/dist/event-factory-_vF1bIJ7.js.map +1 -0
- package/dist/{events-LZFNoESe.d.ts → events-DwTARLMv.d.ts} +139 -137
- package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
- package/dist/in-memory-CeODnZhE.js +150 -0
- package/dist/in-memory-CeODnZhE.js.map +1 -0
- package/dist/index.d.ts +8 -8
- package/dist/index.js +6 -6
- package/dist/interpreter-DKGJ1sSx.js +1452 -0
- package/dist/interpreter-DKGJ1sSx.js.map +1 -0
- package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
- package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-DeBDK8XO.d.ts} +11 -5
- package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
- package/dist/records--54mZEBx.js +675 -0
- package/dist/records--54mZEBx.js.map +1 -0
- package/dist/reduced-state-B1cvy8N_.d.ts +51110 -0
- package/dist/reduced-state-schema-B98exWxQ.d.ts +2338 -0
- package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-DhGVzHBV.d.ts} +12 -6
- package/dist/run-scheduling-wakeup-Mjic4tb_.d.ts +24 -0
- package/dist/services/compaction.d.ts +2 -2
- package/dist/services/compaction.js +2 -2
- package/dist/services/id-generator.d.ts +1 -1
- package/dist/services/id-generator.js +6 -12
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/keep-alive.d.ts +1 -1
- package/dist/services/keep-alive.js.map +1 -1
- package/dist/services/model-call.d.ts +15 -0
- package/dist/services/model-call.js +15 -0
- package/dist/services/model-call.js.map +1 -0
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/model-resolver.js +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- package/dist/services/prompt-projector.d.ts +2 -2
- package/dist/services/prompt-projector.js +49 -5
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/reducer-registry.js +19 -6
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/run-scheduler.d.ts +2 -2
- package/dist/services/run-scheduler.js +25 -2
- package/dist/services/run-scheduler.js.map +1 -0
- package/dist/services/run-scheduling-wakeup.d.ts +2 -0
- package/dist/services/run-scheduling-wakeup.js +13 -0
- package/dist/services/run-scheduling-wakeup.js.map +1 -0
- package/dist/services/runtime-layer.d.ts +17 -33
- package/dist/services/runtime-layer.js +19 -14
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +31 -20
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-event-observer.js.map +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +57 -10
- package/dist/services/session-query.js.map +1 -1
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +127 -37
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-checkpoint-store.js +2 -1
- package/dist/services/sink-checkpoint-store.js.map +1 -1
- package/dist/services/sink-registry.d.ts +2 -2
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/span-names.d.ts +1 -1
- package/dist/services/span-names.js +6 -1
- package/dist/services/span-names.js.map +1 -1
- package/dist/services/tool-registry.d.ts +2 -2
- package/dist/services/tool-registry.js +12 -3
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +3 -3
- package/dist/services/tracing.js +2 -2
- package/dist/services/tracing.js.map +1 -1
- package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-DlP9ITB2.d.ts} +3 -3
- package/dist/{session-state-Bkc6u-Wr.js → session-state-BehvUVyq.js} +659 -164
- package/dist/session-state-BehvUVyq.js.map +1 -0
- package/dist/session-store-BL6sfrnn.d.ts +3326 -0
- package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-DvuHwvx_.d.ts} +3 -4
- package/dist/sink-registry-DskRcyOS.js +345 -0
- package/dist/sink-registry-DskRcyOS.js.map +1 -0
- package/dist/subscription-DZNWFDTV.d.ts +966 -0
- package/dist/subscription-DmO3BcdT.js +505 -0
- package/dist/subscription-DmO3BcdT.js.map +1 -0
- package/dist/testkit/layers.d.ts +30 -23
- package/dist/testkit/layers.js +23 -15
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.d.ts +226 -0
- package/dist/testkit/transcript.js +1475 -0
- package/dist/testkit/transcript.js.map +1 -0
- package/dist/{tool-registry-BJaVNtw4.d.ts → tool-registry-CHHUU9BN.d.ts} +44 -8
- package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
- package/dist/transcript.d.ts +101 -0
- package/dist/transcript.js +107 -0
- package/dist/transcript.js.map +1 -0
- package/dist/types/commands.d.ts +2 -2
- package/dist/types/commands.js +8 -3
- package/dist/types/commands.js.map +1 -1
- package/dist/types/core.d.ts +2 -2
- package/dist/types/core.js +3 -1
- package/dist/types/core.js.map +1 -1
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +5 -5
- package/dist/types/events.js +3 -3
- package/dist/types/tracing.d.ts +1 -1
- package/dist/types/tracing.js.map +1 -1
- package/dist/websocket/events.d.ts +2 -0
- package/dist/websocket/events.js +2 -0
- package/dist/websocket.d.ts +2123 -2552
- package/dist/websocket.js +628 -442
- package/dist/websocket.js.map +1 -1
- package/dist/window-read-Brov9VdQ.d.ts +113 -0
- package/dist/window-read-DPFAA1hM.js +264 -0
- package/dist/window-read-DPFAA1hM.js.map +1 -0
- package/package.json +37 -13
- package/dist/command-queues-DdDB_aYM.d.ts +0 -462
- package/dist/compaction-BgDr5VJy.js.map +0 -1
- package/dist/compaction-ch8z6G9x.d.ts +0 -165
- package/dist/durable-BGFvX7Mh.js.map +0 -1
- package/dist/envelope-DxQzo5rN.js.map +0 -1
- package/dist/event-factory-DTFdy0Cb.js.map +0 -1
- package/dist/event-factory-Di1jwQvm.d.ts +0 -87
- package/dist/index-BVVgDSdq.d.ts +0 -1
- package/dist/message-transcript-DQNlzxle.d.ts +0 -32
- package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
- package/dist/reduced-state-DF0-6mbR.js +0 -921
- package/dist/reduced-state-DF0-6mbR.js.map +0 -1
- package/dist/run-scheduler-CAt7dF6C.js +0 -21
- package/dist/run-scheduler-CAt7dF6C.js.map +0 -1
- package/dist/run-scheduler-xkhZyto5.d.ts +0 -44
- package/dist/runtime-DDSYP9jS.d.ts +0 -63
- package/dist/session-query-B72HY_0L.d.ts +0 -45
- package/dist/session-state-Bkc6u-Wr.js.map +0 -1
- package/dist/session-state-C9YLSAso.d.ts +0 -862
- package/dist/session-store-Cpi_NwTR.d.ts +0 -206
- package/dist/sink-registry-Bl-vQES6.d.ts +0 -133
- package/dist/sink-registry-NDgeyzO0.js +0 -272
- package/dist/sink-registry-NDgeyzO0.js.map +0 -1
package/README.md
CHANGED
|
@@ -92,7 +92,7 @@ projection of state, and the LLM context is a separate pure projection of that s
|
|
|
92
92
|
The UI can preserve tool progress, approvals, sandbox status, and rich product history while the
|
|
93
93
|
LLM context selects and compacts only what the model should see. Applications can model each
|
|
94
94
|
consumer honestly instead of collapsing both into one constrained representation. See the
|
|
95
|
-
[
|
|
95
|
+
[transcript history proposal](https://github.com/advait/effect-durable-agent/blob/master/docs/transcript-history.md) for the planned user-visible projection.
|
|
96
96
|
|
|
97
97
|
### 7. Durable sinks: callbacks that survive failure
|
|
98
98
|
|
|
@@ -179,16 +179,16 @@ versions are not a supported combination; keep the versions identical when upgra
|
|
|
179
179
|
|
|
180
180
|
## Get started
|
|
181
181
|
|
|
182
|
-
Install the core and one host
|
|
182
|
+
Install the core and one host:
|
|
183
183
|
|
|
184
184
|
```bash
|
|
185
|
-
pnpm add effect-durable-agent
|
|
185
|
+
pnpm add effect-durable-agent effect-durable-agent-cloudflare
|
|
186
186
|
```
|
|
187
187
|
|
|
188
188
|
For celld, select its host package at the same version instead:
|
|
189
189
|
|
|
190
190
|
```bash
|
|
191
|
-
pnpm add effect-durable-agent
|
|
191
|
+
pnpm add effect-durable-agent effect-durable-agent-celld
|
|
192
192
|
```
|
|
193
193
|
|
|
194
194
|
The smallest Cloudflare host is a concrete Durable Object subclass:
|
|
@@ -298,7 +298,7 @@ typed boundaries, structured concurrency, and first-class tracing.
|
|
|
298
298
|
- [Testing strategy](https://github.com/advait/effect-durable-agent/blob/master/docs/testing.md)
|
|
299
299
|
- [WebSocket live-event protocol](https://github.com/advait/effect-durable-agent/blob/master/docs/websocket-protocol.md)
|
|
300
300
|
- [Message steering](https://github.com/advait/effect-durable-agent/blob/master/docs/message-steering.md)
|
|
301
|
-
- [
|
|
301
|
+
- [Transcript history proposal](https://github.com/advait/effect-durable-agent/blob/master/docs/transcript-history.md)
|
|
302
302
|
- [Subagents proposal](https://github.com/advait/effect-durable-agent/blob/master/docs/subagents.md)
|
|
303
303
|
- [Maintainer release guide](https://github.com/advait/effect-durable-agent/blob/master/docs/releasing.md)
|
|
304
304
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region src/domain/assert-never.ts
|
|
2
|
+
const formatNeverValue = (value) => {
|
|
3
|
+
try {
|
|
4
|
+
return JSON.stringify(value);
|
|
5
|
+
} catch {
|
|
6
|
+
return String(value);
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
/** Build the defect used when an exhaustive switch receives an impossible value. */
|
|
10
|
+
const assertNeverError = (value, context) => /* @__PURE__ */ new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);
|
|
11
|
+
/** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */
|
|
12
|
+
const assertNever = (value, context) => {
|
|
13
|
+
throw assertNeverError(value, context);
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { assertNeverError as n, assertNever as t };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=assert-never-CoyUpoRB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assert-never-CoyUpoRB.js","names":[],"sources":["../src/domain/assert-never.ts"],"sourcesContent":["const formatNeverValue = (value: never): string => {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\n/** Build the defect used when an exhaustive switch receives an impossible value. */\nexport const assertNeverError = (value: never, context: string) =>\n new Error(`Unhandled ${context}: ${formatNeverValue(value)}`);\n\n/** Throw for impossible branches in pure code after TypeScript exhaustiveness checking. */\nexport const assertNever = (value: never, context: string): never => {\n throw assertNeverError(value, context);\n};\n"],"mappings":";AAAA,MAAM,oBAAoB,UAAyB;CACjD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;AAGA,MAAa,oBAAoB,OAAc,4BAC7C,IAAI,MAAM,aAAa,QAAQ,IAAI,iBAAiB,KAAK,GAAG;;AAG9D,MAAa,eAAe,OAAc,YAA2B;CACnE,MAAM,iBAAiB,OAAO,OAAO;AACvC"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import * as Schema from "effect/Schema";
|
|
2
|
-
|
|
3
2
|
//#region src/types/commands.d.ts
|
|
4
3
|
/** Caller-owned stable retry/correlation key for a submitted command. */
|
|
5
4
|
declare const CommandIdempotencyKey: Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">;
|
|
@@ -17,7 +16,11 @@ declare const UserMessagePart: Schema.Union<readonly [Schema.Struct<{
|
|
|
17
16
|
readonly type: Schema.Literal<"file">;
|
|
18
17
|
readonly mediaType: Schema.String;
|
|
19
18
|
readonly fileName: Schema.optional<Schema.String>;
|
|
20
|
-
readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.
|
|
19
|
+
readonly data: Schema.Union<readonly [Schema.String, Schema.decodeTo<Schema.Uint8Array, Schema.TaggedStruct<"Uint8Array", {
|
|
20
|
+
readonly base64: Schema.Uint8ArrayFromBase64;
|
|
21
|
+
}>>, Schema.decodeTo<Schema.URL, Schema.TaggedStruct<"URL", {
|
|
22
|
+
readonly href: Schema.URLFromString;
|
|
23
|
+
}>>, Schema.Uint8Array, Schema.URL]>;
|
|
21
24
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
22
25
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
23
26
|
}>]>;
|
|
@@ -37,12 +40,18 @@ declare const UserMessageContent: Schema.Union<readonly [Schema.decodeTo<Schema.
|
|
|
37
40
|
readonly type: Schema.Literal<"file">;
|
|
38
41
|
readonly mediaType: Schema.String;
|
|
39
42
|
readonly fileName: Schema.optional<Schema.String>;
|
|
40
|
-
readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.
|
|
43
|
+
readonly data: Schema.Union<readonly [Schema.String, Schema.decodeTo<Schema.Uint8Array, Schema.TaggedStruct<"Uint8Array", {
|
|
44
|
+
readonly base64: Schema.Uint8ArrayFromBase64;
|
|
45
|
+
}>>, Schema.decodeTo<Schema.URL, Schema.TaggedStruct<"URL", {
|
|
46
|
+
readonly href: Schema.URLFromString;
|
|
47
|
+
}>>, Schema.Uint8Array, Schema.URL]>;
|
|
41
48
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
42
49
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
43
50
|
}>]>>]>;
|
|
44
51
|
type UserMessageContent = typeof UserMessageContent.Type;
|
|
45
52
|
declare const SubmitMessageCommand_base: Schema.Class<SubmitMessageCommand, Schema.TaggedStruct<"SubmitMessage", {
|
|
53
|
+
readonly commandId: Schema.optionalKey<Schema.brand<Schema.String, "CommandId">>;
|
|
54
|
+
readonly idempotencyKey: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">>;
|
|
46
55
|
readonly disposition: Schema.Literals<readonly ["queue", "steer", "interrupt"]>;
|
|
47
56
|
readonly content: Schema.Union<readonly [Schema.decodeTo<Schema.NonEmptyArray<Schema.toType<Schema.Struct<{
|
|
48
57
|
readonly type: Schema.Literal<"text">;
|
|
@@ -58,35 +67,37 @@ declare const SubmitMessageCommand_base: Schema.Class<SubmitMessageCommand, Sche
|
|
|
58
67
|
readonly type: Schema.Literal<"file">;
|
|
59
68
|
readonly mediaType: Schema.String;
|
|
60
69
|
readonly fileName: Schema.optional<Schema.String>;
|
|
61
|
-
readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.
|
|
70
|
+
readonly data: Schema.Union<readonly [Schema.String, Schema.decodeTo<Schema.Uint8Array, Schema.TaggedStruct<"Uint8Array", {
|
|
71
|
+
readonly base64: Schema.Uint8ArrayFromBase64;
|
|
72
|
+
}>>, Schema.decodeTo<Schema.URL, Schema.TaggedStruct<"URL", {
|
|
73
|
+
readonly href: Schema.URLFromString;
|
|
74
|
+
}>>, Schema.Uint8Array, Schema.URL]>;
|
|
62
75
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
63
76
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
64
77
|
}>]>>]>;
|
|
65
78
|
readonly expectedPausedMessageIdsToCancel: Schema.optionalKey<Schema.$Array<Schema.brand<Schema.String, "MessageId">>>;
|
|
66
|
-
readonly commandId: Schema.optionalKey<Schema.brand<Schema.String, "CommandId">>;
|
|
67
|
-
readonly idempotencyKey: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">>;
|
|
68
79
|
}>, {}>;
|
|
69
80
|
/** Submit a user message to the session command stream. */
|
|
70
81
|
declare class SubmitMessageCommand extends SubmitMessageCommand_base {}
|
|
71
82
|
declare const PendingMessageCancellationReason: Schema.Literals<readonly ["edit", "user-cancel"]>;
|
|
72
83
|
type PendingMessageCancellationReason = typeof PendingMessageCancellationReason.Type;
|
|
73
84
|
declare const CancelPendingMessageCommand_base: Schema.Class<CancelPendingMessageCommand, Schema.TaggedStruct<"CancelPendingMessage", {
|
|
74
|
-
readonly messageId: Schema.brand<Schema.String, "MessageId">;
|
|
75
|
-
readonly reason: Schema.Literals<readonly ["edit", "user-cancel"]>;
|
|
76
85
|
readonly commandId: Schema.optionalKey<Schema.brand<Schema.String, "CommandId">>;
|
|
77
86
|
readonly idempotencyKey: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">>;
|
|
87
|
+
readonly messageId: Schema.brand<Schema.String, "MessageId">;
|
|
88
|
+
readonly reason: Schema.Literals<readonly ["edit", "user-cancel"]>;
|
|
78
89
|
}>, {}>;
|
|
79
90
|
declare class CancelPendingMessageCommand extends CancelPendingMessageCommand_base {}
|
|
80
91
|
declare const PromotePendingMessageCommand_base: Schema.Class<PromotePendingMessageCommand, Schema.TaggedStruct<"PromotePendingMessage", {
|
|
81
|
-
readonly messageId: Schema.brand<Schema.String, "MessageId">;
|
|
82
92
|
readonly commandId: Schema.optionalKey<Schema.brand<Schema.String, "CommandId">>;
|
|
83
93
|
readonly idempotencyKey: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">>;
|
|
94
|
+
readonly messageId: Schema.brand<Schema.String, "MessageId">;
|
|
84
95
|
}>, {}>;
|
|
85
96
|
declare class PromotePendingMessageCommand extends PromotePendingMessageCommand_base {}
|
|
86
97
|
declare const ResumePendingMessagesCommand_base: Schema.Class<ResumePendingMessagesCommand, Schema.TaggedStruct<"ResumePendingMessages", {
|
|
87
|
-
readonly messageIds: Schema.NonEmptyArray<Schema.brand<Schema.String, "MessageId">>;
|
|
88
98
|
readonly commandId: Schema.optionalKey<Schema.brand<Schema.String, "CommandId">>;
|
|
89
99
|
readonly idempotencyKey: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CommandIdempotencyKey">>;
|
|
100
|
+
readonly messageIds: Schema.NonEmptyArray<Schema.brand<Schema.String, "MessageId">>;
|
|
90
101
|
}>, {}>;
|
|
91
102
|
/** Framework-internal owner for restarting unconsumed messages after unexpected failure. */
|
|
92
103
|
declare class ResumePendingMessagesCommand extends ResumePendingMessagesCommand_base {}
|
|
@@ -99,6 +110,14 @@ declare class StopTurnCommand extends StopTurnCommand_base {}
|
|
|
99
110
|
/** Mutating input accepted by effect-durable-agent before runtime processing. */
|
|
100
111
|
declare const EDACommand: Schema.Union<readonly [typeof SubmitMessageCommand, typeof StopTurnCommand, typeof CancelPendingMessageCommand, typeof PromotePendingMessageCommand, typeof ResumePendingMessagesCommand]>;
|
|
101
112
|
type EDACommand = typeof EDACommand.Type;
|
|
113
|
+
declare const GrantRunCommand_base: Schema.Class<GrantRunCommand, Schema.TaggedStruct<"GrantRun", {
|
|
114
|
+
readonly requestId: Schema.brand<Schema.String, "RunRequestId">;
|
|
115
|
+
}>, {}>;
|
|
116
|
+
/**
|
|
117
|
+
* Trusted scheduler permission, accepted only through the separate grantRun API.
|
|
118
|
+
* Excluded from EDACommand so ordinary session ingress cannot authorize itself.
|
|
119
|
+
*/
|
|
120
|
+
declare class GrantRunCommand extends GrantRunCommand_base {}
|
|
102
121
|
//#endregion
|
|
103
|
-
export {
|
|
104
|
-
//# sourceMappingURL=commands-
|
|
122
|
+
export { PendingMessageCancellationReason as a, StopTurnCommand as c, UserMessageContent as d, UserMessagePart as f, GrantRunCommand as i, SubmitMessageCommand as l, CommandIdempotencyKey as n, PromotePendingMessageCommand as o, EDACommand as r, ResumePendingMessagesCommand as s, CancelPendingMessageCommand as t, SubmitMessageDisposition as u };
|
|
123
|
+
//# sourceMappingURL=commands-BUquEZVP.d.ts.map
|
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
import { ModelResolver } from "./services/model-resolver.js";
|
|
2
1
|
import { ContextVersion, SequenceNumber } from "./types/core.js";
|
|
3
|
-
import {
|
|
2
|
+
import { ModelResolver } from "./services/model-resolver.js";
|
|
3
|
+
import { _ as UsagePayload, s as FailurePayload } from "./envelope-BCzKUq_z.js";
|
|
4
4
|
import { CompactionExecutorId, CompactionPolicyId, CompactionSummaryArtifact } from "./domain/context-projection.js";
|
|
5
|
-
import {
|
|
5
|
+
import { generateTextOfferingTools } from "./services/model-call.js";
|
|
6
|
+
import { durableMessageTranscript, projectionStateThrough } from "./domain/message-transcript.js";
|
|
7
|
+
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
8
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-_vF1bIJ7.js";
|
|
9
|
+
import { EDAToolRegistry } from "./services/tool-registry.js";
|
|
6
10
|
import { IdGenerator } from "./services/id-generator.js";
|
|
7
|
-
import { t as EventFactory } from "./event-factory-DTFdy0Cb.js";
|
|
8
11
|
import { annotateEdaSpan, committedBatchAttributes } from "./services/tracing.js";
|
|
9
12
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
10
13
|
import * as Context from "effect/Context";
|
|
11
14
|
import * as Effect from "effect/Effect";
|
|
12
15
|
import * as Layer from "effect/Layer";
|
|
13
16
|
import * as Schema from "effect/Schema";
|
|
14
|
-
import * as Prompt from "effect/
|
|
17
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
15
18
|
//#region src/services/provider-usage.ts
|
|
16
19
|
/** Normalizes provider usage for both conversation and compaction calls. */
|
|
17
20
|
const makeUsagePayload = (usage) => {
|
|
@@ -65,7 +68,7 @@ const CompactionOutput = Schema.Struct({
|
|
|
65
68
|
usage: Schema.optionalKey(UsagePayload)
|
|
66
69
|
});
|
|
67
70
|
/** Typed failure from policy planning or summary generation. */
|
|
68
|
-
var CompactionError = class extends Schema.
|
|
71
|
+
var CompactionError = class extends Schema.TaggedError()("CompactionError", {
|
|
69
72
|
message: Schema.String,
|
|
70
73
|
usage: Schema.optionalKey(UsagePayload)
|
|
71
74
|
}) {};
|
|
@@ -142,6 +145,33 @@ var CompactionExecutor = class CompactionExecutor extends Context.Service()("@ef
|
|
|
142
145
|
};
|
|
143
146
|
}));
|
|
144
147
|
};
|
|
148
|
+
/**
|
|
149
|
+
* Provider-neutral summary that reuses the conversation's own prompt prefix (instructions, tools,
|
|
150
|
+
* history) and appends the summarization request, so the call reads the conversation from the
|
|
151
|
+
* provider cache. Pair it with a policy that retains nothing (`retainTailTokens: 0`) on providers
|
|
152
|
+
* that bind reasoning to its conversation; use provider-native executors to keep a tail.
|
|
153
|
+
*/
|
|
154
|
+
const promptPrefixSummaryCompactionExecutor = (options = {}) => Layer.succeed(CompactionExecutor, {
|
|
155
|
+
id: CompactionExecutorId.make(options.executorId ?? "prompt-prefix-summary"),
|
|
156
|
+
execute: Effect.fn("agent.compaction")(function* (input) {
|
|
157
|
+
const request = options.instructions ?? `Do not call any tools. ${summaryPromptText}`;
|
|
158
|
+
const prompt = Prompt.fromMessages([...input.prompt.content, Prompt.makeMessage("user", { content: [Prompt.textPart({ text: request })] })]);
|
|
159
|
+
const response = yield* generateTextOfferingTools(input.model, prompt, input.toolkit).pipe(Effect.mapError((error) => new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` })));
|
|
160
|
+
const text = response.text.trim();
|
|
161
|
+
if (text.length === 0) return yield* new CompactionError({
|
|
162
|
+
message: "summary model returned no text",
|
|
163
|
+
usage: makeUsagePayload(response.usage)
|
|
164
|
+
});
|
|
165
|
+
return CompactionOutput.make({
|
|
166
|
+
usage: makeUsagePayload(response.usage),
|
|
167
|
+
text,
|
|
168
|
+
promptMessage: Prompt.makeMessage("user", { content: [Prompt.textPart({ text: `${options.summaryMessagePrefix ?? "Conversation summary:"}\n\n${text}` })] }),
|
|
169
|
+
executorId: CompactionExecutorId.make(options.executorId ?? "prompt-prefix-summary")
|
|
170
|
+
});
|
|
171
|
+
})
|
|
172
|
+
});
|
|
173
|
+
/** EDA's checkpoint summary request, exposed for executors that pass custom instructions. */
|
|
174
|
+
const defaultCompactionSummaryInstructions = () => summaryPromptText;
|
|
145
175
|
/** Framework-owned compaction lifecycle runner. */
|
|
146
176
|
var CompactionRunner = class CompactionRunner extends Context.Service()("@effect-durable-agent/CompactionRunner") {
|
|
147
177
|
static Live = Layer.effect(CompactionRunner, Effect.suspend(() => makeLiveCompactionRunner));
|
|
@@ -153,6 +183,9 @@ const makeLiveCompactionRunner = Effect.gen(function* () {
|
|
|
153
183
|
const executor = yield* CompactionExecutor;
|
|
154
184
|
const keepAlive = yield* EDAKeepAlive;
|
|
155
185
|
const models = yield* ModelResolver;
|
|
186
|
+
const promptProjector = yield* EDAPromptProjector;
|
|
187
|
+
const toolRegistry = yield* EDAToolRegistry;
|
|
188
|
+
const session = yield* SessionContext;
|
|
156
189
|
return { maybeCompact: Effect.fnUntraced(function* (input) {
|
|
157
190
|
const plan = yield* policy.plan({
|
|
158
191
|
state: input.state,
|
|
@@ -188,11 +221,21 @@ const makeLiveCompactionRunner = Effect.gen(function* () {
|
|
|
188
221
|
const started = yield* events.compactionStarted({ compactionId });
|
|
189
222
|
const startedEvents = yield* input.appendDurableEntries([{ event: requested }, { event: started }]);
|
|
190
223
|
const model = yield* models.resolve(input.state.modelSelection);
|
|
224
|
+
const projected = yield* buildEDAPrompt(promptProjector, {
|
|
225
|
+
sessionId: session.sessionId,
|
|
226
|
+
state: projectionStateThrough(input.state, plan.sourceToSeq),
|
|
227
|
+
reducerStates: input.reducerStates,
|
|
228
|
+
context: input.context
|
|
229
|
+
});
|
|
230
|
+
const prompt = models.preparePrompt?.(input.state.modelSelection, projected) ?? projected;
|
|
231
|
+
const toolkit = yield* toolRegistry.getModelToolkit();
|
|
191
232
|
const output = yield* keepAlive.withActiveWork(`compaction:${compactionId}`, executor.execute({
|
|
192
233
|
plan,
|
|
193
234
|
state: input.state,
|
|
194
235
|
context: input.context,
|
|
195
|
-
model
|
|
236
|
+
model,
|
|
237
|
+
prompt,
|
|
238
|
+
toolkit
|
|
196
239
|
})).pipe(Effect.catchTag("CompactionError", (error) => Effect.gen(function* () {
|
|
197
240
|
const failed = yield* events.compactionFailed({
|
|
198
241
|
compactionId,
|
|
@@ -257,6 +300,7 @@ const validatePlan = (plan, state, context) => {
|
|
|
257
300
|
if (plan.retainedFromContextSeq <= plan.sourceToSeq) return "retainedFromContextSeq must start after the summarized source range";
|
|
258
301
|
};
|
|
259
302
|
const normalizeApproximateTokenPolicyOptions = (options) => ({
|
|
303
|
+
retain: options.retain ?? "tail-tokens",
|
|
260
304
|
policyId: CompactionPolicyId.make(options.policyId ?? "approximate-token-threshold"),
|
|
261
305
|
thresholdTokens: positiveNumber(options.thresholdTokens ?? 22e4, "thresholdTokens"),
|
|
262
306
|
retainTailTokens: nonNegativeNumber(options.retainTailTokens ?? 4e4, "retainTailTokens"),
|
|
@@ -276,7 +320,8 @@ const planApproximateTokenCompaction = (state, context, options) => {
|
|
|
276
320
|
const messages = estimatedContextMessages(state);
|
|
277
321
|
if (estimateCurrentPromptChars(state, context, messages) <= options.thresholdTokens * options.charsPerToken) return;
|
|
278
322
|
const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
|
|
279
|
-
const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);
|
|
323
|
+
const retainedFromSeq = options.retain === "last-response" ? lastResponseSeq(messages, currentRetainedFromSeq) : selectRetainedFromSeq(messages, state.lastSeq, options);
|
|
324
|
+
if (retainedFromSeq === void 0) return;
|
|
280
325
|
if (retainedFromSeq <= currentRetainedFromSeq) return;
|
|
281
326
|
const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);
|
|
282
327
|
if (sourceMessages.length === 0) return;
|
|
@@ -291,6 +336,13 @@ const planApproximateTokenCompaction = (state, context, options) => {
|
|
|
291
336
|
retainedFromContextSeq: retainedFromSeq
|
|
292
337
|
});
|
|
293
338
|
};
|
|
339
|
+
/** Sequence of the latest assistant response past the current cursor, if any. */
|
|
340
|
+
const lastResponseSeq = (messages, currentRetainedFromSeq) => {
|
|
341
|
+
for (const entry of [...messages].reverse()) {
|
|
342
|
+
if (entry.seq <= currentRetainedFromSeq) return;
|
|
343
|
+
if (entry.message._tag === "Assistant" || entry.message._tag === "AssistantPartial") return entry.seq;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
294
346
|
const selectRetainedFromSeq = (messages, lastSeq, options) => {
|
|
295
347
|
if (options.retainTailTokens === 0) return SequenceNumber.make(lastSeq + 1);
|
|
296
348
|
const retainTailChars = options.retainTailTokens * options.charsPerToken;
|
|
@@ -373,9 +425,7 @@ const serializeAssistantMessage = (promptParts, content) => {
|
|
|
373
425
|
case "tool-result":
|
|
374
426
|
sideband.push(`tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`);
|
|
375
427
|
break;
|
|
376
|
-
case "tool-approval-request":
|
|
377
|
-
sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);
|
|
378
|
-
break;
|
|
428
|
+
case "tool-approval-request": sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);
|
|
379
429
|
}
|
|
380
430
|
return [
|
|
381
431
|
reasoning.length === 0 ? "" : `[Assistant reasoning]: ${reasoning.join("\n")}`,
|
|
@@ -468,6 +518,6 @@ Rules:
|
|
|
468
518
|
- Preserve exact file paths, tool names, identifiers, and error messages.
|
|
469
519
|
- Do not answer questions from the conversation.`;
|
|
470
520
|
//#endregion
|
|
471
|
-
export { CompactionPolicy as a, defaultCompactionMinSummarizableTokens as c,
|
|
521
|
+
export { CompactionPolicy as a, defaultCompactionMinSummarizableTokens as c, defaultCompactionThresholdTokens as d, promptPrefixSummaryCompactionExecutor as f, CompactionPlan as i, defaultCompactionRetainTailTokens as l, CompactionExecutor as n, CompactionRunner as o, makeUsagePayload as p, CompactionOutput as r, defaultCompactionCharsPerToken as s, CompactionError as t, defaultCompactionSummaryInstructions as u };
|
|
472
522
|
|
|
473
|
-
//# sourceMappingURL=compaction-
|
|
523
|
+
//# sourceMappingURL=compaction-63iEDHHl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compaction-63iEDHHl.js","names":[],"sources":["../src/services/provider-usage.ts","../src/services/compaction.ts"],"sourcesContent":["import type * as Response from \"effect/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/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\nimport type * as LanguageModel from \"effect/ai/LanguageModel\";\nimport { ModelResolver } from \"./model-resolver\";\nimport { generateTextOfferingTools } from \"./model-call\";\nimport { makeUsagePayload } from \"./provider-usage\";\nimport { buildEDAPrompt, EDAPromptProjector } from \"./prompt-projector\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { SessionContext } from \"./session-context\";\nimport { EDAToolRegistry, type EDAModelToolkit } from \"./tool-registry\";\n\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport {\n durableMessageTranscript,\n projectionStateThrough,\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 * What stays verbatim after the summary. `tail-tokens` (default) keeps roughly\n * `retainTailTokens` of recent context. `last-response` keeps exactly the latest assistant\n * response and what followed it, so the summarized range equals the prompt of a request already\n * sent: provider caches cover the compaction call and provider-native compaction keeps the\n * retained response's reasoning valid.\n */\n readonly retain?: \"tail-tokens\" | \"last-response\";\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.LanguageModel;\n /**\n * The provider prompt as it stood through `plan.sourceToSeq`: the same instructions, history and\n * trailing context an inference at that point would send. Executors that reuse it share the\n * conversation's provider cache.\n */\n readonly prompt: Prompt.Prompt;\n /** Tools offered with every inference; reusing them keeps the cached prefix identical. */\n readonly toolkit: EDAModelToolkit | undefined;\n}\n\n/** Typed failure from policy planning or summary generation. */\nexport class CompactionError extends Schema.TaggedError<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/** Prompt-prefix summary executor options. */\nexport interface PromptPrefixSummaryCompactionExecutorOptions {\n /** Stable executor id stored on summary artifacts. */\n readonly executorId?: string;\n /** Summarization request appended after the conversation. Defaults to EDA's checkpoint prompt. */\n readonly instructions?: string;\n /** Prefix used for the synthetic prompt message inserted into future context. */\n readonly summaryMessagePrefix?: string;\n}\n\n/**\n * Provider-neutral summary that reuses the conversation's own prompt prefix (instructions, tools,\n * history) and appends the summarization request, so the call reads the conversation from the\n * provider cache. Pair it with a policy that retains nothing (`retainTailTokens: 0`) on providers\n * that bind reasoning to its conversation; use provider-native executors to keep a tail.\n */\nexport const promptPrefixSummaryCompactionExecutor = (\n options: PromptPrefixSummaryCompactionExecutorOptions = {},\n): Layer.Layer<CompactionExecutor> =>\n Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(options.executorId ?? \"prompt-prefix-summary\"),\n execute: Effect.fn(\"agent.compaction\")(function* (input) {\n const request = options.instructions ?? `Do not call any tools. ${summaryPromptText}`;\n const prompt = Prompt.fromMessages([\n ...input.prompt.content,\n Prompt.makeMessage(\"user\", { content: [Prompt.textPart({ text: request })] }),\n ]);\n const response = yield* generateTextOfferingTools(input.model, prompt, input.toolkit).pipe(\n Effect.mapError(\n (error) =>\n new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` }),\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: [\n Prompt.textPart({\n text: `${options.summaryMessagePrefix ?? \"Conversation summary:\"}\\n\\n${text}`,\n }),\n ],\n }),\n executorId: CompactionExecutorId.make(options.executorId ?? \"prompt-prefix-summary\"),\n });\n }),\n } satisfies CompactionExecutorShape);\n\n/** EDA's checkpoint summary request, exposed for executors that pass custom instructions. */\nexport const defaultCompactionSummaryInstructions = (): string => summaryPromptText;\n\n/** Inputs needed by the framework-owned compaction lifecycle runner. */\nexport interface CompactionRunnerInput {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\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 retain: \"tail-tokens\" | \"last-response\";\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 const promptProjector = yield* EDAPromptProjector;\n const toolRegistry = yield* EDAToolRegistry;\n const session = yield* SessionContext;\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 projected = yield* buildEDAPrompt(promptProjector, {\n sessionId: session.sessionId,\n state: projectionStateThrough(input.state, plan.sourceToSeq),\n reducerStates: input.reducerStates,\n context: input.context,\n });\n const prompt = models.preparePrompt?.(input.state.modelSelection, projected) ?? projected;\n const toolkit = yield* toolRegistry.getModelToolkit();\n const output = yield* keepAlive\n .withActiveWork(\n `compaction:${compactionId}`,\n executor.execute({\n plan,\n state: input.state,\n context: input.context,\n model,\n prompt,\n toolkit,\n }),\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 retain: options.retain ?? \"tail-tokens\",\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 =\n options.retain === \"last-response\"\n ? lastResponseSeq(messages, currentRetainedFromSeq)\n : selectRetainedFromSeq(messages, state.lastSeq, options);\n if (retainedFromSeq === undefined) {\n return undefined;\n }\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\n/** Sequence of the latest assistant response past the current cursor, if any. */\nconst lastResponseSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n currentRetainedFromSeq: SequenceNumber,\n): SequenceNumber | undefined => {\n for (const entry of [...messages].reverse()) {\n if (entry.seq <= currentRetainedFromSeq) {\n return undefined;\n }\n if (entry.message._tag === \"Assistant\" || entry.message._tag === \"AssistantPartial\") {\n return entry.seq;\n }\n }\n return undefined;\n};\n\nconst selectRetainedFromSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n lastSeq: SequenceNumber,\n options: NormalizedApproximateTokenPolicyOptions,\n): SequenceNumber => {\n if (options.retainTailTokens === 0) {\n return SequenceNumber.make(lastSeq + 1);\n }\n\n const retainTailChars = options.retainTailTokens * options.charsPerToken;\n let tailChars = 0;\n let retainedIndex = messages.length;\n for (let index = messages.length - 1; index >= 0; index--) {\n tailChars += messages[index]!.chars;\n retainedIndex = index;\n if (tailChars >= retainTailChars) {\n break;\n }\n }\n return retainedIndex >= messages.length\n ? SequenceNumber.make(lastSeq + 1)\n : messages[retainedIndex]!.seq;\n};\n\nconst estimateCurrentPromptChars = (\n state: ReducedState,\n context: ContextProjection,\n messages: ReadonlyArray<EstimatedContextMessage>,\n): number => {\n const systemChars = Array.from(state.messages.values()).reduce(\n (sum, message) => (message._tag === \"System\" ? sum + message.content.length : sum),\n 0,\n );\n const summaryChars =\n context.currentSummary === undefined\n ? 0\n : estimatePromptMessageChars(context.currentSummary.promptMessage);\n const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);\n return systemChars + summaryChars + messageChars;\n};\n\nconst estimatedContextMessages = (state: ReducedState): ReadonlyArray<EstimatedContextMessage> =>\n durableMessageTranscript(state).map((message) => ({\n message,\n seq: messageSeq(message),\n chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state),\n }));\n\nconst estimateDurableMessageChars = (message: DurableTranscriptMessage): number => {\n switch (message._tag) {\n case \"User\":\n case \"Steering\":\n return estimateUserContentChars(message.content);\n case \"Assistant\":\n case \"AssistantPartial\":\n return estimateAssistantPromptChars(message.promptParts, message.content);\n }\n};\n\nconst estimateAssociatedToolChars = (\n message: DurableTranscriptMessage,\n state: ReducedState,\n): number => {\n if (message._tag !== \"Assistant\" && message._tag !== \"AssistantPartial\") {\n return 0;\n }\n return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n};\n\nconst messageSeq = (message: DurableTranscriptMessage): SequenceNumber =>\n message._tag === \"Steering\" ? message.consumedSeq : message.seq;\n\nconst charsToTokens = (chars: number, charsPerToken: number): number =>\n Math.ceil(chars / charsPerToken);\n\nconst buildSummaryPrompt = (input: CompactionExecutorInput): string | undefined => {\n const sourceText = serializeCompactionSource(input);\n if (sourceText.trim().length === 0) {\n return undefined;\n }\n\n const previousSummary =\n input.context.currentSummary === undefined\n ? \"\"\n : `<previous-summary>\\n${input.context.currentSummary.text}\\n</previous-summary>\\n\\n`;\n return `${previousSummary}<conversation>\\n${sourceText}\\n</conversation>\\n\\n${summaryPromptText}`;\n};\n\nconst serializeCompactionSource = (input: CompactionExecutorInput): string => {\n const lines: Array<string> = [];\n for (const message of durableMessageTranscript(input.state)) {\n const seq = messageSeq(message);\n if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) {\n continue;\n }\n lines.push(serializeDurableMessage(message));\n if (message._tag === \"Assistant\" || message._tag === \"AssistantPartial\") {\n for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) {\n lines.push(serializeToolResultPart(part));\n }\n }\n }\n return lines.filter((line) => line.trim().length > 0).join(\"\\n\\n\");\n};\n\nconst serializeDurableMessage = (message: DurableTranscriptMessage): string => {\n switch (message._tag) {\n case \"User\":\n return `[User]: ${userContentText(message.content)}`;\n case \"Steering\":\n return `[User steering]: ${userContentText(message.content)}`;\n case \"Assistant\":\n case \"AssistantPartial\":\n return serializeAssistantMessage(message.promptParts, message.content);\n }\n};\n\nconst serializeAssistantMessage = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): string => {\n const parts = promptParts ?? assistantContentToPromptParts(content);\n const text: Array<string> = [];\n const reasoning: Array<string> = [];\n const toolCalls: Array<string> = [];\n const sideband: Array<string> = [];\n for (const part of parts) {\n switch (part.type) {\n case \"text\":\n text.push(part.text);\n break;\n case \"reasoning\":\n reasoning.push(part.text);\n break;\n case \"tool-call\":\n toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);\n break;\n case \"file\":\n sideband.push(`file(${part.fileName ?? \"unnamed\"}, ${part.mediaType})`);\n break;\n case \"tool-result\":\n sideband.push(\n `tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`,\n );\n break;\n case \"tool-approval-request\":\n sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);\n break;\n }\n }\n return [\n reasoning.length === 0 ? \"\" : `[Assistant reasoning]: ${reasoning.join(\"\\n\")}`,\n text.length === 0 ? \"\" : `[Assistant]: ${text.join(\"\\n\")}`,\n toolCalls.length === 0 ? \"\" : `[Assistant tool calls]: ${toolCalls.join(\"; \")}`,\n sideband.length === 0 ? \"\" : `[Assistant context]: ${sideband.join(\"; \")}`,\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\");\n};\n\nconst serializeToolResultPart = (part: Prompt.ToolResultPart): string =>\n `[Tool result ${part.name}${part.isFailure ? \" failed\" : \"\"}]: ${truncateForSummary(\n safeJsonStringify(part.result),\n )}`;\n\nconst toolPromptPartsForInference = (\n inferenceId: InferenceId,\n toolCalls: ReducedState[\"toolCalls\"],\n): ReadonlyArray<Prompt.ToolResultPart> =>\n Array.from(toolCalls.values()).flatMap((tool): ReadonlyArray<Prompt.ToolResultPart> => {\n const { decision } = tool;\n if (decision === undefined || decision.inferenceId !== inferenceId) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined ? [] : [decision.promptPart];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [terminal.promptPart];\n });\n\nconst assistantContentToPromptParts = (\n content: AssistantMessageContent,\n): ReadonlyArray<Prompt.AssistantMessagePart> => [\n ...(content.reasoning === undefined ? [] : [Prompt.reasoningPart({ text: content.reasoning })]),\n ...(content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]),\n];\n\nconst estimateAssistantPromptChars = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): number =>\n (promptParts ?? assistantContentToPromptParts(content)).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n\nconst estimateUserContentChars = (\n content: string | ReadonlyArray<Prompt.UserMessagePart>,\n): number =>\n typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n\nconst estimatePromptMessageChars = (message: Prompt.Message): number => {\n if (!(\"content\" in message)) {\n return 0;\n }\n const { content } = message;\n return typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n};\n\ntype PromptContentPart =\n | Prompt.UserMessagePart\n | Prompt.AssistantMessagePart\n | Prompt.ToolMessagePart;\n\nconst estimatePromptPartChars = (part: PromptContentPart): number => {\n switch (part.type) {\n case \"text\":\n return part.text.length;\n case \"reasoning\":\n return part.text.length;\n case \"file\":\n return (\n part.mediaType.length +\n (part.fileName?.length ?? 0) +\n (typeof part.data === \"string\"\n ? part.data.length\n : part.data instanceof URL\n ? part.data.toString().length\n : estimatedBinaryFileChars)\n );\n case \"tool-call\":\n return part.name.length + safeJsonStringify(part.params).length;\n case \"tool-result\":\n return part.name.length + safeJsonStringify(part.result).length;\n case \"tool-approval-response\":\n return part.approvalId.length + (part.reason?.length ?? 0) + 8;\n case \"tool-approval-request\":\n return part.approvalId.length + part.toolCallId.length;\n default:\n return safeJsonStringify(part).length;\n }\n};\n\nconst userContentText = (content: string | ReadonlyArray<Prompt.UserMessagePart>): string =>\n typeof content === \"string\"\n ? content\n : content\n .map((part) => {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"file\":\n return `[file ${part.fileName ?? \"unnamed\"} ${part.mediaType}]`;\n }\n })\n .join(\"\\n\");\n\nconst safeJsonStringify = (value: unknown): string => {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst truncateForSummary = (text: string, maxChars = 2_000): string => {\n if (text.length <= maxChars) {\n return text;\n }\n return `${text.slice(0, maxChars)}\\n\\n[... ${text.length - maxChars} more characters truncated]`;\n};\n\nconst formatUnknownError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst estimatedBinaryFileChars = 4_800;\n\nconst summarizationSystemPrompt =\n \"You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.\";\n\nconst summaryPromptText = `The messages above are conversation history selected for compaction. Create a cumulative context checkpoint summary that another LLM will use to continue the work.\n\nUse this exact structure:\n\n## Goal\n[What the user is trying to accomplish]\n\n## Constraints & Preferences\n- [Requirements, constraints, and preferences]\n\n## Progress\n### Done\n- [x] [Completed work]\n\n### In Progress\n- [ ] [Current unfinished work]\n\n### Blocked\n- [Current blockers, or \"(none)\"]\n\n## Key Decisions\n- **[Decision]**: [Rationale]\n\n## Next Steps\n1. [Concrete next step]\n\n## Critical Context\n- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]\n\nRules:\n- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.\n- Keep the summary concise but sufficient to replace the compacted history.\n- Preserve exact file paths, tool names, identifiers, and error messages.\n- Do not answer questions from the conversation.`;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoB,UAA0B;CACzD,MAAM,sBAAsB,eAAe,MAAM,YAAY,QAAQ;CACrE,MAAM,oBAAoB,eAAe,MAAM,YAAY,SAAS;CACpE,MAAM,wBAAwB,eAAe,MAAM,YAAY,UAAU;CACzE,MAAM,cACJ,eAAe,MAAM,YAAY,KAAK,KACtC,WAAW;EAAC;EAAqB;EAAmB;CAAqB,CAAC;CAC5E,MAAM,aAAa,eAAe,MAAM,aA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K,SAAS,CAAC,CAAC,SACrB;EAEV,KAAK,aACH,OAAO,KAAK,KAAK,SAAS,kBAAkB,KAAK,MAAM,CAAC,CAAC;EAC3D,KAAK,eACH,OAAO,KAAK,KAAK,SAAS,kBAAkB,KAAK,MAAM,CAAC,CAAC;EAC3D,KAAK,0BACH,OAAO,KAAK,WAAW,UAAU,KAAK,QAAQ,UAAU,KAAK;EAC/D,KAAK,yBACH,OAAO,KAAK,WAAW,SAAS,KAAK,WAAW;EAClD,SACE,OAAO,kBAAkB,IAAI,CAAC,CAAC;CACnC;AACF;AAEA,MAAM,mBAAmB,YACvB,OAAO,YAAY,WACf,UACA,QACG,KAAK,SAAS;CACb,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO,KAAK;EACd,KAAK,QACH,OAAO,SAAS,KAAK,YAAY,UAAU,GAAG,KAAK,UAAU;CACjE;AACF,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,MAAM,qBAAqB,UAA2B;CACpD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,MAAM,sBAAsB,MAAc,WAAW,QAAkB;CACrE,IAAI,KAAK,UAAU,UACjB,OAAO;CAET,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,EAAE,WAAW,KAAK,SAAS,SAAS;AACtE;AAEA,MAAM,sBAAsB,UAC1B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,2BAA2B;AAEjC,MAAM,4BACJ;AAEF,MAAM,oBAAoB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as Schema from "effect/Schema";
|
|
2
|
-
|
|
2
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
3
3
|
//#region src/domain/context-projection.d.ts
|
|
4
4
|
/** Stable identifier for the compaction policy that selected a summary plan. */
|
|
5
5
|
declare const CompactionPolicyId: Schema.brand<Schema.NonEmptyString, "CompactionPolicyId">;
|
|
@@ -23,19 +23,7 @@ declare const CompactionSummaryArtifact: Schema.Struct<{
|
|
|
23
23
|
readonly text: Schema.String;
|
|
24
24
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
25
25
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
26
|
-
}>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [
|
|
27
|
-
readonly type: Schema.Literal<"text">;
|
|
28
|
-
readonly text: Schema.String;
|
|
29
|
-
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
30
|
-
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
31
|
-
}>, Schema.Struct<{
|
|
32
|
-
readonly type: Schema.Literal<"file">;
|
|
33
|
-
readonly mediaType: Schema.String;
|
|
34
|
-
readonly fileName: Schema.optional<Schema.String>;
|
|
35
|
-
readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.URL]>;
|
|
36
|
-
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
37
|
-
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
38
|
-
}>]>>]>;
|
|
26
|
+
}>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [typeof Prompt.TextPart, typeof Prompt.FilePart]>>]>;
|
|
39
27
|
readonly "~effect/ai/Prompt/Message": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Message">>;
|
|
40
28
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
41
29
|
}>;
|
|
@@ -61,19 +49,7 @@ declare const ContextProjection: Schema.Struct<{
|
|
|
61
49
|
readonly text: Schema.String;
|
|
62
50
|
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
63
51
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
64
|
-
}>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [
|
|
65
|
-
readonly type: Schema.Literal<"text">;
|
|
66
|
-
readonly text: Schema.String;
|
|
67
|
-
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
68
|
-
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
69
|
-
}>, Schema.Struct<{
|
|
70
|
-
readonly type: Schema.Literal<"file">;
|
|
71
|
-
readonly mediaType: Schema.String;
|
|
72
|
-
readonly fileName: Schema.optional<Schema.String>;
|
|
73
|
-
readonly data: Schema.Union<readonly [Schema.String, Schema.Uint8Array, Schema.URL]>;
|
|
74
|
-
readonly "~effect/ai/Prompt/Part": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Part">>;
|
|
75
|
-
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
76
|
-
}>]>>]>;
|
|
52
|
+
}>>>, Schema.String, never, never>, Schema.$Array<Schema.Union<readonly [typeof Prompt.TextPart, typeof Prompt.FilePart]>>]>;
|
|
77
53
|
readonly "~effect/ai/Prompt/Message": Schema.withDecodingDefaultKey<Schema.Literal<"~effect/ai/Prompt/Message">>;
|
|
78
54
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
79
55
|
}>;
|
|
@@ -88,53 +64,53 @@ declare const emptyContextProjection: {
|
|
|
88
64
|
readonly currentSummary?: {
|
|
89
65
|
readonly compactionId: string & import("effect/Brand").Brand<"CompactionId">;
|
|
90
66
|
readonly summaryId: string & import("effect/Brand").Brand<"SummaryId">;
|
|
67
|
+
readonly previousSummaryId?: (string & import("effect/Brand").Brand<"SummaryId">) | undefined;
|
|
91
68
|
readonly sourceFromSeq: number & import("effect/Brand").Brand<"SequenceNumber">;
|
|
92
69
|
readonly sourceToSeq: number & import("effect/Brand").Brand<"SequenceNumber">;
|
|
93
70
|
readonly retainedFromContextSeq: number & import("effect/Brand").Brand<"SequenceNumber">;
|
|
94
71
|
readonly text: string;
|
|
95
72
|
readonly promptMessage: {
|
|
96
73
|
readonly role: "user";
|
|
97
|
-
readonly content: readonly
|
|
74
|
+
readonly content: readonly ({
|
|
98
75
|
readonly type: "text";
|
|
99
76
|
readonly text: string;
|
|
100
77
|
readonly "~effect/ai/Prompt/Part": "~effect/ai/Prompt/Part";
|
|
101
78
|
readonly options: {
|
|
102
79
|
readonly [x: string]: Schema.Json;
|
|
103
80
|
};
|
|
104
|
-
}
|
|
105
|
-
readonly type: "
|
|
106
|
-
readonly
|
|
81
|
+
} | {
|
|
82
|
+
readonly type: "file";
|
|
83
|
+
readonly mediaType: string;
|
|
84
|
+
readonly fileName?: string | undefined;
|
|
85
|
+
readonly data: string | URL | Uint8Array<ArrayBufferLike>;
|
|
107
86
|
readonly "~effect/ai/Prompt/Part": "~effect/ai/Prompt/Part";
|
|
108
87
|
readonly options: {
|
|
109
88
|
readonly [x: string]: Schema.Json;
|
|
110
89
|
};
|
|
111
|
-
}[]
|
|
90
|
+
})[] | readonly [{
|
|
112
91
|
readonly type: "text";
|
|
113
92
|
readonly text: string;
|
|
114
93
|
readonly "~effect/ai/Prompt/Part": "~effect/ai/Prompt/Part";
|
|
115
94
|
readonly options: {
|
|
116
95
|
readonly [x: string]: Schema.Json;
|
|
117
96
|
};
|
|
118
|
-
}
|
|
97
|
+
}, ...{
|
|
98
|
+
readonly type: "text";
|
|
99
|
+
readonly text: string;
|
|
119
100
|
readonly "~effect/ai/Prompt/Part": "~effect/ai/Prompt/Part";
|
|
120
101
|
readonly options: {
|
|
121
102
|
readonly [x: string]: Schema.Json;
|
|
122
103
|
};
|
|
123
|
-
|
|
124
|
-
readonly mediaType: string;
|
|
125
|
-
readonly data: string | Uint8Array<ArrayBufferLike> | URL;
|
|
126
|
-
readonly fileName?: string | undefined;
|
|
127
|
-
})[];
|
|
104
|
+
}[]];
|
|
128
105
|
readonly "~effect/ai/Prompt/Message": "~effect/ai/Prompt/Message";
|
|
129
106
|
readonly options: {
|
|
130
107
|
readonly [x: string]: Schema.Json;
|
|
131
108
|
};
|
|
132
109
|
};
|
|
133
110
|
readonly policyId: string & import("effect/Brand").Brand<"CompactionPolicyId">;
|
|
134
|
-
readonly previousSummaryId?: (string & import("effect/Brand").Brand<"SummaryId">) | undefined;
|
|
135
111
|
readonly executorId?: (string & import("effect/Brand").Brand<"CompactionExecutorId">) | undefined;
|
|
136
112
|
} | undefined;
|
|
137
113
|
};
|
|
138
114
|
//#endregion
|
|
139
115
|
export { emptyContextProjection as a, ContextProjection as i, CompactionPolicyId as n, CompactionSummaryArtifact as r, CompactionExecutorId as t };
|
|
140
|
-
//# sourceMappingURL=context-projection-
|
|
116
|
+
//# sourceMappingURL=context-projection-Bezx3drD.d.ts.map
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import * as Schema from "effect/Schema";
|
|
2
2
|
import * as Order from "effect/Order";
|
|
3
|
-
|
|
4
3
|
//#region src/types/core.d.ts
|
|
5
4
|
/** Durable conversation identity; one host isolation unit stores one session.
|
|
6
5
|
*
|
|
@@ -19,6 +18,9 @@ type CommandId = typeof CommandId.Type;
|
|
|
19
18
|
/** Processing lifecycle identity triggered by one or more commands. */
|
|
20
19
|
declare const RunId: Schema.brand<Schema.String, "RunId">;
|
|
21
20
|
type RunId = typeof RunId.Type;
|
|
21
|
+
/** Stable deduplication identity for one durable request to authorize a new run. */
|
|
22
|
+
declare const RunRequestId: Schema.brand<Schema.String, "RunRequestId">;
|
|
23
|
+
type RunRequestId = typeof RunRequestId.Type;
|
|
22
24
|
/** One LLM invocation within a run. */
|
|
23
25
|
declare const TurnId: Schema.brand<Schema.String, "TurnId">;
|
|
24
26
|
type TurnId = typeof TurnId.Type;
|
|
@@ -77,5 +79,5 @@ declare const comparePosition: Order.Order<{
|
|
|
77
79
|
readonly subSeq: number & import("effect/Brand").Brand<"SubSequenceNumber">;
|
|
78
80
|
}>;
|
|
79
81
|
//#endregion
|
|
80
|
-
export {
|
|
81
|
-
//# sourceMappingURL=core-
|
|
82
|
+
export { durablePosition as S, SubSequenceNumber as _, CorrelationId as a, TurnId as b, EventId as c, Position as d, PositionOrder as f, SessionId as g, SequenceNumber as h, ContextVersion as i, InferenceId as l, RunRequestId as m, CommandId as n, DurablePosition as o, RunId as p, CompactionId as r, DurableSubSequenceNumber as s, BaseStateId as t, MessageId as u, SummaryId as v, comparePosition as x, ToolCallId as y };
|
|
83
|
+
//# sourceMappingURL=core-BcimKMIv.d.ts.map
|