mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ddd23f4cf9 | ||
|
|
13734eeba9 | ||
|
|
51f04592d5 | ||
|
|
2dd7bf6525 | ||
|
|
393d0608dd | ||
|
|
aa0a91ff6c | ||
|
|
a99a731430 | ||
|
|
201972f548 | ||
|
|
270f25458a |
@@ -403,7 +403,7 @@ initializing → idle ⇄ running
|
||||
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.
|
||||
- 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
|
||||
|
||||
@@ -479,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
+37
-5
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo 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`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── 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)
|
||||
├── agents/
|
||||
│ └── {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
|
||||
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume
|
||||
imports provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`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
@@ -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
|
||||
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
|
||||
without its provider. Deleting the agent deletes its history and every child's, retired ones
|
||||
included.
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
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.
|
||||
|
||||
`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
|
||||
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
|
||||
memory, so a daemon restart loses the owned history: the next resume imports provider history into
|
||||
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come
|
||||
back if the provider history still holds them. Retained history costs memory for every loaded,
|
||||
closed or archived agent until the daemon exits or the agent is deleted.
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
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
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
|
||||
Generated
+20
-1
@@ -45,6 +45,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39719,6 +39722,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40646,7 +40652,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40654,6 +40660,9 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41101,6 +41110,16 @@
|
||||
"@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": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,5 +169,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,5 +47,8 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"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.");
|
||||
|
||||
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?.requiresAttention, false);
|
||||
await waitFor(async () => {
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -171,5 +171,8 @@
|
||||
},
|
||||
"overrides": {
|
||||
"lightningcss": "1.30.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ import {
|
||||
type ManagedAgent,
|
||||
} from "./agent-manager.js";
|
||||
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
|
||||
import { AgentTimeline } from "./timeline/index.js";
|
||||
import { DeferredTimelineBackend } from "./timeline/testing.js";
|
||||
import { AgentTimeline, createStoredAgentTimeline } from "./timeline/index.js";
|
||||
import { DeferredTimelineBackend, openTestTimelineDatabase } from "./timeline/testing.js";
|
||||
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js";
|
||||
@@ -6881,6 +6881,207 @@ test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps
|
||||
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 () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
|
||||
@@ -93,6 +93,7 @@ import {
|
||||
type TimelineAppendResult,
|
||||
type TimelineCommit,
|
||||
type TimelineHead,
|
||||
type TimelinePrompts,
|
||||
type TimelineEntry,
|
||||
type TimelineIngestResult,
|
||||
type TimelineRetirementCommit,
|
||||
@@ -511,6 +512,16 @@ interface HandleStreamEventOptions {
|
||||
fromHistory?: boolean;
|
||||
}
|
||||
|
||||
interface StreamEventDispatch {
|
||||
agent: ActiveManagedAgent;
|
||||
event: AgentStreamEvent;
|
||||
options: HandleStreamEventOptions | undefined;
|
||||
isForegroundEvent: boolean;
|
||||
eventTurnId: string | undefined;
|
||||
terminalDisposition: ActiveTurnTerminalDisposition;
|
||||
flags: StreamEventFlags;
|
||||
}
|
||||
|
||||
interface ManagedAgentBase {
|
||||
id: string;
|
||||
provider: AgentProvider;
|
||||
@@ -1506,6 +1517,12 @@ export class AgentManager {
|
||||
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. */
|
||||
async getLoadedTimelineHead(id: string): Promise<TimelineHead | null> {
|
||||
if (!this.getAgent(id)) return null;
|
||||
@@ -1639,14 +1656,20 @@ export class AgentManager {
|
||||
`Agent ${resolvedAgentId} references unavailable provider '${record.provider}'`,
|
||||
);
|
||||
}
|
||||
return this.createAgentInternal(config, resolvedAgentId, {
|
||||
labels: record.labels,
|
||||
metadata: record.metadata,
|
||||
workspaceId: record.workspaceId,
|
||||
owner: record.owner,
|
||||
background: record.background,
|
||||
env: record.launchEnv,
|
||||
});
|
||||
return this.createAgentInternal(
|
||||
config,
|
||||
resolvedAgentId,
|
||||
{
|
||||
labels: record.labels,
|
||||
metadata: record.metadata,
|
||||
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" },
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1655,6 +1678,7 @@ export class AgentManager {
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
{ history }: { history: "discard" | "keep" } = { history: "discard" },
|
||||
): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
config = this.withConvertedOptions(config);
|
||||
@@ -1677,7 +1701,8 @@ export class AgentManager {
|
||||
};
|
||||
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(
|
||||
config,
|
||||
resolvedAgentId,
|
||||
@@ -4784,6 +4809,8 @@ export class AgentManager {
|
||||
agentId: resolvedAgentId,
|
||||
session,
|
||||
now,
|
||||
// Nothing about an internal agent is on disk, its history included.
|
||||
inMemory: config.internal === true,
|
||||
options,
|
||||
});
|
||||
|
||||
@@ -4907,6 +4934,7 @@ export class AgentManager {
|
||||
agentId: string;
|
||||
session: AgentSession;
|
||||
now: Date;
|
||||
inMemory: boolean;
|
||||
options:
|
||||
| {
|
||||
providerHistory?: readonly TimelineEntry[];
|
||||
@@ -4921,22 +4949,24 @@ export class AgentManager {
|
||||
| { kind: "kept" }
|
||||
| { kind: "imported"; subagents: ProviderSubagentStreamEvent[]; sessionMetrics?: AgentMetric[] }
|
||||
> {
|
||||
const { agentId, session, now, options } = params;
|
||||
const { agentId, session, now, inMemory, options } = params;
|
||||
const scope: TimelineScope = { agentId };
|
||||
if (options?.providerHistory) {
|
||||
const result = await this.timeline.importHistory(scope, options.providerHistory, {
|
||||
timestamp: (options.updatedAt ?? options.createdAt ?? now).toISOString(),
|
||||
inMemory,
|
||||
});
|
||||
return result.kind === "imported" ? { kind: "imported", subagents: [] } : { kind: "kept" };
|
||||
}
|
||||
if (await this.timeline.describe(scope)) return { kind: "kept" };
|
||||
if (!options?.importMissingHistory) {
|
||||
await this.timeline.create(scope, { timestamp: now.toISOString() });
|
||||
await this.timeline.create(scope, { timestamp: now.toISOString() }, { inMemory });
|
||||
return { kind: "created" };
|
||||
}
|
||||
const history = await this.readProviderHistory(session.streamHistory());
|
||||
const result = await this.timeline.importHistory(scope, history.entries, {
|
||||
timestamp: now.toISOString(),
|
||||
inMemory,
|
||||
});
|
||||
return result.kind === "imported"
|
||||
? {
|
||||
@@ -5108,9 +5138,14 @@ export class AgentManager {
|
||||
|
||||
private async discardRetainedAgentState(agentId: string): Promise<void> {
|
||||
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.detachPluginTools(agentId);
|
||||
for (const event of removed) this.publishProviderSubagent(event);
|
||||
this.clearProviderBackgroundWork(agentId);
|
||||
}
|
||||
|
||||
@@ -5444,11 +5479,9 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
event = await this.settleTurnMetrics({ agent, event, options, terminalDisposition });
|
||||
|
||||
const flags: StreamEventFlags = { shouldDispatchEvent: true, shouldNotifyWaiters: true };
|
||||
|
||||
const dispatchPromise = this.dispatchStreamEventByType({
|
||||
event = await this.recordStreamEvent({
|
||||
agent,
|
||||
event,
|
||||
options,
|
||||
@@ -5457,9 +5490,6 @@ export class AgentManager {
|
||||
terminalDisposition,
|
||||
flags,
|
||||
});
|
||||
if (dispatchPromise) {
|
||||
await dispatchPromise;
|
||||
}
|
||||
|
||||
if (!options?.fromHistory) {
|
||||
if (isTurnTerminalEvent(event)) {
|
||||
@@ -5571,15 +5601,32 @@ export class AgentManager {
|
||||
this.emitState(agent);
|
||||
}
|
||||
|
||||
private dispatchStreamEventByType(params: {
|
||||
agent: ActiveManagedAgent;
|
||||
event: AgentStreamEvent;
|
||||
options: HandleStreamEventOptions | undefined;
|
||||
isForegroundEvent: boolean;
|
||||
eventTurnId: string | undefined;
|
||||
terminalDisposition: ActiveTurnTerminalDisposition;
|
||||
flags: StreamEventFlags;
|
||||
}): Promise<void> | undefined {
|
||||
/**
|
||||
* Applies the event by type, then stamps a completed turn's metrics, returning the event as
|
||||
* stamped. Handlers change the agent's state before they write, so a terminal event whose
|
||||
* record fails to write still ends the turn; the failure is logged.
|
||||
*/
|
||||
private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
|
||||
const { agent, options, eventTurnId, terminalDisposition } = params;
|
||||
const event = withTurnMetrics(params);
|
||||
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 } =
|
||||
params;
|
||||
switch (event.type) {
|
||||
@@ -5719,29 +5766,6 @@ export class AgentManager {
|
||||
* 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.
|
||||
*/
|
||||
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: {
|
||||
agent: ActiveManagedAgent;
|
||||
event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
|
||||
@@ -5809,13 +5833,13 @@ export class AgentManager {
|
||||
agent.lifecycle = "error";
|
||||
}
|
||||
agent.lastError = event.error;
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
|
||||
await this.appendSystemErrorTimelineMessage(
|
||||
agent,
|
||||
event.provider,
|
||||
this.formatTurnFailedMessage(event),
|
||||
options,
|
||||
);
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
|
||||
}
|
||||
|
||||
private onStreamTurnCanceled(params: {
|
||||
@@ -6844,3 +6868,22 @@ function pluginPromptContext(
|
||||
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
|
||||
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
await this.load();
|
||||
this.beginDelete(agentId);
|
||||
|
||||
@@ -332,7 +332,7 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
/** A retained item. `seq` is its latest source event, not its display anchor. */
|
||||
export type ProjectedTimelineRow = AgentTimelineRow & TimelineProjectionEntry;
|
||||
|
||||
interface ProjectedTimelinePageOptions {
|
||||
export interface ProjectedTimelinePageOptions {
|
||||
wholeTurns?: boolean;
|
||||
bounds: { minSeq: number; maxSeq: number };
|
||||
direction: TimelineLimitDirection;
|
||||
@@ -340,6 +340,61 @@ interface ProjectedTimelinePageOptions {
|
||||
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. */
|
||||
export class TimelineProjection {
|
||||
private readonly rows: ProjectedTimelineRow[] = [];
|
||||
@@ -375,28 +430,26 @@ export class TimelineProjection {
|
||||
}
|
||||
|
||||
private appendProjected(row: AgentTimelineRow): number {
|
||||
const entry = makeCanonicalEntries([row])[0];
|
||||
const identity = timelineItemIdentity(row.item);
|
||||
const index = identity === null ? undefined : this.identities.get(identity);
|
||||
const existing = index === undefined ? undefined : this.rows[index];
|
||||
const merged = existing ? mergeIdentityEntries(existing, entry) : null;
|
||||
if (merged && index !== undefined) {
|
||||
this.rows[index] = { ...merged, seq: merged.seqEnd };
|
||||
const fold = foldTimelineRow({
|
||||
row,
|
||||
identityRow: index === undefined ? undefined : this.rows[index],
|
||||
lastRow: this.rows.at(-1),
|
||||
});
|
||||
if (fold.kind === "identity" && index !== undefined) {
|
||||
this.rows[index] = fold.row;
|
||||
this.extendSpan(index);
|
||||
return index;
|
||||
}
|
||||
const previous = this.rows.at(-1);
|
||||
const adjacent = previous
|
||||
? mergeReasoningChunks(mergeAssistantChunks([previous, entry]))
|
||||
: [entry];
|
||||
if (previous && adjacent.length === 1) {
|
||||
const mergedText = adjacent[0];
|
||||
this.rows[this.rows.length - 1] = { ...mergedText, seq: mergedText.seqEnd };
|
||||
if (fold.kind === "adjacent") {
|
||||
this.rows[this.rows.length - 1] = fold.row;
|
||||
this.extendSpan(this.rows.length - 1);
|
||||
return this.rows.length - 1;
|
||||
}
|
||||
const entry = fold.row;
|
||||
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);
|
||||
if (last && last.endSeq >= entry.seqStart) {
|
||||
last.endSeq = Math.max(last.endSeq, entry.seqEnd);
|
||||
@@ -516,19 +569,9 @@ export class TimelineProjection {
|
||||
}
|
||||
|
||||
private coalesceRetirements(retirements: readonly TimelineRetirement[]): TimelineRetirement[] {
|
||||
const coalesced: TimelineRetirement[] = [];
|
||||
for (const retirement of retirements) {
|
||||
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;
|
||||
return coalesceTimelineRetirements(retirements, (startSeq, endSeq) =>
|
||||
this.hasActiveAnchorIn(startSeq, endSeq),
|
||||
);
|
||||
}
|
||||
|
||||
private hasActiveAnchorIn(startSeq: number, endSeq: number): boolean {
|
||||
@@ -692,7 +735,7 @@ export class TimelineProjection {
|
||||
const start = input.wholeTurns ? this.wholeTurnWindowStart(requestedStart) : requestedStart;
|
||||
// Choose the window before extending the right edge, so a prompt jump
|
||||
// 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]))
|
||||
low++;
|
||||
}
|
||||
@@ -897,7 +940,7 @@ interface ProjectedEntryCandidate {
|
||||
firstSourceSeq: number;
|
||||
}
|
||||
|
||||
function selectProjectedEntriesAfter(input: {
|
||||
export function selectProjectedEntriesAfter(input: {
|
||||
entries: readonly TimelineProjectionEntry[];
|
||||
/** Seqs covered without an active row; they advance the cursor but add no entry. */
|
||||
covered?: readonly TimelineSeqRange[];
|
||||
@@ -939,7 +982,7 @@ function selectProjectedEntriesAfter(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function continuesProjectedTurn(
|
||||
export function continuesProjectedTurn(
|
||||
previous: TimelineProjectionEntry,
|
||||
next: TimelineProjectionEntry,
|
||||
): boolean {
|
||||
|
||||
@@ -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 {
|
||||
AgentTimeline,
|
||||
TimelineClosedError,
|
||||
TimelineRewindBoundaryError,
|
||||
TimelineRewindPendingError,
|
||||
TimelineRewindTargetError,
|
||||
@@ -9,6 +14,7 @@ export {
|
||||
type TimelineEntry,
|
||||
type TimelineHead,
|
||||
type TimelineImportResult,
|
||||
type TimelinePrompts,
|
||||
type TimelineIngestResult,
|
||||
type TimelineReconcileResult,
|
||||
type TimelineRetirement,
|
||||
@@ -19,3 +25,9 @@ export {
|
||||
type TimelineScope,
|
||||
type TimelineSeed,
|
||||
} 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";
|
||||
export type { TimelineRetirement } from "../../timeline-projection.js";
|
||||
|
||||
export interface TimelinePrompts {
|
||||
head: TimelineHead;
|
||||
rows: ProjectedTimelineRow[];
|
||||
}
|
||||
|
||||
export interface TimelineCommit {
|
||||
row: AgentTimelineRow;
|
||||
epoch: string;
|
||||
@@ -72,6 +77,14 @@ export type TimelineRewindVerdict =
|
||||
| { kind: "absent" };
|
||||
|
||||
/** 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 {
|
||||
constructor(readonly intent: TimelineRewindIntent) {
|
||||
super("Another rewind of this conversation has not settled");
|
||||
@@ -143,6 +156,14 @@ export interface TimelineAppendOptions {
|
||||
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.
|
||||
*
|
||||
@@ -153,23 +174,37 @@ export interface TimelineAppendOptions {
|
||||
export class AgentTimeline {
|
||||
private readonly tails = new Map<string, Promise<void>>();
|
||||
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> {
|
||||
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. */
|
||||
create(scope: TimelineScope, seed: TimelineSeed = {}): Promise<TimelineHead> {
|
||||
return this.run(scope, async () => this.track(scope, await this.backend.create(scope, seed)));
|
||||
create(
|
||||
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. */
|
||||
open(scope: TimelineScope): Promise<TimelineHead> {
|
||||
return this.run(scope, async () => {
|
||||
const existing = await this.backend.head(scope);
|
||||
return existing ?? this.track(scope, await this.backend.create(scope, {}));
|
||||
const existing = await this.backendFor(scope).head(scope);
|
||||
return existing ?? this.track(scope, await this.backendFor(scope).create(scope, {}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,12 +215,13 @@ export class AgentTimeline {
|
||||
importHistory(
|
||||
scope: TimelineScope,
|
||||
entries: readonly TimelineEntry[],
|
||||
options: { timestamp?: string } = {},
|
||||
options: { timestamp?: string } & TimelineRetention = {},
|
||||
): Promise<TimelineImportResult> {
|
||||
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 };
|
||||
const head = await this.backend.create(scope, {
|
||||
const head = await this.backendFor(scope).create(scope, {
|
||||
entries: entries.map(providerHistoryEntry),
|
||||
timestamp: options.timestamp,
|
||||
});
|
||||
@@ -207,8 +243,8 @@ export class AgentTimeline {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) return { kind: "rewind_open" };
|
||||
const plan = planProviderHistory({
|
||||
rows: await this.backend.readRows(scope),
|
||||
prompts: await this.backend.prompts(scope),
|
||||
rows: await this.backendFor(scope).readRows(scope),
|
||||
prompts: await this.prompts(scope),
|
||||
provider: entries.map(providerHistoryEntry),
|
||||
});
|
||||
if (plan.kind !== "append") return plan;
|
||||
@@ -222,7 +258,7 @@ export class AgentTimeline {
|
||||
|
||||
/** The agent's provider children, retired ones included. */
|
||||
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,
|
||||
): Promise<ProviderSubagentDescriptor | null> {
|
||||
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;
|
||||
const descriptor = update(child?.descriptor ?? null);
|
||||
await this.backend.setChild(scope, descriptor);
|
||||
await this.backendFor(scope).setChild(scope, descriptor);
|
||||
return descriptor;
|
||||
});
|
||||
}
|
||||
@@ -248,9 +284,9 @@ export class AgentTimeline {
|
||||
entries: readonly TimelineEntry[],
|
||||
): Promise<TimelineCommit[] | null> {
|
||||
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) 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);
|
||||
});
|
||||
}
|
||||
@@ -258,9 +294,9 @@ export class AgentTimeline {
|
||||
/** Deletes a child's history. A retired child stays stored and resolves false. */
|
||||
removeChild(scope: TimelineScope): Promise<boolean> {
|
||||
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;
|
||||
await this.backend.delete(scope);
|
||||
await this.backendFor(scope).delete(scope);
|
||||
this.sizes.delete(sizeKey(scope));
|
||||
return true;
|
||||
});
|
||||
@@ -269,9 +305,10 @@ export class AgentTimeline {
|
||||
/** Deleting an agent's root history deletes all of its children's too. */
|
||||
delete(scope: TimelineScope): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
await this.backend.delete(scope);
|
||||
await this.backendFor(scope).delete(scope);
|
||||
this.sizes.delete(sizeKey(scope));
|
||||
if (scope.subagentId !== undefined) return;
|
||||
this.memoryAgents.delete(scope.agentId);
|
||||
const childPrefix = sizeKey({ agentId: scope.agentId, subagentId: "" });
|
||||
for (const key of this.sizes.keys()) {
|
||||
if (key.startsWith(childPrefix)) this.sizes.delete(key);
|
||||
@@ -287,7 +324,7 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const clientMessageId = submittedPromptId(entry.item);
|
||||
if (clientMessageId) {
|
||||
const existing = await this.backend.findSubmittedPrompt(scope, clientMessageId);
|
||||
const existing = await this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId);
|
||||
if (existing) {
|
||||
const head = await this.requireHead(scope);
|
||||
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 failure = publishCommitted(options?.publish, commit);
|
||||
return failure
|
||||
@@ -329,7 +366,7 @@ export class AgentTimeline {
|
||||
providerMessageId: string,
|
||||
): Promise<AgentTimelineRow | null> {
|
||||
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[],
|
||||
options?: { turnId?: string },
|
||||
): 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(
|
||||
scope: TimelineScope,
|
||||
clientMessageId: string,
|
||||
): Promise<AgentTimelineRow | null> {
|
||||
return this.run(scope, () => this.backend.findSubmittedPrompt(scope, clientMessageId));
|
||||
return this.run(scope, () =>
|
||||
this.backendFor(scope).findSubmittedPrompt(scope, clientMessageId),
|
||||
);
|
||||
}
|
||||
|
||||
fetch(
|
||||
scope: TimelineScope,
|
||||
options: AgentTimelineFetchOptions = {},
|
||||
): 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[]> {
|
||||
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> {
|
||||
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.
|
||||
*/
|
||||
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 () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
|
||||
const target = (await this.backend.prompts(scope)).find(
|
||||
(prompt) => prompt.messageId === messageId,
|
||||
);
|
||||
const target = (await this.prompts(scope)).find((prompt) => prompt.messageId === messageId);
|
||||
if (!target) throw new TimelineRewindTargetError(messageId);
|
||||
const intent: TimelineRewindIntent = {
|
||||
id: randomUUID(),
|
||||
messageId,
|
||||
targetSeq: target.seqStart,
|
||||
};
|
||||
await this.backend.setRewind(scope, intent);
|
||||
await this.backendFor(scope).setRewind(scope, intent);
|
||||
return intent;
|
||||
});
|
||||
}
|
||||
@@ -405,7 +450,7 @@ export class AgentTimeline {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind?.id !== intentId) return null;
|
||||
const intent = { ...head.rewind, cut };
|
||||
await this.backend.setRewind(scope, intent);
|
||||
await this.backendFor(scope).setRewind(scope, intent);
|
||||
return intent;
|
||||
});
|
||||
}
|
||||
@@ -414,7 +459,7 @@ export class AgentTimeline {
|
||||
abandonRewind(scope: TimelineScope, intentId: string): Promise<void> {
|
||||
return this.run(scope, async () => {
|
||||
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 () => {
|
||||
const intent = (await this.requireHead(scope)).rewind;
|
||||
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;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
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);
|
||||
const result = await this.backend.retire(scope, {
|
||||
const result = await this.backendFor(scope).retire(scope, {
|
||||
retireFromSeq,
|
||||
selectChildren: childrenSpawnedBy,
|
||||
});
|
||||
@@ -474,9 +519,20 @@ export class AgentTimeline {
|
||||
* Callers use it so an event published outside the timeline cannot overtake queued writes.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. */
|
||||
residentSize(scope: TimelineScope): number | null {
|
||||
return this.sizes.get(sizeKey(scope)) ?? null;
|
||||
@@ -486,7 +542,7 @@ export class AgentTimeline {
|
||||
scope: TimelineScope,
|
||||
entries: readonly TimelineEntry[],
|
||||
): 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);
|
||||
return rows.map((row) => ({
|
||||
row,
|
||||
@@ -496,17 +552,31 @@ export class AgentTimeline {
|
||||
}
|
||||
|
||||
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);
|
||||
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 {
|
||||
this.sizes.set(sizeKey(scope), head.size);
|
||||
return head;
|
||||
}
|
||||
|
||||
private run<T>(scope: TimelineScope, operation: () => T | Promise<T>): Promise<T> {
|
||||
if (this.closed) return Promise.reject(new TimelineClosedError());
|
||||
const key = scope.agentId;
|
||||
const previous = this.tails.get(key) ?? Promise.resolve();
|
||||
const result = previous.then(operation);
|
||||
@@ -643,3 +713,13 @@ function sizeKey(scope: TimelineScope): string {
|
||||
function submittedPromptId(item: AgentTimelineItem): string | 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ export interface TimelineRewindIntent {
|
||||
}
|
||||
|
||||
/** An active user prompt: what a rewind addresses. */
|
||||
/** What the timeline knows about an active prompt row; see `toTimelinePrompt`. */
|
||||
export interface TimelinePrompt {
|
||||
seqStart: number;
|
||||
messageId: string | undefined;
|
||||
@@ -119,8 +120,8 @@ export interface AgentTimelineBackend {
|
||||
): MaybePromise<TimelineBackendAppendResult>;
|
||||
/** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>;
|
||||
/** Active user prompts in display order. */
|
||||
prompts(scope: TimelineScope): MaybePromise<TimelinePrompt[]>;
|
||||
/** Active user prompt rows in display order, read without the rest of the history. */
|
||||
promptRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>;
|
||||
/**
|
||||
* Allocates the next sequence number for a retirement of the active rows anchored at or after
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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));
|
||||
const gap =
|
||||
!staleCursor &&
|
||||
direction === "after" &&
|
||||
cursor !== undefined &&
|
||||
hasRows &&
|
||||
cursor.seq < history.minSeq - 1;
|
||||
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 { limitAgentTimelineItemContent } from "../../agent-timeline-content.js";
|
||||
import type { AgentMetric, AgentTimelineItem } from "../../agent-sdk-types.js";
|
||||
import type {
|
||||
AgentTimelineFetchOptions,
|
||||
@@ -16,12 +15,13 @@ import type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
} from "./backend.js";
|
||||
import { UnknownTimelineError } from "./backend.js";
|
||||
import { fetchTimelinePage } from "./fetch-page.js";
|
||||
import { buildSourceRow } from "./source-row.js";
|
||||
|
||||
interface MemoryTimelineState {
|
||||
epoch: string;
|
||||
@@ -37,8 +37,6 @@ interface MemoryTimelineState {
|
||||
childRetired: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
|
||||
|
||||
function scopeKey(scope: TimelineScope): string {
|
||||
return scope.subagentId === undefined
|
||||
? scope.agentId
|
||||
@@ -53,17 +51,6 @@ function cloneRow<T extends AgentTimelineRow>(row: T): T {
|
||||
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. */
|
||||
export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
private readonly states = new Map<string, MemoryTimelineState>();
|
||||
@@ -73,7 +60,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
const startSeq = seed.nextSeq ?? 1;
|
||||
const rows = seed.rows?.length
|
||||
? 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 projection = new TimelineProjection(rows);
|
||||
const state: MemoryTimelineState = {
|
||||
@@ -137,7 +126,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
append(scope: TimelineScope, entries: readonly TimelineEntry[]): TimelineBackendAppendResult {
|
||||
const state = this.requireState(scope);
|
||||
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) {
|
||||
state.projection.append(row);
|
||||
state.nextSeq = row.seq + 1;
|
||||
@@ -150,18 +141,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
return this.requireState(scope).projection.isRetired(entry);
|
||||
}
|
||||
|
||||
prompts(scope: TimelineScope): TimelinePrompt[] {
|
||||
const prompts: TimelinePrompt[] = [];
|
||||
for (const row of this.requireState(scope).projection.getRows()) {
|
||||
if (row.item.type !== "user_message") continue;
|
||||
prompts.push({
|
||||
seqStart: row.seqStart,
|
||||
messageId: row.item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: row.item.clientMessageId !== undefined,
|
||||
});
|
||||
}
|
||||
return prompts;
|
||||
promptRows(scope: TimelineScope): ProjectedTimelineRow[] {
|
||||
return this.requireState(scope)
|
||||
.projection.getRows()
|
||||
.filter((row) => row.item.type === "user_message")
|
||||
.map(cloneRow);
|
||||
}
|
||||
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead {
|
||||
@@ -233,48 +217,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
|
||||
fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult {
|
||||
const state = this.requireState(scope);
|
||||
const direction = options.direction ?? "tail";
|
||||
const cursor = options.cursor;
|
||||
const hasRows = state.minSeq !== 0;
|
||||
const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq };
|
||||
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 fetchTimelinePage({
|
||||
history: state,
|
||||
options,
|
||||
selectPage: (page) => state.projection.selectPage(page),
|
||||
});
|
||||
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[] {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
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.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 { 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 {
|
||||
AgentTimelineFetchOptions,
|
||||
@@ -16,12 +20,12 @@ import type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
} from "./internal/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`.
|
||||
@@ -39,18 +43,37 @@ export interface InspectableTimelineBackend extends AgentTimelineBackend {
|
||||
export const TIMELINE_CONTRACT_BACKENDS: ReadonlyArray<{
|
||||
name: string;
|
||||
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
|
||||
* store, records the committed appends and whole-history reads, and fails the next append or
|
||||
* retirement on request.
|
||||
* store, records the committed appends and whole-history reads, and fails the next append,
|
||||
* retirement, or metrics stamp on request.
|
||||
*/
|
||||
export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
readonly appends: TimelineEntry[][] = [];
|
||||
readRowsCalls = 0;
|
||||
failNextAppend = false;
|
||||
failNextRetire = false;
|
||||
failNextStampTurnMetrics = false;
|
||||
|
||||
constructor(private readonly inner: InspectableTimelineBackend = new MemoryTimelineBackend()) {}
|
||||
|
||||
@@ -85,8 +108,8 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> {
|
||||
return this.defer(() => this.inner.isRetired(scope, entry));
|
||||
}
|
||||
prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
|
||||
return this.defer(() => this.inner.prompts(scope));
|
||||
promptRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
|
||||
return this.defer(() => this.inner.promptRows(scope));
|
||||
}
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> {
|
||||
return this.defer(() => this.inner.setRewind(scope, rewind));
|
||||
@@ -130,7 +153,13 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
metrics: AgentMetric[],
|
||||
options?: { turnId?: string },
|
||||
): 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(
|
||||
scope: TimelineScope,
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
createPersistedWorkspaceRecord,
|
||||
} from "./workspace-registry.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 { hashDaemonPassword } from "./auth.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 () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-cleanup-"));
|
||||
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-restart-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const obsoleteTimelineDirectory = path.join(paseoHome, "agent-timelines");
|
||||
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-timeline-agent-"));
|
||||
await mkdir(obsoleteTimelineDirectory, { recursive: true });
|
||||
await writeFile(path.join(obsoleteTimelineDirectory, "obsolete.json"), "{}\n", "utf-8");
|
||||
|
||||
const daemonHandle = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
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(
|
||||
{ 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(obsoleteTimelineDirectory)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const second = await createTestPaseoDaemon({ paseoHomeRoot, cleanup: false });
|
||||
try {
|
||||
const { agentManager, agentStorage } = second.daemon;
|
||||
const source = await loadAgentHistory(agentId, {
|
||||
agentManager,
|
||||
agentStorage,
|
||||
logger: pino({ level: "silent" }),
|
||||
purpose: "history",
|
||||
});
|
||||
expect(source.kind).toBe("stored");
|
||||
const page = await agentManager.fetchTimeline(agentId, { direction: "tail" });
|
||||
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 {
|
||||
await daemonHandle.close();
|
||||
await Promise.all([
|
||||
rm(paseoHomeRoot, { recursive: true, force: true }),
|
||||
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 }),
|
||||
]);
|
||||
// Windows can hold a closed daemon's directory handles briefly, as in `removeDirs`.
|
||||
const retry = { recursive: true, force: true, maxRetries: 3, retryDelay: 100 };
|
||||
await Promise.all([rm(paseoHomeRoot, retry), rm(agentCwd, retry)]);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { describeHookWorkspace } from "./plugins/lifecycle/index.js";
|
||||
import express from "express";
|
||||
import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http";
|
||||
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 { getHostName } from "./host-name.js";
|
||||
import path from "node:path";
|
||||
@@ -148,6 +148,8 @@ import type { RequestedSpeechProviders } from "./speech/speech-types.js";
|
||||
import { createSpeechService } from "./speech/speech-runtime.js";
|
||||
import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
|
||||
import { AgentManager } from "./agent/agent-manager.js";
|
||||
import { createStoredAgentTimeline, timelineSchema } from "./agent/timeline/index.js";
|
||||
import { openDaemonDatabase } from "./database/index.js";
|
||||
import { AgentStorage } from "./agent/agent-storage.js";
|
||||
import { attachAgentStoragePersistence } from "./persistence-hooks.js";
|
||||
import { createAgentMcpServer } from "./agent/mcp-server.js";
|
||||
@@ -645,6 +647,13 @@ export async function createPaseoDaemon(
|
||||
"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);
|
||||
const bootstrapStart = performance.now();
|
||||
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
|
||||
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
|
||||
@@ -1045,6 +1054,7 @@ export async function createPaseoDaemon(
|
||||
clients: initialAgentManagerState.clients,
|
||||
providerDefinitions: initialAgentManagerState.providerDefinitions,
|
||||
registry: agentStorage,
|
||||
timeline,
|
||||
appendSystemPrompt: config.appendSystemPrompt,
|
||||
onWorkspaceStateMayHaveChanged: ({ cwd }) => {
|
||||
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
|
||||
@@ -2028,6 +2038,8 @@ export async function createPaseoDaemon(
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
||||
}
|
||||
await timeline.close();
|
||||
database.close();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -2103,6 +2115,8 @@ export async function createPaseoDaemon(
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
await timeline.close();
|
||||
database.close();
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
|
||||
@@ -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 { createPaseoApi } from "@getpaseo/client";
|
||||
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 { DatabaseSync } from "node:sqlite";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
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 () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
|
||||
@@ -380,6 +380,7 @@ function clientUsesLegacyWorkspaceRestore(appVersion: string | null): boolean {
|
||||
|
||||
type DeleteFencedAgentStorage = AgentStorage & {
|
||||
beginDelete(agentId: string): void;
|
||||
abandonDelete(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;
|
||||
|
||||
export function resolveWaitForFinishError(options: {
|
||||
@@ -3877,14 +3884,17 @@ export class Session {
|
||||
// durable snapshot, otherwise an in-flight background write can recreate it.
|
||||
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 {
|
||||
await this.agentStorage.remove(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) {
|
||||
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({
|
||||
type: "agent_deleted",
|
||||
@@ -8881,13 +8891,9 @@ export class Session {
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.loadAgentHistoryPayload(msg.agentId);
|
||||
const rows = await this.agentManager.getTimelineRows(msg.agentId);
|
||||
const timeline = await this.agentManager.fetchTimeline(msg.agentId, {
|
||||
direction: "tail",
|
||||
limit: 1,
|
||||
});
|
||||
const { head, rows } = await this.agentManager.getTimelinePrompts(msg.agentId);
|
||||
const index = buildTimelinePromptIndex(
|
||||
this.wireEpoch(timeline.epoch, timeline.retirementCount, source),
|
||||
this.wireEpoch(head.epoch, head.retirementCount, source),
|
||||
rows,
|
||||
);
|
||||
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`);
|
||||
}
|
||||
Reference in New Issue
Block a user