Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 423178804f Keep OpenCode reply paragraphs from running together (#11745)
* fix(opencode): keep reply paragraphs separate across text parts

OpenCode can put multiple text parts in one assistant message. Preserve their paragraph boundary when Paseo joins the streamed chunks or replays history.

* refactor(opencode): name timeline text arguments

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 13:12:52 +00:00
KiritoXD 5f3396fec0 Reject malformed label filters in agent listings (#11707) 2026-12-02 12:42:43 +00:00
Mohamed Boudra 45dfc2b98b Store durable agent message queues in paseo.db (#11740)
* refactor(server): store durable agent message queues in paseo.db

Move AgentMessageQueueStore persistence from per-recipient JSON files under $PASEO_HOME/agent-queues/ into a modular SchemaModule (agent_message_queues) in the existing SQLite daemon database (paseo.db).

Agent message queues have not shipped in a stable release yet, so switching before v0.19.0 avoids carrying permanent JSON-to-SQLite migration code and directory hygiene logic (corrupt/stray file handling). All queue transitions run inside synchronous DaemonDatabase transactions, preserving monotonic per-recipient sequence numbers, idempotency/conflict checks, depth caps, insertBeforeId ordering, urgency clearing, and lossless UTF-8/NUL/surrogate round-trips via JSON-encoded text columns.

* fix(server): JSON-encode queue ids, sessionMode, and fingerprint in SQLite

node:sqlite truncates raw TEXT columns at NUL bytes and replaces lone surrogates with U+FFFD, which could cause accepted messages with non-ASCII/surrogate messageIds to mismatch in markDispatching and stall in dispatching state. Store id, sessionMode, and fingerprint as JSON strings alongside text/payload columns and cover all lookup/mutation operations in the shared contract tests.
2026-12-02 19:14:27 +07:00
paseo-bot[bot] 6cee7dc10d fix(claude): keep goal acknowledgements after transcript import (#11733)
Claude records the goal acknowledgement as local command output. Replay that specific record so a restored conversation retains the same acknowledgement as the live turn.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 12:13:12 +00:00
20 changed files with 1073 additions and 565 deletions
+2 -2
View File
@@ -178,9 +178,9 @@ the switch. Promoting the switch cuts the running turn once the target is known
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
The queue is saved in `$PASEO_HOME/paseo.db` ([data model](data-model.md#agent-message-queues)),
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
queue file holds references. An empty message is refused, and a recipient holds at most 100
queue holds references. An empty message is refused, and a recipient holds at most 100
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
+9 -5
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines and agent message queues in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -60,9 +60,6 @@ $PASEO_HOME/
│ └── {agentId}.json # One file per agent
├── schedules/
│ └── {scheduleId}.json # One file per schedule
├── agent-queues/
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
├── projects/
│ ├── projects.json # Project registry
│ ├── workspaces.json # Workspace registry
@@ -188,7 +185,7 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
(`packages/server/src/server/database/`). Agent timelines and agent message queues live here. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
@@ -222,6 +219,13 @@ of a streamed assistant or reasoning message is stored as one chunk per source e
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
### Agent message queues
`AgentMessageQueueStore` stores undelivered per-recipient messages in `agent_message_queue_items`
and monotonic per-recipient sequence counters in `agent_message_queue_recipients`. Message text and
structured payloads are stored as JSON strings so NUL bytes and lone surrogates round-trip through
`node:sqlite`. See [agent-lifecycle.md](agent-lifecycle.md).
---
## 2. Daemon Configuration
@@ -81,6 +81,11 @@ describe("buildAgentLsFetchOptions", () => {
});
});
it("preserves empty values and punctuation in repeated label filters", () => {
const options = buildAgentLsFetchOptions({ label: ["tag=v=1,rc", "empty="] });
expect(options.filter?.labels).toEqual({ tag: "v=1,rc", empty: "" });
});
it("asks the daemon for internal agents only with --internal", () => {
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
filter: { includeBackground: true },
@@ -126,6 +131,17 @@ describe("buildAgentLsFetchOptions", () => {
});
describe("runLsCommand", () => {
it.each(["team", "=blue", " =blue"])(
"rejects the whole listing when a label filter is malformed (%j)",
async (label) => {
await expect(
listAgents({ daemonTarget, label: ["bot=worker", label] }, async () =>
createPagingClient(),
),
).rejects.toMatchObject({ code: "INVALID_LABEL", message: `Invalid label format: ${label}` });
},
);
it("includes agent snapshot metadata in JSON listings", async () => {
const result = await listAgents({ daemonTarget, global: true }, async () =>
createPagingClient(),
+17 -13
View File
@@ -141,16 +141,20 @@ export interface AgentLsOptions extends CommandOptions {
}
function parseLabelFilters(labels: string[] | undefined): Record<string, string> {
const labelFilters: Record<string, string> = {};
for (const labelStr of labels ?? []) {
const eqIndex = labelStr.indexOf("=");
if (eqIndex !== -1) {
const key = labelStr.slice(0, eqIndex);
const value = labelStr.slice(eqIndex + 1);
labelFilters[key] = value;
}
}
return labelFilters;
return Object.fromEntries(
(labels ?? []).map((label) => {
const separator = label.indexOf("=");
const key = label.slice(0, separator);
if (separator === -1 || !key.trim()) {
throw {
code: "INVALID_LABEL",
message: `Invalid label format: ${label}`,
details: "Labels must include a non-empty key in key=value format",
} satisfies CommandError;
}
return [key, label.slice(separator + 1)];
}),
);
}
export function buildAgentLsFetchOptions(
@@ -211,6 +215,7 @@ export async function listAgents(
options: Parameters<typeof connectToDaemon>[0],
) => Promise<AgentLsClient> = connectToDaemon,
): Promise<AgentLsResult> {
const fetchOptions = buildAgentLsFetchOptions(options);
const client = await connect({ target: options.daemonTarget });
try {
@@ -223,8 +228,6 @@ export async function listAgents(
throw error;
}
const labelFilters = parseLabelFilters(options.label);
const fetchOptions = buildAgentLsFetchOptions(options);
let agents = await fetchAllAgents(client, fetchOptions);
// By default, exclude archived agents. `-a` includes them.
@@ -243,7 +246,8 @@ export async function listAgents(
}
// Apply label filtering only when explicitly requested.
if (Object.keys(labelFilters).length > 0) {
const labelFilters = fetchOptions.filter?.labels;
if (labelFilters) {
agents = agents.filter((a) => {
const agentLabels = a.labels;
for (const [key, value] of Object.entries(labelFilters)) {
@@ -1,12 +1,15 @@
import { mkdtemp, rm } from "node:fs/promises";
import { access, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, onTestFinished, test } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { openDaemonDatabase, type DaemonDatabase } from "../../database/index.js";
import { AgentTurnStartRejectedError } from "../agent-prompt.js";
import type { AgentPromptInput, AgentTimelineItem } from "../agent-sdk-types.js";
import {
agentMessageQueueSchema,
createAgentMessageDelivery,
createJsonAgentMessageQueueStore,
createSqliteAgentMessageQueueStore,
MAX_AGENT_QUEUE_DEPTH,
projectAgentMessages,
type AgentMessageDelivery,
@@ -21,6 +24,23 @@ async function createHome(): Promise<string> {
return paseoHome;
}
const openDatabases: DaemonDatabase[] = [];
function openQueueDatabase(paseoHome: string): DaemonDatabase {
const database = openDaemonDatabase({
path: join(paseoHome, "paseo.db"),
modules: [agentMessageQueueSchema],
logger: createTestLogger(),
});
openDatabases.push(database);
onTestFinished(() => {
database.close();
const index = openDatabases.indexOf(database);
if (index >= 0) openDatabases.splice(index, 1);
});
return database;
}
interface DaemonOptions {
running?: boolean;
/** The provider takes the prompt and the daemon dies before hearing back. */
@@ -58,9 +78,10 @@ function trackWrites(store: AgentMessageQueueStore) {
return { store: tracked, settle };
}
/** One daemon process over the queue files in `paseoHome`. Open another to restart it. */
/** One daemon process over `paseo.db` in `paseoHome`. Open another to restart it. */
function openDaemon(paseoHome: string, options: DaemonOptions = {}) {
const { store, settle } = trackWrites(createJsonAgentMessageQueueStore(paseoHome));
const database = openQueueDatabase(paseoHome);
const { store, settle } = trackWrites(createSqliteAgentMessageQueueStore(database));
const sent: Array<{ ids: readonly string[]; behavior: string; prompt: AgentPromptInput }> = [];
const withdrawn: string[] = [];
const errors: unknown[] = [];
@@ -466,6 +487,7 @@ test("splitting an urgent release persists the urgency downgrade so a restart wa
await first.delivery.close();
// After restart while the first group's turn is running, direct-1 must NOT interrupt it.
await expect(access(join(home, "agent-queues"))).rejects.toMatchObject({ code: "ENOENT" });
const second = openDaemon(home, { running: true });
await second.delivery.start();
await second.settle();
@@ -20,5 +20,8 @@ export {
type QueuedMessageUrgency,
type WithdrawStoreResult,
} from "./store.js";
export { createJsonAgentMessageQueueStore, type CorruptQueueFile } from "./internal/json-store.js";
export { createMemoryAgentMessageQueueStore } from "./internal/memory-store.js";
export {
agentMessageQueueSchema,
createSqliteAgentMessageQueueStore,
} from "./internal/sqlite-store.js";
@@ -1,243 +0,0 @@
import { readdir, readFile, rename, rm } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { AgentAttachmentSchema, QueuedProviderSwitchSchema } from "@getpaseo/protocol/messages";
import { z } from "zod";
import { writeJsonFileAtomic } from "../../../atomic-file.js";
import { agentPromptSourceSchema } from "../envelope.js";
import type { AgentMessageQueueStore } from "../store.js";
import {
assertValidRecipientId,
clearQueue,
clearUrgencyInQueue,
cloneQueuedMessage,
createEmptyRecipientQueueState,
createKeyedSerializer,
enqueueIntoQueue,
isValidRecipientId,
markDispatchingInQueue,
markHeldInQueue,
promoteInQueue,
removeFromQueue,
revertDispatchingInQueue,
sortAllQueuedMessages,
sortQueuedMessages,
withdrawFromQueue,
type RecipientQueueState,
type TransitionOutcome,
} from "./queue-state.js";
const PersistedQueuedMessageSchema = z.object({
id: z.string().min(1),
recipientId: z.string().min(1),
seq: z.number().int().positive(),
enqueuedAt: z.string().min(1),
text: z.string(),
attachments: z.array(AgentAttachmentSchema),
source: agentPromptSourceSchema.nullable(),
sessionMode: z.string().min(1).optional(),
providerSwitch: QueuedProviderSwitchSchema.optional(),
unarchive: z.boolean(),
clearPendingPermissions: z.boolean(),
urgency: z.enum(["steer", "interrupt"]).nullable(),
held: z.boolean(),
state: z.enum(["queued", "dispatching"]),
dispatchAttemptedAt: z.string().min(1).optional(),
fingerprint: z.string().optional(),
});
const PersistedRecipientQueueFileSchema = z.object({
version: z.literal(1),
nextSeq: z.number().int().positive(),
items: z.array(PersistedQueuedMessageSchema),
});
/** The file is there and readable, but does not hold this recipient's queue. */
class CorruptQueueFileError extends Error {
constructor(
readonly filePath: string,
cause: unknown,
) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = "CorruptQueueFileError";
}
}
/** A queue file that could not be read, and where it was moved to. */
export interface CorruptQueueFile {
recipientId: string;
movedTo: string;
error: unknown;
}
/** A stray file in `agent-queues/` whose filename is not a valid recipient id. */
export interface IgnoredQueueFile {
filePath: string;
fileName: string;
}
/** Creates a per-agent atomic JSON file `AgentMessageQueueStore` under `$PASEO_HOME/agent-queues/`. */
export function createJsonAgentMessageQueueStore(
paseoHome: string,
options: {
onCorruptFile?: (file: CorruptQueueFile) => void;
onIgnoredFile?: (file: IgnoredQueueFile) => void;
} = {},
): AgentMessageQueueStore {
const queuesDir = resolve(join(paseoHome, "agent-queues"));
const cache = new Map<string, RecipientQueueState>();
const serializer = createKeyedSerializer();
function recipientFilePath(recipientId: string): string {
assertValidRecipientId(recipientId);
const filePath = resolve(queuesDir, `${recipientId}.json`);
if (dirname(filePath) !== queuesDir || basename(filePath) !== `${recipientId}.json`) {
throw new Error(`Invalid agent queue recipient id: ${recipientId}`);
}
return filePath;
}
async function loadRecipient(recipientId: string): Promise<RecipientQueueState> {
const cached = cache.get(recipientId);
if (cached) {
return cached;
}
const filePath = recipientFilePath(recipientId);
let raw: string;
try {
raw = await readFile(filePath, "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return createEmptyRecipientQueueState();
}
throw error;
}
let parsed: z.infer<typeof PersistedRecipientQueueFileSchema>;
try {
parsed = PersistedRecipientQueueFileSchema.parse(JSON.parse(raw));
for (const item of parsed.items) {
if (item.recipientId !== recipientId) {
throw new Error(
`Mismatched recipientId in ${filePath}: expected ${recipientId}, found ${item.recipientId}`,
);
}
}
} catch (error) {
throw new CorruptQueueFileError(filePath, error);
}
const items = sortQueuedMessages(parsed.items.map(cloneQueuedMessage));
const maxItemSeq = items.reduce((max, item) => Math.max(max, item.seq), 0);
const state: RecipientQueueState = {
nextSeq: Math.max(parsed.nextSeq, maxItemSeq + 1),
items,
};
cache.set(recipientId, state);
return state;
}
/** Keeps the unreadable file for inspection and frees its name for new messages. */
async function setAside(recipientId: string, error: CorruptQueueFileError): Promise<void> {
const movedTo = `${error.filePath}.corrupt.${Date.now()}`;
await rename(error.filePath, movedTo);
options.onCorruptFile?.({ recipientId, movedTo, error: error.cause });
}
async function persistRecipient(recipientId: string, state: RecipientQueueState): Promise<void> {
const filePath = recipientFilePath(recipientId);
if (state.items.length === 0) {
await rm(filePath, { force: true });
return;
}
await writeJsonFileAtomic(filePath, {
version: 1,
nextSeq: state.nextSeq,
items: state.items,
});
}
async function mutate<Result>(
recipientId: string,
transition: (current: RecipientQueueState) => TransitionOutcome<Result>,
): Promise<Result> {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const current = await loadRecipient(recipientId);
const outcome = transition(current);
if (outcome.changed) {
await persistRecipient(recipientId, outcome.nextState);
cache.set(recipientId, outcome.nextState);
}
return outcome.result;
});
}
return {
async listAll() {
await serializer.drainAll();
let entries;
try {
entries = await readdir(queuesDir, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return [];
}
throw error;
}
const recipientIds: string[] = [];
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name.startsWith(".")) {
continue;
}
const recipientId = entry.name.slice(0, -".json".length);
if (!isValidRecipientId(recipientId)) {
options.onIgnoredFile?.({
filePath: join(queuesDir, entry.name),
fileName: entry.name,
});
continue;
}
recipientIds.push(recipientId);
}
const lists = await Promise.all(
recipientIds.map((recipientId) =>
serializer.run(recipientId, async () => {
try {
const state = await loadRecipient(recipientId);
return state.items.map(cloneQueuedMessage);
} catch (error) {
// One bad file must not keep the daemon from starting.
if (!(error instanceof CorruptQueueFileError)) throw error;
await setAside(recipientId, error);
return [];
}
}),
),
);
return sortAllQueuedMessages(lists.flat());
},
async listByRecipient(recipientId) {
assertValidRecipientId(recipientId);
return serializer.run(recipientId, async () => {
const state = await loadRecipient(recipientId);
return state.items.map(cloneQueuedMessage);
});
},
enqueue: (input) => mutate(input.recipientId, (current) => enqueueIntoQueue(current, input)),
markDispatching: (recipientId, ids, attemptedAt) =>
mutate(recipientId, (current) => markDispatchingInQueue(current, ids, attemptedAt)),
revertDispatching: (recipientId, ids) =>
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
clearUrgency: (recipientId, ids) =>
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
promote: (recipientId, targetId, urgency) =>
mutate(recipientId, (current) => promoteInQueue(current, targetId, urgency)),
withdraw: (recipientId, id) => mutate(recipientId, (current) => withdrawFromQueue(current, id)),
remove: (recipientId, ids) => mutate(recipientId, (current) => removeFromQueue(current, ids)),
clearRecipient: (recipientId) => mutate(recipientId, (current) => clearQueue(current)),
};
}
@@ -21,12 +21,8 @@ export interface TransitionOutcome<Result> {
result: Result;
}
export function isValidRecipientId(recipientId: string): boolean {
return RECIPIENT_ID_PATTERN.test(recipientId);
}
export function assertValidRecipientId(recipientId: string): void {
if (!isValidRecipientId(recipientId)) {
if (!RECIPIENT_ID_PATTERN.test(recipientId)) {
throw new Error(`Invalid agent queue recipient id: ${recipientId}`);
}
}
@@ -0,0 +1,507 @@
import type { AgentAttachment, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
import type { DaemonDatabase, SchemaModule, WriteSql } from "../../../database/index.js";
import type { AgentPromptSource } from "../envelope.js";
import {
MAX_AGENT_QUEUE_DEPTH,
type AgentMessageQueueStore,
type EnqueueStoreInput,
type EnqueueStoreResult,
type PersistedQueuedMessage,
type PromoteStoreResult,
type QueuedMessageState,
type QueuedMessageUrgency,
type WithdrawStoreResult,
} from "../store.js";
import { assertValidRecipientId, cloneQueuedMessage, sortQueuedMessages } from "./queue-state.js";
/**
* Tables of the agent message queue store.
*
* `agent_message_queue_recipients` holds the monotonic `next_seq` counter per recipient so
* sequence numbers never regress across withdrawals, removals, clears, or daemon restarts.
*
* `agent_message_queue_items` holds undelivered messages. Caller-supplied strings (`id_json`,
* `text_json`, `session_mode_json`, `fingerprint_json`) and structured payloads
* (`attachments_json`, `source_json`, `provider_switch_json`) are stored as JSON strings because
* `node:sqlite` truncates raw `TEXT` values at the first NUL byte and replaces lone surrogates
* with U+FFFD during UTF-8 conversion.
*/
const SCHEMA_V1 = `
CREATE TABLE agent_message_queue_recipients (
recipient_id TEXT PRIMARY KEY,
next_seq INTEGER NOT NULL CHECK (next_seq >= 1)
);
CREATE TABLE agent_message_queue_items (
recipient_id TEXT NOT NULL REFERENCES agent_message_queue_recipients (recipient_id) ON DELETE CASCADE,
id_json TEXT NOT NULL,
seq INTEGER NOT NULL CHECK (seq >= 1),
enqueued_at TEXT NOT NULL,
text_json TEXT NOT NULL,
attachments_json TEXT NOT NULL,
source_json TEXT,
session_mode_json TEXT,
provider_switch_json TEXT,
unarchive INTEGER NOT NULL CHECK (unarchive IN (0, 1)),
clear_pending_permissions INTEGER NOT NULL CHECK (clear_pending_permissions IN (0, 1)),
urgency TEXT CHECK (urgency IS NULL OR urgency IN ('steer', 'interrupt')),
held INTEGER NOT NULL CHECK (held IN (0, 1)),
state TEXT NOT NULL CHECK (state IN ('queued', 'dispatching')),
dispatch_attempted_at TEXT,
fingerprint_json TEXT,
PRIMARY KEY (recipient_id, id_json),
UNIQUE (recipient_id, seq)
);
`;
/** The agent message queue store's schema in the daemon database. */
export const agentMessageQueueSchema: SchemaModule = {
name: "agent_message_queues",
migrations: [{ up: (sql) => sql.exec(SCHEMA_V1) }],
};
interface QueueItemRow {
recipient_id: string;
id_json: string;
seq: number;
enqueued_at: string;
text_json: string;
attachments_json: string;
source_json: string | null;
session_mode_json: string | null;
provider_switch_json: string | null;
unarchive: number;
clear_pending_permissions: number;
urgency: QueuedMessageUrgency | null;
held: number;
state: QueuedMessageState;
dispatch_attempted_at: string | null;
fingerprint_json: string | null;
}
const ITEM_COLUMNS =
"recipient_id, id_json, seq, enqueued_at, text_json, attachments_json, source_json, " +
"session_mode_json, provider_switch_json, unarchive, clear_pending_permissions, urgency, held, " +
"state, dispatch_attempted_at, fingerprint_json";
function encodeText(value: string): string {
return JSON.stringify(value);
}
function decodeText(value: string): string {
return JSON.parse(value) as string;
}
function deserializeRow(row: QueueItemRow): PersistedQueuedMessage {
const record: PersistedQueuedMessage = {
id: decodeText(row.id_json),
recipientId: row.recipient_id,
seq: row.seq,
enqueuedAt: row.enqueued_at,
text: decodeText(row.text_json),
attachments: JSON.parse(row.attachments_json) as AgentAttachment[],
source: row.source_json === null ? null : (JSON.parse(row.source_json) as AgentPromptSource),
unarchive: row.unarchive === 1,
clearPendingPermissions: row.clear_pending_permissions === 1,
urgency: row.urgency,
held: row.held === 1,
state: row.state,
};
if (row.session_mode_json !== null) {
record.sessionMode = decodeText(row.session_mode_json);
}
if (row.provider_switch_json !== null) {
record.providerSwitch = JSON.parse(row.provider_switch_json) as QueuedProviderSwitch;
}
if (row.dispatch_attempted_at !== null) {
record.dispatchAttemptedAt = row.dispatch_attempted_at;
}
if (row.fingerprint_json !== null) {
record.fingerprint = decodeText(row.fingerprint_json);
}
return record;
}
function allocateSequence(input: {
sql: WriteSql;
recipientId: string;
insertBeforeId: string | undefined;
}): { seq: number; nextSeq: number } {
const { sql, recipientId, insertBeforeId } = input;
const recipientRow = sql.get<{ next_seq: number }>(
"SELECT next_seq FROM agent_message_queue_recipients WHERE recipient_id = ?",
recipientId,
);
const currentNextSeq = recipientRow?.next_seq ?? 1;
const targetRow = insertBeforeId
? sql.get<{ seq: number }>(
"SELECT seq FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
recipientId,
encodeText(insertBeforeId),
)
: undefined;
if (!targetRow) {
return { seq: currentNextSeq, nextSeq: currentNextSeq + 1 };
}
const tailRows = sql.all<{ id_json: string; seq: number }>(
"SELECT id_json, seq FROM agent_message_queue_items " +
"WHERE recipient_id = ? AND seq >= ? ORDER BY seq ASC",
recipientId,
targetRow.seq,
);
let previousSeq = targetRow.seq;
const shifts: Array<{ idJson: string; nextSeq: number }> = [];
for (const item of tailRows) {
const shiftedSeq = Math.max(item.seq, previousSeq + 1);
if (shiftedSeq !== item.seq) {
shifts.push({ idJson: item.id_json, nextSeq: shiftedSeq });
}
previousSeq = shiftedSeq;
}
// Shift in descending seq order so UNIQUE (recipient_id, seq) holds at every step.
for (let index = shifts.length - 1; index >= 0; index -= 1) {
const shift = shifts[index]!;
sql.run(
"UPDATE agent_message_queue_items SET seq = ? WHERE recipient_id = ? AND id_json = ?",
shift.nextSeq,
recipientId,
shift.idJson,
);
}
return {
seq: targetRow.seq,
nextSeq: Math.max(currentNextSeq + 1, previousSeq + 1),
};
}
function buildInsertedRecord(input: {
message: EnqueueStoreInput;
seq: number;
}): PersistedQueuedMessage {
const { message, seq } = input;
const record: PersistedQueuedMessage = {
id: message.id,
recipientId: message.recipientId,
seq,
enqueuedAt: message.enqueuedAt,
text: message.text,
attachments: structuredClone(message.attachments),
source: message.source ? structuredClone(message.source) : null,
unarchive: message.unarchive,
clearPendingPermissions: message.clearPendingPermissions,
urgency: message.urgency,
held: message.held,
state: "queued",
};
if (message.sessionMode !== undefined) {
record.sessionMode = message.sessionMode;
}
if (message.providerSwitch !== undefined) {
record.providerSwitch = structuredClone(message.providerSwitch);
}
if (message.fingerprint !== undefined) {
record.fingerprint = message.fingerprint;
}
return record;
}
function insertQueueRow(input: { sql: WriteSql; record: PersistedQueuedMessage }): void {
const { sql, record } = input;
sql.run(
`INSERT INTO agent_message_queue_items (${ITEM_COLUMNS}) ` +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
record.recipientId,
encodeText(record.id),
record.seq,
record.enqueuedAt,
encodeText(record.text),
JSON.stringify(record.attachments),
record.source === null ? null : JSON.stringify(record.source),
record.sessionMode === undefined ? null : encodeText(record.sessionMode),
record.providerSwitch === undefined ? null : JSON.stringify(record.providerSwitch),
record.unarchive ? 1 : 0,
record.clearPendingPermissions ? 1 : 0,
record.urgency,
record.held ? 1 : 0,
record.state,
null,
record.fingerprint === undefined ? null : encodeText(record.fingerprint),
);
}
function enqueueInTransaction(input: {
sql: WriteSql;
message: EnqueueStoreInput;
}): EnqueueStoreResult {
const { sql, message } = input;
const existingRow = sql.get<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?`,
message.recipientId,
encodeText(message.id),
);
if (existingRow) {
const existing = deserializeRow(existingRow);
if (existing.fingerprint !== message.fingerprint) {
return { status: "conflict" };
}
return { status: "duplicate", record: existing };
}
const countRow = sql.get<{ count: number }>(
"SELECT COUNT(*) AS count FROM agent_message_queue_items WHERE recipient_id = ?",
message.recipientId,
);
if ((countRow?.count ?? 0) >= MAX_AGENT_QUEUE_DEPTH) {
return { status: "full", limit: MAX_AGENT_QUEUE_DEPTH };
}
const { seq, nextSeq } = allocateSequence({
sql,
recipientId: message.recipientId,
insertBeforeId: message.insertBeforeId,
});
sql.run(
"INSERT INTO agent_message_queue_recipients (recipient_id, next_seq) VALUES (?, ?) " +
"ON CONFLICT (recipient_id) DO UPDATE SET next_seq = excluded.next_seq",
message.recipientId,
nextSeq,
);
const record = buildInsertedRecord({ message, seq });
insertQueueRow({ sql, record });
return { status: "inserted", record };
}
/**
* Durable SQLite `AgentMessageQueueStore` backed by the daemon database.
* Open the database with `agentMessageQueueSchema`.
*/
export function createSqliteAgentMessageQueueStore(
database: DaemonDatabase,
): AgentMessageQueueStore {
return {
async listAll(): Promise<PersistedQueuedMessage[]> {
return database.read((sql) =>
sql
.all<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items ORDER BY recipient_id ASC, seq ASC`,
)
.map(deserializeRow),
);
},
async listByRecipient(recipientId: string): Promise<PersistedQueuedMessage[]> {
assertValidRecipientId(recipientId);
return database.read((sql) =>
sql
.all<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
recipientId,
)
.map(deserializeRow),
);
},
async enqueue(input: EnqueueStoreInput): Promise<EnqueueStoreResult> {
assertValidRecipientId(input.recipientId);
if (!input.id) {
throw new Error("Queued message id must be non-empty");
}
if (!input.enqueuedAt) {
throw new Error("Queued message enqueuedAt must be non-empty");
}
return database.write((sql) => enqueueInTransaction({ sql, message: input }));
},
async markDispatching(
recipientId: string,
ids: readonly string[],
attemptedAt: string,
): Promise<PersistedQueuedMessage[]> {
assertValidRecipientId(recipientId);
if (ids.length === 0) {
return [];
}
return database.write((sql) => {
const hasItems = sql.get<{ present: number }>(
"SELECT 1 AS present FROM agent_message_queue_items WHERE recipient_id = ? LIMIT 1",
recipientId,
);
if (!hasItems) {
return [];
}
if (!attemptedAt) {
throw new Error("attemptedAt must be non-empty");
}
const transitioned: PersistedQueuedMessage[] = [];
for (const id of new Set(ids)) {
const updated = sql.get<QueueItemRow>(
"UPDATE agent_message_queue_items " +
"SET state = 'dispatching', dispatch_attempted_at = ? " +
"WHERE recipient_id = ? AND id_json = ? AND state = 'queued' " +
`RETURNING ${ITEM_COLUMNS}`,
attemptedAt,
recipientId,
encodeText(id),
);
if (updated) {
transitioned.push(deserializeRow(updated));
}
}
return sortQueuedMessages(transitioned);
});
},
async revertDispatching(recipientId: string, ids: readonly string[]): Promise<void> {
assertValidRecipientId(recipientId);
if (ids.length === 0) {
return;
}
database.write((sql) => {
for (const id of new Set(ids)) {
sql.run(
"UPDATE agent_message_queue_items " +
"SET state = 'queued', dispatch_attempted_at = NULL " +
"WHERE recipient_id = ? AND id_json = ? AND state = 'dispatching'",
recipientId,
encodeText(id),
);
}
});
},
async markHeld(recipientId: string): Promise<PersistedQueuedMessage[]> {
assertValidRecipientId(recipientId);
return database.write((sql) => {
sql.run(
"UPDATE agent_message_queue_items " +
"SET held = 1, urgency = NULL " +
"WHERE recipient_id = ? AND (held = 0 OR urgency IS NOT NULL)",
recipientId,
);
return sql
.all<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
recipientId,
)
.map(deserializeRow);
});
},
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
assertValidRecipientId(recipientId);
if (ids.length === 0) {
return;
}
database.write((sql) => {
for (const id of new Set(ids)) {
sql.run(
"UPDATE agent_message_queue_items " +
"SET urgency = NULL " +
"WHERE recipient_id = ? AND id_json = ? AND urgency IS NOT NULL",
recipientId,
encodeText(id),
);
}
});
},
async promote(
recipientId: string,
targetId: string,
urgency: QueuedMessageUrgency,
): Promise<PromoteStoreResult> {
assertValidRecipientId(recipientId);
return database.write((sql) => {
const target = sql.get<{ seq: number; state: QueuedMessageState }>(
"SELECT seq, state FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
recipientId,
encodeText(targetId),
);
if (!target) {
return { status: "not_found" };
}
if (target.state === "dispatching") {
return { status: "already_dispatching" };
}
// Prefix 0..target advances in FIFO admission order; items already
// dispatching stay in flight untouched while queued items are released.
sql.run(
"UPDATE agent_message_queue_items " +
"SET held = 0, urgency = ? " +
"WHERE recipient_id = ? AND seq <= ? AND state = 'queued'",
urgency,
recipientId,
target.seq,
);
const items = sql
.all<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
recipientId,
)
.map(deserializeRow);
const promoted = items
.filter((item) => item.seq <= target.seq && item.state === "queued")
.map(cloneQueuedMessage);
return { status: "promoted", promoted, items };
});
},
async withdraw(recipientId: string, id: string): Promise<WithdrawStoreResult> {
assertValidRecipientId(recipientId);
return database.write((sql) => {
const candidate = sql.get<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?`,
recipientId,
encodeText(id),
);
if (!candidate) {
return { status: "not_found" };
}
if (candidate.state === "dispatching") {
return { status: "already_dispatching" };
}
sql.run(
"DELETE FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
recipientId,
encodeText(id),
);
return { status: "withdrawn", item: deserializeRow(candidate) };
});
},
async remove(recipientId: string, ids: readonly string[]): Promise<void> {
assertValidRecipientId(recipientId);
if (ids.length === 0) {
return;
}
database.write((sql) => {
for (const id of new Set(ids)) {
sql.run(
"DELETE FROM agent_message_queue_items WHERE recipient_id = ? AND id_json = ?",
recipientId,
encodeText(id),
);
}
});
},
async clearRecipient(recipientId: string): Promise<PersistedQueuedMessage[]> {
assertValidRecipientId(recipientId);
return database.write((sql) => {
const rows = sql.all<QueueItemRow>(
`SELECT ${ITEM_COLUMNS} FROM agent_message_queue_items WHERE recipient_id = ? ORDER BY seq ASC`,
recipientId,
);
if (rows.length === 0) {
return [];
}
sql.run("DELETE FROM agent_message_queue_items WHERE recipient_id = ?", recipientId);
return rows.map(deserializeRow);
});
},
};
}
@@ -1,18 +1,30 @@
import { access, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { access, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import {
DatabaseClosedError,
openDaemonDatabase,
type DaemonDatabase,
} from "../../../database/index.js";
import { timelineSchema } from "../../timeline/index.js";
import {
MAX_AGENT_QUEUE_DEPTH,
createJsonAgentMessageQueueStore,
agentMessageQueueSchema,
createMemoryAgentMessageQueueStore,
createSqliteAgentMessageQueueStore,
type AgentMessageQueueStore,
type EnqueueStoreInput,
} from "../index.js";
const openDatabases: DaemonDatabase[] = [];
const temporaryHomes: string[] = [];
afterEach(async () => {
for (const database of openDatabases.splice(0).toReversed()) {
database.close();
}
await Promise.all(
temporaryHomes.splice(0).map((home) => rm(home, { recursive: true, force: true })),
);
@@ -24,16 +36,14 @@ async function createTempHome(): Promise<string> {
return home;
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await access(filePath);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return false;
}
throw error;
}
function openQueueDatabase(home: string): DaemonDatabase {
const database = openDaemonDatabase({
path: join(home, "paseo.db"),
modules: [agentMessageQueueSchema],
logger: createTestLogger(),
});
openDatabases.push(database);
return database;
}
function makeInput(overrides: Partial<EnqueueStoreInput> = {}): EnqueueStoreInput {
@@ -51,6 +61,7 @@ function makeInput(overrides: Partial<EnqueueStoreInput> = {}): EnqueueStoreInpu
urgency: overrides.urgency === undefined ? null : overrides.urgency,
held: overrides.held ?? false,
...(overrides.fingerprint !== undefined ? { fingerprint: overrides.fingerprint } : {}),
...(overrides.insertBeforeId !== undefined ? { insertBeforeId: overrides.insertBeforeId } : {}),
};
}
@@ -65,10 +76,11 @@ const adapters: AdapterFactory[] = [
create: async () => ({ store: createMemoryAgentMessageQueueStore() }),
},
{
name: "json",
name: "sqlite",
create: async () => {
const home = await createTempHome();
return { store: createJsonAgentMessageQueueStore(home), home };
const database = openQueueDatabase(home);
return { store: createSqliteAgentMessageQueueStore(database), home };
},
},
];
@@ -182,6 +194,130 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
]);
});
test("round-trips NUL bytes, lone surrogates, CJK, and payloads over 64 KiB losslessly", async () => {
const { store } = await adapter.create();
const trickyId = "msg\0middle\ud800lone\udfff";
const secondId = "before\0\ud800id";
const trickyMode = "mode\0\ud800custom";
const trickyFingerprint = "fp\0\ud800hash";
const trickyText = `prefix\0middle\ud800lone\udfff日本語🚀${"x".repeat(70 * 1024)}`;
const largeAttachmentText = `attach\0\ud800${"y".repeat(70 * 1024)}`;
const inserted = await store.enqueue(
makeInput({
id: trickyId,
text: trickyText,
sessionMode: trickyMode,
fingerprint: trickyFingerprint,
source: { kind: "agent-message", agentId: "sender-1", title: "Worker\0\ud800日本語" },
attachments: [
{
type: "text",
fileName: "big.txt",
mimeType: "text/plain",
size: largeAttachmentText.length,
text: largeAttachmentText,
},
],
}),
);
expect(inserted.status).toBe("inserted");
// Idempotency, insertBeforeId, markDispatching, revertDispatching, promote, clearUrgency,
// withdraw, and remove must all match the exact unmangled id.
const dup = await store.enqueue(
makeInput({ id: trickyId, text: "ignored", fingerprint: trickyFingerprint }),
);
expect(dup).toMatchObject({ status: "duplicate", record: { id: trickyId } });
const before = await store.enqueue(
makeInput({ id: secondId, text: "ahead", insertBeforeId: trickyId, urgency: "steer" }),
);
expect(before).toMatchObject({ status: "inserted", record: { id: secondId, seq: 1 } });
await store.clearUrgency("agent-1", [secondId]);
const promoted = await store.promote("agent-1", trickyId, "interrupt");
expect(promoted.status).toBe("promoted");
if (promoted.status === "promoted") {
expect(promoted.promoted.map((item) => item.id)).toEqual([secondId, trickyId]);
}
const marked = await store.markDispatching("agent-1", [trickyId], "2026-11-30T07:05:00.000Z");
expect(marked.map((item) => item.id)).toEqual([trickyId]);
await store.revertDispatching("agent-1", [trickyId]);
const listed = await store.listByRecipient("agent-1");
expect(listed.map((item) => item.id)).toEqual([secondId, trickyId]);
expect(listed[1]!.text).toBe(trickyText);
expect(listed[1]!.sessionMode).toBe(trickyMode);
expect(listed[1]!.fingerprint).toBe(trickyFingerprint);
expect(listed[1]!.source).toEqual({
kind: "agent-message",
agentId: "sender-1",
title: "Worker\0\ud800日本語",
});
expect(listed[1]!.attachments).toEqual([
{
type: "text",
fileName: "big.txt",
mimeType: "text/plain",
size: largeAttachmentText.length,
text: largeAttachmentText,
},
]);
expect(await store.withdraw("agent-1", secondId)).toMatchObject({
status: "withdrawn",
item: { id: secondId },
});
await store.remove("agent-1", [trickyId]);
expect(await store.listByRecipient("agent-1")).toEqual([]);
});
test("insertBeforeId preserves ordering, shifts contiguous tails, and keeps nextSeq monotonic", async () => {
const { store } = await adapter.create();
await store.enqueue(makeInput({ id: "m1", text: "one" }));
await store.enqueue(makeInput({ id: "m2", text: "two" }));
await store.enqueue(makeInput({ id: "m3", text: "three" }));
await store.enqueue(makeInput({ id: "m4", text: "four" }));
// Create a gap at seq 3 by withdrawing m3.
expect(await store.withdraw("agent-1", "m3")).toMatchObject({ status: "withdrawn" });
// Insert before m1: m1 (1->2), m2 (2->3), gap at 3 absorbs shift so m4 stays at 4.
const beforeFirst = await store.enqueue(
makeInput({ id: "m0", text: "zero", insertBeforeId: "m1" }),
);
expect(beforeFirst).toMatchObject({ status: "inserted", record: { id: "m0", seq: 1 } });
expect((await store.listByRecipient("agent-1")).map((item) => [item.id, item.seq])).toEqual([
["m0", 1],
["m1", 2],
["m2", 3],
["m4", 4],
]);
// Insert before m4: shifts m4 (4->5) and advances nextSeq past both old nextSeq+1 and maxSeq+1.
const beforeTail = await store.enqueue(
makeInput({ id: "m3b", text: "three-b", insertBeforeId: "m4" }),
);
expect(beforeTail).toMatchObject({ status: "inserted", record: { id: "m3b", seq: 4 } });
expect((await store.listByRecipient("agent-1")).map((item) => [item.id, item.seq])).toEqual([
["m0", 1],
["m1", 2],
["m2", 3],
["m3b", 4],
["m4", 5],
]);
// Missing insertBeforeId falls back to appending at nextSeq.
const fallback = await store.enqueue(
makeInput({ id: "m5", text: "five", insertBeforeId: "does-not-exist" }),
);
expect(fallback).toMatchObject({ status: "inserted", record: { id: "m5", seq: 7 } });
});
test("clones inputs and returned records so external mutations cannot corrupt store state", async () => {
const { store } = await adapter.create();
const attachments: EnqueueStoreInput["attachments"] = [
@@ -375,6 +511,31 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
expect("dispatchAttemptedAt" in items[2]!).toBe(false);
});
test("clearUrgency clears urgency for matching ids without changing held or state", async () => {
const { store } = await adapter.create();
await store.enqueue(makeInput({ id: "m1", urgency: "interrupt", held: false }));
await store.enqueue(makeInput({ id: "m2", urgency: "steer", held: true }));
await store.enqueue(makeInput({ id: "m3", urgency: null, held: false }));
await store.markDispatching("agent-1", ["m1"], "2026-11-30T07:05:00.000Z");
await store.clearUrgency("agent-1", ["m1", "m3", "missing"]);
await store.clearUrgency("agent-1", []);
expect(
(await store.listByRecipient("agent-1")).map((item) => ({
id: item.id,
urgency: item.urgency,
held: item.held,
state: item.state,
})),
).toEqual([
{ id: "m1", urgency: null, held: false, state: "dispatching" },
{ id: "m2", urgency: "steer", held: true, state: "queued" },
{ id: "m3", urgency: null, held: false, state: "queued" },
]);
});
test("markHeld marks all items held and clears urgency while preserving state", async () => {
const { store } = await adapter.create();
@@ -523,7 +684,7 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
}
});
test("rejects path traversal and invalid recipient ids on every recipient-scoped operation", async () => {
test("rejects invalid recipient ids on every recipient-scoped operation", async () => {
const { store } = await adapter.create();
const invalidIds = ["", ".", "..", "../escape", "a/b", "a\\b", "a\0b", "agent.json"];
@@ -539,6 +700,9 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
/Invalid agent queue recipient/,
);
await expect(store.markHeld(badId)).rejects.toThrow(/Invalid agent queue recipient/);
await expect(store.clearUrgency(badId, ["msg-1"])).rejects.toThrow(
/Invalid agent queue recipient/,
);
await expect(store.promote(badId, "msg-1", "steer")).rejects.toThrow(
/Invalid agent queue recipient/,
);
@@ -549,29 +713,51 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
});
});
describe("createJsonAgentMessageQueueStore persistence & file hygiene", () => {
test("persists items, states, and monotonic nextSeq across store restarts", async () => {
describe("createSqliteAgentMessageQueueStore persistence & schema", () => {
test("persists items, states, payloads, and monotonic nextSeq across database reopen", async () => {
const home = await createTempHome();
const store1 = createJsonAgentMessageQueueStore(home);
const db1 = openQueueDatabase(home);
const store1 = createSqliteAgentMessageQueueStore(db1);
const largeText = `first\0\ud800${"z".repeat(70 * 1024)}`;
await store1.enqueue(
makeInput({
id: "m1",
text: "first",
text: largeText,
source: { kind: "change-request-update", url: "https://github.com/getpaseo/paseo/pull/1" },
sessionMode: "plan",
fingerprint: "fp-1",
}),
);
await store1.enqueue(makeInput({ id: "m2", text: "second", held: true }));
await store1.enqueue(
makeInput({
id: "m2",
text: "second",
held: true,
providerSwitch: {
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: null,
},
}),
);
await store1.enqueue(makeInput({ id: "m3", text: "third" }));
await store1.markDispatching("agent-1", ["m1"], "2026-11-30T07:10:00.000Z");
await store1.withdraw("agent-1", "m3");
db1.close();
const restarted = createJsonAgentMessageQueueStore(home);
// Never creates the legacy agent-queues directory.
await expect(access(join(home, "agent-queues"))).rejects.toMatchObject({ code: "ENOENT" });
const db2 = openQueueDatabase(home);
const restarted = createSqliteAgentMessageQueueStore(db2);
expect(await restarted.listAll()).toEqual([
expect.objectContaining({
id: "m1",
seq: 1,
text: largeText,
sessionMode: "plan",
state: "dispatching",
dispatchAttemptedAt: "2026-11-30T07:10:00.000Z",
fingerprint: "fp-1",
@@ -581,169 +767,69 @@ describe("createJsonAgentMessageQueueStore persistence & file hygiene", () => {
seq: 2,
held: true,
state: "queued",
providerSwitch: {
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: null,
},
}),
]);
const afterRestartEnqueue = await restarted.enqueue(makeInput({ id: "m4", text: "fourth" }));
expect(afterRestartEnqueue).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
// Monotonic nextSeq also survives clearRecipient + reopen.
await restarted.clearRecipient("agent-1");
db2.close();
const db3 = openQueueDatabase(home);
const afterClear = createSqliteAgentMessageQueueStore(db3);
const fifth = await afterClear.enqueue(makeInput({ id: "m5", text: "fifth" }));
expect(fifth).toMatchObject({ status: "inserted", record: { id: "m5", seq: 5 } });
});
test("deletes empty recipient queue files and avoids creating files for empty operations", async () => {
test("registers agent_message_queues schema alongside timelineSchema and leaves empty recipients untouched", async () => {
const home = await createTempHome();
const store = createJsonAgentMessageQueueStore(home);
const queueFile = join(home, "agent-queues", "agent-1.json");
const database = openDaemonDatabase({
path: join(home, "paseo.db"),
modules: [timelineSchema, agentMessageQueueSchema],
logger: createTestLogger(),
});
openDatabases.push(database);
const version = database.read((sql) =>
sql.get<{ version: number; min_reader_version: number }>(
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
"agent_message_queues",
),
);
expect(version).toEqual({ version: 1, min_reader_version: 1 });
const store = createSqliteAgentMessageQueueStore(database);
expect(await store.listByRecipient("agent-1")).toEqual([]);
expect(await store.markHeld("agent-1")).toEqual([]);
expect(await store.withdraw("agent-1", "missing")).toEqual({ status: "not_found" });
expect(await store.promote("agent-1", "missing", "steer")).toEqual({ status: "not_found" });
await store.clearUrgency("agent-1", ["missing"]);
await store.remove("agent-1", ["missing"]);
expect(await store.clearRecipient("agent-1")).toEqual([]);
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m1" }));
expect(await fileExists(queueFile)).toBe(true);
await store.withdraw("agent-1", "m1");
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m2" }));
expect(await fileExists(queueFile)).toBe(true);
await store.remove("agent-1", ["m2"]);
expect(await fileExists(queueFile)).toBe(false);
await store.enqueue(makeInput({ id: "m3" }));
expect(await fileExists(queueFile)).toBe(true);
await store.clearRecipient("agent-1");
expect(await fileExists(queueFile)).toBe(false);
// Re-enqueuing in the same store instance still preserves monotonic seq after file deletion.
const next = await store.enqueue(makeInput({ id: "m4" }));
expect(next).toMatchObject({ status: "inserted", record: { id: "m4", seq: 4 } });
});
test("ignores hidden temp files in agent-queues directory during listAll", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(join(queuesDir, ".agent-1.json.123.tmp"), "{not json", "utf8");
const store = createJsonAgentMessageQueueStore(home);
await store.enqueue(makeInput({ id: "m1" }));
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1"]);
});
test("fails visibly on invalid persisted JSON, invalid schema, or recipientId mismatch", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(join(queuesDir, "bad-json.json"), "{broken", "utf8");
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("bad-json"),
).rejects.toThrow();
await writeFile(
join(queuesDir, "bad-schema.json"),
JSON.stringify({ version: 1, nextSeq: 1, items: [{ id: 42 }] }),
"utf8",
const recipientCount = database.read((sql) =>
sql.get<{ count: number }>("SELECT COUNT(*) AS count FROM agent_message_queue_recipients"),
);
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("bad-schema"),
).rejects.toThrow();
expect(recipientCount?.count).toBe(0);
});
await writeFile(
join(queuesDir, "wrong-recipient.json"),
JSON.stringify({
version: 1,
nextSeq: 2,
items: [
{
id: "m1",
recipientId: "other-agent",
seq: 1,
enqueuedAt: "2026-11-30T07:00:00.000Z",
text: "hi",
attachments: [],
source: null,
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "queued",
},
],
}),
"utf8",
test("rejects operations with DatabaseClosedError after the database closes", async () => {
const home = await createTempHome();
const database = openQueueDatabase(home);
const store = createSqliteAgentMessageQueueStore(database);
database.close();
await expect(store.listAll()).rejects.toBeInstanceOf(DatabaseClosedError);
await expect(store.enqueue(makeInput({ id: "m1" }))).rejects.toBeInstanceOf(
DatabaseClosedError,
);
await expect(
createJsonAgentMessageQueueStore(home).listByRecipient("wrong-recipient"),
).rejects.toThrow(/Mismatched recipientId/);
});
test("listAll sets one bad queue file aside and still loads every valid queue", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
const writer = createJsonAgentMessageQueueStore(home);
await writer.enqueue(makeInput({ id: "m1", recipientId: "agent-1" }));
await writer.enqueue(makeInput({ id: "m2", recipientId: "agent-2" }));
await writeFile(join(queuesDir, "bad-agent.json"), "{broken", "utf8");
const corrupted: Array<{ recipientId: string; movedTo: string }> = [];
const store = createJsonAgentMessageQueueStore(home, {
onCorruptFile: ({ recipientId, movedTo }) => corrupted.push({ recipientId, movedTo }),
});
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1", "m2"]);
const left = (await readdir(queuesDir)).filter((name) => name.startsWith("bad-agent"));
expect(left).toHaveLength(1);
const aside = left[0];
expect(aside).toMatch(/^bad-agent\.json\.corrupt\.\d+$/);
expect(await readFile(join(queuesDir, aside!), "utf8")).toBe("{broken");
expect(corrupted).toEqual([{ recipientId: "bad-agent", movedTo: join(queuesDir, aside!) }]);
// The recipient starts over with an empty queue.
await store.enqueue(makeInput({ id: "m3", recipientId: "bad-agent" }));
expect((await store.listByRecipient("bad-agent")).map((item) => item.id)).toEqual(["m3"]);
});
test("write failure rejects enqueue and does not pollute in-memory cache", async () => {
const home = await createTempHome();
const store = createJsonAgentMessageQueueStore(home);
expect(await store.listByRecipient("agent-1")).toEqual([]);
// Obstruct the target file path with a directory so rename fails.
await mkdir(join(home, "agent-queues", "agent-1.json"), { recursive: true });
await expect(store.enqueue(makeInput({ id: "m1" }))).rejects.toThrow();
await rm(join(home, "agent-queues", "agent-1.json"), { recursive: true, force: true });
expect(await store.listByRecipient("agent-1")).toEqual([]);
});
test("listAll skips stray .json files with invalid recipient id stems instead of failing startup", async () => {
const home = await createTempHome();
const queuesDir = join(home, "agent-queues");
const writer = createJsonAgentMessageQueueStore(home);
await writer.enqueue(makeInput({ id: "m1", recipientId: "agent-1" }));
await writeFile(
join(queuesDir, "agent (1).json"),
'{"version":1,"nextSeq":1,"items":[]}',
"utf8",
);
await writeFile(join(queuesDir, "backup.2026.json"), "not json", "utf8");
const ignored: Array<{ filePath: string; fileName: string }> = [];
const store = createJsonAgentMessageQueueStore(home, {
onIgnoredFile: (file) => ignored.push(file),
});
expect((await store.listAll()).map((item) => item.id)).toEqual(["m1"]);
expect(ignored.map((file) => file.fileName).sort()).toEqual([
"agent (1).json",
"backup.2026.json",
]);
// Stray files are left untouched on disk.
expect(await readFile(join(queuesDir, "agent (1).json"), "utf8")).toContain('"version":1');
expect(await readFile(join(queuesDir, "backup.2026.json"), "utf8")).toBe("not json");
});
});
@@ -108,6 +108,46 @@ describe("Claude session request journal replay", () => {
},
);
test("restores the goal acknowledgement before the reply that meets the goal", async () => {
const condition = "Your latest reply is exactly the word DONE";
const items = await replay([
{
type: "user",
message: { role: "user", content: `/goal ${condition}` },
},
{
type: "system",
subtype: "local_command",
uuid: "goal-confirmation",
commandRun: { command: "goal", args: condition },
content: `<local-command-stdout>Goal set: ${condition}</local-command-stdout>`,
},
{
type: "assistant",
uuid: "goal-reply",
message: {
role: "assistant",
content: [{ type: "text", text: "DONE" }],
},
},
{
type: "system",
subtype: "local_command",
commandRun: { command: "model" },
content: "<local-command-stdout>Set model to opus</local-command-stdout>",
},
]);
expect(items).toEqual([
{ type: "user_message", text: `/goal ${condition}` },
{
type: "assistant_message",
messageId: "goal-confirmation",
text: `Goal set: ${condition}`,
},
{ type: "assistant_message", messageId: "goal-reply", text: "DONE" },
]);
});
test("preserves system compaction and background task notifications", async () => {
const items = await replay([
{
@@ -7380,6 +7380,30 @@ async function mapAssistantHistoryBlocksWithMessageId(
return items;
}
function readGoalAcknowledgement(entry: ClaudeHistoryEntry): AgentTimelineItem | null {
if (
entry.type !== "system" ||
entry.subtype !== "local_command" ||
typeof entry.content !== "string" ||
!isObjectRecord(entry.commandRun) ||
entry.commandRun.command !== "goal"
) {
return null;
}
const match = /^<local-command-stdout>(Goal set: [\s\S]+)<\/local-command-stdout>$/.exec(
entry.content,
);
if (!match) return null;
const messageId = readTrimmedString(entry.uuid);
return {
type: "assistant_message",
text: match[1].trim(),
...(messageId ? { messageId } : {}),
};
}
function convertClaudeHistoryEntryPreamble(
entry: ClaudeHistoryEntry,
): { shortCircuit: AgentTimelineItem[] } | { proceed: { content: unknown } } {
@@ -7412,6 +7436,10 @@ function convertClaudeHistoryEntryPreamble(
if (steeredPrompt) {
return { shortCircuit: [steeredPrompt] };
}
const goalAcknowledgement = readGoalAcknowledgement(entry);
if (goalAcknowledgement) {
return { shortCircuit: [goalAcknowledgement] };
}
// Only user and assistant records are conversation turns. Claude Code 2.1.x also journals each
// API request as `api-request-blob` records whose message replays the system context.
if (entry.type !== "user" && entry.type !== "assistant") {
@@ -90,7 +90,7 @@ export class JsonlRpcProcess {
private readonly exitSubscribers = new Set<(exit: JsonlRpcExit) => void>();
private stderrBuffer = "";
private nextRequestId = 1;
private readonly closeController = new AbortController();
private disposed = false;
private streamFailure: ProviderStreamLimitError | null = null;
private exited = false;
private stopTimedOut = false;
@@ -147,11 +147,6 @@ export class JsonlRpcProcess {
});
}
/** Aborts with the error that made the transport unusable, even before child exit. */
get closed(): AbortSignal {
return this.closeController.signal;
}
onMessage(callback: (message: Record<string, unknown>) => void): () => void {
this.messageSubscribers.add(callback);
return () => {
@@ -170,7 +165,7 @@ export class JsonlRpcProcess {
command: { type: string; [key: string]: unknown },
timeoutMs?: number | null,
): { id: string; promise: Promise<unknown> } {
if (this.closed.aborted) {
if (this.disposed) {
return {
id: "",
promise: Promise.reject(new Error(`${this.diagnosticName} process is closed`)),
@@ -263,7 +258,7 @@ export class JsonlRpcProcess {
}
send(message: Record<string, unknown>): void {
if (this.closed.aborted) {
if (this.disposed) {
return;
}
if (this.child.stdin.destroyed || !this.child.stdin.writable) {
@@ -279,7 +274,7 @@ export class JsonlRpcProcess {
async close(error = new Error(`${this.diagnosticName} process is closed`)): Promise<void> {
if (this.closing) return this.closing;
if (this.closed.aborted) return;
if (this.disposed) return;
this.failAll(error);
this.closing = this.terminate();
await this.closing;
@@ -355,7 +350,7 @@ export class JsonlRpcProcess {
}
private handleStdinError(error: unknown): void {
if (this.closed.aborted) {
if (this.disposed) {
return;
}
const err = error instanceof Error ? error : new Error(String(error));
@@ -364,10 +359,10 @@ export class JsonlRpcProcess {
}
private failAll(error: Error): void {
if (this.closed.aborted) {
if (this.disposed) {
return;
}
this.closeController.abort(error);
this.disposed = true;
for (const pending of this.pending.values()) {
if (pending.timer) {
clearTimeout(pending.timer);
@@ -1,15 +1,11 @@
import { getEventListeners } from "node:events";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import pino from "pino";
import { afterEach, describe, expect, it, vi } from "vitest";
import { JsonlRpcProcess } from "../jsonl-rpc-process.js";
import type { JsonlRpcExit } from "../jsonl-rpc-process.js";
import { establishOmpProtocol, type OmpProtocolTransport } from "./protocol-session.js";
function transportHarness() {
let receiveMessage: ((message: Record<string, unknown>) => void) | null = null;
const closeController = new AbortController();
let receiveExit: ((exit: JsonlRpcExit) => void) | null = null;
const requests: Array<{ command: Record<string, unknown>; timeoutMs: number | null }> = [];
let response: unknown = { protocolVersion: 2 };
const transport: OmpProtocolTransport = {
@@ -19,7 +15,12 @@ function transportHarness() {
receiveMessage = null;
};
},
closed: closeController.signal,
onExit(receiver) {
receiveExit = receiver;
return () => {
receiveExit = null;
};
},
async request(command, timeoutMs) {
requests.push({ command, timeoutMs });
return response;
@@ -32,7 +33,7 @@ function transportHarness() {
setResponse: (value: unknown) => {
response = value;
},
closeSubscribed: () => getEventListeners(transport.closed, "abort").length > 0,
exitSubscribed: () => receiveExit !== null,
};
}
@@ -48,39 +49,6 @@ afterEach(() => {
});
describe("establishOmpProtocol", () => {
it("reports an unavailable working directory during startup", async () => {
const root = await mkdtemp(join(tmpdir(), "omp-startup-"));
const logger = pino({ level: "silent" });
const transport = new JsonlRpcProcess({
launch: { command: process.execPath, args: ["--version"], cwd: join(root, "missing") },
logger,
});
try {
await expect(
establishOmpProtocol(transport, logger, { readyTimeoutMs: 300 }),
).rejects.toMatchObject({ code: "ENOENT" });
} finally {
await transport.close();
await rm(root, { recursive: true, force: true });
}
});
it("reports why startup was canceled when the transport closes", async () => {
const logger = pino({ level: "silent" });
const transport = new JsonlRpcProcess({
launch: {
command: process.execPath,
args: ["-e", "process.stdin.resume()"],
cwd: process.cwd(),
},
logger,
});
const reason = new Error("Provider refresh canceled");
const result = expect(establishOmpProtocol(transport, logger)).rejects.toBe(reason);
await transport.close(reason);
await result;
});
it("owns readiness and v2 negotiation", async () => {
const harness = transportHarness();
const negotiation = establishOmpProtocol(harness.transport, pino({ level: "silent" }));
@@ -92,7 +60,7 @@ describe("establishOmpProtocol", () => {
timeoutMs: 30_000,
},
]);
expect(harness.closeSubscribed()).toBe(false);
expect(harness.exitSubscribed()).toBe(false);
});
it("uses the configured RPC timeout while waiting for a cold OMP", async () => {
@@ -124,12 +92,12 @@ describe("establishOmpProtocol", () => {
);
await vi.advanceTimersByTimeAsync(19_999);
expect(harness.closeSubscribed()).toBe(true);
expect(harness.exitSubscribed()).toBe(true);
expect(await Promise.race([outcome, Promise.resolve("pending")])).toBe("pending");
await vi.advanceTimersByTimeAsync(1);
await expect(outcome).resolves.toBe("Timed out waiting for OMP to become ready");
expect(harness.closeSubscribed()).toBe(false);
expect(harness.exitSubscribed()).toBe(false);
});
it("keeps protocol v1 when the ready frame has no matching capability", async () => {
@@ -1,12 +1,15 @@
import { addAbortListener } from "node:events";
import type { Logger } from "pino";
import { JSONL_RPC_DEFAULT_TIMEOUT_MS, supportsJsonlRpcProtocolV2 } from "../jsonl-rpc-process.js";
import {
JSONL_RPC_DEFAULT_TIMEOUT_MS,
supportsJsonlRpcProtocolV2,
type JsonlRpcExit,
} from "../jsonl-rpc-process.js";
const OMP_READY_TIMEOUT_MS = 20_000;
export interface OmpProtocolTransport {
onMessage(callback: (message: Record<string, unknown>) => void): () => void;
readonly closed: AbortSignal;
onExit(callback: (exit: JsonlRpcExit) => void): () => void;
request(command: Record<string, unknown>, timeoutMs: number | null): Promise<unknown>;
}
@@ -34,29 +37,28 @@ export async function establishOmpProtocol(
function waitForReady(
transport: OmpProtocolTransport,
readyTimeoutMs: number,
requestTimeoutMs: number,
): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
transport.closed.throwIfAborted();
let settled = false;
let unsubscribeMessage = (): void => {};
let unsubscribeExit = (): void => {};
const timer = setTimeout(
() => finish(() => reject(new Error("Timed out waiting for OMP to become ready"))),
readyTimeoutMs,
() => finish(new Error("Timed out waiting for OMP to become ready")),
requestTimeoutMs,
);
const finish = (settle: () => void): void => {
const finish = (result: Record<string, unknown> | Error): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
unsubscribeMessage();
closeListener[Symbol.dispose]();
settle();
unsubscribeExit();
if (result instanceof Error) reject(result);
else resolve(result);
};
const closeListener = addAbortListener(transport.closed, () =>
finish(() => reject(transport.closed.reason)),
);
unsubscribeMessage = transport.onMessage((message) => {
if (message.type === "ready") finish(() => resolve(message));
if (message.type === "ready") finish(message);
});
unsubscribeExit = transport.onExit(({ error }) => finish(error));
});
}
@@ -1,3 +1,5 @@
import { lastAssistantMessageText } from "../../../assistant-message.js";
import { projectTimelineRows } from "../../../timeline-projection.js";
import { collectTimelineSnapshot } from "../test-utils/v2-timeline.js";
import type { SessionMessageAssistant } from "@opencode/client";
import { execFileSync } from "node:child_process";
@@ -136,3 +138,37 @@ test.each(["delta", "snapshot"] as const)(
expect(retainedBytesAfterStreaming(mode, chunks)).toBeLessThan(textBytes * 32);
},
);
test.each(["snapshot", "stream"] as const)(
"empty reasoning between two text parts keeps their paragraphs distinct in %s",
async (mode) => {
const timeline = new V2Timeline();
const message = assistant([
{ type: "text", text: "I checked content search." },
{ type: "reasoning", text: "" },
{ type: "text", text: "The newly named tool works." },
]);
const liveEvents = [];
if (mode === "stream") {
const commentary = { assistantMessageID: message.id, type: "text" as const, ordinal: 0 };
timeline.startPart(commentary);
liveEvents.push(timeline.delta({ ...commentary, delta: "I checked content search." }));
const final = { ...commentary, ordinal: 1 };
timeline.startPart(final);
liveEvents.push(timeline.delta({ ...final, delta: "The newly" }));
}
const replayEvents = await collectTimelineSnapshot(timeline, [message]);
const rows = [...liveEvents, ...replayEvents].flatMap((event, index) =>
event?.type === "timeline"
? [{ item: event.item, timestamp: event.timestamp, seq: index + 1, turnId: "turn" }]
: [],
);
const replies = projectTimelineRows({ rows, mode: "projected" }).flatMap(({ item }) =>
item.type === "assistant_message" ? [item.text] : [],
);
const expected = "I checked content search.\n\nThe newly named tool works.";
expect.soft(replies).toEqual([expected]);
expect.soft(lastAssistantMessageText(rows)).toBe(expected);
},
);
@@ -49,11 +49,13 @@ export class V2Timeline {
if (!text.startsWith(emitted))
throw new Error("OpenCode changed previously emitted message content");
this.content.set(key, text);
const suffix = detachedSuffix(text, emitted.length);
const item: AgentTimelineItem =
event.type === "text"
? { type: "assistant_message", text: suffix, messageId: event.assistantMessageID }
: { type: "reasoning", text: suffix };
const item = this.textItem({
messageID: event.assistantMessageID,
type: event.type,
ordinal: event.ordinal,
text,
previous: emitted,
});
return { type: "timeline", provider: "opencode", item, timestamp: new Date().toISOString() };
}
@@ -199,10 +201,35 @@ export class V2Timeline {
if (!part.text.startsWith(previous))
throw new Error("OpenCode changed previously emitted message content");
this.content.set(key, part.text);
const suffix = detachedSuffix(part.text, previous.length);
if (part.type === "text")
push({ type: "assistant_message", text: suffix, messageId: messageID });
else push({ type: "reasoning", text: suffix });
push(this.textItem({ messageID, type: part.type, ordinal, text: part.text, previous }));
}
private textItem({
messageID,
type,
ordinal,
text,
previous,
}: {
messageID: string;
type: "text" | "reasoning";
ordinal: number;
text: string;
previous: string;
}): AgentTimelineItem {
const suffix = detachedSuffix(text, previous.length);
if (type === "reasoning") return { type: "reasoning", text: suffix };
// Projection joins chunks with the same message ID. Separate OpenCode text parts
// once, at the first emitted chunk, so live output and history replay agree.
if (previous.length === 0) {
for (let earlier = ordinal - 1; earlier >= 0; earlier--) {
if (this.content.has(textPartKey(messageID, "text", earlier))) {
return { type: "assistant_message", text: `\n\n${suffix}`, messageId: messageID };
}
}
}
return { type: "assistant_message", text: suffix, messageId: messageID };
}
private async toolPart(
+13 -2
View File
@@ -9,7 +9,12 @@ import {
createFinishObservation,
createJsonFinishSubscriptionStore,
} from "./agent/finish-subscriptions/index.js";
import type { AgentMessageDelivery } from "./agent/agent-messages/index.js";
import {
agentMessageQueueSchema,
createSqliteAgentMessageQueueStore,
type AgentMessageDelivery,
type AgentMessageQueueStore,
} from "./agent/agent-messages/index.js";
import type { AgentQueueBackend } from "./session/agent-queue-source.js";
import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
import type { PluginRegistries } from "@getpaseo/protocol/plugin-registry";
@@ -618,10 +623,11 @@ export async function createPaseoDaemon(
await mkdir(config.paseoHome, { recursive: true });
const database = openDaemonDatabase({
path: path.join(config.paseoHome, "paseo.db"),
modules: [timelineSchema],
modules: [timelineSchema, agentMessageQueueSchema],
logger: rootLogger.child({ module: "database" }),
});
const timeline = createStoredAgentTimeline(database);
const agentMessageQueueStore = createSqliteAgentMessageQueueStore(database);
try {
return await assemblePaseoDaemon({
config,
@@ -630,6 +636,7 @@ export async function createPaseoDaemon(
hostMachineKindReady,
database,
timeline,
agentMessageQueueStore,
});
} catch (error) {
await timeline.close();
@@ -646,6 +653,7 @@ interface PaseoDaemonAssembly {
hostMachineKindReady: Promise<HostMachineKind | null>;
database: DaemonDatabase;
timeline: AgentTimeline;
agentMessageQueueStore: AgentMessageQueueStore;
}
async function assemblePaseoDaemon({
@@ -655,6 +663,7 @@ async function assemblePaseoDaemon({
hostMachineKindReady,
database,
timeline,
agentMessageQueueStore,
}: PaseoDaemonAssembly): Promise<PaseoDaemon> {
const bootstrapStart = performance.now();
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
@@ -2056,6 +2065,7 @@ async function assemblePaseoDaemon({
workspaceArchiveOperations,
config.pushNotifications,
tunnelManager,
agentMessageQueueStore,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -2141,6 +2151,7 @@ async function assemblePaseoDaemon({
httpServer.closeAllConnections();
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
}
await wsServer?.agentMessages.close().catch(() => undefined);
await timeline.close();
database.close();
throw error;
@@ -1,10 +1,15 @@
import { AgentStorage } from "../agent/agent-storage.js";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
agentMessageQueueSchema,
createSqliteAgentMessageQueueStore,
} from "../agent/agent-messages/index.js";
import { openDaemonDatabase } from "../database/index.js";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
import type { PersistenceHandle } from "@getpaseo/protocol/messages";
@@ -70,7 +75,7 @@ describe("daemon restart resume", () => {
// These run in separate OS processes so SIGKILL cannot invoke daemon shutdown hooks.
import { fork, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { readFile, mkdtemp, rm, mkdir, writeFile } from "node:fs/promises";
import { readFile, mkdtemp, rm } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -372,12 +377,17 @@ async function readSavedQueue(
paseoHome: string,
agentId: string,
): Promise<Array<{ text: string; held: boolean; attachments: unknown[] }>> {
const dbPath = path.join(paseoHome, "paseo.db");
if (!existsSync(dbPath)) return [];
const database = openDaemonDatabase({
path: dbPath,
modules: [agentMessageQueueSchema],
logger: createTestLogger(),
});
try {
const file = path.join(paseoHome, "agent-queues", `${agentId}.json`);
return JSON.parse(await readFile(file, "utf8")).items;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
return await createSqliteAgentMessageQueueStore(database).listByRecipient(agentId);
} finally {
database.close();
}
}
async function readAllPrompts(root: string): Promise<string[]> {
@@ -600,31 +610,30 @@ test("a message the saved timeline holds is not sent again after a crash mid-dis
await client.close();
await stopFixture(first.child, false);
// What a daemon leaves when it dies after the provider took a queued message.
const queuesDir = path.join(first.paseoHome, "agent-queues");
await mkdir(queuesDir, { recursive: true });
await writeFile(
path.join(queuesDir, `${agent.id}.json`),
JSON.stringify({
version: 1,
nextSeq: 2,
items: [
{
id: "crashed-delivery",
recipientId: agent.id,
seq: 1,
enqueuedAt: new Date().toISOString(),
text,
attachments: [],
source: null,
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
state: "dispatching",
},
],
}),
);
expect(existsSync(path.join(first.paseoHome, "agent-queues"))).toBe(false);
const database = openDaemonDatabase({
path: path.join(first.paseoHome, "paseo.db"),
modules: [agentMessageQueueSchema],
logger: createTestLogger(),
});
try {
const store = createSqliteAgentMessageQueueStore(database);
await store.enqueue({
id: "crashed-delivery",
recipientId: agent.id,
enqueuedAt: new Date().toISOString(),
text,
attachments: [],
source: null,
unarchive: true,
clearPendingPermissions: false,
urgency: null,
held: false,
});
await store.markDispatching(agent.id, ["crashed-delivery"], new Date().toISOString());
} finally {
database.close();
}
const second = await start();
const restarted = await connect(second.port);
+10 -13
View File
@@ -5,8 +5,9 @@ import {
import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js";
import {
createAgentMessageDelivery,
createJsonAgentMessageQueueStore,
createMemoryAgentMessageQueueStore,
type AgentMessageDelivery,
type AgentMessageQueueStore,
} from "./agent/agent-messages/index.js";
import { createAgentQueueBackend, type AgentQueueBackend } from "./session/agent-queue-source.js";
import {
@@ -95,6 +96,12 @@ function resolveWorkspaceArchiveOperations(
): WorkspaceArchiveOperations {
return operations ?? new WorkspaceArchiveOperations();
}
function resolveAgentMessageQueueStore(
store: AgentMessageQueueStore | undefined,
): AgentMessageQueueStore {
return store ?? createMemoryAgentMessageQueueStore();
}
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
@@ -777,6 +784,7 @@ export class VoiceAssistantWebSocketServer {
workspaceArchiveOperations?: WorkspaceArchiveOperations,
pushNotifications?: PushNotifications,
tunnelManager?: TunnelManager | null,
agentMessageQueueStore?: AgentMessageQueueStore,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
@@ -799,18 +807,7 @@ export class VoiceAssistantWebSocketServer {
this.agentManager = agentManager;
this.agentStorage = agentStorage;
this.agentMessages = createAgentMessageDelivery({
store: createJsonAgentMessageQueueStore(paseoHome, {
onCorruptFile: ({ recipientId, movedTo, error }) =>
this.logger.warn(
{ err: error, agentId: recipientId, movedTo },
"Set aside a corrupt agent message queue file",
),
onIgnoredFile: ({ filePath, fileName }) =>
this.logger.warn(
{ filePath, fileName },
"Ignored stray file in agent message queues directory",
),
}),
store: resolveAgentMessageQueueStore(agentMessageQueueStore),
paseoHome,
recipientStatus: async (agentId) => {
const record = await agentStorage.get(agentId);