Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 5fd6783c19 fix(agents): forward history option through createAgentInternal 2026-11-26 02:47:09 +01:00
Mohamed Boudra 4719186fbb test(server): give the terminal workspace test's cleanup longer on Windows
On Windows the stopped `sleeper` script's process can still hold the project
directory as its working directory when the test removes it, failing cleanup
with EBUSY. rm's retries now wait up to about 5 s for the handle to go.
2026-11-26 02:46:04 +01:00
Mohamed Boudra cd2bfa91a8 fix(timeline): serve an empty older page before a retired first turn in SQLite
The SQLite backend's `before` selection had the same gap as the memory
projection fixed on the base branch: with no active row by the cursor it
returned the first later row as the start of an empty page. It now serves the
empty page, matching the memory backend in the contract and differential tests.
2026-11-26 02:46:04 +01:00
Mohamed Boudra b26f19accd feat(timeline): record the provider that wrote each row
An agent's history can span providers once it switches, so a row served with
the agent's current provider would be rendered as the wrong one. Live writes,
provider history imports, opening notices and subagent rows now store their
provider in the row; the timeline page and replay serve it, falling back to
the agent's provider for rows written before this change. SQLite keeps it in
the row JSON, so the schema is unchanged.
2026-11-26 02:46:04 +01:00
Mohamed Boudra 8aba8bde08 fix(daemon): close paseo.db when startup or shutdown fails
A throw while the daemon assembled itself after opening paseo.db, or from a
shutdown step before the timeline close, left the connection and its WAL open
for the next daemon. `createPaseoDaemon` now owns the database and closes it
when assembly throws, and `stop()` closes it in `finally`.
2026-11-26 02:46:04 +01:00
Mohamed Boudra 29c448ac96 fix(timeline): reset an after cursor that is ahead of the history
A client whose cursor is past the stored history (commits lost in a crash, a
restored paseo.db) kept its cursor on an empty page, then dropped the rows
whose seqs it believed it already had. `fetchTimelinePage` now treats it as a
gap, so the client replaces its history with the tail.
2026-11-26 02:45:19 +01:00
Mohamed Boudra e03503c0de test(server): retry removing the restart test's directories on Windows
Windows reported EBUSY removing the agent directory right after the
second daemon closed. Retry the removal as the test daemon's own
cleanup does.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 16c8a188e0 perf(timeline): read the chat outline's cursor from the head, not a tail page
The prompt index fetched a one-row tail page only for its epoch and
retirement count. A tool call updated after other rows makes that page
cover every row in between, so the outline still decoded tool output.
AgentTimeline.readPrompts returns the prompt rows with the head they
belong to, in one timeline operation.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 325a65acac fix(agents): let an agent keep saving its record after a failed delete
The delete RPC fences the record against writes before closing the agent.
Since a failed history delete now leaves the record in place, the fence
stayed up for the rest of the process, so a later rename reported success
and never reached disk. The fence now ends when the delete aborts.
2026-11-26 02:45:19 +01:00
Mohamed Boudra 3c5654d2ab fix(timeline): keep history on reopen, fail deletes that leave it, read only prompts for the outline
- Opening a stored agent with no provider session ran the fresh-create
  cleanup, which deleted its saved timeline. Now that history survives a
  restart, that open erased it; the record-based open now clears only the
  previous session's runtime state.
- The delete RPC removed the registry record first and swallowed a failed
  history delete, replying agent_deleted while the transcript stayed on
  disk with no record to retry from. History now goes first and a failure
  reaches the client as rpc_error with the agent still listed.
- The chat outline built its prompt index from every active row, which on
  SQLite decodes all replies and tool output. Backends now return the
  active prompt rows, which the rewind and import paths already read.
2026-11-26 02:45:19 +01:00
Mohamed Boudra e531eb1f1a chore(nix): update npm dependency hash for the Node 22.16 types 2026-11-26 02:45:19 +01:00
Mohamed Boudra a462c43de2 fix(timeline): keep stored history private, exact, and off the turn's path
- paseo.db and its WAL files are set to mode 0600 on every open. They
  hold every prompt and reply.
- Internal agents keep their history in memory. Before this change it
  went to paseo.db and outlived a crash, which broke the rule that
  nothing about an internal agent is on disk.
- Text chunks are stored as JSON strings. node:sqlite reads a TEXT
  value only up to its first NUL, and a chunk can end inside a
  surrogate pair.
- A turn's handler now changes the agent's state before any timeline
  write. Before, a failed metrics stamp skipped the turn_completed
  handler, so a turn the provider started stayed running.
- Node 22.13, which has node:sqlite but not isTransaction, is refused
  at open.
- If the checkpoint worker cannot start, the daemon logs it and falls
  back to SQLite's auto-checkpoint. Before, the error reported an
  already committed write as failed.
2026-11-26 02:45:18 +01:00
Mohamed Boudra 511306bd25 test(cli): reopen the idle agent explicitly after a supervisor restart
Fetching an agent's timeline now reads stored history without loading the agent, so the agent stays closed until it is reopened.
2026-11-26 02:44:45 +01:00
Mohamed Boudra eed84c01f1 test(agents): prove a run's caller hears a turn whose record failed 2026-11-26 02:44:45 +01:00
Mohamed Boudra 6d21e28e06 feat(timeline): store agent timelines in paseo.db
Agent history now survives a daemon restart, and closed or archived
agents hold no timeline in memory. A history fetch reads paseo.db and
starts no provider.

The daemon opens one SQLite database at $PASEO_HOME/paseo.db with
node:sqlite. Each schema module owns its tables and migrations, and
records a min_reader_version, so an older daemon refuses a database
it cannot read instead of corrupting it. Node 22.16 is the floor,
because DatabaseSync needs it.

A worker thread runs the WAL checkpoints. A checkpoint syncs the
file, and on the daemon thread it stalled the event loop for up to
119 ms on whichever write crossed the auto-checkpoint threshold. If
the worker exits, the daemon returns to SQLite's auto-checkpoint.

