effect-durable-agent 0.1.0-alpha.6 → 0.1.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{command-queues-C8muEqeQ.d.ts → command-queues-DdDB_aYM.d.ts} +11 -18
- package/dist/{compaction-F4HEWzuI.d.ts → compaction-BEor3jKv.d.ts} +27 -8
- package/dist/compaction-BgDr5VJy.js +473 -0
- package/dist/compaction-BgDr5VJy.js.map +1 -0
- package/dist/{context-projection-C43pyxn2.d.ts → context-projection-n6Rdup0N.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/model-usage.d.ts +2 -0
- package/dist/domain/model-usage.js +59 -0
- package/dist/domain/model-usage.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +11 -17
- package/dist/domain/reduced-state-schema.js +6 -11
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +3 -2
- package/dist/domain/reduced-state.js +3 -2
- package/dist/{durable-DsV9PxZC.js → durable-BGFvX7Mh.js} +17 -80
- package/dist/durable-BGFvX7Mh.js.map +1 -0
- package/dist/{durable-B7M6TD_0.d.ts → durable-br2C1bWK.d.ts} +247 -4
- package/dist/envelope-DkZyMIgp.d.ts +191 -0
- package/dist/envelope-DxQzo5rN.js +82 -0
- package/dist/envelope-DxQzo5rN.js.map +1 -0
- package/dist/{event-factory-tcpLgdMN.js → event-factory-DTFdy0Cb.js} +3 -2
- package/dist/{event-factory-tcpLgdMN.js.map → event-factory-DTFdy0Cb.js.map} +1 -1
- package/dist/{event-factory-CLJcyymV.d.ts → event-factory-pFzsPlDs.d.ts} +4 -4
- package/dist/{events-Bb9-Cu-7.d.ts → events-LZFNoESe.d.ts} +2 -188
- package/dist/index.d.ts +5 -4
- package/dist/index.js +4 -3
- package/dist/{message-transcript-DsKTT47f.d.ts → message-transcript-DQNlzxle.d.ts} +3 -3
- package/dist/model-resolver-BPPJAsuh.d.ts +18 -0
- package/dist/model-usage-CdBEkTwU.d.ts +55 -0
- package/dist/{prompt-projector-hqPh5-NI.d.ts → prompt-projector-f4ElyXCE.d.ts} +4 -4
- package/dist/{reduced-state-TMi7ISla.js → reduced-state-DF0-6mbR.js} +25 -30
- package/dist/reduced-state-DF0-6mbR.js.map +1 -0
- package/dist/{reducer-registry--vQFATXb.d.ts → reducer-registry-aFjz_ZLT.d.ts} +2 -2
- package/dist/{runtime-BO9KJq_Y.d.ts → runtime-DbTCb32-.d.ts} +5 -5
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -426
- package/dist/services/model-resolver.d.ts +2 -0
- package/dist/services/model-resolver.js +17 -0
- package/dist/services/model-resolver.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +14 -14
- package/dist/services/runtime-layer.js +8 -7
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +3 -2
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +3 -3
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +2 -1
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tracing.d.ts +1 -1
- package/dist/{session-event-observer-D_aoFnQs.d.ts → session-event-observer-DaFMKKNc.d.ts} +2 -2
- package/dist/{session-query-_Z3Kw6jj.d.ts → session-query-l8xpJYp8.d.ts} +8 -8
- package/dist/{session-state-BfoXKafd.d.ts → session-state-YHFzOGDf.d.ts} +16 -16
- package/dist/{session-state-C4m0j6CJ.js → session-state-aIqe9CLa.js} +30 -39
- package/dist/session-state-aIqe9CLa.js.map +1 -0
- package/dist/{session-store-ofm8FFxs.d.ts → session-store-Cpi_NwTR.d.ts} +3 -3
- package/dist/{sink-checkpoint-store-BQVbI9DQ.d.ts → sink-checkpoint-store-M7qIxoSH.d.ts} +2 -2
- package/dist/{sink-registry-DH6uiEgP.js → sink-registry-NDgeyzO0.js} +4 -4
- package/dist/{sink-registry-DH6uiEgP.js.map → sink-registry-NDgeyzO0.js.map} +1 -1
- package/dist/{sink-registry-PRYbj6dp.d.ts → sink-registry-T1wOUuzq.d.ts} +9 -9
- package/dist/testkit/layers.d.ts +17 -14
- package/dist/testkit/layers.js +10 -8
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-ClHdr_G5.d.ts → tool-registry-BJaVNtw4.d.ts} +3 -3
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +4 -3
- package/dist/types/events.js +3 -2
- package/dist/types/events.js.map +1 -1
- package/dist/websocket.d.ts +83 -4
- package/dist/websocket.js +82 -12
- package/dist/websocket.js.map +1 -1
- package/package.json +10 -1
- package/dist/durable-DsV9PxZC.js.map +0 -1
- package/dist/reduced-state-TMi7ISla.js.map +0 -1
- package/dist/services/compaction.js.map +0 -1
- package/dist/session-state-C4m0j6CJ.js.map +0 -1
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { _ as UsagePayload, c as FailurePayload, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText } from "./envelope-DkZyMIgp.js";
|
|
2
|
+
import { n as TokenConsumptionState } from "./model-usage-CdBEkTwU.js";
|
|
1
3
|
import { _ as SummaryId, i as ContextVersion, l as InferenceId, m as SequenceNumber, n as CommandId, p as RunId, r as CompactionId, u as MessageId, v as ToolCallId, y as TurnId } from "./core-CYT6DBaS.js";
|
|
2
4
|
import { r as EDACommand, u as UserMessageContent } from "./commands-Ce1ec6kH.js";
|
|
3
5
|
import { n as EDARunTrace, t as EDAEventTrace } from "./tracing-BXHAkxkx.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { t as CommittedDurableEvent } from "./session-store-ofm8FFxs.js";
|
|
6
|
+
import { r as AssistantMessageContent, rt as RecoveryContinuation } from "./durable-br2C1bWK.js";
|
|
7
|
+
import { t as CommittedDurableEvent } from "./session-store-Cpi_NwTR.js";
|
|
7
8
|
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
8
9
|
|
|
9
10
|
//#region src/domain/reduced-state.d.ts
|
|
@@ -55,6 +56,7 @@ interface LifecycleTiming {
|
|
|
55
56
|
}
|
|
56
57
|
/** Durable run lifecycle projection tying one run to its owning command ids. */
|
|
57
58
|
interface RunRecord extends LifecycleTiming {
|
|
59
|
+
readonly modelSelection?: ModelSelectionPayload;
|
|
58
60
|
readonly runId: RunId;
|
|
59
61
|
readonly commandIds: ReadonlyArray<CommandId>;
|
|
60
62
|
readonly startedSeq: SequenceNumber;
|
|
@@ -244,18 +246,6 @@ interface StopRequestRecord {
|
|
|
244
246
|
readonly appliedTurnId?: TurnId;
|
|
245
247
|
readonly appliedInferenceId?: InferenceId;
|
|
246
248
|
}
|
|
247
|
-
/** Rolling session totals for provider-reported model token usage. */
|
|
248
|
-
interface TokenUsageTotals {
|
|
249
|
-
readonly inputTokens: number;
|
|
250
|
-
readonly cachedInputTokens: number;
|
|
251
|
-
readonly outputTokens: number;
|
|
252
|
-
readonly textTokens: number;
|
|
253
|
-
readonly reasoningTokens: number;
|
|
254
|
-
}
|
|
255
|
-
/** First-party token consumption metadata folded by the framework reducer. */
|
|
256
|
-
interface TokenConsumptionState {
|
|
257
|
-
readonly total: TokenUsageTotals;
|
|
258
|
-
}
|
|
259
249
|
/** Admitted command that has not yet crossed the `CommandStarted` boundary. */
|
|
260
250
|
interface PendingCommand {
|
|
261
251
|
/** Lifecycle ID for the admitted command. */
|
|
@@ -280,6 +270,8 @@ type ActiveTurnIdentity = {
|
|
|
280
270
|
};
|
|
281
271
|
/** Canonical durable replay product used by queries, recovery, and scheduling. */
|
|
282
272
|
interface ReducedState {
|
|
273
|
+
/** Session execution policy established by configuration or the first historical run. */
|
|
274
|
+
readonly modelSelection?: ModelSelectionPayload;
|
|
283
275
|
readonly lastSeq: SequenceNumber;
|
|
284
276
|
readonly commands: ReadonlyMap<CommandId, CommandRecord>;
|
|
285
277
|
readonly runs: ReadonlyMap<RunId, RunRecord>;
|
|
@@ -317,7 +309,7 @@ declare const initialReducedState: ReducedState;
|
|
|
317
309
|
/** Reserved reducer checkpoint name for the framework-owned `ReducedState`. */
|
|
318
310
|
declare const frameworkReducedStateReducerName = "_eda.framework.reduced-state";
|
|
319
311
|
/** Schema version for the framework-owned `ReducedState` checkpoint payload. */
|
|
320
|
-
declare const frameworkReducedStateReducerSchemaVersion =
|
|
312
|
+
declare const frameworkReducedStateReducerSchemaVersion = 6;
|
|
321
313
|
/** JSON payload stored for the framework-owned reduced-state reducer checkpoint. */
|
|
322
314
|
type ReducedStateCheckpointCommandRecord = Omit<CommandRecord, "command">;
|
|
323
315
|
type SystemMessageRecord = Extract<MessageRecord, {
|
|
@@ -355,6 +347,7 @@ interface ReducedStateCheckpointToolCallRecord extends Omit<ToolCallRecord, "dec
|
|
|
355
347
|
readonly terminal?: ReducedStateCheckpointToolTerminal;
|
|
356
348
|
}
|
|
357
349
|
interface ReducedStateCheckpointPayload {
|
|
350
|
+
readonly modelSelection?: ModelSelectionPayload;
|
|
358
351
|
readonly lastSeq: SequenceNumber;
|
|
359
352
|
readonly commands: ReadonlyArray<readonly [CommandId, ReducedStateCheckpointCommandRecord]>;
|
|
360
353
|
readonly runs: ReadonlyArray<readonly [RunId, RunRecord]>;
|
|
@@ -465,5 +458,5 @@ declare const emptyCommandQueues: CommandQueues;
|
|
|
465
458
|
*/
|
|
466
459
|
declare const deriveCommandQueues: (state: CommandQueueSource) => CommandQueues;
|
|
467
460
|
//#endregion
|
|
468
|
-
export { RunTerminal as A,
|
|
469
|
-
//# sourceMappingURL=command-queues-
|
|
461
|
+
export { RunTerminal as A, decodeReducedStateCheckpoint as B, ReducedStateCheckpointCommandRecord as C, ReducedStateCheckpointToolDecision as D, ReducedStateCheckpointToolCallRecord as E, TurnRecord as F, initialReducedState as G, foldReducedState as H, TurnTerminal as I, reduceCommittedEvents as J, pendingCommands as K, activeCommand as L, ToolCallRecord as M, ToolDecision as N, ReducedStateCheckpointToolTerminal as O, ToolTerminal as P, activeTurnIdentityForCommand as R, ReducedState as S, ReducedStateCheckpointPayload as T, frameworkReducedStateReducerName as U, encodeReducedStateCheckpoint as V, frameworkReducedStateReducerSchemaVersion as W, reducedStateCheckpointEventSeqs as Y, LifecycleTiming as _, deriveCommandQueues as a, RecoverableWork as b, ActiveTurnIdentity as c, CompactionRecord as d, CompactionTerminal as f, LifecycleFailure as g, InferenceTerminal as h, PendingUserMessage as i, StopRequestRecord as j, RunRecord as k, CommandRecord as l, InferenceRecord as m, CommandQueues as n, emptyCommandQueues as o, ContextRecord as p, pendingStopCommand as q, PendingSteeringMessage as r, ActiveCommandEvidence as s, CommandQueueSource as t, CommandTerminal as u, MessageRecord as v, ReducedStateCheckpointMessageRecord as w, RecoveryContinuationRecord as x, PendingCommand as y, classifyRecoverableWork as z };
|
|
462
|
+
//# sourceMappingURL=command-queues-DdDB_aYM.d.ts.map
|
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import { i as ContextProjection, n as CompactionPolicyId, t as CompactionExecutorId } from "./context-projection-
|
|
2
|
-
import { o as EDASessionStoreError, r as DurableAppendEntry, t as CommittedDurableEvent } from "./session-store-
|
|
3
|
-
import { S as ReducedState } from "./command-queues-
|
|
1
|
+
import { i as ContextProjection, n as CompactionPolicyId, t as CompactionExecutorId } from "./context-projection-n6Rdup0N.js";
|
|
2
|
+
import { o as EDASessionStoreError, r as DurableAppendEntry, t as CommittedDurableEvent } from "./session-store-Cpi_NwTR.js";
|
|
3
|
+
import { S as ReducedState } from "./command-queues-DdDB_aYM.js";
|
|
4
|
+
import { t as ModelResolver } from "./model-resolver-BPPJAsuh.js";
|
|
4
5
|
import { t as IdGenerator } from "./id-generator-Ckl8_XWW.js";
|
|
5
|
-
import { t as EventFactory } from "./event-factory-
|
|
6
|
+
import { t as EventFactory } from "./event-factory-pFzsPlDs.js";
|
|
6
7
|
import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
|
|
7
8
|
import * as Context from "effect/Context";
|
|
8
9
|
import * as Effect from "effect/Effect";
|
|
9
10
|
import * as Layer from "effect/Layer";
|
|
10
|
-
import * as Schema from "effect/Schema";
|
|
11
11
|
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
12
13
|
|
|
13
14
|
//#region src/services/compaction.d.ts
|
|
14
15
|
/** Candidate durable range and retained cursor selected by compaction policy. */
|
|
@@ -79,14 +80,32 @@ declare const CompactionOutput: Schema.Struct<{
|
|
|
79
80
|
readonly options: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json>>>>;
|
|
80
81
|
}>;
|
|
81
82
|
readonly executorId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "CompactionExecutorId">>;
|
|
83
|
+
readonly usage: Schema.optionalKey<Schema.Struct<{
|
|
84
|
+
readonly inputTokens: Schema.optionalKey<Schema.Int>;
|
|
85
|
+
readonly cachedInputTokens: Schema.optionalKey<Schema.Int>;
|
|
86
|
+
readonly cacheWriteInputTokens: Schema.optionalKey<Schema.Int>;
|
|
87
|
+
readonly outputTokens: Schema.optionalKey<Schema.Int>;
|
|
88
|
+
readonly textTokens: Schema.optionalKey<Schema.Int>;
|
|
89
|
+
readonly reasoningTokens: Schema.optionalKey<Schema.Int>;
|
|
90
|
+
}>>;
|
|
82
91
|
}>;
|
|
83
92
|
type CompactionOutput = typeof CompactionOutput.Type;
|
|
84
93
|
/** Executor input with framework-minted lifecycle identities. */
|
|
85
94
|
interface CompactionExecutorInput extends CompactionPolicyInput {
|
|
86
95
|
readonly plan: CompactionPlan;
|
|
96
|
+
/** Provider service resolved from the same durable selection used for accounting. */
|
|
97
|
+
readonly model: LanguageModel.Service;
|
|
87
98
|
}
|
|
88
99
|
declare const CompactionError_base: Schema.Class<CompactionError, Schema.TaggedStruct<"CompactionError", {
|
|
89
100
|
readonly message: Schema.String;
|
|
101
|
+
readonly usage: Schema.optionalKey<Schema.Struct<{
|
|
102
|
+
readonly inputTokens: Schema.optionalKey<Schema.Int>;
|
|
103
|
+
readonly cachedInputTokens: Schema.optionalKey<Schema.Int>;
|
|
104
|
+
readonly cacheWriteInputTokens: Schema.optionalKey<Schema.Int>;
|
|
105
|
+
readonly outputTokens: Schema.optionalKey<Schema.Int>;
|
|
106
|
+
readonly textTokens: Schema.optionalKey<Schema.Int>;
|
|
107
|
+
readonly reasoningTokens: Schema.optionalKey<Schema.Int>;
|
|
108
|
+
}>>;
|
|
90
109
|
}>, import("effect/Cause").YieldableError>;
|
|
91
110
|
/** Typed failure from policy planning or summary generation. */
|
|
92
111
|
declare class CompactionError extends CompactionError_base {}
|
|
@@ -123,7 +142,7 @@ declare class CompactionExecutor extends CompactionExecutor_base {
|
|
|
123
142
|
/** Test/app hook for replacing summary generation. */
|
|
124
143
|
static readonly FromFunction: (id: string, execute: CompactionExecutorShape["execute"]) => Layer.Layer<CompactionExecutor>;
|
|
125
144
|
/** Summary executor backed by the configured Effect AI LanguageModel. */
|
|
126
|
-
static readonly LanguageModelSummary: (options?: LanguageModelSummaryCompactionExecutorOptions) => Layer.Layer<CompactionExecutor
|
|
145
|
+
static readonly LanguageModelSummary: (options?: LanguageModelSummaryCompactionExecutorOptions) => Layer.Layer<CompactionExecutor>;
|
|
127
146
|
}
|
|
128
147
|
/** Inputs needed by the framework-owned compaction lifecycle runner. */
|
|
129
148
|
interface CompactionRunnerInput {
|
|
@@ -139,8 +158,8 @@ interface CompactionRunnerShape {
|
|
|
139
158
|
declare const CompactionRunner_base: Context.ServiceClass<CompactionRunner, "@effect-durable-agent/CompactionRunner", CompactionRunnerShape>;
|
|
140
159
|
/** Framework-owned compaction lifecycle runner. */
|
|
141
160
|
declare class CompactionRunner extends CompactionRunner_base {
|
|
142
|
-
static readonly Live: Layer.Layer<CompactionRunner, never, CompactionExecutor | CompactionPolicy | EDAKeepAlive |
|
|
161
|
+
static readonly Live: Layer.Layer<CompactionRunner, never, CompactionExecutor | CompactionPolicy | EDAKeepAlive | ModelResolver | EventFactory | IdGenerator>;
|
|
143
162
|
}
|
|
144
163
|
//#endregion
|
|
145
164
|
export { defaultCompactionRetainTailTokens as _, CompactionExecutorShape as a, CompactionPolicy as c, CompactionRunner as d, CompactionRunnerInput as f, defaultCompactionMinSummarizableTokens as g, defaultCompactionCharsPerToken as h, CompactionExecutorInput as i, CompactionPolicyInput as l, LanguageModelSummaryCompactionExecutorOptions as m, CompactionError as n, CompactionOutput as o, CompactionRunnerShape as p, CompactionExecutor as r, CompactionPlan as s, ApproximateTokenThresholdCompactionPolicyOptions as t, CompactionPolicyShape as u, defaultCompactionThresholdTokens as v };
|
|
146
|
-
//# sourceMappingURL=compaction-
|
|
165
|
+
//# sourceMappingURL=compaction-BEor3jKv.d.ts.map
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import { ModelResolver } from "./services/model-resolver.js";
|
|
2
|
+
import { ContextVersion, SequenceNumber } from "./types/core.js";
|
|
3
|
+
import { g as UsagePayload, s as FailurePayload } from "./envelope-DxQzo5rN.js";
|
|
4
|
+
import { CompactionExecutorId, CompactionPolicyId, CompactionSummaryArtifact } from "./domain/context-projection.js";
|
|
5
|
+
import { durableMessageTranscript } from "./domain/message-transcript.js";
|
|
6
|
+
import { IdGenerator } from "./services/id-generator.js";
|
|
7
|
+
import { t as EventFactory } from "./event-factory-DTFdy0Cb.js";
|
|
8
|
+
import { annotateEdaSpan, committedBatchAttributes } from "./services/tracing.js";
|
|
9
|
+
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
10
|
+
import * as Context from "effect/Context";
|
|
11
|
+
import * as Effect from "effect/Effect";
|
|
12
|
+
import * as Layer from "effect/Layer";
|
|
13
|
+
import * as Schema from "effect/Schema";
|
|
14
|
+
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
15
|
+
//#region src/services/provider-usage.ts
|
|
16
|
+
/** Normalizes provider usage for both conversation and compaction calls. */
|
|
17
|
+
const makeUsagePayload = (usage) => {
|
|
18
|
+
const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);
|
|
19
|
+
const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);
|
|
20
|
+
const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);
|
|
21
|
+
const inputTokens = nonNegativeInt(usage.inputTokens.total) ?? sumDefined([
|
|
22
|
+
uncachedInputTokens,
|
|
23
|
+
cachedInputTokens,
|
|
24
|
+
cacheWriteInputTokens
|
|
25
|
+
]);
|
|
26
|
+
const textTokens = nonNegativeInt(usage.outputTokens.text);
|
|
27
|
+
const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);
|
|
28
|
+
const outputTokens = nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);
|
|
29
|
+
return UsagePayload.make({
|
|
30
|
+
...inputTokens === void 0 ? {} : { inputTokens },
|
|
31
|
+
...cachedInputTokens === void 0 ? {} : { cachedInputTokens },
|
|
32
|
+
...cacheWriteInputTokens === void 0 ? {} : { cacheWriteInputTokens },
|
|
33
|
+
...outputTokens === void 0 ? {} : { outputTokens },
|
|
34
|
+
...textTokens === void 0 ? {} : { textTokens },
|
|
35
|
+
...reasoningTokens === void 0 ? {} : { reasoningTokens }
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
const sumDefined = (values) => {
|
|
39
|
+
const present = values.filter((value) => value !== void 0);
|
|
40
|
+
return present.length === 0 ? void 0 : present.reduce((sum, value) => sum + value, 0);
|
|
41
|
+
};
|
|
42
|
+
const nonNegativeInt = (value) => value === void 0 || !Number.isFinite(value) ? void 0 : Math.max(0, Math.trunc(value));
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/services/compaction.ts
|
|
45
|
+
/** Candidate durable range and retained cursor selected by compaction policy. */
|
|
46
|
+
const CompactionPlan = Schema.Struct({
|
|
47
|
+
policyId: CompactionPolicyId,
|
|
48
|
+
sourceFromSeq: SequenceNumber,
|
|
49
|
+
sourceToSeq: SequenceNumber,
|
|
50
|
+
retainedFromContextSeq: SequenceNumber
|
|
51
|
+
});
|
|
52
|
+
/** Rough token heuristic used by the built-in compaction presets. */
|
|
53
|
+
const defaultCompactionCharsPerToken = 4;
|
|
54
|
+
/** Production-oriented context threshold for the built-in approximate-token policy. */
|
|
55
|
+
const defaultCompactionThresholdTokens = 22e4;
|
|
56
|
+
/** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */
|
|
57
|
+
const defaultCompactionRetainTailTokens = 4e4;
|
|
58
|
+
/** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */
|
|
59
|
+
const defaultCompactionMinSummarizableTokens = 1e4;
|
|
60
|
+
/** Result produced by the summary executor before the framework commits it. */
|
|
61
|
+
const CompactionOutput = Schema.Struct({
|
|
62
|
+
text: Schema.NonEmptyString,
|
|
63
|
+
promptMessage: Prompt.UserMessage,
|
|
64
|
+
executorId: Schema.optionalKey(CompactionExecutorId),
|
|
65
|
+
usage: Schema.optionalKey(UsagePayload)
|
|
66
|
+
});
|
|
67
|
+
/** Typed failure from policy planning or summary generation. */
|
|
68
|
+
var CompactionError = class extends Schema.TaggedErrorClass()("CompactionError", {
|
|
69
|
+
message: Schema.String,
|
|
70
|
+
usage: Schema.optionalKey(UsagePayload)
|
|
71
|
+
}) {};
|
|
72
|
+
/** Decides whether a safe prompt-context rebase should be attempted. */
|
|
73
|
+
var CompactionPolicy = class CompactionPolicy extends Context.Service()("@effect-durable-agent/CompactionPolicy") {
|
|
74
|
+
/** Default policy: compaction is disabled and commits no skip events. */
|
|
75
|
+
static Disabled = Layer.succeed(CompactionPolicy, {
|
|
76
|
+
id: CompactionPolicyId.make("disabled"),
|
|
77
|
+
plan: () => Effect.succeed(void 0)
|
|
78
|
+
});
|
|
79
|
+
/** Test/app hook for replacing the policy with a concrete planner. */
|
|
80
|
+
static FromFunction = (id, plan) => Layer.succeed(CompactionPolicy, {
|
|
81
|
+
id: CompactionPolicyId.make(id),
|
|
82
|
+
plan
|
|
83
|
+
});
|
|
84
|
+
/**
|
|
85
|
+
* Common production policy: compact when approximate prompt context exceeds a token threshold.
|
|
86
|
+
*
|
|
87
|
+
* The policy keeps a recent tail verbatim, summarizes the older prefix, and advances from the
|
|
88
|
+
* current summary cursor so repeated compactions behave like the first one.
|
|
89
|
+
*/
|
|
90
|
+
static ApproximateTokenThreshold = (options = {}) => {
|
|
91
|
+
const normalized = normalizeApproximateTokenPolicyOptions(options);
|
|
92
|
+
return Layer.succeed(CompactionPolicy, {
|
|
93
|
+
id: normalized.policyId,
|
|
94
|
+
plan: ({ state, context }) => Effect.sync(() => planApproximateTokenCompaction(state, context, normalized))
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
/** Produces a cumulative summary artifact for a selected compaction plan. */
|
|
99
|
+
var CompactionExecutor = class CompactionExecutor extends Context.Service()("@effect-durable-agent/CompactionExecutor") {
|
|
100
|
+
/** Placeholder executor for the disabled default policy. It should never be called. */
|
|
101
|
+
static Disabled = Layer.succeed(CompactionExecutor, {
|
|
102
|
+
id: CompactionExecutorId.make("disabled"),
|
|
103
|
+
execute: () => Effect.die(/* @__PURE__ */ new Error("CompactionExecutor.Disabled was called"))
|
|
104
|
+
});
|
|
105
|
+
/** Test/app hook for replacing summary generation. */
|
|
106
|
+
static FromFunction = (id, execute) => Layer.succeed(CompactionExecutor, {
|
|
107
|
+
id: CompactionExecutorId.make(id),
|
|
108
|
+
execute
|
|
109
|
+
});
|
|
110
|
+
/** Summary executor backed by the configured Effect AI LanguageModel. */
|
|
111
|
+
static LanguageModelSummary = (options = {}) => Layer.effect(CompactionExecutor, Effect.sync(() => {
|
|
112
|
+
const executorId = CompactionExecutorId.make(options.executorId ?? "language-model-summary");
|
|
113
|
+
const summaryMessagePrefix = options.summaryMessagePrefix ?? "Conversation summary:";
|
|
114
|
+
return {
|
|
115
|
+
id: executorId,
|
|
116
|
+
execute: Effect.fn("agent.compaction")(function* (input) {
|
|
117
|
+
yield* annotateEdaSpan({
|
|
118
|
+
"eda.compaction.policy_id": input.plan.policyId,
|
|
119
|
+
"eda.compaction.source_from_seq": input.plan.sourceFromSeq,
|
|
120
|
+
"eda.compaction.source_to_seq": input.plan.sourceToSeq,
|
|
121
|
+
"eda.compaction.retained_from_context_seq": input.plan.retainedFromContextSeq,
|
|
122
|
+
"eda.compaction.executor_id": executorId
|
|
123
|
+
});
|
|
124
|
+
const promptText = buildSummaryPrompt(input);
|
|
125
|
+
if (promptText === void 0) return yield* new CompactionError({ message: "compaction plan selected no source messages" });
|
|
126
|
+
const response = yield* input.model.generateText({
|
|
127
|
+
prompt: Prompt.fromMessages([Prompt.makeMessage("system", { content: summarizationSystemPrompt }), Prompt.makeMessage("user", { content: [Prompt.textPart({ text: promptText })] })]),
|
|
128
|
+
toolChoice: "none"
|
|
129
|
+
}).pipe(Effect.mapError((error) => new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` })));
|
|
130
|
+
const text = response.text.trim();
|
|
131
|
+
if (text.length === 0) return yield* new CompactionError({
|
|
132
|
+
message: "summary model returned no text",
|
|
133
|
+
usage: makeUsagePayload(response.usage)
|
|
134
|
+
});
|
|
135
|
+
return CompactionOutput.make({
|
|
136
|
+
usage: makeUsagePayload(response.usage),
|
|
137
|
+
text,
|
|
138
|
+
promptMessage: Prompt.makeMessage("user", { content: [Prompt.textPart({ text: `${summaryMessagePrefix}\n\n${text}` })] }),
|
|
139
|
+
executorId
|
|
140
|
+
});
|
|
141
|
+
})
|
|
142
|
+
};
|
|
143
|
+
}));
|
|
144
|
+
};
|
|
145
|
+
/** Framework-owned compaction lifecycle runner. */
|
|
146
|
+
var CompactionRunner = class CompactionRunner extends Context.Service()("@effect-durable-agent/CompactionRunner") {
|
|
147
|
+
static Live = Layer.effect(CompactionRunner, Effect.suspend(() => makeLiveCompactionRunner));
|
|
148
|
+
};
|
|
149
|
+
const makeLiveCompactionRunner = Effect.gen(function* () {
|
|
150
|
+
const ids = yield* IdGenerator;
|
|
151
|
+
const events = yield* EventFactory;
|
|
152
|
+
const policy = yield* CompactionPolicy;
|
|
153
|
+
const executor = yield* CompactionExecutor;
|
|
154
|
+
const keepAlive = yield* EDAKeepAlive;
|
|
155
|
+
const models = yield* ModelResolver;
|
|
156
|
+
return { maybeCompact: Effect.fnUntraced(function* (input) {
|
|
157
|
+
const plan = yield* policy.plan({
|
|
158
|
+
state: input.state,
|
|
159
|
+
context: input.context
|
|
160
|
+
}).pipe(Effect.catchTag("CompactionError", (error) => Effect.logError("compaction policy failed", { error }).pipe(Effect.as(void 0))));
|
|
161
|
+
if (plan === void 0) {
|
|
162
|
+
yield* annotateEdaSpan({ "eda.compaction.selected": false });
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
yield* annotateEdaSpan({
|
|
166
|
+
"eda.compaction.selected": true,
|
|
167
|
+
"eda.compaction.policy_id": plan.policyId,
|
|
168
|
+
"eda.compaction.source_from_seq": plan.sourceFromSeq,
|
|
169
|
+
"eda.compaction.source_to_seq": plan.sourceToSeq,
|
|
170
|
+
"eda.compaction.retained_from_context_seq": plan.retainedFromContextSeq
|
|
171
|
+
});
|
|
172
|
+
const invalidPlan = validatePlan(plan, input.state, input.context);
|
|
173
|
+
if (invalidPlan !== void 0) {
|
|
174
|
+
yield* Effect.logError("compaction policy returned invalid plan", { reason: invalidPlan });
|
|
175
|
+
return [];
|
|
176
|
+
}
|
|
177
|
+
const compactionId = yield* ids.makeCompactionId();
|
|
178
|
+
const summaryId = yield* ids.makeSummaryId();
|
|
179
|
+
yield* annotateEdaSpan({
|
|
180
|
+
"eda.compaction.id": compactionId,
|
|
181
|
+
"eda.summary.id": summaryId
|
|
182
|
+
});
|
|
183
|
+
const requested = yield* events.compactionRequested({
|
|
184
|
+
compactionId,
|
|
185
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
186
|
+
sourceToSeq: plan.sourceToSeq
|
|
187
|
+
});
|
|
188
|
+
const started = yield* events.compactionStarted({ compactionId });
|
|
189
|
+
const startedEvents = yield* input.appendDurableEntries([{ event: requested }, { event: started }]);
|
|
190
|
+
const model = yield* models.resolve(input.state.modelSelection);
|
|
191
|
+
const output = yield* keepAlive.withActiveWork(`compaction:${compactionId}`, executor.execute({
|
|
192
|
+
plan,
|
|
193
|
+
state: input.state,
|
|
194
|
+
context: input.context,
|
|
195
|
+
model
|
|
196
|
+
})).pipe(Effect.catchTag("CompactionError", (error) => Effect.gen(function* () {
|
|
197
|
+
const failed = yield* events.compactionFailed({
|
|
198
|
+
compactionId,
|
|
199
|
+
...input.state.modelSelection === void 0 ? {} : { modelSelection: input.state.modelSelection },
|
|
200
|
+
...error.usage === void 0 ? {} : { usage: error.usage },
|
|
201
|
+
error: FailurePayload.make({ message: error.message })
|
|
202
|
+
});
|
|
203
|
+
return {
|
|
204
|
+
_tag: "Failed",
|
|
205
|
+
committed: yield* input.appendDurableEntries([{ event: failed }])
|
|
206
|
+
};
|
|
207
|
+
})), Effect.map((result) => "_tag" in result ? result : {
|
|
208
|
+
_tag: "Output",
|
|
209
|
+
output: result
|
|
210
|
+
}));
|
|
211
|
+
if (output._tag === "Failed") return [...startedEvents, ...output.committed];
|
|
212
|
+
const artifact = CompactionSummaryArtifact.make({
|
|
213
|
+
compactionId,
|
|
214
|
+
summaryId,
|
|
215
|
+
...input.context.currentSummary === void 0 ? {} : { previousSummaryId: input.context.currentSummary.summaryId },
|
|
216
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
217
|
+
sourceToSeq: plan.sourceToSeq,
|
|
218
|
+
retainedFromContextSeq: plan.retainedFromContextSeq,
|
|
219
|
+
text: output.output.text,
|
|
220
|
+
promptMessage: output.output.promptMessage,
|
|
221
|
+
policyId: plan.policyId,
|
|
222
|
+
...output.output.executorId === void 0 ? {} : { executorId: output.output.executorId }
|
|
223
|
+
});
|
|
224
|
+
const summaryCreated = yield* events.summaryCreated({
|
|
225
|
+
compactionId,
|
|
226
|
+
summaryId,
|
|
227
|
+
sourceFromSeq: plan.sourceFromSeq,
|
|
228
|
+
sourceToSeq: plan.sourceToSeq,
|
|
229
|
+
summary: artifact
|
|
230
|
+
});
|
|
231
|
+
const contextRebased = yield* events.contextRebased({
|
|
232
|
+
compactionId,
|
|
233
|
+
summaryId,
|
|
234
|
+
contextVersion: ContextVersion.make(input.context.contextVersion + 1),
|
|
235
|
+
retainedFromContextSeq: plan.retainedFromContextSeq
|
|
236
|
+
});
|
|
237
|
+
const completed = yield* events.compactionCompleted({
|
|
238
|
+
compactionId,
|
|
239
|
+
...input.state.modelSelection === void 0 ? {} : { modelSelection: input.state.modelSelection },
|
|
240
|
+
...output.output.usage === void 0 ? {} : { usage: output.output.usage }
|
|
241
|
+
});
|
|
242
|
+
const committed = yield* input.appendDurableEntries([
|
|
243
|
+
{ event: summaryCreated },
|
|
244
|
+
{ event: contextRebased },
|
|
245
|
+
{ event: completed }
|
|
246
|
+
]);
|
|
247
|
+
yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));
|
|
248
|
+
return [...startedEvents, ...committed];
|
|
249
|
+
}) };
|
|
250
|
+
});
|
|
251
|
+
const validatePlan = (plan, state, context) => {
|
|
252
|
+
const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
|
|
253
|
+
if (plan.retainedFromContextSeq <= currentRetainedFromSeq) return "retainedFromContextSeq must advance beyond the current summary cursor";
|
|
254
|
+
if (plan.sourceToSeq > state.lastSeq) return "sourceToSeq must not exceed the current durable head";
|
|
255
|
+
if (plan.retainedFromContextSeq > state.lastSeq + 1) return "retainedFromContextSeq must not skip unsummarized future context";
|
|
256
|
+
if (plan.sourceFromSeq > plan.sourceToSeq) return "sourceFromSeq must be less than or equal to sourceToSeq";
|
|
257
|
+
if (plan.retainedFromContextSeq <= plan.sourceToSeq) return "retainedFromContextSeq must start after the summarized source range";
|
|
258
|
+
};
|
|
259
|
+
const normalizeApproximateTokenPolicyOptions = (options) => ({
|
|
260
|
+
policyId: CompactionPolicyId.make(options.policyId ?? "approximate-token-threshold"),
|
|
261
|
+
thresholdTokens: positiveNumber(options.thresholdTokens ?? 22e4, "thresholdTokens"),
|
|
262
|
+
retainTailTokens: nonNegativeNumber(options.retainTailTokens ?? 4e4, "retainTailTokens"),
|
|
263
|
+
minSummarizableTokens: nonNegativeNumber(options.minSummarizableTokens ?? 1e4, "minSummarizableTokens"),
|
|
264
|
+
charsPerToken: positiveNumber(options.charsPerToken ?? 4, "charsPerToken")
|
|
265
|
+
});
|
|
266
|
+
const positiveNumber = (value, name) => {
|
|
267
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive finite number`);
|
|
268
|
+
return value;
|
|
269
|
+
};
|
|
270
|
+
const nonNegativeNumber = (value, name) => {
|
|
271
|
+
if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative finite number`);
|
|
272
|
+
return value;
|
|
273
|
+
};
|
|
274
|
+
/** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */
|
|
275
|
+
const planApproximateTokenCompaction = (state, context, options) => {
|
|
276
|
+
const messages = estimatedContextMessages(state);
|
|
277
|
+
if (estimateCurrentPromptChars(state, context, messages) <= options.thresholdTokens * options.charsPerToken) return;
|
|
278
|
+
const currentRetainedFromSeq = context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);
|
|
279
|
+
const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);
|
|
280
|
+
if (retainedFromSeq <= currentRetainedFromSeq) return;
|
|
281
|
+
const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);
|
|
282
|
+
if (sourceMessages.length === 0) return;
|
|
283
|
+
if (charsToTokens(sourceMessages.reduce((sum, message) => sum + message.chars, 0), options.charsPerToken) < options.minSummarizableTokens) return;
|
|
284
|
+
const sourceFromSeq = currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0].seq;
|
|
285
|
+
const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);
|
|
286
|
+
if (sourceFromSeq > sourceToSeq) return;
|
|
287
|
+
return CompactionPlan.make({
|
|
288
|
+
policyId: options.policyId,
|
|
289
|
+
sourceFromSeq,
|
|
290
|
+
sourceToSeq,
|
|
291
|
+
retainedFromContextSeq: retainedFromSeq
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
const selectRetainedFromSeq = (messages, lastSeq, options) => {
|
|
295
|
+
if (options.retainTailTokens === 0) return SequenceNumber.make(lastSeq + 1);
|
|
296
|
+
const retainTailChars = options.retainTailTokens * options.charsPerToken;
|
|
297
|
+
let tailChars = 0;
|
|
298
|
+
let retainedIndex = messages.length;
|
|
299
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
300
|
+
tailChars += messages[index].chars;
|
|
301
|
+
retainedIndex = index;
|
|
302
|
+
if (tailChars >= retainTailChars) break;
|
|
303
|
+
}
|
|
304
|
+
return retainedIndex >= messages.length ? SequenceNumber.make(lastSeq + 1) : messages[retainedIndex].seq;
|
|
305
|
+
};
|
|
306
|
+
const estimateCurrentPromptChars = (state, context, messages) => {
|
|
307
|
+
const systemChars = Array.from(state.messages.values()).reduce((sum, message) => message._tag === "System" ? sum + message.content.length : sum, 0);
|
|
308
|
+
const summaryChars = context.currentSummary === void 0 ? 0 : estimatePromptMessageChars(context.currentSummary.promptMessage);
|
|
309
|
+
const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);
|
|
310
|
+
return systemChars + summaryChars + messageChars;
|
|
311
|
+
};
|
|
312
|
+
const estimatedContextMessages = (state) => durableMessageTranscript(state).map((message) => ({
|
|
313
|
+
message,
|
|
314
|
+
seq: messageSeq(message),
|
|
315
|
+
chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state)
|
|
316
|
+
}));
|
|
317
|
+
const estimateDurableMessageChars = (message) => {
|
|
318
|
+
switch (message._tag) {
|
|
319
|
+
case "User":
|
|
320
|
+
case "Steering": return estimateUserContentChars(message.content);
|
|
321
|
+
case "Assistant":
|
|
322
|
+
case "AssistantPartial": return estimateAssistantPromptChars(message.promptParts, message.content);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
const estimateAssociatedToolChars = (message, state) => {
|
|
326
|
+
if (message._tag !== "Assistant" && message._tag !== "AssistantPartial") return 0;
|
|
327
|
+
return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
328
|
+
};
|
|
329
|
+
const messageSeq = (message) => message._tag === "Steering" ? message.consumedSeq : message.seq;
|
|
330
|
+
const charsToTokens = (chars, charsPerToken) => Math.ceil(chars / charsPerToken);
|
|
331
|
+
const buildSummaryPrompt = (input) => {
|
|
332
|
+
const sourceText = serializeCompactionSource(input);
|
|
333
|
+
if (sourceText.trim().length === 0) return;
|
|
334
|
+
return `${input.context.currentSummary === void 0 ? "" : `<previous-summary>\n${input.context.currentSummary.text}\n</previous-summary>\n\n`}<conversation>\n${sourceText}\n</conversation>\n\n${summaryPromptText}`;
|
|
335
|
+
};
|
|
336
|
+
const serializeCompactionSource = (input) => {
|
|
337
|
+
const lines = [];
|
|
338
|
+
for (const message of durableMessageTranscript(input.state)) {
|
|
339
|
+
const seq = messageSeq(message);
|
|
340
|
+
if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) continue;
|
|
341
|
+
lines.push(serializeDurableMessage(message));
|
|
342
|
+
if (message._tag === "Assistant" || message._tag === "AssistantPartial") for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) lines.push(serializeToolResultPart(part));
|
|
343
|
+
}
|
|
344
|
+
return lines.filter((line) => line.trim().length > 0).join("\n\n");
|
|
345
|
+
};
|
|
346
|
+
const serializeDurableMessage = (message) => {
|
|
347
|
+
switch (message._tag) {
|
|
348
|
+
case "User": return `[User]: ${userContentText(message.content)}`;
|
|
349
|
+
case "Steering": return `[User steering]: ${userContentText(message.content)}`;
|
|
350
|
+
case "Assistant":
|
|
351
|
+
case "AssistantPartial": return serializeAssistantMessage(message.promptParts, message.content);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
const serializeAssistantMessage = (promptParts, content) => {
|
|
355
|
+
const parts = promptParts ?? assistantContentToPromptParts(content);
|
|
356
|
+
const text = [];
|
|
357
|
+
const reasoning = [];
|
|
358
|
+
const toolCalls = [];
|
|
359
|
+
const sideband = [];
|
|
360
|
+
for (const part of parts) switch (part.type) {
|
|
361
|
+
case "text":
|
|
362
|
+
text.push(part.text);
|
|
363
|
+
break;
|
|
364
|
+
case "reasoning":
|
|
365
|
+
reasoning.push(part.text);
|
|
366
|
+
break;
|
|
367
|
+
case "tool-call":
|
|
368
|
+
toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);
|
|
369
|
+
break;
|
|
370
|
+
case "file":
|
|
371
|
+
sideband.push(`file(${part.fileName ?? "unnamed"}, ${part.mediaType})`);
|
|
372
|
+
break;
|
|
373
|
+
case "tool-result":
|
|
374
|
+
sideband.push(`tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`);
|
|
375
|
+
break;
|
|
376
|
+
case "tool-approval-request":
|
|
377
|
+
sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
return [
|
|
381
|
+
reasoning.length === 0 ? "" : `[Assistant reasoning]: ${reasoning.join("\n")}`,
|
|
382
|
+
text.length === 0 ? "" : `[Assistant]: ${text.join("\n")}`,
|
|
383
|
+
toolCalls.length === 0 ? "" : `[Assistant tool calls]: ${toolCalls.join("; ")}`,
|
|
384
|
+
sideband.length === 0 ? "" : `[Assistant context]: ${sideband.join("; ")}`
|
|
385
|
+
].filter((line) => line.length > 0).join("\n");
|
|
386
|
+
};
|
|
387
|
+
const serializeToolResultPart = (part) => `[Tool result ${part.name}${part.isFailure ? " failed" : ""}]: ${truncateForSummary(safeJsonStringify(part.result))}`;
|
|
388
|
+
const toolPromptPartsForInference = (inferenceId, toolCalls) => Array.from(toolCalls.values()).flatMap((tool) => {
|
|
389
|
+
const { decision } = tool;
|
|
390
|
+
if (decision === void 0 || decision.inferenceId !== inferenceId) return [];
|
|
391
|
+
if (decision._tag === "Rejected") return decision.promptPart === void 0 ? [] : [decision.promptPart];
|
|
392
|
+
const terminal = tool.terminal;
|
|
393
|
+
if (terminal === void 0 || terminal.promptPart === void 0) return [];
|
|
394
|
+
return [terminal.promptPart];
|
|
395
|
+
});
|
|
396
|
+
const assistantContentToPromptParts = (content) => [...content.reasoning === void 0 ? [] : [Prompt.reasoningPart({ text: content.reasoning })], ...content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]];
|
|
397
|
+
const estimateAssistantPromptChars = (promptParts, content) => (promptParts ?? assistantContentToPromptParts(content)).reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
398
|
+
const estimateUserContentChars = (content) => typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
399
|
+
const estimatePromptMessageChars = (message) => {
|
|
400
|
+
if (!("content" in message)) return 0;
|
|
401
|
+
const { content } = message;
|
|
402
|
+
return typeof content === "string" ? content.length : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);
|
|
403
|
+
};
|
|
404
|
+
const estimatePromptPartChars = (part) => {
|
|
405
|
+
switch (part.type) {
|
|
406
|
+
case "text": return part.text.length;
|
|
407
|
+
case "reasoning": return part.text.length;
|
|
408
|
+
case "file": return part.mediaType.length + (part.fileName?.length ?? 0) + (typeof part.data === "string" ? part.data.length : part.data instanceof URL ? part.data.toString().length : estimatedBinaryFileChars);
|
|
409
|
+
case "tool-call": return part.name.length + safeJsonStringify(part.params).length;
|
|
410
|
+
case "tool-result": return part.name.length + safeJsonStringify(part.result).length;
|
|
411
|
+
case "tool-approval-response": return part.approvalId.length + (part.reason?.length ?? 0) + 8;
|
|
412
|
+
case "tool-approval-request": return part.approvalId.length + part.toolCallId.length;
|
|
413
|
+
default: return safeJsonStringify(part).length;
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
const userContentText = (content) => typeof content === "string" ? content : content.map((part) => {
|
|
417
|
+
switch (part.type) {
|
|
418
|
+
case "text": return part.text;
|
|
419
|
+
case "file": return `[file ${part.fileName ?? "unnamed"} ${part.mediaType}]`;
|
|
420
|
+
}
|
|
421
|
+
}).join("\n");
|
|
422
|
+
const safeJsonStringify = (value) => {
|
|
423
|
+
try {
|
|
424
|
+
return JSON.stringify(value) ?? String(value);
|
|
425
|
+
} catch {
|
|
426
|
+
return String(value);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
const truncateForSummary = (text, maxChars = 2e3) => {
|
|
430
|
+
if (text.length <= maxChars) return text;
|
|
431
|
+
return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} more characters truncated]`;
|
|
432
|
+
};
|
|
433
|
+
const formatUnknownError = (error) => error instanceof Error ? error.message : String(error);
|
|
434
|
+
const estimatedBinaryFileChars = 4800;
|
|
435
|
+
const summarizationSystemPrompt = "You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.";
|
|
436
|
+
const summaryPromptText = `The messages above are conversation history selected for compaction. Create a cumulative context checkpoint summary that another LLM will use to continue the work.
|
|
437
|
+
|
|
438
|
+
Use this exact structure:
|
|
439
|
+
|
|
440
|
+
## Goal
|
|
441
|
+
[What the user is trying to accomplish]
|
|
442
|
+
|
|
443
|
+
## Constraints & Preferences
|
|
444
|
+
- [Requirements, constraints, and preferences]
|
|
445
|
+
|
|
446
|
+
## Progress
|
|
447
|
+
### Done
|
|
448
|
+
- [x] [Completed work]
|
|
449
|
+
|
|
450
|
+
### In Progress
|
|
451
|
+
- [ ] [Current unfinished work]
|
|
452
|
+
|
|
453
|
+
### Blocked
|
|
454
|
+
- [Current blockers, or "(none)"]
|
|
455
|
+
|
|
456
|
+
## Key Decisions
|
|
457
|
+
- **[Decision]**: [Rationale]
|
|
458
|
+
|
|
459
|
+
## Next Steps
|
|
460
|
+
1. [Concrete next step]
|
|
461
|
+
|
|
462
|
+
## Critical Context
|
|
463
|
+
- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]
|
|
464
|
+
|
|
465
|
+
Rules:
|
|
466
|
+
- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.
|
|
467
|
+
- Keep the summary concise but sufficient to replace the compacted history.
|
|
468
|
+
- Preserve exact file paths, tool names, identifiers, and error messages.
|
|
469
|
+
- Do not answer questions from the conversation.`;
|
|
470
|
+
//#endregion
|
|
471
|
+
export { CompactionPolicy as a, defaultCompactionMinSummarizableTokens as c, makeUsagePayload as d, CompactionPlan as i, defaultCompactionRetainTailTokens as l, CompactionExecutor as n, CompactionRunner as o, CompactionOutput as r, defaultCompactionCharsPerToken as s, CompactionError as t, defaultCompactionThresholdTokens as u };
|
|
472
|
+
|
|
473
|
+
//# sourceMappingURL=compaction-BgDr5VJy.js.map
|