effect-durable-agent 0.1.0-alpha.23 → 0.1.0-alpha.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/delivery-Bb7pkQ9o.js +507 -0
  2. package/dist/delivery-Bb7pkQ9o.js.map +1 -0
  3. package/dist/delivery-o6sDIiwO.d.ts +2990 -0
  4. package/dist/in-memory-IgxnTbGb.js +150 -0
  5. package/dist/in-memory-IgxnTbGb.js.map +1 -0
  6. package/dist/{window-read-BDayZf7O.js → interpreter-BdRoYrfL.js} +94 -206
  7. package/dist/interpreter-BdRoYrfL.js.map +1 -0
  8. package/dist/services/reducer-registry.js +1 -1
  9. package/dist/services/runtime-layer.js +3 -3
  10. package/dist/services/runtime.js +1 -1
  11. package/dist/services/session-query.js +2 -2
  12. package/dist/services/session-state.js +1 -1
  13. package/dist/services/session-store.js +271 -1
  14. package/dist/services/session-store.js.map +1 -0
  15. package/dist/services/sink-registry.js +1 -1
  16. package/dist/{session-state-C6SyphC0.js → session-state-BW0l2aNk.js} +3 -3
  17. package/dist/{session-state-C6SyphC0.js.map → session-state-BW0l2aNk.js.map} +1 -1
  18. package/dist/{sink-registry-DtrssBxF.js → sink-registry-D0MetcNq.js} +2 -2
  19. package/dist/{sink-registry-DtrssBxF.js.map → sink-registry-D0MetcNq.js.map} +1 -1
  20. package/dist/{subscription-g5W0Ggqx.js → subscription-Dzr5LqPX.js} +5 -3
  21. package/dist/subscription-Dzr5LqPX.js.map +1 -0
  22. package/dist/testkit/layers.d.ts +8 -2
  23. package/dist/testkit/layers.js +7 -3
  24. package/dist/testkit/layers.js.map +1 -1
  25. package/dist/testkit/transcript.d.ts +226 -0
  26. package/dist/testkit/transcript.js +1475 -0
  27. package/dist/testkit/transcript.js.map +1 -0
  28. package/dist/transcript.d.ts +25 -101
  29. package/dist/transcript.js +4 -3
  30. package/dist/transcript.js.map +1 -1
  31. package/dist/websocket/events.d.ts +2 -0
  32. package/dist/websocket/events.js +2 -0
  33. package/dist/websocket.d.ts +1 -2986
  34. package/dist/websocket.js +3 -504
  35. package/dist/websocket.js.map +1 -1
  36. package/dist/window-read-DBf1Iktt.d.ts +104 -0
  37. package/dist/window-read-U55aAeuz.js +184 -0
  38. package/dist/window-read-U55aAeuz.js.map +1 -0
  39. package/package.json +9 -1
  40. package/dist/session-store-DuEhcqIC.js +0 -414
  41. package/dist/session-store-DuEhcqIC.js.map +0 -1
  42. package/dist/subscription-g5W0Ggqx.js.map +0 -1
  43. package/dist/window-read-BDayZf7O.js.map +0 -1
