@byok-sdk/client 0.9.0 → 0.10.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agent-home.ts","../../src/daemon/agent-memory.ts","../../src/daemon/agent-memory-fs-helper.ts","../../src/bin/agent-memory-mcp-server.ts","../../src/daemon/memory-guidance.ts"],"names":["createHash","path","fsConstants","fs","randomUUID","auditWarning","candidates","record","params"],"mappings":";;;;;;;;AAoBO,IAAM,6BAAA,GAAgC,OAAA;;;ACNtC,IAAM,2BAAA,GAA8B,6BAAA;AAGpC,IAAM,8BAA8B,GAAA,GAAM,IAAA;AAC1C,IAAM,kCAAkC,IAAA,GAAO,IAAA;AAC/C,IAAM,+BAAA,GAAkC,GAAA;AACxC,IAAM,iCAAA,GAAoC,GAAA;AAE1C,IAAM,gCAAA,GAAmC,+BAAA;AAEhD,IAAM,QAAA,GAAW,wBAAA;AACjB,IAAM,YAAA,GAAe,qCAAA;AACrB,IAAM,WAAA,GAAc,sGAAA;AACpB,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAGzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAC1C,YAAY,OAAA,EAAiB;AAAE,IAAA,KAAA,CAAM,OAAO,CAAA;AAAG,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AAAA,EAAoB;AACjF;AACO,IAAM,gCAAA,GAAN,cAA+C,gBAAA,CAAiB;AAAA,EACrE,WAAA,CAAqB,kBAAmC,cAAA,EAAwB;AAC9E,IAAA,KAAA,CAAM,CAAA,yCAAA,EAA4C,gBAAgB,CAAA,UAAA,EAAa,cAAc,CAAA,CAAE,CAAA;AAD5E,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA;AAAmC,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAEtD,IAAA,IAAA,CAAK,IAAA,GAAO,kCAAA;AAAA,EACd;AAAA,EAHq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AE,MAAA,MAAM,QAAA,GAAW,MAAM,2BAAA,CAA4B,OAAA,EAAS,MAAM,IAAI,CAAA;AAAG,MAAA,IAAI,QAAA,KAAa,QAAW,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAC;AAAA,CAAI,CAAA;AAAA,IAAG,CAAA,GAAG;AAAA,EAAG,CAAC,CAAA;AACpW;;;ACzCO,IAAM,qBAAA,GAAwB;AAAA,EACnC,gFAAA;AAAA,EACA,kJAAA;AAAA,EACA,8EAAA;AAAA,EACA,2HAAA;AAAA,EACA;AACF,CAAA,CAAE,KAAK,IAAI;AAEJ,SAAS,2BAA2B,WAAA,EAA6B;AACtE,EAAA,OAAO,GAAG,qBAAqB;;AAAA,EAAO,WAAW,CAAA,CAAA;AACnD","file":"index.js","sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n AgentHomeProjectionPayloadSchema,\n AgentRefSchema,\n type AgentHomeProjectionOutcome,\n type AgentHomeProjectionPayload,\n type AgentRef,\n} from '@byok-sdk/protocol';\nimport { atomicWriteFile } from './util/atomic-write';\nimport {\n acquirePathMutationGate,\n PathMutationGateBusyError,\n type PathMutationGate,\n} from './daemon/path-mutation-gate';\n\nexport type { AgentRef } from '@byok-sdk/protocol';\n\nexport const AGENT_HOME_DIRECTORY = 'agents';\nexport const AGENT_HOME_INTERNAL_DIRECTORY = '.byok';\nexport const AGENT_HOME_PROJECTION_STATE_FILE = 'agent-home-projection.json';\n\nexport class AgentHomeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AgentHomeError';\n }\n}\n\nexport class AgentRefValidationError extends AgentHomeError {\n constructor(message: string) {\n super(message);\n this.name = 'AgentRefValidationError';\n }\n}\n\nexport class AgentHomeResolutionError extends AgentHomeError {\n constructor(message: string) {\n super(message);\n this.name = 'AgentHomeResolutionError';\n }\n}\n\nexport class AgentHomeCollisionError extends AgentHomeResolutionError {\n constructor(message: string) {\n super(message);\n this.name = 'AgentHomeCollisionError';\n }\n}\n\nexport class AgentHomeBusyError extends AgentHomeError {\n constructor(message: string) {\n super(message);\n this.name = 'AgentHomeBusyError';\n }\n}\n\n/** A malformed persisted lease is integrity failure, never retryable contention. */\nexport class AgentHomeLeaseCorruptError extends AgentHomeResolutionError {\n constructor(message: string) {\n super(message);\n this.name = 'AgentHomeLeaseCorruptError';\n }\n}\n\nexport interface AgentHomeResolution {\n readonly agentRef: AgentRef;\n /** Absolute branded storage root supplied by the host, after realpath. */\n readonly hostStorageRoot: string;\n /** SDK-owned `<hostStorageRoot>/agents` authority, after realpath. */\n readonly agentsRoot: string;\n /** Canonical absolute Agent home. This is also the runtime cwd. */\n readonly homeDir: string;\n readonly canonicalHome: string;\n}\n\nexport interface AgentHomeProjectionInput extends AgentHomeResolution {\n readonly cwd: string;\n}\n\nexport interface AgentHomeProjectionApplyInput extends AgentHomeProjectionInput {\n readonly requestId: string;\n readonly projectionHash: string;\n readonly projection: unknown;\n}\n\n/**\n * Optional downstream projection hook. The SDK supplies the canonical home;\n * the host supplies opaque, redacted product content and never joins\n * `agents/<agentId>` itself. The SDK does not parse the projected content.\n */\nexport interface AgentHomeProjection {\n /** Optional creation/task-time host preparation retained as a distinct lifecycle. */\n prepare?(input: AgentHomeProjectionInput): void | Promise<void>;\n /**\n * Task-free opaque desired-state consumer. It must atomically and\n * idempotently ensure its own durable bytes because exact revision/hash\n * requests may replay after local derived-file loss or transport failure.\n */\n apply?(input: AgentHomeProjectionApplyInput): void | Promise<void>;\n}\n\nexport type AgentHomeProjectionFunction = (input: AgentHomeProjectionInput) => void | Promise<void>;\nexport type AgentHomeProjectionApplyFunction = (input: AgentHomeProjectionApplyInput) => void | Promise<void>;\n\nexport interface AgentHomeLease {\n readonly leaseId: string;\n readonly agentRef: AgentRef;\n readonly canonicalHome: string;\n readonly cwd: string;\n /** Filesystem identity captured under the writer lease; task-scoped memory rechecks it before pinning a descriptor. */\n readonly homeIdentity: Readonly<{ dev: bigint; ino: bigint }>;\n release(): Promise<void>;\n}\n\nexport interface AgentHomeBinding {\n readonly resolution: AgentHomeResolution;\n readonly lease: AgentHomeLease;\n}\n\nexport function validateAgentRef(value: unknown): AgentRef {\n let candidate: AgentRef;\n try {\n candidate = AgentRefSchema.parse(value);\n } catch (error) {\n throw new AgentRefValidationError(\n `AgentRef does not match the protocol contract: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return Object.freeze({ agentId: candidate.agentId, profileRevision: candidate.profileRevision });\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\nfunction assertAbsolutePath(value: unknown, label: string): asserts value is string {\n if (typeof value !== 'string' || value.length === 0 || !path.isAbsolute(value)) {\n throw new AgentHomeResolutionError(`${label} must be an absolute path`);\n }\n if (/[\\u0000\\r\\n]/u.test(value)) {\n throw new AgentHomeResolutionError(`${label} must not contain NUL or line breaks`);\n }\n}\n\ninterface ExistingAncestor {\n readonly canonical: string;\n readonly tail: readonly string[];\n}\n\nasync function resolveExistingAncestor(inputPath: string): Promise<ExistingAncestor> {\n let cursor = path.resolve(inputPath);\n const tail: string[] = [];\n for (;;) {\n try {\n return { canonical: await fs.realpath(cursor), tail };\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;\n const parent = path.dirname(cursor);\n if (parent === cursor) throw new AgentHomeResolutionError(`no existing ancestor for ${inputPath}`);\n tail.unshift(path.basename(cursor));\n cursor = parent;\n }\n }\n}\n\nasync function canonicalPath(inputPath: string): Promise<string> {\n const { canonical, tail } = await resolveExistingAncestor(inputPath);\n return path.resolve(canonical, ...tail);\n}\n\nasync function materializeDirectory(inputPath: string): Promise<string> {\n const { canonical, tail } = await resolveExistingAncestor(inputPath);\n let cursor = canonical;\n for (const component of tail) {\n cursor = path.join(cursor, component);\n try {\n const stat = await fs.lstat(cursor);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new AgentHomeResolutionError(`Agent home path component is not a real directory: ${cursor}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n await fs.mkdir(cursor, { mode: 0o700 });\n }\n }\n const realized = await fs.realpath(inputPath);\n if (realized !== cursor) {\n throw new AgentHomeResolutionError(`Agent home path changed through a symlink while being created: ${inputPath}`);\n }\n return realized;\n}\n\nasync function ensureDirectoryNoSymlink(root: string, target: string): Promise<string> {\n if (!isWithin(root, target)) throw new AgentHomeResolutionError('Agent home is outside hostStorageRoot');\n const relative = path.relative(root, target);\n const components = relative === '' ? [] : relative.split(path.sep);\n let cursor = root;\n for (const component of components) {\n cursor = path.join(cursor, component);\n try {\n const stat = await fs.lstat(cursor);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new AgentHomeResolutionError(`Agent home path component is not a real directory: ${cursor}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n await fs.mkdir(cursor, { mode: 0o700 });\n }\n }\n const realized = await fs.realpath(target);\n if (!isWithin(root, realized) || realized !== target) {\n throw new AgentHomeResolutionError('Agent home changed through a symlink while it was being prepared');\n }\n return realized;\n}\n\nasync function ensurePreservedFile(filePath: string): Promise<void> {\n try {\n const handle = await fs.open(filePath, 'wx', 0o600);\n await handle.close();\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n const stat = await fs.lstat(filePath);\n if (!stat.isFile() || stat.isSymbolicLink()) {\n throw new AgentHomeResolutionError(`Agent home preserved file is not a regular file: ${filePath}`);\n }\n}\n\n/**\n * SDK-owned deterministic Agent-home layout. The downstream supplies exactly\n * one absolute branded storage root; there is deliberately no host path\n * resolver and no second workspace authority.\n */\nexport class AgentHomeLayout {\n private readonly hostStorageRootInput: string;\n private readonly agentIdByCanonicalHome = new Map<string, string>();\n private canonicalRoot?: string;\n\n constructor(hostStorageRoot: string) {\n assertAbsolutePath(hostStorageRoot, 'agentHome.hostStorageRoot');\n this.hostStorageRootInput = path.resolve(hostStorageRoot);\n }\n\n async resolve(agentRefInput: AgentRef): Promise<AgentHomeResolution> {\n const gate = await this.acquireRootMutationGate();\n try {\n const agentRef = validateAgentRef(agentRefInput);\n const hostStorageRoot = await this.resolveRoot();\n const agentsRoot = await ensureDirectoryNoSymlink(\n hostStorageRoot,\n path.join(hostStorageRoot, AGENT_HOME_DIRECTORY),\n );\n const lexicalHome = path.join(agentsRoot, agentRef.agentId);\n // Materialize and verify the exact lexical Agent segment. Canonicalizing\n // first would accidentally turn an in-root `two -> one` symlink into the\n // already-valid `one` directory and bypass cross-Agent isolation.\n const canonicalHome = await ensureDirectoryNoSymlink(agentsRoot, lexicalHome);\n const priorAgentId = this.agentIdByCanonicalHome.get(canonicalHome);\n if (priorAgentId !== undefined && priorAgentId !== agentRef.agentId) {\n throw new AgentHomeCollisionError(\n `canonical Agent home ${canonicalHome} is already bound to Agent ${priorAgentId}`,\n );\n }\n this.agentIdByCanonicalHome.set(canonicalHome, agentRef.agentId);\n return Object.freeze({\n agentRef,\n hostStorageRoot,\n agentsRoot,\n homeDir: canonicalHome,\n canonicalHome,\n });\n } finally {\n await gate.release();\n }\n }\n\n /**\n * Prove the canonical root is materializable and writable before the daemon\n * advertises Agent-home capability. No Agent identity or persistent Agent\n * file is created by this preflight.\n */\n async preflight(): Promise<void> {\n const gate = await this.acquireRootMutationGate();\n let probePath: string | undefined;\n let handle: fs.FileHandle | undefined;\n let created = false;\n try {\n const hostStorageRoot = await this.resolveRoot();\n const agentsRoot = await ensureDirectoryNoSymlink(\n hostStorageRoot,\n path.join(hostStorageRoot, AGENT_HOME_DIRECTORY),\n );\n probePath = path.join(agentsRoot, `.byok-agent-home-preflight-${randomUUID()}`);\n handle = await fs.open(probePath, 'wx', 0o600);\n created = true;\n await handle.sync();\n await handle.close();\n handle = undefined;\n await fs.rm(probePath);\n created = false;\n } catch (error) {\n await handle?.close().catch(() => {});\n if (created && probePath !== undefined) await fs.rm(probePath, { force: true }).catch(() => {});\n throw new AgentHomeResolutionError(\n `agentHome.hostStorageRoot preflight failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n } finally {\n await gate.release();\n }\n }\n\n /**\n * Construction-time validation is deliberately non-mutating. The actual\n * writable preflight runs asynchronously after daemon ownership is acquired\n * and before transport/capability publication, where it can participate in\n * the cross-process relocation gate without a sync shadow lock.\n */\n preflightSync(): void {\n assertAbsolutePath(this.hostStorageRootInput, 'agentHome.hostStorageRoot');\n }\n\n private async resolveRoot(): Promise<string> {\n if (this.canonicalRoot !== undefined) return this.canonicalRoot;\n try {\n this.canonicalRoot = await materializeDirectory(this.hostStorageRootInput);\n } catch (error) {\n throw new AgentHomeResolutionError(\n `agentHome.hostStorageRoot is not accessible: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return this.canonicalRoot;\n }\n\n private async acquireRootMutationGate(): Promise<PathMutationGate> {\n try {\n return await acquirePathMutationGate({\n scope: 'agent-home-root',\n targetPath: path.join(this.hostStorageRootInput, AGENT_HOME_DIRECTORY),\n }, { waitMs: 1_000 });\n } catch (error) {\n if (error instanceof PathMutationGateBusyError) {\n throw new AgentHomeBusyError('Agent-home root is reserved for local-state relocation');\n }\n throw error;\n }\n }\n}\n\ninterface StoredLeaseMarker {\n readonly version: 1;\n readonly ownerId: string;\n readonly leaseId: string;\n readonly agentRef: AgentRef;\n readonly canonicalHome: string;\n}\n\nexport function stableAgentHomeOwnerId(storeDir: string, productId: string): string {\n const identity = `${path.resolve(storeDir)}\\0${productId}`;\n return `store-product:${createHash('sha256').update(identity).digest('hex')}`;\n}\n\nfunction parseLeaseMarker(value: string, lockPath: string): StoredLeaseMarker {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new AgentHomeLeaseCorruptError(`Agent home lease marker ${lockPath} is corrupt`);\n }\n if (\n typeof parsed !== 'object' || parsed === null ||\n (parsed as { version?: unknown }).version !== 1 ||\n typeof (parsed as { ownerId?: unknown }).ownerId !== 'string' ||\n typeof (parsed as { leaseId?: unknown }).leaseId !== 'string' ||\n typeof (parsed as { canonicalHome?: unknown }).canonicalHome !== 'string' ||\n !path.isAbsolute((parsed as { canonicalHome: string }).canonicalHome)\n ) {\n throw new AgentHomeLeaseCorruptError(`Agent home lease marker ${lockPath} has an invalid shape`);\n }\n let agentRef: AgentRef;\n try {\n agentRef = validateAgentRef((parsed as { agentRef?: unknown }).agentRef);\n } catch {\n throw new AgentHomeLeaseCorruptError(`Agent home lease marker ${lockPath} has an invalid AgentRef`);\n }\n const marker = parsed as Omit<StoredLeaseMarker, 'agentRef'>;\n return { ...marker, agentRef, canonicalHome: path.resolve(marker.canonicalHome) };\n}\n\n/** One-writer lease backed by both a process registry and an exclusive marker. */\nexport class AgentHomeLeaseManager {\n private static readonly held = new Map<string, string>();\n private readonly ownerId: string;\n\n constructor(options: { ownerId?: string } = {}) {\n this.ownerId = options.ownerId ?? `process:${randomUUID()}`;\n }\n\n async acquire(resolution: AgentHomeResolution): Promise<AgentHomeLease> {\n const { canonicalHome, agentRef } = resolution;\n const leaseId = randomUUID();\n // Reserve synchronously before the first await. Two acquire() calls in\n // one process must not both pass an async filesystem preflight and then\n // misclassify the winner's marker as restart residue.\n if (AgentHomeLeaseManager.held.has(canonicalHome)) {\n throw new AgentHomeBusyError(`Agent home ${canonicalHome} already has a mutable writer lease`);\n }\n AgentHomeLeaseManager.held.set(canonicalHome, leaseId);\n let lockPath: string | undefined;\n let handle: fs.FileHandle | undefined;\n let rootGate: PathMutationGate | undefined;\n let ownsMarker = false;\n let homeIdentity: Readonly<{ dev: bigint; ino: bigint }> | undefined;\n try {\n rootGate = await acquirePathMutationGate({\n scope: 'agent-home-root',\n targetPath: resolution.agentsRoot,\n }, { waitMs: 1_000 });\n await ensureDirectoryNoSymlink(resolution.agentsRoot, canonicalHome);\n const homeStat = await fs.stat(canonicalHome, { bigint: true });\n if (!homeStat.isDirectory()) throw new AgentHomeResolutionError(`Agent home ${canonicalHome} is not a directory`);\n homeIdentity = Object.freeze({ dev: homeStat.dev, ino: homeStat.ino });\n const internalDir = await ensureDirectoryNoSymlink(\n canonicalHome,\n path.join(canonicalHome, AGENT_HOME_INTERNAL_DIRECTORY),\n );\n lockPath = path.join(internalDir, 'agent-home.lease');\n handle = await this.openLeaseMarker(lockPath, canonicalHome, agentRef.agentId);\n ownsMarker = true;\n const marker: StoredLeaseMarker = {\n version: 1,\n ownerId: this.ownerId,\n leaseId,\n agentRef,\n canonicalHome,\n };\n await handle.writeFile(JSON.stringify(marker), 'utf8');\n await handle.sync();\n await handle.close();\n handle = undefined;\n await rootGate.release();\n rootGate = undefined;\n } catch (error) {\n await handle?.close().catch(() => {});\n if (ownsMarker && lockPath !== undefined) await fs.rm(lockPath, { force: true }).catch(() => {});\n await rootGate?.release().catch(() => {});\n if (AgentHomeLeaseManager.held.get(canonicalHome) === leaseId) {\n AgentHomeLeaseManager.held.delete(canonicalHome);\n }\n if (error instanceof PathMutationGateBusyError) {\n throw new AgentHomeBusyError('Agent-home root is reserved for local-state relocation');\n }\n if (error instanceof AgentHomeError) throw error;\n throw new AgentHomeError(`could not acquire Agent home lease: ${error instanceof Error ? error.message : String(error)}`);\n }\n const acquiredLockPath = lockPath;\n if (acquiredLockPath === undefined) throw new AgentHomeError('Agent home lease marker path was not established');\n if (homeIdentity === undefined) throw new AgentHomeError('Agent home lease identity was not established');\n let released = false;\n let releaseAttempt: Promise<void> | undefined;\n return {\n leaseId,\n agentRef,\n canonicalHome,\n cwd: canonicalHome,\n homeIdentity,\n release: () => {\n if (released) return Promise.resolve();\n if (releaseAttempt !== undefined) return releaseAttempt;\n const attempt = (async () => {\n if (AgentHomeLeaseManager.held.get(canonicalHome) !== leaseId) {\n throw new AgentHomeBusyError(`Agent home lease ${leaseId} is no longer owned by this process`);\n }\n let contents: string;\n try {\n contents = await fs.readFile(acquiredLockPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n AgentHomeLeaseManager.held.delete(canonicalHome);\n released = true;\n return;\n }\n throw error;\n }\n const parsed = parseLeaseMarker(contents, acquiredLockPath);\n if (parsed.leaseId !== leaseId || parsed.ownerId !== this.ownerId) {\n throw new AgentHomeBusyError(`Agent home lease marker ${acquiredLockPath} belongs to another writer`);\n }\n await fs.rm(acquiredLockPath);\n AgentHomeLeaseManager.held.delete(canonicalHome);\n released = true;\n })();\n releaseAttempt = attempt.catch((error: unknown) => {\n releaseAttempt = undefined;\n // `release()` is the caller relinquishing this in-process writer.\n // Keep an unknown/other on-disk marker intact, but never let the\n // process registry outlive the failed relinquish and wedge this home\n // after the external marker is repaired or removed.\n if (AgentHomeLeaseManager.held.get(canonicalHome) === leaseId) {\n AgentHomeLeaseManager.held.delete(canonicalHome);\n }\n released = true;\n throw error;\n });\n return releaseAttempt;\n },\n };\n }\n\n private async openLeaseMarker(lockPath: string, canonicalHome: string, agentId: string): Promise<fs.FileHandle> {\n try {\n return await fs.open(lockPath, 'wx', 0o600);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n const prior = parseLeaseMarker(await fs.readFile(lockPath, 'utf8'), lockPath);\n if (prior.ownerId !== this.ownerId) {\n throw new AgentHomeBusyError(`Agent home ${prior.canonicalHome} already has a mutable writer lease`);\n }\n if (prior.canonicalHome !== canonicalHome || prior.agentRef.agentId !== agentId) {\n throw new AgentHomeBusyError(`Agent home lease marker ${lockPath} does not match its canonical Agent identity`);\n }\n // A marker owned by this daemon identity but absent from the in-process\n // registry is crash residue. DaemonOwnerLease prevents two live daemon\n // processes for the same store/product identity, so exact-owner reclaim is\n // the only permitted restart path.\n await fs.rm(lockPath);\n try {\n return await fs.open(lockPath, 'wx', 0o600);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new AgentHomeBusyError(`Agent home lease ${lockPath} was concurrently reclaimed`);\n }\n throw error;\n }\n }\n}\n\nasync function initializeAgentHome(resolution: AgentHomeResolution): Promise<void> {\n await ensureDirectoryNoSymlink(\n resolution.canonicalHome,\n path.join(resolution.canonicalHome, 'notes'),\n );\n await ensurePreservedFile(path.join(resolution.canonicalHome, 'MEMORY.md'));\n}\n\ninterface StoredAgentHomeProjectionState {\n readonly version: 1;\n readonly agentRef: AgentRef;\n readonly requestId: string;\n readonly projectionHash: string;\n}\n\nfunction projectionStatePath(resolution: AgentHomeResolution): string {\n return path.join(\n resolution.canonicalHome,\n AGENT_HOME_INTERNAL_DIRECTORY,\n AGENT_HOME_PROJECTION_STATE_FILE,\n );\n}\n\nasync function readProjectionState(\n resolution: AgentHomeResolution,\n): Promise<StoredAgentHomeProjectionState | undefined> {\n const filePath = projectionStatePath(resolution);\n try {\n const stat = await fs.lstat(filePath);\n if (!stat.isFile() || stat.isSymbolicLink()) {\n throw new AgentHomeResolutionError(`Agent projection state is not a regular file: ${filePath}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fs.readFile(filePath, 'utf8'));\n } catch (error) {\n throw new AgentHomeResolutionError(\n `Agent projection state is corrupt: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n (parsed as { version?: unknown }).version !== 1 ||\n typeof (parsed as { requestId?: unknown }).requestId !== 'string' ||\n typeof (parsed as { projectionHash?: unknown }).projectionHash !== 'string'\n ) {\n throw new AgentHomeResolutionError('Agent projection state has an invalid shape');\n }\n const candidate = parsed as Omit<StoredAgentHomeProjectionState, 'agentRef'> & { agentRef?: unknown };\n const agentRef = validateAgentRef(candidate.agentRef);\n if (agentRef.agentId !== resolution.agentRef.agentId) {\n throw new AgentHomeCollisionError('Agent projection state belongs to a different Agent home');\n }\n return Object.freeze({\n version: 1,\n agentRef,\n requestId: candidate.requestId,\n projectionHash: candidate.projectionHash,\n });\n}\n\nasync function writeProjectionState(\n resolution: AgentHomeResolution,\n payload: AgentHomeProjectionPayload,\n): Promise<void> {\n const filePath = projectionStatePath(resolution);\n const existing = await fs.lstat(filePath).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (existing !== undefined && (!existing.isFile() || existing.isSymbolicLink())) {\n throw new AgentHomeResolutionError(`Agent projection state is not a regular file: ${filePath}`);\n }\n const state: StoredAgentHomeProjectionState = {\n version: 1,\n agentRef: payload.agentRef,\n requestId: payload.requestId,\n projectionHash: payload.projectionHash,\n };\n await atomicWriteFile(filePath, `${JSON.stringify(state)}\\n`, { mode: 0o600, fsync: true });\n}\n\nfunction compareProjectionRevision(left: string, right: string): -1 | 0 | 1 {\n const leftRevision = BigInt(left);\n const rightRevision = BigInt(right);\n return leftRevision < rightRevision ? -1 : leftRevision > rightRevision ? 1 : 0;\n}\n\n/** Coordinates SDK-owned initialization, optional projection, and the lease. */\nexport class AgentHomeManager {\n readonly layout: AgentHomeLayout;\n readonly projection?: AgentHomeProjection;\n readonly leaseManager: AgentHomeLeaseManager;\n\n constructor(options: {\n hostStorageRoot: string;\n projection?: AgentHomeProjection;\n leaseManager?: AgentHomeLeaseManager;\n }) {\n this.layout = new AgentHomeLayout(options.hostStorageRoot);\n this.projection = options.projection;\n this.leaseManager = options.leaseManager ?? new AgentHomeLeaseManager();\n }\n\n async prepare(agentRef: AgentRef): Promise<AgentHomeBinding> {\n const binding = await this.acquire(agentRef);\n try {\n await this.initialize(binding);\n return binding;\n } catch (error) {\n await binding.lease.release().catch(() => {});\n throw error;\n }\n }\n\n /** Validate the configured root before capability publication. */\n async preflight(): Promise<void> {\n await this.layout.preflight();\n }\n\n /** Synchronous construction-time preflight for strict Agent-only admission. */\n preflightSync(): void {\n this.layout.preflightSync();\n }\n\n /** Resolve and lease without applying downstream projection side effects. */\n async acquire(agentRef: AgentRef): Promise<AgentHomeBinding> {\n const resolution = await this.layout.resolve(agentRef);\n const lease = await this.leaseManager.acquire(resolution);\n return Object.freeze({ resolution, lease });\n }\n\n /** Initialize only after any requested session exact-match has succeeded. */\n async initialize(binding: AgentHomeBinding): Promise<void> {\n const { resolution, lease } = binding;\n await initializeAgentHome(resolution);\n const prepare = this.projection?.prepare;\n if (prepare !== undefined) await prepare({ ...resolution, cwd: lease.cwd });\n if (await fs.realpath(resolution.homeDir) !== resolution.canonicalHome) {\n throw new AgentHomeResolutionError('Agent projection changed the canonical home path');\n }\n await initializeAgentHome(resolution);\n }\n\n supportsTaskFreeProjection(): boolean {\n return this.projection?.apply !== undefined;\n }\n\n /**\n * Apply one task-free projection under the same canonical-home writer lease\n * used by Agent execution. The host hook owns an atomic/idempotent ensure of\n * its opaque product bytes, so an exact desired-state replay invokes it again\n * before returning `idempotent`. Only a successful new-state hook followed\n * by the SDK-owned fsynced ordering record can return `applied`.\n */\n async project(input: AgentHomeProjectionPayload): Promise<AgentHomeProjectionOutcome> {\n const payload = AgentHomeProjectionPayloadSchema.parse(input);\n const binding = await this.acquire(payload.agentRef);\n try {\n const { resolution, lease } = binding;\n await initializeAgentHome(resolution);\n const applyProjection = async (): Promise<void> => {\n const apply = this.projection?.apply;\n if (apply === undefined) {\n throw new AgentHomeError('task-free Agent-home projection is not configured');\n }\n await apply({\n ...resolution,\n cwd: lease.cwd,\n requestId: payload.requestId,\n projectionHash: payload.projectionHash,\n projection: payload.projection,\n });\n if (await fs.realpath(resolution.homeDir) !== resolution.canonicalHome) {\n throw new AgentHomeResolutionError('Agent projection changed the canonical home path');\n }\n await initializeAgentHome(resolution);\n };\n const current = await readProjectionState(resolution);\n if (current !== undefined) {\n const order = compareProjectionRevision(\n payload.agentRef.profileRevision,\n current.agentRef.profileRevision,\n );\n if (order < 0) return 'stale';\n if (order === 0) {\n if (payload.projectionHash !== current.projectionHash) return 'conflict';\n await applyProjection();\n return 'idempotent';\n }\n }\n\n await applyProjection();\n await writeProjectionState(resolution, payload);\n return 'applied';\n } finally {\n // A release failure is itself ack-critical: do not let the caller post a\n // completion or advance the mailbox cursor while writer ownership is\n // uncertain.\n await binding.lease.release();\n }\n }\n}\n\nexport function createAgentHomeProjection(prepare: AgentHomeProjectionFunction): AgentHomeProjection {\n return Object.freeze({ prepare });\n}\n\n/**\n * Create the task-free atomic/idempotent opaque desired-state consumer.\n * Exact revision/hash delivery may invoke it again before an idempotent receipt;\n * no task-time fallback is inferred.\n */\nexport function createAgentHomeProjectionConsumer(apply: AgentHomeProjectionApplyFunction): AgentHomeProjection {\n return Object.freeze({ apply });\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { constants as fsConstants, existsSync, promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nimport {\n AGENT_MEMORY_PROJECTION_CAPABILITY,\n AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE,\n AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES,\n AgentMemoryProjectionMutationSchema,\n type AgentMemoryProjectionMutation,\n} from '@byok-sdk/protocol';\nimport { AGENT_HOME_INTERNAL_DIRECTORY, type AgentHomeLease, type AgentRef } from '../agent-home';\nimport type { AgentMemoryFilesystem, AgentMemoryFilesystemFileState } from './agent-memory-filesystem';\n\nexport const AGENT_MEMORY_AUDIT_FILENAME = 'agent-memory-audit-v1.jsonl';\n/** v2 is one atomically replaced state file, never an append-only log. */\nexport const AGENT_MEMORY_OUTBOX_FILENAME = 'agent-memory-redacted-outbox-v2.json';\nexport const AGENT_MEMORY_MAX_FILE_BYTES = 256 * 1024;\nexport const AGENT_MEMORY_MAX_SNAPSHOT_BYTES = 1024 * 1024;\nexport const AGENT_MEMORY_MAX_SNAPSHOT_FILES = 128;\nexport const AGENT_MEMORY_MAX_SNAPSHOT_ENTRIES = 512;\n/** One atomically replaced audit/outbox state must fit the cross-platform helper contract. */\nexport const AGENT_MEMORY_MAX_LOCAL_LOG_BYTES = AGENT_MEMORY_MAX_SNAPSHOT_BYTES;\n\nconst REVISION = /^sha256:[a-f0-9]{64}$/u;\nconst SAFE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;\nconst SECRET_LIKE = /(?:^|[-_.])(secret|token|credential|password|passwd|api[-_]?key|private[-_]?key|cookie)(?:$|[-_.])/iu;\nconst encoder = new TextEncoder();\nconst AGENT_MEMORY_PROJECTION_PUBLISH_TIMEOUT_MS = 10_000;\n\nexport class AgentMemoryError extends Error {\n constructor(message: string) { super(message); this.name = 'AgentMemoryError'; }\n}\nexport class AgentMemoryRevisionConflictError extends AgentMemoryError {\n constructor(readonly expectedRevision: string, readonly actualRevision: string) {\n super(`Agent memory revision conflict: expected ${expectedRevision}, current ${actualRevision}`);\n this.name = 'AgentMemoryRevisionConflictError';\n }\n}\n\nexport interface AgentMemoryTaskContext {\n readonly taskId: string;\n readonly tenantId: string;\n readonly deviceId: string;\n readonly agentRef: AgentRef;\n readonly sessionRef: string;\n readonly runtimeId: string;\n readonly canonicalHome: string;\n readonly leaseId: string;\n readonly homeIdentity: AgentHomeLease['homeIdentity'];\n /** Optional task-scoped external root handle; omission selects the native Linux backend. */\n readonly filesystem?: AgentMemoryFilesystem;\n}\nexport interface AgentMemoryFile { readonly path: string; readonly revision: string; readonly byteCount: number; readonly content: string; }\nexport interface AgentMemorySnapshot { readonly files: readonly AgentMemoryFile[]; readonly totalBytes: number; }\n/**\n * Embedder-owned redaction authority. Its output is opaque bytes: the local\n * relative paths, source revisions, and raw source content never enter the\n * outbox or projection port.\n */\nexport interface AgentMemoryRedactor {\n redact(input: Readonly<AgentMemorySnapshot>): Promise<Uint8Array> | Uint8Array;\n}\n/** Host-issued projection binding; no model-provided consent boolean exists. */\nexport interface AgentMemoryProjectionGrant {\n readonly grantRef: AgentMemoryProjectionMutation['grantRef'];\n readonly writerEpoch: AgentMemoryProjectionMutation['writerEpoch'];\n readonly policyRevision: AgentMemoryProjectionMutation['policyRevision'];\n}\nexport interface AgentMemoryRedactedOutboxRecord {\n readonly version: 2;\n readonly mutation: AgentMemoryProjectionMutation;\n readonly createdAt: string;\n}\n/**\n * Optional bridge to a complete hosted client. It receives the canonical,\n * already-redacted protocol mutation only; this package intentionally owns no\n * consent, cloud transport, or raw-source upload fallback.\n */\nexport interface AgentMemoryProjectionPort {\n publish(input: Readonly<{ mutation: AgentMemoryProjectionMutation }>): Promise<{ readonly accepted: boolean }>;\n}\n/**\n * Replay exposes only ordering metadata. The redacted mutation body remains in\n * the durable outbox and is never copied into a task-close error or outcome.\n */\nexport type AgentMemoryProjectionReplayDrainedOutcome = Readonly<{ readonly status: 'drained' }>;\nexport type AgentMemoryProjectionReplayPendingOutcome = Readonly<{\n readonly status: 'pending';\n readonly writerEpoch: number;\n readonly sourceSeq: number;\n readonly mutationId: string;\n}>;\nexport type AgentMemoryProjectionReplayOutcome = AgentMemoryProjectionReplayDrainedOutcome | AgentMemoryProjectionReplayPendingOutcome;\nconst DRAINED_AGENT_MEMORY_PROJECTION_REPLAY: AgentMemoryProjectionReplayDrainedOutcome = Object.freeze({ status: 'drained' as const });\nexport class AgentMemoryProjectionReplayPendingError extends AgentMemoryError {\n constructor(readonly outcome: AgentMemoryProjectionReplayPendingOutcome) {\n super('Agent memory projection replay remains pending');\n this.name = 'AgentMemoryProjectionReplayPendingError';\n }\n}\n/** Every member is mandatory before network projection is permitted. */\nexport interface AgentMemoryHostedProjection {\n readonly capability?: typeof AGENT_MEMORY_PROJECTION_CAPABILITY;\n readonly grant?: AgentMemoryProjectionGrant;\n readonly redactor?: AgentMemoryRedactor;\n readonly port?: AgentMemoryProjectionPort;\n}\n\nfunction digestBytes(content: Uint8Array): string { return `sha256:${createHash('sha256').update(content).digest('hex')}`; }\nfunction digest(content: string): string { return digestBytes(encoder.encode(content)); }\nfunction nonEmpty(value: unknown): value is string { return typeof value === 'string' && value.length > 0 && !/[\\u0000\\r\\n]/u.test(value); }\nfunction revision(value: unknown): value is string { return typeof value === 'string' && REVISION.test(value); }\nfunction taskContext(value: AgentMemoryTaskContext): AgentMemoryTaskContext {\n if (!value || !nonEmpty(value.taskId) || !nonEmpty(value.tenantId) || !nonEmpty(value.deviceId) || !nonEmpty(value.sessionRef) || !nonEmpty(value.runtimeId) || !nonEmpty(value.leaseId) || !value.agentRef || !nonEmpty(value.agentRef.agentId) || !nonEmpty(value.agentRef.profileRevision) || !path.isAbsolute(value.canonicalHome) || typeof value.homeIdentity?.dev !== 'bigint' || typeof value.homeIdentity.ino !== 'bigint') {\n throw new AgentMemoryError('Agent memory requires an exact active Agent task context');\n }\n return Object.freeze({ ...value, agentRef: Object.freeze({ ...value.agentRef }), homeIdentity: Object.freeze({ ...value.homeIdentity }), canonicalHome: path.resolve(value.canonicalHome) });\n}\n\n/** Model input can name one allowed file, never a root, directory, glob, or internal SDK state. */\nexport function validateAgentMemoryPath(value: unknown): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 1024 || /[\\u0000\\\\]/u.test(value)) throw new AgentMemoryError('memory path is invalid');\n if (value === 'MEMORY.md') return value;\n if (path.posix.isAbsolute(value) || /[*?\\[{]/u.test(value)) throw new AgentMemoryError('memory path must name exactly one file');\n const parts = value.split('/');\n if (parts.length < 2 || parts[0] !== 'notes' || !value.endsWith('.md') || parts.some((part) => part === '' || part === '.' || part === '..' || part === '.byok' || !SAFE_SEGMENT.test(part) || SECRET_LIKE.test(part))) {\n throw new AgentMemoryError('memory path must be MEMORY.md or notes/<safe-relative>.md');\n }\n return value;\n}\n\n/**\n * Node exposes no descriptor-relative filesystem API on macOS or Windows.\n * Linux `/proc/self/fd/<dirfd>/child` is an openat-like primitive: each next\n * component is resolved from a directory descriptor already opened with\n * O_NOFOLLOW, so an Agent cannot redirect a later operation by replacing an\n * ancestor after validation. Other platforms deliberately have no fallback.\n */\nconst SECURE_DIRECTORY_DESCRIPTOR_ROOT = '/proc/self/fd';\n\n/**\n * The sole platform gate for the Agent-memory write authority. Linux retains\n * the native procfs descriptor backend. macOS requires the explicit external\n * helper that passed its local race proof. Windows remains unavailable rather\n * than selecting an unproved fallback.\n */\nexport function isAgentMemorySecureFilesystemAvailable(externalHelperConfigured = false): boolean {\n const nativeLinux = process.platform === 'linux'\n && typeof fsConstants.O_NOFOLLOW === 'number'\n && typeof fsConstants.O_DIRECTORY === 'number'\n && typeof fsConstants.O_NONBLOCK === 'number'\n && existsSync(SECURE_DIRECTORY_DESCRIPTOR_ROOT);\n // Windows remains fail-closed until its real reparse/junction proof exists.\n return nativeLinux || (externalHelperConfigured && process.platform === 'darwin');\n}\n\nfunction requireSecureDirectoryDescriptors(): string {\n if (!isAgentMemorySecureFilesystemAvailable(false) || process.platform !== 'linux') {\n throw new AgentMemoryError('Agent memory is unavailable because this Node platform lacks safe descriptor-relative filesystem operations');\n }\n return SECURE_DIRECTORY_DESCRIPTOR_ROOT;\n}\n\nfunction noFollowFlags(base: number): number {\n requireSecureDirectoryDescriptors();\n return base | fsConstants.O_NOFOLLOW;\n}\n\nfunction descriptorPath(handle: Awaited<ReturnType<typeof fs.open>>): string {\n return `${requireSecureDirectoryDescriptors()}/${handle.fd}`;\n}\n\nasync function openPinnedDirectory(target: string, expectedIdentity?: AgentMemoryTaskContext['homeIdentity']): Promise<Awaited<ReturnType<typeof fs.open>>> {\n requireSecureDirectoryDescriptors();\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined;\n try {\n handle = await fs.open(target, noFollowFlags(fsConstants.O_RDONLY | fsConstants.O_DIRECTORY));\n const stat = await handle.stat({ bigint: true });\n if (!stat.isDirectory() || stat.isSymbolicLink() || (expectedIdentity !== undefined && (stat.dev !== expectedIdentity.dev || stat.ino !== expectedIdentity.ino))) throw new AgentMemoryError('memory directory is not a real directory');\n return handle;\n } catch (error) {\n await handle?.close().catch(() => {});\n if (error instanceof AgentMemoryError) throw error;\n throw new AgentMemoryError('memory directory is unavailable or unsafe');\n }\n}\n\nasync function withPinnedDirectory<T>(home: string, parts: readonly string[], operation: (directory: Awaited<ReturnType<typeof fs.open>>) => Promise<T>, expectedHomeIdentity?: AgentMemoryTaskContext['homeIdentity']): Promise<T> {\n const handles: Array<Awaited<ReturnType<typeof fs.open>>> = [];\n try {\n let directory = await openPinnedDirectory(home, expectedHomeIdentity);\n handles.push(directory);\n for (const part of parts) {\n directory = await openPinnedDirectory(`${descriptorPath(directory)}/${part}`);\n handles.push(directory);\n }\n return await operation(directory);\n } finally {\n await Promise.all(handles.reverse().map((handle) => handle.close().catch(() => {})));\n }\n}\n\nasync function withMemoryParent<T>(context: AgentMemoryTaskContext, relativePath: string, operation: (directory: Awaited<ReturnType<typeof fs.open>>, fileName: string) => Promise<T>): Promise<T> {\n const parts = relativePath.split('/');\n const fileName = parts.pop();\n if (fileName === undefined || parts.some((part) => !SAFE_SEGMENT.test(part) && part !== '.byok')) throw new AgentMemoryError('memory path is invalid');\n return withPinnedDirectory(context.canonicalHome, parts, (directory) => operation(directory, fileName), context.homeIdentity);\n}\n\ntype FileState = AgentMemoryFilesystemFileState;\nasync function readPinnedFile(directory: Awaited<ReturnType<typeof fs.open>>, fileName: string, maxBytes = AGENT_MEMORY_MAX_FILE_BYTES): Promise<FileState> {\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined;\n try {\n // O_NONBLOCK prevents a leaf swapped to a FIFO/device from wedging before\n // descriptor stat can reject it. It has no effect on regular-file reads.\n handle = await fs.open(\n `${descriptorPath(directory)}/${fileName}`,\n noFollowFlags(fsConstants.O_RDONLY | fsConstants.O_NONBLOCK),\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return Object.freeze({ exists: false, content: '', revision: digest(''), byteCount: 0 });\n throw new AgentMemoryError('could not open memory file');\n }\n try {\n const before = await handle.stat({ bigint: true });\n if (!before.isFile() || before.isSymbolicLink() || before.size > BigInt(maxBytes)) throw new AgentMemoryError('memory file is not a bounded regular file');\n const bytes = Buffer.alloc(Number(before.size));\n let offset = 0;\n while (offset < bytes.length) { const read = await handle.read(bytes, offset, bytes.length - offset, offset); if (read.bytesRead === 0) break; offset += read.bytesRead; }\n const after = await handle.stat({ bigint: true });\n if (offset !== bytes.length || after.size !== before.size || after.mtimeNs !== before.mtimeNs || after.ino !== before.ino) throw new AgentMemoryError('memory file changed during read');\n const content = bytes.toString('utf8');\n // A content revision is defined over bytes, while MCP is UTF-8 text. Do\n // not silently hash a replacement-character projection of arbitrary bytes.\n if (!Buffer.from(content, 'utf8').equals(bytes)) throw new AgentMemoryError('memory file is not valid UTF-8');\n return Object.freeze({ exists: true, content, revision: digestBytes(bytes), byteCount: bytes.length });\n } finally { await handle.close().catch(() => {}); }\n}\nasync function readFile(context: AgentMemoryTaskContext, relativePath: string, maxBytes = AGENT_MEMORY_MAX_FILE_BYTES): Promise<FileState> {\n if (context.filesystem !== undefined) return context.filesystem.read(relativePath, maxBytes);\n return withMemoryParent(context, relativePath, (directory, fileName) => readPinnedFile(directory, fileName, maxBytes));\n}\nasync function syncDirectory(directory: Awaited<ReturnType<typeof fs.open>>): Promise<void> {\n try { await directory.sync(); }\n catch (error) { if (!['EINVAL', 'EPERM'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error; }\n}\nasync function replaceNative(context: AgentMemoryTaskContext, relativePath: string, expected: string, content: string): Promise<FileState> {\n const byteCount = encoder.encode(content).byteLength;\n if (byteCount > AGENT_MEMORY_MAX_FILE_BYTES) throw new AgentMemoryError('memory content exceeds its bounded file size');\n return withMemoryParent(context, relativePath, async (directory, fileName) => {\n const before = await readPinnedFile(directory, fileName);\n if (before.revision !== expected) throw new AgentMemoryRevisionConflictError(expected, before.revision);\n const parent = descriptorPath(directory);\n const temporary = `${parent}/.byok-memory-${randomUUID()}.tmp`;\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined;\n try {\n const check = await readPinnedFile(directory, fileName);\n if (check.revision !== expected || check.exists !== before.exists) throw new AgentMemoryRevisionConflictError(expected, check.revision);\n handle = await fs.open(temporary, noFollowFlags(fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL), 0o600);\n await handle.writeFile(content, 'utf8'); await handle.sync(); await handle.close(); handle = undefined;\n const finalCheck = await readPinnedFile(directory, fileName);\n if (finalCheck.revision !== expected || finalCheck.exists !== before.exists) throw new AgentMemoryRevisionConflictError(expected, finalCheck.revision);\n await fs.rename(temporary, `${parent}/${fileName}`); await syncDirectory(directory);\n return Object.freeze({ exists: true, content, revision: digest(content), byteCount });\n } catch (error) {\n await handle?.close().catch(() => {}); await fs.rm(temporary, { force: true }).catch(() => {});\n if (error instanceof AgentMemoryError) throw error;\n throw new AgentMemoryError('could not atomically replace memory file');\n }\n });\n}\nasync function replace(context: AgentMemoryTaskContext, relativePath: string, expected: string, content: string): Promise<FileState> {\n if (context.filesystem !== undefined) return context.filesystem.replace(relativePath, expected, content, AGENT_MEMORY_MAX_FILE_BYTES);\n return replaceNative(context, relativePath, expected, content);\n}\nasync function removeNative(context: AgentMemoryTaskContext, relativePath: string, expected: string): Promise<void> {\n if (relativePath === 'MEMORY.md') throw new AgentMemoryError('MEMORY.md may not be deleted');\n await withMemoryParent(context, relativePath, async (directory, fileName) => {\n const before = await readPinnedFile(directory, fileName);\n if (!before.exists || before.revision !== expected) throw new AgentMemoryRevisionConflictError(expected, before.revision);\n const parent = descriptorPath(directory);\n const tombstone = `${parent}/.byok-memory-delete-${randomUUID()}.tmp`;\n try {\n const check = await readPinnedFile(directory, fileName);\n if (!check.exists || check.revision !== expected) throw new AgentMemoryRevisionConflictError(expected, check.revision);\n await fs.rename(`${parent}/${fileName}`, tombstone); await syncDirectory(directory); await fs.rm(tombstone); await syncDirectory(directory);\n } catch (error) {\n if (error instanceof AgentMemoryError) throw error;\n throw new AgentMemoryError('could not atomically delete memory file');\n }\n });\n}\nasync function remove(context: AgentMemoryTaskContext, relativePath: string, expected: string): Promise<void> {\n if (relativePath === 'MEMORY.md') throw new AgentMemoryError('MEMORY.md may not be deleted');\n if (context.filesystem !== undefined) return context.filesystem.delete(relativePath, expected);\n return removeNative(context, relativePath, expected);\n}\n\n/** Read one SDK-internal bounded state file through the same pinned home authority. */\nasync function readInternalFile(context: AgentMemoryTaskContext, fileName: string): Promise<FileState> {\n const relativePath = `${AGENT_HOME_INTERNAL_DIRECTORY}/${fileName}`;\n if (context.filesystem !== undefined) return context.filesystem.read(relativePath, AGENT_MEMORY_MAX_LOCAL_LOG_BYTES);\n return withPinnedDirectory(\n context.canonicalHome,\n [AGENT_HOME_INTERNAL_DIRECTORY],\n (directory) => readPinnedFile(directory, fileName, AGENT_MEMORY_MAX_LOCAL_LOG_BYTES),\n context.homeIdentity,\n );\n}\n\n/**\n * Atomically replace one SDK-internal bounded state file. Internal state never\n * uses append as an authority: a successful rename contains the whole next\n * state, and an interrupted write leaves the old state readable.\n */\nasync function replaceInternalFile(context: AgentMemoryTaskContext, fileName: string, expectedRevision: string, content: string): Promise<FileState> {\n const byteCount = encoder.encode(content).byteLength;\n if (byteCount > AGENT_MEMORY_MAX_LOCAL_LOG_BYTES) throw new AgentMemoryError('Agent memory internal state exceeds its bounded size');\n const relativePath = `${AGENT_HOME_INTERNAL_DIRECTORY}/${fileName}`;\n if (context.filesystem !== undefined) return context.filesystem.replace(relativePath, expectedRevision, content, AGENT_MEMORY_MAX_LOCAL_LOG_BYTES);\n return withPinnedDirectory(context.canonicalHome, [AGENT_HOME_INTERNAL_DIRECTORY], async (directory) => {\n const before = await readPinnedFile(directory, fileName, AGENT_MEMORY_MAX_LOCAL_LOG_BYTES);\n if (before.revision !== expectedRevision) throw new AgentMemoryRevisionConflictError(expectedRevision, before.revision);\n const parent = descriptorPath(directory);\n const temporary = `${parent}/.byok-agent-memory-${randomUUID()}.tmp`;\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined;\n try {\n handle = await fs.open(temporary, noFollowFlags(fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL), 0o600);\n await handle.writeFile(content, 'utf8'); await handle.sync(); await handle.close(); handle = undefined;\n const check = await readPinnedFile(directory, fileName, AGENT_MEMORY_MAX_LOCAL_LOG_BYTES);\n if (check.revision !== expectedRevision || check.exists !== before.exists) throw new AgentMemoryRevisionConflictError(expectedRevision, check.revision);\n await fs.rename(temporary, `${parent}/${fileName}`); await syncDirectory(directory);\n return Object.freeze({ exists: true, content, revision: digest(content), byteCount });\n } catch (error) {\n await handle?.close().catch(() => {}); await fs.rm(temporary, { force: true }).catch(() => {});\n if (error instanceof AgentMemoryError) throw error;\n throw new AgentMemoryError('could not atomically replace Agent memory internal state');\n }\n }, context.homeIdentity);\n}\n\nfunction boundedAuditTail(previous: string, entry: string): string {\n if (encoder.encode(entry).byteLength > AGENT_MEMORY_MAX_LOCAL_LOG_BYTES) throw new AgentMemoryError('Agent memory audit entry exceeds its bounded size');\n // Audit is intentionally metadata-only and is not a replay authority. Keep\n // complete newest lines only; a malformed old tail cannot wedge a local save.\n const lines = previous.split('\\n').filter((line) => line.length > 0);\n const kept = [entry];\n let byteCount = encoder.encode(entry).byteLength;\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const candidate = `${lines[index]}\\n`;\n const candidateBytes = encoder.encode(candidate).byteLength;\n if (byteCount + candidateBytes > AGENT_MEMORY_MAX_LOCAL_LOG_BYTES) break;\n kept.unshift(candidate); byteCount += candidateBytes;\n }\n return kept.join('');\n}\n\nasync function audit(context: AgentMemoryTaskContext, kind: 'recall' | 'save' | 'snapshot', values: Record<string, unknown>): Promise<void> {\n const entry = `${JSON.stringify({ version: 1, kind, taskId: context.taskId, tenantId: context.tenantId, deviceId: context.deviceId, agentRef: context.agentRef, sessionRef: context.sessionRef, runtimeId: context.runtimeId, ...values, recordedAt: new Date().toISOString() })}\\n`;\n const current = await readInternalFile(context, AGENT_MEMORY_AUDIT_FILENAME);\n await replaceInternalFile(context, AGENT_MEMORY_AUDIT_FILENAME, current.revision, boundedAuditTail(current.content, entry));\n}\n\nexport interface AgentMemoryAuditWarning {\n /** Metadata-only signal: the local source operation already succeeded. */\n readonly code: 'agent_memory_audit_unavailable';\n}\nexport interface AgentMemoryRecallResult {\n readonly path: string;\n readonly revision: string;\n readonly content: string;\n readonly auditWarning?: AgentMemoryAuditWarning;\n}\nexport interface AgentMemorySaveResult {\n readonly path: string;\n readonly revision?: string;\n readonly deleted: boolean;\n readonly auditWarning?: AgentMemoryAuditWarning;\n}\n\nasync function recordAuditWarning(context: AgentMemoryTaskContext, kind: 'recall' | 'save', values: Record<string, unknown>): Promise<AgentMemoryAuditWarning | undefined> {\n try {\n await audit(context, kind, values);\n return undefined;\n } catch {\n // The source read or mutation already succeeded. Never invent a rollback\n // or source failure from a metadata-only observation failure.\n return Object.freeze({ code: 'agent_memory_audit_unavailable' as const });\n }\n}\n\nconst agentMemoryHomeQueues = new Map<string, Promise<void>>();\n\nasync function exclusiveAgentMemoryHome<T>(home: string, fn: () => Promise<T>): Promise<T> {\n const previous = agentMemoryHomeQueues.get(home) ?? Promise.resolve();\n let release!: () => void;\n const next = new Promise<void>((resolve) => { release = resolve; });\n agentMemoryHomeQueues.set(home, next);\n await previous;\n try {\n return await fn();\n } finally {\n release();\n if (agentMemoryHomeQueues.get(home) === next) agentMemoryHomeQueues.delete(home);\n }\n}\n\nexport class AgentMemoryService {\n constructor(private readonly input: AgentMemoryTaskContext) {}\n async recall(input: { readonly path: unknown; readonly ifRevision?: unknown }): Promise<Readonly<AgentMemoryRecallResult>> {\n const context = taskContext(this.input); const relativePath = validateAgentMemoryPath(input.path);\n if (input.ifRevision !== undefined && !revision(input.ifRevision)) throw new AgentMemoryError('ifRevision must be a sha256 content revision');\n const current = await readFile(context, relativePath);\n if (!current.exists) throw new AgentMemoryError('memory file does not exist');\n if (input.ifRevision !== undefined && current.revision !== input.ifRevision) throw new AgentMemoryRevisionConflictError(input.ifRevision, current.revision);\n const auditWarning = await exclusiveAgentMemoryHome(context.canonicalHome, () => recordAuditWarning(context, 'recall', {\n path: relativePath,\n revision: current.revision,\n byteCount: current.byteCount,\n }));\n return Object.freeze({\n path: relativePath,\n revision: current.revision,\n content: current.content,\n ...(auditWarning === undefined ? {} : { auditWarning }),\n });\n }\n async save(input: { readonly op: unknown; readonly path: unknown; readonly expectedRevision: unknown; readonly content?: unknown }): Promise<Readonly<AgentMemorySaveResult>> {\n const context = taskContext(this.input); const relativePath = validateAgentMemoryPath(input.path);\n if ((input.op !== 'replace' && input.op !== 'delete') || !revision(input.expectedRevision)) throw new AgentMemoryError('memory save requires op and sha256 expectedRevision');\n if (input.op === 'replace' && typeof input.content !== 'string') throw new AgentMemoryError('replace requires string content');\n if (input.op === 'delete' && input.content !== undefined) throw new AgentMemoryError('delete does not accept content');\n const expectedRevision = input.expectedRevision;\n const content = input.content;\n return exclusiveAgentMemoryHome(context.canonicalHome, async () => {\n if (input.op === 'delete') {\n await remove(context, relativePath, expectedRevision);\n const auditWarning = await recordAuditWarning(context, 'save', { path: relativePath, operation: 'delete' });\n return Object.freeze({ path: relativePath, deleted: true, ...(auditWarning === undefined ? {} : { auditWarning }) });\n }\n if (typeof content !== 'string') throw new AgentMemoryError('replace requires string content');\n const current = await replace(context, relativePath, expectedRevision, content);\n const auditWarning = await recordAuditWarning(context, 'save', { path: relativePath, operation: 'replace', revision: current.revision, byteCount: current.byteCount });\n return Object.freeze({ path: relativePath, revision: current.revision, deleted: false, ...(auditWarning === undefined ? {} : { auditWarning }) });\n });\n }\n}\n\nasync function memoryNotePaths(context: AgentMemoryTaskContext): Promise<readonly string[]> {\n if (context.filesystem !== undefined) {\n const paths = await context.filesystem.walk('notes', AGENT_MEMORY_MAX_SNAPSHOT_ENTRIES);\n const candidates: string[] = [];\n for (const candidate of paths) {\n try { candidates.push(validateAgentMemoryPath(candidate)); } catch { /* opaque non-memory file */ }\n }\n return Object.freeze(candidates);\n }\n const candidates: string[] = [];\n let entriesSeen = 0;\n async function walk(directory: Awaited<ReturnType<typeof fs.open>>, relativeDirectory: string): Promise<void> {\n const entries = await fs.readdir(descriptorPath(directory), { withFileTypes: true });\n for (const entry of entries) {\n entriesSeen += 1;\n if (entriesSeen > AGENT_MEMORY_MAX_SNAPSHOT_ENTRIES) throw new AgentMemoryError('memory snapshot exceeds bounded directory entries');\n const candidate = `${relativeDirectory}/${entry.name}`;\n if (entry.isSymbolicLink()) throw new AgentMemoryError('memory notes contains a symlink');\n if (entry.isDirectory()) {\n // A directory component has the same safe-name policy as a leaf. An\n // unsafe directory is opaque local state and is never traversed.\n if (SAFE_SEGMENT.test(entry.name) && !SECRET_LIKE.test(entry.name) && entry.name !== '.byok') {\n const nested = await openPinnedDirectory(`${descriptorPath(directory)}/${entry.name}`);\n try { await walk(nested, candidate); } finally { await nested.close().catch(() => {}); }\n }\n continue;\n }\n if (!entry.isFile()) continue;\n try { candidates.push(validateAgentMemoryPath(candidate)); } catch { /* opaque non-memory file */ }\n }\n }\n await withPinnedDirectory(context.canonicalHome, ['notes'], (directory) => walk(directory, 'notes'), context.homeIdentity);\n return Object.freeze(candidates);\n}\n\n/** Bounded stable snapshot, called after Session.close() while the Agent lease still exists. */\nexport async function captureAgentMemorySnapshot(input: AgentMemoryTaskContext): Promise<AgentMemorySnapshot> {\n const context = taskContext(input); const candidates = ['MEMORY.md', ...await memoryNotePaths(context)];\n const paths = [...new Set(candidates)].sort((a, b) => a.localeCompare(b));\n if (paths.length > AGENT_MEMORY_MAX_SNAPSHOT_FILES) throw new AgentMemoryError('memory snapshot exceeds bounded file count');\n const files: AgentMemoryFile[] = []; let totalBytes = 0;\n for (const relativePath of paths) {\n const current = await readFile(context, relativePath);\n if (!current.exists) { if (relativePath === 'MEMORY.md') throw new AgentMemoryError('MEMORY.md disappeared before snapshot'); continue; }\n totalBytes += current.byteCount; if (totalBytes > AGENT_MEMORY_MAX_SNAPSHOT_BYTES) throw new AgentMemoryError('memory snapshot exceeds bounded total size');\n files.push(Object.freeze({ path: relativePath, revision: current.revision, byteCount: current.byteCount, content: current.content }));\n }\n const snapshot = Object.freeze({ files: Object.freeze(files), totalBytes });\n await exclusiveAgentMemoryHome(context.canonicalHome, () => audit(context, 'snapshot', {\n files: files.map((file) => ({ path: file.path, revision: file.revision, byteCount: file.byteCount })),\n }));\n return snapshot;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) return false;\n return left.every((value, index) => value === right[index]);\n}\n\n/** Canonical local-only raw form used solely to reject an obvious identity redactor. */\nfunction rawSnapshotBytes(snapshot: AgentMemorySnapshot): Uint8Array {\n return encoder.encode(JSON.stringify({\n files: snapshot.files.map((file) => ({ path: file.path, revision: file.revision, byteCount: file.byteCount, content: file.content })),\n }));\n}\n\nfunction redactedBytes(raw: AgentMemorySnapshot, candidate: Uint8Array): Uint8Array {\n if (!(candidate instanceof Uint8Array)) throw new AgentMemoryError('redactor must return Uint8Array bytes');\n const bytes = candidate.slice();\n if (bytes.byteLength > AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES) throw new AgentMemoryError('redacted snapshot exceeds bounded projection bytes');\n if (bytesEqual(bytes, rawSnapshotBytes(raw))) throw new AgentMemoryError('identity/pass-through redactor is forbidden');\n return bytes;\n}\n\ninterface OutboxHighWater { readonly writerEpoch: number; readonly sourceSeq: number; }\ninterface OutboxState {\n readonly version: 2;\n readonly currentWriterEpoch: number;\n /** Retained after compaction so a restart cannot reset the current epoch. */\n readonly highWater: readonly OutboxHighWater[];\n /** Redacted immutable mutations only, in source-sequence order. */\n readonly pending: readonly AgentMemoryRedactedOutboxRecord[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value); }\nfunction exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n const actual = Object.keys(value).sort(); const expected = [...keys].sort();\n return actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\nfunction validOrderingValue(value: unknown, allowZero = false): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= (allowZero ? 0 : 1) && value <= AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE;\n}\nfunction freezeOutboxRecord(value: unknown): AgentMemoryRedactedOutboxRecord {\n if (!isPlainRecord(value) || !exactKeys(value, ['version', 'mutation', 'createdAt']) || value.version !== 2 || typeof value.createdAt !== 'string' || value.createdAt.length === 0 || /[\\u0000\\r\\n]/u.test(value.createdAt)) throw new AgentMemoryError('Agent memory outbox state is invalid');\n const mutation = AgentMemoryProjectionMutationSchema.safeParse(value.mutation);\n if (!mutation.success) throw new AgentMemoryError('Agent memory outbox state is invalid');\n return Object.freeze({ version: 2 as const, mutation: Object.freeze(mutation.data), createdAt: value.createdAt });\n}\nfunction freezeOutboxState(value: unknown): OutboxState {\n if (!isPlainRecord(value) || !exactKeys(value, ['version', 'currentWriterEpoch', 'highWater', 'pending']) || value.version !== 2 || !validOrderingValue(value.currentWriterEpoch) || !Array.isArray(value.highWater) || !Array.isArray(value.pending)) throw new AgentMemoryError('Agent memory outbox state is invalid');\n if (value.highWater.length > 1 || value.pending.length > 1) throw new AgentMemoryError('Agent memory outbox state is invalid');\n const highWater = value.highWater.map((entry): OutboxHighWater => {\n if (!isPlainRecord(entry) || !exactKeys(entry, ['writerEpoch', 'sourceSeq']) || !validOrderingValue(entry.writerEpoch) || !validOrderingValue(entry.sourceSeq, true)) throw new AgentMemoryError('Agent memory outbox state is invalid');\n if (entry.writerEpoch !== value.currentWriterEpoch) throw new AgentMemoryError('Agent memory outbox state is invalid');\n return Object.freeze({ writerEpoch: entry.writerEpoch, sourceSeq: entry.sourceSeq });\n }).sort((left, right) => left.writerEpoch - right.writerEpoch);\n const pending = value.pending.map(freezeOutboxRecord).sort((left, right) => left.mutation.sourceSeq - right.mutation.sourceSeq);\n const seenEpochs = new Set<number>(); const highWaterByEpoch = new Map<number, number>();\n for (const entry of highWater) {\n if (seenEpochs.has(entry.writerEpoch)) throw new AgentMemoryError('Agent memory outbox state is invalid');\n seenEpochs.add(entry.writerEpoch); highWaterByEpoch.set(entry.writerEpoch, entry.sourceSeq);\n }\n const mutationIds = new Set<string>(); const sourceSeqs = new Set<number>();\n for (const record of pending) {\n if (record.mutation.writerEpoch !== value.currentWriterEpoch || mutationIds.has(record.mutation.mutationId) || sourceSeqs.has(record.mutation.sourceSeq) || record.mutation.sourceSeq > (highWaterByEpoch.get(record.mutation.writerEpoch) ?? 0)) throw new AgentMemoryError('Agent memory outbox state is invalid');\n mutationIds.add(record.mutation.mutationId); sourceSeqs.add(record.mutation.sourceSeq);\n }\n return Object.freeze({ version: 2 as const, currentWriterEpoch: value.currentWriterEpoch, highWater: Object.freeze(highWater), pending: Object.freeze(pending) });\n}\nfunction outboxStateJson(state: OutboxState): string {\n return JSON.stringify({ version: state.version, currentWriterEpoch: state.currentWriterEpoch, highWater: state.highWater, pending: state.pending });\n}\nfunction initialOutboxState(writerEpoch: number): OutboxState { return freezeOutboxState({ version: 2, currentWriterEpoch: writerEpoch, highWater: [], pending: [] }); }\nfunction stateWithHighWater(state: OutboxState, writerEpoch: number, sourceSeq: number, pending: readonly AgentMemoryRedactedOutboxRecord[]): OutboxState {\n if (writerEpoch !== state.currentWriterEpoch) throw new AgentMemoryError('Agent memory outbox state is invalid');\n return freezeOutboxState({ version: 2, currentWriterEpoch: state.currentWriterEpoch, highWater: [Object.freeze({ writerEpoch, sourceSeq })], pending });\n}\n\nasync function publishAgentMemoryProjection(port: AgentMemoryProjectionPort, mutation: AgentMemoryProjectionMutation): Promise<{ readonly accepted: boolean }> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await new Promise<{ readonly accepted: boolean }>((resolve, reject) => {\n timer = setTimeout(\n () => reject(new AgentMemoryError('Agent memory projection publish timed out')),\n AGENT_MEMORY_PROJECTION_PUBLISH_TIMEOUT_MS,\n );\n try {\n Promise.resolve(port.publish(Object.freeze({ mutation }))).then(resolve, reject);\n } catch (error) {\n reject(error);\n }\n });\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nexport class AgentMemoryRedactedOutbox {\n private state!: OutboxState;\n private fileRevision!: string;\n private writeTail: Promise<void> = Promise.resolve();\n private constructor(private readonly context: AgentMemoryTaskContext, private readonly grant: AgentMemoryProjectionGrant, readonly filePath: string) {}\n static async open(input: AgentMemoryTaskContext, grant: AgentMemoryProjectionGrant): Promise<AgentMemoryRedactedOutbox> {\n const context = taskContext(input);\n const outbox = new AgentMemoryRedactedOutbox(context, grant, path.join(context.canonicalHome, AGENT_HOME_INTERNAL_DIRECTORY, AGENT_MEMORY_OUTBOX_FILENAME));\n await outbox.load(); await outbox.admitGrant();\n return outbox;\n }\n pending(): readonly AgentMemoryRedactedOutboxRecord[] { return this.state.pending; }\n async append(bytes: Uint8Array): Promise<AgentMemoryRedactedOutboxRecord> { return this.exclusive(async () => {\n if (this.state.currentWriterEpoch !== this.grant.writerEpoch) throw new AgentMemoryError('Agent memory outbox writer epoch is stale');\n if (this.state.pending.length > 0) throw new AgentMemoryError('Agent memory outbox has pending projection mutations');\n const currentHighWater = this.state.highWater[0]?.sourceSeq ?? 0;\n if (currentHighWater >= AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE) throw new AgentMemoryError('Agent memory outbox source sequence is exhausted');\n const sourceSeq = currentHighWater + 1;\n const mutation = AgentMemoryProjectionMutationSchema.parse({\n taskId: this.context.taskId, agentRef: this.context.agentRef, sessionRef: this.context.sessionRef, runtimeId: this.context.runtimeId,\n grantRef: this.grant.grantRef, writerEpoch: this.grant.writerEpoch, sourceSeq, mutationId: randomUUID(), policyRevision: this.grant.policyRevision,\n snapshot: { redactedHash: digestBytes(bytes), redactedByteCount: bytes.byteLength, redactedBytes: Buffer.from(bytes).toString('base64url') },\n });\n const record: AgentMemoryRedactedOutboxRecord = Object.freeze({ version: 2, mutation: Object.freeze(mutation), createdAt: new Date().toISOString() });\n await this.persist(stateWithHighWater(this.state, mutation.writerEpoch, mutation.sourceSeq, [record]));\n return record;\n }); }\n async replay(port: AgentMemoryProjectionPort): Promise<AgentMemoryProjectionReplayOutcome> { return this.exclusive(async () => {\n for (const record of this.pending()) {\n if (!(await publishAgentMemoryProjection(port, record.mutation)).accepted) {\n return Object.freeze({\n status: 'pending' as const,\n writerEpoch: record.mutation.writerEpoch,\n sourceSeq: record.mutation.sourceSeq,\n mutationId: record.mutation.mutationId,\n });\n }\n // An accepted mutation is compacted atomically, while the epoch's\n // high-water remains durable across restart.\n await this.persist(freezeOutboxState({\n version: 2, currentWriterEpoch: this.state.currentWriterEpoch, highWater: this.state.highWater,\n pending: this.state.pending.filter((candidate) => candidate.mutation.mutationId !== record.mutation.mutationId),\n }));\n }\n return DRAINED_AGENT_MEMORY_PROJECTION_REPLAY;\n }); }\n private async load(): Promise<void> {\n const current = await readInternalFile(this.context, AGENT_MEMORY_OUTBOX_FILENAME);\n this.fileRevision = current.revision;\n this.state = current.exists ? this.loadBody(current.content) : initialOutboxState(this.grant.writerEpoch);\n }\n private loadBody(body: string): OutboxState {\n try { return freezeOutboxState(JSON.parse(body) as unknown); }\n catch { throw new AgentMemoryError('Agent memory outbox state is invalid'); }\n }\n private async admitGrant(): Promise<void> {\n if (this.grant.writerEpoch < this.state.currentWriterEpoch) throw new AgentMemoryError('Agent memory outbox writer epoch is stale');\n if (this.grant.writerEpoch === this.state.currentWriterEpoch) return;\n // A newer host-issued writer epoch explicitly supersedes an undelivered\n // prior epoch. One atomic replacement clears its pending body and all old\n // high-water; its first source sequence is one. Same-epoch opens cannot\n // reset either pending state or the current epoch's high-water.\n await this.persist(freezeOutboxState({ version: 2, currentWriterEpoch: this.grant.writerEpoch, highWater: [], pending: [] }));\n }\n private async persist(next: OutboxState): Promise<void> {\n const replaced = await replaceInternalFile(this.context, AGENT_MEMORY_OUTBOX_FILENAME, this.fileRevision, outboxStateJson(next));\n this.fileRevision = replaced.revision; this.state = next;\n }\n private async exclusive<T>(fn: () => Promise<T>): Promise<T> {\n const previous = this.writeTail; let release!: () => void;\n this.writeTail = new Promise<void>((resolve) => { release = resolve; }); await previous;\n try { return await fn(); } finally { release(); }\n }\n}\n\n/** Missing capability, grant, redactor, or port has exactly zero network side effects. */\nexport async function snapshotAndProjectAgentMemory(input: AgentMemoryTaskContext, projection: AgentMemoryHostedProjection | undefined): Promise<void> {\n if (projection?.capability !== AGENT_MEMORY_PROJECTION_CAPABILITY || !projection.grant || !projection.redactor || !projection.port) return;\n const context = taskContext(input);\n const outbox = await AgentMemoryRedactedOutbox.open(context, projection.grant);\n // Pending redacted mutations retain their original task/session/runtime/grant\n // binding. Drain them before touching local source files or minting a newer\n // sequence, so an offline replay cannot create a source-sequence gap.\n const initialReplay = await outbox.replay(projection.port);\n if (initialReplay.status === 'pending') throw new AgentMemoryProjectionReplayPendingError(initialReplay);\n const snapshot = await captureAgentMemorySnapshot(context);\n await outbox.append(redactedBytes(snapshot, await projection.redactor.redact(snapshot)));\n const trailingReplay = await outbox.replay(projection.port);\n if (trailingReplay.status === 'pending') throw new AgentMemoryProjectionReplayPendingError(trailingReplay);\n}\n","import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport path from 'node:path';\n\nimport type { AgentHomeLease } from '../agent-home';\nimport { AgentMemoryError, AgentMemoryRevisionConflictError } from './agent-memory';\nimport type { AgentMemoryFilesystem, AgentMemoryFilesystemFileState } from './agent-memory-filesystem';\n\nexport const AGENT_MEMORY_FILESYSTEM_HELPER_PROTOCOL = 2;\nexport const AGENT_MEMORY_FILESYSTEM_HELPER_VERSION = '2';\nconst HELPER_REQUEST_TIMEOUT_MS = 10_000;\nconst HELPER_MAX_JSON_LINE_BYTES = 2 * 1024 * 1024;\nconst HELPER_MAX_CONTENT_BYTES = 1 * 1024 * 1024;\nconst HELPER_MAX_STDERR_BYTES = 4 * 1024;\n\ninterface HelperSuccess {\n readonly id: string;\n readonly ok: true;\n readonly protocol: 2;\n readonly result: Record<string, unknown>;\n}\ninterface HelperFailure {\n readonly id: string;\n readonly ok: false;\n readonly protocol: 2;\n readonly error: { readonly code: string; readonly message: string; readonly actualRevision?: string };\n}\ntype HelperResponse = HelperSuccess | HelperFailure;\ntype Pending = { readonly resolve: (response: HelperSuccess) => void; readonly reject: (error: Error) => void; readonly timer: NodeJS.Timeout };\nclass HelperRevisionConflict extends Error {\n constructor(readonly actualRevision: string) { super('helper revision conflict'); }\n}\n\nfunction safeHelperPath(value: unknown): string {\n if (typeof value !== 'string' || !path.isAbsolute(value) || value.length === 0 || /[\\u0000\\r\\n]/u.test(value)) {\n throw new AgentMemoryError('Agent memory filesystem helper must be an explicit absolute executable path');\n }\n return path.resolve(value);\n}\n\nfunction helperPlatformSupported(): boolean {\n // Windows remains closed until the native reparse/junction matrix is run on\n // a real Windows host. Linux retains its existing native descriptor backend;\n // the external process authority is admitted only for the proven macOS gap.\n return process.platform === 'darwin';\n}\n\nexport function isAgentMemoryFilesystemHelperSupported(): boolean {\n return helperPlatformSupported();\n}\n\nfunction unixIdentity(homeIdentity: AgentHomeLease['homeIdentity']): Readonly<Record<string, string>> {\n return Object.freeze({ kind: 'unix', dev: homeIdentity.dev.toString(10), ino: homeIdentity.ino.toString(10) });\n}\n\nfunction responseRecord(value: unknown): HelperResponse | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n if (typeof record.id !== 'string' || record.protocol !== AGENT_MEMORY_FILESYSTEM_HELPER_PROTOCOL || typeof record.ok !== 'boolean') return undefined;\n if (record.ok) {\n if (record.result === null || typeof record.result !== 'object' || Array.isArray(record.result)) return undefined;\n return record as unknown as HelperSuccess;\n }\n if (record.error === null || typeof record.error !== 'object' || Array.isArray(record.error)) return undefined;\n const error = record.error as Record<string, unknown>;\n if (typeof error.code !== 'string' || typeof error.message !== 'string' || (error.actualRevision !== undefined && typeof error.actualRevision !== 'string')) return undefined;\n return record as unknown as HelperFailure;\n}\n\nfunction boundedFileState(result: Record<string, unknown>, maxBytes: number): AgentMemoryFilesystemFileState {\n let content: string;\n try {\n if (typeof result.contentBase64 !== 'string' || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}|[A-Za-z0-9+/]{3})?$/u.test(result.contentBase64)) {\n throw new Error('invalid base64');\n }\n content = Buffer.from(result.contentBase64, 'base64').toString('utf8');\n } catch {\n throw new AgentMemoryError('Agent memory filesystem helper returned an invalid file state');\n }\n if (\n typeof result.exists !== 'boolean' ||\n typeof result.revision !== 'string' ||\n typeof result.byteCount !== 'number' ||\n !Number.isSafeInteger(result.byteCount) ||\n result.byteCount < 0 ||\n result.byteCount > maxBytes ||\n Buffer.byteLength(content, 'utf8') !== result.byteCount ||\n !/^sha256:[a-f0-9]{64}$/u.test(result.revision)\n ) {\n throw new AgentMemoryError('Agent memory filesystem helper returned an invalid file state');\n }\n return Object.freeze({ exists: result.exists, content, revision: result.revision, byteCount: result.byteCount });\n}\n\nfunction encodeReplaceContent(content: string, maxBytes: number): string {\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > HELPER_MAX_CONTENT_BYTES) {\n throw new AgentMemoryError('Agent memory filesystem helper requested an invalid byte limit');\n }\n const bytes = Buffer.from(content, 'utf8');\n if (bytes.byteLength > maxBytes) {\n throw new AgentMemoryError('Agent memory filesystem helper replacement exceeds its requested byte limit');\n }\n // The private v2 protocol intentionally uses unpadded standard base64. It\n // keeps arbitrary UTF-8 bytes below the bounded JSON-lines transport limit.\n return bytes.toString('base64').replace(/=+$/u, '');\n}\n\nclass AgentMemoryFilesystemHelperClient implements AgentMemoryFilesystem {\n private readonly pending = new Map<string, Pending>();\n private stdoutBuffer = Buffer.alloc(0);\n private sequence = 0;\n private stderrBytes = 0;\n private closed = false;\n private fatalError: Error | undefined;\n\n private constructor(private readonly child: ChildProcessWithoutNullStreams) {\n child.stdout.on('data', (chunk: Buffer | string) => this.handleStdoutChunk(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));\n child.stderr.on('data', (chunk: Buffer | string) => {\n this.stderrBytes += Buffer.byteLength(chunk);\n if (this.stderrBytes > HELPER_MAX_STDERR_BYTES) this.fail(new AgentMemoryError('Agent memory filesystem helper exceeded bounded stderr'));\n });\n child.stdin.on('error', () => this.fail(new AgentMemoryError('Agent memory filesystem helper request could not be written')));\n child.once('error', () => this.fail(new AgentMemoryError('Agent memory filesystem helper could not be started')));\n child.once('exit', (code, signal) => {\n if (!this.closed || code !== 0) this.fail(new AgentMemoryError(`Agent memory filesystem helper exited unexpectedly (${code ?? signal ?? 'unknown'})`));\n });\n }\n\n static async open(input: Readonly<{ helperBin: string; canonicalHome: string; homeIdentity: AgentHomeLease['homeIdentity'] }>): Promise<AgentMemoryFilesystemHelperClient> {\n if (!helperPlatformSupported()) throw new AgentMemoryError('Agent memory filesystem helper is not admitted on this platform');\n const helperBin = safeHelperPath(input.helperBin);\n const child = spawn(helperBin, ['serve'], {\n stdio: ['pipe', 'pipe', 'pipe'],\n shell: false,\n windowsHide: true,\n env: Object.freeze({}),\n });\n const client = new AgentMemoryFilesystemHelperClient(child);\n try {\n const result = await client.request('open', {\n root: path.resolve(input.canonicalHome),\n expectedIdentity: unixIdentity(input.homeIdentity),\n });\n if (result.helperVersion !== AGENT_MEMORY_FILESYSTEM_HELPER_VERSION) throw new AgentMemoryError('Agent memory filesystem helper version mismatch');\n const identity = result.identity;\n if (identity === null || typeof identity !== 'object' || Array.isArray(identity)) throw new AgentMemoryError('Agent memory filesystem helper omitted root identity');\n const actual = identity as Record<string, unknown>;\n const expected = unixIdentity(input.homeIdentity);\n if (actual.kind !== expected.kind || actual.dev !== expected.dev || actual.ino !== expected.ino) throw new AgentMemoryError('Agent memory filesystem helper root identity mismatch');\n return client;\n } catch (error) {\n await client.close().catch(() => {});\n throw error;\n }\n }\n\n async read(relativePath: string, maxBytes: number): Promise<AgentMemoryFilesystemFileState> {\n return boundedFileState(await this.request('read', { path: relativePath, maxBytes }), maxBytes);\n }\n\n async replace(relativePath: string, expectedRevision: string, content: string, maxBytes: number): Promise<AgentMemoryFilesystemFileState> {\n try {\n const contentBase64 = encodeReplaceContent(content, maxBytes);\n return boundedFileState(await this.request('replace', { path: relativePath, expectedRevision, contentBase64, maxBytes }), maxBytes);\n } catch (error) {\n if (error instanceof HelperRevisionConflict) throw new AgentMemoryRevisionConflictError(expectedRevision, error.actualRevision);\n throw error;\n }\n }\n\n async delete(relativePath: string, expectedRevision: string): Promise<void> {\n try {\n await this.request('delete', { path: relativePath, expectedRevision });\n } catch (error) {\n if (error instanceof HelperRevisionConflict) throw new AgentMemoryRevisionConflictError(expectedRevision, error.actualRevision);\n throw error;\n }\n }\n\n async append(relativePath: string, content: string, maxBytes: number): Promise<void> {\n await this.request('append', { path: relativePath, content, maxBytes });\n }\n\n async walk(relativePath: string, maxEntries: number): Promise<readonly string[]> {\n const result = await this.request('walk', { path: relativePath, maxEntries });\n if (!Array.isArray(result.paths) || result.paths.length > maxEntries || result.paths.some((candidate) => typeof candidate !== 'string')) {\n throw new AgentMemoryError('Agent memory filesystem helper returned an invalid walk result');\n }\n return Object.freeze([...result.paths] as string[]);\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n try {\n if (this.child.exitCode === null && this.child.signalCode === null && this.fatalError === undefined) await this.requestWhileClosing('close', {});\n } finally {\n this.child.stdin.end();\n if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill();\n this.rejectPending(new AgentMemoryError('Agent memory filesystem helper is closed'));\n }\n }\n\n private request(op: string, fields: Readonly<Record<string, unknown>>): Promise<Record<string, unknown>> {\n if (this.closed) return Promise.reject(new AgentMemoryError('Agent memory filesystem helper is closed'));\n return this.requestInternal(op, fields);\n }\n\n private requestWhileClosing(op: string, fields: Readonly<Record<string, unknown>>): Promise<Record<string, unknown>> {\n return this.requestInternal(op, fields);\n }\n\n private requestInternal(op: string, fields: Readonly<Record<string, unknown>>): Promise<Record<string, unknown>> {\n if (this.fatalError !== undefined) return Promise.reject(this.fatalError);\n const id = `m${++this.sequence}`;\n let line: string;\n try {\n line = `${JSON.stringify({ id, protocol: AGENT_MEMORY_FILESYSTEM_HELPER_PROTOCOL, op, ...fields })}\\n`;\n } catch {\n return Promise.reject(new AgentMemoryError('Agent memory filesystem helper request could not be encoded'));\n }\n if (Buffer.byteLength(line, 'utf8') > HELPER_MAX_JSON_LINE_BYTES) {\n return Promise.reject(new AgentMemoryError('Agent memory filesystem helper request exceeded bounded stdin'));\n }\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n const error = new AgentMemoryError('Agent memory filesystem helper request timed out');\n reject(error);\n this.fail(error);\n }, HELPER_REQUEST_TIMEOUT_MS);\n timer.unref?.();\n this.pending.set(id, { resolve: (response) => resolve(response.result), reject, timer });\n this.child.stdin.write(line, (error) => {\n if (!error) return;\n const item = this.pending.get(id);\n if (item === undefined) return;\n clearTimeout(item.timer);\n this.pending.delete(id);\n item.reject(new AgentMemoryError('Agent memory filesystem helper request could not be written'));\n });\n });\n }\n\n private handleStdoutChunk(chunk: Buffer): void {\n let offset = 0;\n while (offset < chunk.length && this.fatalError === undefined) {\n const newline = chunk.indexOf(0x0a, offset);\n const end = newline === -1 ? chunk.length : newline;\n const segment = chunk.subarray(offset, end);\n if (this.stdoutBuffer.length + segment.length > HELPER_MAX_JSON_LINE_BYTES) {\n this.fail(new AgentMemoryError('Agent memory filesystem helper exceeded bounded stdout'));\n return;\n }\n this.stdoutBuffer = this.stdoutBuffer.length === 0 ? Buffer.from(segment) : Buffer.concat([this.stdoutBuffer, segment]);\n if (newline === -1) return;\n const line = this.stdoutBuffer;\n this.stdoutBuffer = Buffer.alloc(0);\n this.handleLine(line);\n offset = newline + 1;\n }\n }\n\n private handleLine(line: Buffer): void {\n let parsed: unknown;\n try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(line)); } catch { this.fail(new AgentMemoryError('Agent memory filesystem helper returned malformed JSON')); return; }\n const response = responseRecord(parsed);\n if (response === undefined) { this.fail(new AgentMemoryError('Agent memory filesystem helper returned an invalid response')); return; }\n const item = this.pending.get(response.id);\n if (item === undefined) { this.fail(new AgentMemoryError('Agent memory filesystem helper returned an unsolicited response')); return; }\n clearTimeout(item.timer);\n this.pending.delete(response.id);\n if (response.ok) { item.resolve(response); return; }\n if (response.error.code === 'revision_conflict' && typeof response.error.actualRevision === 'string') {\n item.reject(new HelperRevisionConflict(response.error.actualRevision));\n return;\n }\n item.reject(new AgentMemoryError(`Agent memory filesystem helper rejected the operation: ${response.error.code}`));\n }\n\n private fail(error: Error): void {\n if (this.fatalError !== undefined) return;\n this.fatalError = error;\n this.rejectPending(error);\n if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill();\n }\n\n private rejectPending(error: Error): void {\n for (const item of this.pending.values()) { clearTimeout(item.timer); item.reject(error); }\n this.pending.clear();\n }\n}\n\nexport async function openAgentMemoryFilesystemHelper(input: Readonly<{ helperBin: string; canonicalHome: string; homeIdentity: AgentHomeLease['homeIdentity'] }>): Promise<AgentMemoryFilesystem> {\n return AgentMemoryFilesystemHelperClient.open(input);\n}\n","import { createInterface } from 'node:readline';\n\nexport const AGENT_MEMORY_RECALL_TOOL_NAME = 'memory.recall';\nexport const AGENT_MEMORY_SAVE_TOOL_NAME = 'memory.save';\n\nexport interface AgentMemoryMcpDeps {\n recall(input: { path: string; ifRevision?: string }): Promise<{ path: string; revision: string; content: string; auditWarning?: { code: 'agent_memory_audit_unavailable' } }>;\n save(input: { op: 'replace' | 'delete'; path: string; expectedRevision: string; content?: string }): Promise<{ path: string; revision?: string; deleted: boolean }>;\n}\ninterface RequestLike { jsonrpc?: unknown; id?: unknown; method?: unknown; params?: unknown }\nfunction record(value: unknown): Record<string, unknown> | undefined { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined; }\nfunction invalid(id: unknown, message: string): Record<string, unknown> { return { jsonrpc: '2.0', id, error: { code: -32602, message } }; }\nfunction success(id: unknown, value: unknown): Record<string, unknown> { return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(value) }] } }; }\n\nexport async function handleAgentMemoryMcpRequest(request: RequestLike, deps: AgentMemoryMcpDeps): Promise<Record<string, unknown> | undefined> {\n const id = request.id;\n if (request.method === 'initialize') {\n const params = record(request.params) ?? {};\n return { jsonrpc: '2.0', id, result: { protocolVersion: typeof params.protocolVersion === 'string' ? params.protocolVersion : '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'byok-agent-memory-mcp', version: '0.0.1' } } };\n }\n if (request.method === 'notifications/initialized') return undefined;\n if (request.method === 'tools/list') return {\n jsonrpc: '2.0', id, result: { tools: [\n { name: AGENT_MEMORY_RECALL_TOOL_NAME, description: 'Recall one SDK-owned memory file for this exact active Agent task. Identity and memory root are never model parameters.', inputSchema: { type: 'object', additionalProperties: false, required: ['path'], properties: { path: { type: 'string' }, ifRevision: { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' } } } },\n { name: AGENT_MEMORY_SAVE_TOOL_NAME, description: 'Atomically replace or delete one SDK-owned memory file with exact sha256 compare-and-swap.', inputSchema: { type: 'object', additionalProperties: false, required: ['op', 'path', 'expectedRevision'], properties: { op: { type: 'string', enum: ['replace', 'delete'] }, path: { type: 'string' }, expectedRevision: { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' }, content: { type: 'string' } } } },\n ] },\n };\n if (request.method !== 'tools/call') return id === undefined ? undefined : { jsonrpc: '2.0', id, error: { code: -32601, message: `unknown method: ${String(request.method)}` } };\n const params = record(request.params); const args = record(params?.arguments);\n if (!params || !args || typeof params.name !== 'string') return invalid(id, 'memory tool input must be an object');\n try {\n if (params.name === AGENT_MEMORY_RECALL_TOOL_NAME) {\n if (Object.keys(args).some((key) => key !== 'path' && key !== 'ifRevision') || typeof args.path !== 'string' || (args.ifRevision !== undefined && typeof args.ifRevision !== 'string')) return invalid(id, 'memory.recall accepts only path and optional ifRevision');\n return success(id, await deps.recall({ path: args.path, ...(args.ifRevision === undefined ? {} : { ifRevision: args.ifRevision }) }));\n }\n if (params.name === AGENT_MEMORY_SAVE_TOOL_NAME) {\n if (Object.keys(args).some((key) => key !== 'op' && key !== 'path' && key !== 'expectedRevision' && key !== 'content') || (args.op !== 'replace' && args.op !== 'delete') || typeof args.path !== 'string' || typeof args.expectedRevision !== 'string' || (args.op === 'replace' && typeof args.content !== 'string') || (args.op === 'delete' && args.content !== undefined)) return invalid(id, 'memory.save requires replace|delete, path, expectedRevision, and content only for replace');\n const content = args.content;\n return success(id, await deps.save({ op: args.op, path: args.path, expectedRevision: args.expectedRevision, ...(typeof content === 'string' ? { content } : {}) }));\n }\n return invalid(id, 'unknown Agent memory tool');\n } catch (error) { return { jsonrpc: '2.0', id, error: { code: -32000, message: error instanceof Error ? error.message : String(error) } }; }\n}\n\nexport function serveAgentMemoryMcpOverStdio(input: { deps: AgentMemoryMcpDeps; stdin?: NodeJS.ReadableStream; stdout?: NodeJS.WritableStream }): void {\n const reader = createInterface({ input: input.stdin ?? process.stdin, terminal: false }); const output = input.stdout ?? process.stdout;\n reader.on('line', (line) => { const trimmed = line.trim(); if (!trimmed) return; void (async () => { let request: RequestLike; try { request = JSON.parse(trimmed) as RequestLike; } catch { return; } const response = await handleAgentMemoryMcpRequest(request, input.deps); if (response !== undefined) output.write(`${JSON.stringify(response)}\\n`); })(); });\n}\n","/**\n * Runtime-neutral instructions for an Agent's model-authored local memory.\n *\n * This is deliberately prompt guidance only: the SDK does not read memory\n * content, infer durable values, or auto-inject files into the operation.\n */\nexport const AGENT_MEMORY_GUIDANCE = [\n 'At the start of this Agent task, first read `MEMORY.md` in the provided `cwd`.',\n 'Treat `MEMORY.md` as a concise, self-contained recovery index; if it is empty, initialize a brief index from durable, non-secret task knowledge.',\n 'Read files under `notes/` only as needed, following pointers from the index.',\n 'When task permissions allow and a durable value is learned, update the relevant `notes/` entry and the `MEMORY.md` index.',\n 'Never write credentials, secrets, tokens, API keys, private keys, or other authentication material to `MEMORY.md` or `notes/`.',\n].join('\\n');\n\nexport function prependAgentMemoryGuidance(instruction: string): string {\n return `${AGENT_MEMORY_GUIDANCE}\\n\\n${instruction}`;\n}\n"]}