Skip to content

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): observe new thread messages (#49)

Leoe621b81275a9
diff --git a/apps/server/package.json b/apps/server/package.json
index d7df7e2a5..17b049b7a 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -31,6 +31,8 @@
"@ff-labs/fff-node": "0.9.4",
"@mastra/code-sdk": "1.5.1",
"@mastra/core": "1.63.0",
+ "@mastra/libsql": "1.22.0",
+ "@mastra/memory": "1.28.0",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index ed4a33ca9..2b442cbbe 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -1,14 +1,27 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
import { AuthStorage } from "@mastra/code-sdk/auth/storage";
+import { MessageList } from "@mastra/core/agent";
import { RequestContext } from "@mastra/core/request-context";
+import { Memory } from "@mastra/memory";
+import { ObservationalMemory } from "@mastra/memory/processors";
import {
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
AKERU_TOOL_CATALOG,
ProviderDriverKind,
} from "@t3tools/contracts";
-import { assert, describe, it } from "vite-plus/test";
+import * as DateTime from "effect/DateTime";
+import { assert, describe, expect, it, vi } from "vite-plus/test";
import { AKERU_AGENT_INSTRUCTIONS, AKERU_BOT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";
import {
+ AkeruPassiveObservationalMemoryProcessor,
+ createAkeruObserveHooks,
+ createAkeruMastraHarness,
+ createAkeruMastraMemory,
criticalAkeruAction,
mastraModelId,
resolveAkeruInstructions,
@@ -19,6 +32,191 @@ import { productFeedbackToolInputSchema } from "./AkeruMastraHarness.ts";
import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
describe("AkeruMastraHarness", () => {
+ it("emits observer and reflector metering callbacks", async () => {
+ const started: unknown[] = [];
+ const finished: unknown[] = [];
+ const hooks = createAkeruObserveHooks({
+ startMemoryCall: async (input) => {
+ started.push(input);
+ return `${input.category}-call`;
+ },
+ finishMemoryCall: async (input) => {
+ finished.push(input);
+ },
+ });
+
+ await hooks.onObservationStart?.({ threadId: "thread-1" });
+ await hooks.onObservationEnd?.({
+ threadId: "thread-1",
+ usage: { inputTokens: 10, outputTokens: 5 },
+ });
+ await hooks.onReflectionStart?.({ threadId: "thread-1" });
+ await hooks.onReflectionEnd?.({
+ threadId: "thread-1",
+ usage: { inputTokens: 20, outputTokens: 8 },
+ });
+
+ assert.deepEqual(started, [
+ { threadId: "thread-1", category: "observer" },
+ { threadId: "thread-1", category: "reflector" },
+ ]);
+ assert.deepEqual(finished, [
+ {
+ callId: "observer-call",
+ category: "observer",
+ usage: { inputTokens: 10, outputTokens: 5 },
+ },
+ {
+ callId: "reflector-call",
+ category: "reflector",
+ usage: { inputTokens: 20, outputTokens: 8 },
+ },
+ ]);
+
+ const blocked = createAkeruObserveHooks({
+ startMemoryCall: async () => {
+ throw new Error("Metering rejected");
+ },
+ });
+ await expect(blocked.onObservationStart?.({ threadId: "thread-1" })).rejects.toThrow(
+ "Metering rejected",
+ );
+ });
+
+ it("stores observational memory by thread and restores it after reopening", async () => {
+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-om-store-"));
+ const options = {
+ authStorage: new AuthStorage(NodePath.join(directory, "auth.json")),
+ memoryDbPath: NodePath.join(directory, "observational-memory.sqlite"),
+ };
+ try {
+ const first = await createAkeruMastraMemory(options);
+ assert.equal(first.engine.scope, "thread");
+ assert.isFalse(first.engine.retrieval);
+ await first.memory.createThread({ threadId: "thread-a", resourceId: "resource-a" });
+ await first.memory.createThread({ threadId: "thread-b", resourceId: "resource-b" });
+ await first.close();
+
+ const reopened = await createAkeruMastraMemory(options);
+ assert.deepInclude(
+ await reopened.memory.getThreadById({ threadId: "thread-a", resourceId: "resource-a" }),
+ { id: "thread-a", resourceId: "resource-a" },
+ );
+ assert.isNull(
+ await reopened.memory.getThreadById({ threadId: "thread-a", resourceId: "resource-b" }),
+ );
+ await reopened.close();
+ } finally {
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
+ it("persists only messages created by the current turn", async () => {
+ const persistMessages = vi.fn(async () => undefined);
+ const engine = {
+ getThreadContext: vi.fn(() => ({ threadId: "thread-passive", resourceId: "thread-passive" })),
+ getOrCreateRecord: vi.fn(async () => ({ activeObservations: "" })),
+ buildContextSystemMessages: vi.fn(async () => []),
+ } as unknown as ObservationalMemory;
+ const processor = new AkeruPassiveObservationalMemoryProcessor(engine, {
+ persistMessages,
+ } as unknown as Memory);
+ const messageList = new MessageList({
+ threadId: "thread-passive",
+ resourceId: "thread-passive",
+ });
+ messageList.add(
+ {
+ id: "user-history",
+ role: "user",
+ createdAt: DateTime.toDate(DateTime.makeUnsafe("2026-08-30T20:00:00.000Z")),
+ content: { format: 2, parts: [{ type: "text", text: "Earlier turn." }] },
+ threadId: "thread-passive",
+ resourceId: "thread-passive",
+ },
+ "memory",
+ );
+ for (const message of [
+ {
+ id: "user-current",
+ role: "user" as const,
+ text: "Only this turn.",
+ source: "input" as const,
+ },
+ {
+ id: "assistant-current",
+ role: "assistant" as const,
+ text: "Current reply.",
+ source: "response" as const,
+ },
+ ]) {
+ messageList.add(
+ {
+ id: message.id,
+ role: message.role,
+ createdAt: DateTime.toDate(DateTime.makeUnsafe("2026-08-31T20:00:00.000Z")),
+ content: { format: 2, parts: [{ type: "text", text: message.text }] },
+ threadId: "thread-passive",
+ resourceId: "thread-passive",
+ },
+ message.source,
+ );
+ }
+
+ await processor.processOutputResult({ messageList } as never);
+
+ expect(persistMessages).toHaveBeenCalledOnce();
+ expect(persistMessages).toHaveBeenCalledWith([
+ expect.objectContaining({ id: "user-current" }),
+ expect.objectContaining({ id: "assistant-current" }),
+ ]);
+ });
+
+ it("serializes observations per thread and drains them before close", async () => {
+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-om-queue-"));
+ let releaseFirst!: () => void;
+ const firstBlocked = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ let markStarted!: () => void;
+ const firstStarted = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ let calls = 0;
+ const observe = vi
+ .spyOn(ObservationalMemory.prototype, "observe")
+ .mockImplementation(async () => {
+ calls += 1;
+ if (calls === 1) {
+ markStarted();
+ await firstBlocked;
+ }
+ return undefined as never;
+ });
+ const harness = await createAkeruMastraHarness({
+ authStorage: new AuthStorage(NodePath.join(directory, "auth.json")),
+ memoryDbPath: NodePath.join(directory, "observational-memory.sqlite"),
+ getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
+ });
+ try {
+ const input = { threadId: "thread-queue", modelId: "openai/gpt-5.6-sol" };
+ const first = harness.observeAfterTurn!(input);
+ await firstStarted;
+ const second = harness.observeAfterTurn!(input);
+ expect(observe).toHaveBeenCalledOnce();
+ const close = harness.destroy();
+ releaseFirst();
+ await Promise.all([first, second, close]);
+ expect(observe).toHaveBeenCalledTimes(2);
+ } finally {
+ releaseFirst();
+ observe.mockRestore();
+ await harness.destroy();
+ NodeFS.rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
it("keeps Kimi model names on the Kimi subscription transport", () => {
const authStorage = new AuthStorage("/tmp/akeru-unused-auth.json");
assert.equal(
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index f80d93182..2adb72fb2 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -1,3 +1,5 @@
+import * as NodeURL from "node:url";
+
import { AuthStorage } from "@mastra/code-sdk/auth/storage";
import { openaiCodexProvider } from "@mastra/code-sdk/providers/openai-codex";
import type { ToolsInput } from "@mastra/core/agent";
@@ -6,9 +8,21 @@ import {
type Session,
} from "@mastra/core/agent-controller";
import { createCodingAgent } from "@mastra/core/coding-agent";
-import type { RequestContext } from "@mastra/core/request-context";
+import { RequestContext } from "@mastra/core/request-context";
+import type {
+ Processor,
+ ProcessInputStepArgs,
+ ProcessOutputResultArgs,
+} from "@mastra/core/processors";
import type { StandardSchemaWithJSON } from "@mastra/core/schema";
import { createTool, type NeedsApprovalFn } from "@mastra/core/tools";
+import { LibSQLStore } from "@mastra/libsql";
+import { Memory } from "@mastra/memory";
+import {
+ ObservationalMemory,
+ OBSERVATION_CONTINUATION_HINT,
+ type ObserveHooks,
+} from "@mastra/memory/processors";
import {
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
ProductFeedbackToolDraft,
@@ -77,6 +91,21 @@ export type AkeruMastraSession = Session<AkeruMastraState>;
export interface AkeruMastraHarnessOptions {
readonly authStorage: AuthStorage;
readonly getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>;
+ readonly memoryDbPath: string;
+ readonly startMemoryCall?: (input: {
+ readonly threadId: string;
+ readonly category: "observer" | "reflector";
+ }) => Promise<string | undefined>;
+ readonly finishMemoryCall?: (input: {
+ readonly callId: string;
+ readonly category: "observer" | "reflector";
+ readonly usage?: {
+ readonly inputTokens?: number;
+ readonly outputTokens?: number;
+ readonly totalTokens?: number;
+ };
+ readonly error?: Error;
+ }) => Promise<void>;
readonly getThreadTools: (threadId: string) => ToolsInput;
readonly syncThreadToolApproval?: (
threadId: string,
@@ -96,7 +125,53 @@ export interface AkeruMastraHarness {
threadId: string,
resourceId?: string,
) => Promise<AkeruConversationMemorySnapshot>;
- readonly destroy: () => void;
+ readonly observeAfterTurn?: (input: AkeruBackgroundObservationInput) => Promise<void>;
+ readonly destroy: () => void | Promise<void>;
+}
+
+export interface AkeruBackgroundObservationInput {
+ readonly threadId: string;
+ readonly resourceId?: string;
+ readonly modelId: string;
+ readonly hooks?: ObserveHooks;
+}
+
+type AkeruMastraToolOptions = Pick<
+ AkeruMastraHarnessOptions,
+ "authStorage" | "getKimiAccess" | "getThreadTools" | "syncThreadToolApproval" | "toolRuntime"
+>;
+
+export function createAkeruObserveHooks(
+ options: Pick<AkeruMastraHarnessOptions, "startMemoryCall" | "finishMemoryCall">,
+): ObserveHooks {
+ const active = new Map<string, string>();
+ const start = async (threadId: string | undefined, category: "observer" | "reflector") => {
+ if (!threadId) return;
+ const callId = await options.startMemoryCall?.({ threadId, category });
+ if (callId) active.set(`${threadId}:${category}`, callId);
+ };
+ const finish = async (
+ category: "observer" | "reflector",
+ result: Parameters<NonNullable<ObserveHooks["onObservationEnd"]>>[0],
+ ) => {
+ if (!result.threadId) return;
+ const key = `${result.threadId}:${category}`;
+ const callId = active.get(key);
+ if (!callId) return;
+ active.delete(key);
+ await options.finishMemoryCall?.({
+ callId,
+ category,
+ ...(result.usage ? { usage: result.usage } : {}),
+ ...(result.error ? { error: result.error } : {}),
+ });
+ };
+ return {
+ onObservationStart: ({ threadId } = {}) => start(threadId, "observer"),
+ onObservationEnd: (result) => finish("observer", result),
+ onReflectionStart: ({ threadId } = {}) => start(threadId, "reflector"),
+ onReflectionEnd: (result) => finish("reflector", result),
+ };
}
function controllerContext(requestContext: RequestContext): Record<string, unknown> | undefined {
@@ -121,6 +196,107 @@ function controllerResourceId(requestContext: RequestContext): string | undefine
return typeof value === "string" ? value : undefined;
}
+export class AkeruPassiveObservationalMemoryProcessor implements Processor<"observational-memory"> {
+ readonly id = "observational-memory" as const;
+ readonly name = "Akeru Observational Memory";
+ readonly engine: ObservationalMemory;
+ private readonly memory: Memory;
+
+ constructor(engine: ObservationalMemory, memory: Memory) {
+ this.engine = engine;
+ this.memory = memory;
+ }
+
+ async processInputStep(args: ProcessInputStepArgs) {
+ if (args.stepNumber !== 0) return args.messageList;
+ const context = this.engine.getThreadContext(args.requestContext, args.messageList);
+ if (!context) return args.messageList;
+ const record = await this.engine.getOrCreateRecord(context.threadId, context.resourceId);
+ const chunks = await this.engine.buildContextSystemMessages({ ...context, record });
+ args.messageList.clearSystemMessages("observational-memory");
+ for (const chunk of chunks ?? []) args.messageList.addSystem(chunk, "observational-memory");
+ args.messageList.clearSystemMessages("om-continuation");
+ if (record.activeObservations) {
+ args.messageList.addSystem(
+ `<system-reminder>${OBSERVATION_CONTINUATION_HINT}</system-reminder>`,
+ "om-continuation",
+ );
+ }
+ return args.messageList;
+ }
+
+ async processOutputResult(args: ProcessOutputResultArgs) {
+ const messages = [
+ ...args.messageList.get.input.db(),
+ ...args.messageList.get.response.db(),
+ ].filter((message) => args.messageList.isNewMessage(message));
+ if (messages.length > 0) await this.memory.persistMessages(messages);
+ return args.messageList;
+ }
+}
+
+export async function createAkeruMastraMemory(
+ options: Pick<AkeruMastraHarnessOptions, "authStorage" | "getKimiAccess" | "memoryDbPath">,
+) {
+ const storage = new LibSQLStore({
+ id: "akeru-observational-memory",
+ url: NodeURL.pathToFileURL(options.memoryDbPath).toString(),
+ connectionTimeoutMs: 5_000,
+ });
+ await storage.init();
+ const model = ({ requestContext }: { readonly requestContext: RequestContext }) =>
+ resolveAkeruMastraModel(
+ controllerModelId(requestContext),
+ options.authStorage,
+ options.getKimiAccess,
+ );
+ const memory = new Memory({
+ storage,
+ options: {
+ lastMessages: 10,
+ semanticRecall: false,
+ workingMemory: { enabled: false },
+ observationalMemory: false,
+ },
+ });
+ const memoryStore = await storage.getStore("memory");
+ if (!memoryStore?.supportsObservationalMemory) {
+ await storage.close();
+ throw new Error("The configured memory store does not support observational memory.");
+ }
+ const engine = new ObservationalMemory({
+ storage: memoryStore,
+ memory,
+ scope: "thread",
+ model,
+ retrieval: false,
+ hookExecution: "await",
+ observation: {
+ bufferTokens: false,
+ bufferOnIdle: false,
+ continuationHints: { currentTask: true, suggestedResponse: true },
+ },
+ reflection: {
+ continuationHints: { currentTask: true, suggestedResponse: true },
+ },
+ });
+ const processor = new AkeruPassiveObservationalMemoryProcessor(engine, memory);
+ let closePromise: Promise<void> | undefined;
+ return {
+ memory,
+ storage,
+ engine,
+ processor,
+ close: async () => {
+ closePromise ??= (async () => {
+ await engine.settled();
+ await storage.close();
+ })();
+ await closePromise;
+ },
+ };
+}
+
const MASTRA_MODEL_PREFIX = {
codex: "openai",
kimi: "kimi-for-coding",
@@ -162,7 +338,7 @@ export function resolveAkeruInstructions(requestContext: RequestContext): string
export async function resolveAkeruTools(
requestContext: RequestContext,
- options: AkeruMastraHarnessOptions,
+ options: AkeruMastraToolOptions,
): Promise<ToolsInput> {
const threadId = controllerResourceId(requestContext);
if (!threadId) return {};
@@ -176,7 +352,7 @@ export async function resolveAkeruTools(
function approvalAwareTools(
threadId: string,
tools: ToolsInput,
- options: AkeruMastraHarnessOptions,
+ options: AkeruMastraToolOptions,
): ToolsInput {
return Object.fromEntries(
Object.entries(tools).map(([name, tool]) => {
@@ -351,6 +527,10 @@ export function akeruToolCategory(toolName: string): AkeruToolCategory {
export async function createAkeruMastraHarness(
options: AkeruMastraHarnessOptions,
): Promise<AkeruMastraHarness> {
+ const observationalMemory = await createAkeruMastraMemory(options);
+ const observeHooks = createAkeruObserveHooks(options);
+ const observationTails = new Map<string, Promise<void>>();
+ let closing = false;
const agent = createCodingAgent({
id: "akeru-agent",
name: "Akeru",
@@ -362,12 +542,17 @@ export async function createAkeruMastraHarness(
options.getKimiAccess,
),
tools: ({ requestContext }) => resolveAkeruTools(requestContext, options),
+ memory: observationalMemory.memory,
+ inputProcessors: [observationalMemory.processor],
+ outputProcessors: [observationalMemory.processor],
workspace: undefined,
});
const controller = new MastraAgentController<AkeruMastraState>({
id: "akeru-codex",
agent,
+ storage: observationalMemory.storage,
+ memory: observationalMemory.memory,
modes: [
{ id: "build", name: "Build", defaultModelId: DEFAULT_MODEL_ID },
{
@@ -390,8 +575,72 @@ export async function createAkeruMastraHarness(
intervalHandlers: [],
});
+ const observeAfterTurn = (input: AkeruBackgroundObservationInput) => {
+ if (closing) return Promise.reject(new Error("Akeru observational memory is closing."));
+ const resourceId = input.resourceId ?? input.threadId;
+ const key = `${input.threadId}\u0000${resourceId}`;
+ const prior = observationTails.get(key) ?? Promise.resolve();
+ const work = prior
+ .catch(() => undefined)
+ .then(async () => {
+ const requestContext = new RequestContext();
+ requestContext.setRaw("controller", {
+ resourceId,
+ session: { modelId: input.modelId },
+ });
+ await observationalMemory.engine.observe({
+ threadId: input.threadId,
+ resourceId,
+ requestContext,
+ trigger: "manual",
+ hooks: input.hooks ?? observeHooks,
+ });
+ });
+ observationTails.set(key, work);
+ void work
+ .finally(() => {
+ if (observationTails.get(key) === work) observationTails.delete(key);
+ })
+ .catch(() => undefined);
+ return work;
+ };
+
return {
controller,
- destroy: () => undefined,
+ clearObservationalMemory: (threadId, resourceId) =>
+ observationalMemory.engine.clear(threadId, resourceId),
+ readObservationalMemory: async (threadId, resourceId) => {
+ const normalize = (
+ record: Awaited<ReturnType<typeof observationalMemory.engine.getRecord>>,
+ ) => {
+ if (!record) return null;
+ return {
+ id: record.id,
+ generationCount: record.generationCount,
+ originType: record.originType,
+ activeObservations: record.activeObservations,
+ bufferedObservations: [
+ ...(record.bufferedObservationChunks?.map((chunk) => chunk.observations) ?? []),
+ ...(record.bufferedObservations ? [record.bufferedObservations] : []),
+ ].join("\n\n"),
+ bufferedReflection: record.bufferedReflection ?? null,
+ totalTokensObserved: record.totalTokensObserved,
+ observationTokenCount: record.observationTokenCount,
+ createdAt: record.createdAt.toISOString(),
+ updatedAt: record.updatedAt.toISOString(),
+ };
+ };
+ const [current, history] = await Promise.all([
+ observationalMemory.engine.getRecord(threadId, resourceId),
+ observationalMemory.engine.getHistory(threadId, resourceId, 50),
+ ]);
+ return { current: normalize(current), history: history.map((record) => normalize(record)!) };
+ },
+ observeAfterTurn,
+ destroy: async () => {
+ closing = true;
+ await Promise.allSettled([...observationTails.values()]);
+ await observationalMemory.close();
+ },
};
}
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index d3d2087ca..875f2f4fe 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -25,8 +25,10 @@ import {
} from "@t3tools/contracts";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
+import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { assert, describe, expect, vi } from "vite-plus/test";
@@ -462,7 +464,7 @@ describe("AgentControllerLive", () => {
),
);
- it.effect("passes Akeru subscription auth to the custom memory-free harness", () => {
+ it.effect("passes Akeru subscription auth and memory storage to the custom harness", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
return provideController(
@@ -471,7 +473,7 @@ describe("AgentControllerLive", () => {
const options = mastra.harnessOptions[0];
assert.isDefined(options);
assert.isDefined(options.authStorage);
- assert.notProperty(options, "memory");
+ assert.match(options.memoryDbPath, /mastra-observational-memory\.sqlite$/);
}),
bridge.service,
mastra.factory,
@@ -1268,6 +1270,43 @@ describe("AgentControllerLive", () => {
});
});
+ it.effect("waits for observational memory shutdown before closing the controller scope", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ const destroyStarted = Promise.withResolvers<void>();
+ const destroyReleased = Promise.withResolvers<void>();
+ const factory: NonNullable<AgentControllerLiveOptions["makeMastraHarness"]> = async (
+ options,
+ ) => {
+ const harness = await mastra.factory(options);
+ return {
+ ...harness,
+ destroy: async () => {
+ destroyStarted.resolve();
+ await destroyReleased.promise;
+ },
+ };
+ };
+
+ return Effect.gen(function* () {
+ const scope = yield* Scope.make("sequential");
+ yield* Layer.buildWithScope(makeLayer(bridge.service, factory), scope);
+ let scopeClosed = false;
+ const closeScope = yield* Scope.close(scope, Exit.void).pipe(
+ Effect.tap(() => Effect.sync(() => (scopeClosed = true))),
+ Effect.forkScoped,
+ );
+
+ yield* Effect.promise(() => destroyStarted.promise);
+ yield* Effect.yieldNow;
+ expect(scopeClosed).toBe(false);
+
+ destroyReleased.resolve();
+ yield* Fiber.join(closeScope);
+ expect(scopeClosed).toBe(true);
+ });
+ });
+
it.effect("keeps the same workspace when only session input changes", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 5c8988080..eb19fc429 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -104,6 +104,7 @@ interface ActiveTurn {
readonly assistantMessages: Map<string, ActiveAssistantMessage>;
waiting: boolean;
finished: boolean;
+ memoryQueued: boolean;
}
interface ActiveSession {
@@ -347,6 +348,7 @@ const make = (options?: AgentControllerLiveOptions) =>
makeMastraHarness({
authStorage,
getKimiAccess: () => subscriptionAuth.getKimiForCodingAccess(),
+ memoryDbPath: NodePath.join(config.stateDir, "mastra-observational-memory.sqlite"),
syncThreadToolApproval: async (threadId, toolName, protectedAction) => {
const active = sessions.get(threadId);
if (!active || (!protectedAction && !active.connectorSessionApprovals.has(toolName))) {
@@ -367,6 +369,28 @@ const make = (options?: AgentControllerLiveOptions) =>
PubSub.publishUnsafe(runtimeEvents, event);
};
+ const queueTurnMemory = (threadId: ThreadId, active: ActiveSession, turn: ActiveTurn) => {
+ const resolved = resolvedByThread.get(String(threadId));
+ if (turn.memoryQueued || !bundle.observeAfterTurn || !resolved) return;
+ turn.memoryQueued = true;
+ void bundle
+ .observeAfterTurn({
+ threadId: String(threadId),
+ resourceId: String(threadId),
+ modelId: resolved.mastraModelId,
+ })
+ .catch((cause) => {
+ turn.memoryQueued = false;
+ Effect.runFork(
+ Effect.logWarning("Akeru background observational memory failed.", {
+ threadId,
+ turnId: turn.turnId,
+ cause,
+ }),
+ );
+ });
+ };
+
const baseEvent = (
threadId: ThreadId,
active: Pick<ActiveSession, "provider" | "providerInstanceId">,
@@ -426,6 +450,7 @@ const make = (options?: AgentControllerLiveOptions) =>
) => {
const turn = active.activeTurn;
if (!turn || turn.finished) return;
+ queueTurnMemory(threadId, active, turn);
turn.finished = true;
completeAssistantMessages(threadId, active, turn);
publish({
@@ -1001,6 +1026,7 @@ const make = (options?: AgentControllerLiveOptions) =>
assistantMessages: new Map(),
waiting: false,
finished: false,
+ memoryQueued: false,
};
active.status = "running";
publish({
@@ -1201,7 +1227,9 @@ const make = (options?: AgentControllerLiveOptions) =>
yield* runMastra("destroy", () => bundle.controller.destroy()).pipe(
Effect.ignoreCause({ log: true }),
);
- bundle.destroy();
+ yield* runMastra("bundle.destroy", async () => bundle.destroy()).pipe(
+ Effect.ignoreCause({ log: true }),
+ );
}),
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0b24445ae..0448bacc4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -484,6 +484,12 @@ importers:
'@mastra/core':
specifier: 1.63.0
+ '@mastra/libsql':
+ specifier: 1.22.0
+ '@mastra/memory':
+ specifier: 1.28.0
'@opencode-ai/sdk':
specifier: ^1.3.15
version: 1.15.13