effect-durable-agent 0.1.0-alpha.19 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compaction-Bell28K8.js → compaction-GD1cTPTZ.js} +4 -4
- package/dist/compaction-GD1cTPTZ.js.map +1 -0
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.js +1 -1
- package/dist/domain/context-projection.js.map +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/message-transcript.js +1 -1
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/reduced-state-schema.d.ts +1 -1
- package/dist/domain/reduced-state-schema.js +2 -2
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/reduced-state.js +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/{durable-DRY7AcsF.js → durable-CD__3ztN.js} +67 -4
- package/dist/durable-CD__3ztN.js.map +1 -0
- package/dist/{durable-DoG_e4iL.d.ts → durable-CKdCCqhw.d.ts} +54 -1
- package/dist/{event-factory-CKuWhjS4.js → event-factory-VAci3NJb.js} +2 -2
- package/dist/{event-factory-CKuWhjS4.js.map → event-factory-VAci3NJb.js.map} +1 -1
- package/dist/{events-sxIzJY26.d.ts → events-BWuvzVml.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{model-resolver-BHYVHsam.d.ts → model-resolver-BfM5YA6A.d.ts} +4 -4
- package/dist/{reduced-state-DrSHn_47.d.ts → reduced-state-4FSWDdgT.d.ts} +654 -453
- package/dist/{reduced-state-DFIYylAq.js → reduced-state-Vuud6LCM.js} +2 -2
- package/dist/reduced-state-Vuud6LCM.js.map +1 -0
- package/dist/{reduced-state-schema-CPEmuHLY.d.ts → reduced-state-schema-jyZWJ0QS.d.ts} +19 -1
- package/dist/{reducer-registry-C3ZidOI1.d.ts → reducer-registry-BIhncOHH.d.ts} +4 -4
- package/dist/{run-scheduling-wakeup-COUj3r_B.d.ts → run-scheduling-wakeup-BH2pHE0U.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/id-generator.js +1 -1
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/model-resolver.js +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/prompt-projector.js +1 -1
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/run-scheduler.js +1 -1
- package/dist/services/run-scheduler.js.map +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +12 -9
- package/dist/services/runtime-layer.js +6 -6
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +2 -2
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +5 -5
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tool-registry.js +2 -2
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +1 -1
- package/dist/services/tracing.js +1 -1
- package/dist/{session-event-observer-BDwja1jX.d.ts → session-event-observer-BdZltdrK.d.ts} +2 -2
- package/dist/{session-state-BBzzJrDC.js → session-state-BAzdzqV4.js} +17 -12
- package/dist/session-state-BAzdzqV4.js.map +1 -0
- package/dist/{session-store-B_vh581h.d.ts → session-store-BpitF4Wg.d.ts} +3 -3
- package/dist/{sink-checkpoint-store-2SxoNMbI.d.ts → sink-checkpoint-store-C-SY0cG2.d.ts} +2 -2
- package/dist/{sink-registry-ogHu2Sw7.js → sink-registry-BnWfMABI.js} +4 -4
- package/dist/sink-registry-BnWfMABI.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -10
- package/dist/testkit/layers.js +9 -6
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-DDxbmMpY.d.ts → tool-registry-wPsHagF_.d.ts} +5 -5
- package/dist/types/commands.js +1 -1
- package/dist/types/commands.js.map +1 -1
- package/dist/types/events/durable.d.ts +1 -1
- package/dist/types/events/durable.js +1 -1
- package/dist/types/events.d.ts +2 -2
- package/dist/types/events.js +1 -1
- package/dist/websocket.d.ts +9 -2
- package/dist/websocket.js +1 -1
- package/package.json +8 -8
- package/dist/compaction-Bell28K8.js.map +0 -1
- package/dist/durable-DRY7AcsF.js.map +0 -1
- package/dist/reduced-state-DFIYylAq.js.map +0 -1
- package/dist/session-state-BBzzJrDC.js.map +0 -1
- package/dist/sink-registry-ogHu2Sw7.js.map +0 -1
|
@@ -4,14 +4,14 @@ import { _ as UsagePayload, s as FailurePayload } from "./envelope-BCzKUq_z.js";
|
|
|
4
4
|
import { CompactionExecutorId, CompactionPolicyId, CompactionSummaryArtifact } from "./domain/context-projection.js";
|
|
5
5
|
import { durableMessageTranscript } from "./domain/message-transcript.js";
|
|
6
6
|
import { IdGenerator } from "./services/id-generator.js";
|
|
7
|
-
import { t as EventFactory } from "./event-factory-
|
|
7
|
+
import { t as EventFactory } from "./event-factory-VAci3NJb.js";
|
|
8
8
|
import { annotateEdaSpan, committedBatchAttributes } from "./services/tracing.js";
|
|
9
9
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
10
10
|
import * as Context from "effect/Context";
|
|
11
11
|
import * as Effect from "effect/Effect";
|
|
12
12
|
import * as Layer from "effect/Layer";
|
|
13
13
|
import * as Schema from "effect/Schema";
|
|
14
|
-
import * as Prompt from "effect/
|
|
14
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
15
15
|
//#region src/services/provider-usage.ts
|
|
16
16
|
/** Normalizes provider usage for both conversation and compaction calls. */
|
|
17
17
|
const makeUsagePayload = (usage) => {
|
|
@@ -65,7 +65,7 @@ const CompactionOutput = Schema.Struct({
|
|
|
65
65
|
usage: Schema.optionalKey(UsagePayload)
|
|
66
66
|
});
|
|
67
67
|
/** Typed failure from policy planning or summary generation. */
|
|
68
|
-
var CompactionError = class extends Schema.
|
|
68
|
+
var CompactionError = class extends Schema.TaggedError()("CompactionError", {
|
|
69
69
|
message: Schema.String,
|
|
70
70
|
usage: Schema.optionalKey(UsagePayload)
|
|
71
71
|
}) {};
|
|
@@ -468,4 +468,4 @@ Rules:
|
|
|
468
468
|
//#endregion
|
|
469
469
|
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 };
|
|
470
470
|
|
|
471
|
-
//# sourceMappingURL=compaction-
|
|
471
|
+
//# sourceMappingURL=compaction-GD1cTPTZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compaction-GD1cTPTZ.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 { makeUsagePayload } from \"./provider-usage\";\n\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport {\n durableMessageTranscript,\n type DurableTranscriptMessage,\n} from \"../domain/message-transcript\";\nimport {\n CompactionExecutorId,\n CompactionPolicyId,\n CompactionSummaryArtifact,\n} from \"../domain/context-projection\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport { InferenceId, ContextVersion, SequenceNumber } from \"../types/core\";\nimport { FailurePayload, UsagePayload, type AssistantMessageContent } from \"../types/events\";\nimport { CommittedDurableEvent, DurableAppendEntry, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\n\n/** Candidate durable range and retained cursor selected by compaction policy. */\nexport const CompactionPlan = Schema.Struct({\n policyId: CompactionPolicyId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n retainedFromContextSeq: SequenceNumber,\n});\nexport type CompactionPlan = typeof CompactionPlan.Type;\n\n/** Rough token heuristic used by the built-in compaction presets. */\nexport const defaultCompactionCharsPerToken = 4;\n\n/** Production-oriented context threshold for the built-in approximate-token policy. */\nexport const defaultCompactionThresholdTokens = 220_000;\n\n/** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */\nexport const defaultCompactionRetainTailTokens = 40_000;\n\n/** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */\nexport const defaultCompactionMinSummarizableTokens = 10_000;\n\n/** Approximate-token policy options for common production compaction. */\nexport interface ApproximateTokenThresholdCompactionPolicyOptions {\n /** Stable policy id stored on summary artifacts. */\n readonly policyId?: string;\n /** Context-size threshold that triggers compaction. Defaults to 220k tokens. */\n readonly thresholdTokens?: number;\n /** Recent tail retained verbatim after compaction. Defaults to 40k tokens. */\n readonly retainTailTokens?: number;\n /** Smallest prefix worth summarizing. Defaults to 10k tokens. */\n readonly minSummarizableTokens?: number;\n /** Character-to-token divisor for the approximate estimator. Defaults to 4. */\n readonly charsPerToken?: number;\n}\n\n/** LanguageModel-backed summary executor options. */\nexport interface LanguageModelSummaryCompactionExecutorOptions {\n /** Stable executor id stored on summary artifacts. */\n readonly executorId?: string;\n /** Prefix used for the synthetic prompt message inserted into future context. */\n readonly summaryMessagePrefix?: string;\n}\n\n/** Input visible to policy decisions. */\nexport interface CompactionPolicyInput {\n readonly state: ReducedState;\n readonly context: ContextProjection;\n}\n\n/** Result produced by the summary executor before the framework commits it. */\nexport const CompactionOutput = Schema.Struct({\n text: Schema.NonEmptyString,\n promptMessage: Prompt.UserMessage,\n executorId: Schema.optionalKey(CompactionExecutorId),\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type CompactionOutput = typeof CompactionOutput.Type;\n\n/** Executor input with framework-minted lifecycle identities. */\nexport interface CompactionExecutorInput extends CompactionPolicyInput {\n readonly plan: CompactionPlan;\n /** Provider service resolved from the same durable selection used for accounting. */\n readonly model: LanguageModel.LanguageModel;\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/** Inputs needed by the framework-owned compaction lifecycle runner. */\nexport interface CompactionRunnerInput {\n readonly state: ReducedState;\n readonly context: ContextProjection;\n readonly appendDurableEntries: (\n entries: ReadonlyArray<DurableAppendEntry>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Runtime service that executes framework-owned compaction lifecycles. */\nexport interface CompactionRunnerShape {\n /** Evaluate policy and run one compaction if a plan is selected. */\n readonly maybeCompact: (\n input: CompactionRunnerInput,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Framework-owned compaction lifecycle runner. */\nexport class CompactionRunner extends Context.Service<CompactionRunner, CompactionRunnerShape>()(\n \"@effect-durable-agent/CompactionRunner\",\n) {\n static readonly Live = Layer.effect(\n CompactionRunner,\n Effect.suspend(() => makeLiveCompactionRunner),\n );\n}\n\ninterface NormalizedApproximateTokenPolicyOptions {\n readonly policyId: CompactionPolicyId;\n readonly thresholdTokens: number;\n readonly retainTailTokens: number;\n readonly minSummarizableTokens: number;\n readonly charsPerToken: number;\n}\n\ninterface EstimatedContextMessage {\n readonly chars: number;\n readonly message: DurableTranscriptMessage;\n readonly seq: SequenceNumber;\n}\n\nconst makeLiveCompactionRunner = Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const events = yield* EventFactory;\n const policy = yield* CompactionPolicy;\n const executor = yield* CompactionExecutor;\n const keepAlive = yield* EDAKeepAlive;\n const models = yield* ModelResolver;\n\n const maybeCompact = Effect.fnUntraced(function* (input: CompactionRunnerInput) {\n const plan = yield* policy\n .plan({ state: input.state, context: input.context })\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.logError(\"compaction policy failed\", { error }).pipe(Effect.as(undefined)),\n ),\n );\n if (plan === undefined) {\n yield* annotateEdaSpan({ \"eda.compaction.selected\": false });\n return [];\n }\n yield* annotateEdaSpan({\n \"eda.compaction.selected\": true,\n \"eda.compaction.policy_id\": plan.policyId,\n \"eda.compaction.source_from_seq\": plan.sourceFromSeq,\n \"eda.compaction.source_to_seq\": plan.sourceToSeq,\n \"eda.compaction.retained_from_context_seq\": plan.retainedFromContextSeq,\n });\n const invalidPlan = validatePlan(plan, input.state, input.context);\n if (invalidPlan !== undefined) {\n yield* Effect.logError(\"compaction policy returned invalid plan\", { reason: invalidPlan });\n return [];\n }\n\n const compactionId = yield* ids.makeCompactionId();\n const summaryId = yield* ids.makeSummaryId();\n yield* annotateEdaSpan({\n \"eda.compaction.id\": compactionId,\n \"eda.summary.id\": summaryId,\n });\n const requested = yield* events.compactionRequested({\n compactionId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n });\n const started = yield* events.compactionStarted({ compactionId });\n const startedEvents = yield* input.appendDurableEntries([\n { event: requested },\n { event: started },\n ]);\n\n const model = yield* models.resolve(input.state.modelSelection);\n const output = yield* keepAlive\n .withActiveWork(\n `compaction:${compactionId}`,\n executor.execute({ plan, state: input.state, context: input.context, model }),\n )\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.gen(function* () {\n const failed = yield* events.compactionFailed({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(error.usage === undefined ? {} : { usage: error.usage }),\n error: FailurePayload.make({ message: error.message }),\n });\n const committed = yield* input.appendDurableEntries([{ event: failed }]);\n return { _tag: \"Failed\" as const, committed };\n }),\n ),\n Effect.map((result) =>\n \"_tag\" in result ? result : { _tag: \"Output\" as const, output: result },\n ),\n );\n\n if (output._tag === \"Failed\") {\n return [...startedEvents, ...output.committed];\n }\n\n const artifact = CompactionSummaryArtifact.make({\n compactionId,\n summaryId,\n ...(input.context.currentSummary === undefined\n ? {}\n : { previousSummaryId: input.context.currentSummary.summaryId }),\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n retainedFromContextSeq: plan.retainedFromContextSeq,\n text: output.output.text,\n promptMessage: output.output.promptMessage,\n policyId: plan.policyId,\n ...(output.output.executorId === undefined ? {} : { executorId: output.output.executorId }),\n });\n const summaryCreated = yield* events.summaryCreated({\n compactionId,\n summaryId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n summary: artifact,\n });\n const contextRebased = yield* events.contextRebased({\n compactionId,\n summaryId,\n contextVersion: ContextVersion.make(input.context.contextVersion + 1),\n retainedFromContextSeq: plan.retainedFromContextSeq,\n });\n const completed = yield* events.compactionCompleted({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(output.output.usage === undefined ? {} : { usage: output.output.usage }),\n });\n const committed = yield* input.appendDurableEntries([\n { event: summaryCreated },\n { event: contextRebased },\n { event: completed },\n ]);\n yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));\n return [...startedEvents, ...committed];\n });\n\n return { maybeCompact } satisfies CompactionRunnerShape;\n});\n\nconst validatePlan = (\n plan: CompactionPlan,\n state: ReducedState,\n context: ContextProjection,\n): string | undefined => {\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n if (plan.retainedFromContextSeq <= currentRetainedFromSeq) {\n return \"retainedFromContextSeq must advance beyond the current summary cursor\";\n }\n if (plan.sourceToSeq > state.lastSeq) {\n return \"sourceToSeq must not exceed the current durable head\";\n }\n if (plan.retainedFromContextSeq > state.lastSeq + 1) {\n return \"retainedFromContextSeq must not skip unsummarized future context\";\n }\n if (plan.sourceFromSeq > plan.sourceToSeq) {\n return \"sourceFromSeq must be less than or equal to sourceToSeq\";\n }\n if (plan.retainedFromContextSeq <= plan.sourceToSeq) {\n return \"retainedFromContextSeq must start after the summarized source range\";\n }\n return undefined;\n};\n\nconst normalizeApproximateTokenPolicyOptions = (\n options: ApproximateTokenThresholdCompactionPolicyOptions,\n): NormalizedApproximateTokenPolicyOptions => ({\n policyId: CompactionPolicyId.make(options.policyId ?? \"approximate-token-threshold\"),\n thresholdTokens: positiveNumber(\n options.thresholdTokens ?? defaultCompactionThresholdTokens,\n \"thresholdTokens\",\n ),\n retainTailTokens: nonNegativeNumber(\n options.retainTailTokens ?? defaultCompactionRetainTailTokens,\n \"retainTailTokens\",\n ),\n minSummarizableTokens: nonNegativeNumber(\n options.minSummarizableTokens ?? defaultCompactionMinSummarizableTokens,\n \"minSummarizableTokens\",\n ),\n charsPerToken: positiveNumber(\n options.charsPerToken ?? defaultCompactionCharsPerToken,\n \"charsPerToken\",\n ),\n});\n\nconst positiveNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`${name} must be a positive finite number`);\n }\n return value;\n};\n\nconst nonNegativeNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a non-negative finite number`);\n }\n return value;\n};\n\n/** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */\nconst planApproximateTokenCompaction = (\n state: ReducedState,\n context: ContextProjection,\n options: NormalizedApproximateTokenPolicyOptions,\n): CompactionPlan | undefined => {\n const messages = estimatedContextMessages(state);\n const totalChars = estimateCurrentPromptChars(state, context, messages);\n if (totalChars <= options.thresholdTokens * options.charsPerToken) {\n return undefined;\n }\n\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n const retainedFromSeq = selectRetainedFromSeq(messages, state.lastSeq, options);\n if (retainedFromSeq <= currentRetainedFromSeq) {\n return undefined;\n }\n\n const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);\n if (sourceMessages.length === 0) {\n return undefined;\n }\n\n const summarizableTokens = charsToTokens(\n sourceMessages.reduce((sum, message) => sum + message.chars, 0),\n options.charsPerToken,\n );\n if (summarizableTokens < options.minSummarizableTokens) {\n return undefined;\n }\n\n const sourceFromSeq =\n currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0]!.seq;\n const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);\n if (sourceFromSeq > sourceToSeq) {\n return undefined;\n }\n\n return CompactionPlan.make({\n policyId: options.policyId,\n sourceFromSeq,\n sourceToSeq,\n retainedFromContextSeq: retainedFromSeq,\n });\n};\n\nconst selectRetainedFromSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n lastSeq: SequenceNumber,\n options: NormalizedApproximateTokenPolicyOptions,\n): SequenceNumber => {\n if (options.retainTailTokens === 0) {\n return SequenceNumber.make(lastSeq + 1);\n }\n\n const retainTailChars = options.retainTailTokens * options.charsPerToken;\n let tailChars = 0;\n let retainedIndex = messages.length;\n for (let index = messages.length - 1; index >= 0; index--) {\n tailChars += messages[index]!.chars;\n retainedIndex = index;\n if (tailChars >= retainTailChars) {\n break;\n }\n }\n return retainedIndex >= messages.length\n ? SequenceNumber.make(lastSeq + 1)\n : messages[retainedIndex]!.seq;\n};\n\nconst estimateCurrentPromptChars = (\n state: ReducedState,\n context: ContextProjection,\n messages: ReadonlyArray<EstimatedContextMessage>,\n): number => {\n const systemChars = Array.from(state.messages.values()).reduce(\n (sum, message) => (message._tag === \"System\" ? sum + message.content.length : sum),\n 0,\n );\n const summaryChars =\n context.currentSummary === undefined\n ? 0\n : estimatePromptMessageChars(context.currentSummary.promptMessage);\n const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);\n return systemChars + summaryChars + messageChars;\n};\n\nconst estimatedContextMessages = (state: ReducedState): ReadonlyArray<EstimatedContextMessage> =>\n durableMessageTranscript(state).map((message) => ({\n message,\n seq: messageSeq(message),\n chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state),\n }));\n\nconst estimateDurableMessageChars = (message: DurableTranscriptMessage): number => {\n switch (message._tag) {\n case \"User\":\n case \"Steering\":\n return estimateUserContentChars(message.content);\n case \"Assistant\":\n case \"AssistantPartial\":\n return estimateAssistantPromptChars(message.promptParts, message.content);\n }\n};\n\nconst estimateAssociatedToolChars = (\n message: DurableTranscriptMessage,\n state: ReducedState,\n): number => {\n if (message._tag !== \"Assistant\" && message._tag !== \"AssistantPartial\") {\n return 0;\n }\n return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n};\n\nconst messageSeq = (message: DurableTranscriptMessage): SequenceNumber =>\n message._tag === \"Steering\" ? message.consumedSeq : message.seq;\n\nconst charsToTokens = (chars: number, charsPerToken: number): number =>\n Math.ceil(chars / charsPerToken);\n\nconst buildSummaryPrompt = (input: CompactionExecutorInput): string | undefined => {\n const sourceText = serializeCompactionSource(input);\n if (sourceText.trim().length === 0) {\n return undefined;\n }\n\n const previousSummary =\n input.context.currentSummary === undefined\n ? \"\"\n : `<previous-summary>\\n${input.context.currentSummary.text}\\n</previous-summary>\\n\\n`;\n return `${previousSummary}<conversation>\\n${sourceText}\\n</conversation>\\n\\n${summaryPromptText}`;\n};\n\nconst serializeCompactionSource = (input: CompactionExecutorInput): string => {\n const lines: Array<string> = [];\n for (const message of durableMessageTranscript(input.state)) {\n const seq = messageSeq(message);\n if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) {\n continue;\n }\n lines.push(serializeDurableMessage(message));\n if (message._tag === \"Assistant\" || message._tag === \"AssistantPartial\") {\n for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) {\n lines.push(serializeToolResultPart(part));\n }\n }\n }\n return lines.filter((line) => line.trim().length > 0).join(\"\\n\\n\");\n};\n\nconst serializeDurableMessage = (message: DurableTranscriptMessage): string => {\n switch (message._tag) {\n case \"User\":\n return `[User]: ${userContentText(message.content)}`;\n case \"Steering\":\n return `[User steering]: ${userContentText(message.content)}`;\n case \"Assistant\":\n case \"AssistantPartial\":\n return serializeAssistantMessage(message.promptParts, message.content);\n }\n};\n\nconst serializeAssistantMessage = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): string => {\n const parts = promptParts ?? assistantContentToPromptParts(content);\n const text: Array<string> = [];\n const reasoning: Array<string> = [];\n const toolCalls: Array<string> = [];\n const sideband: Array<string> = [];\n for (const part of parts) {\n switch (part.type) {\n case \"text\":\n text.push(part.text);\n break;\n case \"reasoning\":\n reasoning.push(part.text);\n break;\n case \"tool-call\":\n toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);\n break;\n case \"file\":\n sideband.push(`file(${part.fileName ?? \"unnamed\"}, ${part.mediaType})`);\n break;\n case \"tool-result\":\n sideband.push(\n `tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`,\n );\n break;\n case \"tool-approval-request\":\n sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);\n break;\n }\n }\n return [\n reasoning.length === 0 ? \"\" : `[Assistant reasoning]: ${reasoning.join(\"\\n\")}`,\n text.length === 0 ? \"\" : `[Assistant]: ${text.join(\"\\n\")}`,\n toolCalls.length === 0 ? \"\" : `[Assistant tool calls]: ${toolCalls.join(\"; \")}`,\n sideband.length === 0 ? \"\" : `[Assistant context]: ${sideband.join(\"; \")}`,\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\");\n};\n\nconst serializeToolResultPart = (part: Prompt.ToolResultPart): string =>\n `[Tool result ${part.name}${part.isFailure ? \" failed\" : \"\"}]: ${truncateForSummary(\n safeJsonStringify(part.result),\n )}`;\n\nconst toolPromptPartsForInference = (\n inferenceId: InferenceId,\n toolCalls: ReducedState[\"toolCalls\"],\n): ReadonlyArray<Prompt.ToolResultPart> =>\n Array.from(toolCalls.values()).flatMap((tool): ReadonlyArray<Prompt.ToolResultPart> => {\n const { decision } = tool;\n if (decision === undefined || decision.inferenceId !== inferenceId) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined ? [] : [decision.promptPart];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [terminal.promptPart];\n });\n\nconst assistantContentToPromptParts = (\n content: AssistantMessageContent,\n): ReadonlyArray<Prompt.AssistantMessagePart> => [\n ...(content.reasoning === undefined ? [] : [Prompt.reasoningPart({ text: content.reasoning })]),\n ...(content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]),\n];\n\nconst estimateAssistantPromptChars = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): number =>\n (promptParts ?? assistantContentToPromptParts(content)).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n\nconst estimateUserContentChars = (\n content: string | ReadonlyArray<Prompt.UserMessagePart>,\n): number =>\n typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n\nconst estimatePromptMessageChars = (message: Prompt.Message): number => {\n if (!(\"content\" in message)) {\n return 0;\n }\n const { content } = message;\n return typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n};\n\ntype PromptContentPart =\n | Prompt.UserMessagePart\n | Prompt.AssistantMessagePart\n | Prompt.ToolMessagePart;\n\nconst estimatePromptPartChars = (part: PromptContentPart): number => {\n switch (part.type) {\n case \"text\":\n return part.text.length;\n case \"reasoning\":\n return part.text.length;\n case \"file\":\n return (\n part.mediaType.length +\n (part.fileName?.length ?? 0) +\n (typeof part.data === \"string\"\n ? part.data.length\n : part.data instanceof URL\n ? part.data.toString().length\n : estimatedBinaryFileChars)\n );\n case \"tool-call\":\n return part.name.length + safeJsonStringify(part.params).length;\n case \"tool-result\":\n return part.name.length + safeJsonStringify(part.result).length;\n case \"tool-approval-response\":\n return part.approvalId.length + (part.reason?.length ?? 0) + 8;\n case \"tool-approval-request\":\n return part.approvalId.length + part.toolCallId.length;\n default:\n return safeJsonStringify(part).length;\n }\n};\n\nconst userContentText = (content: string | ReadonlyArray<Prompt.UserMessagePart>): string =>\n typeof content === \"string\"\n ? content\n : content\n .map((part) => {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"file\":\n return `[file ${part.fileName ?? \"unnamed\"} ${part.mediaType}]`;\n }\n })\n .join(\"\\n\");\n\nconst safeJsonStringify = (value: unknown): string => {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst truncateForSummary = (text: string, maxChars = 2_000): string => {\n if (text.length <= maxChars) {\n return text;\n }\n return `${text.slice(0, maxChars)}\\n\\n[... ${text.length - maxChars} more characters truncated]`;\n};\n\nconst formatUnknownError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst estimatedBinaryFileChars = 4_800;\n\nconst summarizationSystemPrompt =\n \"You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.\";\n\nconst summaryPromptText = `The messages above are conversation history selected for compaction. Create a cumulative context checkpoint summary that another LLM will use to continue the work.\n\nUse this exact structure:\n\n## Goal\n[What the user is trying to accomplish]\n\n## Constraints & Preferences\n- [Requirements, constraints, and preferences]\n\n## Progress\n### Done\n- [x] [Completed work]\n\n### In Progress\n- [ ] [Current unfinished work]\n\n### Blocked\n- [Current blockers, or \"(none)\"]\n\n## Key Decisions\n- **[Decision]**: [Rationale]\n\n## Next Steps\n1. [Concrete next step]\n\n## Critical Context\n- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]\n\nRules:\n- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.\n- Keep the summary concise but sufficient to replace the compacted history.\n- Preserve exact file paths, tool names, identifiers, and error messages.\n- Do not answer questions from the conversation.`;\n"],"mappings":";;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoB,UAA0B;CACzD,MAAM,sBAAsB,eAAe,MAAM,YAAY,QAAQ;CACrE,MAAM,oBAAoB,eAAe,MAAM,YAAY,SAAS;CACpE,MAAM,wBAAwB,eAAe,MAAM,YAAY,UAAU;CACzE,MAAM,cACJ,eAAe,MAAM,YAAY,KAAK,KACtC,WAAW;EAAC;EAAqB;EAAmB;CAAqB,CAAC;CAC5E,MAAM,aAAa,eAAe,MAAM,aAAa,IAAI;CACzD,MAAM,kBAAkB,eAAe,MAAM,aAAa,SAAS;CACnE,MAAM,eACJ,eAAe,MAAM,aAAa,KAAK,KAAK,WAAW,CAAC,YAAY,eAAe,CAAC;CAEtF,OAAO,aAAa,KAAK;EACvB,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,sBAAsB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB;EAC/D,GAAI,0BAA0B,KAAA,IAAY,CAAC,IAAI,EAAE,sBAAsB;EACvE,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;EACrD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB;CAC7D,CAAC;AACH;AAEA,MAAM,cAAc,WAA8C;CAChE,MAAM,UAAU,OAAO,QAAQ,UAA2B,UAAU,KAAA,CAAS;CAC7E,OAAO,QAAQ,WAAW,IAAI,KAAA,IAAY,QAAQ,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC;AACzF;AAEA,MAAM,kBAAkB,UACtB,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;;;;AC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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,6 +1,6 @@
|
|
|
1
1
|
import { d as UserMessageContent } from "../commands-3OD-p8dD.js";
|
|
2
2
|
import { b as TurnId, h as SequenceNumber, p as RunId, u as MessageId } from "../core-BcimKMIv.js";
|
|
3
|
-
import { C as RunRecord, f as MessageRecord, p as PendingCommand, r as CommandRecord, t as ActiveCommandEvidence } from "../reduced-state-
|
|
3
|
+
import { C as RunRecord, f as MessageRecord, p as PendingCommand, r as CommandRecord, t as ActiveCommandEvidence } from "../reduced-state-4FSWDdgT.js";
|
|
4
4
|
//#region src/domain/command-queues.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* A steering message admitted for an active run but not necessarily consumed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CompactionId, ContextVersion, SequenceNumber, SummaryId } from "../types/core.js";
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
|
-
import * as Prompt from "effect/
|
|
3
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
4
4
|
//#region src/domain/context-projection.ts
|
|
5
5
|
/** Stable identifier for the compaction policy that selected a summary plan. */
|
|
6
6
|
const CompactionPolicyId = Schema.NonEmptyString.pipe(Schema.brand("CompactionPolicyId"));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-projection.js","names":[],"sources":["../../src/domain/context-projection.ts"],"sourcesContent":["import * as Prompt from \"effect/
|
|
1
|
+
{"version":3,"file":"context-projection.js","names":[],"sources":["../../src/domain/context-projection.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\n\nimport { CompactionId, ContextVersion, SequenceNumber, SummaryId } from \"../types/core\";\n\n/** Stable identifier for the compaction policy that selected a summary plan. */\nexport const CompactionPolicyId = Schema.NonEmptyString.pipe(Schema.brand(\"CompactionPolicyId\"));\nexport type CompactionPolicyId = typeof CompactionPolicyId.Type;\n\n/** Stable identifier for the executor that produced a summary artifact. */\nexport const CompactionExecutorId = Schema.NonEmptyString.pipe(\n Schema.brand(\"CompactionExecutorId\"),\n);\nexport type CompactionExecutorId = typeof CompactionExecutorId.Type;\n\n/** Authoritative cumulative model-context summary written with `SummaryCreated`. */\nexport const CompactionSummaryArtifact = Schema.Struct({\n compactionId: CompactionId,\n summaryId: SummaryId,\n previousSummaryId: Schema.optionalKey(SummaryId),\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n retainedFromContextSeq: SequenceNumber,\n text: Schema.NonEmptyString,\n promptMessage: Prompt.UserMessage,\n policyId: CompactionPolicyId,\n executorId: Schema.optionalKey(CompactionExecutorId),\n});\nexport type CompactionSummaryArtifact = typeof CompactionSummaryArtifact.Type;\n\n/** Current durable context cursor projected from framework reducer state and summary rows. */\nexport const ContextProjection = Schema.Struct({\n contextVersion: ContextVersion,\n currentSummary: Schema.optionalKey(CompactionSummaryArtifact),\n});\nexport type ContextProjection = typeof ContextProjection.Type;\n\n/** Genesis context before any compaction has rebased prompt history. */\nexport const emptyContextProjection = ContextProjection.make({\n contextVersion: ContextVersion.make(0),\n});\n"],"mappings":";;;;;AAMA,MAAa,qBAAqB,OAAO,eAAe,KAAK,OAAO,MAAM,oBAAoB,CAAC;;AAI/F,MAAa,uBAAuB,OAAO,eAAe,KACxD,OAAO,MAAM,sBAAsB,CACrC;;AAIA,MAAa,4BAA4B,OAAO,OAAO;CACrD,cAAc;CACd,WAAW;CACX,mBAAmB,OAAO,YAAY,SAAS;CAC/C,eAAe;CACf,aAAa;CACb,wBAAwB;CACxB,MAAM,OAAO;CACb,eAAe,OAAO;CACtB,UAAU;CACV,YAAY,OAAO,YAAY,oBAAoB;AACrD,CAAC;;AAID,MAAa,oBAAoB,OAAO,OAAO;CAC7C,gBAAgB;CAChB,gBAAgB,OAAO,YAAY,yBAAyB;AAC9D,CAAC;;AAID,MAAa,yBAAyB,kBAAkB,KAAK,EAC3D,gBAAgB,eAAe,KAAK,CAAC,EACvC,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { at as contextProjectionPromptWithUserContents, ct as durableTranscriptPromptWithUserContent, it as contextProjectionPromptWithUserContent, nt as DurableTranscriptMessage, ot as durableMessageTranscript, rt as contextProjectionPrompt, st as durableTranscriptPrompt } from "../reduced-state-
|
|
1
|
+
import { at as contextProjectionPromptWithUserContents, ct as durableTranscriptPromptWithUserContent, it as contextProjectionPromptWithUserContent, nt as DurableTranscriptMessage, ot as durableMessageTranscript, rt as contextProjectionPrompt, st as durableTranscriptPrompt } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
export { DurableTranscriptMessage, contextProjectionPrompt, contextProjectionPromptWithUserContent, contextProjectionPromptWithUserContents, durableMessageTranscript, durableTranscriptPrompt, durableTranscriptPromptWithUserContent };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as Prompt from "effect/
|
|
1
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
2
2
|
//#region src/domain/message-transcript.ts
|
|
3
3
|
/** Derive the durable user/assistant transcript in committed sequence order. */
|
|
4
4
|
const durableMessageTranscript = (state) => Array.from(state.messages.values()).filter(isDurableTranscriptMessage).sort(compareBySeq);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-transcript.js","names":[],"sources":["../../src/domain/message-transcript.ts"],"sourcesContent":["import * as Prompt from \"effect/unstable/ai/Prompt\";\n\nimport type { ContextProjection } from \"./context-projection\";\nimport type { MessageRecord, ReducedState, ToolCallRecord } from \"./reduced-state\";\nimport type { UserMessageContent } from \"../types/commands\";\n\n/** Durable user/assistant message records suitable for a session transcript. */\nexport type DurableTranscriptMessage =\n | Extract<MessageRecord, { readonly _tag: \"User\" | \"Assistant\" | \"AssistantPartial\" }>\n | (Extract<MessageRecord, { readonly _tag: \"Steering\" }> & {\n readonly consumedSeq: NonNullable<\n Extract<MessageRecord, { readonly _tag: \"Steering\" }>[\"consumedSeq\"]\n >;\n });\n\n/** Derive the durable user/assistant transcript in committed sequence order. */\nexport const durableMessageTranscript = (\n state: Pick<ReducedState, \"messages\">,\n): ReadonlyArray<DurableTranscriptMessage> =>\n Array.from(state.messages.values()).filter(isDurableTranscriptMessage).sort(compareBySeq);\n\nconst isDurableTranscriptMessage = (message: MessageRecord): message is DurableTranscriptMessage =>\n (message._tag === \"User\" && message.cancelledSeq === undefined) ||\n message._tag === \"Assistant\" ||\n message._tag === \"AssistantPartial\" ||\n (message._tag === \"Steering\" && message.consumedSeq !== undefined);\n\ntype SystemContextMessage = Extract<MessageRecord, { readonly _tag: \"System\" }>;\ntype PromptContextMessage = DurableTranscriptMessage | SystemContextMessage;\ntype PromptProjectionState = Pick<ReducedState, \"messages\"> &\n Partial<Pick<ReducedState, \"toolCalls\">>;\n\ntype AssistantPromptInfo = {\n readonly order: number;\n readonly toolCallOrderByProviderPartId: ReadonlyMap<string, number>;\n};\n\ntype PromptTranscriptItem =\n | {\n readonly _tag: \"Message\";\n readonly order: number;\n readonly message: PromptContextMessage;\n }\n | {\n readonly _tag: \"Summary\";\n readonly order: number;\n readonly message: Prompt.UserMessage;\n }\n | {\n readonly _tag: \"ToolResult\";\n readonly order: number;\n readonly part: Prompt.ToolResultPart;\n };\n\ntype ToolResultPromptTranscriptItem = Extract<\n PromptTranscriptItem,\n { readonly _tag: \"ToolResult\" }\n>;\n\n/** Convert all durable transcript messages and exact tool-result parts into provider prompt history. */\nexport const durableTranscriptPrompt = (state: PromptProjectionState): Prompt.Prompt =>\n contextProjectionPrompt(state, undefined);\n\n/** Convert the current compacted context into provider prompt history. */\nexport const contextProjectionPrompt = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n): Prompt.Prompt => {\n const messages = promptTranscriptItems(state, context).flatMap(\n (item): ReadonlyArray<Prompt.Message> => {\n switch (item._tag) {\n case \"Message\":\n return [transcriptMessageToPromptMessage(item.message)];\n case \"Summary\":\n return [item.message];\n case \"ToolResult\":\n return [Prompt.makeMessage(\"tool\", { content: [item.part] })];\n }\n },\n );\n validateToolCallPairing(messages);\n return Prompt.fromMessages(messages);\n};\n\n/** Build a provider prompt with extra user content selected by the scheduler but not yet folded. */\nexport const durableTranscriptPromptWithUserContent = (\n state: PromptProjectionState,\n content: UserMessageContent,\n): Prompt.Prompt => contextProjectionPromptWithUserContent(state, undefined, content);\n\n/** Build a compacted provider prompt with extra user content selected by the scheduler. */\nexport const contextProjectionPromptWithUserContent = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n content: UserMessageContent,\n): Prompt.Prompt =>\n Prompt.fromMessages([\n ...contextProjectionPrompt(state, context).content,\n Prompt.makeMessage(\"user\", { content }),\n ]);\n\n/** Build a compacted provider prompt with multiple scheduler-selected user messages. */\nexport const contextProjectionPromptWithUserContents = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n contents: ReadonlyArray<UserMessageContent>,\n): Prompt.Prompt =>\n Prompt.fromMessages([\n ...contextProjectionPrompt(state, context).content,\n ...contents.map((content) => Prompt.makeMessage(\"user\", { content })),\n ]);\n\nconst compareBySeq = (left: DurableTranscriptMessage, right: DurableTranscriptMessage): number =>\n messageTranscriptSeq(left) - messageTranscriptSeq(right) || left.seq - right.seq;\n\nconst promptTranscriptItems = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n): ReadonlyArray<PromptTranscriptItem> => {\n const messages = promptContextMessages(state, context);\n const assistantInfoByInference = new Map(\n messages.flatMap((message) =>\n message._tag === \"Assistant\" || message._tag === \"AssistantPartial\"\n ? [[message.inferenceId, assistantPromptInfo(message)] as const]\n : [],\n ),\n );\n const messageItems = messages.map((message) => ({\n _tag: \"Message\" as const,\n order: promptContextMessageSeq(message),\n message,\n }));\n const summaryItem =\n context?.currentSummary === undefined\n ? []\n : [\n {\n _tag: \"Summary\" as const,\n order: Number.MIN_SAFE_INTEGER,\n message: context.currentSummary.promptMessage,\n },\n ];\n const toolItems = Array.from(state.toolCalls?.values() ?? []).flatMap((tool) =>\n toolPromptItems(tool, assistantInfoByInference),\n );\n return [...messageItems, ...summaryItem, ...toolItems].sort(\n (left, right) => left.order - right.order,\n );\n};\n\nconst toolPromptItems = (\n tool: ToolCallRecord,\n assistantInfoByInference: ReadonlyMap<unknown, AssistantPromptInfo>,\n): ReadonlyArray<ToolResultPromptTranscriptItem> => {\n const { decision } = tool;\n if (decision === undefined) {\n return [];\n }\n const assistant = assistantInfoByInference.get(decision.inferenceId);\n if (assistant === undefined) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined\n ? []\n : [\n {\n _tag: \"ToolResult\",\n order: syntheticToolResultOrder(assistant, decision.providerPartId),\n part: decision.promptPart,\n },\n ];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [\n {\n _tag: \"ToolResult\",\n order: syntheticToolResultOrder(assistant, decision.providerPartId),\n part: terminal.promptPart,\n },\n ];\n};\n\nconst assistantPromptInfo = (\n message: Extract<PromptContextMessage, { readonly _tag: \"Assistant\" | \"AssistantPartial\" }>,\n): AssistantPromptInfo => ({\n order: messageTranscriptSeq(message),\n toolCallOrderByProviderPartId: new Map(\n assistantToolCallParts(message).map(({ part, index }) => [part.id, index] as const),\n ),\n});\n\nconst assistantToolCallParts = (\n message: Extract<PromptContextMessage, { readonly _tag: \"Assistant\" | \"AssistantPartial\" }>,\n): ReadonlyArray<{ readonly part: Prompt.ToolCallPart; readonly index: number }> =>\n (message.promptParts ?? []).flatMap((part, index) =>\n part.type === \"tool-call\" ? [{ part, index }] : [],\n );\n\nconst syntheticToolResultOrder = (assistant: AssistantPromptInfo, providerPartId: string): number =>\n assistant.order +\n 0.1 +\n (assistant.toolCallOrderByProviderPartId.get(providerPartId) ?? 0) * 0.001;\n\nconst validateToolCallPairing = (messages: ReadonlyArray<Prompt.Message>): void => {\n const pending = new Set<string>();\n for (const message of messages) {\n if (pending.size > 0 && message.role !== \"tool\") {\n throw new Error(unpairedToolCallMessage(pending));\n }\n if (message.role === \"tool\") {\n for (const part of message.content) {\n if (part.type === \"tool-result\") {\n pending.delete(part.id);\n }\n }\n continue;\n }\n if (message.role === \"assistant\") {\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) {\n pending.add(part.id);\n }\n }\n }\n }\n if (pending.size > 0) {\n throw new Error(unpairedToolCallMessage(pending));\n }\n};\n\nconst unpairedToolCallMessage = (pending: ReadonlySet<string>): string =>\n `Prompt transcript contains assistant tool-call(s) without matching tool result(s): ${Array.from(\n pending,\n ).join(\", \")}`;\n\nconst promptContextMessages = (\n state: Pick<ReducedState, \"messages\">,\n context: ContextProjection | undefined,\n): ReadonlyArray<PromptContextMessage> => {\n const retainedFromContextSeq = context?.currentSummary?.retainedFromContextSeq ?? 0;\n const messages = durableMessageTranscript(state).filter(\n (message) =>\n isConsumedForPrompt(message) && messageTranscriptSeq(message) >= retainedFromContextSeq,\n );\n const system = Array.from(state.messages.values()).find(\n (message): message is SystemContextMessage => message._tag === \"System\",\n );\n return system === undefined ? messages : [system, ...messages];\n};\n\nconst isConsumedForPrompt = (message: DurableTranscriptMessage): boolean =>\n message._tag !== \"User\" ||\n message.requestedDisposition === undefined ||\n message.consumedSeq !== undefined;\n\nconst transcriptMessageToPromptMessage = (\n message: PromptContextMessage,\n): Prompt.SystemMessage | Prompt.UserMessage | Prompt.AssistantMessage => {\n switch (message._tag) {\n case \"System\":\n return Prompt.makeMessage(\"system\", { content: message.content });\n case \"User\":\n case \"Steering\":\n return Prompt.makeMessage(\"user\", { content: message.content });\n case \"Assistant\":\n case \"AssistantPartial\":\n return Prompt.makeMessage(\"assistant\", {\n content: message.promptParts ?? assistantParts(message.content),\n });\n }\n};\n\nconst messageTranscriptSeq = (message: DurableTranscriptMessage): number =>\n message._tag === \"User\" || message._tag === \"Steering\"\n ? (message.consumedSeq ?? message.seq)\n : message.seq;\n\nconst promptContextMessageSeq = (message: PromptContextMessage): number =>\n message._tag === \"System\" ? Number.NEGATIVE_INFINITY : messageTranscriptSeq(message);\n\nconst assistantParts = (\n content: Extract<\n DurableTranscriptMessage,\n { readonly _tag: \"Assistant\" | \"AssistantPartial\" }\n >[\"content\"],\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"],"mappings":";;;AAgBA,MAAa,4BACX,UAEA,MAAM,KAAK,MAAM,SAAS,OAAO,CAAC,CAAC,CAAC,OAAO,0BAA0B,CAAC,CAAC,KAA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QAAQ,yBAAyB,KAAA,KACjC,QAAQ,gBAAgB,KAAA;AAE1B,MAAM,oCACJ,YACwE;CACxE,QAAQ,QAAQ,MAAhB;EACE,KAAK,UACH,OAAO,OAAO,YAAY,UAAU,EAAE,SAAS,QAAQ,QAAQ,CAAC;EAClE,KAAK;EACL,KAAK,YACH,OAAO,OAAO,YAAY,QAAQ,EAAE,SAAS,QAAQ,QAAQ,CAAC;EAChE,KAAK;EACL,KAAK,oBACH,OAAO,OAAO,YAAY,aAAa,EACrC,SAAS,QAAQ,eAAe,eAAe,QAAQ,OAAO,EAChE,CAAC;CACL;AACF;AAEA,MAAM,wBAAwB,YAC5B,QAAQ,SAAS,UAAU,QAAQ,SAAS,aACvC,QAAQ,eAAe,QAAQ,MAChC,QAAQ;AAEd,MAAM,2BAA2B,YAC/B,QAAQ,SAAS,WAAW,OAAO,oBAAoB,qBAAqB,OAAO;AAErF,MAAM,kBACJ,YAI+C,CAC/C,GAAI,QAAQ,cAAc,KAAA,IAAY,CAAC,IAAI,CAAC,OAAO,cAAc,EAAE,MAAM,QAAQ,UAAU,CAAC,CAAC,GAC7F,GAAI,QAAQ,KAAK,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,SAAS,EAAE,MAAM,QAAQ,KAAK,CAAC,CAAC,CAC/E"}
|
|
1
|
+
{"version":3,"file":"message-transcript.js","names":[],"sources":["../../src/domain/message-transcript.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\";\n\nimport type { ContextProjection } from \"./context-projection\";\nimport type { MessageRecord, ReducedState, ToolCallRecord } from \"./reduced-state\";\nimport type { UserMessageContent } from \"../types/commands\";\n\n/** Durable user/assistant message records suitable for a session transcript. */\nexport type DurableTranscriptMessage =\n | Extract<MessageRecord, { readonly _tag: \"User\" | \"Assistant\" | \"AssistantPartial\" }>\n | (Extract<MessageRecord, { readonly _tag: \"Steering\" }> & {\n readonly consumedSeq: NonNullable<\n Extract<MessageRecord, { readonly _tag: \"Steering\" }>[\"consumedSeq\"]\n >;\n });\n\n/** Derive the durable user/assistant transcript in committed sequence order. */\nexport const durableMessageTranscript = (\n state: Pick<ReducedState, \"messages\">,\n): ReadonlyArray<DurableTranscriptMessage> =>\n Array.from(state.messages.values()).filter(isDurableTranscriptMessage).sort(compareBySeq);\n\nconst isDurableTranscriptMessage = (message: MessageRecord): message is DurableTranscriptMessage =>\n (message._tag === \"User\" && message.cancelledSeq === undefined) ||\n message._tag === \"Assistant\" ||\n message._tag === \"AssistantPartial\" ||\n (message._tag === \"Steering\" && message.consumedSeq !== undefined);\n\ntype SystemContextMessage = Extract<MessageRecord, { readonly _tag: \"System\" }>;\ntype PromptContextMessage = DurableTranscriptMessage | SystemContextMessage;\ntype PromptProjectionState = Pick<ReducedState, \"messages\"> &\n Partial<Pick<ReducedState, \"toolCalls\">>;\n\ntype AssistantPromptInfo = {\n readonly order: number;\n readonly toolCallOrderByProviderPartId: ReadonlyMap<string, number>;\n};\n\ntype PromptTranscriptItem =\n | {\n readonly _tag: \"Message\";\n readonly order: number;\n readonly message: PromptContextMessage;\n }\n | {\n readonly _tag: \"Summary\";\n readonly order: number;\n readonly message: Prompt.UserMessage;\n }\n | {\n readonly _tag: \"ToolResult\";\n readonly order: number;\n readonly part: Prompt.ToolResultPart;\n };\n\ntype ToolResultPromptTranscriptItem = Extract<\n PromptTranscriptItem,\n { readonly _tag: \"ToolResult\" }\n>;\n\n/** Convert all durable transcript messages and exact tool-result parts into provider prompt history. */\nexport const durableTranscriptPrompt = (state: PromptProjectionState): Prompt.Prompt =>\n contextProjectionPrompt(state, undefined);\n\n/** Convert the current compacted context into provider prompt history. */\nexport const contextProjectionPrompt = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n): Prompt.Prompt => {\n const messages = promptTranscriptItems(state, context).flatMap(\n (item): ReadonlyArray<Prompt.Message> => {\n switch (item._tag) {\n case \"Message\":\n return [transcriptMessageToPromptMessage(item.message)];\n case \"Summary\":\n return [item.message];\n case \"ToolResult\":\n return [Prompt.makeMessage(\"tool\", { content: [item.part] })];\n }\n },\n );\n validateToolCallPairing(messages);\n return Prompt.fromMessages(messages);\n};\n\n/** Build a provider prompt with extra user content selected by the scheduler but not yet folded. */\nexport const durableTranscriptPromptWithUserContent = (\n state: PromptProjectionState,\n content: UserMessageContent,\n): Prompt.Prompt => contextProjectionPromptWithUserContent(state, undefined, content);\n\n/** Build a compacted provider prompt with extra user content selected by the scheduler. */\nexport const contextProjectionPromptWithUserContent = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n content: UserMessageContent,\n): Prompt.Prompt =>\n Prompt.fromMessages([\n ...contextProjectionPrompt(state, context).content,\n Prompt.makeMessage(\"user\", { content }),\n ]);\n\n/** Build a compacted provider prompt with multiple scheduler-selected user messages. */\nexport const contextProjectionPromptWithUserContents = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n contents: ReadonlyArray<UserMessageContent>,\n): Prompt.Prompt =>\n Prompt.fromMessages([\n ...contextProjectionPrompt(state, context).content,\n ...contents.map((content) => Prompt.makeMessage(\"user\", { content })),\n ]);\n\nconst compareBySeq = (left: DurableTranscriptMessage, right: DurableTranscriptMessage): number =>\n messageTranscriptSeq(left) - messageTranscriptSeq(right) || left.seq - right.seq;\n\nconst promptTranscriptItems = (\n state: PromptProjectionState,\n context: ContextProjection | undefined,\n): ReadonlyArray<PromptTranscriptItem> => {\n const messages = promptContextMessages(state, context);\n const assistantInfoByInference = new Map(\n messages.flatMap((message) =>\n message._tag === \"Assistant\" || message._tag === \"AssistantPartial\"\n ? [[message.inferenceId, assistantPromptInfo(message)] as const]\n : [],\n ),\n );\n const messageItems = messages.map((message) => ({\n _tag: \"Message\" as const,\n order: promptContextMessageSeq(message),\n message,\n }));\n const summaryItem =\n context?.currentSummary === undefined\n ? []\n : [\n {\n _tag: \"Summary\" as const,\n order: Number.MIN_SAFE_INTEGER,\n message: context.currentSummary.promptMessage,\n },\n ];\n const toolItems = Array.from(state.toolCalls?.values() ?? []).flatMap((tool) =>\n toolPromptItems(tool, assistantInfoByInference),\n );\n return [...messageItems, ...summaryItem, ...toolItems].sort(\n (left, right) => left.order - right.order,\n );\n};\n\nconst toolPromptItems = (\n tool: ToolCallRecord,\n assistantInfoByInference: ReadonlyMap<unknown, AssistantPromptInfo>,\n): ReadonlyArray<ToolResultPromptTranscriptItem> => {\n const { decision } = tool;\n if (decision === undefined) {\n return [];\n }\n const assistant = assistantInfoByInference.get(decision.inferenceId);\n if (assistant === undefined) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined\n ? []\n : [\n {\n _tag: \"ToolResult\",\n order: syntheticToolResultOrder(assistant, decision.providerPartId),\n part: decision.promptPart,\n },\n ];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [\n {\n _tag: \"ToolResult\",\n order: syntheticToolResultOrder(assistant, decision.providerPartId),\n part: terminal.promptPart,\n },\n ];\n};\n\nconst assistantPromptInfo = (\n message: Extract<PromptContextMessage, { readonly _tag: \"Assistant\" | \"AssistantPartial\" }>,\n): AssistantPromptInfo => ({\n order: messageTranscriptSeq(message),\n toolCallOrderByProviderPartId: new Map(\n assistantToolCallParts(message).map(({ part, index }) => [part.id, index] as const),\n ),\n});\n\nconst assistantToolCallParts = (\n message: Extract<PromptContextMessage, { readonly _tag: \"Assistant\" | \"AssistantPartial\" }>,\n): ReadonlyArray<{ readonly part: Prompt.ToolCallPart; readonly index: number }> =>\n (message.promptParts ?? []).flatMap((part, index) =>\n part.type === \"tool-call\" ? [{ part, index }] : [],\n );\n\nconst syntheticToolResultOrder = (assistant: AssistantPromptInfo, providerPartId: string): number =>\n assistant.order +\n 0.1 +\n (assistant.toolCallOrderByProviderPartId.get(providerPartId) ?? 0) * 0.001;\n\nconst validateToolCallPairing = (messages: ReadonlyArray<Prompt.Message>): void => {\n const pending = new Set<string>();\n for (const message of messages) {\n if (pending.size > 0 && message.role !== \"tool\") {\n throw new Error(unpairedToolCallMessage(pending));\n }\n if (message.role === \"tool\") {\n for (const part of message.content) {\n if (part.type === \"tool-result\") {\n pending.delete(part.id);\n }\n }\n continue;\n }\n if (message.role === \"assistant\") {\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) {\n pending.add(part.id);\n }\n }\n }\n }\n if (pending.size > 0) {\n throw new Error(unpairedToolCallMessage(pending));\n }\n};\n\nconst unpairedToolCallMessage = (pending: ReadonlySet<string>): string =>\n `Prompt transcript contains assistant tool-call(s) without matching tool result(s): ${Array.from(\n pending,\n ).join(\", \")}`;\n\nconst promptContextMessages = (\n state: Pick<ReducedState, \"messages\">,\n context: ContextProjection | undefined,\n): ReadonlyArray<PromptContextMessage> => {\n const retainedFromContextSeq = context?.currentSummary?.retainedFromContextSeq ?? 0;\n const messages = durableMessageTranscript(state).filter(\n (message) =>\n isConsumedForPrompt(message) && messageTranscriptSeq(message) >= retainedFromContextSeq,\n );\n const system = Array.from(state.messages.values()).find(\n (message): message is SystemContextMessage => message._tag === \"System\",\n );\n return system === undefined ? messages : [system, ...messages];\n};\n\nconst isConsumedForPrompt = (message: DurableTranscriptMessage): boolean =>\n message._tag !== \"User\" ||\n message.requestedDisposition === undefined ||\n message.consumedSeq !== undefined;\n\nconst transcriptMessageToPromptMessage = (\n message: PromptContextMessage,\n): Prompt.SystemMessage | Prompt.UserMessage | Prompt.AssistantMessage => {\n switch (message._tag) {\n case \"System\":\n return Prompt.makeMessage(\"system\", { content: message.content });\n case \"User\":\n case \"Steering\":\n return Prompt.makeMessage(\"user\", { content: message.content });\n case \"Assistant\":\n case \"AssistantPartial\":\n return Prompt.makeMessage(\"assistant\", {\n content: message.promptParts ?? assistantParts(message.content),\n });\n }\n};\n\nconst messageTranscriptSeq = (message: DurableTranscriptMessage): number =>\n message._tag === \"User\" || message._tag === \"Steering\"\n ? (message.consumedSeq ?? message.seq)\n : message.seq;\n\nconst promptContextMessageSeq = (message: PromptContextMessage): number =>\n message._tag === \"System\" ? Number.NEGATIVE_INFINITY : messageTranscriptSeq(message);\n\nconst assistantParts = (\n content: Extract<\n DurableTranscriptMessage,\n { readonly _tag: \"Assistant\" | \"AssistantPartial\" }\n >[\"content\"],\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"],"mappings":";;;AAgBA,MAAa,4BACX,UAEA,MAAM,KAAK,MAAM,SAAS,OAAO,CAAC,CAAC,CAAC,OAAO,0BAA0B,CAAC,CAAC,KAAK,YAAY;AAE1F,MAAM,8BAA8B,YACjC,QAAQ,SAAS,UAAU,QAAQ,iBAAiB,KAAA,KACrD,QAAQ,SAAS,eACjB,QAAQ,SAAS,sBAChB,QAAQ,SAAS,cAAc,QAAQ,gBAAgB,KAAA;;AAmC1D,MAAa,2BAA2B,UACtC,wBAAwB,OAAO,KAAA,CAAS;;AAG1C,MAAa,2BACX,OACA,YACkB;CAClB,MAAM,WAAW,sBAAsB,OAAO,OAAO,CAAC,CAAC,SACpD,SAAwC;EACvC,QAAQ,KAAK,MAAb;GACE,KAAK,WACH,OAAO,CAAC,iCAAiC,KAAK,OAAO,CAAC;GACxD,KAAK,WACH,OAAO,CAAC,KAAK,OAAO;GACtB,KAAK,cACH,OAAO,CAAC,OAAO,YAAY,QAAQ,EAAE,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;EAChE;CACF,CACF;CACA,wBAAwB,QAAQ;CAChC,OAAO,OAAO,aAAa,QAAQ;AACrC;;AAGA,MAAa,0CACX,OACA,YACkB,uCAAuC,OAAO,KAAA,GAAW,OAAO;;AAGpF,MAAa,0CACX,OACA,SACA,YAEA,OAAO,aAAa,CAClB,GAAG,wBAAwB,OAAO,OAAO,CAAC,CAAC,SAC3C,OAAO,YAAY,QAAQ,EAAE,QAAQ,CAAC,CACxC,CAAC;;AAGH,MAAa,2CACX,OACA,SACA,aAEA,OAAO,aAAa,CAClB,GA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from "../model-usage-0GeHwaaU.js";
|
|
2
|
-
import { A as ToolTerminalSchema, C as RecoveryContinuationRecordSchema, D as StopRequestRecordSchema, E as RunTerminalSchema, M as TurnTerminalSchema, O as ToolCallRecordSchema, S as QueryUserMessageContent, T as RunRecordSchema, _ as MessageRecordSchema, a as CompactionRecordSchema, b as PendingUserMessageSchema, c as InferenceRecordSchema, d as JsonCommandRecordSchema, f as JsonEDACommand, g as JsonUserMessagePart, h as JsonUserMessageContent, i as CommandTerminalSchema, j as TurnRecordSchema, k as ToolDecisionSchema, l as InferenceTerminalSchema, m as JsonPromptFilePart, n as CommandQueuesSchema, o as CompactionTerminalSchema, p as JsonMessageRecordSchema, r as CommandRecordSchema, s as ContextRecordSchema, t as ActiveCommandEvidenceSchema, u as JsonAssistantMessagePart, v as PendingCommandSchema, w as ReducedStateSchema, x as QueryMessageRecordSchema, y as PendingSteeringMessageSchema } from "../reduced-state-schema-
|
|
2
|
+
import { A as ToolTerminalSchema, C as RecoveryContinuationRecordSchema, D as StopRequestRecordSchema, E as RunTerminalSchema, M as TurnTerminalSchema, O as ToolCallRecordSchema, S as QueryUserMessageContent, T as RunRecordSchema, _ as MessageRecordSchema, a as CompactionRecordSchema, b as PendingUserMessageSchema, c as InferenceRecordSchema, d as JsonCommandRecordSchema, f as JsonEDACommand, g as JsonUserMessagePart, h as JsonUserMessageContent, i as CommandTerminalSchema, j as TurnRecordSchema, k as ToolDecisionSchema, l as InferenceTerminalSchema, m as JsonPromptFilePart, n as CommandQueuesSchema, o as CompactionTerminalSchema, p as JsonMessageRecordSchema, r as CommandRecordSchema, s as ContextRecordSchema, t as ActiveCommandEvidenceSchema, u as JsonAssistantMessagePart, v as PendingCommandSchema, w as ReducedStateSchema, x as QueryMessageRecordSchema, y as PendingSteeringMessageSchema } from "../reduced-state-schema-jyZWJ0QS.js";
|
|
3
3
|
export { ActiveCommandEvidenceSchema, CommandQueuesSchema, CommandRecordSchema, CommandTerminalSchema, CompactionRecordSchema, CompactionTerminalSchema, ContextRecordSchema, InferenceRecordSchema, InferenceTerminalSchema, JsonAssistantMessagePart, JsonCommandRecordSchema, JsonEDACommand, JsonMessageRecordSchema, JsonPromptFilePart, JsonUserMessageContent, JsonUserMessagePart, MessageRecordSchema, PendingCommandSchema, PendingSteeringMessageSchema, PendingUserMessageSchema, QueryMessageRecordSchema, QueryUserMessageContent, RecoveryContinuationRecordSchema, ReducedStateSchema, RunRecordSchema, RunTerminalSchema, StopRequestRecordSchema, TokenConsumptionState as TokenConsumptionStateSchema, TokenUsageTotals as TokenUsageTotalsSchema, ToolCallRecordSchema, ToolDecisionSchema, ToolTerminalSchema, TurnRecordSchema, TurnTerminalSchema };
|
|
@@ -4,9 +4,9 @@ import { EDAEventTrace, EDARunTrace } from "../types/tracing.js";
|
|
|
4
4
|
import { _ as UsagePayload, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload } from "../envelope-BCzKUq_z.js";
|
|
5
5
|
import { TokenConsumptionState, TokenUsageTotals } from "./model-usage.js";
|
|
6
6
|
import { CancelPendingMessageCommand, EDACommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand, UserMessageContent } from "../types/commands.js";
|
|
7
|
-
import { r as AssistantMessageContent, ut as RecoveryContinuation } from "../durable-
|
|
7
|
+
import { r as AssistantMessageContent, ut as RecoveryContinuation } from "../durable-CD__3ztN.js";
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
9
|
-
import * as Prompt from "effect/
|
|
9
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
10
10
|
import * as SchemaTransformation from "effect/SchemaTransformation";
|
|
11
11
|
//#region src/domain/reduced-state-schema.ts
|
|
12
12
|
const PromptFilePart = Schema.Struct(Prompt.FilePart.fields);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reduced-state-schema.js","names":[],"sources":["../../src/domain/reduced-state-schema.ts"],"sourcesContent":["import { TokenConsumptionState } from \"./model-usage\";\nimport { RunSchedulingRequestRecord } from \"./run-scheduling\";\nimport * as Prompt from \"effect/unstable/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nexport {\n TokenConsumptionState as TokenConsumptionStateSchema,\n TokenUsageTotals as TokenUsageTotalsSchema,\n} from \"./model-usage\";\n\nimport {\n CancelPendingMessageCommand,\n EDACommand,\n PromotePendingMessageCommand,\n ResumePendingMessagesCommand,\n StopTurnCommand,\n SubmitMessageCommand,\n UserMessageContent,\n} from \"../types/commands\";\nimport {\n CommandId,\n CompactionId,\n ContextVersion,\n SummaryId,\n InferenceId,\n MessageId,\n RunId,\n SequenceNumber,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n AssistantMessageContent,\n EDAEventTrace,\n EDARunTrace,\n FailurePayload,\n ProviderPartId,\n RecoveryContinuation,\n SystemPromptText,\n ToolName,\n UsagePayload,\n ModelSelectionPayload,\n} from \"../types/events\";\n\nconst PromptFilePart = Schema.Struct(Prompt.FilePart.fields);\nconst PromptReasoningPart = Schema.Struct(Prompt.ReasoningPart.fields);\nconst PromptTextPart = Schema.Struct(Prompt.TextPart.fields);\nconst PromptToolApprovalRequestPart = Schema.Struct(Prompt.ToolApprovalRequestPart.fields);\nconst PromptToolCallPart = Schema.Struct(Prompt.ToolCallPart.fields);\nconst PromptToolResultPart = Schema.Struct(Prompt.ToolResultPart.fields);\n\nconst JsonPromptFilePartEncoded = Schema.Struct({\n ...PromptFilePart.fields,\n data: Schema.String,\n});\n\nconst byteArrayDataUrl = (data: Uint8Array, mediaType: string): string => {\n let binary = \"\";\n for (const byte of data) {\n binary += String.fromCharCode(byte);\n }\n return `data:${mediaType};base64,${btoa(binary)}`;\n};\n\n/**\n * Canonical Effect Prompt file part with an explicit JSON string encoding.\n *\n * Strings pass through unchanged, URLs use their href, and bytes become a data\n * URL. Decoding produces the normal Prompt.FilePart type.\n */\nexport const JsonPromptFilePart = JsonPromptFilePartEncoded.pipe(\n Schema.decodeTo(\n Prompt.FilePart,\n SchemaTransformation.transform<Prompt.FilePartEncoded, typeof JsonPromptFilePartEncoded.Type>({\n decode: (part) => part,\n encode: (part) => ({\n ...part,\n \"~effect/ai/Prompt/Part\": \"~effect/ai/Prompt/Part\",\n data:\n typeof part.data === \"string\"\n ? part.data\n : part.data instanceof URL\n ? part.data.href\n : byteArrayDataUrl(part.data, part.mediaType),\n options: part.options ?? {},\n }),\n }),\n ),\n);\n\nexport const JsonUserMessagePart = Schema.Union([PromptTextPart, JsonPromptFilePart]);\nexport const JsonUserMessageContent = Schema.Union([\n Prompt.ContentFromString,\n Schema.NonEmptyArray(JsonUserMessagePart),\n]);\n\nexport const JsonAssistantMessagePart = Schema.Union([\n PromptTextPart,\n JsonPromptFilePart,\n PromptReasoningPart,\n PromptToolCallPart,\n PromptToolResultPart,\n PromptToolApprovalRequestPart,\n]);\n\n/**\n * Command schema for JSON snapshots.\n *\n * Every command except SubmitMessage is reused directly. SubmitMessage only\n * replaces canonical Prompt file data with its explicit JSON string projection.\n */\nexport const JsonEDACommand = Schema.Union([\n Schema.Struct({\n ...SubmitMessageCommand.fields,\n content: JsonUserMessageContent,\n }),\n StopTurnCommand,\n CancelPendingMessageCommand,\n PromotePendingMessageCommand,\n ResumePendingMessagesCommand,\n]);\n\nexport const CommandTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Cancelled\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const RunTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Interrupted\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const TurnTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n seq: SequenceNumber,\n usage: Schema.optionalKey(UsagePayload),\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Stopped\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const InferenceTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n seq: SequenceNumber,\n usage: Schema.optionalKey(UsagePayload),\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n]);\n\nconst LifecycleTimingFields = {\n durationMs: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))),\n startedAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n terminalAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n};\n\nexport const CommandRecordSchema = Schema.Struct({\n admittedSeq: Schema.optionalKey(SequenceNumber),\n admissionTrace: Schema.optionalKey(EDAEventTrace),\n command: Schema.optionalKey(EDACommand),\n commandId: CommandId,\n startedSeq: Schema.optionalKey(SequenceNumber),\n terminal: Schema.optionalKey(CommandTerminalSchema),\n});\n\nexport const JsonCommandRecordSchema = Schema.Struct({\n ...CommandRecordSchema.fields,\n command: Schema.optionalKey(JsonEDACommand),\n});\n\nexport const RunRecordSchema = Schema.Struct({\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n ...LifecycleTimingFields,\n commandIds: Schema.Array(CommandId),\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(RunTerminalSchema),\n trace: EDARunTrace,\n});\n\nexport const TurnRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(TurnTerminalSchema),\n turnId: TurnId,\n});\n\nexport const InferenceRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n inferenceId: InferenceId,\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(InferenceTerminalSchema),\n turnId: TurnId,\n});\n\nexport const ToolDecisionSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Created\"),\n inferenceId: InferenceId,\n params: Schema.Unknown,\n promptPart: Schema.optionalKey(PromptToolCallPart),\n providerExecuted: Schema.Boolean,\n providerPartId: ProviderPartId,\n runId: RunId,\n seq: SequenceNumber,\n toolName: ToolName,\n turnId: TurnId,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Rejected\"),\n inferenceId: InferenceId,\n modelFeedback: Schema.String,\n promptPart: Schema.optionalKey(PromptToolResultPart),\n providerPartId: ProviderPartId,\n reason: Schema.Literals([\"unknown-tool\", \"invalid-params\"]),\n runId: RunId,\n seq: SequenceNumber,\n toolName: ToolName,\n turnId: TurnId,\n }),\n]);\n\nexport const ToolTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n promptPart: Schema.optionalKey(PromptToolResultPart),\n result: Schema.Unknown,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n promptPart: Schema.optionalKey(PromptToolResultPart),\n seq: SequenceNumber,\n }),\n]);\n\nexport const ToolCallRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n decision: Schema.optionalKey(ToolDecisionSchema),\n startedSeq: Schema.optionalKey(SequenceNumber),\n terminal: Schema.optionalKey(ToolTerminalSchema),\n toolCallId: ToolCallId,\n});\n\nconst MessageIdentityFields = {\n createdAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n messageId: MessageId,\n seq: SequenceNumber,\n};\n\nconst PendingMessageStateFields = {\n cancellationReason: Schema.optionalKey(Schema.String),\n cancelledByCommandId: Schema.optionalKey(CommandId),\n cancelledSeq: Schema.optionalKey(SequenceNumber),\n consumedSeq: Schema.optionalKey(SequenceNumber),\n consumedTurnId: Schema.optionalKey(TurnId),\n pausedByCommandId: Schema.optionalKey(CommandId),\n pausedSeq: Schema.optionalKey(SequenceNumber),\n promotedSeq: Schema.optionalKey(SequenceNumber),\n};\n\nconst messageRecordSchema = <UserContent extends Schema.Top, AssistantPart extends Schema.Top>(\n userContent: UserContent,\n assistantPart: AssistantPart,\n) =>\n Schema.Union([\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"System\"),\n content: SystemPromptText,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n ...PendingMessageStateFields,\n _tag: Schema.Literal(\"User\"),\n commandId: CommandId,\n content: userContent,\n disposition: Schema.optionalKey(Schema.Literals([\"queue\", \"steer\"])),\n requestedDisposition: Schema.optionalKey(Schema.Literals([\"queue\", \"steer\"])),\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n ...PendingMessageStateFields,\n _tag: Schema.Literal(\"Steering\"),\n commandId: CommandId,\n content: userContent,\n runId: RunId,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"Assistant\"),\n content: AssistantMessageContent,\n imported: Schema.optionalKey(Schema.Literal(true)),\n inferenceId: InferenceId,\n promptParts: Schema.optionalKey(Schema.Array(assistantPart)),\n runId: RunId,\n turnId: TurnId,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"AssistantPartial\"),\n content: AssistantMessageContent,\n inferenceId: InferenceId,\n promptParts: Schema.optionalKey(Schema.Array(assistantPart)),\n reason: Schema.String,\n runId: RunId,\n turnId: TurnId,\n }),\n ]);\n\nexport const MessageRecordSchema = messageRecordSchema(\n UserMessageContent,\n Schema.Union([\n PromptTextPart,\n PromptFilePart,\n PromptReasoningPart,\n PromptToolCallPart,\n PromptToolResultPart,\n PromptToolApprovalRequestPart,\n ]),\n);\n\n/** Lossless structured-clone query content; admission string transforms do not apply. */\nexport const QueryUserMessageContent = Schema.toType(UserMessageContent);\n\n/** Message query records preserve Prompt-part arrays and their structured-clone fields. */\nexport const QueryMessageRecordSchema = messageRecordSchema(\n QueryUserMessageContent,\n Schema.Union([\n Schema.toType(PromptTextPart),\n Schema.toType(PromptFilePart),\n Schema.toType(PromptReasoningPart),\n Schema.toType(PromptToolCallPart),\n Schema.toType(PromptToolResultPart),\n Schema.toType(PromptToolApprovalRequestPart),\n ]),\n);\n\nexport const JsonMessageRecordSchema = messageRecordSchema(\n JsonUserMessageContent,\n JsonAssistantMessagePart,\n);\n\nexport const RecoveryContinuationRecordSchema = Schema.Struct({\n ...RecoveryContinuation.fields,\n seq: SequenceNumber,\n});\n\n/** Structured-clone schema for the existing StopRequestRecord query representation. */\nexport const StopRequestRecordSchema = Schema.Struct({\n commandId: CommandId,\n requestedSeq: SequenceNumber,\n requestedRunId: Schema.optionalKey(RunId),\n requestedTurnId: Schema.optionalKey(TurnId),\n appliedSeq: Schema.optionalKey(SequenceNumber),\n appliedRunId: Schema.optionalKey(RunId),\n appliedTurnId: Schema.optionalKey(TurnId),\n appliedInferenceId: Schema.optionalKey(InferenceId),\n});\n\n/** Structured-clone schema for the existing CompactionTerminal query representation. */\nexport const CompactionTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({ _tag: Schema.Literal(\"Failed\"), seq: SequenceNumber, error: FailurePayload }),\n]);\n\n/** Structured-clone schema for the existing CompactionRecord query representation. */\nexport const CompactionRecordSchema = Schema.Struct({\n compactionId: CompactionId,\n requestedSeq: Schema.optionalKey(SequenceNumber),\n startedSeq: Schema.optionalKey(SequenceNumber),\n summaryCreatedSeq: Schema.optionalKey(SequenceNumber),\n summaryId: Schema.optionalKey(SummaryId),\n sourceFromSeq: Schema.optionalKey(SequenceNumber),\n sourceToSeq: Schema.optionalKey(SequenceNumber),\n rebasedSeq: Schema.optionalKey(SequenceNumber),\n contextVersion: Schema.optionalKey(ContextVersion),\n terminal: Schema.optionalKey(CompactionTerminalSchema),\n});\n\n/** Structured-clone schema for the existing ContextRecord query representation. */\nexport const ContextRecordSchema = Schema.Struct({\n version: ContextVersion,\n currentSummaryId: Schema.optionalKey(SummaryId),\n});\n\n/** Structured-clone schema for the existing ActiveCommandEvidence query representation. */\nexport const ActiveCommandEvidenceSchema = Schema.Struct({\n commandId: CommandId,\n runId: Schema.optionalKey(RunId),\n});\n\n/** Structured-clone schema for the existing PendingCommand query representation. */\nexport const PendingCommandSchema = Schema.Struct({\n commandId: CommandId,\n command: EDACommand,\n admittedSeq: SequenceNumber,\n admissionTrace: Schema.optionalKey(EDAEventTrace),\n});\n\n/** Structured-clone schema for the existing PendingSteeringMessage query representation. */\nexport const PendingSteeringMessageSchema = Schema.Struct({\n messageId: MessageId,\n commandId: CommandId,\n runId: RunId,\n content: QueryUserMessageContent,\n queuedSeq: SequenceNumber,\n consumedSeq: Schema.optionalKey(SequenceNumber),\n consumedTurnId: Schema.optionalKey(TurnId),\n});\n\n/** Structured-clone schema for the existing PendingUserMessage query representation. */\nexport const PendingUserMessageSchema = Schema.Struct({\n messageId: MessageId,\n commandId: CommandId,\n content: QueryUserMessageContent,\n submittedSeq: SequenceNumber,\n effectiveSeq: SequenceNumber,\n disposition: Schema.Union([Schema.Literal(\"queue\"), Schema.Literal(\"steer\")]),\n targetRunId: Schema.optionalKey(RunId),\n pausedByCommandId: Schema.optionalKey(CommandId),\n});\n\n/** Structured-clone schema for the existing CommandQueues query representation. */\nexport const CommandQueuesSchema = Schema.Struct({\n active: Schema.optional(ActiveCommandEvidenceSchema),\n pendingCommands: Schema.Array(PendingCommandSchema),\n queuedCommands: Schema.Array(PendingCommandSchema),\n activeControlCommands: Schema.Array(PendingCommandSchema),\n steeringByRun: Schema.ReadonlyMap(RunId, Schema.Array(PendingSteeringMessageSchema)),\n pendingQueue: Schema.Array(PendingUserMessageSchema),\n pendingSteers: Schema.Array(PendingUserMessageSchema),\n pausedQueue: Schema.Array(PendingUserMessageSchema),\n});\n\n/** Structured-clone schema for the existing ReducedState query representation. */\nexport const ReducedStateSchema = Schema.Struct({\n runSchedulingRequest: Schema.optionalKey(RunSchedulingRequestRecord),\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n lastSeq: SequenceNumber,\n commands: Schema.ReadonlyMap(CommandId, CommandRecordSchema),\n runs: Schema.ReadonlyMap(RunId, RunRecordSchema),\n recoveryContinuations: Schema.ReadonlyMap(RunId, RecoveryContinuationRecordSchema),\n turns: Schema.ReadonlyMap(TurnId, TurnRecordSchema),\n inferences: Schema.ReadonlyMap(InferenceId, InferenceRecordSchema),\n toolCalls: Schema.ReadonlyMap(ToolCallId, Schema.toType(ToolCallRecordSchema)),\n messages: Schema.ReadonlyMap(MessageId, QueryMessageRecordSchema),\n stopRequests: Schema.ReadonlyMap(CommandId, StopRequestRecordSchema),\n compactions: Schema.ReadonlyMap(CompactionId, CompactionRecordSchema),\n context: ContextRecordSchema,\n tokenConsumption: TokenConsumptionState,\n commandQueues: CommandQueuesSchema,\n});\n"],"mappings":";;;;;;;;;;;AA4CA,MAAM,iBAAiB,OAAO,OAAO,OAAO,SAAS,MAAM;AAC3D,MAAM,sBAAsB,OAAO,OAAO,OAAO,cAAc,MAAM;AACrE,MAAM,iBAAiB,OAAO,OAAO,OAAO,SAAS,MAAM;AAC3D,MAAM,gCAAgC,OAAO,OAAO,OAAO,wBAAwB,MAAM;AACzF,MAAM,qBAAqB,OAAO,OAAO,OAAO,aAAa,MAAM;AACnE,MAAM,uBAAuB,OAAO,OAAO,OAAO,eAAe,MAAM;AAEvE,MAAM,4BAA4B,OAAO,OAAO;CAC9C,GAAG,eAAe;CAClB,MAAM,OAAO;AACf,CAAC;AAED,MAAM,oBAAoB,MAAkB,cAA8B;CACxE,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,MACjB,UAAU,OAAO,a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wBAAwB;AACpD,CAAC;;AAGD,MAAa,qBAAqB,OAAO,OAAO;CAC9C,sBAAsB,OAAO,YAAY,0BAA0B;CACnE,gBAAgB,OAAO,YAAY,qBAAqB;CACxD,SAAS;CACT,UAAU,OAAO,YAAY,WAAW,mBAAmB;CAC3D,MAAM,OAAO,YAAY,OAAO,eAAe;CAC/C,uBAAuB,OAAO,YAAY,OAAO,gCAAgC;CACjF,OAAO,OAAO,YAAY,QAAQ,gBAAgB;CAClD,YAAY,OAAO,YAAY,aAAa,qBAAqB;CACjE,WAAW,OAAO,YAAY,YAAY,OAAO,OAAO,oBAAoB,CAAC;CAC7E,UAAU,OAAO,YAAY,WAAW,wBAAwB;CAChE,cAAc,OAAO,YAAY,WAAW,uBAAuB;CACnE,aAAa,OAAO,YAAY,cAAc,sBAAsB;CACpE,SAAS;CACT,kBAAkB;CAClB,eAAe;AACjB,CAAC"}
|
|
1
|
+
{"version":3,"file":"reduced-state-schema.js","names":[],"sources":["../../src/domain/reduced-state-schema.ts"],"sourcesContent":["import { TokenConsumptionState } from \"./model-usage\";\nimport { RunSchedulingRequestRecord } from \"./run-scheduling\";\nimport * as Prompt from \"effect/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nexport {\n TokenConsumptionState as TokenConsumptionStateSchema,\n TokenUsageTotals as TokenUsageTotalsSchema,\n} from \"./model-usage\";\n\nimport {\n CancelPendingMessageCommand,\n EDACommand,\n PromotePendingMessageCommand,\n ResumePendingMessagesCommand,\n StopTurnCommand,\n SubmitMessageCommand,\n UserMessageContent,\n} from \"../types/commands\";\nimport {\n CommandId,\n CompactionId,\n ContextVersion,\n SummaryId,\n InferenceId,\n MessageId,\n RunId,\n SequenceNumber,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n AssistantMessageContent,\n EDAEventTrace,\n EDARunTrace,\n FailurePayload,\n ProviderPartId,\n RecoveryContinuation,\n SystemPromptText,\n ToolName,\n UsagePayload,\n ModelSelectionPayload,\n} from \"../types/events\";\n\nconst PromptFilePart = Schema.Struct(Prompt.FilePart.fields);\nconst PromptReasoningPart = Schema.Struct(Prompt.ReasoningPart.fields);\nconst PromptTextPart = Schema.Struct(Prompt.TextPart.fields);\nconst PromptToolApprovalRequestPart = Schema.Struct(Prompt.ToolApprovalRequestPart.fields);\nconst PromptToolCallPart = Schema.Struct(Prompt.ToolCallPart.fields);\nconst PromptToolResultPart = Schema.Struct(Prompt.ToolResultPart.fields);\n\nconst JsonPromptFilePartEncoded = Schema.Struct({\n ...PromptFilePart.fields,\n data: Schema.String,\n});\n\nconst byteArrayDataUrl = (data: Uint8Array, mediaType: string): string => {\n let binary = \"\";\n for (const byte of data) {\n binary += String.fromCharCode(byte);\n }\n return `data:${mediaType};base64,${btoa(binary)}`;\n};\n\n/**\n * Canonical Effect Prompt file part with an explicit JSON string encoding.\n *\n * Strings pass through unchanged, URLs use their href, and bytes become a data\n * URL. Decoding produces the normal Prompt.FilePart type.\n */\nexport const JsonPromptFilePart = JsonPromptFilePartEncoded.pipe(\n Schema.decodeTo(\n Prompt.FilePart,\n SchemaTransformation.transform<Prompt.FilePartEncoded, typeof JsonPromptFilePartEncoded.Type>({\n decode: (part) => part,\n encode: (part) => ({\n ...part,\n \"~effect/ai/Prompt/Part\": \"~effect/ai/Prompt/Part\",\n data:\n typeof part.data === \"string\"\n ? part.data\n : part.data instanceof URL\n ? part.data.href\n : byteArrayDataUrl(part.data, part.mediaType),\n options: part.options ?? {},\n }),\n }),\n ),\n);\n\nexport const JsonUserMessagePart = Schema.Union([PromptTextPart, JsonPromptFilePart]);\nexport const JsonUserMessageContent = Schema.Union([\n Prompt.ContentFromString,\n Schema.NonEmptyArray(JsonUserMessagePart),\n]);\n\nexport const JsonAssistantMessagePart = Schema.Union([\n PromptTextPart,\n JsonPromptFilePart,\n PromptReasoningPart,\n PromptToolCallPart,\n PromptToolResultPart,\n PromptToolApprovalRequestPart,\n]);\n\n/**\n * Command schema for JSON snapshots.\n *\n * Every command except SubmitMessage is reused directly. SubmitMessage only\n * replaces canonical Prompt file data with its explicit JSON string projection.\n */\nexport const JsonEDACommand = Schema.Union([\n Schema.Struct({\n ...SubmitMessageCommand.fields,\n content: JsonUserMessageContent,\n }),\n StopTurnCommand,\n CancelPendingMessageCommand,\n PromotePendingMessageCommand,\n ResumePendingMessagesCommand,\n]);\n\nexport const CommandTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Cancelled\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const RunTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Interrupted\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const TurnTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n seq: SequenceNumber,\n usage: Schema.optionalKey(UsagePayload),\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Stopped\"),\n reason: Schema.String,\n seq: SequenceNumber,\n }),\n]);\n\nexport const InferenceTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n seq: SequenceNumber,\n usage: Schema.optionalKey(UsagePayload),\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n seq: SequenceNumber,\n }),\n]);\n\nconst LifecycleTimingFields = {\n durationMs: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))),\n startedAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n terminalAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n};\n\nexport const CommandRecordSchema = Schema.Struct({\n admittedSeq: Schema.optionalKey(SequenceNumber),\n admissionTrace: Schema.optionalKey(EDAEventTrace),\n command: Schema.optionalKey(EDACommand),\n commandId: CommandId,\n startedSeq: Schema.optionalKey(SequenceNumber),\n terminal: Schema.optionalKey(CommandTerminalSchema),\n});\n\nexport const JsonCommandRecordSchema = Schema.Struct({\n ...CommandRecordSchema.fields,\n command: Schema.optionalKey(JsonEDACommand),\n});\n\nexport const RunRecordSchema = Schema.Struct({\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n ...LifecycleTimingFields,\n commandIds: Schema.Array(CommandId),\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(RunTerminalSchema),\n trace: EDARunTrace,\n});\n\nexport const TurnRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(TurnTerminalSchema),\n turnId: TurnId,\n});\n\nexport const InferenceRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n inferenceId: InferenceId,\n runId: RunId,\n startedSeq: SequenceNumber,\n terminal: Schema.optionalKey(InferenceTerminalSchema),\n turnId: TurnId,\n});\n\nexport const ToolDecisionSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Created\"),\n inferenceId: InferenceId,\n params: Schema.Unknown,\n promptPart: Schema.optionalKey(PromptToolCallPart),\n providerExecuted: Schema.Boolean,\n providerPartId: ProviderPartId,\n runId: RunId,\n seq: SequenceNumber,\n toolName: ToolName,\n turnId: TurnId,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Rejected\"),\n inferenceId: InferenceId,\n modelFeedback: Schema.String,\n promptPart: Schema.optionalKey(PromptToolResultPart),\n providerPartId: ProviderPartId,\n reason: Schema.Literals([\"unknown-tool\", \"invalid-params\"]),\n runId: RunId,\n seq: SequenceNumber,\n toolName: ToolName,\n turnId: TurnId,\n }),\n]);\n\nexport const ToolTerminalSchema = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Completed\"),\n promptPart: Schema.optionalKey(PromptToolResultPart),\n result: Schema.Unknown,\n seq: SequenceNumber,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Failed\"),\n error: FailurePayload,\n promptPart: Schema.optionalKey(PromptToolResultPart),\n seq: SequenceNumber,\n }),\n]);\n\nexport const ToolCallRecordSchema = Schema.Struct({\n ...LifecycleTimingFields,\n decision: Schema.optionalKey(ToolDecisionSchema),\n startedSeq: Schema.optionalKey(SequenceNumber),\n terminal: Schema.optionalKey(ToolTerminalSchema),\n toolCallId: ToolCallId,\n});\n\nconst MessageIdentityFields = {\n createdAtMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n messageId: MessageId,\n seq: SequenceNumber,\n};\n\nconst PendingMessageStateFields = {\n cancellationReason: Schema.optionalKey(Schema.String),\n cancelledByCommandId: Schema.optionalKey(CommandId),\n cancelledSeq: Schema.optionalKey(SequenceNumber),\n consumedSeq: Schema.optionalKey(SequenceNumber),\n consumedTurnId: Schema.optionalKey(TurnId),\n pausedByCommandId: Schema.optionalKey(CommandId),\n pausedSeq: Schema.optionalKey(SequenceNumber),\n promotedSeq: Schema.optionalKey(SequenceNumber),\n};\n\nconst messageRecordSchema = <UserContent extends Schema.Top, AssistantPart extends Schema.Top>(\n userContent: UserContent,\n assistantPart: AssistantPart,\n) =>\n Schema.Union([\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"System\"),\n content: SystemPromptText,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n ...PendingMessageStateFields,\n _tag: Schema.Literal(\"User\"),\n commandId: CommandId,\n content: userContent,\n disposition: Schema.optionalKey(Schema.Literals([\"queue\", \"steer\"])),\n requestedDisposition: Schema.optionalKey(Schema.Literals([\"queue\", \"steer\"])),\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n ...PendingMessageStateFields,\n _tag: Schema.Literal(\"Steering\"),\n commandId: CommandId,\n content: userContent,\n runId: RunId,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"Assistant\"),\n content: AssistantMessageContent,\n imported: Schema.optionalKey(Schema.Literal(true)),\n inferenceId: InferenceId,\n promptParts: Schema.optionalKey(Schema.Array(assistantPart)),\n runId: RunId,\n turnId: TurnId,\n }),\n Schema.Struct({\n ...MessageIdentityFields,\n _tag: Schema.Literal(\"AssistantPartial\"),\n content: AssistantMessageContent,\n inferenceId: InferenceId,\n promptParts: Schema.optionalKey(Schema.Array(assistantPart)),\n reason: Schema.String,\n runId: RunId,\n turnId: TurnId,\n }),\n ]);\n\nexport const MessageRecordSchema = messageRecordSchema(\n UserMessageContent,\n Schema.Union([\n PromptTextPart,\n PromptFilePart,\n PromptReasoningPart,\n PromptToolCallPart,\n PromptToolResultPart,\n PromptToolApprovalRequestPart,\n ]),\n);\n\n/** Lossless structured-clone query content; admission string transforms do not apply. */\nexport const QueryUserMessageContent = Schema.toType(UserMessageContent);\n\n/** Message query records preserve Prompt-part arrays and their structured-clone fields. */\nexport const QueryMessageRecordSchema = messageRecordSchema(\n QueryUserMessageContent,\n Schema.Union([\n Schema.toType(PromptTextPart),\n Schema.toType(PromptFilePart),\n Schema.toType(PromptReasoningPart),\n Schema.toType(PromptToolCallPart),\n Schema.toType(PromptToolResultPart),\n Schema.toType(PromptToolApprovalRequestPart),\n ]),\n);\n\nexport const JsonMessageRecordSchema = messageRecordSchema(\n JsonUserMessageContent,\n JsonAssistantMessagePart,\n);\n\nexport const RecoveryContinuationRecordSchema = Schema.Struct({\n ...RecoveryContinuation.fields,\n seq: SequenceNumber,\n});\n\n/** Structured-clone schema for the existing StopRequestRecord query representation. */\nexport const StopRequestRecordSchema = Schema.Struct({\n commandId: CommandId,\n requestedSeq: SequenceNumber,\n requestedRunId: Schema.optionalKey(RunId),\n requestedTurnId: Schema.optionalKey(TurnId),\n appliedSeq: Schema.optionalKey(SequenceNumber),\n appliedRunId: Schema.optionalKey(RunId),\n appliedTurnId: Schema.optionalKey(TurnId),\n appliedInferenceId: Schema.optionalKey(InferenceId),\n});\n\n/** Structured-clone schema for the existing CompactionTerminal query representation. */\nexport const CompactionTerminalSchema = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Completed\"), seq: SequenceNumber }),\n Schema.Struct({ _tag: Schema.Literal(\"Failed\"), seq: SequenceNumber, error: FailurePayload }),\n]);\n\n/** Structured-clone schema for the existing CompactionRecord query representation. */\nexport const CompactionRecordSchema = Schema.Struct({\n compactionId: CompactionId,\n requestedSeq: Schema.optionalKey(SequenceNumber),\n startedSeq: Schema.optionalKey(SequenceNumber),\n summaryCreatedSeq: Schema.optionalKey(SequenceNumber),\n summaryId: Schema.optionalKey(SummaryId),\n sourceFromSeq: Schema.optionalKey(SequenceNumber),\n sourceToSeq: Schema.optionalKey(SequenceNumber),\n rebasedSeq: Schema.optionalKey(SequenceNumber),\n contextVersion: Schema.optionalKey(ContextVersion),\n terminal: Schema.optionalKey(CompactionTerminalSchema),\n});\n\n/** Structured-clone schema for the existing ContextRecord query representation. */\nexport const ContextRecordSchema = Schema.Struct({\n version: ContextVersion,\n currentSummaryId: Schema.optionalKey(SummaryId),\n});\n\n/** Structured-clone schema for the existing ActiveCommandEvidence query representation. */\nexport const ActiveCommandEvidenceSchema = Schema.Struct({\n commandId: CommandId,\n runId: Schema.optionalKey(RunId),\n});\n\n/** Structured-clone schema for the existing PendingCommand query representation. */\nexport const PendingCommandSchema = Schema.Struct({\n commandId: CommandId,\n command: EDACommand,\n admittedSeq: SequenceNumber,\n admissionTrace: Schema.optionalKey(EDAEventTrace),\n});\n\n/** Structured-clone schema for the existing PendingSteeringMessage query representation. */\nexport const PendingSteeringMessageSchema = Schema.Struct({\n messageId: MessageId,\n commandId: CommandId,\n runId: RunId,\n content: QueryUserMessageContent,\n queuedSeq: SequenceNumber,\n consumedSeq: Schema.optionalKey(SequenceNumber),\n consumedTurnId: Schema.optionalKey(TurnId),\n});\n\n/** Structured-clone schema for the existing PendingUserMessage query representation. */\nexport const PendingUserMessageSchema = Schema.Struct({\n messageId: MessageId,\n commandId: CommandId,\n content: QueryUserMessageContent,\n submittedSeq: SequenceNumber,\n effectiveSeq: SequenceNumber,\n disposition: Schema.Union([Schema.Literal(\"queue\"), Schema.Literal(\"steer\")]),\n targetRunId: Schema.optionalKey(RunId),\n pausedByCommandId: Schema.optionalKey(CommandId),\n});\n\n/** Structured-clone schema for the existing CommandQueues query representation. */\nexport const CommandQueuesSchema = Schema.Struct({\n active: Schema.optional(ActiveCommandEvidenceSchema),\n pendingCommands: Schema.Array(PendingCommandSchema),\n queuedCommands: Schema.Array(PendingCommandSchema),\n activeControlCommands: Schema.Array(PendingCommandSchema),\n steeringByRun: Schema.ReadonlyMap(RunId, Schema.Array(PendingSteeringMessageSchema)),\n pendingQueue: Schema.Array(PendingUserMessageSchema),\n pendingSteers: Schema.Array(PendingUserMessageSchema),\n pausedQueue: Schema.Array(PendingUserMessageSchema),\n});\n\n/** Structured-clone schema for the existing ReducedState query representation. */\nexport const ReducedStateSchema = Schema.Struct({\n runSchedulingRequest: Schema.optionalKey(RunSchedulingRequestRecord),\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n lastSeq: SequenceNumber,\n commands: Schema.ReadonlyMap(CommandId, CommandRecordSchema),\n runs: Schema.ReadonlyMap(RunId, RunRecordSchema),\n recoveryContinuations: Schema.ReadonlyMap(RunId, RecoveryContinuationRecordSchema),\n turns: Schema.ReadonlyMap(TurnId, TurnRecordSchema),\n inferences: Schema.ReadonlyMap(InferenceId, InferenceRecordSchema),\n toolCalls: Schema.ReadonlyMap(ToolCallId, Schema.toType(ToolCallRecordSchema)),\n messages: Schema.ReadonlyMap(MessageId, QueryMessageRecordSchema),\n stopRequests: Schema.ReadonlyMap(CommandId, StopRequestRecordSchema),\n compactions: Schema.ReadonlyMap(CompactionId, CompactionRecordSchema),\n context: ContextRecordSchema,\n tokenConsumption: TokenConsumptionState,\n commandQueues: CommandQueuesSchema,\n});\n"],"mappings":";;;;;;;;;;;AA4CA,MAAM,iBAAiB,OAAO,OAAO,OAAO,SAAS,MAAM;AAC3D,MAAM,sBAAsB,OAAO,OAAO,OAAO,cAAc,MAAM;AACrE,MAAM,iBAAiB,OAAO,OAAO,OAAO,SAAS,MAAM;AAC3D,MAAM,gCAAgC,OAAO,OAAO,OAAO,wBAAwB,MAAM;AACzF,MAAM,qBAAqB,OAAO,OAAO,OAAO,aAAa,MAAM;AACnE,MAAM,uBAAuB,OAAO,OAAO,OAAO,eAAe,MAAM;AAEvE,MAAM,4BAA4B,OAAO,OAAO;CAC9C,GAAG,eAAe;CAClB,MAAM,OAAO;AACf,CAAC;AAED,MAAM,oBAAoB,MAAkB,cAA8B;CACxE,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,MACjB,UAAU,OAAO,aAAa,IAAI;CAEpC,OAAO,QAAQ,UAAU,UAAU,KAAK,MAAM;AAChD;;;;;;;AAQA,MAAa,qBAAqB,0BAA0B,KAC1D,OAAO,SACL,OAAO,UACP,qBAAqB,UAAyE;CAC5F,SAAS,SAAS;CAClB,SAAS,UAAU;EACjB,GAAG;EACH,0BAA0B;EAC1B,MACE,OAAO,KAAK,SAAS,WACjB,KAAK,OACL,KAAK,gBAAgB,MACnB,KAAK,KAAK,OACV,iBAAiB,KAAK,MAAM,KAAK,SAAS;EAClD,SAAS,KAAK,WAAW,CAAC;CAC5B;AACF,CAAC,CACH,CACF;AAEA,MAAa,sBAAsB,OAAO,MAAM,CAAC,gBAAgB,kBAAkB,CAAC;AACpF,MAAa,yBAAyB,OAAO,MAAM,CACjD,OAAO,mBACP,OAAO,cAAc,mBAAmB,CAC1C,CAAC;AAED,MAAa,2BAA2B,OAAO,MAAM;CACnD;CACA;CACA;CAC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,3 @@
|
|
|
1
|
-
import { A as TurnTerminal, B as pendingCommands, C as RunRecord, D as ToolDecision, E as ToolCallRecord, F as encodeReducedStateCheckpoint, H as reduceCommittedEvents, I as foldReducedState, L as frameworkReducedStateReducerName, M as activeTurnIdentityForCommand, N as classifyRecoverableWork, O as ToolTerminal, P as decodeReducedStateCheckpoint, R as frameworkReducedStateReducerSchemaVersion, S as ReducedStateCheckpointToolTerminal, T as StopRequestRecord, U as reducedStateCheckpointEventSeqs, V as pendingStopCommand, _ as ReducedStateCheckpointCommandRecord, a as CompactionRecord, b as ReducedStateCheckpointToolCallRecord, c as InferenceRecord, d as LifecycleTiming, f as MessageRecord, g as ReducedState, h as RecoveryContinuationRecord, i as CommandTerminal, j as activeCommand, k as TurnRecord, l as InferenceTerminal, m as RecoverableWork, n as ActiveTurnIdentity, o as CompactionTerminal, p as PendingCommand, r as CommandRecord, s as ContextRecord, t as ActiveCommandEvidence, u as LifecycleFailure, v as ReducedStateCheckpointMessageRecord, w as RunTerminal, x as ReducedStateCheckpointToolDecision, y as ReducedStateCheckpointPayload, z as initialReducedState } from "../reduced-state-
|
|
1
|
+
import { A as TurnTerminal, B as pendingCommands, C as RunRecord, D as ToolDecision, E as ToolCallRecord, F as encodeReducedStateCheckpoint, H as reduceCommittedEvents, I as foldReducedState, L as frameworkReducedStateReducerName, M as activeTurnIdentityForCommand, N as classifyRecoverableWork, O as ToolTerminal, P as decodeReducedStateCheckpoint, R as frameworkReducedStateReducerSchemaVersion, S as ReducedStateCheckpointToolTerminal, T as StopRequestRecord, U as reducedStateCheckpointEventSeqs, V as pendingStopCommand, _ as ReducedStateCheckpointCommandRecord, a as CompactionRecord, b as ReducedStateCheckpointToolCallRecord, c as InferenceRecord, d as LifecycleTiming, f as MessageRecord, g as ReducedState, h as RecoveryContinuationRecord, i as CommandTerminal, j as activeCommand, k as TurnRecord, l as InferenceTerminal, m as RecoverableWork, n as ActiveTurnIdentity, o as CompactionTerminal, p as PendingCommand, r as CommandRecord, s as ContextRecord, t as ActiveCommandEvidence, u as LifecycleFailure, v as ReducedStateCheckpointMessageRecord, w as RunTerminal, x as ReducedStateCheckpointToolDecision, y as ReducedStateCheckpointPayload, z as initialReducedState } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
import { n as TokenConsumptionState, r as TokenUsageTotals } from "../model-usage-0GeHwaaU.js";
|
|
3
3
|
export { ActiveCommandEvidence, ActiveTurnIdentity, CommandRecord, CommandTerminal, CompactionRecord, CompactionTerminal, ContextRecord, InferenceRecord, InferenceTerminal, LifecycleFailure, LifecycleTiming, MessageRecord, PendingCommand, RecoverableWork, RecoveryContinuationRecord, ReducedState, ReducedStateCheckpointCommandRecord, ReducedStateCheckpointMessageRecord, ReducedStateCheckpointPayload, ReducedStateCheckpointToolCallRecord, ReducedStateCheckpointToolDecision, ReducedStateCheckpointToolTerminal, RunRecord, RunTerminal, StopRequestRecord, TokenConsumptionState, type TokenUsageTotals, ToolCallRecord, ToolDecision, ToolTerminal, TurnRecord, TurnTerminal, activeCommand, activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, frameworkReducedStateReducerSchemaVersion, initialReducedState, pendingCommands, pendingStopCommand, reduceCommittedEvents, reducedStateCheckpointEventSeqs };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { TokenConsumptionState } from "./model-usage.js";
|
|
2
|
-
import { a as encodeReducedStateCheckpoint, c as frameworkReducedStateReducerSchemaVersion, d as pendingStopCommand, f as reduceCommittedEvents, i as decodeReducedStateCheckpoint, l as initialReducedState, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName, t as activeCommand, u as pendingCommands } from "../reduced-state-
|
|
2
|
+
import { a as encodeReducedStateCheckpoint, c as frameworkReducedStateReducerSchemaVersion, d as pendingStopCommand, f as reduceCommittedEvents, i as decodeReducedStateCheckpoint, l as initialReducedState, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName, t as activeCommand, u as pendingCommands } from "../reduced-state-Vuud6LCM.js";
|
|
3
3
|
export { TokenConsumptionState, activeCommand, activeTurnIdentityForCommand, classifyRecoverableWork, decodeReducedStateCheckpoint, encodeReducedStateCheckpoint, foldReducedState, frameworkReducedStateReducerName, frameworkReducedStateReducerSchemaVersion, initialReducedState, pendingCommands, pendingStopCommand, reduceCommittedEvents, reducedStateCheckpointEventSeqs };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Bt as RunSchedulingCancellationPlan, Ft as DeferredRunResolution, Gt as canGrantRun, Ht as RunSchedulingRequest, It as LocalRunResolution, Jt as runSchedulingInputMessageIds, Kt as planRunSchedulingCancellation, Lt as RunGrantResult, Rt as RunRequestOutcome, Ut as RunSchedulingRequestRecord, Vt as RunSchedulingInput, Wt as RunSchedulingWork, Yt as waitingRunControl, qt as planWaitingRunInterruption, zt as RunResolution } from "../reduced-state-
|
|
1
|
+
import { Bt as RunSchedulingCancellationPlan, Ft as DeferredRunResolution, Gt as canGrantRun, Ht as RunSchedulingRequest, It as LocalRunResolution, Jt as runSchedulingInputMessageIds, Kt as planRunSchedulingCancellation, Lt as RunGrantResult, Rt as RunRequestOutcome, Ut as RunSchedulingRequestRecord, Vt as RunSchedulingInput, Wt as RunSchedulingWork, Yt as waitingRunControl, qt as planWaitingRunInterruption, zt as RunResolution } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
export { DeferredRunResolution, LocalRunResolution, RunGrantResult, RunRequestOutcome, RunResolution, RunSchedulingCancellationPlan, RunSchedulingInput, RunSchedulingRequest, RunSchedulingRequestRecord, RunSchedulingWork, canGrantRun, planRunSchedulingCancellation, planWaitingRunInterruption, runSchedulingInputMessageIds, waitingRunControl };
|
|
@@ -5,7 +5,8 @@ import { _ as UsagePayload, b as schemaV1, c as ForeignDurableEvent, f as Provid
|
|
|
5
5
|
import { EDACommand, UserMessageContent } from "./types/commands.js";
|
|
6
6
|
import * as Effect from "effect/Effect";
|
|
7
7
|
import * as Schema from "effect/Schema";
|
|
8
|
-
import * as Prompt from "effect/
|
|
8
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
9
|
+
import * as Exit from "effect/Exit";
|
|
9
10
|
//#region src/types/events/internal.ts
|
|
10
11
|
/** Build a built-in durable event schema from its fixed event type and payload schema. */
|
|
11
12
|
const durableEventSchema = (type, payload) => Schema.Struct({
|
|
@@ -23,6 +24,66 @@ const ephemeralEventSchema = (type, payload) => Schema.Struct({
|
|
|
23
24
|
schemaVersion: Schema.Literal(schemaV1),
|
|
24
25
|
payload
|
|
25
26
|
});
|
|
27
|
+
const isPlainRecord = (value) => {
|
|
28
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
29
|
+
const prototype = Object.getPrototypeOf(value);
|
|
30
|
+
return prototype === Object.prototype || prototype === null;
|
|
31
|
+
};
|
|
32
|
+
/** Own data property, including a literal `__proto__` key from JSON, without touching prototypes. */
|
|
33
|
+
const setOwn = (target, key, value) => {
|
|
34
|
+
Object.defineProperty(target, key, {
|
|
35
|
+
configurable: true,
|
|
36
|
+
enumerable: true,
|
|
37
|
+
value,
|
|
38
|
+
writable: true
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
/** Whether a decode dropped any input key. Values returned by reference were not reshaped. */
|
|
42
|
+
const droppedKeys = (input, decoded) => {
|
|
43
|
+
if (input === decoded) return false;
|
|
44
|
+
if (Array.isArray(input) && Array.isArray(decoded)) return input.some((item, index) => droppedKeys(item, decoded[index]));
|
|
45
|
+
if (!isPlainRecord(input) || !isPlainRecord(decoded)) return false;
|
|
46
|
+
return Object.keys(input).some((key) => !Object.hasOwn(decoded, key) || droppedKeys(input[key], decoded[key]));
|
|
47
|
+
};
|
|
48
|
+
/** The schema's encoding of this subtree when it has the input's container shape. */
|
|
49
|
+
const sameShape = (input, encoded) => Array.isArray(input) && Array.isArray(encoded) || isPlainRecord(input) && isPlainRecord(encoded) ? encoded : void 0;
|
|
50
|
+
/**
|
|
51
|
+
* Re-attach input properties the schema does not model. A key is unknown when the schema's own
|
|
52
|
+
* encoding lacks it, so keys consumed by renaming transformations stay consumed. Where no encoding
|
|
53
|
+
* of the same shape is available, such as a union member that encodes to a string, a key is
|
|
54
|
+
* unknown when the decoded value lacks it. Only subtrees that dropped a key are copied.
|
|
55
|
+
*/
|
|
56
|
+
const retainUnknown = (input, encoded, decoded) => {
|
|
57
|
+
if (!droppedKeys(input, decoded)) return decoded;
|
|
58
|
+
const known = sameShape(input, encoded);
|
|
59
|
+
if (Array.isArray(input) && Array.isArray(decoded) && input.length === decoded.length) {
|
|
60
|
+
const items = Array.isArray(known) ? known : [];
|
|
61
|
+
return Object.assign([], decoded, decoded.map((item, index) => retainUnknown(input[index], items[index], item)));
|
|
62
|
+
}
|
|
63
|
+
if (!isPlainRecord(input) || !isPlainRecord(decoded)) return decoded;
|
|
64
|
+
const modelled = isPlainRecord(known) ? known : decoded;
|
|
65
|
+
const unknown = {};
|
|
66
|
+
const retained = {};
|
|
67
|
+
for (const key of Object.keys(input)) if (!Object.hasOwn(modelled, key)) setOwn(unknown, key, input[key]);
|
|
68
|
+
else if (Object.hasOwn(decoded, key)) setOwn(retained, key, retainUnknown(input[key], modelled[key], decoded[key]));
|
|
69
|
+
return Object.assign(unknown, decoded, retained);
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Effect 4 removed `onExcessProperty: "preserve"`. Durable facts written by other framework or
|
|
73
|
+
* application versions must still re-encode at persistence and protocol boundaries without losing
|
|
74
|
+
* fields, so decode with the default policy and re-attach what the schema does not model. The
|
|
75
|
+
* extra encode runs only when the decode dropped a key; decode-only schemas use decoded keys.
|
|
76
|
+
*/
|
|
77
|
+
const decodeRetainingExcess = (schema) => {
|
|
78
|
+
const decode = Schema.decodeUnknownSync(schema);
|
|
79
|
+
const encode = Schema.encodeUnknownExit(schema);
|
|
80
|
+
return (input) => {
|
|
81
|
+
const decoded = decode(input);
|
|
82
|
+
if (!droppedKeys(input, decoded)) return decoded;
|
|
83
|
+
const encoded = encode(decoded);
|
|
84
|
+
return retainUnknown(input, Exit.isSuccess(encoded) ? encoded.value : void 0, decoded);
|
|
85
|
+
};
|
|
86
|
+
};
|
|
26
87
|
//#endregion
|
|
27
88
|
//#region src/types/events/durable.ts
|
|
28
89
|
/** Establishes a session's execution policy before its first run; not a model-switch operation. */
|
|
@@ -678,6 +739,8 @@ const CurrentEDADurableEvent = Schema.Union([
|
|
|
678
739
|
const EDADurableEvent = Schema.Union([LegacyAttemptEvent, CurrentEDADurableEvent]);
|
|
679
740
|
/** Current V1 framework durable event schema. Future versions route beside this alias. */
|
|
680
741
|
const EDADurableEventV1 = EDADurableEvent;
|
|
742
|
+
/** Framework facts from other EDA versions keep payload fields this version does not model. */
|
|
743
|
+
const decodeEDADurableEventV1 = decodeRetainingExcess(EDADurableEventV1);
|
|
681
744
|
/** Decode one framework-owned durable event through the namespace/type/version router. */
|
|
682
745
|
const decodeUnknownEDADurableEventSync = (input) => {
|
|
683
746
|
return decodeFrameworkEnvelope(Schema.decodeUnknownSync(DurableEventEnvelope)(input));
|
|
@@ -685,7 +748,7 @@ const decodeUnknownEDADurableEventSync = (input) => {
|
|
|
685
748
|
const decodeFrameworkEnvelope = (envelope) => {
|
|
686
749
|
if (envelope.namespace !== "effect-durable-agent") throw new Error(`EDADurableEvent decoder only accepts namespace ${effectDurableAgentNamespace}; received ${envelope.namespace}`);
|
|
687
750
|
switch (envelope.schemaVersion) {
|
|
688
|
-
case schemaV1: return
|
|
751
|
+
case schemaV1: return decodeEDADurableEventV1(envelope);
|
|
689
752
|
default: throw new Error(`Unsupported EDA durable event schemaVersion ${envelope.schemaVersion} for ${envelope.type}`);
|
|
690
753
|
}
|
|
691
754
|
};
|
|
@@ -711,6 +774,6 @@ const decodeDurableEventSync = (input) => {
|
|
|
711
774
|
};
|
|
712
775
|
};
|
|
713
776
|
//#endregion
|
|
714
|
-
export { LegacyAttemptEvent as $, pendingMessagesPausedEventType as $n, ToolCallRejectedPayload as $t, CompactionFailedEvent as A, baseStateCreatedEventType as An, SessionConfiguredEvent as At, ContextRebasedPayload as B, compactionRequestedEventType as Bn, SummaryCreatedEvent as Bt, CommandEvent as C, UserMessagePromotedEvent as Cn, turnStartedEventType as Cr, RunSchedulingGrantedPayload as Ct, CommandStartedPayload as D, assistantMessageCommittedEventType as Dn, userMessagePromotedEventType as Dr, RunSchedulingRequestedPayload as Dt, CommandStartedEvent as E, UserMessageSubmittedPayload as En, userMessageCommittedEventType as Er, RunSchedulingRequestedEvent as Et, CompactionStartedPayload as F, commandCompletedEventType as Fn, StopControlEvent as Ft, InferenceCompletedEvent as G, decodeUnknownEDADurableEvent as Gn, ToolCallCompletedPayload as Gt, DecodedDurableEvent as H, contextProjectedEventType as Hn, SystemMessageCommittedEvent as Ht, ContextAndCompactionEvent as I, commandFailedEventType as In, StopTurnAppliedEvent as It, InferenceFailedEvent as J, inferenceCompletedEventType as Jn, ToolCallEvent as Jt, InferenceCompletedPayload as K, decodeUnknownEDADurableEventSync as Kn, ToolCallCreatedEvent as Kt, ContextProjectedEvent as L, commandStartedEventType as Ln, StopTurnAppliedPayload as Lt, CompactionRequestedEvent as M, baseStateRequestedEventType as Mn, SteeringMessageCancelledPayload as Mt, CompactionRequestedPayload as N, commandAdmittedEventType as Nn, SteeringMessageQueuedEvent as Nt, CompactionCompletedEvent as O, assistantMessageImportedEventType as On, userMessageSubmittedEventType as Or, RunStartedEvent as Ot, CompactionStartedEvent as P, commandCancelledEventType as Pn, SteeringMessageQueuedPayload as Pt, LegacyAssistantMessageCommittedEvent as Q, messageQueuePausedEventType as Qn, ToolCallRejectedEvent as Qt, ContextProjectedPayload as R, compactionCompletedEventType as Rn, StopTurnRequestedEvent as Rt, CommandCompletedPayload as S, UserMessageDisposition as Sn, turnFailedEventType as Sr, RunSchedulingGrantedEvent as St, CommandFailedPayload as T, UserMessageSubmittedEvent as Tn, userMessageCancelledEventType as Tr, RunSchedulingInvalidatedPayload as Tt, EDADurableEvent as U, contextRebasedEventType as Un, SystemMessageCommittedPayload as Ut, CurrentEDADurableEvent as V, compactionStartedEventType as Vn, SummaryCreatedPayload as Vt, EDADurableEventV1 as W, decodeDurableEventSync as Wn, ToolCallCompletedEvent as Wt, InferenceStartedEvent as X, inferenceStartedEventType as Xn, ToolCallFailedPayload as Xt, InferenceFailedPayload as Y, inferenceFailedEventType as Yn, ToolCallFailedEvent as Yt, InferenceStartedPayload as Z, interpretLegacyAttemptForReduction as Zn, ToolCallPromptPart as Zt, CommandAdmittedEvent as _, UserMessageCancellationReason as _n, toolCallCreatedEventType as _r, RunInterruptedEvent as _t, AssistantMessageImportedPayload as a, ToolPromptPart as an, runSchedulingGrantedEventType as ar, MessageQueuePausedPayload as at, CommandCancelledPayload as b, UserMessageCommittedEvent as bn, toolCallStartedEventType as br, RunSchedulingDeliveredPayload as bt, AssistantPromptPart as c, TurnCompletedEvent as cn, runStartedEventType as cr, RecoveryCompletedEvent as ct, BaseStateCreatedPayload as d, TurnFailedEvent as dn, steeringMessageQueuedEventType as dr, RecoveryEvent as dt, ToolCallRejectionFeedback as en, recoveryCompletedEventType as er, LegacyToolCallCreatedEvent as et, BaseStateEvent as f, TurnFailedPayload as fn, stopTurnAppliedEventType as fr, RunCompletedEvent as ft, BaseStateRequestedPayload as g, TurnStoppedPayload as gn, toolCallCompletedEventType as gr, RunFailedPayload as gt, BaseStateRequestedEvent as h, TurnStoppedEvent as hn, systemMessageCommittedEventType as hr, RunFailedEvent as ht, AssistantMessageImportedEvent as i, ToolFailurePromptPart as in, runSchedulingDeliveredEventType as ir, MessageQueuePausedEvent as it, CompactionFailedPayload as j, baseStateFailedEventType as jn, SteeringMessageCancelledEvent as jt, CompactionCompletedPayload as k, assistantPartialCommittedEventType as kn,
|
|
777
|
+
export { LegacyAttemptEvent as $, pendingMessagesPausedEventType as $n, ToolCallRejectedPayload as $t, CompactionFailedEvent as A, baseStateCreatedEventType as An, ephemeralEventSchema as Ar, SessionConfiguredEvent as At, ContextRebasedPayload as B, compactionRequestedEventType as Bn, SummaryCreatedEvent as Bt, CommandEvent as C, UserMessagePromotedEvent as Cn, turnStartedEventType as Cr, RunSchedulingGrantedPayload as Ct, CommandStartedPayload as D, assistantMessageCommittedEventType as Dn, userMessagePromotedEventType as Dr, RunSchedulingRequestedPayload as Dt, CommandStartedEvent as E, UserMessageSubmittedPayload as En, userMessageCommittedEventType as Er, RunSchedulingRequestedEvent as Et, CompactionStartedPayload as F, commandCompletedEventType as Fn, StopControlEvent as Ft, InferenceCompletedEvent as G, decodeUnknownEDADurableEvent as Gn, ToolCallCompletedPayload as Gt, DecodedDurableEvent as H, contextProjectedEventType as Hn, SystemMessageCommittedEvent as Ht, ContextAndCompactionEvent as I, commandFailedEventType as In, StopTurnAppliedEvent as It, InferenceFailedEvent as J, inferenceCompletedEventType as Jn, ToolCallEvent as Jt, InferenceCompletedPayload as K, decodeUnknownEDADurableEventSync as Kn, ToolCallCreatedEvent as Kt, ContextProjectedEvent as L, commandStartedEventType as Ln, StopTurnAppliedPayload as Lt, CompactionRequestedEvent as M, baseStateRequestedEventType as Mn, SteeringMessageCancelledPayload as Mt, CompactionRequestedPayload as N, commandAdmittedEventType as Nn, SteeringMessageQueuedEvent as Nt, CompactionCompletedEvent as O, assistantMessageImportedEventType as On, userMessageSubmittedEventType as Or, RunStartedEvent as Ot, CompactionStartedEvent as P, commandCancelledEventType as Pn, SteeringMessageQueuedPayload as Pt, LegacyAssistantMessageCommittedEvent as Q, messageQueuePausedEventType as Qn, ToolCallRejectedEvent as Qt, ContextProjectedPayload as R, compactionCompletedEventType as Rn, StopTurnRequestedEvent as Rt, CommandCompletedPayload as S, UserMessageDisposition as Sn, turnFailedEventType as Sr, RunSchedulingGrantedEvent as St, CommandFailedPayload as T, UserMessageSubmittedEvent as Tn, userMessageCancelledEventType as Tr, RunSchedulingInvalidatedPayload as Tt, EDADurableEvent as U, contextRebasedEventType as Un, SystemMessageCommittedPayload as Ut, CurrentEDADurableEvent as V, compactionStartedEventType as Vn, SummaryCreatedPayload as Vt, EDADurableEventV1 as W, decodeDurableEventSync as Wn, ToolCallCompletedEvent as Wt, InferenceStartedEvent as X, inferenceStartedEventType as Xn, ToolCallFailedPayload as Xt, InferenceFailedPayload as Y, inferenceFailedEventType as Yn, ToolCallFailedEvent as Yt, InferenceStartedPayload as Z, interpretLegacyAttemptForReduction as Zn, ToolCallPromptPart as Zt, CommandAdmittedEvent as _, UserMessageCancellationReason as _n, toolCallCreatedEventType as _r, RunInterruptedEvent as _t, AssistantMessageImportedPayload as a, ToolPromptPart as an, runSchedulingGrantedEventType as ar, MessageQueuePausedPayload as at, CommandCancelledPayload as b, UserMessageCommittedEvent as bn, toolCallStartedEventType as br, RunSchedulingDeliveredPayload as bt, AssistantPromptPart as c, TurnCompletedEvent as cn, runStartedEventType as cr, RecoveryCompletedEvent as ct, BaseStateCreatedPayload as d, TurnFailedEvent as dn, steeringMessageQueuedEventType as dr, RecoveryEvent as dt, ToolCallRejectionFeedback as en, recoveryCompletedEventType as er, LegacyToolCallCreatedEvent as et, BaseStateEvent as f, TurnFailedPayload as fn, stopTurnAppliedEventType as fr, RunCompletedEvent as ft, BaseStateRequestedPayload as g, TurnStoppedPayload as gn, toolCallCompletedEventType as gr, RunFailedPayload as gt, BaseStateRequestedEvent as h, TurnStoppedEvent as hn, systemMessageCommittedEventType as hr, RunFailedEvent as ht, AssistantMessageImportedEvent as i, ToolFailurePromptPart as in, runSchedulingDeliveredEventType as ir, MessageQueuePausedEvent as it, CompactionFailedPayload as j, baseStateFailedEventType as jn, SteeringMessageCancelledEvent as jt, CompactionCompletedPayload as k, assistantPartialCommittedEventType as kn, decodeRetainingExcess as kr, RunStartedPayload as kt, AssistantPromptParts as l, TurnCompletedPayload as ln, sessionConfiguredEventType as lr, RecoveryCompletedPayload as lt, BaseStateFailedPayload as m, TurnStartedPayload as mn, summaryCreatedEventType as mr, RunEvent as mt, AssistantMessageCommittedPayload as n, ToolCallStartedEvent as nn, runFailedEventType as nr, LegacyTurnAttemptStartedEvent as nt, AssistantPartialCommittedEvent as o, ToolRejectionPromptPart as on, runSchedulingInvalidatedEventType as or, PendingMessagesPausedEvent as ot, BaseStateFailedEvent as p, TurnStartedEvent as pn, stopTurnRequestedEventType as pr, RunCompletedPayload as pt, InferenceEvent as q, durableEventEnvelope as qn, ToolCallCreatedPayload as qt, AssistantMessageContent as r, ToolCallStartedPayload as rn, runInterruptedEventType as rr, MessageEvent as rt, AssistantPartialCommittedPayload as s, ToolSuccessPromptPart as sn, runSchedulingRequestedEventType as sr, PendingMessagesPausedPayload as st, AssistantMessageCommittedEvent as t, ToolCallRejectionReason as tn, runCompletedEventType as tr, LegacyTurnAttemptCompletedEvent as tt, BaseStateCreatedEvent as u, TurnEvent as un, steeringMessageCancelledEventType as ur, RecoveryContinuation as ut, CommandAdmittedPayload as v, UserMessageCancelledEvent as vn, toolCallFailedEventType as vr, RunInterruptedPayload as vt, CommandFailedEvent as w, UserMessagePromotedPayload as wn, turnStoppedEventType as wr, RunSchedulingInvalidatedEvent as wt, CommandCompletedEvent as x, UserMessageCommittedPayload as xn, turnCompletedEventType as xr, RunSchedulingEvent as xt, CommandCancelledEvent as y, UserMessageCancelledPayload as yn, toolCallRejectedEventType as yr, RunSchedulingDeliveredEvent as yt, ContextRebasedEvent as z, compactionFailedEventType as zn, StopTurnRequestedPayload as zt };
|
|
715
778
|
|
|
716
|
-
//# sourceMappingURL=durable-
|
|
779
|
+
//# sourceMappingURL=durable-CD__3ztN.js.map
|