@yielded/agent 0.1.0-beta.179 → 0.1.0-beta.182
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/{Admin-NvXFPDIM.d.mts → Admin-C4mPa0M2.d.mts} +5 -5
- package/dist/{AgentRuntime-DrQfy4cL.mjs → AgentRuntime-1OjlOCa9.mjs} +14 -9
- package/dist/AgentRuntime-1OjlOCa9.mjs.map +1 -0
- package/dist/{AgentRuntime-Dx5u_FJD.d.mts → AgentRuntime-CVsnQBPe.d.mts} +4 -4
- package/dist/{DurableAgentRuntime-CWhu1exp.mjs → DurableAgentRuntime-D2I_T2Yt.mjs} +12 -7
- package/dist/DurableAgentRuntime-D2I_T2Yt.mjs.map +1 -0
- package/dist/{EventSource-DNyaWmyQ.d.mts → EventSource-gc82d-f6.d.mts} +2 -2
- package/dist/InMemory.d.mts +1 -1
- package/dist/{MessageDelivery-CLzWJImC.d.mts → MessageDelivery-DrQKvh93.d.mts} +4 -4
- package/dist/{PreparedInputAdmission-BQ9UCLFS.d.mts → PreparedInputAdmission-CrqdFUd8.d.mts} +3 -3
- package/dist/{RunContinuation-CL0wBsQE.d.mts → RunContinuation-DMbA81sZ.d.mts} +4 -3
- package/dist/{RunContinuation-BF95Ncv2.mjs → RunContinuation-DWiO2K9D.mjs} +6 -1
- package/dist/{RunContinuation-BF95Ncv2.mjs.map → RunContinuation-DWiO2K9D.mjs.map} +1 -1
- package/dist/{RunEvent-C5jVQZ6K.d.mts → RunEvent-Bh1p4zAO.d.mts} +2 -2
- package/dist/{RunOptions-BANtohGk.d.mts → RunOptions-aBHR-Eqm.d.mts} +6 -3
- package/dist/{Subagent-C7F7c8Op.mjs → Subagent-BRiDyUS4.mjs} +2 -2
- package/dist/{Subagent-C7F7c8Op.mjs.map → Subagent-BRiDyUS4.mjs.map} +1 -1
- package/dist/{Subagent-5ulnV6An.d.mts → Subagent-FypBXZP1.d.mts} +4 -4
- package/dist/{Subscription-D2yn6Eo3.d.mts → Subscription-Bx0LiX3x.d.mts} +2 -2
- package/dist/{SubscriptionInput-Cog4x7Rd.d.mts → SubscriptionInput-CBFCfuOF.d.mts} +2 -2
- package/dist/{ThreadHistory-KPPBJLJb.d.mts → ThreadHistory-ajQhqZDY.d.mts} +2 -2
- package/dist/{ThreadImport-em89zmM-.d.mts → ThreadImport-DTV_ario.d.mts} +4 -4
- package/dist/{ThreadImport-BoTfjjrz.mjs → ThreadImport-DlCLjRHK.mjs} +2 -2
- package/dist/{ThreadImport-BoTfjjrz.mjs.map → ThreadImport-DlCLjRHK.mjs.map} +1 -1
- package/dist/{WorkerAdmission-CtX1HRkm.mjs → WorkerAdmission-Cxg_REhE.mjs} +2 -2
- package/dist/{WorkerAdmission-CtX1HRkm.mjs.map → WorkerAdmission-Cxg_REhE.mjs.map} +1 -1
- package/dist/{agent-registration-Dt57NAP6.mjs → agent-registration-C6tkQz8r.mjs} +2 -2
- package/dist/{agent-registration-Dt57NAP6.mjs.map → agent-registration-C6tkQz8r.mjs.map} +1 -1
- package/dist/capabilities/BrowserUse.d.mts +9 -3
- package/dist/capabilities/BrowserUse.mjs +14 -2
- package/dist/capabilities/BrowserUse.mjs.map +1 -1
- package/dist/capabilities/Commands.d.mts +1 -1
- package/dist/capabilities/Redaction.d.mts +1 -1
- package/dist/capabilities/RunHooks.d.mts +1 -1
- package/dist/capabilities/Subagent.d.mts +1 -1
- package/dist/capabilities/Subagent.mjs +1 -1
- package/dist/core/RunEvent.d.mts +1 -1
- package/dist/core/RunEvent.mjs +1 -1
- package/dist/core/RunEvent.mjs.map +1 -1
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/AgentRegistration.mjs +1 -1
- package/dist/durable/Certification.d.mts +1 -1
- package/dist/durable/CommittedActivity.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.mjs +2 -2
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
- package/dist/durable/LifecyclePublication.d.mts +1 -1
- package/dist/durable/MessageDelivery.d.mts +1 -1
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
- package/dist/durable/PersistentHistory.d.mts +2 -2
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/RecordFormat.mjs +1 -2
- package/dist/durable/RecordFormat.mjs.map +1 -1
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/RunContinuation.d.mts +2 -2
- package/dist/durable/RunContinuation.mjs +1 -1
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/RunStorage.d.mts +1 -1
- package/dist/durable/Scheduling.d.mts +1 -1
- package/dist/durable/SettlementPublisher.d.mts +1 -1
- package/dist/durable/SqlMemoryStore.d.mts +2 -15
- package/dist/durable/SqlMemoryStore.mjs +1 -1
- package/dist/durable/SqlMemoryStore.mjs.map +1 -1
- package/dist/durable/SqlStorageOwner.d.mts +20 -0
- package/dist/durable/SqlStorageOwner.mjs +7 -0
- package/dist/durable/SqlStorageOwner.mjs.map +1 -0
- package/dist/durable/SubmissionLedger.d.mts +1 -1
- package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +1 -1
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionTools.d.mts +2 -2
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/Subscriptions.d.mts +5 -5
- package/dist/durable/ThreadArchiveRange.d.mts +1 -1
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadImport.d.mts +1 -1
- package/dist/durable/ThreadImport.mjs +1 -1
- package/dist/durable/ThreadInvariants.d.mts +3 -3
- package/dist/durable/ThreadInvariants.mjs +2 -2
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadReader.d.mts +1 -1
- package/dist/durable/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.mjs +1 -1
- package/dist/durable/ThreadTransfer.d.mts +1 -1
- package/dist/durable/ThreadWork.d.mts +1 -1
- package/dist/durable/ThreadWork.mjs +1 -1
- package/dist/durable/WorkerAdmission.d.mts +1 -1
- package/dist/durable/WorkerAdmission.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +1 -1
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/RunOptions.d.mts +1 -1
- package/dist/engine/RunOptions.mjs.map +1 -1
- package/dist/engine/ThreadHistory.d.mts +1 -1
- package/dist/index.d.mts +13 -13
- package/dist/index.mjs +6 -6
- package/dist/{run-context-reader-kpO9xhP2.d.mts → run-context-reader-CIdG5tdJ.d.mts} +2 -2
- package/package.json +1 -1
- package/src/capabilities/BrowserUse.ts +26 -3
- package/src/core/RunEvent.ts +1 -1
- package/src/durable/DurableAgentRuntime.ts +40 -4
- package/src/durable/RecordFormat.ts +2 -2
- package/src/durable/RunContinuation.ts +10 -0
- package/src/durable/SqlMemoryStore.ts +3 -21
- package/src/durable/SqlStorageOwner.ts +24 -0
- package/src/engine/RunOptions.ts +4 -1
- package/src/engine/internal/agent-runtime.ts +56 -8
- package/dist/AgentRuntime-DrQfy4cL.mjs.map +0 -1
- package/dist/DurableAgentRuntime-CWhu1exp.mjs.map +0 -1
|
@@ -5,8 +5,8 @@ import { r as Diagnostic } from "../FailureDiagnostic-DvHruCSJ.mjs";
|
|
|
5
5
|
import { t as AgentPolicy } from "../AgentPolicy-B4lbCU2T.mjs";
|
|
6
6
|
import { b as DefinitionDigests } from "../Records-BTnGRdcf.mjs";
|
|
7
7
|
import { t as DigestError } from "../Digest-DjUgS5PG.mjs";
|
|
8
|
-
import { sn as Settlement } from "../Admin-
|
|
9
|
-
import { a as MessageDeliveryError, c as MessageDeliveryFailure, m as MessageDeliveryStore } from "../MessageDelivery-
|
|
8
|
+
import { sn as Settlement } from "../Admin-C4mPa0M2.mjs";
|
|
9
|
+
import { a as MessageDeliveryError, c as MessageDeliveryFailure, m as MessageDeliveryStore } from "../MessageDelivery-DrQKvh93.mjs";
|
|
10
10
|
import { Effect, Schema } from "effect";
|
|
11
11
|
//#region src/durable/MessageDeliveryStoreConformance.d.ts
|
|
12
12
|
declare const MessageDeliveryConformanceViolation_base: Schema.Class<MessageDeliveryConformanceViolation, Schema.TaggedStruct<"MessageDeliveryConformanceViolation", {
|
|
@@ -106,6 +106,25 @@ export declare const makeMessageDeliveryFixture: (messageId?: any, owner?: any,
|
|
|
106
106
|
readonly reportKind?: "update" | undefined;
|
|
107
107
|
} | undefined;
|
|
108
108
|
readonly messageAdmission?: {
|
|
109
|
+
readonly schemaVersion: 1;
|
|
110
|
+
readonly message: {
|
|
111
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
112
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
113
|
+
};
|
|
114
|
+
readonly peerName: string;
|
|
115
|
+
readonly sender: {
|
|
116
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
117
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
118
|
+
};
|
|
119
|
+
readonly returnAddress: {
|
|
120
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
121
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
122
|
+
};
|
|
123
|
+
readonly inReplyTo?: {
|
|
124
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
125
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
126
|
+
} | undefined;
|
|
127
|
+
} | {
|
|
109
128
|
readonly _tag: "WorkerCompletion";
|
|
110
129
|
readonly budgetExhausted: boolean;
|
|
111
130
|
readonly schemaVersion: 1;
|
|
@@ -146,25 +165,6 @@ export declare const makeMessageDeliveryFixture: (messageId?: any, owner?: any,
|
|
|
146
165
|
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
147
166
|
};
|
|
148
167
|
readonly update: Update;
|
|
149
|
-
} | {
|
|
150
|
-
readonly schemaVersion: 1;
|
|
151
|
-
readonly message: {
|
|
152
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
153
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
154
|
-
};
|
|
155
|
-
readonly peerName: string;
|
|
156
|
-
readonly sender: {
|
|
157
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
158
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
159
|
-
};
|
|
160
|
-
readonly returnAddress: {
|
|
161
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
162
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
163
|
-
};
|
|
164
|
-
readonly inReplyTo?: {
|
|
165
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
166
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
167
|
-
} | undefined;
|
|
168
168
|
} | undefined;
|
|
169
169
|
};
|
|
170
170
|
readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
|
|
@@ -290,6 +290,25 @@ export declare const makeWorkerUpdateDeliveryFixture: (id: string) => Effect.Eff
|
|
|
290
290
|
readonly reportKind?: "update" | undefined;
|
|
291
291
|
} | undefined;
|
|
292
292
|
readonly messageAdmission?: {
|
|
293
|
+
readonly schemaVersion: 1;
|
|
294
|
+
readonly message: {
|
|
295
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
296
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
297
|
+
};
|
|
298
|
+
readonly peerName: string;
|
|
299
|
+
readonly sender: {
|
|
300
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
301
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
302
|
+
};
|
|
303
|
+
readonly returnAddress: {
|
|
304
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
305
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
306
|
+
};
|
|
307
|
+
readonly inReplyTo?: {
|
|
308
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
309
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
310
|
+
} | undefined;
|
|
311
|
+
} | {
|
|
293
312
|
readonly _tag: "WorkerCompletion";
|
|
294
313
|
readonly budgetExhausted: boolean;
|
|
295
314
|
readonly schemaVersion: 1;
|
|
@@ -330,25 +349,6 @@ export declare const makeWorkerUpdateDeliveryFixture: (id: string) => Effect.Eff
|
|
|
330
349
|
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
331
350
|
};
|
|
332
351
|
readonly update: Update;
|
|
333
|
-
} | {
|
|
334
|
-
readonly schemaVersion: 1;
|
|
335
|
-
readonly message: {
|
|
336
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
337
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
338
|
-
};
|
|
339
|
-
readonly peerName: string;
|
|
340
|
-
readonly sender: {
|
|
341
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
342
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
343
|
-
};
|
|
344
|
-
readonly returnAddress: {
|
|
345
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
346
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
347
|
-
};
|
|
348
|
-
readonly inReplyTo?: {
|
|
349
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
350
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
351
|
-
} | undefined;
|
|
352
352
|
} | undefined;
|
|
353
353
|
};
|
|
354
354
|
readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as ThreadHistory } from "../ThreadHistory-
|
|
2
|
-
import { Wi as ThreadStore, bo as StorageOwner } from "../Admin-
|
|
1
|
+
import { t as ThreadHistory } from "../ThreadHistory-ajQhqZDY.mjs";
|
|
2
|
+
import { Wi as ThreadStore, bo as StorageOwner } from "../Admin-C4mPa0M2.mjs";
|
|
3
3
|
import { Layer } from "effect";
|
|
4
4
|
declare namespace PersistentHistory_d_exports {
|
|
5
5
|
export { layer };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { r as admitPreparedInput, t as PreparedInputAdmission } from "../PreparedInputAdmission-
|
|
1
|
+
import { r as admitPreparedInput, t as PreparedInputAdmission } from "../PreparedInputAdmission-CrqdFUd8.mjs";
|
|
2
2
|
export { PreparedInputAdmission, admitPreparedInput };
|
|
@@ -19,7 +19,6 @@ var RecordFormatError = class extends Schema.TaggedError()("RecordFormatError",
|
|
|
19
19
|
/** An archive owns its wire JSON explicitly; the typed fields are only a read view. */
|
|
20
20
|
var ExportedRecord = class extends RecordEnvelope.extend("@effect-agent/thread/ExportedRecord")({ wire: RecordJson }) {};
|
|
21
21
|
const decodeRecord = Schema.decodeUnknownEffect(RecordEnvelope);
|
|
22
|
-
const sameRecord = Schema.toEquivalence(RecordEnvelope);
|
|
23
22
|
const parseRecordObject = Schema.decodeEffect(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)));
|
|
24
23
|
const decodeExportedRecord = Schema.decodeUnknownEffect(ExportedRecord);
|
|
25
24
|
/**
|
|
@@ -53,7 +52,7 @@ const decodeExportRecord = Effect.fnUntraced(function* (format, input) {
|
|
|
53
52
|
*/
|
|
54
53
|
const ExportRecord = RecordJson.pipe(Schema.decodeTo(Schema.toType(ExportedRecord), {
|
|
55
54
|
decode: decodeView,
|
|
56
|
-
encode: SchemaGetter.transformEffect((record) => decodeRecord(record.wire).pipe(Effect.mapError((error) => error.issue), Effect.flatMap((view) =>
|
|
55
|
+
encode: SchemaGetter.transformEffect((record) => decodeRecord(record.wire).pipe(Effect.mapError((error) => error.issue), Effect.flatMap((view) => Schema.toEquivalence(RecordEnvelope)(view, record) ? Effect.succeed(record.wire) : Effect.fail(new SchemaIssue.InvalidValue({ message: "Archive record view differs from its wire JSON; export the source again" })))))
|
|
57
56
|
}));
|
|
58
57
|
/** Canonical read transport preserves exact evidence while exposing the supported typed view. */
|
|
59
58
|
const ReadRecord = RecordJson.pipe(Schema.decodeTo(Schema.toType(RecordEnvelope), {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RecordFormat.mjs","names":[],"sources":["../../src/durable/RecordFormat.ts"],"sourcesContent":["import { Effect, Schema, SchemaGetter, SchemaIssue } from \"effect\";\n\nimport {\n CanonicalBatch,\n CanonicalRecordEnvelope,\n CURRENT_RECORD_FORMAT,\n RecordEnvelope,\n RecordJson,\n} from \"./Records.ts\";\n\nexport class RecordFormatError extends Schema.TaggedError<RecordFormatError>()(\n \"RecordFormatError\",\n {\n format: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** An archive owns its wire JSON explicitly; the typed fields are only a read view. */\nexport class ExportedRecord extends RecordEnvelope.extend<ExportedRecord>(\n \"@effect-agent/thread/ExportedRecord\",\n)({ wire: RecordJson }) {}\n\nconst decodeRecord = Schema.decodeUnknownEffect(RecordEnvelope);\
|
|
1
|
+
{"version":3,"file":"RecordFormat.mjs","names":[],"sources":["../../src/durable/RecordFormat.ts"],"sourcesContent":["import { Effect, Schema, SchemaGetter, SchemaIssue } from \"effect\";\n\nimport {\n CanonicalBatch,\n CanonicalRecordEnvelope,\n CURRENT_RECORD_FORMAT,\n RecordEnvelope,\n RecordJson,\n} from \"./Records.ts\";\n\nexport class RecordFormatError extends Schema.TaggedError<RecordFormatError>()(\n \"RecordFormatError\",\n {\n format: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** An archive owns its wire JSON explicitly; the typed fields are only a read view. */\nexport class ExportedRecord extends RecordEnvelope.extend<ExportedRecord>(\n \"@effect-agent/thread/ExportedRecord\",\n)({ wire: RecordJson }) {}\n\nconst decodeRecord = Schema.decodeUnknownEffect(RecordEnvelope);\n\nconst parseRecordObject = Schema.decodeEffect(\n Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),\n);\n\nconst decodeExportedRecord = Schema.decodeUnknownEffect(ExportedRecord);\n\n/**\n * Decode stored text directly into its final record, retaining additive wire.\n * Parsing owns the object; the final schema checks the wire bounds and supported fields once.\n * Object-input codecs still validate caller-owned wire when constructing the read view.\n */\nexport const decodeExportRecordJson = (\n encoded: string,\n): Effect.Effect<ExportedRecord, Schema.SchemaError> =>\n parseRecordObject(encoded).pipe(\n Effect.flatMap((wire) => decodeExportedRecord({ ...wire, wire })),\n );\n\n// Both codecs validate RecordJson before this getter; decode the supported view once.\nconst decodeView = SchemaGetter.transformEffect((value: RecordJson) =>\n decodeRecord(value).pipe(\n Effect.map((record) =>\n ExportedRecord.make({ ...record, wire: value }, { disableChecks: true }),\n ),\n Effect.mapError((error) => error.issue),\n ),\n);\n\n/** Decode at the archive boundary, retaining unknown additive fields for a lossless backup. */\nexport const decodeExportRecord = Effect.fnUntraced(function* (format: string, input: RecordJson) {\n if (format !== CURRENT_RECORD_FORMAT)\n return yield* RecordFormatError.make({ format, message: \"Unsupported record format\" });\n\n return yield* Schema.decodeEffect(ExportRecord)(input).pipe(\n Effect.mapError(() => RecordFormatError.make({ format, message: \"Invalid canonical record\" })),\n );\n});\n\n/**\n * Preserve additive fields without process-local side state. Copy with ExportedRecord.make\n * or this codec. Normalizing through RecordEnvelope discards the wire and cannot be encoded\n * as an archive record. Editing the typed view also fails rather than silently changing a log.\n */\nexport const ExportRecord = RecordJson.pipe(\n Schema.decodeTo(Schema.toType(ExportedRecord), {\n decode: decodeView,\n encode: SchemaGetter.transformEffect((record) =>\n decodeRecord(record.wire).pipe(\n Effect.mapError((error) => error.issue),\n // Derive the memoized equivalence only when an archive is encoded.\n Effect.flatMap((view) =>\n Schema.toEquivalence(RecordEnvelope)(view, record)\n ? Effect.succeed(record.wire)\n : Effect.fail(\n new SchemaIssue.InvalidValue({\n message:\n \"Archive record view differs from its wire JSON; export the source again\",\n }),\n ),\n ),\n ),\n ),\n }),\n);\n\n/** Canonical read transport preserves exact evidence while exposing the supported typed view. */\nexport const ReadRecord = RecordJson.pipe(\n Schema.decodeTo(Schema.toType(RecordEnvelope), {\n decode: decodeView,\n encode: SchemaGetter.transformEffect((record) =>\n (record instanceof ExportedRecord\n ? Schema.encodeEffect(ExportRecord)(record)\n : Schema.encodeEffect(RecordEnvelope)(record)\n ).pipe(Effect.mapError((error) => error.issue)),\n ),\n }),\n);\n\nexport const ReadEnvelope = Schema.Struct({\n ...CanonicalRecordEnvelope.fields,\n record: ReadRecord,\n}).pipe(\n Schema.decodeTo(Schema.toType(CanonicalRecordEnvelope), {\n decode: SchemaGetter.transform((fields) =>\n CanonicalRecordEnvelope.make(fields, { disableChecks: true }),\n ),\n encode: SchemaGetter.transform((envelope) => envelope),\n }),\n);\n\n/** Batch identity plus lossless record wire, used when checking a complete immutable log. */\nexport const ExportBatch = Schema.Struct({\n ...CanonicalBatch.fields,\n records: Schema.NonEmptyArray(ExportRecord).check(Schema.isMaxLength(256)),\n});\n"],"mappings":";;;;;;;;;;;;;;AAUA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,QAAQ,OAAO;CACf,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,iBAAb,cAAoC,eAAe,OACjD,qCACF,CAAC,CAAC,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,CAAC;AAEzB,MAAM,eAAe,OAAO,oBAAoB,cAAc;AAE9D,MAAM,oBAAoB,OAAO,aAC/B,OAAO,eAAe,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC,CACpE;AAEA,MAAM,uBAAuB,OAAO,oBAAoB,cAAc;;;;;;AAOtE,MAAa,0BACX,YAEA,kBAAkB,OAAO,CAAC,CAAC,KACzB,OAAO,SAAS,SAAS,qBAAqB;CAAE,GAAG;CAAM;AAAK,CAAC,CAAC,CAClE;AAGF,MAAM,aAAa,aAAa,iBAAiB,UAC/C,aAAa,KAAK,CAAC,CAAC,KAClB,OAAO,KAAK,WACV,eAAe,KAAK;CAAE,GAAG;CAAQ,MAAM;AAAM,GAAG,EAAE,eAAe,KAAK,CAAC,CACzE,GACA,OAAO,UAAU,UAAU,MAAM,KAAK,CACxC,CACF;;AAGA,MAAa,qBAAqB,OAAO,WAAW,WAAW,QAAgB,OAAmB;CAChG,IAAI,WAAA,yBACF,OAAO,OAAO,kBAAkB,KAAK;EAAE;EAAQ,SAAS;CAA4B,CAAC;CAEvF,OAAO,OAAO,OAAO,aAAa,YAAY,CAAC,CAAC,KAAK,CAAC,CAAC,KACrD,OAAO,eAAe,kBAAkB,KAAK;EAAE;EAAQ,SAAS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as DeclaredPendingBatchEvidence, G as RecoveryDecision, H as OpenToolCallEvidence, I as DelegationAdmissionEvidence, J as ReleaseOrphanChildReservation, K as RecoveryEvidence, L as EnsureWaitingForChild, M as AwaitUnknownResolution, N as CompleteChildAdmission, O as AwaitChildAdmissionResolution, P as CompleteMaterialization, Q as RepairSubagentStartLink, R as FinalizeLedgerFromHistory, T as ApplyJoinAccounting, U as PendingApprovalEvidence, V as OpenDelegationCallEvidence, W as PropagateChildAbort, X as RepairJoinMarker, Y as RepairInputMarker, Z as RepairReadiness, at as SettleJoinedWithHost, et as ResumePendingToolBatch, it as SettleAborted, j as AwaitParentEstablishment, k as AwaitChildSettlement, nt as ResumeWaitingParent, ot as classifyRecovery, rt as RevertJoining, st as pendingApprovalForRecovery, tt as ResumeSuspended, w as ApplyInput, z as MarkUnknown } from "../Admin-
|
|
1
|
+
import { $ as ResumeFromTurnBoundary, A as AwaitHostSettlement, B as NoAction, D as AwaitApprovalDecision, E as ApplyUnknownResolutions, F as DeclaredPendingBatchEvidence, G as RecoveryDecision, H as OpenToolCallEvidence, I as DelegationAdmissionEvidence, J as ReleaseOrphanChildReservation, K as RecoveryEvidence, L as EnsureWaitingForChild, M as AwaitUnknownResolution, N as CompleteChildAdmission, O as AwaitChildAdmissionResolution, P as CompleteMaterialization, Q as RepairSubagentStartLink, R as FinalizeLedgerFromHistory, T as ApplyJoinAccounting, U as PendingApprovalEvidence, V as OpenDelegationCallEvidence, W as PropagateChildAbort, X as RepairJoinMarker, Y as RepairInputMarker, Z as RepairReadiness, at as SettleJoinedWithHost, et as ResumePendingToolBatch, it as SettleAborted, j as AwaitParentEstablishment, k as AwaitChildSettlement, nt as ResumeWaitingParent, ot as classifyRecovery, rt as RevertJoining, st as pendingApprovalForRecovery, tt as ResumeSuspended, w as ApplyInput, z as MarkUnknown } from "../Admin-C4mPa0M2.mjs";
|
|
2
2
|
export { ApplyInput, ApplyJoinAccounting, ApplyUnknownResolutions, AwaitApprovalDecision, AwaitChildAdmissionResolution, AwaitChildSettlement, AwaitHostSettlement, AwaitParentEstablishment, AwaitUnknownResolution, CompleteChildAdmission, CompleteMaterialization, DeclaredPendingBatchEvidence, DelegationAdmissionEvidence, EnsureWaitingForChild, FinalizeLedgerFromHistory, MarkUnknown, NoAction, OpenDelegationCallEvidence, OpenToolCallEvidence, PendingApprovalEvidence, PropagateChildAbort, RecoveryDecision, RecoveryEvidence, ReleaseOrphanChildReservation, RepairInputMarker, RepairJoinMarker, RepairReadiness, RepairSubagentStartLink, ResumeFromTurnBoundary, ResumePendingToolBatch, ResumeSuspended, ResumeWaitingParent, RevertJoining, SettleAborted, SettleJoinedWithHost, classifyRecovery, pendingApprovalForRecovery };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { C as EvidenceReference, ot as RunContextRecorded, st as RunContinuation } from "../Records-BTnGRdcf.mjs";
|
|
2
|
-
import { _o as ProgressAppendRecord } from "../Admin-
|
|
3
|
-
import { S as resolveEvidence, _ as executionRunIds, a as canonicalRecordBytes, b as terminalUsageCharge, c as prepareProgressAppend, d as resolveExecutionEvidence, f as runEvidence, g as canonicalRunIds, h as verifyRunContinuations, l as readContinuation, m as validateSuffix, n as CurrentRunWriter, o as isOperationalRecord, p as validateProgressAppend, r as ProgressAppendReader, s as makeProgressWriter, t as CurrentRunSettlement, u as readRunEvidenceSnapshot, v as isPreContinuationFact, x as reference, y as isWorkHandoff } from "../RunContinuation-
|
|
2
|
+
import { _o as ProgressAppendRecord } from "../Admin-C4mPa0M2.mjs";
|
|
3
|
+
import { S as resolveEvidence, _ as executionRunIds, a as canonicalRecordBytes, b as terminalUsageCharge, c as prepareProgressAppend, d as resolveExecutionEvidence, f as runEvidence, g as canonicalRunIds, h as verifyRunContinuations, l as readContinuation, m as validateSuffix, n as CurrentRunWriter, o as isOperationalRecord, p as validateProgressAppend, r as ProgressAppendReader, s as makeProgressWriter, t as CurrentRunSettlement, u as readRunEvidenceSnapshot, v as isPreContinuationFact, x as reference, y as isWorkHandoff } from "../RunContinuation-DMbA81sZ.mjs";
|
|
4
4
|
export { CurrentRunSettlement, CurrentRunWriter, EvidenceReference, ProgressAppendReader, type ProgressAppendRecord, RunContextRecorded, RunContinuation, canonicalRecordBytes, canonicalRunIds, executionRunIds, isOperationalRecord, isPreContinuationFact, isWorkHandoff, makeProgressWriter, prepareProgressAppend, readContinuation, readRunEvidenceSnapshot, reference, resolveEvidence, resolveExecutionEvidence, runEvidence, terminalUsageCharge, validateProgressAppend, validateSuffix, verifyRunContinuations };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { it as RunContinuation, rt as RunContextRecorded, x as EvidenceReference } from "../Records-CZRedCE7.mjs";
|
|
2
2
|
import { _t as executionRunIds, bt as isWorkHandoff, gt as canonicalRunIds, vt as isPreContinuationFact, xt as terminalUsageCharge } from "../ThreadStore-D2rqtt7k.mjs";
|
|
3
|
-
import { a as canonicalRecordBytes, b as reference, c as prepareProgressAppend, d as resolveExecutionEvidence, f as runEvidence, h as verifyRunContinuations, l as readContinuation, m as validateSuffix, n as CurrentRunWriter, o as isOperationalRecord, p as validateProgressAppend, r as ProgressAppendReader, s as makeProgressWriter, t as CurrentRunSettlement, u as readRunEvidenceSnapshot, x as resolveEvidence } from "../RunContinuation-
|
|
3
|
+
import { a as canonicalRecordBytes, b as reference, c as prepareProgressAppend, d as resolveExecutionEvidence, f as runEvidence, h as verifyRunContinuations, l as readContinuation, m as validateSuffix, n as CurrentRunWriter, o as isOperationalRecord, p as validateProgressAppend, r as ProgressAppendReader, s as makeProgressWriter, t as CurrentRunSettlement, u as readRunEvidenceSnapshot, x as resolveEvidence } from "../RunContinuation-DWiO2K9D.mjs";
|
|
4
4
|
export { CurrentRunSettlement, CurrentRunWriter, EvidenceReference, ProgressAppendReader, RunContextRecorded, RunContinuation, canonicalRecordBytes, canonicalRunIds, executionRunIds, isOperationalRecord, isPreContinuationFact, isWorkHandoff, makeProgressWriter, prepareProgressAppend, readContinuation, readRunEvidenceSnapshot, reference, resolveEvidence, resolveExecutionEvidence, runEvidence, terminalUsageCharge, validateProgressAppend, validateSuffix, verifyRunContinuations };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $o as subagentJoinedRecordId, Ao as agentUpdateRecordId, Bo as modelResponseInterruptedRecordId, Co as JournalBoundary, Cs as workerOriginRecordId, Do as RunJournalUsage, Eo as RunJournalProjection, Es as toolCallSettledRecordId, Fo as compactionRecordId, Go as promptFromCanonicalRecords, Ho as peerMessageRecordId, Io as firstWorkerInputRecordId, Jo as runDurationRecordId, Ko as runCompletedRecordId, Lo as initialRunJournal, Mo as childIdempotencyKeyFor, No as childThreadIdFor, Po as compactionBatchId, Qo as subagentJoinBatchId, Ro as markUnknownBatchId, Ss as workerInputRecordId, To as RunJournalError, Uo as projectRunJournal, Vo as modelResponseRecordId, Wo as projectRunJournalStream, Xo as runStartedBatchId, Yo as runIdForSubmission, Zo as runStartedRecordId, _s as turnIdForRun, as as subagentStartedRecordId, bs as turnResultsBatch, cs as toolCallResolutionBatchId, ds as toolCallUnknownRecordId, es as subagentLineageBatchId, fs as toolStepSettledBatchId, gs as turnCanonicalBatch, hs as turnBatchId, is as subagentStartedBatchId, jo as approvalDecisionBatchId, ko as TurnCommitInput, ls as toolCallResolvedRecordId, ms as turnApprovalsBatchId, ns as subagentRequestedBatchId, os as toolApprovalDecisionRecordId, ps as toolStepSettledRecordId, qo as runDurationBatchId, rs as subagentRequestedRecordId, ss as toolApprovalRequestRecordId, ts as subagentLineageRecordId, us as toolCallResultBatchId, vs as turnResponseBatch, wo as RunJournalContext, ws as workerReportRecordId, xs as turnResultsBatchId, ys as turnResponseBatchId, zo as modelResponseInterruptedBatchId } from "../Admin-
|
|
1
|
+
import { $o as subagentJoinedRecordId, Ao as agentUpdateRecordId, Bo as modelResponseInterruptedRecordId, Co as JournalBoundary, Cs as workerOriginRecordId, Do as RunJournalUsage, Eo as RunJournalProjection, Es as toolCallSettledRecordId, Fo as compactionRecordId, Go as promptFromCanonicalRecords, Ho as peerMessageRecordId, Io as firstWorkerInputRecordId, Jo as runDurationRecordId, Ko as runCompletedRecordId, Lo as initialRunJournal, Mo as childIdempotencyKeyFor, No as childThreadIdFor, Po as compactionBatchId, Qo as subagentJoinBatchId, Ro as markUnknownBatchId, Ss as workerInputRecordId, To as RunJournalError, Uo as projectRunJournal, Vo as modelResponseRecordId, Wo as projectRunJournalStream, Xo as runStartedBatchId, Yo as runIdForSubmission, Zo as runStartedRecordId, _s as turnIdForRun, as as subagentStartedRecordId, bs as turnResultsBatch, cs as toolCallResolutionBatchId, ds as toolCallUnknownRecordId, es as subagentLineageBatchId, fs as toolStepSettledBatchId, gs as turnCanonicalBatch, hs as turnBatchId, is as subagentStartedBatchId, jo as approvalDecisionBatchId, ko as TurnCommitInput, ls as toolCallResolvedRecordId, ms as turnApprovalsBatchId, ns as subagentRequestedBatchId, os as toolApprovalDecisionRecordId, ps as toolStepSettledRecordId, qo as runDurationBatchId, rs as subagentRequestedRecordId, ss as toolApprovalRequestRecordId, ts as subagentLineageRecordId, us as toolCallResultBatchId, vs as turnResponseBatch, wo as RunJournalContext, ws as workerReportRecordId, xs as turnResultsBatchId, ys as turnResponseBatchId, zo as modelResponseInterruptedBatchId } from "../Admin-C4mPa0M2.mjs";
|
|
2
2
|
export { JournalBoundary, RunJournalContext, RunJournalError, RunJournalProjection, RunJournalUsage, TurnCommitInput, agentUpdateRecordId, approvalDecisionBatchId, childIdempotencyKeyFor, childThreadIdFor, compactionBatchId, compactionRecordId, firstWorkerInputRecordId, initialRunJournal, markUnknownBatchId, modelResponseInterruptedBatchId, modelResponseInterruptedRecordId, modelResponseRecordId, peerMessageRecordId, projectRunJournal, projectRunJournalStream, promptFromCanonicalRecords, runCompletedRecordId, runDurationBatchId, runDurationRecordId, runIdForSubmission, runStartedBatchId, runStartedRecordId, subagentJoinBatchId, subagentJoinedRecordId, subagentLineageBatchId, subagentLineageRecordId, subagentRequestedBatchId, subagentRequestedRecordId, subagentStartedBatchId, subagentStartedRecordId, toolApprovalDecisionRecordId, toolApprovalRequestRecordId, toolCallResolutionBatchId, toolCallResolvedRecordId, toolCallResultBatchId, toolCallSettledRecordId, toolCallUnknownRecordId, toolStepSettledBatchId, toolStepSettledRecordId, turnApprovalsBatchId, turnBatchId, turnCanonicalBatch, turnIdForRun, turnResponseBatch, turnResponseBatchId, turnResultsBatch, turnResultsBatchId, workerInputRecordId, workerOriginRecordId, workerReportRecordId };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Fr as RunStorageSession, Ir as RunWriter, Lr as layer, Mr as RunChildBudgetReservation, Nr as RunOwnership, Pr as RunStorage, Rr as make, So as makeStorageOwner, bo as StorageOwner, jr as RunChildAttachment, vo as MutationGate, xo as StorageOwnerService, yo as OwnerGeneration, zr as makeRunWriter } from "../Admin-
|
|
1
|
+
import { Fr as RunStorageSession, Ir as RunWriter, Lr as layer, Mr as RunChildBudgetReservation, Nr as RunOwnership, Pr as RunStorage, Rr as make, So as makeStorageOwner, bo as StorageOwner, jr as RunChildAttachment, vo as MutationGate, xo as StorageOwnerService, yo as OwnerGeneration, zr as makeRunWriter } from "../Admin-C4mPa0M2.mjs";
|
|
2
2
|
export { type MutationGate, type OwnerGeneration, RunChildAttachment, RunChildBudgetReservation, RunOwnership, RunStorage, RunStorageSession, RunWriter, StorageOwner, type StorageOwnerService, layer, make, makeRunWriter, makeStorageOwner };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as Principal } from "../Receipt-BkM21Qiu.mjs";
|
|
2
2
|
import { b as DefinitionDigests } from "../Records-BTnGRdcf.mjs";
|
|
3
|
-
import { cr as DurableSubmitAgent, pt as AdmissionFence } from "../Admin-
|
|
3
|
+
import { cr as DurableSubmitAgent, pt as AdmissionFence } from "../Admin-C4mPa0M2.mjs";
|
|
4
4
|
import { A as ScheduleSnapshotPage, B as ScheduledInputAdmission, C as ScheduleRecord, D as ScheduleScope, F as ScheduleTimingRequest, I as ScheduleValidationError, L as ScheduleWake, M as ScheduleStore, N as ScheduleStoreFailure, W as SchedulingLimits, c as ScheduleDestination, f as ScheduleId, j as ScheduleStorageError, k as ScheduleSnapshot, m as ScheduleKey, n as ScheduleAuthorizationError, r as ScheduleAuthorizer, y as ScheduleOwner } from "../Schedule-CDgTz0vj.mjs";
|
|
5
5
|
import { Context, Crypto, Effect, Layer, Schema } from "effect";
|
|
6
6
|
declare namespace Scheduling_d_exports {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Br as SettlementPublication, Gr as validateCanonicalSettlement, Hr as SettlementPublicationFailure, Kr as validateJoinedSettlement, Ur as SettlementPublicationResult, Vr as SettlementPublicationAuthority, Wr as SettlementPublisher, qr as validatePublication } from "../Admin-
|
|
1
|
+
import { Br as SettlementPublication, Gr as validateCanonicalSettlement, Hr as SettlementPublicationFailure, Kr as validateJoinedSettlement, Ur as SettlementPublicationResult, Vr as SettlementPublicationAuthority, Wr as SettlementPublisher, qr as validatePublication } from "../Admin-C4mPa0M2.mjs";
|
|
2
2
|
export { SettlementPublication, SettlementPublicationAuthority, SettlementPublicationFailure, SettlementPublicationResult, SettlementPublisher, validateCanonicalSettlement, validateJoinedSettlement, validatePublication };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { n as MemoryContent } from "../MemoryReference-B8Q3UJoJ.mjs";
|
|
2
2
|
import { t as Any } from "../MemoryNamespace-BbRW5p71.mjs";
|
|
3
3
|
import { MemoryDocument, MemoryMutationFailpoint, MemoryMutationFailure, MemoryReader, MemoryStorageError, MemoryWrite, MemoryWriteError, MemoryWriter } from "../core/MemoryStore.mjs";
|
|
4
|
+
import { SqlStorageOwner } from "./SqlStorageOwner.mjs";
|
|
4
5
|
import { Context, Effect, Layer, Schema } from "effect";
|
|
5
6
|
import * as SqlClientService from "effect/sql/SqlClient";
|
|
6
|
-
import { SqlError } from "effect/sql/SqlError";
|
|
7
7
|
//#region src/durable/SqlMemoryStore.d.ts
|
|
8
8
|
/** Ordered commands committed atomically by the SQL memory adapter. */
|
|
9
9
|
export declare const SqlMemoryWriteBatch: Schema.$Array<Schema.Union<readonly [Schema.TaggedStruct<"Put", {
|
|
@@ -701,20 +701,6 @@ declare const SqlMemoryBatchWriter_base: Context.ServiceClass<SqlMemoryBatchWrit
|
|
|
701
701
|
* Supplied by the memory store Layers alongside MemoryWriter's single-command API.
|
|
702
702
|
*/
|
|
703
703
|
export declare class SqlMemoryBatchWriter extends SqlMemoryBatchWriter_base {}
|
|
704
|
-
/**
|
|
705
|
-
* An exclusive database owner's transaction gate. All cached services over that database
|
|
706
|
-
* must share this identity, and every failed transaction must run its invalidators before
|
|
707
|
-
* releasing readers. Hosts with independent database writers must leave this unset.
|
|
708
|
-
*/
|
|
709
|
-
export interface SqlStorageOwner {
|
|
710
|
-
/** Cache identity for transaction decorators; omission uses the owner itself.
|
|
711
|
-
* Shared identities must name the same database, reader gate and invalidator set. */
|
|
712
|
-
readonly identity?: object;
|
|
713
|
-
readonly read: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
714
|
-
readonly transaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | SqlError, R | SqlClientService.SqlClient>;
|
|
715
|
-
readonly invalidators: Set<() => void>;
|
|
716
|
-
}
|
|
717
|
-
export declare const SqlStorageOwner: Context.Reference<SqlStorageOwner | undefined>;
|
|
718
704
|
/**
|
|
719
705
|
* Independent adapter limits. Counts and encoded bytes include durable operation receipts.
|
|
720
706
|
* Bytes count UTF-8 row payloads plus 128 bytes per row, excluding SQLite pages/indexes.
|
|
@@ -739,4 +725,5 @@ export declare const memoryStoreLayer: Layer.Layer<MemoryReader | MemoryWriter |
|
|
|
739
725
|
/** Reads an existing memory schema without writes, transactions, or mutation failpoints. */
|
|
740
726
|
export declare const memoryReaderLayer: Layer.Layer<MemoryReader, MemoryStorageError, SqlClientService.SqlClient>;
|
|
741
727
|
//#endregion
|
|
728
|
+
export { SqlStorageOwner };
|
|
742
729
|
//# sourceMappingURL=SqlMemoryStore.d.mts.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { n as utf8ByteLength } from "../utf8-B5pAmhTo.mjs";
|
|
2
2
|
import { MemoryNamespaceAddress } from "../core/MemoryNamespace.mjs";
|
|
3
3
|
import { MemoryDocument, MemoryKey, MemoryMutationFailpoint, MemoryOperationConflict, MemoryReader, MemoryStorageError, MemoryWrite, MemoryWriter, applyMemoryWrite } from "../core/MemoryStore.mjs";
|
|
4
|
+
import { SqlStorageOwner } from "./SqlStorageOwner.mjs";
|
|
4
5
|
import { Clock, Context, Effect, Layer, Schema } from "effect";
|
|
5
6
|
import * as SqlClientService from "effect/sql/SqlClient";
|
|
6
7
|
//#region src/durable/SqlMemoryStore.ts
|
|
@@ -29,7 +30,6 @@ const SqlMemoryWriteBatch = Schema.Array(MemoryWrite.Wire).check(Schema.isMaxLen
|
|
|
29
30
|
* Supplied by the memory store Layers alongside MemoryWriter's single-command API.
|
|
30
31
|
*/
|
|
31
32
|
var SqlMemoryBatchWriter = class extends Context.Service()("@effect-agent/thread/SqlMemoryBatchWriter") {};
|
|
32
|
-
const SqlStorageOwner = Context.Reference("@effect-agent/thread/SqlStorageOwner", { defaultValue: () => void 0 });
|
|
33
33
|
/**
|
|
34
34
|
* Independent adapter limits. Counts and encoded bytes include durable operation receipts.
|
|
35
35
|
* Bytes count UTF-8 row payloads plus 128 bytes per row, excluding SQLite pages/indexes.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SqlMemoryStore.mjs","names":[],"sources":["../../src/durable/SqlMemoryStore.ts"],"sourcesContent":["import { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/sql/SqlClient\";\nimport type { SqlError } from \"effect/sql/SqlError\";\n\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { type Any as MemoryNamespace, MemoryNamespaceAddress } from \"../core/MemoryNamespace.ts\";\nimport {\n applyMemoryWrite,\n MemoryDocument,\n MemoryKey,\n MemoryMutationFailpoint,\n type MemoryMutationFailure,\n MemoryOperationConflict,\n MemoryReader,\n MemoryStorageError,\n MemoryWrite,\n type MemoryWriteError,\n MemoryWriter,\n} from \"../core/MemoryStore.ts\";\n\nconst STORAGE_VERSION = 2 as const;\nconst METADATA_COMPONENT = \"memory\";\nconst DOCUMENT_TABLE = \"effect_agent_memory_documents_v1\";\nconst RECEIPT_TABLE = \"effect_agent_memory_receipts_v1\";\nconst USAGE_COMPONENT = \"memory-usage\";\nconst USAGE_TABLE = \"effect_agent_memory_usage_v1\";\nconst MAX_STORED_JSON_CODE_UNITS = 16 * 1024 * 1024;\nconst StoredJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_JSON_CODE_UNITS));\n\nconst EncodedMemoryChange = Schema.Struct({\n commandJson: StoredJson,\n documentJson: StoredJson,\n resultJson: StoredJson,\n});\n\nconst makeEquivalentContent = () =>\n Schema.toEquivalence(Schema.toEncoded(MemoryWrite.Wire.members[0].fields.content));\n\nlet equivalentContent: ReturnType<typeof makeEquivalentContent> | undefined;\n\nconst makeEquivalentScopes = () => Schema.toEquivalence(MemoryWrite.Wire.members[0].fields.scopes);\nlet equivalentScopes: ReturnType<typeof makeEquivalentScopes> | undefined;\n\n/** Ordered commands committed atomically by the SQL memory adapter. */\nexport const SqlMemoryWriteBatch = Schema.Array(MemoryWrite.Wire).check(Schema.isMaxLength(128));\n\n/**\n * SQL-only bulk writing. Results preserve input order, including exact operation replays.\n * Commands see earlier staged revisions; any refusal rolls back the entire batch. Storage\n * limits apply to every intermediate transition. Empty batches succeed without mutation.\n * Supplied by the memory store Layers alongside MemoryWriter's single-command API.\n */\nexport class SqlMemoryBatchWriter extends Context.Service<\n SqlMemoryBatchWriter,\n {\n readonly changeMany: <Namespace extends MemoryNamespace>(\n writes: ReadonlyArray<MemoryWrite<Namespace>>,\n ) => Effect.Effect<ReadonlyArray<MemoryDocument<Namespace>>, MemoryWriteError>;\n }\n>()(\"@effect-agent/thread/SqlMemoryBatchWriter\") {}\n\n/**\n * An exclusive database owner's transaction gate. All cached services over that database\n * must share this identity, and every failed transaction must run its invalidators before\n * releasing readers. Hosts with independent database writers must leave this unset.\n */\nexport interface SqlStorageOwner {\n /** Cache identity for transaction decorators; omission uses the owner itself.\n * Shared identities must name the same database, reader gate and invalidator set. */\n readonly identity?: object;\n readonly read: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n readonly transaction: <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | SqlError, R | SqlClientService.SqlClient>;\n readonly invalidators: Set<() => void>;\n}\n\nexport const SqlStorageOwner = Context.Reference<SqlStorageOwner | undefined>(\n \"@effect-agent/thread/SqlStorageOwner\",\n { defaultValue: () => undefined },\n);\n\n/**\n * Independent adapter limits. Counts and encoded bytes include durable operation receipts.\n * Bytes count UTF-8 row payloads plus 128 bytes per row, excluding SQLite pages/indexes.\n * Replacements charge their byte delta; receipts and tombstones are never pruned.\n * Optional reserves (default zero) withhold capacity from Put, within the hard totals.\n * They require exclusive upgraded writer ownership: older writers count toward usage\n * but do not honor reserves. Limits are captured when the writer Layer is built.\n */\nexport const SqlMemoryLimits = Context.Reference<{\n readonly maxRowBytes: number;\n readonly maxStorageBytes: number;\n readonly maxDocuments: number;\n readonly maxReceipts: number;\n readonly reservedWithdrawalBytes?: number;\n readonly reservedWithdrawalReceipts?: number;\n}>(\"@effect-agent/thread/SqlMemoryLimits\", {\n defaultValue: () => ({\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n maxStorageBytes: Number.MAX_SAFE_INTEGER,\n maxDocuments: Number.MAX_SAFE_INTEGER,\n maxReceipts: Number.MAX_SAFE_INTEGER,\n }),\n});\n\nconst Limits = Schema.Struct({\n maxRowBytes: Schema.Natural,\n maxStorageBytes: Schema.Natural,\n maxDocuments: Schema.Natural,\n maxReceipts: Schema.Natural,\n reservedWithdrawalBytes: Schema.optional(Schema.Natural),\n reservedWithdrawalReceipts: Schema.optional(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (limits) =>\n (limits.reservedWithdrawalBytes ?? 0) <= limits.maxStorageBytes &&\n (limits.reservedWithdrawalReceipts ?? 0) <= limits.maxReceipts,\n { expected: \"withdrawal reserves within hard storage limits\" },\n ),\n);\n\nconst UsageRow = Schema.Struct({\n documents: Schema.Natural,\n receipts: Schema.Natural,\n bytes: Schema.Natural,\n});\n\ntype DocumentView = { readonly document: MemoryDocument; readonly bytes: number } | null;\ntype ReceiptView = { readonly commandJson: string; readonly result: MemoryDocument } | null;\ntype MemoryView =\n | { readonly _tag: \"Document\"; readonly value: DocumentView }\n | { readonly _tag: \"Receipt\"; readonly value: ReceiptView }\n | { readonly _tag: \"Usage\"; readonly value: typeof UsageRow.Type };\n\n// Demand-loaded views are disposable. The shared owner's gate keeps writes invisible\n// until commit, and its rollback invalidator discards every speculative view together.\nclass MemoryViews {\n private readonly entries = new Map<\n string,\n { readonly view: MemoryView; readonly bytes: number }\n >();\n private bytes = 0;\n\n readonly clear = () => {\n this.entries.clear();\n this.bytes = 0;\n };\n\n get(key: string): MemoryView | undefined {\n const entry = this.entries.get(key);\n\n if (entry === undefined) return undefined;\n this.entries.delete(key);\n this.entries.set(key, entry);\n\n return entry.view;\n }\n\n set(key: string, view: MemoryView): void {\n const previous = this.entries.get(key);\n\n if (previous !== undefined) this.bytes -= previous.bytes;\n this.entries.delete(key);\n const bytes = utf8ByteLength(key) + utf8ByteLength(JSON.stringify(view)) + 128;\n\n if (bytes > 4 * 1024 * 1024) return;\n this.entries.set(key, { view, bytes });\n this.bytes += bytes;\n while (this.entries.size > 128 || this.bytes > 4 * 1024 * 1024) {\n const oldest = this.entries.entries().next().value;\n\n if (oldest === undefined) break;\n this.bytes -= oldest[1].bytes;\n this.entries.delete(oldest[0]);\n }\n }\n}\n\nconst ownedViews = new WeakMap<object, MemoryViews>();\n\nconst memoryViews = Effect.fnUntraced(function* () {\n const owner = yield* SqlStorageOwner;\n\n if (owner === undefined) return undefined;\n const identity = owner.identity ?? owner;\n let views = ownedViews.get(identity);\n\n if (views === undefined) {\n views = new MemoryViews();\n ownedViews.set(identity, views);\n owner.invalidators.add(views.clear);\n }\n\n return views;\n});\n\nconst documentViewKey = (key: MemoryKey) =>\n JSON.stringify([\"document\", key.namespace.address, key.id]);\n\nconst receiptViewKey = (write: MemoryWrite) =>\n JSON.stringify([\"receipt\", write.key.namespace.address, write.operationId]);\n\n// These expressions deliberately match the legacy aggregate's logical byte accounting.\nconst documentBytesSql = (row: string) =>\n `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.document_json AS BLOB)) + 128`;\n\nconst receiptBytesSql = (row: string) =>\n `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.operation_id AS BLOB)) + length(CAST(${row}.command_json AS BLOB)) + length(CAST(${row}.result_json AS BLOB)) + 128`;\n\n// Triggers keep already-open version-2 writers accounted for. Their admission policy\n// is still the old policy; deployment must drain them before relying on reserves.\nconst usageTriggers = [\n { table: DOCUMENT_TABLE, count: \"documents\", bytes: documentBytesSql },\n { table: RECEIPT_TABLE, count: \"receipts\", bytes: receiptBytesSql },\n].flatMap(({ table, count, bytes }) =>\n [\"INSERT\", \"UPDATE\", \"DELETE\"].map((event) => ({\n name: `${table}_usage_${event.toLowerCase()}`,\n sql: `CREATE TRIGGER ${table}_usage_${event.toLowerCase()} AFTER ${event} ON ${table}\n BEGIN\n UPDATE ${USAGE_TABLE} SET\n ${count} = ${count} + ${event === \"INSERT\" ? 1 : event === \"DELETE\" ? -1 : 0},\n bytes = bytes + (${event === \"DELETE\" ? \"0\" : bytes(\"NEW\")}) - (${event === \"INSERT\" ? \"0\" : bytes(\"OLD\")})\n WHERE singleton = 1;\n SELECT CASE WHEN changes() <> 1 THEN RAISE(ABORT, 'missing memory usage') END;\n END`,\n })),\n);\n\nclass MemoryMetadataRow extends Schema.Class<MemoryMetadataRow>(\n \"@effect-agent/storage-sqlite/MemoryMetadataRow\",\n)({\n version: Schema.Int,\n}) {}\n\nclass MemoryTableRow extends Schema.Class<MemoryTableRow>(\n \"@effect-agent/storage-sqlite/MemoryTableRow\",\n)({\n name: Schema.NonEmptyString,\n}) {}\n\nclass MemoryDocumentRow extends Schema.Class<MemoryDocumentRow>(\n \"@effect-agent/storage-sqlite/MemoryDocumentRow\",\n)({\n namespace: MemoryNamespaceAddress,\n source_id: MemoryKey.Wire.fields.id,\n format_version: Schema.Int,\n generation: Schema.Int,\n revision: Schema.NonEmptyString,\n document_json: StoredJson,\n stored_bytes: Schema.Natural,\n}) {}\n\nclass MemoryReceiptRow extends Schema.Class<MemoryReceiptRow>(\n \"@effect-agent/storage-sqlite/MemoryReceiptRow\",\n)({\n namespace: MemoryNamespaceAddress,\n operation_id: MemoryWrite.Wire.members[0].fields.operationId,\n source_id: MemoryKey.Wire.fields.id,\n format_version: Schema.Int,\n command_json: StoredJson,\n result_json: StoredJson,\n}) {}\n\nclass MemoryChangeCountRow extends Schema.Class<MemoryChangeCountRow>(\n \"@effect-agent/storage-sqlite/MemoryChangeCountRow\",\n)({\n changed: Schema.Int,\n}) {}\n\nclass StoredMemoryCommand extends Schema.Class<StoredMemoryCommand>(\n \"@effect-agent/storage-sqlite/StoredMemoryCommand\",\n)({\n version: Schema.Literal(STORAGE_VERSION),\n value: MemoryWrite.Wire,\n}) {}\n\nclass StoredMemoryResult extends Schema.Class<StoredMemoryResult>(\n \"@effect-agent/storage-sqlite/StoredMemoryResult\",\n)({\n version: Schema.Literal(STORAGE_VERSION),\n value: MemoryDocument.Wire,\n}) {}\n\nconst StoredVersionHeader = Schema.Struct({ version: Schema.Int });\n\nexport type SqliteMemoryInitializationError = MemoryStorageError | MemoryMutationFailure;\n\nconst storageError = (\n operation: string,\n reason: MemoryStorageError[\"reason\"] = \"unavailable\",\n): MemoryStorageError => MemoryStorageError.make({ operation, reason });\n\nconst query = <A extends object>(\n effect: Effect.Effect<ReadonlyArray<A>, SqlError>,\n operation: string,\n) => effect.pipe(Effect.mapError(() => storageError(operation)));\n\nconst decodeRows = <A, I>(\n schema: Schema.Codec<A, I, never>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.Effect<ReadonlyArray<A>, MemoryStorageError> =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst decodeInput = <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, MemoryStorageError> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => storageError(operation, \"invalid-input\")),\n );\n\nconst encodeJson = <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: A,\n operation: string,\n): Effect.Effect<string, MemoryStorageError> =>\n Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst validateEncodedChange = Effect.fnUntraced(function* (\n encoded: typeof EncodedMemoryChange.Type,\n operation: string,\n): Effect.fn.Return<void, MemoryStorageError> {\n yield* Schema.decodeEffect(EncodedMemoryChange)(encoded).pipe(\n Effect.mapError(() => storageError(operation, \"invalid-input\")),\n );\n});\n\nconst decodeVersionedJson = Effect.fnUntraced(function* <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: string,\n operation: string,\n): Effect.fn.Return<A, MemoryStorageError> {\n const header = yield* Schema.decodeEffect(Schema.fromJsonString(StoredVersionHeader))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\n if (header.version !== STORAGE_VERSION) {\n return yield* storageError(operation, \"incompatible\");\n }\n\n const decoded = yield* Schema.decodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\n const canonical = yield* encodeJson(schema, decoded, operation);\n\n if (canonical !== value) return yield* storageError(operation, \"corrupt\");\n\n return decoded;\n});\n\nconst validateDocument = Effect.fnUntraced(function* (\n document: MemoryDocument,\n key: MemoryKey,\n operation: string,\n): Effect.fn.Return<MemoryDocument, MemoryStorageError> {\n if (\n document.key.namespace.address !== key.namespace.address ||\n document.key.id !== key.id ||\n document.source.id !== key.id ||\n document.source.revision !== String(document.generation) ||\n (document.generation === 1) !== (document.predecessor === null) ||\n (document.predecessor !== null &&\n (document.predecessor.id !== key.id ||\n document.predecessor.revision !== String(document.generation - 1)))\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n\n return document;\n});\n\nconst validateReceiptResult = Effect.fnUntraced(function* (\n command: MemoryWrite,\n result: MemoryDocument,\n operation: string,\n): Effect.fn.Return<void, MemoryStorageError> {\n if ((result.predecessor?.revision ?? null) !== command.expectedRevision) {\n return yield* storageError(operation, \"corrupt\");\n }\n if (command._tag === \"Put\") {\n if (result._tag !== \"ActiveMemoryDocument\" || result.source.locator !== command.locator) {\n return yield* storageError(operation, \"corrupt\");\n }\n if (\n !(equivalentContent ??= makeEquivalentContent())(command.content, result.content) ||\n !(equivalentScopes ??= makeEquivalentScopes())(command.scopes, result.scopes)\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n\n return;\n }\n if (\n result._tag !== \"WithdrawnMemoryDocument\" ||\n result.reason !== command.reason ||\n result.predecessor === null ||\n result.source.locator !== result.predecessor.locator\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n});\n\nconst readUsage = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const views = yield* memoryViews();\n const operation = \"read memory usage\";\n\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT documents, receipts, bytes FROM effect_agent_memory_usage_v1 WHERE singleton = 1\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(UsageRow, rows, operation)));\n\n if (rows.length !== 1) return yield* storageError(operation, \"corrupt\");\n\n views?.set(\"usage\", { _tag: \"Usage\", value: rows[0] });\n\n return rows[0];\n});\n\n// Called inside schema initialization's transaction. The separate marker distinguishes\n// a legacy store from damaged established accounting; reopening never rebuilds counters.\nconst initializeMemoryUsage = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const failpoint = yield* MemoryMutationFailpoint;\n const operation = \"initialize memory usage\";\n\n const metadata = yield* sql<Record<string, unknown>>`\n SELECT version FROM effect_agent_memory_metadata WHERE component = ${USAGE_COMPONENT}\n `.pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));\n\n const objects = yield* sql<Record<string, unknown>>`\n SELECT name FROM sqlite_master\n WHERE name = ${USAGE_TABLE} OR name IN ${sql.in(usageTriggers.map((trigger) => trigger.name))}\n `.pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));\n\n if (metadata.length === 0) {\n if (objects.length !== 0) return yield* storageError(operation, \"corrupt\");\n yield* failpoint.hit(\"memory:initialize:before-accounting\");\n yield* sql`\n CREATE TABLE effect_agent_memory_usage_v1 (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n documents INTEGER NOT NULL CHECK (typeof(documents) = 'integer' AND documents BETWEEN 0 AND 9007199254740991),\n receipts INTEGER NOT NULL CHECK (typeof(receipts) = 'integer' AND receipts BETWEEN 0 AND 9007199254740991),\n bytes INTEGER NOT NULL CHECK (typeof(bytes) = 'integer' AND bytes BETWEEN 0 AND 9007199254740991)\n )\n `;\n yield* sql`\n INSERT INTO effect_agent_memory_usage_v1 (singleton, documents, receipts, bytes)\n SELECT 1,\n (SELECT COUNT(*) FROM effect_agent_memory_documents_v1),\n (SELECT COUNT(*) FROM effect_agent_memory_receipts_v1),\n COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(document_json AS BLOB)) + 128) FROM effect_agent_memory_documents_v1), 0) +\n COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(operation_id AS BLOB)) + length(CAST(command_json AS BLOB)) +\n length(CAST(result_json AS BLOB)) + 128) FROM effect_agent_memory_receipts_v1), 0)\n `;\n for (const trigger of usageTriggers) yield* sql.unsafe(trigger.sql);\n yield* sql`\n INSERT INTO effect_agent_memory_metadata (component, version) VALUES (${USAGE_COMPONENT}, 1)\n `;\n yield* failpoint.hit(\"memory:initialize:after-accounting\");\n } else {\n if (metadata.length !== 1 || metadata[0].version !== 1) {\n return yield* storageError(operation, \"incompatible\");\n }\n if (objects.length !== usageTriggers.length + 1) {\n return yield* storageError(operation, \"corrupt\");\n }\n }\n yield* readUsage();\n});\n\nconst initializeMemorySchema = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const transaction = owner === undefined ? sql.withTransaction : owner.transaction;\n const failpoint = yield* MemoryMutationFailpoint;\n\n yield* failpoint.hit(\"memory:initialize:before\");\n yield* transaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE IF NOT EXISTS effect_agent_memory_metadata (\n component TEXT PRIMARY KEY NOT NULL,\n version INTEGER NOT NULL\n )\n `;\n\n const metadataRows = yield* sql<Record<string, unknown>>`\n SELECT version\n FROM effect_agent_memory_metadata\n WHERE component = ${METADATA_COMPONENT}\n `;\n\n const metadata = yield* decodeRows(\n MemoryMetadataRow,\n metadataRows,\n \"decode memory schema version\",\n );\n\n if (metadata.length > 1)\n return yield* storageError(\"decode memory schema version\", \"corrupt\");\n const currentVersion = metadata[0]?.version;\n\n if (currentVersion !== undefined && currentVersion !== STORAGE_VERSION) {\n return yield* storageError(\"initialize memory schema\", \"incompatible\");\n }\n if (currentVersion === undefined) {\n const tableRows = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table' AND name IN (${DOCUMENT_TABLE}, ${RECEIPT_TABLE})\n `;\n\n const existingTables = yield* decodeRows(\n MemoryTableRow,\n tableRows,\n \"inspect memory schema\",\n );\n\n if (existingTables.length > 0) {\n return yield* storageError(\"initialize memory schema\", \"incompatible\");\n }\n yield* sql`\n CREATE TABLE effect_agent_memory_documents_v1 (\n namespace TEXT NOT NULL,\n source_id TEXT NOT NULL,\n format_version INTEGER NOT NULL,\n generation INTEGER NOT NULL,\n revision TEXT NOT NULL,\n document_json TEXT NOT NULL,\n PRIMARY KEY (namespace, source_id)\n )\n `;\n yield* sql`\n CREATE TABLE effect_agent_memory_receipts_v1 (\n namespace TEXT NOT NULL,\n operation_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n format_version INTEGER NOT NULL,\n command_json TEXT NOT NULL,\n result_json TEXT NOT NULL,\n PRIMARY KEY (namespace, operation_id)\n )\n `;\n yield* sql`\n INSERT INTO effect_agent_memory_metadata (component, version)\n VALUES (${METADATA_COMPONENT}, ${STORAGE_VERSION})\n `;\n }\n yield* sql`\n SELECT namespace, source_id, format_version, generation, revision, document_json\n FROM effect_agent_memory_documents_v1\n LIMIT 0\n `;\n yield* sql`\n SELECT namespace, operation_id, source_id, format_version, command_json, result_json\n FROM effect_agent_memory_receipts_v1\n LIMIT 0\n `;\n yield* initializeMemoryUsage();\n }),\n ).pipe(Effect.catchTag(\"SqlError\", () => Effect.fail(storageError(\"initialize memory schema\"))));\n yield* failpoint.hit(\"memory:initialize:after\");\n});\n\nconst makeMemoryReader = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const views = yield* memoryViews();\n\n const readDocuments = Effect.fnUntraced(\n function* (\n keys: ReadonlyArray<MemoryKey>,\n operation: string,\n ): Effect.fn.Return<ReadonlyMap<string, DocumentView>, MemoryStorageError> {\n const found = new Map<string, DocumentView>();\n const missing = new Map<string, MemoryKey>();\n\n for (const key of keys) {\n const viewKey = documentViewKey(key);\n const cached = views?.get(viewKey);\n\n if (cached?._tag === \"Document\") found.set(viewKey, cached.value);\n else missing.set(viewKey, key);\n }\n const pending = Array.from(missing);\n\n // Each exact composite key uses two bindings. No history or unrelated rows are loaded.\n for (let index = 0; index < pending.length; index += 50) {\n const requested = new Map(pending.slice(index, index + 50));\n\n const rawRows = yield* query(\n sql<Record<string, unknown>>`\n SELECT namespace, source_id, format_version, generation, revision, document_json,\n length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(document_json AS BLOB)) + 128 AS stored_bytes\n FROM effect_agent_memory_documents_v1\n WHERE ${sql.or(\n Array.from(\n requested.values(),\n (key) => sql`(namespace = ${key.namespace.address} AND source_id = ${key.id})`,\n ),\n )}\n `,\n operation,\n );\n\n const rows = yield* decodeRows(MemoryDocumentRow, rawRows, operation);\n\n for (const row of rows) {\n const viewKey = JSON.stringify([\"document\", row.namespace, row.source_id]);\n const key = requested.get(viewKey);\n\n if (key === undefined || found.has(viewKey))\n return yield* storageError(operation, \"corrupt\");\n if (row.format_version !== STORAGE_VERSION)\n return yield* storageError(operation, \"incompatible\");\n\n const stored = yield* decodeVersionedJson(\n StoredMemoryResult,\n row.document_json,\n operation,\n );\n\n const document = stored.value;\n\n yield* validateDocument(document, key, operation);\n if (row.generation !== document.generation || row.revision !== document.source.revision)\n return yield* storageError(operation, \"corrupt\");\n found.set(viewKey, { document, bytes: row.stored_bytes });\n }\n\n for (const viewKey of requested.keys()) {\n const value = found.get(viewKey) ?? null;\n\n found.set(viewKey, value);\n views?.set(viewKey, { _tag: \"Document\", value });\n }\n }\n\n return found;\n },\n (effect) => (owner === undefined ? effect : owner.read(effect)),\n );\n\n const get = Effect.fnUntraced(function* (key: MemoryKey) {\n const decodedKey = yield* decodeInput(MemoryKey.Wire, key, \"get memory document\");\n\n const documents = yield* readDocuments([decodedKey], \"get memory document\");\n\n return documents.get(documentViewKey(decodedKey))?.document ?? null;\n });\n\n return { get, readDocuments };\n});\n\nconst makeMemoryServices = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const views = yield* memoryViews();\n\n const usage = readUsage().pipe(\n Effect.provideService(SqlClientService.SqlClient, sql),\n Effect.provideService(SqlStorageOwner, owner),\n );\n\n const transaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n owner === undefined\n ? sql.withTransaction(effect)\n : owner.transaction(effect).pipe(Effect.provideService(SqlClientService.SqlClient, sql));\n\n const failpoint = yield* MemoryMutationFailpoint;\n const limits = yield* decodeInput(Limits, yield* SqlMemoryLimits, \"memory storage limits\");\n\n yield* initializeMemorySchema();\n const { get, readDocuments } = yield* makeMemoryReader();\n\n const readReceipts = Effect.fnUntraced(function* (\n writes: ReadonlyArray<MemoryWrite>,\n operation: string,\n ): Effect.fn.Return<ReadonlyMap<string, ReceiptView>, MemoryStorageError> {\n const found = new Map<string, ReceiptView>();\n const missing = new Map<string, MemoryWrite>();\n\n for (const write of writes) {\n const viewKey = receiptViewKey(write);\n const cached = views?.get(viewKey);\n\n if (cached?._tag === \"Receipt\") found.set(viewKey, cached.value);\n else missing.set(viewKey, write);\n }\n const pending = Array.from(missing);\n\n for (let index = 0; index < pending.length; index += 50) {\n const requested = new Map(pending.slice(index, index + 50));\n\n const rawRows = yield* query(\n sql<Record<string, unknown>>`\n SELECT namespace, operation_id, source_id, format_version, command_json, result_json\n FROM effect_agent_memory_receipts_v1\n WHERE ${sql.or(\n Array.from(\n requested.values(),\n (write) =>\n sql`(namespace = ${write.key.namespace.address} AND operation_id = ${write.operationId})`,\n ),\n )}\n `,\n operation,\n );\n\n const rows = yield* decodeRows(MemoryReceiptRow, rawRows, operation);\n\n for (const row of rows) {\n const viewKey = JSON.stringify([\"receipt\", row.namespace, row.operation_id]);\n\n if (!requested.has(viewKey) || found.has(viewKey))\n return yield* storageError(operation, \"corrupt\");\n if (row.format_version !== STORAGE_VERSION)\n return yield* storageError(operation, \"incompatible\");\n\n const command = yield* decodeVersionedJson(\n StoredMemoryCommand,\n row.command_json,\n `${operation} command`,\n );\n\n const result = yield* decodeVersionedJson(\n StoredMemoryResult,\n row.result_json,\n `${operation} result`,\n );\n\n if (\n row.namespace !== command.value.key.namespace.address ||\n row.operation_id !== command.value.operationId ||\n row.source_id !== command.value.key.id ||\n result.value.key.namespace.address !== command.value.key.namespace.address ||\n result.value.key.id !== command.value.key.id\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n yield* validateDocument(result.value, command.value.key, operation);\n yield* validateReceiptResult(command.value, result.value, operation);\n found.set(viewKey, { commandJson: row.command_json, result: result.value });\n }\n\n for (const viewKey of requested.keys()) {\n const value = found.get(viewKey) ?? null;\n\n found.set(viewKey, value);\n views?.set(viewKey, { _tag: \"Receipt\", value });\n }\n }\n\n return found;\n });\n\n const changeMany = Effect.fnUntraced(function* (writes: ReadonlyArray<MemoryWrite>) {\n const operation = \"change memory document\";\n const decodedWrites = yield* decodeInput(SqlMemoryWriteBatch, writes, operation);\n\n if (decodedWrites.length === 0) return [];\n\n const commands = yield* Effect.forEach(decodedWrites, (write) =>\n encodeJson(\n StoredMemoryCommand,\n StoredMemoryCommand.make({ version: STORAGE_VERSION, value: write }),\n \"encode memory command\",\n ).pipe(Effect.map((commandJson) => ({ write, commandJson }))),\n );\n\n yield* failpoint.hit(\"memory:change:before\");\n\n // The adapter must serialize before reading receipts and state. Node uses BEGIN\n // IMMEDIATE; Durable Objects use the driver's storage-backed transaction and permit.\n const transactionResult = yield* transaction(\n Effect.gen(function* () {\n const retainedReceipts = yield* readReceipts(decodedWrites, operation);\n\n const retainedDocuments = yield* readDocuments(\n decodedWrites\n .filter((write) => retainedReceipts.get(receiptViewKey(write)) === null)\n .map((write) => write.key),\n operation,\n );\n\n const documents = new Map<\n string,\n {\n readonly document: MemoryDocument;\n readonly bytes: number;\n readonly documentJson: string;\n }\n >();\n\n const receipts = new Map<\n string,\n {\n readonly write: MemoryWrite;\n readonly commandJson: string;\n readonly resultJson: string;\n readonly result: MemoryDocument;\n }\n >();\n\n const results: Array<MemoryDocument> = [];\n let projectedUsage: typeof UsageRow.Type | undefined;\n\n for (const { write, commandJson } of commands) {\n const receiptKey = receiptViewKey(write);\n const receipt = receipts.get(receiptKey) ?? retainedReceipts.get(receiptKey) ?? null;\n\n if (receipt !== null) {\n if (receipt.commandJson !== commandJson) {\n return yield* MemoryOperationConflict.make({\n key: write.key,\n operationId: write.operationId,\n });\n }\n results.push(receipt.result);\n continue;\n }\n\n const documentKey = documentViewKey(write.key);\n\n const currentRow =\n documents.get(documentKey) ?? retainedDocuments.get(documentKey) ?? null;\n\n const current = currentRow?.document ?? null;\n const modifiedAt = yield* Clock.currentTimeMillis;\n const next = yield* applyMemoryWrite(current, write, modifiedAt);\n\n const resultJson = yield* encodeJson(\n StoredMemoryResult,\n StoredMemoryResult.make({ version: STORAGE_VERSION, value: next }),\n \"encode memory result\",\n );\n\n const documentJson = resultJson;\n\n yield* validateEncodedChange({ commandJson, documentJson, resultJson }, operation);\n\n const bytes = utf8ByteLength;\n const identityBytes = bytes(next.key.namespace.address) + bytes(next.key.id);\n const resultBytes = bytes(resultJson);\n const documentBytes = identityBytes + resultBytes + 128;\n\n const receiptBytes =\n identityBytes + bytes(write.operationId) + bytes(commandJson) + resultBytes + 128;\n\n if (Math.max(documentBytes, receiptBytes) > limits.maxRowBytes) {\n return yield* storageError(\"memory row byte limit\", \"invalid-input\");\n }\n\n const cachedUsage = views?.get(\"usage\");\n\n const used =\n projectedUsage ?? (cachedUsage?._tag === \"Usage\" ? cachedUsage.value : yield* usage);\n\n if (used.bytes < (currentRow?.bytes ?? 0) || (current !== null && used.documents === 0)) {\n return yield* storageError(\"read memory usage\", \"corrupt\");\n }\n\n const maxReceipts =\n limits.maxReceipts -\n (write._tag === \"Put\" ? (limits.reservedWithdrawalReceipts ?? 0) : 0);\n\n const maxStorageBytes =\n limits.maxStorageBytes -\n (write._tag === \"Put\" ? (limits.reservedWithdrawalBytes ?? 0) : 0);\n\n // Check every staged transition, including intermediate document sizes and\n // receipts. A later shrinking command cannot evade the earlier write's limits.\n if (\n used.documents > limits.maxDocuments - (current === null ? 1 : 0) ||\n used.receipts >= maxReceipts ||\n used.bytes - (currentRow?.bytes ?? 0) > maxStorageBytes - documentBytes - receiptBytes\n ) {\n return yield* storageError(\"memory storage limit\", \"invalid-input\");\n }\n\n projectedUsage = {\n documents: used.documents + (current === null ? 1 : 0),\n receipts: used.receipts + 1,\n bytes: used.bytes - (currentRow?.bytes ?? 0) + documentBytes + receiptBytes,\n };\n documents.set(documentKey, { document: next, bytes: documentBytes, documentJson });\n receipts.set(receiptKey, { write, commandJson, resultJson, result: next });\n results.push(next);\n }\n\n if (projectedUsage === undefined) return { documents: results, changed: false };\n\n // Both persisted rows have six bound columns: sixteen rows stay below the DO\n // driver's 100-parameter limit. The surrounding transaction owns all revision\n // checks, and only the final row for each key needs physical writeback.\n const documentRows = Array.from(documents.values(), ({ document, documentJson }) => ({\n namespace: document.key.namespace.address,\n source_id: document.key.id,\n format_version: STORAGE_VERSION,\n generation: document.generation,\n revision: document.source.revision,\n document_json: documentJson,\n }));\n\n for (let index = 0; index < documentRows.length; index += 16) {\n const chunk = documentRows.slice(index, index + 16);\n\n const changedRows = yield* sql<Record<string, unknown>>`\n INSERT INTO effect_agent_memory_documents_v1 ${sql.insert(chunk)}\n ON CONFLICT (namespace, source_id) DO UPDATE SET\n format_version = excluded.format_version,\n generation = excluded.generation,\n revision = excluded.revision,\n document_json = excluded.document_json\n RETURNING 1 AS changed\n `;\n\n const changed = yield* decodeRows(MemoryChangeCountRow, changedRows, operation);\n\n if (changed.length !== chunk.length || changed.some((row) => row.changed !== 1)) {\n return yield* storageError(operation, \"corrupt\");\n }\n }\n yield* failpoint.hit(\"memory:change:after-state\");\n\n const receiptRows = Array.from(receipts.values(), ({ write, commandJson, resultJson }) => ({\n namespace: write.key.namespace.address,\n operation_id: write.operationId,\n source_id: write.key.id,\n format_version: STORAGE_VERSION,\n command_json: commandJson,\n result_json: resultJson,\n }));\n\n for (let index = 0; index < receiptRows.length; index += 16) {\n yield* sql`\n INSERT INTO effect_agent_memory_receipts_v1 ${sql.insert(receiptRows.slice(index, index + 16))}\n `;\n }\n yield* failpoint.hit(\"memory:change:after-receipt\");\n\n for (const [key, { document, bytes }] of documents)\n views?.set(key, { _tag: \"Document\", value: { document, bytes } });\n for (const [key, { commandJson, result }] of receipts)\n views?.set(key, { _tag: \"Receipt\", value: { commandJson, result } });\n views?.set(\"usage\", { _tag: \"Usage\", value: projectedUsage });\n\n return { documents: results, changed: true };\n }),\n ).pipe(Effect.catchTag(\"SqlError\", () => Effect.fail(storageError(operation))));\n\n if (transactionResult.changed) yield* failpoint.hit(\"memory:change:after\");\n\n return transactionResult.documents;\n });\n\n const change = Effect.fnUntraced(function* (write: MemoryWrite) {\n return (yield* changeMany([write]))[0];\n });\n\n const batchWriter = SqlMemoryBatchWriter.of({\n changeMany: Effect.fnUntraced(function* <Namespace extends MemoryNamespace>(\n writes: ReadonlyArray<MemoryWrite<Namespace>>,\n ) {\n const documents = yield* changeMany(writes);\n\n return yield* Effect.forEach(documents, (document, index) =>\n MemoryDocument.restore(writes[index].key.namespace, document),\n );\n }),\n });\n\n return Context.make(MemoryReader, MemoryReader.fromAdapter({ get })).pipe(\n Context.add(MemoryWriter, MemoryWriter.fromAdapter({ change })),\n Context.add(SqlMemoryBatchWriter, batchWriter),\n );\n});\n\n/** SQLite memory ports with the mutation failpoint kept injectable for recovery tests. */\nexport const memoryStoreLayerWithFailpoints: Layer.Layer<\n MemoryReader | MemoryWriter | SqlMemoryBatchWriter,\n SqliteMemoryInitializationError,\n SqlClientService.SqlClient | MemoryMutationFailpoint\n> = Layer.effectContext(makeMemoryServices());\n\n/** SQLite memory reader, single writer and batch writer with the production no-op failpoint. */\nexport const memoryStoreLayer: Layer.Layer<\n MemoryReader | MemoryWriter | SqlMemoryBatchWriter,\n SqliteMemoryInitializationError,\n SqlClientService.SqlClient\n> = memoryStoreLayerWithFailpoints.pipe(Layer.provide(MemoryMutationFailpoint.layer));\n\n/** Reads an existing memory schema without writes, transactions, or mutation failpoints. */\nexport const memoryReaderLayer: Layer.Layer<\n MemoryReader,\n MemoryStorageError,\n SqlClientService.SqlClient\n> = Layer.effect(\n MemoryReader,\n Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"open memory reader\";\n\n const tables = yield* query(\n sql<Record<string, unknown>>`\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name IN (\n 'effect_agent_memory_metadata', ${DOCUMENT_TABLE}, ${RECEIPT_TABLE}\n )\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));\n\n if (tables.length !== 3) {\n return yield* storageError(operation, tables.length === 0 ? \"unavailable\" : \"incompatible\");\n }\n\n const metadata = yield* query(\n sql<Record<string, unknown>>`\n SELECT version FROM effect_agent_memory_metadata WHERE component = ${METADATA_COMPONENT}\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));\n\n if (metadata.length !== 1 || metadata[0].version !== STORAGE_VERSION) {\n return yield* storageError(operation, \"incompatible\");\n }\n yield* query(\n sql`\n SELECT namespace, source_id, format_version, generation, revision, document_json\n FROM effect_agent_memory_documents_v1 LIMIT 0\n `,\n operation,\n );\n const { get } = yield* makeMemoryReader();\n\n return MemoryReader.fromAdapter({ get });\n }),\n);\n"],"mappings":";;;;;;AAoBA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,cAAc;AAEpB,MAAM,aAAa,OAAO,OAAO,MAAM,OAAO,YAAY,QAA0B,CAAC;AAErF,MAAM,sBAAsB,OAAO,OAAO;CACxC,aAAa;CACb,cAAc;CACd,YAAY;AACd,CAAC;AAED,MAAM,8BACJ,OAAO,cAAc,OAAO,UAAU,YAAY,KAAK,QAAQ,EAAE,CAAC,OAAO,OAAO,CAAC;AAEnF,IAAI;AAEJ,MAAM,6BAA6B,OAAO,cAAc,YAAY,KAAK,QAAQ,EAAE,CAAC,OAAO,MAAM;AACjG,IAAI;;AAGJ,MAAa,sBAAsB,OAAO,MAAM,YAAY,IAAI,CAAC,CAAC,MAAM,OAAO,YAAY,GAA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
+
{"version":3,"file":"SqlMemoryStore.mjs","names":[],"sources":["../../src/durable/SqlMemoryStore.ts"],"sourcesContent":["import { Clock, Context, Effect, Layer, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/sql/SqlClient\";\nimport type { SqlError } from \"effect/sql/SqlError\";\n\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { type Any as MemoryNamespace, MemoryNamespaceAddress } from \"../core/MemoryNamespace.ts\";\nimport {\n applyMemoryWrite,\n MemoryDocument,\n MemoryKey,\n MemoryMutationFailpoint,\n type MemoryMutationFailure,\n MemoryOperationConflict,\n MemoryReader,\n MemoryStorageError,\n MemoryWrite,\n type MemoryWriteError,\n MemoryWriter,\n} from \"../core/MemoryStore.ts\";\nimport { SqlStorageOwner } from \"./SqlStorageOwner.ts\";\n\nexport { SqlStorageOwner } from \"./SqlStorageOwner.ts\";\n\nconst STORAGE_VERSION = 2 as const;\nconst METADATA_COMPONENT = \"memory\";\nconst DOCUMENT_TABLE = \"effect_agent_memory_documents_v1\";\nconst RECEIPT_TABLE = \"effect_agent_memory_receipts_v1\";\nconst USAGE_COMPONENT = \"memory-usage\";\nconst USAGE_TABLE = \"effect_agent_memory_usage_v1\";\nconst MAX_STORED_JSON_CODE_UNITS = 16 * 1024 * 1024;\nconst StoredJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_JSON_CODE_UNITS));\n\nconst EncodedMemoryChange = Schema.Struct({\n commandJson: StoredJson,\n documentJson: StoredJson,\n resultJson: StoredJson,\n});\n\nconst makeEquivalentContent = () =>\n Schema.toEquivalence(Schema.toEncoded(MemoryWrite.Wire.members[0].fields.content));\n\nlet equivalentContent: ReturnType<typeof makeEquivalentContent> | undefined;\n\nconst makeEquivalentScopes = () => Schema.toEquivalence(MemoryWrite.Wire.members[0].fields.scopes);\nlet equivalentScopes: ReturnType<typeof makeEquivalentScopes> | undefined;\n\n/** Ordered commands committed atomically by the SQL memory adapter. */\nexport const SqlMemoryWriteBatch = Schema.Array(MemoryWrite.Wire).check(Schema.isMaxLength(128));\n\n/**\n * SQL-only bulk writing. Results preserve input order, including exact operation replays.\n * Commands see earlier staged revisions; any refusal rolls back the entire batch. Storage\n * limits apply to every intermediate transition. Empty batches succeed without mutation.\n * Supplied by the memory store Layers alongside MemoryWriter's single-command API.\n */\nexport class SqlMemoryBatchWriter extends Context.Service<\n SqlMemoryBatchWriter,\n {\n readonly changeMany: <Namespace extends MemoryNamespace>(\n writes: ReadonlyArray<MemoryWrite<Namespace>>,\n ) => Effect.Effect<ReadonlyArray<MemoryDocument<Namespace>>, MemoryWriteError>;\n }\n>()(\"@effect-agent/thread/SqlMemoryBatchWriter\") {}\n\n/**\n * Independent adapter limits. Counts and encoded bytes include durable operation receipts.\n * Bytes count UTF-8 row payloads plus 128 bytes per row, excluding SQLite pages/indexes.\n * Replacements charge their byte delta; receipts and tombstones are never pruned.\n * Optional reserves (default zero) withhold capacity from Put, within the hard totals.\n * They require exclusive upgraded writer ownership: older writers count toward usage\n * but do not honor reserves. Limits are captured when the writer Layer is built.\n */\nexport const SqlMemoryLimits = Context.Reference<{\n readonly maxRowBytes: number;\n readonly maxStorageBytes: number;\n readonly maxDocuments: number;\n readonly maxReceipts: number;\n readonly reservedWithdrawalBytes?: number;\n readonly reservedWithdrawalReceipts?: number;\n}>(\"@effect-agent/thread/SqlMemoryLimits\", {\n defaultValue: () => ({\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n maxStorageBytes: Number.MAX_SAFE_INTEGER,\n maxDocuments: Number.MAX_SAFE_INTEGER,\n maxReceipts: Number.MAX_SAFE_INTEGER,\n }),\n});\n\nconst Limits = Schema.Struct({\n maxRowBytes: Schema.Natural,\n maxStorageBytes: Schema.Natural,\n maxDocuments: Schema.Natural,\n maxReceipts: Schema.Natural,\n reservedWithdrawalBytes: Schema.optional(Schema.Natural),\n reservedWithdrawalReceipts: Schema.optional(Schema.Natural),\n}).check(\n Schema.makeFilter(\n (limits) =>\n (limits.reservedWithdrawalBytes ?? 0) <= limits.maxStorageBytes &&\n (limits.reservedWithdrawalReceipts ?? 0) <= limits.maxReceipts,\n { expected: \"withdrawal reserves within hard storage limits\" },\n ),\n);\n\nconst UsageRow = Schema.Struct({\n documents: Schema.Natural,\n receipts: Schema.Natural,\n bytes: Schema.Natural,\n});\n\ntype DocumentView = { readonly document: MemoryDocument; readonly bytes: number } | null;\ntype ReceiptView = { readonly commandJson: string; readonly result: MemoryDocument } | null;\ntype MemoryView =\n | { readonly _tag: \"Document\"; readonly value: DocumentView }\n | { readonly _tag: \"Receipt\"; readonly value: ReceiptView }\n | { readonly _tag: \"Usage\"; readonly value: typeof UsageRow.Type };\n\n// Demand-loaded views are disposable. The shared owner's gate keeps writes invisible\n// until commit, and its rollback invalidator discards every speculative view together.\nclass MemoryViews {\n private readonly entries = new Map<\n string,\n { readonly view: MemoryView; readonly bytes: number }\n >();\n private bytes = 0;\n\n readonly clear = () => {\n this.entries.clear();\n this.bytes = 0;\n };\n\n get(key: string): MemoryView | undefined {\n const entry = this.entries.get(key);\n\n if (entry === undefined) return undefined;\n this.entries.delete(key);\n this.entries.set(key, entry);\n\n return entry.view;\n }\n\n set(key: string, view: MemoryView): void {\n const previous = this.entries.get(key);\n\n if (previous !== undefined) this.bytes -= previous.bytes;\n this.entries.delete(key);\n const bytes = utf8ByteLength(key) + utf8ByteLength(JSON.stringify(view)) + 128;\n\n if (bytes > 4 * 1024 * 1024) return;\n this.entries.set(key, { view, bytes });\n this.bytes += bytes;\n while (this.entries.size > 128 || this.bytes > 4 * 1024 * 1024) {\n const oldest = this.entries.entries().next().value;\n\n if (oldest === undefined) break;\n this.bytes -= oldest[1].bytes;\n this.entries.delete(oldest[0]);\n }\n }\n}\n\nconst ownedViews = new WeakMap<object, MemoryViews>();\n\nconst memoryViews = Effect.fnUntraced(function* () {\n const owner = yield* SqlStorageOwner;\n\n if (owner === undefined) return undefined;\n const identity = owner.identity ?? owner;\n let views = ownedViews.get(identity);\n\n if (views === undefined) {\n views = new MemoryViews();\n ownedViews.set(identity, views);\n owner.invalidators.add(views.clear);\n }\n\n return views;\n});\n\nconst documentViewKey = (key: MemoryKey) =>\n JSON.stringify([\"document\", key.namespace.address, key.id]);\n\nconst receiptViewKey = (write: MemoryWrite) =>\n JSON.stringify([\"receipt\", write.key.namespace.address, write.operationId]);\n\n// These expressions deliberately match the legacy aggregate's logical byte accounting.\nconst documentBytesSql = (row: string) =>\n `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.document_json AS BLOB)) + 128`;\n\nconst receiptBytesSql = (row: string) =>\n `length(CAST(${row}.namespace AS BLOB)) + length(CAST(${row}.source_id AS BLOB)) + length(CAST(${row}.operation_id AS BLOB)) + length(CAST(${row}.command_json AS BLOB)) + length(CAST(${row}.result_json AS BLOB)) + 128`;\n\n// Triggers keep already-open version-2 writers accounted for. Their admission policy\n// is still the old policy; deployment must drain them before relying on reserves.\nconst usageTriggers = [\n { table: DOCUMENT_TABLE, count: \"documents\", bytes: documentBytesSql },\n { table: RECEIPT_TABLE, count: \"receipts\", bytes: receiptBytesSql },\n].flatMap(({ table, count, bytes }) =>\n [\"INSERT\", \"UPDATE\", \"DELETE\"].map((event) => ({\n name: `${table}_usage_${event.toLowerCase()}`,\n sql: `CREATE TRIGGER ${table}_usage_${event.toLowerCase()} AFTER ${event} ON ${table}\n BEGIN\n UPDATE ${USAGE_TABLE} SET\n ${count} = ${count} + ${event === \"INSERT\" ? 1 : event === \"DELETE\" ? -1 : 0},\n bytes = bytes + (${event === \"DELETE\" ? \"0\" : bytes(\"NEW\")}) - (${event === \"INSERT\" ? \"0\" : bytes(\"OLD\")})\n WHERE singleton = 1;\n SELECT CASE WHEN changes() <> 1 THEN RAISE(ABORT, 'missing memory usage') END;\n END`,\n })),\n);\n\nclass MemoryMetadataRow extends Schema.Class<MemoryMetadataRow>(\n \"@effect-agent/storage-sqlite/MemoryMetadataRow\",\n)({\n version: Schema.Int,\n}) {}\n\nclass MemoryTableRow extends Schema.Class<MemoryTableRow>(\n \"@effect-agent/storage-sqlite/MemoryTableRow\",\n)({\n name: Schema.NonEmptyString,\n}) {}\n\nclass MemoryDocumentRow extends Schema.Class<MemoryDocumentRow>(\n \"@effect-agent/storage-sqlite/MemoryDocumentRow\",\n)({\n namespace: MemoryNamespaceAddress,\n source_id: MemoryKey.Wire.fields.id,\n format_version: Schema.Int,\n generation: Schema.Int,\n revision: Schema.NonEmptyString,\n document_json: StoredJson,\n stored_bytes: Schema.Natural,\n}) {}\n\nclass MemoryReceiptRow extends Schema.Class<MemoryReceiptRow>(\n \"@effect-agent/storage-sqlite/MemoryReceiptRow\",\n)({\n namespace: MemoryNamespaceAddress,\n operation_id: MemoryWrite.Wire.members[0].fields.operationId,\n source_id: MemoryKey.Wire.fields.id,\n format_version: Schema.Int,\n command_json: StoredJson,\n result_json: StoredJson,\n}) {}\n\nclass MemoryChangeCountRow extends Schema.Class<MemoryChangeCountRow>(\n \"@effect-agent/storage-sqlite/MemoryChangeCountRow\",\n)({\n changed: Schema.Int,\n}) {}\n\nclass StoredMemoryCommand extends Schema.Class<StoredMemoryCommand>(\n \"@effect-agent/storage-sqlite/StoredMemoryCommand\",\n)({\n version: Schema.Literal(STORAGE_VERSION),\n value: MemoryWrite.Wire,\n}) {}\n\nclass StoredMemoryResult extends Schema.Class<StoredMemoryResult>(\n \"@effect-agent/storage-sqlite/StoredMemoryResult\",\n)({\n version: Schema.Literal(STORAGE_VERSION),\n value: MemoryDocument.Wire,\n}) {}\n\nconst StoredVersionHeader = Schema.Struct({ version: Schema.Int });\n\nexport type SqliteMemoryInitializationError = MemoryStorageError | MemoryMutationFailure;\n\nconst storageError = (\n operation: string,\n reason: MemoryStorageError[\"reason\"] = \"unavailable\",\n): MemoryStorageError => MemoryStorageError.make({ operation, reason });\n\nconst query = <A extends object>(\n effect: Effect.Effect<ReadonlyArray<A>, SqlError>,\n operation: string,\n) => effect.pipe(Effect.mapError(() => storageError(operation)));\n\nconst decodeRows = <A, I>(\n schema: Schema.Codec<A, I, never>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.Effect<ReadonlyArray<A>, MemoryStorageError> =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst decodeInput = <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, MemoryStorageError> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => storageError(operation, \"invalid-input\")),\n );\n\nconst encodeJson = <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: A,\n operation: string,\n): Effect.Effect<string, MemoryStorageError> =>\n Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst validateEncodedChange = Effect.fnUntraced(function* (\n encoded: typeof EncodedMemoryChange.Type,\n operation: string,\n): Effect.fn.Return<void, MemoryStorageError> {\n yield* Schema.decodeEffect(EncodedMemoryChange)(encoded).pipe(\n Effect.mapError(() => storageError(operation, \"invalid-input\")),\n );\n});\n\nconst decodeVersionedJson = Effect.fnUntraced(function* <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: string,\n operation: string,\n): Effect.fn.Return<A, MemoryStorageError> {\n const header = yield* Schema.decodeEffect(Schema.fromJsonString(StoredVersionHeader))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\n if (header.version !== STORAGE_VERSION) {\n return yield* storageError(operation, \"incompatible\");\n }\n\n const decoded = yield* Schema.decodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\n const canonical = yield* encodeJson(schema, decoded, operation);\n\n if (canonical !== value) return yield* storageError(operation, \"corrupt\");\n\n return decoded;\n});\n\nconst validateDocument = Effect.fnUntraced(function* (\n document: MemoryDocument,\n key: MemoryKey,\n operation: string,\n): Effect.fn.Return<MemoryDocument, MemoryStorageError> {\n if (\n document.key.namespace.address !== key.namespace.address ||\n document.key.id !== key.id ||\n document.source.id !== key.id ||\n document.source.revision !== String(document.generation) ||\n (document.generation === 1) !== (document.predecessor === null) ||\n (document.predecessor !== null &&\n (document.predecessor.id !== key.id ||\n document.predecessor.revision !== String(document.generation - 1)))\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n\n return document;\n});\n\nconst validateReceiptResult = Effect.fnUntraced(function* (\n command: MemoryWrite,\n result: MemoryDocument,\n operation: string,\n): Effect.fn.Return<void, MemoryStorageError> {\n if ((result.predecessor?.revision ?? null) !== command.expectedRevision) {\n return yield* storageError(operation, \"corrupt\");\n }\n if (command._tag === \"Put\") {\n if (result._tag !== \"ActiveMemoryDocument\" || result.source.locator !== command.locator) {\n return yield* storageError(operation, \"corrupt\");\n }\n if (\n !(equivalentContent ??= makeEquivalentContent())(command.content, result.content) ||\n !(equivalentScopes ??= makeEquivalentScopes())(command.scopes, result.scopes)\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n\n return;\n }\n if (\n result._tag !== \"WithdrawnMemoryDocument\" ||\n result.reason !== command.reason ||\n result.predecessor === null ||\n result.source.locator !== result.predecessor.locator\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n});\n\nconst readUsage = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const views = yield* memoryViews();\n const operation = \"read memory usage\";\n\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT documents, receipts, bytes FROM effect_agent_memory_usage_v1 WHERE singleton = 1\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(UsageRow, rows, operation)));\n\n if (rows.length !== 1) return yield* storageError(operation, \"corrupt\");\n\n views?.set(\"usage\", { _tag: \"Usage\", value: rows[0] });\n\n return rows[0];\n});\n\n// Called inside schema initialization's transaction. The separate marker distinguishes\n// a legacy store from damaged established accounting; reopening never rebuilds counters.\nconst initializeMemoryUsage = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const failpoint = yield* MemoryMutationFailpoint;\n const operation = \"initialize memory usage\";\n\n const metadata = yield* sql<Record<string, unknown>>`\n SELECT version FROM effect_agent_memory_metadata WHERE component = ${USAGE_COMPONENT}\n `.pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));\n\n const objects = yield* sql<Record<string, unknown>>`\n SELECT name FROM sqlite_master\n WHERE name = ${USAGE_TABLE} OR name IN ${sql.in(usageTriggers.map((trigger) => trigger.name))}\n `.pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));\n\n if (metadata.length === 0) {\n if (objects.length !== 0) return yield* storageError(operation, \"corrupt\");\n yield* failpoint.hit(\"memory:initialize:before-accounting\");\n yield* sql`\n CREATE TABLE effect_agent_memory_usage_v1 (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n documents INTEGER NOT NULL CHECK (typeof(documents) = 'integer' AND documents BETWEEN 0 AND 9007199254740991),\n receipts INTEGER NOT NULL CHECK (typeof(receipts) = 'integer' AND receipts BETWEEN 0 AND 9007199254740991),\n bytes INTEGER NOT NULL CHECK (typeof(bytes) = 'integer' AND bytes BETWEEN 0 AND 9007199254740991)\n )\n `;\n yield* sql`\n INSERT INTO effect_agent_memory_usage_v1 (singleton, documents, receipts, bytes)\n SELECT 1,\n (SELECT COUNT(*) FROM effect_agent_memory_documents_v1),\n (SELECT COUNT(*) FROM effect_agent_memory_receipts_v1),\n COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(document_json AS BLOB)) + 128) FROM effect_agent_memory_documents_v1), 0) +\n COALESCE((SELECT SUM(length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(operation_id AS BLOB)) + length(CAST(command_json AS BLOB)) +\n length(CAST(result_json AS BLOB)) + 128) FROM effect_agent_memory_receipts_v1), 0)\n `;\n for (const trigger of usageTriggers) yield* sql.unsafe(trigger.sql);\n yield* sql`\n INSERT INTO effect_agent_memory_metadata (component, version) VALUES (${USAGE_COMPONENT}, 1)\n `;\n yield* failpoint.hit(\"memory:initialize:after-accounting\");\n } else {\n if (metadata.length !== 1 || metadata[0].version !== 1) {\n return yield* storageError(operation, \"incompatible\");\n }\n if (objects.length !== usageTriggers.length + 1) {\n return yield* storageError(operation, \"corrupt\");\n }\n }\n yield* readUsage();\n});\n\nconst initializeMemorySchema = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const transaction = owner === undefined ? sql.withTransaction : owner.transaction;\n const failpoint = yield* MemoryMutationFailpoint;\n\n yield* failpoint.hit(\"memory:initialize:before\");\n yield* transaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE IF NOT EXISTS effect_agent_memory_metadata (\n component TEXT PRIMARY KEY NOT NULL,\n version INTEGER NOT NULL\n )\n `;\n\n const metadataRows = yield* sql<Record<string, unknown>>`\n SELECT version\n FROM effect_agent_memory_metadata\n WHERE component = ${METADATA_COMPONENT}\n `;\n\n const metadata = yield* decodeRows(\n MemoryMetadataRow,\n metadataRows,\n \"decode memory schema version\",\n );\n\n if (metadata.length > 1)\n return yield* storageError(\"decode memory schema version\", \"corrupt\");\n const currentVersion = metadata[0]?.version;\n\n if (currentVersion !== undefined && currentVersion !== STORAGE_VERSION) {\n return yield* storageError(\"initialize memory schema\", \"incompatible\");\n }\n if (currentVersion === undefined) {\n const tableRows = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table' AND name IN (${DOCUMENT_TABLE}, ${RECEIPT_TABLE})\n `;\n\n const existingTables = yield* decodeRows(\n MemoryTableRow,\n tableRows,\n \"inspect memory schema\",\n );\n\n if (existingTables.length > 0) {\n return yield* storageError(\"initialize memory schema\", \"incompatible\");\n }\n yield* sql`\n CREATE TABLE effect_agent_memory_documents_v1 (\n namespace TEXT NOT NULL,\n source_id TEXT NOT NULL,\n format_version INTEGER NOT NULL,\n generation INTEGER NOT NULL,\n revision TEXT NOT NULL,\n document_json TEXT NOT NULL,\n PRIMARY KEY (namespace, source_id)\n )\n `;\n yield* sql`\n CREATE TABLE effect_agent_memory_receipts_v1 (\n namespace TEXT NOT NULL,\n operation_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n format_version INTEGER NOT NULL,\n command_json TEXT NOT NULL,\n result_json TEXT NOT NULL,\n PRIMARY KEY (namespace, operation_id)\n )\n `;\n yield* sql`\n INSERT INTO effect_agent_memory_metadata (component, version)\n VALUES (${METADATA_COMPONENT}, ${STORAGE_VERSION})\n `;\n }\n yield* sql`\n SELECT namespace, source_id, format_version, generation, revision, document_json\n FROM effect_agent_memory_documents_v1\n LIMIT 0\n `;\n yield* sql`\n SELECT namespace, operation_id, source_id, format_version, command_json, result_json\n FROM effect_agent_memory_receipts_v1\n LIMIT 0\n `;\n yield* initializeMemoryUsage();\n }),\n ).pipe(Effect.catchTag(\"SqlError\", () => Effect.fail(storageError(\"initialize memory schema\"))));\n yield* failpoint.hit(\"memory:initialize:after\");\n});\n\nconst makeMemoryReader = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const views = yield* memoryViews();\n\n const readDocuments = Effect.fnUntraced(\n function* (\n keys: ReadonlyArray<MemoryKey>,\n operation: string,\n ): Effect.fn.Return<ReadonlyMap<string, DocumentView>, MemoryStorageError> {\n const found = new Map<string, DocumentView>();\n const missing = new Map<string, MemoryKey>();\n\n for (const key of keys) {\n const viewKey = documentViewKey(key);\n const cached = views?.get(viewKey);\n\n if (cached?._tag === \"Document\") found.set(viewKey, cached.value);\n else missing.set(viewKey, key);\n }\n const pending = Array.from(missing);\n\n // Each exact composite key uses two bindings. No history or unrelated rows are loaded.\n for (let index = 0; index < pending.length; index += 50) {\n const requested = new Map(pending.slice(index, index + 50));\n\n const rawRows = yield* query(\n sql<Record<string, unknown>>`\n SELECT namespace, source_id, format_version, generation, revision, document_json,\n length(CAST(namespace AS BLOB)) + length(CAST(source_id AS BLOB)) +\n length(CAST(document_json AS BLOB)) + 128 AS stored_bytes\n FROM effect_agent_memory_documents_v1\n WHERE ${sql.or(\n Array.from(\n requested.values(),\n (key) => sql`(namespace = ${key.namespace.address} AND source_id = ${key.id})`,\n ),\n )}\n `,\n operation,\n );\n\n const rows = yield* decodeRows(MemoryDocumentRow, rawRows, operation);\n\n for (const row of rows) {\n const viewKey = JSON.stringify([\"document\", row.namespace, row.source_id]);\n const key = requested.get(viewKey);\n\n if (key === undefined || found.has(viewKey))\n return yield* storageError(operation, \"corrupt\");\n if (row.format_version !== STORAGE_VERSION)\n return yield* storageError(operation, \"incompatible\");\n\n const stored = yield* decodeVersionedJson(\n StoredMemoryResult,\n row.document_json,\n operation,\n );\n\n const document = stored.value;\n\n yield* validateDocument(document, key, operation);\n if (row.generation !== document.generation || row.revision !== document.source.revision)\n return yield* storageError(operation, \"corrupt\");\n found.set(viewKey, { document, bytes: row.stored_bytes });\n }\n\n for (const viewKey of requested.keys()) {\n const value = found.get(viewKey) ?? null;\n\n found.set(viewKey, value);\n views?.set(viewKey, { _tag: \"Document\", value });\n }\n }\n\n return found;\n },\n (effect) => (owner === undefined ? effect : owner.read(effect)),\n );\n\n const get = Effect.fnUntraced(function* (key: MemoryKey) {\n const decodedKey = yield* decodeInput(MemoryKey.Wire, key, \"get memory document\");\n\n const documents = yield* readDocuments([decodedKey], \"get memory document\");\n\n return documents.get(documentViewKey(decodedKey))?.document ?? null;\n });\n\n return { get, readDocuments };\n});\n\nconst makeMemoryServices = Effect.fnUntraced(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const owner = yield* SqlStorageOwner;\n const views = yield* memoryViews();\n\n const usage = readUsage().pipe(\n Effect.provideService(SqlClientService.SqlClient, sql),\n Effect.provideService(SqlStorageOwner, owner),\n );\n\n const transaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n owner === undefined\n ? sql.withTransaction(effect)\n : owner.transaction(effect).pipe(Effect.provideService(SqlClientService.SqlClient, sql));\n\n const failpoint = yield* MemoryMutationFailpoint;\n const limits = yield* decodeInput(Limits, yield* SqlMemoryLimits, \"memory storage limits\");\n\n yield* initializeMemorySchema();\n const { get, readDocuments } = yield* makeMemoryReader();\n\n const readReceipts = Effect.fnUntraced(function* (\n writes: ReadonlyArray<MemoryWrite>,\n operation: string,\n ): Effect.fn.Return<ReadonlyMap<string, ReceiptView>, MemoryStorageError> {\n const found = new Map<string, ReceiptView>();\n const missing = new Map<string, MemoryWrite>();\n\n for (const write of writes) {\n const viewKey = receiptViewKey(write);\n const cached = views?.get(viewKey);\n\n if (cached?._tag === \"Receipt\") found.set(viewKey, cached.value);\n else missing.set(viewKey, write);\n }\n const pending = Array.from(missing);\n\n for (let index = 0; index < pending.length; index += 50) {\n const requested = new Map(pending.slice(index, index + 50));\n\n const rawRows = yield* query(\n sql<Record<string, unknown>>`\n SELECT namespace, operation_id, source_id, format_version, command_json, result_json\n FROM effect_agent_memory_receipts_v1\n WHERE ${sql.or(\n Array.from(\n requested.values(),\n (write) =>\n sql`(namespace = ${write.key.namespace.address} AND operation_id = ${write.operationId})`,\n ),\n )}\n `,\n operation,\n );\n\n const rows = yield* decodeRows(MemoryReceiptRow, rawRows, operation);\n\n for (const row of rows) {\n const viewKey = JSON.stringify([\"receipt\", row.namespace, row.operation_id]);\n\n if (!requested.has(viewKey) || found.has(viewKey))\n return yield* storageError(operation, \"corrupt\");\n if (row.format_version !== STORAGE_VERSION)\n return yield* storageError(operation, \"incompatible\");\n\n const command = yield* decodeVersionedJson(\n StoredMemoryCommand,\n row.command_json,\n `${operation} command`,\n );\n\n const result = yield* decodeVersionedJson(\n StoredMemoryResult,\n row.result_json,\n `${operation} result`,\n );\n\n if (\n row.namespace !== command.value.key.namespace.address ||\n row.operation_id !== command.value.operationId ||\n row.source_id !== command.value.key.id ||\n result.value.key.namespace.address !== command.value.key.namespace.address ||\n result.value.key.id !== command.value.key.id\n ) {\n return yield* storageError(operation, \"corrupt\");\n }\n yield* validateDocument(result.value, command.value.key, operation);\n yield* validateReceiptResult(command.value, result.value, operation);\n found.set(viewKey, { commandJson: row.command_json, result: result.value });\n }\n\n for (const viewKey of requested.keys()) {\n const value = found.get(viewKey) ?? null;\n\n found.set(viewKey, value);\n views?.set(viewKey, { _tag: \"Receipt\", value });\n }\n }\n\n return found;\n });\n\n const changeMany = Effect.fnUntraced(function* (writes: ReadonlyArray<MemoryWrite>) {\n const operation = \"change memory document\";\n const decodedWrites = yield* decodeInput(SqlMemoryWriteBatch, writes, operation);\n\n if (decodedWrites.length === 0) return [];\n\n const commands = yield* Effect.forEach(decodedWrites, (write) =>\n encodeJson(\n StoredMemoryCommand,\n StoredMemoryCommand.make({ version: STORAGE_VERSION, value: write }),\n \"encode memory command\",\n ).pipe(Effect.map((commandJson) => ({ write, commandJson }))),\n );\n\n yield* failpoint.hit(\"memory:change:before\");\n\n // The adapter must serialize before reading receipts and state. Node uses BEGIN\n // IMMEDIATE; Durable Objects use the driver's storage-backed transaction and permit.\n const transactionResult = yield* transaction(\n Effect.gen(function* () {\n const retainedReceipts = yield* readReceipts(decodedWrites, operation);\n\n const retainedDocuments = yield* readDocuments(\n decodedWrites\n .filter((write) => retainedReceipts.get(receiptViewKey(write)) === null)\n .map((write) => write.key),\n operation,\n );\n\n const documents = new Map<\n string,\n {\n readonly document: MemoryDocument;\n readonly bytes: number;\n readonly documentJson: string;\n }\n >();\n\n const receipts = new Map<\n string,\n {\n readonly write: MemoryWrite;\n readonly commandJson: string;\n readonly resultJson: string;\n readonly result: MemoryDocument;\n }\n >();\n\n const results: Array<MemoryDocument> = [];\n let projectedUsage: typeof UsageRow.Type | undefined;\n\n for (const { write, commandJson } of commands) {\n const receiptKey = receiptViewKey(write);\n const receipt = receipts.get(receiptKey) ?? retainedReceipts.get(receiptKey) ?? null;\n\n if (receipt !== null) {\n if (receipt.commandJson !== commandJson) {\n return yield* MemoryOperationConflict.make({\n key: write.key,\n operationId: write.operationId,\n });\n }\n results.push(receipt.result);\n continue;\n }\n\n const documentKey = documentViewKey(write.key);\n\n const currentRow =\n documents.get(documentKey) ?? retainedDocuments.get(documentKey) ?? null;\n\n const current = currentRow?.document ?? null;\n const modifiedAt = yield* Clock.currentTimeMillis;\n const next = yield* applyMemoryWrite(current, write, modifiedAt);\n\n const resultJson = yield* encodeJson(\n StoredMemoryResult,\n StoredMemoryResult.make({ version: STORAGE_VERSION, value: next }),\n \"encode memory result\",\n );\n\n const documentJson = resultJson;\n\n yield* validateEncodedChange({ commandJson, documentJson, resultJson }, operation);\n\n const bytes = utf8ByteLength;\n const identityBytes = bytes(next.key.namespace.address) + bytes(next.key.id);\n const resultBytes = bytes(resultJson);\n const documentBytes = identityBytes + resultBytes + 128;\n\n const receiptBytes =\n identityBytes + bytes(write.operationId) + bytes(commandJson) + resultBytes + 128;\n\n if (Math.max(documentBytes, receiptBytes) > limits.maxRowBytes) {\n return yield* storageError(\"memory row byte limit\", \"invalid-input\");\n }\n\n const cachedUsage = views?.get(\"usage\");\n\n const used =\n projectedUsage ?? (cachedUsage?._tag === \"Usage\" ? cachedUsage.value : yield* usage);\n\n if (used.bytes < (currentRow?.bytes ?? 0) || (current !== null && used.documents === 0)) {\n return yield* storageError(\"read memory usage\", \"corrupt\");\n }\n\n const maxReceipts =\n limits.maxReceipts -\n (write._tag === \"Put\" ? (limits.reservedWithdrawalReceipts ?? 0) : 0);\n\n const maxStorageBytes =\n limits.maxStorageBytes -\n (write._tag === \"Put\" ? (limits.reservedWithdrawalBytes ?? 0) : 0);\n\n // Check every staged transition, including intermediate document sizes and\n // receipts. A later shrinking command cannot evade the earlier write's limits.\n if (\n used.documents > limits.maxDocuments - (current === null ? 1 : 0) ||\n used.receipts >= maxReceipts ||\n used.bytes - (currentRow?.bytes ?? 0) > maxStorageBytes - documentBytes - receiptBytes\n ) {\n return yield* storageError(\"memory storage limit\", \"invalid-input\");\n }\n\n projectedUsage = {\n documents: used.documents + (current === null ? 1 : 0),\n receipts: used.receipts + 1,\n bytes: used.bytes - (currentRow?.bytes ?? 0) + documentBytes + receiptBytes,\n };\n documents.set(documentKey, { document: next, bytes: documentBytes, documentJson });\n receipts.set(receiptKey, { write, commandJson, resultJson, result: next });\n results.push(next);\n }\n\n if (projectedUsage === undefined) return { documents: results, changed: false };\n\n // Both persisted rows have six bound columns: sixteen rows stay below the DO\n // driver's 100-parameter limit. The surrounding transaction owns all revision\n // checks, and only the final row for each key needs physical writeback.\n const documentRows = Array.from(documents.values(), ({ document, documentJson }) => ({\n namespace: document.key.namespace.address,\n source_id: document.key.id,\n format_version: STORAGE_VERSION,\n generation: document.generation,\n revision: document.source.revision,\n document_json: documentJson,\n }));\n\n for (let index = 0; index < documentRows.length; index += 16) {\n const chunk = documentRows.slice(index, index + 16);\n\n const changedRows = yield* sql<Record<string, unknown>>`\n INSERT INTO effect_agent_memory_documents_v1 ${sql.insert(chunk)}\n ON CONFLICT (namespace, source_id) DO UPDATE SET\n format_version = excluded.format_version,\n generation = excluded.generation,\n revision = excluded.revision,\n document_json = excluded.document_json\n RETURNING 1 AS changed\n `;\n\n const changed = yield* decodeRows(MemoryChangeCountRow, changedRows, operation);\n\n if (changed.length !== chunk.length || changed.some((row) => row.changed !== 1)) {\n return yield* storageError(operation, \"corrupt\");\n }\n }\n yield* failpoint.hit(\"memory:change:after-state\");\n\n const receiptRows = Array.from(receipts.values(), ({ write, commandJson, resultJson }) => ({\n namespace: write.key.namespace.address,\n operation_id: write.operationId,\n source_id: write.key.id,\n format_version: STORAGE_VERSION,\n command_json: commandJson,\n result_json: resultJson,\n }));\n\n for (let index = 0; index < receiptRows.length; index += 16) {\n yield* sql`\n INSERT INTO effect_agent_memory_receipts_v1 ${sql.insert(receiptRows.slice(index, index + 16))}\n `;\n }\n yield* failpoint.hit(\"memory:change:after-receipt\");\n\n for (const [key, { document, bytes }] of documents)\n views?.set(key, { _tag: \"Document\", value: { document, bytes } });\n for (const [key, { commandJson, result }] of receipts)\n views?.set(key, { _tag: \"Receipt\", value: { commandJson, result } });\n views?.set(\"usage\", { _tag: \"Usage\", value: projectedUsage });\n\n return { documents: results, changed: true };\n }),\n ).pipe(Effect.catchTag(\"SqlError\", () => Effect.fail(storageError(operation))));\n\n if (transactionResult.changed) yield* failpoint.hit(\"memory:change:after\");\n\n return transactionResult.documents;\n });\n\n const change = Effect.fnUntraced(function* (write: MemoryWrite) {\n return (yield* changeMany([write]))[0];\n });\n\n const batchWriter = SqlMemoryBatchWriter.of({\n changeMany: Effect.fnUntraced(function* <Namespace extends MemoryNamespace>(\n writes: ReadonlyArray<MemoryWrite<Namespace>>,\n ) {\n const documents = yield* changeMany(writes);\n\n return yield* Effect.forEach(documents, (document, index) =>\n MemoryDocument.restore(writes[index].key.namespace, document),\n );\n }),\n });\n\n return Context.make(MemoryReader, MemoryReader.fromAdapter({ get })).pipe(\n Context.add(MemoryWriter, MemoryWriter.fromAdapter({ change })),\n Context.add(SqlMemoryBatchWriter, batchWriter),\n );\n});\n\n/** SQLite memory ports with the mutation failpoint kept injectable for recovery tests. */\nexport const memoryStoreLayerWithFailpoints: Layer.Layer<\n MemoryReader | MemoryWriter | SqlMemoryBatchWriter,\n SqliteMemoryInitializationError,\n SqlClientService.SqlClient | MemoryMutationFailpoint\n> = Layer.effectContext(makeMemoryServices());\n\n/** SQLite memory reader, single writer and batch writer with the production no-op failpoint. */\nexport const memoryStoreLayer: Layer.Layer<\n MemoryReader | MemoryWriter | SqlMemoryBatchWriter,\n SqliteMemoryInitializationError,\n SqlClientService.SqlClient\n> = memoryStoreLayerWithFailpoints.pipe(Layer.provide(MemoryMutationFailpoint.layer));\n\n/** Reads an existing memory schema without writes, transactions, or mutation failpoints. */\nexport const memoryReaderLayer: Layer.Layer<\n MemoryReader,\n MemoryStorageError,\n SqlClientService.SqlClient\n> = Layer.effect(\n MemoryReader,\n Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"open memory reader\";\n\n const tables = yield* query(\n sql<Record<string, unknown>>`\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name IN (\n 'effect_agent_memory_metadata', ${DOCUMENT_TABLE}, ${RECEIPT_TABLE}\n )\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(MemoryTableRow, rows, operation)));\n\n if (tables.length !== 3) {\n return yield* storageError(operation, tables.length === 0 ? \"unavailable\" : \"incompatible\");\n }\n\n const metadata = yield* query(\n sql<Record<string, unknown>>`\n SELECT version FROM effect_agent_memory_metadata WHERE component = ${METADATA_COMPONENT}\n `,\n operation,\n ).pipe(Effect.flatMap((rows) => decodeRows(MemoryMetadataRow, rows, operation)));\n\n if (metadata.length !== 1 || metadata[0].version !== STORAGE_VERSION) {\n return yield* storageError(operation, \"incompatible\");\n }\n yield* query(\n sql`\n SELECT namespace, source_id, format_version, generation, revision, document_json\n FROM effect_agent_memory_documents_v1 LIMIT 0\n `,\n operation,\n );\n const { get } = yield* makeMemoryReader();\n\n return MemoryReader.fromAdapter({ get });\n }),\n);\n"],"mappings":";;;;;;;AAuBA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,cAAc;AAEpB,MAAM,aAAa,OAAO,OAAO,MAAM,OAAO,YAAY,QAA0B,CAAC;AAErF,MAAM,sBAAsB,OAAO,OAAO;CACxC,aAAa;CACb,cAAc;CACd,YAAY;AACd,CAAC;AAED,MAAM,8BACJ,OAAO,cAAc,OAAO,UAAU,YAAY,KAAK,QAAQ,EAAE,CAAC,OAAO,OAAO,CAAC;AAEnF,IAAI;AAEJ,MAAM,6BAA6B,OAAO,cAAc,YAAY,KAAK,QAAQ,EAAE,CAAC,OAAO,MAAM;AACjG,IAAI;;AAGJ,MAAa,sBAAsB,OAAO,MAAM,YAAY,IAAI,CAAC,CAAC,MAAM,OAAO,YAAY,GAAG,CAAC;;;;;;;AAQ/F,IAAa,uBAAb,cAA0C,QAAQ,QAOhD,CAAC,CA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,CAAC,IAAI,WAAW,QAAQ,CAC9D;CACF,CAAC,EACH,CAAC;CAED,OAAO,QAAQ,KAAK,cAAc,aAAa,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KACnE,QAAQ,IAAI,cAAc,aAAa,YAAY,EAAE,OAAO,CAAC,CAAC,GAC9D,QAAQ,IAAI,sBAAsB,WAAW,CAC/C;AACF,CAAC;;AAGD,MAAa,iCAIT,MAAM,cAAc,mBAAmB,CAAC;;AAG5C,MAAa,mBAIT,+BAA+B,KAAK,MAAM,QAAQ,wBAAwB,KAAK,CAAC;;AAGpF,MAAa,oBAIT,MAAM,OACR,cACA,OAAO,IAAI,aAAa;CACtB,MAAM,MAAM,OAAO,iBAAiB;CACpC,MAAM,YAAY;CAElB,MAAM,SAAS,OAAO,MACpB,GAA4B;;;4CAGU,eAAe,IAAI,cAAc;;SAGvE,SACF,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,WAAW,gBAAgB,MAAM,SAAS,CAAC,CAAC;CAE5E,IAAI,OAAO,WAAW,GACpB,OAAO,OAAO,aAAa,WAAW,OAAO,WAAW,IAAI,gBAAgB,cAAc;CAG5F,MAAM,WAAW,OAAO,MACtB,GAA4B;6EAC2C,mBAAmB;SAE1F,SACF,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,WAAW,mBAAmB,MAAM,SAAS,CAAC,CAAC;CAE/E,IAAI,SAAS,WAAW,KAAK,SAAS,EAAE,CAAC,YAAY,iBACnD,OAAO,OAAO,aAAa,WAAW,cAAc;CAEtD,OAAO,MACL,GAAG;;;SAIH,SACF;CACA,MAAM,EAAE,QAAQ,OAAO,iBAAiB;CAExC,OAAO,aAAa,YAAY,EAAE,IAAI,CAAC;AACzC,CAAC,CACH"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Context, Effect } from "effect";
|
|
2
|
+
import * as SqlClientService from "effect/sql/SqlClient";
|
|
3
|
+
import { SqlError } from "effect/sql/SqlError";
|
|
4
|
+
//#region src/durable/SqlStorageOwner.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* An exclusive database owner's transaction gate. All cached services over that database
|
|
7
|
+
* must share this identity, and every failed transaction must run its invalidators before
|
|
8
|
+
* releasing readers. Hosts with independent database writers must leave this unset.
|
|
9
|
+
*/
|
|
10
|
+
export interface SqlStorageOwner {
|
|
11
|
+
/** Cache identity for transaction decorators; omission uses the owner itself.
|
|
12
|
+
* Shared identities must name the same database, reader gate and invalidator set. */
|
|
13
|
+
readonly identity?: object;
|
|
14
|
+
readonly read: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
15
|
+
readonly transaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | SqlError, R | SqlClientService.SqlClient>;
|
|
16
|
+
readonly invalidators: Set<() => void>;
|
|
17
|
+
}
|
|
18
|
+
export declare const SqlStorageOwner: Context.Reference<SqlStorageOwner | undefined>;
|
|
19
|
+
//#endregion
|
|
20
|
+
//# sourceMappingURL=SqlStorageOwner.d.mts.map
|