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
Mohamed Boudra 5b2aa7e0ca fix(server): preserve session mode boundaries on direct sends and urgent queue releases (#11722)
* fix(server): preserve session mode boundaries on direct sends and urgent queue releases

Direct sends and urgent queue releases previously collected all queued messages up to the first provider switch and dispatched them as a single prompt under one session mode. A queued read-only or plan-mode message followed by a direct broader-permission prompt (or vice versa) was silently coalesced and executed under the wrong permission mode, and queued non-agent slash commands were wrapped into combined prompts.

Unify ordinary draining, urgent releases, and direct-send coalescing behind one shared dispatchGroups boundary rule covering provider switches, conflicting explicit session modes, and non-agent slash commands. When queued messages ahead of a direct send cannot share one dispatch, enqueue the direct prompt with urgency so the preceding boundary group runs first in FIFO order under its own mode and the direct prompt follows in a separate turn under its own mode.

* fix(server,app): persist urgency downgrades, preserve queue order, and defer receipts on queued direct sends

Address review findings on queued direct sends and split urgent releases:
- Defer MessageReceipts completion when sendDirect queues behind a boundary so receipts only complete via onDelivered.
- Persist clearUrgency on deferred groups before dispatching the first group so daemon restarts do not revive consumed interrupts.
- Support insertBeforeId in AgentMessageQueueStore and admit() so queued direct sends keep their slot ahead of queued provider switches and concurrent arrivals.
- Pass raw text and attachments from Session into DirectPrompt so delivery stays synchronous without re-parsing provider prompts or writing image files.
- Clear the optimistic composer timeline bubble in dispatchComposerAgentMessage when a direct send or switch returns deliveryStatus: queued.
- Remove new barrel re-exports from agent-messages/index.ts and await receipt.dispatched directly in delivery.test.ts.

* fix(server,app): dedupe retried queued direct sends, settle queued switch draft, and avoid eager image writes

Address follow-up review findings:
- Dedupe retried direct sends in sendDirect when direct.messageId is already queued in memory (with fingerprint conflict check) so retries return the existing queued receipt instead of duplicating or interrupting.
- Settle the staged provider switch draft via onProviderSwitchQueued in dispatchComposerAgentMessage when a direct switch returns deliveryStatus: queued.
- Only persist inline images via Session.queuedAttachments on direct sends when the recipient queue is non-empty, avoiding unused uploads on empty queues.
- Remove conditional assertion from delivery.test.ts using expectQueuedReceipt helper.

* fix(server): resolve inline direct-send attachments lazily inside queue save

Remove the racy Session.list(agentId) pre-check by passing a lazy resolveAttachments callback into DirectPrompt. Delivery admits the item into its exact in-memory slot synchronously and runs resolveAttachments inside item.saved only when the direct send actually queues behind a boundary, keeping both memory and store order aligned ahead of concurrent arrivals while writing zero files on immediate direct sends.

* fix(server): preserve live hold/withdraw state and store order across concurrent lazy saves

After awaiting lazy attachment resolution in save():
- Skip persisting if the message was withdrawn or rejected during the wait, and read current item.held and item.urgency rather than stale pre-await values.
- Insert before the first already-persisted successor in inbox.messages (tracked via item.persisted) so out-of-order upload completions still preserve admission order in the store.

* fix(server): close provider-switch, implicit-mode, and stray queue-file edge cases

- Respect direct providerSwitch boundaries in boundaryOfDirect()/canCoalesceDirect() so unheld messages or explicit-mode messages are not coalesced onto the target provider, while preserving Stop-held unset-mode queue carry-over.
- Treat any explicit sessionMode differing from an earlier group's mode (including undefined) as a dispatch boundary so later explicit-mode sends never retroactively promote earlier implicit-mode queued messages.
- Validate queue filename stems in createJsonAgentMessageQueueStore.listAll() before loading so stray .json files with invalid recipient ID stems are logged and ignored instead of aborting daemon startup.

* test(server): extract shared mode-boundary daemon E2E helper
2026-12-02 18:24:22 +07:00
Mohamed Boudra f576407576 fix(database): harden SQLite daemon storage defaults and statement caching (#11726)
* fix(database): harden SQLite daemon storage defaults and statement caching

Hardens the daemon SQLite layer before v0.19.0 creates paseo.db files in the wild:

- Enable PRAGMA auto_vacuum = INCREMENTAL on empty databases (page_count = 0) before creating page 1, so space reclamation never requires a blocking full VACUUM later.
- Bypass the prepared statement cache when bound string/binary parameters exceed 64 KiB (node:sqlite lacks clearBindings() and retains the last bound buffer in native memory), cap the cache with a 256-entry LRU, and evict statements on execution or iteration errors.
- Guard savepoint rollback with connection.isTransaction so SQLite auto-rollbacks (e.g. SQLITE_FULL/SQLITE_IOERR or ON CONFLICT ROLLBACK) preserve the original error instead of masking it with 'no such savepoint'.
- Probe schema_versions read-only before running mutating PRAGMAs so older daemons reject newer databases without altering page 1 or creating WAL sidecars, and pre-create missing database files atomically with O_CREAT|O_EXCL at 0o600 without opening existing inodes.
- Raise busy_timeout to 5000ms and set synchronous = NORMAL + checkpoint_fullfsync = ON on both the main connection and WalCheckpointer, set temp_store = MEMORY on main, keep a 10,000-page wal_autocheckpoint backstop while off-thread checkpointing is active, and skip WalCheckpointer if SQLite does not enter WAL mode.

* refactor(database): remove test-only accessors and harden lock test coordination

Addresses review feedback:
- Keep SqliteDaemonDatabase private with no test-only accessors and test statement cache bypass, saturation, and error eviction through the public DaemonDatabase interface.
- Keep the journal_mode === 'wal' decision in openDaemonDatabase without repeating it in checkpointOffThread.
- Extract named IterateInput and WalCheckpointerInput interfaces for multi-field parameter objects.
- Coordinate WalCheckpointer exclusive-lock contention deterministically using 0ms-timeout probe workers instead of fixed sleeps.
2026-12-02 18:10:25 +07:00
paseo-bot[bot] b2b05b599e fix(app): keep workspace sorting available when a host is offline (#11728)
The sidebar restores cached workspaces before their host sends its feature list. Keep the time sorts available until a host is known to lack support.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 10:42:45 +00:00
Mohamed Boudra 8fc8cb51b4 fix(server): validate schedule IDs in ScheduleStore (#11727)
Validate schedule IDs against [a-zA-Z0-9_-]+ and verify directory containment in ScheduleStore, and map InvalidScheduleIdError to PaseoToolInputError in the agent tool catalog.
2026-12-02 17:23:07 +07:00
TheCouchCommanderandjamescordrey-ops 18dc910689 fix(gitea): resolve bracketed IPv6 workspace remotes through Tea logins (#11692)
* fix(gitea): resolve bracketed IPv6 workspace remotes through Tea logins

* fix(gitea): canonicalize IPv6 literals when matching Tea logins

---------

Co-authored-by: jamescordrey-ops <jamescordrey-ops@users.noreply.github.com>
2026-12-02 10:18:52 +00:00
Mohamed Boudra 711188aadc fix(omp): handle lone checkbox labels and form edge cases in ask history (#11706)
* fix(omp): handle lone checkbox labels and form edge cases in ask history

* fix(omp): show Yes for checked lone checkbox asks in history
2026-12-02 16:59:56 +07:00
Mohamed Boudra d207bc5a57 feat(plugin): expose untrusted on lifecycle hooks and harden worktree-include copies (#11709)
* feat(plugin): expose untrusted on worktree and workspace lifecycle hooks

* fix(worktree-include): skip untrusted worktrees and harden destination copies

* fix(worktree-include): allow tracked destination symlinks and match realpath in test

Check only parent directory symlinks before git check-ignore so tracked leaf symlinks in the destination worktree are skipped instead of aborting creation, while ignored leaf symlinks still fail before copying. Also compare sourceCheckout with createRealpathAwarePathMatcher in paseo-worktree-service.test.ts to handle Windows short/long path and separator differences.
2026-12-02 16:59:06 +07:00
Mohamed Boudra f3213a2259 fix(daemon): harden WAL checkpointer fallback and propagate provider history read errors (#11711)
* fix(daemon): keep a failed WAL checkpoint fallback from crashing the daemon

When the WAL checkpointer worker ends on its own, the exit handler re-enabled SQLite's auto-checkpoint with no guard. A throw there (closed connection) was an uncaught exception that ended the daemon. It now logs a warning. A failing close() during a failed open also no longer replaces the DatabaseOpenError.

* fix(daemon): bound WAL checkpointer failures and propagate provider history errors

* fix(claude): reject waiting history readers when rewind rebind transcript load fails

* fix(claude): skip unparseable JSONL lines exceeding max string length during replay
2026-12-02 16:58:34 +07:00
paseo-bot[bot]andClaude Opus 5.5 370afb86c6 Keep a newer New workspace draft typed while creation finishes (#11720)
Since #11660, text typed on the web is published to the draft store after
the next paint. When workspace creation finished inside that frame, the
cleanup still saw the old draft version, cleared the draft as sent, and the
clear also dropped the unpublished text. Reopening New workspace showed an
empty composer. The cleanup now publishes pending text before it compares.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 09:44:37 +00:00
paseo-bot[bot] 6caf7f6653 fix(app): attach files pasted into the web composer (#11718)
The browser paste listener handled raster images and skipped other clipboard files. Send browser files through the same composer upload path as picked and dropped files.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 09:42:50 +00:00
73 changed files with 5236 additions and 801 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
@@ -21,6 +21,7 @@ import {
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
pasteFilesIntoComposer,
sendDraftToQueue,
expectQueuedMessageButton,
startRunningMockAgent,
@@ -152,7 +153,7 @@ test.describe("Composer attachments", () => {
// needed before this can be exercised end-to-end.
});
test("attaches, previews, and removes an image before dropping a file", async ({
test("attaches files from the menu, clipboard, and drag and drop", async ({
page,
withWorkspace,
}) => {
@@ -185,6 +186,19 @@ test.describe("Composer attachments", () => {
await expectComposerFocused(page);
});
await test.step("paste a Markdown file into the composer", async () => {
const file = {
name: "notes.md",
mimeType: "text/markdown",
buffer: Buffer.from("# Clipboard notes"),
};
const handled = await pasteFilesIntoComposer(page, [file]);
await expect(page.getByText(file.name, { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
expect(handled).toBe(true);
await expectComposerDraft(page, "");
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
@@ -192,6 +206,15 @@ test.describe("Composer attachments", () => {
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
await test.step("paste a file and an image together", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
const file = { ...TEST_JSON, name: "clipboard.json" };
await pasteFilesIntoComposer(page, [file, TEST_IMAGE]);
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
await expectAttachmentPill(page, "composer-image-attachment-pill");
});
});
test("dropped JSON file renders as a file attachment in New Workspace", async ({ page }) => {
@@ -2,6 +2,8 @@ import path from "node:path";
import type { Page, TestInfo } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
closeMobileAgentSidebar,
expectMobileAgentSidebarHidden,
@@ -141,6 +143,7 @@ async function withPaseoOwnedWorktree(
async function readCachedRowIds(
page: Page,
rowKind: "workspace" | "checkpoint",
hostServerId = getServerId(),
): Promise<string[]> {
return page.evaluate(
async ({ serverId, kind }) => {
@@ -169,7 +172,7 @@ async function readCachedRowIds(
database.close();
}
},
{ serverId: getServerId(), kind: rowKind },
{ serverId: hostServerId, kind: rowKind },
);
}
@@ -317,7 +320,60 @@ async function expectRecoveredWorkspacesAfterReload(
});
}
async function expectTimeSortingAvailable(page: Page): Promise<void> {
await page.getByLabel("Display preferences", { exact: true }).click();
await page.getByRole("menuitem", { name: /^Sort/ }).click();
await expect(page.getByRole("menuitem", { name: "Created", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Last prompt", exact: true })).toBeVisible();
await page.getByRole("menuitem", { name: "Created", exact: true }).click();
await page.getByLabel("Display preferences", { exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Sort/ })).toContainText("Created");
await page.keyboard.press("Escape");
}
async function cacheSecondaryHostWorkspace(page: Page, serverId: string, workspaceId: string) {
await expect(page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`)).toBeVisible();
await expect.poll(() => readCachedRowIds(page, "workspace", serverId)).toContain(workspaceId);
}
test.describe("Sidebar workspace list", () => {
test("keeps time sorting when a host's cached workspaces load offline", async ({ page }) => {
test.setTimeout(120_000);
const laptop = await startIsolatedHostDaemon("sidebar-sort-laptop");
try {
const other = await startIsolatedHostDaemon("sidebar-sort-other");
try {
const workspace = await seedWorkspace({
repoPrefix: "sidebar-sort-laptop-",
port: laptop.port,
});
try {
await gotoAppShell(page);
const hosts = [
{ ...laptop, label: "Laptop" },
{ ...other, label: "Other host" },
];
await test.step("cache the laptop workspace while its host is online", async () => {
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
await test.step("reopen the sidebar with the laptop offline", async () => {
await laptop.close();
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
} finally {
await workspace.cleanup();
}
} finally {
await other.close();
}
} finally {
await laptop.close();
}
});
test("recovers missing workspaces from a damaged legacy cache after reload", async ({
page,
}, testInfo) => {
+40 -14
View File
@@ -178,24 +178,50 @@ export async function attachFileFromMenu(
await (await chooserPromise).setFiles(file);
}
export async function dropFileOnComposer(
page: Page,
file: { name: string; mimeType: string; buffer: Buffer },
): Promise<void> {
const dataTransfer = await page.evaluateHandle(
({ name, mimeType, base64 }) => {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
const droppedFile = new File([bytes], name, { type: mimeType });
interface TransferFile {
name: string;
mimeType: string;
buffer: Buffer;
}
function createFileTransfer(page: Page, files: TransferFile[]) {
return page.evaluateHandle(
(entries) => {
const transfer = new DataTransfer();
transfer.items.add(droppedFile);
for (const { name, mimeType, base64 } of entries) {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
transfer.items.add(new File([bytes], name, { type: mimeType }));
}
return transfer;
},
{
name: file.name,
mimeType: file.mimeType,
base64: file.buffer.toString("base64"),
},
files.map(({ name, mimeType, buffer }) => ({
name,
mimeType,
base64: buffer.toString("base64"),
})),
);
}
export async function pasteFilesIntoComposer(page: Page, files: TransferFile[]): Promise<boolean> {
const clipboardData = await createFileTransfer(page, files);
try {
const input = composerInput(page);
await input.focus();
return await input.evaluate((element, transfer) => {
const event = new ClipboardEvent("paste", {
clipboardData: transfer,
bubbles: true,
cancelable: true,
});
return !element.dispatchEvent(event);
}, clipboardData);
} finally {
await clipboardData.dispose();
}
}
export async function dropFileOnComposer(page: Page, file: TransferFile): Promise<void> {
const dataTransfer = await createFileTransfer(page, [file]);
const composerRoot = page.getByTestId("message-input-root").filter({ visible: true }).first();
await expect(composerRoot).toBeVisible({ timeout: 10_000 });
@@ -1,4 +1,4 @@
import { getFileExtension } from "@/attachments/file-types";
import { getFileExtension, getMimeTypeFromPath } from "@/attachments/file-types";
import { copyDesktopAttachmentFile } from "@/desktop/attachments/desktop-file-commands";
import { readDesktopFileBase64 } from "@/desktop/attachments/desktop-preview-url";
@@ -8,6 +8,14 @@ export interface SelectedFile {
readBytes(): Promise<Uint8Array>;
}
export function selectedFileFromWebFile(file: File): SelectedFile {
return {
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
};
}
function base64ToUint8Array(base64: string): Uint8Array {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
+59
View File
@@ -995,6 +995,65 @@ describe("attachments restored from a queued message", () => {
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
});
it("clears the optimistic timeline bubble when a direct send is queued behind a boundary", async () => {
const client = createFakeSendClient();
client.sendAgentMessage = async (agentId, text, options) => {
client.calls.push({ agentId, text, options });
return { deliveryStatus: "queued", messageId: options.messageId };
};
const stream = createFakeStream();
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "follow up",
attachments: [],
submission: stream,
activeTurnBehavior: "interrupt",
});
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("clears the optimistic timeline bubble and settles staged switch via queued callback when a direct provider switch is queued", async () => {
const client = createFakeSendClient();
client.switchAgentProvider = async () => ({
deliveryStatus: "queued",
agent: undefined,
});
const stream = createFakeStream();
let committed = 0;
let queued = 0;
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "switch later",
attachments: [],
submission: stream,
currentProvider: "claude",
stagedProviderSwitch: {
provider: "codex",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
},
onProviderSwitchCommitted: () => {
committed += 1;
},
onProviderSwitchQueued: () => {
queued += 1;
},
});
expect(committed).toBe(0);
expect(queued).toBe(1);
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("counts a restored forge item as selected and toggles it off", () => {
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
+20 -1
View File
@@ -217,6 +217,7 @@ export interface DispatchComposerAgentMessageInput {
currentModel?: string | null;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
onProviderSwitchQueued?: () => void;
}
function buildPendingProviderSwitch(
@@ -242,6 +243,15 @@ function buildPendingProviderSwitch(
});
}
function isQueuedDeliveryResult(result: unknown): boolean {
return (
typeof result === "object" &&
result !== null &&
"deliveryStatus" in result &&
result.deliveryStatus === "queued"
);
}
export async function dispatchComposerAgentMessage(
input: DispatchComposerAgentMessageInput,
): Promise<void> {
@@ -281,16 +291,25 @@ export async function dispatchComposerAgentMessage(
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
input.onProviderSwitchQueued?.();
return;
}
input.submission.accept(input.agentId, clientMessageId);
await input.onProviderSwitchCommitted?.(result.agent);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
const result = await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
return;
}
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
input.submission.reject(input.agentId, clientMessageId);
@@ -3,7 +3,11 @@ import {
isRasterImageFile,
isRasterImagePath,
} from "@/attachments/file-types";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
import type { DroppedItem } from "@/components/file-drop/types";
interface DroppedAttachmentsRuntime {
@@ -36,12 +40,7 @@ export function droppedItemsToSelectedFiles(
if (isRasterImageFile(item.file)) {
continue;
}
const file = item.file;
files.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
files.push(selectedFileFromWebFile(item.file));
continue;
}
+14 -1
View File
@@ -166,7 +166,7 @@ import type {
WorkspaceFileComposerAttachment,
WorkspaceComposerAttachment,
} from "@/attachments/types";
import type { SelectedFile } from "@/attachments/selected-file";
import { selectedFileFromWebFile, type SelectedFile } from "@/attachments/selected-file";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
import type { ComposerFocusOptions } from "@/composer/model";
@@ -1775,6 +1775,11 @@ function ComposerContentImpl({
}
}
},
onProviderSwitchQueued: () => {
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
@@ -2041,6 +2046,13 @@ function ComposerContentImpl({
[addFiles, client, t],
);
const handlePasteFiles = useCallback(
(files: File[]) => {
void uploadSelectedFiles(files.map(selectedFileFromWebFile));
},
[uploadSelectedFiles],
);
const handlePickFile = useCallback(async () => {
if (!client) {
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
@@ -2698,6 +2710,7 @@ function ComposerContentImpl({
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteFiles={handlePasteFiles}
onPasteImages={handleNativePasteImages}
client={client}
isReadyForDictation={isDictationReady}
+29 -2
View File
@@ -21,6 +21,7 @@ import {
useRef,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useImperativeHandle,
useMemo,
@@ -64,6 +65,7 @@ import {
collectImageFilesFromClipboardData,
filesToImageAttachments,
} from "@/utils/image-attachments-from-files";
import { isRasterImageFile } from "@/attachments/file-types";
import type { ComposerAttachment } from "@/attachments/types";
import type { ImageAttachment, MessagePayload, TextReplacement } from "@/composer/types";
import { focusWithRetries } from "@/utils/web-focus";
@@ -81,7 +83,7 @@ import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
import { isNative, isWeb } from "@/constants/platform";
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { RenderProfile } from "@/utils/render-profiler";
@@ -173,6 +175,7 @@ export interface MessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef?: (node: View | null) => void;
onAddImages?: (images: ImageAttachment[]) => void;
onPasteFiles?: (files: File[]) => void;
onPasteImages?: (files: readonly NativePastedFile[]) => void;
client: DaemonClient | null;
/** Dictation start gate from host runtime (socket connected + directory ready). */
@@ -520,22 +523,36 @@ function getTextInputNativeElement(current: ComposerTextInputHandle | null): HTM
interface PasteEffectArgs {
textarea: HTMLElement | null;
isConnected: boolean;
isSubmitLoading: boolean;
disabled: boolean;
isDictating: boolean;
isRealtimeVoiceForCurrentAgent: boolean;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
}
function usePasteEffect(args: PasteEffectArgs): void {
const {
textarea,
isConnected,
isSubmitLoading,
disabled,
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
} = args;
const pasteFiles = useEffectEvent((clipboardData: DataTransfer | null) => {
if (!isConnected || isSubmitLoading || !onPasteFiles || getIsElectron()) return false;
const files = Array.from(clipboardData?.files ?? []).filter((file) => !isRasterImageFile(file));
if (files.length === 0) return false;
onPasteFiles(files);
return true;
});
useEffect(() => {
if (!isWeb) return;
@@ -546,8 +563,13 @@ function usePasteEffect(args: PasteEffectArgs): void {
if (disabled || isDictating || isRealtimeVoiceForCurrentAgent) return;
const imageFiles = collectImageFilesFromClipboardData(event.clipboardData);
const didPasteFiles = pasteFiles(event.clipboardData);
if (didPasteFiles) event.preventDefault();
if (imageFiles.length === 0) {
if (pasteLinkedClipboardText(textarea, event.clipboardData)) event.preventDefault();
if (!didPasteFiles && pasteLinkedClipboardText(textarea, event.clipboardData)) {
event.preventDefault();
}
return;
}
if (!isConnected || !onAddImages) return;
@@ -1191,6 +1213,7 @@ interface ResolvedMessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef: ((node: View | null) => void) | undefined;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
client: DaemonClient | null;
isReadyForDictation: boolean | undefined;
@@ -1239,6 +1262,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
attachmentMenuItems: props.attachmentMenuItems,
onAttachButtonRef: props.onAttachButtonRef,
onAddImages: props.onAddImages,
onPasteFiles: props.onPasteFiles,
onPasteImages: props.onPasteImages,
client: props.client,
isReadyForDictation: props.isReadyForDictation,
@@ -1321,6 +1345,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
attachmentMenuItems,
onAttachButtonRef,
onAddImages,
onPasteFiles,
onPasteImages,
client,
isReadyForDictation,
@@ -1874,6 +1899,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
isSubmitLoading,
});
const handleSelectionChange = useCallback(
+6 -10
View File
@@ -4,7 +4,11 @@ import { File } from "expo-file-system";
import { getDesktopHost, isElectronRuntime } from "@/desktop/host";
import { isWeb } from "@/constants/platform";
import { getMimeTypeFromPath } from "@/attachments/file-types";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
async function pickFilesWithDesktopDialog(): Promise<SelectedFile[] | null> {
const dialog = getDesktopHost()?.dialog;
@@ -52,15 +56,7 @@ function pickFilesWithWebInput(): Promise<SelectedFile[] | null> {
return;
}
const result: SelectedFile[] = [];
for (const file of files) {
result.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
}
resolve(result);
resolve(files.map(selectedFileFromWebFile));
});
input.addEventListener("cancel", () => {
@@ -1,4 +1,4 @@
import { useHostFeatureMap } from "@/runtime/host-features";
import { useHostFeatureAvailabilityMap } from "@/runtime/host-features";
import { useCallback, useEffect, useMemo } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { useCreateFlowStore } from "@/stores/create-flow-store";
@@ -142,8 +142,9 @@ export function useSidebarWorkspacesList(options?: {
const workspaceSort = useSidebarViewStore((state) => state.workspaceSort);
const groupMode = useSidebarViewStore((state) => state.groupMode);
const sortSupport = useHostFeatureMap(directoryServerIds, "workspaceSortTimes");
const workspaceSortSupported = [...sortSupport.values()].every(Boolean);
const sortSupport = useHostFeatureAvailabilityMap(directoryServerIds, "workspaceSortTimes");
// Cached workspaces are visible before their host sends server info.
const workspaceSortSupported = ![...sortSupport.values()].includes(false);
const sort =
groupMode === "project" && (workspaceSort === "manual" || workspaceSortSupported)
? workspaceSort
@@ -151,6 +151,17 @@ describe("createWorkspaceAgentInBackground", () => {
expect(draftText()).toBe("a different idea");
});
it("keeps text typed while workspace creation was pending that has not been published yet", () => {
const clearConsumedDraft = captureCleanup();
useDraftStore.getState().stageDraftText({ draftKey: DRAFT_KEY, text: "Keep this newer draft" });
// Creation completes before the staged text is published after the next paint.
clearConsumedDraft();
useDraftStore.getState().flushDraftText(DRAFT_KEY);
expect(draftText()).toBe("Keep this newer draft");
});
it("keeps a newer draft written while workspace creation was pending", async () => {
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
@@ -40,6 +40,8 @@ export function captureWorkspaceDraftCleanup(input: WorkspaceDraftCleanupInput):
const attachments = useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey];
return () => {
// Text typed into a newer draft is published after the next paint; it is newer state too.
useDraftStore.getState().flushDraftText(input.draftKey);
// These stores update independently. A context-only edit does not bump the text version.
// Any newer draft state owns the whole draft, including its unchanged context.
if (
@@ -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)) {
+19
View File
@@ -552,9 +552,28 @@ describe("lifecycle hook SDK types", () => {
const path: string = worktree.path;
const branch: string = worktree.branch;
const source: string = worktree.sourceCheckout;
const untrusted: boolean = worktree.untrusted;
void path;
void branch;
void source;
void untrusted;
// @ts-expect-error Trust status is read-only.
worktree.untrusted = false;
// @ts-expect-error Worktree facts have no workspace identity.
worktree.workspaceId;
});
server.addHook("workspace.create.after", async ({ workspace }) => {
const untrusted: boolean = workspace.untrusted;
void untrusted;
// @ts-expect-error Trust status is read-only.
workspace.untrusted = false;
});
server.addHook("workspace.archive.after", async ({ workspace }) => {
const untrusted: boolean = workspace.untrusted;
void untrusted;
// @ts-expect-error Trust status is read-only.
workspace.untrusted = false;
});
server.addHook("workspace.create.before", async ({ request }) => ({ ...request, title: "Changed" }));
server.addHook("workspace.create.before", async () => {});
server.addHook("agent.open.before", async () => {});
+4
View File
@@ -19,6 +19,8 @@ export interface PluginHookWorkspace {
cwd: string;
name: string | null;
archivedAt: string | null;
/** True when the workspace comes from an untrusted source such as a fork change request. */
readonly untrusted: boolean;
/** Data plugins stored on the workspace. Paseo never reads a key. */
metadata: Record<string, JsonValue>;
}
@@ -27,6 +29,8 @@ export interface PluginHookWorktree {
path: string;
branch: string;
sourceCheckout: string;
/** True when the worktree comes from an untrusted source such as a fork change request. */
readonly untrusted: boolean;
}
/** Resolved creation options before Git fetches refs or chooses a unique branch name. */
+3 -1
View File
@@ -84,7 +84,9 @@ export function parseGitRemoteLocation(remoteUrl: string): GitRemoteLocation | n
return null;
}
const normalizedPath = normalizeRemotePath(path);
if (!isValidRemoteHost(host) || !normalizedPath) return null;
// URL already validates bracketed IPv6 literals. Keep the brackets for URL builders.
const validHost = host.startsWith("[") || isValidRemoteHost(host);
if (!validHost || !normalizedPath) return null;
const protocol = parsed.protocol.toLowerCase();
const port =
@@ -1208,28 +1208,39 @@ function createRecipient(
async person(
prompt: string,
messageId: string,
outcome: { fail?: Error; started?: Promise<void> } = {},
outcome: { fail?: Error; started?: Promise<void>; sessionMode?: string } = {},
) {
const prompts: AgentPromptInput[] = [];
const modes: Array<string | undefined> = [];
const result = await delivery
.sendDirect({ recipientId: "recipient", prompt, messageId }, async (joined) => {
prompts.push(joined.prompt);
if (outcome.fail) throw outcome.fail;
const joinedIds =
typeof joined.prompt === "string"
? parseAgentMessages(joined.prompt)?.map((message) => message.id)
: undefined;
received.push(...(joinedIds ?? [messageId]));
running = true;
return {
disposition: "turn_started" as const,
started: outcome.started ?? Promise.resolve(),
};
})
.sendDirect(
{
recipientId: "recipient",
prompt,
messageId,
sessionMode: outcome.sessionMode,
},
async (joined) => {
prompts.push(joined.prompt);
modes.push(joined.sessionMode);
if (outcome.fail) throw outcome.fail;
const joinedIds =
typeof joined.prompt === "string"
? parseAgentMessages(joined.prompt)?.map((message) => message.id)
: undefined;
received.push(...(joinedIds ?? [messageId]));
running = true;
return {
disposition: "turn_started" as const,
started: outcome.started ?? Promise.resolve(),
};
},
)
.catch((error: unknown) => error);
const [sentPrompt] = prompts;
return {
prompt: sentPrompt,
sessionMode: modes[0],
result,
ids:
typeof sentPrompt === "string"
@@ -2425,3 +2436,824 @@ test("an agent's steer behind a queued switch does not cut the running turn to s
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["switch"]]);
await recipient.delivery.close();
});
test("a direct broader-mode send does not coalesce a queued plan-mode message and preserves FIFO mode order", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Inspect files only",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Edit files now", "direct-1", {
sessionMode: "bypassPermissions",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
// Direct send did NOT coalesce plan-1 into a bypassPermissions prompt.
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
]);
// Once the plan turn finishes, the direct send runs separately in bypassPermissions.
await recipient.endTurn();
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
{
ids: ["direct-1"],
behavior: "steer",
idleOnly: true,
mode: "bypassPermissions",
},
]);
expect(recipient.received).toEqual(["plan-1", "direct-1"]);
expect(recipient.delivery.hasPending("recipient")).toBe(false);
await recipient.delivery.close();
});
test("a direct plan-mode send does not coalesce a queued broader-mode message and preserves FIFO mode order", async () => {
const recipient = createRecipient();
const broad = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "broad-1",
text: "Apply patch",
sessionMode: "bypassPermissions",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Now review read-only", "direct-plan", {
sessionMode: "plan",
});
await expect(broad.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent).toEqual([
{
ids: ["broad-1"],
behavior: "interrupt",
idleOnly: false,
mode: "bypassPermissions",
},
]);
await recipient.endTurn();
expect(recipient.sent).toEqual([
{
ids: ["broad-1"],
behavior: "interrupt",
idleOnly: false,
mode: "bypassPermissions",
},
{
ids: ["direct-plan"],
behavior: "steer",
idleOnly: true,
mode: "plan",
},
]);
expect(recipient.received).toEqual(["broad-1", "direct-plan"]);
await recipient.delivery.close();
});
test.each([
{
name: "same explicit mode",
queuedMode: "plan",
directMode: "plan",
expectedMode: "plan",
},
{
name: "queued explicit mode with unset direct mode",
queuedMode: "plan",
directMode: undefined,
expectedMode: "plan",
},
])(
"a direct send still coalesces with a queued message when modes are compatible ($name)",
async ({ queuedMode, directMode, expectedMode }) => {
const recipient = createRecipient();
const queued = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "queued-1",
text: "Queued note",
sessionMode: queuedMode,
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Direct follow-up", "direct-1", {
sessionMode: directMode,
});
await expect(queued.dispatched).resolves.toBe("turn_started");
expect(direct.result).toMatchObject({ disposition: "turn_started" });
expect(direct.ids).toEqual(["queued-1", "direct-1"]);
expect(direct.sessionMode).toBe(expectedMode);
expect(recipient.sent).toEqual([]);
expect(recipient.delivery.hasPending("recipient")).toBe(false);
await recipient.delivery.close();
},
);
test("multiple queued messages across a mode boundary followed by a direct send never merge across modes", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan first",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
const broad = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "broad-1",
text: "Edit second",
sessionMode: "bypassPermissions",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Edit third", "direct-broad", {
sessionMode: "bypassPermissions",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
]);
await recipient.endTurn();
await expect(broad.dispatched).resolves.toBe("turn_started");
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
{
ids: ["broad-1", "direct-broad"],
behavior: "steer",
idleOnly: true,
mode: "bypassPermissions",
},
]);
expect(recipient.received).toEqual(["plan-1", "broad-1", "direct-broad"]);
await recipient.delivery.close();
});
test("a direct send with unset mode still respects an existing mode boundary in the queue", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan first",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "broad-1",
text: "Edit second",
sessionMode: "bypassPermissions",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Follow up", "direct-unset");
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
{ ids: ["plan-1"], mode: "plan" },
]);
await recipient.endTurn();
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
{ ids: ["plan-1"], mode: "plan" },
{ ids: ["broad-1", "direct-unset"], mode: "bypassPermissions" },
]);
await recipient.delivery.close();
});
test("a direct send behind a queued non-agent slash command keeps the command raw and alone", async () => {
const recipient = createRecipient();
const command = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "cmd-1",
text: "/review",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Summarize findings", "direct-1");
await expect(command.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["cmd-1"]]);
await recipient.endTurn();
expect(recipient.sent.map(({ ids }) => ids)).toEqual([["cmd-1"], ["direct-1"]]);
await recipient.delivery.close();
});
test("an urgent interrupt with a conflicting mode does not coalesce a queued plan-mode message", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Inspect only",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
const urgent = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "urgent-broad",
source: { kind: "agent-message", agentId: "sender" },
text: "Modify now",
sessionMode: "bypassPermissions",
activeTurnBehavior: "interrupt",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
]);
await recipient.endTurn();
await expect(urgent.dispatched).resolves.toBe("turn_started");
expect(recipient.sent).toEqual([
{
ids: ["plan-1"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
{
ids: ["urgent-broad"],
behavior: "steer",
idleOnly: true,
mode: "bypassPermissions",
},
]);
await recipient.delivery.close();
});
test("a direct broader-mode send after Stop reopens a held plan-mode message without coalescing across modes", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-held",
text: "Plan before stop",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.stop();
await recipient.tick();
expect(recipient.sent).toEqual([]);
const direct = await recipient.person("Edit after stop", "direct-after-stop", {
sessionMode: "bypassPermissions",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent).toEqual([
{
ids: ["plan-held"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
]);
await recipient.endTurn();
expect(recipient.sent).toEqual([
{
ids: ["plan-held"],
behavior: "interrupt",
idleOnly: false,
mode: "plan",
},
{
ids: ["direct-after-stop"],
behavior: "steer",
idleOnly: true,
mode: "bypassPermissions",
},
]);
await recipient.delivery.close();
});
function expectQueuedReceipt(result: {
disposition: string;
receipt?: { dispatched: Promise<unknown> };
}) {
expect(result.disposition).toBe("queued");
if (result.disposition !== "queued" || !result.receipt) {
throw new Error(`Expected queued disposition, received ${result.disposition}`);
}
return result.receipt;
}
test("a direct broader-mode send does not coalesce a plan-mode dispatch returned to the queue after busy rejection", async () => {
const clock = createClock();
let busy = true;
let releaseFirstAttempt!: () => void;
const firstAttemptStarted = new Promise<void>((resolve) => {
releaseFirstAttempt = resolve;
});
let finishFirstAttempt!: () => void;
const firstAttemptGate = new Promise<void>((resolve) => {
finishFirstAttempt = resolve;
});
let wake!: (recipientId: string) => void;
let attempts = 0;
const dispatched: Array<{ ids: readonly string[]; mode?: string }> = [];
const directPrompts: AgentPromptInput[] = [];
const delivery = createAgentMessageDelivery({
store: createMemoryAgentMessageQueueStore(),
schedule: clock.schedule,
isRunning: () => busy,
subscribe: (listener) => {
wake = listener;
return () => {};
},
dispatch: async (request) => {
attempts++;
if (attempts === 1) {
releaseFirstAttempt();
await firstAttemptGate;
throw new AgentTurnBusyError("turn started concurrently");
}
if (!request.admit()) throw new Error("not admitted");
dispatched.push({ ids: request.messageIds, mode: request.sessionMode });
busy = true;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
busy = false;
const planned = await delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan first",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await firstAttemptStarted;
// plan-1 is currently marked dispatching/claimed in flight when the direct send arrives.
const directPromise = delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-1",
prompt: "Edit now",
sessionMode: "bypassPermissions",
},
async (joined) => {
directPrompts.push(joined.prompt);
return { disposition: "turn_started", started: Promise.resolve() };
},
);
// A later message admitted while direct-1 waits must stay behind direct-1.
const later = await delivery.enqueue({
recipientId: "recipient",
messageId: "later-1",
text: "Later message",
sessionMode: "default",
activeTurnBehavior: "queue",
});
// First attempt fails with AgentTurnBusyError and hands plan-1 back to queued before direct runs.
busy = true;
finishFirstAttempt();
const directResult = await directPromise;
await expect(planned.dispatched).resolves.toBe("turn_started");
expect(directPrompts).toEqual([]);
const queuedDirectReceipt = expectQueuedReceipt(directResult);
expect(dispatched).toEqual([{ ids: ["plan-1"], mode: "plan" }]);
busy = false;
wake("recipient");
await expect(queuedDirectReceipt.dispatched).resolves.toBe("turn_started");
expect(dispatched).toEqual([
{ ids: ["plan-1"], mode: "plan" },
{ ids: ["direct-1"], mode: "bypassPermissions" },
]);
busy = false;
wake("recipient");
await expect(later.dispatched).resolves.toBe("turn_started");
expect(dispatched).toEqual([
{ ids: ["plan-1"], mode: "plan" },
{ ids: ["direct-1"], mode: "bypassPermissions" },
{ ids: ["later-1"], mode: "default" },
]);
await delivery.close();
});
test("a direct send with a conflicting mode stays ahead of a queued provider switch on the current provider", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan on current provider",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.queueSwitch("switch", "codex");
recipient.send("queue", "after");
await recipient.tick();
const direct = await recipient.person("Edit on current provider", "direct-1", {
sessionMode: "bypassPermissions",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
{ ids: ["plan-1"], mode: "plan", switchTo: undefined },
]);
await recipient.endTurn();
await recipient.endTurn();
await recipient.endTurn();
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
{ ids: ["plan-1"], mode: "plan", switchTo: undefined },
{ ids: ["direct-1"], mode: "bypassPermissions", switchTo: undefined },
{ ids: ["switch"], mode: undefined, switchTo: "codex" },
{ ids: ["after"], mode: undefined, switchTo: undefined },
]);
await recipient.delivery.close();
});
test("retrying a direct send that is already queued returns its queued receipt without duplicating or interrupting", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan first",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.tick();
let directCalls = 0;
const first = await recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-retry",
prompt: "Edit later",
sessionMode: "bypassPermissions",
fingerprint: "fp-1",
},
async () => {
directCalls += 1;
return { disposition: "turn_started", started: Promise.resolve() };
},
);
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
// plan-1 is now running and direct-retry is waiting in the queue.
const firstReceipt = expectQueuedReceipt(first);
const retry = await recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-retry",
prompt: "Edit later",
sessionMode: "bypassPermissions",
fingerprint: "fp-1",
},
async () => {
directCalls += 1;
return { disposition: "turn_started", started: Promise.resolve() };
},
);
expect(expectQueuedReceipt(retry)).toBe(firstReceipt);
expect(directCalls).toBe(0);
expect(recipient.sent).toEqual([
{ ids: ["plan-1"], behavior: "interrupt", idleOnly: false, mode: "plan" },
]);
await expect(
recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-retry",
prompt: "Different body",
sessionMode: "bypassPermissions",
fingerprint: "fp-different",
},
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
),
).rejects.toThrow("agent_request_key_conflict");
await recipient.endTurn();
await expect(firstReceipt.dispatched).resolves.toBe("turn_started");
expect(recipient.sent).toEqual([
{ ids: ["plan-1"], behavior: "interrupt", idleOnly: false, mode: "plan" },
{ ids: ["direct-retry"], behavior: "steer", idleOnly: true, mode: "bypassPermissions" },
]);
await recipient.delivery.close();
});
test("lazy direct-send attachments resolve only when queued and preserve order ahead of concurrent arrivals", async () => {
const store = createMemoryAgentMessageQueueStore();
const recipient = createRecipient({ store });
// Direct send on an empty queue runs immediately without invoking resolveAttachments.
let emptyResolverCalls = 0;
await recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-empty",
prompt: "Look",
text: "Look",
resolveAttachments: async () => {
emptyResolverCalls += 1;
return [];
},
},
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
);
expect(emptyResolverCalls).toBe(0);
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "plan-1",
text: "Plan first",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.tick();
let finishAttachments!: () => void;
const attachmentGate = new Promise<void>((resolve) => {
finishAttachments = resolve;
});
let queuedResolverCalls = 0;
const directPromise = recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "direct-img",
prompt: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }],
text: "",
sessionMode: "bypassPermissions",
resolveAttachments: async () => {
queuedResolverCalls += 1;
await attachmentGate;
return [
{
type: "github_issue",
mimeType: "application/github-issue",
number: 7,
title: "Attached context",
url: "https://example.com/7",
},
];
},
},
async () => ({ disposition: "turn_started", started: Promise.resolve() }),
);
// Another message arrives while resolveAttachments is still pending.
const later = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "later-1",
text: "Later message",
sessionMode: "default",
activeTurnBehavior: "queue",
});
finishAttachments();
const directResult = await directPromise;
const directReceipt = expectQueuedReceipt(directResult);
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(queuedResolverCalls).toBe(1);
// Store order matches admission order: direct-img stays ahead of later-1 with its attachment.
expect(await store.listByRecipient("recipient")).toMatchObject([
{ id: "direct-img", attachments: [{ type: "github_issue", number: 7 }] },
{ id: "later-1" },
]);
await recipient.endTurn();
await expect(directReceipt.dispatched).resolves.toBe("turn_started");
await recipient.endTurn();
await expect(later.dispatched).resolves.toBe("turn_started");
expect(recipient.sent.map(({ ids, mode }) => ({ ids, mode }))).toEqual([
{ ids: ["plan-1"], mode: "plan" },
{ ids: ["direct-img"], mode: "bypassPermissions" },
{ ids: ["later-1"], mode: "default" },
]);
await recipient.delivery.close();
});
test("a direct provider switch does not coalesce a queued or Stop-held plan-mode message onto the target provider", async () => {
const recipient = createRecipient();
const planned = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "claude-plan",
text: "QUEUED_FOR_CLAUDE_ONLY",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.stop();
await recipient.tick();
let directSwitchCalls = 0;
const result = await recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "switch-codex",
prompt: "DIRECT_SWITCH_TO_CODEX",
text: "DIRECT_SWITCH_TO_CODEX",
sessionMode: "plan",
providerSwitch: { provider: "codex", modeId: "plan" },
},
async () => {
directSwitchCalls += 1;
return { disposition: "turn_started", started: Promise.resolve() };
},
);
const queuedSwitch = expectQueuedReceipt(result);
await expect(planned.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(directSwitchCalls).toBe(0);
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
{ ids: ["claude-plan"], mode: "plan", switchTo: undefined },
]);
await recipient.endTurn();
await expect(queuedSwitch.dispatched).resolves.toBe("turn_started");
expect(recipient.sent.map(({ ids, mode, switchTo }) => ({ ids, mode, switchTo }))).toEqual([
{ ids: ["claude-plan"], mode: "plan", switchTo: undefined },
{ ids: ["switch-codex"], mode: "plan", switchTo: "codex" },
]);
await recipient.delivery.close();
});
test("a direct provider switch does not steal an unheld collecting message onto the target provider", async () => {
const recipient = createRecipient({ running: false });
const queued = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "claude-collecting",
source: { kind: "agent-message", agentId: "worker" },
text: "Collecting for current provider",
activeTurnBehavior: "queue",
});
let directSwitchCalls = 0;
const result = await recipient.delivery.sendDirect(
{
recipientId: "recipient",
messageId: "switch-codex",
prompt: "Switch now",
text: "Switch now",
providerSwitch: { provider: "codex" },
},
async () => {
directSwitchCalls += 1;
return { disposition: "turn_started", started: Promise.resolve() };
},
);
const queuedSwitch = expectQueuedReceipt(result);
await expect(queued.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(directSwitchCalls).toBe(0);
expect(recipient.sent.map(({ ids, switchTo }) => ({ ids, switchTo }))).toEqual([
{ ids: ["claude-collecting"], switchTo: undefined },
]);
await recipient.endTurn();
await expect(queuedSwitch.dispatched).resolves.toBe("turn_started");
expect(recipient.sent.map(({ ids, switchTo }) => ({ ids, switchTo }))).toEqual([
{ ids: ["claude-collecting"], switchTo: undefined },
{ ids: ["switch-codex"], switchTo: "codex" },
]);
await recipient.delivery.close();
});
test("an explicit-mode direct or queued send does not retroactively promote an earlier implicit-mode queued message", async () => {
const recipient = createRecipient();
const implicit = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "implicit-1",
text: "Run in existing mode",
activeTurnBehavior: "queue",
});
await recipient.tick();
const direct = await recipient.person("Switch to bypass", "direct-bypass", {
sessionMode: "bypassPermissions",
});
await expect(implicit.dispatched).resolves.toBe("turn_started");
await recipient.settle();
expect(direct.prompt).toBeUndefined();
expect(direct.result).toMatchObject({ disposition: "queued" });
expect(recipient.sent).toEqual([
{
ids: ["implicit-1"],
behavior: "interrupt",
idleOnly: false,
mode: undefined,
},
]);
await recipient.endTurn();
expect(recipient.sent).toEqual([
{
ids: ["implicit-1"],
behavior: "interrupt",
idleOnly: false,
mode: undefined,
},
{
ids: ["direct-bypass"],
behavior: "steer",
idleOnly: true,
mode: "bypassPermissions",
},
]);
// Ordinary queue draining also refuses to promote an earlier implicit-mode message.
const implicitQueued = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "implicit-2",
text: "Stay in current mode",
activeTurnBehavior: "queue",
});
const explicitQueued = await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "explicit-2",
text: "Now enter plan",
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await recipient.endTurn();
await expect(implicitQueued.dispatched).resolves.toBe("turn_started");
expect(recipient.sent.at(-1)).toMatchObject({
ids: ["implicit-2"],
idleOnly: true,
mode: undefined,
});
await recipient.endTurn();
await expect(explicitQueued.dispatched).resolves.toBe("turn_started");
expect(recipient.sent.at(-1)).toMatchObject({
ids: ["explicit-2"],
idleOnly: true,
mode: "plan",
});
await recipient.delivery.close();
});
@@ -7,7 +7,11 @@ import {
} from "../agent-prompt.js";
import { randomUUID } from "node:crypto";
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
import type { AgentAttachment, QueuedProviderSwitch } from "@getpaseo/protocol/messages";
import type {
AgentAttachment,
QueuedProviderSwitch,
UploadedFileAttachment,
} from "@getpaseo/protocol/messages";
import type {
AgentPromptContentBlock,
AgentPromptInput,
@@ -49,7 +53,7 @@ interface Message {
beforeDispatch?: () => void;
onDispatch?: (disposition: PromptDispatchDisposition) => void;
}
interface Receipt {
export interface AgentMessageReceipt {
status: "queued";
messageId: string;
activeTurnBehavior: AgentMessageBehavior;
@@ -57,8 +61,11 @@ interface Receipt {
guidance: string;
dispatched: Promise<PromptDispatchDisposition>;
}
export type DirectSendResult<Result extends PromptDispatchResult> =
| Result
| { disposition: "queued"; receipt: AgentMessageReceipt };
/** What a queued message is. Urgency and the hold change while it waits. */
type QueuedContent = Omit<EnqueueStoreInput, "urgency" | "held">;
type QueuedContent = Omit<EnqueueStoreInput, "urgency" | "held" | "insertBeforeId">;
interface Admitted extends QueuedContent {
/** claimed: a dispatch has it. It leaves the queue when the provider admits the prompt. */
state: "queued" | "claimed" | "withdrawn" | "rejected";
@@ -69,7 +76,9 @@ interface Admitted extends QueuedContent {
outOfBandDeclined: boolean;
/** Settles once the store holds it. Nothing dispatches it before that. */
saved: Promise<void>;
receipt: Receipt;
/** True once the record exists in the store (for ordering concurrent lazy saves). */
persisted: boolean;
receipt: AgentMessageReceipt;
resolve(disposition: PromptDispatchDisposition): void;
reject(error: unknown): void;
beforeDispatch?: () => void;
@@ -126,11 +135,22 @@ interface DispatchRequest {
interface DirectPrompt {
recipientId: string;
prompt: AgentPromptInput;
/** Raw message text when the caller has it, used if queueing behind a boundary. */
text?: string;
/** Raw message attachments when the caller has them, used if queueing behind a boundary. */
attachments?: readonly AgentAttachment[];
/** Lazy attachment persistence invoked only when a direct prompt is queued behind a boundary. */
resolveAttachments?: () => Promise<AgentAttachment[]>;
uploadedImages?: readonly UploadedImage[];
source?: AgentPromptSource;
messageId?: string;
sessionMode?: string;
providerSwitch?: QueuedProviderSwitch;
activeTurnBehavior?: QueuedMessageUrgency;
clearPendingPermissions?: boolean;
fingerprint?: string;
unarchive?: boolean;
onDispatch?: (disposition: PromptDispatchDisposition) => void;
/** It continues the turn the queue is waiting on, so it takes nothing queued with it. */
resumesTurn?: boolean;
}
@@ -188,16 +208,18 @@ export interface AgentMessageDelivery {
* Admit a message and resolve once it is saved. A queued one waits for the running turn to
* end; a steer or an interrupt releases at once, with everything queued before it.
*/
enqueue(message: Message): Promise<Receipt>;
enqueue(message: Message): Promise<AgentMessageReceipt>;
/**
* Send a prompt that does not wait its turn. The messages admitted before it go ahead of it
* in the same provider prompt, so none starts a turn of its own afterwards. Its place is
* decided by this call, whenever the recipient gets to it. A command travels alone.
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
* coalescing, the prompt is queued behind those messages and releases the first group at once.
* A direct command or restart-resume travels alone.
*/
sendDirect<Result extends PromptDispatchResult>(
direct: DirectPrompt,
send: (joined: JoinedPrompt) => Promise<Result>,
): Promise<Result>;
): Promise<DirectSendResult<Result>>;
/** The saved queue in delivery order. `held`: it waits for the recipient's next prompt. */
list(recipientId: string): Promise<{ held: boolean; items: PersistedQueuedMessage[] }>;
/** Settles with the delivery of a message still in the queue. Undefined once it has left. */
@@ -288,36 +310,152 @@ function beforeSwitch(messages: Admitted[]): Admitted[] {
return index < 0 ? messages : messages.slice(0, index);
}
interface DispatchBoundary {
readonly prompt: AgentPromptInput;
readonly source: AgentPromptSource | null | undefined;
readonly sessionMode?: string;
readonly providerSwitch?: QueuedProviderSwitch;
}
function travelsAlone(entry: DispatchBoundary): boolean {
return Boolean(entry.providerSwitch) || (!entry.source && isCommand(entry.prompt));
}
function hasConflictingSessionMode(input: {
groupMode: string | undefined;
nextMode: string | undefined;
}): boolean {
// An explicit sessionMode switches modes for this message and onward, so it cannot coalesce
// onto an earlier group with either a different mode or an unset (implicit) mode.
return input.nextMode !== undefined && input.groupMode !== input.nextMode;
}
/**
* Provider switches, explicitly conflicting session modes and non-agent commands require
* separate, ordered dispatches.
*/
function modeGroups(messages: Admitted[]): Admitted[][] {
const groups: Admitted[][] = [];
let group: Admitted[] = [];
function dispatchGroups<Entry>(input: {
entries: readonly Entry[];
boundaryOf: (entry: Entry) => DispatchBoundary;
}): Entry[][] {
const groups: Entry[][] = [];
let group: Entry[] = [];
let mode: string | undefined;
for (const message of messages) {
if (message.providerSwitch || (!message.source && isCommand(message.text))) {
for (const entry of input.entries) {
const boundary = input.boundaryOf(entry);
if (travelsAlone(boundary)) {
if (group.length) {
groups.push(group);
group = [];
mode = undefined;
}
groups.push([message]);
groups.push([entry]);
continue;
}
if (mode && message.sessionMode && mode !== message.sessionMode) {
if (
group.length > 0 &&
hasConflictingSessionMode({ groupMode: mode, nextMode: boundary.sessionMode })
) {
groups.push(group);
group = [];
mode = undefined;
}
group.push(message);
mode ??= message.sessionMode;
group.push(entry);
mode ??= boundary.sessionMode;
}
if (group.length) groups.push(group);
return groups;
}
function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
return {
prompt: message.text,
source: message.source,
sessionMode: message.sessionMode,
providerSwitch: message.providerSwitch,
};
}
function boundaryOfDirect(input: {
direct: DirectPrompt;
includeProviderSwitch: boolean;
}): DispatchBoundary {
return {
prompt: input.direct.prompt,
source: input.direct.source,
sessionMode: input.direct.sessionMode,
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
};
}
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
}
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
// A direct provider switch only carries a Stop-held queue when every held message has no
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
// or explicit mode belongs to the current provider and must not move across providers.
const carriesHeldSwitch =
Boolean(input.direct.providerSwitch) &&
!input.direct.providerSwitch?.modeId &&
input.direct.sessionMode === undefined &&
input.ahead.length > 0 &&
input.ahead.every((message) => message.held && message.sessionMode === undefined);
const entries: DispatchBoundary[] = [
...input.ahead.map(boundaryOfAdmitted),
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
];
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
}
function toUploadedImageAttachments(
uploadedImages: readonly UploadedImage[] | undefined,
): Array<UploadedFileAttachment & { role: "image" }> {
return (uploadedImages ?? []).map((image) => ({
type: "uploaded_file",
role: "image",
id: image.id,
fileName: image.fileName,
mimeType: image.mimeType,
size: image.size,
path: image.path,
}));
}
function isPlainTextBlock(block: AgentPromptContentBlock): block is { type: "text"; text: string } {
return block.type === "text" && !("contextKind" in block);
}
function directQueueContent(direct: DirectPrompt): {
text: string;
attachments: AgentAttachment[];
} {
if (direct.text !== undefined || direct.attachments !== undefined) {
return {
text: direct.text ?? "",
attachments: [...(direct.attachments ?? [])],
};
}
const uploadedAttachments = toUploadedImageAttachments(direct.uploadedImages);
if (typeof direct.prompt === "string") {
return { text: direct.prompt, attachments: uploadedAttachments };
}
const textParts: string[] = [];
const otherAttachments: AgentAttachment[] = [];
for (const block of direct.prompt) {
if (isPlainTextBlock(block)) {
textParts.push(block.text);
} else if (block.type !== "image") {
otherAttachments.push(block);
}
}
return {
text: textParts.join("\n\n"),
attachments: [...uploadedAttachments, ...otherAttachments],
};
}
/**
* Owns the order in which prompts reach a recipient. Delivery order equals admission order:
* only a prefix of the queue is ever dispatched, except a command a provider runs out of band.
@@ -408,6 +546,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
batch: Ready[],
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
): DispatchRequest {
const messages = messagesOf(batch);
return {
@@ -422,10 +561,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
prompt: formatBatch(batch),
uploadedImages: uploadedImagesOf(batch),
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
activeTurnBehavior: messages.some((message) => message.urgency === "interrupt")
? "interrupt"
: "steer",
// An interrupt may follow a message that asked for another mode; the latest choice wins.
activeTurnBehavior:
activeTurnBehavior ??
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
// Every message in a batch belongs to one compatible mode group.
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
providerSwitch: messages[0]?.providerSwitch,
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
@@ -580,6 +719,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
batch: Admitted[],
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
): Promise<void> {
for (;;) {
const prepared = await prepare(recipientId, batch);
@@ -592,7 +732,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await handBack(recipientId, messages);
continue;
}
const request = requestFor(recipientId, dispatching, idleOnly, stopped);
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
let disposition: PromptDispatchDisposition;
try {
for (const message of messages) message.beforeDispatch?.();
@@ -667,8 +807,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
/**
* Dispatch what the latest steer or interrupt releases: it does not jump the queue, so
* everything admitted before it goes first. A provider switch bounds the release, because it
* cannot share a prompt. False when nothing may go into the running turn.
* everything admitted before it goes first. The first compatible boundary group runs now
* (respecting provider switches, conflicting session modes and non-agent commands), and
* later groups follow as turns end. False when nothing may go into the running turn.
*/
async function release(
recipientId: string,
@@ -677,14 +818,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
): Promise<boolean> {
const last = ahead.findLastIndex(isUrgent);
if (last < 0) return false;
const released = ahead.slice(0, last + 1);
const released = ahead.slice(0, last + 1).filter(isQueued);
const [first] = released;
if (!first) return false;
// Only releasing the switch itself replaces the running turn with it.
if (first?.providerSwitch && !isUrgent(first)) return false;
const now = first?.providerSwitch ? [first] : beforeSwitch(released);
// The rest follows when the turn these start ends.
for (const message of released.slice(now.length)) message.urgency = null;
await deliver(recipientId, now, false, stopped);
if (first.providerSwitch && !isUrgent(first)) return false;
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
const behavior: QueuedMessageUrgency = released.some(
(message) => message.urgency === "interrupt",
)
? "interrupt"
: "steer";
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
// so a daemon restart while the first group runs does not revive consumed urgency.
const deferred = released.slice(now.length);
if (deferred.length) {
for (const message of deferred) message.urgency = null;
const deferredIds = idsOf(deferred);
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
}
await deliver(recipientId, now, false, stopped, behavior);
return true;
}
@@ -764,10 +917,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
};
}
function admit(item: Admitted): void {
function admit(item: Admitted, insertBeforeId?: string): void {
const inbox = inboxes.get(item.recipientId) ?? emptyInbox();
inboxes.set(item.recipientId, inbox);
inbox.messages.push(item);
const insertIndex = insertBeforeId
? inbox.messages.findIndex((entry) => entry.id === insertBeforeId)
: -1;
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
else inbox.messages.push(item);
inbox.cancelTimer();
if (item.urgency) {
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
@@ -795,7 +952,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
function createAdmitted(
content: QueuedContent,
state: Pick<Admitted, "urgency" | "held">,
receipt: Pick<Receipt, "activeTurnBehavior" | "guidance">,
receipt: Pick<AgentMessageReceipt, "activeTurnBehavior" | "guidance">,
): Admitted {
let resolve!: Admitted["resolve"];
let reject!: Admitted["reject"];
@@ -813,6 +970,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
state: "queued",
outOfBandDeclined: false,
saved: Promise.resolve(),
persisted: false,
};
}
@@ -820,7 +978,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
recipientId: string,
activeTurnBehavior: AgentMessageBehavior,
source: AgentPromptSource | null,
): Pick<Receipt, "activeTurnBehavior" | "guidance"> {
): Pick<AgentMessageReceipt, "activeTurnBehavior" | "guidance"> {
return {
activeTurnBehavior,
guidance: describeAgentMessage({
@@ -832,10 +990,29 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
};
}
/** The store is called before this first yields, so saved order is admission order. */
async function save(item: Admitted): Promise<void> {
const { recipientId, id, urgency, held } = item;
/** The store is called before this first yields (unless attachments are resolved lazily). */
async function save(
item: Admitted,
insertBeforeId?: string,
resolveAttachments?: () => Promise<AgentAttachment[]>,
): Promise<void> {
const { recipientId, id } = item;
try {
if (resolveAttachments) {
item.attachments = [...(await resolveAttachments())];
// A Stop, withdrawal, or archive during lazy attachment saving may have mutated or removed item.
if (isWithdrawn(item) || item.state === "rejected") return;
}
if (!item.text.trim() && !item.attachments.length) {
throw new Error("Agent message is empty");
}
const inboxMessages = inboxes.get(recipientId)?.messages;
const itemIndex = inboxMessages ? inboxMessages.indexOf(item) : -1;
const nextPersistedId =
itemIndex >= 0
? inboxMessages?.slice(itemIndex + 1).find((entry) => entry.persisted)?.id
: undefined;
const storeInsertBeforeId = nextPersistedId ?? insertBeforeId;
const result = await store.enqueue({
recipientId,
id,
@@ -848,12 +1025,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
unarchive: item.unarchive,
clearPendingPermissions: item.clearPendingPermissions,
fingerprint: item.fingerprint,
urgency,
held,
urgency: item.urgency,
held: item.held,
...(storeInsertBeforeId ? { insertBeforeId: storeInsertBeforeId } : {}),
});
if (result.status === "conflict") throw new Error("agent_request_key_conflict");
if (result.status === "full")
throw new Error(`Agent ${recipientId} already has ${result.limit} queued messages`);
item.persisted = true;
// A dispatch the store never saw removed already reached the recipient.
if (result.status === "duplicate" && result.record.state === "dispatching")
claim(item, "turn_started");
@@ -980,12 +1159,15 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const saved = records.filter((record) => !admitted.has(record.id));
if (!saved.length) return;
const restored = saved.map(
({ seq: _seq, state: _state, dispatchAttemptedAt: _at, ...record }) =>
createAdmitted(
({ seq: _seq, state: _state, dispatchAttemptedAt: _at, ...record }) => {
const item = createAdmitted(
record,
{ urgency: record.urgency, held: record.held },
receiptFor(recipientId, record.urgency ?? "queue", record.source),
),
);
item.persisted = true;
return item;
},
);
const inbox = existing ?? emptyInbox();
if (!existing && saved.every((record) => record.held)) inbox.phase = "held";
@@ -1016,6 +1198,82 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await Promise.all(writes);
}
async function enqueueMessage(
message: Message,
options: {
insertBeforeId?: string;
resolveAttachments?: () => Promise<AgentAttachment[]>;
} = {},
): Promise<AgentMessageReceipt> {
if (closed) throw new Error("Agent message delivery is closed");
const { recipientId, fingerprint } = message;
const { insertBeforeId, resolveAttachments } = options;
const attachments = [...(message.attachments ?? [])];
if (!message.text.trim() && !attachments.length && !resolveAttachments) {
throw new Error("Agent message is empty");
}
const id = message.messageId ?? randomUUID();
const queued = inboxes.get(recipientId)?.messages.find((entry) => entry.id === id);
if (queued) {
if (queued.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
await queued.saved;
return queued.receipt;
}
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
const source = message.source ?? null;
const item = createAdmitted(
{
recipientId,
id,
enqueuedAt: new Date().toISOString(),
text: message.text,
attachments,
source,
sessionMode: message.sessionMode,
providerSwitch: message.providerSwitch,
unarchive: message.unarchive !== false,
clearPendingPermissions: message.clearPendingPermissions === true,
fingerprint,
},
{ urgency: activeTurnBehavior === "queue" ? null : activeTurnBehavior, held: false },
receiptFor(recipientId, activeTurnBehavior, source),
);
item.beforeDispatch = message.beforeDispatch;
item.onDispatch = message.onDispatch;
// Admit into memory first so a lazy attachment resolver still preserves exact queue order.
if (item.state === "queued") admit(item, insertBeforeId);
item.saved = save(item, insertBeforeId, resolveAttachments);
item.saved.catch(() => undefined);
await item.saved;
announceEnqueued(recipientId, id, source);
return item.receipt;
}
function enqueueDirect(input: {
direct: DirectPrompt;
insertBeforeId?: string;
}): Promise<AgentMessageReceipt> {
const { direct, insertBeforeId } = input;
const { text, attachments } = directQueueContent(direct);
return enqueueMessage(
{
recipientId: direct.recipientId,
messageId: direct.messageId,
source: direct.source,
text,
attachments,
sessionMode: direct.sessionMode,
providerSwitch: direct.providerSwitch,
unarchive: direct.unarchive,
clearPendingPermissions: direct.clearPendingPermissions,
activeTurnBehavior: direct.activeTurnBehavior ?? "interrupt",
fingerprint: direct.fingerprint,
onDispatch: direct.onDispatch,
},
{ insertBeforeId, resolveAttachments: direct.resolveAttachments },
);
}
return {
async start({ waitForResume } = {}) {
const queues = new Map<string, PersistedQueuedMessage[]>();
@@ -1043,52 +1301,27 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
);
}
},
async enqueue(message) {
if (closed) throw new Error("Agent message delivery is closed");
const { recipientId, fingerprint } = message;
const attachments = [...(message.attachments ?? [])];
if (!message.text.trim() && !attachments.length) throw new Error("Agent message is empty");
const id = message.messageId ?? randomUUID();
const queued = inboxes.get(recipientId)?.messages.find((entry) => entry.id === id);
if (queued) {
if (queued.fingerprint !== fingerprint) throw new Error("agent_request_key_conflict");
await queued.saved;
return queued.receipt;
}
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
const source = message.source ?? null;
const item = createAdmitted(
{
recipientId,
id,
enqueuedAt: new Date().toISOString(),
text: message.text,
attachments,
source,
sessionMode: message.sessionMode,
providerSwitch: message.providerSwitch,
unarchive: message.unarchive !== false,
clearPendingPermissions: message.clearPendingPermissions === true,
fingerprint,
},
{ urgency: activeTurnBehavior === "queue" ? null : activeTurnBehavior, held: false },
receiptFor(recipientId, activeTurnBehavior, source),
);
item.beforeDispatch = message.beforeDispatch;
item.onDispatch = message.onDispatch;
item.saved = save(item);
item.saved.catch(() => undefined);
// Its place is taken now, so a Stop or a prompt sent during the write finds it.
if (item.state === "queued") admit(item);
await item.saved;
announceEnqueued(recipientId, id, source);
return item.receipt;
enqueue(message) {
return enqueueMessage(message);
},
sendDirect<Result extends PromptDispatchResult>(
async sendDirect<Result extends PromptDispatchResult>(
direct: DirectPrompt,
send: (joined: JoinedPrompt) => Promise<Result>,
): Promise<Result> {
): Promise<DirectSendResult<Result>> {
const { recipientId } = direct;
// A retried direct send whose earlier attempt was queued must return that queued entry
// rather than coalescing with itself or interrupting the turn ahead of it.
if (direct.messageId) {
const existing = inboxes
.get(recipientId)
?.messages.find((entry) => entry.id === direct.messageId);
if (existing) {
if (existing.fingerprint !== direct.fingerprint)
throw new Error("agent_request_key_conflict");
await existing.saved;
return { disposition: "queued", receipt: existing.receipt };
}
}
// Its place in line is decided now: what is queued goes with it, what comes later follows.
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
@@ -1097,15 +1330,36 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const ahead = beforeSwitch(queued);
const behind = queued.slice(ahead.length);
const stopped = inbox ? watchForStop(inbox) : () => false;
return new Promise<Result>((resolve, reject) => {
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
// the earlier group runs first under its own mode and this prompt follows on its own turn
// before any queued provider switch or later arrival.
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
return { disposition: "queued", receipt };
}
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
run(recipientId, async () => {
let riders: Admitted[] = [];
let result: Result;
try {
const dispatching = await markDispatching(
recipientId,
await prepare(recipientId, ahead),
);
const pending = closed ? [] : await prepare(recipientId, ahead);
if (
!closed &&
takesQueue &&
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
) {
const aheadSet = new Set(ahead);
const insertBeforeId = inboxes
.get(recipientId)
?.messages.find((entry) => !aheadSet.has(entry))?.id;
const receipt = await enqueueDirect({ direct, insertBeforeId });
resolve({ disposition: "queued", receipt });
return;
}
const dispatching = await markDispatching(recipientId, pending);
riders = messagesOf(dispatching);
for (const message of riders) message.state = "claimed";
for (const message of riders) message.beforeDispatch?.();
@@ -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[] = [];
@@ -443,3 +464,36 @@ test("a message that cannot be read is dropped instead of blocking the ones behi
expect(await daemon.saved("parent")).toEqual([]);
await daemon.delivery.close();
});
test("splitting an urgent release persists the urgency downgrade so a restart waits for the resumed turn", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
const planned = await queue(first.delivery, "plan-1", {
sessionMode: "plan",
activeTurnBehavior: "queue",
});
await queue(first.delivery, "direct-1", {
sessionMode: "bypassPermissions",
activeTurnBehavior: "interrupt",
});
await expect(planned.dispatched).resolves.toBe("turn_started");
await first.settle();
expect(first.sent.map(({ ids }) => ids)).toEqual([["plan-1"]]);
expect(await first.delivery.list("parent")).toMatchObject({
held: false,
items: [{ id: "direct-1", urgency: null, state: "queued" }],
});
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();
expect(second.sent).toEqual([]);
await second.endTurn();
expect(second.sent.map(({ ids }) => ids)).toEqual([["direct-1"]]);
await second.delivery.close();
});
@@ -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,220 +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,
cloneQueuedMessage,
createEmptyRecipientQueueState,
createKeyedSerializer,
enqueueIntoQueue,
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;
}
/** Creates a per-agent atomic JSON file `AgentMessageQueueStore` under `$PASEO_HOME/agent-queues/`. */
export function createJsonAgentMessageQueueStore(
paseoHome: string,
options: { onCorruptFile?: (file: CorruptQueueFile) => 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 = entries
.filter(
(entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.startsWith("."),
)
.map((entry) => entry.name.slice(0, -".json".length));
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)),
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)),
};
}
@@ -2,6 +2,7 @@ import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js
import {
assertValidRecipientId,
clearQueue,
clearUrgencyInQueue,
cloneQueuedMessage,
createEmptyRecipientQueueState,
createKeyedSerializer,
@@ -61,6 +62,8 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
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)),
@@ -134,10 +134,19 @@ export function enqueueIntoQueue(
};
}
const insertIndex = input.insertBeforeId
? current.items.findIndex((item) => item.id === input.insertBeforeId)
: -1;
const items = current.items.map(cloneQueuedMessage);
let seq = current.nextSeq;
if (insertIndex >= 0) {
seq = items[insertIndex]!.seq;
}
const record: PersistedQueuedMessage = {
id: input.id,
recipientId: input.recipientId,
seq: current.nextSeq,
seq,
enqueuedAt: input.enqueuedAt,
text: input.text,
attachments: structuredClone(input.attachments),
@@ -154,10 +163,26 @@ export function enqueueIntoQueue(
...(input.fingerprint !== undefined ? { fingerprint: input.fingerprint } : {}),
};
if (insertIndex >= 0) {
items.splice(insertIndex, 0, record);
for (let index = insertIndex + 1; index < items.length; index += 1) {
items[index]!.seq = Math.max(items[index]!.seq, items[index - 1]!.seq + 1);
}
const maxSeq = items[items.length - 1]!.seq;
return {
nextState: {
nextSeq: Math.max(current.nextSeq + 1, maxSeq + 1),
items,
},
changed: true,
result: { status: "inserted", record: cloneQueuedMessage(record) },
};
}
return {
nextState: {
nextSeq: current.nextSeq + 1,
items: sortQueuedMessages([...current.items.map(cloneQueuedMessage), record]),
items: sortQueuedMessages([...items, record]),
},
changed: true,
result: { status: "inserted", record: cloneQueuedMessage(record) },
@@ -234,6 +259,36 @@ export function revertDispatchingInQueue(
};
}
export function clearUrgencyInQueue(
current: RecipientQueueState,
ids: readonly string[],
): TransitionOutcome<void> {
if (ids.length === 0 || current.items.length === 0) {
return { nextState: current, changed: false, result: undefined };
}
const targetIds = new Set(ids);
let changed = false;
const nextItems = current.items.map((item) => {
const copy = cloneQueuedMessage(item);
if (targetIds.has(copy.id) && copy.urgency !== null) {
copy.urgency = null;
changed = true;
}
return copy;
});
if (!changed) {
return { nextState: current, changed: false, result: undefined };
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: undefined,
};
}
export function markHeldInQueue(
current: RecipientQueueState,
): TransitionOutcome<PersistedQueuedMessage[]> {
@@ -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,142 +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([]);
});
});
@@ -30,7 +30,10 @@ export interface PersistedQueuedMessage {
export type EnqueueStoreInput = Omit<
PersistedQueuedMessage,
"seq" | "state" | "dispatchAttemptedAt"
>;
> & {
/** Insert immediately before this queued item when present, preserving its position. */
insertBeforeId?: string;
};
export type EnqueueStoreResult =
| { status: "inserted"; record: PersistedQueuedMessage }
@@ -70,6 +73,7 @@ export interface AgentMessageQueueStore {
): Promise<PersistedQueuedMessage[]>;
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
promote(
recipientId: string,
targetId: string,
@@ -3,16 +3,17 @@ import {
type AgentMessageDelivery,
type AgentPromptSource,
} from "./agent-messages/index.js";
import type { DirectSendResult } from "./agent-messages/delivery.js";
import type { Logger } from "pino";
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
import type { ActiveTurnBehavior, AgentAttachment } from "@getpaseo/protocol/messages";
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
import type { AgentManager, AgentPromptSubmissionOptions, ManagedAgent } from "./agent-manager.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import type { AgentStorage } from "./agent-storage.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
export type AgentUnarchiveController = Pick<AgentManager, "notifyAgentState" | "unarchiveSnapshot">;
@@ -341,10 +342,20 @@ export interface SendPromptToAgentParams {
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
export interface SendDirectPromptParams extends SendPromptToAgentParams {
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
/** Raw message text when the caller has it, used if queueing behind a boundary. */
text?: string;
/** Raw message attachments when the caller has them, used if queueing behind a boundary. */
attachments?: readonly AgentAttachment[];
/** Lazy attachment persistence invoked only when a direct prompt is queued behind a boundary. */
resolveAttachments?: () => Promise<AgentAttachment[]>;
/** The sender's identity for retries of `messageId` when queued behind a boundary. */
fingerprint?: string;
/** Resumes a turn the daemon's restart cut off, so queued messages stay behind it. */
resumesTurn?: boolean;
}
export type SendDirectPromptResult = DirectSendResult<PromptDispatchResult>;
export interface StartCreatedAgentInitialPromptParams {
agentStorage: AgentStorage;
agentManager: AgentManager;
@@ -449,17 +460,34 @@ async function resolvePromptSource(
*/
export async function sendPromptToAgent(
params: SendDirectPromptParams,
): Promise<PromptDispatchResult> {
const { agentMessages, source, messageId, resumesTurn, ...send } = params;
): Promise<SendDirectPromptResult> {
const {
agentMessages,
source,
messageId,
text,
attachments,
resolveAttachments,
fingerprint,
resumesTurn,
...send
} = params;
return agentMessages.sendDirect(
{
recipientId: params.agentId,
prompt: params.prompt,
text,
attachments,
resolveAttachments,
uploadedImages: params.uploadedImages,
source: await resolvePromptSource(source, params.agentManager, params.agentStorage),
messageId,
sessionMode: params.sessionMode,
activeTurnBehavior: params.activeTurnBehavior === "steer" ? "steer" : "interrupt",
clearPendingPermissions: params.clearPendingPermissions,
fingerprint,
unarchive: params.unarchive,
onDispatch: params.onDispatch,
resumesTurn,
},
(joined) =>
@@ -8,6 +8,9 @@ import pino from "pino";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { createTestPaseoDaemon } from "../../../test-utils/paseo-daemon.js";
import { AgentManager } from "../../agent-manager.js";
import { createStoredAgentTimeline } from "../../timeline/index.js";
import { openTestTimelineDatabase } from "../../timeline/testing.js";
import type { ClaudeRewindSdk } from "./rewind.js";
import { ClaudeAgentClient } from "./agent.js";
import { claudeProjectDirSync } from "./project-dir.js";
@@ -17,8 +20,9 @@ import type { ClaudeQueryFactory } from "./query.js";
import { collectSessionTurnEvents } from "../test-utils/session-stream-adapter.js";
/**
* A resumed Claude agent whose transcript is missing or unreadable opens with an empty timeline.
* The daemon log at its default level has to say which, and where it looked.
* A resumed Claude agent whose transcript is missing (`ENOENT`) opens with an empty timeline.
* An unreadable transcript (`EISDIR`, `EACCES`, I/O error) must reject so `AgentManager` does not
* latch an empty timeline into `paseo.db`, while logging where it looked.
*/
const SESSION_ID = "history-load-session";
@@ -652,8 +656,13 @@ describe("ClaudeAgentSession persisted history load", () => {
},
);
test("logs the resolved transcript path when the transcript does not exist", async () => {
await (await resume()).close();
test("logs the resolved transcript path and returns empty history when the transcript does not exist", async () => {
const session = await resume();
try {
expect(await Array.fromAsync(session.streamHistory())).toEqual([]);
} finally {
await session.close();
}
expect(records).toContainEqual(
expect.objectContaining({
@@ -665,11 +674,44 @@ describe("ClaudeAgentSession persisted history load", () => {
);
});
test("logs a warning with the error when the transcript cannot be read", async () => {
test("skips a corrupt or truncated JSON line without failing transcript replay", async () => {
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
writeFileSync(
transcriptPath(),
[
JSON.stringify({ type: "user", uuid: "u1", message: { content: "before glitch" } }),
'{"type":"assistant","message":{"content":"truncated',
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "after glitch" } }),
].join("\n"),
);
const session = await resume();
try {
const history = await Array.fromAsync(session.streamHistory());
expect(history).toEqual([
{
type: "timeline",
provider: "claude",
timestamp: undefined,
item: { type: "user_message", text: "before glitch", messageId: "u1" },
},
{
type: "timeline",
provider: "claude",
timestamp: undefined,
item: { type: "assistant_message", text: "after glitch", messageId: "a1" },
},
]);
} finally {
await session.close();
}
});
test("rejects and logs a warning when the transcript cannot be read", async () => {
// A directory at the transcript path exists but cannot be read as a file.
mkdirSync(transcriptPath(), { recursive: true });
await (await resume()).close();
await expect(resume()).rejects.toThrow(/EISDIR/);
expect(records).toContainEqual(
expect.objectContaining({
@@ -682,6 +724,230 @@ describe("ClaudeAgentSession persisted history load", () => {
);
});
test("leaves agent unregistered with no paseo.db row on unreadable transcript, then imports full history on retry", async () => {
const database = openTestTimelineDatabase();
const timeline = createStoredAgentTimeline(database);
const client = new ClaudeAgentClient({
logger: pino({ level: "info" }, { write: (line: string) => records.push(JSON.parse(line)) }),
queryFactory: () => {
throw new Error("history load must not start a query");
},
resolveBinary: async () => process.execPath,
resolveVersion: async () => "2.1.220",
});
const manager = new AgentManager({
clients: { claude: client },
logger: pino({ level: "silent" }),
timeline,
});
// Make the transcript path unreadable (directory -> EISDIR on all platforms).
mkdirSync(transcriptPath(), { recursive: true });
const agentId = "00000000-0000-4000-8000-000000000001";
const handle = { provider: "claude" as const, sessionId: SESSION_ID };
try {
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
/EISDIR/,
);
expect(manager.getAgent(agentId)).toBeNull();
expect(await manager.hasStoredHistory(agentId)).toBe(false);
expect(
database.read((sql) =>
sql.all("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?", agentId),
),
).toEqual([]);
// Restore a readable transcript and retry: full history must now import cleanly.
rmSync(transcriptPath(), { recursive: true, force: true });
writeFileSync(
transcriptPath(),
[
JSON.stringify({ type: "user", uuid: "u1", message: { content: "hello" } }),
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "world" } }),
].join("\n"),
);
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
expect(await manager.hasStoredHistory(agentId)).toBe(true);
const items = await manager.getTimeline(agentId);
expect(items).toEqual([
{ type: "user_message", text: "hello", messageId: "u1" },
{ type: "assistant_message", text: "world", messageId: "a1" },
]);
} finally {
await manager.closeAgent(agentId).catch(() => undefined);
}
});
// chmod does not remove read access on Windows, or for root.
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"propagates EACCES on unreadable transcript without latching empty history, then succeeds on retry",
async () => {
const database = openTestTimelineDatabase();
const timeline = createStoredAgentTimeline(database);
const client = new ClaudeAgentClient({
logger: pino(
{ level: "info" },
{ write: (line: string) => records.push(JSON.parse(line)) },
),
queryFactory: () => {
throw new Error("history load must not start a query");
},
resolveBinary: async () => process.execPath,
resolveVersion: async () => "2.1.220",
});
const manager = new AgentManager({
clients: { claude: client },
logger: pino({ level: "silent" }),
timeline,
});
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
writeFileSync(
transcriptPath(),
[
JSON.stringify({ type: "user", uuid: "u1", message: { content: "secret prompt" } }),
JSON.stringify({ type: "assistant", uuid: "a1", message: { content: "secret reply" } }),
].join("\n"),
);
chmodSync(transcriptPath(), 0o000);
const agentId = "00000000-0000-4000-8000-000000000002";
const handle = { provider: "claude" as const, sessionId: SESSION_ID };
try {
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
/EACCES/,
);
expect(manager.getAgent(agentId)).toBeNull();
expect(await manager.hasStoredHistory(agentId)).toBe(false);
chmodSync(transcriptPath(), 0o600);
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
expect(await manager.hasStoredHistory(agentId)).toBe(true);
const items = await manager.getTimeline(agentId);
expect(items).toEqual([
{ type: "user_message", text: "secret prompt", messageId: "u1" },
{ type: "assistant_message", text: "secret reply", messageId: "a1" },
]);
} finally {
chmodSync(transcriptPath(), 0o600);
await manager.closeAgent(agentId).catch(() => undefined);
}
},
);
test("rejects waiting readers and resets history readiness when rebind transcript load fails, then succeeds on retry", async () => {
const entries = [
{ type: "user", uuid: "u1", message: { content: "first" } },
{ type: "assistant", uuid: "a1", message: { content: "first reply" } },
{ type: "user", uuid: "u2", message: { content: "second" } },
];
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
writeFileSync(transcriptPath(), entries.map((entry) => JSON.stringify(entry)).join("\n"));
const forkId = "retryable-fork";
const forkFile = path.join(path.dirname(transcriptPath()), `${forkId}.jsonl`);
// Make the forked transcript unreadable on the initial rebind read.
mkdirSync(forkFile, { recursive: true });
let releaseRetirement!: () => void;
const retirementGate = new Promise<void>((resolve) => {
releaseRetirement = resolve;
});
let retirementStarted!: () => void;
const retiring = new Promise<void>((resolve) => {
retirementStarted = resolve;
});
let pendingRead: ((value: unknown) => void) | undefined;
let firstQuery = true;
const queryFactory = ((input) => {
if (!firstQuery) return replyFactory("live reply")(input);
firstQuery = false;
const messages = [
{ type: "assistant", uuid: "before-rebind", message: { content: "before rebind" } },
{ type: "result", subtype: "success", total_cost_usd: 0 },
];
return {
async next() {
const value = messages.shift();
if (value) return { done: false, value };
return new Promise((resolve) => {
pendingRead = resolve;
});
},
close() {
pendingRead?.({ done: true, value: undefined });
},
async return() {
retirementStarted();
await retirementGate;
return { done: true, value: undefined };
},
async supportedCommands() {
return [];
},
[Symbol.asyncIterator]() {
return this;
},
};
}) as ClaudeQueryFactory;
const session = await resume(queryFactory, {
async forkSession() {
return { sessionId: forkId };
},
});
try {
await Array.fromAsync(session.streamHistory());
await collectSessionTurnEvents(session, "before rewind");
const rewind = session.revertConversation!({ messageId: "u2" });
await retiring;
// Attach a reader while rebind is in flight; it must receive the EISDIR error, not [].
const waitingRead = Array.fromAsync(session.streamHistory());
releaseRetirement();
await rewind;
await expect(waitingRead).rejects.toThrow(/EISDIR/);
// A subsequent read while still unreadable also rejects (no empty latching).
await expect(Array.fromAsync(session.streamHistory())).rejects.toThrow(/EISDIR/);
// Restoring the transcript lets a retry on the same session load full forked history.
rmSync(forkFile, { recursive: true, force: true });
writeFileSync(
forkFile,
entries
.slice(0, 2)
.map((entry) => JSON.stringify(entry))
.join("\n"),
);
const retried = await Array.fromAsync(session.streamHistory());
expect(retried).toEqual([
{
type: "timeline",
provider: "claude",
timestamp: undefined,
item: { type: "user_message", text: "first", messageId: "u1" },
},
{
type: "timeline",
provider: "claude",
timestamp: undefined,
item: { type: "assistant_message", text: "first reply", messageId: "a1" },
},
]);
} finally {
releaseRetirement();
await session.close();
}
});
test("replays a message steered into a running turn as the user's message", async () => {
const queued = (commandMode: string, prompt: unknown, sourceUuid?: string) => ({
type: "attachment",
@@ -839,14 +1105,14 @@ describe("ClaudeAgentSession persisted history load", () => {
// chmod does not remove read access on Windows, or for root.
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"logs a warning with the error when Claude's project folders cannot be listed",
"rejects and logs a warning with the error when Claude's project folders cannot be listed",
async () => {
// The transcript is not under cwd's folder, so the lookup lists the other project folders.
mkdirSync(path.join(configDir, "projects"), { recursive: true });
chmodSync(path.join(configDir, "projects"), 0o000);
try {
await (await resume()).close();
await expect(resume()).rejects.toThrow(/EACCES/);
} finally {
chmodSync(path.join(configDir, "projects"), 0o755);
}
@@ -260,6 +260,9 @@ describe("importing a renamed Claude session", () => {
const imported = await importSession(sessionId);
expect(imported.config.title).toBe("Slow query hunt");
expect(imported.timeline.map((entry) => entry.item)).toContainEqual(
expect.objectContaining({ type: "user_message", text: "Trace the slow query" }),
);
});
test("reads the rename from behind more records than one read covers", async () => {
@@ -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([
{
@@ -1887,8 +1887,13 @@ export class ClaudeAgentClient implements AgentClient {
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
return session;
try {
await session.ensureHistoryReady();
return session;
} catch (error) {
await session.close();
throw error;
}
}
async getCatalogCacheKey(_options: FetchCatalogOptions): Promise<string> {
@@ -2689,7 +2694,7 @@ class ClaudeAgentSession implements AgentSession {
{ type: "provider_subagent" }
>[] = [];
private historyPending = false;
// Readiness never rejects; history/rebind failures are logged at their owning boundary.
// Clears back to null when a transcript read fails so a retry re-reads from disk.
private historyReady: Promise<void> | null = null;
private historySessionId: string | null = null;
private replayingHistory = false;
@@ -3501,7 +3506,7 @@ class ClaudeAgentSession implements AgentSession {
"provider.claude.session_close.start",
);
this.closed = true;
await this.ensureHistoryReady();
await this.historyReady?.catch(() => {});
this.rejectAllPendingPermissions(new Error("Claude session closed"));
// AgentManager settles the run after runtime release. Preserve cleanup records
// without reporting this closure as an explicit turn cancellation.
@@ -3845,9 +3850,19 @@ class ClaudeAgentSession implements AgentSession {
]);
}
})();
this.historyReady = rebind.catch((error) => {
const tracked = rebind.catch((error) => {
this.logger.warn({ err: error, sessionId }, "Failed to rebind Claude session");
if (this.historySessionId === sessionId) {
if (this.historyReady === tracked) {
this.historyReady = null;
}
throw error;
}
});
// Avoid an unhandled rejection if no reader is awaiting `historyReady`, while still
// propagating the read error to any reader already waiting on the rebound history.
tracked.catch(() => {});
this.historyReady = tracked;
return rebind;
}
@@ -6143,9 +6158,18 @@ class ClaudeAgentSession implements AgentSession {
ensureHistoryReady(): Promise<void> {
if (!this.historyReady) {
this.historyReady = this.historySessionId
? this.loadPersistedHistory(this.historySessionId)
: Promise.resolve();
if (!this.historySessionId) {
this.historyReady = Promise.resolve();
} else {
const load = this.loadPersistedHistory(this.historySessionId);
const pending = load.catch((error) => {
if (this.historyReady === pending) {
this.historyReady = null;
}
throw error;
});
this.historyReady = pending;
}
}
return this.historyReady;
}
@@ -6164,36 +6188,70 @@ class ClaudeAgentSession implements AgentSession {
return;
}
await withClaudeReplayHistory(historyPath, async (history) => {
const replay = await this.ingestPersistedSidechains(history);
await this.ingestPersistedHistory(history.parentEntries, replay);
const providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[] =
[];
const replay = await this.ingestPersistedSidechains(history, providerSubagentEvents);
const timeline = await this.ingestPersistedHistory(
history.parentEntries,
replay,
providerSubagentEvents,
);
if (providerSubagentEvents.length > 0) {
this.persistedProviderSubagentEvents = [
...this.persistedProviderSubagentEvents,
...providerSubagentEvents,
];
this.historyPending = true;
}
if (timeline.length > 0) {
this.persistedHistory = [...this.persistedHistory, ...timeline];
this.historyPending = true;
}
});
} catch (error) {
this.resetPersistedHistoryReplayState();
if (historyPath && isMissingTranscriptError({ error, historyPath })) {
this.logger.info(
{ sessionId, cwd: this.config.cwd, historyPath },
"No Claude transcript to load history from",
);
return;
}
this.logger.warn(
{ err: error, sessionId, historyPath },
"Failed to load Claude history from transcript",
);
throw error;
} finally {
this.replayingHistory = false;
}
}
private resetPersistedHistoryReplayState(): void {
this.persistedHistory = [];
this.persistedProviderSubagentEvents = [];
this.historyPending = false;
this.userMessageIds = [];
this.rewindTurnAnchors.length = 0;
this.taskState.reset();
this.taskProtocolSource.reset();
}
private async ingestPersistedHistory(
entries: Iterable<ClaudeHistoryEntry> | AsyncIterable<ClaudeHistoryEntry>,
replay: ClaudeReplayOwnership,
): Promise<void> {
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
): Promise<PersistedTimelineEntry[]> {
const timeline: PersistedTimelineEntry[] = [];
for await (const entry of entries) {
await this.ingestPersistedHistoryEntry(entry, timeline, replay);
}
if (timeline.length > 0) {
this.persistedHistory = [...this.persistedHistory, ...timeline];
this.historyPending = true;
await this.ingestPersistedHistoryEntry(entry, timeline, replay, providerSubagentEvents);
}
return timeline;
}
private async ingestPersistedSidechains(
history: ClaudeReplayHistory,
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
): Promise<ClaudeReplayOwnership> {
const sidecarToolCallIdsByTaskId = new Map<string, string>();
for (const { agentId, meta } of history.subagents) {
@@ -6245,13 +6303,12 @@ class ClaudeAgentSession implements AgentSession {
if (observations.length === 0) return replay;
for (const event of foldSubagentObservations(observations)) {
this.persistedProviderSubagentEvents.push({
providerSubagentEvents.push({
type: "provider_subagent",
provider: "claude",
event,
});
}
this.historyPending = true;
return replay;
}
@@ -6259,6 +6316,7 @@ class ClaudeAgentSession implements AgentSession {
entry: ClaudeHistoryEntry,
timeline: PersistedTimelineEntry[],
replay: ClaudeReplayOwnership,
providerSubagentEvents: Extract<AgentStreamEvent, { type: "provider_subagent" }>[],
): Promise<void> {
if (entry.isSidechain) {
return;
@@ -6274,7 +6332,7 @@ class ClaudeAgentSession implements AgentSession {
: undefined;
if (notificationOwner) {
for (const item of await this.convertHistoryEntry(entry)) {
this.persistedProviderSubagentEvents.push({
providerSubagentEvents.push({
type: "provider_subagent",
provider: "claude",
event: {
@@ -7322,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 } } {
@@ -7354,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") {
@@ -7952,3 +8038,8 @@ async function transcriptExists(file: string): Promise<boolean> {
throw error;
}
}
function isMissingTranscriptError(input: { error: unknown; historyPath: string }): boolean {
const err = input.error as NodeJS.ErrnoException | null;
return err?.code === "ENOENT" && err.path === input.historyPath;
}
@@ -1,3 +1,4 @@
import { constants as bufferConstants } from "node:buffer";
import { assignTaskNotificationReplayIds } from "./task-notification-tool-call.js";
import fs, { type FileHandle } from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
@@ -46,6 +47,7 @@ async function* locatedRecords(
let offset = 0;
let pieces: Buffer[] = [];
let length = 0;
let oversized = false;
while (remaining > 0) {
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null);
@@ -59,37 +61,54 @@ async function* locatedRecords(
await setImmediate();
sliceStartedAt = performance.now();
}
pieces.push(buffer.subarray(start, end));
length += end - start;
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
const location = {
file,
offset,
length,
timestamp: normalizeProviderReplayTimestamp(entry?.timestamp),
};
if (!oversized && length <= bufferConstants.MAX_STRING_LENGTH) {
pieces.push(buffer.subarray(start, end));
const entry = parseRecordBuffer({ pieces, length });
if (entry) {
yield {
entry,
location: {
file,
offset,
length,
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
},
};
}
}
offset += length + 1;
pieces = [];
length = 0;
if (entry) yield { entry, location };
oversized = false;
start = end + 1;
}
if (start < count) {
pieces.push(buffer.subarray(start, count));
length += count - start;
// A single JSONL line longer than V8's max string length can never be parsed; drop its
// buffered slices immediately while tracking byte length so subsequent line offsets stay exact.
if (oversized || length > bufferConstants.MAX_STRING_LENGTH) {
oversized = true;
pieces = [];
} else {
pieces.push(buffer.subarray(start, count));
}
}
}
if (!oversized && length > 0 && length <= bufferConstants.MAX_STRING_LENGTH) {
const entry = parseRecordBuffer({ pieces, length });
if (entry) {
yield {
entry,
location: {
file,
offset,
length,
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
},
};
}
}
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
if (entry)
yield {
entry,
location: {
file,
offset,
length,
timestamp: normalizeProviderReplayTimestamp(entry.timestamp),
},
};
}
/** Indexed sources parse only their own records using descriptors owned by this replay. */
@@ -156,6 +175,21 @@ function isToolResult(entry: TranscriptEntry): boolean {
);
}
function parseRecordBuffer(input: {
pieces: readonly Buffer[];
length: number;
}): TranscriptEntry | null {
try {
const line =
input.pieces.length === 1
? input.pieces[0]!.toString("utf8")
: Buffer.concat(input.pieces, input.length).toString("utf8");
return parseRecord(line);
} catch {
return null;
}
}
function parseRecord(line: string): TranscriptEntry | null {
try {
const value: unknown = JSON.parse(line);
@@ -397,5 +397,146 @@ describe("OMP tool call mapper", () => {
),
).toEqual({ type: "plain_text", label: "Rollout scope", text: "Ask interrupted by message" });
});
test("uses a lone checkbox option label as the question and Yes as its checked answer", () => {
const checkboxHtml =
'<form><label><input type="checkbox" name="agree" value="yes">I accept the terms</label></form>';
expect(mapOmpToolDetail(parseToolArgs("ask", { html: checkboxHtml }), null)).toMatchObject({
type: "plain_text",
label: "I accept the terms",
});
expect(
mapOmpToolDetail(
parseToolArgs("ask", { html: checkboxHtml }),
parseToolResult({
content: [{ type: "text", text: 'User answers:\n{\n "agree": "yes"\n}' }],
details: {
answers: [
{
name: "agree",
question: "I accept the terms",
answer: "I accept the terms",
},
],
},
}),
),
).toEqual({
type: "plain_text",
label: "I accept the terms",
text: "I accept the terms\nYes",
});
expect(
mapOmpToolDetail(
parseToolArgs("ask", { html: checkboxHtml }),
parseToolResult({
content: [{ type: "text", text: 'User answers:\n{\n "agree": "yes"\n}' }],
}),
),
).toEqual({
type: "plain_text",
label: "I accept the terms",
text: "I accept the terms\nYes",
});
});
test("maps multi-field details.answers and handles missing question, missing name, and empty answers", () => {
const multiHtml = [
"<form>",
" <fieldset>",
" <legend>Rollout scope</legend>",
' <label><input type="radio" name="scope" value="one">Staging only</label>',
" </fieldset>",
' <label>Notes <textarea name="notes"></textarea></label>',
"</form>",
].join("\n");
expect(
mapOmpToolDetail(
parseToolArgs("ask", { html: multiHtml }),
parseToolResult({
content: [{ type: "text", text: 'User answers:\n{"scope":"one","notes":""}' }],
details: {
answers: [
{ name: "scope", answer: "Staging only" },
{ question: "Extra question", answer: "Custom reply" },
{ name: "notes", question: "Notes", answer: "" },
],
},
}),
),
).toEqual({
type: "plain_text",
label: "Rollout scope",
text: "Rollout scope\nStaging only\n\nExtra question\nCustom reply",
});
});
test("maps checkbox arrays, free-text fields, unmatched options, and skips empty values in User answers", () => {
const multiHtml = [
"<form>",
" <p>Which tools?</p>",
' <label><input type="checkbox" name="tools" value="d">Docker</label>',
' <label><input type="checkbox" name="tools" value="k">Kubernetes</label>',
' <label>Days <input type="number" name="days"></label>',
' <label>Note <textarea name="note"></textarea></label>',
' <label>Optional <input type="text" name="optional"></label>',
"</form>",
].join("\n");
expect(
mapOmpToolDetail(
parseToolArgs("ask", { html: multiHtml }),
parseToolResult({
content: [
{
type: "text",
text: 'User answers:\n{"tools":["d","custom-cli"],"days":7,"note":"keep logs","optional":""}',
},
],
}),
),
).toEqual({
type: "plain_text",
label: "Which tools?",
text: "Which tools?\nDocker, custom-cli\n\nDays\n7\n\nNote\nkeep logs",
});
});
test("falls back to raw text with the form question when User answers JSON is malformed", () => {
expect(
mapOmpToolDetail(
parseToolArgs("ask", { html }),
parseToolResult({
content: [{ type: "text", text: "User answers:\n{not valid json" }],
}),
),
).toEqual({
type: "plain_text",
label: "Rollout scope",
text: "User answers:\n{not valid json",
});
});
test("preserves legacy multi-question details.results mapping", () => {
expect(
mapOmpToolDetail(
parseToolArgs("ask", {
questions: [{ question: "Which colors?" }, { question: "Which shape?" }],
}),
parseToolResult({
content: [{ type: "text", text: "raw" }],
details: {
results: [
{ question: "Which colors?", selectedOptions: ["Red", "Blue"] },
{ question: "Which shape?", customInput: "Hexagon" },
],
},
}),
),
).toEqual({
type: "plain_text",
label: "Which colors?",
text: "Which colors?\nRed, Blue\n\nWhich shape?\nHexagon",
});
});
});
});
@@ -124,7 +124,8 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
const details =
result && typeof result !== "string" && isRecord(result.details) ? result.details : {};
const form = readAskForm(args.html);
const formLines = readFormAnswers(details, form, extractTextFromToolResult(result));
const resultText = extractTextFromToolResult(result);
const formLines = readFormAnswers({ details, form, resultText });
const answers = Array.isArray(details.results) ? details.results : [details];
const lines =
formLines ??
@@ -138,7 +139,8 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
[...selected, firstString(answer.customInput)].filter(Boolean).join(", ") || "No selection";
return question ? [`${question}\n${response}`] : [];
});
const text = lines.length ? lines.join("\n\n") : extractTextFromToolResult(result);
const text = lines.length ? lines.join("\n\n") : resultText;
const firstFormQuestion = form?.fields[0] ? formFieldQuestion(form.fields[0]) : undefined;
return {
type: "plain_text",
label:
@@ -146,7 +148,7 @@ function mapOmpAskDetail(rawArgs: unknown, result: OmpToolResult): ToolCallDetai
details.question,
formLines?.[0]?.split("\n", 1)[0],
askedQuestion,
form?.fields[0] && formFieldQuestion(form.fields[0]),
firstFormQuestion?.split("\n", 1)[0],
args.question,
args.title,
) ?? "Question",
@@ -164,17 +166,24 @@ function readAskForm(html: unknown): OmpHtmlForm | undefined {
}
}
/** A field's question: the last paragraph of its prompt, which is its legend or label. */
/** A field's question: the last paragraph of its prompt (legend/label), a lone option's label, or its name. */
function formFieldQuestion(field: OmpFormField): string | undefined {
const loneOptionLabel =
field.kind === "choice" && field.options.length === 1 ? field.options[0]?.label : undefined;
return firstString(
field.prompt
.split(/\n\s*\n/)
.at(-1)
?.trim(),
loneOptionLabel,
field.name,
);
}
function isLoneCheckbox(field: OmpFormField | undefined): boolean {
return field?.kind === "choice" && field.control === "checkbox" && field.options.length === 1;
}
/**
* The answers to an HTML-form ask, one `question\nanswer` block per field.
* OMP 19 reports them in `details.answers` (`{ name, question, answer }`,
@@ -182,17 +191,20 @@ function formFieldQuestion(field: OmpFormField): string | undefined {
* (`User answers:\n{ "<name>": "<value>" }`) is read against the form so a
* chosen value shows as its option's text.
*/
function readFormAnswers(
details: Record<string, unknown>,
form: OmpHtmlForm | undefined,
resultText: string | undefined,
): string[] | undefined {
function readFormAnswers(input: {
details: Record<string, unknown>;
form: OmpHtmlForm | undefined;
resultText: string | undefined;
}): string[] | undefined {
const { details, form, resultText } = input;
if (Array.isArray(details.answers)) {
const lines = details.answers.flatMap((entry) => {
if (!isRecord(entry)) return [];
const field = form?.fields.find((candidate) => candidate.name === entry.name);
const question = firstString(entry.question, field && formFieldQuestion(field), entry.name);
const answer = formatFormAnswer(entry.answer);
const rawAnswer = formatFormAnswer(entry.answer);
const answer =
rawAnswer && isLoneCheckbox(field) && rawAnswer === question ? "Yes" : rawAnswer;
return question && answer ? [`${question}\n${answer}`] : [];
});
if (lines.length) return lines;
@@ -201,15 +213,18 @@ function readFormAnswers(
const values = readUserAnswersText(resultText);
if (!values) return undefined;
const lines = form.fields.flatMap((field) => {
if (!(field.name in values)) return [];
if (!Object.hasOwn(values, field.name)) return [];
const question = formFieldQuestion(field);
const raw = values[field.name];
const chosen = (Array.isArray(raw) ? raw : [raw]).map((value) => {
const option =
field.kind === "choice" ? field.options.find((entry) => entry.value === value) : undefined;
return option?.label ?? formatFormAnswer(value);
if (option && isLoneCheckbox(field) && option.label === question) {
return "Yes";
}
return firstString(option?.label, formatFormAnswer(value));
});
const answer = chosen.filter(Boolean).join(", ");
const question = formFieldQuestion(field);
return question && answer ? [`${question}\n${answer}`] : [];
});
return lines.length ? lines : undefined;
@@ -4,6 +4,9 @@ import os from "node:os";
import path from "node:path";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { AgentManager } from "../agent-manager.js";
import { createStoredAgentTimeline } from "../timeline/index.js";
import { openTestTimelineDatabase } from "../timeline/testing.js";
import type { Event as OpenCodeEvent } from "@opencode-ai/sdk/v2/client";
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client";
import type { OpenCodeEventSource } from "./opencode/event-consumer.js";
@@ -2343,6 +2346,229 @@ describe("OpenCode adapter startTurn error handling", () => {
]);
});
test("streamHistory throws when session.messages fails or returns no data", async () => {
const errorClient = {
session: {
get: async () => ({ data: { revert: undefined }, error: undefined }),
messages: async () => ({
data: undefined,
error: { name: "ServerError", message: "backend unavailable" },
}),
},
} as never;
const errorSession = new __openCodeInternals.OpenCodeAgentSession(
{ provider: "opencode", cwd: "/tmp/repo" },
errorClient,
"ses_msg_error",
createTestLogger(),
{},
);
await expect(Array.fromAsync(errorSession.streamHistory())).rejects.toThrow(
/Failed to load OpenCode session messages for ses_msg_error.*backend unavailable/,
);
const emptyClient = {
session: {
get: async () => ({ data: { revert: undefined }, error: undefined }),
messages: async () => ({ data: undefined, error: undefined }),
},
} as never;
const emptySession = new __openCodeInternals.OpenCodeAgentSession(
{ provider: "opencode", cwd: "/tmp/repo" },
emptyClient,
"ses_msg_empty",
createTestLogger(),
{},
);
await expect(Array.fromAsync(emptySession.streamHistory())).rejects.toThrow(
/Failed to load OpenCode session messages for ses_msg_empty.*empty response/,
);
});
test("streamHistory throws when session.get fails on a reverted session, then filters reverted turns on retry", async () => {
let failGet = true;
let messagesCalls = 0;
const fakeClient = {
session: {
get: async () =>
failGet
? {
data: undefined,
error: { name: "NotFoundError", message: "session missing" },
}
: {
data: { revert: { messageID: "msg_reverted" } },
error: undefined,
},
messages: async () => {
messagesCalls += 1;
return {
data: [
{
info: { id: "msg_kept", sessionID: "ses_get_error", role: "user" },
parts: [
{
id: "prt_kept",
sessionID: "ses_get_error",
messageID: "msg_kept",
type: "text",
text: "kept prompt",
},
],
},
{
info: { id: "msg_reverted", sessionID: "ses_get_error", role: "user" },
parts: [
{
id: "prt_reverted",
sessionID: "ses_get_error",
messageID: "msg_reverted",
type: "text",
text: "reverted prompt",
},
],
},
],
error: undefined,
};
},
},
} as never;
const session = new __openCodeInternals.OpenCodeAgentSession(
{ provider: "opencode", cwd: "/tmp/repo" },
fakeClient,
"ses_get_error",
createTestLogger(),
{},
);
await expect(Array.fromAsync(session.streamHistory())).rejects.toThrow(
/Failed to load OpenCode session ses_get_error.*session missing/,
);
expect(messagesCalls).toBe(0);
failGet = false;
expect(await Array.fromAsync(session.streamHistory())).toEqual([
{
type: "timeline",
provider: "opencode",
item: { type: "user_message", text: "kept prompt", messageId: "msg_kept" },
},
]);
});
test("leaves agent unregistered with no paseo.db row when session.messages fails, then imports on retry", async () => {
const cwd = mkdtempSync(path.join(os.tmpdir(), "opencode-history-retry-"));
const database = openTestTimelineDatabase();
const timeline = createStoredAgentTimeline(database);
let failMessages = true;
const fakeSdkClient = {
session: {
get: async () => ({ data: { revert: undefined }, error: undefined }),
messages: async () => {
if (failMessages) {
return {
data: undefined,
error: { name: "NetworkError", message: "temporary RPC outage" },
};
}
return {
data: [
{
info: { id: "msg_user", sessionID: "ses_retry", role: "user" },
parts: [
{
id: "prt_user",
sessionID: "ses_retry",
messageID: "msg_user",
type: "text",
text: "hello opencode",
},
],
},
{
info: { id: "msg_assistant", sessionID: "ses_retry", role: "assistant" },
parts: [
{
id: "prt_assistant",
sessionID: "ses_retry",
messageID: "msg_assistant",
type: "text",
text: "recovered reply",
},
],
},
],
error: undefined,
};
},
abort: async () => ({ data: undefined, error: undefined }),
},
app: {
agents: async () => ({ data: [], error: undefined }),
},
command: {
list: async () => ({ data: [], error: undefined }),
},
} as never;
const fakeProviderClient = {
provider: "opencode" as const,
capabilities: {},
isAvailable: async () => true,
startSession: async () => {
throw new Error("not used");
},
resumeSession: async (handle: { sessionId: string }, overrides?: { cwd?: string }) =>
new __openCodeInternals.OpenCodeAgentSession(
{ provider: "opencode", cwd: overrides?.cwd ?? cwd },
fakeSdkClient,
handle.sessionId,
createTestLogger(),
{},
),
};
const manager = new AgentManager({
clients: { opencode: fakeProviderClient as never },
logger: createTestLogger(),
timeline,
});
const agentId = "00000000-0000-4000-8000-000000000010";
const handle = { provider: "opencode" as const, sessionId: "ses_retry" };
try {
await expect(manager.resumeAgentFromPersistence(handle, { cwd }, agentId)).rejects.toThrow(
/temporary RPC outage/,
);
expect(manager.getAgent(agentId)).toBeNull();
expect(await manager.hasStoredHistory(agentId)).toBe(false);
expect(
database.read((sql) =>
sql.all("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?", agentId),
),
).toEqual([]);
failMessages = false;
await manager.resumeAgentFromPersistence(handle, { cwd }, agentId);
expect(await manager.hasStoredHistory(agentId)).toBe(true);
expect(await manager.getTimeline(agentId)).toEqual([
{ type: "user_message", text: "hello opencode", messageId: "msg_user" },
{ type: "assistant_message", text: "recovered reply", messageId: "msg_assistant" },
]);
} finally {
await manager.closeAgent(agentId).catch(() => undefined);
rmSync(cwd, { recursive: true, force: true });
}
});
test("emits turn_failed when client.session.promptAsync throws synchronously", async () => {
// Yield the server-connected event, then park forever. The adapter waits
// for that first event before sending the prompt.
@@ -4946,19 +4946,27 @@ class OpenCodeAgentSession implements AgentSession {
sessionID: this.sessionId,
directory: this.config.cwd,
});
if (sessionResponse.error || !sessionResponse.data) {
throw new Error(
`Failed to load OpenCode session ${this.sessionId}: ${
sessionResponse.error ? toDiagnosticErrorMessage(sessionResponse.error) : "empty response"
}`,
);
}
const response = await this.client.session.messages({
sessionID: this.sessionId,
directory: this.config.cwd,
});
if (response.error || !response.data) {
return;
throw new Error(
`Failed to load OpenCode session messages for ${this.sessionId}: ${
response.error ? toDiagnosticErrorMessage(response.error) : "empty response"
}`,
);
}
const messages = filterOpenCodeRevertedMessages(
response.data,
sessionResponse.error ? null : sessionResponse.data?.revert,
);
const messages = filterOpenCodeRevertedMessages(response.data, sessionResponse.data.revert);
for (const message of messages) {
for (const event of buildOpenCodeReplayTimelineEvents(message)) {
yield event;
@@ -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(
@@ -118,22 +118,24 @@ class CountingDatabase implements DaemonDatabase {
describe("SQLite timeline backend against the memory backend", () => {
it("stores the same history and serves the same pages on seeded randomized timelines", () => {
const random = seededRandom(0x5eed_0001);
const memory = new MemoryTimelineBackend();
const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase());
const backends = [memory, sqlite] as const;
for (let scenario = 0; scenario < 40; scenario++) {
const memory = new MemoryTimelineBackend();
const sqlite = new SqliteTimelineBackend(openTestTimelineDatabase());
const backends = [memory, sqlite] as const;
for (const backend of backends) backend.create(scope, { epoch: "e" });
const scenarioScope: TimelineScope = { agentId: `agent-${scenario}` };
const seededScope: TimelineScope = { agentId: `seeded-${scenario}` };
for (const backend of backends) backend.create(scenarioScope, { epoch: "e" });
let turn = 0;
for (let step = 0; step < 120; step++) {
const roll = random(20);
const identity = String(random(6));
const text = `${scenario}-${step}`;
if (roll === 0) {
const prompts = memory.promptRows(scope);
const prompts = memory.promptRows(scenarioScope);
if (prompts.length > 0) {
const retireFromSeq = prompts[random(prompts.length)].seqStart;
const results = backends.map((backend) =>
backend.retire(scope, { retireFromSeq, selectChildren: () => [] }),
backend.retire(scenarioScope, { retireFromSeq, selectChildren: () => [] }),
);
expect(results[1]).toEqual(results[0]);
}
@@ -143,7 +145,11 @@ describe("SQLite timeline backend against the memory backend", () => {
const turnId = random(2) === 0 ? String(turn) : undefined;
const metrics = [{ name: "tokens", value: step }] as never;
const results = backends.map((backend) =>
backend.stampTurnMetrics(scope, metrics, turnId === undefined ? {} : { turnId }),
backend.stampTurnMetrics(
scenarioScope,
metrics,
turnId === undefined ? {} : { turnId },
),
);
expect(results[1]).toEqual(results[0]);
continue;
@@ -151,7 +157,7 @@ describe("SQLite timeline backend against the memory backend", () => {
if (roll === 2) {
const clientMessageId = `client-${random(step + 1)}`;
const results = backends.map((backend) =>
backend.attachProviderMessageId(scope, clientMessageId, `provider-${step}`),
backend.attachProviderMessageId(scenarioScope, clientMessageId, `provider-${step}`),
);
expect(results[1]).toEqual(results[0]);
continue;
@@ -174,16 +180,16 @@ describe("SQLite timeline backend against the memory backend", () => {
},
];
const next = entry(items[random(items.length)], { turnId: String(turn) });
const retired = backends.map((backend) => backend.isRetired(scope, next));
const retired = backends.map((backend) => backend.isRetired(scenarioScope, next));
expect(retired[1]).toBe(retired[0]);
const results = backends.map((backend) => backend.append(scope, [next]));
const results = backends.map((backend) => backend.append(scenarioScope, [next]));
expect(results[1]).toEqual(results[0]);
}
expectSameHistory(memory, sqlite);
expectSameHistory(memory, sqlite, scenarioScope);
// Seeding from projected rows, as an import does, keeps both in step too.
const rows = memory.readRows(scope);
for (const backend of backends) backend.create({ agentId: "seeded" }, { rows, epoch: "e" });
expectSameHistory(memory, sqlite, { agentId: "seeded" });
const rows = memory.readRows(scenarioScope);
for (const backend of backends) backend.create(seededScope, { rows, epoch: "e" });
expectSameHistory(memory, sqlite, seededScope);
}
});
});
@@ -3,6 +3,7 @@ import { changeRequestStatusSchema } from "../../../services/change-request-sour
import { registerPluginTools } from "./plugin-tools.js";
import type { FinishSubscriptions, FinishRegistration } from "../finish-subscriptions/index.js";
import type { AgentMessageDelivery } from "../agent-messages/index.js";
import type { AgentMessageReceipt } from "../agent-messages/delivery.js";
import {
createHostResolver,
HostOperationRejectedError,
@@ -71,6 +72,7 @@ import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode
import type { CreatePaseoWorktreeWorkflowFn } from "../../worktree-session.js";
import { computeNextRunAt, validateScheduleCadence } from "../../schedule/cron.js";
import {
InvalidScheduleIdError,
ScheduleNotFoundError,
ScheduleStateConflictError,
type ScheduleService,
@@ -1136,7 +1138,7 @@ function createToolCatalog(
try {
schedule = await scheduleService.inspect(id);
} catch (error) {
if (error instanceof ScheduleNotFoundError) {
if (error instanceof ScheduleNotFoundError || error instanceof InvalidScheduleIdError) {
throw new PaseoToolInputError(error.message);
}
throw error;
@@ -1153,7 +1155,7 @@ function createToolCatalog(
try {
return await action();
} catch (error) {
if (error instanceof ScheduleStateConflictError) {
if (error instanceof ScheduleStateConflictError || error instanceof InvalidScheduleIdError) {
throw new PaseoToolInputError(error.message);
}
throw error;
@@ -2149,6 +2151,24 @@ function createToolCatalog(
),
);
}
function formatQueuedResponse(receipt: AgentMessageReceipt) {
void receipt.dispatched.catch(() => {
rejectNotification();
});
return {
content: [],
structuredContent: {
success: true,
deliveryStatus: receipt.status,
messageId: receipt.messageId,
activeTurnBehavior: receipt.activeTurnBehavior,
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
guidance: notifying
? `${receipt.guidance} ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
: receipt.guidance,
},
};
}
if (callerAgentId) {
const receipt = await agentMessages()
@@ -2169,22 +2189,7 @@ function createToolCatalog(
rejectNotification();
throw error;
});
void receipt.dispatched.catch(() => {
rejectNotification();
});
return {
content: [],
structuredContent: {
success: true,
deliveryStatus: receipt.status,
messageId: receipt.messageId,
activeTurnBehavior: receipt.activeTurnBehavior,
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
guidance: notifying
? `${receipt.guidance} ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
: receipt.guidance,
},
};
return formatQueuedResponse(receipt);
}
const dispatch = await sendPromptToAgent({
@@ -2193,7 +2198,7 @@ function createToolCatalog(
agentStorage,
agentId,
prompt,
source: callerAgentId ? { kind: "agent-message", agentId: callerAgentId } : undefined,
source: undefined,
sessionMode,
activeTurnBehavior,
onDispatch: confirmDispatch,
@@ -2207,6 +2212,9 @@ function createToolCatalog(
});
// Return once the provider has accepted the turn, so the status reports it running.
if (dispatch.disposition === "queued") {
return formatQueuedResponse(dispatch.receipt);
}
const { disposition } = dispatch;
if (dispatch.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch(
+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;
@@ -204,3 +204,154 @@ test("paseo.agents.ref().send with activeTurnBehavior queue works while running
await close();
}
});
/** A Claude recipient running an initial turn, with named turn gates to inspect each mode transition. */
async function createModeBoundaryRecipient(input: {
initialModeId: string;
title: string;
initialPrompt: string;
heldPrompts: readonly string[];
}) {
const artifacts = path.resolve(".artifacts");
await mkdir(artifacts, { recursive: true });
const root = await mkdtemp(path.join(artifacts, "agent-mode-boundary-"));
const executedTurns: Array<{ prompt: string; modeId: string | undefined }> = [];
const gates = new Map<string, { promise: Promise<void>; release: () => void }>();
for (const prompt of [input.initialPrompt, ...input.heldPrompts]) {
let release!: () => void;
const promise = new Promise<void>((resolve) => {
release = resolve;
});
gates.set(prompt, { promise, release });
}
const daemon = await createTestPaseoDaemon({
agentClients: createTestAgentClients({
onStartTurn: (prompt, config) => {
executedTurns.push({ prompt: String(prompt), modeId: config.modeId });
},
beforeTurnComplete: async (prompt) => {
const text = String(prompt);
for (const [needle, gate] of gates) {
if (text.includes(needle)) {
await gate.promise;
return;
}
}
},
}),
paseoHomeRoot: path.join(root, "daemon"),
staticDir: path.join(root, "static"),
cleanup: false,
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const close = async () => {
for (const gate of gates.values()) {
gate.release();
}
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true });
};
try {
await client.connect();
await client.fetchAgents({ subscribe: {} });
const agent = await client.createAgent({
provider: "claude",
cwd: root,
modeId: input.initialModeId,
title: input.title,
});
await client.sendMessage(agent.id, input.initialPrompt);
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "running");
const releaseTurn = (prompt: string) => {
gates.get(prompt)?.release();
};
const waitForTurn = async (index: number) => {
await expect.poll(() => executedTurns.length, { timeout: 10_000 }).toBe(index + 1);
return executedTurns[index];
};
return { agent, client, releaseTurn, waitForTurn, close };
} catch (error) {
await close();
throw error;
}
}
test("a direct broader-mode send behind a queued plan-mode message runs as two separate turns in their respective modes", async () => {
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
initialModeId: "default",
title: "Mode Boundary Worker",
initialPrompt: "Initial work",
heldPrompts: ["Inspect files read-only"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
activeTurnBehavior: "queue",
sessionMode: "plan",
});
expect(queuedReceipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
const directReceipt = await client.sendAgentMessage(agent.id, "Edit production files", {
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
releaseTurn("Initial work");
expect(await waitForTurn(1)).toEqual({
prompt: "Inspect files read-only",
modeId: "plan",
});
releaseTurn("Inspect files read-only");
expect(await waitForTurn(2)).toEqual({
prompt: "Edit production files",
modeId: "bypassPermissions",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
} finally {
await close();
}
});
test("a direct bypassPermissions send behind a queued implicit-mode message on a restricted-mode agent runs as two separate turns", async () => {
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
initialModeId: "always-ask",
title: "Implicit Mode Worker",
initialPrompt: "Initial restricted turn",
heldPrompts: ["Queued in existing mode"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
activeTurnBehavior: "queue",
});
expect(queuedReceipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
const directReceipt = await client.sendAgentMessage(agent.id, "Apply edits in bypass mode", {
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
releaseTurn("Initial restricted turn");
expect(await waitForTurn(1)).toEqual({
prompt: "Queued in existing mode",
modeId: "always-ask",
});
releaseTurn("Queued in existing mode");
expect(await waitForTurn(2)).toEqual({
prompt: "Apply edits in bypass mode",
modeId: "bypassPermissions",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
} finally {
await close();
}
});
@@ -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);
@@ -1,6 +1,8 @@
import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import pino from "pino";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import {
@@ -13,6 +15,7 @@ import {
type SchemaModule,
type WriteSql,
} from "./index.js";
import { SqliteDaemonDatabase } from "./internal/daemon-database.js";
import { WalCheckpointer } from "./internal/wal-checkpointer.js";
let directory: string;
@@ -71,16 +74,59 @@ function versions(database: DaemonDatabase) {
}
describe("opening the daemon database", () => {
it("creates the file in WAL mode with foreign keys on", () => {
it("creates the file in WAL mode with production PRAGMAs and incremental auto_vacuum", () => {
const database = open([notes]);
expect(
database.read((sql) => ({
journal: sql.get<{ journal_mode: string }>("PRAGMA journal_mode")!.journal_mode,
foreignKeys: sql.get<{ foreign_keys: number }>("PRAGMA foreign_keys")!.foreign_keys,
synchronous: sql.get<{ synchronous: number }>("PRAGMA synchronous")!.synchronous,
checkpointFullfsync: sql.get<{ checkpoint_fullfsync: number }>(
"PRAGMA checkpoint_fullfsync",
)!.checkpoint_fullfsync,
tempStore: sql.get<{ temp_store: number }>("PRAGMA temp_store")!.temp_store,
busyTimeout: sql.get<{ timeout: number }>("PRAGMA busy_timeout")!.timeout,
autoVacuum: sql.get<{ auto_vacuum: number }>("PRAGMA auto_vacuum")!.auto_vacuum,
walAutocheckpoint: sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")!
.wal_autocheckpoint,
})),
).toEqual({ journal: "wal", foreignKeys: 1, synchronous: 1 });
).toEqual({
journal: "wal",
foreignKeys: 1,
synchronous: 1,
checkpointFullfsync: 1,
tempStore: 2,
busyTimeout: 5000,
autoVacuum: 2,
walAutocheckpoint: 10_000,
});
expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]);
const reopened = reopen(database, [notes]);
expect(
reopened.read((sql) => sql.get<{ auto_vacuum: number }>("PRAGMA auto_vacuum")!.auto_vacuum),
).toBe(2);
});
it("opens an existing auto_vacuum = NONE database without forcing a full vacuum", () => {
const existing = new DatabaseSync(databasePath);
try {
existing.exec("CREATE TABLE legacy_items (id INTEGER PRIMARY KEY, label TEXT NOT NULL)");
existing.prepare("INSERT INTO legacy_items (label) VALUES (?)").run("preserved");
expect(existing.prepare("PRAGMA auto_vacuum").get()).toEqual({ auto_vacuum: 0 });
} finally {
existing.close();
}
const database = open([notes]);
expect(
database.read((sql) => ({
autoVacuum: sql.get<{ auto_vacuum: number }>("PRAGMA auto_vacuum")!.auto_vacuum,
legacy: sql.all<{ label: string }>("SELECT label FROM legacy_items"),
})),
).toEqual({
autoVacuum: 0,
legacy: [{ label: "preserved" }],
});
});
it("keeps committed rows across a reopen and runs no migration twice", () => {
@@ -190,6 +236,39 @@ describe("opening the daemon database", () => {
expect((error as Error).message).toContain(databasePath);
});
it("refuses a database a newer daemon changed without mutating journal_mode or creating WAL sidecars", () => {
const future = new DatabaseSync(databasePath);
try {
future.exec("PRAGMA journal_mode = DELETE");
future.exec(
"CREATE TABLE schema_versions (" +
"module TEXT PRIMARY KEY, version INTEGER NOT NULL, min_reader_version INTEGER NOT NULL)",
);
future
.prepare(
"INSERT INTO schema_versions (module, version, min_reader_version) VALUES (?, ?, ?)",
)
.run("notes", 2, 2);
} finally {
future.close();
}
const bytesBefore = readFileSync(databasePath);
expect(readdirSync(directory)).toEqual(["paseo.db"]);
expect(() =>
openDaemonDatabase({ path: databasePath, modules: [notes], logger: createTestLogger() }),
).toThrow(DatabaseSchemaTooNewError);
expect(readdirSync(directory)).toEqual(["paseo.db"]);
expect(readFileSync(databasePath).equals(bytesBefore)).toBe(true);
const probe = new DatabaseSync(databasePath);
try {
expect(probe.prepare("PRAGMA journal_mode").get()).toEqual({ journal_mode: "delete" });
} finally {
probe.close();
}
});
it("fails with the path when the file is not a database", () => {
const corrupt = path.join(directory, "corrupt.db");
writeFileSync(corrupt, "this is not a sqlite file, it is some text long enough to be read");
@@ -313,11 +392,208 @@ it("refuses to reuse a statement that an unfinished iterator holds", () => {
database.read(reuse);
});
it("checkpoints the WAL off the daemon thread, never during a write", async () => {
it.skipIf(process.platform === "win32")(
"creates a brand-new database and its WAL files with 0o600 permissions under a permissive umask",
() => {
const umask = process.umask(0o022);
try {
const database = open([notes]);
database.write((sql) => insert(sql, "secret"));
for (const file of [databasePath, `${databasePath}-wal`, `${databasePath}-shm`]) {
expect({ file, mode: statSync(file).mode & 0o777 }).toEqual({ file, mode: 0o600 });
}
} finally {
process.umask(umask);
}
},
);
it("preserves the original error when SQLite auto-rolls back the outer transaction inside a savepoint", () => {
const strict: SchemaModule = {
name: "strict",
migrations: [
{
up: (sql) =>
sql.exec(
"CREATE TABLE strict_items (id INTEGER PRIMARY KEY, code TEXT UNIQUE ON CONFLICT ROLLBACK)",
),
},
],
};
const database = open([strict]);
database.write((sql) => sql.run("INSERT INTO strict_items (code) VALUES (?)", "dup"));
let caught: unknown;
try {
database.write((outer) => {
outer.run("INSERT INTO strict_items (code) VALUES (?)", "rolled-back");
database.write((inner) => {
inner.run("INSERT INTO strict_items (code) VALUES (?)", "dup");
});
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(Error);
expect((caught as Error).message).toMatch(/UNIQUE constraint failed/i);
expect((caught as Error).message).not.toMatch(/no such savepoint/i);
expect(
database.read((sql) =>
sql.all<{ code: string }>("SELECT code FROM strict_items ORDER BY id").map((row) => row.code),
),
).toEqual(["dup"]);
database.write((sql) => sql.run("INSERT INTO strict_items (code) VALUES (?)", "after"));
expect(
database.read((sql) =>
sql.all<{ code: string }>("SELECT code FROM strict_items ORDER BY id").map((row) => row.code),
),
).toEqual(["dup", "after"]);
});
describe("statement cache hardening", () => {
const MAX_CACHED_PARAM_BYTES = 64 * 1024;
it("bypasses the statement cache when bound parameters exceed 64 KiB", () => {
const blobs: SchemaModule = {
name: "blobs",
migrations: [
{
up: (sql) =>
sql.exec("CREATE TABLE blobs_items (id INTEGER PRIMARY KEY, text TEXT, raw BLOB)"),
},
],
};
const database = open([blobs]);
const largeString = "a".repeat(MAX_CACHED_PARAM_BYTES + 1);
const largeMultibyte = "€".repeat(30_000); // 30k chars, 90k UTF-8 bytes > 64 KiB
const largeUint8 = new Uint8Array(MAX_CACHED_PARAM_BYTES + 1);
largeUint8[0] = 7;
const largeBuffer = Buffer.alloc(MAX_CACHED_PARAM_BYTES + 1, 9);
const boundaryString = "b".repeat(MAX_CACHED_PARAM_BYTES);
database.write((sql) => {
sql.run("INSERT INTO blobs_items (text) VALUES (?)", largeString);
sql.run("INSERT INTO blobs_items (text) VALUES (?)", largeMultibyte);
sql.run("INSERT INTO blobs_items (raw) VALUES (?)", largeUint8);
sql.run("INSERT INTO blobs_items (raw) VALUES (?)", largeBuffer);
sql.run("INSERT INTO blobs_items (text) VALUES (?)", boundaryString);
});
const rows = database.read((sql) =>
sql.all<{ text: string | null; raw: Uint8Array | null }>(
"SELECT text, raw FROM blobs_items ORDER BY id",
),
);
expect(rows[0].text?.length).toBe(MAX_CACHED_PARAM_BYTES + 1);
expect(rows[1].text?.length).toBe(30_000);
expect(rows[2].raw?.byteLength).toBe(MAX_CACHED_PARAM_BYTES + 1);
expect(rows[2].raw?.[0]).toBe(7);
expect(rows[3].raw?.byteLength).toBe(MAX_CACHED_PARAM_BYTES + 1);
expect(rows[3].raw?.[0]).toBe(9);
expect(rows[4].text?.length).toBe(MAX_CACHED_PARAM_BYTES);
// An open cached iterator blocks re-entry on the same SQL, whereas bypassed (>64 KiB) calls
// prepare a one-shot statement and do not collide with the cached statement.
const probeQuery = "SELECT id FROM blobs_items WHERE id = 1 AND ? IS NOT NULL";
function reuseCachedIterator(sql: ReadSql): void {
sql.iterate(probeQuery, "small")[Symbol.iterator]().next();
expect(() => sql.all(probeQuery, "small")).toThrow(/already iterating/);
expect(() => sql.all(probeQuery, boundaryString)).toThrow(/already iterating/);
expect(sql.all<{ id: number }>(probeQuery, largeString)).toEqual([{ id: 1 }]);
expect(sql.all<{ id: number }>(probeQuery, largeMultibyte)).toEqual([{ id: 1 }]);
expect(sql.all<{ id: number }>(probeQuery, largeUint8)).toEqual([{ id: 1 }]);
expect(sql.all<{ id: number }>(probeQuery, largeBuffer)).toEqual([{ id: 1 }]);
}
database.read(reuseCachedIterator);
// Conversely, iterating with a >64 KiB param does not occupy the cached entry for that SQL.
function iterateLargeThenSmall(sql: ReadSql): void {
sql.iterate(probeQuery, largeString)[Symbol.iterator]().next();
expect(sql.all<{ id: number }>(probeQuery, "small")).toEqual([{ id: 1 }]);
}
database.read(iterateLargeThenSmall);
});
it("handles more distinct statements than the LRU limit while protecting active iterators", () => {
const database = open([notes]);
const query = (index: number) => `SELECT ${index} AS n`;
function saturateCacheWithActiveIterator(sql: ReadSql): void {
const first = sql.iterate<{ n: number }>(query(0))[Symbol.iterator]().next();
expect(first).toEqual({ done: false, value: { n: 0 } });
for (let index = 1; index <= 300; index++) {
expect(sql.get<{ n: number }>(query(index))).toEqual({ n: index });
}
// Active iterator was never evicted by the 300 newer queries.
expect(() => sql.all(query(0))).toThrow(/already iterating/);
}
database.read(saturateCacheWithActiveIterator);
// Re-running older queries after saturation succeeds cleanly.
expect(database.read((sql) => sql.get<{ n: number }>(query(0)))).toEqual({ n: 0 });
expect(database.read((sql) => sql.get<{ n: number }>(query(1)))).toEqual({ n: 1 });
});
it("evicts a cached statement when run, get, all, or iterate throws so reuse succeeds cleanly", () => {
const database = open([notes]);
const insertById = "INSERT INTO notes_items (id, text) VALUES (?, ?)";
function insertDuplicate(sql: WriteSql): void {
sql.run(insertById, 1, "dup");
}
database.write((sql) => sql.run(insertById, 1, '{"a":1}'));
expect(() => database.write(insertDuplicate)).toThrow(/UNIQUE/);
database.write((sql) => sql.run(insertById, 2, '{"a":2}'));
const getJson = "SELECT json_extract(?, '$.a') AS a /* get */";
function getInvalidJson(sql: ReadSql): unknown {
return sql.get(getJson, "not json");
}
expect(database.read((sql) => sql.get<{ a: number }>(getJson, '{"a":1}'))).toEqual({ a: 1 });
expect(() => database.read(getInvalidJson)).toThrow(/malformed JSON/i);
expect(database.read((sql) => sql.get<{ a: number }>(getJson, '{"a":3}'))).toEqual({ a: 3 });
const allJson = "SELECT json_extract(?, '$.a') AS a /* all */";
function allInvalidJson(sql: ReadSql): unknown {
return sql.all(allJson, "not json");
}
expect(database.read((sql) => sql.all<{ a: number }>(allJson, '{"a":1}'))).toEqual([{ a: 1 }]);
expect(() => database.read(allInvalidJson)).toThrow(/malformed JSON/i);
expect(database.read((sql) => sql.all<{ a: number }>(allJson, '{"a":4}'))).toEqual([{ a: 4 }]);
const iterateJson = "SELECT json_extract(text, '$.a') AS a FROM notes_items ORDER BY id";
expect(database.read((sql) => Array.from(sql.iterate<{ a: number }>(iterateJson)))).toEqual([
{ a: 1 },
{ a: 2 },
]);
database.write((sql) => sql.run(insertById, 3, "not json"));
function failMidIterationThenReuseInSameTx(sql: ReadSql): void {
const iterator = sql.iterate<{ a: number }>(iterateJson)[Symbol.iterator]();
expect(iterator.next()).toEqual({ done: false, value: { a: 1 } });
expect(iterator.next()).toEqual({ done: false, value: { a: 2 } });
expect(() => iterator.next()).toThrow(/malformed JSON/i);
// After throwing mid-iteration, the statement is closed and evicted, so starting a fresh
// iteration in the same transaction does not throw "already iterating".
const retry = sql.iterate<{ a: number }>(iterateJson)[Symbol.iterator]();
expect(retry.next()).toEqual({ done: false, value: { a: 1 } });
}
database.read(failMidIterationThenReuseInSameTx);
database.write((sql) => sql.run("DELETE FROM notes_items WHERE id = ?", 3));
expect(database.read((sql) => Array.from(sql.iterate<{ a: number }>(iterateJson)))).toEqual([
{ a: 1 },
{ a: 2 },
]);
});
});
it("checkpoints the WAL off the daemon thread with a 10,000-page writer backstop", async () => {
const database = open([notes]);
expect(
database.read((sql) => sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")),
).toEqual({ wal_autocheckpoint: 0 });
).toEqual({ wal_autocheckpoint: 10_000 });
const fileSize = () => statSync(databasePath).size;
const before = fileSize();
const writeBatch = (sql: WriteSql) => {
@@ -331,6 +607,23 @@ it("checkpoints the WAL off the daemon thread, never during a write", async () =
});
});
it("keeps checkpointing on-thread when the database does not enter WAL mode", () => {
const database = openDaemonDatabase({
path: ":memory:",
modules: [notes],
logger: createTestLogger(),
});
opened.push(database);
database.write((sql) => insert(sql, "in-memory"));
expect(
database.read((sql) => ({
journalMode: sql.get<{ journal_mode: string }>("PRAGMA journal_mode")!.journal_mode,
walAutocheckpoint: sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")!
.wal_autocheckpoint,
})),
).toEqual({ journalMode: "memory", walAutocheckpoint: 1000 });
});
it("rejects every call after close", () => {
const database = open([notes]);
database.close();
@@ -365,4 +658,137 @@ describe("the WAL checkpointer", () => {
await vi.waitFor(() => expect(exited).toBe(true), { timeout: 10_000, interval: 20 });
expect(checkpointer.stop()).toBe(true);
});
it("backs off and exits after repeated checkpoint failures instead of looping forever", async () => {
const warnings: string[] = [];
const logger = pino(
{ level: "warn" },
{ write: (line: string) => void warnings.push(JSON.parse(line).msg) },
);
const blocker = new DatabaseSync(databasePath);
blocker.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)");
blocker.exec("PRAGMA locking_mode = EXCLUSIVE");
blocker.exec("BEGIN EXCLUSIVE");
blocker.exec("INSERT INTO notes_items (text) VALUES ('locked')");
let exited = false;
const checkpointer = new WalCheckpointer({
path: databasePath,
logger,
onExit: () => {
exited = true;
},
intervalMs: 25,
maxConsecutiveFailures: 3,
busyTimeoutMs: 0,
});
try {
await vi.waitFor(() => expect(exited).toBe(true), { timeout: 5_000, interval: 20 });
expect(warnings.filter((msg) => msg === "Database WAL checkpoint failed")).toHaveLength(3);
expect(checkpointer.stop()).toBe(true);
} finally {
checkpointer.stop();
blocker.exec("ROLLBACK");
blocker.close();
}
});
it("opens with hardened PRAGMAs and waits through an exclusive lock before resuming checkpoints", async () => {
const writer = new DatabaseSync(databasePath);
writer.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0;");
writer.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)");
const sizeBefore = statSync(databasePath).size;
writer.exec("PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;");
const insertRow = writer.prepare("INSERT INTO notes_items (text) VALUES (?)");
for (let row = 0; row < 400; row++) insertRow.run(`locked-${"z".repeat(1000)}`);
const warnings: string[] = [];
const logger = pino(
{ level: "warn" },
{ write: (line: string) => void warnings.push(JSON.parse(line).msg) },
);
let exited = false;
const checkpointer = new WalCheckpointer({
path: databasePath,
logger,
onExit: () => {
exited = true;
},
intervalMs: 20,
});
try {
// Spawn two sequential 0ms-timeout probes while the exclusive lock is held: proves the lock
// rejects immediate open/PRAGMA attempts and ensures the 5000ms worker started earlier has
// entered SQLite's busy wait before we release the lock.
for (let attempt = 0; attempt < 2; attempt++) {
const probeWarnings: string[] = [];
let probeExited = false;
const probe = new WalCheckpointer({
path: databasePath,
logger: pino(
{ level: "warn" },
{ write: (line: string) => void probeWarnings.push(JSON.parse(line).error ?? "") },
),
onExit: () => {
probeExited = true;
},
intervalMs: 20,
maxConsecutiveFailures: 1,
busyTimeoutMs: 0,
});
try {
await vi.waitFor(() => expect(probeExited).toBe(true), { timeout: 10_000, interval: 20 });
expect(probeWarnings.some((message) => /locked/i.test(message))).toBe(true);
} finally {
probe.stop();
}
}
// Release the exclusive lock and verify the 5000ms checkpointer completes its PRAGMAs and
// checkpoints the WAL into the database file without warnings or exiting.
writer.exec("COMMIT");
writer.exec("PRAGMA locking_mode = NORMAL; SELECT 1 FROM notes_items LIMIT 1;");
await vi.waitFor(
() => expect(statSync(databasePath).size).toBeGreaterThan(sizeBefore + 200_000),
{ timeout: 10_000, interval: 20 },
);
expect(checkpointer.stop()).toBe(true);
expect(exited).toBe(false);
expect(warnings).toEqual([]);
} finally {
checkpointer.stop();
try {
if (writer.isTransaction) writer.exec("ROLLBACK");
writer.close();
} catch {
// Already closed.
}
}
});
});
describe("a checkpointer that ends while the database cannot take the fallback", () => {
it("logs a warning instead of throwing from the worker's exit event", async () => {
const warnings: string[] = [];
const logger = pino(
{ level: "warn" },
{ write: (line: string) => void warnings.push(JSON.parse(line).msg) },
);
const connection = new DatabaseSync(databasePath);
connection.exec("PRAGMA journal_mode = WAL");
connection.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)");
const database = new SqliteDaemonDatabase(connection, logger);
// The worker opens a file that does not exist, so it ends on its own after the first write.
database.checkpointOffThread(path.join(directory, "missing", "paseo.db"));
database.write((sql) => insert(sql, "a"));
// The connection closes before the worker's exit event reaches the daemon thread.
connection.close();
await vi.waitFor(
() => expect(warnings).toContain("Database could not resume its own WAL checkpoints"),
{ timeout: 10_000, interval: 20 },
);
});
});
@@ -1,6 +1,6 @@
import type { DatabaseSync, SQLInputValue, StatementSync } from "node:sqlite";
import type { Logger } from "pino";
import { ensurePrivateFile } from "../../private-files.js";
import { createPrivateFileIfMissing, ensurePrivateFile } from "../../private-files.js";
import { WalCheckpointer } from "./wal-checkpointer.js";
export type SqlValue = SQLInputValue;
@@ -85,8 +85,12 @@ export class DatabaseSchemaTooNewError extends Error {
}
}
const BUSY_TIMEOUT_MS = 1000;
const BUSY_TIMEOUT_MS = 5000;
const JOURNAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
const SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES = 1000;
const OFF_THREAD_AUTOCHECKPOINT_BACKSTOP_PAGES = 10_000;
const STATEMENT_CACHE_MAX_ENTRIES = 256;
const STATEMENT_CACHE_MAX_PARAM_BYTES = 64 * 1024;
/**
* Opens the database at `path`, creating the file when absent in a directory that must exist, and
@@ -100,34 +104,104 @@ export function openDaemonDatabase(input: {
let connection: DatabaseSync | undefined;
try {
const sqlite = loadSqlite();
const isFile = input.path !== ":memory:" && input.path !== "";
if (isFile) createPrivateFileIfMissing(input.path);
connection = new sqlite.DatabaseSync(input.path, { timeout: BUSY_TIMEOUT_MS });
assertSupported(connection);
// The file holds every prompt and reply. SQLite gives the WAL and shared-memory files it
// creates the database file's mode; files left by an earlier open are fixed here.
if (input.path !== ":memory:") {
for (const file of [input.path, `${input.path}-wal`, `${input.path}-shm`]) {
ensurePrivateFile(file);
}
assertCompatibleSchema({ connection, path: input.path, modules: input.modules });
// The file holds every prompt and reply. Tighten existing files before WAL mode creates
// sidecars that inherit the database file's mode, and again after migration creates them.
if (isFile) ensurePrivateDatabaseFiles(input.path);
if (isEmptyDatabase(connection)) {
connection.exec("PRAGMA auto_vacuum = INCREMENTAL");
}
const journalMode = enableWalMode(connection);
connection.exec(
[
"PRAGMA journal_mode = WAL",
"PRAGMA synchronous = NORMAL",
"PRAGMA checkpoint_fullfsync = ON",
"PRAGMA foreign_keys = ON",
"PRAGMA temp_store = MEMORY",
`PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT_BYTES}`,
].join(";"),
);
const database = new SqliteDaemonDatabase(connection, input.logger);
migrate(database, input.path, input.modules);
if (input.path !== ":memory:") database.checkpointOffThread(input.path);
migrate({ database, file: input.path, modules: input.modules });
if (isFile) ensurePrivateDatabaseFiles(input.path);
if (isFile) {
if (journalMode === "wal") {
database.checkpointOffThread(input.path);
} else {
input.logger.warn(
{ journalMode },
"Database did not enter WAL mode; checkpointing on the daemon thread",
);
}
}
return database;
} catch (error) {
connection?.close();
closeAfterFailedOpen({ connection, logger: input.logger });
if (error instanceof DatabaseSchemaTooNewError) throw error;
throw new DatabaseOpenError(input.path, error);
}
}
/** The open already failed; a failing close must not replace that error. */
function closeAfterFailedOpen(input: { connection: DatabaseSync | undefined; logger: Logger }) {
try {
input.connection?.close();
} catch (error) {
input.logger.warn({ err: error }, "Database connection did not close after a failed open");
}
}
function ensurePrivateDatabaseFiles(filePath: string): void {
for (const file of [filePath, `${filePath}-wal`, `${filePath}-shm`]) {
ensurePrivateFile(file);
}
}
function isEmptyDatabase(connection: DatabaseSync): boolean {
const row = connection.prepare("PRAGMA page_count").get() as { page_count?: number } | undefined;
return row?.page_count === 0;
}
function enableWalMode(connection: DatabaseSync): string {
const row = connection.prepare("PRAGMA journal_mode = WAL").get() as
| { journal_mode?: string }
| undefined;
return row?.journal_mode?.toLowerCase() ?? "";
}
/**
* Checks `schema_versions` using read-only queries before running mutating PRAGMAs so an older
* daemon never alters page 1 or creates WAL sidecars on a newer database.
*/
function assertCompatibleSchema(input: {
connection: DatabaseSync;
path: string;
modules: readonly SchemaModule[];
}): void {
const hasVersionsTable = input.connection
.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_versions'")
.get();
if (!hasVersionsTable) return;
const statement = input.connection.prepare(
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
);
for (const module of input.modules) {
const stored = statement.get(module.name) as StoredVersion | undefined;
if (stored && stored.min_reader_version > module.migrations.length) {
throw new DatabaseSchemaTooNewError(
input.path,
module.name,
stored.min_reader_version,
module.migrations.length,
);
}
}
}
function loadSqlite(): typeof import("node:sqlite") {
// Loaded on open, not imported: Node 22 warns that the module is experimental when it loads, and
// CLI commands import this package without opening a database.
@@ -149,17 +223,21 @@ function assertSupported(connection: DatabaseSync): void {
}
}
function migrate(database: DaemonDatabase, file: string, modules: readonly SchemaModule[]): void {
database.write((sql) => {
function migrate(input: {
database: DaemonDatabase;
file: string;
modules: readonly SchemaModule[];
}): void {
input.database.write((sql) => {
sql.exec(
"CREATE TABLE IF NOT EXISTS schema_versions (" +
"module TEXT PRIMARY KEY, version INTEGER NOT NULL, min_reader_version INTEGER NOT NULL)",
);
const names = new Set<string>();
for (const module of modules) {
for (const module of input.modules) {
if (names.has(module.name)) throw new Error(`Schema module '${module.name}' is listed twice`);
names.add(module.name);
migrateModule(sql, file, module);
migrateModule({ sql, file: input.file, module });
}
});
}
@@ -169,7 +247,8 @@ interface StoredVersion {
min_reader_version: number;
}
function migrateModule(sql: WriteSql, file: string, module: SchemaModule): void {
function migrateModule(input: { sql: WriteSql; file: string; module: SchemaModule }): void {
const { sql, file, module } = input;
const known = module.migrations.length;
const stored = sql.get<StoredVersion>(
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
@@ -205,13 +284,25 @@ type CheckpointerState =
| { kind: "pending"; path: string }
| { kind: "worker"; worker: WalCheckpointer };
const SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES = 1000;
interface OpenIteration {
close(): void;
}
class SqliteDaemonDatabase implements DaemonDatabase {
interface PreparedStatement {
statement: StatementSync;
cached: boolean;
}
interface IterateInput {
sql: string;
prepared: StatementSync;
cached: boolean;
params: SqlValue[];
iterations: Set<OpenIteration>;
assertValid: () => void;
}
export class SqliteDaemonDatabase implements DaemonDatabase {
private state: TransactionState = "none";
private savepoints = 0;
private closed = false;
@@ -239,10 +330,11 @@ class SqliteDaemonDatabase implements DaemonDatabase {
/**
* Moves WAL checkpoints to a worker thread, started by the first committed write, so a
* read-only open starts no thread. Until then SQLite's auto-checkpoint stays off.
* read-only open starts no thread. Keeps a writer auto-checkpoint backstop so a stalled or
* outpaced worker cannot grow the WAL unboundedly.
*/
checkpointOffThread(file: string): void {
this.connection.exec("PRAGMA wal_autocheckpoint = 0");
this.connection.exec(`PRAGMA wal_autocheckpoint = ${OFF_THREAD_AUTOCHECKPOINT_BACKSTOP_PAGES}`);
this.checkpointer = { kind: "pending", path: file };
}
@@ -289,8 +381,10 @@ class SqliteDaemonDatabase implements DaemonDatabase {
this.connection.exec(`RELEASE ${name}`);
return result;
} catch (error) {
this.connection.exec(`ROLLBACK TO ${name}`);
this.connection.exec(`RELEASE ${name}`);
if (this.connection.isTransaction) {
this.connection.exec(`ROLLBACK TO ${name}`);
this.connection.exec(`RELEASE ${name}`);
}
throw error;
} finally {
this.savepoints--;
@@ -304,23 +398,43 @@ class SqliteDaemonDatabase implements DaemonDatabase {
const assertValid = () => {
if (!valid) throw new Error("A database handle was used after its transaction ended");
};
const statement = (sql: string) => {
const execute = <R>(input: {
sql: string;
params: readonly SqlValue[];
run: (prepared: StatementSync) => R;
}): R => {
assertValid();
const prepared = this.statement(sql);
if (this.iterating.has(prepared)) {
throw new Error(`A statement is already iterating: ${sql}`);
const { statement, cached } = this.prepareStatement({ sql: input.sql, params: input.params });
try {
return input.run(statement);
} catch (error) {
if (cached) this.evictStatement({ sql: input.sql, statement });
throw error;
}
return prepared;
};
const handle: WriteSql = {
get: <R>(sql: string, ...params: SqlValue[]) =>
statement(sql).get(...params) as R | undefined,
all: <R>(sql: string, ...params: SqlValue[]) => statement(sql).all(...params) as R[],
iterate: <R>(sql: string, ...params: SqlValue[]) =>
this.iterate<R>(statement(sql), params, iterations, assertValid),
run: (sql: string, ...params: SqlValue[]) => ({
changes: Number(statement(sql).run(...params).changes),
}),
execute({ sql, params, run: (prepared) => prepared.get(...params) as R | undefined }),
all: <R>(sql: string, ...params: SqlValue[]) =>
execute({ sql, params, run: (prepared) => prepared.all(...params) as R[] }),
iterate: <R>(sql: string, ...params: SqlValue[]) => {
assertValid();
const { statement, cached } = this.prepareStatement({ sql, params });
return this.iterate<R>({
sql,
prepared: statement,
cached,
params,
iterations,
assertValid,
});
},
run: (sql: string, ...params: SqlValue[]) =>
execute({
sql,
params,
run: (prepared) => ({ changes: Number(prepared.run(...params).changes) }),
}),
exec: (sql: string) => {
assertValid();
this.connection.exec(sql);
@@ -338,13 +452,15 @@ class SqliteDaemonDatabase implements DaemonDatabase {
}
}
private iterate<R>(
prepared: StatementSync,
params: SqlValue[],
iterations: Set<OpenIteration>,
assertValid: () => void,
): Iterable<R> {
const rows = prepared.iterate(...params);
private iterate<R>(input: IterateInput): Iterable<R> {
const { sql, prepared, cached, params, iterations, assertValid } = input;
let rows: ReturnType<StatementSync["iterate"]>;
try {
rows = prepared.iterate(...params);
} catch (error) {
if (cached) this.evictStatement({ sql, statement: prepared });
throw error;
}
let done = false;
const iteration: OpenIteration = {
close: () => {
@@ -361,11 +477,21 @@ class SqliteDaemonDatabase implements DaemonDatabase {
next: () => {
assertValid();
if (done) return { done: true, value: undefined };
const next = rows.next();
if (next.done) iteration.close();
return next.done
? { done: true, value: undefined }
: { done: false, value: next.value as R };
try {
const next = rows.next();
if (next.done) iteration.close();
return next.done
? { done: true, value: undefined }
: { done: false, value: next.value as R };
} catch (error) {
if (cached) this.evictStatement({ sql, statement: prepared });
try {
iteration.close();
} catch {
// Preserve the execution error from rows.next().
}
throw error;
}
},
return: () => {
iteration.close();
@@ -383,6 +509,7 @@ class SqliteDaemonDatabase implements DaemonDatabase {
path: this.checkpointer.path,
logger: this.logger,
onExit: () => this.checkpointOnThread(),
busyTimeoutMs: BUSY_TIMEOUT_MS,
});
this.checkpointer = { kind: "worker", worker };
} catch (error) {
@@ -391,21 +518,60 @@ class SqliteDaemonDatabase implements DaemonDatabase {
}
}
/** The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. */
/**
* The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. Runs from
* the worker's exit event, where a throw would be an uncaught exception that ends the daemon.
*/
private checkpointOnThread(): void {
if (this.closed) return;
this.logger.warn("Database WAL checkpointer exited; checkpointing on the daemon thread");
this.checkpointer = { kind: "on_thread" };
this.connection.exec(`PRAGMA wal_autocheckpoint = ${SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES}`);
try {
this.connection.exec(`PRAGMA wal_autocheckpoint = ${SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES}`);
} catch (error) {
this.logger.warn({ err: error }, "Database could not resume its own WAL checkpoints");
}
}
private statement(sql: string): StatementSync {
let prepared = this.statements.get(sql);
if (!prepared) {
prepared = this.connection.prepare(sql);
this.statements.set(sql, prepared);
private prepareStatement(input: { sql: string; params: readonly SqlValue[] }): PreparedStatement {
// node:sqlite has no clearBindings(); bypass the cache when bound buffers exceed 64 KiB so
// cached statements do not pin large payloads in native memory indefinitely.
if (exceedsStatementCacheParamBudget(input.params)) {
return { statement: this.connection.prepare(input.sql), cached: false };
}
const existing = this.statements.get(input.sql);
if (existing) {
if (this.iterating.has(existing)) {
throw new Error(`A statement is already iterating: ${input.sql}`);
}
this.statements.delete(input.sql);
this.statements.set(input.sql, existing);
return { statement: existing, cached: true };
}
const prepared = this.connection.prepare(input.sql);
if (
this.statements.size >= STATEMENT_CACHE_MAX_ENTRIES &&
!this.evictLeastRecentlyUsedStatement()
) {
return { statement: prepared, cached: false };
}
this.statements.set(input.sql, prepared);
return { statement: prepared, cached: true };
}
private evictLeastRecentlyUsedStatement(): boolean {
for (const [oldestSql, oldestStatement] of this.statements) {
if (this.iterating.has(oldestStatement)) continue;
this.statements.delete(oldestSql);
return true;
}
return false;
}
private evictStatement(input: { sql: string; statement: StatementSync }): void {
if (this.statements.get(input.sql) === input.statement) {
this.statements.delete(input.sql);
}
return prepared;
}
private assertOpen(): void {
@@ -413,6 +579,30 @@ class SqliteDaemonDatabase implements DaemonDatabase {
}
}
function exceedsStatementCacheParamBudget(params: readonly SqlValue[]): boolean {
let maxPossibleBytes = 0;
for (const param of params) {
if (typeof param === "string") {
if (param.length > STATEMENT_CACHE_MAX_PARAM_BYTES) return true;
maxPossibleBytes += param.length * 3;
} else if (ArrayBuffer.isView(param)) {
if (param.byteLength > STATEMENT_CACHE_MAX_PARAM_BYTES) return true;
maxPossibleBytes += param.byteLength;
}
}
if (maxPossibleBytes <= STATEMENT_CACHE_MAX_PARAM_BYTES) return false;
let exactBytes = 0;
for (const param of params) {
if (typeof param === "string") {
exactBytes += Buffer.byteLength(param, "utf8");
} else if (ArrayBuffer.isView(param)) {
exactBytes += param.byteLength;
}
if (exactBytes > STATEMENT_CACHE_MAX_PARAM_BYTES) return true;
}
return false;
}
function isThenable(value: unknown): boolean {
return (
typeof value === "object" &&
@@ -1,8 +1,12 @@
import { Worker } from "node:worker_threads";
import type { Logger } from "pino";
const BUSY_TIMEOUT_MS = 5000;
const CHECKPOINT_INTERVAL_MS = 1000;
const MAX_BACKOFF_MS = 30_000;
const MAX_CONSECUTIVE_FAILURES = 5;
const STOP_TIMEOUT_MS = 2000;
const CHECKPOINTER_PRAGMAS = "PRAGMA synchronous = NORMAL; PRAGMA checkpoint_fullfsync = ON";
const RUNNING = 0;
const STOPPING = 1;
@@ -10,19 +14,34 @@ const STOPPED = 1;
/**
* Runs in the worker. It sleeps on the shared state, so `stop` wakes it at once, and needs no
* event loop: a checkpoint is one synchronous call.
* event loop: a checkpoint is one synchronous call. Repeated checkpoint errors back off and then
* exit so the daemon thread takes over WAL checkpoints instead of looping forever.
*/
const WORKER_SOURCE = `
const { parentPort, workerData } = require("node:worker_threads");
const state = new Int32Array(workerData.state);
let connection;
try {
connection = new (process.getBuiltinModule("node:sqlite").DatabaseSync)(workerData.path);
while (Atomics.wait(state, 0, ${RUNNING}, workerData.intervalMs) === "timed-out") {
connection = new (process.getBuiltinModule("node:sqlite").DatabaseSync)(workerData.path, {
timeout: workerData.busyTimeoutMs,
});
let pragmasApplied = false;
let consecutiveFailures = 0;
let waitMs = workerData.intervalMs;
while (Atomics.wait(state, 0, ${RUNNING}, waitMs) === "timed-out") {
try {
if (!pragmasApplied) {
connection.exec(workerData.pragmas);
pragmasApplied = true;
}
connection.prepare("PRAGMA wal_checkpoint(PASSIVE)").get();
consecutiveFailures = 0;
waitMs = workerData.intervalMs;
} catch (error) {
consecutiveFailures += 1;
parentPort.postMessage(String(error && error.message ? error.message : error));
if (consecutiveFailures >= workerData.maxConsecutiveFailures) break;
waitMs = Math.min(workerData.maxBackoffMs, workerData.intervalMs * 2 ** consecutiveFailures);
}
}
} catch (error) {
@@ -34,6 +53,15 @@ try {
}
`;
export interface WalCheckpointerInput {
path: string;
logger: Logger;
onExit: () => void;
intervalMs?: number;
maxConsecutiveFailures?: number;
busyTimeoutMs?: number;
}
/**
* Copies committed WAL pages into the database file from a worker thread. A checkpoint syncs the
* file to disk, which takes up to a hundred milliseconds; on the daemon thread it would stall the
@@ -46,14 +74,19 @@ export class WalCheckpointer {
private stopped = false;
/** `onExit` runs when the worker ends before `stop`, so checkpoints have stopped. */
constructor(input: { path: string; logger: Logger; onExit: () => void }) {
constructor(input: WalCheckpointerInput) {
const { logger } = input;
const intervalMs = input.intervalMs ?? CHECKPOINT_INTERVAL_MS;
this.worker = new Worker(WORKER_SOURCE, {
eval: true,
workerData: {
path: input.path,
state: this.state.buffer,
intervalMs: CHECKPOINT_INTERVAL_MS,
intervalMs,
maxBackoffMs: Math.max(intervalMs, MAX_BACKOFF_MS),
maxConsecutiveFailures: input.maxConsecutiveFailures ?? MAX_CONSECUTIVE_FAILURES,
busyTimeoutMs: input.busyTimeoutMs ?? BUSY_TIMEOUT_MS,
pragmas: CHECKPOINTER_PRAGMAS,
},
// Node 22 prints an experimental warning when the worker loads node:sqlite; the daemon
// already printed it once.
@@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, test } from "vitest";
import { MessageReceipts } from "./index.js";
import { fingerprintRequest, MessageReceipts } from "./index.js";
const directories: string[] = [];
afterEach(async () => {
@@ -76,3 +76,31 @@ test("a send that fails before beforeDispatch can be retried with the same messa
await requests.send(input);
expect(sends).toBe(1);
});
test("a send that defers to the queue does not write a completed receipt until complete is called", async () => {
const { requests, directory } = await fixture();
let attempts = 0;
const request = { prompt: "edit" };
const input = {
agentId: "agent",
messageId: "deferred",
request,
send: async () => {
attempts++;
return "queued" as const;
},
};
await requests.send(input);
// Retrying before delivery completes is not suppressed by a premature completed receipt.
await new MessageReceipts(directory).send(input);
expect(attempts).toBe(2);
// Once the queue completes delivery, retries observe the completed receipt.
await requests.complete({
agentId: "agent",
messageId: "deferred",
fingerprint: fingerprintRequest(request),
});
await new MessageReceipts(directory).send(input);
expect(attempts).toBe(2);
});
@@ -16,8 +16,10 @@ interface SendMessageInput {
/**
* Delivers the message. It awaits `beforeDispatch` immediately before the provider can receive
* the message; a failure before that call proves nothing was submitted and leaves no receipt.
* Returning `"queued"` hands delivery ownership to the queue, so no completed receipt is written
* until `complete` is called on dispatch.
*/
send: (beforeDispatch: () => Promise<void>) => Promise<void>;
send: (beforeDispatch: () => Promise<void>) => Promise<"queued" | void>;
}
interface AcceptMessageInput {
@@ -95,11 +97,13 @@ export class MessageReceipts {
if (await this.isDelivered(key, fingerprint)) return;
const receipt = { fingerprint, agentId: input.agentId };
let pending: Promise<void> | null = null;
await input.send(() => {
const outcome = await input.send(() => {
pending ??= writeJsonFileAtomic(file, { ...receipt, state: "pending" });
return pending;
});
await writeJsonFileAtomic(file, { ...receipt, state: "completed" });
if (outcome !== "queued") {
await writeJsonFileAtomic(file, { ...receipt, state: "completed" });
}
}
}
@@ -5,6 +5,7 @@ import path from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import type { ForgeService } from "../services/forge-service.js";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { WorkspaceGitRuntimeSnapshot, WorkspaceGitService } from "./workspace-git-service.js";
import type {
PersistedProjectRecord,
@@ -1081,15 +1082,118 @@ test.skipIf(isPlatform("win32"))(
},
);
test("passes untrusted: true to worktree.create.after and workspace.create.after for cross-repository checkouts and false for normal workspaces", async () => {
const { repoDir, tempDir } = createGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const worktreeAfterPayloads: unknown[] = [];
const workspaceAfterPayloads: unknown[] = [];
const lifecycle: PluginLifecycle = {
wait: async (_name, payload) => {
worktreeAfterPayloads.push(payload);
},
emit: (name, event) => {
if (name === "workspace.create.after") {
workspaceAfterPayloads.push(event);
}
},
before: async (_name, request) => request,
};
const deps = createDeps({ lifecycle });
deps.github.getPullRequestCheckoutTarget = async ({ number }) => ({
number,
baseRefName: "main",
headRefName: `pr-${number}`,
headOwnerLogin: "fork-owner",
headRepositorySshUrl: null,
headRepositoryUrl: "https://github.com/fork-owner/repo.git",
isCrossRepository: true,
checkoutRefs: [{ remoteName: "origin", remoteRef: `refs/pull/${number}/head` }],
});
// 1. Cross-repository PR checkout -> untrusted: true
const forkCheckout = await createPaseoWorktree(
{
cwd: repoDir,
action: "checkout",
checkoutSource: { kind: "change_request", forge: "github", number: 123 },
paseoHome: path.join(tempDir, ".paseo"),
},
deps,
);
expect(forkCheckout.created).toBe(true);
// 2. Normal branch-off worktree -> untrusted: false
const normalWorktree = await createPaseoWorktree(
{
cwd: repoDir,
branchName: "feature/trusted",
worktreeSlug: "feature-trusted",
paseoHome: path.join(tempDir, ".paseo"),
},
deps,
);
expect(normalWorktree.created).toBe(true);
// 3. Normal local directory workspace -> untrusted: false
const localWorkspace = await deps.workspaceProvisioning.createWorkspaceForDirectory(repoDir);
const matchesRepoDir = createRealpathAwarePathMatcher(repoDir);
expect(worktreeAfterPayloads).toEqual([
{
worktree: {
path: forkCheckout.worktree.worktreePath,
branch: forkCheckout.worktree.branchName,
sourceCheckout: expect.any(String),
untrusted: true,
},
},
{
worktree: {
path: normalWorktree.worktree.worktreePath,
branch: normalWorktree.worktree.branchName,
sourceCheckout: expect.any(String),
untrusted: false,
},
},
]);
for (const payload of worktreeAfterPayloads as { worktree: { sourceCheckout: string } }[]) {
expect(matchesRepoDir(payload.worktree.sourceCheckout)).toBe(true);
}
expect(workspaceAfterPayloads).toEqual([
{
workspace: expect.objectContaining({
id: forkCheckout.workspace.workspaceId,
untrusted: true,
}),
},
{
workspace: expect.objectContaining({
id: normalWorktree.workspace.workspaceId,
untrusted: false,
}),
},
{
workspace: expect.objectContaining({
id: localWorkspace.workspaceId,
untrusted: false,
}),
},
]);
});
interface TestDeps extends CreatePaseoWorktreeDeps {
projects: Map<string, PersistedProjectRecord>;
workspaces: Map<string, PersistedWorkspaceRecord>;
workspaceProvisioning: ReturnType<typeof createWorkspaceProvisioningService>;
}
function createDeps(options?: {
events?: string[];
projects?: Map<string, PersistedProjectRecord>;
workspaces?: Map<string, PersistedWorkspaceRecord>;
lifecycle?: PluginLifecycle;
}): TestDeps {
const events = options?.events ?? [];
const projects = options?.projects ?? new Map<string, PersistedProjectRecord>();
@@ -1156,10 +1260,12 @@ function createDeps(options?: {
workspaceGitService,
isDirectory: async () => true,
logger: createTestLogger(),
lifecycle: options?.lifecycle,
});
return {
github: createGitHubServiceStub(),
lifecycle: options?.lifecycle,
projects,
workspaces,
workspaceGitService,
@@ -92,6 +92,7 @@ async function createPaseoWorktreeWithPriority(
path: createdWorktree.worktree.worktreePath,
branch: createdWorktree.worktree.branchName,
sourceCheckout: workspaceCwdPlan.sourceCheckout,
untrusted: Boolean(createdWorktree.untrustedSource),
},
});
}
@@ -1496,6 +1496,7 @@ test.each([false, true])(
path: cwd,
branch: "plugin-branch",
sourceCheckout: await realpath(repository),
untrusted: false,
});
expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain(
created.workspace!.id,
@@ -1,7 +1,7 @@
import { expect, test } from "vitest";
import { createPaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { validateBeforeResult, PluginHookHandlers } from "./index.js";
import { describeHookWorkspace, validateBeforeResult, PluginHookHandlers } from "./index.js";
const paseo = createPaseoApi(
new DaemonClient({ url: "ws://127.0.0.1:1/ws", clientId: "lifecycle-unit" }),
@@ -604,3 +604,30 @@ test("agent creation hooks keep the workspace, including from plugins that omit
validateBeforeResult("agent.create.before", request, { ...request, workspaceId: "wks_b" }),
).rejects.toThrow("agent.create.before hooks cannot change the workspace");
});
test("describeHookWorkspace exposes untrusted based on untrustedSource", () => {
const base = {
workspaceId: "wks_1",
projectId: "prj_1",
cwd: "/work/a",
kind: "worktree" as const,
displayName: "pr-42",
title: null,
metadata: {},
createdAt: "2026-04-22T00:00:00.000Z",
updatedAt: "2026-04-22T00:00:00.000Z",
archivedAt: null,
};
expect(describeHookWorkspace(base)).toMatchObject({ id: "wks_1", untrusted: false });
expect(
describeHookWorkspace({
...base,
untrustedSource: {
kind: "change_request",
forge: "github",
number: 42,
headRepository: "fork-owner/repo",
},
}),
).toMatchObject({ id: "wks_1", untrusted: true });
});
@@ -236,6 +236,7 @@ export function describeHookWorkspace(workspace: PersistedWorkspaceRecord): Plug
cwd: workspace.cwd,
name: workspace.title,
archivedAt: workspace.archivedAt,
untrusted: Boolean(workspace.untrustedSource),
metadata: workspace.metadata,
};
}
@@ -24,6 +24,24 @@ export function ensurePrivateFile(filePath: string): void {
applyPrivateMode(filePath, PRIVATE_FILE_MODE);
}
/**
* Creates an empty private file (`0o600`) when absent without opening an existing file. Uses
* `O_CREAT | O_EXCL` (`wx`) so an existing inode is never opened and closed (closing any fd to an
* already-open inode drops POSIX `fcntl` locks held by this process).
*/
export function createPrivateFileIfMissing(filePath: string): void {
if (process.platform === "win32") return;
try {
writeFileSync(filePath, "", { flag: "wx", mode: PRIVATE_FILE_MODE });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "EEXIST" || code === "ENOENT" || code === "EISDIR" || code === "ENOTDIR") {
return;
}
throw error;
}
}
export function writePrivateFileAtomicSync(
filePath: string,
data: string | NodeJS.ArrayBufferView,
@@ -13,7 +13,9 @@ import { resolveCreateAgentTitles } from "../agent/create-agent-title.js";
import { type BoundCreateAgentCommand, formatProviderModel } from "../agent/create-agent/create.js";
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
import type { CreatePaseoWorktreeWorkflowResult } from "../worktree-session.js";
import { ScheduleStore } from "./store.js";
import { InvalidScheduleIdError, ScheduleStore } from "./store.js";
export { InvalidScheduleIdError };
import { computeNextRunAt, validateScheduleCadence } from "./cron.js";
import { foldFeatureValues } from "../agent/option-controls.js";
import type {
@@ -1,4 +1,4 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { Writable } from "node:stream";
@@ -362,4 +362,137 @@ describe("ScheduleStore", () => {
});
expect(await gatedStore.list()).toHaveLength(2);
});
test.each(["../sibling", "../config", "a/b", "a\\b", ".", "..", "", "abc\0def", "foo.bar"])(
"rejects invalid schedule id %j across get, update, and delete without touching parent files",
async (invalidId) => {
const schedulesDir = join(tempDir, "schedules");
const scopedStore = new ScheduleStore(schedulesDir, createTestLogger());
const configPath = join(tempDir, "config.json");
const siblingPath = join(tempDir, "sibling.json");
const configContent = JSON.stringify({ port: 6767 });
const siblingContent = JSON.stringify({
id: "../sibling",
name: "outside",
prompt: "do not touch",
cadence: { type: "every", everyMs: 60_000 },
target: { type: "new-agent", config: { provider: "claude", cwd: tempDir } },
status: "active",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
nextRunAt: "2026-01-01T00:01:00.000Z",
lastRunAt: null,
pausedAt: null,
expiresAt: null,
maxRuns: null,
runs: [],
});
await writeFile(configPath, configContent);
await writeFile(siblingPath, siblingContent);
await expect(scopedStore.get(invalidId)).rejects.toThrow(/invalid schedule id/i);
await expect(
scopedStore.update(invalidId, (schedule) => ({ ...schedule, prompt: "mutated" })),
).rejects.toThrow(/invalid schedule id/i);
await expect(scopedStore.delete(invalidId)).rejects.toThrow(/invalid schedule id/i);
expect(await readFile(configPath, "utf-8")).toBe(configContent);
expect(await readFile(siblingPath, "utf-8")).toBe(siblingContent);
},
);
test("ignores persisted schedule files with invalid ids during list and upsertByNameAndTarget", async () => {
const schedulesDir = join(tempDir, "schedules");
const scopedStore = new ScheduleStore(schedulesDir, createTestLogger());
const siblingPath = join(tempDir, "sibling.json");
const siblingContent = JSON.stringify({ hello: "outside" });
await writeFile(siblingPath, siblingContent);
const target = {
type: "new-agent" as const,
config: { provider: "claude" as const, cwd: tempDir },
};
const scheduleWithInvalidId = {
id: "../sibling",
name: "poisoned",
prompt: "before",
cadence: { type: "every" as const, everyMs: 60_000 },
target,
status: "active" as const,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
nextRunAt: "2026-01-01T00:01:00.000Z",
lastRunAt: null,
pausedAt: null,
expiresAt: null,
maxRuns: null,
runs: [],
};
await scopedStore.list();
await writeFile(join(schedulesDir, "poisoned.json"), JSON.stringify(scheduleWithInvalidId));
expect(await scopedStore.list()).toEqual([]);
const upserted = await scopedStore.upsertByNameAndTarget("poisoned", target, {
create: () => ({
name: "poisoned",
prompt: "safe",
cadence: { type: "every", everyMs: 60_000 },
target,
status: "active",
createdAt: "2026-01-01T00:02:00.000Z",
updatedAt: "2026-01-01T00:02:00.000Z",
nextRunAt: "2026-01-01T00:03:00.000Z",
lastRunAt: null,
pausedAt: null,
expiresAt: null,
maxRuns: null,
runs: [],
}),
update: () => {
throw new Error("should not update schedule with invalid id");
},
});
expect(upserted.id).toMatch(/^[0-9a-f]{8}$/);
expect(await readFile(siblingPath, "utf-8")).toBe(siblingContent);
});
test.each(["deadbeef", "schedule-1", "my_schedule_2", "00000000-0000-0000-0000-000000000322"])(
"allows legitimate schedule id format %s across get, update, and delete",
async (validId) => {
const schedulesDir = join(tempDir, "schedules");
const scopedStore = new ScheduleStore(schedulesDir, createTestLogger());
await scopedStore.list();
const record = {
id: validId,
name: "legacy",
prompt: "before",
cadence: { type: "every" as const, everyMs: 60_000 },
target: {
type: "new-agent" as const,
config: { provider: "claude" as const, cwd: tempDir },
},
status: "active" as const,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
nextRunAt: "2026-01-01T00:01:00.000Z",
lastRunAt: null,
pausedAt: null,
expiresAt: null,
maxRuns: null,
runs: [],
};
await writeFile(join(schedulesDir, `${validId}.json`), JSON.stringify(record));
expect(await scopedStore.get(validId)).toEqual(record);
const updated = await scopedStore.update(validId, (current) => ({
...current,
prompt: "after",
}));
expect(updated?.prompt).toBe("after");
await scopedStore.delete(validId);
expect(await scopedStore.get(validId)).toBeNull();
},
);
});
+55 -9
View File
@@ -1,14 +1,28 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, readdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { basename, dirname, join, resolve } from "node:path";
import type { Logger } from "pino";
import {
StoredScheduleSchema,
type ScheduleTarget,
type StoredSchedule,
} from "@getpaseo/protocol/schedule/types";
import { isPathInsideRoot } from "../../utils/path.js";
import { writeJsonFileAtomic } from "../atomic-file.js";
const SCHEDULE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
export class InvalidScheduleIdError extends Error {
constructor(id: string) {
super(`Invalid schedule id: ${JSON.stringify(id)}`);
this.name = "InvalidScheduleIdError";
}
}
export function isValidScheduleId(id: string): boolean {
return typeof id === "string" && SCHEDULE_ID_PATTERN.test(id);
}
function generateScheduleId(): string {
return randomBytes(4).toString("hex");
}
@@ -104,7 +118,14 @@ function parseStoredSchedule(
} catch (error) {
return { success: false, error };
}
return StoredScheduleSchema.safeParse(json);
const parsed = StoredScheduleSchema.safeParse(json);
if (!parsed.success) {
return parsed;
}
if (!isValidScheduleId(parsed.data.id)) {
return { success: false, error: new InvalidScheduleIdError(parsed.data.id) };
}
return parsed;
}
async function readScheduleFile(filePath: string): Promise<string | null> {
@@ -119,6 +140,7 @@ async function readScheduleFile(filePath: string): Promise<string | null> {
}
export class ScheduleStore {
private readonly resolvedDir: string;
private readonly scheduleMutations = new Map<string, Promise<unknown>>();
private readonly identityMutations = new Map<string, Promise<unknown>>();
private reportedInvalidFiles = new Set<string>();
@@ -127,10 +149,23 @@ export class ScheduleStore {
private readonly dir: string,
private readonly logger: Logger,
private readonly onChange?: (schedule: StoredSchedule, change: "write" | "delete") => void,
) {}
) {
this.resolvedDir = resolve(dir);
}
private filePath(id: string): string {
return join(this.dir, `${id}.json`);
if (!isValidScheduleId(id)) {
throw new InvalidScheduleIdError(id);
}
const resolvedPath = resolve(this.resolvedDir, `${id}.json`);
if (
!isPathInsideRoot(this.resolvedDir, resolvedPath) ||
dirname(resolvedPath) !== this.resolvedDir ||
basename(resolvedPath) !== `${id}.json`
) {
throw new InvalidScheduleIdError(id);
}
return resolvedPath;
}
private async ensureDir(): Promise<void> {
@@ -172,9 +207,17 @@ export class ScheduleStore {
}
async get(id: string): Promise<StoredSchedule | null> {
const filePath = this.filePath(id);
await this.ensureDir();
const content = await readScheduleFile(this.filePath(id));
return content === null ? null : StoredScheduleSchema.parse(JSON.parse(content));
const content = await readScheduleFile(filePath);
if (content === null) {
return null;
}
const schedule = StoredScheduleSchema.parse(JSON.parse(content));
if (!isValidScheduleId(schedule.id)) {
throw new InvalidScheduleIdError(schedule.id);
}
return schedule;
}
async create(schedule: Omit<StoredSchedule, "id">): Promise<StoredSchedule> {
@@ -186,6 +229,7 @@ export class ScheduleStore {
}
async update(id: string, updater: ScheduleUpdater): Promise<StoredSchedule | null> {
this.filePath(id);
return this.serializeScheduleMutation(id, async () => {
const current = await this.get(id);
if (!current) {
@@ -240,8 +284,9 @@ export class ScheduleStore {
}
private async write(schedule: StoredSchedule): Promise<void> {
const filePath = this.filePath(schedule.id);
await this.ensureDir();
await writeJsonFileAtomic(this.filePath(schedule.id), schedule);
await writeJsonFileAtomic(filePath, schedule);
this.onChange?.(schedule, "write");
}
@@ -249,12 +294,13 @@ export class ScheduleStore {
id: string,
assertDeletable?: (schedule: StoredSchedule | null) => void,
): Promise<void> {
const filePath = this.filePath(id);
await this.serializeScheduleMutation(id, async () => {
const content = await readScheduleFile(this.filePath(id));
const content = await readScheduleFile(filePath);
const parsed = content === null ? null : parseStoredSchedule(content);
const schedule = parsed?.success ? parsed.data : null;
assertDeletable?.(schedule);
await rm(this.filePath(id), { force: true });
await rm(filePath, { force: true });
if (schedule) {
this.onChange?.(schedule, "delete");
}
+45 -3
View File
@@ -9979,11 +9979,25 @@ export class Session {
);
return;
}
const send = async (beforeDispatch: () => Promise<void>) => {
let switchQueued = false;
const send = async (beforeDispatch: () => Promise<void>): Promise<"queued" | void> => {
// The switch takes its place in the agent's message order, so a message sent while the
// target opens runs after it, on the target.
const switched = await this.agentMessages.sendDirect(
{ recipientId: agentId, prompt, uploadedImages, messageId: msg.messageId },
{
recipientId: agentId,
prompt,
text: msg.text,
attachments: msg.images?.length ? undefined : msg.attachments,
...(msg.images?.length
? { resolveAttachments: () => this.queuedAttachments(msg) }
: {}),
uploadedImages,
messageId: msg.messageId,
sessionMode: providerSwitch.modeId ?? undefined,
providerSwitch,
fingerprint: fingerprintRequest(request),
},
(joined) =>
startProviderSwitchTurn({
agentManager: this.agentManager,
@@ -9996,6 +10010,15 @@ export class Session {
beforeDispatch,
}),
);
if (switched.disposition === "queued") {
switchQueued = true;
void switched.receipt.dispatched.catch((error) => {
if (error instanceof Error && error.name === "AbortError") return;
this.handleAgentRunError(agentId, error, "Failed to dispatch queued provider switch");
});
await this.agentQueue.flush({ agentId });
return "queued";
}
const stored = await this.agentStorage.get(agentId);
if (stored && !stored.title && !stored.lastUserMessageAt) {
const { provisionalTitle } = resolveCreateAgentTitles({ initialPrompt: msg.text });
@@ -10026,6 +10049,12 @@ export class Session {
requestId: msg.requestId,
agentId,
accepted: true,
...(switchQueued
? {
deliveryStatus: "queued" as const,
messageId: msg.messageId,
}
: {}),
...(agentPayload ? { agent: agentPayload } : {}),
error: null,
},
@@ -10197,7 +10226,7 @@ export class Session {
this.handleAgentRunError(agentId, error, "Failed to dispatch queued agent message");
});
};
const send = async (beforeDispatch: () => Promise<void>) => {
const send = async (beforeDispatch: () => Promise<void>): Promise<"queued" | void> => {
if (!msg.sourceAgentId) await this.prepareAgentMessage(agentId, msg.text);
const result = await sendPromptToAgent({
agentMessages: this.agentMessages,
@@ -10205,14 +10234,27 @@ export class Session {
agentStorage: this.agentStorage,
agentId,
prompt,
text: msg.text,
attachments: msg.images?.length ? undefined : msg.attachments,
...(msg.images?.length ? { resolveAttachments: () => this.queuedAttachments(msg) } : {}),
...(uploadedImages.length > 0 ? { uploadedImages } : {}),
messageId: msg.messageId,
fingerprint,
activeTurnBehavior: requested === "steer" ? "steer" : "interrupt",
sessionMode: msg.sessionMode,
clearPendingPermissions: true,
beforeDispatch,
logger: this.sessionLogger,
});
if (result.disposition === "queued") {
queuedReceipt = result.receipt;
void result.receipt.dispatched.catch((error) => {
if (error instanceof Error && error.name === "AbortError") return;
this.handleAgentRunError(agentId, error, "Failed to dispatch queued agent message");
});
await this.agentQueue.flush({ agentId });
return "queued";
}
if (result.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(
this.agentManager,
+10 -8
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,13 +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",
),
}),
store: resolveAgentMessageQueueStore(agentMessageQueueStore),
paseoHome,
recipientStatus: async (agentId) => {
const record = await agentStorage.get(agentId);
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { createForgeService } from "./forge-registry.js";
import { createForgeResolver, forgeForHost, parseRemoteHost } from "./forge-resolver.js";
import { findTeaLoginNameForHost } from "./gitea-checks.js";
function createSshHostnameResolver(hostnameByAlias: Record<string, string | null>) {
return vi.fn(async (host: string): Promise<string | null> => {
@@ -63,6 +64,34 @@ describe("createForgeResolver", () => {
expect(probeForge).toHaveBeenCalledWith("gitlab.example.com");
});
it("resolves an IPv6 workspace origin through its Tea login", async () => {
const logins = JSON.stringify([{ name: "local", ssh_host: "[::1]:2222" }]);
const resolver = createForgeResolver({
resolveRemoteUrl: async () => "ssh://git@[::1]:2222/qa/demo.git",
resolveSshHostname: resolveSshHostnameAsLiteralHost,
probeForge: async (host) => (findTeaLoginNameForHost(logins, host) ? "forgejo" : null),
});
await expect(resolver.resolve("/repo")).resolves.toMatchObject({
forge: "forgejo",
host: "[::1]",
});
});
it("resolves an IPv6 workspace origin when the Tea login spells the address in full", async () => {
const logins = JSON.stringify([{ name: "local", ssh_host: "[0:0:0:0:0:0:0:1]:2222" }]);
const resolver = createForgeResolver({
resolveRemoteUrl: async () => "ssh://git@[::1]:2222/qa/demo.git",
resolveSshHostname: resolveSshHostnameAsLiteralHost,
probeForge: async (host) => (findTeaLoginNameForHost(logins, host) ? "forgejo" : null),
});
await expect(resolver.resolve("/repo")).resolves.toMatchObject({
forge: "forgejo",
host: "[::1]",
});
});
it("resolves an SSH alias that maps to github.com", async () => {
const probeForge = vi.fn(async () => {
throw new Error("github cloud alias should not probe CLI auth");
+37 -2
View File
@@ -236,8 +236,41 @@ export function findTeaLoginNameForBaseUrl(stdout: string, baseUrl: string): str
return match?.name ?? null;
}
// Bracketed IPv6 literals keep their brackets in URLs and in Tea login
// hosts (where a ":port" may follow the closing bracket). Compare hosts
// with the brackets removed so "[::1]" and "[::1]:2222" match "::1".
export function unwrapIpv6Brackets(host: string): string {
if (host.startsWith("[") && host.endsWith("]")) {
return host.slice(1, -1);
}
return host;
}
// Canonicalize an IPv6 literal so different spellings of one address
// ("0:0:0:0:0:0:0:1" and "::1") compare equal. Anything that does not
// parse as an IPv6 literal passes through unchanged.
function normalizeIpv6Literal(address: string): string {
if (!address.includes(":")) {
return address;
}
try {
return unwrapIpv6Brackets(new URL(`http://[${address}]/`).hostname);
} catch {
return address;
}
}
function normalizeTeaLoginCandidate(candidate: string): string {
const normalized = normalizeHost(candidate);
if (normalized.startsWith("[")) {
const closing = normalized.indexOf("]");
if (closing !== -1) return normalizeIpv6Literal(normalized.slice(1, closing));
}
return normalizeIpv6Literal(normalized);
}
export function findTeaLoginNameForHost(stdout: string, host: string): string | null {
const targetHost = normalizeHost(host);
const targetHost = normalizeIpv6Literal(unwrapIpv6Brackets(normalizeHost(host)));
const match = parseTeaLogins(stdout).find((login) => {
const candidates = [login.ssh_host, login.name];
if (login.url) {
@@ -247,7 +280,9 @@ export function findTeaLoginNameForHost(stdout: string, host: string): string |
// ignore malformed login url
}
}
return candidates.some((candidate) => candidate && normalizeHost(candidate) === targetHost);
return candidates.some(
(candidate) => candidate && normalizeTeaLoginCandidate(candidate) === targetHost,
);
});
return match?.name ?? null;
}
@@ -0,0 +1,93 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { PluginHookPayload, PluginServerContext } from "@getpaseo/plugin/server";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import contribute from "./index.server.js";
let root: string;
let source: string;
let worktree: string;
function git(cwd: string, args: string[]): void {
execFileSync("git", args, { cwd, stdio: "pipe" });
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), "worktree-include-plugin-"));
source = join(root, "source");
worktree = join(root, "worktree");
await mkdir(source);
git(source, ["init", "-b", "main", "-q"]);
await writeFile(join(source, ".gitignore"), ".env\n");
await writeFile(join(source, ".worktreeinclude"), ".env\n");
git(source, ["add", ".gitignore", ".worktreeinclude"]);
git(source, [
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"-c",
"commit.gpgsign=false",
"commit",
"-q",
"-m",
"initial",
]);
await writeFile(join(source, ".env"), "SECRET=local");
git(source, ["worktree", "add", "-q", "-b", "feature", worktree]);
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
function registerAfterHook() {
let handler: ((payload: PluginHookPayload<"worktree.create.after">) => Promise<void>) | undefined;
const server = {
addHook(
name: string,
fn: (payload: PluginHookPayload<"worktree.create.after">) => Promise<void>,
) {
if (name === "worktree.create.after") handler = fn;
return () => {};
},
} as unknown as PluginServerContext;
contribute(server);
if (!handler) throw new Error("Expected worktree.create.after hook registration");
return handler;
}
describe("worktree-include plugin", () => {
it("skips copying .worktreeinclude files for untrusted worktrees", async () => {
const onAfter = registerAfterHook();
await onAfter({
worktree: {
path: worktree,
branch: "fork-pr",
sourceCheckout: source,
untrusted: true,
},
});
expect(existsSync(join(worktree, ".env"))).toBe(false);
});
it("copies .worktreeinclude files for trusted worktrees", async () => {
const onAfter = registerAfterHook();
await onAfter({
worktree: {
path: worktree,
branch: "feature",
sourceCheckout: source,
untrusted: false,
},
});
expect(await readFile(join(worktree, ".env"), "utf8")).toBe("SECRET=local");
});
});
+1
View File
@@ -3,6 +3,7 @@ import { copyWorktreeIncludes } from "./server/copy.js";
export default function contribute(server: PluginServerContext) {
return server.addHook("worktree.create.after", async ({ worktree }) => {
if (worktree.untrusted) return;
await copyWorktreeIncludes(worktree.path, worktree.sourceCheckout);
});
}
+114 -1
View File
@@ -1,6 +1,6 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -15,6 +15,9 @@ async function writeSource(files: Record<string, string>): Promise<void> {
await mkdir(dirname(join(source, file)), { recursive: true });
await writeFile(join(source, file), contents);
}
if (".gitignore" in files) {
await writeFile(join(worktree, ".gitignore"), files[".gitignore"]!);
}
}
// Total directories Git visits while listing files, read from its trace2 events.
@@ -47,6 +50,7 @@ beforeEach(async () => {
await mkdir(source);
await mkdir(worktree);
execFileSync("git", ["init", "-q", source]);
execFileSync("git", ["init", "-q", worktree]);
});
afterEach(async () => {
@@ -250,6 +254,7 @@ describe("copyWorktreeIncludes", () => {
it("matches patterns case-insensitively when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
execFileSync("git", ["-C", worktree, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": ".env\nconfig/\n",
".worktreeinclude": ".ENV\nCONFIG/a.json\n",
@@ -262,6 +267,7 @@ describe("copyWorktreeIncludes", () => {
it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
execFileSync("git", ["-C", worktree, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": "Config/\nÉTÉ/\n",
".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n",
@@ -301,4 +307,111 @@ describe("copyWorktreeIncludes", () => {
expect(await copied()).toEqual(["newdir/.env"]);
});
it("rejects a symlinked parent directory in the destination worktree", async () => {
const outside = join(root, "outside");
await mkdir(outside);
await writeSource({
".gitignore": "config/*.local.json\n",
".worktreeinclude": "config/*.local.json\n",
"config/app.local.json": "SECRET=local",
});
await symlink(outside, join(worktree, "config"));
await expect(copyWorktreeIncludes(worktree, source)).rejects.toThrow(/symlink/i);
expect(existsSync(join(outside, "app.local.json"))).toBe(false);
});
it("rejects a dangling leaf symlink in the destination worktree", async () => {
const outside = join(root, "outside");
await mkdir(outside);
const outsideTarget = join(outside, "stolen.env");
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=local",
});
await symlink(outsideTarget, join(worktree, ".env"));
await expect(copyWorktreeIncludes(worktree, source)).rejects.toThrow(/symlink/i);
expect(existsSync(outsideTarget)).toBe(false);
});
it("rejects a live leaf symlink in the destination worktree", async () => {
const outside = join(root, "outside");
await mkdir(outside);
const outsideTarget = join(outside, "existing.env");
await writeFile(outsideTarget, "ORIGINAL");
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=local",
});
await symlink(outsideTarget, join(worktree, ".env"));
await expect(copyWorktreeIncludes(worktree, source)).rejects.toThrow(/symlink/i);
expect(await readFile(outsideTarget, "utf8")).toBe("ORIGINAL");
});
it("skips files that are not gitignored in the destination worktree", async () => {
await writeSource({
".gitignore": ".env\nconfig/*.local.json\n",
".worktreeinclude": ".env\nconfig/*.local.json\n",
".env": "SECRET=root",
"config/app.local.json": "SECRET=config",
});
// Destination worktree only ignores .env, not config/*.local.json.
await writeFile(join(worktree, ".gitignore"), ".env\n");
const result = await copyWorktreeIncludes(worktree, source);
expect(result).toEqual({
kind: "copied",
copied: [".env"],
skipped: ["config/app.local.json"],
});
expect(existsSync(join(worktree, "config"))).toBe(false);
});
it("skips files that are tracked in the destination worktree even when deleted on disk", async () => {
await writeSource({
".gitignore": ".env\nconfig/*.local.json\n",
".worktreeinclude": ".env\nconfig/*.local.json\n",
".env": "SECRET=source",
"config/app.local.json": "SECRET=config",
});
await writeFile(join(worktree, ".gitignore"), ".env\nconfig/*.local.json\n");
await writeFile(join(worktree, ".env"), "TRACKED=1");
execFileSync("git", ["add", ".gitignore"], { cwd: worktree, stdio: "pipe" });
execFileSync("git", ["add", "-f", ".env"], { cwd: worktree, stdio: "pipe" });
await rm(join(worktree, ".env"));
const result = await copyWorktreeIncludes(worktree, source);
expect(result).toEqual({
kind: "copied",
copied: ["config/app.local.json"],
skipped: [".env"],
});
expect(existsSync(join(worktree, ".env"))).toBe(false);
});
it("skips a tracked symlink in the destination worktree", async () => {
await writeSource({
".gitignore": "local.json\n",
".worktreeinclude": "local.json\n",
"local.json": '{"secret":true}',
});
await writeFile(join(worktree, ".gitignore"), "local.json\n");
await writeFile(join(worktree, "shared.json"), '{"shared":true}');
await symlink("shared.json", join(worktree, "local.json"));
execFileSync("git", ["add", ".gitignore", "shared.json"], { cwd: worktree, stdio: "pipe" });
execFileSync("git", ["add", "-f", "local.json"], { cwd: worktree, stdio: "pipe" });
const result = await copyWorktreeIncludes(worktree, source);
expect(result).toEqual({
kind: "copied",
copied: [],
skipped: ["local.json"],
});
expect(await readFile(join(worktree, "shared.json"), "utf8")).toBe('{"shared":true}');
});
});
+112 -10
View File
@@ -1,10 +1,10 @@
// Derived from cprecioso/paseo-worktreeinclude (MIT); see ./LICENSE in the plugin root.
// Copyright (c) 2026 Carlos Precioso.
import { execFile } from "node:child_process";
import { constants, existsSync } from "node:fs";
import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { constants, existsSync, type Stats } from "node:fs";
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { isAbsolute, join, relative, sep } from "node:path";
import { promisify } from "node:util";
const exec = promisify(execFile);
@@ -47,31 +47,133 @@ const splitNul = (s: string) => s.split("\0").filter(Boolean);
const isDirectory = (entry: string) => entry.endsWith("/");
// Copy files that match .worktreeinclude (gitignore syntax)
// AND are gitignored, so tracked files are never touched.
// AND are gitignored and untracked in both source and destination,
// rejecting symlinks in destination path components.
export async function copyWorktreeIncludes(worktree: string, source: string): Promise<CopyResult> {
if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" };
const matches = await findIncludedFiles(source);
if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] };
const ignored = await checkIgnore(source, [], matches);
const sourceIgnored = await checkIgnore(source, [], matches);
if (sourceIgnored.length === 0) return { kind: "copied", copied: [], skipped: [] };
const candidates = sourceIgnored.map((file) => ({
file,
segments: destinationSegments(worktree, file),
}));
// Reject symlinks in parent directories before git check-ignore traverses them;
// leaf symlinks are checked below only when the destination path is ignored/untracked.
for (const { file, segments } of candidates) {
await assertNoDestinationParentSymlinks(worktree, file, segments.slice(0, -1));
}
const destinationIgnored = new Set(await checkIgnore(worktree, [], sourceIgnored));
const copied: string[] = [];
const skipped: string[] = [];
for (const file of ignored) {
const dest = join(worktree, file);
if (existsSync(dest)) {
for (const { file, segments } of candidates) {
if (!destinationIgnored.has(file)) {
skipped.push(file);
continue;
}
const dest = join(worktree, ...segments);
await ensureDestinationDirectory(worktree, file, segments.slice(0, -1));
const destStats = await lstatOrNull(dest);
if (destStats !== null) {
if (destStats.isSymbolicLink()) {
throw new Error(
`Refusing to copy "${file}": destination path component "${file}" is a symlink`,
);
}
skipped.push(file);
continue;
}
await mkdir(dirname(dest), { recursive: true });
// Clone (APFS/btrfs copy-on-write) when supported, else fall back to a regular copy.
await copyFile(join(source, file), dest, constants.COPYFILE_FICLONE);
// COPYFILE_EXCL uses O_CREAT | O_EXCL so a destination symlink is never followed.
await copyFile(join(source, file), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
copied.push(file);
}
return { kind: "copied", copied, skipped };
}
function destinationSegments(worktree: string, file: string): string[] {
if (!file || isAbsolute(file) || (process.platform === "win32" && file.includes("\\"))) {
throw new Error(`Refusing to copy "${file}": invalid relative destination path`);
}
const segments = file.split("/");
if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) {
throw new Error(`Refusing to copy "${file}": invalid relative destination path`);
}
const dest = join(worktree, ...segments);
const rel = relative(worktree, dest);
if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
throw new Error(`Refusing to copy "${file}": destination escapes worktree`);
}
return segments;
}
async function lstatOrNull(target: string): Promise<Stats | null> {
try {
return await lstat(target);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
}
async function assertNoDestinationParentSymlinks(
worktree: string,
file: string,
parentSegments: readonly string[],
): Promise<void> {
let current = worktree;
for (let i = 0; i < parentSegments.length; i++) {
current = join(current, parentSegments[i]!);
const stats = await lstatOrNull(current);
if (stats === null) return;
if (stats.isSymbolicLink()) {
const component = parentSegments.slice(0, i + 1).join("/");
throw new Error(
`Refusing to copy "${file}": destination path component "${component}" is a symlink`,
);
}
if (!stats.isDirectory()) return;
}
}
async function ensureDestinationDirectory(
worktree: string,
file: string,
parentSegments: readonly string[],
): Promise<void> {
let current = worktree;
for (let i = 0; i < parentSegments.length; i++) {
current = join(current, parentSegments[i]!);
const component = parentSegments.slice(0, i + 1).join("/");
let stats = await lstatOrNull(current);
if (stats === null) {
try {
await mkdir(current);
continue;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
stats = await lstat(current);
}
}
if (stats.isSymbolicLink()) {
throw new Error(
`Refusing to copy "${file}": destination path component "${component}" is a symlink`,
);
}
if (!stats.isDirectory()) {
throw new Error(
`Cannot copy "${file}": destination path component "${component}" is not a directory`,
);
}
}
}
// Git lists a directory it ignores as a whole, such as node_modules/, as one entry.
// Only directories that a pattern matches or names a path inside are searched, and
// only as deep as the pattern names, so creating a worktree does not walk every file
+12 -9
View File
@@ -88,6 +88,7 @@ interface PluginHookWorkspace {
cwd: string;
name: string | null;
archivedAt: string | null;
readonly untrusted: boolean;
metadata: Record<string, JsonValue>;
}
@@ -97,14 +98,15 @@ type PluginTurnOutcome =
| { kind: "canceled"; reason: string };
```
| Field | Shape / meaning |
| ------------ | -------------------------------------------------------------------------------------- |
| `background` | `true` for a [background agent](#background-agents) |
| `turnId` | Provider-reported `string` or `null`; unique across resumed sessions |
| `timeline` | Deprecated, always `[]`; fetch history with the SDK. |
| `request` | SDK `AgentPermissionRequest`; `kind` is `tool`, `plan`, `question`, `mode`, or `other` |
| `resolution` | SDK `AgentPermissionResponse` |
| `archivedAt` | Timestamp string |
| Field | Shape / meaning |
| ------------ | --------------------------------------------------------------------------------------------------- |
| `background` | `true` for a [background agent](#background-agents) |
| `untrusted` | `true` when the workspace or worktree comes from an untrusted source, such as a fork change request |
| `turnId` | Provider-reported `string` or `null`; unique across resumed sessions |
| `timeline` | Deprecated, always `[]`; fetch history with the SDK. |
| `request` | SDK `AgentPermissionRequest`; `kind` is `tool`, `plan`, `question`, `mode`, or `other` |
| `resolution` | SDK `AgentPermissionResponse` |
| `archivedAt` | Timestamp string |
## Metadata
@@ -231,7 +233,7 @@ Ordering: `worktree.create.before` → worktree manager `create` (or `git worktr
## worktree.create.after
Paseo waits for this hook after a new git worktree exists and before workspace registration, setup, terminals, or agents. Receives `{ worktree: { path, branch, sourceCheckout } }`: the absolute worktree path, branch name, and source checkout directory. There is no workspace id yet. Return nothing; write files directly into the worktree. Throwing or exceeding 30 seconds aborts creation and removes the new worktree.
Paseo waits for this hook after a new git worktree exists and before workspace registration, setup, terminals, or agents. Receives `{ worktree: { path, branch, sourceCheckout, untrusted } }`: the absolute worktree path, branch name, source checkout directory, and whether the worktree comes from an untrusted source such as a fork change request. There is no workspace id yet. Return nothing; write files directly into the worktree. Skip copying secrets or running repository-defined automation when `worktree.untrusted` is `true`. Throwing or exceeding 30 seconds aborts creation and removes the new worktree.
This covers branch-off, branch checkout, and PR checkout creation. Restoring a missing archived worktree uses a separate recovery path and does not fire this hook.
@@ -239,6 +241,7 @@ This covers branch-off, branch checkout, and PR checkout creation. Restoring a m
import { copyFile } from "node:fs/promises";
server.addHook("worktree.create.after", async ({ worktree }) => {
if (worktree.untrusted) return;
await copyFile(`${worktree.sourceCheckout}/.env`, `${worktree.path}/.env`);
});
```
+4 -1
View File
@@ -86,6 +86,7 @@ interface PluginHookWorkspace {
cwd: string;
name: string | null;
archivedAt: string | null;
readonly untrusted: boolean;
metadata: Record<string, JsonValue>;
}
@@ -98,6 +99,7 @@ type PluginTurnOutcome =
| 字段 | 结构 / 含义 |
| ------------ | ---------------------------------------------------------------------------------------- |
| `background` | [后台 Agent](#background-agents) 为 `true` |
| `untrusted` | 工作区或 worktree 来自不受信任的来源(例如 fork 变更请求)时为 `true` |
| `turnId` | Provider 报告的 `string` 或 `null`;在会话恢复后仍保持唯一 |
| `timeline` | 已弃用,始终为 `[]`;通过 SDK 获取历史。 |
| `request` | SDK 的 `AgentPermissionRequest`;`kind` 为 `tool`、`plan`、`question`、`mode` 或 `other` |
@@ -228,7 +230,7 @@ Paseo 解析父目录中的符号链接并验证返回的路径。路径必须
## worktree.create.after {#worktreecreateafter}
新的 git worktree 在磁盘上创建后,Paseo 会等待此钩子,然后才注册工作区、运行 setup、打开终端或启动 Agent。收到 `{ worktree: { path, branch, sourceCheckout } }`,分别是 worktree 绝对路径、分支名、来源 checkout 目录。此时还没有工作区 id。无需返回数据,直接写入 worktree 即可。抛出错误或超过 30 秒会中止创建并删除新 worktree。
新的 git worktree 在磁盘上创建后,Paseo 会等待此钩子,然后才注册工作区、运行 setup、打开终端或启动 Agent。收到 `{ worktree: { path, branch, sourceCheckout, untrusted } }`,分别是 worktree 绝对路径、分支名、来源 checkout 目录,以及该 worktree 是否来自不受信任的来源(例如 fork 变更请求)。此时还没有工作区 id。无需返回数据,直接写入 worktree 即可。当 `worktree.untrusted` 为 `true` 时,跳过复制密钥或运行仓库内定义的自动化逻辑。抛出错误或超过 30 秒会中止创建并删除新 worktree。
此钩子覆盖新建分支、检出分支和检出 PR。恢复缺失的已归档 worktree 使用独立路径,不触发此钩子。
@@ -236,6 +238,7 @@ Paseo 解析父目录中的符号链接并验证返回的路径。路径必须
import { copyFile } from "node:fs/promises";
server.addHook("worktree.create.after", async ({ worktree }) => {
if (worktree.untrusted) return;
await copyFile(`${worktree.sourceCheckout}/.env`, `${worktree.path}/.env`);
});
```
+3 -2
View File
@@ -43,10 +43,11 @@ Paseo does not search inside a directory that Git ignores as a whole, such as `n
The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run.
- Without `.worktreeinclude`, the plugin copies nothing.
- Matching files must exist in the source checkout.
- Matching files must exist in the source checkout and remain gitignored and untracked in the destination worktree.
- Untrusted cross-repository checkouts, such as fork pull requests, skip copying.
- Existing destination files are skipped, preserving their contents.
- Copies happen during creation, with no ongoing synchronization between checkouts.
- A copy error aborts creation and removes the new worktree. Avoid including symlinked directories or nested repositories, which cannot be copied as files.
- A copy error or a symlink in a destination path aborts creation and removes the new worktree. Avoid including symlinked directories or nested repositories, which cannot be copied as files.
## Run commands during setup
@@ -43,10 +43,11 @@ config/*.local.json
内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。
- 没有 `.worktreeinclude` 时,插件不会复制任何文件。
- 匹配的文件必须存在于源检出中。
- 匹配的文件必须存在于源检出中,并且在目标 worktree 中仍处于 Git 忽略且未跟踪状态。
- 不受信任的跨仓库检出(例如 fork PR)会跳过复制。
- 目标中已存在的文件会被跳过,保留原有内容。
- 复制发生在创建期间,之后不会在检出之间持续同步。
- 复制错误会中止创建并删除新 worktree。避免包含符号链接目录或嵌套仓库,因为它们无法作为文件复制。
- 复制错误或目标路径中的符号链接会中止创建并删除新 worktree。避免包含符号链接目录或嵌套仓库,因为它们无法作为文件复制。
## 在 setup 期间运行命令 {#run-commands-during-setup}