@zvada/agent-server 0.3.23 → 0.3.25
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 +64 -0
- package/README.md +14 -5
- package/dist/accounts/chatgpt.js +144 -0
- package/dist/accounts/check.js +71 -0
- package/dist/accounts/claude.js +80 -0
- package/dist/accounts/endpoint.js +104 -0
- package/dist/accounts/http.js +58 -0
- package/dist/accounts/index.js +9 -0
- package/dist/client/client.js +745 -0
- package/dist/client/connection.js +338 -0
- package/dist/client/history.js +49 -0
- package/dist/client/index.js +6 -0
- package/dist/client/listeners.js +19 -0
- package/dist/client/logins.js +92 -0
- package/dist/client/rpc.js +105 -0
- package/dist/client/streams.js +432 -0
- package/dist/client/transports.js +118 -0
- package/dist/client/turns.js +122 -0
- package/dist/core/agents/acp/acp-agent.js +425 -0
- package/dist/core/agents/acp/adapter.js +231 -0
- package/dist/core/agents/acp/client.js +222 -0
- package/dist/core/agents/acp/known-agents.js +57 -0
- package/dist/core/agents/acp/mappings.js +164 -0
- package/dist/core/agents/acp/requests.js +79 -0
- package/dist/core/agents/attachments.js +14 -0
- package/dist/core/agents/base.js +64 -0
- package/dist/core/agents/claude-code/adapter.js +474 -0
- package/dist/core/agents/claude-code/approvals.js +245 -0
- package/dist/core/agents/claude-code/claude-agent.js +319 -0
- package/dist/core/agents/claude-code/credentials.js +142 -0
- package/dist/core/agents/claude-code/events.js +11 -0
- package/dist/core/agents/claude-code/login.js +217 -0
- package/dist/core/agents/claude-code/mcp.js +181 -0
- package/dist/core/agents/claude-code/models.js +74 -0
- package/dist/core/agents/claude-code/options.js +240 -0
- package/dist/core/agents/claude-code/outcome.js +204 -0
- package/dist/core/agents/claude-code/results.js +58 -0
- package/dist/core/agents/claude-code/sdk-pair.js +59 -0
- package/dist/core/agents/claude-code/session.js +593 -0
- package/dist/core/agents/claude-code/spawn.js +125 -0
- package/dist/core/agents/claude-code/spend.js +118 -0
- package/dist/core/agents/claude-code/tools.js +131 -0
- package/dist/core/agents/claude-code/turn-usage.js +121 -0
- package/dist/core/agents/claude-code/turn.js +199 -0
- package/dist/core/agents/codex-app-server/adapter.js +463 -0
- package/dist/core/agents/codex-app-server/client.js +338 -0
- package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
- package/dist/core/agents/codex-app-server/commands.js +184 -0
- package/dist/core/agents/codex-app-server/credentials.js +92 -0
- package/dist/core/agents/codex-app-server/effort.js +13 -0
- package/dist/core/agents/codex-app-server/events.js +18 -0
- package/dist/core/agents/codex-app-server/homes.js +118 -0
- package/dist/core/agents/codex-app-server/input.js +52 -0
- package/dist/core/agents/codex-app-server/items.js +307 -0
- package/dist/core/agents/codex-app-server/login.js +183 -0
- package/dist/core/agents/codex-app-server/mcp.js +323 -0
- package/dist/core/agents/codex-app-server/models.js +160 -0
- package/dist/core/agents/codex-app-server/options.js +155 -0
- package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
- package/dist/core/agents/codex-app-server/protocol.js +38 -0
- package/dist/core/agents/codex-app-server/requests.js +250 -0
- package/dist/core/agents/codex-app-server/session.js +278 -0
- package/dist/core/agents/codex-app-server/subagents.js +260 -0
- package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
- package/dist/core/agents/codex-app-server/turn-items.js +69 -0
- package/dist/core/agents/codex-app-server/turn.js +448 -0
- package/dist/core/agents/codex-app-server/user-login.js +78 -0
- package/dist/core/agents/config-fingerprint.js +10 -0
- package/dist/core/agents/credentials.js +71 -0
- package/dist/core/agents/diffs.js +27 -0
- package/dist/core/agents/elicitation.js +42 -0
- package/dist/core/agents/inherit-config.js +5 -0
- package/dist/core/agents/login.js +56 -0
- package/dist/core/agents/mcp-config.js +109 -0
- package/dist/core/agents/plan.js +6 -0
- package/dist/core/agents/process-pool.js +307 -0
- package/dist/core/agents/registry.js +49 -0
- package/dist/core/agents/scripted/adapter.js +86 -0
- package/dist/core/agents/scripted/mcp-call.js +74 -0
- package/dist/core/agents/scripted/scripted-agent.js +331 -0
- package/dist/core/agents/scripted/scripts.js +154 -0
- package/dist/core/agents/scripted/steps.js +87 -0
- package/dist/core/agents/session-agent.js +209 -0
- package/dist/core/agents/stderr-tail.js +71 -0
- package/dist/core/agents/thinking-levels.js +9 -0
- package/dist/core/agents/types.js +1 -0
- package/dist/core/diagnostics.js +23 -0
- package/dist/core/index.js +31 -0
- package/dist/core/presets.js +114 -0
- package/dist/core/processes/identity.js +92 -0
- package/dist/core/processes/lifeline.js +218 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +164 -0
- package/dist/core/provision/cache-trust.js +121 -0
- package/dist/core/provision/cache-usage.js +61 -0
- package/dist/core/provision/checksums.js +22 -0
- package/dist/core/provision/extract.js +29 -0
- package/dist/core/provision/index.js +4 -0
- package/dist/core/provision/install-build.js +99 -0
- package/dist/core/provision/npm.js +316 -0
- package/dist/core/provision/pins.js +35 -0
- package/dist/core/provision/platform.js +65 -0
- package/dist/core/provision/provisioner.js +372 -0
- package/dist/core/provision/releases.js +68 -0
- package/dist/core/provision/tools.js +279 -0
- package/dist/core/proxy/anthropic-proxy.js +163 -0
- package/dist/core/proxy/api-key-store.js +30 -0
- package/dist/core/proxy/index.js +3 -0
- package/dist/core/proxy/loopback.js +86 -0
- package/dist/core/runtime/agent-runtime.js +437 -0
- package/dist/core/runtime/event-processor.js +379 -0
- package/dist/core/runtime/event-sink.js +65 -0
- package/dist/core/runtime/harness-clis.js +83 -0
- package/dist/core/runtime/harness-logins.js +313 -0
- package/dist/core/runtime/login-reads.js +71 -0
- package/dist/core/runtime/model-lists.js +160 -0
- package/dist/core/runtime/permission-policy.js +84 -0
- package/dist/core/runtime/request-broker.js +139 -0
- package/dist/core/runtime/steering.js +79 -0
- package/dist/core/runtime/turn-outcome.js +16 -0
- package/dist/core/runtime/turn.js +339 -0
- package/dist/core/utils/bounded.js +13 -0
- package/dist/core/utils/deadline.js +57 -0
- package/dist/core/utils/errors.js +176 -0
- package/dist/core/utils/is-record.js +4 -0
- package/dist/core/utils/loopback.js +11 -0
- package/dist/index.js +4 -0
- package/dist/operator/index.js +10 -0
- package/dist/operator/mcp.js +139 -0
- package/dist/operator/operator.js +499 -0
- package/dist/operator/render.js +408 -0
- package/dist/operator/view.js +35 -0
- package/dist/protocol/account.js +96 -0
- package/dist/protocol/async-queue.js +65 -0
- package/dist/protocol/auth.js +169 -0
- package/dist/protocol/canonical.js +18 -0
- package/dist/protocol/clis.js +63 -0
- package/dist/protocol/config.js +137 -0
- package/dist/protocol/conversation.js +231 -0
- package/dist/protocol/credentials.js +142 -0
- package/dist/protocol/errors.js +190 -0
- package/dist/protocol/execution.js +28 -0
- package/dist/protocol/factories.js +231 -0
- package/dist/protocol/guards.js +71 -0
- package/dist/protocol/harness.js +93 -0
- package/dist/protocol/history.js +201 -0
- package/dist/protocol/ids.js +37 -0
- package/dist/protocol/index.js +36 -0
- package/dist/protocol/lifecycle.js +562 -0
- package/dist/protocol/meta-keys.js +17 -0
- package/dist/protocol/meta.js +13 -0
- package/dist/protocol/model-catalog.js +223 -0
- package/dist/protocol/models.js +84 -0
- package/dist/protocol/part-input.js +94 -0
- package/dist/protocol/parts.js +166 -0
- package/dist/protocol/plan.js +31 -0
- package/dist/protocol/reduce.js +484 -0
- package/dist/protocol/selectors.js +136 -0
- package/dist/protocol/seq-cursor.js +37 -0
- package/dist/protocol/stop-reasons.js +41 -0
- package/dist/protocol/thinking.js +31 -0
- package/dist/protocol/time.js +21 -0
- package/dist/protocol/tokens.js +57 -0
- package/dist/protocol/tool-closure.js +70 -0
- package/dist/protocol/tool-state.js +153 -0
- package/dist/protocol/verify.js +467 -0
- package/dist/protocol/vocabulary.js +27 -0
- package/dist/protocol/wire-api.js +94 -0
- package/dist/protocol/wire.js +669 -0
- package/dist/server/acp/binding.js +251 -0
- package/dist/server/acp/session-records.js +53 -0
- package/dist/server/acp/translate.js +401 -0
- package/dist/server/agent-server.js +338 -0
- package/dist/server/bin.js +492 -0
- package/dist/server/feedback.js +216 -0
- package/dist/server/history.js +123 -0
- package/dist/server/index.js +8 -0
- package/dist/server/install.js +171 -0
- package/dist/server/open-parts.js +87 -0
- package/dist/server/routes.js +292 -0
- package/dist/server/secrets.js +19 -0
- package/dist/server/session-gate.js +54 -0
- package/dist/server/session-log.js +66 -0
- package/dist/server/session-store.js +243 -0
- package/dist/server/subscriptions.js +189 -0
- package/dist/server/transports.js +214 -0
- package/dist/server/wire-error.js +26 -0
- package/dist/sync/event-log.js +89 -0
- package/dist/sync/fit.js +202 -0
- package/dist/sync/history-reader.js +33 -0
- package/dist/sync/history-sqlite.js +281 -0
- package/dist/sync/history.js +163 -0
- package/dist/sync/index.js +5 -0
- package/dist/sync/journal-sqlite.js +316 -0
- package/dist/sync/journal.js +10 -0
- package/dist/sync/live-tails.js +85 -0
- package/dist/sync/node-sqlite.js +27 -0
- package/dist/sync/projection.js +32 -0
- package/dist/sync/recovery.js +117 -0
- package/dist/sync/retry.js +45 -0
- package/dist/sync/schema.js +73 -0
- package/dist/sync/sql.js +94 -0
- package/dist/sync/sqlite-file.js +31 -0
- package/dist/sync/sqlite.js +18 -0
- package/dist/sync/worker.js +212 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +28 -11
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/session.d.ts +8 -0
- package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
- package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
- package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
- package/dist/types/core/agents/process-pool.d.ts +8 -0
- package/dist/types/core/agents/process-pool.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- package/dist/types/server/routes.d.ts.map +1 -1
- package/dist/types/server/transports.d.ts +2 -1
- package/dist/types/server/transports.d.ts.map +1 -1
- package/dist/types/sync/node-sqlite.d.ts +4 -1
- package/dist/types/sync/node-sqlite.d.ts.map +1 -1
- package/docs/consuming.md +56 -7
- package/docs/deploy.md +35 -0
- package/docs/harnesses.md +30 -5
- package/package.json +43 -18
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/approvals.ts +5 -1
- package/src/core/agents/claude-code/claude-agent.ts +32 -5
- package/src/core/agents/claude-code/options.ts +28 -11
- package/src/core/agents/claude-code/session.ts +13 -0
- package/src/core/agents/codex-app-server/homes.ts +11 -2
- package/src/core/agents/codex-app-server/login.ts +30 -0
- package/src/core/agents/codex-app-server/requests.ts +7 -6
- package/src/core/agents/codex-app-server/session.ts +11 -2
- package/src/core/agents/process-pool.ts +30 -4
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/presets.ts +3 -2
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/bin.ts +25 -10
- package/src/server/routes.ts +3 -2
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
import { AuthUpdatedSchema, HarnessCliProgressSchema, SessionOverflowParamsSchema, WIRE_ERROR_CODES, WIRE_METHODS, decodeWireEventEnvelope, decodeWireMessage, generateUUIDv7, } from "../protocol/index.js";
|
|
2
|
+
import { Connection, ConnectionClosedError, ConnectionRefusedError, ProtocolVersionMismatchError, } from "./connection.js";
|
|
3
|
+
import { createHistoryClient } from "./history.js";
|
|
4
|
+
import { Listeners } from "./listeners.js";
|
|
5
|
+
import { startLogin } from "./logins.js";
|
|
6
|
+
import { WireRequestError } from "./rpc.js";
|
|
7
|
+
import { EventGapError, Streams } from "./streams.js";
|
|
8
|
+
import { connectTransport, socketTransport, spawnTransport, } from "./transports.js";
|
|
9
|
+
import { Turns } from "./turns.js";
|
|
10
|
+
export { ConnectionClosedError, ConnectionRefusedError, EventGapError, ProtocolVersionMismatchError, };
|
|
11
|
+
/** `signal` stops the handle following its turn. */
|
|
12
|
+
function stopOn(handle, signal) {
|
|
13
|
+
if (!signal)
|
|
14
|
+
return;
|
|
15
|
+
const stop = () => handle.fail(signal.reason ?? new Error("stopped following the turn"));
|
|
16
|
+
if (signal.aborted) {
|
|
17
|
+
stop();
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
21
|
+
const off = () => signal.removeEventListener("abort", stop);
|
|
22
|
+
void handle.result.then(off, off);
|
|
23
|
+
}
|
|
24
|
+
// @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel sent right behind its start reaches the turn
|
|
25
|
+
/**
|
|
26
|
+
* The `turn/start`s this client has not sent yet, each from before its
|
|
27
|
+
* first `await` until its first send or its end. The server takes a
|
|
28
|
+
* connection's requests in order and admits a turn in its start's handler,
|
|
29
|
+
* so a cancel for one of their turns goes out after that first send. Once
|
|
30
|
+
* sent, a start delays no cancel: after a redial a cancel can overtake its
|
|
31
|
+
* re-send, and is answered `no_active_turn`. Before its first send a start
|
|
32
|
+
* waits only on the handshake, a request the client's close fails, so no
|
|
33
|
+
* cancel waits past the close.
|
|
34
|
+
*/
|
|
35
|
+
class Starts {
|
|
36
|
+
unsent = new Set();
|
|
37
|
+
/** Record a start; the function returned lets it go (its first send, or its end), and may be called again. */
|
|
38
|
+
begin(sessionId, turnId) {
|
|
39
|
+
let settle = () => { };
|
|
40
|
+
const gone = new Promise((resolve) => {
|
|
41
|
+
settle = resolve;
|
|
42
|
+
});
|
|
43
|
+
const start = { sessionId, turnId, gone };
|
|
44
|
+
this.unsent.add(start);
|
|
45
|
+
return () => {
|
|
46
|
+
this.unsent.delete(start);
|
|
47
|
+
settle();
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** `send`, once no start of `turnId` (without one, of the session) is unsent; in the call when none is. */
|
|
51
|
+
after(sessionId, turnId, send) {
|
|
52
|
+
const waiting = [...this.unsent].filter((start) => start.sessionId === sessionId && (turnId === undefined || start.turnId === turnId));
|
|
53
|
+
if (waiting.length === 0)
|
|
54
|
+
return send();
|
|
55
|
+
return Promise.all(waiting.map((start) => start.gone)).then(send);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** How often `prepareClis` asks again while an install runs, besides when one ends. */
|
|
59
|
+
const PREPARE_POLL_MS = 2_000;
|
|
60
|
+
/**
|
|
61
|
+
* Typed client for the agent-server wire. Turns are quick-ack: `runTurn`
|
|
62
|
+
* resolves once the server accepts the turn and hands back an async iterable
|
|
63
|
+
* of its events, from its `turn.started` to its `turn.ended`. The client
|
|
64
|
+
* follows the sessions it subscribed to (and its turns subscribe): each
|
|
65
|
+
* session's `seq` is tracked so duplicates are dropped and gaps healed via
|
|
66
|
+
* `events/replay`, and — in `connect` mode — a dropped socket is redialed and
|
|
67
|
+
* its sessions subscribed again.
|
|
68
|
+
*/
|
|
69
|
+
export class AgentServerClient {
|
|
70
|
+
options;
|
|
71
|
+
connection;
|
|
72
|
+
turns = new Turns();
|
|
73
|
+
starts = new Starts();
|
|
74
|
+
progress = new Listeners();
|
|
75
|
+
authUpdates = new Listeners();
|
|
76
|
+
streams;
|
|
77
|
+
/** `subscribeAll` calls whose ask no server has answered yet: across redials, the next answer settles them. */
|
|
78
|
+
allAsked = [];
|
|
79
|
+
/** Portable history operations (`history/*`), independent of execution subscriptions. */
|
|
80
|
+
history;
|
|
81
|
+
constructor(factory, options, redials, url) {
|
|
82
|
+
this.options = options;
|
|
83
|
+
this.connection = new Connection(factory, options, redials, {
|
|
84
|
+
line: (line, transport) => this.handleLine(line, transport),
|
|
85
|
+
opened: (redialed) => this.streams.reconnected(redialed),
|
|
86
|
+
serverChanged: () => this.streams.adoptFreshLogs(),
|
|
87
|
+
reconnected: () => {
|
|
88
|
+
this.streams.resume();
|
|
89
|
+
this.subscribeAgain();
|
|
90
|
+
},
|
|
91
|
+
closed: (error) => {
|
|
92
|
+
this.turns.failAll(error);
|
|
93
|
+
this.answeredAll(error);
|
|
94
|
+
},
|
|
95
|
+
}, url);
|
|
96
|
+
this.streams = new Streams({
|
|
97
|
+
transport: () => this.connection.transport,
|
|
98
|
+
open: () => !this.connection.closed,
|
|
99
|
+
replay: (sessionId, fromSeq) => this.replay(sessionId, fromSeq),
|
|
100
|
+
resubscribe: (sessionId, turnId) => void this.resubscribe(sessionId, turnId),
|
|
101
|
+
resubscribeAll: () => void this.requestAll(),
|
|
102
|
+
maxReplayAttempts: options.maxReplayAttempts ?? 3,
|
|
103
|
+
replayRetryDelayMs: options.replayRetryDelayMs ?? options.reconnectDelayMs ?? 250,
|
|
104
|
+
}, this.turns);
|
|
105
|
+
this.history = createHistoryClient((method, params) => this.connection.request(method, params), () => this.initialize(), options);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Bring your own transport: the factory is invoked for the initial
|
|
109
|
+
* connection and for every reconnect attempt (reconnect defaults to true).
|
|
110
|
+
*/
|
|
111
|
+
static async fromTransportFactory(factory, options = {}) {
|
|
112
|
+
const client = new AgentServerClient(factory, options, options.reconnect ?? true);
|
|
113
|
+
await client.connection.open();
|
|
114
|
+
return client;
|
|
115
|
+
}
|
|
116
|
+
/** Spawn an agent-server subprocess and talk over its stdio. */
|
|
117
|
+
static async spawn(spawnOpts, options = {}) {
|
|
118
|
+
const client = new AgentServerClient(() => spawnTransport(spawnOpts), options, options.reconnect ?? false);
|
|
119
|
+
await client.connection.open();
|
|
120
|
+
return client;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Dial a listening agent-server (reconnects by default). One that refuses
|
|
124
|
+
* the client (401: the token it sent, or that it sent none) fails it with
|
|
125
|
+
* `ConnectionRefusedError`, and is not redialed.
|
|
126
|
+
*/
|
|
127
|
+
static async connect(url, options = {}) {
|
|
128
|
+
const headers = options.token === undefined ? undefined : { authorization: `Bearer ${options.token}` };
|
|
129
|
+
const client = new AgentServerClient(() => connectTransport(url, headers), options, options.reconnect ?? true, url);
|
|
130
|
+
await client.connection.open();
|
|
131
|
+
return client;
|
|
132
|
+
}
|
|
133
|
+
/** Wrap an already-connected socket (e.g. the accepted end of a dial-out). */
|
|
134
|
+
static async attach(socket, options = {}) {
|
|
135
|
+
const transport = "onLine" in socket ? socket : socketTransport(socket);
|
|
136
|
+
let used = false;
|
|
137
|
+
const client = new AgentServerClient(() => {
|
|
138
|
+
if (used)
|
|
139
|
+
throw new ConnectionClosedError("attached socket cannot be re-opened");
|
|
140
|
+
used = true;
|
|
141
|
+
return transport;
|
|
142
|
+
}, options, false);
|
|
143
|
+
await client.connection.open();
|
|
144
|
+
return client;
|
|
145
|
+
}
|
|
146
|
+
// ---- turns ---------------------------------------------------------------
|
|
147
|
+
/** Handshake (memoized). Called lazily by `runTurn`/`startTurn`. */
|
|
148
|
+
initialize() {
|
|
149
|
+
return this.connection.initialize();
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Start a turn and stream it, from its `turn.started` to its `turn.ended`.
|
|
153
|
+
* Ids are minted client-side when omitted. The start subscribes this client
|
|
154
|
+
* to the session from its head until the turn ends, so it downloads none
|
|
155
|
+
* of its history; a start re-sent after a redial converges on the turn the
|
|
156
|
+
* server admitted and catches up on it from its `turn.started`. `signal`
|
|
157
|
+
* stops the handle, as on `joinTurn`: the turn runs on (`cancelTurn` stops
|
|
158
|
+
* it), and `onEvent` hears it to its end.
|
|
159
|
+
*/
|
|
160
|
+
async runTurn(params, options = {}) {
|
|
161
|
+
const sessionId = params.sessionId ?? generateUUIDv7();
|
|
162
|
+
const turnId = params.turnId ?? generateUUIDv7();
|
|
163
|
+
// Before the first `await`: a cancel sent right behind this call goes out after the start.
|
|
164
|
+
const release = this.starts.begin(sessionId, turnId);
|
|
165
|
+
try {
|
|
166
|
+
await this.initialize();
|
|
167
|
+
if (this.turns.running(sessionId))
|
|
168
|
+
throw new Error(`session ${sessionId} already has an active turn`);
|
|
169
|
+
const handle = this.turns.open(sessionId, turnId, true);
|
|
170
|
+
try {
|
|
171
|
+
stopOn(handle, options.signal);
|
|
172
|
+
// `resend` sends (or fails for no connection) before its first `await`, in this call.
|
|
173
|
+
const sending = this.connection.resend(WIRE_METHODS.turnStart, { ...params, sessionId, turnId, subscribe: true },
|
|
174
|
+
// A turn that already ended streams nothing: its end is in the ack.
|
|
175
|
+
(ack) => {
|
|
176
|
+
if (!ack.terminal)
|
|
177
|
+
this.joinAt(handle, ack.headSeq, { turnId });
|
|
178
|
+
});
|
|
179
|
+
release();
|
|
180
|
+
const accepted = await sending;
|
|
181
|
+
const { terminal } = accepted;
|
|
182
|
+
if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
|
|
183
|
+
throw new Error("Turn receipt belongs to a different request");
|
|
184
|
+
// A retried start of a turn that already ended: its end, without its events
|
|
185
|
+
// (`replay` or `history` serve its transcript).
|
|
186
|
+
if (terminal)
|
|
187
|
+
handle.push(terminal);
|
|
188
|
+
else
|
|
189
|
+
await this.catchUp(handle, accepted.deduplicated
|
|
190
|
+
? (accepted.startedSeq ?? accepted.headSeq + 1)
|
|
191
|
+
: accepted.headSeq + 1, accepted.headSeq);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
handle.fail(error);
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
return this.handleOf(handle);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
release();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Quick-ack only: the turn's events reach `onEvent` through its
|
|
205
|
+
* `turn.ended` (unless `subscribe: false`), and `replay` serves what came
|
|
206
|
+
* before.
|
|
207
|
+
*/
|
|
208
|
+
async startTurn(params) {
|
|
209
|
+
const sessionId = params.sessionId ?? generateUUIDv7();
|
|
210
|
+
const turnId = params.turnId ?? generateUUIDv7();
|
|
211
|
+
// As in `runTurn`: a cancel sent right behind this call goes out after the start.
|
|
212
|
+
const release = this.starts.begin(sessionId, turnId);
|
|
213
|
+
try {
|
|
214
|
+
await this.initialize();
|
|
215
|
+
// `request` sends (or fails for no connection) in this call.
|
|
216
|
+
const answer = this.connection.request(WIRE_METHODS.turnStart, { ...params, sessionId, turnId }, (ack) => {
|
|
217
|
+
if (params.subscribe !== false && !ack.terminal)
|
|
218
|
+
this.streams.joined(sessionId, ack.headSeq, { turnId });
|
|
219
|
+
});
|
|
220
|
+
release();
|
|
221
|
+
return await answer;
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
release();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Join the turn running in `sessionId`. Yields, each once and in seq
|
|
229
|
+
* order: the session's kept events from `fromSeq` (default: the turn's
|
|
230
|
+
* `turn.started`), the turn's open parts as of the join, then live frames
|
|
231
|
+
* through the turn's `turn.ended` — so even when this client already
|
|
232
|
+
* follows the session or another handle joined earlier. Resolves once the
|
|
233
|
+
* catch-up is replayed (`catchUp` counts it); `undefined` when no turn is
|
|
234
|
+
* running. `steer` and `result` work as on `runTurn`'s handle. Joining
|
|
235
|
+
* watches the session (`subscribe`).
|
|
236
|
+
*/
|
|
237
|
+
async joinTurn(sessionId, options = {}) {
|
|
238
|
+
await this.initialize();
|
|
239
|
+
let handle;
|
|
240
|
+
const answer = await this.subscribeTo({ sessionId }, (ack) => {
|
|
241
|
+
if (!ack.activeTurn)
|
|
242
|
+
return this.streams.joined(sessionId, ack.headSeq, "watch");
|
|
243
|
+
handle = this.turns.open(sessionId, ack.activeTurn.turnId, false);
|
|
244
|
+
this.joinAt(handle, ack.headSeq, "watch");
|
|
245
|
+
});
|
|
246
|
+
if (!handle)
|
|
247
|
+
return undefined;
|
|
248
|
+
stopOn(handle, options.signal);
|
|
249
|
+
const fromSeq = options.fromSeq ?? answer.activeTurn?.startedSeq ?? answer.headSeq + 1;
|
|
250
|
+
await this.catchUp(handle, fromSeq, answer.headSeq);
|
|
251
|
+
return this.handleOf(handle);
|
|
252
|
+
}
|
|
253
|
+
// @ref LLP 0001#d13--input-while-a-turn-runs-steers-it — the client half
|
|
254
|
+
/**
|
|
255
|
+
* Add input to a running turn. The agent reads it at its next step, where
|
|
256
|
+
* the turn's stream shows it as a user message (`steerMessageId(steerId)`);
|
|
257
|
+
* a turn that ends first lists it in `turn.ended.undeliveredSteers`.
|
|
258
|
+
* `no_active_turn` means the turn takes no more input — send it as a new
|
|
259
|
+
* turn; `unsupported` means the harness cannot steer. `steerId` is minted
|
|
260
|
+
* when omitted; a re-send with the same one converges, so a steer whose
|
|
261
|
+
* answer was lost to a reconnect is re-sent, never doubled. A session this
|
|
262
|
+
* client does not follow is followed first, until the turn ends, so the
|
|
263
|
+
* steer's user message, its receipt, reaches it.
|
|
264
|
+
*/
|
|
265
|
+
async steerTurn(params) {
|
|
266
|
+
await this.initialize();
|
|
267
|
+
const { sessionId, turnId } = params;
|
|
268
|
+
// One it cannot subscribe to still takes the steer; only its receipt is lost.
|
|
269
|
+
if (!this.streams.follows(sessionId))
|
|
270
|
+
await this.subscribeTo({ sessionId, turnId }, (ack) => {
|
|
271
|
+
// A turn that is not running subscribes nothing, and is not followed.
|
|
272
|
+
if (ack.activeTurn?.turnId === turnId)
|
|
273
|
+
this.streams.joined(sessionId, ack.headSeq, { turnId });
|
|
274
|
+
}).catch(() => undefined);
|
|
275
|
+
return this.connection.resend(WIRE_METHODS.turnSteer, {
|
|
276
|
+
...params,
|
|
277
|
+
steerId: params.steerId ?? generateUUIDv7(),
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Cancel the session's active turn; resolves once cancellation propagated.
|
|
282
|
+
* Pass `turnId` to make the cancel turn-stamped: a late cancel meant for a
|
|
283
|
+
* finished turn then returns `{outcome: "no_active_turn", activeTurnId}`
|
|
284
|
+
* instead of killing the turn that replaced it. `{outcome: "unconfirmed"}`
|
|
285
|
+
* means the harness did not acknowledge the interrupt — the agent may still
|
|
286
|
+
* be running; `turn.ended` remains the source of truth. A cancel for a
|
|
287
|
+
* turn this client is starting (`runTurn`, `startTurn`) goes out after
|
|
288
|
+
* that start's first send, so one sent right behind the start reaches the
|
|
289
|
+
* turn. After a reconnect a cancel can reach the server before a re-sent
|
|
290
|
+
* start, and is then answered `no_active_turn`.
|
|
291
|
+
*/
|
|
292
|
+
cancelTurn(sessionId, turnId) {
|
|
293
|
+
return this.starts.after(sessionId, turnId, () => this.connection.request(WIRE_METHODS.turnCancel, {
|
|
294
|
+
sessionId,
|
|
295
|
+
...(turnId !== undefined ? { turnId } : {}),
|
|
296
|
+
}));
|
|
297
|
+
}
|
|
298
|
+
/** Answer a `permission.requested` event. */
|
|
299
|
+
async respondPermission(sessionId, requestId, outcome) {
|
|
300
|
+
const { accepted } = await this.connection.request(WIRE_METHODS.permissionRespond, {
|
|
301
|
+
sessionId,
|
|
302
|
+
requestId,
|
|
303
|
+
outcome,
|
|
304
|
+
});
|
|
305
|
+
return accepted;
|
|
306
|
+
}
|
|
307
|
+
/** Answer an `elicitation.requested` event. */
|
|
308
|
+
async respondElicitation(sessionId, requestId, outcome) {
|
|
309
|
+
const { accepted } = await this.connection.request(WIRE_METHODS.elicitationRespond, {
|
|
310
|
+
sessionId,
|
|
311
|
+
requestId,
|
|
312
|
+
outcome,
|
|
313
|
+
});
|
|
314
|
+
return accepted;
|
|
315
|
+
}
|
|
316
|
+
// ---- sessions ------------------------------------------------------------
|
|
317
|
+
/**
|
|
318
|
+
* Watch a session until `unsubscribe` (or its end): its kept events after
|
|
319
|
+
* `afterSeq` reach `onEvent` (and the session's handles), each once and in
|
|
320
|
+
* order, then its open parts, then its frames live; after a redial, what a
|
|
321
|
+
* dropped connection missed. Refused `unknownSession` when the server has
|
|
322
|
+
* no log for it, and `subscriptionLimit` past the sessions a connection may
|
|
323
|
+
* watch.
|
|
324
|
+
*/
|
|
325
|
+
async subscribe(sessionId, options = {}) {
|
|
326
|
+
await this.initialize();
|
|
327
|
+
// What it holds, or `afterSeq`, it catches up from with `events/replay`.
|
|
328
|
+
const answer = await this.subscribeTo({ sessionId }, (ack) => this.streams.joined(sessionId, ack.headSeq, "watch", options.afterSeq));
|
|
329
|
+
return {
|
|
330
|
+
sessionId,
|
|
331
|
+
headSeq: answer.headSeq,
|
|
332
|
+
...(answer.activeTurn && { activeTurn: answer.activeTurn }),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Stop watching a session; `false` when this client did not. A turn of
|
|
337
|
+
* this client's that runs there is still followed to its end.
|
|
338
|
+
*/
|
|
339
|
+
async unsubscribe(sessionId) {
|
|
340
|
+
const watched = this.streams.watches(sessionId);
|
|
341
|
+
this.streams.unwatch(sessionId);
|
|
342
|
+
const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribe, {
|
|
343
|
+
sessionId,
|
|
344
|
+
});
|
|
345
|
+
return unsubscribed || watched;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Every session's frames, live from now, to `onEvent` (observers): no
|
|
349
|
+
* history, the open parts of running turns, and after a redial, the gaps a
|
|
350
|
+
* dropped connection left healed. The client follows every session from
|
|
351
|
+
* the ask until `unsubscribeAll`: a connection that drops before the
|
|
352
|
+
* answer asks the server it redials, whose answer this waits for; it fails
|
|
353
|
+
* when the server refuses it or the client closes.
|
|
354
|
+
*/
|
|
355
|
+
async subscribeAll() {
|
|
356
|
+
// @ref LLP 0008#what-requests-do-to-subscriptions — the intent is recorded at the ask, so every later server is asked
|
|
357
|
+
this.streams.followAll();
|
|
358
|
+
const answered = new Promise((resolve, reject) => this.allAsked.push({ resolve, reject }));
|
|
359
|
+
try {
|
|
360
|
+
await this.initialize();
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
// A dropped connection: its redial asks every session (`subscribeAgain`).
|
|
364
|
+
if (!this.redialing(error))
|
|
365
|
+
this.answeredAll(error);
|
|
366
|
+
return answered;
|
|
367
|
+
}
|
|
368
|
+
void this.requestAll();
|
|
369
|
+
return answered;
|
|
370
|
+
}
|
|
371
|
+
/** Stop following every session (`subscribeAll`); those subscribed by name stay. */
|
|
372
|
+
async unsubscribeAll() {
|
|
373
|
+
this.streams.unfollowAll();
|
|
374
|
+
this.answeredAll();
|
|
375
|
+
const { unsubscribed } = await this.connection.request(WIRE_METHODS.sessionUnsubscribeAll, {});
|
|
376
|
+
return unsubscribed;
|
|
377
|
+
}
|
|
378
|
+
/** Release an idle session's replay history and harness-native resources. */
|
|
379
|
+
async closeSession(sessionId) {
|
|
380
|
+
if (this.turns.running(sessionId))
|
|
381
|
+
throw new Error(`cannot close session ${sessionId} while its turn is active`);
|
|
382
|
+
const { closed } = await this.connection.request(WIRE_METHODS.sessionClose, { sessionId });
|
|
383
|
+
this.streams.forget(sessionId);
|
|
384
|
+
return closed;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Durable servers: let an idle session's agent go (its process, a Codex
|
|
388
|
+
* home it holds) while the session stays open, as after a restart. Its
|
|
389
|
+
* next turn names its native conversation (`config.resumeSessionId`; a turn
|
|
390
|
+
* that does not is refused `resumeRequired`, whose data names it), also a
|
|
391
|
+
* turn another client of the session sends: nothing tells it of the
|
|
392
|
+
* release. `false` when the server holds no open session by that id.
|
|
393
|
+
*/
|
|
394
|
+
async releaseSession(sessionId) {
|
|
395
|
+
await this.initialize();
|
|
396
|
+
const { released } = await this.connection.request(WIRE_METHODS.sessionRelease, {
|
|
397
|
+
sessionId,
|
|
398
|
+
});
|
|
399
|
+
return released;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* The models a harness offers for the login and folder a turn with the same
|
|
403
|
+
* `cwd`, `env` and `apiKey` would use. `source: "catalog"` (with `error`)
|
|
404
|
+
* means the CLI did not answer and the list is agent-server's built-in one,
|
|
405
|
+
* as it is while the harness's CLI is not installed yet: a read installs
|
|
406
|
+
* nothing (`prepareClis` does), and the first list after the install is live.
|
|
407
|
+
*/
|
|
408
|
+
listModels(params) {
|
|
409
|
+
return this.connection.request(WIRE_METHODS.modelsList, params);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Where each harness's CLI is on the server (every harness when absent):
|
|
413
|
+
* `ready`, `missing` (what its first turn installs), `installing`,
|
|
414
|
+
* `failed` (with `error`) or `unmanaged`. Installs nothing.
|
|
415
|
+
*/
|
|
416
|
+
async listClis(harnesses) {
|
|
417
|
+
await this.initialize();
|
|
418
|
+
const { clis } = await this.connection.request(WIRE_METHODS.clisList, {
|
|
419
|
+
...(harnesses && { harnesses }),
|
|
420
|
+
});
|
|
421
|
+
return clis;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Install each harness's CLI on the server now, so a first turn does not
|
|
425
|
+
* wait for it, and answer once each is ready or failed. The server answers
|
|
426
|
+
* `clis/prepare` at once, since an install outlasts a request's timeout;
|
|
427
|
+
* this waits for `clis/progress` to say an install ended, asking
|
|
428
|
+
* `clis/list` then and every few seconds, across a redial to the same
|
|
429
|
+
* server. Safe to call again: a running install is joined. `signal` stops
|
|
430
|
+
* the waiting, not the install.
|
|
431
|
+
*/
|
|
432
|
+
async prepareClis(harnesses, options = {}) {
|
|
433
|
+
const { signal } = options;
|
|
434
|
+
signal?.throwIfAborted();
|
|
435
|
+
// Before the first request: a redial asks again only of the server it knows.
|
|
436
|
+
await this.initialize();
|
|
437
|
+
const which = { ...(harnesses && { harnesses }) };
|
|
438
|
+
let wake = () => { };
|
|
439
|
+
const off = this.progress.add(({ phase }) => {
|
|
440
|
+
if (phase === "ready" || phase === "failed")
|
|
441
|
+
wake();
|
|
442
|
+
});
|
|
443
|
+
/** `work`, or the signal's reason once it aborts. */
|
|
444
|
+
const unlessAborted = (work) => {
|
|
445
|
+
if (!signal)
|
|
446
|
+
return work(new Promise(() => { }));
|
|
447
|
+
let stop = () => { };
|
|
448
|
+
const aborted = new Promise((_, reject) => {
|
|
449
|
+
stop = () => reject(signal.reason);
|
|
450
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
451
|
+
});
|
|
452
|
+
return work(aborted).finally(() => signal.removeEventListener("abort", stop));
|
|
453
|
+
};
|
|
454
|
+
try {
|
|
455
|
+
let { clis } = await unlessAborted((aborted) => Promise.race([this.connection.resend(WIRE_METHODS.clisPrepare, which), aborted]));
|
|
456
|
+
while (clis.some((cli) => cli.state === "installing")) {
|
|
457
|
+
({ clis } = await unlessAborted(async (aborted) => {
|
|
458
|
+
let timer;
|
|
459
|
+
try {
|
|
460
|
+
await Promise.race([
|
|
461
|
+
new Promise((resolve) => {
|
|
462
|
+
timer = setTimeout(resolve, PREPARE_POLL_MS);
|
|
463
|
+
wake = resolve;
|
|
464
|
+
}),
|
|
465
|
+
aborted,
|
|
466
|
+
]);
|
|
467
|
+
}
|
|
468
|
+
finally {
|
|
469
|
+
clearTimeout(timer);
|
|
470
|
+
}
|
|
471
|
+
return Promise.race([this.connection.resend(WIRE_METHODS.clisList, which), aborted]);
|
|
472
|
+
}));
|
|
473
|
+
}
|
|
474
|
+
return clis;
|
|
475
|
+
}
|
|
476
|
+
finally {
|
|
477
|
+
off();
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
/** Fetch kept events (`seq >= fromSeq`) without touching what the client follows.
|
|
481
|
+
* A durable server answers a page at a time: `hasMore` asks for the next. */
|
|
482
|
+
replay(sessionId, fromSeq) {
|
|
483
|
+
return this.connection.request(WIRE_METHODS.eventsReplay, { sessionId, fromSeq });
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* The session's kept events from `fromSeq` through `throughSeq` (default:
|
|
487
|
+
* the last), oldest first: every page `replay` answers. Fails
|
|
488
|
+
* `EventGapError` when some of them were evicted.
|
|
489
|
+
*/
|
|
490
|
+
async replayAll(sessionId, fromSeq, throughSeq = Number.POSITIVE_INFINITY) {
|
|
491
|
+
const kept = [];
|
|
492
|
+
for (let from = fromSeq; from <= throughSeq;) {
|
|
493
|
+
const page = await this.replay(sessionId, from);
|
|
494
|
+
if (page.firstAvailableSeq !== null && page.firstAvailableSeq > from)
|
|
495
|
+
throw new EventGapError(`events ${from}..${page.firstAvailableSeq - 1} for session ${sessionId} were evicted`);
|
|
496
|
+
for (const envelope of page.events)
|
|
497
|
+
if (envelope.seq >= from && envelope.seq <= throughSeq)
|
|
498
|
+
kept.push(envelope);
|
|
499
|
+
const last = page.events.at(-1)?.seq;
|
|
500
|
+
if (!page.hasMore || last === undefined || last >= throughSeq)
|
|
501
|
+
break;
|
|
502
|
+
from = last + 1;
|
|
503
|
+
}
|
|
504
|
+
return kept;
|
|
505
|
+
}
|
|
506
|
+
/** Durable servers: a turn's receipt, even for a turn a restart cut off. */
|
|
507
|
+
async getTurn(sessionId, turnId) {
|
|
508
|
+
await this.initialize();
|
|
509
|
+
return this.connection.request(WIRE_METHODS.turnGet, { sessionId, turnId });
|
|
510
|
+
}
|
|
511
|
+
/** Durable servers: the session's head, native id, and whether a restart cut off its last turn. */
|
|
512
|
+
async getSession(sessionId) {
|
|
513
|
+
await this.initialize();
|
|
514
|
+
return this.connection.request(WIRE_METHODS.sessionGet, { sessionId });
|
|
515
|
+
}
|
|
516
|
+
/** Durable servers: lift the fence a restart put on a session. Check first
|
|
517
|
+
* that its native execution stopped: history alone cannot prove that a
|
|
518
|
+
* detached agent or tool process is dead. */
|
|
519
|
+
async confirmSessionStopped(params) {
|
|
520
|
+
await this.initialize();
|
|
521
|
+
const { recovered } = await this.connection.request(WIRE_METHODS.sessionConfirmStopped, params);
|
|
522
|
+
return recovered;
|
|
523
|
+
}
|
|
524
|
+
// ---- logins ----------------------------------------------------------------
|
|
525
|
+
/**
|
|
526
|
+
* Each harness's login on the server (every harness when `harnesses` is
|
|
527
|
+
* absent), for the store and environment a turn with `env` would use:
|
|
528
|
+
* signed in, with what and as whom, signed out, or unknown and why; the
|
|
529
|
+
* logins it offers; and the login under way to that store
|
|
530
|
+
* (`loginUnderWay`), whoever started it, so a second window or a handle
|
|
531
|
+
* whose connection dropped finds it. A read installs nothing: a harness
|
|
532
|
+
* whose CLI is not installed yet is `unknown` with no methods
|
|
533
|
+
* (`prepareClis` installs it, as `login` does).
|
|
534
|
+
*/
|
|
535
|
+
async authStatus(options = {}) {
|
|
536
|
+
await this.initialize();
|
|
537
|
+
const { auth } = await this.connection.request(WIRE_METHODS.authStatus, options);
|
|
538
|
+
return auth;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Start one of a harness's logins through its CLI's own flow: answered
|
|
542
|
+
* once the CLI says where the user signs in (`url`, `userCode`, or from
|
|
543
|
+
* another device `codeUrl`, then `complete` with the code it shows).
|
|
544
|
+
* `done` resolves with the harness's login once it succeeded. Every
|
|
545
|
+
* connection hears it start (`onAuthUpdated`, `auth.loginUnderWay`), and
|
|
546
|
+
* a newer login to the same store cancels it. It installs the harness's
|
|
547
|
+
* CLI first when it is not there yet, inside the 20 s the CLI has to
|
|
548
|
+
* start the login: on a slow network, `prepareClis` first.
|
|
549
|
+
*/
|
|
550
|
+
async login(harness, method, options = {}) {
|
|
551
|
+
await this.initialize();
|
|
552
|
+
return startLogin({
|
|
553
|
+
updates: this.authUpdates,
|
|
554
|
+
connection: this.connection.events,
|
|
555
|
+
complete: (loginId, code) => this.connection.request(WIRE_METHODS.authComplete, { loginId, code }),
|
|
556
|
+
cancel: (loginId) => this.connection.request(WIRE_METHODS.authCancel, { loginId }),
|
|
557
|
+
}, () => this.connection.request(WIRE_METHODS.authLogin, { harness, method, ...options }));
|
|
558
|
+
}
|
|
559
|
+
/** Remove a harness's CLI login on the server; answers its login after. */
|
|
560
|
+
async logout(harness, options = {}) {
|
|
561
|
+
await this.initialize();
|
|
562
|
+
return this.connection.request(WIRE_METHODS.authLogout, { harness, ...options });
|
|
563
|
+
}
|
|
564
|
+
// ---- observing -----------------------------------------------------------
|
|
565
|
+
/** The frames of the sessions this client follows, each once and in order (post-dedupe). */
|
|
566
|
+
onEvent(handler) {
|
|
567
|
+
return this.streams.events.add(handler);
|
|
568
|
+
}
|
|
569
|
+
/** A harness's CLI being installed on the server, whatever caused it (`clis/progress`). */
|
|
570
|
+
onCliProgress(handler) {
|
|
571
|
+
return this.progress.add(handler);
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* A harness's login changed on the server, a login started (no `login`;
|
|
575
|
+
* `auth.loginUnderWay` is it), or a login ended (`login`), whoever caused
|
|
576
|
+
* it (`auth/updated`). Every update's `auth` carries the login then under
|
|
577
|
+
* way to that harness, if any.
|
|
578
|
+
*/
|
|
579
|
+
onAuthUpdated(handler) {
|
|
580
|
+
return this.authUpdates.add(handler);
|
|
581
|
+
}
|
|
582
|
+
/** Observe unrecoverable delivery gaps even when using startTurn without a handle. */
|
|
583
|
+
onEventGap(handler) {
|
|
584
|
+
return this.streams.gaps.add(handler);
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Observe the connection: a drop, each redial attempt, the reconnect (and
|
|
588
|
+
* whether the server is still the one whose logs this client followed),
|
|
589
|
+
* and the end. Handlers run synchronously, before requests waiting on the
|
|
590
|
+
* redial are sent again; one that throws is ignored.
|
|
591
|
+
*/
|
|
592
|
+
onConnection(handler) {
|
|
593
|
+
return this.connection.events.add(handler);
|
|
594
|
+
}
|
|
595
|
+
/** Ask the server to shut down, then close this client. */
|
|
596
|
+
async shutdownServer() {
|
|
597
|
+
await this.connection.request(WIRE_METHODS.shutdown, {}).catch(() => undefined);
|
|
598
|
+
await this.close();
|
|
599
|
+
}
|
|
600
|
+
async close() {
|
|
601
|
+
this.connection.close();
|
|
602
|
+
}
|
|
603
|
+
// ---- internals -------------------------------------------------------------
|
|
604
|
+
handleLine(line, transport) {
|
|
605
|
+
const message = decodeWireMessage(line);
|
|
606
|
+
if (message.kind === "response") {
|
|
607
|
+
this.connection.rpc.settle(message);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (message.kind !== "notification")
|
|
611
|
+
return;
|
|
612
|
+
if (message.method === WIRE_METHODS.event) {
|
|
613
|
+
try {
|
|
614
|
+
// An unknown event TYPE is preserved and still advances seq. Only a
|
|
615
|
+
// malformed envelope or a malformed KNOWN event lands in the catch —
|
|
616
|
+
// a server bug, which must not be papered over by advancing past it.
|
|
617
|
+
this.streams.accept(decodeWireEventEnvelope(message.params), transport);
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
// undeliverable; the next event's seq gap raises it honestly
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
else if (message.method === WIRE_METHODS.sessionOverflow) {
|
|
624
|
+
const notice = SessionOverflowParamsSchema.safeParse(message.params);
|
|
625
|
+
if (notice.success)
|
|
626
|
+
this.streams.overflowed(notice.data);
|
|
627
|
+
}
|
|
628
|
+
else if (message.method === WIRE_METHODS.clisProgress) {
|
|
629
|
+
const progress = HarnessCliProgressSchema.safeParse(message.params);
|
|
630
|
+
if (progress.success)
|
|
631
|
+
this.progress.emit(progress.data);
|
|
632
|
+
}
|
|
633
|
+
else if (message.method === WIRE_METHODS.authUpdated) {
|
|
634
|
+
const update = AuthUpdatedSchema.safeParse(message.params);
|
|
635
|
+
if (update.success)
|
|
636
|
+
this.authUpdates.emit(update.data);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* A start or join's answer, the moment it arrives: the handle's point
|
|
641
|
+
* among the frames. What follows the point waits for the catch-up before it.
|
|
642
|
+
*/
|
|
643
|
+
joinAt(handle, headSeq, follow) {
|
|
644
|
+
this.streams.joined(handle.sessionId, headSeq, follow);
|
|
645
|
+
handle.point = { headSeq, position: this.streams.position };
|
|
646
|
+
handle.catchingUp();
|
|
647
|
+
}
|
|
648
|
+
/** The kept events from `fromSeq` through `headSeq`, replayed into the handle before what followed its point. */
|
|
649
|
+
async catchUp(handle, fromSeq, headSeq) {
|
|
650
|
+
let replayed;
|
|
651
|
+
try {
|
|
652
|
+
replayed = await this.replayAll(handle.sessionId, fromSeq, headSeq);
|
|
653
|
+
}
|
|
654
|
+
catch (error) {
|
|
655
|
+
handle.fail(error instanceof WireRequestError && error.code === WIRE_ERROR_CODES.unknownSession
|
|
656
|
+
? new EventGapError(`session ${handle.sessionId} is unknown to the server (restarted?)`)
|
|
657
|
+
: error);
|
|
658
|
+
throw error;
|
|
659
|
+
}
|
|
660
|
+
handle.caughtUp(replayed.map((envelope) => envelope.event));
|
|
661
|
+
}
|
|
662
|
+
handleOf(handle) {
|
|
663
|
+
const { sessionId, turnId } = handle;
|
|
664
|
+
return {
|
|
665
|
+
sessionId,
|
|
666
|
+
turnId,
|
|
667
|
+
events: handle.queue,
|
|
668
|
+
result: handle.result,
|
|
669
|
+
get catchUp() {
|
|
670
|
+
return handle.catchUp;
|
|
671
|
+
},
|
|
672
|
+
steer: (input, steerId) => this.steerTurn({ sessionId, turnId, input, ...(steerId !== undefined && { steerId }) }),
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Subscribe to the session again (a redial, an overflow), for the turn of
|
|
677
|
+
* this client's it runs or, without one, watching it; what it missed heals
|
|
678
|
+
* by replay. A turn the answer says runs no more ended by its `headSeq`:
|
|
679
|
+
* the session is followed through there, then let go. A refusal is the
|
|
680
|
+
* server's answer: the session is followed no more.
|
|
681
|
+
*/
|
|
682
|
+
async resubscribe(sessionId, turnId) {
|
|
683
|
+
try {
|
|
684
|
+
await this.subscribeTo({ sessionId, ...(turnId !== undefined && { turnId }) }, (ack) => {
|
|
685
|
+
if (turnId === undefined)
|
|
686
|
+
this.streams.joined(sessionId, ack.headSeq, "watch");
|
|
687
|
+
else if (ack.activeTurn?.turnId === turnId)
|
|
688
|
+
this.streams.joined(sessionId, ack.headSeq, { turnId });
|
|
689
|
+
// @ref LLP 0008#client-api — followed through the head, then let go
|
|
690
|
+
else
|
|
691
|
+
this.streams.turnEnded(sessionId, turnId, ack.headSeq);
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
catch (error) {
|
|
695
|
+
// Any other failure: a dropped connection subscribes again once redialed.
|
|
696
|
+
if (!(error instanceof WireRequestError))
|
|
697
|
+
return;
|
|
698
|
+
if (error.code === WIRE_ERROR_CODES.unknownSession)
|
|
699
|
+
this.streams.missing(sessionId);
|
|
700
|
+
else
|
|
701
|
+
this.streams.refused(sessionId, error.message);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
/** A failure a redial heals: the connection dropped and will be redialed, which subscribes again. */
|
|
705
|
+
redialing(error) {
|
|
706
|
+
return (error instanceof ConnectionClosedError && this.connection.redials && !this.connection.closed);
|
|
707
|
+
}
|
|
708
|
+
/** Settle the `subscribeAll` calls waiting for an answer: answered, or failed with `error`. */
|
|
709
|
+
answeredAll(error) {
|
|
710
|
+
for (const waiter of this.allAsked.splice(0))
|
|
711
|
+
if (error === undefined)
|
|
712
|
+
waiter.resolve();
|
|
713
|
+
else
|
|
714
|
+
waiter.reject(error);
|
|
715
|
+
}
|
|
716
|
+
// @ref LLP 0008#what-requests-do-to-subscriptions — a redial subscribes the running turns first
|
|
717
|
+
/** After a redial: every session followed, from what the client holds, pipelined. */
|
|
718
|
+
subscribeAgain() {
|
|
719
|
+
for (const { sessionId, turnId } of this.streams.resubscriptions())
|
|
720
|
+
void this.resubscribe(sessionId, turnId);
|
|
721
|
+
if (this.streams.followsAll)
|
|
722
|
+
void this.requestAll();
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* `session/subscribeAll`, sent now; its answer settles the `subscribeAll`
|
|
726
|
+
* calls waiting. Refused, the client follows every session no more; dropped,
|
|
727
|
+
* the redial asks again.
|
|
728
|
+
*/
|
|
729
|
+
async requestAll() {
|
|
730
|
+
try {
|
|
731
|
+
await this.connection.request(WIRE_METHODS.sessionSubscribeAll, {}, ({ sessions }) => this.streams.joinedAll(sessions));
|
|
732
|
+
this.answeredAll();
|
|
733
|
+
}
|
|
734
|
+
catch (error) {
|
|
735
|
+
if (error instanceof WireRequestError)
|
|
736
|
+
this.streams.refusedAll(error.message);
|
|
737
|
+
if (!this.redialing(error))
|
|
738
|
+
this.answeredAll(error);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
/** `session/subscribe` for one session, `onAnswer` given its point the moment it arrives. */
|
|
742
|
+
subscribeTo(params, onAnswer) {
|
|
743
|
+
return this.connection.request(WIRE_METHODS.sessionSubscribe, params, onAnswer);
|
|
744
|
+
}
|
|
745
|
+
}
|