@zvada/agent-server 0.3.17 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +30 -2
- package/docs/consuming.md +9 -2
- package/docs/harnesses.md +11 -3
- package/docs/sync-experiment.md +190 -0
- package/docs/sync-history.md +181 -0
- package/docs/sync-integration.md +133 -0
- package/package.json +14 -2
- package/src/client/client.ts +138 -33
- package/src/client/history.ts +88 -0
- package/src/client/index.ts +1 -1
- package/src/client/request.ts +19 -0
- package/src/core/index.ts +2 -0
- package/src/core/provision/pins.ts +2 -1
- package/src/core/runtime/agent-runtime.ts +53 -23
- package/src/core/runtime/event-processor.ts +10 -5
- package/src/core/runtime/event-sink.ts +45 -2
- package/src/core/runtime/model-lists.ts +24 -9
- package/src/protocol/history.ts +267 -0
- package/src/protocol/ids.ts +4 -5
- package/src/protocol/index.ts +1 -0
- package/src/protocol/wire.ts +82 -1
- package/src/server/agent-server.ts +167 -94
- package/src/server/bin.ts +22 -1
- package/src/server/history.ts +166 -0
- package/src/server/index.ts +1 -0
- package/src/server/session-store.ts +225 -0
- package/src/server/wire-error.ts +52 -0
- package/src/sync/event-log.ts +132 -0
- package/src/sync/fit.ts +124 -0
- package/src/sync/history-reader.ts +52 -0
- package/src/sync/history-sqlite.ts +344 -0
- package/src/sync/history.ts +226 -0
- package/src/sync/index.ts +6 -0
- package/src/sync/journal-sqlite.ts +353 -0
- package/src/sync/journal.ts +73 -0
- package/src/sync/node-sqlite.ts +20 -0
- package/src/sync/recovery.ts +112 -0
- package/src/sync/retry.ts +49 -0
- package/src/sync/schema.ts +56 -0
- package/src/sync/sql.ts +106 -0
- package/src/sync/sqlite-file.ts +38 -0
- package/src/sync/sqlite.ts +21 -0
- package/src/sync/worker.ts +259 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,61 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.18
|
|
4
|
+
|
|
5
|
+
- A turn on a full model id that the model list names only through an alias,
|
|
6
|
+
such as `claude-opus-5-5` (listed as `opus`), gets that row's thinking
|
|
7
|
+
levels: its level is fitted and `turn.ended.execution.appliedThinkingLevel`
|
|
8
|
+
reports it. Such a turn reported no applied level, although its level ran.
|
|
9
|
+
- A message's or compaction's id now carries exactly its event's `timestamp`:
|
|
10
|
+
`message.started` and `session.compaction` take one clock reading for both,
|
|
11
|
+
so a consumer that dates a row by its UUIDv7 id agrees with one that reads
|
|
12
|
+
the event. They could differ by a millisecond. `generateUUIDv7()` in
|
|
13
|
+
`/protocol` takes an optional `timestamp` for this.
|
|
14
|
+
- Durable sessions: `new AgentServer(runtime, { journal })` with a SQLite journal
|
|
15
|
+
(`/sync/sqlite` for Bun, `/sync/node-sqlite` for Node 22.16+) commits each
|
|
16
|
+
turn's admission before its ack and each event before it is broadcast, so
|
|
17
|
+
sessions, replay and turn receipts survive a restart. A turn a restart cut
|
|
18
|
+
off is recorded interrupted and its session refuses turns until
|
|
19
|
+
`session/confirmStopped`; `turn/get` and `session/get` read receipts and
|
|
20
|
+
state. See `docs/sync-experiment.md`.
|
|
21
|
+
- Portable history: `history/*` on the wire, `client.history`, and
|
|
22
|
+
`transferHistory`, `openHistory`, `followHistory` and `startHistorySync` in
|
|
23
|
+
`/sync` copy hash-chained session history between stores and let viewers
|
|
24
|
+
read it without executing it. See `docs/sync-history.md`.
|
|
25
|
+
- Both are experimental: the `/sync` exports, the journal's wire methods and
|
|
26
|
+
the journal's file format may change in minor releases. A server without a
|
|
27
|
+
journal is unaffected.
|
|
28
|
+
- A client that redials (`connect`, `fromTransportFactory`) now treats a
|
|
29
|
+
request left unanswered for `requestTimeoutMs` (30s) as a dead connection:
|
|
30
|
+
it fails with `ConnectionClosedError`, drops the socket and redials, and
|
|
31
|
+
its turns heal by replay. A client that cannot redial (`attach`, `spawn`)
|
|
32
|
+
still fails only that request, with `internalError`.
|
|
33
|
+
- `client.watch(sessionId, afterSeq?)` follows a session this client did not
|
|
34
|
+
start, such as a turn another client left running: its logged events now,
|
|
35
|
+
later ones live, and after a redial the ones a dropped connection missed.
|
|
36
|
+
- A `turn/start` whose acknowledgement a dropped connection lost left the turn
|
|
37
|
+
running unseen: `runTurn` reported the connection error. It now re-sends the
|
|
38
|
+
start after redialing the same server (or the same journal), at most three
|
|
39
|
+
times, which joins the running turn; a restarted server without a journal is
|
|
40
|
+
not re-sent to.
|
|
41
|
+
- `AgentRuntime.shutdown()` missed a turn still being set up when it began:
|
|
42
|
+
the turn then ran unaborted until the drain timeout. Every run now stops when
|
|
43
|
+
shutdown starts.
|
|
44
|
+
- A sink whose writes are a durability boundary throws the new
|
|
45
|
+
`EventSinkError` to stop its turn: the harness is cancelled and a retry of the
|
|
46
|
+
turn converges on the failure. Other sink errors stay diagnostics, as before.
|
|
47
|
+
`serialSink` orders an async sink's writes, and `teeSink`, which skipped the
|
|
48
|
+
remaining sinks once one threw, now gives every sink every event.
|
|
49
|
+
- Turns whose ids differ only in where a colon falls (`"a:b"`/`"c"` and
|
|
50
|
+
`"a"`/`"b:c"`) were treated as the same turn: the second converged onto the
|
|
51
|
+
first instead of running.
|
|
52
|
+
- A second `AgentServer.shutdown()` call returned before the first finished
|
|
53
|
+
draining, so a host awaiting it could exit with turns still settling. Every
|
|
54
|
+
caller now waits for the same drain.
|
|
55
|
+
- A `turn/start` whose requester disconnected while its acknowledgement was
|
|
56
|
+
written left the session busy forever: the turn was admitted but never ran.
|
|
57
|
+
It now runs and releases the session.
|
|
58
|
+
|
|
3
59
|
## 0.3.17
|
|
4
60
|
|
|
5
61
|
- Codex token usage counts each turn. Both Codex harnesses reported Codex's
|
package/README.md
CHANGED
|
@@ -5,14 +5,17 @@ OpenAI Codex (SDK + app-server), and any [ACP](https://agentclientprotocol.com)
|
|
|
5
5
|
agent behind one interface with a single normalized event stream, multi-turn
|
|
6
6
|
sessions, resume, engine-brokered permissions, and pinned CLI provisioning.
|
|
7
7
|
|
|
8
|
-
One package, four seats — pick the subpath for how you consume it:
|
|
8
|
+
One package, four main seats — pick the subpath for how you consume it:
|
|
9
9
|
|
|
10
10
|
| Import | Seat |
|
|
11
11
|
| --- | --- |
|
|
12
12
|
| `@zvada/agent-server` (or `/protocol`) | **The wire contract** — zod schemas for `Part`, `LifecycleEvent`, `RunRequest`, wire method envelopes, harness/model/thinking vocabulary, token usage, UUIDv7 ids. Zod-only, safe in any runtime (workers, browsers, node, bun). |
|
|
13
13
|
| `@zvada/agent-server/core` | **The engine** — `AgentRuntime`, harness agents + adapters, registry, CLI provisioning. Embed it in-process behind an `EventSink`. |
|
|
14
14
|
| `@zvada/agent-server/server` | **The standard wire** — serve the engine over JSON-RPC 2.0 NDJSON (stdio / WebSocket listen / dial-out) with quick-ack turns, per-session `seq`, bounded replay, and an ACP v1 binding (`--acp`). Ships the `agent-server` bin. |
|
|
15
|
-
| `@zvada/agent-server/client` | **The typed consumer client** — spawn/connect/attach, `runTurn` as an async iterable, permission responses, reconnect with sequenced replay healing. Depends only on the contract + node builtins. |
|
|
15
|
+
| `@zvada/agent-server/client` | **The typed consumer client** — spawn/connect/attach, `runTurn` as an async iterable, permission responses, reconnect with sequenced replay healing (a turn start whose ack a dropped connection lost is re-sent and joins the running turn), `watch` to follow a session another client started. Depends only on the contract + node builtins. |
|
|
16
|
+
| `@zvada/agent-server/sync` | **Experimental.** Optional durable journal port and history helpers: transfer, open, follow, managed sync. |
|
|
17
|
+
| `@zvada/agent-server/sync/sqlite` | **Experimental.** Bun SQLite journal with its history and checkpoint store. |
|
|
18
|
+
| `@zvada/agent-server/sync/node-sqlite` | **Experimental.** Same storage under Node >=22.16 using built-in SQLite (itself experimental in Node 22). |
|
|
16
19
|
| `@zvada/agent-server/core/proxy` | Optional BYOK Anthropic proxy building block. |
|
|
17
20
|
|
|
18
21
|
## Embed the engine
|
|
@@ -56,6 +59,20 @@ for await (const event of turn.events) console.log(event.type);
|
|
|
56
59
|
await client.closeSession(turn.sessionId);
|
|
57
60
|
```
|
|
58
61
|
|
|
62
|
+
## Durable sessions (experimental)
|
|
63
|
+
|
|
64
|
+
`bunx @zvada/agent-server --listen 127.0.0.1:4747 --journal ./data/sessions.sqlite` enables
|
|
65
|
+
persistent admission, commit-before-broadcast history, and replay across process
|
|
66
|
+
restarts. Each session's history is served over the `history/*` methods, which
|
|
67
|
+
`/sync` helpers copy, follow and fork into host-owned stores; nothing contacts a
|
|
68
|
+
cloud service automatically. See [the design and recovery contract](docs/sync-experiment.md)
|
|
69
|
+
and [the history SDK](docs/sync-history.md).
|
|
70
|
+
|
|
71
|
+
This surface is experimental: the `/sync` exports, the journal's wire methods
|
|
72
|
+
(`history/*`, `turn/get`, `session/get`, `session/confirmStopped`) and the
|
|
73
|
+
journal's file format may change in minor releases. Read the changelog before
|
|
74
|
+
upgrading a host that keeps journals. Without a journal, nothing here applies.
|
|
75
|
+
|
|
59
76
|
## Agent feedback
|
|
60
77
|
|
|
61
78
|
If you are an AI agent working with this package and something is broken,
|
|
@@ -111,3 +128,14 @@ for await (const event of turn.events) conversation = reduceConversation(convers
|
|
|
111
128
|
(now deprecated); the subpaths above are their one-to-one replacements.
|
|
112
129
|
|
|
113
130
|
MIT
|
|
131
|
+
|
|
132
|
+
### Live sync verification and consumer integration
|
|
133
|
+
|
|
134
|
+
See [sync integration](docs/sync-integration.md) for the AGNT embedded-runtime and
|
|
135
|
+
Deus WebSocket seams, read-only viewers and remaining platform contracts.
|
|
136
|
+
In this workspace, `bun run control-agent-server doctor` checks the installed CLI;
|
|
137
|
+
`bun run control-agent-server replay session-sync --live-model` runs the real CLI
|
|
138
|
+
and Claude model, copies history into a separate local process and database,
|
|
139
|
+
exercises lost acknowledgements and restarts, and retains proof for two independent
|
|
140
|
+
viewers. This opt-in recipe uses the existing provider login and a synthetic
|
|
141
|
+
conversation, with tools disabled.
|
package/docs/consuming.md
CHANGED
|
@@ -314,9 +314,16 @@ released. It contains conversation history and MCP credentials. Never share
|
|
|
314
314
|
it between sessions or use the operator's normal Codex home. AGNT supplies
|
|
315
315
|
and owns these directories for its callers.
|
|
316
316
|
|
|
317
|
+
This isolates writable MCP configuration and conversation state; it does not
|
|
318
|
+
require a separate ChatGPT login for each home. An embedding host can supply
|
|
319
|
+
access credentials through [`codexAppServer.resolveAuth`](harnesses.md#host-managed-codex-authentication)
|
|
320
|
+
while retaining login and token renewal in its own account manager.
|
|
321
|
+
|
|
317
322
|
The repository's interactive CLI accepts `--codex-home=/absolute/private/path`
|
|
318
|
-
and remembers the path for `--continue`; the operator supplies
|
|
319
|
-
|
|
323
|
+
and remembers the path for `--continue`; the operator supplies the existing home.
|
|
324
|
+
Standalone CLI use relies on native authentication in that home. `--connect`
|
|
325
|
+
can use an embedded server's external authentication instead.
|
|
326
|
+
The ACP **server binding** (`createAcpAgentApp` /
|
|
320
327
|
`agent-server --acp --harness codex-app-server`) has no per-session environment
|
|
321
328
|
resource seam in this release. It rejects supplied Codex MCP servers explicitly
|
|
322
329
|
at `session/new` or `session/resume`. Use the engine or standard JSON-RPC API
|
package/docs/harnesses.md
CHANGED
|
@@ -72,9 +72,10 @@ model's levels when it knows them: a level above the model's top becomes that
|
|
|
72
72
|
top (`ultra` on a model whose top is `max` runs `max`), and on Codex `off`
|
|
73
73
|
becomes the model's lowest (current models reject `minimal`). The levels come
|
|
74
74
|
from the list `models()` read for the turn's login and folder; for a concrete
|
|
75
|
-
model id, any login's list or the catalog also serves,
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
model id, any login's list or the catalog also serves, even one that names the
|
|
76
|
+
model only as what an alias runs (an API key's Claude list names Opus 5.5 only
|
|
77
|
+
through `opus`). An alias such as Claude's `opus` runs a model that depends on
|
|
78
|
+
the account, so only its own login's list fits it. `turn.ended.execution.appliedThinkingLevel` says which
|
|
78
79
|
level ran. It is absent when that is unknown, or when the turn failed or was
|
|
79
80
|
cancelled before the model answered:
|
|
80
81
|
|
|
@@ -139,6 +140,13 @@ The ChatGPT variant's `tokens` contain `accessToken`, `chatgptAccountId`, and
|
|
|
139
140
|
optional `chatgptPlanType`; `refresh(previousAccountId)` supplies renewed tokens.
|
|
140
141
|
These types are exported from `/core`.
|
|
141
142
|
|
|
143
|
+
Authentication and session storage are independent. Per-turn MCP still needs an
|
|
144
|
+
isolated `CODEX_HOME` for writable configuration and conversation history, but
|
|
145
|
+
`chatgptAuthTokens` lets the host authenticate that session without a separate
|
|
146
|
+
native login or copying `auth.json` into each home. Keep one account manager
|
|
147
|
+
responsible for token storage and renewal, and resolve its selected credentials
|
|
148
|
+
for each session. The engine does not implement an OAuth login UI or token store.
|
|
149
|
+
|
|
142
150
|
The resolver runs before every turn. The engine explicitly authenticates before
|
|
143
151
|
thread creation/resume and reauthenticates warm processes, so changing the
|
|
144
152
|
selected account takes effect on the next turn. Throw from the resolver when
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Durable sessions and shared history (experiment)
|
|
2
|
+
|
|
3
|
+
An optional journal makes agent-server sessions survive process restarts: every
|
|
4
|
+
admitted turn and every event is committed before it is acknowledged or
|
|
5
|
+
delivered. The same journal serves each session's history over one portable
|
|
6
|
+
history protocol (`history/*`), so other hosts can copy, follow, cache and fork
|
|
7
|
+
it without running an agent. AGNT and Deus Machine are not connected or
|
|
8
|
+
modified; [the integration guide](sync-integration.md) maps their seams and
|
|
9
|
+
[shared history](sync-history.md) documents the history SDK.
|
|
10
|
+
|
|
11
|
+
Agent-server owns admission receipts, event ordering, local persistence, replay
|
|
12
|
+
and the history contract: shared execution infrastructure. The product owns
|
|
13
|
+
identity, authorization, machine registration, cloud storage, routing,
|
|
14
|
+
retention, native process ownership and its views.
|
|
15
|
+
|
|
16
|
+
```mermaid
|
|
17
|
+
flowchart LR
|
|
18
|
+
H[Harness adapter] --> C[Canonical LifecycleEvent]
|
|
19
|
+
C --> J[Journal commit]
|
|
20
|
+
J --> W[Live wire and events/replay]
|
|
21
|
+
J --> S[history/* : pull, follow, fork]
|
|
22
|
+
S --> R[Relay or cache: import, verify hash chain]
|
|
23
|
+
R --> V[Viewers: canonical reducer]
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
It is an append-only, hash-chained log per session, not Git or a CRDT: one
|
|
27
|
+
executing owner writes a session, `(sourceId, sessionId, seq)` names an event,
|
|
28
|
+
and copies never become executable.
|
|
29
|
+
|
|
30
|
+
## Run it
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
bunx @zvada/agent-server --listen 127.0.0.1:4747 --journal ./data/sessions.sqlite
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`--journal` works with `--stdio`, `--listen` and `--dial`, not with the ACP
|
|
37
|
+
server binding (`--acp`). Without it, behavior is the original volatile wire.
|
|
38
|
+
When embedding:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { createAgentRuntime } from "@zvada/agent-server/core";
|
|
42
|
+
import { AgentServer, listen } from "@zvada/agent-server/server";
|
|
43
|
+
import { SqliteSessionJournal } from "@zvada/agent-server/sync/sqlite"; // Node: NodeSqliteSessionJournal from /sync/node-sqlite
|
|
44
|
+
|
|
45
|
+
const journal = new SqliteSessionJournal("./data/sessions.sqlite");
|
|
46
|
+
const server = new AgentServer(createAgentRuntime(), {
|
|
47
|
+
journal,
|
|
48
|
+
history: { store: journal.history, authorize: (transport, ref, op) => acl.allows(transport, ref, op) },
|
|
49
|
+
onJournalError: (error) => console.error("journal failed; restart recovers", error),
|
|
50
|
+
onShutdown: () => journal.close(),
|
|
51
|
+
});
|
|
52
|
+
listen(server, { hostname: "127.0.0.1", port: 4747 });
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The server takes execution ownership of the journal (one owner per journal; a
|
|
56
|
+
second `AgentServer` on it throws) and releases it on shutdown. The host opens
|
|
57
|
+
the journal and closes it after shutdown. SQLite runs in WAL with
|
|
58
|
+
`synchronous=FULL` and an exclusive lock, so a second process cannot open the
|
|
59
|
+
file; serve other readers over the wire.
|
|
60
|
+
|
|
61
|
+
## What changes on the wire
|
|
62
|
+
|
|
63
|
+
| Surface | Durable server |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `initialize.historyId` | The journal's identity: the `sourceId` of every session history it serves. It outlives the process, and so do seq cursors: a client keeps them across a restart. |
|
|
66
|
+
| `turn/start` | Admission is committed (with the input) before the ack. A retry converges on the receipt: `deduplicated: true`, plus `terminal` once the turn ended. A redialing client re-sends a start whose ack it lost, unless the server's logs are new (a volatile restart). |
|
|
67
|
+
| `events/replay` | Served from the journal, a page at a time; `hasMore` asks for the next. Closed sessions answer `unknownSession`, as on volatile servers. |
|
|
68
|
+
| `turn/get` | A turn's receipt: `admitted`, `completed` or `interrupted`, its input and terminal event. |
|
|
69
|
+
| `session/get` | `headSeq`, `nativeSessionId`, `closed`, `recoveryRequired`. |
|
|
70
|
+
| `session/confirmStopped` | Lifts the fence a restart put on a session, fenced by `expectedHeadSeq`. |
|
|
71
|
+
| `history/*` | Opt-in (`history` option): the [history protocol](sync-history.md). |
|
|
72
|
+
|
|
73
|
+
The three journal-only methods answer `methodNotFound` on volatile servers.
|
|
74
|
+
Refusals have their own codes; anything else is an `internalError`:
|
|
75
|
+
|
|
76
|
+
| Code | Meaning | `data` |
|
|
77
|
+
| --- | --- | --- |
|
|
78
|
+
| `turnConflict` (-32006) | The turn id was admitted with other input. | `turnId` |
|
|
79
|
+
| `sessionClosed` (-32007) | A closed durable session id is never reused. | |
|
|
80
|
+
| `recoveryRequired` (-32008) | A restart cut off the session's last turn. | `headSeq` |
|
|
81
|
+
| `resumeRequired` (-32009) | This process has not run the session: pass its native id as `config.resumeSessionId`. | `nativeSessionId` |
|
|
82
|
+
| `notAuthorized` (-32010) | The host refused a history operation. | |
|
|
83
|
+
| `unknownHistory` (-32011) | No such history, or not at that version. | |
|
|
84
|
+
| `historyConflict` (-32012) | Contradicts committed history: payload, hash, stale expected head or reused commit id. | |
|
|
85
|
+
|
|
86
|
+
A request the journal cannot store (an id over 512 characters, input over the
|
|
87
|
+
record limit, `includeRaw`) is `invalidParams`, never a server fault.
|
|
88
|
+
|
|
89
|
+
## Guarantees
|
|
90
|
+
|
|
91
|
+
1. **Admission before ack.** The session binding, turn id, a SHA-256
|
|
92
|
+
fingerprint of input and config (no credentials stored) and the input itself
|
|
93
|
+
commit before `turn/start` answers. Admission checks, in order: duplicate,
|
|
94
|
+
closed, unconfirmed interruption, resume, harness change, raw output, active
|
|
95
|
+
turn.
|
|
96
|
+
2. **Event before delivery.** Each event commits (and advances its hash chain)
|
|
97
|
+
before broadcast. `turn.ended` settles the receipt and `session.ended` closes
|
|
98
|
+
the session in the same transaction. An event the journal cannot store is
|
|
99
|
+
stored cut down to fit, marked `[agent-server: N bytes omitted to fit the
|
|
100
|
+
journal]`, or as a notice in its place; the turn and other sessions go on.
|
|
101
|
+
3. **A decision follows its record.** The harness receives a permission
|
|
102
|
+
decision only after `permission.resolved` is written; a failed write refuses
|
|
103
|
+
the tool. Async sinks that must record a request before a reentrant response
|
|
104
|
+
wrap themselves in `serialSink`.
|
|
105
|
+
4. **A failed write stops.** A sink signals that its writes are a durability
|
|
106
|
+
boundary by throwing `EventSinkError`: the runtime stops that turn, cancels
|
|
107
|
+
its harness, and a retry of the same turn converges on the failure instead
|
|
108
|
+
of running again. The journal store then stays failed, and the server stops
|
|
109
|
+
as if shut down (`onJournalError`, then `onShutdown`) without delivering
|
|
110
|
+
anything it did not commit. Restart recovery decides what the cut-off turns
|
|
111
|
+
did.
|
|
112
|
+
5. **Restart recovery.** Taking ownership ends every turn a previous owner left
|
|
113
|
+
admitted: pending permissions resolve as cancelled, running tools fail with
|
|
114
|
+
an outcome-unknown error, streaming text is done and open messages end, so
|
|
115
|
+
the history still passes `verifyStreamContract`. The receipt keeps its input
|
|
116
|
+
and becomes `interrupted`; the session is fenced (`recoveryRequired`). Nothing
|
|
117
|
+
is rerun. A host confirms the native process stopped (`session/confirmStopped`)
|
|
118
|
+
and resumes the native session explicitly.
|
|
119
|
+
|
|
120
|
+
No exactly-once external tool execution is claimed: a tool may act before its
|
|
121
|
+
next event is recorded.
|
|
122
|
+
|
|
123
|
+
## Storage
|
|
124
|
+
|
|
125
|
+
One schema (`user_version` 2) in `src/sync/schema.ts`. Every history this file
|
|
126
|
+
holds, executed here or copied in, is a `histories` row (descriptor and head)
|
|
127
|
+
and `events` rows `(source_id, session_id, seq, hash, body)`: the canonical
|
|
128
|
+
event JSON with its hash inline. `sessions` and `turns` hold execution state;
|
|
129
|
+
`commits` and `checkpoints` serve branches and cached projections.
|
|
130
|
+
`EventLog.append` is the one write path for execution, commits, imports and
|
|
131
|
+
recovery. Nothing has shipped, so there are no migrations; a journal from the
|
|
132
|
+
earlier experiment layout is refused.
|
|
133
|
+
|
|
134
|
+
Measured on Bun 1.3.6 against the previous layout (separate replica and hash
|
|
135
|
+
tables):
|
|
136
|
+
|
|
137
|
+
| | Before | Now |
|
|
138
|
+
| --- | --- | --- |
|
|
139
|
+
| Statements to append one event | 7 | 4 |
|
|
140
|
+
| Statements to read a 256-record history page | 264 | 5 |
|
|
141
|
+
| Open with 2,000 sessions | 8,010 statements, 25 ms | 15 statements, 3.8 ms |
|
|
142
|
+
| WAL per 330-byte event (FULL sync, one commit each) | 23.9 KB | 14.9 KB |
|
|
143
|
+
|
|
144
|
+
Every stored hash is unchanged: the preimage is built from the stored body
|
|
145
|
+
(`historyRecordPreimage`), checked against all records of a live run.
|
|
146
|
+
|
|
147
|
+
## Learned from Delta
|
|
148
|
+
|
|
149
|
+
Delta.app's local client (0.1.0, inspected statically) persists pending facts,
|
|
150
|
+
validates acceptance against prepared state, reconnects when a request times
|
|
151
|
+
out, and checks history at the point of use. This experiment follows those
|
|
152
|
+
principles on agent-server's own canonical model: commit before acknowledging,
|
|
153
|
+
a receiver's committed prefix decides what is resent, an unanswered request
|
|
154
|
+
replaces its connection, and imports verify the hash chain. Where measurement
|
|
155
|
+
disagreed it diverges: Delta clusters tables `WITHOUT ROWID`, but for events of
|
|
156
|
+
agent-server's size an ordinary table appended faster (77 vs 109 µs per 330-byte
|
|
157
|
+
event) with the same WAL. Delta keeps a durable outbox because its history is a
|
|
158
|
+
DAG; a linear log's destination head already is the outbox, so no receipts are
|
|
159
|
+
stored locally.
|
|
160
|
+
|
|
161
|
+
## Outside this experiment
|
|
162
|
+
|
|
163
|
+
- No AGNT/Deus integration, public relay, deployment or credential exchange.
|
|
164
|
+
- Retention, compaction, blob offload and erasure are not implemented.
|
|
165
|
+
- One writer per session. Copying an active journal into two writable stores is
|
|
166
|
+
unsupported; fork instead.
|
|
167
|
+
- Physical power loss, disk exhaustion and real network partitions were not
|
|
168
|
+
tested; faults are injected. `synchronous=FULL` on macOS does not issue
|
|
169
|
+
`F_FULLFSYNC`. The database is not encrypted, and inputs and tool output can
|
|
170
|
+
be sensitive.
|
|
171
|
+
|
|
172
|
+
## Verification
|
|
173
|
+
|
|
174
|
+
From a checkout of this repository:
|
|
175
|
+
|
|
176
|
+
```sh
|
|
177
|
+
bun run test packages/agent-server/test/sync # real Bun and Node SQLite, sockets, SIGKILL
|
|
178
|
+
bun run control-agent-server replay session-sync --live-model
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The deterministic suite covers admission and refusals, recovery and fencing,
|
|
182
|
+
sink failure, lost acknowledgements, tamper rollback, paged replay, the hash
|
|
183
|
+
format and owner exclusion. On 2026-10-21 the live recipe passed 113 assertions
|
|
184
|
+
with three real Claude Code 2.1.288 / Haiku turns (473 events): restart and
|
|
185
|
+
native resume, a lost import ACK, two viewers, a friend following live (223 of
|
|
186
|
+
224 pages before the source finished), forks, the managed worker, checkpoints
|
|
187
|
+
and a separate Node v22.23.3 viewer. A crash drill (SIGKILL while a tool runs,
|
|
188
|
+
Claude and Codex) passed 14 of 14 checks per harness; a killed Claude CLI keeps
|
|
189
|
+
running its tool, which is why recovery never reruns and asks the host to
|
|
190
|
+
confirm.
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# Shared history: open, follow, pull and fork
|
|
2
|
+
|
|
3
|
+
A friend opens a session from an authorized relay, reads its committed history,
|
|
4
|
+
then follows new output while the owner works. The owner commits locally first;
|
|
5
|
+
a worker copies the missing suffix to the relay, and viewers read the relay's
|
|
6
|
+
durable copy. After a disconnection, the same version cursor requests only what
|
|
7
|
+
is missing. The owner can go offline; uploaded history stays readable.
|
|
8
|
+
|
|
9
|
+
```mermaid
|
|
10
|
+
sequenceDiagram
|
|
11
|
+
participant A as Computer A / execution owner
|
|
12
|
+
participant R as Authorized relay / durable store
|
|
13
|
+
participant B as Friend / Computer B
|
|
14
|
+
A->>A: Commit canonical events
|
|
15
|
+
A->>R: Import missing history pages
|
|
16
|
+
R->>R: Verify prefix and hash chain, commit
|
|
17
|
+
R-->>A: Committed version
|
|
18
|
+
B->>R: Open / pull history
|
|
19
|
+
R-->>B: Bounded snapshot pages
|
|
20
|
+
B->>R: Wait after saved version
|
|
21
|
+
A->>R: Import new output
|
|
22
|
+
R-->>B: Head advanced
|
|
23
|
+
B->>R: Pull after saved version
|
|
24
|
+
R-->>B: Missing suffix
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## The protocol
|
|
28
|
+
|
|
29
|
+
Every history is `{sourceId, sessionId}`: the store that writes it and its
|
|
30
|
+
session. A version is `{sourceId, sessionId, seq, hash}`. Version 0 hashes the
|
|
31
|
+
canonical descriptor; each record hashes `{event, previous, seq}`. Both are
|
|
32
|
+
SHA-256 (hex) of `canonicalHistoryJson` (sorted keys, undefined fields dropped),
|
|
33
|
+
and `historyRootPreimage` / `historyRecordPreimage` in `/protocol` define the
|
|
34
|
+
exact bytes for other implementations. The hash detects a divergent prefix or
|
|
35
|
+
an altered page; it is not a signature. The host binds authenticated producers
|
|
36
|
+
to source identities.
|
|
37
|
+
|
|
38
|
+
| Method | Port / SDK | Behavior |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `history/list` | `list({after, limit})` | Keyset pages of at most 100 heads; catalog permission required. |
|
|
41
|
+
| `history/head` | `head(ref)` | Descriptor and current version. |
|
|
42
|
+
| `history/pull` | `read({...ref, after, through, limit, maxBytes})` | At most 256 records and 8 MiB; `through` pins a snapshot. |
|
|
43
|
+
| `history/import` | `import(slice)` | Verify identity, prefix, descriptor and hash chain; commit atomically before answering. Records already held must be identical. |
|
|
44
|
+
| `history/fork` | `fork({sessionId, from})` | A new locally owned branch pinned to an immutable parent version; omit `from` for a root. |
|
|
45
|
+
| `history/commit` | `commit({commitId, expected, events})` | Append to a local branch if `expected` is its head. A retried commit id returns its first version; reused for other content, it conflicts. |
|
|
46
|
+
| `history/wait` | `wait({after, timeoutMs}, signal)` | Wakeup only: answers when the head moves or after at most 20 s; pull after it. Eight per connection. |
|
|
47
|
+
| `history/checkpoint` | `checkpoint({through})` | A saved projection at or before the cut, or null. Never built on read. |
|
|
48
|
+
|
|
49
|
+
`HistoryReader` ⊂ `HistoryArchive` ⊂ `HistoryApi` ⊂ `HistoryStore` are the
|
|
50
|
+
portable ports in `/protocol`; `client.history` is the promise-returning
|
|
51
|
+
`AsyncHistoryApi` over the wire, and `journal.history` is the SQLite store.
|
|
52
|
+
Every refusal is a `HistoryError` with a `reason`, and a remote store fails the
|
|
53
|
+
way a local one does:
|
|
54
|
+
|
|
55
|
+
| `reason` | Wire code | Retry? |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| `missing` | `unknownHistory` | No; `transferHistory` treats a missing destination as empty. |
|
|
58
|
+
| `conflict` | `historyConflict` | No: committed history disagrees. |
|
|
59
|
+
| `unauthorized` | `notAuthorized` | No. |
|
|
60
|
+
| `invalid` | `invalidParams` | No. |
|
|
61
|
+
|
|
62
|
+
Retry transport failures only: `ConnectionClosedError`. A reconnecting client
|
|
63
|
+
(connect mode) also fails a request left unanswered past `requestTimeoutMs`
|
|
64
|
+
that way and redials, since a half-open socket would otherwise hang it.
|
|
65
|
+
|
|
66
|
+
## Helpers in `/sync`
|
|
67
|
+
|
|
68
|
+
| Helper | Behavior |
|
|
69
|
+
| --- | --- |
|
|
70
|
+
| `transferHistory(source, destination, ref, options)` | Copies pinned ancestors, then the leaf's missing suffix. The destination's committed head decides what is sent, so a lost acknowledgement costs nothing. `maxPages` / `maxBytes` bound one pass; only `complete: true` certifies the target. A destination already beyond the source is complete. |
|
|
71
|
+
| `openHistory(reader, ref)` | Ancestor and leaf segments, each reduced at its fixed version, from a compatible checkpoint plus its tail when one exists. |
|
|
72
|
+
| `followHistory(api, ref, {after, retry, signal})` | Snapshot pages, then each committed suffix, as an async iterable; resumes from the last yielded version. |
|
|
73
|
+
| `startHistorySync(source, destination, ref, options)` | The managed worker below. |
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { AgentServerClient, ConnectionClosedError } from "@zvada/agent-server/client";
|
|
77
|
+
import { decodeLifecycleEvent, reduceConversation } from "@zvada/agent-server/protocol";
|
|
78
|
+
import { followHistory, openHistory, transferHistory } from "@zvada/agent-server/sync";
|
|
79
|
+
|
|
80
|
+
const viewer = await AgentServerClient.connect(authenticatedViewerUrl);
|
|
81
|
+
const ref = { sourceId, sessionId }; // From the product's authorized share list.
|
|
82
|
+
const opened = await openHistory(viewer.history, ref);
|
|
83
|
+
let conversation = opened.segments.at(-1)!.conversation;
|
|
84
|
+
for await (const page of followHistory(viewer.history, ref, {
|
|
85
|
+
after: opened.version,
|
|
86
|
+
signal: viewClosed,
|
|
87
|
+
retry: (error, failures) =>
|
|
88
|
+
error instanceof ConnectionClosedError && failures <= 20 ? Math.min(250 * 2 ** failures, 5000) : undefined,
|
|
89
|
+
onState: (state) => showConnectionState(state),
|
|
90
|
+
})) {
|
|
91
|
+
for (const { event } of page.records)
|
|
92
|
+
conversation = reduceConversation(conversation, decodeLifecycleEvent(event));
|
|
93
|
+
render(conversation); // Persist it with page.next if the view survives restarts.
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Computer B keeps a local copy, ancestors included, and branches from it.
|
|
97
|
+
await transferHistory(relay.history, localStore.history, ref, { pageSize: 128 });
|
|
98
|
+
const branch = localStore.history.fork({ sessionId: crypto.randomUUID(), from: localStore.history.head(ref).version });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Managed worker
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const job = startHistorySync(journal.history, cloudWriter.history, ref, {
|
|
105
|
+
batchMs: 25,
|
|
106
|
+
retry: (error, failures) =>
|
|
107
|
+
error instanceof ConnectionClosedError && failures <= 20 ? Math.min(250 * 2 ** failures, 5000) : undefined,
|
|
108
|
+
});
|
|
109
|
+
const unsubscribe = job.subscribe((status) => updateSyncIndicator(status));
|
|
110
|
+
// Before an action that promises uploaded history:
|
|
111
|
+
const shared = await job.flush({ timeoutMs: 30_000, signal: actionSignal });
|
|
112
|
+
// On shutdown: stop execution, optionally flush, then join the worker.
|
|
113
|
+
unsubscribe();
|
|
114
|
+
await job.stop();
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Start one worker per selected history and destination, and recreate them from
|
|
118
|
+
the product's share configuration on launch; nothing is uploaded implicitly.
|
|
119
|
+
Swap source and destination to pull into a local cache.
|
|
120
|
+
|
|
121
|
+
- **Idle costs one wait.** The worker waits on the source after what the
|
|
122
|
+
destination holds; a pass runs only once the source moves. An idle worker
|
|
123
|
+
makes no destination calls, no writes and no status changes.
|
|
124
|
+
- **The destination is the record.** Nothing is saved locally: a restarted
|
|
125
|
+
worker asks the destination what it holds, so a wiped or replaced destination
|
|
126
|
+
is refilled. A host that wants to show "last synced" across restarts stores
|
|
127
|
+
`status().acknowledged` itself.
|
|
128
|
+
- **Status** is `starting`, `syncing`, `synced`, `retrying`, `blocked` or
|
|
129
|
+
`stopped`, with the source head and acknowledged version as last observed,
|
|
130
|
+
pending records, and imported pages, records and bytes. It describes the last
|
|
131
|
+
observation, not a promise about the peer.
|
|
132
|
+
- **Retries** follow the host's policy. The failure count resets only on
|
|
133
|
+
progress (an imported page) or a wait that found nothing new, never on a read
|
|
134
|
+
that changed nothing. A refusal (`HistoryError`) blocks the worker; `done`
|
|
135
|
+
resolves on stop or block, and a blocked worker is recreated once its cause is
|
|
136
|
+
fixed.
|
|
137
|
+
- **Barriers** pin a version when called: `flush()` the source head,
|
|
138
|
+
`waitUntilSynced(version)` a given one. They verify the version's hash first,
|
|
139
|
+
so a forged one below the acknowledged head is refused; their deadline covers
|
|
140
|
+
that check, and they reject on block or stop.
|
|
141
|
+
|
|
142
|
+
## Checkpoints
|
|
143
|
+
|
|
144
|
+
`journal.history.createCheckpoint(ref, {through?, maxRecords?})` stores one
|
|
145
|
+
projection per history and reducer format from the previous one plus new
|
|
146
|
+
events, capped at 8 MiB; a failure leaves the previous one. Schedule it from the
|
|
147
|
+
host (every N events, or at turn boundaries); it runs synchronously, so bound
|
|
148
|
+
each increment. `openHistory` applies a checkpoint only at or before each
|
|
149
|
+
segment's pinned cut, after verifying that prefix, then folds the tail; a newer
|
|
150
|
+
checkpoint never substitutes for an older fork cut. Unknown formats and older
|
|
151
|
+
servers fall back to replaying events, and `{checkpoints: false}` forces it.
|
|
152
|
+
The format `agent-server.conversation.v1` changes whenever reducer semantics do.
|
|
153
|
+
No method accepts an uploaded projection: stores build them from their own
|
|
154
|
+
events, which stay authoritative.
|
|
155
|
+
|
|
156
|
+
## Forks are history, not sessions
|
|
157
|
+
|
|
158
|
+
Explicit commits apply to locally owned branches; executed sessions grow only
|
|
159
|
+
through execution. A branch stores its own suffix and a parent cut that parent
|
|
160
|
+
growth cannot move; ancestry segments keep their message and turn ids. A fork
|
|
161
|
+
id is reserved in its store's execution namespace: `turn/start` refuses it.
|
|
162
|
+
Continuing a fork with a model needs a provider context bridge (importing native
|
|
163
|
+
state, or a new session seeded from chosen history), plus the workspace; nothing
|
|
164
|
+
replays tools or invents native session files.
|
|
165
|
+
|
|
166
|
+
## Hosting
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
new AgentServer(runtime, {
|
|
170
|
+
journal, // Only on an execution owner.
|
|
171
|
+
history: { store: journal.history, authorize: (transport, ref, operation) => acl.canAccess(transport, ref, operation) },
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`authorize` runs for every history request (`read`, `write`, or `list` with no
|
|
176
|
+
ref) and again before a delayed `wait` answers; read never implies write. It
|
|
177
|
+
protects `history/*` only. A viewer endpoint must also refuse the execution
|
|
178
|
+
methods (`turn/start`, permission responses, shutdown) and the product's
|
|
179
|
+
tool/auth side channel: authenticate the whole transport and allow only history
|
|
180
|
+
methods. The CLI's `--journal` serves history on its trusted execution wire; it
|
|
181
|
+
is not a public endpoint.
|