@agent-socket/sdk 0.1.0
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/LICENSE +190 -0
- package/README.md +122 -0
- package/dist/agents-md.d.ts +13 -0
- package/dist/agents-md.js +39 -0
- package/dist/backoff.d.ts +24 -0
- package/dist/backoff.js +35 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/preamble.d.ts +38 -0
- package/dist/preamble.js +74 -0
- package/dist/session.d.ts +3 -0
- package/dist/session.js +637 -0
- package/dist/transport.d.ts +10 -0
- package/dist/transport.js +48 -0
- package/dist/types.d.ts +210 -0
- package/dist/types.js +2 -0
- package/package.json +38 -0
package/dist/session.js
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
// Session — the live SDK state, owns a WebSocket and routes frames.
|
|
2
|
+
//
|
|
3
|
+
// Public API matches design doc §4.2.
|
|
4
|
+
import { openWs, READY_STATE_OPEN } from "./transport.js";
|
|
5
|
+
import { exponentialBackoff } from "./backoff.js";
|
|
6
|
+
const DEFAULT_BASE_URL = "https://agentsocket.dev";
|
|
7
|
+
const DEFAULT_HEARTBEAT_INTERVAL_MS = 25_000;
|
|
8
|
+
const DEFAULT_HEARTBEAT_TIMEOUT_MS = 50_000;
|
|
9
|
+
// The relay refused a resume: wrong secret, or the session already ended.
|
|
10
|
+
class ResumeRejected extends Error {
|
|
11
|
+
}
|
|
12
|
+
const RESUME_REJECTED_CLOSE = 4401;
|
|
13
|
+
// The relay closed this socket because a resume with our secret replaced it.
|
|
14
|
+
const REPLACED_CLOSE = 4410;
|
|
15
|
+
// Closing a socket whose handshake we abandoned. Not 1000, which tells the
|
|
16
|
+
// relay the app is done and ends the session.
|
|
17
|
+
const HANDSHAKE_ABORT_CLOSE = 4000;
|
|
18
|
+
/** Open a session. Returns a Session object once register_reply { ok } is received. */
|
|
19
|
+
export async function connect(opts) {
|
|
20
|
+
const session = new SessionImpl(opts);
|
|
21
|
+
const { resumed } = await session._connectAndRegister();
|
|
22
|
+
// Resumed from a saved secret: adopt the session's live tokens so a later
|
|
23
|
+
// fallback to a fresh session can re-mint them.
|
|
24
|
+
if (resumed)
|
|
25
|
+
await session._adoptTokens().catch(() => { });
|
|
26
|
+
return session;
|
|
27
|
+
}
|
|
28
|
+
class SessionImpl {
|
|
29
|
+
baseUrl;
|
|
30
|
+
appId;
|
|
31
|
+
agentsMd;
|
|
32
|
+
appDescription;
|
|
33
|
+
// Tools by `${METHOD} ${path}` for fast dispatch
|
|
34
|
+
toolsByRoute = new Map();
|
|
35
|
+
toolDefs;
|
|
36
|
+
autoReconnect;
|
|
37
|
+
onDisconnect;
|
|
38
|
+
onSessionChanged;
|
|
39
|
+
onReconnect;
|
|
40
|
+
heartbeatIntervalMs;
|
|
41
|
+
heartbeatTimeoutMs;
|
|
42
|
+
ws = null;
|
|
43
|
+
_sessionId = "";
|
|
44
|
+
_resumeSecret = null;
|
|
45
|
+
// Tokens revoked while disconnected; the resume frame carries them.
|
|
46
|
+
pendingRevokes = new Set();
|
|
47
|
+
registered = false;
|
|
48
|
+
giveUpReconnect = false;
|
|
49
|
+
attempt = 0;
|
|
50
|
+
pendingFrameReplies = new Map();
|
|
51
|
+
// Tokens we've minted in *this* session (for autoReconnect remint)
|
|
52
|
+
myTokens = new Map(); // keyed by full token string
|
|
53
|
+
// updateTools calls run one at a time, in call order.
|
|
54
|
+
toolsChain = Promise.resolve();
|
|
55
|
+
// Callers waiting for the session to be (re)connected.
|
|
56
|
+
connectedWaiters = [];
|
|
57
|
+
// Heartbeat state
|
|
58
|
+
heartbeatPingTimer = null;
|
|
59
|
+
heartbeatTimeoutTimer = null;
|
|
60
|
+
pendingPingId = null;
|
|
61
|
+
constructor(opts) {
|
|
62
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
63
|
+
this.appId = opts.appId;
|
|
64
|
+
this.agentsMd = opts.agentsMd;
|
|
65
|
+
this.appDescription = opts.appDescription ?? "";
|
|
66
|
+
this.toolDefs = opts.tools.map((t) => ({
|
|
67
|
+
...t,
|
|
68
|
+
method: (t.method ?? "POST").toUpperCase(),
|
|
69
|
+
}));
|
|
70
|
+
for (const t of this.toolDefs) {
|
|
71
|
+
this.toolsByRoute.set(`${t.method} ${t.path}`, t.handler);
|
|
72
|
+
}
|
|
73
|
+
this.autoReconnect = opts.autoReconnect ?? true;
|
|
74
|
+
this.onDisconnect = opts.onDisconnect ?? (this.autoReconnect ? exponentialBackoff() : ({ giveUp }) => giveUp());
|
|
75
|
+
this.onSessionChanged = opts.onSessionChanged;
|
|
76
|
+
this.onReconnect = opts.onReconnect;
|
|
77
|
+
if (opts.resume) {
|
|
78
|
+
this._sessionId = opts.resume.sessionId;
|
|
79
|
+
this._resumeSecret = opts.resume.secret;
|
|
80
|
+
}
|
|
81
|
+
this.heartbeatIntervalMs = opts.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
|
|
82
|
+
this.heartbeatTimeoutMs = opts.heartbeatTimeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;
|
|
83
|
+
}
|
|
84
|
+
get sessionId() { return this._sessionId; }
|
|
85
|
+
get resumeSecret() { return this._resumeSecret; }
|
|
86
|
+
get connected() { return this.registered && this.ws !== null && this.ws.readyState === READY_STATE_OPEN; }
|
|
87
|
+
// Resume the current session if we hold its secret; if the relay refuses
|
|
88
|
+
// (4401: bad secret or session ended), fall back to a fresh one at once.
|
|
89
|
+
// Other failures (network, timeout) throw so the caller backs off and the
|
|
90
|
+
// next attempt tries the resume again.
|
|
91
|
+
async _connectAndRegister() {
|
|
92
|
+
if (this._resumeSecret && this._sessionId) {
|
|
93
|
+
try {
|
|
94
|
+
await this._handshake(true);
|
|
95
|
+
return { resumed: true };
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
if (!(e instanceof ResumeRejected))
|
|
99
|
+
throw e;
|
|
100
|
+
this._resumeSecret = null;
|
|
101
|
+
this.pendingRevokes.clear(); // those tokens died with the session
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
await this._handshake(false);
|
|
105
|
+
return { resumed: false };
|
|
106
|
+
}
|
|
107
|
+
async _handshake(resume) {
|
|
108
|
+
const wsUrl = this.baseUrl.replace(/^http/, "ws") + "/v1/_ws"
|
|
109
|
+
+ (resume ? `?session=${encodeURIComponent(this._sessionId)}` : "");
|
|
110
|
+
const ws = openWs(wsUrl);
|
|
111
|
+
this.ws = ws;
|
|
112
|
+
try {
|
|
113
|
+
await this._waitOpen(ws);
|
|
114
|
+
// Always the current tool set: after updateTools, a resume or a fresh
|
|
115
|
+
// session registers the updated tools, not the ones passed to connect().
|
|
116
|
+
const registration = {
|
|
117
|
+
appId: this.appId,
|
|
118
|
+
agentsMd: this.agentsMd,
|
|
119
|
+
appDescription: this.appDescription,
|
|
120
|
+
tools: wireTools(this.toolDefs),
|
|
121
|
+
};
|
|
122
|
+
// The secret goes in the first frame, not the URL, so it stays out of logs.
|
|
123
|
+
this._sendFrame(resume
|
|
124
|
+
? { type: "resume", sessionId: this._sessionId, secret: this._resumeSecret, ...registration, revokeTokens: [...this.pendingRevokes] }
|
|
125
|
+
: { type: "register", ...registration });
|
|
126
|
+
const reply = await this._waitForRegisterReply(ws, 10_000);
|
|
127
|
+
if (!reply.ok) {
|
|
128
|
+
if (resume && reply.error?.code === "resume_failed")
|
|
129
|
+
throw new ResumeRejected("resume rejected");
|
|
130
|
+
throw new Error(`register failed: ${reply.error?.code ?? "unknown"}`);
|
|
131
|
+
}
|
|
132
|
+
if (this.giveUpReconnect)
|
|
133
|
+
throw new Error("session closed");
|
|
134
|
+
this._sessionId = reply.sessionId;
|
|
135
|
+
this._resumeSecret = typeof reply.resumeSecret === "string" ? reply.resumeSecret : null;
|
|
136
|
+
if (resume)
|
|
137
|
+
this.pendingRevokes.clear();
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
if (resume && e.closeCode === RESUME_REJECTED_CLOSE)
|
|
141
|
+
e = new ResumeRejected("resume rejected");
|
|
142
|
+
// Handlers aren't installed yet, so this close can't trigger a reconnect.
|
|
143
|
+
try {
|
|
144
|
+
ws.close(this.giveUpReconnect ? 1000 : HANDSHAKE_ABORT_CLOSE, "handshake failed");
|
|
145
|
+
}
|
|
146
|
+
catch { }
|
|
147
|
+
if (this.ws === ws)
|
|
148
|
+
this.ws = null;
|
|
149
|
+
throw e;
|
|
150
|
+
}
|
|
151
|
+
this._installHandlers(ws);
|
|
152
|
+
this.registered = true;
|
|
153
|
+
this._scheduleNextPing();
|
|
154
|
+
this._settleConnectedWaiters(null);
|
|
155
|
+
}
|
|
156
|
+
// Track the live session's tokens as ours (after resuming from a saved secret).
|
|
157
|
+
async _adoptTokens() {
|
|
158
|
+
for (const t of await this.listAgentTokens()) {
|
|
159
|
+
if (!this.myTokens.has(t.token)) {
|
|
160
|
+
this.myTokens.set(t.token, { token: t.token, url: t.url, label: t.label, mintedAt: t.mintedAt, sessionId: this._sessionId });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// ── Public methods ──────────────────────────────────────────────────
|
|
165
|
+
async mintAgentToken(opts) {
|
|
166
|
+
const id = this._uid();
|
|
167
|
+
this._sendFrame({ type: "mint_agent_token", id, label: opts.label });
|
|
168
|
+
const reply = await this._awaitReply(id, 10_000);
|
|
169
|
+
if (!reply.ok) {
|
|
170
|
+
const code = reply.error?.code ?? "unknown";
|
|
171
|
+
throw new Error(`mint failed: ${code}`);
|
|
172
|
+
}
|
|
173
|
+
const token = reply.token;
|
|
174
|
+
const url = this._rewriteUrl(reply.url);
|
|
175
|
+
const info = {
|
|
176
|
+
token,
|
|
177
|
+
url,
|
|
178
|
+
label: reply.label ?? opts.label,
|
|
179
|
+
mintedAt: Date.now(),
|
|
180
|
+
sessionId: this._sessionId,
|
|
181
|
+
};
|
|
182
|
+
this.myTokens.set(token, info);
|
|
183
|
+
return { token, url, label: info.label, expiresAt: reply.expiresAt ?? null };
|
|
184
|
+
}
|
|
185
|
+
async revokeAgentToken(token) {
|
|
186
|
+
// Forget it first so a reconnect can't re-mint it. While disconnected the
|
|
187
|
+
// relay may be holding the session for a resume, so the resume frame
|
|
188
|
+
// revokes it before the app goes live again.
|
|
189
|
+
const known = this.myTokens.delete(token);
|
|
190
|
+
if (!this.connected) {
|
|
191
|
+
if (this._resumeSecret)
|
|
192
|
+
this.pendingRevokes.add(token);
|
|
193
|
+
return { ok: known };
|
|
194
|
+
}
|
|
195
|
+
const id = this._uid();
|
|
196
|
+
this._sendFrame({ type: "revoke_agent_token", id, token });
|
|
197
|
+
const reply = await this._awaitReply(id, 10_000);
|
|
198
|
+
return { ok: !!reply.ok || known };
|
|
199
|
+
}
|
|
200
|
+
async listAgentTokens() {
|
|
201
|
+
const id = this._uid();
|
|
202
|
+
this._sendFrame({ type: "list_agent_tokens", id });
|
|
203
|
+
const reply = await this._awaitReply(id, 10_000);
|
|
204
|
+
const tokens = reply.tokens ?? [];
|
|
205
|
+
return tokens.map((t) => ({
|
|
206
|
+
token: t.token,
|
|
207
|
+
url: this._rewriteUrl(t.url),
|
|
208
|
+
label: t.label ?? "",
|
|
209
|
+
expiresAt: null,
|
|
210
|
+
mintedAt: t.mintedAt ?? 0,
|
|
211
|
+
}));
|
|
212
|
+
}
|
|
213
|
+
updateTools(tools, agentsMd) {
|
|
214
|
+
const run = () => this._updateTools(tools, agentsMd);
|
|
215
|
+
const p = this.toolsChain.then(run, run);
|
|
216
|
+
this.toolsChain = p.catch(() => { });
|
|
217
|
+
return p;
|
|
218
|
+
}
|
|
219
|
+
async _updateTools(tools, agentsMd) {
|
|
220
|
+
if (!Array.isArray(tools))
|
|
221
|
+
throw new TypeError("updateTools: tools must be an array");
|
|
222
|
+
if (agentsMd !== undefined && typeof agentsMd !== "string")
|
|
223
|
+
throw new TypeError("updateTools: agentsMd must be a string");
|
|
224
|
+
const defs = tools.map((t) => ({ ...t, method: (t.method ?? "POST").toUpperCase() }));
|
|
225
|
+
for (const t of defs) {
|
|
226
|
+
if (typeof t.handler !== "function")
|
|
227
|
+
throw new TypeError(`updateTools: ${t.method} ${t.path} has no handler`);
|
|
228
|
+
}
|
|
229
|
+
for (;;) {
|
|
230
|
+
if (this.giveUpReconnect)
|
|
231
|
+
throw new Error("updateTools: session closed");
|
|
232
|
+
// Disconnected: wait for the reconnect (whose resume re-sends the
|
|
233
|
+
// current tools), then send the update on the new socket.
|
|
234
|
+
if (!this.connected) {
|
|
235
|
+
await this._waitConnected();
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const ws = this.ws;
|
|
239
|
+
// Serve old and new handlers until the relay confirms, so a call routed
|
|
240
|
+
// just after the relay switched still finds its handler.
|
|
241
|
+
const prev = this.toolsByRoute;
|
|
242
|
+
const during = new Map(prev);
|
|
243
|
+
for (const t of defs)
|
|
244
|
+
during.set(`${t.method} ${t.path}`, t.handler);
|
|
245
|
+
this.toolsByRoute = during;
|
|
246
|
+
const id = this._uid();
|
|
247
|
+
this._sendFrame({ type: "update_tools", id, tools: wireTools(defs), ...(agentsMd !== undefined ? { agentsMd } : {}) });
|
|
248
|
+
let reply;
|
|
249
|
+
try {
|
|
250
|
+
reply = await this._awaitReply(id, 10_000);
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
if (this.toolsByRoute === during)
|
|
254
|
+
this.toolsByRoute = prev;
|
|
255
|
+
// The socket dropped before the reply. The relay may or may not have
|
|
256
|
+
// applied it, but the resume replaces its tools with ours (the old
|
|
257
|
+
// set), so just send the update again once reconnected.
|
|
258
|
+
if (this.ws !== ws || !this.connected)
|
|
259
|
+
continue;
|
|
260
|
+
throw e;
|
|
261
|
+
}
|
|
262
|
+
if (!reply.ok) {
|
|
263
|
+
if (this.toolsByRoute === during)
|
|
264
|
+
this.toolsByRoute = prev;
|
|
265
|
+
const code = reply.error?.code ?? "unknown";
|
|
266
|
+
throw Object.assign(new Error(`update_tools failed: ${code}${reply.error?.message ? ` (${reply.error.message})` : ""}`), { code });
|
|
267
|
+
}
|
|
268
|
+
this.toolDefs = defs;
|
|
269
|
+
this.toolsByRoute = new Map(defs.map((t) => [`${t.method} ${t.path}`, t.handler]));
|
|
270
|
+
if (agentsMd !== undefined)
|
|
271
|
+
this.agentsMd = agentsMd;
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
_waitConnected() {
|
|
276
|
+
if (this.connected)
|
|
277
|
+
return Promise.resolve();
|
|
278
|
+
return new Promise((resolve, reject) => this.connectedWaiters.push({ resolve, reject }));
|
|
279
|
+
}
|
|
280
|
+
_settleConnectedWaiters(err) {
|
|
281
|
+
const waiters = this.connectedWaiters;
|
|
282
|
+
this.connectedWaiters = [];
|
|
283
|
+
for (const w of waiters)
|
|
284
|
+
err ? w.reject(err) : w.resolve();
|
|
285
|
+
}
|
|
286
|
+
completeTask(taskId, result) {
|
|
287
|
+
if (typeof taskId !== "string" || taskId.length === 0) {
|
|
288
|
+
throw new Error("completeTask: taskId must be a non-empty string");
|
|
289
|
+
}
|
|
290
|
+
if (!this.connected) {
|
|
291
|
+
throw new Error("completeTask: WS not open");
|
|
292
|
+
}
|
|
293
|
+
const status = result?.status ?? 200;
|
|
294
|
+
const frame = { type: "task_complete", taskId, status, body: result?.body };
|
|
295
|
+
if (result?.headers && typeof result.headers === "object") {
|
|
296
|
+
frame.headers = result.headers;
|
|
297
|
+
}
|
|
298
|
+
this._sendFrame(frame);
|
|
299
|
+
}
|
|
300
|
+
ping() {
|
|
301
|
+
if (!this.connected)
|
|
302
|
+
return;
|
|
303
|
+
if (this.pendingPingId !== null)
|
|
304
|
+
return;
|
|
305
|
+
this._sendPing();
|
|
306
|
+
}
|
|
307
|
+
close() {
|
|
308
|
+
this.giveUpReconnect = true;
|
|
309
|
+
this.registered = false;
|
|
310
|
+
this._teardownHeartbeat();
|
|
311
|
+
this._failPending();
|
|
312
|
+
this._settleConnectedWaiters(new Error("session closed"));
|
|
313
|
+
try {
|
|
314
|
+
this.ws?.close(1000, "client closed");
|
|
315
|
+
}
|
|
316
|
+
catch { }
|
|
317
|
+
this.ws = null;
|
|
318
|
+
}
|
|
319
|
+
// ── Internals ───────────────────────────────────────────────────────
|
|
320
|
+
_uid() { return Math.random().toString(36).slice(2, 12); }
|
|
321
|
+
_waitOpen(ws) {
|
|
322
|
+
if (ws.readyState === READY_STATE_OPEN)
|
|
323
|
+
return Promise.resolve();
|
|
324
|
+
return new Promise((resolve, reject) => {
|
|
325
|
+
const onOpen = () => { cleanup(); resolve(); };
|
|
326
|
+
const onError = (e) => { cleanup(); reject(e instanceof Error ? e : new Error("ws failed to open")); };
|
|
327
|
+
const onClose = () => onError(null);
|
|
328
|
+
const cleanup = () => {
|
|
329
|
+
ws.removeListener("open", onOpen);
|
|
330
|
+
ws.removeListener("error", onError);
|
|
331
|
+
ws.removeListener("close", onClose);
|
|
332
|
+
};
|
|
333
|
+
ws.addListener("open", onOpen);
|
|
334
|
+
ws.addListener("error", onError);
|
|
335
|
+
ws.addListener("close", onClose);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
_installHandlers(ws) {
|
|
339
|
+
ws.addListener("message", (data) => { if (ws === this.ws)
|
|
340
|
+
this._onMessage(String(data)); });
|
|
341
|
+
ws.addListener("close", (...args) => {
|
|
342
|
+
if (ws === this.ws)
|
|
343
|
+
this._onClose(args[0] ?? 1006, args[1] ?? "");
|
|
344
|
+
});
|
|
345
|
+
ws.addListener("error", (_e) => { });
|
|
346
|
+
}
|
|
347
|
+
_onMessage(data) {
|
|
348
|
+
let msg;
|
|
349
|
+
try {
|
|
350
|
+
msg = JSON.parse(data);
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
this._scheduleNextPing(); // any inbound traffic resets the idle timer
|
|
356
|
+
switch (msg.type) {
|
|
357
|
+
case "tool_call":
|
|
358
|
+
void this._handleToolCall(msg);
|
|
359
|
+
return;
|
|
360
|
+
case "ping":
|
|
361
|
+
this._sendFrame({ type: "pong", id: msg.id });
|
|
362
|
+
return;
|
|
363
|
+
case "pong":
|
|
364
|
+
if (msg.id === this.pendingPingId) {
|
|
365
|
+
this.pendingPingId = null;
|
|
366
|
+
if (this.heartbeatTimeoutTimer) {
|
|
367
|
+
clearTimeout(this.heartbeatTimeoutTimer);
|
|
368
|
+
this.heartbeatTimeoutTimer = null;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return;
|
|
372
|
+
default: {
|
|
373
|
+
if (typeof msg.id === "string") {
|
|
374
|
+
const p = this.pendingFrameReplies.get(msg.id);
|
|
375
|
+
if (p) {
|
|
376
|
+
this.pendingFrameReplies.delete(msg.id);
|
|
377
|
+
p.resolve(msg);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
// unmatched — ignore
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
async _handleToolCall(msg) {
|
|
386
|
+
// Validate the frame BEFORE building the route. A malformed tool_call
|
|
387
|
+
// (missing/non-string method or path) used to throw here on
|
|
388
|
+
// `.toUpperCase()` — outside the try below — producing an unhandled
|
|
389
|
+
// rejection (the call site is `void this._handleToolCall(msg)`) AND no
|
|
390
|
+
// tool_reply, so the agent's HTTP request hung until the relay's
|
|
391
|
+
// tool_timeout. Reply with an error instead so the agent gets a prompt
|
|
392
|
+
// response for any frame carrying an id.
|
|
393
|
+
if (typeof msg.method !== "string" || typeof msg.path !== "string") {
|
|
394
|
+
if (typeof msg.id === "string") {
|
|
395
|
+
this._sendFrame({
|
|
396
|
+
type: "tool_reply",
|
|
397
|
+
id: msg.id,
|
|
398
|
+
status: 400,
|
|
399
|
+
body: { error: { code: "bad_tool_call", message: "tool_call requires string method and path" } },
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const route = `${msg.method.toUpperCase()} ${msg.path}`;
|
|
405
|
+
const handler = this.toolsByRoute.get(route);
|
|
406
|
+
if (!handler) {
|
|
407
|
+
this._sendFrame({
|
|
408
|
+
type: "tool_reply",
|
|
409
|
+
id: msg.id,
|
|
410
|
+
status: 404,
|
|
411
|
+
body: { error: { code: "not_found", message: `no handler for ${route}` } },
|
|
412
|
+
});
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const ctx = {
|
|
416
|
+
method: msg.method,
|
|
417
|
+
path: msg.path,
|
|
418
|
+
body: msg.body ?? "",
|
|
419
|
+
headers: msg.headers ?? {},
|
|
420
|
+
};
|
|
421
|
+
try {
|
|
422
|
+
const result = await handler(ctx);
|
|
423
|
+
const { status, body, taskId, headers } = normalizeResult(result);
|
|
424
|
+
const frame = { type: "tool_reply", id: msg.id, status, body };
|
|
425
|
+
if (status === 202 && typeof taskId === "string" && taskId.length > 0) {
|
|
426
|
+
frame.taskId = taskId;
|
|
427
|
+
}
|
|
428
|
+
if (headers && typeof headers === "object") {
|
|
429
|
+
frame.headers = headers;
|
|
430
|
+
}
|
|
431
|
+
this._sendFrame(frame);
|
|
432
|
+
}
|
|
433
|
+
catch (e) {
|
|
434
|
+
// Prefer a duck-typed `.message` over String(e) — handlers that throw
|
|
435
|
+
// plain objects like `{message, code}` (idiomatic in older JS without
|
|
436
|
+
// Error subclasses) otherwise stringify to "[object Object]".
|
|
437
|
+
const eMaybe = e;
|
|
438
|
+
const message = typeof eMaybe?.message === "string"
|
|
439
|
+
? eMaybe.message
|
|
440
|
+
: (e instanceof Error ? e.message : String(e));
|
|
441
|
+
this._sendFrame({
|
|
442
|
+
type: "tool_reply",
|
|
443
|
+
id: msg.id,
|
|
444
|
+
status: 500,
|
|
445
|
+
body: { error: { code: "handler_error", message } },
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
_onClose(code, reason) {
|
|
450
|
+
this.registered = false;
|
|
451
|
+
this._teardownHeartbeat();
|
|
452
|
+
this._failPending();
|
|
453
|
+
this.ws = null;
|
|
454
|
+
// Another connection resumed this session with our secret, so it's theirs
|
|
455
|
+
// now. Start a fresh session on reconnect rather than taking it back.
|
|
456
|
+
if (code === REPLACED_CLOSE) {
|
|
457
|
+
this._resumeSecret = null;
|
|
458
|
+
this.pendingRevokes.clear();
|
|
459
|
+
}
|
|
460
|
+
this._disconnected(reason || "ws closed");
|
|
461
|
+
}
|
|
462
|
+
// The single reconnect path: after a drop and after each failed attempt.
|
|
463
|
+
_disconnected(reason) {
|
|
464
|
+
if (this.giveUpReconnect)
|
|
465
|
+
return;
|
|
466
|
+
this.attempt += 1;
|
|
467
|
+
let resolved = false;
|
|
468
|
+
const reconnect = () => {
|
|
469
|
+
if (resolved)
|
|
470
|
+
return;
|
|
471
|
+
resolved = true;
|
|
472
|
+
// Re-check giveUpReconnect at fire-time. A consumer's onDisconnect can
|
|
473
|
+
// schedule reconnect() via setTimeout (e.g. exponentialBackoff). If the
|
|
474
|
+
// app calls session.close() during that delay, the timer still fires —
|
|
475
|
+
// without this check it would open a brand-new WS on a closed session.
|
|
476
|
+
if (this.giveUpReconnect)
|
|
477
|
+
return;
|
|
478
|
+
void this._reconnectAndRemint();
|
|
479
|
+
};
|
|
480
|
+
const giveUp = () => {
|
|
481
|
+
if (resolved)
|
|
482
|
+
return;
|
|
483
|
+
resolved = true;
|
|
484
|
+
this.giveUpReconnect = true;
|
|
485
|
+
this._settleConnectedWaiters(new Error("session closed"));
|
|
486
|
+
};
|
|
487
|
+
void this.onDisconnect({ reason, attempt: this.attempt, reconnect, giveUp });
|
|
488
|
+
}
|
|
489
|
+
async _reconnectAndRemint() {
|
|
490
|
+
const priorSessionId = this._sessionId;
|
|
491
|
+
let resumed;
|
|
492
|
+
try {
|
|
493
|
+
({ resumed } = await this._connectAndRegister());
|
|
494
|
+
}
|
|
495
|
+
catch (e) {
|
|
496
|
+
this._disconnected(e instanceof Error ? e.message : "reconnect failed");
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
this.attempt = 0;
|
|
500
|
+
// A resume keeps every token. A fresh session doesn't: re-mint the ones
|
|
501
|
+
// still in myTokens (revoke removes them) under the new session-id. A
|
|
502
|
+
// resume can still find stale ones when an earlier re-mint was cut short.
|
|
503
|
+
const tokensRemapped = new Map();
|
|
504
|
+
if (!resumed && !this.autoReconnect)
|
|
505
|
+
this.myTokens.clear();
|
|
506
|
+
for (const old of Array.from(this.myTokens.values())) {
|
|
507
|
+
if (old.sessionId === this._sessionId || !this.myTokens.has(old.token))
|
|
508
|
+
continue;
|
|
509
|
+
let fresh;
|
|
510
|
+
try {
|
|
511
|
+
fresh = await this.mintAgentToken({ label: old.label });
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
if (!this.connected)
|
|
515
|
+
break; // dropped again; the next reconnect retries the rest
|
|
516
|
+
this.myTokens.delete(old.token);
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
if (!this.myTokens.delete(old.token)) {
|
|
520
|
+
void this.revokeAgentToken(fresh.token).catch(() => { }); // revoked while re-minting
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
tokensRemapped.set(old.url, fresh.url);
|
|
524
|
+
}
|
|
525
|
+
if ((priorSessionId !== this._sessionId || tokensRemapped.size > 0) && this.onSessionChanged) {
|
|
526
|
+
void this.onSessionChanged({
|
|
527
|
+
priorSessionId,
|
|
528
|
+
sessionId: this._sessionId,
|
|
529
|
+
tokensRemapped,
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
if (this.onReconnect)
|
|
533
|
+
void this.onReconnect({ sessionId: this._sessionId, resumed });
|
|
534
|
+
}
|
|
535
|
+
_failPending() {
|
|
536
|
+
for (const p of this.pendingFrameReplies.values())
|
|
537
|
+
p.reject(new Error("ws closed"));
|
|
538
|
+
this.pendingFrameReplies.clear();
|
|
539
|
+
}
|
|
540
|
+
_sendFrame(frame) {
|
|
541
|
+
if (!this.ws)
|
|
542
|
+
return;
|
|
543
|
+
try {
|
|
544
|
+
this.ws.send(JSON.stringify(frame));
|
|
545
|
+
}
|
|
546
|
+
catch { }
|
|
547
|
+
}
|
|
548
|
+
_waitForRegisterReply(ws, timeoutMs) {
|
|
549
|
+
return new Promise((resolve, reject) => {
|
|
550
|
+
const done = (err, msg) => {
|
|
551
|
+
clearTimeout(timer);
|
|
552
|
+
ws.removeListener("message", onMessage);
|
|
553
|
+
ws.removeListener("close", onClose);
|
|
554
|
+
err ? reject(err) : resolve(msg);
|
|
555
|
+
};
|
|
556
|
+
const onMessage = (data) => {
|
|
557
|
+
let msg;
|
|
558
|
+
try {
|
|
559
|
+
msg = JSON.parse(String(data));
|
|
560
|
+
}
|
|
561
|
+
catch {
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (msg.type === "register_reply")
|
|
565
|
+
done(null, msg);
|
|
566
|
+
};
|
|
567
|
+
const onClose = (...args) => {
|
|
568
|
+
const closeCode = args[0] ?? 1006;
|
|
569
|
+
done(Object.assign(new Error(`ws closed before register_reply (${closeCode})`), { closeCode }));
|
|
570
|
+
};
|
|
571
|
+
const timer = setTimeout(() => done(new Error(`register_reply timeout after ${timeoutMs}ms`)), timeoutMs);
|
|
572
|
+
ws.addListener("message", onMessage);
|
|
573
|
+
ws.addListener("close", onClose);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
_awaitReply(id, timeoutMs) {
|
|
577
|
+
return new Promise((resolve, reject) => {
|
|
578
|
+
const timer = setTimeout(() => {
|
|
579
|
+
this.pendingFrameReplies.delete(id);
|
|
580
|
+
reject(new Error(`awaitReply(${id}) timeout after ${timeoutMs}ms`));
|
|
581
|
+
}, timeoutMs);
|
|
582
|
+
this.pendingFrameReplies.set(id, {
|
|
583
|
+
resolve: (v) => { clearTimeout(timer); resolve(v); },
|
|
584
|
+
reject: (e) => { clearTimeout(timer); reject(e); },
|
|
585
|
+
});
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
_rewriteUrl(url) {
|
|
589
|
+
return url.replace(/^__BASE__/, this.baseUrl);
|
|
590
|
+
}
|
|
591
|
+
_scheduleNextPing() {
|
|
592
|
+
if (this.heartbeatPingTimer)
|
|
593
|
+
clearTimeout(this.heartbeatPingTimer);
|
|
594
|
+
this.heartbeatPingTimer = setTimeout(() => this._sendPing(), this.heartbeatIntervalMs);
|
|
595
|
+
}
|
|
596
|
+
_sendPing() {
|
|
597
|
+
if (!this.ws || this.ws.readyState !== READY_STATE_OPEN)
|
|
598
|
+
return;
|
|
599
|
+
this.pendingPingId = this._uid();
|
|
600
|
+
this._sendFrame({ type: "ping", id: this.pendingPingId });
|
|
601
|
+
if (this.heartbeatTimeoutTimer)
|
|
602
|
+
clearTimeout(this.heartbeatTimeoutTimer);
|
|
603
|
+
this.heartbeatTimeoutTimer = setTimeout(() => {
|
|
604
|
+
// No pong in window — close as dead.
|
|
605
|
+
try {
|
|
606
|
+
this.ws?.close(1011, "dead heartbeat");
|
|
607
|
+
}
|
|
608
|
+
catch { }
|
|
609
|
+
}, this.heartbeatTimeoutMs);
|
|
610
|
+
}
|
|
611
|
+
_teardownHeartbeat() {
|
|
612
|
+
if (this.heartbeatPingTimer) {
|
|
613
|
+
clearTimeout(this.heartbeatPingTimer);
|
|
614
|
+
this.heartbeatPingTimer = null;
|
|
615
|
+
}
|
|
616
|
+
if (this.heartbeatTimeoutTimer) {
|
|
617
|
+
clearTimeout(this.heartbeatTimeoutTimer);
|
|
618
|
+
this.heartbeatTimeoutTimer = null;
|
|
619
|
+
}
|
|
620
|
+
this.pendingPingId = null;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function wireTools(defs) {
|
|
624
|
+
return defs.map((t) => ({
|
|
625
|
+
method: t.method,
|
|
626
|
+
path: t.path,
|
|
627
|
+
description: t.description,
|
|
628
|
+
...(t.input_schema !== undefined ? { input_schema: t.input_schema } : {}),
|
|
629
|
+
}));
|
|
630
|
+
}
|
|
631
|
+
function normalizeResult(result) {
|
|
632
|
+
if (result && typeof result === "object" && "status" in result && typeof result.status === "number") {
|
|
633
|
+
const r = result;
|
|
634
|
+
return { status: r.status, body: r.body, taskId: r.taskId, headers: r.headers };
|
|
635
|
+
}
|
|
636
|
+
return { status: 200, body: result };
|
|
637
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface MinWS {
|
|
2
|
+
send(data: string): void;
|
|
3
|
+
close(code?: number, reason?: string): void;
|
|
4
|
+
/** "open" | "message" | "close" | "error" */
|
|
5
|
+
addListener(event: string, fn: (...args: unknown[]) => void): void;
|
|
6
|
+
removeListener(event: string, fn: (...args: unknown[]) => void): void;
|
|
7
|
+
readonly readyState: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function openWs(url: string): MinWS;
|
|
10
|
+
export declare const READY_STATE_OPEN = 1;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// WebSocket transport over the runtime's native WebSocket (browsers, Workers,
|
|
2
|
+
// Node 22+). Wraps it in a minimal send/close/addListener surface.
|
|
3
|
+
const READY_OPEN = 1;
|
|
4
|
+
export function openWs(url) {
|
|
5
|
+
const Native = globalThis.WebSocket;
|
|
6
|
+
if (!Native)
|
|
7
|
+
throw new Error("No global WebSocket — agent-socket needs a browser, Workers, or Node 22+.");
|
|
8
|
+
return wrapNative(new Native(url));
|
|
9
|
+
}
|
|
10
|
+
function wrapNative(ws) {
|
|
11
|
+
// Map our addListener/removeListener naming to addEventListener/removeEventListener
|
|
12
|
+
// and adapt event objects to the listener signatures the SDK expects.
|
|
13
|
+
const adapters = new WeakMap();
|
|
14
|
+
return {
|
|
15
|
+
send: (data) => ws.send(data),
|
|
16
|
+
close: (code, reason) => ws.close(code, reason),
|
|
17
|
+
get readyState() { return ws.readyState; },
|
|
18
|
+
addListener: (event, fn) => {
|
|
19
|
+
let adapter;
|
|
20
|
+
switch (event) {
|
|
21
|
+
case "message":
|
|
22
|
+
adapter = (ev) => fn(ev.data);
|
|
23
|
+
break;
|
|
24
|
+
case "close":
|
|
25
|
+
adapter = (ev) => {
|
|
26
|
+
const ce = ev;
|
|
27
|
+
fn(ce.code, ce.reason);
|
|
28
|
+
};
|
|
29
|
+
break;
|
|
30
|
+
case "error":
|
|
31
|
+
adapter = (ev) => fn(ev);
|
|
32
|
+
break;
|
|
33
|
+
case "open":
|
|
34
|
+
default:
|
|
35
|
+
adapter = () => fn();
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
adapters.set(fn, adapter);
|
|
39
|
+
ws.addEventListener(event, adapter);
|
|
40
|
+
},
|
|
41
|
+
removeListener: (event, fn) => {
|
|
42
|
+
const adapter = adapters.get(fn);
|
|
43
|
+
if (adapter)
|
|
44
|
+
ws.removeEventListener(event, adapter);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export const READY_STATE_OPEN = READY_OPEN;
|