Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(memory): add RPC and shared client state (#45)
Leo5fee5787fc59
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.tsindex 95ba4a7d9..c79b241a5 100644--- a/apps/server/src/auth/RpcAuthorization.test.ts+++ b/apps/server/src/auth/RpcAuthorization.test.ts@@ -30,6 +30,18 @@ describe("RPC authorization scopes", () => {);});+ it("separates memory reads from memory changes", () => {+ expect(requiredScopeForRpcMethod(WS_METHODS.memoryInspect)).toBe(AuthOrchestrationReadScope);+ expect(requiredScopeForRpcMethod(WS_METHODS.memoryExport)).toBe(AuthOrchestrationReadScope);+ expect(requiredScopeForRpcMethod(WS_METHODS.memoryImportPreview)).toBe(+ AuthOrchestrationReadScope,+ );+ expect(requiredScopeForRpcMethod(WS_METHODS.memoryImportApply)).toBe(+ AuthOrchestrationOperateScope,+ );+ expect(requiredScopeForRpcMethod(WS_METHODS.memoryMutate)).toBe(AuthOrchestrationOperateScope);+ });+it("allows relay status reads without granting relay installation access", () => {expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(AuthRelayReadScope,diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 087e7763d..25397b5f8 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -62,6 +62,11 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,+ [WS_METHODS.memoryInspect]: AuthOrchestrationReadScope,+ [WS_METHODS.memoryExport]: AuthOrchestrationReadScope,+ [WS_METHODS.memoryImportPreview]: AuthOrchestrationReadScope,+ [WS_METHODS.memoryImportApply]: AuthOrchestrationOperateScope,+ [WS_METHODS.memoryMutate]: AuthOrchestrationOperateScope,[WS_METHODS.portabilityExport]: AuthOrchestrationReadScope,[WS_METHODS.portabilityPreviewImport]: AuthOrchestrationReadScope,[WS_METHODS.portabilityApplyImport]: AuthOrchestrationOperateScope,diff --git a/apps/server/src/memory/MemoryExport.ts b/apps/server/src/memory/MemoryExport.tsindex 6a656beab..0f186bb77 100644--- a/apps/server/src/memory/MemoryExport.ts+++ b/apps/server/src/memory/MemoryExport.ts@@ -1,7 +1,7 @@import * as NodeCrypto from "node:crypto";import {- AkeruMemoryArchive,+ AkeruMemoryArchiveV2,type AkeruConversationMemorySnapshot,type AkeruMemoryArchiveTarget,type AkeruMemoryRevision,@@ -97,7 +97,7 @@ export function exportAkeruMemory(input: {})),conversations: conversations.map(({ threadId, sha256 }) => ({ threadId, sha256 })),});- return yield* Schema.decodeUnknownEffect(AkeruMemoryArchive)({+ return yield* Schema.decodeUnknownEffect(AkeruMemoryArchiveV2)({schemaVersion: 2,anchorThreadId: input.access.threadId,target: input.target,diff --git a/apps/server/src/memory/MemoryRpc.test.ts b/apps/server/src/memory/MemoryRpc.test.tsnew file mode 100644index 000000000..774112c87--- /dev/null+++ b/apps/server/src/memory/MemoryRpc.test.ts@@ -0,0 +1,179 @@+import {+ AkeruMemoryOperationError,+ AkeruMemoryCandidateId,+ AkeruMemoryId,+ AkeruMemoryRootId,+ AkeruMemoryEntityId,+ AkeruMemoryPartitionId,+ AkeruMemoryTenantId,+ AkeruMemoryUserId,+ BotId,+ ProjectId,+ ThreadId,+ type AkeruMemoryRevision,+} from "@t3tools/contracts";+import { assert, describe, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { createMemoryRpcHandlers } from "./MemoryRpc.ts";+import {+ EntityMemoryConflictError,+ type EntityMemoryRepositoryShape,+ type TombstoneEntityMemoryInput,+} from "./Services/EntityMemoryRepository.ts";+import {+ MemoryCandidateConflictError,+ type MemoryCandidateRepositoryShape,+} from "./Services/MemoryCandidateRepository.ts";++const access = {+ tenantId: AkeruMemoryTenantId.make("local"),+ userId: AkeruMemoryUserId.make("owner"),+ threadId: ThreadId.make("authorized-thread"),+ projectId: ProjectId.make("project"),+ workspaceRoot: "/tmp/project",+ botId: BotId.make("bot"),+ groupId: null,+ respondingBotId: BotId.make("bot"),+ groupMemberBotIds: [],+};++const revision = {+ id: AkeruMemoryId.make("revision-3"),+ rootId: AkeruMemoryRootId.make("root-1"),+ revision: 3,+ partition: {+ tenantId: access.tenantId,+ scope: "thread",+ partitionId: AkeruMemoryPartitionId.make("authorized-thread"),+ },+ entityKind: "other",+ entityId: AkeruMemoryEntityId.make("authorized-thread"),+ kind: "fact",+ value: {},+ fact: "A fact",+ sourceThreadId: ThreadId.make("source-thread"),+ sourceMessageId: null,+ authorBotId: BotId.make("bot"),+ initiatingUserId: AkeruMemoryUserId.make("owner"),+ createdAt: "2026-08-31T20:00:00.000Z",+ confirmedAt: "2026-08-31T20:00:00.000Z",+ updatedAt: "2026-08-31T20:00:00.000Z",+ confidence: 1,+ approvalState: "approved",+ supersedesId: null,+ supersededById: null,+ visibility: "private",+ deletionState: "active",+ pinned: false,+ sensitive: false,+ affectedBotIds: [BotId.make("bot")],+} satisfies AkeruMemoryRevision;++const candidates = {+ create: () => Effect.die("not used"),+ listPending: () => Effect.succeed([]),+ approve: () => Effect.die("not used"),+ reject: () => Effect.die("not used"),+} satisfies MemoryCandidateRepositoryShape;++describe("memory RPC handlers", () => {+ it.effect("exports conversation memory only from the authorized thread", () =>+ Effect.gen(function* () {+ const readThreads: ThreadId[] = [];+ const repository = {+ listByPartitions: () => Effect.succeed([revision]),+ } as unknown as EntityMemoryRepositoryShape;+ const handlers = createMemoryRpcHandlers({+ repository,+ candidates,+ readConversation: (threadId) =>+ Effect.sync(() => {+ readThreads.push(threadId);+ return { current: null, history: [] };+ }),+ clearConversation: () => Effect.void,+ });++ const archive = yield* handlers.exportArchive({+ access,+ target: "thread",+ complete: true,+ createdAt: "2026-08-31T21:00:00.000Z",+ });++ assert.deepEqual(readThreads, [access.threadId]);+ assert.equal(archive.anchorThreadId, access.threadId);+ assert.equal(archive.conversations[0]?.threadId, access.threadId);+ }),+ );++ it.effect(+ "passes delete revisions to tombstone and returns stale OCC as an operation error",+ () =>+ Effect.gen(function* () {+ const seen: number[] = [];+ const repository = {+ tombstone: (input: TombstoneEntityMemoryInput) =>+ Effect.sync(() => seen.push(input.expectedRevision)).pipe(+ Effect.andThen(+ Effect.fail(+ new EntityMemoryConflictError({+ rootId: input.rootId,+ expectedRevision: input.expectedRevision,+ actualRevision: 4,+ }),+ ),+ ),+ ),+ } as unknown as EntityMemoryRepositoryShape;+ const handlers = createMemoryRpcHandlers({+ repository,+ candidates,+ readConversation: () => Effect.succeed({ current: null, history: [] }),+ clearConversation: () => Effect.void,+ });++ const failure = yield* handlers+ .mutate(access, {+ operation: "fact.delete",+ memoryId: revision.rootId,+ expectedRevision: 3,+ })+ .pipe(Effect.flip);++ assert.deepEqual(seen, [3]);+ assert.instanceOf(failure, AkeruMemoryOperationError);+ assert.include(failure.detail, "Expected 3, found 4");+ }),+ );++ it.effect("returns candidate repository failures as operation errors", () =>+ Effect.gen(function* () {+ const candidateId = AkeruMemoryCandidateId.make("candidate-1");+ const failure = new MemoryCandidateConflictError({+ candidateId,+ detail: "The candidate batch failed.",+ });+ const handlers = createMemoryRpcHandlers({+ repository: {} as EntityMemoryRepositoryShape,+ candidates: {+ ...candidates,+ listPending: () => Effect.fail(failure),+ },+ readConversation: () => Effect.succeed({ current: null, history: [] }),+ clearConversation: () => Effect.void,+ });++ const result = yield* handlers+ .mutate(access, {+ operation: "candidate.decide",+ decision: { candidateId, decision: "reject" },+ })+ .pipe(Effect.flip);++ assert.instanceOf(result, AkeruMemoryOperationError);+ assert.include(result.detail, "candidate batch failed");+ }),+ );+});diff --git a/apps/server/src/memory/MemoryRpc.ts b/apps/server/src/memory/MemoryRpc.tsnew file mode 100644index 000000000..e64ef9e90--- /dev/null+++ b/apps/server/src/memory/MemoryRpc.ts@@ -0,0 +1,281 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeCrypto from "node:crypto";++import {+ AkeruMemoryEntityId,+ AkeruMemoryId,+ AkeruMemoryOperationError,+ AkeruMemoryRootId,+ type AkeruConversationMemorySnapshot,+ type AkeruMemoryArchiveTarget,+ type AkeruMemoryArchiveV2,+ type AkeruMemoryCandidateDecision,+ type AkeruMemoryMutation,+ type AkeruMemoryMutationResult,+ type AkeruMemoryRevision,+ type AkeruMemoryTargetScope,+ type AkeruMemoryThreadAccess,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";++import { deriveAkeruWorkspaceId, resolveAuthorizedMemoryPartitions } from "./EntityMemoryAccess.ts";+import { exportAkeruMemory } from "./MemoryExport.ts";+import { applyAkeruMemoryImport, previewAkeruMemoryImport } from "./MemoryImport.ts";+import type { EntityMemoryRepositoryShape } from "./Services/EntityMemoryRepository.ts";+import type { MemoryCandidateRepositoryShape } from "./Services/MemoryCandidateRepository.ts";++const nowIso = () => DateTime.formatIso(DateTime.nowUnsafe());+const affectedBotIds = (access: AkeruMemoryThreadAccess) =>+ access.groupId === null+ ? access.botId === null+ ? []+ : [access.botId]+ : [...access.groupMemberBotIds];++const entityFor = (+ scope: AkeruMemoryRevision["partition"]["scope"],+ access: AkeruMemoryThreadAccess,+) => {+ switch (scope) {+ case "user":+ case "bot-user":+ return { entityKind: "user" as const, entityId: AkeruMemoryEntityId.make(access.userId) };+ case "bot":+ if (access.botId === null) throw new Error("This thread has no private bot identity.");+ return { entityKind: "bot" as const, entityId: AkeruMemoryEntityId.make(access.botId) };+ case "project":+ return {+ entityKind: "project" as const,+ entityId: AkeruMemoryEntityId.make(access.projectId),+ };+ case "group":+ if (access.groupId === null) throw new Error("This thread is not in a group.");+ return { entityKind: "group" as const, entityId: AkeruMemoryEntityId.make(access.groupId) };+ case "workspace":+ return {+ entityKind: "workspace" as const,+ entityId: AkeruMemoryEntityId.make(deriveAkeruWorkspaceId(access.workspaceRoot)),+ };+ case "thread":+ return { entityKind: "other" as const, entityId: AkeruMemoryEntityId.make(access.threadId) };+ }+};++const partitionFor = (scope: AkeruMemoryTargetScope, access: AkeruMemoryThreadAccess) =>+ resolveAuthorizedMemoryPartitions(access).pipe(+ Effect.flatMap((partitions) => {+ const storedScope = scope === "private" ? "bot-user" : scope;+ const partition = partitions.find((candidate) => candidate.scope === storedScope);+ return partition+ ? Effect.succeed(partition)+ : Effect.fail(+ new AkeruMemoryOperationError({+ operation: "mutate",+ detail: `Memory scope '${scope}' is not available to this thread.`,+ }),+ );+ }),+ );++const decideCandidate = Effect.fn("MemoryRpc.decideCandidate")(function* (input: {+ readonly candidates: MemoryCandidateRepositoryShape;+ readonly access: AkeruMemoryThreadAccess;+ readonly decision: AkeruMemoryCandidateDecision;+}) {+ const candidate = (yield* input.candidates.listPending({ access: input.access })).find(+ (item) => item.candidateId === input.decision.candidateId,+ );+ if (!candidate) {+ return yield* new AkeruMemoryOperationError({+ operation: "mutate",+ detail: "The memory candidate is missing or already decided.",+ });+ }+ const decidedAt = nowIso();+ if (input.decision.decision === "reject") {+ return yield* input.candidates.reject({+ access: input.access,+ candidateId: candidate.candidateId,+ receiptId: `memory-${NodeCrypto.randomUUID()}`,+ decidedAt,+ });+ }+ const partition = yield* partitionFor(input.decision.scope ?? candidate.scope, input.access);+ const revision: AkeruMemoryRevision = {+ id: AkeruMemoryId.make(NodeCrypto.randomUUID()),+ rootId: AkeruMemoryRootId.make(NodeCrypto.randomUUID()),+ revision: 1,+ partition,+ ...entityFor(partition.scope, input.access),+ kind: "fact",+ value: {},+ fact: input.decision.fact ?? candidate.fact,+ sourceThreadId: candidate.sourceThreadId,+ sourceMessageId: candidate.sourceMessageId,+ authorBotId: candidate.authorBotId,+ initiatingUserId: candidate.initiatingUserId,+ createdAt: candidate.createdAt,+ confirmedAt: decidedAt,+ updatedAt: decidedAt,+ confidence: candidate.confidence,+ approvalState: "approved",+ supersedesId: null,+ supersededById: null,+ visibility: partition.visibility,+ deletionState: "active",+ pinned: false,+ sensitive: candidate.sensitive,+ affectedBotIds: affectedBotIds(input.access),+ };+ return yield* input.candidates.approve({+ access: input.access,+ candidateId: candidate.candidateId,+ revision,+ receiptId: `memory-${NodeCrypto.randomUUID()}`,+ decidedAt,+ });+});++export interface MemoryRpcBackend {+ readonly repository: EntityMemoryRepositoryShape;+ readonly candidates: MemoryCandidateRepositoryShape;+ readonly readConversation: (+ threadId: AkeruMemoryThreadAccess["threadId"],+ ) => Effect.Effect<AkeruConversationMemorySnapshot, AkeruMemoryOperationError>;+ readonly clearConversation: (+ threadId: AkeruMemoryThreadAccess["threadId"],+ ) => Effect.Effect<void, AkeruMemoryOperationError>;+}++export const memoryOperationError = (operation: string, cause: unknown) =>+ new AkeruMemoryOperationError({+ operation,+ detail:+ cause instanceof Error+ ? cause.message+ : typeof cause === "string"+ ? cause+ : "The memory operation failed.",+ });++export function createMemoryRpcHandlers(backend: MemoryRpcBackend) {+ const inspect = (access: AkeruMemoryThreadAccess) =>+ Effect.gen(function* () {+ const { durable, pending, conversation } = yield* Effect.all({+ durable: backend.repository.listCurrent({ access }),+ pending: backend.candidates.listPending({ access }),+ conversation: backend.readConversation(access.threadId),+ });+ const histories = yield* Effect.forEach(+ durable,+ (revision) =>+ backend.repository+ .listHistory({ access, rootId: revision.rootId })+ .pipe(Effect.map((revisions) => ({ rootId: revision.rootId, revisions }))),+ { concurrency: 4 },+ );+ return { threadId: access.threadId, durable, histories, pending, conversation };+ });++ const mutate = (access: AkeruMemoryThreadAccess, mutation: AkeruMemoryMutation) =>+ Effect.gen(function* () {+ if (mutation.operation === "candidate.decide") {+ const receipt = yield* decideCandidate({+ candidates: backend.candidates,+ access,+ decision: mutation.decision,+ });+ return { kind: "candidate", receipt } satisfies AkeruMemoryMutationResult;+ }+ if (mutation.operation === "conversation.clear") {+ yield* backend.clearConversation(access.threadId);+ return { kind: "conversation-cleared" } satisfies AkeruMemoryMutationResult;+ }+ if (mutation.operation === "fact.forget" || mutation.operation === "fact.delete") {+ const revision = yield* backend.repository.tombstone({+ access,+ rootId: mutation.memoryId,+ expectedRevision: mutation.expectedRevision,+ memoryId: AkeruMemoryId.make(NodeCrypto.randomUUID()),+ updatedAt: nowIso(),+ });+ return mutation.operation === "fact.delete"+ ? ({ kind: "deleted", memoryId: mutation.memoryId } satisfies AkeruMemoryMutationResult)+ : ({ kind: "revision", revision } satisfies AkeruMemoryMutationResult);+ }+ const current = yield* backend.repository.getCurrent({ access, rootId: mutation.memoryId });+ const updatedAt = nowIso();+ const base = {+ ...current,+ id: AkeruMemoryId.make(NodeCrypto.randomUUID()),+ revision: mutation.expectedRevision + 1,+ updatedAt,+ confirmedAt: updatedAt,+ supersedesId: current.id,+ supersededById: null,+ } satisfies AkeruMemoryRevision;+ const revision =+ mutation.operation === "fact.edit"+ ? { ...base, fact: mutation.fact }+ : mutation.operation === "fact.pin"+ ? { ...base, pinned: mutation.pinned }+ : yield* partitionFor(mutation.scope, access).pipe(+ Effect.map((partition) => ({+ ...base,+ partition,+ ...entityFor(partition.scope, access),+ visibility: partition.visibility,+ affectedBotIds: affectedBotIds(access),+ })),+ );+ const saved = yield* backend.repository.revise({+ access,+ expectedRevision: mutation.expectedRevision,+ revision,+ });+ return { kind: "revision", revision: saved } satisfies AkeruMemoryMutationResult;+ });++ return {+ inspect: (access: AkeruMemoryThreadAccess) =>+ inspect(access).pipe(Effect.mapError((cause) => memoryOperationError("inspect", cause))),+ mutate: (access: AkeruMemoryThreadAccess, mutation: AkeruMemoryMutation) =>+ mutate(access, mutation).pipe(+ Effect.mapError((cause) => memoryOperationError("mutate", cause)),+ ),+ exportArchive: (input: {+ readonly access: AkeruMemoryThreadAccess;+ readonly target: AkeruMemoryArchiveTarget;+ readonly complete: boolean;+ readonly createdAt: string;+ }) =>+ backend.readConversation(input.access.threadId).pipe(+ Effect.flatMap((snapshot) =>+ exportAkeruMemory({+ repository: backend.repository,+ ...input,+ conversations: [{ threadId: input.access.threadId, snapshot }],+ }),+ ),+ Effect.mapError((cause) => memoryOperationError("export", cause)),+ ),+ previewImport: (input: {+ readonly access: AkeruMemoryThreadAccess;+ readonly target: AkeruMemoryArchiveTarget;+ readonly archive: AkeruMemoryArchiveV2;+ }) =>+ previewAkeruMemoryImport({ repository: backend.repository, ...input }).pipe(+ Effect.mapError((cause) => memoryOperationError("importPreview", cause)),+ ),+ applyImport: (input: {+ readonly access: AkeruMemoryThreadAccess;+ readonly target: AkeruMemoryArchiveTarget;+ readonly archive: AkeruMemoryArchiveV2;+ readonly previewHash: string;+ }) =>+ applyAkeruMemoryImport({ repository: backend.repository, ...input }).pipe(+ Effect.mapError((cause) => memoryOperationError("importApply", cause)),+ ),+ };+}diff --git a/apps/server/src/orchestration/runtimeLayer.ts b/apps/server/src/orchestration/runtimeLayer.tsindex f92a04ac9..8d79d7be4 100644--- a/apps/server/src/orchestration/runtimeLayer.ts+++ b/apps/server/src/orchestration/runtimeLayer.ts@@ -10,6 +10,14 @@ import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipelineimport { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";+import { EntityMemoryRepositoryLive } from "../memory/Layers/EntityMemoryRepository.ts";+import { MemoryCandidateRepositoryLive } from "../memory/Layers/MemoryCandidateRepository.ts";+import { MemoryRevisionWriteLockLive } from "../memory/Services/MemoryRevisionWriteLock.ts";++const MemoryRepositoriesLive = Layer.mergeAll(+ EntityMemoryRepositoryLive,+ MemoryCandidateRepositoryLive,+).pipe(Layer.provide(MemoryRevisionWriteLockLive));export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(OrchestrationEventStoreLive,@@ -27,6 +35,7 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(ProjectionBotRepositoryLive,ProjectionGroupRepositoryLive,BotUsageLedgerLive,+ MemoryRepositoriesLive,// Shared background-liveness and plan-progress registries: written by// runtime ingestion, read by the snapshot query. provideMerge feeds the// same instance to the snapshot query here and re-exports it for runtimediff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.tsindex f8235609b..5a08b0cb4 100644--- a/apps/server/src/provider/AkeruMastraHarness.ts+++ b/apps/server/src/provider/AkeruMastraHarness.ts@@ -14,6 +14,7 @@ import {ProductFeedbackToolDraft,classifyAkeruExternalCommand,classifyAkeruSensitivePath,+ type AkeruConversationMemorySnapshot,type ProviderDriverKind,type ProductFeedbackToolDraft as ProductFeedbackToolDraftValue,} from "@t3tools/contracts";@@ -89,6 +90,11 @@ export interface AkeruMastraHarness {MastraAgentController<AkeruMastraState>,"init" | "createSession" | "deleteSession" | "destroy">;+ readonly clearObservationalMemory?: (threadId: string, resourceId?: string) => Promise<void>;+ readonly readObservationalMemory?: (+ threadId: string,+ resourceId?: string,+ ) => Promise<AkeruConversationMemorySnapshot>;readonly destroy: () => void;}diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.tsindex 1153db245..648aa9bad 100644--- a/apps/server/src/provider/Layers/AgentController.test.ts+++ b/apps/server/src/provider/Layers/AgentController.test.ts@@ -468,6 +468,33 @@ describe("AgentControllerLive", () => {);});+ it.effect("rejects conversation memory calls when the harness has no memory", () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ return provideController(+ Effect.gen(function* () {+ const controller = yield* AgentController;+ const readError = yield* controller.readConversationMemory!(codexThreadId).pipe(+ Effect.flip,+ );+ const clearError = yield* controller.clearConversationMemory!(codexThreadId).pipe(+ Effect.flip,+ );++ assert.deepInclude(readError, {+ _tag: "AgentControllerRuntimeError",+ operation: "memory.read",+ });+ assert.deepInclude(clearError, {+ _tag: "AgentControllerRuntimeError",+ operation: "memory.clear",+ });+ }),+ bridge.service,+ mastra.factory,+ );+ });+it.effect("boots a real Mastra Code controller and creates a Codex session", () => {const bridge = makeBridge();const layer = makeAgentControllerLive().pipe(diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 30d4647cf..612ad321a 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -1138,6 +1138,28 @@ const make = (options?: AgentControllerLiveOptions) =>);return AgentController.of({+ readConversationMemory: (threadId) =>+ bundle.readObservationalMemory+ ? runMastra("memory.read", () =>+ bundle.readObservationalMemory!(String(threadId), String(threadId)),+ )+ : Effect.fail(+ new AgentControllerRuntimeError({+ operation: "memory.read",+ detail: "Conversation memory is unavailable.",+ }),+ ),+ clearConversationMemory: (threadId) =>+ bundle.clearObservationalMemory+ ? runMastra("memory.clear", () =>+ bundle.clearObservationalMemory!(String(threadId), String(threadId)),+ )+ : Effect.fail(+ new AgentControllerRuntimeError({+ operation: "memory.clear",+ detail: "Conversation memory is unavailable.",+ }),+ ),resolveEngine,inspectEngine,startSession,diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.tsindex cdfc008b3..52d5cd792 100644--- a/apps/server/src/provider/Services/AgentController.ts+++ b/apps/server/src/provider/Services/AgentController.ts@@ -1,4 +1,5 @@import type {+ AkeruConversationMemorySnapshot,BotEngine,ModelSelection,ProviderInteractionMode,@@ -34,6 +35,14 @@ export interface AgentControllerEngineSelection extends AgentControllerAvailable}export interface AgentControllerShape {+ readonly readConversationMemory?: (+ threadId: ThreadId,+ ) => Effect.Effect<AkeruConversationMemorySnapshot, AgentControllerError>;++ readonly clearConversationMemory?: (+ threadId: ThreadId,+ ) => Effect.Effect<void, AgentControllerError>;+/** Resolve a thread's selected mode and model to an available Akeru provider instance. */readonly resolveEngine: (input: {readonly threadId: ThreadId;diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex ae4280bc9..2c9b02da6 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -10,6 +10,9 @@ import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import {+ AkeruMemoryTenantId,+ AkeruMemoryUserId,+ type AkeruMemoryThreadAccess,DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,AuthAccessStreamError,type AuthAccessStreamEvent,@@ -96,6 +99,9 @@ import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngiimport * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";import * as ProjectionBots from "./persistence/Services/ProjectionBots.ts";import * as ProjectionGroups from "./persistence/Services/ProjectionGroups.ts";+import { EntityMemoryRepository } from "./memory/Services/EntityMemoryRepository.ts";+import { MemoryCandidateRepository } from "./memory/Services/MemoryCandidateRepository.ts";+import { createMemoryRpcHandlers, memoryOperationError } from "./memory/MemoryRpc.ts";import {observeRpcEffect as instrumentRpcEffect,observeRpcStream as instrumentRpcStream,@@ -469,6 +475,8 @@ const makeWsRpcLayer = (const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;const projectionBots = yield* ProjectionBots.ProjectionBotRepository;const projectionGroups = yield* ProjectionGroups.ProjectionGroupRepository;+ const entityMemoryRepository = yield* Effect.serviceOption(EntityMemoryRepository);+ const memoryCandidates = yield* Effect.serviceOption(MemoryCandidateRepository);const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;const analytics = yield* AnalyticsService.AnalyticsService;// Every command dispatched on this connection carries the connecting@@ -565,6 +573,91 @@ const makeWsRpcLayer = (const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;const usage = yield* UsageService.UsageService;const relayClient = yield* RelayClient.RelayClient;+ const memory =+ Option.isSome(entityMemoryRepository) && Option.isSome(memoryCandidates)+ ? createMemoryRpcHandlers({+ repository: entityMemoryRepository.value,+ candidates: memoryCandidates.value,+ readConversation: (threadId) =>+ agentController.readConversationMemory+ ? agentController+ .readConversationMemory(threadId)+ .pipe(+ Effect.mapError((cause) => memoryOperationError("readConversation", cause)),+ )+ : Effect.fail(+ memoryOperationError(+ "readConversation",+ "Conversation memory is unavailable.",+ ),+ ),+ clearConversation: (threadId) =>+ agentController.clearConversationMemory+ ? agentController+ .clearConversationMemory(threadId)+ .pipe(+ Effect.mapError((cause) =>+ memoryOperationError("clearConversation", cause),+ ),+ )+ : Effect.fail(+ memoryOperationError(+ "clearConversation",+ "Conversation memory is unavailable.",+ ),+ ),+ })+ : null;+ const requireMemory = (operation: string) =>+ memory === null+ ? Effect.fail(memoryOperationError(operation, "Memory is unavailable."))+ : Effect.succeed(memory);+ const resolveMemoryAccess = (operation: string, threadId: ThreadId) =>+ Effect.gen(function* () {+ const thread = yield* projectionSnapshotQuery+ .getThreadShellById(threadId)+ .pipe(Effect.mapError((cause) => memoryOperationError(operation, cause)));+ if (Option.isNone(thread)) {+ return yield* memoryOperationError(operation, "The thread does not exist.");+ }+ const project = yield* projectionSnapshotQuery+ .getProjectShellById(thread.value.projectId)+ .pipe(Effect.mapError((cause) => memoryOperationError(operation, cause)));+ if (Option.isNone(project)) {+ return yield* memoryOperationError(operation, "The thread project does not exist.");+ }+ const groupId = thread.value.groupId ?? null;+ const groupMemberBotIds =+ groupId === null+ ? []+ : yield* projectionGroups.getById({ groupId }).pipe(+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ memoryOperationError(operation, "The thread group does not exist."),+ ),+ onSome: (group) =>+ Effect.succeed(group.members.map((member) => member.botId)),+ }),+ ),+ Effect.mapError((cause) => memoryOperationError(operation, cause)),+ );+ return {+ tenantId: AkeruMemoryTenantId.make("local"),+ userId: AkeruMemoryUserId.make("owner"),+ threadId,+ projectId: thread.value.projectId,+ workspaceRoot: project.value.workspaceRoot,+ botId:+ groupId === null+ ? (thread.value.respondingBotId ?? thread.value.botId ?? null)+ : null,+ groupId,+ respondingBotId: thread.value.respondingBotId ?? thread.value.botId ?? null,+ groupMemberBotIds,+ } satisfies AkeruMemoryThreadAccess;+ });const authorizationError = (requiredScope: AuthEnvironmentScope) =>new EnvironmentAuthorizationError({message: `The authenticated token is missing required scope: ${requiredScope}.`,@@ -2160,6 +2253,78 @@ const makeWsRpcLayer = (observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {"rpc.aggregate": "server",}),+ [WS_METHODS.memoryInspect]: (input) =>+ observeRpcEffect(+ WS_METHODS.memoryInspect,+ Effect.all({+ access: resolveMemoryAccess("inspect", input.threadId),+ memory: requireMemory("inspect"),+ }).pipe(Effect.flatMap(({ access, memory }) => memory.inspect(access))),+ { "rpc.aggregate": "memory" },+ ),+ [WS_METHODS.memoryExport]: (input) =>+ observeRpcEffect(+ WS_METHODS.memoryExport,+ Effect.all({+ access: resolveMemoryAccess("export", input.threadId),+ createdAt: nowIso,+ memory: requireMemory("export"),+ }).pipe(+ Effect.flatMap(({ access, createdAt, memory }) =>+ memory.exportArchive({+ access,+ target: input.target,+ complete: input.complete,+ createdAt,+ }),+ ),+ ),+ { "rpc.aggregate": "memory" },+ ),+ [WS_METHODS.memoryImportPreview]: (input) =>+ observeRpcEffect(+ WS_METHODS.memoryImportPreview,+ Effect.all({+ access: resolveMemoryAccess("importPreview", input.threadId),+ memory: requireMemory("importPreview"),+ }).pipe(+ Effect.flatMap(({ access, memory }) =>+ memory.previewImport({+ access,+ target: input.target,+ archive: input.archive,+ }),+ ),+ ),+ { "rpc.aggregate": "memory" },+ ),+ [WS_METHODS.memoryImportApply]: (input) =>+ observeRpcEffect(+ WS_METHODS.memoryImportApply,+ Effect.all({+ access: resolveMemoryAccess("importApply", input.threadId),+ memory: requireMemory("importApply"),+ }).pipe(+ Effect.flatMap(({ access, memory }) =>+ memory.applyImport({+ access,+ target: input.target,+ archive: input.archive,+ previewHash: input.previewHash,+ }),+ ),+ ),+ { "rpc.aggregate": "memory" },+ ),+ [WS_METHODS.memoryMutate]: (input) =>+ observeRpcEffect(+ WS_METHODS.memoryMutate,+ Effect.all({+ access: resolveMemoryAccess("mutate", input.threadId),+ memory: requireMemory("mutate"),+ }).pipe(Effect.flatMap(({ access, memory }) => memory.mutate(access, input.mutation))),+ { "rpc.aggregate": "memory" },+ ),[WS_METHODS.cloudGetRelayClientStatus]: (_input) =>observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, {"rpc.aggregate": "cloud",diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex b6affba2b..799e06163 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -131,6 +131,10 @@"types": "./src/state/server.ts","default": "./src/state/server.ts"},+ "./state/memory": {+ "types": "./src/state/memory.ts",+ "default": "./src/state/memory.ts"+ },"./state/bot-inbox": {"types": "./src/state/botInbox.ts","default": "./src/state/botInbox.ts"diff --git a/packages/client-runtime/src/state/memory.test.ts b/packages/client-runtime/src/state/memory.test.tsnew file mode 100644index 000000000..71d14bc56--- /dev/null+++ b/packages/client-runtime/src/state/memory.test.ts@@ -0,0 +1,108 @@+import { EnvironmentId, ThreadId, WS_METHODS } from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as SubscriptionRef from "effect/SubscriptionRef";+import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";+import { vi } from "vite-plus/test";++import {+ AVAILABLE_CONNECTION_STATE,+ PrimaryConnectionTarget,+ type PreparedConnection,+ type SupervisorConnectionState,+} from "../connection/model.ts";+import * as EnvironmentRegistry from "../connection/registry.ts";+import * as EnvironmentSupervisor from "../connection/supervisor.ts";+import type { WsRpcProtocolClient } from "../rpc/protocol.ts";+import type { RpcSession } from "../rpc/session.ts";+import { createMemoryEnvironmentAtoms } from "./memory.ts";++const environmentId = EnvironmentId.make("memory-environment");++it.effect("routes memory commands and refreshes inspection after changes", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const calls: string[] = [];+ const client = {+ [WS_METHODS.memoryExport]: () =>+ Effect.sync(() => calls.push(WS_METHODS.memoryExport)).pipe(+ Effect.as({ schemaVersion: 2 } as never),+ ),+ [WS_METHODS.memoryMutate]: () =>+ Effect.sync(() => calls.push(WS_METHODS.memoryMutate)).pipe(+ Effect.as({ kind: "conversation-cleared" } as never),+ ),+ } as unknown as WsRpcProtocolClient;+ const session: RpcSession = {+ client,+ initialConfig: Effect.never,+ ready: Effect.void,+ probe: Effect.void,+ closed: Effect.never,+ };+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({+ target: new PrimaryConnectionTarget({+ environmentId,+ label: "Memory environment",+ httpBaseUrl: "https://memory.example.test",+ wsBaseUrl: "wss://memory.example.test",+ }),+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({+ ...AVAILABLE_CONNECTION_STATE,+ desired: true,+ network: "online",+ phase: "connected",+ attempt: 1,+ generation: 1,+ }),+ session: yield* SubscriptionRef.make(Option.some(session)),+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_id, effect) =>+ Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);+ const atoms = createMemoryEnvironmentAtoms(+ Atom.runtime(+ Layer.succeed(+ EnvironmentRegistry.EnvironmentRegistry,+ EnvironmentRegistry.EnvironmentRegistry.of({+ run,+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),+ ),+ ),+ );+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>+ Effect.sync(() => value.dispose()),+ );+ const refresh = vi.spyOn(registry, "refresh");+ const threadId = ThreadId.make("thread-memory");++ const exported = yield* Effect.promise(() =>+ atoms.exportArchive.run(registry, {+ environmentId,+ input: { threadId, target: "thread", complete: true },+ }),+ );+ const mutated = yield* Effect.promise(() =>+ atoms.mutate.run(registry, {+ environmentId,+ input: { threadId, mutation: { operation: "conversation.clear" } },+ }),+ );++ expect(AsyncResult.isSuccess(exported)).toBe(true);+ expect(AsyncResult.isSuccess(mutated)).toBe(true);+ expect(calls).toEqual([WS_METHODS.memoryExport, WS_METHODS.memoryMutate]);+ expect(refresh).toHaveBeenCalledWith(+ atoms.inspect({+ environmentId,+ input: { threadId },+ }),+ );+ }),+ ),+);diff --git a/packages/client-runtime/src/state/memory.ts b/packages/client-runtime/src/state/memory.tsnew file mode 100644index 000000000..01382644a--- /dev/null+++ b/packages/client-runtime/src/state/memory.ts@@ -0,0 +1,75 @@+import { type EnvironmentId, type ThreadId, WS_METHODS } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import { Atom, type AtomRegistry } from "effect/unstable/reactivity";++import type { EnvironmentRegistry } from "../connection/registry.ts";+import {+ createAtomCommandScheduler,+ createEnvironmentRpcCommand,+ createEnvironmentRpcQueryAtomFamily,+} from "./runtime.ts";++export function createMemoryEnvironmentAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,+) {+ const inspect = createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:memory:inspect",+ tag: WS_METHODS.memoryInspect,+ staleTimeMs: 5_000,+ });+ const scheduler = createAtomCommandScheduler();+ const concurrency = {+ mode: "serial" as const,+ key: ({+ environmentId,+ input,+ }: {+ readonly environmentId: EnvironmentId;+ readonly input: { readonly threadId: ThreadId };+ }) => `${environmentId}:${input.threadId}`,+ };+ const refresh = (+ target: {+ readonly environmentId: EnvironmentId;+ readonly input: { readonly threadId: ThreadId };+ },+ registry: AtomRegistry.AtomRegistry,+ ) =>+ Effect.sync(() =>+ registry.refresh(+ inspect({+ environmentId: target.environmentId,+ input: { threadId: target.input.threadId },+ }),+ ),+ );++ return {+ inspect,+ exportArchive: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:memory:export",+ tag: WS_METHODS.memoryExport,+ scheduler,+ }),+ previewImport: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:memory:import-preview",+ tag: WS_METHODS.memoryImportPreview,+ scheduler,+ concurrency,+ }),+ applyImport: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:memory:import-apply",+ tag: WS_METHODS.memoryImportApply,+ scheduler,+ concurrency,+ onSettled: refresh,+ }),+ mutate: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:memory:mutate",+ tag: WS_METHODS.memoryMutate,+ scheduler,+ concurrency,+ onSettled: refresh,+ }),+ };+}diff --git a/packages/contracts/src/akeruMemory.test.ts b/packages/contracts/src/akeruMemory.test.tsindex aa111c8aa..8342a32d7 100644--- a/packages/contracts/src/akeruMemory.test.ts+++ b/packages/contracts/src/akeruMemory.test.ts@@ -9,6 +9,7 @@ import {AkeruMemoryCandidate,AkeruMemoryCandidateDecision,AkeruMemoryExportInput,+ AkeruMemoryImportPreviewInput,AkeruMemoryDecisionReceipt,AkeruMemoryPacket,AkeruMemoryMutateInput,@@ -105,6 +106,25 @@ describe("Akeru memory contracts", () => {}),);+ it.effect("rejects version 1 import archives at the RPC boundary", () =>+ Effect.gen(function* () {+ const result = yield* Schema.decodeUnknownEffect(AkeruMemoryImportPreviewInput)({+ threadId: "thread-1",+ target: "thread",+ archive: {+ schemaVersion: 1,+ threadId: "thread-1",+ complete: true,+ createdAt: "2026-08-30T21:00:00.000Z",+ files: [],+ manifestSha256: "a".repeat(64),+ },+ }).pipe(Effect.exit);++ assert.isTrue(result._tag === "Failure");+ }),+ );+it.effect("requires rejected decisions and durable receipts to identify the candidate", () =>Effect.gen(function* () {const rejected = yield* Schema.decodeUnknownEffect(AkeruMemoryCandidateDecision)({diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex f30ad87c2..680f26f2f 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -2,6 +2,20 @@ import * as Schema from "effect/Schema";import * as Rpc from "effect/unstable/rpc/Rpc";import * as RpcGroup from "effect/unstable/rpc/RpcGroup";+import {+ AkeruMemoryArchiveV2,+ AkeruMemoryExportInput,+ AkeruMemoryImportApplyInput,+ AkeruMemoryImportApplyResult,+ AkeruMemoryImportPreview,+ AkeruMemoryImportPreviewInput,+ AkeruMemoryInspectInput,+ AkeruMemoryMutateInput,+ AkeruMemoryMutationResult,+ AkeruMemoryOperationError,+ AkeruMemorySnapshot,+} from "./akeruMemory.ts";+import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";import {AuthAccessStreamError,@@ -305,6 +319,11 @@ export const WS_METHODS = {serverReportHostPowerState: "server.reportHostPowerState",serverGetBackgroundPolicy: "server.getBackgroundPolicy",serverGetUsageSummary: "server.getUsageSummary",+ memoryInspect: "memory.inspect",+ memoryExport: "memory.export",+ memoryImportPreview: "memory.importPreview",+ memoryImportApply: "memory.importApply",+ memoryMutate: "memory.mutate",portabilityExport: "portability.export",portabilityPreviewImport: "portability.previewImport",portabilityApplyImport: "portability.applyImport",@@ -558,6 +577,36 @@ export const WsServerGetBackgroundPolicyRpc = Rpc.make(WS_METHODS.serverGetBackgerror: EnvironmentAuthorizationError,});+export const WsMemoryInspectRpc = Rpc.make(WS_METHODS.memoryInspect, {+ payload: AkeruMemoryInspectInput,+ success: AkeruMemorySnapshot,+ error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),+});++export const WsMemoryExportRpc = Rpc.make(WS_METHODS.memoryExport, {+ payload: AkeruMemoryExportInput,+ success: AkeruMemoryArchiveV2,+ error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),+});++export const WsMemoryImportPreviewRpc = Rpc.make(WS_METHODS.memoryImportPreview, {+ payload: AkeruMemoryImportPreviewInput,+ success: AkeruMemoryImportPreview,+ error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),+});++export const WsMemoryImportApplyRpc = Rpc.make(WS_METHODS.memoryImportApply, {+ payload: AkeruMemoryImportApplyInput,+ success: AkeruMemoryImportApplyResult,+ error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),+});++export const WsMemoryMutateRpc = Rpc.make(WS_METHODS.memoryMutate, {+ payload: AkeruMemoryMutateInput,+ success: AkeruMemoryMutationResult,+ error: Schema.Union([AkeruMemoryOperationError, EnvironmentAuthorizationError]),+});+export const WsPortabilityExportRpc = Rpc.make(WS_METHODS.portabilityExport, {payload: Schema.Struct({}),success: PortabilityExportResult,@@ -1015,6 +1064,11 @@ export const WsRpcGroup = RpcGroup.make(WsServerReportClientActivityRpc,WsServerReportHostPowerStateRpc,WsServerGetBackgroundPolicyRpc,+ WsMemoryInspectRpc,+ WsMemoryExportRpc,+ WsMemoryImportPreviewRpc,+ WsMemoryImportApplyRpc,+ WsMemoryMutateRpc,WsPortabilityExportRpc,WsPortabilityPreviewImportRpc,WsPortabilityApplyImportRpc,