@effect-agent/storage-memory 0.1.0-beta.85 → 0.1.0-beta.86

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.
@@ -1,5 +1,5 @@
1
1
  import { Layer } from "effect";
2
- import { MessageDeliveryError, MessageDeliveryStore, MessageDeliveryStoreLimits } from "@effect-agent/thread/MessageDelivery";
2
+ import { MessageDeliveryError, MessageDeliveryStore, MessageDeliveryStoreLimits } from "effect-agent/message-delivery";
3
3
  declare namespace MemoryMessageDeliveryStore_d_exports {
4
4
  export { MemoryMessageDeliveryStoreLive, MemoryMessageDeliveryStoreOptions, memoryMessageDeliveryStoreLayer };
5
5
  }
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { ScheduleInstant } from "@effect-agent/thread/Schedule";
3
2
  import { Effect, Layer, Ref, Schema, Semaphore } from "effect";
4
- import { ThreadId } from "@effect-agent/core/Identifiers";
5
- import { MessageDeliveryChange, MessageDeliveryError, MessageDeliveryFailpoint, MessageDeliveryKey, MessageDeliveryPageRequest, MessageDeliveryRecord, MessageDeliveryStore, MessageDeliveryStoreLimits, applyMessageDeliveryChange, defaultMessageDeliveryStoreLimits, isWorkerUpdateDelivery, messageDeliveryCapacity, messageDeliveryDeadline, messageDeliveryKeyString, messageDeliveryUsesCapacity, sameMessageDeliveryIdentity, validateMessageDelivery } from "@effect-agent/thread/MessageDelivery";
3
+ import { ScheduleInstant } from "effect-agent/schedule";
4
+ import { ThreadId } from "effect-agent/identifiers";
5
+ import { MessageDeliveryChange, MessageDeliveryError, MessageDeliveryFailpoint, MessageDeliveryKey, MessageDeliveryPageRequest, MessageDeliveryRecord, MessageDeliveryStore, MessageDeliveryStoreLimits, applyMessageDeliveryChange, defaultMessageDeliveryStoreLimits, isWorkerUpdateDelivery, messageDeliveryCapacity, messageDeliveryDeadline, messageDeliveryKeyString, messageDeliveryUsesCapacity, sameMessageDeliveryIdentity, validateMessageDelivery } from "effect-agent/message-delivery";
6
6
  //#region src/MemoryMessageDeliveryStore.ts
