@zvada/agent-server 0.3.23 → 0.3.24
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 +34 -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 +686 -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 +330 -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 +91 -0
- package/dist/core/processes/lifeline.js +210 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +163 -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 +28 -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 +434 -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 +329 -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 +141 -0
- package/dist/protocol/errors.js +181 -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 +291 -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/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 +24 -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/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- 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 +30 -4
- package/docs/deploy.md +28 -0
- package/docs/harnesses.md +13 -1
- package/package.json +43 -18
- 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 +24 -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/presets.ts +3 -2
- package/src/server/bin.ts +25 -10
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { WIRE_METHODS, WireRefusal, encodeNotification, isLiveEnvelope, } from "../protocol/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Sessions a connection may watch (`session/subscribe`; `session/subscribeAll`
|
|
4
|
+
* counts once). The subscriptions its turns hold do not count.
|
|
5
|
+
*/
|
|
6
|
+
export const DEFAULT_MAX_SUBSCRIPTIONS = 256;
|
|
7
|
+
/**
|
|
8
|
+
* How far behind a connection may fall before the server stops streaming it
|
|
9
|
+
* a session: twice a replay page's budget, so one page of catch-up does not
|
|
10
|
+
* overflow a live subscription.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_MAX_BACKLOG_BYTES = 16 * 1024 * 1024;
|
|
13
|
+
// @ref LLP 0008#design-subscriptions — a connection receives the sessions it subscribes to
|
|
14
|
+
/**
|
|
15
|
+
* The connections the server serves, and the sessions each receives. A
|
|
16
|
+
* session's frames go to the connections subscribed to it, or to every
|
|
17
|
+
* session; filtering delivery, not an authorization boundary. A connection
|
|
18
|
+
* that falls `maxBacklogBytes` behind stops receiving the session it fell
|
|
19
|
+
* behind on (`session/overflow`): every frame it then misses is recoverable,
|
|
20
|
+
* a kept event by replay and a delta by the open part a subscription sends.
|
|
21
|
+
*/
|
|
22
|
+
export class Subscriptions {
|
|
23
|
+
limits;
|
|
24
|
+
connections = new Map();
|
|
25
|
+
constructor(limits) {
|
|
26
|
+
this.limits = limits;
|
|
27
|
+
}
|
|
28
|
+
attach(transport) {
|
|
29
|
+
this.connections.set(transport, {
|
|
30
|
+
sessions: new Map(),
|
|
31
|
+
watched: new Set(),
|
|
32
|
+
turns: new Map(),
|
|
33
|
+
all: false,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/** The connection closed: its subscriptions die with it. */
|
|
37
|
+
detach(transport) {
|
|
38
|
+
this.connections.delete(transport);
|
|
39
|
+
}
|
|
40
|
+
transports() {
|
|
41
|
+
return [...this.connections.keys()];
|
|
42
|
+
}
|
|
43
|
+
// @ref LLP 0008#caps — the cap bounds what a connection watches, not the turns it runs
|
|
44
|
+
/**
|
|
45
|
+
* Stream `sessionId` to `transport` from `headSeq`. A watch is refused past
|
|
46
|
+
* the cap, before anything changes, and counts from then on, a session
|
|
47
|
+
* first subscribed for its turn included. A turn's subscription is never
|
|
48
|
+
* refused and ends with the turn: each turn is work the caller runs, and
|
|
49
|
+
* bounds itself, and the backlog bound still bounds what the connection is
|
|
50
|
+
* sent.
|
|
51
|
+
*/
|
|
52
|
+
subscribe(transport, sessionId, headSeq, scope) {
|
|
53
|
+
const connection = this.connections.get(transport);
|
|
54
|
+
if (!connection)
|
|
55
|
+
return;
|
|
56
|
+
if (scope !== "watch")
|
|
57
|
+
connection.turns.set(sessionId, scope.turnId);
|
|
58
|
+
else if (!connection.watched.has(sessionId)) {
|
|
59
|
+
this.assertBelowCap(connection);
|
|
60
|
+
connection.watched.add(sessionId);
|
|
61
|
+
}
|
|
62
|
+
connection.sessions.set(sessionId, headSeq);
|
|
63
|
+
}
|
|
64
|
+
subscribeAll(transport) {
|
|
65
|
+
const connection = this.connections.get(transport);
|
|
66
|
+
if (!connection || connection.all)
|
|
67
|
+
return;
|
|
68
|
+
this.assertBelowCap(connection);
|
|
69
|
+
connection.all = true;
|
|
70
|
+
}
|
|
71
|
+
/** Stop watching the session; a running turn's own subscription lasts until the turn ends. */
|
|
72
|
+
unsubscribe(transport, sessionId) {
|
|
73
|
+
const connection = this.connections.get(transport);
|
|
74
|
+
if (!connection?.watched.delete(sessionId))
|
|
75
|
+
return false;
|
|
76
|
+
if (!connection.turns.has(sessionId))
|
|
77
|
+
connection.sessions.delete(sessionId);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
unsubscribeAll(transport) {
|
|
81
|
+
const connection = this.connections.get(transport);
|
|
82
|
+
if (!connection?.all)
|
|
83
|
+
return false;
|
|
84
|
+
connection.all = false;
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* One frame of a session, to every connection that receives the session.
|
|
89
|
+
* After a `turn.ended`, the connections subscribed for that turn alone are
|
|
90
|
+
* subscribed no more; after `session.ended`, none is: a reused volatile id
|
|
91
|
+
* starts with none.
|
|
92
|
+
*/
|
|
93
|
+
deliver(envelope) {
|
|
94
|
+
const { sessionId, event } = envelope;
|
|
95
|
+
let line;
|
|
96
|
+
for (const [transport, connection] of this.connections) {
|
|
97
|
+
if (!receives(connection, sessionId))
|
|
98
|
+
continue;
|
|
99
|
+
line ??= encodeNotification(WIRE_METHODS.event, envelope);
|
|
100
|
+
this.send(transport, connection, envelope, line);
|
|
101
|
+
}
|
|
102
|
+
if (event.type === "session.ended")
|
|
103
|
+
for (const connection of this.connections.values())
|
|
104
|
+
drop(connection, sessionId);
|
|
105
|
+
else if (event.type === "turn.ended")
|
|
106
|
+
for (const connection of this.connections.values()) {
|
|
107
|
+
if (connection.turns.get(sessionId) !== event.turnId)
|
|
108
|
+
continue;
|
|
109
|
+
connection.turns.delete(sessionId);
|
|
110
|
+
if (!connection.watched.has(sessionId))
|
|
111
|
+
connection.sessions.delete(sessionId);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* A server's own notification, to every connection whatever it follows
|
|
116
|
+
* (`clis/progress`). Small and rare, so no backlog bound; one transport
|
|
117
|
+
* that throws keeps no other from it.
|
|
118
|
+
*/
|
|
119
|
+
notifyAll(method, params) {
|
|
120
|
+
const line = encodeNotification(method, params);
|
|
121
|
+
for (const transport of this.connections.keys()) {
|
|
122
|
+
try {
|
|
123
|
+
transport.send(line);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// Its own failure.
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** Frames for one connection only: the open parts that follow its subscription. */
|
|
131
|
+
sendTo(transport, envelopes) {
|
|
132
|
+
const connection = this.connections.get(transport);
|
|
133
|
+
for (const envelope of envelopes) {
|
|
134
|
+
// An overflow on the first of them drops the rest with the subscription.
|
|
135
|
+
if (!connection || !receives(connection, envelope.sessionId))
|
|
136
|
+
continue;
|
|
137
|
+
this.send(transport, connection, envelope, encodeNotification(WIRE_METHODS.event, envelope));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
assertBelowCap(connection) {
|
|
141
|
+
const held = connection.watched.size + (connection.all ? 1 : 0);
|
|
142
|
+
if (held >= this.limits.maxSubscriptions)
|
|
143
|
+
throw new WireRefusal("subscriptionLimit", `this connection watches ${held} sessions; unsubscribe one first`, { limit: this.limits.maxSubscriptions });
|
|
144
|
+
}
|
|
145
|
+
send(transport, connection, envelope, line) {
|
|
146
|
+
// @ref LLP 0008#backpressure-and-overflow — over the bound, drop the subscription, not the frame's recovery
|
|
147
|
+
if ((transport.bufferedAmount?.() ?? 0) > this.limits.maxBacklogBytes) {
|
|
148
|
+
this.overflow(transport, connection, envelope.sessionId);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
transport.send(line);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
// One faulty transport must not starve the others; a kept event is in
|
|
156
|
+
// the session log, so the client heals via replay.
|
|
157
|
+
}
|
|
158
|
+
if (!isLiveEnvelope(envelope) && connection.sessions.has(envelope.sessionId))
|
|
159
|
+
connection.sessions.set(envelope.sessionId, envelope.seq);
|
|
160
|
+
}
|
|
161
|
+
/** Stop streaming the session (and, under `session/subscribeAll`, every session) to a connection this far behind. */
|
|
162
|
+
overflow(transport, connection, sessionId) {
|
|
163
|
+
const notices = [];
|
|
164
|
+
const lastSeq = connection.sessions.get(sessionId);
|
|
165
|
+
if (lastSeq !== undefined) {
|
|
166
|
+
drop(connection, sessionId);
|
|
167
|
+
notices.push({ sessionId, lastSeq });
|
|
168
|
+
}
|
|
169
|
+
if (connection.all) {
|
|
170
|
+
connection.all = false;
|
|
171
|
+
notices.push({ all: true });
|
|
172
|
+
}
|
|
173
|
+
for (const notice of notices) {
|
|
174
|
+
try {
|
|
175
|
+
transport.send(encodeNotification(WIRE_METHODS.sessionOverflow, notice));
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// A transport that cannot take the notice is closing: its close drops the rest.
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const receives = (connection, sessionId) => connection.all || connection.sessions.has(sessionId);
|
|
184
|
+
/** The connection's subscription to the session ends, however it was made. */
|
|
185
|
+
function drop(connection, sessionId) {
|
|
186
|
+
connection.sessions.delete(sessionId);
|
|
187
|
+
connection.watched.delete(sessionId);
|
|
188
|
+
connection.turns.delete(sessionId);
|
|
189
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/// <reference types="bun" />
|
|
2
|
+
import { timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { isLoopbackHost } from "../core/utils/loopback.js";
|
|
5
|
+
import { channelTransport, pushNdjsonLines } from "../protocol/index.js";
|
|
6
|
+
/**
|
|
7
|
+
* NDJSON over stdio — for a parent process that spawns the server and owns its
|
|
8
|
+
* pipes (deus-machine's model). Nothing else may write to stdout in this mode;
|
|
9
|
+
* logs belong on stderr.
|
|
10
|
+
*/
|
|
11
|
+
export function stdioTransport(stdin = process.stdin,
|
|
12
|
+
/** `writableLength`, where the stream has one, bounds how far behind a subscription may fall. */
|
|
13
|
+
stdout = process.stdout) {
|
|
14
|
+
const rl = createInterface({ input: stdin, terminal: false });
|
|
15
|
+
const { transport, push, end } = channelTransport({
|
|
16
|
+
send: (line) => void stdout.write(`${line}\n`),
|
|
17
|
+
close: () => rl.close(),
|
|
18
|
+
bufferedAmount: () => stdout.writableLength ?? 0,
|
|
19
|
+
});
|
|
20
|
+
rl.on("line", push);
|
|
21
|
+
rl.on("close", () => end("stdin closed"));
|
|
22
|
+
// A dead parent pipe (EPIPE) must route through the close path — an
|
|
23
|
+
// unhandled stream 'error' would crash the process instead.
|
|
24
|
+
stdin.on("error", (err) => end(`stdin error: ${err.message}`));
|
|
25
|
+
stdout.on("error", (err) => end(`stdout error: ${err.message}`));
|
|
26
|
+
return transport;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* How far past the server's backlog bound (`maxBacklogBytes`) a listener's
|
|
30
|
+
* socket may buffer before Bun closes it: room for the frame that crossed the
|
|
31
|
+
* bound, the `session/overflow` notice behind it, and the responses after it.
|
|
32
|
+
*/
|
|
33
|
+
const SOCKET_HEADROOM_BYTES = 64 * 1024 * 1024;
|
|
34
|
+
/** A WebSocket as a wire transport: its frames come in line by line, each line goes out as a frame. */
|
|
35
|
+
function socketTransport(ws,
|
|
36
|
+
/** What the socket has yet to write out. */
|
|
37
|
+
bufferedAmount) {
|
|
38
|
+
const { transport, push, end } = channelTransport({
|
|
39
|
+
send: (line) => void ws.send(line),
|
|
40
|
+
close: () => ws.close(),
|
|
41
|
+
bufferedAmount,
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
transport,
|
|
45
|
+
received: (data) => pushNdjsonLines(push, data),
|
|
46
|
+
closed: () => end("socket closed"),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** An origin as a browser sends it: lowercase `scheme://host[:port]`, nothing after. */
|
|
50
|
+
const ORIGIN = /^[a-z][a-z\d+.-]*:\/\/(?:[a-z\d.-]+|\[[\da-f:.]+\])(?::\d{1,5})?$/;
|
|
51
|
+
/**
|
|
52
|
+
* Throws when `opts` would open a listener to someone it cannot tell from its
|
|
53
|
+
* client: an `Error` whose `code` says why, `emptyToken`, `tokenRequired` (a
|
|
54
|
+
* host beyond loopback without a token) or `invalidOrigin` (an allowed origin
|
|
55
|
+
* no browser sends). `listen` calls it before it binds; a host calls it first
|
|
56
|
+
* to refuse its options before it starts anything, in its own words.
|
|
57
|
+
*/
|
|
58
|
+
export function assertListenOptions(opts) {
|
|
59
|
+
const hostname = opts.hostname ?? "127.0.0.1";
|
|
60
|
+
if (opts.token === "")
|
|
61
|
+
throw optionsError("emptyToken", "the listener's token is empty");
|
|
62
|
+
// @ref LLP 0001#d16--a-listener-answers-native-clients-only-and-needs-a-token-beyond-loopback
|
|
63
|
+
if (opts.token === undefined && !isLoopbackHost(hostname))
|
|
64
|
+
throw optionsError("tokenRequired", `listening on ${hostname} can be reached from other machines, so it needs a token (ListenOptions.token); or listen on 127.0.0.1`);
|
|
65
|
+
for (const origin of opts.allowedOrigins ?? [])
|
|
66
|
+
if (!ORIGIN.test(origin))
|
|
67
|
+
throw optionsError("invalidOrigin", `${JSON.stringify(origin)} is not an origin: allow each as a browser sends it, scheme://host[:port] (no path, wildcard or null)`);
|
|
68
|
+
}
|
|
69
|
+
function optionsError(code, message) {
|
|
70
|
+
return Object.assign(new Error(message), { code });
|
|
71
|
+
}
|
|
72
|
+
/** What refuses an upgrade before it is one: a browser not allowed, or one without the token. */
|
|
73
|
+
function upgradeGuard(opts) {
|
|
74
|
+
const allowed = new Set(opts.allowedOrigins);
|
|
75
|
+
const token = opts.token === undefined ? undefined : Buffer.from(opts.token);
|
|
76
|
+
return (req) => {
|
|
77
|
+
// @ref LLP 0001#d16--a-listener-answers-native-clients-only-and-needs-a-token-beyond-loopback
|
|
78
|
+
// Any page may open a WebSocket to localhost (CORS does not apply), and
|
|
79
|
+
// a browser names the page's origin on every one; a native client sends none.
|
|
80
|
+
const origin = req.headers.get("origin");
|
|
81
|
+
if (origin !== null && !allowed.has(origin))
|
|
82
|
+
return new Response("origin not allowed", { status: 403 });
|
|
83
|
+
if (token && !carries(req.headers.get("authorization"), token))
|
|
84
|
+
return new Response("unauthorized", {
|
|
85
|
+
status: 401,
|
|
86
|
+
headers: { "www-authenticate": "Bearer" },
|
|
87
|
+
});
|
|
88
|
+
return undefined;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** `Authorization: Bearer <token>`, compared in constant time. */
|
|
92
|
+
function carries(authorization, token) {
|
|
93
|
+
const given = /^bearer +(.*)$/i.exec(authorization ?? "")?.[1];
|
|
94
|
+
if (given === undefined)
|
|
95
|
+
return false;
|
|
96
|
+
const bytes = Buffer.from(given);
|
|
97
|
+
return bytes.length === token.length && timingSafeEqual(bytes, token);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Accept WebSocket clients (agnt's model: the consumer connects to us). Each
|
|
101
|
+
* accepted socket becomes an attached transport, which receives the sessions
|
|
102
|
+
* it subscribes to. It answers native clients, and browsers only from
|
|
103
|
+
* `allowedOrigins`; beyond loopback it requires a `token`. Bun only: under
|
|
104
|
+
* any other runtime it throws an error that says what works there.
|
|
105
|
+
*/
|
|
106
|
+
export function listen(server, opts = {}) {
|
|
107
|
+
assertListenOptions(opts);
|
|
108
|
+
if (!("Bun" in globalThis))
|
|
109
|
+
throw new Error("listen needs Bun (its WebSocket server is Bun.serve): run under Bun, or here serve the wire over stdio (stdioTransport), dial out to the client (dial), or attach each socket of a WebSocket server of your own (channelTransport, server.attach)");
|
|
110
|
+
const guard = upgradeGuard(opts);
|
|
111
|
+
const bun = Bun.serve({
|
|
112
|
+
port: opts.port ?? 0,
|
|
113
|
+
hostname: opts.hostname ?? "127.0.0.1",
|
|
114
|
+
fetch(req, srv) {
|
|
115
|
+
if (opts.path && new URL(req.url).pathname !== opts.path) {
|
|
116
|
+
return new Response("not found", { status: 404 });
|
|
117
|
+
}
|
|
118
|
+
const refused = guard(req);
|
|
119
|
+
if (refused)
|
|
120
|
+
return refused;
|
|
121
|
+
return srv.upgrade(req, { data: {} })
|
|
122
|
+
? undefined
|
|
123
|
+
: new Response("websocket upgrade required", { status: 426 });
|
|
124
|
+
},
|
|
125
|
+
websocket: {
|
|
126
|
+
// Above the server's own bound: the overflow notice it sends there is
|
|
127
|
+
// never dropped by Bun's (16 MiB by default, the bound's own default).
|
|
128
|
+
backpressureLimit: server.maxBacklogBytes + SOCKET_HEADROOM_BYTES,
|
|
129
|
+
// @ref LLP 0008#backpressure-and-overflow — a connection is told it overflowed, or closed
|
|
130
|
+
// Past it, a send Bun would drop closes the connection instead: the
|
|
131
|
+
// client redials and replays rather than wait for a lost line.
|
|
132
|
+
closeOnBackpressureLimit: true,
|
|
133
|
+
open(ws) {
|
|
134
|
+
ws.data.socket = socketTransport(ws, () => ws.getBufferedAmount());
|
|
135
|
+
server.attach(ws.data.socket.transport);
|
|
136
|
+
},
|
|
137
|
+
message(ws, message) {
|
|
138
|
+
ws.data.socket?.received(message);
|
|
139
|
+
},
|
|
140
|
+
close(ws) {
|
|
141
|
+
ws.data.socket?.closed();
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
const port = bun.port ?? opts.port ?? 0;
|
|
146
|
+
const host = bun.hostname ?? opts.hostname ?? "127.0.0.1";
|
|
147
|
+
return {
|
|
148
|
+
// An IPv6 host takes brackets in a URL.
|
|
149
|
+
url: `ws://${host.includes(":") ? `[${host}]` : host}:${port}${opts.path ?? ""}`,
|
|
150
|
+
port,
|
|
151
|
+
stop: () => void bun.stop(true),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Dial out to a consumer and keep redialing on drop (echo's model: the
|
|
156
|
+
* sandboxed server opens a reverse connection to the backend). The remote end
|
|
157
|
+
* replays missed events via `events/replay` after each reconnect.
|
|
158
|
+
*/
|
|
159
|
+
export function dial(server, url, opts = {}) {
|
|
160
|
+
const base = opts.retryDelayMs ?? 500;
|
|
161
|
+
const cap = opts.maxRetryDelayMs ?? 30_000;
|
|
162
|
+
let stopped = false;
|
|
163
|
+
let attempt = 0;
|
|
164
|
+
let current = null;
|
|
165
|
+
let socket = null;
|
|
166
|
+
let timer = null;
|
|
167
|
+
const connect = () => {
|
|
168
|
+
if (stopped)
|
|
169
|
+
return;
|
|
170
|
+
opts.onStateChange?.("connecting");
|
|
171
|
+
const ws = opts.headers ? new WebSocket(url, { headers: opts.headers }) : new WebSocket(url);
|
|
172
|
+
socket = ws;
|
|
173
|
+
const wire = socketTransport(ws, () => ws.bufferedAmount);
|
|
174
|
+
ws.addEventListener("open", () => {
|
|
175
|
+
if (stopped) {
|
|
176
|
+
ws.close();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
attempt = 0;
|
|
180
|
+
current = wire.transport;
|
|
181
|
+
server.attach(wire.transport);
|
|
182
|
+
opts.onStateChange?.("connected");
|
|
183
|
+
});
|
|
184
|
+
ws.addEventListener("message", (ev) => wire.received(ev.data));
|
|
185
|
+
ws.addEventListener("close", () => {
|
|
186
|
+
wire.closed();
|
|
187
|
+
if (socket === ws)
|
|
188
|
+
socket = null;
|
|
189
|
+
if (current === wire.transport)
|
|
190
|
+
current = null;
|
|
191
|
+
if (stopped)
|
|
192
|
+
return;
|
|
193
|
+
opts.onStateChange?.("closed");
|
|
194
|
+
attempt += 1;
|
|
195
|
+
timer = setTimeout(connect, Math.min(cap, base * 2 ** Math.min(attempt - 1, 6)));
|
|
196
|
+
});
|
|
197
|
+
// A close event always follows; nothing to do here.
|
|
198
|
+
ws.addEventListener("error", () => { });
|
|
199
|
+
};
|
|
200
|
+
connect();
|
|
201
|
+
return {
|
|
202
|
+
stop() {
|
|
203
|
+
stopped = true;
|
|
204
|
+
if (timer)
|
|
205
|
+
clearTimeout(timer);
|
|
206
|
+
if (current)
|
|
207
|
+
current.close();
|
|
208
|
+
else
|
|
209
|
+
socket?.close();
|
|
210
|
+
socket = null;
|
|
211
|
+
current = null;
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { AgentServerError, UnsupportedAttachmentError } from "../core/index.js";
|
|
2
|
+
import { WIRE_ERROR_CODES, WireRefusal, isWireErrorName, } from "../protocol/index.js";
|
|
3
|
+
/** Parse a request's params, or refuse them as `invalidParams`. */
|
|
4
|
+
export function parseParams(schema, params) {
|
|
5
|
+
const parsed = schema.safeParse(params);
|
|
6
|
+
if (!parsed.success)
|
|
7
|
+
throw new WireRefusal("invalidParams", "invalid params", parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })));
|
|
8
|
+
return parsed.data;
|
|
9
|
+
}
|
|
10
|
+
/** The error response for anything a handler threw: a refusal answers with the
|
|
11
|
+
* wire error it names, the engine's own refusals with theirs, and everything
|
|
12
|
+
* else is an `internalError`. */
|
|
13
|
+
export function wireErrorOf(error) {
|
|
14
|
+
if (error instanceof WireRefusal) {
|
|
15
|
+
const refusal = error;
|
|
16
|
+
return { code: WIRE_ERROR_CODES[refusal.code], message: refusal.message, data: refusal.data };
|
|
17
|
+
}
|
|
18
|
+
if (error instanceof AgentServerError && isWireErrorName(error.code))
|
|
19
|
+
return { code: WIRE_ERROR_CODES[error.code], message: error.message, data: error.data };
|
|
20
|
+
if (error instanceof UnsupportedAttachmentError)
|
|
21
|
+
return { code: WIRE_ERROR_CODES.invalidParams, message: error.message };
|
|
22
|
+
return {
|
|
23
|
+
code: WIRE_ERROR_CODES.internalError,
|
|
24
|
+
message: error instanceof Error ? error.message : String(error),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { canonicalJson, historyRecordPreimage, historyRootPreimage, } from "../protocol/index.js";
|
|
3
|
+
/** Lowercase hex sha256: history versions, turn and commit fingerprints. */
|
|
4
|
+
export const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
5
|
+
const toHead = (row) => ({
|
|
6
|
+
// Written by this store from a validated descriptor.
|
|
7
|
+
descriptor: JSON.parse(row.descriptor),
|
|
8
|
+
version: {
|
|
9
|
+
sourceId: row.source_id,
|
|
10
|
+
sessionId: row.session_id,
|
|
11
|
+
seq: row.head_seq,
|
|
12
|
+
hash: row.head_hash,
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
/**
|
|
16
|
+
* Every history a store holds: its descriptor, its head, and its hash-chained
|
|
17
|
+
* records. The only code that touches the `histories` and `events` tables.
|
|
18
|
+
* Writes run inside the caller's transaction.
|
|
19
|
+
*/
|
|
20
|
+
export class EventLog {
|
|
21
|
+
db;
|
|
22
|
+
constructor(db) {
|
|
23
|
+
this.db = db;
|
|
24
|
+
}
|
|
25
|
+
head(ref) {
|
|
26
|
+
const row = this.db.one("SELECT * FROM histories WHERE source_id=? AND session_id=?", ref.sourceId, ref.sessionId);
|
|
27
|
+
return row && toHead(row);
|
|
28
|
+
}
|
|
29
|
+
/** Heads in (sourceId, sessionId) order, after `after` when given. */
|
|
30
|
+
heads(after, limit) {
|
|
31
|
+
const rows = after
|
|
32
|
+
? this.db.all("SELECT * FROM histories WHERE source_id>? OR (source_id=? AND session_id>?) ORDER BY source_id,session_id LIMIT ?", after.sourceId, after.sourceId, after.sessionId, limit)
|
|
33
|
+
: this.db.all("SELECT * FROM histories ORDER BY source_id,session_id LIMIT ?", limit);
|
|
34
|
+
return rows.map(toHead);
|
|
35
|
+
}
|
|
36
|
+
/** A new, empty history. */
|
|
37
|
+
create(descriptor) {
|
|
38
|
+
const root = this.root(descriptor);
|
|
39
|
+
this.db.run("INSERT INTO histories(source_id,session_id,descriptor,head_seq,head_hash) VALUES (?,?,?,0,?)", descriptor.sourceId, descriptor.sessionId, canonicalJson(descriptor), root.hash);
|
|
40
|
+
return root;
|
|
41
|
+
}
|
|
42
|
+
/** A history's version 0. */
|
|
43
|
+
root(descriptor) {
|
|
44
|
+
const { sourceId, sessionId } = descriptor;
|
|
45
|
+
return { sourceId, sessionId, seq: 0, hash: sha256(historyRootPreimage(descriptor)) };
|
|
46
|
+
}
|
|
47
|
+
/** Records `bodies` (canonical event JSON) after `head`, the current head; returns the new one. */
|
|
48
|
+
append(head, bodies) {
|
|
49
|
+
let { seq, hash } = head;
|
|
50
|
+
for (const body of bodies) {
|
|
51
|
+
seq += 1;
|
|
52
|
+
hash = sha256(historyRecordPreimage(hash, seq, body));
|
|
53
|
+
this.db.run("INSERT INTO events(source_id,session_id,seq,hash,body) VALUES (?,?,?,?,?)", head.sourceId, head.sessionId, seq, hash, body);
|
|
54
|
+
}
|
|
55
|
+
this.db.run("UPDATE histories SET head_seq=?, head_hash=? WHERE source_id=? AND session_id=?", seq, hash, head.sourceId, head.sessionId);
|
|
56
|
+
return { ...head, seq, hash };
|
|
57
|
+
}
|
|
58
|
+
/** The version at `seq`, when the history reaches it. */
|
|
59
|
+
at(ref, seq) {
|
|
60
|
+
if (seq === 0) {
|
|
61
|
+
const head = this.head(ref);
|
|
62
|
+
return head && this.root(head.descriptor);
|
|
63
|
+
}
|
|
64
|
+
const row = this.db.one("SELECT hash FROM events WHERE source_id=? AND session_id=? AND seq=?", ref.sourceId, ref.sessionId, seq);
|
|
65
|
+
return row && { sourceId: ref.sourceId, sessionId: ref.sessionId, seq, hash: row.hash };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The records after `afterSeq` through `throughSeq` that fit in `maxBytes`
|
|
69
|
+
* together, oldest first and at most `limit`: each costs its body and the
|
|
70
|
+
* `overhead` its reader puts around it (the `index`th of the page). A first
|
|
71
|
+
* record too large alone comes alone when `oversizedFirst`, else the page
|
|
72
|
+
* is empty.
|
|
73
|
+
*/
|
|
74
|
+
page(ref, afterSeq, throughSeq, opts) {
|
|
75
|
+
const rows = [];
|
|
76
|
+
let bytes = 0;
|
|
77
|
+
for (const row of this.records(ref, afterSeq, throughSeq, opts.limit)) {
|
|
78
|
+
bytes += Buffer.byteLength(row.body) + opts.overhead(row, rows.length);
|
|
79
|
+
if (bytes > opts.maxBytes && (rows.length > 0 || !opts.oversizedFirst))
|
|
80
|
+
break;
|
|
81
|
+
rows.push(row);
|
|
82
|
+
}
|
|
83
|
+
return rows;
|
|
84
|
+
}
|
|
85
|
+
/** Records after `afterSeq` through `throughSeq`, oldest first. */
|
|
86
|
+
records(ref, afterSeq, throughSeq, limit = -1) {
|
|
87
|
+
return this.db.each("SELECT seq,hash,body FROM events WHERE source_id=? AND session_id=? AND seq>? AND seq<=? ORDER BY seq LIMIT ?", ref.sourceId, ref.sessionId, afterSeq, throughSeq, limit);
|
|
88
|
+
}
|
|
89
|
+
}
|