@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
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Integrating durable sessions and shared history
|
|
2
|
+
|
|
3
|
+
The engine can own the durable conversation; the product still owns who may run
|
|
4
|
+
it, who may view it, and where its files and native agent state live. This
|
|
5
|
+
experiment provides the engine contract and a reproducible local proof. It does
|
|
6
|
+
not deploy or change AGNT or Deus Machine. See [the design](sync-experiment.md)
|
|
7
|
+
and [the history SDK](sync-history.md).
|
|
8
|
+
|
|
9
|
+
## The interfaces a product consumes
|
|
10
|
+
|
|
11
|
+
| Caller | Interface | Persistent truth |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| Executing host | `new AgentServer(existingRuntime, {journal, history})` | One journal owner: input and receipt before the ack, each event before broadcast. |
|
|
14
|
+
| Command client | `runTurn` / `startTurn`, `getTurn`, `getSession`, `confirmSessionStopped` | Stable command ids; a retry converges on its receipt (`deduplicated`, saved `terminal`), and `runTurn` re-sends a start whose ack a dropped connection lost; interrupted execution is fenced until confirmed. |
|
|
15
|
+
| Uploader | `startHistorySync(journal.history, cloud, ref)` | The cloud's committed head decides what remains; nothing is queued locally. |
|
|
16
|
+
| Cloud storage | a `HistoryArchive`: `head`, `read`, `import` (+ `wait`, `checkpoint` for viewers) | Verify the prefix and hash chain, then commit the page and head in one transaction. |
|
|
17
|
+
| Viewer | `client.history` + `openHistory` / `followHistory` | Read-only reconstruction with the canonical reducer, separate from executable sessions. |
|
|
18
|
+
|
|
19
|
+
`sourceId` identifies a journal, `sessionId` the logical session, and `seq` one
|
|
20
|
+
ordered fact; the native Claude/Codex session id is different, and none is a
|
|
21
|
+
credential. Records are agent-server's canonical events (messages, parts,
|
|
22
|
+
deltas, tools, permissions, terminal facts), copied as their original JSON,
|
|
23
|
+
future fields included. The native provider session file is never sent. Render
|
|
24
|
+
with the canonical reducer, after storage.
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { AgentServerClient } from "@zvada/agent-server/client";
|
|
28
|
+
import { openHistory, startHistorySync } from "@zvada/agent-server/sync";
|
|
29
|
+
|
|
30
|
+
// Executing host: upload one shared session to an authenticated cloud adapter.
|
|
31
|
+
const job = startHistorySync(journal.history, cloudArchive, { sourceId: journal.sourceId, sessionId });
|
|
32
|
+
await job.flush(); // before promising the share
|
|
33
|
+
// A viewer elsewhere:
|
|
34
|
+
const viewer = await AgentServerClient.connect(authenticatedViewerUrl);
|
|
35
|
+
const { segments } = await openHistory(viewer.history, { sourceId, sessionId });
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`history.authorize` runs for every history request, and read never implies
|
|
39
|
+
write. It protects `history/*` only: the execution wire is trusted. A public
|
|
40
|
+
endpoint authenticates the whole connection and allows only history methods,
|
|
41
|
+
or adapts the storage ports behind the platform's existing authenticated API.
|
|
42
|
+
The live proof's loopback `/writer` and `/viewer` paths simulate roles, not
|
|
43
|
+
authentication.
|
|
44
|
+
|
|
45
|
+
## AGNT: keep the embedded runtime and existing platform connection
|
|
46
|
+
|
|
47
|
+
Read-only reference: `agnt/new-chat` (resolved checkout `castries`), HEAD
|
|
48
|
+
`57b6c880e3bb029e60fbb97d048ce4b0d216138f` on inspection.
|
|
49
|
+
|
|
50
|
+
The sidecar calls `engine.runtime.run` in `apps/sidecar/src/agents/controller.ts`.
|
|
51
|
+
Runtime construction and auth/MCP hooks live in `apps/sidecar/src/agents/engine.ts`;
|
|
52
|
+
`ws/turn-outbox.ts` keeps the ACK stream in memory; `ws/connection-manager.ts`
|
|
53
|
+
owns the outgoing platform WebSocket. It does not use AgentServer's journaled
|
|
54
|
+
command path today.
|
|
55
|
+
|
|
56
|
+
A migration wraps the **existing customized runtime** in AgentServer and routes
|
|
57
|
+
sidecar commands through its client, over an in-process `channelTransport` pair
|
|
58
|
+
or the same process's wire. Runtime hooks, auth proxy, tool policies and MCP
|
|
59
|
+
objects stay at the embed tier. Every turn must go through the journaled host:
|
|
60
|
+
persisting from an `onEvent` observer misses admission and failure ordering.
|
|
61
|
+
|
|
62
|
+
AGNT keeps its sidecar-initiated WebSocket and routing. The platform implements
|
|
63
|
+
a `HistoryArchive` over its transactional store, maps account permissions to
|
|
64
|
+
source identities and fans out committed history. The SQLite store takes any
|
|
65
|
+
synchronous connection: file creation and PRAGMAs live in the Bun and Node
|
|
66
|
+
adapters, and a connection may run its own transactions (`SqlConnection.transaction`),
|
|
67
|
+
as a Durable Object's `transactionSync` would. That adapter, and a package
|
|
68
|
+
export for it without the Bun and Node imports, are not built or tested here.
|
|
69
|
+
Run one worker per shared session; recreate it on startup and reconnect. A
|
|
70
|
+
`HistoryError` blocks the worker instead of retrying forever.
|
|
71
|
+
|
|
72
|
+
AGNT has two completion barriers today: the model's `turn.ended`, then the
|
|
73
|
+
controller's Git autosave before product `agent:status`. That later status must
|
|
74
|
+
stay independently durable; do not make the canonical turn end mean Git
|
|
75
|
+
finished. Keep a product-operation receipt alongside the transcript.
|
|
76
|
+
|
|
77
|
+
The turn fingerprint covers input and config, including auth and env (only the
|
|
78
|
+
hash is stored), so a retry with refreshed credentials is refused as a conflict.
|
|
79
|
+
After an uncertain start, read `getTurn(sessionId, turnId)` before restaging
|
|
80
|
+
auth or minting a new turn id.
|
|
81
|
+
|
|
82
|
+
## Deus Machine: attach to the existing wire, keep one execution host
|
|
83
|
+
|
|
84
|
+
Read-only reference: `deus-machine/new-computer-product-explore` (resolved
|
|
85
|
+
checkout `amman`), HEAD `869cc5b45a65414daa88569a9266d37bb5325153` with
|
|
86
|
+
pre-existing local changes. Those files were not modified.
|
|
87
|
+
|
|
88
|
+
`apps/agent-server/index.ts` already constructs the upstream `AgentServer` as
|
|
89
|
+
`WireServer`, with its runtime from `agents/core/engine.ts`; `wire.ts`
|
|
90
|
+
multiplexes `deus/*` tools, auth and app registration, and
|
|
91
|
+
`apps/backend/src/services/agent/client.ts` wraps the standard SDK.
|
|
92
|
+
|
|
93
|
+
Pass a persistent journal at that construction site, close it after the server
|
|
94
|
+
shuts down, and add a worker using the existing cloud session mapping. The
|
|
95
|
+
packaged app runs Node: use `NodeSqliteSessionJournal` from `/sync/node-sqlite`
|
|
96
|
+
(Node 22.16 or later; same schema and guarantees as the Bun adapter), after
|
|
97
|
+
checking the packaged runtime version.
|
|
98
|
+
|
|
99
|
+
A viewer must not send `deus/hello` or register as the tool/auth host; only the
|
|
100
|
+
execution backend owns that role. Hydrate viewers through the projection-only
|
|
101
|
+
path in `event-handler.ts`: replaying history must not retrigger title
|
|
102
|
+
generation, Git checkpoints, automations or tools. Several people commanding one
|
|
103
|
+
running agent still need one execution owner and an authorized command router.
|
|
104
|
+
|
|
105
|
+
## What becomes simpler, and what stays the product's
|
|
106
|
+
|
|
107
|
+
| Today | With the journal | Still the product's |
|
|
108
|
+
| --- | --- | --- |
|
|
109
|
+
| In-memory history dies with the sidecar | History and interrupted receipts survive process replacement | Back up the disk; stop orphaned native work. |
|
|
110
|
+
| A retry may repeat execution | An identical command converges on its receipt | Stable ids; reconciling refreshed auth or config. |
|
|
111
|
+
| A lost ACK leaves delivery uncertain | The destination's committed head decides what is resent | Scheduling, connectivity, auth refresh. |
|
|
112
|
+
| Each product rebuilds conversations differently | One canonical reducer over portable history | Projection cursors, UI, side-effect-free hydration. |
|
|
113
|
+
| Viewers need the producer online | Relayed history stays readable offline | Membership, worker lifetime, retention. |
|
|
114
|
+
|
|
115
|
+
Retries remain necessary; what changes is that each one has a committed
|
|
116
|
+
version to resume from instead of a guess about whether a write happened.
|
|
117
|
+
|
|
118
|
+
## Reproduce the live proof
|
|
119
|
+
|
|
120
|
+
From the agent-server worktree, with Bun and an existing Claude login:
|
|
121
|
+
|
|
122
|
+
```sh
|
|
123
|
+
bun run control-agent-server doctor
|
|
124
|
+
bun run control-agent-server checks session-sync
|
|
125
|
+
bun run control-agent-server replay session-sync --live-model
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Proofs go to `.context/proof/session-sync/<run>/` (or `--out <new-dir>`), never
|
|
129
|
+
overwriting an earlier one. `result.json` records the source digest, exact
|
|
130
|
+
commands, the provider version and every named assertion; traces, databases,
|
|
131
|
+
viewer snapshots and logs stay alongside, including for failed runs. This is a
|
|
132
|
+
local process, storage and network proof: no public cloud, product UI, real WAN,
|
|
133
|
+
Codex or ACP live run, or native home transfer is exercised. See `gaps`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zvada/agent-server",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.18",
|
|
4
4
|
"description": "Harness-agnostic agent execution engine: run Claude Code, Codex (SDK/CLI + app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -77,7 +77,19 @@
|
|
|
77
77
|
"types": "./src/client/index.ts",
|
|
78
78
|
"default": "./src/client/index.ts"
|
|
79
79
|
},
|
|
80
|
-
"./package.json": "./package.json"
|
|
80
|
+
"./package.json": "./package.json",
|
|
81
|
+
"./sync": {
|
|
82
|
+
"types": "./src/sync/index.ts",
|
|
83
|
+
"default": "./src/sync/index.ts"
|
|
84
|
+
},
|
|
85
|
+
"./sync/sqlite": {
|
|
86
|
+
"types": "./src/sync/sqlite.ts",
|
|
87
|
+
"default": "./src/sync/sqlite.ts"
|
|
88
|
+
},
|
|
89
|
+
"./sync/node-sqlite": {
|
|
90
|
+
"types": "./src/sync/node-sqlite.ts",
|
|
91
|
+
"default": "./src/sync/node-sqlite.ts"
|
|
92
|
+
}
|
|
81
93
|
},
|
|
82
94
|
"dependencies": {
|
|
83
95
|
"zod": "^4.0.0"
|
package/src/client/client.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
+
type AsyncHistoryApi,
|
|
2
3
|
AsyncQueue,
|
|
3
4
|
type DecodedEventsReplayResult,
|
|
4
5
|
type DecodedLifecycleEvent,
|
|
5
6
|
type DecodedWireEventEnvelope,
|
|
7
|
+
type DurableSession,
|
|
8
|
+
DurableSessionSchema,
|
|
6
9
|
type InitializeResult,
|
|
7
10
|
InitializeResultSchema,
|
|
8
11
|
type JsonRpcId,
|
|
@@ -11,11 +14,16 @@ import {
|
|
|
11
14
|
type PermissionOutcome,
|
|
12
15
|
PermissionRespondResultSchema,
|
|
13
16
|
SessionCloseResultSchema,
|
|
17
|
+
type SessionConfirmStoppedParams,
|
|
18
|
+
SessionConfirmStoppedResultSchema,
|
|
14
19
|
ShutdownResultSchema,
|
|
15
20
|
type TurnCancelResult,
|
|
16
21
|
TurnCancelResultSchema,
|
|
17
22
|
type TurnEndedEvent,
|
|
23
|
+
type TurnReceipt,
|
|
24
|
+
TurnReceiptSchema,
|
|
18
25
|
type TurnStartParams,
|
|
26
|
+
type TurnStartResult,
|
|
19
27
|
TurnStartResultSchema,
|
|
20
28
|
type UnknownEvent,
|
|
21
29
|
WIRE_ERROR_CODES,
|
|
@@ -32,6 +40,8 @@ import {
|
|
|
32
40
|
generateUUIDv7,
|
|
33
41
|
isUnknownEvent,
|
|
34
42
|
} from "../protocol/index.ts";
|
|
43
|
+
import { createHistoryClient } from "./history.ts";
|
|
44
|
+
import { DEFAULT_REQUEST_TIMEOUT_MS, type ResultSchema, WireRequestError } from "./request.ts";
|
|
35
45
|
import {
|
|
36
46
|
type SpawnServerOptions,
|
|
37
47
|
type WebSocketLike,
|
|
@@ -40,18 +50,6 @@ import {
|
|
|
40
50
|
spawnTransport,
|
|
41
51
|
} from "./transports.ts";
|
|
42
52
|
|
|
43
|
-
/** The server answered a request with a JSON-RPC error. */
|
|
44
|
-
export class WireRequestError extends Error {
|
|
45
|
-
override readonly name = "WireRequestError";
|
|
46
|
-
constructor(
|
|
47
|
-
readonly code: number,
|
|
48
|
-
message: string,
|
|
49
|
-
readonly data?: unknown,
|
|
50
|
-
) {
|
|
51
|
-
super(message);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
53
|
/** The transport dropped (and reconnection, if enabled, gave up). */
|
|
56
54
|
export class ConnectionClosedError extends Error {
|
|
57
55
|
override readonly name = "ConnectionClosedError";
|
|
@@ -97,6 +95,9 @@ export interface AgentServerClientOptions {
|
|
|
97
95
|
maxReconnectAttempts?: number;
|
|
98
96
|
/** Base reconnect delay; grows exponentially, capped at 10s. */
|
|
99
97
|
reconnectDelayMs?: number;
|
|
98
|
+
/** A request unanswered this long fails. With reconnection (connect mode)
|
|
99
|
+
* the connection is presumed half-open and redialed, and the request fails
|
|
100
|
+
* with ConnectionClosedError. Default 30s. */
|
|
100
101
|
requestTimeoutMs?: number;
|
|
101
102
|
/** Attempts to heal one sequence gap before failing its turn. Default 3. */
|
|
102
103
|
maxReplayAttempts?: number;
|
|
@@ -119,10 +120,6 @@ interface InternalTurn {
|
|
|
119
120
|
rejectResult: (error: unknown) => void;
|
|
120
121
|
}
|
|
121
122
|
|
|
122
|
-
interface ResultSchema<T> {
|
|
123
|
-
safeParse(raw: unknown): { success: true; data: T } | { success: false };
|
|
124
|
-
}
|
|
125
|
-
|
|
126
123
|
/**
|
|
127
124
|
* `events/replay` decoded the Law-6 way. Using `EventsReplayResultSchema`
|
|
128
125
|
* here would embed the closed event union in the very path that heals a gap,
|
|
@@ -152,6 +149,9 @@ const MODEL_LIST: ResultSchema<ModelList> = {
|
|
|
152
149
|
|
|
153
150
|
type TransportFactory = () => Promise<WireTransport> | WireTransport;
|
|
154
151
|
|
|
152
|
+
/** Re-sends of a `turn/start` whose connection dropped before its ack. */
|
|
153
|
+
const MAX_TURN_START_RESENDS = 3;
|
|
154
|
+
|
|
155
155
|
/**
|
|
156
156
|
* Typed client for the agent-server wire. Turns are quick-ack: `runTurn`
|
|
157
157
|
* resolves once the server accepts the turn and hands back an async iterable
|
|
@@ -180,12 +180,22 @@ export class AgentServerClient {
|
|
|
180
180
|
private initializePromise: Promise<InitializeResult> | null = null;
|
|
181
181
|
private closed = false;
|
|
182
182
|
private reconnecting = false;
|
|
183
|
+
/** The running reconnect loop, for a request that waits to be re-sent. */
|
|
184
|
+
private reconnection: Promise<void> | null = null;
|
|
185
|
+
/** Portable history operations (`history/*`), independent of execution subscriptions. */
|
|
186
|
+
readonly history: AsyncHistoryApi;
|
|
183
187
|
|
|
184
188
|
private constructor(
|
|
185
189
|
private readonly factory: TransportFactory,
|
|
186
190
|
private readonly options: AgentServerClientOptions,
|
|
187
191
|
private readonly reconnectEnabled: boolean,
|
|
188
|
-
) {
|
|
192
|
+
) {
|
|
193
|
+
this.history = createHistoryClient(
|
|
194
|
+
(method, params, schema) => this.request(method, params, schema),
|
|
195
|
+
() => this.initialize(),
|
|
196
|
+
options,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
189
199
|
|
|
190
200
|
/**
|
|
191
201
|
* Bring your own transport: the factory is invoked for the initial
|
|
@@ -266,12 +276,14 @@ export class AgentServerClient {
|
|
|
266
276
|
);
|
|
267
277
|
}
|
|
268
278
|
// The restart question, answered by the handshake instead of
|
|
269
|
-
// inferred from seq patterns: a changed
|
|
270
|
-
//
|
|
271
|
-
|
|
279
|
+
// inferred from seq patterns: a changed identity means every session
|
|
280
|
+
// log we were tracking died with the old process. Durable logs
|
|
281
|
+
// (`historyId`) outlive it, and so do our cursors.
|
|
282
|
+
const logIdentity = result.historyId ?? result.instanceId;
|
|
283
|
+
if (this.serverInstanceId !== undefined && this.serverInstanceId !== logIdentity) {
|
|
272
284
|
this.adoptFreshLogs();
|
|
273
285
|
}
|
|
274
|
-
this.serverInstanceId =
|
|
286
|
+
this.serverInstanceId = logIdentity;
|
|
275
287
|
return result;
|
|
276
288
|
})
|
|
277
289
|
.catch((err) => {
|
|
@@ -336,11 +348,21 @@ export class AgentServerClient {
|
|
|
336
348
|
result.catch(() => undefined);
|
|
337
349
|
this.turnBySession.set(sessionId, { turnId, queue, resolveResult, rejectResult });
|
|
338
350
|
try {
|
|
339
|
-
await this.
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
351
|
+
const accepted = await this.admitTurn({ ...params, sessionId, turnId });
|
|
352
|
+
// A duplicate durable turn may have finished before this handle existed.
|
|
353
|
+
// Its completion is returned without duplicating the global event stream;
|
|
354
|
+
// `replay` or `history` serve its full transcript.
|
|
355
|
+
if (
|
|
356
|
+
accepted.terminal &&
|
|
357
|
+
(accepted.terminal.sessionId !== sessionId || accepted.terminal.turnId !== turnId)
|
|
358
|
+
)
|
|
359
|
+
throw new Error("Turn receipt belongs to a different request");
|
|
360
|
+
if (accepted.terminal && this.turnBySession.get(sessionId)?.turnId === turnId) {
|
|
361
|
+
this.turnBySession.delete(sessionId);
|
|
362
|
+
queue.push(accepted.terminal);
|
|
363
|
+
resolveResult(accepted.terminal);
|
|
364
|
+
queue.end();
|
|
365
|
+
}
|
|
344
366
|
} catch (err) {
|
|
345
367
|
this.turnBySession.delete(sessionId);
|
|
346
368
|
queue.fail(err);
|
|
@@ -350,8 +372,37 @@ export class AgentServerClient {
|
|
|
350
372
|
return { sessionId, turnId, events: queue, result };
|
|
351
373
|
}
|
|
352
374
|
|
|
375
|
+
/**
|
|
376
|
+
* `turn/start`, re-sent over a redialed connection: the server converges a
|
|
377
|
+
* repeated `{sessionId, turnId}` onto the turn it admitted, so a start whose
|
|
378
|
+
* ack was lost continues instead of failing while the turn runs unseen. Not
|
|
379
|
+
* to a server with fresh logs (a volatile restart): the turn died with the
|
|
380
|
+
* old process, or never reached it, and a re-send could run it again. A few
|
|
381
|
+
* re-sends at most: a server that accepts connections but never answers the
|
|
382
|
+
* start would otherwise be retried forever.
|
|
383
|
+
*/
|
|
384
|
+
private async admitTurn(
|
|
385
|
+
params: TurnStartParams & { sessionId: string; turnId: string },
|
|
386
|
+
): Promise<TurnStartResult> {
|
|
387
|
+
for (let resends = 0; ; resends++) {
|
|
388
|
+
const identity = this.serverInstanceId;
|
|
389
|
+
try {
|
|
390
|
+
return await this.request(WIRE_METHODS.turnStart, params, TurnStartResultSchema);
|
|
391
|
+
} catch (error) {
|
|
392
|
+
if (
|
|
393
|
+
!(error instanceof ConnectionClosedError) ||
|
|
394
|
+
!this.reconnectEnabled ||
|
|
395
|
+
resends >= MAX_TURN_START_RESENDS
|
|
396
|
+
)
|
|
397
|
+
throw error;
|
|
398
|
+
await this.reconnection;
|
|
399
|
+
if (this.closed || !this.transport || this.serverInstanceId !== identity) throw error;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
353
404
|
/** Quick-ack only — observe the turn via `onEvent` / `replay`. */
|
|
354
|
-
async startTurn(params: TurnStartParams): Promise<
|
|
405
|
+
async startTurn(params: TurnStartParams): Promise<TurnStartResult> {
|
|
355
406
|
await this.initialize();
|
|
356
407
|
const sessionId = params.sessionId ?? generateUUIDv7();
|
|
357
408
|
const turnId = params.turnId ?? generateUUIDv7();
|
|
@@ -421,17 +472,56 @@ export class AgentServerClient {
|
|
|
421
472
|
return this.request(WIRE_METHODS.modelsList, params, MODEL_LIST);
|
|
422
473
|
}
|
|
423
474
|
|
|
424
|
-
/** Fetch buffered events (`seq >= fromSeq`) without touching seq tracking.
|
|
475
|
+
/** Fetch buffered events (`seq >= fromSeq`) without touching seq tracking.
|
|
476
|
+
* A durable server answers a page at a time: `hasMore` asks for the next. */
|
|
425
477
|
replay(sessionId: string, fromSeq: number): Promise<DecodedEventsReplayResult> {
|
|
426
478
|
return this.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq }, REPLAY_RESULT);
|
|
427
479
|
}
|
|
428
480
|
|
|
481
|
+
/** Durable servers: a turn's receipt, even for a turn a restart cut off. */
|
|
482
|
+
async getTurn(sessionId: string, turnId: string): Promise<TurnReceipt> {
|
|
483
|
+
await this.initialize();
|
|
484
|
+
return this.request(WIRE_METHODS.turnGet, { sessionId, turnId }, TurnReceiptSchema);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Durable servers: the session's head, native id, and whether a restart cut off its last turn. */
|
|
488
|
+
async getSession(sessionId: string): Promise<DurableSession> {
|
|
489
|
+
await this.initialize();
|
|
490
|
+
return this.request(WIRE_METHODS.sessionGet, { sessionId }, DurableSessionSchema);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Durable servers: lift the fence a restart put on a session. Check first
|
|
494
|
+
* that its native execution stopped: history alone cannot prove that a
|
|
495
|
+
* detached agent or tool process is dead. */
|
|
496
|
+
async confirmSessionStopped(params: SessionConfirmStoppedParams): Promise<boolean> {
|
|
497
|
+
await this.initialize();
|
|
498
|
+
return (
|
|
499
|
+
await this.request(
|
|
500
|
+
WIRE_METHODS.sessionConfirmStopped,
|
|
501
|
+
params,
|
|
502
|
+
SessionConfirmStoppedResultSchema,
|
|
503
|
+
)
|
|
504
|
+
).recovered;
|
|
505
|
+
}
|
|
506
|
+
|
|
429
507
|
/** Firehose of sequenced events across all sessions (post-dedupe, in order). */
|
|
430
508
|
onEvent(handler: (envelope: DecodedWireEventEnvelope) => void): () => void {
|
|
431
509
|
this.eventHandlers.add(handler);
|
|
432
510
|
return () => this.eventHandlers.delete(handler);
|
|
433
511
|
}
|
|
434
512
|
|
|
513
|
+
/**
|
|
514
|
+
* Follow a session this client did not start, such as a turn another client
|
|
515
|
+
* left running: its events after `afterSeq` reach `onEvent`, those already
|
|
516
|
+
* logged now and later ones live, and after a redial the ones a dropped
|
|
517
|
+
* connection missed. A session already tracked keeps its position. Gaps that
|
|
518
|
+
* cannot be filled reach `onEventGap`.
|
|
519
|
+
*/
|
|
520
|
+
watch(sessionId: string, afterSeq = 0): void {
|
|
521
|
+
if (!this.cursor.sessions().includes(sessionId)) this.cursor.seek(sessionId, afterSeq);
|
|
522
|
+
void this.syncSession(sessionId);
|
|
523
|
+
}
|
|
524
|
+
|
|
435
525
|
/** Observe unrecoverable delivery gaps even when using startTurn without a handle. */
|
|
436
526
|
onEventGap(handler: (gap: SessionEventGap) => void): () => void {
|
|
437
527
|
this.gapHandlers.add(handler);
|
|
@@ -482,7 +572,9 @@ export class AgentServerClient {
|
|
|
482
572
|
this.failAllTurns(new ConnectionClosedError(reason ?? "connection closed"));
|
|
483
573
|
return;
|
|
484
574
|
}
|
|
485
|
-
|
|
575
|
+
this.reconnection ??= this.reconnectLoop().finally(() => {
|
|
576
|
+
this.reconnection = null;
|
|
577
|
+
});
|
|
486
578
|
}
|
|
487
579
|
|
|
488
580
|
private async reconnectLoop(): Promise<void> {
|
|
@@ -671,6 +763,11 @@ export class AgentServerClient {
|
|
|
671
763
|
);
|
|
672
764
|
this.cursor.seek(sessionId, replayed.firstAvailableSeq - 1);
|
|
673
765
|
}
|
|
766
|
+
if (replayed.hasMore) {
|
|
767
|
+
if (this.cursor.last(sessionId) < fromSeq) throw new Error("Replay made no progress");
|
|
768
|
+
attempt = 0; // successful pages do not consume the transport retry budget
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
674
771
|
break;
|
|
675
772
|
} catch (err) {
|
|
676
773
|
if (!isCurrent()) return;
|
|
@@ -767,13 +864,21 @@ export class AgentServerClient {
|
|
|
767
864
|
const transport = this.transport;
|
|
768
865
|
if (!transport) return Promise.reject(new ConnectionClosedError("not connected"));
|
|
769
866
|
const id = this.nextId++;
|
|
770
|
-
const timeoutMs = this.options.requestTimeoutMs ??
|
|
867
|
+
const timeoutMs = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
771
868
|
return new Promise<T>((resolve, reject) => {
|
|
772
869
|
const timer = setTimeout(() => {
|
|
773
870
|
this.pending.delete(id);
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
871
|
+
// A healthy server answers every request in time (`history/wait` is
|
|
872
|
+
// bounded below this): a client that can redial replaces the
|
|
873
|
+
// half-open connection. One that cannot (attach, and spawn, whose
|
|
874
|
+
// transport is the server process) fails only this request.
|
|
875
|
+
if (this.reconnectEnabled && this.transport === transport) {
|
|
876
|
+
reject(new ConnectionClosedError(`request timed out: ${method}`));
|
|
877
|
+
transport.close();
|
|
878
|
+
} else
|
|
879
|
+
reject(
|
|
880
|
+
new WireRequestError(WIRE_ERROR_CODES.internalError, `request timed out: ${method}`),
|
|
881
|
+
);
|
|
777
882
|
}, timeoutMs);
|
|
778
883
|
this.pending.set(id, {
|
|
779
884
|
resolve: (raw) => {
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AsyncHistoryApi,
|
|
3
|
+
HISTORY_ERROR_CODES,
|
|
4
|
+
HISTORY_METHODS,
|
|
5
|
+
HISTORY_WAIT_TIMEOUT_MS,
|
|
6
|
+
HistoryCatalogSchema,
|
|
7
|
+
HistoryCheckpointSchema,
|
|
8
|
+
HistoryError,
|
|
9
|
+
HistoryHeadSchema,
|
|
10
|
+
HistorySliceSchema,
|
|
11
|
+
HistoryVersionSchema,
|
|
12
|
+
WIRE_ERROR_CODES,
|
|
13
|
+
} from "../protocol/index.ts";
|
|
14
|
+
import {
|
|
15
|
+
DEFAULT_REQUEST_TIMEOUT_MS,
|
|
16
|
+
type Request,
|
|
17
|
+
type ResultSchema,
|
|
18
|
+
WireRequestError,
|
|
19
|
+
} from "./request.ts";
|
|
20
|
+
|
|
21
|
+
const REASONS = new Map(
|
|
22
|
+
Object.entries(HISTORY_ERROR_CODES).map(([reason, code]) => [
|
|
23
|
+
code as number,
|
|
24
|
+
reason as HistoryError["reason"],
|
|
25
|
+
]),
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
/** History RPC adaptation has no execution, reconnection or event-cursor state.
|
|
29
|
+
* A refusal fails with the HistoryError a local store would have thrown. */
|
|
30
|
+
export function createHistoryClient(
|
|
31
|
+
sendRequest: Request,
|
|
32
|
+
initialize: () => Promise<unknown>,
|
|
33
|
+
options: { requestTimeoutMs?: number },
|
|
34
|
+
): AsyncHistoryApi {
|
|
35
|
+
const call = async <T>(method: string, params: unknown, schema: ResultSchema<T>) => {
|
|
36
|
+
await initialize();
|
|
37
|
+
try {
|
|
38
|
+
return await sendRequest(method, params, schema);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
const reason = error instanceof WireRequestError ? REASONS.get(error.code) : undefined;
|
|
41
|
+
throw reason ? new HistoryError(reason, (error as Error).message) : error;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
checkpoint: async (request) => {
|
|
46
|
+
try {
|
|
47
|
+
return await call(HISTORY_METHODS.checkpoint, request, HistoryCheckpointSchema.nullable());
|
|
48
|
+
} catch (error) {
|
|
49
|
+
// Older servers can still supply authoritative events. Never hide ACL failures.
|
|
50
|
+
if (error instanceof WireRequestError && error.code === WIRE_ERROR_CODES.methodNotFound)
|
|
51
|
+
return null;
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
list: (request = {}) => call(HISTORY_METHODS.list, request, HistoryCatalogSchema),
|
|
56
|
+
head: (ref) => call(HISTORY_METHODS.head, ref, HistoryHeadSchema),
|
|
57
|
+
// Pages are checked where they are trusted: by `readHistoryPage`, which every
|
|
58
|
+
// helper reads through, and by the store that imports them.
|
|
59
|
+
read: (request) => call(HISTORY_METHODS.read, request, HistorySliceSchema),
|
|
60
|
+
import: (page) => call(HISTORY_METHODS.import, page, HistoryVersionSchema),
|
|
61
|
+
fork: (request) => call(HISTORY_METHODS.fork, request, HistoryHeadSchema),
|
|
62
|
+
commit: (request) => call(HISTORY_METHODS.commit, request, HistoryVersionSchema),
|
|
63
|
+
// Abort ends the local wait immediately. The server wait is independently bounded
|
|
64
|
+
// and is also cancelled if this transport closes.
|
|
65
|
+
wait: async (request, signal) => {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
const wait = call(
|
|
68
|
+
HISTORY_METHODS.wait,
|
|
69
|
+
{
|
|
70
|
+
...request,
|
|
71
|
+
timeoutMs: Math.min(
|
|
72
|
+
request.timeoutMs ?? HISTORY_WAIT_TIMEOUT_MS,
|
|
73
|
+
// Answered before the request itself times out.
|
|
74
|
+
Math.max(0, (options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS) - 1000),
|
|
75
|
+
),
|
|
76
|
+
},
|
|
77
|
+
HistoryHeadSchema,
|
|
78
|
+
);
|
|
79
|
+
if (!signal) return wait;
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const abort = () => reject(signal.reason);
|
|
82
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
83
|
+
wait.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
84
|
+
if (signal.aborted) abort();
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
package/src/client/index.ts
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
2
|
+
|
|
3
|
+
/** The server answered a request with a JSON-RPC error. */
|
|
4
|
+
export class WireRequestError extends Error {
|
|
5
|
+
override readonly name = "WireRequestError";
|
|
6
|
+
constructor(
|
|
7
|
+
readonly code: number,
|
|
8
|
+
message: string,
|
|
9
|
+
readonly data?: unknown,
|
|
10
|
+
) {
|
|
11
|
+
super(message);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ResultSchema<T> {
|
|
16
|
+
safeParse(raw: unknown): { success: true; data: T } | { success: false };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type Request = <T>(method: string, params: unknown, schema: ResultSchema<T>) => Promise<T>;
|
package/src/core/index.ts
CHANGED
|
@@ -5,8 +5,10 @@ export { AgentRuntime, type RunSummary, type TurnAdmission } from "./runtime/age
|
|
|
5
5
|
export { type DiagnosticHandler, type EngineDiagnostic, emitDiagnostic } from "./diagnostics.ts";
|
|
6
6
|
export {
|
|
7
7
|
type EventSink,
|
|
8
|
+
EventSinkError,
|
|
8
9
|
callbackSink,
|
|
9
10
|
CollectingSink,
|
|
11
|
+
serialSink,
|
|
10
12
|
teeSink,
|
|
11
13
|
} from "./runtime/event-sink.ts";
|
|
12
14
|
export { EventProcessor, endedExecution } from "./runtime/event-processor.ts";
|
|
@@ -37,7 +37,8 @@ export const DEFAULT_PINS: Record<CliTool, string> = {
|
|
|
37
37
|
claude: "0.3.288",
|
|
38
38
|
// 0.160.0 re-verified 2026-10-03 against generate-ts: thread/turn/item
|
|
39
39
|
// methods, token usage, approvals, and host-managed ChatGPT auth changed
|
|
40
|
-
// only additively since 0.153.4.
|
|
40
|
+
// only additively since 0.153.4. Of the GPT-6 family, 0.153.4 lists only
|
|
41
|
+
// gpt-6-astra; the rest needs 0.159 or newer.
|
|
41
42
|
// Since 0.160 a thread has one writer: resuming it from a second process
|
|
42
43
|
// fails until the first releases it.
|
|
43
44
|
codex: "0.160.0",
|