7
7
  var MemoryMessageDeliveryStore_exports = /* @__PURE__ */ __exportAll({
8
8
  MemoryMessageDeliveryStoreLive: () => MemoryMessageDeliveryStoreLive,
@@ -1 +1 @@
1
- {"version":3,"file":"MemoryMessageDeliveryStore.mjs","names":[],"sources":["../src/MemoryMessageDeliveryStore.ts"],"sourcesContent":["import { ThreadId } from \"@effect-agent/core/Identifiers\";\nimport {\n applyMessageDeliveryChange,\n defaultMessageDeliveryStoreLimits,\n MessageDeliveryChange,\n MessageDeliveryError,\n MessageDeliveryFailpoint,\n MessageDeliveryKey,\n MessageDeliveryPageRequest,\n MessageDeliveryRecord,\n MessageDeliveryStore,\n MessageDeliveryStoreLimits,\n messageDeliveryDeadline,\n messageDeliveryKeyString,\n messageDeliveryUsesCapacity,\n isWorkerUpdateDelivery,\n messageDeliveryCapacity,\n sameMessageDeliveryIdentity,\n validateMessageDelivery,\n} from \"@effect-agent/thread/MessageDelivery\";\nimport { ScheduleInstant } from \"@effect-agent/thread/Schedule\";\nimport { Effect, Layer, Ref, Schema, Semaphore } from \"effect\";\n\nconst codec = Schema.fromJsonString(MessageDeliveryRecord);\n\nconst decode = (text: string) =>\n Schema.decodeEffect(codec)(text).pipe(\n Effect.mapError(() => MessageDeliveryError.make({ reason: \"corrupt\", operation: \"decode\" })),\n );\n\nconst Scan = Schema.Struct({\n nowMillis: ScheduleInstant,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ownerThreadId: Schema.optionalKey(ThreadId),\n});\n\nexport interface MemoryMessageDeliveryStoreOptions {\n /** UTF-8 bound on the complete stored record, including a processed Settlement. */\n readonly maxStoredValueBytes?: number;\n}\n\n/** Reference adapter. All retained rows are bounded; completed deduplication evidence is never evicted. */\nexport const memoryMessageDeliveryStoreLayer = (\n limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,\n options: MemoryMessageDeliveryStoreOptions = {},\n): Layer.Layer<MessageDeliveryStore, MessageDeliveryError> =>\n Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, \"limits\");\n\n const maxStoredValueBytes = yield* validateMessageDelivery(\n Schema.Int.check(Schema.isGreaterThan(0)),\n options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,\n \"stored-value-limit\",\n );\n\n const state = yield* Ref.make<ReadonlyMap<string, string>>(new Map());\n const lock = yield* Semaphore.make(1);\n const failpoint = yield* MessageDeliveryFailpoint;\n\n const encode = Effect.fn(\"MemoryMessageDeliveryStore.encode\")(function* (\n record: MessageDeliveryRecord,\n ) {\n const text = yield* Schema.encodeEffect(codec)(record).pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"corrupt\", operation: \"encode\" }),\n ),\n );\n\n if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"stored-value-bytes\",\n });\n }\n\n return text;\n });\n\n const all = Effect.fn(\"MemoryMessageDeliveryStore.all\")(function* () {\n return yield* Effect.forEach((yield* Ref.get(state)).values(), decode);\n });\n\n const insert: MessageDeliveryStore[\"Service\"][\"insert\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.insert\",\n )(function* (record) {\n const encoded = yield* encode(record);\n const input = yield* decode(encoded);\n\n if (\n input.version !== 1 ||\n input.status !== \"pending\" ||\n input.leaseUntilMillis !== null ||\n input.retry.attempts !== 0 ||\n input.retry.generation !== 0 ||\n input.retry.automaticAttempts !== 0 ||\n input.retry.nextAttemptAtMillis !== input.createdAtMillis ||\n input.retry.lastAttemptAtMillis !== null ||\n input.retry.lastFailure !== null ||\n input.deadlineAtMillis !== input.initialDeadlineAtMillis\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"validation\",\n operation: \"insert-state\",\n });\n }\n if (\n new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >\n config.maxEnvelopeBytes\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"envelope-bytes\",\n });\n }\n yield* failpoint.hit(\"message-delivery:insert:before\");\n\n const inserted = yield* lock.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const records = yield* Ref.get(state);\n const key = messageDeliveryKeyString(input.key);\n const existingText = records.get(key);\n\n if (existingText !== undefined) {\n const existing = yield* decode(existingText);\n\n if (!sameMessageDeliveryIdentity(existing, input))\n return yield* MessageDeliveryError.make({\n reason: \"conflict\",\n operation: \"insert\",\n });\n\n return existing;\n }\n\n const owned = (yield* all()).filter(\n (record) =>\n record.key.ownerThreadId === input.key.ownerThreadId &&\n isWorkerUpdateDelivery(record) === isWorkerUpdateDelivery(input),\n );\n\n const capacity = messageDeliveryCapacity(config, isWorkerUpdateDelivery(input));\n\n if (\n owned.length >= capacity.retained ||\n owned.filter(messageDeliveryUsesCapacity).length >= capacity.pending\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"insert\",\n });\n }\n yield* Ref.set(state, new Map(records).set(key, encoded));\n\n return input;\n }),\n ),\n );\n\n yield* failpoint.hit(\"message-delivery:insert:after\");\n\n return yield* decode(yield* encode(inserted));\n });\n\n const get: MessageDeliveryStore[\"Service\"][\"get\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.get\",\n )(function* (key) {\n const input = yield* validateMessageDelivery(MessageDeliveryKey, key, \"get\");\n const text = (yield* Ref.get(state)).get(messageDeliveryKeyString(input));\n\n return text === undefined ? null : yield* decode(text);\n });\n\n const change: MessageDeliveryStore[\"Service\"][\"change\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.change\",\n )(function* (key, change) {\n const input = yield* validateMessageDelivery(MessageDeliveryChange, change, \"change\");\n const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, \"change\");\n const point = `message-delivery:${input._tag.toLowerCase()}`;\n\n yield* failpoint.hit(`${point}:before`);\n\n const changed = yield* lock.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const existing = yield* get(decodedKey);\n\n if (existing === null)\n return yield* MessageDeliveryError.make({\n reason: \"not-found\",\n operation: \"change\",\n });\n const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input));\n const encoded = yield* encode(next);\n\n yield* Ref.update(state, (records) =>\n new Map(records).set(messageDeliveryKeyString(decodedKey), encoded),\n );\n\n return next;\n }),\n ),\n );\n\n yield* failpoint.hit(`${point}:after`);\n\n return yield* decode(yield* encode(changed));\n });\n\n return MessageDeliveryStore.of({\n limits: config,\n maxStoredValueBytes,\n insert,\n get,\n change,\n list: Effect.fn(\"MemoryMessageDeliveryStore.list\")(function* (request) {\n const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, \"list\");\n\n const records = (yield* all())\n .filter(\n (record) =>\n record.key.ownerThreadId === input.ownerThreadId &&\n (input.after === undefined || record.key.messageId > input.after),\n )\n .sort((left, right) =>\n left.key.messageId < right.key.messageId\n ? -1\n : left.key.messageId > right.key.messageId\n ? 1\n : 0,\n );\n\n const items = records.slice(0, input.limit);\n\n return {\n items,\n next: records.length > input.limit ? (items.at(-1)?.key.messageId ?? null) : null,\n };\n }),\n due: Effect.fn(\"MemoryMessageDeliveryStore.due\")(\n function* (nowMillis, limit, ownerThreadId) {\n const input = yield* validateMessageDelivery(\n Scan,\n { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },\n \"due\",\n );\n\n return (yield* all())\n .flatMap((record) => {\n const deadline = messageDeliveryDeadline(record);\n\n return deadline !== null &&\n deadline <= input.nowMillis &&\n (input.ownerThreadId === undefined ||\n input.ownerThreadId === record.key.ownerThreadId)\n ? [{ key: record.key, deadline }]\n : [];\n })\n .sort(\n (left, right) =>\n left.deadline - right.deadline ||\n (messageDeliveryKeyString(left.key) < messageDeliveryKeyString(right.key)\n ? -1\n : 1),\n )\n .slice(0, input.limit)\n .map((record) => record.key);\n },\n ),\n nextDeadline: Effect.fn(\"MemoryMessageDeliveryStore.nextDeadline\")(\n function* (ownerThreadId) {\n if (ownerThreadId !== undefined)\n yield* validateMessageDelivery(ThreadId, ownerThreadId, \"nextDeadline\");\n let next: number | null = null;\n\n for (const record of yield* all()) {\n if (ownerThreadId !== undefined && ownerThreadId !== record.key.ownerThreadId)\n continue;\n const deadline = messageDeliveryDeadline(record);\n\n if (deadline !== null && (next === null || deadline < next)) next = deadline;\n }\n\n return next;\n },\n ),\n });\n }),\n );\n\nexport const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer();\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,QAAQ,OAAO,eAAe,qBAAqB;AAEzD,MAAM,UAAU,SACd,OAAO,aAAa,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAC/B,OAAO,eAAe,qBAAqB,KAAK;CAAE,QAAQ;CAAW,WAAW;AAAS,CAAC,CAAC,CAC7F;AAEF,MAAM,OAAO,OAAO,OAAO;CACzB,WAAW;CACX,OAAO,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,GAAG,CAAC;CAChF,eAAe,OAAO,YAAY,QAAQ;AAC5C,CAAC;;AAQD,MAAa,mCACX,SAAqC,mCACrC,UAA6C,CAAC,MAE9C,MAAM,OACJ,sBACA,OAAO,IAAI,aAAa;CACtB,MAAM,SAAS,OAAO,wBAAwB,4BAA4B,QAAQ,QAAQ;CAE1F,MAAM,sBAAsB,OAAO,wBACjC,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC,GACxC,QAAQ,uBAAuB,UAC/B,oBACF;CAEA,MAAM,QAAQ,OAAO,IAAI,qBAAkC,IAAI,IAAI,CAAC;CACpE,MAAM,OAAO,OAAO,UAAU,KAAK,CAAC;CACpC,MAAM,YAAY,OAAO;CAEzB,MAAM,SAAS,OAAO,GAAG,mCAAmC,CAAC,CAAC,WAC5D,QACA;EACA,MAAM,OAAO,OAAO,OAAO,aAAa,KAAK,CAAC,CAAC,MAAM,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C,WAAW,WAAW,OAAO,eAAe;GAC1C,MAAM,QAAQ,OAAO,wBACnB,MACA;IAAE;IAAW;IAAO,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;GAAG,GAC9E,KACF;GAEA,QAAQ,OAAO,IAAI,EAAA,CAChB,SAAS,WAAW;IACnB,MAAM,WAAW,wBAAwB,MAAM;IAE/C,OAAO,aAAa,QAClB,YAAY,MAAM,cACjB,MAAM,kBAAkB,KAAA,KACvB,MAAM,kBAAkB,OAAO,IAAI,iBACnC,CAAC;KAAE,KAAK,OAAO;KAAK;IAAS,CAAC,IAC9B,CAAC;GACP,CAAC,CAAC,CACD,MACE,MAAM,UACL,KAAK,WAAW,MAAM,aACrB,yBAAyB,KAAK,GAAG,IAAI,yBAAyB,MAAM,GAAG,IACpE,KACA,EACR,CAAC,CACA,MAAM,GAAG,MAAM,KAAK,CAAC,CACrB,KAAK,WAAW,OAAO,GAAG;EAC/B,CACF;EACA,cAAc,OAAO,GAAG,yCAAyC,CAAC,CAChE,WAAW,eAAe;GACxB,IAAI,kBAAkB,KAAA,GACpB,OAAO,wBAAwB,UAAU,eAAe,cAAc;GACxE,IAAI,OAAsB;GAE1B,KAAK,MAAM,UAAU,OAAO,IAAI,GAAG;IACjC,IAAI,kBAAkB,KAAA,KAAa,kBAAkB,OAAO,IAAI,eAC9D;IACF,MAAM,WAAW,wBAAwB,MAAM;IAE/C,IAAI,aAAa,SAAS,SAAS,QAAQ,WAAW,OAAO,OAAO;GACtE;GAEA,OAAO;EACT,CACF;CACF,CAAC;AACH,CAAC,CACH;AAEF,MAAa,iCAAiC,gCAAgC"}
1
+ {"version":3,"file":"MemoryMessageDeliveryStore.mjs","names":[],"sources":["../src/MemoryMessageDeliveryStore.ts"],"sourcesContent":["import { Effect, Layer, Ref, Schema, Semaphore } from \"effect\";\nimport { ThreadId } from \"effect-agent/identifiers\";\nimport {\n applyMessageDeliveryChange,\n defaultMessageDeliveryStoreLimits,\n MessageDeliveryChange,\n MessageDeliveryError,\n MessageDeliveryFailpoint,\n MessageDeliveryKey,\n MessageDeliveryPageRequest,\n MessageDeliveryRecord,\n MessageDeliveryStore,\n MessageDeliveryStoreLimits,\n messageDeliveryDeadline,\n messageDeliveryKeyString,\n messageDeliveryUsesCapacity,\n isWorkerUpdateDelivery,\n messageDeliveryCapacity,\n sameMessageDeliveryIdentity,\n validateMessageDelivery,\n} from \"effect-agent/message-delivery\";\nimport { ScheduleInstant } from \"effect-agent/schedule\";\n\nconst codec = Schema.fromJsonString(MessageDeliveryRecord);\n\nconst decode = (text: string) =>\n Schema.decodeEffect(codec)(text).pipe(\n Effect.mapError(() => MessageDeliveryError.make({ reason: \"corrupt\", operation: \"decode\" })),\n );\n\nconst Scan = Schema.Struct({\n nowMillis: ScheduleInstant,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ownerThreadId: Schema.optionalKey(ThreadId),\n});\n\nexport interface MemoryMessageDeliveryStoreOptions {\n /** UTF-8 bound on the complete stored record, including a processed Settlement. */\n readonly maxStoredValueBytes?: number;\n}\n\n/** Reference adapter. All retained rows are bounded; completed deduplication evidence is never evicted. */\nexport const memoryMessageDeliveryStoreLayer = (\n limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,\n options: MemoryMessageDeliveryStoreOptions = {},\n): Layer.Layer<MessageDeliveryStore, MessageDeliveryError> =>\n Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, \"limits\");\n\n const maxStoredValueBytes = yield* validateMessageDelivery(\n Schema.Int.check(Schema.isGreaterThan(0)),\n options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,\n \"stored-value-limit\",\n );\n\n const state = yield* Ref.make<ReadonlyMap<string, string>>(new Map());\n const lock = yield* Semaphore.make(1);\n const failpoint = yield* MessageDeliveryFailpoint;\n\n const encode = Effect.fn(\"MemoryMessageDeliveryStore.encode\")(function* (\n record: MessageDeliveryRecord,\n ) {\n const text = yield* Schema.encodeEffect(codec)(record).pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"corrupt\", operation: \"encode\" }),\n ),\n );\n\n if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"stored-value-bytes\",\n });\n }\n\n return text;\n });\n\n const all = Effect.fn(\"MemoryMessageDeliveryStore.all\")(function* () {\n return yield* Effect.forEach((yield* Ref.get(state)).values(), decode);\n });\n\n const insert: MessageDeliveryStore[\"Service\"][\"insert\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.insert\",\n )(function* (record) {\n const encoded = yield* encode(record);\n const input = yield* decode(encoded);\n\n if (\n input.version !== 1 ||\n input.status !== \"pending\" ||\n input.leaseUntilMillis !== null ||\n input.retry.attempts !== 0 ||\n input.retry.generation !== 0 ||\n input.retry.automaticAttempts !== 0 ||\n input.retry.nextAttemptAtMillis !== input.createdAtMillis ||\n input.retry.lastAttemptAtMillis !== null ||\n input.retry.lastFailure !== null ||\n input.deadlineAtMillis !== input.initialDeadlineAtMillis\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"validation\",\n operation: \"insert-state\",\n });\n }\n if (\n new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >\n config.maxEnvelopeBytes\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"envelope-bytes\",\n });\n }\n yield* failpoint.hit(\"message-delivery:insert:before\");\n\n const inserted = yield* lock.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const records = yield* Ref.get(state);\n const key = messageDeliveryKeyString(input.key);\n const existingText = records.get(key);\n\n if (existingText !== undefined) {\n const existing = yield* decode(existingText);\n\n if (!sameMessageDeliveryIdentity(existing, input))\n return yield* MessageDeliveryError.make({\n reason: \"conflict\",\n operation: \"insert\",\n });\n\n return existing;\n }\n\n const owned = (yield* all()).filter(\n (record) =>\n record.key.ownerThreadId === input.key.ownerThreadId &&\n isWorkerUpdateDelivery(record) === isWorkerUpdateDelivery(input),\n );\n\n const capacity = messageDeliveryCapacity(config, isWorkerUpdateDelivery(input));\n\n if (\n owned.length >= capacity.retained ||\n owned.filter(messageDeliveryUsesCapacity).length >= capacity.pending\n ) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"insert\",\n });\n }\n yield* Ref.set(state, new Map(records).set(key, encoded));\n\n return input;\n }),\n ),\n );\n\n yield* failpoint.hit(\"message-delivery:insert:after\");\n\n return yield* decode(yield* encode(inserted));\n });\n\n const get: MessageDeliveryStore[\"Service\"][\"get\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.get\",\n )(function* (key) {\n const input = yield* validateMessageDelivery(MessageDeliveryKey, key, \"get\");\n const text = (yield* Ref.get(state)).get(messageDeliveryKeyString(input));\n\n return text === undefined ? null : yield* decode(text);\n });\n\n const change: MessageDeliveryStore[\"Service\"][\"change\"] = Effect.fn(\n \"MemoryMessageDeliveryStore.change\",\n )(function* (key, change) {\n const input = yield* validateMessageDelivery(MessageDeliveryChange, change, \"change\");\n const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, \"change\");\n const point = `message-delivery:${input._tag.toLowerCase()}`;\n\n yield* failpoint.hit(`${point}:before`);\n\n const changed = yield* lock.withPermit(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const existing = yield* get(decodedKey);\n\n if (existing === null)\n return yield* MessageDeliveryError.make({\n reason: \"not-found\",\n operation: \"change\",\n });\n const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input));\n const encoded = yield* encode(next);\n\n yield* Ref.update(state, (records) =>\n new Map(records).set(messageDeliveryKeyString(decodedKey), encoded),\n );\n\n return next;\n }),\n ),\n );\n\n yield* failpoint.hit(`${point}:after`);\n\n return yield* decode(yield* encode(changed));\n });\n\n return MessageDeliveryStore.of({\n limits: config,\n maxStoredValueBytes,\n insert,\n get,\n change,\n list: Effect.fn(\"MemoryMessageDeliveryStore.list\")(function* (request) {\n const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, \"list\");\n\n const records = (yield* all())\n .filter(\n (record) =>\n record.key.ownerThreadId === input.ownerThreadId &&\n (input.after === undefined || record.key.messageId > input.after),\n )\n .sort((left, right) =>\n left.key.messageId < right.key.messageId\n ? -1\n : left.key.messageId > right.key.messageId\n ? 1\n : 0,\n );\n\n const items = records.slice(0, input.limit);\n\n return {\n items,\n next: records.length > input.limit ? (items.at(-1)?.key.messageId ?? null) : null,\n };\n }),\n due: Effect.fn(\"MemoryMessageDeliveryStore.due\")(\n function* (nowMillis, limit, ownerThreadId) {\n const input = yield* validateMessageDelivery(\n Scan,\n { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },\n \"due\",\n );\n\n return (yield* all())\n .flatMap((record) => {\n const deadline = messageDeliveryDeadline(record);\n\n return deadline !== null &&\n deadline <= input.nowMillis &&\n (input.ownerThreadId === undefined ||\n input.ownerThreadId === record.key.ownerThreadId)\n ? [{ key: record.key, deadline }]\n : [];\n })\n .sort(\n (left, right) =>\n left.deadline - right.deadline ||\n (messageDeliveryKeyString(left.key) < messageDeliveryKeyString(right.key)\n ? -1\n : 1),\n )\n .slice(0, input.limit)\n .map((record) => record.key);\n },\n ),\n nextDeadline: Effect.fn(\"MemoryMessageDeliveryStore.nextDeadline\")(\n function* (ownerThreadId) {\n if (ownerThreadId !== undefined)\n yield* validateMessageDelivery(ThreadId, ownerThreadId, \"nextDeadline\");\n let next: number | null = null;\n\n for (const record of yield* all()) {\n if (ownerThreadId !== undefined && ownerThreadId !== record.key.ownerThreadId)\n continue;\n const deadline = messageDeliveryDeadline(record);\n\n if (deadline !== null && (next === null || deadline < next)) next = deadline;\n }\n\n return next;\n },\n ),\n });\n }),\n );\n\nexport const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer();\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,QAAQ,OAAO,eAAe,qBAAqB;AAEzD,MAAM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,MAAM,UACL,KAAK,WAAW,MAAM,aACrB,yBAAyB,KAAK,GAAG,IAAI,yBAAyB,MAAM,GAAG,IACpE,KACA,EACR,CAAC,CACA,MAAM,GAAG,MAAM,KAAK,CAAC,CACrB,KAAK,WAAW,OAAO,GAAG;EAC/B,CACF;EACA,cAAc,OAAO,GAAG,yCAAyC,CAAC,CAChE,WAAW,eAAe;GACxB,IAAI,kBAAkB,KAAA,GACpB,OAAO,wBAAwB,UAAU,eAAe,cAAc;GACxE,IAAI,OAAsB;GAE1B,KAAK,MAAM,UAAU,OAAO,IAAI,GAAG;IACjC,IAAI,kBAAkB,KAAA,KAAa,kBAAkB,OAAO,IAAI,eAC9D;IACF,MAAM,WAAW,wBAAwB,MAAM;IAE/C,IAAI,aAAa,SAAS,SAAS,QAAQ,WAAW,OAAO,OAAO;GACtE;GAEA,OAAO;EACT,CACF;CACF,CAAC;AACH,CAAC,CACH;AAEF,MAAa,iCAAiC,gCAAgC"}
@@ -1,5 +1,5 @@
1
- import { ScheduleStore } from "@effect-agent/thread/Schedule";
2
1
  import { Layer } from "effect";
2
+ import { ScheduleStore } from "effect-agent/schedule";
3
3
  declare namespace MemoryScheduleStore_d_exports {
4
4
  export { MemoryScheduleStoreLive, memoryScheduleStoreLayer };
5
5
  }
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { ScheduleCapacityError, ScheduleChange, ScheduleConflict, ScheduleDueCursor, ScheduleFailpoint, ScheduleKey, ScheduleNotFound, ScheduleOwner, SchedulePageRequest, ScheduleRecord, ScheduleStorageError, ScheduleStore, defaultSchedulingLimits } from "@effect-agent/thread/Schedule";
3
- import { applyScheduleChange, compareScheduleKeys, compareScheduleNames, scheduleDeadline, scheduleKeyOf, scheduleKeyString, scheduleOwnerKey, scheduleUsesCapacity } from "@effect-agent/thread/ScheduleTransition";
4
2
  import { Effect, Layer, Ref, Result, Schema } from "effect";
3
+ import { ScheduleCapacityError, ScheduleChange, ScheduleConflict, ScheduleDueCursor, ScheduleFailpoint, ScheduleKey, ScheduleNotFound, ScheduleOwner, SchedulePageRequest, ScheduleRecord, ScheduleStorageError, ScheduleStore, defaultSchedulingLimits } from "effect-agent/schedule";
4
+ import { applyScheduleChange, compareScheduleKeys, compareScheduleNames, scheduleDeadline, scheduleKeyOf, scheduleKeyString, scheduleOwnerKey, scheduleUsesCapacity } from "effect-agent/schedule-transition";
5
5
  //#region src/MemoryScheduleStore.ts
6
6
  var MemoryScheduleStore_exports = /* @__PURE__ */ __exportAll({
7
7
  MemoryScheduleStoreLive: () => MemoryScheduleStoreLive,
@@ -1 +1 @@
1
- {"version":3,"file":"MemoryScheduleStore.mjs","names":[],"sources":["../src/MemoryScheduleStore.ts"],"sourcesContent":["import {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n ScheduleKey,\n ScheduleNotFound,\n ScheduleOwner,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@effect-agent/thread/Schedule\";\nimport {\n scheduleUsesCapacity,\n applyScheduleChange,\n compareScheduleKeys,\n compareScheduleNames,\n scheduleDeadline,\n scheduleKeyString,\n scheduleKeyOf,\n scheduleOwnerKey,\n} from \"@effect-agent/thread/ScheduleTransition\";\nimport { Effect, Layer, Ref, Result, Schema } from \"effect\";\n\ninterface MemoryScheduleState {\n readonly records: ReadonlyMap<string, string>;\n}\n\nconst storageError = (operation: string, reason: \"unavailable\" | \"corrupt\") =>\n ScheduleStorageError.make({ operation, reason });\n\nconst encodeRecord = (operation: string, record: ScheduleRecord) =>\n Effect.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(record),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeRecord = (operation: string, encoded: string) =>\n Effect.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(encoded),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(value),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>\n scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);\n\nconst makeScheduleStore = Effect.gen(function* () {\n const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() });\n const failpoint = yield* ScheduleFailpoint;\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"MemoryScheduleStore.insert\")(\n (record, ownerLimit) =>\n Effect.gen(function* () {\n const encoded = yield* encodeRecord(\"insert\", record);\n\n yield* failpoint.hit(\"schedule:insert:before\");\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleCapacityError | ScheduleStorageError\n >,\n MemoryScheduleState,\n ] => {\n const key = scheduleKeyString(record);\n const existingText = current.records.get(key);\n\n if (existingText !== undefined) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (decoded.success.creationFingerprint === record.creationFingerprint) {\n return [Result.succeed(decoded.success), current];\n }\n\n return [\n Result.fail(\n ScheduleConflict.make({ reason: \"creation\", key: scheduleKeyOf(record) }),\n ),\n current,\n ];\n }\n\n let ownerCount = 0;\n\n for (const text of current.records.values()) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (\n sameOwner(decoded.success, record.owner) &&\n scheduleUsesCapacity(decoded.success)\n )\n ownerCount += 1;\n }\n if (ownerCount >= ownerLimit) {\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n const records = new Map(current.records);\n\n records.set(key, encoded);\n const next = { records };\n\n return [Result.succeed(record), next];\n },\n ),\n );\n\n const inserted = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(\"schedule:insert:after\");\n\n return yield* decodeRecord(\"insert\", yield* encodeRecord(\"insert\", inserted));\n }),\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"MemoryScheduleStore.get\")(\n function* (key) {\n const decodedKey = yield* decodeInput(\"get\", ScheduleKey, key);\n const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey));\n\n return text === undefined ? null : yield* decodeRecord(\"get\", text);\n },\n );\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"MemoryScheduleStore.list\")(\n function* (request) {\n const decodedRequest = yield* decodeInput(\"list\", SchedulePageRequest, request);\n const records: Array<ScheduleRecord> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"list\", text);\n\n if (\n sameOwner(record, decodedRequest.owner) &&\n (decodedRequest.after === undefined ||\n compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)\n ) {\n records.push(record);\n }\n }\n records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId));\n const hasNext = records.length > decodedRequest.limit;\n const items = records.slice(0, decodedRequest.limit);\n\n return {\n items,\n next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,\n };\n },\n );\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"MemoryScheduleStore.change\")(\n (key, command, ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner) =>\n Effect.gen(function* () {\n const decodedKey = yield* decodeInput(\"change\", ScheduleKey, key);\n const decodedCommand = yield* decodeInput(\"change\", ScheduleChange, command);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`);\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError\n >,\n MemoryScheduleState,\n ] => {\n const storageKey = scheduleKeyString(decodedKey);\n const text = current.records.get(storageKey);\n\n if (text === undefined) {\n return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current];\n }\n\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n const applied = applyScheduleChange(decoded.success, decodedCommand);\n\n if (Result.isFailure(applied)) {\n return [Result.fail(applied.failure), current];\n }\n if (applied.success === decoded.success) {\n return [Result.succeed(decoded.success), current];\n }\n if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {\n let count = 0;\n\n for (const text of current.records.values()) {\n const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(\n text,\n );\n\n if (Result.isFailure(candidate))\n return [Result.fail(storageError(\"change\", \"corrupt\")), current];\n if (\n sameOwner(candidate.success, decodedKey.owner) &&\n scheduleUsesCapacity(candidate.success)\n )\n count += 1;\n }\n if (count >= ownerLimit)\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n\n const encoded = Result.try({\n try: () =>\n Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(encoded)) {\n return [Result.fail(encoded.failure), current];\n }\n const records = new Map(current.records);\n\n records.set(storageKey, encoded.success);\n const next = { records };\n\n return [Result.succeed(applied.success), next];\n },\n ),\n );\n\n const changed = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`);\n\n return yield* decodeRecord(\"change\", yield* encodeRecord(\"change\", changed));\n }),\n );\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"MemoryScheduleStore.due\")(\n function* (nowMillis, limit, owner, after) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"due\", ScheduleOwner, owner);\n\n const cursor =\n after === undefined ? undefined : yield* decodeInput(\"due\", ScheduleDueCursor, after);\n\n const records: Array<ScheduleDueCursor> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"due\", text);\n const deadline = scheduleDeadline(record);\n\n if (\n deadline !== null &&\n deadline <= nowMillis &&\n (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&\n (cursor === undefined ||\n deadline > cursor.deadlineAtMillis ||\n (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))\n ) {\n records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline });\n }\n }\n records.sort((left, right) => {\n const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis;\n\n return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right);\n });\n\n return records.slice(0, limit);\n },\n );\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"MemoryScheduleStore.nextDeadline\",\n )(function* (owner) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"nextDeadline\", ScheduleOwner, owner);\n\n let earliest: number | null = null;\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"nextDeadline\", text);\n\n if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue;\n const deadline = scheduleDeadline(record);\n\n if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline;\n }\n\n return earliest;\n });\n\n return ScheduleStore.of({ insert, get, list, change, due, nextDeadline });\n});\n\nexport const memoryScheduleStoreLayer = (): Layer.Layer<ScheduleStore> =>\n Layer.effect(ScheduleStore, makeScheduleStore);\n\nexport const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore> = memoryScheduleStoreLay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K;EACxE,CAAC;EAED,OAAO,QAAQ,MAAM,GAAG,KAAK;CAC/B,CACF;CAEA,MAAM,eAAyD,OAAO,GACpE,kCACF,CAAC,CAAC,WAAW,OAAO;EAClB,MAAM,eACJ,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,YAAY,gBAAgB,eAAe,KAAK;EAE3F,IAAI,WAA0B;EAE9B,KAAK,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK,EAAA,CAAG,QAAQ,OAAO,GAAG;GAC3D,MAAM,SAAS,OAAO,aAAa,gBAAgB,IAAI;GAEvD,IAAI,iBAAiB,KAAA,KAAa,CAAC,UAAU,QAAQ,YAAY,GAAG;GACpE,MAAM,WAAW,iBAAiB,MAAM;GAExC,IAAI,aAAa,SAAS,aAAa,QAAQ,WAAW,WAAW,WAAW;EAClF;EAEA,OAAO;CACT,CAAC;CAED,OAAO,cAAc,GAAG;EAAE;EAAQ;EAAK;EAAM;EAAQ;EAAK;CAAa,CAAC;AAC1E,CAAC;AAED,MAAa,iCACX,MAAM,OAAO,eAAe,iBAAiB;AAE/C,MAAa,0BAAsD,yBAAyB"}
1
+ {"version":3,"file":"MemoryScheduleStore.mjs","names":[],"sources":["../src/MemoryScheduleStore.ts"],"sourcesContent":["import { Effect, Layer, Ref, Result, Schema } from \"effect\";\nimport {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n ScheduleKey,\n ScheduleNotFound,\n ScheduleOwner,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"effect-agent/schedule\";\nimport {\n scheduleUsesCapacity,\n applyScheduleChange,\n compareScheduleKeys,\n compareScheduleNames,\n scheduleDeadline,\n scheduleKeyString,\n scheduleKeyOf,\n scheduleOwnerKey,\n} from \"effect-agent/schedule-transition\";\n\ninterface MemoryScheduleState {\n readonly records: ReadonlyMap<string, string>;\n}\n\nconst storageError = (operation: string, reason: \"unavailable\" | \"corrupt\") =>\n ScheduleStorageError.make({ operation, reason });\n\nconst encodeRecord = (operation: string, record: ScheduleRecord) =>\n Effect.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(record),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeRecord = (operation: string, encoded: string) =>\n Effect.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(encoded),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(value),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>\n scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);\n\nconst makeScheduleStore = Effect.gen(function* () {\n const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() });\n const failpoint = yield* ScheduleFailpoint;\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"MemoryScheduleStore.insert\")(\n (record, ownerLimit) =>\n Effect.gen(function* () {\n const encoded = yield* encodeRecord(\"insert\", record);\n\n yield* failpoint.hit(\"schedule:insert:before\");\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleCapacityError | ScheduleStorageError\n >,\n MemoryScheduleState,\n ] => {\n const key = scheduleKeyString(record);\n const existingText = current.records.get(key);\n\n if (existingText !== undefined) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (decoded.success.creationFingerprint === record.creationFingerprint) {\n return [Result.succeed(decoded.success), current];\n }\n\n return [\n Result.fail(\n ScheduleConflict.make({ reason: \"creation\", key: scheduleKeyOf(record) }),\n ),\n current,\n ];\n }\n\n let ownerCount = 0;\n\n for (const text of current.records.values()) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (\n sameOwner(decoded.success, record.owner) &&\n scheduleUsesCapacity(decoded.success)\n )\n ownerCount += 1;\n }\n if (ownerCount >= ownerLimit) {\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n const records = new Map(current.records);\n\n records.set(key, encoded);\n const next = { records };\n\n return [Result.succeed(record), next];\n },\n ),\n );\n\n const inserted = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(\"schedule:insert:after\");\n\n return yield* decodeRecord(\"insert\", yield* encodeRecord(\"insert\", inserted));\n }),\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"MemoryScheduleStore.get\")(\n function* (key) {\n const decodedKey = yield* decodeInput(\"get\", ScheduleKey, key);\n const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey));\n\n return text === undefined ? null : yield* decodeRecord(\"get\", text);\n },\n );\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"MemoryScheduleStore.list\")(\n function* (request) {\n const decodedRequest = yield* decodeInput(\"list\", SchedulePageRequest, request);\n const records: Array<ScheduleRecord> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"list\", text);\n\n if (\n sameOwner(record, decodedRequest.owner) &&\n (decodedRequest.after === undefined ||\n compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)\n ) {\n records.push(record);\n }\n }\n records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId));\n const hasNext = records.length > decodedRequest.limit;\n const items = records.slice(0, decodedRequest.limit);\n\n return {\n items,\n next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,\n };\n },\n );\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"MemoryScheduleStore.change\")(\n (key, command, ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner) =>\n Effect.gen(function* () {\n const decodedKey = yield* decodeInput(\"change\", ScheduleKey, key);\n const decodedCommand = yield* decodeInput(\"change\", ScheduleChange, command);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`);\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError\n >,\n MemoryScheduleState,\n ] => {\n const storageKey = scheduleKeyString(decodedKey);\n const text = current.records.get(storageKey);\n\n if (text === undefined) {\n return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current];\n }\n\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n const applied = applyScheduleChange(decoded.success, decodedCommand);\n\n if (Result.isFailure(applied)) {\n return [Result.fail(applied.failure), current];\n }\n if (applied.success === decoded.success) {\n return [Result.succeed(decoded.success), current];\n }\n if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {\n let count = 0;\n\n for (const text of current.records.values()) {\n const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(\n text,\n );\n\n if (Result.isFailure(candidate))\n return [Result.fail(storageError(\"change\", \"corrupt\")), current];\n if (\n sameOwner(candidate.success, decodedKey.owner) &&\n scheduleUsesCapacity(candidate.success)\n )\n count += 1;\n }\n if (count >= ownerLimit)\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n\n const encoded = Result.try({\n try: () =>\n Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(encoded)) {\n return [Result.fail(encoded.failure), current];\n }\n const records = new Map(current.records);\n\n records.set(storageKey, encoded.success);\n const next = { records };\n\n return [Result.succeed(applied.success), next];\n },\n ),\n );\n\n const changed = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`);\n\n return yield* decodeRecord(\"change\", yield* encodeRecord(\"change\", changed));\n }),\n );\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"MemoryScheduleStore.due\")(\n function* (nowMillis, limit, owner, after) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"due\", ScheduleOwner, owner);\n\n const cursor =\n after === undefined ? undefined : yield* decodeInput(\"due\", ScheduleDueCursor, after);\n\n const records: Array<ScheduleDueCursor> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"due\", text);\n const deadline = scheduleDeadline(record);\n\n if (\n deadline !== null &&\n deadline <= nowMillis &&\n (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&\n (cursor === undefined ||\n deadline > cursor.deadlineAtMillis ||\n (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))\n ) {\n records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline });\n }\n }\n records.sort((left, right) => {\n const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis;\n\n return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right);\n });\n\n return records.slice(0, limit);\n },\n );\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"MemoryScheduleStore.nextDeadline\",\n )(function* (owner) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"nextDeadline\", ScheduleOwner, owner);\n\n let earliest: number | null = null;\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"nextDeadline\", text);\n\n if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue;\n const deadline = scheduleDeadline(record);\n\n if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline;\n }\n\n return earliest;\n });\n\n return ScheduleStore.of({ insert, get, list, change, due, nextDeadline });\n});\n\nexport const memoryScheduleStoreLayer = (): Layer.Layer<ScheduleStore> =>\n Layer.effect(ScheduleStore, makeScheduleStore);\n\nexport const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore> = memoryScheduleStoreLayer();\n"],"mappings":";;;;;;;;;AA+BA,MAAM,gBAAgB,WAAmB,WACvC,qBAAqB,KAAK;CAAE;CAAW;AAAO,CAAC;AAEjD,MAAM,gBAAgB,WAAmB,WACvC,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,cAAc,CAAC,CAAC,CAAC,MAAM;CAC1E,aAAa,aAAa,WAAW,SAAS;AAChD,CAAC;AAEH,MAAM,gBAAgB,WAAmB,YACvC,OAAO,IAAI;CACT,WAAW,OAAO,WAAW,OAAO,eAAe,cAAc,CAAC,CAAC,CAAC,OAAO;CAC3E,aAAa,aAAa,WAAW,SAAS;AAChD,CAAC;AAEH,MAAM,eAAqB,WAAmB,QAA4B,UACxE,OAAO,IAAI;CACT,WAAW,OAAO,kBAAkB,MAAM,CAAC,CAAC,KAAK;CACjD,aAAa,aAAa,WAAW,SAAS;AAChD,CAAC;AAEH,MAAM,aAAa,QAAwB,UACzC,iBAAiB,OAAO,KAAK,MAAM,iBAAiB,KAAK;AAE3D,MAAM,oBAAoB,OAAO,IAAI,aAAa;CAChD,MAAM,QAAQ,OAAO,IAAI,KAA0B,EAAE,yBAAS,IAAI,IAAI,EAAE,CAAC;CACzE,MAAM,YAAY,OAAO;CAEzB,MAAM,SAA6C,OAAO,GAAG,4BAA4B,CAAC,EACvF,QAAQ,eACP,OAAO,IAAI,aAAa;EACtB,MAAM,UAAU,OAAO,aAAa,UAAU,MAAM;EAEpD,OAAO,UAAU,IAAI,wBAAwB;EAE7C,MAAM,WAAW,OAAO,OAAO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WAAW,KAAA,KACV,WAAW,OAAO,oBACjB,aAAa,OAAO,oBAAoB,oBAAoB,QAAQ,MAAM,IAAI,IAEjF,QAAQ,KAAK;IAAE,GAAG,cAAc,MAAM;IAAG,kBAAkB;GAAS,CAAC;EAEzE;EACA,QAAQ,MAAM,MAAM,UAAU;GAC5B,MAAM,aAAa,KAAK,mBAAmB,MAAM;GAEjD,OAAO,eAAe,IAAI,aAAa,oBAAoB,MAAM,KAAK;EACxE,CAAC;EAED,OAAO,QAAQ,MAAM,GAAG,KAAK;CAC/B,CACF;CAEA,MAAM,eAAyD,OAAO,GACpE,kCACF,CAAC,CAAC,WAAW,OAAO;EAClB,MAAM,eACJ,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,YAAY,gBAAgB,eAAe,KAAK;EAE3F,IAAI,WAA0B;EAE9B,KAAK,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK,EAAA,CAAG,QAAQ,OAAO,GAAG;GAC3D,MAAM,SAAS,OAAO,aAAa,gBAAgB,IAAI;GAEvD,IAAI,iBAAiB,KAAA,KAAa,CAAC,UAAU,QAAQ,YAAY,GAAG;GACpE,MAAM,WAAW,iBAAiB,MAAM;GAExC,IAAI,aAAa,SAAS,aAAa,QAAQ,WAAW,WAAW,WAAW;EAClF;EAEA,OAAO;CACT,CAAC;CAED,OAAO,cAAc,GAAG;EAAE;EAAQ;EAAK;EAAM;EAAQ;EAAK;CAAa,CAAC;AAC1E,CAAC;AAED,MAAa,iCACX,MAAM,OAAO,eAAe,iBAAiB;AAE/C,MAAa,0BAAsD,yBAAyB"}
@@ -1,5 +1,5 @@
1
1
  import { Layer, Schema } from "effect";
2
- import { MemoryIndexError, SemanticMemoryIndex, SemanticMemoryProfile } from "@effect-agent/core/SemanticMemoryIndex";
2
+ import { MemoryIndexError, SemanticMemoryIndex, SemanticMemoryProfile } from "effect-agent/semantic-memory-index";
3
3
  declare namespace MemorySemanticIndex_d_exports {
4
4
  export { InMemorySemanticIndexCapacity, inMemorySemanticIndexLayer };
5
5
  }
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { Clock, Effect, Encoding, Layer, Ref, Schema } from "effect";
3
- import { MemoryKey } from "@effect-agent/core/MemoryStore";
4
- import { MemoryIndexCandidate, MemoryIndexError, MemoryIndexQuery, MemoryIndexReplacement, MemoryIndexSearch, MemoryIndexSource, SemanticMemoryChunk, SemanticMemoryIndex, SemanticMemoryProfile } from "@effect-agent/core/SemanticMemoryIndex";
3
+ import { MemoryKey } from "effect-agent/memory-store";
4
+ import { MemoryIndexCandidate, MemoryIndexError, MemoryIndexQuery, MemoryIndexReplacement, MemoryIndexSearch, MemoryIndexSource, SemanticMemoryChunk, SemanticMemoryIndex, SemanticMemoryProfile } from "effect-agent/semantic-memory-index";
5
5
  //#region src/MemorySemanticIndex.ts
6
6
  var MemorySemanticIndex_exports = /* @__PURE__ */ __exportAll({
7
7
  InMemorySemanticIndexCapacity: () => InMemorySemanticIndexCapacity,
@@ -1 +1 @@
1
- {"version":3,"file":"MemorySemanticIndex.mjs","names":[],"sources":["../src/MemorySemanticIndex.ts"],"sourcesContent":["import { MemoryKey } from \"@effect-agent/core/MemoryStore\";\nimport {\n MemoryIndexCandidate,\n MemoryIndexError,\n MemoryIndexQuery,\n MemoryIndexReplacement,\n MemoryIndexSearch,\n MemoryIndexSource,\n SemanticMemoryChunk,\n SemanticMemoryIndex,\n SemanticMemoryProfile,\n} from \"@effect-agent/core/SemanticMemoryIndex\";\nimport { Clock, Effect, Encoding, Layer, Ref, Schema } from \"effect\";\n\nconst PositiveCapacity = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_536 }));\nconst MaxStoredVectorComponents = 16_777_216;\n\n/**\n * Hard per-Layer bounds for disposable semantic index state. maxChunks times profile dimensions\n * must not exceed 16,777,216 vector components. maxSourceBytes bounds the aggregate UTF-8 JSON\n * of retained source identities and defaults to 16 MiB; it is not a general heap limit.\n */\nexport class InMemorySemanticIndexCapacity extends Schema.Class<InMemorySemanticIndexCapacity>(\n \"@effect-agent/storage-memory/InMemorySemanticIndexCapacity\",\n)({\n maxSources: PositiveCapacity,\n maxChunks: PositiveCapacity,\n maxSourceBytes: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 67_108_864 })),\n ),\n}) {}\n\ntype StoredEntry = {\n readonly source: MemoryIndexSource;\n readonly sourceBytes: number;\n} & (\n | {\n readonly _tag: \"Indexed\";\n readonly chunks: ReadonlyArray<SemanticMemoryChunk>;\n readonly indexedAt: number;\n }\n | { readonly _tag: \"Withdrawn\" }\n);\n\ninterface IndexData {\n readonly closed: boolean;\n readonly entries: ReadonlyMap<string, StoredEntry>;\n readonly sourceBytes: number;\n}\n\nconst sameProfile = Schema.toEquivalence(SemanticMemoryProfile);\nconst sameSource = Schema.toEquivalence(MemoryIndexSource.Wire);\n\nconst error = (operation: string, reason: MemoryIndexError[\"reason\"]): MemoryIndexError =>\n MemoryIndexError.make({ operation, reason });\n\nconst keyString = (key: MemoryKey): string => JSON.stringify([key.namespace.address, key.id]);\n\nconst sourceIdentityBytes = (source: MemoryIndexSource): number =>\n Encoding.encodeHex(JSON.stringify(source)).length / 2;\n\nconst decodeBoundary = Effect.fn(\"InMemorySemanticIndex.decodeBoundary\")(function* <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: unknown,\n operation: string,\n): Effect.fn.Return<A, MemoryIndexError> {\n return yield* Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap((decoded) => Schema.encodeEffect(schema)(decoded).pipe(Effect.as(decoded))),\n Effect.mapError(() => error(operation, \"invalid-input\")),\n );\n});\n\nconst freezeSource = (source: MemoryIndexSource): MemoryIndexSource =>\n Object.freeze(\n MemoryIndexSource.make({\n key: Object.freeze(\n MemoryKey.make({\n ...source.key,\n namespace: Object.freeze({ address: source.key.namespace.address }),\n }),\n ),\n source: Object.freeze({ ...source.source }),\n sourceGeneration: source.sourceGeneration,\n }),\n );\n\nconst freezeChunk = (chunk: SemanticMemoryChunk): SemanticMemoryChunk =>\n Object.freeze(SemanticMemoryChunk.make({ ...chunk, vector: Object.freeze([...chunk.vector]) }));\n\nconst sourceIsFenced = (source: MemoryIndexSource, existing: StoredEntry): boolean =>\n source.sourceGeneration < existing.source.sourceGeneration ||\n (source.sourceGeneration === existing.source.sourceGeneration &&\n !sameSource(source, existing.source));\n\nconst squaredNorm = (vector: ReadonlyArray<number>): number | null => {\n let sum = 0;\n\n for (const value of vector) {\n sum += value * value;\n if (!Number.isFinite(sum)) return null;\n }\n\n return sum > 0 ? sum : null;\n};\n\nconst validVector = (vector: ReadonlyArray<number>, profile: SemanticMemoryProfile): boolean =>\n vector.length === profile.dimensions && squaredNorm(vector) !== null;\n\nconst validateChunks = Effect.fn(\"InMemorySemanticIndex.validateChunks\")(function* (\n chunks: ReadonlyArray<SemanticMemoryChunk>,\n profile: SemanticMemoryProfile,\n operation: string,\n): Effect.fn.Return<void, MemoryIndexError> {\n let nextByte = 0;\n const passageIds = new Set<string>();\n\n for (let index = 0; index < chunks.length; index++) {\n const chunk = chunks[index];\n const byteLength = Encoding.encodeHex(chunk.text).length / 2;\n\n if (\n chunk.ordinal !== index ||\n chunk.startByte !== nextByte ||\n chunk.endByte <= chunk.startByte ||\n chunk.endByte - chunk.startByte !== byteLength ||\n byteLength > profile.maxChunkBytes ||\n passageIds.has(chunk.passageId) ||\n !validVector(chunk.vector, profile)\n ) {\n return yield* error(operation, \"invalid-input\");\n }\n passageIds.add(chunk.passageId);\n nextByte = chunk.endByte;\n }\n});\n\nconst cosine = (left: ReadonlyArray<number>, right: ReadonlyArray<number>): number => {\n const leftNorm = Math.sqrt(squaredNorm(left) ?? 1);\n const rightNorm = Math.sqrt(squaredNorm(right) ?? 1);\n let score = 0;\n\n for (let index = 0; index < left.length; index++) {\n score += (left[index] / leftNorm) * (right[index] / rightNorm);\n }\n const bounded = Math.max(-1, Math.min(1, score));\n\n return bounded === 0 ? 0 : bounded;\n};\n\nconst compareText = (left: string, right: string): number =>\n left < right ? -1 : left > right ? 1 : 0;\n\nconst makeIndex = Effect.fn(\"InMemorySemanticIndex.make\")(function* (\n rawProfile: SemanticMemoryProfile,\n rawCapacity: InMemorySemanticIndexCapacity,\n) {\n const profile = Object.freeze(\n SemanticMemoryProfile.make({\n ...(yield* decodeBoundary(\n SemanticMemoryProfile,\n rawProfile,\n \"configure semantic memory index\",\n )),\n }),\n );\n\n const capacity = yield* decodeBoundary(\n InMemorySemanticIndexCapacity,\n rawCapacity,\n \"configure semantic memory index\",\n );\n\n if (capacity.maxChunks * profile.dimensions > MaxStoredVectorComponents) {\n return yield* error(\"configure semantic memory index\", \"invalid-input\");\n }\n const maxSourceBytes = capacity.maxSourceBytes ?? 16_777_216;\n const data = yield* Ref.make<IndexData>({ closed: false, entries: new Map(), sourceBytes: 0 });\n\n yield* Effect.addFinalizer(() =>\n Ref.set(data, { closed: true, entries: new Map(), sourceBytes: 0 }),\n );\n\n const ensureOpen = Effect.fn(\"InMemorySemanticIndex.ensureOpen\")(function* (operation: string) {\n if ((yield* Ref.get(data)).closed) return yield* error(operation, \"unavailable\");\n });\n\n const replace: SemanticMemoryIndex[\"Service\"][\"replace\"] = Effect.fn(\n \"InMemorySemanticIndex.replace\",\n )(function* (rawRequest) {\n const operation = \"replace semantic memory source\";\n\n yield* ensureOpen(operation);\n const request = yield* decodeBoundary(MemoryIndexReplacement.Wire, rawRequest, operation);\n const source = freezeSource(request.source);\n const sourceBytes = sourceIdentityBytes(source);\n const chunks = Object.freeze(request.chunks.map(freezeChunk));\n\n if (source.source.id !== source.key.id) return yield* error(operation, \"invalid-input\");\n if (!sameProfile(request.profile, profile)) return yield* error(operation, \"incompatible\");\n yield* validateChunks(chunks, profile, operation);\n const indexedAt = yield* Clock.currentTimeMillis;\n\n const failure = yield* Ref.modify(\n data,\n (current): readonly [MemoryIndexError | undefined, IndexData] => {\n if (current.closed) return [error(operation, \"unavailable\"), current];\n const id = keyString(source.key);\n const existing = current.entries.get(id);\n\n if (\n existing !== undefined &&\n (existing._tag === \"Withdrawn\" || sourceIsFenced(source, existing))\n ) {\n return [error(operation, \"fenced\"), current];\n }\n if (existing === undefined && current.entries.size >= capacity.maxSources) {\n return [error(operation, \"budget\"), current];\n }\n const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;\n\n if (nextSourceBytes > maxSourceBytes) return [error(operation, \"budget\"), current];\n let count = chunks.length;\n\n for (const [entryId, entry] of current.entries) {\n if (entryId !== id && entry._tag === \"Indexed\") count += entry.chunks.length;\n }\n if (count > capacity.maxChunks) return [error(operation, \"budget\"), current];\n const entries = new Map(current.entries);\n\n entries.set(id, { _tag: \"Indexed\", source, sourceBytes, chunks, indexedAt });\n\n return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];\n },\n );\n\n if (failure !== undefined) return yield* failure;\n });\n\n const withdraw: SemanticMemoryIndex[\"Service\"][\"withdraw\"] = Effect.fn(\n \"InMemorySemanticIndex.withdraw\",\n )(function* (rawSource) {\n const operation = \"withdraw semantic memory source\";\n\n yield* ensureOpen(operation);\n\n const source = freezeSource(\n yield* decodeBoundary(MemoryIndexSource.Wire, rawSource, operation),\n );\n\n const sourceBytes = sourceIdentityBytes(source);\n\n if (source.source.id !== source.key.id) return yield* error(operation, \"invalid-input\");\n\n const failure = yield* Ref.modify(\n data,\n (current): readonly [MemoryIndexError | undefined, IndexData] => {\n if (current.closed) return [error(operation, \"unavailable\"), current];\n const id = keyString(source.key);\n const existing = current.entries.get(id);\n\n if (existing !== undefined) {\n if (existing._tag === \"Withdrawn\") {\n return [\n sameSource(source, existing.source) ? undefined : error(operation, \"fenced\"),\n current,\n ];\n }\n if (sourceIsFenced(source, existing)) return [error(operation, \"fenced\"), current];\n } else if (current.entries.size >= capacity.maxSources) {\n return [error(operation, \"budget\"), current];\n }\n const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;\n\n if (nextSourceBytes > maxSourceBytes) return [error(operation, \"budget\"), current];\n const entries = new Map(current.entries);\n\n entries.set(id, { _tag: \"Withdrawn\", source, sourceBytes });\n\n return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];\n },\n );\n\n if (failure !== undefined) return yield* failure;\n });\n\n const search = Effect.fn(\"InMemorySemanticIndex.search\")(function* (rawQuery: MemoryIndexQuery) {\n const operation = \"search semantic memory index\";\n\n yield* ensureOpen(operation);\n const query = yield* decodeBoundary(MemoryIndexQuery.Wire, rawQuery, operation);\n const vector = Object.freeze([...query.vector]);\n\n if (!validVector(vector, profile)) return yield* error(operation, \"invalid-input\");\n const current = yield* Ref.get(data);\n\n if (current.closed) return yield* error(operation, \"unavailable\");\n let scannedChunks = 0;\n let inspectedSources = 0;\n const candidates: Array<MemoryIndexCandidate> = [];\n\n for (const entry of current.entries.values()) {\n inspectedSources += 1;\n if (inspectedSources % 128 === 0) yield* Effect.yieldNow;\n if (\n entry.source.key.namespace.address !== query.namespace.address ||\n entry._tag !== \"Indexed\"\n )\n continue;\n scannedChunks += entry.chunks.length;\n if (scannedChunks > query.maxScannedChunks) return yield* error(operation, \"budget\");\n }\n for (const entry of current.entries.values()) {\n if (\n entry.source.key.namespace.address !== query.namespace.address ||\n entry._tag !== \"Indexed\"\n )\n continue;\n yield* Effect.yieldNow;\n for (const chunk of entry.chunks) {\n const score = cosine(vector, chunk.vector);\n\n if (score < query.minScore) continue;\n candidates.push(\n MemoryIndexCandidate.make({\n ...entry.source,\n passageId: chunk.passageId,\n ordinal: chunk.ordinal,\n startByte: chunk.startByte,\n endByte: chunk.endByte,\n text: chunk.text,\n score,\n indexedAt: entry.indexedAt,\n }),\n );\n }\n }\n candidates.sort(\n (left, right) =>\n right.score - left.score ||\n compareText(left.key.id, right.key.id) ||\n compareText(left.source.revision, right.source.revision) ||\n left.ordinal - right.ordinal,\n );\n yield* ensureOpen(operation);\n\n return MemoryIndexSearch.make({ candidates: candidates.slice(0, query.limit), scannedChunks });\n });\n\n return SemanticMemoryIndex.fromAdapter({ profile, replace, withdraw, search });\n});\n\n/** Scoped disposable semantic index. No persistent build or recovery state is retained. */\nexport const inMemorySemanticIndexLayer = (\n profile: SemanticMemoryProfile,\n capacity: InMemorySemanticIndexCapacity,\n): Layer.Layer<SemanticMemoryIndex, MemoryIndexError> =>\n Layer.effect(SemanticMemoryIndex, makeIndex(profile, capacity));\n"],"mappings":";;;;;;;;;AAcA,MAAM,mBAAmB,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAO,CAAC,CAAC;AAC3F,MAAM,4BAA4B;;;;;;AAOlC,IAAa,gCAAb,cAAmD,OAAO,MACxD,4DACF,CAAC,CAAC;CACA,YAAY;CACZ,WAAW;CACX,gBAAgB,OAAO,YACrB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAW,CAAC,CAAC,CACxE;AACF,CAAC,CAAC,CAAC,CAAC;AAoBJ,MAAM,cAAc,OAAO,cAAc,qBAAqB;AAC9D,MAAM,aAAa,OAAO,cAAc,kBAAkB,IAAI;AAE9D,MAAM,SAAS,WAAmB,WAChC,iBAAiB,KAAK;CAAE;CAAW;AAAO,CAAC;AAE7C,MAAM,aAAa,QAA2B,KAAK,UAAU,CAAC,IAAI,UAAU,SAAS,IAAI,EAAE,CAAC;AAE5F,MAAM,uBAAuB,WAC3B,SAAS,UAAU,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,SAAS;AAEtD,MAAM,iBAAiB,OAAO,GAAG,sCAAsC,CAAC,CAAC,WACvE,QACA,OACA,WACuC;CACvC,OAAO,OAAO,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACtD,OAAO,SAAS,YAAY,OAAO,aAAa,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,OAAO,GAAG,OAAO,CAAC,CAAC,GACzF,OAAO,eAAe,MAAM,WAAW,eAAe,CAAC,CACzD;AACF,CAAC;AAED,MAAM,gB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,QAAQ,OAAO,QAAQ,MAAM,MAAM;IAEzC,IAAI,QAAQ,MAAM,UAAU;IAC5B,WAAW,KACT,qBAAqB,KAAK;KACxB,GAAG,MAAM;KACT,WAAW,MAAM;KACjB,SAAS,MAAM;KACf,WAAW,MAAM;KACjB,SAAS,MAAM;KACf,MAAM,MAAM;KACZ;KACA,WAAW,MAAM;IACnB,CAAC,CACH;GACF;EACF;EACA,WAAW,MACR,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,YAAY,KAAK,IAAI,IAAI,MAAM,IAAI,EAAE,KACrC,YAAY,KAAK,OAAO,UAAU,MAAM,OAAO,QAAQ,KACvD,KAAK,UAAU,MAAM,OACzB;EACA,OAAO,WAAW,SAAS;EAE3B,OAAO,kBAAkB,KAAK;GAAE,YAAY,WAAW,MAAM,GAAG,MAAM,KAAK;GAAG;EAAc,CAAC;CAC/F,CAAC;CAED,OAAO,oBAAoB,YAAY;EAAE;EAAS;EAAS;EAAU;CAAO,CAAC;AAC/E,CAAC;;AAGD,MAAa,8BACX,SACA,aAEA,MAAM,OAAO,qBAAqB,UAAU,SAAS,QAAQ,CAAC"}
1
+ {"version":3,"file":"MemorySemanticIndex.mjs","names":[],"sources":["../src/MemorySemanticIndex.ts"],"sourcesContent":["import { Clock, Effect, Encoding, Layer, Ref, Schema } from \"effect\";\nimport { MemoryKey } from \"effect-agent/memory-store\";\nimport {\n MemoryIndexCandidate,\n MemoryIndexError,\n MemoryIndexQuery,\n MemoryIndexReplacement,\n MemoryIndexSearch,\n MemoryIndexSource,\n SemanticMemoryChunk,\n SemanticMemoryIndex,\n SemanticMemoryProfile,\n} from \"effect-agent/semantic-memory-index\";\n\nconst PositiveCapacity = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_536 }));\nconst MaxStoredVectorComponents = 16_777_216;\n\n/**\n * Hard per-Layer bounds for disposable semantic index state. maxChunks times profile dimensions\n * must not exceed 16,777,216 vector components. maxSourceBytes bounds the aggregate UTF-8 JSON\n * of retained source identities and defaults to 16 MiB; it is not a general heap limit.\n */\nexport class InMemorySemanticIndexCapacity extends Schema.Class<InMemorySemanticIndexCapacity>(\n \"@effect-agent/storage-memory/InMemorySemanticIndexCapacity\",\n)({\n maxSources: PositiveCapacity,\n maxChunks: PositiveCapacity,\n maxSourceBytes: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 67_108_864 })),\n ),\n}) {}\n\ntype StoredEntry = {\n readonly source: MemoryIndexSource;\n readonly sourceBytes: number;\n} & (\n | {\n readonly _tag: \"Indexed\";\n readonly chunks: ReadonlyArray<SemanticMemoryChunk>;\n readonly indexedAt: number;\n }\n | { readonly _tag: \"Withdrawn\" }\n);\n\ninterface IndexData {\n readonly closed: boolean;\n readonly entries: ReadonlyMap<string, StoredEntry>;\n readonly sourceBytes: number;\n}\n\nconst sameProfile = Schema.toEquivalence(SemanticMemoryProfile);\nconst sameSource = Schema.toEquivalence(MemoryIndexSource.Wire);\n\nconst error = (operation: string, reason: MemoryIndexError[\"reason\"]): MemoryIndexError =>\n MemoryIndexError.make({ operation, reason });\n\nconst keyString = (key: MemoryKey): string => JSON.stringify([key.namespace.address, key.id]);\n\nconst sourceIdentityBytes = (source: MemoryIndexSource): number =>\n Encoding.encodeHex(JSON.stringify(source)).length / 2;\n\nconst decodeBoundary = Effect.fn(\"InMemorySemanticIndex.decodeBoundary\")(function* <A, I>(\n schema: Schema.Codec<A, I, never>,\n value: unknown,\n operation: string,\n): Effect.fn.Return<A, MemoryIndexError> {\n return yield* Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap((decoded) => Schema.encodeEffect(schema)(decoded).pipe(Effect.as(decoded))),\n Effect.mapError(() => error(operation, \"invalid-input\")),\n );\n});\n\nconst freezeSource = (source: MemoryIndexSource): MemoryIndexSource =>\n Object.freeze(\n MemoryIndexSource.make({\n key: Object.freeze(\n MemoryKey.make({\n ...source.key,\n namespace: Object.freeze({ address: source.key.namespace.address }),\n }),\n ),\n source: Object.freeze({ ...source.source }),\n sourceGeneration: source.sourceGeneration,\n }),\n );\n\nconst freezeChunk = (chunk: SemanticMemoryChunk): SemanticMemoryChunk =>\n Object.freeze(SemanticMemoryChunk.make({ ...chunk, vector: Object.freeze([...chunk.vector]) }));\n\nconst sourceIsFenced = (source: MemoryIndexSource, existing: StoredEntry): boolean =>\n source.sourceGeneration < existing.source.sourceGeneration ||\n (source.sourceGeneration === existing.source.sourceGeneration &&\n !sameSource(source, existing.source));\n\nconst squaredNorm = (vector: ReadonlyArray<number>): number | null => {\n let sum = 0;\n\n for (const value of vector) {\n sum += value * value;\n if (!Number.isFinite(sum)) return null;\n }\n\n return sum > 0 ? sum : null;\n};\n\nconst validVector = (vector: ReadonlyArray<number>, profile: SemanticMemoryProfile): boolean =>\n vector.length === profile.dimensions && squaredNorm(vector) !== null;\n\nconst validateChunks = Effect.fn(\"InMemorySemanticIndex.validateChunks\")(function* (\n chunks: ReadonlyArray<SemanticMemoryChunk>,\n profile: SemanticMemoryProfile,\n operation: string,\n): Effect.fn.Return<void, MemoryIndexError> {\n let nextByte = 0;\n const passageIds = new Set<string>();\n\n for (let index = 0; index < chunks.length; index++) {\n const chunk = chunks[index];\n const byteLength = Encoding.encodeHex(chunk.text).length / 2;\n\n if (\n chunk.ordinal !== index ||\n chunk.startByte !== nextByte ||\n chunk.endByte <= chunk.startByte ||\n chunk.endByte - chunk.startByte !== byteLength ||\n byteLength > profile.maxChunkBytes ||\n passageIds.has(chunk.passageId) ||\n !validVector(chunk.vector, profile)\n ) {\n return yield* error(operation, \"invalid-input\");\n }\n passageIds.add(chunk.passageId);\n nextByte = chunk.endByte;\n }\n});\n\nconst cosine = (left: ReadonlyArray<number>, right: ReadonlyArray<number>): number => {\n const leftNorm = Math.sqrt(squaredNorm(left) ?? 1);\n const rightNorm = Math.sqrt(squaredNorm(right) ?? 1);\n let score = 0;\n\n for (let index = 0; index < left.length; index++) {\n score += (left[index] / leftNorm) * (right[index] / rightNorm);\n }\n const bounded = Math.max(-1, Math.min(1, score));\n\n return bounded === 0 ? 0 : bounded;\n};\n\nconst compareText = (left: string, right: string): number =>\n left < right ? -1 : left > right ? 1 : 0;\n\nconst makeIndex = Effect.fn(\"InMemorySemanticIndex.make\")(function* (\n rawProfile: SemanticMemoryProfile,\n rawCapacity: InMemorySemanticIndexCapacity,\n) {\n const profile = Object.freeze(\n SemanticMemoryProfile.make({\n ...(yield* decodeBoundary(\n SemanticMemoryProfile,\n rawProfile,\n \"configure semantic memory index\",\n )),\n }),\n );\n\n const capacity = yield* decodeBoundary(\n InMemorySemanticIndexCapacity,\n rawCapacity,\n \"configure semantic memory index\",\n );\n\n if (capacity.maxChunks * profile.dimensions > MaxStoredVectorComponents) {\n return yield* error(\"configure semantic memory index\", \"invalid-input\");\n }\n const maxSourceBytes = capacity.maxSourceBytes ?? 16_777_216;\n const data = yield* Ref.make<IndexData>({ closed: false, entries: new Map(), sourceBytes: 0 });\n\n yield* Effect.addFinalizer(() =>\n Ref.set(data, { closed: true, entries: new Map(), sourceBytes: 0 }),\n );\n\n const ensureOpen = Effect.fn(\"InMemorySemanticIndex.ensureOpen\")(function* (operation: string) {\n if ((yield* Ref.get(data)).closed) return yield* error(operation, \"unavailable\");\n });\n\n const replace: SemanticMemoryIndex[\"Service\"][\"replace\"] = Effect.fn(\n \"InMemorySemanticIndex.replace\",\n )(function* (rawRequest) {\n const operation = \"replace semantic memory source\";\n\n yield* ensureOpen(operation);\n const request = yield* decodeBoundary(MemoryIndexReplacement.Wire, rawRequest, operation);\n const source = freezeSource(request.source);\n const sourceBytes = sourceIdentityBytes(source);\n const chunks = Object.freeze(request.chunks.map(freezeChunk));\n\n if (source.source.id !== source.key.id) return yield* error(operation, \"invalid-input\");\n if (!sameProfile(request.profile, profile)) return yield* error(operation, \"incompatible\");\n yield* validateChunks(chunks, profile, operation);\n const indexedAt = yield* Clock.currentTimeMillis;\n\n const failure = yield* Ref.modify(\n data,\n (current): readonly [MemoryIndexError | undefined, IndexData] => {\n if (current.closed) return [error(operation, \"unavailable\"), current];\n const id = keyString(source.key);\n const existing = current.entries.get(id);\n\n if (\n existing !== undefined &&\n (existing._tag === \"Withdrawn\" || sourceIsFenced(source, existing))\n ) {\n return [error(operation, \"fenced\"), current];\n }\n if (existing === undefined && current.entries.size >= capacity.maxSources) {\n return [error(operation, \"budget\"), current];\n }\n const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;\n\n if (nextSourceBytes > maxSourceBytes) return [error(operation, \"budget\"), current];\n let count = chunks.length;\n\n for (const [entryId, entry] of current.entries) {\n if (entryId !== id && entry._tag === \"Indexed\") count += entry.chunks.length;\n }\n if (count > capacity.maxChunks) return [error(operation, \"budget\"), current];\n const entries = new Map(current.entries);\n\n entries.set(id, { _tag: \"Indexed\", source, sourceBytes, chunks, indexedAt });\n\n return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];\n },\n );\n\n if (failure !== undefined) return yield* failure;\n });\n\n const withdraw: SemanticMemoryIndex[\"Service\"][\"withdraw\"] = Effect.fn(\n \"InMemorySemanticIndex.withdraw\",\n )(function* (rawSource) {\n const operation = \"withdraw semantic memory source\";\n\n yield* ensureOpen(operation);\n\n const source = freezeSource(\n yield* decodeBoundary(MemoryIndexSource.Wire, rawSource, operation),\n );\n\n const sourceBytes = sourceIdentityBytes(source);\n\n if (source.source.id !== source.key.id) return yield* error(operation, \"invalid-input\");\n\n const failure = yield* Ref.modify(\n data,\n (current): readonly [MemoryIndexError | undefined, IndexData] => {\n if (current.closed) return [error(operation, \"unavailable\"), current];\n const id = keyString(source.key);\n const existing = current.entries.get(id);\n\n if (existing !== undefined) {\n if (existing._tag === \"Withdrawn\") {\n return [\n sameSource(source, existing.source) ? undefined : error(operation, \"fenced\"),\n current,\n ];\n }\n if (sourceIsFenced(source, existing)) return [error(operation, \"fenced\"), current];\n } else if (current.entries.size >= capacity.maxSources) {\n return [error(operation, \"budget\"), current];\n }\n const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;\n\n if (nextSourceBytes > maxSourceBytes) return [error(operation, \"budget\"), current];\n const entries = new Map(current.entries);\n\n entries.set(id, { _tag: \"Withdrawn\", source, sourceBytes });\n\n return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];\n },\n );\n\n if (failure !== undefined) return yield* failure;\n });\n\n const search = Effect.fn(\"InMemorySemanticIndex.search\")(function* (rawQuery: MemoryIndexQuery) {\n const operation = \"search semantic memory index\";\n\n yield* ensureOpen(operation);\n const query = yield* decodeBoundary(MemoryIndexQuery.Wire, rawQuery, operation);\n const vector = Object.freeze([...query.vector]);\n\n if (!validVector(vector, profile)) return yield* error(operation, \"invalid-input\");\n const current = yield* Ref.get(data);\n\n if (current.closed) return yield* error(operation, \"unavailable\");\n let scannedChunks = 0;\n let inspectedSources = 0;\n const candidates: Array<MemoryIndexCandidate> = [];\n\n for (const entry of current.entries.values()) {\n inspectedSources += 1;\n if (inspectedSources % 128 === 0) yield* Effect.yieldNow;\n if (\n entry.source.key.namespace.address !== query.namespace.address ||\n entry._tag !== \"Indexed\"\n )\n continue;\n scannedChunks += entry.chunks.length;\n if (scannedChunks > query.maxScannedChunks) return yield* error(operation, \"budget\");\n }\n for (const entry of current.entries.values()) {\n if (\n entry.source.key.namespace.address !== query.namespace.address ||\n entry._tag !== \"Indexed\"\n )\n continue;\n yield* Effect.yieldNow;\n for (const chunk of entry.chunks) {\n const score = cosine(vector, chunk.vector);\n\n if (score < query.minScore) continue;\n candidates.push(\n MemoryIndexCandidate.make({\n ...entry.source,\n passageId: chunk.passageId,\n ordinal: chunk.ordinal,\n startByte: chunk.startByte,\n endByte: chunk.endByte,\n text: chunk.text,\n score,\n indexedAt: entry.indexedAt,\n }),\n );\n }\n }\n candidates.sort(\n (left, right) =>\n right.score - left.score ||\n compareText(left.key.id, right.key.id) ||\n compareText(left.source.revision, right.source.revision) ||\n left.ordinal - right.ordinal,\n );\n yield* ensureOpen(operation);\n\n return MemoryIndexSearch.make({ candidates: candidates.slice(0, query.limit), scannedChunks });\n });\n\n return SemanticMemoryIndex.fromAdapter({ profile, replace, withdraw, search });\n});\n\n/** Scoped disposable semantic index. No persistent build or recovery state is retained. */\nexport const inMemorySemanticIndexLayer = (\n profile: SemanticMemoryProfile,\n capacity: InMemorySemanticIndexCapacity,\n): Layer.Layer<SemanticMemoryIndex, MemoryIndexError> =>\n Layer.effect(SemanticMemoryIndex, makeIndex(profile, capacity));\n"],"mappings":";;;;;;;;;AAcA,MAAM,mBAAmB,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAO,CAAC,CAAC;AAC3F,MAAM,4BAA4B;;;;;;AAOlC,IAAa,gCAAb,cAAmD,OAAO,MACxD,4DACF,CAAC,CAAC;CACA,YAAY;CACZ,WAAW;CACX,gBAAgB,OAAO,YACrB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAW,CAAC,CAAC,CACxE;AACF,CAAC,CAAC,CAAC,CAAC;AAoBJ,MAAM,cAAc,OAAO,cAAc,qBAAqB;AAC9D,MAAM,aAAa,OAAO,cAAc,kBAAkB,IAAI;AAE9D,MAAM,SAAS,WAAmB,WAChC,iBAAiB,KAAK;CAAE;CAAW;AAAO,CAAC;AAE7C,MAAM,aAAa,QAA2B,KAAK,UAAU,CAAC,IAAI,UAAU,SAAS,IAAI,EAAE,CAAC;AAE5F,MAAM,uBAAuB,WAC3B,SAAS,UAAU,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,SAAS;AAEtD,MAAM,iBAAiB,OAAO,GAAG,sCAAsC,CAAC,CAAC,WACvE,QACA,OACA,WACuC;CACvC,OAAO,OAAO,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACtD,OAAO,SAAS,YAAY,OAAO,aAAa,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,OAAO,GAAG,OAAO,CAAC,CAAC,GACzF,OAAO,eAAe,MAAM,WAAW,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KAAK,MAAM,SAAS,MAAM,QAAQ;IAChC,MAAM,QAAQ,OAAO,QAAQ,MAAM,MAAM;IAEzC,IAAI,QAAQ,MAAM,UAAU;IAC5B,WAAW,KACT,qBAAqB,KAAK;KACxB,GAAG,MAAM;KACT,WAAW,MAAM;KACjB,SAAS,MAAM;KACf,WAAW,MAAM;KACjB,SAAS,MAAM;KACf,MAAM,MAAM;KACZ;KACA,WAAW,MAAM;IACnB,CAAC,CACH;GACF;EACF;EACA,WAAW,MACR,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,YAAY,KAAK,IAAI,IAAI,MAAM,IAAI,EAAE,KACrC,YAAY,KAAK,OAAO,UAAU,MAAM,OAAO,QAAQ,KACvD,KAAK,UAAU,MAAM,OACzB;EACA,OAAO,WAAW,SAAS;EAE3B,OAAO,kBAAkB,KAAK;GAAE,YAAY,WAAW,MAAM,GAAG,MAAM,KAAK;GAAG;EAAc,CAAC;CAC/F,CAAC;CAED,OAAO,oBAAoB,YAAY;EAAE;EAAS;EAAS;EAAU;CAAO,CAAC;AAC/E,CAAC;;AAGD,MAAa,8BACX,SACA,aAEA,MAAM,OAAO,qBAAqB,UAAU,SAAS,QAAQ,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { Effect, Layer, Option } from "effect";
2
- import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
2
+ import { SubmissionLedger } from "effect-agent/submission-ledger";
3
3
  declare namespace MemorySubmissionLedger_d_exports {
4
4
  export { MemorySubmissionLedgerLive, MemorySubmissionLedgerOptions, memorySubmissionLedgerLayer };
5
5
  }
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { Cause, Clock, DateTime, Duration, Effect, Exit, Fiber, Layer, Option, Ref, Schema, Stream } from "effect";
3
- import { AttemptId, ReceiptId, SubmissionId } from "@effect-agent/core/Identifiers";
4
- import { InputMessage } from "@effect-agent/core/Messaging";
5
- import { PersistedJson, ProducerEpoch, WorkerAdmission } from "@effect-agent/thread/Records";
6
- import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionIndeterminate, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, DEFAULT_OWNERSHIP_LEASE_DURATION, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, OwnershipToken, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementReservation, SettlementReservationSnapshot, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SuspendRequest, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, settlementFailureFromRecord } from "@effect-agent/thread/SubmissionLedger";
3
+ import { AttemptId, ReceiptId, SubmissionId } from "effect-agent/identifiers";
4
+ import { InputMessage } from "effect-agent/messaging";
5
+ import { PersistedJson, ProducerEpoch, WorkerAdmission } from "effect-agent/records";
6
+ import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionIndeterminate, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, DEFAULT_OWNERSHIP_LEASE_DURATION, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, OwnershipToken, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementReservation, SettlementReservationSnapshot, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SuspendRequest, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, settlementFailureFromRecord } from "effect-agent/submission-ledger";
7
7
  //#region src/MemorySubmissionLedger.ts
8
8
  var MemorySubmissionLedger_exports = /* @__PURE__ */ __exportAll({
9
9
  MemorySubmissionLedgerLive: () => MemorySubmissionLedgerLive,