@ferricstore/ferricstore 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +2 -2
  2. package/dist/index.cjs +591 -133
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +61 -7
  5. package/dist/index.d.ts +61 -7
  6. package/dist/index.js +586 -129
  7. package/dist/index.js.map +1 -1
  8. package/dist/langgraph.cjs.map +1 -1
  9. package/dist/langgraph.d.cts +1 -1
  10. package/dist/langgraph.d.ts +1 -1
  11. package/dist/langgraph.js.map +1 -1
  12. package/dist/{outcomes-DmBwnq0Y.d.cts → outcomes-CcX956h4.d.cts} +20 -1
  13. package/dist/{outcomes-BbFDp3AH.d.ts → outcomes-DLJYTrX8.d.ts} +20 -1
  14. package/docs/api/assets/hierarchy.js +1 -1
  15. package/docs/api/assets/navigation.js +1 -1
  16. package/docs/api/assets/search.js +1 -1
  17. package/docs/api/classes/ConnectionClosedError.html +1 -1
  18. package/docs/api/classes/FerricStoreClient.html +68 -23
  19. package/docs/api/classes/FerricStoreError.html +1 -1
  20. package/docs/api/classes/FlowAlreadyExistsError.html +1 -1
  21. package/docs/api/classes/FlowBatchError.html +1 -1
  22. package/docs/api/classes/FlowNotFoundError.html +1 -1
  23. package/docs/api/classes/FlowQueryError.html +1 -1
  24. package/docs/api/classes/FlowWrongStateError.html +1 -1
  25. package/docs/api/classes/HTTPTransportError.html +1 -1
  26. package/docs/api/classes/InvalidCommandError.html +1 -1
  27. package/docs/api/classes/LeaseRenewalError.html +3 -3
  28. package/docs/api/classes/LockHeldError.html +1 -1
  29. package/docs/api/classes/LockNotOwnedError.html +1 -1
  30. package/docs/api/classes/OverloadedError.html +1 -1
  31. package/docs/api/classes/QueueCompletionError.html +1 -1
  32. package/docs/api/classes/RequestTimeoutError.html +1 -1
  33. package/docs/api/classes/RerouteError.html +1 -1
  34. package/docs/api/classes/StaleLeaseError.html +1 -1
  35. package/docs/api/classes/StalePolicyGenerationError.html +1 -1
  36. package/docs/api/classes/Workflow.html +19 -19
  37. package/docs/api/classes/WorkflowClient.html +4 -4
  38. package/docs/api/classes/WorkflowContext.html +74 -36
  39. package/docs/api/classes/WorkflowFlowCommands.html +26 -22
  40. package/docs/api/classes/WorkflowWorker.html +6 -6
  41. package/docs/api/functions/complete.html +1 -1
  42. package/docs/api/functions/fail.html +1 -1
  43. package/docs/api/functions/isAlreadyAppliedOutcome.html +41 -0
  44. package/docs/api/functions/isOutcome.html +1 -1
  45. package/docs/api/functions/retry.html +1 -1
  46. package/docs/api/functions/transition.html +1 -1
  47. package/docs/api/hierarchy.html +55 -47
  48. package/docs/api/index.html +2 -2
  49. package/docs/api/interfaces/AdminListOptions.html +1 -1
  50. package/docs/api/interfaces/AdvanceOptions.html +141 -0
  51. package/docs/api/interfaces/AlreadyAppliedOutcome.html +69 -0
  52. package/docs/api/interfaces/AppliedStepOutcome.html +87 -0
  53. package/docs/api/interfaces/CancelOptions.html +6 -6
  54. package/docs/api/interfaces/CompleteOptions.html +4 -4
  55. package/docs/api/interfaces/CompleteOutcome.html +13 -13
  56. package/docs/api/interfaces/CreateManyOptions.html +1 -1
  57. package/docs/api/interfaces/EffectCompensateOptions.html +1 -1
  58. package/docs/api/interfaces/EffectConfirmOptions.html +1 -1
  59. package/docs/api/interfaces/EffectFailOptions.html +1 -1
  60. package/docs/api/interfaces/EffectStatusOptions.html +1 -1
  61. package/docs/api/interfaces/FailOptions.html +4 -4
  62. package/docs/api/interfaces/FailOutcome.html +13 -13
  63. package/docs/api/interfaces/FerricStoreClientFromUrlOptions.html +1 -1
  64. package/docs/api/interfaces/FerricStoreClientOptions.html +1 -1
  65. package/docs/api/interfaces/FlowQueryCountResult.html +1 -1
  66. package/docs/api/interfaces/FlowQueryIndexBuild.html +1 -1
  67. package/docs/api/interfaces/FlowQueryIndexProgress.html +1 -1
  68. package/docs/api/interfaces/FlowQueryIndexValidation.html +1 -1
  69. package/docs/api/interfaces/FlowQueryRecordsResult.html +1 -1
  70. package/docs/api/interfaces/HistoryOptions.html +16 -16
  71. package/docs/api/interfaces/InvocationCreateOptions.html +1 -1
  72. package/docs/api/interfaces/LeaseMutationOptions.html +1 -1
  73. package/docs/api/interfaces/LimitListOptions.html +1 -1
  74. package/docs/api/interfaces/MutateOptions.html +1 -1
  75. package/docs/api/interfaces/NamedValueMutation.html +9 -9
  76. package/docs/api/interfaces/ReadOptions.html +12 -12
  77. package/docs/api/interfaces/ReclaimOptions.html +1 -1
  78. package/docs/api/interfaces/ReplayedStepResult.html +73 -0
  79. package/docs/api/interfaces/RequestContextOptions.html +1 -1
  80. package/docs/api/interfaces/RetryOptions.html +4 -4
  81. package/docs/api/interfaces/RetryOutcome.html +13 -13
  82. package/docs/api/interfaces/RunStepsItem.html +3 -3
  83. package/docs/api/interfaces/RunStepsManyOptions.html +11 -11
  84. package/docs/api/interfaces/SearchOptions.html +13 -13
  85. package/docs/api/interfaces/StepContinueOptions.html +1 -1
  86. package/docs/api/interfaces/StepOptions.html +159 -0
  87. package/docs/api/interfaces/StepResult.html +67 -0
  88. package/docs/api/interfaces/TDigestCreateOptions.html +1 -1
  89. package/docs/api/interfaces/TDigestMergeOptions.html +1 -1
  90. package/docs/api/interfaces/TransitionOptions.html +1 -1
  91. package/docs/api/interfaces/TransitionOutcome.html +14 -14
  92. package/docs/api/modules.html +6 -6
  93. package/docs/api/types/ConnectionRequestDisposition.html +1 -1
  94. package/docs/api/types/ManagementPairs.html +1 -1
  95. package/docs/api/types/Outcome.html +1 -1
  96. package/docs/api/types/SearchStateMeta.html +1 -1
  97. package/docs/api/types/WorkflowStepResult.html +38 -0
  98. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/langgraph.ts","../src/langgraph/checkpoint.ts","../src/agent-persistence/durability.ts","../src/errors.ts","../src/langgraph/store.ts","../src/langgraph/flow.ts","../src/outcomes.ts"],"sourcesContent":["export {\n FerricStoreSaver,\n type FerricStoreSaverOptions,\n type LangGraphChannelVersions,\n type LangGraphPendingWrite\n} from \"./langgraph/checkpoint.js\";\nexport {\n FerricStoreStore,\n type FerricStoreStoreOptions\n} from \"./langgraph/store.js\";\nexport {\n LangGraphFlow,\n LangGraphFlowContext,\n LangGraphFlowRun,\n type FerricFlowHandlerContext,\n type InvokableLangGraph,\n type LangGraphFlowOptions,\n type LangGraphInvocationConfig,\n type LangGraphOutcomeMapper\n} from \"./langgraph/flow.js\";\nexport type {\n FerricStoreCommandClient,\n FerricStoreLockOptions\n} from \"./agent-persistence/durability.js\";\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n BaseCheckpointSaver,\n copyCheckpoint,\n type Checkpoint,\n type CheckpointMetadata,\n type CheckpointTuple\n} from \"@langchain/langgraph\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\n\nimport {\n arrayResponse,\n integerResponse,\n normalizeKeyPrefix,\n positiveInteger,\n readAtomicValue,\n textResponse,\n type FerricStoreCommandClient,\n type FerricStoreLockOptions,\n type FerricStoreMutationLease,\n withMutationLocks\n} from \"../agent-persistence/durability.js\";\n\nexport type LangGraphPendingWrite = [channel: string, value: unknown];\nexport type LangGraphChannelVersions = Record<string, string | number>;\ntype SerializerProtocol = BaseCheckpointSaver[\"serde\"];\n\nconst FORMAT_VERSION = 1;\nconst LEGACY_EPOCH_PREFIX = \"legacy:\";\nconst CURRENT_EPOCH_PREFIX = \"v2:\";\nconst CHECKPOINT_FIELD_PREFIX = \"checkpoint:\";\nconst WRITE_FIELD_PREFIX = \"write:\";\nconst WRITES_INDEX: Readonly<Record<string, number>> = {\n __error__: -1,\n __interrupt__: -3,\n __resume__: -4,\n __scheduled__: -2\n};\n\ninterface CheckpointRecord {\n readonly checkpoint: Checkpoint;\n readonly checkpointId: string;\n readonly checkpointNs: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly metadata: CheckpointMetadata;\n readonly parentCheckpointId?: string;\n readonly threadId: string;\n}\n\ninterface PendingWriteRecord {\n readonly channel: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly index: number;\n readonly taskId: string;\n readonly value: unknown;\n}\n\ninterface ThreadEpoch {\n readonly legacyFallback: boolean;\n readonly raw: Buffer | undefined;\n readonly value: string | undefined;\n}\n\nexport interface FerricStoreSaverOptions extends FerricStoreLockOptions {\n /** FerricStore key prefix. Defaults to `langgraph:checkpoint`. */\n keyPrefix?: string;\n /** Number of catalog/hash entries read per page. Defaults to 256. */\n scanCount?: number;\n /** Optional LangGraph serializer. The framework JSON-plus serializer is used by default. */\n serde?: SerializerProtocol;\n}\n\n/** Durable, epoch-fenced LangGraph.js checkpoint saver backed by FerricStore. */\nexport class FerricStoreSaver extends BaseCheckpointSaver {\n readonly client: FerricStoreCommandClient;\n readonly keyPrefix: string;\n readonly scanCount: number;\n private readonly lockOptions: FerricStoreLockOptions;\n\n constructor(client: FerricStoreCommandClient, options: FerricStoreSaverOptions = {}) {\n super(options.serde);\n this.client = client;\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix ?? \"langgraph:checkpoint\", \"langgraph:checkpoint\");\n this.scanCount = positiveInteger(options.scanCount, 256, \"scanCount\");\n this.lockOptions = {\n lockRetryMs: options.lockRetryMs,\n lockTtlMs: options.lockTtlMs,\n lockWaitMs: options.lockWaitMs\n };\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const { checkpointNs, threadId } = identity(config);\n const key = this.threadKey(threadId, checkpointNs);\n const epoch = await this.readThreadEpoch(threadId);\n let id = checkpointId(config);\n let record: CheckpointRecord | undefined;\n if (id != null) {\n record = await this.readRecordAtEpoch(key, id, epoch);\n } else {\n for (const candidate of await this.checkpointIdsAtEpoch(key, epoch)) {\n record = await this.readRecordAtEpoch(key, candidate, epoch);\n if (record != null) {\n id = candidate;\n break;\n }\n }\n }\n if (id == null || record == null) return undefined;\n return await this.tupleFromRecord(key, record);\n }\n\n async *list(config: RunnableConfig, options: {\n limit?: number;\n before?: RunnableConfig;\n filter?: Record<string, unknown>;\n } = {}): AsyncGenerator<CheckpointTuple> {\n const limit = options.limit;\n if (limit != null && (!Number.isSafeInteger(limit) || limit < 0)) {\n throw new TypeError(\"limit must be a non-negative safe integer\");\n }\n if (limit === 0) return;\n const beforeId = options.before == null ? undefined : checkpointId(options.before);\n const configurable = config.configurable;\n const threadId = optionalText(configurable?.thread_id, \"thread_id\");\n const expectedId = optionalText(configurable?.checkpoint_id ?? configurable?.thread_ts, \"checkpoint_id\");\n const namespaceSpecified = configurable != null && Object.hasOwn(configurable, \"checkpoint_ns\");\n const checkpointNs = namespaceSpecified ? requiredText(configurable?.checkpoint_ns, \"checkpoint_ns\", true) : undefined;\n\n const matches: { key: string; record: CheckpointRecord }[] = [];\n if (threadId == null) {\n await this.collectGlobal(matches, beforeId, expectedId, checkpointNs, options.filter, limit);\n } else {\n const keys = checkpointNs == null\n ? await this.threadKeys(threadId)\n : [this.threadKey(threadId, checkpointNs)];\n for (const key of keys) {\n const epoch = await this.readThreadEpoch(threadId);\n const ids = expectedId == null\n ? await this.checkpointIdsAtEpoch(key, epoch)\n : [expectedId];\n for (const id of ids) {\n if (beforeId != null && id >= beforeId) continue;\n const record = await this.readRecordAtEpoch(key, id, epoch);\n if (record == null || !metadataMatches(record.metadata, options.filter)) continue;\n matches.push({ key, record });\n }\n }\n matches.sort((left, right) => right.record.checkpointId.localeCompare(left.record.checkpointId));\n if (limit != null) matches.splice(limit);\n }\n\n for (const match of matches) yield await this.tupleFromRecord(match.key, match.record);\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: LangGraphChannelVersions\n ): Promise<RunnableConfig> {\n void _newVersions;\n const { checkpointNs, threadId } = identity(config);\n if (typeof checkpoint.id !== \"string\" || checkpoint.id.length === 0) {\n throw new TypeError(\"checkpoint.id must be a non-empty string\");\n }\n const parentCheckpointId = checkpointId(config);\n const record: CheckpointRecord = {\n checkpoint: copyCheckpoint(checkpoint),\n checkpointId: checkpoint.id,\n checkpointNs,\n formatVersion: FORMAT_VERSION,\n metadata,\n ...(parentCheckpointId == null ? {} : { parentCheckpointId }),\n threadId\n };\n const key = this.threadKey(threadId, checkpointNs);\n await withMutationLocks(this.client, [this.threadLockKey(threadId)], async (lease) => {\n const epoch = await this.ensureThreadEpoch(threadId, lease);\n const locator = checkpointLocator(checkpoint.id, key, threadId);\n // Discovery indexes are append-only and published before the CAS record.\n // Readers validate the record in the current thread epoch, so stale\n // writers and interrupted publications remain invisible.\n await lease.publish(\"SADD\", this.threadCatalogKey(threadId), key);\n await lease.publish(\"ZADD\", this.threadLocatorCatalogKey(threadId), 0, locator);\n await lease.publish(\"ZADD\", this.catalogKey(), 0, locator);\n await lease.publish(\"ZADD\", this.checkpointIndexKey(key), 0, checkpoint.id);\n await lease.publish(\"ZADD\", this.atomicCheckpointIndexKey(key, requireEpoch(epoch)), 0, checkpoint.id);\n const dataKey = this.checkpointRecordKey(key, requireEpoch(epoch), checkpoint.id);\n const value = await this.serialize(record);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const expected = await readAtomicValue(this.client, dataKey, \"LangGraph atomic checkpoint record\");\n if (await lease.compareAndSet(dataKey, expected, value)) {\n await this.assertCurrentEpoch(threadId, epoch);\n return;\n }\n }\n throw new Error(\"concurrent FerricStore LangGraph checkpoint mutation did not converge\");\n }, this.lockOptions);\n return checkpointConfig(threadId, checkpointNs, checkpoint.id);\n }\n\n async putWrites(config: RunnableConfig, writes: LangGraphPendingWrite[], taskId: string): Promise<void> {\n const { checkpointNs, threadId } = identity(config);\n const id = checkpointId(config);\n if (id == null) throw new TypeError(\"putWrites requires configurable.checkpoint_id\");\n if (typeof taskId !== \"string\" || taskId.length === 0) throw new TypeError(\"taskId must be non-empty text\");\n const snapshots = await Promise.all(writes.map(async ([channel, value], fallbackIndex) => {\n if (typeof channel !== \"string\") throw new TypeError(\"pending-write channel must be text\");\n const index = WRITES_INDEX[channel] ?? fallbackIndex;\n const record: PendingWriteRecord = {\n channel,\n formatVersion: FORMAT_VERSION,\n index,\n taskId,\n value\n };\n return { index, value: await this.serialize(record) };\n }));\n const key = this.threadKey(threadId, checkpointNs);\n await withMutationLocks(this.client, [this.threadLockKey(threadId)], async (lease) => {\n const epoch = await this.ensureThreadEpoch(threadId, lease);\n const epochValue = requireEpoch(epoch);\n await lease.publish(\"SADD\", this.threadCatalogKey(threadId), key);\n for (const snapshot of snapshots) {\n const dataKey = this.pendingWriteKey(key, epochValue, id, taskId, snapshot.index);\n const indexKey = this.atomicPendingWriteIndexKey(key, epochValue, id);\n await lease.publish(\"ZADD\", indexKey, 0, dataKey);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const expected = await readAtomicValue(this.client, dataKey, \"LangGraph atomic pending write\");\n if (snapshot.index >= 0 && expected != null) break;\n if (snapshot.index >= 0 && epoch.legacyFallback) {\n const legacy = await this.client.command(\"HGET\", key, writeField(id, taskId, snapshot.index));\n if (legacy != null) break;\n }\n if (await lease.compareAndSet(dataKey, expected, snapshot.value)) break;\n if (attempt === 7) {\n throw new Error(\"concurrent FerricStore LangGraph pending-write mutation did not converge\");\n }\n }\n }\n await this.assertCurrentEpoch(threadId, epoch);\n }, this.lockOptions);\n }\n\n async deleteThread(threadId: string): Promise<void> {\n const normalized = requiredText(threadId, \"threadId\");\n await withMutationLocks(this.client, [this.threadLockKey(normalized)], async (lease) => {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const epoch = await this.ensureThreadEpoch(normalized, lease);\n const next = Buffer.from(`${CURRENT_EPOCH_PREFIX}${randomUUID()}`, \"utf8\");\n if (await lease.compareAndSet(this.threadEpochKey(normalized), epoch.raw, next)) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph thread deletion did not converge\");\n }, this.lockOptions);\n }\n\n private catalogKey(): string {\n return `${this.keyPrefix}:checkpoints`;\n }\n\n private threadCatalogKey(threadId: string): string {\n const digest = sha256(threadId);\n return `${this.keyPrefix}:{lgt:${digest}}:namespaces`;\n }\n\n private threadLocatorCatalogKey(threadId: string): string {\n return `${this.threadCatalogKey(threadId)}:checkpoint-locators`;\n }\n\n private threadLockKey(threadId: string): string {\n return `${this.keyPrefix}:{lgt:${sha256(threadId)}}:mutation-lock`;\n }\n\n private threadKey(threadId: string, checkpointNs: string): string {\n return `${this.keyPrefix}:{lg:${sha256(lengthPrefixed([threadId, checkpointNs]))}}:thread`;\n }\n\n private checkpointIndexKey(threadKey: string): string {\n return `${threadKey}:checkpoint-index`;\n }\n\n private threadEpochKey(threadId: string): string {\n return `${this.threadCatalogKey(threadId)}:atomic-epoch`;\n }\n\n private atomicCheckpointIndexKey(threadKey: string, epoch: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:checkpoint-index`;\n }\n\n private atomicPendingWriteIndexKey(threadKey: string, epoch: string, checkpointId: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:writes:${encodeComponent(checkpointId)}`;\n }\n\n private checkpointRecordKey(threadKey: string, epoch: string, checkpointId: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:checkpoint:${encodeComponent(checkpointId)}`;\n }\n\n private pendingWriteKey(\n threadKey: string,\n epoch: string,\n checkpointId: string,\n taskId: string,\n index: number\n ): string {\n return `${threadKey}:atomic:${sha256(epoch)}:write:${encodeComponent(checkpointId)}:${encodeComponent(taskId)}:${index}`;\n }\n\n private async readThreadEpoch(threadId: string): Promise<ThreadEpoch> {\n const raw = await readAtomicValue(this.client, this.threadEpochKey(threadId), \"LangGraph thread epoch\");\n if (raw == null) return { legacyFallback: true, raw, value: undefined };\n const value = raw.toString(\"utf8\");\n if (!value.startsWith(LEGACY_EPOCH_PREFIX) && !value.startsWith(CURRENT_EPOCH_PREFIX)) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph thread epoch\");\n }\n return { legacyFallback: value.startsWith(LEGACY_EPOCH_PREFIX), raw, value };\n }\n\n private async ensureThreadEpoch(\n threadId: string,\n lease: FerricStoreMutationLease\n ): Promise<ThreadEpoch> {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const epoch = await this.readThreadEpoch(threadId);\n if (epoch.value != null) return epoch;\n const raw = Buffer.from(`${LEGACY_EPOCH_PREFIX}${randomUUID()}`, \"utf8\");\n if (await lease.compareAndSet(this.threadEpochKey(threadId), undefined, raw)) {\n return { legacyFallback: true, raw, value: raw.toString(\"utf8\") };\n }\n }\n throw new Error(\"concurrent FerricStore LangGraph epoch initialization did not converge\");\n }\n\n private async assertCurrentEpoch(threadId: string, expected: ThreadEpoch): Promise<void> {\n const current = await this.readThreadEpoch(threadId);\n if (expected.raw == null || current.raw?.equals(expected.raw) !== true) {\n throw new Error(\"FerricStore LangGraph thread epoch changed while committing data\");\n }\n }\n\n private async serialize(value: unknown): Promise<Buffer> {\n const [type, data] = await this.serde.dumpsTyped(value);\n const typeBytes = Buffer.from(type, \"utf8\");\n if (typeBytes.length > 65_535) throw new TypeError(\"serialized LangGraph type name is too long\");\n const header = Buffer.allocUnsafe(2);\n header.writeUInt16BE(typeBytes.length);\n return Buffer.concat([header, typeBytes, Buffer.from(data)]);\n }\n\n private async deserialize<T>(value: unknown, name: string): Promise<T> {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(`FerricStore returned a non-binary ${name}`);\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n if (bytes.length < 2) throw new Error(`invalid FerricStore ${name}`);\n const typeLength = bytes.readUInt16BE(0);\n if (bytes.length < typeLength + 2) throw new Error(`truncated FerricStore ${name}`);\n const type = bytes.subarray(2, typeLength + 2).toString(\"utf8\");\n return await this.serde.loadsTyped(type, bytes.subarray(typeLength + 2)) as T;\n }\n\n private async readRecordAtEpoch(\n key: string,\n id: string,\n epoch: ThreadEpoch\n ): Promise<CheckpointRecord | undefined> {\n let value: unknown;\n if (epoch.value != null) {\n value = await this.client.command(\"GET\", this.checkpointRecordKey(key, epoch.value, id));\n if (value == null && epoch.legacyFallback) {\n value = await this.client.command(\"HGET\", key, checkpointField(id));\n }\n } else {\n value = await this.client.command(\"HGET\", key, checkpointField(id));\n }\n if (value == null) return undefined;\n const record = await this.deserialize<CheckpointRecord>(value, \"LangGraph checkpoint record\");\n if (record.formatVersion !== FORMAT_VERSION || record.checkpointId !== id) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph checkpoint record\");\n }\n return record;\n }\n\n private async pendingWritesAtEpoch(\n key: string,\n id: string,\n epoch: ThreadEpoch\n ): Promise<[string, string, unknown][]> {\n const records = new Map<string, PendingWriteRecord>();\n if (epoch.value != null) {\n const keys = arrayResponse(\n await this.client.command(\"ZRANGE\", this.atomicPendingWriteIndexKey(key, epoch.value, id), 0, -1),\n \"LangGraph atomic pending-write index response\"\n );\n for (const rawKey of keys) {\n const dataKey = textResponse(rawKey, \"LangGraph pending-write key\");\n const value = await this.client.command(\"GET\", dataKey);\n if (value == null) continue;\n const record = await this.deserialize<PendingWriteRecord>(value, \"LangGraph pending write\");\n records.set(pendingWriteIdentity(record), record);\n }\n }\n if (epoch.legacyFallback) {\n const fields = await this.scanHash(key, `${WRITE_FIELD_PREFIX}${encodeComponent(id)}:*`);\n for (const [, value] of fields) {\n const record = await this.deserialize<PendingWriteRecord>(value, \"LangGraph pending write\");\n const identity = pendingWriteIdentity(record);\n if (!records.has(identity)) records.set(identity, record);\n }\n }\n const ordered = [...records.values()];\n for (const record of ordered) {\n if (record.formatVersion !== FORMAT_VERSION) {\n throw new Error(\"unsupported FerricStore LangGraph pending-write format\");\n }\n }\n ordered.sort((left, right) => left.taskId.localeCompare(right.taskId) || left.index - right.index);\n return ordered.map((record) => [record.taskId, record.channel, record.value]);\n }\n\n private async tupleFromRecord(key: string, record: CheckpointRecord): Promise<CheckpointTuple> {\n const epoch = await this.readThreadEpoch(record.threadId);\n return {\n checkpoint: record.checkpoint,\n config: checkpointConfig(record.threadId, record.checkpointNs, record.checkpointId),\n metadata: record.metadata,\n pendingWrites: await this.pendingWritesAtEpoch(key, record.checkpointId, epoch),\n ...(record.parentCheckpointId == null\n ? {}\n : { parentConfig: checkpointConfig(record.threadId, record.checkpointNs, record.parentCheckpointId) })\n };\n }\n\n private async scanHash(key: string, pattern: string): Promise<[unknown, unknown][]> {\n let cursor = 0;\n const result: [unknown, unknown][] = [];\n do {\n const response = arrayResponse(\n await this.client.command(\"HSCAN\", key, cursor, \"MATCH\", pattern, \"COUNT\", this.scanCount),\n \"HSCAN response\"\n );\n if (response.length !== 2) throw new Error(\"FerricStore HSCAN response must contain cursor and items\");\n cursor = integerResponse(response[0], \"HSCAN cursor\");\n const values = response[1];\n if (values instanceof Map) {\n result.push(...values.entries());\n } else {\n const flat = arrayResponse(values, \"HSCAN items\");\n if (flat.length % 2 !== 0) throw new Error(\"FerricStore HSCAN returned an odd item count\");\n for (let index = 0; index < flat.length; index += 2) result.push([flat[index], flat[index + 1]]);\n }\n } while (cursor !== 0);\n return result;\n }\n\n private async threadKeys(threadId: string): Promise<string[]> {\n const values = arrayResponse(\n await this.client.command(\"SMEMBERS\", this.threadCatalogKey(threadId)),\n \"thread checkpoint catalog response\"\n );\n return values.map((value) => textResponse(value, \"thread checkpoint key\")).sort();\n }\n\n private async checkpointIdsAtEpoch(key: string, epoch: ThreadEpoch): Promise<string[]> {\n const ids = new Set<string>();\n if (epoch.value != null) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.atomicCheckpointIndexKey(key, epoch.value), 0, -1),\n \"atomic checkpoint index response\"\n );\n for (const value of values) ids.add(textResponse(value, \"checkpoint ID\"));\n }\n if (epoch.legacyFallback) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.checkpointIndexKey(key), 0, -1),\n \"checkpoint index response\"\n );\n for (const value of values) ids.add(textResponse(value, \"checkpoint ID\"));\n }\n return [...ids].sort((left, right) => right.localeCompare(left));\n }\n\n private async collectGlobal(\n result: { key: string; record: CheckpointRecord }[],\n beforeId: string | undefined,\n expectedId: string | undefined,\n checkpointNs: string | undefined,\n filter: Record<string, unknown> | undefined,\n limit: number | undefined\n ): Promise<void> {\n let offset = 0;\n const seen = new Set<string>();\n while (limit == null || result.length < limit) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.catalogKey(), offset, offset + this.scanCount - 1),\n \"global checkpoint catalog response\"\n );\n if (values.length === 0) break;\n for (const value of values) {\n const locator = decodeCheckpointLocator(value);\n const { checkpointId: id, threadKey: key } = locator;\n if (expectedId != null && id !== expectedId) continue;\n if (beforeId != null && id >= beforeId) continue;\n let record: CheckpointRecord | undefined;\n if (locator.threadId != null) {\n record = await this.readRecordAtEpoch(key, id, await this.readThreadEpoch(locator.threadId));\n } else {\n const legacy = await this.client.command(\"HGET\", key, checkpointField(id));\n if (legacy != null) {\n const candidate = await this.deserialize<CheckpointRecord>(legacy, \"LangGraph checkpoint record\");\n record = await this.readRecordAtEpoch(key, id, await this.readThreadEpoch(candidate.threadId));\n }\n }\n if (\n record == null ||\n checkpointNs != null && record.checkpointNs !== checkpointNs ||\n !metadataMatches(record.metadata, filter)\n ) continue;\n const identity = lengthPrefixed([record.threadId, record.checkpointNs, record.checkpointId]).toString(\"base64url\");\n if (seen.has(identity)) continue;\n seen.add(identity);\n result.push({ key, record });\n if (limit != null && result.length >= limit) break;\n }\n offset += values.length;\n if (values.length < this.scanCount) break;\n }\n }\n}\n\nfunction identity(config: RunnableConfig): { checkpointNs: string; threadId: string } {\n if (config.configurable == null || typeof config.configurable !== \"object\") {\n throw new TypeError(\"LangGraph config must contain configurable.thread_id\");\n }\n return {\n checkpointNs: requiredText(config.configurable.checkpoint_ns ?? \"\", \"checkpoint_ns\", true),\n threadId: requiredText(config.configurable.thread_id, \"thread_id\")\n };\n}\n\nfunction checkpointId(config: RunnableConfig): string | undefined {\n return optionalText(config.configurable?.checkpoint_id ?? config.configurable?.thread_ts, \"checkpoint_id\");\n}\n\nfunction checkpointConfig(threadId: string, checkpointNs: string, id: string): RunnableConfig {\n return { configurable: { checkpoint_id: id, checkpoint_ns: checkpointNs, thread_id: threadId } };\n}\n\nfunction requiredText(value: unknown, name: string, allowEmpty = false): string {\n if (typeof value !== \"string\" || (!allowEmpty && value.length === 0)) {\n throw new TypeError(`${name} must be ${allowEmpty ? \"text\" : \"non-empty text\"}`);\n }\n return value;\n}\n\nfunction optionalText(value: unknown, name: string): string | undefined {\n if (value == null || value === \"\") return undefined;\n return requiredText(value, name);\n}\n\nfunction metadataMatches(metadata: CheckpointMetadata, filter: Record<string, unknown> | undefined): boolean {\n return filter == null || Object.entries(filter).every(([key, value]) => {\n const actual = Object.getOwnPropertyDescriptor(metadata, key)?.value as unknown;\n return Object.is(actual, value);\n });\n}\n\nfunction checkpointField(id: string): string {\n return `${CHECKPOINT_FIELD_PREFIX}${encodeComponent(id)}`;\n}\n\nfunction writeField(id: string, taskId: string, index: number): string {\n return `${WRITE_FIELD_PREFIX}${encodeComponent(id)}:${encodeComponent(taskId)}:${index}`;\n}\n\nfunction encodeComponent(value: string): string {\n return Buffer.from(value, \"utf8\").toString(\"base64url\");\n}\n\nfunction checkpointLocator(id: string, threadKey: string, threadId?: string): Buffer {\n if (threadId == null) return Buffer.concat([orderedText(id), Buffer.from(threadKey, \"utf8\")]);\n const threadIdBytes = Buffer.from(threadId, \"utf8\");\n const length = Buffer.allocUnsafe(4);\n length.writeUInt32BE(threadIdBytes.length);\n return Buffer.concat([\n orderedText(id),\n Buffer.from([0, 1]),\n length,\n threadIdBytes,\n Buffer.from(threadKey, \"utf8\")\n ]);\n}\n\nfunction decodeCheckpointLocator(value: unknown): {\n checkpointId: string;\n threadId?: string;\n threadKey: string;\n} {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary checkpoint locator\");\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n const decoded = decodeOrderedText(bytes, 0);\n let offset = decoded.offset;\n let threadId: string | undefined;\n if (bytes[offset] === 0 && bytes[offset + 1] === 1) {\n offset += 2;\n if (bytes.length < offset + 4) throw new Error(\"truncated FerricStore checkpoint locator\");\n const length = bytes.readUInt32BE(offset);\n offset += 4;\n if (bytes.length < offset + length) throw new Error(\"truncated FerricStore checkpoint locator thread ID\");\n threadId = bytes.subarray(offset, offset + length).toString(\"utf8\");\n offset += length;\n if (threadId.length === 0) throw new Error(\"FerricStore checkpoint locator has an empty thread ID\");\n }\n const threadKey = bytes.subarray(offset).toString(\"utf8\");\n if (threadKey.length === 0) throw new Error(\"FerricStore checkpoint locator has an empty thread key\");\n return { checkpointId: decoded.value, ...(threadId == null ? {} : { threadId }), threadKey };\n}\n\nfunction orderedText(value: string): Buffer {\n const output: number[] = [];\n for (const byte of Buffer.from(value, \"utf8\")) {\n if (byte === 0) output.push(0, 255);\n else output.push(byte);\n }\n output.push(0, 0);\n return Buffer.from(output);\n}\n\nfunction decodeOrderedText(bytes: Buffer, start: number): { offset: number; value: string } {\n const output: number[] = [];\n let offset = start;\n while (offset < bytes.length) {\n const byte = bytes[offset];\n if (byte == null) throw new Error(\"truncated FerricStore checkpoint locator\");\n offset += 1;\n if (byte !== 0) {\n output.push(byte);\n continue;\n }\n const escaped = bytes[offset];\n offset += 1;\n if (escaped === 0) return { offset, value: Buffer.from(output).toString(\"utf8\") };\n if (escaped === 255) output.push(0);\n else throw new Error(\"invalid FerricStore checkpoint locator escape\");\n }\n throw new Error(\"unterminated FerricStore checkpoint locator\");\n}\n\nfunction sha256(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction lengthPrefixed(values: readonly string[]): Buffer {\n const parts: Buffer[] = [];\n for (const value of values) {\n const payload = Buffer.from(value, \"utf8\");\n const length = Buffer.allocUnsafe(8);\n length.writeBigUInt64BE(BigInt(payload.length));\n parts.push(length, payload);\n }\n return Buffer.concat(parts);\n}\n\nfunction requireEpoch(epoch: ThreadEpoch): string {\n if (epoch.value == null) throw new Error(\"FerricStore LangGraph thread epoch is not initialized\");\n return epoch.value;\n}\n\nfunction pendingWriteIdentity(record: PendingWriteRecord): string {\n return lengthPrefixed([record.taskId, String(record.index)]).toString(\"base64url\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { LockHeldError } from \"../errors.js\";\nimport type { Command, CommandArgument } from \"../internal.js\";\n\nexport interface FerricStoreCommandClient {\n command(...args: CommandArgument[]): Promise<unknown>;\n pipeline?(commands: readonly Command[]): Promise<unknown[]>;\n}\n\nexport interface FerricStoreLockOptions {\n /** Lease duration for adapter mutation locks. Defaults to five minutes. */\n lockTtlMs?: number;\n /** Maximum time to wait for a contended mutation lock. Defaults to 30 seconds. */\n lockWaitMs?: number;\n /** Delay between lock acquisition attempts. Defaults to 10 milliseconds. */\n lockRetryMs?: number;\n}\n\nexport interface FerricStoreMutationLease {\n /** Aborted as soon as lock ownership is known to have been lost. */\n readonly signal: AbortSignal;\n /** Throw when this mutation no longer owns every requested lock. */\n assertOwned(): void;\n /** Publish an idempotent, add-only discovery entry before its CAS record. */\n publish(...args: CommandArgument[]): Promise<unknown>;\n /** Atomically replace a value only when its last-read bytes are still current. */\n compareAndSet(key: string, expected: Buffer | undefined, value: Buffer): Promise<boolean>;\n}\n\ninterface RequiredLockOptions {\n readonly lockRetryMs: number;\n readonly lockTtlMs: number;\n readonly lockWaitMs: number;\n}\n\nconst DEFAULT_LOCK_OPTIONS: RequiredLockOptions = {\n lockRetryMs: 10,\n lockTtlMs: 300_000,\n lockWaitMs: 30_000\n};\n\nexport function normalizeKeyPrefix(value: string, defaultValue: string): string {\n const prefix = value.length === 0 ? defaultValue : value;\n if (prefix.includes(\"\\0\")) throw new TypeError(\"keyPrefix must not contain NUL bytes\");\n const normalized = prefix.replace(/:+$/u, \"\");\n if (normalized.length === 0) throw new TypeError(\"keyPrefix must contain a character other than ':'\");\n return normalized;\n}\n\nexport function positiveInteger(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized <= 0) {\n throw new TypeError(`${name} must be a positive safe integer`);\n }\n return normalized;\n}\n\nexport function nonNegativeInteger(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized < 0) {\n throw new TypeError(`${name} must be a non-negative safe integer`);\n }\n return normalized;\n}\n\nexport function textResponse(value: unknown, name: string): string {\n if (typeof value === \"string\") return value;\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value).toString(\"utf8\");\n throw new TypeError(`FerricStore returned an invalid ${name}`);\n}\n\nexport function arrayResponse(value: unknown, name: string): unknown[] {\n if (!Array.isArray(value)) throw new TypeError(`FerricStore returned an invalid ${name}`);\n return value;\n}\n\nexport function integerResponse(value: unknown, name: string): number {\n const parsed = typeof value === \"number\" ? value : Number(textResponse(value, name));\n if (!Number.isSafeInteger(parsed)) throw new TypeError(`FerricStore returned an invalid ${name}`);\n return parsed;\n}\n\nexport async function executeCommands(\n client: FerricStoreCommandClient,\n commands: readonly Command[]\n): Promise<unknown[]> {\n if (commands.length === 0) return [];\n if (client.pipeline != null) return await client.pipeline(commands);\n return await Promise.all(commands.map(async (command) => await client.command(...command)));\n}\n\nexport async function readAtomicValue(\n client: FerricStoreCommandClient,\n key: string,\n name: string\n): Promise<Buffer | undefined> {\n const value = await client.command(\"GET\", key);\n if (value == null) return undefined;\n if (typeof value === \"string\") return Buffer.from(value, \"utf8\");\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value);\n throw new TypeError(`FerricStore returned a non-binary ${name}`);\n}\n\nexport async function compareAndSetAtomicValue(\n client: FerricStoreCommandClient,\n key: string,\n expected: Buffer | undefined,\n value: Buffer\n): Promise<boolean> {\n if (expected == null) {\n const response = await client.command(\"SET\", key, value, \"NX\");\n if (response == null || response === false) return false;\n if (response === true) return true;\n return textResponse(response, \"SET NX response\").toUpperCase() === \"OK\";\n }\n const response = await client.command(\"CAS\", key, expected, value);\n if (response == null || response === false) return false;\n if (response === true) return true;\n return integerResponse(response, \"CAS response\") === 1;\n}\n\nexport async function withMutationLocks<T>(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n operation: (lease: FerricStoreMutationLease) => Promise<T>,\n options: FerricStoreLockOptions = {}\n): Promise<T> {\n const orderedKeys = [...new Set(keys)].sort();\n if (orderedKeys.length === 0) {\n const signal = new AbortController().signal;\n return await operation({\n signal,\n assertOwned: () => undefined,\n publish: async (...args) => await additiveCommand(client, args),\n compareAndSet: async (key, expected, value) =>\n await compareAndSetAtomicValue(client, key, expected, value)\n });\n }\n\n const normalized: RequiredLockOptions = {\n lockRetryMs: positiveInteger(options.lockRetryMs, DEFAULT_LOCK_OPTIONS.lockRetryMs, \"lockRetryMs\"),\n lockTtlMs: positiveInteger(options.lockTtlMs, DEFAULT_LOCK_OPTIONS.lockTtlMs, \"lockTtlMs\"),\n lockWaitMs: nonNegativeInteger(options.lockWaitMs, DEFAULT_LOCK_OPTIONS.lockWaitMs, \"lockWaitMs\")\n };\n if (normalized.lockRetryMs >= normalized.lockTtlMs) {\n throw new TypeError(\"lockRetryMs must be less than lockTtlMs\");\n }\n const owner = randomUUID();\n const acquired: string[] = [];\n const deadline = performance.now() + normalized.lockWaitMs;\n let primaryError: unknown;\n let heartbeatError: unknown;\n let releaseError: unknown;\n let result: T | undefined;\n let operationCompleted = false;\n let conditionalCommitCompleted = false;\n const heartbeatAbort = new AbortController();\n const ownershipAbort = new AbortController();\n const lastExtended = new Map<string, number>();\n const loseOwnership = (error: unknown): Error => {\n const normalizedError = errorObject(error);\n heartbeatError ??= normalizedError;\n if (!ownershipAbort.signal.aborted) ownershipAbort.abort(normalizedError);\n return normalizedError;\n };\n const assertOwned = (): void => {\n if (heartbeatError != null) throw errorObject(heartbeatError);\n if (ownershipAbort.signal.aborted) throw errorObject(ownershipAbort.signal.reason);\n };\n const renewOwned = async (): Promise<void> => {\n assertOwned();\n for (const key of acquired) {\n try {\n const response = await client.command(\"EXTEND\", key, owner, normalized.lockTtlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n throw new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`);\n }\n lastExtended.set(key, performance.now());\n } catch (error) {\n throw loseOwnership(new Error(\n `could not validate FerricStore lock ${JSON.stringify(key)} before mutating data`,\n { cause: error }\n ));\n }\n }\n assertOwned();\n };\n const lease: FerricStoreMutationLease = {\n signal: ownershipAbort.signal,\n assertOwned,\n publish: async (...args) => {\n await renewOwned();\n const response = await additiveCommand(client, args);\n assertOwned();\n return response;\n },\n compareAndSet: async (key, expected, value) => {\n await renewOwned();\n const committed = await compareAndSetAtomicValue(client, key, expected, value);\n if (committed) conditionalCommitCompleted = true;\n else assertOwned();\n return committed;\n }\n };\n\n try {\n for (const key of orderedKeys) {\n while (!(await tryAcquireLock(client, key, owner, normalized.lockTtlMs))) {\n if (performance.now() >= deadline) {\n throw new Error(`timed out acquiring FerricStore lock ${JSON.stringify(key)}`);\n }\n await extendAcquiredLocks(client, acquired, owner, normalized.lockTtlMs);\n await delay(normalized.lockRetryMs);\n }\n acquired.push(key);\n }\n await extendAcquiredLocks(client, acquired, owner, normalized.lockTtlMs);\n for (const key of acquired) lastExtended.set(key, performance.now());\n\n const heartbeat = renewLocks(\n client,\n acquired,\n owner,\n normalized.lockTtlMs,\n lastExtended,\n heartbeatAbort.signal,\n (error) => {\n loseOwnership(error);\n }\n );\n try {\n result = await operation(lease);\n operationCompleted = true;\n } catch (error) {\n primaryError = error;\n } finally {\n heartbeatAbort.abort();\n await heartbeat;\n }\n } catch (error) {\n primaryError ??= error;\n } finally {\n heartbeatAbort.abort();\n for (const key of acquired.reverse()) {\n try {\n await client.command(\"UNLOCK\", key, owner);\n } catch (error) {\n releaseError ??= error;\n }\n }\n }\n if (primaryError != null) throw errorObject(primaryError);\n if (heartbeatError != null && !conditionalCommitCompleted) throw errorObject(heartbeatError);\n if (releaseError != null && !(heartbeatError != null && conditionalCommitCompleted)) {\n throw errorObject(releaseError);\n }\n if (!operationCompleted) throw new Error(\"FerricStore mutation did not complete\");\n return result as T;\n}\n\nasync function additiveCommand(\n client: FerricStoreCommandClient,\n args: readonly CommandArgument[]\n): Promise<unknown> {\n const rawName = args[0];\n const name = typeof rawName === \"string\"\n ? rawName.toUpperCase()\n : Buffer.isBuffer(rawName) || rawName instanceof Uint8Array\n ? Buffer.from(rawName).toString(\"utf8\").toUpperCase()\n : \"\";\n if (name !== \"SADD\" && name !== \"ZADD\") {\n throw new TypeError(\"FerricStore mutation leases only publish add-only SADD or ZADD indexes\");\n }\n if (name === \"ZADD\" && (\n args.length < 4 ||\n args.length % 2 !== 0 ||\n args.slice(2).some((value, index) => index % 2 === 0 && Number(value) !== 0)\n )) {\n throw new TypeError(\"FerricStore mutation leases only publish zero-score ZADD indexes\");\n }\n return await client.command(...args);\n}\n\nasync function extendAcquiredLocks(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n owner: string,\n ttlMs: number\n): Promise<void> {\n for (const key of keys) {\n const response = await client.command(\"EXTEND\", key, owner, ttlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n throw new Error(`lost FerricStore lock ${JSON.stringify(key)} before mutating data`);\n }\n }\n}\n\nasync function tryAcquireLock(\n client: FerricStoreCommandClient,\n key: string,\n owner: string,\n ttlMs: number\n): Promise<boolean> {\n try {\n const response = await client.command(\"LOCK\", key, owner, ttlMs);\n return response === true || response === \"OK\" || Buffer.isBuffer(response) && response.equals(Buffer.from(\"OK\"));\n } catch (error) {\n if (error instanceof LockHeldError) return false;\n throw error;\n }\n}\n\nasync function renewLocks(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n owner: string,\n ttlMs: number,\n lastExtended: Map<string, number>,\n signal: AbortSignal,\n onError: (error: unknown) => void\n): Promise<void> {\n const intervalMs = Math.max(Math.floor(ttlMs / 3), 1);\n const retryMs = Math.min(Math.max(Math.floor(intervalMs / 10), 1), 1_000);\n let waitMs = intervalMs;\n while (!signal.aborted) {\n try {\n await delay(waitMs, undefined, { signal });\n } catch (error) {\n if (signal.aborted) return;\n onError(error);\n return;\n }\n const now = performance.now();\n let retry = false;\n for (const key of keys) {\n try {\n const response = await client.command(\"EXTEND\", key, owner, ttlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n onError(new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`));\n return;\n }\n lastExtended.set(key, now);\n } catch (error) {\n if (now - (lastExtended.get(key) ?? 0) >= ttlMs) {\n onError(new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`, { cause: error }));\n return;\n }\n retry = true;\n }\n }\n waitMs = retry ? retryMs : intervalMs;\n }\n}\n\nfunction errorObject(value: unknown): Error {\n return value instanceof Error ? value : new Error(\"FerricStore mutation failed\", { cause: value });\n}\n","export class FerricStoreError extends Error {\n readonly code: string = \"ferricstore_error\";\n readonly raw: unknown;\n readonly retryable: boolean | undefined;\n readonly safeToRetry: boolean | undefined;\n readonly retryAfterMs: number | undefined;\n\n constructor(message: string, options: {\n raw?: unknown;\n cause?: unknown;\n retryable?: boolean;\n safeToRetry?: boolean;\n retryAfterMs?: number;\n } = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.raw = options.raw;\n this.retryable = options.retryable ?? structuredBooleanField(options.raw, \"retryable\");\n this.safeToRetry = options.safeToRetry ?? structuredBooleanField(options.raw, \"safe_to_retry\");\n this.retryAfterMs = options.retryAfterMs ?? structuredIntegerField(options.raw, \"retry_after_ms\");\n }\n}\n\nexport class HTTPTransportError extends FerricStoreError {\n override readonly code = \"http_transport\";\n readonly statusCode: number | undefined;\n\n constructor(message: string, options: ConstructorParameters<typeof FerricStoreError>[1] & {\n statusCode?: number;\n } = {}) {\n super(message, options);\n this.statusCode = options.statusCode;\n }\n}\n\nexport type RequestDisposition = \"unsent\" | \"possibly_sent\";\n/** @deprecated Use RequestDisposition; retained for source compatibility. */\nexport type ConnectionRequestDisposition = RequestDisposition;\n\n/** Connection closure annotated with whether the current request may have reached the server. */\nexport class ConnectionClosedError extends FerricStoreError {\n override readonly code = \"connection_closed\";\n readonly requestDisposition: RequestDisposition;\n\n constructor(\n requestDisposition: RequestDisposition,\n options: { raw?: unknown; cause?: unknown; message?: string } = {}\n ) {\n super(\n options.message ?? (requestDisposition === \"unsent\"\n ? \"FerricStore connection is closed\"\n : \"FerricStore connection closed\"),\n options\n );\n this.requestDisposition = requestDisposition;\n }\n}\n\n/** Request timeout annotated with whether the request may have reached the server. */\nexport class RequestTimeoutError extends FerricStoreError {\n override readonly code = \"request_timeout\";\n readonly requestDisposition: RequestDisposition;\n readonly timeoutMs: number;\n\n constructor(\n timeoutMs: number,\n requestDisposition: RequestDisposition,\n options: { raw?: unknown; cause?: unknown } = {}\n ) {\n super(`FerricStore request timed out after ${timeoutMs}ms`, options);\n this.requestDisposition = requestDisposition;\n this.timeoutMs = timeoutMs;\n }\n}\n\nexport class FlowNotFoundError extends FerricStoreError {\n override readonly code = \"flow_not_found\";\n}\n\nexport class FlowWrongStateError extends FerricStoreError {\n override readonly code = \"flow_wrong_state\";\n}\n\nexport class StaleLeaseError extends FerricStoreError {\n override readonly code = \"stale_lease\";\n}\n\n/** FLOW.POLICY.SET expected_generation did not match the stored generation. */\nexport class StalePolicyGenerationError extends FerricStoreError {\n override readonly code = \"stale_policy_generation\";\n}\n\nexport class FlowAlreadyExistsError extends FerricStoreError {\n override readonly code = \"flow_already_exists\";\n}\n\nexport class LockHeldError extends FerricStoreError {\n override readonly code = \"lock_held\";\n}\n\nexport class LockNotOwnedError extends FerricStoreError {\n override readonly code = \"lock_not_owned\";\n}\n\nexport class InvalidCommandError extends FerricStoreError {\n override readonly code = \"invalid_command\";\n}\n\nexport class OverloadedError extends FerricStoreError {\n override readonly code = \"overloaded\";\n readonly reason: string | undefined;\n\n constructor(\n message: string,\n options: {\n raw?: unknown;\n cause?: unknown;\n retryAfterMs?: number;\n reason?: string;\n retryable?: boolean;\n safeToRetry?: boolean;\n } = {}\n ) {\n const local = options.raw == null;\n super(message, {\n ...options,\n retryable: options.retryable ?? (local ? true : undefined),\n safeToRetry: options.safeToRetry ?? (local ? true : undefined)\n });\n this.reason = options.reason;\n }\n}\n\n/** The contacted endpoint cannot serve this route and topology should be refreshed. */\nexport class RerouteError extends FerricStoreError {\n override readonly code = \"reroute\";\n}\n\nconst OVERLOAD_CODES = new Set([\n \"backpressure\",\n \"busy\",\n \"flow_control_window_exhausted\",\n \"lane_queue_full\",\n \"overloaded\"\n]);\n\nexport function classifyServerError(\n message: string,\n raw?: unknown,\n cause?: unknown,\n status?: number | string\n): FerricStoreError {\n const lower = message.toLowerCase();\n const structuredCode = structuredStringField(raw, \"code\");\n const code = structuredCode?.toLowerCase();\n const retry = {\n retryable: structuredBooleanField(raw, \"retryable\"),\n safeToRetry: structuredBooleanField(raw, \"safe_to_retry\"),\n retryAfterMs: structuredIntegerField(raw, \"retry_after_ms\") ?? intField(lower, \"retry_after_ms\")\n };\n\n if (isRerouteStatus(status) || code === \"reroute\") {\n return new RerouteError(message, { cause, raw, ...definedRetryMetadata(retry) });\n }\n if (isBusyStatus(status) || isOverloadCode(structuredCode) || overloadMessage(lower)) {\n return new OverloadedError(message, {\n cause,\n raw,\n ...definedRetryMetadata(retry),\n reason: structuredStringField(raw, \"reason\") ?? structuredCode ?? stringField(lower, \"reason\"),\n retryAfterMs: retry.retryAfterMs\n });\n }\n if (code === \"flow_already_exists\" || (lower.includes(\"flow\") && lower.includes(\"already exists\"))) {\n return new FlowAlreadyExistsError(message, { cause, raw });\n }\n if (lower.includes(\"flow wrong state\") || code === \"flow_wrong_state\") {\n return new FlowWrongStateError(message, { cause, raw });\n }\n if (\n code === \"stale_lease\"\n || code === \"stale_flow_lease\"\n || lower.includes(\"stale flow lease\")\n || lower.includes(\"stale lease\")\n || lower.includes(\"stale token\")\n ) {\n return new StaleLeaseError(message, { cause, raw });\n }\n if (\n code === \"stale_generation\"\n || code === \"stale_policy_generation\"\n || code === \"stale_flow_policy_generation\"\n || lower.includes(\"stale flow policy generation\")\n || lower.includes(\"stale policy generation\")\n ) {\n return new StalePolicyGenerationError(message, { cause, raw });\n }\n if (\n code === \"flow_not_found\"\n || (lower.includes(\"flow\") && (lower.includes(\"not found\") || lower.includes(\"does not exist\")))\n ) {\n return new FlowNotFoundError(message, { cause, raw });\n }\n if (code === \"lock_held\" || lower.includes(\"lock is held\") || lower.includes(\"held by another owner\")) {\n return new LockHeldError(message, { cause, raw });\n }\n if (code === \"lock_not_owned\" || lower.includes(\"not the lock owner\") || lower.includes(\"caller is not the lock owner\")) {\n return new LockNotOwnedError(message, { cause, raw });\n }\n if (code === \"invalid_command\" || lower.includes(\"wrong number of arguments\") || lower.includes(\"syntax error\")) {\n return new InvalidCommandError(message, { cause, raw });\n }\n\n return new FerricStoreError(message, { cause, raw, ...definedRetryMetadata(retry) });\n}\n\nexport function mapException(error: unknown): unknown {\n if (error instanceof FerricStoreError) {\n return error;\n }\n\n if (!(error instanceof Error)) {\n return error;\n }\n\n const message = error.message;\n const serverLike =\n error.name === \"ResponseError\" ||\n message.startsWith(\"ERR \") ||\n message.startsWith(\"WRONGTYPE \") ||\n message.startsWith(\"DISTLOCK \");\n\n if (!serverLike) {\n return error;\n }\n\n return classifyServerError(message, error, error);\n}\n\nfunction intField(message: string, name: string): number | undefined {\n const match = new RegExp(`\\\\b${name}=([0-9]+)\\\\b`).exec(message);\n return match?.[1] == null ? undefined : nonNegativeSafeIntegerText(match[1]);\n}\n\nfunction isBusyStatus(status: number | string | undefined): boolean {\n return status === 4 || (typeof status === \"string\" && (status === \"4\" || status.toLowerCase() === \"busy\"));\n}\n\nfunction isRerouteStatus(status: number | string | undefined): boolean {\n return status === 5 || (typeof status === \"string\" && (status === \"5\" || status.toLowerCase() === \"reroute\"));\n}\n\nfunction isOverloadCode(code: string | undefined): boolean {\n return code != null && OVERLOAD_CODES.has(code.toLowerCase());\n}\n\nfunction overloadMessage(message: string): boolean {\n return /\\boverloaded\\b/u.test(message) || /(?:^|\\s)busy(?:\\s|:|$)/u.test(message);\n}\n\nfunction structuredIntegerField(raw: unknown, name: string): number | undefined {\n const value = structuredField(raw, name);\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n }\n if (typeof value === \"bigint\") {\n return value >= 0n && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n }\n const text = binaryText(value);\n return text == null ? undefined : nonNegativeSafeIntegerText(text);\n}\n\nfunction structuredBooleanField(raw: unknown, name: string): boolean | undefined {\n const value = structuredField(raw, name);\n if (typeof value === \"boolean\") return value;\n const text = binaryText(value)?.toLowerCase();\n if (text === \"true\" || text === \"1\") return true;\n if (text === \"false\" || text === \"0\") return false;\n return undefined;\n}\n\nfunction definedRetryMetadata(metadata: {\n readonly retryable?: boolean;\n readonly safeToRetry?: boolean;\n readonly retryAfterMs?: number;\n}): { retryable?: boolean; safeToRetry?: boolean; retryAfterMs?: number } {\n return {\n ...(metadata.retryable == null ? {} : { retryable: metadata.retryable }),\n ...(metadata.safeToRetry == null ? {} : { safeToRetry: metadata.safeToRetry }),\n ...(metadata.retryAfterMs == null ? {} : { retryAfterMs: metadata.retryAfterMs })\n };\n}\n\nfunction nonNegativeSafeIntegerText(value: string): number | undefined {\n if (!/^[0-9]+$/u.test(value)) return undefined;\n const parsed = Number.parseInt(value, 10);\n return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction structuredStringField(raw: unknown, name: string): string | undefined {\n return binaryText(structuredField(raw, name));\n}\n\nfunction structuredField(raw: unknown, name: string): unknown {\n if (raw instanceof Map) {\n if (raw.has(name)) return raw.get(name);\n for (const [key, value] of raw.entries()) {\n if (binaryText(key) === name) return value;\n }\n return undefined;\n }\n if (typeof raw === \"object\" && raw != null && Object.hasOwn(raw, name)) {\n return (raw as Record<string, unknown>)[name];\n }\n return undefined;\n}\n\nfunction binaryText(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value).toString(\"utf8\");\n return undefined;\n}\n\nfunction stringField(message: string, name: string): string | undefined {\n const match = new RegExp(`\\\\b${name}=([a-z0-9_:-]+)\\\\b`).exec(message);\n return match?.[1];\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n BaseStore,\n type GetOperation,\n type Item,\n type ListNamespacesOperation,\n type MatchCondition,\n type Operation,\n type OperationResults,\n type PutOperation,\n type SearchOperation\n} from \"@langchain/langgraph\";\n\nimport {\n arrayResponse,\n normalizeKeyPrefix,\n positiveInteger,\n readAtomicValue,\n type FerricStoreCommandClient,\n type FerricStoreLockOptions,\n type FerricStoreMutationLease,\n withMutationLocks\n} from \"../agent-persistence/durability.js\";\n\nconst FORMAT_VERSION = 1;\nconst ITEM_FIELD_PREFIX = \"item:\";\nconst DELETED_ITEM = Buffer.from(\"ferricstore:langgraph:item:deleted:v2\", \"utf8\");\ntype SearchItem = Item & { score?: number };\n\ninterface StoredItem {\n readonly createdAt: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly key: string;\n readonly namespace: string[];\n readonly updatedAt: string;\n readonly value: Record<string, unknown>;\n}\n\nexport interface FerricStoreStoreOptions extends FerricStoreLockOptions {\n /** FerricStore key prefix. Defaults to `langgraph:store`. */\n keyPrefix?: string;\n /** Number of catalog entries read per page. Defaults to 256. */\n scanCount?: number;\n}\n\n/**\n * LangGraph.js long-term memory store backed by FerricStore.\n *\n * It implements hierarchical namespaces, exact/comparison filters, ordered\n * pagination, batching, CAS-protected item commits, and append-only discovery\n * indexes. Vector search is deliberately rejected until a semantic index is\n * configured rather than silently returning an unranked result.\n */\nexport class FerricStoreStore extends BaseStore {\n readonly client: FerricStoreCommandClient;\n readonly keyPrefix: string;\n readonly scanCount: number;\n private readonly lockOptions: FerricStoreLockOptions;\n\n constructor(client: FerricStoreCommandClient, options: FerricStoreStoreOptions = {}) {\n super();\n this.client = client;\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix ?? \"langgraph:store\", \"langgraph:store\");\n this.scanCount = positiveInteger(options.scanCount, 256, \"scanCount\");\n this.lockOptions = {\n lockRetryMs: options.lockRetryMs,\n lockTtlMs: options.lockTtlMs,\n lockWaitMs: options.lockWaitMs\n };\n }\n\n async batch<Op extends Operation[]>(operations: Op): Promise<OperationResults<Op>> {\n if (!Array.isArray(operations)) throw new TypeError(\"operations must be an array\");\n const lockKeys = operations\n .filter(isPutOperation)\n .map((operation) => {\n validatePut(operation);\n return this.itemLockKey(operation.namespace, operation.key);\n });\n\n return await withMutationLocks(this.client, lockKeys, async (lease) => {\n const results: unknown[] = [];\n const puts = new Map<string, PutOperation>();\n for (const operation of operations) {\n if (isPutOperation(operation)) {\n puts.set(JSON.stringify([operation.namespace, operation.key]), operation);\n results.push(undefined);\n } else if (isSearchOperation(operation)) {\n results.push(await this.searchOperation(operation));\n } else if (isGetOperation(operation)) {\n results.push(await this.getOperation(operation));\n } else if (isListNamespacesOperation(operation)) {\n results.push(await this.listNamespacesOperation(operation));\n } else {\n throw new TypeError(\"unsupported LangGraph store operation\");\n }\n }\n for (const operation of puts.values()) await this.putOperation(operation, lease);\n return results as OperationResults<Op>;\n }, this.lockOptions);\n }\n\n private catalogKey(): string {\n return `${this.keyPrefix}:namespaces`;\n }\n\n private namespaceKey(namespace: readonly string[]): string {\n return `${this.keyPrefix}:{lgs:${sha256(namespaceIdentity(namespace))}}:namespace`;\n }\n\n private itemLockKey(namespace: readonly string[], key: string): string {\n return `${this.keyPrefix}:{lgsi:${itemIdentityDigest(namespace, key)}}:mutation-lock`;\n }\n\n private itemDataKey(namespace: readonly string[], key: string): string {\n return `${this.keyPrefix}:{lgsi:${itemIdentityDigest(namespace, key)}}:atomic-item`;\n }\n\n private async getOperation(operation: GetOperation): Promise<Item | null> {\n validateNamespace(operation.namespace);\n if (typeof operation.key !== \"string\") throw new TypeError(\"store key must be text\");\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n return snapshot.record == null ? null : itemFromRecord(snapshot.record);\n }\n\n private async putOperation(operation: PutOperation, lease: FerricStoreMutationLease): Promise<void> {\n validatePut(operation);\n const dataKey = this.itemDataKey(operation.namespace, operation.key);\n const locator = catalogMember(operation.namespace, operation.key);\n if (operation.value == null) {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n if (snapshot.expected?.equals(DELETED_ITEM) === true) return;\n if (await lease.compareAndSet(dataKey, snapshot.expected, DELETED_ITEM)) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph store deletion did not converge\");\n }\n const storedValue = snapshotJsonValue(operation.value);\n // The catalog is append-only. Readers validate the current CAS-protected\n // item, so a stale or interrupted publication cannot hide a newer value.\n await lease.publish(\"ZADD\", this.catalogKey(), 0, locator);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n const now = new Date().toISOString();\n const record: StoredItem = {\n createdAt: snapshot.record?.createdAt ?? now,\n formatVersion: FORMAT_VERSION,\n key: operation.key,\n namespace: [...operation.namespace],\n updatedAt: now,\n value: storedValue\n };\n if (await lease.compareAndSet(dataKey, snapshot.expected, encodeItem(record))) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph store mutation did not converge\");\n }\n\n private async searchOperation(operation: SearchOperation): Promise<SearchItem[]> {\n validateNamespacePrefix(operation.namespacePrefix);\n if (operation.query != null) {\n throw new Error(\n \"FerricStoreStore semantic query search is not configured; use metadata filters or a vector-enabled store\"\n );\n }\n const limit = normalizePageNumber(operation.limit, 10, \"search limit\");\n const offset = normalizePageNumber(operation.offset, 0, \"search offset\");\n if (limit === 0) return [];\n const matches: SearchItem[] = [];\n for await (const locator of this.catalogLocators()) {\n if (!startsWithNamespace(locator.namespace, operation.namespacePrefix)) continue;\n const item = await this.readCatalogItem(locator.namespace, locator.key);\n if (item == null || !matchesFilter(item.value, operation.filter)) continue;\n matches.push(item);\n if (matches.length >= offset + limit) break;\n }\n return matches.slice(offset, offset + limit);\n }\n\n private async listNamespacesOperation(operation: ListNamespacesOperation): Promise<string[][]> {\n const limit = normalizePageNumber(operation.limit, 100, \"namespace limit\");\n const offset = normalizePageNumber(operation.offset, 0, \"namespace offset\");\n const maxDepth = operation.maxDepth == null\n ? undefined\n : positiveInteger(operation.maxDepth, operation.maxDepth, \"maxDepth\");\n if (limit === 0) return [];\n const namespaces = new Map<string, string[]>();\n for await (const locator of this.catalogLocators()) {\n const item = await this.readCatalogItem(locator.namespace, locator.key);\n if (item == null) continue;\n if (!matchesConditions(item.namespace, operation.matchConditions)) continue;\n const namespace = maxDepth == null ? item.namespace : item.namespace.slice(0, maxDepth);\n namespaces.set(JSON.stringify(namespace), namespace);\n }\n return [...namespaces.values()]\n .sort(compareNamespaces)\n .slice(offset, offset + limit);\n }\n\n private async readCatalogItem(namespace: string[], key: string): Promise<Item | null> {\n const snapshot = await this.readItemSnapshot(namespace, key);\n return snapshot.record == null ? null : itemFromRecord(snapshot.record);\n }\n\n private async readItemSnapshot(\n namespace: readonly string[],\n key: string\n ): Promise<{ expected: Buffer | undefined; record: StoredItem | null }> {\n const expected = await readAtomicValue(\n this.client,\n this.itemDataKey(namespace, key),\n \"LangGraph atomic store item\"\n );\n if (expected != null) {\n return {\n expected,\n record: expected.equals(DELETED_ITEM) ? null : decodeItemRecord(expected)\n };\n }\n const legacy = await this.client.command(\"HGET\", this.namespaceKey(namespace), itemField(key));\n return { expected, record: legacy == null ? null : decodeItemRecord(legacy) };\n }\n\n private async *catalogLocators(): AsyncGenerator<{ key: string; namespace: string[] }> {\n let offset = 0;\n while (true) {\n const values = arrayResponse(\n await this.client.command(\"ZRANGE\", this.catalogKey(), offset, offset + this.scanCount - 1),\n \"LangGraph store catalog response\"\n );\n if (values.length === 0) return;\n for (const value of values) yield decodeCatalogMember(value);\n offset += values.length;\n if (values.length < this.scanCount) return;\n }\n }\n}\n\nfunction isPutOperation(operation: Operation): operation is PutOperation {\n return \"namespace\" in operation && \"key\" in operation && \"value\" in operation;\n}\n\nfunction isGetOperation(operation: Operation): operation is GetOperation {\n return \"namespace\" in operation && \"key\" in operation && !(\"value\" in operation);\n}\n\nfunction isSearchOperation(operation: Operation): operation is SearchOperation {\n return \"namespacePrefix\" in operation;\n}\n\nfunction isListNamespacesOperation(operation: Operation): operation is ListNamespacesOperation {\n return !(\"namespace\" in operation) && !(\"namespacePrefix\" in operation);\n}\n\nfunction validatePut(operation: PutOperation): void {\n validateNamespace(operation.namespace);\n if (typeof operation.key !== \"string\") throw new TypeError(\"store key must be text\");\n if (operation.value == null) return;\n if (typeof operation.value !== \"object\" || Array.isArray(operation.value)) {\n throw new TypeError(\"LangGraph store values must be JSON objects\");\n }\n validateJson(operation.value, new WeakSet());\n}\n\nfunction validateNamespace(namespace: readonly string[]): void {\n if (!Array.isArray(namespace) || namespace.length === 0) {\n throw new Error(\"namespace cannot be empty\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\" || label.length === 0 || label.includes(\".\")) {\n throw new Error(\"namespace labels must be non-empty strings without periods\");\n }\n }\n if (namespace[0] === \"langgraph\") throw new Error('root namespace label cannot be \"langgraph\"');\n}\n\nfunction validateNamespacePrefix(namespace: readonly string[]): void {\n if (!Array.isArray(namespace)) throw new TypeError(\"namespacePrefix must be an array\");\n if (namespace.length > 0) validateNamespace(namespace);\n}\n\nfunction validateJson(value: unknown, ancestors: WeakSet<object>): void {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (value === undefined) throw new TypeError(\"LangGraph store values must not contain undefined\");\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(\"LangGraph store numbers must be finite\");\n return;\n }\n if (typeof value !== \"object\") throw new TypeError(\"LangGraph store values must be JSON serializable\");\n if (ancestors.has(value)) throw new TypeError(\"LangGraph store values must not be cyclic\");\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const keys = Reflect.ownKeys(value);\n if (\n keys.length !== value.length + 1 ||\n keys.some((key) => typeof key !== \"string\" || key !== \"length\" && !isArrayIndex(key, value.length))\n ) {\n throw new TypeError(\"LangGraph store arrays must not be sparse or customized\");\n }\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (descriptor == null || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"LangGraph store arrays contain an unsupported item\");\n }\n validateJson(descriptor.value as unknown, ancestors);\n }\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"LangGraph store values must contain only JSON objects\");\n }\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== \"string\") throw new TypeError(\"LangGraph store objects must not have symbol keys\");\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor == null || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"LangGraph store objects contain an unsupported property\");\n }\n validateJson(descriptor.value as unknown, ancestors);\n }\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotJsonValue(value: Record<string, unknown>): Record<string, unknown> {\n validateJson(value, new WeakSet());\n return JSON.parse(JSON.stringify(value)) as Record<string, unknown>;\n}\n\nfunction encodeItem(record: StoredItem): Buffer {\n return Buffer.from(JSON.stringify(record), \"utf8\");\n}\n\nfunction itemFromRecord(record: StoredItem): Item {\n return {\n createdAt: new Date(record.createdAt),\n key: record.key,\n namespace: [...record.namespace],\n updatedAt: new Date(record.updatedAt),\n value: record.value\n };\n}\n\nfunction itemIdentityDigest(namespace: readonly string[], key: string): string {\n const keyBytes = Buffer.from(key, \"utf8\");\n return sha256(Buffer.concat([\n namespaceIdentity(namespace),\n uint64(keyBytes.length),\n keyBytes\n ]));\n}\n\nfunction decodeItemRecord(value: unknown): StoredItem {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary LangGraph store item\");\n }\n const text = typeof value === \"string\" ? value : Buffer.from(value).toString(\"utf8\");\n let record: unknown;\n try {\n record = JSON.parse(text);\n } catch (error) {\n throw new Error(\"invalid FerricStore LangGraph store item\", { cause: error });\n }\n if (\n record == null ||\n typeof record !== \"object\" ||\n (record as Partial<StoredItem>).formatVersion !== FORMAT_VERSION ||\n typeof (record as Partial<StoredItem>).key !== \"string\" ||\n !Array.isArray((record as Partial<StoredItem>).namespace) ||\n typeof (record as Partial<StoredItem>).createdAt !== \"string\" ||\n typeof (record as Partial<StoredItem>).updatedAt !== \"string\" ||\n (record as Partial<StoredItem>).value == null ||\n typeof (record as Partial<StoredItem>).value !== \"object\"\n ) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph store item\");\n }\n return record as StoredItem;\n}\n\nfunction matchesFilter(value: Record<string, unknown>, filter: Record<string, unknown> | undefined): boolean {\n return filter == null || Object.entries(filter).every(([key, expected]) => compareValue(value[key], expected));\n}\n\nfunction compareValue(value: unknown, expected: unknown): boolean {\n if (expected != null && typeof expected === \"object\" && !Array.isArray(expected)) {\n const entries = Object.entries(expected);\n if (entries.length > 0 && entries.every(([key]) => FILTER_OPERATORS.has(key))) {\n return entries.every(([operator, operand]) => applyOperator(value, operator, operand));\n }\n return value != null && typeof value === \"object\" && !Array.isArray(value) &&\n entries.every(([key, nested]) => compareValue((value as Record<string, unknown>)[key], nested));\n }\n if (Array.isArray(expected)) {\n return Array.isArray(value) && value.length === expected.length &&\n value.every((item, index) => compareValue(item, expected[index]));\n }\n return Object.is(value, expected);\n}\n\nfunction applyOperator(value: unknown, operator: string, expected: unknown): boolean {\n switch (operator) {\n case \"$eq\": return Object.is(value, expected);\n case \"$ne\": return !Object.is(value, expected);\n case \"$gt\": return comparable(value, expected, (left, right) => left > right);\n case \"$gte\": return comparable(value, expected, (left, right) => left >= right);\n case \"$in\": return Array.isArray(expected) && expected.some((item) => Object.is(item, value));\n case \"$lt\": return comparable(value, expected, (left, right) => left < right);\n case \"$lte\": return comparable(value, expected, (left, right) => left <= right);\n case \"$nin\": return !Array.isArray(expected) || expected.every((item) => !Object.is(item, value));\n default: throw new Error(`unsupported filter operator: ${operator}`);\n }\n}\n\nfunction comparable(\n value: unknown,\n expected: unknown,\n compare: (left: number, right: number) => boolean\n): boolean {\n try {\n return compare(Number(value), Number(expected));\n } catch {\n return false;\n }\n}\n\nconst FILTER_OPERATORS = new Set([\"$eq\", \"$gt\", \"$gte\", \"$in\", \"$lt\", \"$lte\", \"$ne\", \"$nin\"]);\n\nfunction matchesConditions(namespace: string[], conditions: MatchCondition[] | undefined): boolean {\n return conditions == null || conditions.every((condition) => {\n if (namespace.length < condition.path.length) return false;\n const actual = condition.matchType === \"prefix\" ? namespace : [...namespace].reverse();\n const pattern = condition.matchType === \"prefix\" ? condition.path : [...condition.path].reverse();\n return pattern.every((component, index) => component === \"*\" || actual[index] === component);\n });\n}\n\nfunction startsWithNamespace(namespace: readonly string[], prefix: readonly string[]): boolean {\n return prefix.length <= namespace.length && prefix.every((value, index) => namespace[index] === value);\n}\n\nfunction normalizePageNumber(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized < 0) {\n throw new TypeError(`${name} must be a non-negative safe integer`);\n }\n return normalized;\n}\n\nfunction compareNamespaces(left: readonly string[], right: readonly string[]): number {\n const count = Math.min(left.length, right.length);\n for (let index = 0; index < count; index += 1) {\n const compared = (left[index] ?? \"\").localeCompare(right[index] ?? \"\");\n if (compared !== 0) return compared;\n }\n return left.length - right.length;\n}\n\nfunction itemField(key: string): string {\n return `${ITEM_FIELD_PREFIX}${Buffer.from(key, \"utf8\").toString(\"base64url\")}`;\n}\n\nfunction namespaceIdentity(namespace: readonly string[]): Buffer {\n return Buffer.concat(namespace.flatMap((component) => {\n const payload = Buffer.from(component, \"utf8\");\n return [uint64(payload.length), payload];\n }));\n}\n\nfunction catalogMember(namespace: readonly string[], key: string): Buffer {\n return Buffer.concat([\n ...namespace.map(orderedText),\n Buffer.from([0, 0]),\n orderedText(key)\n ]);\n}\n\nfunction decodeCatalogMember(value: unknown): { key: string; namespace: string[] } {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary LangGraph store locator\");\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n const namespace: string[] = [];\n let offset = 0;\n while (true) {\n if (bytes[offset] === 0 && bytes[offset + 1] === 0) {\n offset += 2;\n break;\n }\n const decoded = decodeOrderedText(bytes, offset);\n namespace.push(decoded.value);\n offset = decoded.offset;\n }\n const key = decodeOrderedText(bytes, offset);\n if (key.offset !== bytes.length || namespace.length === 0) {\n throw new Error(\"invalid FerricStore LangGraph store locator\");\n }\n return { key: key.value, namespace };\n}\n\nfunction orderedText(value: string): Buffer {\n const output: number[] = [];\n for (const byte of Buffer.from(value, \"utf8\")) {\n if (byte === 0) output.push(0, 255);\n else output.push(byte);\n }\n output.push(0, 0);\n return Buffer.from(output);\n}\n\nfunction decodeOrderedText(bytes: Buffer, start: number): { offset: number; value: string } {\n const output: number[] = [];\n let offset = start;\n while (offset < bytes.length) {\n const byte = bytes[offset];\n if (byte == null) throw new Error(\"truncated FerricStore LangGraph store locator\");\n offset += 1;\n if (byte !== 0) {\n output.push(byte);\n continue;\n }\n const escaped = bytes[offset];\n offset += 1;\n if (escaped === 0) return { offset, value: Buffer.from(output).toString(\"utf8\") };\n if (escaped === 255) output.push(0);\n else throw new Error(\"invalid FerricStore LangGraph store locator escape\");\n }\n throw new Error(\"unterminated FerricStore LangGraph store locator\");\n}\n\nfunction uint64(value: number): Buffer {\n const result = Buffer.allocUnsafe(8);\n result.writeBigUInt64BE(BigInt(value));\n return result;\n}\n\nfunction sha256(value: Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isArrayIndex(key: string, length: number): boolean {\n if (!/^(?:0|[1-9]\\d*)$/u.test(key)) return false;\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n","import { createHash } from \"node:crypto\";\n\nimport { Command } from \"@langchain/langgraph\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\n\nimport { complete, fail, transition, type Outcome } from \"../outcomes.js\";\n\nexport type LangGraphInvocationConfig = RunnableConfig & { context?: unknown } & Record<string, unknown>;\n\nexport interface InvokableLangGraph<Input = unknown, Output = unknown> {\n invoke(input: Input | Command | null, options?: LangGraphInvocationConfig): Promise<Output>;\n getState?(options: LangGraphInvocationConfig): Promise<unknown>;\n}\n\n/** Structural subset of WorkflowContext required by the LangGraph bridge. */\nexport interface FerricFlowHandlerContext {\n readonly id: string;\n readonly logicalState: string;\n readonly partitionKey?: string;\n readonly payload: unknown;\n readonly state: string;\n readonly type: string;\n readonly values: Record<string, unknown>;\n}\n\nexport class LangGraphFlowContext {\n readonly flow: FerricFlowHandlerContext;\n readonly threadId: string;\n readonly checkpointNs: string;\n\n constructor(flow: FerricFlowHandlerContext, threadId: string, checkpointNs: string) {\n this.flow = flow;\n this.threadId = threadId;\n this.checkpointNs = checkpointNs;\n }\n\n get id(): string { return this.flow.id; }\n get type(): string { return this.flow.type; }\n get state(): string { return this.flow.state; }\n get partitionKey(): string | undefined { return this.flow.partitionKey; }\n get payload(): unknown { return this.flow.payload; }\n get values(): Record<string, unknown> { return this.flow.values; }\n}\n\nexport class LangGraphFlowRun<Output = unknown> {\n readonly value: Output;\n readonly threadId: string;\n readonly checkpointNs: string;\n readonly interrupts: readonly unknown[];\n\n constructor(value: Output, threadId: string, checkpointNs: string, interrupts: readonly unknown[]) {\n this.value = value;\n this.threadId = threadId;\n this.checkpointNs = checkpointNs;\n this.interrupts = interrupts;\n }\n\n get interrupted(): boolean { return this.interrupts.length > 0; }\n\n get interruptValues(): readonly unknown[] {\n return this.interrupts.map((item) =>\n item != null && typeof item === \"object\" && \"value\" in item\n ? (item).value\n : item);\n }\n}\n\nexport type LangGraphOutcomeMapper<Output> = (\n run: LangGraphFlowRun<Output>,\n flow: FerricFlowHandlerContext\n) => Outcome | Promise<Outcome>;\n\nexport interface LangGraphFlowOptions<Input, Output> {\n input?: (flow: FerricFlowHandlerContext) => Input | Promise<Input>;\n threadId?: (flow: FerricFlowHandlerContext) => string | Promise<string>;\n checkpointNs?: string | ((flow: FerricFlowHandlerContext) => string | Promise<string>);\n config?: (flow: FerricFlowHandlerContext) => LangGraphInvocationConfig | undefined | Promise<LangGraphInvocationConfig | undefined>;\n context?: (flow: FerricFlowHandlerContext) => unknown | Promise<unknown>;\n onComplete?: LangGraphOutcomeMapper<Output>;\n onInterrupt?: LangGraphOutcomeMapper<Output>;\n interruptState?: string;\n /** Resume an already-checkpointed graph with null input. Defaults to true. */\n recoverExisting?: boolean;\n invokeOptions?: LangGraphInvocationConfig;\n}\n\n/** Bind a LangGraph.js invocation to a leased FerricFlow workflow handler. */\nexport class LangGraphFlow<Input = unknown, Output = unknown> {\n readonly graph: InvokableLangGraph<Input, Output>;\n private readonly options: LangGraphFlowOptions<Input, Output>;\n\n constructor(graph: InvokableLangGraph<Input, Output>, options: LangGraphFlowOptions<Input, Output> = {}) {\n if (options.onInterrupt != null && options.interruptState != null) {\n throw new TypeError(\"onInterrupt and interruptState are mutually exclusive\");\n }\n if (options.interruptState != null) requireText(options.interruptState, \"interruptState\");\n this.graph = graph;\n this.options = { ...options };\n }\n\n async config(flow: FerricFlowHandlerContext, graphContext?: unknown): Promise<LangGraphInvocationConfig> {\n const invokeOptions = this.options.invokeOptions ?? {};\n const additional = await this.options.config?.(flow) ?? {};\n const baseConfigurable = invokeOptions.configurable ?? {};\n if (typeof baseConfigurable !== \"object\" || Array.isArray(baseConfigurable)) {\n throw new TypeError(\"LangGraph invokeOptions configurable must be an object\");\n }\n const rawConfigurable = additional.configurable ?? {};\n if (typeof rawConfigurable !== \"object\" || Array.isArray(rawConfigurable)) {\n throw new TypeError(\"LangGraph config configurable must be an object\");\n }\n const baseMetadata = invokeOptions.metadata ?? {};\n if (typeof baseMetadata !== \"object\" || Array.isArray(baseMetadata)) {\n throw new TypeError(\"LangGraph invokeOptions metadata must be an object\");\n }\n const rawMetadata = additional.metadata ?? {};\n if (typeof rawMetadata !== \"object\" || Array.isArray(rawMetadata)) {\n throw new TypeError(\"LangGraph config metadata must be an object\");\n }\n const threadId = requireText(\n await (this.options.threadId?.(flow) ?? defaultThreadId(flow)),\n \"threadId\"\n );\n const checkpointNsOption = this.options.checkpointNs ?? \"\";\n const checkpointNs = requireText(\n await (typeof checkpointNsOption === \"function\" ? checkpointNsOption(flow) : checkpointNsOption),\n \"checkpointNs\",\n true\n );\n const context = graphContext === undefined\n ? this.options.context != null\n ? await this.options.context(flow)\n : Object.hasOwn(additional, \"context\")\n ? additional.context\n : Object.hasOwn(invokeOptions, \"context\")\n ? invokeOptions.context\n : new LangGraphFlowContext(flow, threadId, checkpointNs)\n : graphContext;\n return {\n ...invokeOptions,\n ...additional,\n configurable: {\n ...baseConfigurable,\n ...rawConfigurable,\n checkpoint_ns: checkpointNs,\n thread_id: threadId\n },\n context,\n metadata: {\n ...baseMetadata,\n ...rawMetadata,\n ferricflow_id: flow.id,\n ferricflow_state: flow.logicalState,\n ferricflow_type: flow.type\n }\n };\n }\n\n async invoke(\n flow: FerricFlowHandlerContext,\n graphInput?: Input | Command | null,\n graphContext?: unknown\n ): Promise<LangGraphFlowRun<Output>> {\n const config = await this.config(flow, graphContext);\n let input = graphInput;\n if (input === undefined) {\n let hasCheckpoint = false;\n if ((this.options.recoverExisting ?? true) && this.graph.getState != null) {\n hasCheckpoint = snapshotHasCheckpoint(await this.graph.getState(config));\n }\n input = hasCheckpoint\n ? null\n : this.options.input == null\n ? flow.payload as Input\n : await this.options.input(flow);\n }\n const value = await this.graph.invoke(input, config);\n const configurable = config.configurable;\n return new LangGraphFlowRun(\n value,\n requireText(configurable?.thread_id, \"thread_id\"),\n requireText(configurable?.checkpoint_ns ?? \"\", \"checkpoint_ns\", true),\n interrupts(value)\n );\n }\n\n async outcome(run: LangGraphFlowRun<Output>, flow: FerricFlowHandlerContext): Promise<Outcome> {\n const mapper = run.interrupted ? this.options.onInterrupt : this.options.onComplete;\n if (mapper != null) return await mapper(run, flow);\n const stateMeta = {\n langgraph_checkpoint_ns: run.checkpointNs,\n langgraph_interrupt_count: run.interrupts.length,\n langgraph_interrupted: run.interrupted,\n langgraph_thread_id: run.threadId\n };\n if (!run.interrupted) return complete({ result: run.value, stateMeta });\n if (this.options.interruptState != null) {\n return transition(this.options.interruptState, { stateMeta });\n }\n return fail({\n error: {\n checkpointNs: run.checkpointNs,\n interruptCount: run.interrupts.length,\n threadId: run.threadId,\n type: \"unhandled_langgraph_interrupt\"\n },\n stateMeta\n });\n }\n\n async handle(\n flow: FerricFlowHandlerContext,\n graphInput?: Input | Command | null,\n graphContext?: unknown\n ): Promise<Outcome> {\n return await this.outcome(await this.invoke(flow, graphInput, graphContext), flow);\n }\n\n async resume(flow: FerricFlowHandlerContext, value: unknown, graphContext?: unknown): Promise<Outcome> {\n return await this.handle(flow, new Command({ resume: value }), graphContext);\n }\n\n async handler(flow: FerricFlowHandlerContext): Promise<Outcome> {\n return await this.handle(flow);\n }\n}\n\nfunction interrupts(value: unknown): readonly unknown[] {\n if (value == null || typeof value !== \"object\" || !(\"__interrupt__\" in value)) return [];\n const raw = (value as { __interrupt__?: unknown }).__interrupt__;\n if (raw == null) return [];\n return Array.isArray(raw) ? raw : [raw];\n}\n\nfunction snapshotHasCheckpoint(snapshot: unknown): boolean {\n if (snapshot == null || typeof snapshot !== \"object\") return false;\n const value = snapshot as Record<string, unknown>;\n if (value.config != null && typeof value.config === \"object\") {\n const configurable = (value.config as { configurable?: unknown }).configurable;\n if (\n configurable != null &&\n typeof configurable === \"object\" &&\n typeof (configurable as { checkpoint_id?: unknown }).checkpoint_id === \"string\"\n ) return true;\n }\n return value.createdAt != null || value.metadata != null;\n}\n\nfunction defaultThreadId(flow: FerricFlowHandlerContext): string {\n const identity = Buffer.concat([\n identityComponent(flow.type),\n identityComponent(flow.partitionKey),\n identityComponent(flow.id)\n ]);\n return `ferricflow:${createHash(\"sha256\").update(identity).digest(\"hex\")}`;\n}\n\nfunction identityComponent(value: string | undefined): Buffer {\n if (value == null) return Buffer.concat([Buffer.from(\"n\"), uint64(0)]);\n const payload = Buffer.from(value, \"utf8\");\n return Buffer.concat([Buffer.from(\"s\"), uint64(payload.length), payload]);\n}\n\nfunction uint64(value: number): Buffer {\n const result = Buffer.allocUnsafe(8);\n result.writeBigUInt64BE(BigInt(value));\n return result;\n}\n\nfunction requireText(value: unknown, name: string, allowEmpty = false): string {\n if (typeof value !== \"string\" || (!allowEmpty && value.length === 0) || value.includes(\"\\0\")) {\n throw new TypeError(`${name} must be ${allowEmpty ? \"text\" : \"non-empty text\"} without NUL bytes`);\n }\n return value;\n}\n","import type { StateMeta } from \"./types.js\";\nimport type { CommandArgument } from \"./internal.js\";\n\nconst OUTCOME_BRAND = Symbol(\"ferricstore.outcome\");\n\nexport type Outcome = TransitionOutcome | CompleteOutcome | RetryOutcome | FailOutcome;\n\nexport interface NamedValueMutation {\n values?: Record<string, unknown>;\n valueRefs?: Record<string, string>;\n dropValues?: string[];\n overrideValues?: string[];\n attributesMerge?: Record<string, CommandArgument>;\n attributesDelete?: string[];\n stateMeta?: StateMeta;\n}\n\nexport interface TransitionOutcome extends NamedValueMutation {\n readonly kind: \"transition\";\n readonly toState: string;\n readonly payload?: unknown;\n readonly priority?: number;\n readonly runAtMs?: number;\n}\n\nexport interface CompleteOutcome extends NamedValueMutation {\n readonly kind: \"complete\";\n readonly payload?: unknown;\n readonly result?: unknown;\n readonly ttlMs?: number;\n}\n\nexport interface RetryOutcome extends NamedValueMutation {\n readonly kind: \"retry\";\n readonly error?: unknown;\n readonly payload?: unknown;\n readonly runAtMs?: number;\n}\n\nexport interface FailOutcome extends NamedValueMutation {\n readonly kind: \"fail\";\n readonly error?: unknown;\n readonly payload?: unknown;\n readonly ttlMs?: number;\n}\n\nexport function transition(\n toState: string,\n options: Omit<TransitionOutcome, \"kind\" | \"toState\"> = {}\n): TransitionOutcome {\n return brandOutcome({ ...options, kind: \"transition\", toState });\n}\n\nexport function complete(options: Omit<CompleteOutcome, \"kind\"> = {}): CompleteOutcome {\n return brandOutcome({ ...options, kind: \"complete\" });\n}\n\nexport function retry(options: Omit<RetryOutcome, \"kind\"> = {}): RetryOutcome {\n return brandOutcome({ ...options, kind: \"retry\" });\n}\n\nexport function fail(options: Omit<FailOutcome, \"kind\"> = {}): FailOutcome {\n return brandOutcome({ ...options, kind: \"fail\" });\n}\n\nexport function isOutcome(value: unknown): value is Outcome {\n if (\n typeof value !== \"object\" ||\n value == null ||\n !Object.hasOwn(value, OUTCOME_BRAND) ||\n (value as Record<PropertyKey, unknown>)[OUTCOME_BRAND] !== true\n ) {\n return false;\n }\n const outcome = value as Partial<Outcome>;\n if (outcome.kind === \"transition\") {\n return typeof outcome.toState === \"string\";\n }\n return outcome.kind === \"complete\" || outcome.kind === \"retry\" || outcome.kind === \"fail\";\n}\n\nfunction brandOutcome<T extends Outcome>(outcome: T): T {\n Object.defineProperty(outcome, \"kind\", {\n configurable: false,\n enumerable: true,\n value: outcome.kind,\n writable: false\n });\n if (outcome.kind === \"transition\") {\n Object.defineProperty(outcome, \"toState\", {\n configurable: false,\n enumerable: true,\n value: outcome.toState,\n writable: false\n });\n }\n Object.defineProperty(outcome, OUTCOME_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false\n });\n return outcome;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,sBAAuC;AAEvC,uBAMO;;;ACRP,yBAA2B;AAC3B,sBAAoC;;;ACD7B,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC,OAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,UAMzB,CAAC,GAAG;AACN,UAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AACvC,SAAK,OAAO,WAAW;AACvB,SAAK,MAAM,QAAQ;AACnB,SAA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I,OAAO,UAAU,YAAa,CAAC,cAAc,MAAM,WAAW,KAAM,MAAM,SAAS,IAAI,GAAG;AAC5F,UAAM,IAAI,UAAU,GAAG,IAAI,YAAY,aAAa,SAAS,gBAAgB,oBAAoB;AAAA,EACnG;AACA,SAAO;AACT;","names":["import_node_crypto","response","delay","checkpointId","identity","import_node_crypto","import_langgraph","FORMAT_VERSION","sha256","orderedText","decodeOrderedText","import_node_crypto","import_langgraph","interrupts","identity","uint64"]}
