π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): local message store and write-behind sync for device-hosted runs (#18908)
Arvin Xuff9bcb66ecd1
diff --git a/apps/cli/src/runtime/CliMessageTransport.ts b/apps/cli/src/runtime/CliMessageTransport.tsnew file mode 100644index 00000000000..d0f13977b25--- /dev/null+++ b/apps/cli/src/runtime/CliMessageTransport.ts@@ -0,0 +1,138 @@+import type {+ CreateAssistantMessageOptions,+ MessageTransport,+ QueryMessagesInput,+ QueryMessagesOptions,+ RuntimeMessageRef,+ UpdateToolMessageInput,+} from '@lobechat/agent-runtime';+import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';++import { LocalMessageStore } from './LocalMessageStore';+import type { MessageWriteQueue } from './MessageWriteQueue';++const toRef = (message: UIChatMessage): RuntimeMessageRef => ({+ agentId: message.agentId,+ groupId: message.groupId,+ id: message.id,+ model: message.model,+ parentId: message.parentId,+ provider: message.provider,+ role: message.role,+ threadId: message.threadId,+ topicId: message.topicId,+});++export interface CliMessageTransportOptions {+ /** Omit to run with no cloud replica at all. */+ queue?: MessageWriteQueue;+ store?: LocalMessageStore;+}++/**+ * {@link MessageTransport} for an agent run executing on a device.+ *+ * Reads are answered from memory and writes return as soon as the local store+ * has them; cloud replication happens behind the run. This is the difference+ * that makes local execution worth doing β the server adapter's `query()` is a+ * database round trip, and the runtime issues one after every tool batch, so a+ * naive device transport that read back from the cloud would trade the dispatch+ * latency it just saved for read latency instead.+ *+ * Message ids are minted here rather than by the database. That is what lets a+ * create return without waiting: the id the executor anchors its follow-up+ * writes to is already known, and the same id is what the replica is+ * eventually written under, so a replay rewrites rather than duplicates.+ */+export class CliMessageTransport implements MessageTransport {+ readonly store: LocalMessageStore;+ private readonly queue?: MessageWriteQueue;++ constructor(options: CliMessageTransportOptions = {}) {+ this.store = options.store ?? new LocalMessageStore();+ this.queue = options.queue;+ }++ async createAssistantMessage(+ params: CreateMessageParams,+ options?: CreateAssistantMessageOptions,+ ): Promise<RuntimeMessageRef> {+ const withClientId = options?.idempotencyKey+ ? { ...params, clientId: options.idempotencyKey }+ : params;++ const before = this.store.size;+ const message = this.store.insert(withClientId, nanoid());++ // A redelivered step resolves to the row already stored, so the replica+ // must not be told to create it twice.+ if (this.store.size > before) {+ await this.queue?.enqueue({+ message: { ...withClientId, id: message.id },+ type: 'createMessage',+ });+ }++ return toRef(message);+ }++ async createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {+ const message = this.store.insert(params, nanoid());+ await this.queue?.enqueue({ message: { ...params, id: message.id }, type: 'createMessage' });+ return toRef(message);+ }++ async deleteMessage(id: string): Promise<void> {+ this.store.delete(id);+ // Intentionally not replicated: `message.batchMutate` has no delete+ // operation, so a deletion cannot be expressed in the replay log. The rows+ // the runtime deletes are placeholders it created moments earlier in the+ // same run, so the replica converges as long as the create is dropped too β+ // which it is not yet. Tracked as the one known divergence; a delete+ // operation on the cloud procedure closes it.+ }++ async findById(id: string): Promise<RuntimeMessageRef | undefined> {+ const message = this.store.get(id);+ return message ? toRef(message) : undefined;+ }++ async findToolMessageIdByToolCallId(+ toolCallId: string,+ parentMessageId: string,+ ): Promise<string | undefined> {+ return this.store.findToolMessageIdByToolCallId(toolCallId, parentMessageId);+ }++ async query(+ params?: QueryMessagesInput,+ options?: QueryMessagesOptions,+ ): Promise<UIChatMessage[]> {+ return this.store.query(params, options);+ }++ async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {+ this.store.update(id, params);+ await this.queue?.enqueue({ id, type: 'updateMessage', value: params });+ }++ async updatePluginState(id: string, state: Record<string, any>): Promise<void> {+ this.store.updatePluginState(id, state);+ // The cloud's batch union has no plugin-state operation of its own; the+ // tool-message one carries the same column.+ await this.queue?.enqueue({ id, type: 'updateToolMessage', value: { pluginState: state } });+ }++ async updateToolIntervention(id: string, intervention: Record<string, any>): Promise<void> {+ this.store.updateToolIntervention(id, intervention);+ // Also not expressible in the batch union β intervention lives on the+ // plugin row. Local state is correct; the replica lags on approval status+ // until the cloud procedure grows an operation for it.+ }++ async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {+ this.store.updateToolMessage(id, params);+ await this.queue?.enqueue({ id, type: 'updateToolMessage', value: params });+ }+}diff --git a/apps/cli/src/runtime/LocalMessageStore.test.ts b/apps/cli/src/runtime/LocalMessageStore.test.tsnew file mode 100644index 00000000000..81801999fbf--- /dev/null+++ b/apps/cli/src/runtime/LocalMessageStore.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it } from 'vitest';++import { LocalMessageStore } from './LocalMessageStore';++const base = { agentId: 'agent-1', content: 'x', role: 'assistant' as const, topicId: 'topic-1' };++describe('LocalMessageStore query scoping', () => {+ it('treats an absent filter as IS NULL, not as "any"', () => {+ const store = new LocalMessageStore();+ store.insert({ ...base, threadId: null });+ store.insert({ ...base, content: 'in-thread', threadId: 'thread-1' });++ // Mirrors `matchThread(undefined)` β `isNull(messages.threadId)`. Treating+ // it as "any" would fold thread messages into a mainline read and hand the+ // model a conversation the server would never have produced.+ const mainline = store.query({ agentId: 'agent-1', topicId: 'topic-1' });+ expect(mainline).toHaveLength(1);+ expect(mainline[0].content).toBe('x');++ const thread = store.query({ agentId: 'agent-1', threadId: 'thread-1', topicId: 'topic-1' });+ expect(thread).toHaveLength(1);+ expect(thread[0].content).toBe('in-thread');+ });++ it('excludes rows outside the requested topic', () => {+ const store = new LocalMessageStore();+ store.insert(base);+ store.insert({ ...base, content: 'other', topicId: 'topic-2' });++ expect(store.query({ agentId: 'agent-1', topicId: 'topic-1' })).toHaveLength(1);+ });++ it('filters a group read on groupId alone', () => {+ const store = new LocalMessageStore();+ store.insert({ ...base, agentId: 'member-a', groupId: 'group-1' });+ store.insert({ ...base, agentId: 'member-b', groupId: 'group-1' });++ // Members share the group but carry different agentIds β adding agentId to+ // a group read would drop every member row but one.+ expect(store.query({ agentId: 'member-a', groupId: 'group-1', topicId: 'topic-1' })).toHaveLength(2);+ });++ it('keeps delegated-agent replies in a concrete-topic read', () => {+ const store = new LocalMessageStore();+ store.insert(base);+ store.insert({ ...base, agentId: 'delegate-9', content: 'callAgent reply' });++ // A concrete topic IS the conversation boundary and may legitimately hold+ // messages from several agents. Scoping a topic read by agentId deletes+ // delegated turns from the model's context β silently, and only on device.+ const messages = store.query({ agentId: 'agent-1', topicId: 'topic-1' });+ expect(messages.map((m) => m.content)).toEqual(['x', 'callAgent reply']);+ });++ it('still requires agent scope for an inbox read with no topic', () => {+ const store = new LocalMessageStore();+ store.insert({ ...base, topicId: undefined });+ store.insert({ ...base, agentId: 'other-agent', content: 'not mine', topicId: undefined });++ expect(store.query({ agentId: 'agent-1' }).map((m) => m.content)).toEqual(['x']);+ });++ it('excludes group messages from a plain topic read', () => {+ const store = new LocalMessageStore();+ store.insert(base);+ store.insert({ ...base, content: 'in a group', groupId: 'group-1' });++ // `matchGroup(undefined)` is `isNull(groupId)` on the server.+ expect(store.query({ topicId: 'topic-1' }).map((m) => m.content)).toEqual(['x']);+ });++ it('returns a thread together with its parent messages', () => {+ const store = new LocalMessageStore();+ const parent = store.insert({ ...base, content: 'the message the thread hangs off' });+ store.insert({ ...base, content: 'in thread', threadId: 'thread-1' });+ store.registerThreadParents('thread-1', [parent.id]);++ // The server resolves the thread's source message and returns it alongside+ // the thread rows. Without the parents a device-hosted thread starts the+ // model mid-conversation.+ const messages = store.query({ agentId: 'agent-1', threadId: 'thread-1', topicId: 'topic-1' });+ expect(messages.map((m) => m.content)).toEqual([+ 'the message the thread hangs off',+ 'in thread',+ ]);+ });++ it('falls back to exact thread matching when no parents were registered', () => {+ const store = new LocalMessageStore();+ store.insert({ ...base, content: 'parent' });+ store.insert({ ...base, content: 'in thread', threadId: 'thread-1' });++ // Mirrors the server's own fallback for a thread with no source message.+ expect(+ store.query({ threadId: 'thread-1', topicId: 'topic-1' }).map((m) => m.content),+ ).toEqual(['in thread']);+ });++ it('orders by creation, keeping insertion order within the same millisecond', () => {+ const store = new LocalMessageStore();+ for (const content of ['a', 'b', 'c', 'd']) store.insert({ ...base, content });++ expect(store.query({ agentId: 'agent-1', topicId: 'topic-1' }).map((m) => m.content)).toEqual([+ 'a',+ 'b',+ 'c',+ 'd',+ ]);+ });+});++describe('LocalMessageStore writes', () => {+ it('returns the existing row when a step is redelivered under the same key', () => {+ const store = new LocalMessageStore();+ const first = store.insert({ ...base, clientId: 'step-7' });+ const second = store.insert({ ...base, clientId: 'step-7', content: 'retry' });++ expect(second.id).toBe(first.id);+ expect(store.size).toBe(1);+ // The first write wins, matching the server's conflict path which returns+ // the persisted row rather than overwriting it.+ expect(second.content).toBe('x');+ });++ it('scopes the tool-call lookup to the assistant that made the call', () => {+ const store = new LocalMessageStore();+ const parentA = store.insert({ ...base, content: 'turn A' });+ const parentB = store.insert({ ...base, content: 'turn B' });+ const rowA = store.insert({+ ...base,+ content: 'result A',+ parentId: parentA.id,+ role: 'tool',+ tool_call_id: 'reused-id',+ } as never);+ store.insert({+ ...base,+ content: 'result B',+ parentId: parentB.id,+ role: 'tool',+ tool_call_id: 'reused-id',+ } as never);++ // `tool_call_id` is provider-supplied and can repeat across turns, so an+ // unscoped match would resolve to the wrong row β and this lookup feeds a write.+ expect(store.findToolMessageIdByToolCallId('reused-id', parentA.id)).toBe(rowA.id);+ expect(store.findToolMessageIdByToolCallId('reused-id', 'no-such-parent')).toBeUndefined();+ });++ it('merges plugin state rather than replacing it', () => {+ const store = new LocalMessageStore();+ const row = store.insert({ ...base, role: 'tool' });++ store.updatePluginState(row.id, { phase: 'running' });+ store.updatePluginState(row.id, { progress: 0.5 });++ // A tool reporting progress incrementally relies on earlier keys surviving.+ expect(store.get(row.id)?.pluginState).toEqual({ phase: 'running', progress: 0.5 });+ });++ it('patches metadata instead of replacing it', () => {+ const store = new LocalMessageStore();+ const row = store.insert({ ...base, metadata: { operationId: 'op-1', tps: 12 } } as never);++ store.update(row.id, { metadata: { totalTokens: 40 } } as never);++ // A `call_llm` step stamps provenance up front and finalizes with a second,+ // partial metadata write β a shallow spread would drop `operationId`, which+ // the cloud replica would still have.+ expect(store.get(row.id)?.metadata).toEqual({+ operationId: 'op-1',+ totalTokens: 40,+ tps: 12,+ });+ });++ it('forgets the idempotency key when the row is deleted', () => {+ const store = new LocalMessageStore();+ const first = store.insert({ ...base, clientId: 'step-7' });+ store.delete(first.id);++ // Otherwise the key would resolve to a row that no longer exists and the+ // re-created message would be silently dropped.+ const second = store.insert({ ...base, clientId: 'step-7' });+ expect(second.id).not.toBe(first.id);+ expect(store.size).toBe(1);+ });+});diff --git a/apps/cli/src/runtime/LocalMessageStore.ts b/apps/cli/src/runtime/LocalMessageStore.tsnew file mode 100644index 00000000000..aac31dd67a8--- /dev/null+++ b/apps/cli/src/runtime/LocalMessageStore.ts@@ -0,0 +1,261 @@+import type {+ QueryMessagesInput,+ QueryMessagesOptions,+ UpdateToolMessageInput,+} from '@lobechat/agent-runtime';+import { parse } from '@lobechat/conversation-flow';+import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';+import { merge, nanoid } from '@lobechat/utils';++/**+ * In-memory conversation store for a locally executed agent run.+ *+ * The runtime re-reads the whole message list after every tool step+ * (`executors/tool.ts` calls `messages.query()` twice per batch) and does a+ * parent preflight on every `call_llm`. On the server those are local database+ * queries; for a run executing on a device they must NOT become network round+ * trips, or the latency saved by running tools locally is handed straight back.+ *+ * So this store β not the cloud β is the authority for the duration of a run.+ * Replication to the cloud is a separate, asynchronous concern; nothing here+ * blocks on it.+ *+ * Semantics deliberately mirror `MessageModel.query`, because the runtime's+ * rebuilt state has to be the same shape either way:+ *+ * - An ABSENT scope filter means `IS NULL`, not "any". `matchTopic(undefined)`+ * is `isNull(messages.topicId)` on the server, so a query without a+ * `threadId` returns mainline messages only β never the whole topic+ * including its threads.+ * - Results are ordered by `(createdAt, id)` ascending.+ * - `flatten` runs the same `@lobechat/conversation-flow` parser the server+ * adapter uses, so grouped/tool rows collapse identically.+ */+export class LocalMessageStore {+ private readonly messages = new Map<string, UIChatMessage>();+ /** `clientId` β message id, for idempotent re-creation of one logical step. */+ private readonly byClientId = new Map<string, string>();+ /** Monotonic tiebreaker so messages created in the same millisecond keep insertion order. */+ private sequence = 0;+ private readonly sequenceById = new Map<string, number>();+ /**+ * `threadId` β the ids a thread read must include alongside its own rows.+ *+ * The server derives these by resolving the thread's `sourceMessageId`+ * against the `threads` table; a device has no such table, so the host+ * registers them when it hydrates. Unregistered, a thread read falls back to+ * exact `threadId` matching β which is also the server's own fallback when a+ * thread has no source message.+ */+ private readonly threadParents = new Map<string, Set<string>>();++ insert(params: CreateMessageParams, id: string = nanoid()): UIChatMessage {+ const existingId = params.clientId ? this.byClientId.get(params.clientId) : undefined;+ if (existingId) {+ const existing = this.messages.get(existingId);+ // Mirrors the server's idempotency conflict path: a redelivered step+ // returns the row already written rather than inserting a second one.+ if (existing) return existing;+ }++ const now = Date.now();+ // `clientId` is the idempotency key, not a message field; `sessionId` is the+ // deprecated predecessor of `agentId` and has no place on `UIChatMessage`.+ // Both are still forwarded to the cloud replica by the transport, which+ // sends the original params β the server resolves `sessionId` to an agent.+ const { clientId, sessionId: _sessionId, ...rest } = params;++ const message = {+ ...rest,+ content: params.content,+ createdAt: now,+ id,+ role: params.role,+ updatedAt: now,+ } as UIChatMessage;++ this.messages.set(id, message);+ this.sequenceById.set(id, this.sequence++);+ if (clientId) this.byClientId.set(clientId, id);++ return message;+ }++ get(id: string): UIChatMessage | undefined {+ return this.messages.get(id);+ }++ delete(id: string): void {+ this.messages.delete(id);+ this.sequenceById.delete(id);+ for (const [clientId, mappedId] of this.byClientId) {+ if (mappedId === id) this.byClientId.delete(clientId);+ }+ }++ update(id: string, params: Partial<UpdateMessageParams>): void {+ const existing = this.messages.get(id);+ if (!existing) return;++ const { metadata, ...rest } = params;+ const next = { ...existing, ...rest, updatedAt: Date.now() } as UIChatMessage;++ // `metadata` is patched, not replaced. A `call_llm` step stamps provenance+ // (operationId and friends) up front and finalizes with a second, partial+ // metadata write; a shallow spread would drop everything the first write+ // put there. The canonical model deep-merges here, so the local read-back+ // has to as well or device-hosted state quietly loses fields the cloud+ // replica still has.+ if (metadata !== undefined) {+ next.metadata = merge(existing.metadata ?? {}, metadata) as UIChatMessage['metadata'];+ }++ this.messages.set(id, next);+ }++ /**+ * Declare the messages a thread read must return alongside the thread's own+ * rows β the thread's source message and its ancestors.+ */+ registerThreadParents(threadId: string, parentMessageIds: string[]): void {+ this.threadParents.set(threadId, new Set(parentMessageIds));+ }++ updatePluginState(id: string, state: Record<string, any>): void {+ const existing = this.messages.get(id);+ if (!existing) return;+ // Merged, not replaced β the server's `updatePluginState` patches the row's+ // existing state, and a tool that reports progress incrementally relies on+ // earlier keys surviving.+ this.messages.set(id, {+ ...existing,+ pluginState: { ...existing.pluginState, ...state },+ updatedAt: Date.now(),+ });+ }++ updateToolIntervention(id: string, intervention: Record<string, any>): void {+ const existing = this.messages.get(id);+ if (!existing) return;+ this.messages.set(id, {+ ...existing,+ pluginIntervention: intervention as UIChatMessage['pluginIntervention'],+ updatedAt: Date.now(),+ });+ }++ updateToolMessage(id: string, params: UpdateToolMessageInput): void {+ const existing = this.messages.get(id);+ if (!existing) return;++ const next: UIChatMessage = { ...existing, updatedAt: Date.now() };+ if (params.content !== undefined) next.content = params.content;+ if (params.metadata !== undefined) {+ next.metadata = { ...existing.metadata, ...params.metadata } as never;+ }+ if (params.pluginError !== undefined) next.pluginError = params.pluginError;+ if (params.pluginState !== undefined) {+ next.pluginState = { ...existing.pluginState, ...params.pluginState };+ }++ this.messages.set(id, next);+ }++ /**+ * The tool row already holding this call, scoped to the assistant message+ * that made it β `tool_call_id` is provider-supplied, so an unscoped match+ * can hit a reused id from an unrelated turn.+ */+ findToolMessageIdByToolCallId(toolCallId: string, parentMessageId: string): string | undefined {+ for (const message of this.messages.values()) {+ if (+ message.role === 'tool' &&+ message.parentId === parentMessageId &&+ message.tool_call_id === toolCallId+ ) {+ return message.id;+ }+ }+ return undefined;+ }++ query(params: QueryMessagesInput = {}, options: QueryMessagesOptions = {}): UIChatMessage[] {+ const { agentId, groupId, threadId, topicId } = params;+ const all = [...this.messages.values()];++ // Three branches, mirroring `MessageModel.query`. They are not variations+ // on one predicate β each scopes differently, and collapsing them is how a+ // local store starts returning a different conversation than the server.+ let matches: UIChatMessage[];++ if (threadId) {+ // A complete thread is its own rows PLUS the parent messages it hangs+ // off; a thread read that returned only the former would start the model+ // mid-conversation. Scoped by topic when one is known, because a topic+ // thread can legitimately carry replies from delegated agents that the+ // parent-agent filter would drop.+ const parents = this.threadParents.get(threadId) ?? new Set<string>();+ matches = all.filter((message) => {+ if (message.threadId !== threadId && !parents.has(message.id)) return false;+ return topicId ? message.topicId === topicId : !agentId || message.agentId === agentId;+ });+ } else if (groupId) {+ // Group chat scopes on groupId alone: members share the group but carry+ // different agentIds, so adding agentId would drop every member row.+ matches = all.filter(+ (message) =>+ message.groupId === groupId &&+ this.matchesScope(message.topicId, topicId) &&+ this.matchesScope(message.threadId, threadId),+ );+ } else {+ matches = all.filter((message) => {+ // A concrete topic IS the conversation boundary and may hold messages+ // from several agents β `callAgent` replies among them. Only an inbox+ // read, which has no topic, still needs agent scope. Applying agentId+ // universally silently deletes delegated-agent turns from the model's+ // context on a device-hosted run.+ const inConversation = topicId+ ? message.topicId === topicId+ : (!agentId || message.agentId === agentId) && message.topicId == null;++ return (+ inConversation &&+ this.matchesScope(message.groupId, groupId) &&+ this.matchesScope(message.threadId, threadId)+ );+ });+ }++ matches.sort((a, b) => {+ if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;+ return (this.sequenceById.get(a.id) ?? 0) - (this.sequenceById.get(b.id) ?? 0);+ });++ if (!options.flatten) return matches;++ const { flatList } = parse(matches as never);+ return flatList as unknown as UIChatMessage[];+ }++ /** Every message, insertion-ordered. Used to seed a run from prior history. */+ all(): UIChatMessage[] {+ return this.query({}, {});+ }++ /** Seed prior conversation history fetched once at run start. */+ hydrate(messages: UIChatMessage[]): void {+ for (const message of messages) {+ this.messages.set(message.id, message);+ this.sequenceById.set(message.id, this.sequence++);+ }+ }++ get size(): number {+ return this.messages.size;+ }++ private matchesScope(value: string | null | undefined, filter: string | undefined): boolean {+ return filter ? value === filter : value === null || value === undefined;+ }+}diff --git a/apps/cli/src/runtime/MessageWriteQueue.test.ts b/apps/cli/src/runtime/MessageWriteQueue.test.tsnew file mode 100644index 00000000000..304f811d0e2--- /dev/null+++ b/apps/cli/src/runtime/MessageWriteQueue.test.ts@@ -0,0 +1,244 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MessageWriteQueue } from './MessageWriteQueue';+import type { MessageSyncOperation } from './messageSync';++let dir: string;+let logPath: string;++const op = (id: string): MessageSyncOperation => ({+ message: { content: id, id, role: 'assistant' },+ type: 'createMessage',+});++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'write-queue-'));+ logPath = path.join(dir, 'pending.jsonl');+});++afterEach(async () => {+ await fs.rm(dir, { force: true, recursive: true });+});++describe('MessageWriteQueue', () => {+ it('does not make the caller wait on the sink', async () => {+ let release: () => void = () => {};+ const queue = new MessageWriteQueue({+ sink: { flush: () => new Promise<void>((resolve) => (release = resolve)) },+ });++ // The whole point: enqueue is synchronous, so the agent loop never blocks+ // on replication.+ await queue.enqueue(op('a'));+ expect(queue.pending).toBe(1);++ release();+ });++ it('coalesces operations that arrive while a batch is in flight', async () => {+ const batches: number[] = [];+ let resolveFirst: () => void = () => {};+ const queue = new MessageWriteQueue({+ sink: {+ flush: async (operations) => {+ batches.push(operations.length);+ if (batches.length === 1) await new Promise<void>((r) => (resolveFirst = r));+ },+ },+ });++ await queue.enqueue(op('a'));+ await vi.waitFor(() => expect(batches).toHaveLength(1));++ // Three more arrive mid-flight; they should ship as ONE follow-up batch,+ // not three round trips queued behind each other.+ await queue.enqueue(op('b'));+ await queue.enqueue(op('c'));+ await queue.enqueue(op('d'));+ resolveFirst();+ await queue.drain();++ expect(batches).toEqual([1, 3]);+ });++ it('retries a failing batch and reports failure only after giving up', async () => {+ let attempts = 0;+ const queue = new MessageWriteQueue({+ initialBackoffMs: 1,+ sink: {+ flush: async () => {+ attempts += 1;+ if (attempts < 3) throw new Error('network down');+ },+ },+ });++ await queue.enqueue(op('a'));+ await queue.drain();++ expect(attempts).toBe(3);+ expect(queue.failed).toBe(false);+ });++ it('leaves unconfirmed operations on disk and replays them after a crash', async () => {+ // First process: the sink never succeeds, so nothing is confirmed.+ const dying = new MessageWriteQueue({+ initialBackoffMs: 1,+ logPath,+ onError: () => {},+ sink: { flush: async () => { throw new Error('offline'); } },+ });+ await dying.enqueue(op('a'));+ await dying.enqueue(op('b'));+ await dying.drain().catch(() => {});++ expect((await fs.readFile(logPath, 'utf8')).trim().split('\n')).toHaveLength(2);++ // Second process, network restored: the log is replayed, then cleared.+ const delivered: MessageSyncOperation[] = [];+ const revived = new MessageWriteQueue({+ logPath,+ sink: {+ flush: async (operations) => {+ delivered.push(...operations);+ },+ },+ });++ expect(await revived.recover()).toBe(2);+ await revived.drain();++ expect(delivered.map((o) => (o.type === 'createMessage' ? o.message.id : ''))).toEqual([+ 'a',+ 'b',+ ]);+ await expect(fs.readFile(logPath, 'utf8')).rejects.toThrow();+ });++ it('survives a replay of a batch the backend already has', async () => {+ // The crash window: the sink commits, then the process dies before the+ // acknowledgement is recorded. On restart the identical batch is replayed+ // and a plain-insert backend rejects it as a duplicate. Without the+ // classifier that batch fails forever, exhausts its retries, and ends ALL+ // later replication for the run.+ await fs.writeFile(logPath, `${JSON.stringify(op('a'))}\n`, 'utf8');++ let calls = 0;+ const queue = new MessageWriteQueue({+ initialBackoffMs: 1,+ logPath,+ sink: {+ flush: async () => {+ calls += 1;+ throw new Error('duplicate key value violates unique constraint');+ },+ isAlreadyApplied: (error) => String(error).includes('duplicate key'),+ },+ });++ expect(await queue.recover()).toBe(1);+ await queue.drain();++ expect(calls).toBe(1);+ expect(queue.failed).toBe(false);+ // Acknowledged, so the log is cleared rather than replayed again forever.+ await expect(fs.readFile(logPath, 'utf8')).rejects.toThrow();+ });++ it('without the classifier a replayed batch still stops replication', async () => {+ // Documents why `isAlreadyApplied` exists: this is the behaviour it fixes.+ await fs.writeFile(logPath, `${JSON.stringify(op('a'))}\n`, 'utf8');++ const queue = new MessageWriteQueue({+ initialBackoffMs: 1,+ logPath,+ onError: () => {},+ sink: { flush: async () => { throw new Error('duplicate key'); } },+ });++ await queue.recover();+ await queue.drain().catch(() => {});+ expect(queue.failed).toBe(true);+ });++ it('has the record on disk before the enqueue resolves', async () => {+ const queue = new MessageWriteQueue({+ logPath,+ sink: { flush: () => new Promise<void>(() => {}) },+ });++ await queue.enqueue(op('a'));++ // Not "eventually" β by the time enqueue resolves. Anything less leaves a+ // window where an operation is neither sent nor recoverable.+ expect((await fs.readFile(logPath, 'utf8')).trim()).toBe(JSON.stringify(op('a')));+ });++ it('reports an unwritable log instead of failing the run', async () => {+ const warnings: string[] = [];+ const queue = new MessageWriteQueue({+ // A directory where the file should be β appending can never succeed.+ logPath: dir,+ onError: (message) => warnings.push(message),+ sink: { flush: async () => {} },+ });++ // Replication is no longer crash-safe, and that is surfaced β but a working+ // run is not killed because its replica log is inaccessible.+ await expect(queue.enqueue(op('a'))).resolves.toBeUndefined();+ expect(queue.degraded).toBe(true);+ expect(warnings.join()).toContain('not durable');++ await queue.drain();+ });++ it('recovers the intact entries when the last log line was truncated', async () => {+ // A process killed mid-append leaves a partial trailing line. The entries+ // before it are still deliverable and must not be thrown away with it.+ await fs.writeFile(logPath, `${JSON.stringify(op('a'))}\n{"type":"createMess`, 'utf8');++ const delivered: MessageSyncOperation[] = [];+ const queue = new MessageWriteQueue({+ logPath,+ onError: () => {},+ sink: {+ flush: async (operations) => {+ delivered.push(...operations);+ },+ },+ });++ expect(await queue.recover()).toBe(1);+ await queue.drain();+ expect(delivered).toHaveLength(1);+ });++ it('keeps operations appended while a batch was in flight', async () => {+ let resolveFirst: () => void = () => {};+ let calls = 0;+ const queue = new MessageWriteQueue({+ logPath,+ sink: {+ flush: async () => {+ calls += 1;+ if (calls === 1) await new Promise<void>((r) => (resolveFirst = r));+ },+ },+ });++ await queue.enqueue(op('a'));+ await vi.waitFor(() => expect(calls).toBe(1));+ await queue.enqueue(op('b'));++ // Confirming the first batch must trim only its own prefix β truncating the+ // whole file here would discard `b`, which nothing has delivered yet.+ resolveFirst();+ await queue.drain();++ await expect(fs.readFile(logPath, 'utf8')).rejects.toThrow();+ expect(calls).toBe(2);+ });+});diff --git a/apps/cli/src/runtime/MessageWriteQueue.ts b/apps/cli/src/runtime/MessageWriteQueue.tsnew file mode 100644index 00000000000..07a484ed10a--- /dev/null+++ b/apps/cli/src/runtime/MessageWriteQueue.ts@@ -0,0 +1,267 @@+import fs from 'node:fs/promises';+import path from 'node:path';++import { MAX_SYNC_BATCH, type MessageSyncOperation, type MessageSyncSink } from './messageSync';++const FLUSH_INTERVAL_MS = 250;+const MAX_RETRIES = 5;+const INITIAL_BACKOFF_MS = 500;+const MAX_BACKOFF_MS = 8_000;++const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++export interface MessageWriteQueueOptions {+ /** First retry delay; doubles up to {@link MAX_BACKOFF_MS}. Injectable so tests+ * need not sit through the real schedule. */+ initialBackoffMs?: number;+ /**+ * Append-only log of operations not yet confirmed by the sink. Omit to run+ * without crash recovery (tests, or a run that tolerates losing its replica).+ */+ logPath?: string;+ maxRetries?: number;+ onError?: (message: string) => void;+ sink: MessageSyncSink;+}++/**+ * Write-behind replication of local messages to the cloud.+ *+ * The point is that `enqueue` returns immediately: the runtime has already+ * written to {@link LocalMessageStore} and read its own write back from+ * memory, so nothing in the agent loop waits on the network. Batches ship in+ * the background and the cloud becomes eventually consistent.+ *+ * Durability comes from the log rather than from blocking. Each operation is+ * appended as one JSON line before it is considered accepted; lines are only+ * dropped once the sink has confirmed them. A process killed mid-run therefore+ * leaves exactly the un-replicated operations on disk, and {@link recover}+ * replays them. Every operation carries the message id assigned locally, so a+ * replay that overlaps an already-delivered batch rewrites the same rows+ * instead of duplicating them.+ */+export class MessageWriteQueue {+ private buffer: MessageSyncOperation[] = [];+ private fatalError: Error | null = null;+ private pumping = false;+ private timer: ReturnType<typeof setTimeout> | null = null;+ private worker: Promise<void> = Promise.resolve();+ /** Serializes log appends so concurrent enqueues cannot interleave a line. */+ private logWrites: Promise<void> = Promise.resolve();+ private logDegraded = false;++ constructor(private readonly options: MessageWriteQueueOptions) {}++ /** True once a batch has exhausted its retries; later operations are logged but not sent. */+ get failed(): boolean {+ return this.fatalError !== null;+ }++ /**+ * True once a log append has failed. Replication still runs, but a crash from+ * here on loses whatever has not yet been confirmed.+ */+ get degraded(): boolean {+ return this.logDegraded;+ }++ get pending(): number {+ return this.buffer.length;+ }++ /**+ * Record a mutation for eventual replication.+ *+ * Awaits the log append but never the network β the distinction is the whole+ * design. A local append costs microseconds; the network round trip this+ * exists to avoid costs hundreds of milliseconds. Returning before the record+ * is on disk would leave a window where an operation is neither sent nor+ * recoverable, which is the one thing a write-ahead log must not allow.+ */+ async enqueue(operation: MessageSyncOperation): Promise<void> {+ await this.appendToLog(operation);++ if (this.fatalError) return;+ this.buffer.push(operation);++ if (this.pumping) return;+ if (this.buffer.length >= MAX_SYNC_BATCH) {+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ this.startPump();+ } else if (!this.timer) {+ this.timer = setTimeout(() => {+ this.timer = null;+ this.startPump();+ }, FLUSH_INTERVAL_MS);+ }+ }++ /** Flush everything buffered and wait for the sink to settle. */+ async drain(): Promise<void> {+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ this.startPump();+ await this.worker;+ await this.logWrites;+ if (this.fatalError) throw this.fatalError;+ }++ /**+ * Replay operations a previous process logged but never confirmed.+ *+ * Called at start-up, before the run enqueues anything of its own, so the+ * replayed operations ship ahead of the new ones and the cloud sees them in+ * their original order.+ */+ async recover(): Promise<number> {+ const logPath = this.options.logPath;+ if (!logPath) return 0;++ const raw = await fs.readFile(logPath, 'utf8').catch(() => '');+ if (!raw.trim()) return 0;++ let recovered = 0;+ for (const line of raw.split('\n')) {+ if (!line.trim()) continue;+ try {+ this.buffer.push(JSON.parse(line) as MessageSyncOperation);+ recovered += 1;+ } catch {+ // A process killed mid-append leaves one truncated trailing line. The+ // operations before it are intact and still worth replaying, so skip+ // the fragment rather than discarding the whole log.+ this.warn('skipped a truncated entry in the write log');+ }+ }++ if (recovered > 0) this.startPump();+ return recovered;+ }++ private startPump(): void {+ if (this.pumping || this.fatalError || this.buffer.length === 0) return;+ this.pumping = true;+ this.worker = this.pump();+ }++ private async pump(): Promise<void> {+ try {+ while (!this.fatalError && this.buffer.length > 0) {+ // Spliced at send time, not when the flush was scheduled, so operations+ // arriving during a slow request coalesce into the next batch instead+ // of fragmenting into micro-batches queued behind it.+ const batch = this.buffer.splice(0, MAX_SYNC_BATCH);+ await this.send(batch);+ }+ } finally {+ this.pumping = false;+ }+ }++ private async send(batch: MessageSyncOperation[]): Promise<void> {+ let backoff = this.options.initialBackoffMs ?? INITIAL_BACKOFF_MS;+ const maxRetries = this.options.maxRetries ?? MAX_RETRIES;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ await this.options.sink.flush(batch);+ await this.confirm(batch.length);+ return;+ } catch (error) {+ // A batch replayed after a crash reaches a backend that already has+ // those rows. Retrying it can never succeed, and letting it exhaust the+ // retries would set `fatalError` and end replication for the whole run.+ if (this.options.sink.isAlreadyApplied?.(error)) {+ await this.confirm(batch.length);+ return;+ }+ if (attempt === maxRetries) {+ this.fatalError = error instanceof Error ? error : new Error(String(error));+ this.warn(`giving up on a batch of ${batch.length}: ${this.fatalError.message}`);+ return;+ }+ await sleep(backoff);+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);+ }+ }+ }++ /**+ * Drop the confirmed prefix from the log.+ *+ * Rewriting the remainder rather than truncating: entries appended while the+ * batch was in flight sit after the confirmed ones and must survive.+ */+ private async confirm(count: number): Promise<void> {+ const logPath = this.options.logPath;+ if (!logPath) return;++ this.logWrites = this.logWrites.then(async () => {+ try {+ const raw = await fs.readFile(logPath, 'utf8').catch(() => '');+ const remaining = raw+ .split('\n')+ .filter((line) => line.trim())+ .slice(count);++ if (remaining.length === 0) {+ await fs.rm(logPath, { force: true });+ return;+ }+ await this.writeAtomic(logPath, `${remaining.join('\n')}\n`);+ } catch (error) {+ this.warn(`failed to trim the write log: ${String(error)}`);+ }+ });+ await this.logWrites;+ }++ /**+ * Append one record, serialized against other appends so two enqueues cannot+ * interleave a line.+ *+ * A failure here is surfaced and marks the queue {@link degraded} rather than+ * throwing: an unwritable log means replication is no longer crash-safe, but+ * the run itself is still correct and its trace is still being recorded+ * locally. Killing a working agent run because its replica log is+ * inaccessible trades a recoverable problem for an unrecoverable one.+ */+ private async appendToLog(operation: MessageSyncOperation): Promise<void> {+ const logPath = this.options.logPath;+ if (!logPath) return;++ this.logWrites = this.logWrites.then(async () => {+ await fs.mkdir(path.dirname(logPath), { recursive: true });+ await fs.appendFile(logPath, `${JSON.stringify(operation)}\n`, 'utf8');+ });++ try {+ await this.logWrites;+ } catch (error) {+ this.logDegraded = true;+ this.warn(`write log is not durable: ${String(error)}`);+ // Reset the chain so one failure does not reject every later append.+ this.logWrites = Promise.resolve();+ }+ }++ private async writeAtomic(filePath: string, content: string): Promise<void> {+ const tmp = `${filePath}.${process.pid}.tmp`;+ try {+ await fs.writeFile(tmp, content, 'utf8');+ await fs.rename(tmp, filePath);+ } catch (error) {+ await fs.rm(tmp, { force: true }).catch(() => {});+ throw error;+ }+ }++ private warn(message: string): void {+ this.options.onError?.(message);+ }+}diff --git a/apps/cli/src/runtime/messageSync.ts b/apps/cli/src/runtime/messageSync.tsnew file mode 100644index 00000000000..0aa8c0e6393--- /dev/null+++ b/apps/cli/src/runtime/messageSync.ts@@ -0,0 +1,53 @@+import type { UpdateToolMessageInput } from '@lobechat/agent-runtime';+import type { CreateMessageParams, UpdateMessageParams } from '@lobechat/types';++/**+ * One durable mutation, in the shape the cloud's `message.batchMutate`+ * procedure accepts. Deliberately a narrow union rather than "whatever the+ * store did": the replica is rebuilt by replaying these, so anything not+ * expressible here would silently diverge.+ */+export type MessageSyncOperation =+ | { message: CreateMessageParams & { id: string }; type: 'createMessage' }+ | { id: string; type: 'updateMessage'; value: Partial<UpdateMessageParams> }+ | { id: string; type: 'updateToolMessage'; value: UpdateToolMessageInput };++/**+ * Where a locally executed run replicates its messages.+ *+ * A port, not a tRPC client, for two reasons: the queue is testable without a+ * network, and the CLI is not the only possible host for a local runtime.+ */+export interface MessageSyncSink {+ /**+ * Deliver a batch. MUST throw on failure so the queue can retry β a sink that+ * swallows errors turns a lost batch into silent data loss.+ *+ * MUST also be idempotent for a repeated identical batch. Redelivery is not+ * an edge case: a process that dies after the sink commits but before the+ * queue records the acknowledgement will replay that batch on restart, and+ * every operation carries a locally-minted id, so the retry is byte-identical.+ * A sink backed by a plain insert will reject it as a duplicate.+ *+ * The cloud procedure caps a batch at 200 operations; the queue respects that.+ */+ flush: (operations: MessageSyncOperation[]) => Promise<void>;+ /**+ * Classify a `flush` rejection as "these rows are already there".+ *+ * Without this a single replayed batch is fatal: it fails forever, exhausts+ * the retries, and stops ALL later replication β one crash at the wrong+ * moment silently ends the cloud replica for the rest of the run. Sinks whose+ * backend cannot express an upsert use this to acknowledge a duplicate+ * instead.+ */+ isAlreadyApplied?: (error: unknown) => boolean;+}++/** Cloud limit on one `message.batchMutate` call. */+export const MAX_SYNC_BATCH = 200;++/** Drops everything. For runs that deliberately keep no cloud replica. */+export class NoopMessageSyncSink implements MessageSyncSink {+ async flush(): Promise<void> {}+}diff --git a/apps/cli/src/runtime/runtimeIntegration.test.ts b/apps/cli/src/runtime/runtimeIntegration.test.tsnew file mode 100644index 00000000000..cc457c1726e--- /dev/null+++ b/apps/cli/src/runtime/runtimeIntegration.test.ts@@ -0,0 +1,196 @@+import type { AgentRuntimeHost } from '@lobechat/agent-runtime';+import { callTool, callToolsBatch } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { CliMessageTransport } from './CliMessageTransport';+import type { MessageSyncOperation } from './messageSync';+import { MessageWriteQueue } from './MessageWriteQueue';++/**+ * Drives the REAL agent-runtime tool executors against the local transport, so+ * the store is checked against the contract the runtime actually imposes rather+ * than against my reading of it. In particular the runtime re-queries the whole+ * message list after every tool step β that read has to be answered locally and+ * has to return what the executor expects, or a device-hosted run silently+ * rebuilds the wrong state.+ */+const createCost = () => ({+ calculatedAt: '2026-07-09T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+});++const createUsage = () => ({+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+});++const createState = (overrides?: Record<string, unknown>) =>+ ({+ cost: createCost(),+ createdAt: '2026-07-09T00:00:00.000Z',+ lastModified: '2026-07-09T00:00:00.000Z',+ maxSteps: 100,+ messages: [],+ metadata: { agentId: 'agent-1', topicId: 'topic-1' },+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createUsage(),+ ...overrides,+ }) as never;++const createToolCall = (id = 'tool-call-1') => ({+ apiName: 'search',+ arguments: '{"query":"test"}',+ id,+ identifier: 'web-search',+ type: 'default' as const,+});++describe('CliMessageTransport driving the real runtime executors', () => {+ let transport: CliMessageTransport;+ let queue: MessageWriteQueue;+ let flushed: MessageSyncOperation[][];+ let host: AgentRuntimeHost;++ beforeEach(() => {+ flushed = [];+ queue = new MessageWriteQueue({+ sink: {+ flush: async (operations) => {+ flushed.push(operations);+ },+ },+ });+ transport = new CliMessageTransport({ queue });++ host = {+ operation: { operationId: 'op-1', stepIndex: 2 },+ transports: {+ messages: transport,+ stream: {+ publishChunk: vi.fn().mockResolvedValue(undefined),+ publishError: vi.fn().mockResolvedValue(undefined),+ publishEvent: vi.fn().mockResolvedValue(undefined),+ },+ tools: {+ getCost: vi.fn().mockReturnValue(0),+ handleError: vi.fn(),+ maxRetries: 2,+ run: vi.fn().mockResolvedValue({+ attempts: 1,+ result: { content: 'Tool result', executionTime: 100, state: {}, success: true },+ // Without this the executor keeps the row in memory instead of+ // re-reading the store β which would leave the very path this+ // suite exists to cover untested.+ resultPersisted: true,+ }),+ },+ },+ } as unknown as AgentRuntimeHost;+ });++ it('persists a tool result and rebuilds state from the local store', async () => {+ const assistant = await transport.createAssistantMessage({+ // Deliberately NO agentId: the runtime re-queries with the state's+ // `agentId`, but a concrete topic is the conversation boundary, so this+ // row must still come back β the same rule that keeps delegated-agent+ // (`callAgent`) replies in context.+ content: 'calling a tool',+ role: 'assistant',+ topicId: 'topic-1',+ });++ const result = await callTool(host)(+ {+ payload: { parentMessageId: assistant.id, toolCalling: createToolCall() },+ type: 'call_tool',+ } as never,+ createState(),+ );++ // `newState.messages` is the runtime's re-query through this transport β+ // it must come back with the tool row that was just written.+ const rebuilt = result.newState.messages;+ expect(rebuilt).toContainEqual(+ expect.objectContaining({ content: 'Tool result', role: 'tool' }),+ );+ expect(rebuilt).toContainEqual(expect.objectContaining({ id: assistant.id }));+ expect(result.nextContext?.phase).toBe('tool_result');+ });++ it('answers the runtime read-back without waiting on the sink', async () => {+ // A sink that never settles stands in for an unreachable network.+ const stalled = new MessageWriteQueue({ sink: { flush: () => new Promise<void>(() => {}) } });+ const offline = new CliMessageTransport({ queue: stalled });+ const offlineHost = {+ ...host,+ transports: { ...host.transports, messages: offline },+ } as AgentRuntimeHost;++ const assistant = await offline.createAssistantMessage({+ agentId: 'agent-1',+ content: 'calling a tool',+ role: 'assistant',+ topicId: 'topic-1',+ });++ // Would hang if any step awaited replication.+ const result = await callTool(offlineHost)(+ {+ payload: { parentMessageId: assistant.id, toolCalling: createToolCall() },+ type: 'call_tool',+ } as never,+ createState(),+ );++ expect(result.newState.messages).toContainEqual(+ expect.objectContaining({ content: 'Tool result', role: 'tool' }),+ );+ });++ it('keeps one row per tool call across a batch and queues each for replication', async () => {+ const assistant = await transport.createAssistantMessage({+ agentId: 'agent-1',+ content: 'calling three tools',+ role: 'assistant',+ topicId: 'topic-1',+ });++ const result = await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: assistant.id,+ toolsCalling: [createToolCall('c1'), createToolCall('c2'), createToolCall('c3')],+ },+ type: 'call_tools_batch',+ } as never,+ createState(),+ );++ const toolRows = result.newState.messages.filter((m: { role: string }) => m.role === 'tool');+ expect(toolRows).toHaveLength(3);+ // Distinct rows, not one row overwritten three times.+ expect(new Set(toolRows.map((m: { id: string }) => m.id)).size).toBe(3);++ await queue.drain();+ const operations = flushed.flat();+ // One assistant + three tool rows.+ expect(operations.filter((o) => o.type === 'createMessage')).toHaveLength(4);+ // Every replicated create carries the id assigned locally, so a replay+ // rewrites the same row instead of inserting a duplicate.+ for (const op of operations) {+ if (op.type === 'createMessage') expect(op.message.id).toBeTruthy();+ }+ });+});diff --git a/apps/cli/vitest.config.mts b/apps/cli/vitest.config.mtsindex b94b29b002e..39a861f9c78 100644--- a/apps/cli/vitest.config.mts+++ b/apps/cli/vitest.config.mts@@ -3,6 +3,18 @@ import path from 'node:path';import { defineConfig } from 'vitest/config';export default defineConfig({+ plugins: [+ // Importing `@lobechat/agent-runtime` pulls in `@lobechat/context-engine`,+ // which reaches `@lobechat/agent-templates` and its `.md` prompt files.+ // Vitest would otherwise try to parse the Markdown as JavaScript. Mirrors+ // the root config's `raw-md` plugin; the content is irrelevant to the CLI.+ {+ name: 'raw-md',+ transform(_code: string, id: string) {+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };+ },+ },+ ],resolve: {alias: [{