@@ -0,0 +1,150 @@
1
+ import { SequenceNumber } from "./types/core.js";
2
+ import { t as planTranscriptBatch } from "./interpreter-BdRoYrfL.js";
3
+ import { E as TranscriptOrder, G as isTopLevelTranscriptRecord, W as isPendingTranscriptUserRecord } from "./records-DWKEjuqb.js";
4
+ //#region src/transcript/in-memory.ts
5
+ const aliasKey = (namespace, key) => `${namespace}\u0000${key}`;
6
+ /** The carried definition for a stored version, if this release still carries it. */
7
+ const carriedTranscriptDefinition = (config, version) => config.current.version === version ? config.current : config.previous?.version === version ? config.previous : void 0;
8
+ /** An empty version before any event is projected. */
9
+ const emptyTranscriptVersion = (version, role) => ({
10
+ meta: {
11
+ version,
12
+ role,
13
+ cursor: SequenceNumber.make(0),
14
+ status: { _tag: "Ok" }
15
+ },
16
+ records: /* @__PURE__ */ new Map(),
17
+ aliases: /* @__PURE__ */ new Map(),
18
+ ordinals: /* @__PURE__ */ new Map()
19
+ });
20
+ const lookupOf = (version) => ({
21
+ cursor: version.meta.cursor,
22
+ record: (id) => version.records.get(id),
23
+ alias: (namespace, key) => version.aliases.get(aliasKey(namespace, key)),
24
+ nextOrdinal: (anchorSeq) => version.ordinals.get(anchorSeq) ?? 0
25
+ });
26
+ const applyPlan = (version, plan) => {
27
+ const records = new Map(version.records);
28
+ const aliases = new Map(version.aliases);
29
+ const ordinals = new Map(version.ordinals);
30
+ for (const record of plan.records) {
31
+ records.set(record.id, record);
32
+ if ("position" in record && record.position !== void 0) {
33
+ const { anchorSeq, ordinal } = record.position;
34
+ ordinals.set(anchorSeq, Math.max(ordinals.get(anchorSeq) ?? 0, ordinal + 1));
35
+ }
36
+ }
37
+ for (const alias of plan.aliases) {
38
+ const key = aliasKey(alias.namespace, alias.key);
39
+ if (!aliases.has(key)) aliases.set(key, alias.recordId);
40
+ }
41
+ return {
42
+ meta: {
43
+ ...version.meta,
44
+ cursor: plan.throughSeq
45
+ },
46
+ records,
47
+ aliases,
48
+ ordinals
49
+ };
50
+ };
51
+ /**
52
+ * Project committed events into one version, or freeze it.
53
+ *
54
+ * A projection failure marks only this version failed at its unchanged cursor and leaves its
55
+ * rows exactly as they were, so it remains a consistent last-good cut.
56
+ */
57
+ const advanceTranscriptVersion = (version, definition, committed) => {
58
+ const fresh = committed.filter((entry) => entry.position.seq > version.meta.cursor);
59
+ const first = fresh[0];
60
+ if (first === void 0 || version.meta.status._tag === "Failed") return version;
61
+ try {
62
+ return applyPlan(version, planTranscriptBatch(lookupOf(version), fresh, definition));
63
+ } catch (error) {
64
+ return {
65
+ ...version,
66
+ meta: {
67
+ ...version.meta,
68
+ status: {
69
+ _tag: "Failed",
70
+ failedAtSeq: first.position.seq,
71
+ error: error instanceof Error ? error.message : String(error)
72
+ }
73
+ }
74
+ };
75
+ }
76
+ };
77
+ /** Maintain every carried, healthy version for a committed append; others stay frozen. */
78
+ const maintainTranscripts = (state, committed) => ({
79
+ ...state,
80
+ versions: state.versions.map((version) => {
81
+ const definition = carriedTranscriptDefinition(state.config, version.meta.version);
82
+ return definition === void 0 ? version : advanceTranscriptVersion(version, definition, committed);
83
+ })
84
+ });
85
+ /**
86
+ * Converge a session to the current definition, as the adapter's builder does in slices.
87
+ *
88
+ * A building version that is not `current` is discarded. If the active version is not `current`,
89
+ * `current` is built from the log (never from old rows) and, once it reaches the head, becomes
90
+ * active and the old version is deleted. A failed build leaves the active version serving; only a
91
+ * new definition repairs it. A brand-new log simply initializes `current`.
92
+ */
93
+ const convergeTranscripts = (state, log) => {
94
+ const current = state.config.current;
95
+ const versions = state.versions.filter((version) => version.meta.role === "active" || version.meta.version === current.version);
96
+ if (versions.find((version) => version.meta.role === "active")?.meta.version === current.version) return {
97
+ ...state,
98
+ versions
99
+ };
100
+ const building = versions.find((version) => version.meta.role === "building") ?? emptyTranscriptVersion(current.version, "building");
101
+ const built = advanceTranscriptVersion(building, current, log);
102
+ if (built.meta.status._tag === "Failed") return {
103
+ ...state,
104
+ versions: [...versions.filter((version) => version !== building), built]
105
+ };
106
+ return {
107
+ ...state,
108
+ versions: [{
109
+ ...built,
110
+ meta: {
111
+ ...built.meta,
112
+ role: "active"
113
+ }
114
+ }]
115
+ };
116
+ };
117
+ /** Initial transcript state for a store whose log already holds `log`. */
118
+ const initialTranscriptState = (incarnation, config, log) => convergeTranscripts({
119
+ incarnation,
120
+ config,
121
+ versions: []
122
+ }, log);
123
+ const topLevelOrder = (record) => ({
124
+ anchorSeq: record.position?.anchorSeq ?? 0,
125
+ ordinal: record.position?.ordinal ?? 0,
126
+ recordId: record.id
127
+ });
128
+ /** Window reads over the active version, or undefined while nothing is servable. */
129
+ const inMemoryTranscriptWindowSource = (state) => {
130
+ const active = state.versions.find((version) => version.meta.role === "active");
131
+ if (active === void 0) return void 0;
132
+ const records = Array.from(active.records.values());
133
+ const ordered = records.filter(isTopLevelTranscriptRecord).sort((left, right) => TranscriptOrder(topLevelOrder(left), topLevelOrder(right)));
134
+ const compare = (record, key) => TranscriptOrder(topLevelOrder(record), key);
135
+ return {
136
+ incarnation: state.incarnation,
137
+ meta: active.meta,
138
+ carried: carriedTranscriptDefinition(state.config, active.meta.version) !== void 0,
139
+ topLevelBefore: (key, limit, inclusive) => ordered.filter((record) => key === void 0 || (inclusive ? compare(record, key) <= 0 : compare(record, key) < 0)).reverse().slice(0, limit),
140
+ topLevelAfter: (key, limit, inclusive) => ordered.filter((record) => key === void 0 || (inclusive ? compare(record, key) >= 0 : compare(record, key) > 0)).slice(0, limit),
141
+ record: (id) => active.records.get(id),
142
+ alias: (namespace, key) => active.aliases.get(aliasKey(namespace, key)),
143
+ toolsOf: (assistantId) => records.flatMap((record) => record.kind === "tool" && record.assistantId === assistantId ? [record] : []),
144
+ pendingUsers: () => records.filter(isPendingTranscriptUserRecord)
145
+ };
146
+ };
147
+ //#endregion
148
+ export { maintainTranscripts as a, initialTranscriptState as i, emptyTranscriptVersion as n, inMemoryTranscriptWindowSource as r, advanceTranscriptVersion as t };
149
+
150
+ //# sourceMappingURL=in-memory-IgxnTbGb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory-IgxnTbGb.js","names":[],"sources":["../src/transcript/in-memory.ts"],"sourcesContent":["import type { CommittedDurableEvent } from \"../services/session-store\";\nimport { SequenceNumber } from \"../types/core\";\nimport { planTranscriptBatch } from \"./interpreter\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type { TranscriptAliasNamespace, TranscriptChangePlan, TranscriptLookup } from \"./plan\";\nimport {\n TranscriptOrder,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptTopLevelRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport type { TranscriptMaintenanceConfig } from \"./store\";\nimport type { TranscriptVersionMeta } from \"./window\";\nimport type { TranscriptWindowSource } from \"./window-read\";\n\n/**\n * The in-memory store's transcript state: the semantic model of the adapter's tables\n * (`transcript_records`, `transcript_aliases`, `transcript_meta`), kept inside the store's\n * `Ref.modify` critical section so maintenance commits atomically with the appended events.\n */\nexport interface InMemoryTranscriptVersion {\n readonly meta: TranscriptVersionMeta;\n readonly records: ReadonlyMap<TranscriptRecordId, TranscriptRecord>;\n readonly aliases: ReadonlyMap<string, TranscriptRecordId>;\n readonly ordinals: ReadonlyMap<number, number>;\n}\n\nexport interface InMemoryTranscriptState {\n readonly incarnation: TranscriptLogIncarnation;\n readonly config: TranscriptMaintenanceConfig;\n readonly versions: ReadonlyArray<InMemoryTranscriptVersion>;\n}\n\nconst aliasKey = (namespace: TranscriptAliasNamespace, key: string) => `${namespace}\\u0000${key}`;\n\n/** The carried definition for a stored version, if this release still carries it. */\nexport const carriedTranscriptDefinition = (\n config: TranscriptMaintenanceConfig,\n version: TranscriptVersion,\n): TranscriptDefinition | undefined =>\n config.current.version === version\n ? config.current\n : config.previous?.version === version\n ? config.previous\n : undefined;\n\n/** An empty version before any event is projected. */\nexport const emptyTranscriptVersion = (\n version: TranscriptVersion,\n role: TranscriptVersionMeta[\"role\"],\n): InMemoryTranscriptVersion => ({\n meta: { version, role, cursor: SequenceNumber.make(0), status: { _tag: \"Ok\" } },\n records: new Map(),\n aliases: new Map(),\n ordinals: new Map(),\n});\n\nconst lookupOf = (version: InMemoryTranscriptVersion): TranscriptLookup => ({\n cursor: version.meta.cursor,\n record: (id) => version.records.get(id),\n alias: (namespace, key) => version.aliases.get(aliasKey(namespace, key)),\n nextOrdinal: (anchorSeq) => version.ordinals.get(anchorSeq) ?? 0,\n});\n\nconst applyPlan = (\n version: InMemoryTranscriptVersion,\n plan: TranscriptChangePlan,\n): InMemoryTranscriptVersion => {\n const records = new Map(version.records);\n const aliases = new Map(version.aliases);\n const ordinals = new Map(version.ordinals);\n for (const record of plan.records) {\n records.set(record.id, record);\n if (\"position\" in record && record.position !== undefined) {\n const { anchorSeq, ordinal } = record.position;\n ordinals.set(anchorSeq, Math.max(ordinals.get(anchorSeq) ?? 0, ordinal + 1));\n }\n }\n for (const alias of plan.aliases) {\n const key = aliasKey(alias.namespace, alias.key);\n if (!aliases.has(key)) aliases.set(key, alias.recordId);\n }\n return { meta: { ...version.meta, cursor: plan.throughSeq }, records, aliases, ordinals };\n};\n\n/**\n * Project committed events into one version, or freeze it.\n *\n * A projection failure marks only this version failed at its unchanged cursor and leaves its\n * rows exactly as they were, so it remains a consistent last-good cut.\n */\nexport const advanceTranscriptVersion = (\n version: InMemoryTranscriptVersion,\n definition: TranscriptDefinition,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptVersion => {\n const fresh = committed.filter((entry) => entry.position.seq > version.meta.cursor);\n const first = fresh[0];\n if (first === undefined || version.meta.status._tag === \"Failed\") return version;\n try {\n return applyPlan(version, planTranscriptBatch(lookupOf(version), fresh, definition));\n } catch (error) {\n return {\n ...version,\n meta: {\n ...version.meta,\n status: {\n _tag: \"Failed\",\n failedAtSeq: first.position.seq,\n error: error instanceof Error ? error.message : String(error),\n },\n },\n };\n }\n};\n\n/** Maintain every carried, healthy version for a committed append; others stay frozen. */\nexport const maintainTranscripts = (\n state: InMemoryTranscriptState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => ({\n ...state,\n versions: state.versions.map((version) => {\n const definition = carriedTranscriptDefinition(state.config, version.meta.version);\n return definition === undefined\n ? version\n : advanceTranscriptVersion(version, definition, committed);\n }),\n});\n\n/**\n * Converge a session to the current definition, as the adapter's builder does in slices.\n *\n * A building version that is not `current` is discarded. If the active version is not `current`,\n * `current` is built from the log (never from old rows) and, once it reaches the head, becomes\n * active and the old version is deleted. A failed build leaves the active version serving; only a\n * new definition repairs it. A brand-new log simply initializes `current`.\n */\nexport const convergeTranscripts = (\n state: InMemoryTranscriptState,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => {\n const current = state.config.current;\n const versions = state.versions.filter(\n (version) => version.meta.role === \"active\" || version.meta.version === current.version,\n );\n const active = versions.find((version) => version.meta.role === \"active\");\n if (active?.meta.version === current.version) return { ...state, versions };\n\n const building =\n versions.find((version) => version.meta.role === \"building\") ??\n emptyTranscriptVersion(current.version, \"building\");\n const built = advanceTranscriptVersion(building, current, log);\n if (built.meta.status._tag === \"Failed\") {\n return { ...state, versions: [...versions.filter((version) => version !== building), built] };\n }\n return { ...state, versions: [{ ...built, meta: { ...built.meta, role: \"active\" } }] };\n};\n\n/** Initial transcript state for a store whose log already holds `log`. */\nexport const initialTranscriptState = (\n incarnation: TranscriptLogIncarnation,\n config: TranscriptMaintenanceConfig,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => convergeTranscripts({ incarnation, config, versions: [] }, log);\n\nconst topLevelOrder = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\n/** Window reads over the active version, or undefined while nothing is servable. */\nexport const inMemoryTranscriptWindowSource = (\n state: InMemoryTranscriptState,\n): TranscriptWindowSource | undefined => {\n const active = state.versions.find((version) => version.meta.role === \"active\");\n if (active === undefined) return undefined;\n const records = Array.from(active.records.values());\n const ordered = records\n .filter(isTopLevelTranscriptRecord)\n .sort((left, right) => TranscriptOrder(topLevelOrder(left), topLevelOrder(right)));\n const compare = (record: TranscriptTopLevelRecord, key: TranscriptOrderKey) =>\n TranscriptOrder(topLevelOrder(record), key);\n return {\n incarnation: state.incarnation,\n meta: active.meta,\n carried: carriedTranscriptDefinition(state.config, active.meta.version) !== undefined,\n topLevelBefore: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) <= 0 : compare(record, key) < 0),\n )\n .reverse()\n .slice(0, limit),\n topLevelAfter: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) >= 0 : compare(record, key) > 0),\n )\n .slice(0, limit),\n record: (id) => active.records.get(id),\n alias: (namespace, key) => active.aliases.get(aliasKey(namespace, key)),\n toolsOf: (assistantId) =>\n records.flatMap((record) =>\n record.kind === \"tool\" && record.assistantId === assistantId ? [record] : [],\n ),\n pendingUsers: () => records.filter(isPendingTranscriptUserRecord),\n };\n};\n"],"mappings":";;;;AAsCA,MAAM,YAAY,WAAqC,QAAgB,GAAG,UAAU,QAAQ;;AAG5F,MAAa,+BACX,QACA,YAEA,OAAO,QAAQ,YAAY,UACvB,OAAO,UACP,OAAO,U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,WAAW,GAAG,CAAC;EACtE,UAAU,gBACR,QAAQ,SAAS,WACf,OAAO,SAAS,UAAU,OAAO,gBAAgB,cAAc,CAAC,MAAM,IAAI,CAAC,CAC7E;EACF,oBAAoB,QAAQ,OAAO,6BAA6B;CAClE;AACF"}
@@ -1,14 +1,86 @@
1
- import { CommandId, SequenceNumber } from "./types/core.js";
2
- import { f as ProviderPartId, g as UnixEpochMillis, h as ToolName, l as ModelSelectionPayload, p as SchemaVersion, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
1
+ import { CommandId } from "./types/core.js";
2
+ import { f as ProviderPartId, g as UnixEpochMillis, h as ToolName, l as ModelSelectionPayload, p as SchemaVersion, s as FailurePayload } from "./envelope-BCzKUq_z.js";
3
3
  import { addModelUsage } from "./domain/model-usage.js";
4
4
  import { CommandIdempotencyKey } from "./types/commands.js";
5
5
  import { $n as pendingMessagesPausedEventType, An as baseStateCreatedEventType, Bn as compactionRequestedEventType, Cr as turnStartedEventType, Dn as assistantMessageCommittedEventType, Dr as userMessagePromotedEventType, Er as userMessageCommittedEventType, Fn as commandCompletedEventType, Hn as contextProjectedEventType, In as commandFailedEventType, Jn as inferenceCompletedEventType, Ln as commandStartedEventType, Mn as baseStateRequestedEventType, Nn as commandAdmittedEventType, On as assistantMessageImportedEventType, Or as userMessageSubmittedEventType, Pn as commandCancelledEventType, Qn as messageQueuePausedEventType, Rn as compactionCompletedEventType, Sr as turnFailedEventType, Tr as userMessageCancelledEventType, Un as contextRebasedEventType, Vn as compactionStartedEventType, Xn as inferenceStartedEventType, Yn as inferenceFailedEventType, Zn as interpretLegacyAttemptForReduction, _r as toolCallCreatedEventType, ar as runSchedulingGrantedEventType, br as toolCallStartedEventType, cr as runStartedEventType, dr as steeringMessageQueuedEventType, er as recoveryCompletedEventType, fr as stopTurnAppliedEventType, gr as toolCallCompletedEventType, hr as systemMessageCommittedEventType, ir as runSchedulingDeliveredEventType, jn as baseStateFailedEventType, kn as assistantPartialCommittedEventType, lr as sessionConfiguredEventType, mr as summaryCreatedEventType, nr as runFailedEventType, or as runSchedulingInvalidatedEventType, pr as stopTurnRequestedEventType, rr as runInterruptedEventType, sr as runSchedulingRequestedEventType, tr as runCompletedEventType, ur as steeringMessageCancelledEventType, vr as toolCallFailedEventType, wr as turnStoppedEventType, xr as turnCompletedEventType, yr as toolCallRejectedEventType, zn as compactionFailedEventType } from "./durable-CD__3ztN.js";
6
6
  import { t as assertNever } from "./assert-never-CoyUpoRB.js";
7
- import { A as TranscriptRecordFromEnvelope, E as TranscriptOrder, H as TranscriptVersion, K as runGroupStatus, O as TranscriptRecord, S as TranscriptDecorationKey, W as isPendingTranscriptUserRecord, Y as transcriptRecordId, Z as sha256Hex, b as TranscriptDecorationEntryId, h as TranscriptClassification, w as TranscriptFieldPath } from "./records-DWKEjuqb.js";
8
- import * as Context from "effect/Context";
7
+ import { A as TranscriptRecordFromEnvelope, H as TranscriptVersion, K as runGroupStatus, O as TranscriptRecord, S as TranscriptDecorationKey, Y as transcriptRecordId, Z as sha256Hex, b as TranscriptDecorationEntryId, h as TranscriptClassification, w as TranscriptFieldPath } from "./records-DWKEjuqb.js";
9
8
  import * as Effect from "effect/Effect";
10
9
  import * as Schema from "effect/Schema";
11
- import * as Result from "effect/Result";
10
+ //#region src/transcript/body.ts
11
+ const bodyEncoder = new TextEncoder();
12
+ /**
13
+ * A body value normalized to the JSON a persisted log holds: what the interpreter inlines and what
14
+ * a reference resolves to, so the two can never disagree. A value with no JSON text (`undefined`,
15
+ * a function) is `null`; a value with no JSON form at all (a bigint, a cycle) is `undefined`.
16
+ */
17
+ const normalizeTranscriptBodyValue = (value) => {
18
+ let json;
19
+ try {
20
+ json = JSON.stringify(value);
21
+ } catch {
22
+ return;
23
+ }
24
+ const normalized = json === void 0 ? null : JSON.parse(json);
25
+ if (!Schema.is(Schema.Json)(normalized)) return void 0;
26
+ return {
27
+ value: normalized,
28
+ byteLength: json === void 0 ? 4 : bodyEncoder.encode(json).length
29
+ };
30
+ };
31
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
32
+ /** An own property, or `undefined`: never an inherited name such as `toString`. */
33
+ const own = (value, key) => isRecord(value) && Object.prototype.hasOwnProperty.call(value, key) ? Reflect.get(value, key) : void 0;
34
+ const assistantEventTypes = /* @__PURE__ */ new Set([
35
+ assistantMessageCommittedEventType,
36
+ assistantPartialCommittedEventType,
37
+ assistantMessageImportedEventType
38
+ ]);
39
+ /**
40
+ * The value at a body site of a framework event, or `undefined` when `path` names no body.
41
+ *
42
+ * The interpreter creates bodies at exactly three sites: tool parameters
43
+ * (`ToolCallCreated` `promptPart.params`), tool results (`ToolCallCompleted` `promptPart.result`)
44
+ * and provider-executed tool results inside assistant output (`promptParts[i].result` of a
45
+ * well-formed `tool-result` part). Nothing else in the log is a body, so a reference can never
46
+ * reach a system prompt, a command input or an app event.
47
+ */
48
+ const bodySiteValue = (event, path) => {
49
+ if (event.namespace !== "effect-durable-agent") return void 0;
50
+ const [first, second, third, ...rest] = path;
51
+ if (rest.length > 0) return void 0;
52
+ if (event.type === toolCallCreatedEventType || event.type === toolCallCompletedEventType) {
53
+ const field = event.type === toolCallCreatedEventType ? "params" : "result";
54
+ const promptPart = own(event.payload, "promptPart");
55
+ return first === "promptPart" && second === field && third === void 0 && isRecord(promptPart) ? { value: own(promptPart, field) } : void 0;
56
+ }
57
+ if (!assistantEventTypes.has(event.type)) return void 0;
58
+ if (first !== "promptParts" || typeof second !== "number" || third !== "result") return void 0;
59
+ const parts = own(event.payload, "promptParts");
60
+ const part = Array.isArray(parts) ? parts[second] : void 0;
61
+ return own(part, "type") === "tool-result" && Schema.is(ProviderPartId)(own(part, "id")) && Schema.is(ToolName)(own(part, "name")) ? { value: own(part, "result") } : void 0;
62
+ };
63
+ /**
64
+ * Resolve a body reference against the committed event it names: the read side of the
65
+ * interpreter's body rule. Resolving through the log keeps a `Ref` valid after projection rows are
66
+ * rebuilt or deleted; any path that is not a body site resolves to nothing.
67
+ */
68
+ const resolveTranscriptBody = (event, path) => {
69
+ const site = bodySiteValue(event, path);
70
+ if (site === void 0) return {
71
+ _tag: "Missing",
72
+ message: "the path names no transcript body"
73
+ };
74
+ const normalized = normalizeTranscriptBodyValue(site.value);
75
+ return normalized === void 0 ? {
76
+ _tag: "Missing",
77
+ message: "the body has no JSON form"
78
+ } : {
79
+ _tag: "Found",
80
+ value: normalized.value
81
+ };
82
+ };
83
+ //#endregion
12
84
  //#region src/transcript/version.ts
13
85
  /**
14
86
  * EDA's transcript semantic revision.
@@ -419,7 +491,7 @@ const replayBufferedDecorations = (batch, seq, user) => {
419
491
  ...decorations,
420
492
  [fallback.to]: source
421
493
  };
422
- if (jsonBytes$1(next) <= transcriptMappingBounds.maxDecorationBytes) decorations = next;
494
+ if (jsonBytes(next) <= transcriptMappingBounds.maxDecorationBytes) decorations = next;
423
495
  }
424
496
  }
425
497
  return decorations === decorated.decorations ? decorated : {
@@ -444,7 +516,7 @@ const withinBudget = (operations) => {
444
516
  const kept = [];
445
517
  let bytes = 2;
446
518
  for (const operation of operations.slice(0, 32)) {
447
- bytes += jsonBytes$1(operation) + 1;
519
+ bytes += jsonBytes(operation) + 1;
448
520
  if (bytes > transcriptMappingBounds.maxDecorationBytes) break;
449
521
  kept.push(operation);
450
522
  }
@@ -453,9 +525,9 @@ const withinBudget = (operations) => {
453
525
  /** Apply one operation unless the record's decorations would exceed their byte budget. */
454
526
  const applyPrepared = (definition, target, prepared) => {
455
527
  const next = applyOperation(definition, target, prepared);
456
- return next === target || jsonBytes$1(next.decorations) <= transcriptMappingBounds.maxDecorationBytes ? next : target;
528
+ return next === target || jsonBytes(next.decorations) <= transcriptMappingBounds.maxDecorationBytes ? next : target;
457
529
  };
458
- const jsonBytes$1 = (value) => encoder$1.encode(canonicalJson(value)).length;
530
+ const jsonBytes = (value) => encoder.encode(canonicalJson(value)).length;
459
531
  const applyOperation = (definition, target, prepared) => {
460
532
  const operation = mappingIndex(definition).byName.get(prepared.mapping)?.operations[prepared.operation];
461
533
  if (operation === void 0) return target;
@@ -525,7 +597,7 @@ const extract = (value, path) => path.reduce((current, key) => {
525
597
  if (current === null || typeof current !== "object" || Array.isArray(current)) return;
526
598
  return Object.getOwnPropertyDescriptor(current, key)?.value;
527
599
  }, value);
528
- const encoder$1 = new TextEncoder();
600
+ const encoder = new TextEncoder();
529
601
  /**
530
602
  * A payload value as the JSON a persisted log holds (so a live projection and a rebuild agree),
531
603
  * within the value bound; otherwise nothing.
@@ -536,7 +608,7 @@ const boundedJson = (value) => {
536
608
  const json = JSON.stringify(value);
537
609
  if (json === void 0) return void 0;
538
610
  const normalized = JSON.parse(json);
539
- return Schema.is(Schema.Json)(normalized) && encoder$1.encode(canonicalJson(normalized)).length <= transcriptMappingBounds.maxValueBytes ? normalized : void 0;
611
+ return Schema.is(Schema.Json)(normalized) && encoder.encode(canonicalJson(normalized)).length <= transcriptMappingBounds.maxValueBytes ? normalized : void 0;
540
612
  } catch {
541
613
  return;
542
614
  }
@@ -636,7 +708,7 @@ var TranscriptBatch = class {
636
708
  };
637
709
  const aliasKey = (namespace, key) => `${namespace}\u0000${key}`;
638
710
  const matchesRecordSchema = Schema.is(TranscriptRecord);
639
- const encodeRecord$1 = Schema.encodeSync(TranscriptRecordFromEnvelope);
711
+ const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
640
712
  const describeCause = (cause) => cause instanceof Error ? cause.message : String(cause);
641
713
  /**
642
714
  * Why a record could not be stored, if it could not: it must satisfy the stored-row schema,
@@ -646,7 +718,7 @@ const describeCause = (cause) => cause instanceof Error ? cause.message : String
646
718
  const storageProblem = (record) => {
647
719
  let envelope;
648
720
  try {
649
- envelope = encodeRecord$1(record);
721
+ envelope = encodeRecord(record);
650
722
  } catch (cause) {
651
723
  return `does not satisfy the transcript record schema: ${describeCause(cause)}`;
652
724
  }
@@ -1325,26 +1397,17 @@ const timingOf = (record) => ({
1325
1397
  ...record?.terminalAtMs === void 0 ? {} : { terminalAtMs: record.terminalAtMs },
1326
1398
  ...record?.durationMs === void 0 ? {} : { durationMs: record.durationMs }
1327
1399
  });
1328
- const bodyEncoder = new TextEncoder();
1329
1400
  /**
1330
1401
  * A body read from a committed event, normalized to the JSON a persisted log holds, so a live
1331
- * projection and a rebuild from storage agree. A value with no JSON form (a bigint or a cycle) is
1332
- * a projection failure.
1402
+ * projection, a rebuild from storage and a reference resolved later all agree. A value with no
1403
+ * JSON form (a bigint or a cycle) is a projection failure.
1333
1404
  */
1334
1405
  const inlineBody = (value, seq, path) => {
1335
- const notJson = () => new TranscriptProjectionError({ message: `body at seq ${seq} ${JSON.stringify(path)} is not JSON` });
1336
- let json;
1337
- try {
1338
- json = JSON.stringify(value);
1339
- } catch {
1340
- throw notJson();
1341
- }
1342
- const normalized = json === void 0 ? null : JSON.parse(json);
1343
- if (!Schema.is(Schema.Json)(normalized)) throw notJson();
1344
- const byteLength = json === void 0 ? 4 : bodyEncoder.encode(json).length;
1345
- return byteLength <= 65536 ? {
1406
+ const normalized = normalizeTranscriptBodyValue(value);
1407
+ if (normalized === void 0) throw new TranscriptProjectionError({ message: `body at seq ${seq} ${JSON.stringify(path)} is not JSON` });
1408
+ return normalized.byteLength <= 65536 ? {
1346
1409
  _tag: "Inline",
1347
- value: normalized,
1410
+ value: normalized.value,
1348
1411
  source: {
1349
1412
  seq,
1350
1413
  path
@@ -1355,7 +1418,7 @@ const inlineBody = (value, seq, path) => {
1355
1418
  seq,
1356
1419
  path
1357
1420
  },
1358
- byteLength
1421
+ byteLength: normalized.byteLength
1359
1422
  };
1360
1423
  };
1361
1424
  /** A model selection as the JSON a persisted log holds; settings with no JSON form are dropped. */
@@ -1384,181 +1447,6 @@ const jsonFailure = (error) => {
1384
1447
  };
1385
1448
  const mapNonEmpty = (items, f) => [f(items[0]), ...items.slice(1).map(f)];
1386
1449
  //#endregion
1387
- //#region src/transcript/store.ts
1388
- /** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */
1389
- var TranscriptCursorMismatch = class extends Schema.TaggedError()("TranscriptCursorMismatch", { message: Schema.String }) {};
1390
- /** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */
1391
- var EDATranscriptStore = class extends Context.Service()("@effect-durable-agent/EDATranscriptStore") {};
1392
- //#endregion
1393
- //#region src/transcript/window-read.ts
1394
- /** Readiness of a served version: why its cut may be behind the log. */
1395
- const transcriptReadiness = (meta, carried) => {
1396
- if (!carried) return { _tag: "UpdatingHistory" };
1397
- switch (meta.status._tag) {
1398
- case "Ok": return { _tag: "Ready" };
1399
- case "Failed": return {
1400
- _tag: "Degraded",
1401
- failedAtSeq: meta.status.failedAtSeq,
1402
- error: meta.status.error
1403
- };
1404
- }
1405
- };
1406
- /** The empty window served while no version is servable yet. */
1407
- const buildingTranscriptWindow = (incarnation, version) => ({
1408
- incarnation,
1409
- version,
1410
- throughSeq: SequenceNumber.make(0),
1411
- records: [],
1412
- dependencies: [],
1413
- hasOlder: false,
1414
- hasNewer: false,
1415
- readiness: { _tag: "Building" }
1416
- });
1417
- const orderKey = (record) => ({
1418
- anchorSeq: record.position?.anchorSeq ?? 0,
1419
- ordinal: record.position?.ordinal ?? 0,
1420
- recordId: record.id
1421
- });
1422
- const cursorKey = (cursor) => ({
1423
- anchorSeq: cursor.anchorSeq,
1424
- ordinal: cursor.ordinal,
1425
- recordId: cursor.recordId
1426
- });
1427
- /**
1428
- * Assemble one window from a source at a single cut.
1429
- *
1430
- * The response never contains anything newer than the served version's cursor: a frozen (failed
1431
- * or no longer carried) version's rows, pending users and session context all stop at its last
1432
- * good cut, which is the degraded-read rule. Bodies above the inline limit become references;
1433
- * if the response still exceeds the byte budget, records are dropped from the far end of the
1434
- * selection, keeping at least one so paging always progresses.
1435
- */
1436
- const readTranscriptWindowFrom = (source, selector, limits) => {
1437
- const version = source.meta.version;
1438
- for (const cursor of selectorCursors(selector)) if (cursor.incarnation !== source.incarnation || cursor.version !== version) return Result.fail(new TranscriptCursorMismatch({ message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}` }));
1439
- const selected = selectTopLevel(source, selector, limits.maxRecords);
1440
- const keepNewest = selector._tag === "Latest" || selector._tag === "Page" && selector.direction === "before";
1441
- let top = selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes));
1442
- let dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
1443
- while (top.length > 1 && windowBytes(top, dependencies) > limits.maxBytes) {
1444
- top = keepNewest ? top.slice(1) : top.slice(0, -1);
1445
- dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
1446
- }
1447
- const first = top[0];
1448
- const last = top[top.length - 1];
1449
- const [hasOlder, hasNewer] = first === void 0 || last === void 0 ? emptySelectionNeighbours(source, selector) : [source.topLevelBefore(orderKey(first), 1, false).length > 0, source.topLevelAfter(orderKey(last), 1, false).length > 0];
1450
- return Result.succeed({
1451
- incarnation: source.incarnation,
1452
- version,
1453
- throughSeq: source.meta.cursor,
1454
- records: top,
1455
- dependencies,
1456
- hasOlder,
1457
- hasNewer,
1458
- readiness: transcriptReadiness(source.meta, source.carried)
1459
- });
1460
- };
1461
- const selectorCursors = (selector) => {
1462
- switch (selector._tag) {
1463
- case "Latest": return [];
1464
- case "Page": return [selector.cursor];
1465
- case "Range": return [selector.from, selector.to];
1466
- }
1467
- };
1468
- const selectTopLevel = (source, selector, maxRecords) => {
1469
- switch (selector._tag) {
1470
- case "Latest": return [...source.topLevelBefore(void 0, Math.min(selector.count, maxRecords), false)].reverse();
1471
- case "Page": {
1472
- const count = Math.min(selector.count, maxRecords);
1473
- return selector.direction === "before" ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse() : source.topLevelAfter(cursorKey(selector.cursor), count, false);
1474
- }
1475
- case "Range": {
1476
- const to = cursorKey(selector.to);
1477
- return source.topLevelAfter(cursorKey(selector.from), maxRecords, true).filter((record) => TranscriptOrder(orderKey(record), to) <= 0);
1478
- }
1479
- }
1480
- };
1481
- const emptySelectionNeighbours = (source, selector) => {
1482
- switch (selector._tag) {
1483
- case "Latest": return [false, false];
1484
- case "Page": {
1485
- const key = cursorKey(selector.cursor);
1486
- return selector.direction === "before" ? [false, source.topLevelAfter(key, 1, true).length > 0] : [source.topLevelBefore(key, 1, true).length > 0, false];
1487
- }
1488
- case "Range": return [source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0, source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0];
1489
- }
1490
- };
1491
- /** Session context, then each record's run group and tools in part order, then pending users. */
1492
- const collectDependencies = (source, top, maxInlineBodyBytes) => {
1493
- const dependencies = /* @__PURE__ */ new Map();
1494
- const add = (record) => {
1495
- if (record !== void 0 && !dependencies.has(record.id)) dependencies.set(record.id, withBodyRefs(record, maxInlineBodyBytes));
1496
- };
1497
- add(source.record(transcriptRecordId.session));
1498
- for (const record of top) switch (record.kind) {
1499
- case "assistant": {
1500
- if (record.runGroupId !== void 0) add(source.record(record.runGroupId));
1501
- const partOrder = new Map(record.parts.flatMap((part, index) => part._tag === "ToolCall" && part.toolId !== void 0 ? [[part.toolId, index]] : []));
1502
- [...source.toolsOf(record.id)].sort((left, right) => (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
1503
- break;
1504
- }
1505
- case "user": {
1506
- const runId = record.state._tag === "Consumed" ? record.state.runId : void 0;
1507
- const groupId = (runId === void 0 ? void 0 : source.alias("runId", runId)) ?? source.alias("runCommand", record.commandId);
1508
- if (groupId !== void 0) add(source.record(groupId));
1509
- break;
1510
- }
1511
- }
1512
- [...source.pendingUsers()].filter(isPendingTranscriptUserRecord).sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
1513
- return Array.from(dependencies.values());
1514
- };
1515
- const encoder = new TextEncoder();
1516
- const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
1517
- const jsonBytes = (value) => {
1518
- const json = JSON.stringify(value);
1519
- return json === void 0 ? 0 : encoder.encode(json).length;
1520
- };
1521
- const windowBytes = (top, dependencies) => [...top, ...dependencies].reduce((total, record) => total + jsonBytes(encodeRecord(record)), 0);
1522
- const bodyRef = (body, maxInlineBodyBytes) => {
1523
- if (body._tag === "Ref") return body;
1524
- const byteLength = jsonBytes(body.value);
1525
- return byteLength <= maxInlineBodyBytes ? body : {
1526
- _tag: "Ref",
1527
- source: body.source,
1528
- byteLength: NonNegativeInt.make(byteLength)
1529
- };
1530
- };
1531
- /** Replace inline bodies above the limit with references to their immutable log source. */
1532
- const withBodyRefs = (record, maxInlineBodyBytes) => {
1533
- switch (record.kind) {
1534
- case "tool": {
1535
- const tool = {
1536
- ...record,
1537
- ...record.params === void 0 ? {} : { params: bodyRef(record.params, maxInlineBodyBytes) },
1538
- lifecycle: record.lifecycle._tag === "Completed" ? {
1539
- _tag: "Completed",
1540
- result: bodyRef(record.lifecycle.result, maxInlineBodyBytes)
1541
- } : record.lifecycle
1542
- };
1543
- return {
1544
- ...record,
1545
- ...tool
1546
- };
1547
- }
1548
- case "assistant": {
1549
- const parts = record.parts.map((part) => part._tag === "ToolResult" ? {
1550
- ...part,
1551
- result: bodyRef(part.result, maxInlineBodyBytes)
1552
- } : part);
1553
- return {
1554
- ...record,
1555
- parts
1556
- };
1557
- }
1558
- default: return record;
1559
- }
1560
- };
1561
- //#endregion
1562
- export { transcriptSemanticRevision as C, computeTranscriptVersion as S, TranscriptUserFallback as _, TranscriptCursorMismatch as a, transcriptMappingBounds as b, TranscriptProjectionError as c, TranscriptListEntryKey as d, TranscriptMappedEvent as f, TranscriptMappings as g, TranscriptMappingTarget as h, EDATranscriptStore as i, TranscriptDefinition as l, TranscriptMappingOperation as m, readTranscriptWindowFrom as n, planTranscriptBatch as o, TranscriptMapping as p, transcriptReadiness as r, TranscriptAliasNamespace as s, buildingTranscriptWindow as t, TranscriptDefinitionError as u, emptyTranscriptMappings as v, canonicalJson as x, makeTranscriptDefinition as y };
1450
+ export { computeTranscriptVersion as _, TranscriptDefinitionError as a, TranscriptMapping as c, TranscriptMappings as d, TranscriptUserFallback as f, canonicalJson as g, transcriptMappingBounds as h, TranscriptDefinition as i, TranscriptMappingOperation as l, makeTranscriptDefinition as m, TranscriptAliasNamespace as n, TranscriptListEntryKey as o, emptyTranscriptMappings as p, TranscriptProjectionError as r, TranscriptMappedEvent as s, planTranscriptBatch as t, TranscriptMappingTarget as u, transcriptSemanticRevision as v, resolveTranscriptBody as y };
1563
1451
 
1564
- //# sourceMappingURL=window-read-BDayZf7O.js.map
1452
+ //# sourceMappingURL=interpreter-BdRoYrfL.js.map