1
+ {"version":3,"sources":["../src/langgraph.ts","../src/langgraph/checkpoint.ts","../src/agent-persistence/durability.ts","../src/errors.ts","../src/langgraph/store.ts","../src/langgraph/flow.ts","../src/outcomes.ts"],"sourcesContent":["export {\n FerricStoreSaver,\n type FerricStoreSaverOptions,\n type LangGraphChannelVersions,\n type LangGraphPendingWrite\n} from \"./langgraph/checkpoint.js\";\nexport {\n FerricStoreStore,\n type FerricStoreStoreOptions\n} from \"./langgraph/store.js\";\nexport {\n LangGraphFlow,\n LangGraphFlowContext,\n LangGraphFlowRun,\n type FerricFlowHandlerContext,\n type InvokableLangGraph,\n type LangGraphFlowOptions,\n type LangGraphInvocationConfig,\n type LangGraphOutcomeMapper\n} from \"./langgraph/flow.js\";\nexport type {\n FerricStoreCommandClient,\n FerricStoreLockOptions\n} from \"./agent-persistence/durability.js\";\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n BaseCheckpointSaver,\n copyCheckpoint,\n type Checkpoint,\n type CheckpointMetadata,\n type CheckpointTuple\n} from \"@langchain/langgraph\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\n\nimport {\n arrayResponse,\n integerResponse,\n normalizeKeyPrefix,\n positiveInteger,\n readAtomicValue,\n textResponse,\n type FerricStoreCommandClient,\n type FerricStoreLockOptions,\n type FerricStoreMutationLease,\n withMutationLocks\n} from \"../agent-persistence/durability.js\";\n\nexport type LangGraphPendingWrite = [channel: string, value: unknown];\nexport type LangGraphChannelVersions = Record<string, string | number>;\ntype SerializerProtocol = BaseCheckpointSaver[\"serde\"];\n\nconst FORMAT_VERSION = 1;\nconst LEGACY_EPOCH_PREFIX = \"legacy:\";\nconst CURRENT_EPOCH_PREFIX = \"v2:\";\nconst CHECKPOINT_FIELD_PREFIX = \"checkpoint:\";\nconst WRITE_FIELD_PREFIX = \"write:\";\nconst WRITES_INDEX: Readonly<Record<string, number>> = {\n __error__: -1,\n __interrupt__: -3,\n __resume__: -4,\n __scheduled__: -2\n};\n\ninterface CheckpointRecord {\n readonly checkpoint: Checkpoint;\n readonly checkpointId: string;\n readonly checkpointNs: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly metadata: CheckpointMetadata;\n readonly parentCheckpointId?: string;\n readonly threadId: string;\n}\n\ninterface PendingWriteRecord {\n readonly channel: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly index: number;\n readonly taskId: string;\n readonly value: unknown;\n}\n\ninterface ThreadEpoch {\n readonly legacyFallback: boolean;\n readonly raw: Buffer | undefined;\n readonly value: string | undefined;\n}\n\nexport interface FerricStoreSaverOptions extends FerricStoreLockOptions {\n /** FerricStore key prefix. Defaults to `langgraph:checkpoint`. */\n keyPrefix?: string;\n /** Number of catalog/hash entries read per page. Defaults to 256. */\n scanCount?: number;\n /** Optional LangGraph serializer. The framework JSON-plus serializer is used by default. */\n serde?: SerializerProtocol;\n}\n\n/** Durable, epoch-fenced LangGraph.js checkpoint saver backed by FerricStore. */\nexport class FerricStoreSaver extends BaseCheckpointSaver {\n readonly client: FerricStoreCommandClient;\n readonly keyPrefix: string;\n readonly scanCount: number;\n private readonly lockOptions: FerricStoreLockOptions;\n\n constructor(client: FerricStoreCommandClient, options: FerricStoreSaverOptions = {}) {\n super(options.serde);\n this.client = client;\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix ?? \"langgraph:checkpoint\", \"langgraph:checkpoint\");\n this.scanCount = positiveInteger(options.scanCount, 256, \"scanCount\");\n this.lockOptions = {\n lockRetryMs: options.lockRetryMs,\n lockTtlMs: options.lockTtlMs,\n lockWaitMs: options.lockWaitMs\n };\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const { checkpointNs, threadId } = identity(config);\n const key = this.threadKey(threadId, checkpointNs);\n const epoch = await this.readThreadEpoch(threadId);\n let id = checkpointId(config);\n let record: CheckpointRecord | undefined;\n if (id != null) {\n record = await this.readRecordAtEpoch(key, id, epoch);\n } else {\n for (const candidate of await this.checkpointIdsAtEpoch(key, epoch)) {\n record = await this.readRecordAtEpoch(key, candidate, epoch);\n if (record != null) {\n id = candidate;\n break;\n }\n }\n }\n if (id == null || record == null) return undefined;\n return await this.tupleFromRecord(key, record);\n }\n\n async *list(config: RunnableConfig, options: {\n limit?: number;\n before?: RunnableConfig;\n filter?: Record<string, unknown>;\n } = {}): AsyncGenerator<CheckpointTuple> {\n const limit = options.limit;\n if (limit != null && (!Number.isSafeInteger(limit) || limit < 0)) {\n throw new TypeError(\"limit must be a non-negative safe integer\");\n }\n if (limit === 0) return;\n const beforeId = options.before == null ? undefined : checkpointId(options.before);\n const configurable = config.configurable;\n const threadId = optionalText(configurable?.thread_id, \"thread_id\");\n const expectedId = optionalText(configurable?.checkpoint_id ?? configurable?.thread_ts, \"checkpoint_id\");\n const namespaceSpecified = configurable != null && Object.hasOwn(configurable, \"checkpoint_ns\");\n const checkpointNs = namespaceSpecified ? requiredText(configurable?.checkpoint_ns, \"checkpoint_ns\", true) : undefined;\n\n const matches: { key: string; record: CheckpointRecord }[] = [];\n if (threadId == null) {\n await this.collectGlobal(matches, beforeId, expectedId, checkpointNs, options.filter, limit);\n } else {\n const keys = checkpointNs == null\n ? await this.threadKeys(threadId)\n : [this.threadKey(threadId, checkpointNs)];\n for (const key of keys) {\n const epoch = await this.readThreadEpoch(threadId);\n const ids = expectedId == null\n ? await this.checkpointIdsAtEpoch(key, epoch)\n : [expectedId];\n for (const id of ids) {\n if (beforeId != null && id >= beforeId) continue;\n const record = await this.readRecordAtEpoch(key, id, epoch);\n if (record == null || !metadataMatches(record.metadata, options.filter)) continue;\n matches.push({ key, record });\n }\n }\n matches.sort((left, right) => right.record.checkpointId.localeCompare(left.record.checkpointId));\n if (limit != null) matches.splice(limit);\n }\n\n for (const match of matches) yield await this.tupleFromRecord(match.key, match.record);\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: LangGraphChannelVersions\n ): Promise<RunnableConfig> {\n void _newVersions;\n const { checkpointNs, threadId } = identity(config);\n if (typeof checkpoint.id !== \"string\" || checkpoint.id.length === 0) {\n throw new TypeError(\"checkpoint.id must be a non-empty string\");\n }\n const parentCheckpointId = checkpointId(config);\n const record: CheckpointRecord = {\n checkpoint: copyCheckpoint(checkpoint),\n checkpointId: checkpoint.id,\n checkpointNs,\n formatVersion: FORMAT_VERSION,\n metadata,\n ...(parentCheckpointId == null ? {} : { parentCheckpointId }),\n threadId\n };\n const key = this.threadKey(threadId, checkpointNs);\n await withMutationLocks(this.client, [this.threadLockKey(threadId)], async (lease) => {\n const epoch = await this.ensureThreadEpoch(threadId, lease);\n const locator = checkpointLocator(checkpoint.id, key, threadId);\n // Discovery indexes are append-only and published before the CAS record.\n // Readers validate the record in the current thread epoch, so stale\n // writers and interrupted publications remain invisible.\n await lease.publish(\"SADD\", this.threadCatalogKey(threadId), key);\n await lease.publish(\"ZADD\", this.threadLocatorCatalogKey(threadId), 0, locator);\n await lease.publish(\"ZADD\", this.catalogKey(), 0, locator);\n await lease.publish(\"ZADD\", this.checkpointIndexKey(key), 0, checkpoint.id);\n await lease.publish(\"ZADD\", this.atomicCheckpointIndexKey(key, requireEpoch(epoch)), 0, checkpoint.id);\n const dataKey = this.checkpointRecordKey(key, requireEpoch(epoch), checkpoint.id);\n const value = await this.serialize(record);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const expected = await readAtomicValue(this.client, dataKey, \"LangGraph atomic checkpoint record\");\n if (await lease.compareAndSet(dataKey, expected, value)) {\n await this.assertCurrentEpoch(threadId, epoch);\n return;\n }\n }\n throw new Error(\"concurrent FerricStore LangGraph checkpoint mutation did not converge\");\n }, this.lockOptions);\n return checkpointConfig(threadId, checkpointNs, checkpoint.id);\n }\n\n async putWrites(config: RunnableConfig, writes: LangGraphPendingWrite[], taskId: string): Promise<void> {\n const { checkpointNs, threadId } = identity(config);\n const id = checkpointId(config);\n if (id == null) throw new TypeError(\"putWrites requires configurable.checkpoint_id\");\n if (typeof taskId !== \"string\" || taskId.length === 0) throw new TypeError(\"taskId must be non-empty text\");\n const snapshots = await Promise.all(writes.map(async ([channel, value], fallbackIndex) => {\n if (typeof channel !== \"string\") throw new TypeError(\"pending-write channel must be text\");\n const index = WRITES_INDEX[channel] ?? fallbackIndex;\n const record: PendingWriteRecord = {\n channel,\n formatVersion: FORMAT_VERSION,\n index,\n taskId,\n value\n };\n return { index, value: await this.serialize(record) };\n }));\n const key = this.threadKey(threadId, checkpointNs);\n await withMutationLocks(this.client, [this.threadLockKey(threadId)], async (lease) => {\n const epoch = await this.ensureThreadEpoch(threadId, lease);\n const epochValue = requireEpoch(epoch);\n await lease.publish(\"SADD\", this.threadCatalogKey(threadId), key);\n for (const snapshot of snapshots) {\n const dataKey = this.pendingWriteKey(key, epochValue, id, taskId, snapshot.index);\n const indexKey = this.atomicPendingWriteIndexKey(key, epochValue, id);\n await lease.publish(\"ZADD\", indexKey, 0, dataKey);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const expected = await readAtomicValue(this.client, dataKey, \"LangGraph atomic pending write\");\n if (snapshot.index >= 0 && expected != null) break;\n if (snapshot.index >= 0 && epoch.legacyFallback) {\n const legacy = await this.client.command(\"HGET\", key, writeField(id, taskId, snapshot.index));\n if (legacy != null) break;\n }\n if (await lease.compareAndSet(dataKey, expected, snapshot.value)) break;\n if (attempt === 7) {\n throw new Error(\"concurrent FerricStore LangGraph pending-write mutation did not converge\");\n }\n }\n }\n await this.assertCurrentEpoch(threadId, epoch);\n }, this.lockOptions);\n }\n\n async deleteThread(threadId: string): Promise<void> {\n const normalized = requiredText(threadId, \"threadId\");\n await withMutationLocks(this.client, [this.threadLockKey(normalized)], async (lease) => {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const epoch = await this.ensureThreadEpoch(normalized, lease);\n const next = Buffer.from(`${CURRENT_EPOCH_PREFIX}${randomUUID()}`, \"utf8\");\n if (await lease.compareAndSet(this.threadEpochKey(normalized), epoch.raw, next)) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph thread deletion did not converge\");\n }, this.lockOptions);\n }\n\n private catalogKey(): string {\n return `${this.keyPrefix}:checkpoints`;\n }\n\n private threadCatalogKey(threadId: string): string {\n const digest = sha256(threadId);\n return `${this.keyPrefix}:{lgt:${digest}}:namespaces`;\n }\n\n private threadLocatorCatalogKey(threadId: string): string {\n return `${this.threadCatalogKey(threadId)}:checkpoint-locators`;\n }\n\n private threadLockKey(threadId: string): string {\n return `${this.keyPrefix}:{lgt:${sha256(threadId)}}:mutation-lock`;\n }\n\n private threadKey(threadId: string, checkpointNs: string): string {\n return `${this.keyPrefix}:{lg:${sha256(lengthPrefixed([threadId, checkpointNs]))}}:thread`;\n }\n\n private checkpointIndexKey(threadKey: string): string {\n return `${threadKey}:checkpoint-index`;\n }\n\n private threadEpochKey(threadId: string): string {\n return `${this.threadCatalogKey(threadId)}:atomic-epoch`;\n }\n\n private atomicCheckpointIndexKey(threadKey: string, epoch: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:checkpoint-index`;\n }\n\n private atomicPendingWriteIndexKey(threadKey: string, epoch: string, checkpointId: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:writes:${encodeComponent(checkpointId)}`;\n }\n\n private checkpointRecordKey(threadKey: string, epoch: string, checkpointId: string): string {\n return `${threadKey}:atomic:${sha256(epoch)}:checkpoint:${encodeComponent(checkpointId)}`;\n }\n\n private pendingWriteKey(\n threadKey: string,\n epoch: string,\n checkpointId: string,\n taskId: string,\n index: number\n ): string {\n return `${threadKey}:atomic:${sha256(epoch)}:write:${encodeComponent(checkpointId)}:${encodeComponent(taskId)}:${index}`;\n }\n\n private async readThreadEpoch(threadId: string): Promise<ThreadEpoch> {\n const raw = await readAtomicValue(this.client, this.threadEpochKey(threadId), \"LangGraph thread epoch\");\n if (raw == null) return { legacyFallback: true, raw, value: undefined };\n const value = raw.toString(\"utf8\");\n if (!value.startsWith(LEGACY_EPOCH_PREFIX) && !value.startsWith(CURRENT_EPOCH_PREFIX)) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph thread epoch\");\n }\n return { legacyFallback: value.startsWith(LEGACY_EPOCH_PREFIX), raw, value };\n }\n\n private async ensureThreadEpoch(\n threadId: string,\n lease: FerricStoreMutationLease\n ): Promise<ThreadEpoch> {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const epoch = await this.readThreadEpoch(threadId);\n if (epoch.value != null) return epoch;\n const raw = Buffer.from(`${LEGACY_EPOCH_PREFIX}${randomUUID()}`, \"utf8\");\n if (await lease.compareAndSet(this.threadEpochKey(threadId), undefined, raw)) {\n return { legacyFallback: true, raw, value: raw.toString(\"utf8\") };\n }\n }\n throw new Error(\"concurrent FerricStore LangGraph epoch initialization did not converge\");\n }\n\n private async assertCurrentEpoch(threadId: string, expected: ThreadEpoch): Promise<void> {\n const current = await this.readThreadEpoch(threadId);\n if (expected.raw == null || current.raw?.equals(expected.raw) !== true) {\n throw new Error(\"FerricStore LangGraph thread epoch changed while committing data\");\n }\n }\n\n private async serialize(value: unknown): Promise<Buffer> {\n const [type, data] = await this.serde.dumpsTyped(value);\n const typeBytes = Buffer.from(type, \"utf8\");\n if (typeBytes.length > 65_535) throw new TypeError(\"serialized LangGraph type name is too long\");\n const header = Buffer.allocUnsafe(2);\n header.writeUInt16BE(typeBytes.length);\n return Buffer.concat([header, typeBytes, Buffer.from(data)]);\n }\n\n private async deserialize<T>(value: unknown, name: string): Promise<T> {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(`FerricStore returned a non-binary ${name}`);\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n if (bytes.length < 2) throw new Error(`invalid FerricStore ${name}`);\n const typeLength = bytes.readUInt16BE(0);\n if (bytes.length < typeLength + 2) throw new Error(`truncated FerricStore ${name}`);\n const type = bytes.subarray(2, typeLength + 2).toString(\"utf8\");\n return await this.serde.loadsTyped(type, bytes.subarray(typeLength + 2)) as T;\n }\n\n private async readRecordAtEpoch(\n key: string,\n id: string,\n epoch: ThreadEpoch\n ): Promise<CheckpointRecord | undefined> {\n let value: unknown;\n if (epoch.value != null) {\n value = await this.client.command(\"GET\", this.checkpointRecordKey(key, epoch.value, id));\n if (value == null && epoch.legacyFallback) {\n value = await this.client.command(\"HGET\", key, checkpointField(id));\n }\n } else {\n value = await this.client.command(\"HGET\", key, checkpointField(id));\n }\n if (value == null) return undefined;\n const record = await this.deserialize<CheckpointRecord>(value, \"LangGraph checkpoint record\");\n if (record.formatVersion !== FORMAT_VERSION || record.checkpointId !== id) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph checkpoint record\");\n }\n return record;\n }\n\n private async pendingWritesAtEpoch(\n key: string,\n id: string,\n epoch: ThreadEpoch\n ): Promise<[string, string, unknown][]> {\n const records = new Map<string, PendingWriteRecord>();\n if (epoch.value != null) {\n const keys = arrayResponse(\n await this.client.command(\"ZRANGE\", this.atomicPendingWriteIndexKey(key, epoch.value, id), 0, -1),\n \"LangGraph atomic pending-write index response\"\n );\n for (const rawKey of keys) {\n const dataKey = textResponse(rawKey, \"LangGraph pending-write key\");\n const value = await this.client.command(\"GET\", dataKey);\n if (value == null) continue;\n const record = await this.deserialize<PendingWriteRecord>(value, \"LangGraph pending write\");\n records.set(pendingWriteIdentity(record), record);\n }\n }\n if (epoch.legacyFallback) {\n const fields = await this.scanHash(key, `${WRITE_FIELD_PREFIX}${encodeComponent(id)}:*`);\n for (const [, value] of fields) {\n const record = await this.deserialize<PendingWriteRecord>(value, \"LangGraph pending write\");\n const identity = pendingWriteIdentity(record);\n if (!records.has(identity)) records.set(identity, record);\n }\n }\n const ordered = [...records.values()];\n for (const record of ordered) {\n if (record.formatVersion !== FORMAT_VERSION) {\n throw new Error(\"unsupported FerricStore LangGraph pending-write format\");\n }\n }\n ordered.sort((left, right) => left.taskId.localeCompare(right.taskId) || left.index - right.index);\n return ordered.map((record) => [record.taskId, record.channel, record.value]);\n }\n\n private async tupleFromRecord(key: string, record: CheckpointRecord): Promise<CheckpointTuple> {\n const epoch = await this.readThreadEpoch(record.threadId);\n return {\n checkpoint: record.checkpoint,\n config: checkpointConfig(record.threadId, record.checkpointNs, record.checkpointId),\n metadata: record.metadata,\n pendingWrites: await this.pendingWritesAtEpoch(key, record.checkpointId, epoch),\n ...(record.parentCheckpointId == null\n ? {}\n : { parentConfig: checkpointConfig(record.threadId, record.checkpointNs, record.parentCheckpointId) })\n };\n }\n\n private async scanHash(key: string, pattern: string): Promise<[unknown, unknown][]> {\n let cursor = 0;\n const result: [unknown, unknown][] = [];\n do {\n const response = arrayResponse(\n await this.client.command(\"HSCAN\", key, cursor, \"MATCH\", pattern, \"COUNT\", this.scanCount),\n \"HSCAN response\"\n );\n if (response.length !== 2) throw new Error(\"FerricStore HSCAN response must contain cursor and items\");\n cursor = integerResponse(response[0], \"HSCAN cursor\");\n const values = response[1];\n if (values instanceof Map) {\n result.push(...values.entries());\n } else {\n const flat = arrayResponse(values, \"HSCAN items\");\n if (flat.length % 2 !== 0) throw new Error(\"FerricStore HSCAN returned an odd item count\");\n for (let index = 0; index < flat.length; index += 2) result.push([flat[index], flat[index + 1]]);\n }\n } while (cursor !== 0);\n return result;\n }\n\n private async threadKeys(threadId: string): Promise<string[]> {\n const values = arrayResponse(\n await this.client.command(\"SMEMBERS\", this.threadCatalogKey(threadId)),\n \"thread checkpoint catalog response\"\n );\n return values.map((value) => textResponse(value, \"thread checkpoint key\")).sort();\n }\n\n private async checkpointIdsAtEpoch(key: string, epoch: ThreadEpoch): Promise<string[]> {\n const ids = new Set<string>();\n if (epoch.value != null) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.atomicCheckpointIndexKey(key, epoch.value), 0, -1),\n \"atomic checkpoint index response\"\n );\n for (const value of values) ids.add(textResponse(value, \"checkpoint ID\"));\n }\n if (epoch.legacyFallback) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.checkpointIndexKey(key), 0, -1),\n \"checkpoint index response\"\n );\n for (const value of values) ids.add(textResponse(value, \"checkpoint ID\"));\n }\n return [...ids].sort((left, right) => right.localeCompare(left));\n }\n\n private async collectGlobal(\n result: { key: string; record: CheckpointRecord }[],\n beforeId: string | undefined,\n expectedId: string | undefined,\n checkpointNs: string | undefined,\n filter: Record<string, unknown> | undefined,\n limit: number | undefined\n ): Promise<void> {\n let offset = 0;\n const seen = new Set<string>();\n while (limit == null || result.length < limit) {\n const values = arrayResponse(\n await this.client.command(\"ZREVRANGE\", this.catalogKey(), offset, offset + this.scanCount - 1),\n \"global checkpoint catalog response\"\n );\n if (values.length === 0) break;\n for (const value of values) {\n const locator = decodeCheckpointLocator(value);\n const { checkpointId: id, threadKey: key } = locator;\n if (expectedId != null && id !== expectedId) continue;\n if (beforeId != null && id >= beforeId) continue;\n let record: CheckpointRecord | undefined;\n if (locator.threadId != null) {\n record = await this.readRecordAtEpoch(key, id, await this.readThreadEpoch(locator.threadId));\n } else {\n const legacy = await this.client.command(\"HGET\", key, checkpointField(id));\n if (legacy != null) {\n const candidate = await this.deserialize<CheckpointRecord>(legacy, \"LangGraph checkpoint record\");\n record = await this.readRecordAtEpoch(key, id, await this.readThreadEpoch(candidate.threadId));\n }\n }\n if (\n record == null ||\n checkpointNs != null && record.checkpointNs !== checkpointNs ||\n !metadataMatches(record.metadata, filter)\n ) continue;\n const identity = lengthPrefixed([record.threadId, record.checkpointNs, record.checkpointId]).toString(\"base64url\");\n if (seen.has(identity)) continue;\n seen.add(identity);\n result.push({ key, record });\n if (limit != null && result.length >= limit) break;\n }\n offset += values.length;\n if (values.length < this.scanCount) break;\n }\n }\n}\n\nfunction identity(config: RunnableConfig): { checkpointNs: string; threadId: string } {\n if (config.configurable == null || typeof config.configurable !== \"object\") {\n throw new TypeError(\"LangGraph config must contain configurable.thread_id\");\n }\n return {\n checkpointNs: requiredText(config.configurable.checkpoint_ns ?? \"\", \"checkpoint_ns\", true),\n threadId: requiredText(config.configurable.thread_id, \"thread_id\")\n };\n}\n\nfunction checkpointId(config: RunnableConfig): string | undefined {\n return optionalText(config.configurable?.checkpoint_id ?? config.configurable?.thread_ts, \"checkpoint_id\");\n}\n\nfunction checkpointConfig(threadId: string, checkpointNs: string, id: string): RunnableConfig {\n return { configurable: { checkpoint_id: id, checkpoint_ns: checkpointNs, thread_id: threadId } };\n}\n\nfunction requiredText(value: unknown, name: string, allowEmpty = false): string {\n if (typeof value !== \"string\" || (!allowEmpty && value.length === 0)) {\n throw new TypeError(`${name} must be ${allowEmpty ? \"text\" : \"non-empty text\"}`);\n }\n return value;\n}\n\nfunction optionalText(value: unknown, name: string): string | undefined {\n if (value == null || value === \"\") return undefined;\n return requiredText(value, name);\n}\n\nfunction metadataMatches(metadata: CheckpointMetadata, filter: Record<string, unknown> | undefined): boolean {\n return filter == null || Object.entries(filter).every(([key, value]) => {\n const actual = Object.getOwnPropertyDescriptor(metadata, key)?.value as unknown;\n return Object.is(actual, value);\n });\n}\n\nfunction checkpointField(id: string): string {\n return `${CHECKPOINT_FIELD_PREFIX}${encodeComponent(id)}`;\n}\n\nfunction writeField(id: string, taskId: string, index: number): string {\n return `${WRITE_FIELD_PREFIX}${encodeComponent(id)}:${encodeComponent(taskId)}:${index}`;\n}\n\nfunction encodeComponent(value: string): string {\n return Buffer.from(value, \"utf8\").toString(\"base64url\");\n}\n\nfunction checkpointLocator(id: string, threadKey: string, threadId?: string): Buffer {\n if (threadId == null) return Buffer.concat([orderedText(id), Buffer.from(threadKey, \"utf8\")]);\n const threadIdBytes = Buffer.from(threadId, \"utf8\");\n const length = Buffer.allocUnsafe(4);\n length.writeUInt32BE(threadIdBytes.length);\n return Buffer.concat([\n orderedText(id),\n Buffer.from([0, 1]),\n length,\n threadIdBytes,\n Buffer.from(threadKey, \"utf8\")\n ]);\n}\n\nfunction decodeCheckpointLocator(value: unknown): {\n checkpointId: string;\n threadId?: string;\n threadKey: string;\n} {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary checkpoint locator\");\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n const decoded = decodeOrderedText(bytes, 0);\n let offset = decoded.offset;\n let threadId: string | undefined;\n if (bytes[offset] === 0 && bytes[offset + 1] === 1) {\n offset += 2;\n if (bytes.length < offset + 4) throw new Error(\"truncated FerricStore checkpoint locator\");\n const length = bytes.readUInt32BE(offset);\n offset += 4;\n if (bytes.length < offset + length) throw new Error(\"truncated FerricStore checkpoint locator thread ID\");\n threadId = bytes.subarray(offset, offset + length).toString(\"utf8\");\n offset += length;\n if (threadId.length === 0) throw new Error(\"FerricStore checkpoint locator has an empty thread ID\");\n }\n const threadKey = bytes.subarray(offset).toString(\"utf8\");\n if (threadKey.length === 0) throw new Error(\"FerricStore checkpoint locator has an empty thread key\");\n return { checkpointId: decoded.value, ...(threadId == null ? {} : { threadId }), threadKey };\n}\n\nfunction orderedText(value: string): Buffer {\n const output: number[] = [];\n for (const byte of Buffer.from(value, \"utf8\")) {\n if (byte === 0) output.push(0, 255);\n else output.push(byte);\n }\n output.push(0, 0);\n return Buffer.from(output);\n}\n\nfunction decodeOrderedText(bytes: Buffer, start: number): { offset: number; value: string } {\n const output: number[] = [];\n let offset = start;\n while (offset < bytes.length) {\n const byte = bytes[offset];\n if (byte == null) throw new Error(\"truncated FerricStore checkpoint locator\");\n offset += 1;\n if (byte !== 0) {\n output.push(byte);\n continue;\n }\n const escaped = bytes[offset];\n offset += 1;\n if (escaped === 0) return { offset, value: Buffer.from(output).toString(\"utf8\") };\n if (escaped === 255) output.push(0);\n else throw new Error(\"invalid FerricStore checkpoint locator escape\");\n }\n throw new Error(\"unterminated FerricStore checkpoint locator\");\n}\n\nfunction sha256(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction lengthPrefixed(values: readonly string[]): Buffer {\n const parts: Buffer[] = [];\n for (const value of values) {\n const payload = Buffer.from(value, \"utf8\");\n const length = Buffer.allocUnsafe(8);\n length.writeBigUInt64BE(BigInt(payload.length));\n parts.push(length, payload);\n }\n return Buffer.concat(parts);\n}\n\nfunction requireEpoch(epoch: ThreadEpoch): string {\n if (epoch.value == null) throw new Error(\"FerricStore LangGraph thread epoch is not initialized\");\n return epoch.value;\n}\n\nfunction pendingWriteIdentity(record: PendingWriteRecord): string {\n return lengthPrefixed([record.taskId, String(record.index)]).toString(\"base64url\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { LockHeldError } from \"../errors.js\";\nimport type { Command, CommandArgument } from \"../internal.js\";\n\nexport interface FerricStoreCommandClient {\n command(...args: CommandArgument[]): Promise<unknown>;\n pipeline?(commands: readonly Command[]): Promise<unknown[]>;\n}\n\nexport interface FerricStoreLockOptions {\n /** Lease duration for adapter mutation locks. Defaults to five minutes. */\n lockTtlMs?: number;\n /** Maximum time to wait for a contended mutation lock. Defaults to 30 seconds. */\n lockWaitMs?: number;\n /** Delay between lock acquisition attempts. Defaults to 10 milliseconds. */\n lockRetryMs?: number;\n}\n\nexport interface FerricStoreMutationLease {\n /** Aborted as soon as lock ownership is known to have been lost. */\n readonly signal: AbortSignal;\n /** Throw when this mutation no longer owns every requested lock. */\n assertOwned(): void;\n /** Publish an idempotent, add-only discovery entry before its CAS record. */\n publish(...args: CommandArgument[]): Promise<unknown>;\n /** Atomically replace a value only when its last-read bytes are still current. */\n compareAndSet(key: string, expected: Buffer | undefined, value: Buffer): Promise<boolean>;\n}\n\ninterface RequiredLockOptions {\n readonly lockRetryMs: number;\n readonly lockTtlMs: number;\n readonly lockWaitMs: number;\n}\n\nconst DEFAULT_LOCK_OPTIONS: RequiredLockOptions = {\n lockRetryMs: 10,\n lockTtlMs: 300_000,\n lockWaitMs: 30_000\n};\n\nexport function normalizeKeyPrefix(value: string, defaultValue: string): string {\n const prefix = value.length === 0 ? defaultValue : value;\n if (prefix.includes(\"\\0\")) throw new TypeError(\"keyPrefix must not contain NUL bytes\");\n const normalized = prefix.replace(/:+$/u, \"\");\n if (normalized.length === 0) throw new TypeError(\"keyPrefix must contain a character other than ':'\");\n return normalized;\n}\n\nexport function positiveInteger(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized <= 0) {\n throw new TypeError(`${name} must be a positive safe integer`);\n }\n return normalized;\n}\n\nexport function nonNegativeInteger(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized < 0) {\n throw new TypeError(`${name} must be a non-negative safe integer`);\n }\n return normalized;\n}\n\nexport function textResponse(value: unknown, name: string): string {\n if (typeof value === \"string\") return value;\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value).toString(\"utf8\");\n throw new TypeError(`FerricStore returned an invalid ${name}`);\n}\n\nexport function arrayResponse(value: unknown, name: string): unknown[] {\n if (!Array.isArray(value)) throw new TypeError(`FerricStore returned an invalid ${name}`);\n return value;\n}\n\nexport function integerResponse(value: unknown, name: string): number {\n const parsed = typeof value === \"number\" ? value : Number(textResponse(value, name));\n if (!Number.isSafeInteger(parsed)) throw new TypeError(`FerricStore returned an invalid ${name}`);\n return parsed;\n}\n\nexport async function executeCommands(\n client: FerricStoreCommandClient,\n commands: readonly Command[]\n): Promise<unknown[]> {\n if (commands.length === 0) return [];\n if (client.pipeline != null) return await client.pipeline(commands);\n return await Promise.all(commands.map(async (command) => await client.command(...command)));\n}\n\nexport async function readAtomicValue(\n client: FerricStoreCommandClient,\n key: string,\n name: string\n): Promise<Buffer | undefined> {\n const value = await client.command(\"GET\", key);\n if (value == null) return undefined;\n if (typeof value === \"string\") return Buffer.from(value, \"utf8\");\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value);\n throw new TypeError(`FerricStore returned a non-binary ${name}`);\n}\n\nexport async function compareAndSetAtomicValue(\n client: FerricStoreCommandClient,\n key: string,\n expected: Buffer | undefined,\n value: Buffer\n): Promise<boolean> {\n if (expected == null) {\n const response = await client.command(\"SET\", key, value, \"NX\");\n if (response == null || response === false) return false;\n if (response === true) return true;\n return textResponse(response, \"SET NX response\").toUpperCase() === \"OK\";\n }\n const response = await client.command(\"CAS\", key, expected, value);\n if (response == null || response === false) return false;\n if (response === true) return true;\n return integerResponse(response, \"CAS response\") === 1;\n}\n\nexport async function withMutationLocks<T>(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n operation: (lease: FerricStoreMutationLease) => Promise<T>,\n options: FerricStoreLockOptions = {}\n): Promise<T> {\n const orderedKeys = [...new Set(keys)].sort();\n if (orderedKeys.length === 0) {\n const signal = new AbortController().signal;\n return await operation({\n signal,\n assertOwned: () => undefined,\n publish: async (...args) => await additiveCommand(client, args),\n compareAndSet: async (key, expected, value) =>\n await compareAndSetAtomicValue(client, key, expected, value)\n });\n }\n\n const normalized: RequiredLockOptions = {\n lockRetryMs: positiveInteger(options.lockRetryMs, DEFAULT_LOCK_OPTIONS.lockRetryMs, \"lockRetryMs\"),\n lockTtlMs: positiveInteger(options.lockTtlMs, DEFAULT_LOCK_OPTIONS.lockTtlMs, \"lockTtlMs\"),\n lockWaitMs: nonNegativeInteger(options.lockWaitMs, DEFAULT_LOCK_OPTIONS.lockWaitMs, \"lockWaitMs\")\n };\n if (normalized.lockRetryMs >= normalized.lockTtlMs) {\n throw new TypeError(\"lockRetryMs must be less than lockTtlMs\");\n }\n const owner = randomUUID();\n const acquired: string[] = [];\n const deadline = performance.now() + normalized.lockWaitMs;\n let primaryError: unknown;\n let heartbeatError: unknown;\n let releaseError: unknown;\n let result: T | undefined;\n let operationCompleted = false;\n let conditionalCommitCompleted = false;\n const heartbeatAbort = new AbortController();\n const ownershipAbort = new AbortController();\n const lastExtended = new Map<string, number>();\n const loseOwnership = (error: unknown): Error => {\n const normalizedError = errorObject(error);\n heartbeatError ??= normalizedError;\n if (!ownershipAbort.signal.aborted) ownershipAbort.abort(normalizedError);\n return normalizedError;\n };\n const assertOwned = (): void => {\n if (heartbeatError != null) throw errorObject(heartbeatError);\n if (ownershipAbort.signal.aborted) throw errorObject(ownershipAbort.signal.reason);\n };\n const renewOwned = async (): Promise<void> => {\n assertOwned();\n for (const key of acquired) {\n try {\n const response = await client.command(\"EXTEND\", key, owner, normalized.lockTtlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n throw new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`);\n }\n lastExtended.set(key, performance.now());\n } catch (error) {\n throw loseOwnership(new Error(\n `could not validate FerricStore lock ${JSON.stringify(key)} before mutating data`,\n { cause: error }\n ));\n }\n }\n assertOwned();\n };\n const lease: FerricStoreMutationLease = {\n signal: ownershipAbort.signal,\n assertOwned,\n publish: async (...args) => {\n await renewOwned();\n const response = await additiveCommand(client, args);\n assertOwned();\n return response;\n },\n compareAndSet: async (key, expected, value) => {\n await renewOwned();\n const committed = await compareAndSetAtomicValue(client, key, expected, value);\n if (committed) conditionalCommitCompleted = true;\n else assertOwned();\n return committed;\n }\n };\n\n try {\n for (const key of orderedKeys) {\n while (!(await tryAcquireLock(client, key, owner, normalized.lockTtlMs))) {\n if (performance.now() >= deadline) {\n throw new Error(`timed out acquiring FerricStore lock ${JSON.stringify(key)}`);\n }\n await extendAcquiredLocks(client, acquired, owner, normalized.lockTtlMs);\n await delay(normalized.lockRetryMs);\n }\n acquired.push(key);\n }\n await extendAcquiredLocks(client, acquired, owner, normalized.lockTtlMs);\n for (const key of acquired) lastExtended.set(key, performance.now());\n\n const heartbeat = renewLocks(\n client,\n acquired,\n owner,\n normalized.lockTtlMs,\n lastExtended,\n heartbeatAbort.signal,\n (error) => {\n loseOwnership(error);\n }\n );\n try {\n result = await operation(lease);\n operationCompleted = true;\n } catch (error) {\n primaryError = error;\n } finally {\n heartbeatAbort.abort();\n await heartbeat;\n }\n } catch (error) {\n primaryError ??= error;\n } finally {\n heartbeatAbort.abort();\n for (const key of acquired.reverse()) {\n try {\n await client.command(\"UNLOCK\", key, owner);\n } catch (error) {\n releaseError ??= error;\n }\n }\n }\n if (primaryError != null) throw errorObject(primaryError);\n if (heartbeatError != null && !conditionalCommitCompleted) throw errorObject(heartbeatError);\n if (releaseError != null && !(heartbeatError != null && conditionalCommitCompleted)) {\n throw errorObject(releaseError);\n }\n if (!operationCompleted) throw new Error(\"FerricStore mutation did not complete\");\n return result as T;\n}\n\nasync function additiveCommand(\n client: FerricStoreCommandClient,\n args: readonly CommandArgument[]\n): Promise<unknown> {\n const rawName = args[0];\n const name = typeof rawName === \"string\"\n ? rawName.toUpperCase()\n : Buffer.isBuffer(rawName) || rawName instanceof Uint8Array\n ? Buffer.from(rawName).toString(\"utf8\").toUpperCase()\n : \"\";\n if (name !== \"SADD\" && name !== \"ZADD\") {\n throw new TypeError(\"FerricStore mutation leases only publish add-only SADD or ZADD indexes\");\n }\n if (name === \"ZADD\" && (\n args.length < 4 ||\n args.length % 2 !== 0 ||\n args.slice(2).some((value, index) => index % 2 === 0 && Number(value) !== 0)\n )) {\n throw new TypeError(\"FerricStore mutation leases only publish zero-score ZADD indexes\");\n }\n return await client.command(...args);\n}\n\nasync function extendAcquiredLocks(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n owner: string,\n ttlMs: number\n): Promise<void> {\n for (const key of keys) {\n const response = await client.command(\"EXTEND\", key, owner, ttlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n throw new Error(`lost FerricStore lock ${JSON.stringify(key)} before mutating data`);\n }\n }\n}\n\nasync function tryAcquireLock(\n client: FerricStoreCommandClient,\n key: string,\n owner: string,\n ttlMs: number\n): Promise<boolean> {\n try {\n const response = await client.command(\"LOCK\", key, owner, ttlMs);\n return response === true || response === \"OK\" || Buffer.isBuffer(response) && response.equals(Buffer.from(\"OK\"));\n } catch (error) {\n if (error instanceof LockHeldError) return false;\n throw error;\n }\n}\n\nasync function renewLocks(\n client: FerricStoreCommandClient,\n keys: readonly string[],\n owner: string,\n ttlMs: number,\n lastExtended: Map<string, number>,\n signal: AbortSignal,\n onError: (error: unknown) => void\n): Promise<void> {\n const intervalMs = Math.max(Math.floor(ttlMs / 3), 1);\n const retryMs = Math.min(Math.max(Math.floor(intervalMs / 10), 1), 1_000);\n let waitMs = intervalMs;\n while (!signal.aborted) {\n try {\n await delay(waitMs, undefined, { signal });\n } catch (error) {\n if (signal.aborted) return;\n onError(error);\n return;\n }\n const now = performance.now();\n let retry = false;\n for (const key of keys) {\n try {\n const response = await client.command(\"EXTEND\", key, owner, ttlMs);\n if (integerResponse(response, \"EXTEND response\") !== 1) {\n onError(new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`));\n return;\n }\n lastExtended.set(key, now);\n } catch (error) {\n if (now - (lastExtended.get(key) ?? 0) >= ttlMs) {\n onError(new Error(`lost FerricStore lock ${JSON.stringify(key)} while mutating data`, { cause: error }));\n return;\n }\n retry = true;\n }\n }\n waitMs = retry ? retryMs : intervalMs;\n }\n}\n\nfunction errorObject(value: unknown): Error {\n return value instanceof Error ? value : new Error(\"FerricStore mutation failed\", { cause: value });\n}\n","export class FerricStoreError extends Error {\n readonly code: string = \"ferricstore_error\";\n readonly raw: unknown;\n readonly retryable: boolean | undefined;\n readonly safeToRetry: boolean | undefined;\n readonly retryAfterMs: number | undefined;\n\n constructor(message: string, options: {\n raw?: unknown;\n cause?: unknown;\n retryable?: boolean;\n safeToRetry?: boolean;\n retryAfterMs?: number;\n } = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.raw = options.raw;\n this.retryable = options.retryable ?? structuredBooleanField(options.raw, \"retryable\");\n this.safeToRetry = options.safeToRetry ?? structuredBooleanField(options.raw, \"safe_to_retry\");\n this.retryAfterMs = options.retryAfterMs ?? structuredIntegerField(options.raw, \"retry_after_ms\");\n }\n}\n\nexport class HTTPTransportError extends FerricStoreError {\n override readonly code = \"http_transport\";\n readonly statusCode: number | undefined;\n\n constructor(message: string, options: ConstructorParameters<typeof FerricStoreError>[1] & {\n statusCode?: number;\n } = {}) {\n super(message, options);\n this.statusCode = options.statusCode;\n }\n}\n\nexport type RequestDisposition = \"unsent\" | \"possibly_sent\";\n/** @deprecated Use RequestDisposition; retained for source compatibility. */\nexport type ConnectionRequestDisposition = RequestDisposition;\n\n/** Connection closure annotated with whether the current request may have reached the server. */\nexport class ConnectionClosedError extends FerricStoreError {\n override readonly code = \"connection_closed\";\n readonly requestDisposition: RequestDisposition;\n\n constructor(\n requestDisposition: RequestDisposition,\n options: { raw?: unknown; cause?: unknown; message?: string } = {}\n ) {\n super(\n options.message ?? (requestDisposition === \"unsent\"\n ? \"FerricStore connection is closed\"\n : \"FerricStore connection closed\"),\n options\n );\n this.requestDisposition = requestDisposition;\n }\n}\n\n/** Request timeout annotated with whether the request may have reached the server. */\nexport class RequestTimeoutError extends FerricStoreError {\n override readonly code = \"request_timeout\";\n readonly requestDisposition: RequestDisposition;\n readonly timeoutMs: number;\n\n constructor(\n timeoutMs: number,\n requestDisposition: RequestDisposition,\n options: { raw?: unknown; cause?: unknown } = {}\n ) {\n super(`FerricStore request timed out after ${timeoutMs}ms`, options);\n this.requestDisposition = requestDisposition;\n this.timeoutMs = timeoutMs;\n }\n}\n\nexport class FlowNotFoundError extends FerricStoreError {\n override readonly code = \"flow_not_found\";\n}\n\nexport class FlowWrongStateError extends FerricStoreError {\n override readonly code = \"flow_wrong_state\";\n}\n\nexport class StaleLeaseError extends FerricStoreError {\n override readonly code = \"stale_lease\";\n}\n\n/** FLOW.POLICY.SET expected_generation did not match the stored generation. */\nexport class StalePolicyGenerationError extends FerricStoreError {\n override readonly code = \"stale_policy_generation\";\n}\n\nexport class FlowAlreadyExistsError extends FerricStoreError {\n override readonly code = \"flow_already_exists\";\n}\n\nexport class LockHeldError extends FerricStoreError {\n override readonly code = \"lock_held\";\n}\n\nexport class LockNotOwnedError extends FerricStoreError {\n override readonly code = \"lock_not_owned\";\n}\n\nexport class InvalidCommandError extends FerricStoreError {\n override readonly code = \"invalid_command\";\n}\n\nexport class OverloadedError extends FerricStoreError {\n override readonly code = \"overloaded\";\n readonly reason: string | undefined;\n\n constructor(\n message: string,\n options: {\n raw?: unknown;\n cause?: unknown;\n retryAfterMs?: number;\n reason?: string;\n retryable?: boolean;\n safeToRetry?: boolean;\n } = {}\n ) {\n const local = options.raw == null;\n super(message, {\n ...options,\n retryable: options.retryable ?? (local ? true : undefined),\n safeToRetry: options.safeToRetry ?? (local ? true : undefined)\n });\n this.reason = options.reason;\n }\n}\n\n/** The contacted endpoint cannot serve this route and topology should be refreshed. */\nexport class RerouteError extends FerricStoreError {\n override readonly code = \"reroute\";\n}\n\nconst OVERLOAD_CODES = new Set([\n \"backpressure\",\n \"busy\",\n \"flow_control_window_exhausted\",\n \"lane_queue_full\",\n \"overloaded\"\n]);\n\nexport function classifyServerError(\n message: string,\n raw?: unknown,\n cause?: unknown,\n status?: number | string\n): FerricStoreError {\n const lower = message.toLowerCase();\n const structuredCode = structuredStringField(raw, \"code\");\n const code = structuredCode?.toLowerCase();\n const retry = {\n retryable: structuredBooleanField(raw, \"retryable\"),\n safeToRetry: structuredBooleanField(raw, \"safe_to_retry\"),\n retryAfterMs: structuredIntegerField(raw, \"retry_after_ms\") ?? intField(lower, \"retry_after_ms\")\n };\n\n if (isRerouteStatus(status) || code === \"reroute\") {\n return new RerouteError(message, { cause, raw, ...definedRetryMetadata(retry) });\n }\n if (isBusyStatus(status) || isOverloadCode(structuredCode) || overloadMessage(lower)) {\n return new OverloadedError(message, {\n cause,\n raw,\n ...definedRetryMetadata(retry),\n reason: structuredStringField(raw, \"reason\") ?? structuredCode ?? stringField(lower, \"reason\"),\n retryAfterMs: retry.retryAfterMs\n });\n }\n if (code === \"flow_already_exists\" || (lower.includes(\"flow\") && lower.includes(\"already exists\"))) {\n return new FlowAlreadyExistsError(message, { cause, raw });\n }\n if (lower.includes(\"flow wrong state\") || code === \"flow_wrong_state\") {\n return new FlowWrongStateError(message, { cause, raw });\n }\n if (\n code === \"stale_lease\"\n || code === \"stale_flow_lease\"\n || lower.includes(\"stale flow lease\")\n || lower.includes(\"stale lease\")\n || lower.includes(\"stale token\")\n ) {\n return new StaleLeaseError(message, { cause, raw });\n }\n if (\n code === \"stale_generation\"\n || code === \"stale_policy_generation\"\n || code === \"stale_flow_policy_generation\"\n || lower.includes(\"stale flow policy generation\")\n || lower.includes(\"stale policy generation\")\n ) {\n return new StalePolicyGenerationError(message, { cause, raw });\n }\n if (\n code === \"flow_not_found\"\n || (lower.includes(\"flow\") && (lower.includes(\"not found\") || lower.includes(\"does not exist\")))\n ) {\n return new FlowNotFoundError(message, { cause, raw });\n }\n if (code === \"lock_held\" || lower.includes(\"lock is held\") || lower.includes(\"held by another owner\")) {\n return new LockHeldError(message, { cause, raw });\n }\n if (code === \"lock_not_owned\" || lower.includes(\"not the lock owner\") || lower.includes(\"caller is not the lock owner\")) {\n return new LockNotOwnedError(message, { cause, raw });\n }\n if (code === \"invalid_command\" || lower.includes(\"wrong number of arguments\") || lower.includes(\"syntax error\")) {\n return new InvalidCommandError(message, { cause, raw });\n }\n\n return new FerricStoreError(message, { cause, raw, ...definedRetryMetadata(retry) });\n}\n\nexport function mapException(error: unknown): unknown {\n if (error instanceof FerricStoreError) {\n return error;\n }\n\n if (!(error instanceof Error)) {\n return error;\n }\n\n const message = error.message;\n const serverLike =\n error.name === \"ResponseError\" ||\n message.startsWith(\"ERR \") ||\n message.startsWith(\"WRONGTYPE \") ||\n message.startsWith(\"DISTLOCK \");\n\n if (!serverLike) {\n return error;\n }\n\n return classifyServerError(message, error, error);\n}\n\nfunction intField(message: string, name: string): number | undefined {\n const match = new RegExp(`\\\\b${name}=([0-9]+)\\\\b`).exec(message);\n return match?.[1] == null ? undefined : nonNegativeSafeIntegerText(match[1]);\n}\n\nfunction isBusyStatus(status: number | string | undefined): boolean {\n return status === 4 || (typeof status === \"string\" && (status === \"4\" || status.toLowerCase() === \"busy\"));\n}\n\nfunction isRerouteStatus(status: number | string | undefined): boolean {\n return status === 5 || (typeof status === \"string\" && (status === \"5\" || status.toLowerCase() === \"reroute\"));\n}\n\nfunction isOverloadCode(code: string | undefined): boolean {\n return code != null && OVERLOAD_CODES.has(code.toLowerCase());\n}\n\nfunction overloadMessage(message: string): boolean {\n return /\\boverloaded\\b/u.test(message) || /(?:^|\\s)busy(?:\\s|:|$)/u.test(message);\n}\n\nfunction structuredIntegerField(raw: unknown, name: string): number | undefined {\n const value = structuredField(raw, name);\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n }\n if (typeof value === \"bigint\") {\n return value >= 0n && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n }\n const text = binaryText(value);\n return text == null ? undefined : nonNegativeSafeIntegerText(text);\n}\n\nfunction structuredBooleanField(raw: unknown, name: string): boolean | undefined {\n const value = structuredField(raw, name);\n if (typeof value === \"boolean\") return value;\n const text = binaryText(value)?.toLowerCase();\n if (text === \"true\" || text === \"1\") return true;\n if (text === \"false\" || text === \"0\") return false;\n return undefined;\n}\n\nfunction definedRetryMetadata(metadata: {\n readonly retryable?: boolean;\n readonly safeToRetry?: boolean;\n readonly retryAfterMs?: number;\n}): { retryable?: boolean; safeToRetry?: boolean; retryAfterMs?: number } {\n return {\n ...(metadata.retryable == null ? {} : { retryable: metadata.retryable }),\n ...(metadata.safeToRetry == null ? {} : { safeToRetry: metadata.safeToRetry }),\n ...(metadata.retryAfterMs == null ? {} : { retryAfterMs: metadata.retryAfterMs })\n };\n}\n\nfunction nonNegativeSafeIntegerText(value: string): number | undefined {\n if (!/^[0-9]+$/u.test(value)) return undefined;\n const parsed = Number.parseInt(value, 10);\n return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction structuredStringField(raw: unknown, name: string): string | undefined {\n return binaryText(structuredField(raw, name));\n}\n\nfunction structuredField(raw: unknown, name: string): unknown {\n if (raw instanceof Map) {\n if (raw.has(name)) return raw.get(name);\n for (const [key, value] of raw.entries()) {\n if (binaryText(key) === name) return value;\n }\n return undefined;\n }\n if (typeof raw === \"object\" && raw != null && Object.hasOwn(raw, name)) {\n return (raw as Record<string, unknown>)[name];\n }\n return undefined;\n}\n\nfunction binaryText(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value).toString(\"utf8\");\n return undefined;\n}\n\nfunction stringField(message: string, name: string): string | undefined {\n const match = new RegExp(`\\\\b${name}=([a-z0-9_:-]+)\\\\b`).exec(message);\n return match?.[1];\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n BaseStore,\n type GetOperation,\n type Item,\n type ListNamespacesOperation,\n type MatchCondition,\n type Operation,\n type OperationResults,\n type PutOperation,\n type SearchOperation\n} from \"@langchain/langgraph\";\n\nimport {\n arrayResponse,\n normalizeKeyPrefix,\n positiveInteger,\n readAtomicValue,\n type FerricStoreCommandClient,\n type FerricStoreLockOptions,\n type FerricStoreMutationLease,\n withMutationLocks\n} from \"../agent-persistence/durability.js\";\n\nconst FORMAT_VERSION = 1;\nconst ITEM_FIELD_PREFIX = \"item:\";\nconst DELETED_ITEM = Buffer.from(\"ferricstore:langgraph:item:deleted:v2\", \"utf8\");\ntype SearchItem = Item & { score?: number };\n\ninterface StoredItem {\n readonly createdAt: string;\n readonly formatVersion: typeof FORMAT_VERSION;\n readonly key: string;\n readonly namespace: string[];\n readonly updatedAt: string;\n readonly value: Record<string, unknown>;\n}\n\nexport interface FerricStoreStoreOptions extends FerricStoreLockOptions {\n /** FerricStore key prefix. Defaults to `langgraph:store`. */\n keyPrefix?: string;\n /** Number of catalog entries read per page. Defaults to 256. */\n scanCount?: number;\n}\n\n/**\n * LangGraph.js long-term memory store backed by FerricStore.\n *\n * It implements hierarchical namespaces, exact/comparison filters, ordered\n * pagination, batching, CAS-protected item commits, and append-only discovery\n * indexes. Vector search is deliberately rejected until a semantic index is\n * configured rather than silently returning an unranked result.\n */\nexport class FerricStoreStore extends BaseStore {\n readonly client: FerricStoreCommandClient;\n readonly keyPrefix: string;\n readonly scanCount: number;\n private readonly lockOptions: FerricStoreLockOptions;\n\n constructor(client: FerricStoreCommandClient, options: FerricStoreStoreOptions = {}) {\n super();\n this.client = client;\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix ?? \"langgraph:store\", \"langgraph:store\");\n this.scanCount = positiveInteger(options.scanCount, 256, \"scanCount\");\n this.lockOptions = {\n lockRetryMs: options.lockRetryMs,\n lockTtlMs: options.lockTtlMs,\n lockWaitMs: options.lockWaitMs\n };\n }\n\n async batch<Op extends Operation[]>(operations: Op): Promise<OperationResults<Op>> {\n if (!Array.isArray(operations)) throw new TypeError(\"operations must be an array\");\n const lockKeys = operations\n .filter(isPutOperation)\n .map((operation) => {\n validatePut(operation);\n return this.itemLockKey(operation.namespace, operation.key);\n });\n\n return await withMutationLocks(this.client, lockKeys, async (lease) => {\n const results: unknown[] = [];\n const puts = new Map<string, PutOperation>();\n for (const operation of operations) {\n if (isPutOperation(operation)) {\n puts.set(JSON.stringify([operation.namespace, operation.key]), operation);\n results.push(undefined);\n } else if (isSearchOperation(operation)) {\n results.push(await this.searchOperation(operation));\n } else if (isGetOperation(operation)) {\n results.push(await this.getOperation(operation));\n } else if (isListNamespacesOperation(operation)) {\n results.push(await this.listNamespacesOperation(operation));\n } else {\n throw new TypeError(\"unsupported LangGraph store operation\");\n }\n }\n for (const operation of puts.values()) await this.putOperation(operation, lease);\n return results as OperationResults<Op>;\n }, this.lockOptions);\n }\n\n private catalogKey(): string {\n return `${this.keyPrefix}:namespaces`;\n }\n\n private namespaceKey(namespace: readonly string[]): string {\n return `${this.keyPrefix}:{lgs:${sha256(namespaceIdentity(namespace))}}:namespace`;\n }\n\n private itemLockKey(namespace: readonly string[], key: string): string {\n return `${this.keyPrefix}:{lgsi:${itemIdentityDigest(namespace, key)}}:mutation-lock`;\n }\n\n private itemDataKey(namespace: readonly string[], key: string): string {\n return `${this.keyPrefix}:{lgsi:${itemIdentityDigest(namespace, key)}}:atomic-item`;\n }\n\n private async getOperation(operation: GetOperation): Promise<Item | null> {\n validateNamespace(operation.namespace);\n if (typeof operation.key !== \"string\") throw new TypeError(\"store key must be text\");\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n return snapshot.record == null ? null : itemFromRecord(snapshot.record);\n }\n\n private async putOperation(operation: PutOperation, lease: FerricStoreMutationLease): Promise<void> {\n validatePut(operation);\n const dataKey = this.itemDataKey(operation.namespace, operation.key);\n const locator = catalogMember(operation.namespace, operation.key);\n if (operation.value == null) {\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n if (snapshot.expected?.equals(DELETED_ITEM) === true) return;\n if (await lease.compareAndSet(dataKey, snapshot.expected, DELETED_ITEM)) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph store deletion did not converge\");\n }\n const storedValue = snapshotJsonValue(operation.value);\n // The catalog is append-only. Readers validate the current CAS-protected\n // item, so a stale or interrupted publication cannot hide a newer value.\n await lease.publish(\"ZADD\", this.catalogKey(), 0, locator);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n const snapshot = await this.readItemSnapshot(operation.namespace, operation.key);\n const now = new Date().toISOString();\n const record: StoredItem = {\n createdAt: snapshot.record?.createdAt ?? now,\n formatVersion: FORMAT_VERSION,\n key: operation.key,\n namespace: [...operation.namespace],\n updatedAt: now,\n value: storedValue\n };\n if (await lease.compareAndSet(dataKey, snapshot.expected, encodeItem(record))) return;\n }\n throw new Error(\"concurrent FerricStore LangGraph store mutation did not converge\");\n }\n\n private async searchOperation(operation: SearchOperation): Promise<SearchItem[]> {\n validateNamespacePrefix(operation.namespacePrefix);\n if (operation.query != null) {\n throw new Error(\n \"FerricStoreStore semantic query search is not configured; use metadata filters or a vector-enabled store\"\n );\n }\n const limit = normalizePageNumber(operation.limit, 10, \"search limit\");\n const offset = normalizePageNumber(operation.offset, 0, \"search offset\");\n if (limit === 0) return [];\n const matches: SearchItem[] = [];\n for await (const locator of this.catalogLocators()) {\n if (!startsWithNamespace(locator.namespace, operation.namespacePrefix)) continue;\n const item = await this.readCatalogItem(locator.namespace, locator.key);\n if (item == null || !matchesFilter(item.value, operation.filter)) continue;\n matches.push(item);\n if (matches.length >= offset + limit) break;\n }\n return matches.slice(offset, offset + limit);\n }\n\n private async listNamespacesOperation(operation: ListNamespacesOperation): Promise<string[][]> {\n const limit = normalizePageNumber(operation.limit, 100, \"namespace limit\");\n const offset = normalizePageNumber(operation.offset, 0, \"namespace offset\");\n const maxDepth = operation.maxDepth == null\n ? undefined\n : positiveInteger(operation.maxDepth, operation.maxDepth, \"maxDepth\");\n if (limit === 0) return [];\n const namespaces = new Map<string, string[]>();\n for await (const locator of this.catalogLocators()) {\n const item = await this.readCatalogItem(locator.namespace, locator.key);\n if (item == null) continue;\n if (!matchesConditions(item.namespace, operation.matchConditions)) continue;\n const namespace = maxDepth == null ? item.namespace : item.namespace.slice(0, maxDepth);\n namespaces.set(JSON.stringify(namespace), namespace);\n }\n return [...namespaces.values()]\n .sort(compareNamespaces)\n .slice(offset, offset + limit);\n }\n\n private async readCatalogItem(namespace: string[], key: string): Promise<Item | null> {\n const snapshot = await this.readItemSnapshot(namespace, key);\n return snapshot.record == null ? null : itemFromRecord(snapshot.record);\n }\n\n private async readItemSnapshot(\n namespace: readonly string[],\n key: string\n ): Promise<{ expected: Buffer | undefined; record: StoredItem | null }> {\n const expected = await readAtomicValue(\n this.client,\n this.itemDataKey(namespace, key),\n \"LangGraph atomic store item\"\n );\n if (expected != null) {\n return {\n expected,\n record: expected.equals(DELETED_ITEM) ? null : decodeItemRecord(expected)\n };\n }\n const legacy = await this.client.command(\"HGET\", this.namespaceKey(namespace), itemField(key));\n return { expected, record: legacy == null ? null : decodeItemRecord(legacy) };\n }\n\n private async *catalogLocators(): AsyncGenerator<{ key: string; namespace: string[] }> {\n let offset = 0;\n while (true) {\n const values = arrayResponse(\n await this.client.command(\"ZRANGE\", this.catalogKey(), offset, offset + this.scanCount - 1),\n \"LangGraph store catalog response\"\n );\n if (values.length === 0) return;\n for (const value of values) yield decodeCatalogMember(value);\n offset += values.length;\n if (values.length < this.scanCount) return;\n }\n }\n}\n\nfunction isPutOperation(operation: Operation): operation is PutOperation {\n return \"namespace\" in operation && \"key\" in operation && \"value\" in operation;\n}\n\nfunction isGetOperation(operation: Operation): operation is GetOperation {\n return \"namespace\" in operation && \"key\" in operation && !(\"value\" in operation);\n}\n\nfunction isSearchOperation(operation: Operation): operation is SearchOperation {\n return \"namespacePrefix\" in operation;\n}\n\nfunction isListNamespacesOperation(operation: Operation): operation is ListNamespacesOperation {\n return !(\"namespace\" in operation) && !(\"namespacePrefix\" in operation);\n}\n\nfunction validatePut(operation: PutOperation): void {\n validateNamespace(operation.namespace);\n if (typeof operation.key !== \"string\") throw new TypeError(\"store key must be text\");\n if (operation.value == null) return;\n if (typeof operation.value !== \"object\" || Array.isArray(operation.value)) {\n throw new TypeError(\"LangGraph store values must be JSON objects\");\n }\n validateJson(operation.value, new WeakSet());\n}\n\nfunction validateNamespace(namespace: readonly string[]): void {\n if (!Array.isArray(namespace) || namespace.length === 0) {\n throw new Error(\"namespace cannot be empty\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\" || label.length === 0 || label.includes(\".\")) {\n throw new Error(\"namespace labels must be non-empty strings without periods\");\n }\n }\n if (namespace[0] === \"langgraph\") throw new Error('root namespace label cannot be \"langgraph\"');\n}\n\nfunction validateNamespacePrefix(namespace: readonly string[]): void {\n if (!Array.isArray(namespace)) throw new TypeError(\"namespacePrefix must be an array\");\n if (namespace.length > 0) validateNamespace(namespace);\n}\n\nfunction validateJson(value: unknown, ancestors: WeakSet<object>): void {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (value === undefined) throw new TypeError(\"LangGraph store values must not contain undefined\");\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(\"LangGraph store numbers must be finite\");\n return;\n }\n if (typeof value !== \"object\") throw new TypeError(\"LangGraph store values must be JSON serializable\");\n if (ancestors.has(value)) throw new TypeError(\"LangGraph store values must not be cyclic\");\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const keys = Reflect.ownKeys(value);\n if (\n keys.length !== value.length + 1 ||\n keys.some((key) => typeof key !== \"string\" || key !== \"length\" && !isArrayIndex(key, value.length))\n ) {\n throw new TypeError(\"LangGraph store arrays must not be sparse or customized\");\n }\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (descriptor == null || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"LangGraph store arrays contain an unsupported item\");\n }\n validateJson(descriptor.value as unknown, ancestors);\n }\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"LangGraph store values must contain only JSON objects\");\n }\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== \"string\") throw new TypeError(\"LangGraph store objects must not have symbol keys\");\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor == null || !descriptor.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\"LangGraph store objects contain an unsupported property\");\n }\n validateJson(descriptor.value as unknown, ancestors);\n }\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotJsonValue(value: Record<string, unknown>): Record<string, unknown> {\n validateJson(value, new WeakSet());\n return JSON.parse(JSON.stringify(value)) as Record<string, unknown>;\n}\n\nfunction encodeItem(record: StoredItem): Buffer {\n return Buffer.from(JSON.stringify(record), \"utf8\");\n}\n\nfunction itemFromRecord(record: StoredItem): Item {\n return {\n createdAt: new Date(record.createdAt),\n key: record.key,\n namespace: [...record.namespace],\n updatedAt: new Date(record.updatedAt),\n value: record.value\n };\n}\n\nfunction itemIdentityDigest(namespace: readonly string[], key: string): string {\n const keyBytes = Buffer.from(key, \"utf8\");\n return sha256(Buffer.concat([\n namespaceIdentity(namespace),\n uint64(keyBytes.length),\n keyBytes\n ]));\n}\n\nfunction decodeItemRecord(value: unknown): StoredItem {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary LangGraph store item\");\n }\n const text = typeof value === \"string\" ? value : Buffer.from(value).toString(\"utf8\");\n let record: unknown;\n try {\n record = JSON.parse(text);\n } catch (error) {\n throw new Error(\"invalid FerricStore LangGraph store item\", { cause: error });\n }\n if (\n record == null ||\n typeof record !== \"object\" ||\n (record as Partial<StoredItem>).formatVersion !== FORMAT_VERSION ||\n typeof (record as Partial<StoredItem>).key !== \"string\" ||\n !Array.isArray((record as Partial<StoredItem>).namespace) ||\n typeof (record as Partial<StoredItem>).createdAt !== \"string\" ||\n typeof (record as Partial<StoredItem>).updatedAt !== \"string\" ||\n (record as Partial<StoredItem>).value == null ||\n typeof (record as Partial<StoredItem>).value !== \"object\"\n ) {\n throw new Error(\"unsupported or corrupt FerricStore LangGraph store item\");\n }\n return record as StoredItem;\n}\n\nfunction matchesFilter(value: Record<string, unknown>, filter: Record<string, unknown> | undefined): boolean {\n return filter == null || Object.entries(filter).every(([key, expected]) => compareValue(value[key], expected));\n}\n\nfunction compareValue(value: unknown, expected: unknown): boolean {\n if (expected != null && typeof expected === \"object\" && !Array.isArray(expected)) {\n const entries = Object.entries(expected);\n if (entries.length > 0 && entries.every(([key]) => FILTER_OPERATORS.has(key))) {\n return entries.every(([operator, operand]) => applyOperator(value, operator, operand));\n }\n return value != null && typeof value === \"object\" && !Array.isArray(value) &&\n entries.every(([key, nested]) => compareValue((value as Record<string, unknown>)[key], nested));\n }\n if (Array.isArray(expected)) {\n return Array.isArray(value) && value.length === expected.length &&\n value.every((item, index) => compareValue(item, expected[index]));\n }\n return Object.is(value, expected);\n}\n\nfunction applyOperator(value: unknown, operator: string, expected: unknown): boolean {\n switch (operator) {\n case \"$eq\": return Object.is(value, expected);\n case \"$ne\": return !Object.is(value, expected);\n case \"$gt\": return comparable(value, expected, (left, right) => left > right);\n case \"$gte\": return comparable(value, expected, (left, right) => left >= right);\n case \"$in\": return Array.isArray(expected) && expected.some((item) => Object.is(item, value));\n case \"$lt\": return comparable(value, expected, (left, right) => left < right);\n case \"$lte\": return comparable(value, expected, (left, right) => left <= right);\n case \"$nin\": return !Array.isArray(expected) || expected.every((item) => !Object.is(item, value));\n default: throw new Error(`unsupported filter operator: ${operator}`);\n }\n}\n\nfunction comparable(\n value: unknown,\n expected: unknown,\n compare: (left: number, right: number) => boolean\n): boolean {\n try {\n return compare(Number(value), Number(expected));\n } catch {\n return false;\n }\n}\n\nconst FILTER_OPERATORS = new Set([\"$eq\", \"$gt\", \"$gte\", \"$in\", \"$lt\", \"$lte\", \"$ne\", \"$nin\"]);\n\nfunction matchesConditions(namespace: string[], conditions: MatchCondition[] | undefined): boolean {\n return conditions == null || conditions.every((condition) => {\n if (namespace.length < condition.path.length) return false;\n const actual = condition.matchType === \"prefix\" ? namespace : [...namespace].reverse();\n const pattern = condition.matchType === \"prefix\" ? condition.path : [...condition.path].reverse();\n return pattern.every((component, index) => component === \"*\" || actual[index] === component);\n });\n}\n\nfunction startsWithNamespace(namespace: readonly string[], prefix: readonly string[]): boolean {\n return prefix.length <= namespace.length && prefix.every((value, index) => namespace[index] === value);\n}\n\nfunction normalizePageNumber(value: number | undefined, fallback: number, name: string): number {\n const normalized = value ?? fallback;\n if (!Number.isSafeInteger(normalized) || normalized < 0) {\n throw new TypeError(`${name} must be a non-negative safe integer`);\n }\n return normalized;\n}\n\nfunction compareNamespaces(left: readonly string[], right: readonly string[]): number {\n const count = Math.min(left.length, right.length);\n for (let index = 0; index < count; index += 1) {\n const compared = (left[index] ?? \"\").localeCompare(right[index] ?? \"\");\n if (compared !== 0) return compared;\n }\n return left.length - right.length;\n}\n\nfunction itemField(key: string): string {\n return `${ITEM_FIELD_PREFIX}${Buffer.from(key, \"utf8\").toString(\"base64url\")}`;\n}\n\nfunction namespaceIdentity(namespace: readonly string[]): Buffer {\n return Buffer.concat(namespace.flatMap((component) => {\n const payload = Buffer.from(component, \"utf8\");\n return [uint64(payload.length), payload];\n }));\n}\n\nfunction catalogMember(namespace: readonly string[], key: string): Buffer {\n return Buffer.concat([\n ...namespace.map(orderedText),\n Buffer.from([0, 0]),\n orderedText(key)\n ]);\n}\n\nfunction decodeCatalogMember(value: unknown): { key: string; namespace: string[] } {\n if (!(typeof value === \"string\" || Buffer.isBuffer(value) || value instanceof Uint8Array)) {\n throw new TypeError(\"FerricStore returned a non-binary LangGraph store locator\");\n }\n const bytes = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : Buffer.from(value);\n const namespace: string[] = [];\n let offset = 0;\n while (true) {\n if (bytes[offset] === 0 && bytes[offset + 1] === 0) {\n offset += 2;\n break;\n }\n const decoded = decodeOrderedText(bytes, offset);\n namespace.push(decoded.value);\n offset = decoded.offset;\n }\n const key = decodeOrderedText(bytes, offset);\n if (key.offset !== bytes.length || namespace.length === 0) {\n throw new Error(\"invalid FerricStore LangGraph store locator\");\n }\n return { key: key.value, namespace };\n}\n\nfunction orderedText(value: string): Buffer {\n const output: number[] = [];\n for (const byte of Buffer.from(value, \"utf8\")) {\n if (byte === 0) output.push(0, 255);\n else output.push(byte);\n }\n output.push(0, 0);\n return Buffer.from(output);\n}\n\nfunction decodeOrderedText(bytes: Buffer, start: number): { offset: number; value: string } {\n const output: number[] = [];\n let offset = start;\n while (offset < bytes.length) {\n const byte = bytes[offset];\n if (byte == null) throw new Error(\"truncated FerricStore LangGraph store locator\");\n offset += 1;\n if (byte !== 0) {\n output.push(byte);\n continue;\n }\n const escaped = bytes[offset];\n offset += 1;\n if (escaped === 0) return { offset, value: Buffer.from(output).toString(\"utf8\") };\n if (escaped === 255) output.push(0);\n else throw new Error(\"invalid FerricStore LangGraph store locator escape\");\n }\n throw new Error(\"unterminated FerricStore LangGraph store locator\");\n}\n\nfunction uint64(value: number): Buffer {\n const result = Buffer.allocUnsafe(8);\n result.writeBigUInt64BE(BigInt(value));\n return result;\n}\n\nfunction sha256(value: Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isArrayIndex(key: string, length: number): boolean {\n if (!/^(?:0|[1-9]\\d*)$/u.test(key)) return false;\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n","import { createHash } from \"node:crypto\";\n\nimport { Command } from \"@langchain/langgraph\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\n\nimport { complete, fail, transition, type Outcome } from \"../outcomes.js\";\n\nexport type LangGraphInvocationConfig = RunnableConfig & { context?: unknown } & Record<string, unknown>;\n\nexport interface InvokableLangGraph<Input = unknown, Output = unknown> {\n invoke(input: Input | Command | null, options?: LangGraphInvocationConfig): Promise<Output>;\n getState?(options: LangGraphInvocationConfig): Promise<unknown>;\n}\n\n/** Structural subset of WorkflowContext required by the LangGraph bridge. */\nexport interface FerricFlowHandlerContext {\n readonly id: string;\n readonly logicalState: string;\n readonly partitionKey?: string;\n readonly payload: unknown;\n readonly state: string;\n readonly type: string;\n readonly values: Record<string, unknown>;\n}\n\nexport class LangGraphFlowContext {\n readonly flow: FerricFlowHandlerContext;\n readonly threadId: string;\n readonly checkpointNs: string;\n\n constructor(flow: FerricFlowHandlerContext, threadId: string, checkpointNs: string) {\n this.flow = flow;\n this.threadId = threadId;\n this.checkpointNs = checkpointNs;\n }\n\n get id(): string { return this.flow.id; }\n get type(): string { return this.flow.type; }\n get state(): string { return this.flow.state; }\n get partitionKey(): string | undefined { return this.flow.partitionKey; }\n get payload(): unknown { return this.flow.payload; }\n get values(): Record<string, unknown> { return this.flow.values; }\n}\n\nexport class LangGraphFlowRun<Output = unknown> {\n readonly value: Output;\n readonly threadId: string;\n readonly checkpointNs: string;\n readonly interrupts: readonly unknown[];\n\n constructor(value: Output, threadId: string, checkpointNs: string, interrupts: readonly unknown[]) {\n this.value = value;\n this.threadId = threadId;\n this.checkpointNs = checkpointNs;\n this.interrupts = interrupts;\n }\n\n get interrupted(): boolean { return this.interrupts.length > 0; }\n\n get interruptValues(): readonly unknown[] {\n return this.interrupts.map((item) =>\n item != null && typeof item === \"object\" && \"value\" in item\n ? (item).value\n : item);\n }\n}\n\nexport type LangGraphOutcomeMapper<Output> = (\n run: LangGraphFlowRun<Output>,\n flow: FerricFlowHandlerContext\n) => Outcome | Promise<Outcome>;\n\nexport interface LangGraphFlowOptions<Input, Output> {\n input?: (flow: FerricFlowHandlerContext) => Input | Promise<Input>;\n threadId?: (flow: FerricFlowHandlerContext) => string | Promise<string>;\n checkpointNs?: string | ((flow: FerricFlowHandlerContext) => string | Promise<string>);\n config?: (flow: FerricFlowHandlerContext) => LangGraphInvocationConfig | undefined | Promise<LangGraphInvocationConfig | undefined>;\n context?: (flow: FerricFlowHandlerContext) => unknown | Promise<unknown>;\n onComplete?: LangGraphOutcomeMapper<Output>;\n onInterrupt?: LangGraphOutcomeMapper<Output>;\n interruptState?: string;\n /** Resume an already-checkpointed graph with null input. Defaults to true. */\n recoverExisting?: boolean;\n invokeOptions?: LangGraphInvocationConfig;\n}\n\n/** Bind a LangGraph.js invocation to a leased FerricFlow workflow handler. */\nexport class LangGraphFlow<Input = unknown, Output = unknown> {\n readonly graph: InvokableLangGraph<Input, Output>;\n private readonly options: LangGraphFlowOptions<Input, Output>;\n\n constructor(graph: InvokableLangGraph<Input, Output>, options: LangGraphFlowOptions<Input, Output> = {}) {\n if (options.onInterrupt != null && options.interruptState != null) {\n throw new TypeError(\"onInterrupt and interruptState are mutually exclusive\");\n }\n if (options.interruptState != null) requireText(options.interruptState, \"interruptState\");\n this.graph = graph;\n this.options = { ...options };\n }\n\n async config(flow: FerricFlowHandlerContext, graphContext?: unknown): Promise<LangGraphInvocationConfig> {\n const invokeOptions = this.options.invokeOptions ?? {};\n const additional = await this.options.config?.(flow) ?? {};\n const baseConfigurable = invokeOptions.configurable ?? {};\n if (typeof baseConfigurable !== \"object\" || Array.isArray(baseConfigurable)) {\n throw new TypeError(\"LangGraph invokeOptions configurable must be an object\");\n }\n const rawConfigurable = additional.configurable ?? {};\n if (typeof rawConfigurable !== \"object\" || Array.isArray(rawConfigurable)) {\n throw new TypeError(\"LangGraph config configurable must be an object\");\n }\n const baseMetadata = invokeOptions.metadata ?? {};\n if (typeof baseMetadata !== \"object\" || Array.isArray(baseMetadata)) {\n throw new TypeError(\"LangGraph invokeOptions metadata must be an object\");\n }\n const rawMetadata = additional.metadata ?? {};\n if (typeof rawMetadata !== \"object\" || Array.isArray(rawMetadata)) {\n throw new TypeError(\"LangGraph config metadata must be an object\");\n }\n const threadId = requireText(\n await (this.options.threadId?.(flow) ?? defaultThreadId(flow)),\n \"threadId\"\n );\n const checkpointNsOption = this.options.checkpointNs ?? \"\";\n const checkpointNs = requireText(\n await (typeof checkpointNsOption === \"function\" ? checkpointNsOption(flow) : checkpointNsOption),\n \"checkpointNs\",\n true\n );\n const context = graphContext === undefined\n ? this.options.context != null\n ? await this.options.context(flow)\n : Object.hasOwn(additional, \"context\")\n ? additional.context\n : Object.hasOwn(invokeOptions, \"context\")\n ? invokeOptions.context\n : new LangGraphFlowContext(flow, threadId, checkpointNs)\n : graphContext;\n return {\n ...invokeOptions,\n ...additional,\n configurable: {\n ...baseConfigurable,\n ...rawConfigurable,\n checkpoint_ns: checkpointNs,\n thread_id: threadId\n },\n context,\n metadata: {\n ...baseMetadata,\n ...rawMetadata,\n ferricflow_id: flow.id,\n ferricflow_state: flow.logicalState,\n ferricflow_type: flow.type\n }\n };\n }\n\n async invoke(\n flow: FerricFlowHandlerContext,\n graphInput?: Input | Command | null,\n graphContext?: unknown\n ): Promise<LangGraphFlowRun<Output>> {\n const config = await this.config(flow, graphContext);\n let input = graphInput;\n if (input === undefined) {\n let hasCheckpoint = false;\n if ((this.options.recoverExisting ?? true) && this.graph.getState != null) {\n hasCheckpoint = snapshotHasCheckpoint(await this.graph.getState(config));\n }\n input = hasCheckpoint\n ? null\n : this.options.input == null\n ? flow.payload as Input\n : await this.options.input(flow);\n }\n const value = await this.graph.invoke(input, config);\n const configurable = config.configurable;\n return new LangGraphFlowRun(\n value,\n requireText(configurable?.thread_id, \"thread_id\"),\n requireText(configurable?.checkpoint_ns ?? \"\", \"checkpoint_ns\", true),\n interrupts(value)\n );\n }\n\n async outcome(run: LangGraphFlowRun<Output>, flow: FerricFlowHandlerContext): Promise<Outcome> {\n const mapper = run.interrupted ? this.options.onInterrupt : this.options.onComplete;\n if (mapper != null) return await mapper(run, flow);\n const stateMeta = {\n langgraph_checkpoint_ns: run.checkpointNs,\n langgraph_interrupt_count: run.interrupts.length,\n langgraph_interrupted: run.interrupted,\n langgraph_thread_id: run.threadId\n };\n if (!run.interrupted) return complete({ result: run.value, stateMeta });\n if (this.options.interruptState != null) {\n return transition(this.options.interruptState, { stateMeta });\n }\n return fail({\n error: {\n checkpointNs: run.checkpointNs,\n interruptCount: run.interrupts.length,\n threadId: run.threadId,\n type: \"unhandled_langgraph_interrupt\"\n },\n stateMeta\n });\n }\n\n async handle(\n flow: FerricFlowHandlerContext,\n graphInput?: Input | Command | null,\n graphContext?: unknown\n ): Promise<Outcome> {\n return await this.outcome(await this.invoke(flow, graphInput, graphContext), flow);\n }\n\n async resume(flow: FerricFlowHandlerContext, value: unknown, graphContext?: unknown): Promise<Outcome> {\n return await this.handle(flow, new Command({ resume: value }), graphContext);\n }\n\n async handler(flow: FerricFlowHandlerContext): Promise<Outcome> {\n return await this.handle(flow);\n }\n}\n\nfunction interrupts(value: unknown): readonly unknown[] {\n if (value == null || typeof value !== \"object\" || !(\"__interrupt__\" in value)) return [];\n const raw = (value as { __interrupt__?: unknown }).__interrupt__;\n if (raw == null) return [];\n return Array.isArray(raw) ? raw : [raw];\n}\n\nfunction snapshotHasCheckpoint(snapshot: unknown): boolean {\n if (snapshot == null || typeof snapshot !== \"object\") return false;\n const value = snapshot as Record<string, unknown>;\n if (value.config != null && typeof value.config === \"object\") {\n const configurable = (value.config as { configurable?: unknown }).configurable;\n if (\n configurable != null &&\n typeof configurable === \"object\" &&\n typeof (configurable as { checkpoint_id?: unknown }).checkpoint_id === \"string\"\n ) return true;\n }\n return value.createdAt != null || value.metadata != null;\n}\n\nfunction defaultThreadId(flow: FerricFlowHandlerContext): string {\n const identity = Buffer.concat([\n identityComponent(flow.type),\n identityComponent(flow.partitionKey),\n identityComponent(flow.id)\n ]);\n return `ferricflow:${createHash(\"sha256\").update(identity).digest(\"hex\")}`;\n}\n\nfunction identityComponent(value: string | undefined): Buffer {\n if (value == null) return Buffer.concat([Buffer.from(\"n\"), uint64(0)]);\n const payload = Buffer.from(value, \"utf8\");\n return Buffer.concat([Buffer.from(\"s\"), uint64(payload.length), payload]);\n}\n\nfunction uint64(value: number): Buffer {\n const result = Buffer.allocUnsafe(8);\n result.writeBigUInt64BE(BigInt(value));\n return result;\n}\n\nfunction requireText(value: unknown, name: string, allowEmpty = false): string {\n if (typeof value !== \"string\" || (!allowEmpty && value.length === 0) || value.includes(\"\\0\")) {\n throw new TypeError(`${name} must be ${allowEmpty ? \"text\" : \"non-empty text\"} without NUL bytes`);\n }\n return value;\n}\n","import type { ClaimedItem, StateMeta } from \"./types.js\";\nimport type { CommandArgument } from \"./internal.js\";\n\nconst OUTCOME_BRAND = Symbol(\"ferricstore.outcome\");\nconst ALREADY_APPLIED_BRAND = Symbol(\"ferricstore.alreadyApplied\");\nconst REPLAYED_STEP_BRAND = Symbol(\"ferricstore.replayedStep\");\n\nexport type Outcome = TransitionOutcome | CompleteOutcome | RetryOutcome | FailOutcome;\n\n/** A workflow handler mutation already committed with this refreshed claim. */\nexport interface AlreadyAppliedOutcome {\n readonly job: ClaimedItem;\n readonly kind: \"already_applied\";\n}\n\n/** A durable workflow step result that is also an already-applied outcome. */\nexport interface AppliedStepOutcome<TResult> extends AlreadyAppliedOutcome {\n readonly applied: true;\n readonly result: TResult;\n}\n\n/** A stored durable-step result recovered without a mutation in this invocation. */\nexport interface ReplayedStepResult<TResult> {\n readonly applied: false;\n readonly job: ClaimedItem;\n readonly result: TResult;\n}\n\n/** Result of a context durable step, distinguishing a new commit from replay. */\nexport type WorkflowStepResult<TResult> = AppliedStepOutcome<TResult> | ReplayedStepResult<TResult>;\n\nexport interface NamedValueMutation {\n values?: Record<string, unknown>;\n valueRefs?: Record<string, string>;\n dropValues?: string[];\n overrideValues?: string[];\n attributesMerge?: Record<string, CommandArgument>;\n attributesDelete?: string[];\n stateMeta?: StateMeta;\n}\n\nexport interface TransitionOutcome extends NamedValueMutation {\n readonly kind: \"transition\";\n readonly toState: string;\n readonly payload?: unknown;\n readonly priority?: number;\n readonly runAtMs?: number;\n}\n\nexport interface CompleteOutcome extends NamedValueMutation {\n readonly kind: \"complete\";\n readonly payload?: unknown;\n readonly result?: unknown;\n readonly ttlMs?: number;\n}\n\nexport interface RetryOutcome extends NamedValueMutation {\n readonly kind: \"retry\";\n readonly error?: unknown;\n readonly payload?: unknown;\n readonly runAtMs?: number;\n}\n\nexport interface FailOutcome extends NamedValueMutation {\n readonly kind: \"fail\";\n readonly error?: unknown;\n readonly payload?: unknown;\n readonly ttlMs?: number;\n}\n\nexport function transition(\n toState: string,\n options: Omit<TransitionOutcome, \"kind\" | \"toState\"> = {}\n): TransitionOutcome {\n return brandOutcome({ ...options, kind: \"transition\", toState });\n}\n\nexport function complete(options: Omit<CompleteOutcome, \"kind\"> = {}): CompleteOutcome {\n return brandOutcome({ ...options, kind: \"complete\" });\n}\n\nexport function retry(options: Omit<RetryOutcome, \"kind\"> = {}): RetryOutcome {\n return brandOutcome({ ...options, kind: \"retry\" });\n}\n\nexport function fail(options: Omit<FailOutcome, \"kind\"> = {}): FailOutcome {\n return brandOutcome({ ...options, kind: \"fail\" });\n}\n\n/** @internal Create a marker only after the corresponding mutation commits. */\nexport function alreadyApplied(job: ClaimedItem): AlreadyAppliedOutcome {\n return brandAlreadyApplied({ job, kind: \"already_applied\" });\n}\n\n/** @internal Create a durable result marker only after a new commit. */\nexport function appliedStep<TResult>(job: ClaimedItem, result: TResult): AppliedStepOutcome<TResult> {\n return brandAlreadyApplied({ applied: true, job, kind: \"already_applied\", result });\n}\n\n/** @internal Create a replay result that must not suppress the handler's next outcome. */\nexport function replayedStep<TResult>(job: ClaimedItem, result: TResult): ReplayedStepResult<TResult> {\n const replayed: ReplayedStepResult<TResult> = { applied: false, job, result };\n Object.defineProperty(replayed, REPLAYED_STEP_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false\n });\n return replayed;\n}\n\nexport function isOutcome(value: unknown): value is Outcome {\n if (\n typeof value !== \"object\" ||\n value == null ||\n !Object.hasOwn(value, OUTCOME_BRAND) ||\n (value as Record<PropertyKey, unknown>)[OUTCOME_BRAND] !== true\n ) {\n return false;\n }\n const outcome = value as Partial<Outcome>;\n if (outcome.kind === \"transition\") {\n return typeof outcome.toState === \"string\";\n }\n return outcome.kind === \"complete\" || outcome.kind === \"retry\" || outcome.kind === \"fail\";\n}\n\nexport function isAlreadyAppliedOutcome(value: unknown): value is AlreadyAppliedOutcome {\n return typeof value === \"object\" && value != null &&\n Object.hasOwn(value, ALREADY_APPLIED_BRAND) &&\n (value as Record<PropertyKey, unknown>)[ALREADY_APPLIED_BRAND] === true &&\n (value as Partial<AlreadyAppliedOutcome>).kind === \"already_applied\";\n}\n\n/** @internal */\nexport function isReplayedStepResult(value: unknown): value is ReplayedStepResult<unknown> {\n return typeof value === \"object\" && value != null &&\n Object.hasOwn(value, REPLAYED_STEP_BRAND) &&\n (value as Record<PropertyKey, unknown>)[REPLAYED_STEP_BRAND] === true &&\n (value as Partial<ReplayedStepResult<unknown>>).applied === false;\n}\n\nfunction brandOutcome<T extends Outcome>(outcome: T): T {\n Object.defineProperty(outcome, \"kind\", {\n configurable: false,\n enumerable: true,\n value: outcome.kind,\n writable: false\n });\n if (outcome.kind === \"transition\") {\n Object.defineProperty(outcome, \"toState\", {\n configurable: false,\n enumerable: true,\n value: outcome.toState,\n writable: false\n });\n }\n Object.defineProperty(outcome, OUTCOME_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false\n });\n return outcome;\n}\n\nfunction brandAlreadyApplied<T extends AlreadyAppliedOutcome>(outcome: T): T {\n Object.defineProperty(outcome, \"kind\", {\n configurable: false,\n enumerable: true,\n value: \"already_applied\",\n writable: false\n });\n Object.defineProperty(outcome, ALREADY_APPLIED_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false\n });\n return outcome;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,sBAAuC;AAEvC,uBAMO;;;ACRP,yBAA2B;AAC3B,sBAAoC;;;ACD7B,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC,OAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,UAMzB,CAAC,GAAG;AACN,UAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AACvC,SAAK,OAAO,WAAW;AACvB,SAAK,MAAM,QAAQ;AACnB,SAAK,YAAY,QAAQ,aAAa,uBAAuB,QAAQ,KAAK,WAAW;AACrF,SAAK,cAAc,QAAQ,eAAe,uBAAuB,QAAQ,KAAK,eAAe;AAC7F,SAAK,eAAe,QAAQ,gBAAgB,uBAAuB,QAAQ,KAAK,gBAAgB;AAAA,EAClG;AACF;AA2EO,IAAM,gBAAN,cAA4B,iBAAiB;AAAA,EAChC,OAAO;AAC3B;AAkKA,SAAS,uBAAuB,KAAc,MAAkC;AAC9E,QAAM,QAAQ,gBAAgB,KAAK,IAAI;AACvC,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,OAAO,cAAc,KAA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sC;AAClE,QACE,gBAAgB,QAChB,OAAO,iBAAiB,YACxB,OAAQ,aAA6C,kBAAkB,SACvE,QAAO;AAAA,EACX;AACA,SAAO,MAAM,aAAa,QAAQ,MAAM,YAAY;AACtD;AAEA,SAAS,gBAAgB,MAAwC;AAC/D,QAAMC,YAAW,OAAO,OAAO;AAAA,IAC7B,kBAAkB,KAAK,IAAI;AAAA,IAC3B,kBAAkB,KAAK,YAAY;AAAA,IACnC,kBAAkB,KAAK,EAAE;AAAA,EAC3B,CAAC;AACD,SAAO,kBAAc,gCAAW,QAAQ,EAAE,OAAOA,SAAQ,EAAE,OAAO,KAAK,CAAC;AAC1E;AAEA,SAAS,kBAAkB,OAAmC;AAC5D,MAAI,SAAS,KAAM,QAAO,OAAO,OAAO,CAAC,OAAO,KAAK,GAAG,GAAGC,QAAO,CAAC,CAAC,CAAC;AACrE,QAAM,UAAU,OAAO,KAAK,OAAO,MAAM;AACzC,SAAO,OAAO,OAAO,CAAC,OAAO,KAAK,GAAG,GAAGA,QAAO,QAAQ,MAAM,GAAG,OAAO,CAAC;AAC1E;AAEA,SAASA,QAAO,OAAuB;AACrC,QAAM,SAAS,OAAO,YAAY,CAAC;AACnC,SAAO,iBAAiB,OAAO,KAAK,CAAC;AACrC,SAAO;AACT;AAEA,SAAS,YAAY,OAAgB,MAAc,aAAa,OAAe;AAC7E,MAAI,OAAO,UAAU,YAAa,CAAC,cAAc,MAAM,WAAW,KAAM,MAAM,SAAS,IAAI,GAAG;AAC5F,UAAM,IAAI,UAAU,GAAG,IAAI,YAAY,aAAa,SAAS,gBAAgB,oBAAoB;AAAA,EACnG;AACA,SAAO;AACT;","names":["import_node_crypto","response","delay","checkpointId","identity","import_node_crypto","import_langgraph","FORMAT_VERSION","sha256","orderedText","decodeOrderedText","import_node_crypto","import_langgraph","interrupts","identity","uint64"]}