A turn's final event now ends the run even when the timeline fails
to write it. Before this change the error escaped handleStreamEvent
before settleTerminalRun, so the agent stayed running and its waiters
hung. The durable store makes that write fallible, and shutdown made
it fail: settled() rejected after close.
2026-11-26 02:44:45 +01:00
36 changed files with 3821 additions and 380 deletions
+2 -1
View File
@@ -403,7 +403,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items. client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics. - Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up. - Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id. - Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
## Right-sidebar boundary: directory-backed vs workspace-owned ## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -479,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
``` ```
$PASEO_HOME/ $PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record ├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry ├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry ├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images ├── projects/icons/ # Custom project icon images
+37 -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 `worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`. checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is 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 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`). All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,6 +53,7 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600) ├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file ├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600) ├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable) ├── daemon.log # Default log file (path configurable)
├── agents/ ├── agents/
│ └── {sanitized-cwd}/ │ └── {sanitized-cwd}/
@@ -181,11 +182,42 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
--- ---
## Runtime-only Agent Timelines ## Daemon database
Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind `$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume (`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
imports provider history. See [owned history](timeline-sync.md#owned-history). `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
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
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).
--- ---
+12 -7
View File
@@ -46,19 +46,24 @@ deleting the agent, or a provider removing one of its own children, deletes hist
for example because the provider stored expanded attachment text, the chat stays unchanged and for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again. Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them - **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Deleting the agent deletes its history and every child's, retired ones without its provider. Opening a stored agent that has no provider session to resume starts its
included. first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created. `epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its `AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The only backend keeps everything in `TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
memory, so a daemon restart loses the owned history: the next resume imports provider history into [daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
back if the provider history still holds them. Retained history costs memory for every loaded, closed or archived agent holds no history in memory. Each fetch reads the page from the database
closed or archived agent until the daemon exits or the agent is deleted. and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
+1 -1
View File
@@ -1 +1 @@
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28= sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
+20 -1
View File
@@ -45,6 +45,9 @@
"react-dom": "19.2.3", "react-dom": "19.2.3",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"ws": "^8.20.0" "ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
} }
}, },
"node_modules/@0no-co/graphql.web": { "node_modules/@0no-co/graphql.web": {
@@ -39719,6 +39722,9 @@
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vitest": "^4.1.6", "vitest": "^4.1.6",
"zx": "^8.8.5" "zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
} }
}, },
"packages/cli/node_modules/@vitest/expect": { "packages/cli/node_modules/@vitest/expect": {
@@ -40646,7 +40652,7 @@
"@playwright/test": "^1.56.1", "@playwright/test": "^1.56.1",
"@types/express": "^4.17.20", "@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0", "@types/markdown-it": "^14.2.0",
"@types/node": "^20.9.0", "@types/node": "^22.16.0",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7", "@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8", "@types/ws": "^8.5.8",
@@ -40654,6 +40660,9 @@
"cross-env": "^10.1.0", "cross-env": "^10.1.0",
"tsx": "^4.6.0", "tsx": "^4.6.0",
"vitest": "^4.1.6" "vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
} }
}, },
"packages/server/node_modules/@esbuild/aix-ppc64": { "packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41101,6 +41110,16 @@
"@types/mdurl": "^2" "@types/mdurl": "^2"
} }
}, },
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": { "packages/server/node_modules/@vitest/expect": {
"version": "4.1.6", "version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
+3
View File
@@ -169,5 +169,8 @@
"tiny-async-pool": { "tiny-async-pool": {
"semver@^5": "5.7.2" "semver@^5": "5.7.2"
} }
},
"engines": {
"node": ">=22.16.0"
} }
} }
+3
View File
@@ -47,5 +47,8 @@
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vitest": "^4.1.6", "vitest": "^4.1.6",
"zx": "^8.8.5" "zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
} }
} }
@@ -210,7 +210,12 @@ try {
console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited."); console.log("Foreground SIGINT reached the supervisor. The worker and ACP processes exited.");
daemon = await startSupervisor(); daemon = await startSupervisor();
const restoredIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent; // The stored timeline is served without reopening the agent.
const storedIdle = (await daemon.client.fetchAgentTimeline(idle.id)).agent;
assert.equal(storedIdle?.status, "closed");
assert.equal(storedIdle?.requiresAttention, false);
await daemon.client.refreshAgent(idle.id);
const restoredIdle = (await daemon.client.fetchAgent(idle.id))?.agent;
assert.equal(restoredIdle?.status, "idle"); assert.equal(restoredIdle?.status, "idle");
assert.equal(restoredIdle?.requiresAttention, false); assert.equal(restoredIdle?.requiresAttention, false);
await waitFor(async () => { await waitFor(async () => {
+4 -1
View File
@@ -160,7 +160,7 @@
"@playwright/test": "^1.56.1", "@playwright/test": "^1.56.1",
"@types/express": "^4.17.20", "@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0", "@types/markdown-it": "^14.2.0",
"@types/node": "^20.9.0", "@types/node": "^22.16.0",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7", "@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8", "@types/ws": "^8.5.8",
@@ -171,5 +171,8 @@
}, },
"overrides": { "overrides": {
"lightningcss": "1.30.1" "lightningcss": "1.30.1"
},
"engines": {
"node": ">=22.16.0"
} }
} }
@@ -22,8 +22,8 @@ import {
type ManagedAgent, type ManagedAgent,
} from "./agent-manager.js"; } from "./agent-manager.js";
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
import { AgentTimeline } from "./timeline/index.js"; import { AgentTimeline, createStoredAgentTimeline } from "./timeline/index.js";
import { DeferredTimelineBackend } from "./timeline/testing.js"; import { DeferredTimelineBackend, openTestTimelineDatabase } from "./timeline/testing.js";
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
import { ForegroundPromptStart } from "./agent-run-state.js"; import { ForegroundPromptStart } from "./agent-run-state.js";
import { import {
@@ -971,6 +971,52 @@ test("Reload agent keeps the history and its identity, and adds only what the pr
} }
}); });
test("records the provider that wrote each row, live or from provider history", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-row-provider-"));
class HistorySession extends TestAgentSession {
override async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
yield {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "continue", messageId: "provider-1" },
};
}
}
class HistoryClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new HistorySession(config);
}
override async resumeSession(
_handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
): Promise<AgentSession> {
return new HistorySession({ provider: "codex", cwd: config?.cwd ?? workdir });
}
}
const manager = new AgentManager({
clients: { codex: new HistoryClient() },
timeline: new AgentTimeline(new DeferredTimelineBackend()),
logger,
});
let agentId: string | null = null;
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
agentId = agent.id;
expect(await reloadAgent(manager, agent.id)).toEqual({ kind: "appended" });
await manager.appendTimelineItem(agent.id, { type: "assistant_message", text: "live" });
await manager.flush();
const page = await manager.fetchTimeline(agent.id);
expect(page.rows.map((row) => row.provider)).toEqual(["codex", "codex"]);
} finally {
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
});
test("Reload agent adds the provider children of new turns and leaves the children Paseo shows alone", async () => { test("Reload agent adds the provider children of new turns and leaves the children Paseo shows alone", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-timeline-reload-children-")); const workdir = mkdtempSync(join(tmpdir(), "agent-manager-timeline-reload-children-"));
const providerHistory: AgentStreamEvent[] = [ const providerHistory: AgentStreamEvent[] = [
@@ -6898,6 +6944,207 @@ test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt); expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
}); });
test("a turn ends even when the timeline fails to record how it ended", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-terminal-record-failure-"));
class FailingTurnClient extends TestAgentClient {
readonly session = new TestAgentSession({ provider: "codex", cwd: workdir });
override async createSession(): Promise<AgentSession> {
return this.session;
}
}
const client = new FailingTurnClient();
const backend = new DeferredTimelineBackend();
const manager = new AgentManager({
clients: { codex: client },
timeline: new AgentTimeline(backend),
logger,
});
onTestFinished(async () => {
await manager.closeAgent(agent.id);
await manager.flush();
rmSync(workdir, { recursive: true, force: true });
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const running = waitForAgentLifecycle(manager, agent.id, "running");
client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "failed-turn" });
await running;
const failed = waitForAgentLifecycle(manager, agent.id, "error");
// The turn's error message is the write that fails.
backend.failNextAppend = true;
client.session.pushEvent({
type: "turn_failed",
provider: "codex",
turnId: "failed-turn",
error: "Selected model is at capacity.",
});
await failed;
expect(manager.getAgent(agent.id)?.lifecycle).toBe("error");
// The failed turn no longer holds the agent: its next turn runs and records.
const runningAgain = waitForAgentLifecycle(manager, agent.id, "running");
client.session.pushEvent({ type: "turn_started", provider: "codex", turnId: "next-turn" });
await runningAgain;
});
test("a run's caller hears how its turn ended even when the timeline fails to record it", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-run-record-failure-"));
const turnId = "failing-run";
class HeldTurnSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
setTimeout(() => this.pushEvent({ type: "turn_started", provider: "codex", turnId }), 0);
return { turnId };
}
}
const session = new HeldTurnSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const backend = new DeferredTimelineBackend();
const manager = new AgentManager({
clients: { codex: client },
timeline: new AgentTimeline(backend),
logger,
});
onTestFinished(async () => {
await manager.closeAgent(agent.id);
await manager.flush();
rmSync(workdir, { recursive: true, force: true });
});
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const running = waitForAgentLifecycle(manager, agent.id, "running");
const run = manager.runAgent(agent.id, "hello");
await running;
await manager.flush();
// The turn's error message is the write that fails.
const failed = waitForAgentLifecycle(manager, agent.id, "error");
backend.failNextAppend = true;
session.pushEvent({
type: "turn_failed",
provider: "codex",
turnId,
error: "Selected model is at capacity.",
});
await expect(run).rejects.toThrow("Selected model is at capacity.");
await failed;
});
test("a turn the provider started ends even when the timeline fails to record its metrics", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-metrics-record-failure-"));
const session = new TestAgentSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const backend = new DeferredTimelineBackend();
const manager = new AgentManager({
clients: { codex: client },
timeline: new AgentTimeline(backend),
logger,
});
onTestFinished(async () => {
await manager.closeAgent(agent.id);
await manager.flush();
rmSync(workdir, { recursive: true, force: true });
});
const agent = await manager.createAgent(
{ provider: "codex", cwd: workdir, model: "gpt-5.2-codex" },
undefined,
{ workspaceId: undefined },
);
const running = waitForAgentLifecycle(manager, agent.id, "running");
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "provider-turn" });
await running;
const idle = waitForAgentLifecycle(manager, agent.id, "idle");
backend.failNextStampTurnMetrics = true;
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "provider-turn" });
await idle;
expect(backend.failNextStampTurnMetrics).toBe(false);
});
test("an internal agent's history stays out of the daemon database", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-internal-timeline-"));
const database = openTestTimelineDatabase();
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
timeline: createStoredAgentTimeline(database),
logger,
});
onTestFinished(async () => {
await manager.closeAgent(internal.id);
await manager.closeAgent(visible.id);
await manager.flush();
rmSync(workdir, { recursive: true, force: true });
});
const internal = await manager.createAgent(
{ provider: "codex", cwd: workdir, internal: true },
undefined,
{ workspaceId: undefined },
);
const visible = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const reply: AgentTimelineItem = { type: "assistant_message", text: "a commit message" };
await manager.appendTimelineItem(internal.id, reply);
await manager.appendTimelineItem(visible.id, reply);
await manager.flush();
expect(await manager.getTimeline(internal.id)).toEqual([reply]);
const storedAgents = database.read((sql) =>
sql
.all<{ agent_id: string }>("SELECT agent_id FROM timeline_scopes")
.map((row) => row.agent_id),
);
expect(storedAgents).toEqual([visible.id]);
});
test("reopening an agent the provider never gave a session keeps its saved history", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reopen-without-session-"));
const storagePath = join(workdir, "agents");
const database = openTestTimelineDatabase();
function startDaemon(): { manager: AgentManager; storage: AgentStorage } {
const storage = new AgentStorage(storagePath, logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
timeline: createStoredAgentTimeline(database),
logger,
});
return { manager, storage };
}
const first = startDaemon();
const agent = await first.manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const reply: AgentTimelineItem = { type: "assistant_message", text: "kept across restarts" };
await first.manager.appendTimelineItem(agent.id, reply);
await first.manager.closeAgent(agent.id);
await first.manager.flush();
const record = await first.storage.get(agent.id);
if (!record) throw new Error("Created agent was not persisted");
await first.storage.upsert({ ...record, persistence: null });
const second = startDaemon();
onTestFinished(async () => {
await second.manager.closeAgent(agent.id);
await second.manager.flush();
rmSync(workdir, { recursive: true, force: true });
});
await ensureAgentLoaded(agent.id, {
agentManager: second.manager,
agentStorage: second.storage,
logger,
});
expect(await second.manager.getTimeline(agent.id)).toEqual([reply]);
});
test("markAgentUnread restores error attention on a read errored agent", async () => { test("markAgentUnread restores error attention on a read errored agent", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-")); const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
const storage = new AgentStorage(join(workdir, "agents"), logger); const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -7273,6 +7520,7 @@ test("getTimelineRows falls back to the in-memory timeline when no durable store
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }], sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
collapsed: ["assistant_merge"], collapsed: ["assistant_merge"],
timestamp: expect.any(String), timestamp: expect.any(String),
provider: "codex",
item: { type: "assistant_message", text: "row onerow two" }, item: { type: "assistant_message", text: "row onerow two" },
}, },
]); ]);
+112 -60
View File
@@ -97,6 +97,7 @@ import {
type TimelineAppendResult, type TimelineAppendResult,
type TimelineCommit, type TimelineCommit,
type TimelineHead, type TimelineHead,
type TimelinePrompts,
type TimelineEntry, type TimelineEntry,
type TimelineIngestResult, type TimelineIngestResult,
type TimelineRetirementCommit, type TimelineRetirementCommit,
@@ -535,6 +536,16 @@ interface HandleStreamEventOptions {
fromHistory?: boolean; fromHistory?: boolean;
} }
interface StreamEventDispatch {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
options: HandleStreamEventOptions | undefined;
isForegroundEvent: boolean;
eventTurnId: string | undefined;
terminalDisposition: ActiveTurnTerminalDisposition;
flags: StreamEventFlags;
}
interface ManagedAgentBase { interface ManagedAgentBase {
id: string; id: string;
provider: AgentProvider; provider: AgentProvider;
@@ -815,7 +826,11 @@ function validateAgentId(agentId: string, source: string): string {
} }
function toTimelineEntry(event: Extract<AgentStreamEvent, { type: "timeline" }>): TimelineEntry { function toTimelineEntry(event: Extract<AgentStreamEvent, { type: "timeline" }>): TimelineEntry {
return event.timestamp ? { item: event.item, timestamp: event.timestamp } : { item: event.item }; return {
item: event.item,
provider: event.provider,
...(event.timestamp ? { timestamp: event.timestamp } : {}),
};
} }
/** The live event that publishes a row committed from provider history. */ /** The live event that publishes a row committed from provider history. */
@@ -829,6 +844,7 @@ function historyEvent(provider: AgentProvider, commit: TimelineCommit): AgentStr
} }
function projectImportedTimelineEntries( function projectImportedTimelineEntries(
provider: AgentProvider,
entries: readonly ImportedTimelineEntry[], entries: readonly ImportedTimelineEntry[],
): TimelineEntry[] { ): TimelineEntry[] {
const projected: TimelineEntry[] = []; const projected: TimelineEntry[] = [];
@@ -836,9 +852,11 @@ function projectImportedTimelineEntries(
const projection = new TimelineProjection(); const projection = new TimelineProjection();
for (const entry of entries) { for (const entry of entries) {
for (const item of projectAgentMessages(entry.item)) { for (const item of projectAgentMessages(entry.item)) {
const timelineEntry: TimelineEntry = entry.timestamp const timelineEntry: TimelineEntry = {
? { item, timestamp: entry.timestamp } item,
: { item }; provider,
...(entry.timestamp ? { timestamp: entry.timestamp } : {}),
};
projected.push(timelineEntry); projected.push(timelineEntry);
projection.append({ projection.append({
seq: projected.length, seq: projected.length,
@@ -1570,6 +1588,12 @@ export class AgentManager {
return await this.timeline.readRows({ agentId: id }); return await this.timeline.readRows({ agentId: id });
} }
/** The agent's active prompt rows and timeline head, without its replies or tool output. */
async getTimelinePrompts(id: string): Promise<TimelinePrompts> {
await this.requireHistory(id);
return await this.timeline.readPrompts({ agentId: id });
}
/** The timeline head of a loaded agent, or null when this agent is not loaded. Never loads. */ /** The timeline head of a loaded agent, or null when this agent is not loaded. Never loads. */
async getLoadedTimelineHead(id: string): Promise<TimelineHead | null> { async getLoadedTimelineHead(id: string): Promise<TimelineHead | null> {
if (!this.getAgent(id)) return null; if (!this.getAgent(id)) return null;
@@ -1703,14 +1727,20 @@ export class AgentManager {
`Agent ${resolvedAgentId} references unavailable provider '${record.provider}'`, `Agent ${resolvedAgentId} references unavailable provider '${record.provider}'`,
); );
} }
return this.createAgentInternal(config, resolvedAgentId, { return this.createAgentInternal(
labels: record.labels, config,
metadata: record.metadata, resolvedAgentId,
workspaceId: record.workspaceId, {
owner: record.owner, labels: record.labels,
background: record.background, metadata: record.metadata,
env: record.launchEnv, workspaceId: record.workspaceId,
}); owner: record.owner,
background: record.background,
env: record.launchEnv,
},
// The stored agent's history is still its own; registration keeps it.
{ history: "keep" },
);
}), }),
); );
} }
@@ -1719,9 +1749,10 @@ export class AgentManager {
config: AgentSessionConfig, config: AgentSessionConfig,
resolvedAgentId: string, resolvedAgentId: string,
options: CreateAgentOptions, options: CreateAgentOptions,
historyOptions: { history: "discard" | "keep" } = { history: "discard" },
): Promise<ManagedAgent> { ): Promise<ManagedAgent> {
return this.launchAgent(resolvedAgentId, () => return this.launchAgent(resolvedAgentId, () =>
this.createAgentSession(config, resolvedAgentId, options), this.createAgentSession(config, resolvedAgentId, options, historyOptions),
); );
} }
@@ -1729,6 +1760,7 @@ export class AgentManager {
config: AgentSessionConfig, config: AgentSessionConfig,
resolvedAgentId: string, resolvedAgentId: string,
options: CreateAgentOptions, options: CreateAgentOptions,
{ history }: { history: "discard" | "keep" } = { history: "discard" },
): Promise<ManagedAgent> { ): Promise<ManagedAgent> {
this.assertAcceptingAgentRegistrations(); this.assertAcceptingAgentRegistrations();
config = this.withConvertedOptions(config); config = this.withConvertedOptions(config);
@@ -1752,7 +1784,8 @@ export class AgentManager {
}; };
options = { ...options, env: request.env, metadata: request.metadata ?? options.metadata }; options = { ...options, env: request.env, metadata: request.metadata ?? options.metadata };
} }
await this.deleteAgentState(resolvedAgentId); if (history === "keep") this.discardRuntimeState(resolvedAgentId);
else await this.deleteAgentState(resolvedAgentId);
const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig( const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig(
config, config,
resolvedAgentId, resolvedAgentId,
@@ -2032,7 +2065,7 @@ export class AgentManager {
}), }),
{ resolveDefaultModel: false }, { resolveDefaultModel: false },
); );
const importedEntries = projectImportedTimelineEntries(imported.timeline); const importedEntries = projectImportedTimelineEntries(input.provider, imported.timeline);
const initialTitle = resolveImportedAgentTitle(importedConfig, importedEntries); const initialTitle = resolveImportedAgentTitle(importedConfig, importedEntries);
handedToRegistration = true; handedToRegistration = true;
@@ -3383,7 +3416,7 @@ export class AgentManager {
const write = this.timeline const write = this.timeline
.ingest( .ingest(
scope, scope,
{ item: event.item }, { item: event.item, provider: event.provider },
{ publish: (commit) => this.publishTimelineEvent(agent.id, event, commit) }, { publish: (commit) => this.publishTimelineEvent(agent.id, event, commit) },
) )
.then((result) => this.reportUnpublished(agent.id, result)); .then((result) => this.reportUnpublished(agent.id, result));
@@ -3447,7 +3480,7 @@ export class AgentManager {
const event: AgentStreamEvent = { type: "timeline", item, provider: agent.provider }; const event: AgentStreamEvent = { type: "timeline", item, provider: agent.provider };
const result = await this.timeline.ingest( const result = await this.timeline.ingest(
{ agentId }, { agentId },
{ item }, { item, provider: agent.provider },
{ publish: (commit) => this.publishTimelineEvent(agentId, event, commit) }, { publish: (commit) => this.publishTimelineEvent(agentId, event, commit) },
); );
if (result.kind === "dropped") { if (result.kind === "dropped") {
@@ -4913,6 +4946,8 @@ export class AgentManager {
agentId: resolvedAgentId, agentId: resolvedAgentId,
session, session,
now, now,
// Nothing about an internal agent is on disk, its history included.
inMemory: config.internal === true,
options, options,
}); });
@@ -4953,7 +4988,7 @@ export class AgentManager {
if (timelineInit.kind === "created") { if (timelineInit.kind === "created") {
await this.timeline.append( await this.timeline.append(
{ agentId: managed.id }, { agentId: managed.id },
projectImportedTimelineEntries(session.initialTimeline), projectImportedTimelineEntries(managed.provider, session.initialTimeline),
); );
} }
this.refreshSessionPersistence(managed); this.refreshSessionPersistence(managed);
@@ -5038,6 +5073,7 @@ export class AgentManager {
agentId: string; agentId: string;
session: AgentSession; session: AgentSession;
now: Date; now: Date;
inMemory: boolean;
options: options:
| { | {
providerHistory?: readonly TimelineEntry[]; providerHistory?: readonly TimelineEntry[];
@@ -5052,22 +5088,24 @@ export class AgentManager {
| { kind: "kept" } | { kind: "kept" }
| { kind: "imported"; subagents: ProviderSubagentStreamEvent[]; sessionMetrics?: AgentMetric[] } | { kind: "imported"; subagents: ProviderSubagentStreamEvent[]; sessionMetrics?: AgentMetric[] }
> { > {
const { agentId, session, now, options } = params; const { agentId, session, now, inMemory, options } = params;
const scope: TimelineScope = { agentId }; const scope: TimelineScope = { agentId };
if (options?.providerHistory) { if (options?.providerHistory) {
const result = await this.timeline.importHistory(scope, options.providerHistory, { const result = await this.timeline.importHistory(scope, options.providerHistory, {
timestamp: (options.updatedAt ?? options.createdAt ?? now).toISOString(), timestamp: (options.updatedAt ?? options.createdAt ?? now).toISOString(),
inMemory,
}); });
return result.kind === "imported" ? { kind: "imported", subagents: [] } : { kind: "kept" }; return result.kind === "imported" ? { kind: "imported", subagents: [] } : { kind: "kept" };
} }
if (await this.timeline.describe(scope)) return { kind: "kept" }; if (await this.timeline.describe(scope)) return { kind: "kept" };
if (!options?.importMissingHistory) { if (!options?.importMissingHistory) {
await this.timeline.create(scope, { timestamp: now.toISOString() }); await this.timeline.create(scope, { timestamp: now.toISOString() }, { inMemory });
return { kind: "created" }; return { kind: "created" };
} }
const history = await this.readProviderHistory(session.streamHistory()); const history = await this.readProviderHistory(session.streamHistory());
const result = await this.timeline.importHistory(scope, history.entries, { const result = await this.timeline.importHistory(scope, history.entries, {
timestamp: now.toISOString(), timestamp: now.toISOString(),
inMemory,
}); });
return result.kind === "imported" return result.kind === "imported"
? { ? {
@@ -5239,9 +5277,14 @@ export class AgentManager {
private async discardRetainedAgentState(agentId: string): Promise<void> { private async discardRetainedAgentState(agentId: string): Promise<void> {
const removed = await this.providerSubagents.deleteParent(agentId); const removed = await this.providerSubagents.deleteParent(agentId);
this.discardRuntimeState(agentId);
for (const event of removed) this.publishProviderSubagent(event);
}
/** What a previous session of the agent left in this process; its saved history stays. */
private discardRuntimeState(agentId: string): void {
this.paseoToolPolicies.delete(agentId); this.paseoToolPolicies.delete(agentId);
this.detachPluginTools(agentId); this.detachPluginTools(agentId);
for (const event of removed) this.publishProviderSubagent(event);
this.clearProviderBackgroundWork(agentId); this.clearProviderBackgroundWork(agentId);
} }
@@ -5575,11 +5618,9 @@ export class AgentManager {
); );
} }
event = await this.settleTurnMetrics({ agent, event, options, terminalDisposition });
const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true }; const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true };
const dispatchPromise = this.dispatchStreamEventByType({ event = await this.recordStreamEvent({
agent, agent,
event, event,
options, options,
@@ -5588,9 +5629,6 @@ export class AgentManager {
terminalDisposition, terminalDisposition,
flags, flags,
}); });
if (dispatchPromise) {
await dispatchPromise;
}
if (!options?.fromHistory) { if (!options?.fromHistory) {
if (isTurnTerminalEvent(event)) { if (isTurnTerminalEvent(event)) {
@@ -5702,15 +5740,32 @@ export class AgentManager {
this.emitState(agent); this.emitState(agent);
} }
private dispatchStreamEventByType(params: { /**
agent: ActiveManagedAgent; * Applies the event by type, then stamps a completed turn's metrics, returning the event as
event: AgentStreamEvent; * stamped. Handlers change the agent's state before they write, so a terminal event whose
options: HandleStreamEventOptions | undefined; * record fails to write still ends the turn; the failure is logged.
isForegroundEvent: boolean; */
eventTurnId: string | undefined; private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
terminalDisposition: ActiveTurnTerminalDisposition; const { agent, options, eventTurnId, terminalDisposition } = params;
flags: StreamEventFlags; const event = withTurnMetrics(params);
}): Promise<void> | undefined { try {
await this.dispatchStreamEventByType({ ...params, event });
if (event.type === "turn_completed" && event.metrics && terminalDisposition !== "stale") {
await this.timeline.stampTurnMetrics({ agentId: agent.id }, event.metrics, {
turnId: event.turnId,
});
}
} catch (error) {
if (options?.fromHistory || !isTurnTerminalEvent(event)) throw error;
this.logger.error(
{ err: error, agentId: agent.id, turnId: eventTurnId, eventType: event.type },
"Failed to record how the turn ended",
);
}
return event;
}
private dispatchStreamEventByType(params: StreamEventDispatch): Promise<void> | undefined {
const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition, flags } = const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition, flags } =
params; params;
switch (event.type) { switch (event.type) {
@@ -5850,29 +5905,6 @@ export class AgentManager {
* Decides what a completed turn shows and records it on the turn's footer row, so * Decides what a completed turn shows and records it on the turn's footer row, so
* the live event and a later timeline fetch agree. * the live event and a later timeline fetch agree.
*/ */
private async settleTurnMetrics(params: {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
options: HandleStreamEventOptions | undefined;
terminalDisposition: ActiveTurnTerminalDisposition;
}): Promise<AgentStreamEvent> {
if (params.event.type !== "turn_completed") return params.event;
const { agent } = params;
const { metrics: reported, ...event } = params.event;
// A replayed turn may have run on another model than the agent has now.
const model = params.options?.fromHistory
? null
: (agent.runtimeInfo?.model ?? agent.config.model);
const metrics = withModelMetric(sanitizeAgentMetrics(reported), model);
if (metrics.length === 0) return event;
if (params.terminalDisposition !== "stale") {
await this.timeline.stampTurnMetrics({ agentId: agent.id }, metrics, {
turnId: event.turnId,
});
}
return { ...event, metrics };
}
private onStreamTurnCompleted(params: { private onStreamTurnCompleted(params: {
agent: ActiveManagedAgent; agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "turn_completed" }>; event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
@@ -5940,13 +5972,13 @@ export class AgentManager {
agent.lifecycle = "error"; agent.lifecycle = "error";
} }
agent.lastError = event.error; agent.lastError = event.error;
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
await this.appendSystemErrorTimelineMessage( await this.appendSystemErrorTimelineMessage(
agent, agent,
event.provider, event.provider,
this.formatTurnFailedMessage(event), this.formatTurnFailedMessage(event),
options, options,
); );
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
} }
private onStreamTurnCanceled(params: { private onStreamTurnCanceled(params: {
@@ -6094,6 +6126,7 @@ export class AgentManager {
{ agentId }, { agentId },
{ {
item, item,
provider,
...(turnId !== undefined ? { turnId } : {}), ...(turnId !== undefined ? { turnId } : {}),
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}), ...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
}, },
@@ -6976,3 +7009,22 @@ async function requireLaunchWrap(client: AgentClient): Promise<void> {
if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider); if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider);
await client.requireLaunchWrap?.(); await client.requireLaunchWrap?.();
} }
/**
* A completed turn with its metrics sanitized and the model added; a replayed turn may have run
* on another model than the agent has now, so it gets none.
*/
function withTurnMetrics(params: {
agent: ActiveManagedAgent;
event: AgentStreamEvent;
options: HandleStreamEventOptions | undefined;
}): AgentStreamEvent {
if (params.event.type !== "turn_completed") return params.event;
const { agent } = params;
const { metrics: reported, ...event } = params.event;
const model = params.options?.fromHistory
? null
: (agent.runtimeInfo?.model ?? agent.config.model);
const metrics = withModelMetric(sanitizeAgentMetrics(reported), model);
return metrics.length === 0 ? event : { ...event, metrics };
}
@@ -364,6 +364,11 @@ export class AgentStorage {
this.deleting.add(agentId); this.deleting.add(agentId);
} }
/** Ends a delete that did not happen; the agent's record takes writes again. */
abandonDelete(agentId: string): void {
this.deleting.delete(agentId);
}
async remove(agentId: string): Promise<void> { async remove(agentId: string): Promise<void> {
await this.load(); await this.load();
this.beginDelete(agentId); this.beginDelete(agentId);
@@ -1,10 +1,12 @@
import type { ProjectedTimelineRow, TimelineRetirement } from "./timeline-projection.js"; import type { ProjectedTimelineRow, TimelineRetirement } from "./timeline-projection.js";
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentMetric, AgentProvider, AgentTimelineItem } from "./agent-sdk-types.js";
export interface AgentTimelineRow { export interface AgentTimelineRow {
seq: number; seq: number;
timestamp: string; timestamp: string;
item: AgentTimelineItem; item: AgentTimelineItem;
/** The provider that wrote the row; an agent's history can span providers. */
readonly provider?: AgentProvider;
readonly turnId?: string; readonly turnId?: string;
readonly providerMessageId?: string; readonly providerMessageId?: string;
/** Metrics of the turn this row carries the footer for. */ /** Metrics of the turn this row carries the footer for. */
@@ -95,7 +95,7 @@ export class ProviderSubagentStore {
if (event.type === "timeline") { if (event.type === "timeline") {
const commits = await this.timeline.recordChildEntries(scope, [ const commits = await this.timeline.recordChildEntries(scope, [
{ item: event.item, timestamp: event.timestamp }, { item: event.item, provider, timestamp: event.timestamp },
]); ]);
if (!commits) return null; if (!commits) return null;
const [{ row, epoch }] = commits; const [{ row, epoch }] = commits;
@@ -1,5 +1,10 @@
import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn"; import { continuesTimelineTurn, isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn";
import type { AgentMetric, AgentTimelineItem, ToolCallDetail } from "./agent-sdk-types.js"; import type {
AgentMetric,
AgentProvider,
AgentTimelineItem,
ToolCallDetail,
} from "./agent-sdk-types.js";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity"; import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
@@ -20,6 +25,7 @@ export type TimelineLimitDirection = "tail" | "before" | "after";
export interface TimelineProjectionEntry { export interface TimelineProjectionEntry {
item: AgentTimelineItem; item: AgentTimelineItem;
provider?: AgentProvider;
turnId?: string; turnId?: string;
providerMessageId?: string; providerMessageId?: string;
turnMetrics?: AgentMetric[]; turnMetrics?: AgentMetric[];
@@ -135,6 +141,7 @@ function makeCanonicalEntries(rows: readonly AgentTimelineRow[]): WorkingEntry[]
return { return {
item: row.item, item: row.item,
timestamp: row.timestamp, timestamp: row.timestamp,
...(row.provider ? { provider: row.provider } : {}),
...(row.turnId ? { turnId: row.turnId } : {}), ...(row.turnId ? { turnId: row.turnId } : {}),
...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}), ...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}),
...(row.turnMetrics ? { turnMetrics: row.turnMetrics } : {}), ...(row.turnMetrics ? { turnMetrics: row.turnMetrics } : {}),
@@ -332,7 +339,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
/** A retained item. `seq` is its latest source event, not its display anchor. */ /** A retained item. `seq` is its latest source event, not its display anchor. */
export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry; export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry;
interface ProjectedTimelinePageOptions { export interface ProjectedTimelinePageOptions {
wholeTurns?: boolean; wholeTurns?: boolean;
bounds: { minSeq: number; maxSeq: number }; bounds: { minSeq: number; maxSeq: number };
direction: TimelineLimitDirection; direction: TimelineLimitDirection;
@@ -340,6 +347,61 @@ interface ProjectedTimelinePageOptions {
limit?: number; limit?: number;
} }
/**
* How a new source row lands in a projection:
* - `identity`: it updates `identityRow`, the active row with the same item identity;
* - `adjacent`: it continues `lastRow`, the last active row (streamed assistant or reasoning text);
* - `new`: it becomes a new last row.
* The result is the whole projected row. For `adjacent`, a merged text is `lastRow`'s text followed
* by the new chunk, so a `lastRow` passed with empty text yields the chunk alone.
*/
export type TimelineRowFold =
| { kind: "identity"; row: ProjectedTimelineRow }
| { kind: "adjacent"; row: ProjectedTimelineRow }
| { kind: "new"; row: ProjectedTimelineRow };
export function foldTimelineRow(input: {
row: AgentTimelineRow;
/** The row the projection holds for `timelineItemIdentity(row.item)`, if any. */
identityRow: ProjectedTimelineRow | undefined;
lastRow: ProjectedTimelineRow | undefined;
}): TimelineRowFold {
const entry = makeCanonicalEntries([input.row])[0];
const merged = input.identityRow ? mergeIdentityEntries(input.identityRow, entry) : null;
if (merged) return { kind: "identity", row: { ...merged, seq: merged.seqEnd } };
const previous = input.lastRow;
const adjacent = previous
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
: [entry];
if (previous && adjacent.length === 1) {
return { kind: "adjacent", row: { ...adjacent[0], seq: adjacent[0].seqEnd } };
}
return { kind: "new", row: { ...entry, seq: entry.seqEnd } };
}
/**
* Merges neighbouring retirements that no active row separates. Merging keeps the meaning (drop
* rows anchored in `[retireFromSeq, seq)`) and bounds the count by the active rows in the span.
*/
export function coalesceTimelineRetirements(
retirements: readonly TimelineRetirement[],
hasActiveAnchorIn: (startSeq: number, endSeq: number) => boolean,
): TimelineRetirement[] {
const coalesced: TimelineRetirement[] = [];
for (const retirement of retirements) {
const previous = coalesced.at(-1);
if (previous && !hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) {
coalesced[coalesced.length - 1] = {
seq: retirement.seq,
retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq),
};
continue;
}
coalesced.push({ ...retirement });
}
return coalesced;
}
/** Owns projected state; source events are consumed, never retained. */ /** Owns projected state; source events are consumed, never retained. */
export class TimelineProjection { export class TimelineProjection {
private readonly rows: ProjectedTimelineRow[] = []; private readonly rows: ProjectedTimelineRow[] = [];
@@ -375,28 +437,26 @@ export class TimelineProjection {
} }
private appendProjected(row: AgentTimelineRow): number { private appendProjected(row: AgentTimelineRow): number {
const entry = makeCanonicalEntries([row])[0];
const identity = timelineItemIdentity(row.item); const identity = timelineItemIdentity(row.item);
const index = identity === null ? undefined : this.identities.get(identity); const index = identity === null ? undefined : this.identities.get(identity);
const existing = index === undefined ? undefined : this.rows[index]; const fold = foldTimelineRow({
const merged = existing ? mergeIdentityEntries(existing, entry) : null; row,
if (merged && index !== undefined) { identityRow: index === undefined ? undefined : this.rows[index],
this.rows[index] = { ...merged, seq: merged.seqEnd }; lastRow: this.rows.at(-1),
});
if (fold.kind === "identity" && index !== undefined) {
this.rows[index] = fold.row;
this.extendSpan(index); this.extendSpan(index);
return index; return index;
} }
const previous = this.rows.at(-1); if (fold.kind === "adjacent") {
const adjacent = previous this.rows[this.rows.length - 1] = fold.row;
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
: [entry];
if (previous && adjacent.length === 1) {
const mergedText = adjacent[0];
this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd };
this.extendSpan(this.rows.length - 1); this.extendSpan(this.rows.length - 1);
return this.rows.length - 1; return this.rows.length - 1;
} }
const entry = fold.row;
if (identity !== null) this.identities.set(identity, this.rows.length); if (identity !== null) this.identities.set(identity, this.rows.length);
this.rows.push({ ...entry, seq: entry.seqEnd }); this.rows.push(entry);
const last = this.spans.at(-1); const last = this.spans.at(-1);
if (last && last.endSeq >= entry.seqStart) { if (last && last.endSeq >= entry.seqStart) {
last.endSeq = Math.max(last.endSeq, entry.seqEnd); last.endSeq = Math.max(last.endSeq, entry.seqEnd);
@@ -516,19 +576,9 @@ export class TimelineProjection {
} }
private coalesceRetirements(retirements: readonly TimelineRetirement[]): TimelineRetirement[] { private coalesceRetirements(retirements: readonly TimelineRetirement[]): TimelineRetirement[] {
const coalesced: TimelineRetirement[] = []; return coalesceTimelineRetirements(retirements, (startSeq, endSeq) =>
for (const retirement of retirements) { this.hasActiveAnchorIn(startSeq, endSeq),
const previous = coalesced.at(-1); );
if (previous && !this.hasActiveAnchorIn(previous.seq, retirement.retireFromSeq)) {
coalesced[coalesced.length - 1] = {
seq: retirement.seq,
retireFromSeq: Math.min(previous.retireFromSeq, retirement.retireFromSeq),
};
continue;
}
coalesced.push({ ...retirement });
}
return coalesced;
} }
private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean { private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean {
@@ -693,7 +743,7 @@ export class TimelineProjection {
const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart; const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart;
// Choose the window before extending the right edge, so a prompt jump // Choose the window before extending the right edge, so a prompt jump
// cannot lose its target when the next turn is arbitrarily large. // cannot lose its target when the next turn is arbitrarily large.
if (input.wholeTurns) { if (input.wholeTurns && low > 0) {
while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low])) while (low < this.rows.length && continuesProjectedTurn(this.rows[low - 1], this.rows[low]))
low++; low++;
} }
@@ -898,7 +948,7 @@ interface ProjectedEntryCandidate {
firstSourceSeq: number; firstSourceSeq: number;
} }
function selectProjectedEntriesAfter(input: { export function selectProjectedEntriesAfter(input: {
entries: readonly TimelineProjectionEntry[]; entries: readonly TimelineProjectionEntry[];
/** Seqs covered without an active row; they advance the cursor but add no entry. */ /** Seqs covered without an active row; they advance the cursor but add no entry. */
covered?: readonly TimelineSeqRange[]; covered?: readonly TimelineSeqRange[];
@@ -940,7 +990,7 @@ function selectProjectedEntriesAfter(input: {
}; };
} }
function continuesProjectedTurn( export function continuesProjectedTurn(
previous: TimelineProjectionEntry, previous: TimelineProjectionEntry,
next: TimelineProjectionEntry, next: TimelineProjectionEntry,
): boolean { ): boolean {
@@ -64,6 +64,24 @@ describe.each(
expect(published).toEqual([1, 2, 3]); expect(published).toEqual([1, 2, 3]);
}); });
it("keeps the provider that wrote each row, and a merged row the one it started with", async () => {
const timeline = createTimeline();
await timeline.create(root("a"), { epoch: "e" });
await timeline.append(root("a"), [
{ item: { type: "user_message", text: "prompt" }, provider: "codex" },
{ item: { type: "assistant_message", text: "A" }, provider: "claude" },
{ item: { type: "assistant_message", text: "B" }, provider: "claude" },
{ item: { type: "user_message", text: "unattributed" } },
]);
const page = await timeline.fetch(root("a"), { direction: "tail", limit: 0 });
expect(page.rows.map((row) => [row.item.type, row.provider])).toEqual([
["user_message", "codex"],
["assistant_message", "claude"],
["user_message", undefined],
]);
});
it("publishes each commit before the next operation starts", async () => { it("publishes each commit before the next operation starts", async () => {
const timeline = createTimeline(); const timeline = createTimeline();
await timeline.create(root("a"), { epoch: "e" }); await timeline.create(root("a"), { epoch: "e" });
@@ -353,6 +371,27 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("history paging over a $name backend",
], ],
}); });
}); });
it("resets an after cursor ahead of the history, as after a restored database", async () => {
const timeline = new AgentTimeline(create());
await timeline.create(root("agent-1"), { epoch: "epoch-1", nextSeq: 8, rows: seededRows });
const result = await timeline.fetch(root("agent-1"), {
direction: "after",
cursor: { epoch: "epoch-1", seq: 20 },
limit: 1,
});
// Without the reset the client keeps its cursor and drops seqs 8 to 20 when they arrive.
expect(result).toMatchObject({
direction: "after",
reset: true,
staleCursor: false,
gap: true,
window: { minSeq: 5, maxSeq: 7, nextSeq: 8 },
rows: [{ seq: 7 }],
});
});
}); });
describe("projected timeline retention", () => { describe("projected timeline retention", () => {
@@ -615,7 +654,8 @@ async function assertSelectionMatchesReference(
const expected = selectReferenceProjectedTimelinePage({ const expected = selectReferenceProjectedTimelinePage({
rows, rows,
bounds: actual.window, bounds: actual.window,
direction, // A reset serves the tail, as `fetchTimelinePage` does.
direction: actual.reset ? "tail" : direction,
limit, limit,
cursorSeq, cursorSeq,
}); });
@@ -1,5 +1,10 @@
import type { DaemonDatabase } from "../../database/index.js";
import { AgentTimeline } from "./internal/agent-timeline.js";
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
export { export {
AgentTimeline, AgentTimeline,
TimelineClosedError,
TimelineRewindBoundaryError, TimelineRewindBoundaryError,
TimelineRewindPendingError, TimelineRewindPendingError,
TimelineRewindTargetError, TimelineRewindTargetError,
@@ -9,6 +14,7 @@ export {
type TimelineEntry, type TimelineEntry,
type TimelineHead, type TimelineHead,
type TimelineImportResult, type TimelineImportResult,
type TimelinePrompts,
type TimelineIngestResult, type TimelineIngestResult,
type TimelineReconcileResult, type TimelineReconcileResult,
type TimelineRetirement, type TimelineRetirement,
@@ -19,3 +25,9 @@ export {
type TimelineScope, type TimelineScope,
type TimelineSeed, type TimelineSeed,
} from "./internal/agent-timeline.js"; } from "./internal/agent-timeline.js";
export { timelineSchema } from "./internal/sqlite-backend.js";
/** The daemon's timeline, stored in the daemon database. Open the database with `timelineSchema`. */
export function createStoredAgentTimeline(database: DaemonDatabase): AgentTimeline {
return new AgentTimeline(new SqliteTimelineBackend(database));
}
@@ -36,6 +36,11 @@ export type {
} from "./backend.js"; } from "./backend.js";
export type { TimelineRetirement } from "../../timeline-projection.js"; export type { TimelineRetirement } from "../../timeline-projection.js";
export interface TimelinePrompts {
head: TimelineHead;
rows: ProjectedTimelineRow[];
}
export interface TimelineCommit { export interface TimelineCommit {
row: AgentTimelineRow; row: AgentTimelineRow;
epoch: string; epoch: string;
@@ -72,6 +77,14 @@ export type TimelineRewindVerdict =
| { kind: "absent" }; | { kind: "absent" };
/** Another rewind is open on the history; it must settle first. */ /** Another rewind is open on the history; it must settle first. */
/** The timeline was closed for shutdown; it takes no more operations. */
export class TimelineClosedError extends Error {
constructor() {
super("The agent timeline is closed");
this.name = "TimelineClosedError";
}
}
export class TimelineRewindPendingError extends Error { export class TimelineRewindPendingError extends Error {
constructor(readonly intent: TimelineRewindIntent) { constructor(readonly intent: TimelineRewindIntent) {
super("Another rewind of this conversation has not settled"); super("Another rewind of this conversation has not settled");
@@ -143,6 +156,14 @@ export interface TimelineAppendOptions {
publish?: (commits: TimelineCommit[]) => void; publish?: (commits: TimelineCommit[]) => void;
} }
/**
* Where a new history lives. `inMemory` keeps an agent's history, its children included, in
* process memory only, for agents that must leave nothing on disk; it ends with the process.
*/
export interface TimelineRetention {
inMemory?: boolean;
}
/** /**
* Owner of agent timeline history: item identity, sequence numbers, projection, and reads. * Owner of agent timeline history: item identity, sequence numbers, projection, and reads.
* *
@@ -153,23 +174,37 @@ export interface TimelineAppendOptions {
export class AgentTimeline { export class AgentTimeline {
private readonly tails = new Map<string, Promise<void>>(); private readonly tails = new Map<string, Promise<void>>();
private readonly sizes = new Map<string, number>(); private readonly sizes = new Map<string, number>();
private closed = false;
constructor(private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend()) {} /** Agents whose history lives only in `memory`; see `TimelineRetention`. */
private readonly memoryAgents = new Set<string>();
constructor(
private readonly backend: AgentTimelineBackend = new MemoryTimelineBackend(),
private readonly memory: AgentTimelineBackend = new MemoryTimelineBackend(),
) {}
describe(scope: TimelineScope): Promise<TimelineHead | null> { describe(scope: TimelineScope): Promise<TimelineHead | null> {
return this.run(scope, () => this.backend.head(scope)); return this.run(scope, () => this.backendFor(scope).head(scope));
} }
/** Creates the scope's history with a new identity, replacing any existing history. */ /** Creates the scope's history with a new identity, replacing any existing history. */
create(scope: TimelineScope, seed: TimelineSeed = {}): Promise<TimelineHead> { create(
return this.run(scope, async () => this.track(scope, await this.backend.create(scope, seed))); scope: TimelineScope,
seed: TimelineSeed = {},
options: TimelineRetention = {},
): Promise<TimelineHead> {
return this.run(scope, async () => {
this.retain(scope, options);
return this.track(scope, await this.backendFor(scope).create(scope, seed));
});
} }
/** Returns the existing history, or creates an empty one. */ /** Returns the existing history, or creates an empty one. */
open(scope: TimelineScope): Promise<TimelineHead> { open(scope: TimelineScope): Promise<TimelineHead> {
return this.run(scope, async () => { return this.run(scope, async () => {
const existing = await this.backend.head(scope); const existing = await this.backendFor(scope).head(scope);
return existing ?? this.track(scope, await this.backend.create(scope, {})); return existing ?? this.track(scope, await this.backendFor(scope).create(scope, {}));
}); });
} }
@@ -180,12 +215,13 @@ export class AgentTimeline {
importHistory( importHistory(
scope: TimelineScope, scope: TimelineScope,
entries: readonly TimelineEntry[], entries: readonly TimelineEntry[],
options: { timestamp?: string } = {}, options: { timestamp?: string } & TimelineRetention = {},
): Promise<TimelineImportResult> { ): Promise<TimelineImportResult> {
return this.run(scope, async () => { return this.run(scope, async () => {
const existing = await this.backend.head(scope); this.retain(scope, options);
const existing = await this.backendFor(scope).head(scope);
if (existing) return { kind: "present", head: existing }; if (existing) return { kind: "present", head: existing };
const head = await this.backend.create(scope, { const head = await this.backendFor(scope).create(scope, {
entries: entries.map(providerHistoryEntry), entries: entries.map(providerHistoryEntry),
timestamp: options.timestamp, timestamp: options.timestamp,
}); });
@@ -207,8 +243,8 @@ export class AgentTimeline {
const head = await this.requireHead(scope); const head = await this.requireHead(scope);
if (head.rewind) return { kind: "rewind_open" }; if (head.rewind) return { kind: "rewind_open" };
const plan = planProviderHistory({ const plan = planProviderHistory({
rows: await this.backend.readRows(scope), rows: await this.backendFor(scope).readRows(scope),
prompts: await this.backend.prompts(scope), prompts: await this.prompts(scope),
provider: entries.map(providerHistoryEntry), provider: entries.map(providerHistoryEntry),
}); });
if (plan.kind !== "append") return plan; if (plan.kind !== "append") return plan;
@@ -222,7 +258,7 @@ export class AgentTimeline {
/** The agent's provider children, retired ones included. */ /** The agent's provider children, retired ones included. */
listChildren(agentId: string): Promise<TimelineChild[]> { listChildren(agentId: string): Promise<TimelineChild[]> {
return this.run({ agentId }, () => this.backend.children(agentId)); return this.run({ agentId }, () => this.backendFor({ agentId }).children(agentId));
} }
/** /**
@@ -234,10 +270,10 @@ export class AgentTimeline {
update: (previous: ProviderSubagentDescriptor | null) => ProviderSubagentDescriptor, update: (previous: ProviderSubagentDescriptor | null) => ProviderSubagentDescriptor,
): Promise<ProviderSubagentDescriptor | null> { ): Promise<ProviderSubagentDescriptor | null> {
return this.run(scope, async () => { return this.run(scope, async () => {
const child = await this.backend.child(scope); const child = await this.backendFor(scope).child(scope);
if (child?.retired) return null; if (child?.retired) return null;
const descriptor = update(child?.descriptor ?? null); const descriptor = update(child?.descriptor ?? null);
await this.backend.setChild(scope, descriptor); await this.backendFor(scope).setChild(scope, descriptor);
return descriptor; return descriptor;
}); });
} }
@@ -248,9 +284,9 @@ export class AgentTimeline {
entries: readonly TimelineEntry[], entries: readonly TimelineEntry[],
): Promise<TimelineCommit[] | null> { ): Promise<TimelineCommit[] | null> {
return this.run(scope, async () => { return this.run(scope, async () => {
const child = await this.backend.child(scope); const child = await this.backendFor(scope).child(scope);
if (child?.retired) return null; if (child?.retired) return null;
if (!child) this.track(scope, await this.backend.create(scope, {})); if (!child) this.track(scope, await this.backendFor(scope).create(scope, {}));
return entries.length === 0 ? [] : await this.commit(scope, entries); return entries.length === 0 ? [] : await this.commit(scope, entries);
}); });
} }
@@ -258,9 +294,9 @@ export class AgentTimeline {
/** Deletes a child's history. A retired child stays stored and resolves false. */ /** Deletes a child's history. A retired child stays stored and resolves false. */
removeChild(scope: TimelineScope): Promise<boolean> { removeChild(scope: TimelineScope): Promise<boolean> {
return this.run(scope, async () => { return this.run(scope, async () => {
const child = await this.backend.child(scope); const child = await this.backendFor(scope).child(scope);
if (child?.retired) return false; if (child?.retired) return false;
await this.backend.delete(scope); await this.backendFor(scope).delete(scope);
this.sizes.delete(sizeKey(scope)); this.sizes.delete(sizeKey(scope));
return true; return true;
}); });
@@ -269,9 +305,10 @@ export class AgentTimeline {
/** Deleting an agent's root history deletes all of its children's too. */ /** Deleting an agent's root history deletes all of its children's too. */
delete(scope: TimelineScope): Promise<void> { delete(scope: TimelineScope): Promise<void> {
return this.run(scope, async () => { return this.run(scope, async () => {
await this.backend.delete(scope); await this.backendFor(scope).delete(scope);
this.sizes.delete(sizeKey(scope)); this.sizes.delete(sizeKey(scope));
if (scope.subagentId !== undefined) return; if (scope.subagentId !== undefined) return;
this.memoryAgents.delete(scope.agentId);
const childPrefix = sizeKey({ agentId: scope.agentId, subagentId: "" }); const childPrefix = sizeKey({ agentId: scope.agentId, subagentId: "" });
for (const key of this.sizes.keys()) { for (const key of this.sizes.keys()) {
if (key.startsWith(childPrefix)) this.sizes.delete(key); if (key.startsWith(childPrefix)) this.sizes.delete(key);
@@ -287,7 +324,7 @@ export class AgentTimeline {
return this.run(scope, async () => { return this.run(scope, async () => {
const clientMessageId = submittedPromptId(entry.item); const clientMessageId = submittedPromptId(entry.item);
if (clientMessageId) { if (clientMessageId) {
const existing = await this.backend.findSubmittedPrompt(scope, clientMessageId); const existing = await this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId);
if (existing) { if (existing) {
const head = await this.requireHead(scope); const head = await this.requireHead(scope);
return { return {
@@ -298,7 +335,7 @@ export class AgentTimeline {
}; };
} }
} }
if (await this.backend.isRetired(scope, entry)) return { kind: "dropped" }; if (await this.backendFor(scope).isRetired(scope, entry)) return { kind: "dropped" };
const [commit] = await this.commit(scope, [entry]); const [commit] = await this.commit(scope, [entry]);
const failure = publishCommitted(options?.publish, commit); const failure = publishCommitted(options?.publish, commit);
return failure return failure
@@ -329,7 +366,7 @@ export class AgentTimeline {
providerMessageId: string, providerMessageId: string,
): Promise<AgentTimelineRow | null> { ): Promise<AgentTimelineRow | null> {
return this.run(scope, () => return this.run(scope, () =>
this.backend.attachProviderMessageId(scope, clientMessageId, providerMessageId), this.backendFor(scope).attachProviderMessageId(scope, clientMessageId, providerMessageId),
); );
} }
@@ -339,29 +376,39 @@ export class AgentTimeline {
metrics: AgentMetric[], metrics: AgentMetric[],
options?: { turnId?: string }, options?: { turnId?: string },
): Promise<ProjectedTimelineRow | null> { ): Promise<ProjectedTimelineRow | null> {
return this.run(scope, () => this.backend.stampTurnMetrics(scope, metrics, options)); return this.run(scope, () => this.backendFor(scope).stampTurnMetrics(scope, metrics, options));
} }
findSubmittedPrompt( findSubmittedPrompt(
scope: TimelineScope, scope: TimelineScope,
clientMessageId: string, clientMessageId: string,
): Promise<AgentTimelineRow | null> { ): Promise<AgentTimelineRow | null> {
return this.run(scope, () => this.backend.findSubmittedPrompt(scope, clientMessageId)); return this.run(scope, () =>
this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId),
);
} }
fetch( fetch(
scope: TimelineScope, scope: TimelineScope,
options: AgentTimelineFetchOptions = {}, options: AgentTimelineFetchOptions = {},
): Promise<AgentTimelineFetchResult> { ): Promise<AgentTimelineFetchResult> {
return this.run(scope, () => this.backend.fetch(scope, options)); return this.run(scope, () => this.backendFor(scope).fetch(scope, options));
} }
readRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> { readRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
return this.run(scope, () => this.backend.readRows(scope)); return this.run(scope, () => this.backendFor(scope).readRows(scope));
}
/** The active user prompt rows and the head they belong to, without replies or tool output. */
readPrompts(scope: TimelineScope): Promise<TimelinePrompts> {
return this.run(scope, async () => ({
head: await this.requireHead(scope),
rows: await this.backendFor(scope).promptRows(scope),
}));
} }
lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> { lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> {
return this.run(scope, () => this.backend.lastItem(scope)); return this.run(scope, () => this.backendFor(scope).lastItem(scope));
} }
/** /**
@@ -370,7 +417,7 @@ export class AgentTimeline {
* before it ends the run. Null when the history has no assistant message. * before it ends the run. Null when the history has no assistant message.
*/ */
lastAssistantMessage(scope: TimelineScope): Promise<string | null> { lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
return this.run(scope, () => this.backend.lastAssistantMessage(scope)); return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
} }
/** /**
@@ -381,16 +428,14 @@ export class AgentTimeline {
return this.run(scope, async () => { return this.run(scope, async () => {
const head = await this.requireHead(scope); const head = await this.requireHead(scope);
if (head.rewind) throw new TimelineRewindPendingError(head.rewind); if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
const target = (await this.backend.prompts(scope)).find( const target = (await this.prompts(scope)).find((prompt) => prompt.messageId === messageId);
(prompt) => prompt.messageId === messageId,
);
if (!target) throw new TimelineRewindTargetError(messageId); if (!target) throw new TimelineRewindTargetError(messageId);
const intent: TimelineRewindIntent = { const intent: TimelineRewindIntent = {
id: randomUUID(), id: randomUUID(),
messageId, messageId,
targetSeq: target.seqStart, targetSeq: target.seqStart,
}; };
await this.backend.setRewind(scope, intent); await this.backendFor(scope).setRewind(scope, intent);
return intent; return intent;
}); });
} }
@@ -405,7 +450,7 @@ export class AgentTimeline {
const head = await this.requireHead(scope); const head = await this.requireHead(scope);
if (head.rewind?.id !== intentId) return null; if (head.rewind?.id !== intentId) return null;
const intent = { ...head.rewind, cut }; const intent = { ...head.rewind, cut };
await this.backend.setRewind(scope, intent); await this.backendFor(scope).setRewind(scope, intent);
return intent; return intent;
}); });
} }
@@ -414,7 +459,7 @@ export class AgentTimeline {
abandonRewind(scope: TimelineScope, intentId: string): Promise<void> { abandonRewind(scope: TimelineScope, intentId: string): Promise<void> {
return this.run(scope, async () => { return this.run(scope, async () => {
const head = await this.requireHead(scope); const head = await this.requireHead(scope);
if (head.rewind?.id === intentId) await this.backend.setRewind(scope, null); if (head.rewind?.id === intentId) await this.backendFor(scope).setRewind(scope, null);
}); });
} }
@@ -430,7 +475,7 @@ export class AgentTimeline {
return this.run(scope, async () => { return this.run(scope, async () => {
const intent = (await this.requireHead(scope)).rewind; const intent = (await this.requireHead(scope)).rewind;
if (intent?.id !== intentId) return { kind: "absent" }; if (intent?.id !== intentId) return { kind: "absent" };
return judgeRewindEvidence(intent, await this.backend.prompts(scope), providerPromptIds); return judgeRewindEvidence(intent, await this.prompts(scope), providerPromptIds);
}); });
} }
@@ -448,9 +493,9 @@ export class AgentTimeline {
const intent = head.rewind; const intent = head.rewind;
if (intent?.id !== intentId) return { kind: "absent" }; if (intent?.id !== intentId) return { kind: "absent" };
if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome"); if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome");
const retireFromSeq = resolveRetireFromSeq(intent, await this.backend.prompts(scope)); const retireFromSeq = resolveRetireFromSeq(intent, await this.prompts(scope));
if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent); if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent);
const result = await this.backend.retire(scope, { const result = await this.backendFor(scope).retire(scope, {
retireFromSeq, retireFromSeq,
selectChildren: childrenSpawnedBy, selectChildren: childrenSpawnedBy,
}); });
@@ -474,9 +519,20 @@ export class AgentTimeline {
* Callers use it so an event published outside the timeline cannot overtake queued writes. * Callers use it so an event published outside the timeline cannot overtake queued writes.
*/ */
settled(scope: TimelineScope): Promise<void> { settled(scope: TimelineScope): Promise<void> {
// A closed timeline takes no operations, so the ones already queued are all there is.
if (this.closed) return this.tails.get(scope.agentId) ?? Promise.resolve();
return this.run(scope, settledOperation); return this.run(scope, settledOperation);
} }
/**
* Refuses new operations with `TimelineClosedError` and resolves once every operation called
* before it has finished. The daemon calls it before closing the store.
*/
async close(): Promise<void> {
this.closed = true;
await Promise.all(this.tails.values());
}
/** Projected row count as of the last committed write, for diagnostics. */ /** Projected row count as of the last committed write, for diagnostics. */
residentSize(scope: TimelineScope): number | null { residentSize(scope: TimelineScope): number | null {
return this.sizes.get(sizeKey(scope)) ?? null; return this.sizes.get(sizeKey(scope)) ?? null;
@@ -486,7 +542,7 @@ export class AgentTimeline {
scope: TimelineScope, scope: TimelineScope,
entries: readonly TimelineEntry[], entries: readonly TimelineEntry[],
): Promise<TimelineCommit[]> { ): Promise<TimelineCommit[]> {
const { rows, head } = await this.backend.append(scope, entries.map(boundEntry)); const { rows, head } = await this.backendFor(scope).append(scope, entries.map(boundEntry));
this.track(scope, head); this.track(scope, head);
return rows.map((row) => ({ return rows.map((row) => ({
row, row,
@@ -496,17 +552,31 @@ export class AgentTimeline {
} }
private async requireHead(scope: TimelineScope): Promise<TimelineHead> { private async requireHead(scope: TimelineScope): Promise<TimelineHead> {
const head = await this.backend.head(scope); const head = await this.backendFor(scope).head(scope);
if (!head) throw new UnknownTimelineError(scope); if (!head) throw new UnknownTimelineError(scope);
return head; return head;
} }
private backendFor(scope: TimelineScope): AgentTimelineBackend {
return this.memoryAgents.has(scope.agentId) ? this.memory : this.backend;
}
private async prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
return (await this.backendFor(scope).promptRows(scope)).map(toTimelinePrompt);
}
/** An agent stays in memory until its history is deleted. */
private retain(scope: TimelineScope, options: TimelineRetention): void {
if (options.inMemory && scope.subagentId === undefined) this.memoryAgents.add(scope.agentId);
}
private track(scope: TimelineScope, head: TimelineHead): TimelineHead { private track(scope: TimelineScope, head: TimelineHead): TimelineHead {
this.sizes.set(sizeKey(scope), head.size); this.sizes.set(sizeKey(scope), head.size);
return head; return head;
} }
private run<T>(scope: TimelineScope, operation: () => T | Promise<T>): Promise<T> { private run<T>(scope: TimelineScope, operation: () => T | Promise<T>): Promise<T> {
if (this.closed) return Promise.reject(new TimelineClosedError());
const key = scope.agentId; const key = scope.agentId;
const previous = this.tails.get(key) ?? Promise.resolve(); const previous = this.tails.get(key) ?? Promise.resolve();
const result = previous.then(operation); const result = previous.then(operation);
@@ -643,3 +713,13 @@ function sizeKey(scope: TimelineScope): string {
function submittedPromptId(item: AgentTimelineItem): string | null { function submittedPromptId(item: AgentTimelineItem): string | null {
return item.type === "user_message" && item.clientMessageId ? item.clientMessageId : null; return item.type === "user_message" && item.clientMessageId ? item.clientMessageId : null;
} }
function toTimelinePrompt(row: ProjectedTimelineRow): TimelinePrompt {
const item = row.item as Extract<AgentTimelineItem, { type: "user_message" }>;
return {
seqStart: row.seqStart,
messageId: item.messageId,
providerMessageId: row.providerMessageId,
submitted: item.clientMessageId !== undefined,
};
}
@@ -1,5 +1,6 @@
import type { import type {
AgentMetric, AgentMetric,
AgentProvider,
AgentTimelineItem, AgentTimelineItem,
ConversationRewindCut, ConversationRewindCut,
} from "../../agent-sdk-types.js"; } from "../../agent-sdk-types.js";
@@ -19,6 +20,8 @@ export interface TimelineScope {
export interface TimelineEntry { export interface TimelineEntry {
item: AgentTimelineItem; item: AgentTimelineItem;
/** The provider that wrote the entry. */
provider?: AgentProvider;
timestamp?: string; timestamp?: string;
turnId?: string; turnId?: string;
providerMessageId?: string; providerMessageId?: string;
@@ -61,6 +64,7 @@ export interface TimelineRewindIntent {
} }
/** An active user prompt: what a rewind addresses. */ /** An active user prompt: what a rewind addresses. */
/** What the timeline knows about an active prompt row; see `toTimelinePrompt`. */
export interface TimelinePrompt { export interface TimelinePrompt {
seqStart: number; seqStart: number;
messageId: string | undefined; messageId: string | undefined;
@@ -119,8 +123,8 @@ export interface AgentTimelineBackend {
): MaybePromise<TimelineBackendAppendResult>; ): MaybePromise<TimelineBackendAppendResult>;
/** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */ /** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */
isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>; isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>;
/** Active user prompts in display order. */ /** Active user prompt rows in display order, read without the rest of the history. */
prompts(scope: TimelineScope): MaybePromise<TimelinePrompt[]>; promptRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>; setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>;
/** /**
* Allocates the next sequence number for a retirement of the active rows anchored at or after * Allocates the next sequence number for a retirement of the active rows anchored at or after
@@ -0,0 +1,78 @@
import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js";
import type {
AgentTimelineFetchOptions,
AgentTimelineFetchResult,
} from "../../agent-timeline-store-types.js";
import type {
ProjectedTimelinePageOptions,
ProjectedTimelinePageSelection,
} from "../../timeline-projection.js";
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
export interface TimelinePageHistory {
epoch: string;
/** 0 before any commit. */
minSeq: number;
nextSeq: number;
retirementCount: number;
}
/**
* The fetch contract every backend shares: cursor validation, gap and stale-cursor resets, and the
* served item budget. `selectPage` is the backend's projected page selection.
*/
export function fetchTimelinePage(input: {
history: TimelinePageHistory;
options: AgentTimelineFetchOptions;
selectPage: (options: ProjectedTimelinePageOptions) => ProjectedTimelinePageSelection;
}): AgentTimelineFetchResult {
const { history, options } = input;
const direction = options.direction ?? "tail";
const cursor = options.cursor;
const hasRows = history.minSeq !== 0;
const window = {
minSeq: history.minSeq,
maxSeq: history.nextSeq - 1,
nextSeq: history.nextSeq,
};
const staleCursor =
cursor !== undefined &&
(cursor.epoch !== history.epoch ||
(cursor.retirementCount !== undefined && cursor.retirementCount !== history.retirementCount));
// An after cursor is a gap when history it needs was dropped, or when it is ahead of the
// history (lost commits, a restored database): left alone, the client would drop new rows.
const gap =
!staleCursor &&
direction === "after" &&
cursor !== undefined &&
((hasRows && cursor.seq < history.minSeq - 1) || cursor.seq > window.maxSeq);
const reset = staleCursor || gap;
const page = input.selectPage({
bounds: window,
direction: reset ? "tail" : direction,
cursorSeq: cursor?.seq,
limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT,
wholeTurns: options.wholeTurns,
});
return {
epoch: history.epoch,
direction,
reset,
staleCursor,
gap,
window,
hasOlder: page.hasOlder,
hasNewer: page.hasNewer,
startSeq: page.startSeq,
endSeq: page.endSeq,
// Stored rows are already within budget; this bounds assistant and reasoning merges.
rows: page.entries.map((entry) =>
Object.assign({ seq: entry.seqEnd }, entry, {
item: limitAgentTimelineItemContent(entry.item),
}),
),
retirements: page.retirements,
retirementCount: history.retirementCount,
};
}
@@ -1,5 +1,4 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { limitAgentTimelineItemContent } from "../../agent-timeline-content.js";
import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js"; import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js";
import type { import type {
AgentTimelineFetchOptions, AgentTimelineFetchOptions,
@@ -16,12 +15,13 @@ import type {
TimelineChild, TimelineChild,
TimelineEntry, TimelineEntry,
TimelineHead, TimelineHead,
TimelinePrompt,
TimelineRewindIntent, TimelineRewindIntent,
TimelineScope, TimelineScope,
TimelineSeed, TimelineSeed,
} from "./backend.js"; } from "./backend.js";
import { UnknownTimelineError } from "./backend.js"; import { UnknownTimelineError } from "./backend.js";
import { fetchTimelinePage } from "./fetch-page.js";
import { buildSourceRow } from "./source-row.js";
interface MemoryTimelineState { interface MemoryTimelineState {
epoch: string; epoch: string;
@@ -37,8 +37,6 @@ interface MemoryTimelineState {
childRetired: boolean; childRetired: boolean;
} }
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
function scopeKey(scope: TimelineScope): string { function scopeKey(scope: TimelineScope): string {
return scope.subagentId === undefined return scope.subagentId === undefined
? scope.agentId ? scope.agentId
@@ -53,17 +51,6 @@ function cloneRow<T extends AgentTimelineRow>(row: T): T {
return { ...row }; return { ...row };
} }
function buildRow(entry: TimelineEntry, seq: number, timestamp: string): AgentTimelineRow {
return {
seq,
timestamp: entry.timestamp ?? timestamp,
item: entry.item,
...(entry.turnId ? { turnId: entry.turnId } : {}),
...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}),
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
/** Volatile backend: history lives in process memory and is lost when the daemon exits. */ /** Volatile backend: history lives in process memory and is lost when the daemon exits. */
export class MemoryTimelineBackend implements AgentTimelineBackend { export class MemoryTimelineBackend implements AgentTimelineBackend {
private readonly states = new Map<string, MemoryTimelineState>(); private readonly states = new Map<string, MemoryTimelineState>();
@@ -73,7 +60,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
const startSeq = seed.nextSeq ?? 1; const startSeq = seed.nextSeq ?? 1;
const rows = seed.rows?.length const rows = seed.rows?.length
? seed.rows.map(cloneRow) ? seed.rows.map(cloneRow)
: (seed.entries ?? []).map((entry, index) => buildRow(entry, startSeq + index, timestamp)); : (seed.entries ?? []).map((entry, index) =>
buildSourceRow(entry, startSeq + index, timestamp),
);
const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq); const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq);
const projection = new TimelineProjection(rows); const projection = new TimelineProjection(rows);
const state: MemoryTimelineState = { const state: MemoryTimelineState = {
@@ -137,7 +126,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult { append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult {
const state = this.requireState(scope); const state = this.requireState(scope);
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
const rows = entries.map((entry, index) => buildRow(entry, state.nextSeq + index, timestamp)); const rows = entries.map((entry, index) =>
buildSourceRow(entry, state.nextSeq + index, timestamp),
);
for (const row of rows) { for (const row of rows) {
state.projection.append(row); state.projection.append(row);
state.nextSeq = row.seq + 1; state.nextSeq = row.seq + 1;
@@ -150,18 +141,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
return this.requireState(scope).projection.isRetired(entry); return this.requireState(scope).projection.isRetired(entry);
} }
prompts(scope: TimelineScope): TimelinePrompt[] { promptRows(scope: TimelineScope): ProjectedTimelineRow[] {
const prompts: TimelinePrompt[] = []; return this.requireState(scope)
for (const row of this.requireState(scope).projection.getRows()) { .projection.getRows()
if (row.item.type !== "user_message") continue; .filter((row) => row.item.type === "user_message")
prompts.push({ .map(cloneRow);
seqStart: row.seqStart,
messageId: row.item.messageId,
providerMessageId: row.providerMessageId,
submitted: row.item.clientMessageId !== undefined,
});
}
return prompts;
} }
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead { setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead {
@@ -233,48 +217,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult { fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult {
const state = this.requireState(scope); const state = this.requireState(scope);
const direction = options.direction ?? "tail"; return fetchTimelinePage({
const cursor = options.cursor; history: state,
const hasRows = state.minSeq !== 0; options,
const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq }; selectPage: (page) => state.projection.selectPage(page),
const staleCursor =
cursor !== undefined &&
(cursor.epoch !== state.epoch ||
(cursor.retirementCount !== undefined && cursor.retirementCount !== state.retirementCount));
const gap =
!staleCursor &&
direction === "after" &&
cursor !== undefined &&
hasRows &&
cursor.seq < state.minSeq - 1;
const reset = staleCursor || gap;
const page = state.projection.selectPage({
bounds: window,
direction: reset ? "tail" : direction,
cursorSeq: cursor?.seq,
limit: options.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT,
wholeTurns: options.wholeTurns,
}); });
return {
epoch: state.epoch,
direction,
reset,
staleCursor,
gap,
window,
hasOlder: page.hasOlder,
hasNewer: page.hasNewer,
startSeq: page.startSeq,
endSeq: page.endSeq,
// Stored rows are already within budget; this bounds assistant and reasoning merges.
rows: page.entries.map((entry) =>
Object.assign({ seq: entry.seqEnd }, entry, {
item: limitAgentTimelineItemContent(entry.item),
}),
),
retirements: page.retirements,
retirementCount: state.retirementCount,
};
} }
readRows(scope: TimelineScope): ProjectedTimelineRow[] { readRows(scope: TimelineScope): ProjectedTimelineRow[] {
@@ -0,0 +1,19 @@
import type { AgentTimelineRow } from "../../agent-timeline-store-types.js";
import type { TimelineEntry } from "./backend.js";
/** The source row an entry commits as, at `seq`. */
export function buildSourceRow(
entry: TimelineEntry,
seq: number,
timestamp: string,
): AgentTimelineRow {
return {
seq,
timestamp: entry.timestamp ?? timestamp,
item: entry.item,
...(entry.provider ? { provider: entry.provider } : {}),
...(entry.turnId ? { turnId: entry.turnId } : {}),
...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}),
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,498 @@
import { describe, expect, it } from "vitest";
import type { AgentTimelineItem } from "../agent-sdk-types.js";
import type { AgentTimelineFetchOptions } from "../agent-timeline-store-types.js";
import type { ProviderSubagentDescriptor } from "../provider-subagents/store.js";
import type { DaemonDatabase, ReadSql, WriteSql } from "../../database/index.js";
import { MemoryTimelineBackend } from "./internal/memory-backend.js";
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
import { DeferredTimelineBackend, openTestTimelineDatabase } from "./testing.js";
import {
AgentTimeline,
TimelineClosedError,
type TimelineEntry,
type TimelineScope,
} from "./index.js";
const scope: TimelineScope = { agentId: "agent" };
const TIMESTAMP = "2026-11-25T10:00:00.000Z";
function entry(item: AgentTimelineItem, fields: Omit<TimelineEntry, "item"> = {}): TimelineEntry {
return { item, timestamp: TIMESTAMP, ...fields };
}
function tool(callId: string, status: "running" | "completed", label = callId): AgentTimelineItem {
return {
type: "tool_call",
callId,
name: "shell",
status,
error: null,
detail: { type: "plain_text", label },
};
}
function descriptor(id: string, toolCallId: string | null): ProviderSubagentDescriptor {
return {
id,
parentAgentId: "agent",
parentSubagentId: null,
provider: "claude",
title: null,
description: null,
status: "running",
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
toolCallId,
cwd: null,
subtitle: null,
};
}
function seededRandom(seed: number): (bound: number) => number {
let state = seed;
return (bound) => {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
return Math.floor((state / 0x1_0000_0000) * bound);
};
}
/** Every row of every timeline table, to compare stored state before and after a failed write. */
function dumpTables(database: DaemonDatabase): Record<string, unknown[]> {
return database.read((sql) => {
const tables = sql
.all<{ name: string }>(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'timeline_%' ORDER BY name",
)
.map((table) => table.name);
return Object.fromEntries(tables.map((table) => [table, sql.all(`SELECT * FROM ${table}`)]));
});
}
/** Counts the rows the backend's queries return, to prove a read touches a bounded slice. */
class CountingDatabase implements DaemonDatabase {
rowsRead = 0;
constructor(private readonly inner: DaemonDatabase) {}
write<T>(fn: (sql: WriteSql) => T): T {
return this.inner.write((sql) => fn({ ...this.counting(sql), run: sql.run, exec: sql.exec }));
}
read<T>(fn: (sql: ReadSql) => T): T {
return this.inner.read((sql) => fn(this.counting(sql)));
}
close(): void {
this.inner.close();
}
private counting(sql: ReadSql): ReadSql {
return {
get: (query, ...params) => {
const row = sql.get(query, ...params);
if (row !== undefined) this.rowsRead += 1;
return row as never;
},
all: (query, ...params) => {
const rows = sql.all(query, ...params);
this.rowsRead += rows.length;
return rows as never;
},
iterate: <T>(query: string, ...params: Parameters<ReadSql["get"]>[1][]) => {
const rows = sql.iterate<T>(query, ...params);
const count = () => (this.rowsRead += 1);
return {
*[Symbol.iterator]() {
for (const row of rows) {
count();
yield row;
}
},
};
},
};
}
}
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);
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" });
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);
if (prompts.length > 0) {
const retireFromSeq = prompts[random(prompts.length)].seqStart;
const results = backends.map((backend) =>
backend.retire(scope, { retireFromSeq, selectChildren: () => [] }),
);
expect(results[1]).toEqual(results[0]);
}
continue;
}
if (roll === 1) {
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 }),
);
expect(results[1]).toEqual(results[0]);
continue;
}
if (roll === 2) {
const clientMessageId = `client-${random(step + 1)}`;
const results = backends.map((backend) =>
backend.attachProviderMessageId(scope, clientMessageId, `provider-${step}`),
);
expect(results[1]).toEqual(results[0]);
continue;
}
if (random(8) === 0) turn += 1;
const items: AgentTimelineItem[] = [
{ type: "user_message", text, messageId: `m-${step}`, clientMessageId: `client-${step}` },
{ type: "user_message", text, messageId: `m-${step}` },
{ type: "assistant_message", text },
{ type: "assistant_message", text, messageId: identity },
{ type: "reasoning", text },
tool(identity, random(2) === 0 ? "running" : "completed", text),
{
type: "plugin",
id: identity,
pluginId: "test",
kind: "state",
version: 1,
data: { text },
},
];
const next = entry(items[random(items.length)], { turnId: String(turn) });
const retired = backends.map((backend) => backend.isRetired(scope, next));
expect(retired[1]).toBe(retired[0]);
const results = backends.map((backend) => backend.append(scope, [next]));
expect(results[1]).toEqual(results[0]);
}
expectSameHistory(memory, sqlite);
// 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" });
}
});
});
function expectSameHistory(
memory: MemoryTimelineBackend,
sqlite: SqliteTimelineBackend,
target: TimelineScope = scope,
): void {
expect(sqlite.head(target)).toEqual(memory.head(target));
expect(sqlite.readRows(target)).toEqual(memory.readRows(target));
expect(sqlite.retiredRows(target)).toEqual(memory.retiredRows(target));
expect(sqlite.promptRows(target)).toEqual(memory.promptRows(target));
expect(sqlite.lastItem(target)).toEqual(memory.lastItem(target));
expect(sqlite.lastAssistantMessage(target)).toEqual(memory.lastAssistantMessage(target));
const maxSeq = memory.head(target)!.seq;
for (const direction of ["tail", "before", "after"] as const) {
for (const wholeTurns of [false, true]) {
for (const limit of [0, 1, 3, 10]) {
for (const cursorSeq of [0, 1, Math.floor(maxSeq / 3), Math.floor(maxSeq / 2), maxSeq]) {
const options: AgentTimelineFetchOptions = {
direction,
wholeTurns,
limit,
cursor: { epoch: "e", seq: cursorSeq },
};
expect({ options, page: sqlite.fetch(target, options) }).toEqual({
options,
page: memory.fetch(target, options),
});
}
}
}
}
}
describe("SQLite timeline durability", () => {
it("keeps rows, turns, metrics, provider ids, rewinds, and children across a restart", async () => {
const file = nextTestDatabasePath();
let database = openTestTimelineDatabase(file);
let timeline = new AgentTimeline(new SqliteTimelineBackend(database));
await timeline.create(scope, { epoch: "e" });
await timeline.ingest(
scope,
entry(
{ type: "user_message", text: "first", messageId: "m1", clientMessageId: "c1" },
{ turnId: "t1" },
),
);
await timeline.attachProviderMessageId(scope, "c1", "p1");
await timeline.append(scope, [
entry({ type: "assistant_message", text: "Hel" }, { turnId: "t1" }),
entry({ type: "assistant_message", text: "lo" }, { turnId: "t1" }),
entry(tool("spawn", "running"), { turnId: "t1" }),
]);
await timeline.stampTurnMetrics(scope, [{ name: "tokens", value: 3 }] as never, {
turnId: "t1",
});
await timeline.append(scope, [
entry({ type: "user_message", text: "second", messageId: "m2" }, { turnId: "t2" }),
entry({ type: "assistant_message", text: "Done" }, { turnId: "t2" }),
]);
const child: TimelineScope = { agentId: "agent", subagentId: "child" };
await timeline.recordChild(child, () => descriptor("child", "spawn"));
await timeline.recordChildEntries(child, [entry({ type: "assistant_message", text: "kid" })]);
const intent = await timeline.beginRewind(scope, "m1");
await timeline.recordRewindCut(scope, intent.id, { kind: "at_target" });
const rowsBefore = await timeline.readRows(scope);
const headBefore = await timeline.describe(scope);
await timeline.close();
database.close();
database = openTestTimelineDatabase(file);
timeline = new AgentTimeline(new SqliteTimelineBackend(database));
expect(await timeline.describe(scope)).toEqual(headBefore);
expect(headBefore?.rewind).toMatchObject({ id: intent.id, cut: { kind: "at_target" } });
const rowsAfter = await timeline.readRows(scope);
expect(rowsAfter).toEqual(rowsBefore);
expect(rowsAfter.map((row) => row.turnId)).toEqual(["t1", "t1", "t1", "t2", "t2"]);
expect(rowsAfter[0].providerMessageId).toBe("p1");
expect(rowsAfter[1]).toMatchObject({
item: { text: "Hello" },
turnMetrics: [{ name: "tokens", value: 3 }],
});
// Turn ids survive, so a whole-turns tail still stops at the last turn (#10030).
const lastTurn = await timeline.fetch(scope, { direction: "tail", limit: 1, wholeTurns: true });
expect(lastTurn.rows.map((row) => row.turnId)).toEqual(["t2", "t2"]);
expect(await timeline.listChildren("agent")).toEqual([
{ subagentId: "child", descriptor: descriptor("child", "spawn"), retired: false },
]);
expect((await timeline.readRows(child)).map((row) => row.item)).toEqual([
{ type: "assistant_message", text: "kid" },
]);
// The rewind opened before the restart completes after it.
const completion = await timeline.completeRewind(scope, intent.id);
expect(completion).toMatchObject({ kind: "retired", retiredChildIds: ["child"] });
await timeline.close();
database.close();
database = openTestTimelineDatabase(file);
const backend = new SqliteTimelineBackend(database);
timeline = new AgentTimeline(backend);
expect(await timeline.readRows(scope)).toEqual([]);
expect(backend.retiredRows(scope)).toEqual(rowsBefore);
expect(await timeline.describe(scope)).toMatchObject({ retirementCount: 1, rewind: null });
expect(await timeline.listChildren("agent")).toMatchObject([
{ subagentId: "child", retired: true },
]);
// Late output of a retired tool call is still dropped.
expect(await timeline.ingest(scope, entry(tool("spawn", "completed")))).toEqual({
kind: "dropped",
});
const tail = await timeline.fetch(scope, { direction: "tail" });
expect(tail.retirements).toEqual([{ seq: 7, retireFromSeq: 1 }]);
await timeline.close();
database.close();
});
it("finishes queued writes on close, then refuses new ones", async () => {
const file = nextTestDatabasePath();
let database = openTestTimelineDatabase(file);
const timeline = new AgentTimeline(
new DeferredTimelineBackend(new SqliteTimelineBackend(database)),
);
await timeline.create(scope, { epoch: "e" });
const writes = ["a", "b", "c"].map((text) =>
timeline.append(scope, [entry({ type: "user_message", text })]),
);
await timeline.close();
await expect(
timeline.append(scope, [entry({ type: "user_message", text: "late" })]),
).rejects.toBeInstanceOf(TimelineClosedError);
// Nothing is left to wait for, so code that orders itself behind the timeline still runs.
await expect(timeline.settled(scope)).resolves.toBeUndefined();
await Promise.all(writes);
database.close();
database = openTestTimelineDatabase(file);
const rows = new SqliteTimelineBackend(database).readRows(scope);
expect(rows.map((row) => row.item)).toMatchObject([
{ text: "a" },
{ text: "b" },
{ text: "c" },
]);
database.close();
});
});
describe("SQLite timeline write failures", () => {
function failOn(database: DaemonDatabase, table: string): void {
database.write((sql) =>
sql.exec(
`CREATE TRIGGER fail_${table} BEFORE INSERT ON ${table} ` +
"BEGIN SELECT RAISE(ABORT, 'disk full'); END",
),
);
}
it("leaves no part of a failed append", () => {
const database = openTestTimelineDatabase();
const backend = new SqliteTimelineBackend(database);
backend.create(scope, { epoch: "e" });
backend.append(scope, [entry({ type: "user_message", text: "kept" })]);
const before = dumpTables(database);
failOn(database, "timeline_text");
// The prompt is written before the reply's text fails.
expect(() =>
backend.append(scope, [
entry({ type: "user_message", text: "lost" }),
entry({ type: "assistant_message", text: "lost" }),
]),
).toThrow(/disk full/);
expect(dumpTables(database)).toEqual(before);
expect(backend.head(scope)).toMatchObject({ seq: 1, size: 1 });
database.close();
});
it("leaves no part of a failed retirement", () => {
const database = openTestTimelineDatabase();
const backend = new SqliteTimelineBackend(database);
backend.create(scope, { epoch: "e" });
backend.append(scope, [
entry({ type: "user_message", text: "one", messageId: "m1" }, { turnId: "t1" }),
entry(tool("call", "running"), { turnId: "t1" }),
]);
backend.setChild({ agentId: "agent", subagentId: "child" }, descriptor("child", "call"));
backend.setRewind(scope, { id: "r", messageId: "m1", targetSeq: 1 });
const before = dumpTables(database);
failOn(database, "timeline_retirements");
// Rows, keys, ranges, and the child are written before the retirement fails.
expect(() =>
backend.retire(scope, { retireFromSeq: 1, selectChildren: () => ["child"] }),
).toThrow(/disk full/);
expect(dumpTables(database)).toEqual(before);
expect(backend.isRetired(scope, entry(tool("call", "completed")))).toBe(false);
database.close();
});
});
describe("SQLite timeline reads", () => {
function longHistory(): { database: CountingDatabase; backend: SqliteTimelineBackend } {
const database = new CountingDatabase(openTestTimelineDatabase());
const backend = new SqliteTimelineBackend(database);
backend.create(scope, { epoch: "e" });
for (let batch = 0; batch < 50; batch++) {
const entries: TimelineEntry[] = [];
for (let index = 0; index < 10; index++) {
const turnId = `t${batch * 10 + index}`;
entries.push(
entry({ type: "user_message", text: turnId, messageId: turnId }, { turnId }),
entry(tool(`${turnId}-call`, "completed"), { turnId }),
entry({ type: "assistant_message", text: "a" }, { turnId }),
entry({ type: "assistant_message", text: "b" }, { turnId }),
);
}
backend.append(scope, entries);
}
return { database, backend };
}
it("reads a bounded slice of a long history for a page", () => {
const { database, backend } = longHistory();
expect(backend.head(scope)).toMatchObject({ seq: 2000, size: 1500 });
const pages: AgentTimelineFetchOptions[] = [
{ direction: "tail", limit: 20 },
{ direction: "tail", limit: 20, wholeTurns: true },
{ direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 } },
{ direction: "before", limit: 20, cursor: { epoch: "e", seq: 1000 }, wholeTurns: true },
{ direction: "after", limit: 20, cursor: { epoch: "e", seq: 1000 } },
];
for (const options of pages) {
database.rowsRead = 0;
expect(backend.fetch(scope, options).rows.length).toBeGreaterThanOrEqual(20);
expect(database.rowsRead, JSON.stringify(options)).toBeLessThan(150);
}
// The chat outline lists every prompt; it reads none of the 1,000 other rows.
database.rowsRead = 0;
expect(backend.promptRows(scope)).toHaveLength(500);
expect(database.rowsRead).toBeLessThanOrEqual(501);
for (const read of [
() => backend.head(scope),
() => backend.lastItem(scope),
() => backend.lastAssistantMessage(scope),
() => backend.isRetired(scope, entry(tool("t3-call", "completed"))),
() => backend.findSubmittedPrompt(scope, "absent"),
() => backend.stampTurnMetrics(scope, [], { turnId: "t499" }),
]) {
database.rowsRead = 0;
read();
expect(database.rowsRead).toBeLessThan(20);
}
database.close();
});
it("writes a streamed chunk without rewriting the message's earlier text", () => {
const database = openTestTimelineDatabase();
const backend = new SqliteTimelineBackend(database);
backend.create(scope, { epoch: "e" });
const storedRowSize = () =>
database.read(
(sql) => sql.get<{ size: number }>("SELECT length(row) AS size FROM timeline_rows")!.size,
);
for (let chunk = 0; chunk < 100; chunk++) {
backend.append(scope, [entry({ type: "assistant_message", text: "x".repeat(1000) })]);
}
// The row holds only its metadata; the 100,000 characters of text are chunks beside it.
expect(storedRowSize()).toBeLessThan(300);
expect(backend.lastAssistantMessage(scope)).toHaveLength(100_000);
database.close();
});
it("reads back streamed text exactly, including a NUL and a pair split across chunks", () => {
const file = nextTestDatabasePath();
const chunks = ["before\0after ", "\ud83d", "\ude00 end"];
const writer = openTestTimelineDatabase(file);
const written = new SqliteTimelineBackend(writer);
written.create(scope, { epoch: "e" });
for (const text of chunks) {
written.append(scope, [entry({ type: "assistant_message", text })]);
}
writer.close();
const reopened = new SqliteTimelineBackend(openTestTimelineDatabase(file));
expect(reopened.readRows(scope).map((row) => row.item)).toEqual([
{ type: "assistant_message", text: chunks.join("") },
]);
});
it("reads the chat outline's prompts and cursor without a tool's interleaved rows", async () => {
const database = new CountingDatabase(openTestTimelineDatabase());
const timeline = new AgentTimeline(new SqliteTimelineBackend(database));
await timeline.create(scope, { epoch: "e" });
// The tool row spans everything between its start and its update, so a one-row tail page
// covers all 200 tool rows in between.
const entries: TimelineEntry[] = [
entry({ type: "user_message", text: "run it", messageId: "p1" }),
entry(tool("long", "running")),
];
for (let index = 0; index < 200; index++) entries.push(entry(tool(`t${index}`, "completed")));
entries.push(entry(tool("long", "completed")));
await timeline.append(scope, entries);
database.rowsRead = 0;
const outline = await timeline.readPrompts(scope);
expect(outline.head).toMatchObject({ epoch: "e", retirementCount: 0 });
expect(outline.rows.map((row) => row.item)).toEqual([entries[0]!.item]);
expect(database.rowsRead).toBeLessThan(5);
await timeline.close();
database.close();
});
});
@@ -1,4 +1,8 @@
import { setImmediate as nextTurn } from "node:timers/promises"; import { setImmediate as nextTurn } from "node:timers/promises";
import { onTestFinished } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
import { openDaemonDatabase, type DaemonDatabase } from "../../database/index.js";
import type { AgentMetric, AgentTimelineItem } from "../agent-sdk-types.js"; import type { AgentMetric, AgentTimelineItem } from "../agent-sdk-types.js";
import type { import type {
AgentTimelineFetchOptions, AgentTimelineFetchOptions,
@@ -16,12 +20,12 @@ import type {
TimelineChild, TimelineChild,
TimelineEntry, TimelineEntry,
TimelineHead, TimelineHead,
TimelinePrompt,
TimelineRewindIntent, TimelineRewindIntent,
TimelineScope, TimelineScope,
TimelineSeed, TimelineSeed,
} from "./internal/backend.js"; } from "./internal/backend.js";
import { MemoryTimelineBackend } from "./internal/memory-backend.js"; import { MemoryTimelineBackend } from "./internal/memory-backend.js";
import { SqliteTimelineBackend, timelineSchema } from "./internal/sqlite-backend.js";
/** /**
* Testing entry point of the timeline module. Production code imports `./index.js`. * Testing entry point of the timeline module. Production code imports `./index.js`.
@@ -39,18 +43,37 @@ export interface InspectableTimelineBackend extends AgentTimelineBackend {
export const TIMELINE_CONTRACT_BACKENDS: ReadonlyArray<{ export const TIMELINE_CONTRACT_BACKENDS: ReadonlyArray<{
name: string; name: string;
create: () => InspectableTimelineBackend; create: () => InspectableTimelineBackend;
}> = [{ name: "memory", create: () => new MemoryTimelineBackend() }]; }> = [
{ name: "memory", create: () => new MemoryTimelineBackend() },
{ name: "sqlite", create: () => new SqliteTimelineBackend(openTestTimelineDatabase()) },
];
/**
* Opens a fresh file-backed timeline database, closed when the calling test finishes, in a
* directory removed when the process exits. Pass the path of an earlier database to reopen it, as
* a daemon restart does.
*/
export function openTestTimelineDatabase(file?: string): DaemonDatabase {
const database = openDaemonDatabase({
path: file ?? nextTestDatabasePath(),
modules: [timelineSchema],
logger: createTestLogger(),
});
onTestFinished(() => database.close());
return database;
}
/** /**
* Wraps a backend: defers every call by a turn of the event loop, the shape of an I/O-backed * Wraps a backend: defers every call by a turn of the event loop, the shape of an I/O-backed
* store, records the committed appends and whole-history reads, and fails the next append or * store, records the committed appends and whole-history reads, and fails the next append,
* retirement on request. * retirement, or metrics stamp on request.
*/ */
export class DeferredTimelineBackend implements AgentTimelineBackend { export class DeferredTimelineBackend implements AgentTimelineBackend {
readonly appends: TimelineEntry[][] = []; readonly appends: TimelineEntry[][] = [];
readRowsCalls = 0; readRowsCalls = 0;
failNextAppend = false; failNextAppend = false;
failNextRetire = false; failNextRetire = false;
failNextStampTurnMetrics = false;
constructor(private readonly inner: InspectableTimelineBackend = new MemoryTimelineBackend()) {} constructor(private readonly inner: InspectableTimelineBackend = new MemoryTimelineBackend()) {}
@@ -85,8 +108,8 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> { isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> {
return this.defer(() => this.inner.isRetired(scope, entry)); return this.defer(() => this.inner.isRetired(scope, entry));
} }
prompts(scope: TimelineScope): Promise<TimelinePrompt[]> { promptRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
return this.defer(() => this.inner.prompts(scope)); return this.defer(() => this.inner.promptRows(scope));
} }
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> { setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> {
return this.defer(() => this.inner.setRewind(scope, rewind)); return this.defer(() => this.inner.setRewind(scope, rewind));
@@ -130,7 +153,13 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
metrics: AgentMetric[], metrics: AgentMetric[],
options?: { turnId?: string }, options?: { turnId?: string },
): Promise<ProjectedTimelineRow | null> { ): Promise<ProjectedTimelineRow | null> {
return this.defer(() => this.inner.stampTurnMetrics(scope, metrics, options)); return this.defer(() => {
if (this.failNextStampTurnMetrics) {
this.failNextStampTurnMetrics = false;
throw new Error("disk full");
}
return this.inner.stampTurnMetrics(scope, metrics, options);
});
} }
findSubmittedPrompt( findSubmittedPrompt(
scope: TimelineScope, scope: TimelineScope,
@@ -7,7 +7,7 @@ import type { Query } from "@anthropic-ai/claude-agent-sdk";
import { ClaudeAgentClient } from "./agent/providers/claude/agent.js"; import { ClaudeAgentClient } from "./agent/providers/claude/agent.js";
import http from "node:http"; import http from "node:http";
import path from "node:path"; import path from "node:path";
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import pino from "pino"; import pino from "pino";
import { afterEach, describe, expect, test, vi } from "vitest"; import { afterEach, describe, expect, test, vi } from "vitest";
import { WebSocket } from "ws"; import { WebSocket } from "ws";
@@ -22,7 +22,7 @@ import {
createPersistedWorkspaceRecord, createPersistedWorkspaceRecord,
} from "./workspace-registry.js"; } from "./workspace-registry.js";
import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js"; import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js";
import { ensureAgentLoaded } from "./agent/agent-loading.js"; import { ensureAgentLoaded, loadAgentHistory } from "./agent/agent-loading.js";
import { AgentManagerShuttingDownError } from "./agent/agent-manager.js"; import { AgentManagerShuttingDownError } from "./agent/agent-manager.js";
import { hashDaemonPassword } from "./auth.js"; import { hashDaemonPassword } from "./auth.js";
import { generateLocalPairingOffer } from "./pairing-offer.js"; import { generateLocalPairingOffer } from "./pairing-offer.js";
@@ -94,63 +94,57 @@ describe("paseo daemon bootstrap", () => {
} }
}); });
test("keeps timeline activity in memory and removes obsolete timeline files at startup", async () => { test("stores timelines in paseo.db and serves them after a restart without loading the agent", async () => {
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-cleanup-")); const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-restart-"));
const paseoHome = path.join(paseoHomeRoot, ".paseo"); const paseoHome = path.join(paseoHomeRoot, ".paseo");
const obsoleteTimelineDirectory = path.join(paseoHome, "agent-timelines"); const obsoleteTimelineDirectory = path.join(paseoHome, "agent-timelines");
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-")); const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-"));
await mkdir(obsoleteTimelineDirectory, { recursive: true }); await mkdir(obsoleteTimelineDirectory, { recursive: true });
await writeFile(path.join(obsoleteTimelineDirectory, "obsolete.json"), "{}\n", "utf-8"); await writeFile(path.join(obsoleteTimelineDirectory, "obsolete.json"), "{}\n", "utf-8");
const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
try { try {
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); const first = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
let agentId: string;
try {
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
const agent = await first.daemon.agentManager.createAgent(
{ provider: "codex", cwd: agentCwd },
undefined,
{ workspaceId: undefined },
);
agentId = agent.id;
await first.daemon.agentManager.appendTimelineItem(agent.id, {
type: "assistant_message",
text: "kept across the restart",
});
await first.daemon.agentManager.flush();
} finally {
await first.close();
}
await access(path.join(paseoHome, "paseo.db"));
const agent = await daemonHandle.daemon.agentManager.createAgent( const second = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
{ provider: "codex", cwd: agentCwd }, try {
undefined, const { agentManager, agentStorage } = second.daemon;
{ workspaceId: undefined }, const source = await loadAgentHistory(agentId, {
); agentManager,
await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, { agentStorage,
type: "assistant_message", logger: pino({ level: "silent" }),
text: "timeline stays in memory", purpose: "history",
}); });
await daemonHandle.daemon.agentManager.flush(); expect(source.kind).toBe("stored");
const page = await agentManager.fetchTimeline(agentId, { direction: "tail" });
await expect(access(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" }); expect(page.rows.map((row) => row.item)).toContainEqual({
type: "assistant_message",
text: "kept across the restart",
});
expect(agentManager.getAgent(agentId)).toBeNull();
} finally {
await second.close();
}
} finally { } finally {
await daemonHandle.close(); // Windows can hold a closed daemon's directory handles briefly, as in `removeDirs`.
await Promise.all([ const retry = { recursive: true, force: true, maxRetries: 3, retryDelay: 100 };
rm(paseoHomeRoot, { recursive: true, force: true }), await Promise.all([rm(paseoHomeRoot, retry), rm(agentCwd, retry)]);
rm(agentCwd, { recursive: true, force: true }),
]);
}
});
test("does not create a timeline directory for live timeline activity", async () => {
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-memory-"));
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-"));
const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
const timelineDirectory = path.join(daemonHandle.paseoHome, "agent-timelines");
try {
const agent = await daemonHandle.daemon.agentManager.createAgent(
{ provider: "codex", cwd: agentCwd },
undefined,
{ workspaceId: undefined },
);
await daemonHandle.daemon.agentManager.appendTimelineItem(agent.id, {
type: "assistant_message",
text: "timeline stays in memory",
});
await daemonHandle.daemon.agentManager.flush();
await expect(access(timelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
await daemonHandle.close();
await Promise.all([
rm(paseoHomeRoot, { recursive: true, force: true }),
rm(agentCwd, { recursive: true, force: true }),
]);
} }
}); });
@@ -441,6 +435,62 @@ describe("paseo daemon bootstrap", () => {
} }
}); });
// SQLite removes paseo.db's WAL file when the last connection closes cleanly.
test("closes paseo.db when the daemon fails to start", async () => {
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-failed-start-"));
const paseoHome = path.join(paseoHomeRoot, ".paseo");
// A directory where the keypair file belongs makes construction throw after paseo.db opens.
const keyPairPath = path.join(paseoHome, "daemon-keypair.json");
await mkdir(path.join(keyPairPath, "blocked"), { recursive: true });
const config: PaseoDaemonConfig = {
listen: "127.0.0.1:0",
paseoHome,
corsAllowedOrigins: [],
hostnames: true,
mcpEnabled: false,
mcpDebug: false,
agentClients: createTestAgentClients(),
agentStoragePath: path.join(paseoHome, "agents"),
relayEnabled: false,
appBaseUrl: "https://app.paseo.sh",
openai: undefined,
speech: undefined,
};
try {
await expect(
createPaseoDaemon(config, pino({ level: "silent" }), {
builtinPlugins: new BuiltinPluginLoader(undefined, []),
lazyTerminalWorker: true,
}),
).rejects.toThrow();
await access(path.join(paseoHome, "paseo.db"));
await expect(access(path.join(paseoHome, "paseo.db-wal"))).rejects.toMatchObject({
code: "ENOENT",
});
} finally {
// The keypair loader narrows the directory's mode to a private file's.
await chmod(keyPairPath, 0o700);
await rm(paseoHomeRoot, { recursive: true, force: true });
}
});
test("closes paseo.db when an earlier shutdown step fails", async () => {
const daemonHandle = await createTestPaseoDaemon();
const credentialPath = path.join(daemonHandle.paseoHome, "local-credential");
try {
// A directory where the local credential belongs makes the first shutdown step throw.
await rm(credentialPath, { force: true });
await mkdir(path.join(credentialPath, "blocked"), { recursive: true });
await expect(daemonHandle.daemon.stop()).rejects.toThrow();
await expect(access(path.join(daemonHandle.paseoHome, "paseo.db-wal"))).rejects.toMatchObject(
{ code: "ENOENT" },
);
} finally {
await rm(credentialPath, { recursive: true, force: true });
await daemonHandle.close();
}
});
test("rolls back daemon listener when standalone service proxy startup fails", async () => { test("rolls back daemon listener when standalone service proxy startup fails", async () => {
const occupiedServer = http.createServer((_req, res) => { const occupiedServer = http.createServer((_req, res) => {
res.end("occupied"); res.end("occupied");
+148 -85
View File
@@ -14,9 +14,13 @@ import { describeHookWorkspace } from "./plugins/lifecycle/index.js";
import express from "express"; import express from "express";
import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http"; import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http";
import { constants, existsSync, unlinkSync } from "fs"; import { constants, existsSync, unlinkSync } from "fs";
import { open, rm, stat } from "fs/promises"; import { mkdir, open, rm, stat } from "fs/promises";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js"; import {
getCachedHostMachineKind,
primeHostMachineKind,
type HostMachineKind,
} from "./host-machine-kind.js";
import { getHostName } from "./host-name.js"; import { getHostName } from "./host-name.js";
import path from "node:path"; import path from "node:path";
import { createMcpHandler } from "@modelcontextprotocol/server"; import { createMcpHandler } from "@modelcontextprotocol/server";
@@ -149,6 +153,12 @@ import type { RequestedSpeechProviders } from "./speech/speech-types.js";
import { createSpeechService } from "./speech/speech-runtime.js"; import { createSpeechService } from "./speech/speech-runtime.js";
import { createSpeechSettingsOwner } from "./speech/speech-settings.js"; import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
import { AgentManager } from "./agent/agent-manager.js"; import { AgentManager } from "./agent/agent-manager.js";
import {
createStoredAgentTimeline,
timelineSchema,
type AgentTimeline,
} from "./agent/timeline/index.js";
import { openDaemonDatabase, type DaemonDatabase } from "./database/index.js";
import { AgentStorage } from "./agent/agent-storage.js"; import { AgentStorage } from "./agent/agent-storage.js";
import { attachAgentStoragePersistence } from "./persistence-hooks.js"; import { attachAgentStoragePersistence } from "./persistence-hooks.js";
import { createAgentMcpServer } from "./agent/mcp-server.js"; import { createAgentMcpServer } from "./agent/mcp-server.js";
@@ -650,6 +660,47 @@ export async function createPaseoDaemon(
"Failed to remove obsolete agent timeline data", "Failed to remove obsolete agent timeline data",
); );
}); });
await mkdir(config.paseoHome, { recursive: true });
const database = openDaemonDatabase({
path: path.join(config.paseoHome, "paseo.db"),
modules: [timelineSchema],
logger: rootLogger.child({ module: "database" }),
});
const timeline = createStoredAgentTimeline(database);
try {
return await assemblePaseoDaemon({
config,
logger,
dependencies,
hostMachineKindReady,
database,
timeline,
});
} catch (error) {
await timeline.close();
database.close();
throw error;
}
}
/** What `createPaseoDaemon` opens before assembling the daemon around it. */
interface PaseoDaemonAssembly {
config: PaseoDaemonConfig;
logger: Logger;
dependencies: PaseoDaemonDependencies;
hostMachineKindReady: Promise<HostMachineKind | null>;
database: DaemonDatabase;
timeline: AgentTimeline;
}
async function assemblePaseoDaemon({
config,
logger,
dependencies,
hostMachineKindReady,
database,
timeline,
}: PaseoDaemonAssembly): Promise<PaseoDaemon> {
const bootstrapStart = performance.now(); const bootstrapStart = performance.now();
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`; const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url); const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
@@ -1055,6 +1106,7 @@ export async function createPaseoDaemon(
clients: initialAgentManagerState.clients, clients: initialAgentManagerState.clients,
providerDefinitions: initialAgentManagerState.providerDefinitions, providerDefinitions: initialAgentManagerState.providerDefinitions,
registry: agentStorage, registry: agentStorage,
timeline,
appendSystemPrompt: config.appendSystemPrompt, appendSystemPrompt: config.appendSystemPrompt,
onWorkspaceStateMayHaveChanged: ({ cwd }) => { onWorkspaceStateMayHaveChanged: ({ cwd }) => {
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd); workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
@@ -2059,99 +2111,110 @@ export async function createPaseoDaemon(
httpServer.closeAllConnections(); httpServer.closeAllConnections();
await new Promise<void>((resolve) => httpServer.close(() => resolve())); await new Promise<void>((resolve) => httpServer.close(() => resolve()));
} }
await timeline.close();
database.close();
throw error; throw error;
} }
}; };
const stop = async (options?: { keepTerminals?: boolean }) => { const stop = async (options?: { keepTerminals?: boolean }) => {
const keepTerminals = options?.keepTerminals === true; try {
let terminalShutdownError: unknown = null; const keepTerminals = options?.keepTerminals === true;
localCredential = null; let terminalShutdownError: unknown = null;
await deleteLocalCredential(config.paseoHome); localCredential = null;
// Stop tracking plugin provider registrations before anything tears plugins await deleteLocalCredential(config.paseoHome);
// down, so plugin shutdown cannot withdraw a provider from under an agent // Stop tracking plugin provider registrations before anything tears plugins
// that is still open. Plugins themselves are stopped once every session // down, so plugin shutdown cannot withdraw a provider from under an agent
// they serve has been closed, further down. // that is still open. Plugins themselves are stopped once every session
unsubscribePluginProviders(); // they serve has been closed, further down.
await hubRelationships.stop(); unsubscribePluginProviders();
workspaceReconciliation.dispose(); await hubRelationships.stop();
scriptHealthMonitor.stop(); workspaceReconciliation.dispose();
unsubscribeIdleRuntimeCleanup(); scriptHealthMonitor.stop();
await idleRuntimeCleanup.close(); unsubscribeIdleRuntimeCleanup();
// Freeze both ingress and registration before taking the agent closure snapshot. await idleRuntimeCleanup.close();
wsServer?.prepareForShutdown(); // Freeze both ingress and registration before taking the agent closure snapshot.
await changeRequestWatches.close(); wsServer?.prepareForShutdown();
await finishSubscriptions.close(); await changeRequestWatches.close();
await wsServer?.agentMessages.close(); await finishSubscriptions.close();
agentManager.prepareForShutdown(); await wsServer?.agentMessages.close();
await restartRecovery.captureRunningAgents(); agentManager.prepareForShutdown();
await closeAllAgents(logger, agentManager); await restartRecovery.captureRunningAgents();
await withTimeout({ await closeAllAgents(logger, agentManager);
promise: pluginRuntime.drainEvents(), await withTimeout({
timeoutMs: AGENT_CLOSE_TIMEOUT_MS, promise: pluginRuntime.drainEvents(),
label: "drain plugin lifecycle events", timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
}).catch((error) => logger.warn({ err: error }, "Plugin lifecycle events did not finish")); label: "drain plugin lifecycle events",
let shutdownFlushTimedOut = false; }).catch((error) => logger.warn({ err: error }, "Plugin lifecycle events did not finish"));
await withTimeout({ let shutdownFlushTimedOut = false;
promise: agentManager.flushForShutdown(),
timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
label: "flush agent shutdown tasks",
}).catch((error) => {
shutdownFlushTimedOut = true;
logger.warn({ err: error }, "Agent shutdown tasks did not finish before provider shutdown");
});
detachAgentStoragePersistence();
await agentStorage.flush().catch(() => undefined);
await agentProviderRuntime.shutdown();
if (shutdownFlushTimedOut) {
await withTimeout({ await withTimeout({
promise: agentManager.flushForShutdown(), promise: agentManager.flushForShutdown(),
timeoutMs: AGENT_CLOSE_TIMEOUT_MS, timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
label: "flush agent shutdown tasks after provider shutdown", label: "flush agent shutdown tasks",
}).catch((error) => }).catch((error) => {
logger.warn({ err: error }, "Agent shutdown tasks did not finish after provider shutdown"), shutdownFlushTimedOut = true;
); logger.warn({ err: error }, "Agent shutdown tasks did not finish before provider shutdown");
});
detachAgentStoragePersistence();
await agentStorage.flush().catch(() => undefined); await agentStorage.flush().catch(() => undefined);
} await agentProviderRuntime.shutdown();
await pluginRuntime.stopAllPlugins(); if (shutdownFlushTimedOut) {
try { await withTimeout({
if (keepTerminals) { promise: agentManager.flushForShutdown(),
await terminalManager.detach(); timeoutMs: AGENT_CLOSE_TIMEOUT_MS,
logger.info("Terminals left running for the next daemon"); label: "flush agent shutdown tasks after provider shutdown",
} else { }).catch((error) =>
await terminalManager.closeTerminals(); logger.warn(
{ err: error },
"Agent shutdown tasks did not finish after provider shutdown",
),
);
await agentStorage.flush().catch(() => undefined);
} }
} catch (error) { await pluginRuntime.stopAllPlugins();
// Finish the rest of the shutdown, then report it: the supervisor and `daemon stop` try {
// retry the cleanup from the record the reaper kept. if (keepTerminals) {
terminalShutdownError = error; await terminalManager.detach();
logger.error({ err: error }, "Terminal shutdown failed"); logger.info("Terminals left running for the next daemon");
} } else {
await speechService.stop(); await terminalManager.closeTerminals();
await scheduleService.stop().catch(() => undefined); }
await relayRuntime?.stop().catch(() => undefined); } catch (error) {
if (wsServer) { // Finish the rest of the shutdown, then report it: the supervisor and `daemon stop`
await wsServer.close(); // retry the cleanup from the record the reaper kept.
} terminalShutdownError = error;
forgeResolver.dispose(); logger.error({ err: error }, "Terminal shutdown failed");
await serviceProxy.stopStandalone(); }
// Force-drop remaining sockets so httpServer.close() resolves promptly. await speechService.stop();
// We've already closed wsServer (which sent ws-layer close frames) and await scheduleService.stop().catch(() => undefined);
// stopped every other service, so anything still attached is a TCP await relayRuntime?.stop().catch(() => undefined);
// socket whose higher-level shutdown hasn't fully released it (e.g. if (wsServer) {
// upgraded WS sockets in the closing handshake, or HTTP keep-alive await wsServer.close();
// sockets in CLOSE_WAIT). closeIdleConnections() does not catch }
// upgraded sockets, so we use closeAllConnections() here. forgeResolver.dispose();
httpServer.closeAllConnections(); await serviceProxy.stopStandalone();
await new Promise<void>((resolve) => { // Force-drop remaining sockets so httpServer.close() resolves promptly.
httpServer.close(() => resolve()); // We've already closed wsServer (which sent ws-layer close frames) and
}); // stopped every other service, so anything still attached is a TCP
// Clean up socket files // socket whose higher-level shutdown hasn't fully released it (e.g.
if (listenTarget.type === "socket" && existsSync(listenTarget.path)) { // upgraded WS sockets in the closing handshake, or HTTP keep-alive
unlinkSync(listenTarget.path); // sockets in CLOSE_WAIT). closeIdleConnections() does not catch
} // upgraded sockets, so we use closeAllConnections() here.
if (terminalShutdownError) { httpServer.closeAllConnections();
throw terminalShutdownError; await new Promise<void>((resolve) => {
httpServer.close(() => resolve());
});
// Clean up socket files
if (listenTarget.type === "socket" && existsSync(listenTarget.path)) {
unlinkSync(listenTarget.path);
}
if (terminalShutdownError) {
throw terminalShutdownError;
}
} finally {
// A failed shutdown step must not leave paseo.db open for the next daemon.
await timeline.close();
database.close();
} }
}; };
@@ -25,7 +25,9 @@ afterEach(async () => {
await client.close(); await client.close();
await sdk.close(); await sdk.close();
await daemon.close(); await daemon.close();
await rm(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); // Windows releases a stopped script's working directory after the process exits; rm's
// retries wait up to about 5 s for it.
await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}); });
test("SDK and workspace handles preserve ownership and actual process directories", async () => { test("SDK and workspace handles preserve ownership and actual process directories", async () => {
@@ -0,0 +1,368 @@
import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import {
DatabaseClosedError,
DatabaseOpenError,
DatabaseSchemaTooNewError,
openDaemonDatabase,
type DaemonDatabase,
type ReadSql,
type SchemaModule,
type WriteSql,
} from "./index.js";
import { WalCheckpointer } from "./internal/wal-checkpointer.js";
let directory: string;
let databasePath: string;
const opened: DaemonDatabase[] = [];
beforeEach(() => {
directory = mkdtempSync(path.join(tmpdir(), "paseo-database-"));
databasePath = path.join(directory, "paseo.db");
});
afterEach(() => {
for (const database of opened.splice(0)) database.close();
rmSync(directory, { recursive: true, force: true });
});
function open(modules: readonly SchemaModule[]): DaemonDatabase {
const database = openDaemonDatabase({ path: databasePath, modules, logger: createTestLogger() });
opened.push(database);
return database;
}
function reopen(database: DaemonDatabase, modules: readonly SchemaModule[]): DaemonDatabase {
database.close();
return open(modules);
}
const notes: SchemaModule = {
name: "notes",
migrations: [
{
up: (sql) =>
sql.exec("CREATE TABLE notes_items (id INTEGER PRIMARY KEY, text TEXT NOT NULL)"),
},
],
};
function count(database: DaemonDatabase, table: string): number {
return database.read((sql) => sql.get<{ n: number }>(`SELECT count(*) AS n FROM ${table}`)!.n);
}
function tableNames(database: DaemonDatabase): string[] {
return database.read((sql) =>
sql
.all<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
.map((row) => row.name),
);
}
function versions(database: DaemonDatabase) {
return database.read((sql) =>
sql.all<{ module: string; version: number; min_reader_version: number }>(
"SELECT module, version, min_reader_version FROM schema_versions ORDER BY module",
),
);
}
describe("opening the daemon database", () => {
it("creates the file in WAL mode with foreign keys on", () => {
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,
})),
).toEqual({ journal: "wal", foreignKeys: 1, synchronous: 1 });
expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]);
});
it("keeps committed rows across a reopen and runs no migration twice", () => {
let database = open([notes]);
database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES (?)", "kept"));
database = reopen(database, [notes]);
expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([
{ text: "kept" },
]);
expect(versions(database)).toEqual([{ module: "notes", version: 1, min_reader_version: 1 }]);
});
it("runs only the pending migrations of a module that gained some", () => {
let database = open([notes]);
database.write((sql) => sql.run("INSERT INTO notes_items (text) VALUES ('a')"));
database = reopen(database, [
{
name: "notes",
migrations: [
...notes.migrations,
{ up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") },
],
},
]);
expect(database.read((sql) => sql.all("SELECT text, pinned FROM notes_items"))).toEqual([
{ text: "a", pinned: null },
]);
expect(versions(database)).toEqual([{ module: "notes", version: 2, min_reader_version: 1 }]);
});
it("migrates several modules independently", () => {
const tags: SchemaModule = {
name: "tags",
migrations: [{ up: (sql) => sql.exec("CREATE TABLE tags_items (name TEXT)") }],
};
let database = open([notes]);
database = reopen(database, [notes, tags]);
expect(tableNames(database)).toEqual(["notes_items", "schema_versions", "tags_items"]);
expect(versions(database).map((row) => [row.module, row.version])).toEqual([
["notes", 1],
["tags", 1],
]);
});
it("rolls every migration back when one fails, so the next open retries from the same state", () => {
const failing: SchemaModule = {
name: "notes",
migrations: [
...notes.migrations,
{
up: (sql) => {
sql.exec("CREATE TABLE notes_extra (id INTEGER)");
throw new Error("migration bug");
},
},
],
};
expect(() =>
openDaemonDatabase({ path: databasePath, modules: [failing], logger: createTestLogger() }),
).toThrow(DatabaseOpenError);
const database = open([]);
expect(tableNames(database)).toEqual(["schema_versions"]);
});
it("opens a database a newer daemon changed additively, and ignores stores it does not know", () => {
const newer: SchemaModule = {
name: "notes",
migrations: [
...notes.migrations,
{ up: (sql) => sql.exec("ALTER TABLE notes_items ADD COLUMN pinned INTEGER") },
],
};
const unknownStore: SchemaModule = {
name: "future",
migrations: [{ up: (sql) => sql.exec("CREATE TABLE future_items (id INTEGER)") }],
};
let database = open([newer, unknownStore]);
database.write((sql) => sql.run("INSERT INTO notes_items (text, pinned) VALUES ('a', 1)"));
database = reopen(database, [notes]);
expect(database.read((sql) => sql.all("SELECT text FROM notes_items"))).toEqual([
{ text: "a" },
]);
expect(versions(database)).toEqual([
{ module: "future", version: 1, min_reader_version: 1 },
{ module: "notes", version: 2, min_reader_version: 1 },
]);
});
it("refuses a database a newer daemon changed in a way this daemon cannot read", () => {
const breaking: SchemaModule = {
name: "notes",
migrations: [
...notes.migrations,
{ up: (sql) => sql.exec("DROP TABLE notes_items"), breaking: true },
],
};
open([breaking]).close();
opened.length = 0;
let error: unknown;
try {
openDaemonDatabase({ path: databasePath, modules: [notes], logger: createTestLogger() });
} catch (thrown) {
error = thrown;
}
expect(error).toBeInstanceOf(DatabaseSchemaTooNewError);
expect(error).toMatchObject({ module: "notes", minReaderVersion: 2, knownVersion: 1 });
expect((error as Error).message).toContain(databasePath);
});
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");
let error: unknown;
try {
openDaemonDatabase({ path: corrupt, modules: [notes], logger: createTestLogger() });
} catch (thrown) {
error = thrown;
}
expect(error).toBeInstanceOf(DatabaseOpenError);
expect((error as Error).message).toContain(corrupt);
});
});
function insert(sql: WriteSql, text: string): void {
sql.run("INSERT INTO notes_items (text) VALUES (?)", text);
}
function insertThenThrow(sql: WriteSql, text: string): never {
insert(sql, text);
throw new Error(`failed after ${text}`);
}
function texts(database: DaemonDatabase): string[] {
return database.read((sql) =>
sql.all<{ text: string }>("SELECT text FROM notes_items ORDER BY id").map((row) => row.text),
);
}
it.skipIf(process.platform === "win32")(
"keeps the database and its WAL files private to the user, including a file created readable",
() => {
const umask = process.umask(0o022);
try {
writeFileSync(databasePath, "", { mode: 0o644 });
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("rolls a write back when its callback throws", () => {
const database = open([notes]);
expect(() => database.write((sql) => insertThenThrow(sql, "lost"))).toThrow("failed after lost");
expect(count(database, "notes_items")).toBe(0);
});
it("rolls back only a nested write that throws", () => {
const database = open([notes]);
const writeOuter = (sql: WriteSql) => {
insert(sql, "outer");
expect(() => database.write((inner) => insertThenThrow(inner, "inner"))).toThrow(
"failed after inner",
);
database.write((inner) => insert(inner, "second"));
};
database.write(writeOuter);
expect(texts(database)).toEqual(["outer", "second"]);
});
it("joins a read nested in a write, which sees the write's uncommitted rows", () => {
const database = open([notes]);
database.write((sql) => {
insert(sql, "pending");
expect(count(database, "notes_items")).toBe(1);
});
});
it("refuses a write inside a read", () => {
const database = open([notes]);
const writeInsideRead = () => database.write((sql) => insert(sql, "late"));
expect(() => database.read(writeInsideRead)).toThrow(/inside a read/);
});
it("refuses an asynchronous callback and rolls its work back", () => {
const database = open([notes]);
const writeAsync = async (sql: WriteSql) => insert(sql, "async");
expect(() => database.write(writeAsync)).toThrow(/synchronous/);
expect(count(database, "notes_items")).toBe(0);
});
it("invalidates a handle once its callback returns", () => {
const database = open([notes]);
let leaked: WriteSql | undefined;
database.write((sql) => {
leaked = sql;
});
expect(() => insert(leaked!, "late")).toThrow(/after its transaction/);
expect(count(database, "notes_items")).toBe(0);
});
it("closes an unfinished iterator before the transaction ends", () => {
const database = open([notes]);
database.write((sql) => ["a", "b", "c"].forEach((text) => insert(sql, text)));
let rest: Iterator<unknown> | undefined;
const first = database.read((sql) => {
const iterator = sql.iterate("SELECT text FROM notes_items ORDER BY id")[Symbol.iterator]();
rest = iterator;
return iterator.next().value;
});
expect(first).toEqual({ text: "a" });
expect(() => rest!.next()).toThrow(/after its transaction/);
// A statement left open makes schema changes fail with "database table is locked".
database.write((sql) => sql.exec("DROP TABLE notes_items"));
expect(tableNames(database)).toEqual(["schema_versions"]);
});
it("refuses to reuse a statement that an unfinished iterator holds", () => {
const database = open([notes]);
database.write((sql) => insert(sql, "a"));
const query = "SELECT text FROM notes_items";
const reuse = (sql: ReadSql) => {
sql.iterate(query)[Symbol.iterator]().next();
expect(() => sql.all(query)).toThrow(/already iterating/);
};
database.read(reuse);
});
it("checkpoints the WAL off the daemon thread, never during a write", async () => {
const database = open([notes]);
expect(
database.read((sql) => sql.get<{ wal_autocheckpoint: number }>("PRAGMA wal_autocheckpoint")),
).toEqual({ wal_autocheckpoint: 0 });
const fileSize = () => statSync(databasePath).size;
const before = fileSize();
const writeBatch = (sql: WriteSql) => {
for (let row = 0; row < 50; row++) insert(sql, "x".repeat(1000));
};
for (let batch = 0; batch < 20; batch++) database.write(writeBatch);
// Writes go to the WAL. Only a checkpoint copies them into the database file.
await vi.waitFor(() => expect(fileSize()).toBeGreaterThan(before + 500_000), {
timeout: 10_000,
interval: 50,
});
});
it("rejects every call after close", () => {
const database = open([notes]);
database.close();
expect(() => database.read((sql) => sql.all("SELECT 1"))).toThrow(DatabaseClosedError);
expect(() => database.close()).not.toThrow();
});
describe("the WAL checkpointer", () => {
it("stops and closes its connection when asked, without reporting an exit", () => {
open([notes]).write((sql) => insert(sql, "a"));
let exited = false;
const checkpointer = new WalCheckpointer({
path: databasePath,
logger: createTestLogger(),
onExit: () => {
exited = true;
},
});
expect(checkpointer.stop()).toBe(true);
expect(exited).toBe(false);
});
it("reports a worker that ends on its own, so the database can checkpoint itself again", async () => {
let exited = false;
const checkpointer = new WalCheckpointer({
path: path.join(directory, "missing", "paseo.db"),
logger: createTestLogger(),
onExit: () => {
exited = true;
},
});
await vi.waitFor(() => expect(exited).toBe(true), { timeout: 10_000, interval: 20 });
expect(checkpointer.stop()).toBe(true);
});
});
@@ -0,0 +1,12 @@
export {
DatabaseClosedError,
DatabaseOpenError,
DatabaseSchemaTooNewError,
openDaemonDatabase,
type DaemonDatabase,
type Migration,
type ReadSql,
type SchemaModule,
type SqlValue,
type WriteSql,
} from "./internal/daemon-database.js";
@@ -0,0 +1,426 @@
import type { DatabaseSync, SQLInputValue, StatementSync } from "node:sqlite";
import type { Logger } from "pino";
import { ensurePrivateFile } from "../../private-files.js";
import { WalCheckpointer } from "./wal-checkpointer.js";
export type SqlValue = SQLInputValue;
/** Queries available inside `DaemonDatabase.read`. A handle is valid only inside its callback. */
export interface ReadSql {
get<T>(sql: string, ...params: SqlValue[]): T | undefined;
all<T>(sql: string, ...params: SqlValue[]): T[];
/** Lazy rows. An unfinished iteration is closed when the callback returns. */
iterate<T>(sql: string, ...params: SqlValue[]): Iterable<T>;
}
/** Queries available inside `DaemonDatabase.write`. */
export interface WriteSql extends ReadSql {
run(sql: string, ...params: SqlValue[]): { changes: number };
/** Runs one or more statements without caching them, for schema changes. */
exec(sql: string): void;
}
export interface Migration {
up(sql: WriteSql): void;
/**
* The change leaves the schema unreadable for a daemon that knows only the earlier migrations,
* for example a dropped or renamed column. Additive changes leave this unset.
*/
breaking?: boolean;
}
/** A store's schema: its tables, named with the store's prefix, and their migrations in order. */
export interface SchemaModule {
name: string;
/** Append-only. The module's version is the number of migrations applied. */
migrations: readonly Migration[];
}
/**
* The daemon's SQLite database. Calls are synchronous and run on the caller's thread, so
* transactions never interleave. A callback must not be asynchronous: a transaction never spans
* an `await`.
*/
export interface DaemonDatabase {
/** One write transaction. A throw rolls it back. Nested in a write, it is a savepoint. */
write<T>(fn: (sql: WriteSql) => T): T;
/** One consistent read. Nested in a read or write, it joins the outer transaction. */
read<T>(fn: (sql: ReadSql) => T): T;
/** Checkpoints the WAL and closes the file. Later calls throw `DatabaseClosedError`. */
close(): void;
}
export class DatabaseClosedError extends Error {
constructor() {
super("The daemon database is closed");
this.name = "DatabaseClosedError";
}
}
/** The database cannot be used: `node:sqlite` is missing, or the file cannot be opened or migrated. */
export class DatabaseOpenError extends Error {
constructor(
readonly path: string,
cause: unknown,
) {
super(`Cannot open the Paseo database at ${path}: ${describeError(cause)}`, { cause });
this.name = "DatabaseOpenError";
}
}
/** A newer daemon changed a store's schema in a way this daemon cannot read. */
export class DatabaseSchemaTooNewError extends Error {
constructor(
readonly path: string,
readonly module: string,
readonly minReaderVersion: number,
readonly knownVersion: number,
) {
super(
`The Paseo database at ${path} was changed by a newer Paseo: store '${module}' needs ` +
`schema version ${minReaderVersion}, this daemon knows version ${knownVersion}. ` +
"Update Paseo to use it.",
);
this.name = "DatabaseSchemaTooNewError";
}
}
const BUSY_TIMEOUT_MS = 1000;
const JOURNAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
/**
* Opens the database at `path`, creating the file when absent in a directory that must exist, and
* brings every module's schema up to date in one transaction. Throws `DatabaseOpenError` or `DatabaseSchemaTooNewError`.
*/
export function openDaemonDatabase(input: {
path: string;
modules: readonly SchemaModule[];
logger: Logger;
}): DaemonDatabase {
let connection: DatabaseSync | undefined;
try {
const sqlite = loadSqlite();
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);
}
}
connection.exec(
[
"PRAGMA journal_mode = WAL",
"PRAGMA synchronous = NORMAL",
"PRAGMA foreign_keys = ON",
`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);
return database;
} catch (error) {
connection?.close();
if (error instanceof DatabaseSchemaTooNewError) throw error;
throw new DatabaseOpenError(input.path, error);
}
}
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.
// Node before 20.16 has no getBuiltinModule; the engines field does not stop a global install.
const sqlite =
typeof process.getBuiltinModule === "function"
? process.getBuiltinModule("node:sqlite")
: undefined;
if (!sqlite) {
throw new Error(`node:sqlite is unavailable in Node ${process.versions.node}; use >= 22.16`);
}
return sqlite;
}
/** Node 22.13 has node:sqlite without `isTransaction`, which rollback needs. */
function assertSupported(connection: DatabaseSync): void {
if (typeof connection.isTransaction !== "boolean") {
throw new Error(`node:sqlite in Node ${process.versions.node} is too old; use >= 22.16`);
}
}
function migrate(database: DaemonDatabase, file: string, modules: readonly SchemaModule[]): void {
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) {
if (names.has(module.name)) throw new Error(`Schema module '${module.name}' is listed twice`);
names.add(module.name);
migrateModule(sql, file, module);
}
});
}
interface StoredVersion {
version: number;
min_reader_version: number;
}
function migrateModule(sql: WriteSql, file: string, module: SchemaModule): void {
const known = module.migrations.length;
const stored = sql.get<StoredVersion>(
"SELECT version, min_reader_version FROM schema_versions WHERE module = ?",
module.name,
);
if (stored && stored.min_reader_version > known) {
throw new DatabaseSchemaTooNewError(file, module.name, stored.min_reader_version, known);
}
const from = stored?.version ?? 0;
if (from >= known) return;
// The first migration creates the store, so no daemon that predates it can read the store.
let minReaderVersion = Math.max(stored?.min_reader_version ?? 0, 1);
for (let index = from; index < known; index++) {
const migration = module.migrations[index];
migration.up(sql);
if (migration.breaking) minReaderVersion = index + 1;
}
sql.run(
"INSERT INTO schema_versions (module, version, min_reader_version) VALUES (?, ?, ?) " +
"ON CONFLICT (module) DO UPDATE SET version = excluded.version, " +
"min_reader_version = excluded.min_reader_version",
module.name,
known,
minReaderVersion,
);
}
type TransactionState = "none" | "read" | "write";
/** Who checkpoints the WAL: SQLite on each commit, a worker not yet started, or the worker. */
type CheckpointerState =
| { kind: "on_thread" }
| { kind: "pending"; path: string }
| { kind: "worker"; worker: WalCheckpointer };
const SQLITE_DEFAULT_AUTOCHECKPOINT_PAGES = 1000;
interface OpenIteration {
close(): void;
}
class SqliteDaemonDatabase implements DaemonDatabase {
private state: TransactionState = "none";
private savepoints = 0;
private closed = false;
private readonly statements = new Map<string, StatementSync>();
private readonly iterating = new Set<StatementSync>();
private checkpointer: CheckpointerState = { kind: "on_thread" };
constructor(
private readonly connection: DatabaseSync,
private readonly logger: Logger,
) {}
write<T>(fn: (sql: WriteSql) => T): T {
this.assertOpen();
if (this.state === "read") throw new Error("Cannot write inside a read transaction");
if (this.state === "write") return this.savepoint(fn);
return this.transaction("write", "BEGIN IMMEDIATE", fn);
}
read<T>(fn: (sql: ReadSql) => T): T {
this.assertOpen();
if (this.state !== "none") return this.scoped(fn);
return this.transaction("read", "BEGIN", fn);
}
/**
* 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.
*/
checkpointOffThread(file: string): void {
this.connection.exec("PRAGMA wal_autocheckpoint = 0");
this.checkpointer = { kind: "pending", path: file };
}
close(): void {
if (this.closed) return;
if (this.state !== "none") throw new Error("Cannot close the database inside a transaction");
this.closed = true;
if (this.checkpointer.kind === "worker" && !this.checkpointer.worker.stop()) {
this.logger.warn("Database WAL checkpointer did not stop before close");
}
try {
const result = this.connection.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get() as
| { busy: number }
| undefined;
if (result?.busy) this.logger.warn("Database WAL checkpoint was blocked by another reader");
} catch (error) {
this.logger.warn({ err: error }, "Database WAL checkpoint failed before close");
}
this.statements.clear();
this.connection.close();
}
private transaction<T>(state: TransactionState, begin: string, fn: (sql: WriteSql) => T): T {
this.connection.exec(begin);
this.state = state;
try {
const result = this.scoped(fn);
this.connection.exec("COMMIT");
if (state === "write") this.startPendingCheckpointer();
return result;
} catch (error) {
if (this.connection.isTransaction) this.connection.exec("ROLLBACK");
throw error;
} finally {
this.state = "none";
}
}
private savepoint<T>(fn: (sql: WriteSql) => T): T {
const name = `paseo_${++this.savepoints}`;
this.connection.exec(`SAVEPOINT ${name}`);
try {
const result = this.scoped(fn);
this.connection.exec(`RELEASE ${name}`);
return result;
} catch (error) {
this.connection.exec(`ROLLBACK TO ${name}`);
this.connection.exec(`RELEASE ${name}`);
throw error;
} finally {
this.savepoints--;
}
}
/** Runs `fn` with a handle that stops working, and closes its iterations, when `fn` returns. */
private scoped<T>(fn: (sql: WriteSql) => T): T {
let valid = true;
const iterations = new Set<OpenIteration>();
const assertValid = () => {
if (!valid) throw new Error("A database handle was used after its transaction ended");
};
const statement = (sql: string) => {
assertValid();
const prepared = this.statement(sql);
if (this.iterating.has(prepared)) {
throw new Error(`A statement is already iterating: ${sql}`);
}
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),
}),
exec: (sql: string) => {
assertValid();
this.connection.exec(sql);
},
};
try {
const result = fn(handle);
if (isThenable(result)) {
throw new Error("A database transaction callback must be synchronous");
}
return result;
} finally {
valid = false;
for (const iteration of iterations) iteration.close();
}
}
private iterate<R>(
prepared: StatementSync,
params: SqlValue[],
iterations: Set<OpenIteration>,
assertValid: () => void,
): Iterable<R> {
const rows = prepared.iterate(...params);
let done = false;
const iteration: OpenIteration = {
close: () => {
if (done) return;
done = true;
this.iterating.delete(prepared);
iterations.delete(iteration);
rows.return?.();
},
};
this.iterating.add(prepared);
iterations.add(iteration);
const iterator: Iterator<R> = {
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 };
},
return: () => {
iteration.close();
return { done: true, value: undefined };
},
};
return { [Symbol.iterator]: () => iterator };
}
/** Runs after a write commits, so it never throws: the write has already happened. */
private startPendingCheckpointer(): void {
if (this.checkpointer.kind !== "pending") return;
try {
const worker = new WalCheckpointer({
path: this.checkpointer.path,
logger: this.logger,
onExit: () => this.checkpointOnThread(),
});
this.checkpointer = { kind: "worker", worker };
} catch (error) {
this.logger.warn({ err: error }, "Database WAL checkpointer did not start");
this.checkpointOnThread();
}
}
/** The worker ended on its own: let SQLite checkpoint again, so the WAL stays bounded. */
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}`);
}
private statement(sql: string): StatementSync {
let prepared = this.statements.get(sql);
if (!prepared) {
prepared = this.connection.prepare(sql);
this.statements.set(sql, prepared);
}
return prepared;
}
private assertOpen(): void {
if (this.closed) throw new DatabaseClosedError();
}
}
function isThenable(value: unknown): boolean {
return (
typeof value === "object" &&
value !== null &&
typeof (value as { then?: unknown }).then === "function"
);
}
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -0,0 +1,88 @@
import { Worker } from "node:worker_threads";
import type { Logger } from "pino";
const CHECKPOINT_INTERVAL_MS = 1000;
const STOP_TIMEOUT_MS = 2000;
const RUNNING = 0;
const STOPPING = 1;
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.
*/
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") {
try {
connection.prepare("PRAGMA wal_checkpoint(PASSIVE)").get();
} catch (error) {
parentPort.postMessage(String(error && error.message ? error.message : error));
}
}
} catch (error) {
parentPort.postMessage(String(error && error.message ? error.message : error));
} finally {
try { connection && connection.close(); } catch {}
Atomics.store(state, 1, ${STOPPED});
Atomics.notify(state, 1);
}
`;
/**
* 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
* event loop on whichever write crossed SQLite's auto-checkpoint threshold. A passive checkpoint
* takes no lock a writer needs, so it runs alongside the daemon's writes.
*/
export class WalCheckpointer {
private readonly state = new Int32Array(new SharedArrayBuffer(8));
private readonly worker: Worker;
private stopped = false;
/** `onExit` runs when the worker ends before `stop`, so checkpoints have stopped. */
constructor(input: { path: string; logger: Logger; onExit: () => void }) {
const { logger } = input;
this.worker = new Worker(WORKER_SOURCE, {
eval: true,
workerData: {
path: input.path,
state: this.state.buffer,
intervalMs: CHECKPOINT_INTERVAL_MS,
},
// Node 22 prints an experimental warning when the worker loads node:sqlite; the daemon
// already printed it once.
stderr: true,
});
this.worker.stderr.resume();
this.worker.on("message", (message: string) => {
logger.warn({ error: message }, "Database WAL checkpoint failed");
});
this.worker.on("error", (error) => {
logger.warn({ err: error }, "Database WAL checkpointer failed");
});
this.worker.on("exit", () => {
if (!this.stopped) input.onExit();
});
this.worker.unref();
}
/**
* Stops the worker, blocking until it has closed its connection, for at most two seconds. False
* when it had not closed by then; it is terminated either way.
*/
stop(): boolean {
if (this.stopped) return true;
this.stopped = true;
Atomics.store(this.state, 0, STOPPING);
Atomics.notify(this.state, 0);
const closed = Atomics.wait(this.state, 1, 0, STOP_TIMEOUT_MS) !== "timed-out";
void this.worker.terminate();
return closed;
}
}
@@ -1,7 +1,10 @@
import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js"; import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js";
import { createPaseoApi } from "@getpaseo/client"; import { createPaseoApi } from "@getpaseo/client";
import type { AgentManager } from "./agent/agent-manager.js"; import type { AgentManager } from "./agent/agent-manager.js";
import { AgentStorage } from "./agent/agent-storage.js";
import { createTestLogger } from "../test-utils/test-logger.js";
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { DatabaseSync } from "node:sqlite";
import { mkdir, readFile, writeFile } from "node:fs/promises"; import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { expect, test } from "vitest"; import { expect, test } from "vitest";
@@ -1423,6 +1426,42 @@ test("archive and delete replies retain their historical names and reach only th
} }
}); });
test("a delete that cannot remove the agent's history fails and leaves the agent usable", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
// A second connection to the daemon's database makes the history delete fail.
const database = new DatabaseSync(path.join(daemon.paseoHome, "paseo.db"));
try {
await admin.connect();
const agent = await admin.createAgent({ provider: "codex", cwd: daemon.staticDir });
database.exec(`CREATE TRIGGER refuse_history_delete BEFORE DELETE ON timeline_scopes
BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END`);
await expect(admin.deleteAgent(agent.id)).rejects.toThrow("disk I/O error");
const afterFailure = await admin.fetchAgents();
expect(afterFailure.entries.map((entry) => entry.agent.id)).toEqual([agent.id]);
await admin.updateAgent(agent.id, { name: "After the failed delete" });
// A fresh reader of the agent directory sees only what reached disk.
const stored = await new AgentStorage(
path.join(daemon.paseoHome, "agents"),
createTestLogger(),
).get(agent.id);
expect(stored?.title).toBe("After the failed delete");
database.exec("DROP TRIGGER refuse_history_delete");
await admin.deleteAgent(agent.id);
expect((await admin.fetchAgents()).entries).toEqual([]);
expect(
database.prepare("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?").all(agent.id),
).toEqual([]);
} finally {
database.close();
await admin.close();
await daemon.close();
}
});
test("Hub bootstrap sends its server ID before the producer's synchronous snapshot", async () => { test("Hub bootstrap sends its server ID before the producer's synchronous snapshot", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
+19 -12
View File
@@ -380,6 +380,7 @@ function clientUsesLegacyWorkspaceRestore(appVersion: string | null): boolean {
type DeleteFencedAgentStorage = AgentStorage & { type DeleteFencedAgentStorage = AgentStorage & {
beginDelete(agentId: string): void; beginDelete(agentId: string): void;
abandonDelete(agentId: string): void;
}; };
function beginAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string): void { function beginAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string): void {
@@ -388,6 +389,12 @@ function beginAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string
} }
} }
function abandonAgentDeleteIfSupported(agentStorage: AgentStorage, agentId: string): void {
if ("abandonDelete" in agentStorage && typeof agentStorage.abandonDelete === "function") {
(agentStorage as DeleteFencedAgentStorage).abandonDelete(agentId);
}
}
const FETCH_AGENTS_SORT_KEYS = ["status_priority", "created_at", "updated_at", "title"] as const; const FETCH_AGENTS_SORT_KEYS = ["status_priority", "created_at", "updated_at", "title"] as const;
export function resolveWaitForFinishError(options: { export function resolveWaitForFinishError(options: {
@@ -3884,14 +3891,17 @@ export class Session {
// durable snapshot, otherwise an in-flight background write can recreate it. // durable snapshot, otherwise an in-flight background write can recreate it.
await this.agentManager.flush(); await this.agentManager.flush();
// History goes before the record: if it cannot be removed, the request fails and the record
// stays, so the user still sees the agent, can keep using it, and can delete it again.
try { try {
await this.agentStorage.remove(agentId);
await this.agentManager.deleteAgentState(agentId); await this.agentManager.deleteAgentState(agentId);
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
} catch (error) { } catch (error) {
this.sessionLogger.error({ err: error, agentId }, `Failed to fully delete agent ${agentId}`); abandonAgentDeleteIfSupported(this.agentStorage, agentId);
throw error;
} }
await this.agentStorage.remove(agentId);
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
this.emit({ this.emit({
type: "agent_deleted", type: "agent_deleted",
@@ -5603,7 +5613,7 @@ export class Session {
} }
const event = serializeAgentStreamEvent({ const event = serializeAgentStreamEvent({
type: "timeline", type: "timeline",
provider, provider: row.provider ?? provider,
item: row.item, item: row.item,
...(row.turnId ? { turnId: row.turnId } : {}), ...(row.turnId ? { turnId: row.turnId } : {}),
timestamp: row.timestamp, timestamp: row.timestamp,
@@ -8774,7 +8784,8 @@ export class Session {
: {}), : {}),
entries: entries.map((entry) => { entries: entries.map((entry) => {
const payloadEntry = { const payloadEntry = {
provider: agentPayload.provider, // A row keeps the provider that wrote it; older rows have none.
provider: entry.provider ?? agentPayload.provider,
item: entry.item, item: entry.item,
timestamp: entry.timestamp, timestamp: entry.timestamp,
seqStart: entry.seqStart, seqStart: entry.seqStart,
@@ -8905,13 +8916,9 @@ export class Session {
): Promise<void> { ): Promise<void> {
try { try {
await this.loadAgentHistoryPayload(msg.agentId); await this.loadAgentHistoryPayload(msg.agentId);
const rows = await this.agentManager.getTimelineRows(msg.agentId); const { head, rows } = await this.agentManager.getTimelinePrompts(msg.agentId);
const timeline = await this.agentManager.fetchTimeline(msg.agentId, {
direction: "tail",
limit: 1,
});
const index = buildTimelinePromptIndex( const index = buildTimelinePromptIndex(
this.wireEpoch(timeline.epoch, timeline.retirementCount, source), this.wireEpoch(head.epoch, head.retirementCount, source),
rows, rows,
); );
this.emitForSource( this.emitForSource(
@@ -0,0 +1,17 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
let directory: string | undefined;
let count = 0;
/** A path for a test database that no other test uses, in a directory removed at process exit. */
export function nextTestDatabasePath(): string {
if (!directory) {
const created = mkdtempSync(path.join(tmpdir(), "paseo-database-"));
directory = created;
process.once("exit", () => rmSync(created, { recursive: true, force: true }));
}
count += 1;
return path.join(directory, `test-${count}.db`);
}
@@ -458,6 +458,26 @@ describe("wire compatibility", () => {
expect(currentParsed.payload.entries[0]?.collapsed).toContain("reasoning_merge"); expect(currentParsed.payload.entries[0]?.collapsed).toContain("reasoning_merge");
}); });
test("serves each entry with the provider that wrote it, the agent's when the row has none", async () => {
const response = await emitTimelineResponse({
rows: [
{
seq: 1,
timestamp: "2026-05-02T00:00:00.000Z",
provider: "claude",
item: { type: "user_message", text: "prompt" },
},
{
seq: 2,
timestamp: "2026-05-02T00:00:01.000Z",
item: { type: "assistant_message", text: "done" },
},
],
});
expect(response.payload.entries.map((entry) => entry.provider)).toEqual(["claude", "codex"]);
});
test("carries canonical turn IDs to new clients while legacy schemas ignore them", async () => { test("carries canonical turn IDs to new clients while legacy schemas ignore them", async () => {
const response = await emitTimelineResponse({ const response = await emitTimelineResponse({
rows: [ rows: [