Repository navigation
Expand file tree
/
Copy pathdaemon-client-transport.ts
More file actions
658 lines (615 loc) · 20.7 KB
/
Copy pathdaemon-client-transport.ts
File metadata and controls
658 lines (615 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
import type { RequestProgressSink } from '@agent-device/contracts/progress';
import net from 'node:net';
import { AppError } from '@agent-device/kernel/errors';
import { loadNodeHttpRequester, readNodeHttpResponseBody } from '@agent-device/host-kit/transport';
import type { DaemonRequest, DaemonResponse } from '../daemon/daemon-request.ts';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import type { DaemonPaths, DaemonTransportPreference } from '../daemon-resolution.ts';
import {
readDaemonHttpProgressResponse,
readDaemonSocketProgressResponse,
shouldReadDaemonProgressStream,
} from './daemon-client-progress.ts';
import {
buildDaemonHttpAuthHeaders,
buildDaemonHttpUrl,
DAEMON_HTTP_INSTANCE_HEADER,
DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER,
DAEMON_RPC_PROTOCOL_VERSION,
} from '@agent-device/contracts/daemon-http';
import { buildHttpRpcPayload, handleDaemonHttpResponseBody } from './daemon-client-rpc.ts';
import { handleRequestTimeout } from './daemon-client-timeout.ts';
import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts';
import { readVersion } from '@agent-device/host-kit/version';
type ResolvedDaemonTransport = 'socket' | 'http';
type SendRequestOptions = {
onProgress?: RequestProgressSink;
onIdentityChange?: (health: RemoteDaemonHealth | undefined) => void;
};
const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500;
const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000;
export const DAEMON_HTTP_ENDPOINT_UNAVAILABLE_MESSAGE = 'Daemon HTTP endpoint is unavailable';
export const DAEMON_SOCKET_ENDPOINT_UNAVAILABLE_MESSAGE = 'Daemon socket endpoint is unavailable';
export type RemoteDaemonHealth = {
reachable: boolean;
statusCode?: number;
service?: string;
version?: string;
rpcProtocolVersion?: number;
instanceId?: string;
/** The daemon behind a proxy, as the proxy's health reported it. */
upstream?: RemoteDaemonHealthLink;
};
type RemoteDaemonHealthLink = Pick<
RemoteDaemonHealth,
'service' | 'version' | 'rpcProtocolVersion' | 'instanceId'
>;
export async function canConnect(
info: DaemonInfo,
preference: DaemonTransportPreference,
): Promise<boolean> {
const transport = chooseTransport(info, preference);
if (await canConnectWithTransport(info, transport)) return true;
const fallback = chooseAutoFallbackTransport(info, preference, transport);
return fallback ? await canConnectWithTransport(info, fallback) : false;
}
async function canConnectWithTransport(
info: DaemonInfo,
transport: ResolvedDaemonTransport,
): Promise<boolean> {
return transport === 'http' ? await canConnectHttp(info) : await canConnectSocket(info.port);
}
export function canConnectSocket(port: number | undefined): Promise<boolean> {
if (!port) return Promise.resolve(false);
return new Promise((resolve) => {
let settled = false;
const socket = net.createConnection({ host: '127.0.0.1', port }, () => {
finish(true);
});
const finish = (reachable: boolean) => {
if (settled) return;
settled = true;
socket.destroy();
resolve(reachable);
};
socket.setTimeout(LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS);
socket.on('timeout', () => {
finish(false);
});
socket.on('error', () => {
finish(false);
});
});
}
function canConnectHttp(info: DaemonInfo): Promise<boolean> {
return readDaemonHttpHealth(info).then((health) => health.reachable);
}
export async function readRemoteDaemonHealth(info: DaemonInfo): Promise<RemoteDaemonHealth> {
const health = await readDaemonHttpHealth(info);
if (!info.baseUrl || !health.reachable) return health;
// Every link a command RPC crosses has to speak the client's protocol: a proxy that reports a
// skewed daemon behind it fails here, before the RPC, exactly like a skewed proxy does.
const incompatible = [health, health.upstream].find(
(link) =>
typeof link?.rpcProtocolVersion === 'number' &&
link.rpcProtocolVersion !== DAEMON_RPC_PROTOCOL_VERSION,
);
if (incompatible) {
throw new AppError('COMMAND_FAILED', 'Remote daemon RPC protocol is incompatible', {
daemonBaseUrl: info.baseUrl,
clientVersion: readVersion(),
remoteVersion: incompatible.version,
remoteService: incompatible.service,
supportedRpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
remoteRpcProtocolVersion: incompatible.rpcProtocolVersion,
hint: 'Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol.',
});
}
return health;
}
async function readDaemonHttpHealth(info: DaemonInfo): Promise<RemoteDaemonHealth> {
const endpoint = info.baseUrl
? buildDaemonHttpUrl(info.baseUrl, 'health')
: info.httpPort
? `http://127.0.0.1:${info.httpPort}/health`
: null;
if (!endpoint) return { reachable: false };
const url = new URL(endpoint);
const transport = await loadNodeHttpRequester(url.protocol);
const timeoutMs = info.baseUrl
? REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS
: LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS;
return await new Promise((resolve) => {
const headers = info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {};
const req = transport.request(
{
protocol: url.protocol,
host: url.hostname,
port: url.port,
path: url.pathname + url.search,
method: 'GET',
timeout: timeoutMs,
headers,
},
(res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
const statusCode = res.statusCode ?? 500;
resolve({
reachable: statusCode < 500,
statusCode,
...readHealthPayload(body),
});
});
},
);
req.on('timeout', () => {
req.destroy();
resolve({ reachable: false });
});
req.on('error', () => {
resolve({ reachable: false });
});
req.end();
});
}
function readHealthPayload(body: string): Omit<RemoteDaemonHealth, 'reachable' | 'statusCode'> {
try {
const parsed = JSON.parse(body) as { upstream?: unknown };
const upstream =
parsed.upstream && typeof parsed.upstream === 'object'
? readHealthLink(parsed.upstream as Record<string, unknown>)
: undefined;
return {
...readHealthLink(parsed as Record<string, unknown>),
...(upstream ? { upstream } : {}),
};
} catch {
return {};
}
}
function readHealthLink(parsed: Record<string, unknown>): RemoteDaemonHealthLink {
return {
service: typeof parsed.service === 'string' ? parsed.service : undefined,
version: typeof parsed.version === 'string' ? parsed.version : undefined,
rpcProtocolVersion:
typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined,
...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}),
};
}
export async function sendRequest(
info: DaemonInfo,
req: DaemonRequest,
preference: DaemonTransportPreference,
statePaths: DaemonPaths,
timeoutMs: number | undefined,
options: SendRequestOptions = {},
): Promise<DaemonResponse> {
const transport = chooseTransport(info, preference);
try {
return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, options);
} catch (error) {
const fallback = chooseAutoFallbackTransport(info, preference, transport);
if (!fallback || !isSafeAutoTransportFallbackError(error, transport)) throw error;
return await sendRequestWithTransport(info, req, statePaths, timeoutMs, fallback, options);
}
}
async function sendRequestWithTransport(
info: DaemonInfo,
req: DaemonRequest,
statePaths: DaemonPaths,
timeoutMs: number | undefined,
transport: ResolvedDaemonTransport,
options: SendRequestOptions,
): Promise<DaemonResponse> {
return transport === 'http'
? await sendHttpRequest(info, req, statePaths, timeoutMs, options)
: await sendSocketRequest(info, req, statePaths, timeoutMs, options);
}
function chooseTransport(
info: DaemonInfo,
preference: DaemonTransportPreference,
): ResolvedDaemonTransport {
if (info.baseUrl) {
// Defensive guard: resolveClientSettings rejects this earlier for normal CLI flow.
if (preference === 'socket') {
throw new AppError('COMMAND_FAILED', 'Remote daemon endpoint only supports HTTP transport', {
daemonBaseUrl: info.baseUrl,
});
}
return 'http';
}
if (preference === 'http' || preference === 'socket') {
return requireDaemonTransport(info, preference);
}
const autoOrder: ResolvedDaemonTransport[] =
info.transport === 'socket' || info.transport === 'dual'
? ['socket', 'http']
: ['http', 'socket'];
const available = autoOrder.find((transport) => hasDaemonTransport(info, transport));
if (available) return available;
throw new AppError('COMMAND_FAILED', 'Daemon metadata has no reachable transport');
}
function hasDaemonTransport(info: DaemonInfo, transport: ResolvedDaemonTransport): boolean {
return transport === 'http' ? Boolean(info.httpPort) : Boolean(info.port);
}
function chooseAutoFallbackTransport(
info: DaemonInfo,
preference: DaemonTransportPreference,
attempted: ResolvedDaemonTransport,
): ResolvedDaemonTransport | null {
if (preference !== 'auto' || info.baseUrl) return null;
const fallback = attempted === 'socket' ? 'http' : 'socket';
return hasDaemonTransport(info, fallback) ? fallback : null;
}
function isSafeAutoTransportFallbackError(
error: unknown,
attempted: ResolvedDaemonTransport,
): boolean {
return (
attempted === 'socket' &&
error instanceof AppError &&
error.code === 'COMMAND_FAILED' &&
error.message === 'Failed to communicate with daemon' &&
error.details?.daemonSocketRequestWritten === false
);
}
function requireDaemonTransport(
info: DaemonInfo,
transport: ResolvedDaemonTransport,
): ResolvedDaemonTransport {
if (hasDaemonTransport(info, transport)) return transport;
throw new AppError(
'COMMAND_FAILED',
transport === 'http'
? DAEMON_HTTP_ENDPOINT_UNAVAILABLE_MESSAGE
: DAEMON_SOCKET_ENDPOINT_UNAVAILABLE_MESSAGE,
);
}
function handleTransportError(
err: unknown,
requestId: string | undefined,
remote: boolean,
details: Record<string, unknown> = {},
): AppError {
emitDiagnostic({
level: 'error',
phase: 'daemon_request_socket_error',
data: {
requestId,
message: err instanceof Error ? (err as Error).message : String(err),
},
});
return new AppError(
'COMMAND_FAILED',
'Failed to communicate with daemon',
{
...details,
requestId,
hint: remote
? 'Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.'
: 'Retry command. If this persists, clean stale daemon metadata and start a fresh session.',
},
err instanceof Error ? err : undefined,
);
}
async function sendSocketRequest(
info: DaemonInfo,
req: DaemonRequest,
statePaths: DaemonPaths,
timeoutMs: number | undefined,
options: SendRequestOptions,
): Promise<DaemonResponse> {
const port = info.port;
if (!port) throw new AppError('COMMAND_FAILED', DAEMON_SOCKET_ENDPOINT_UNAVAILABLE_MESSAGE);
return new Promise((resolve, reject) => {
let requestWritten = false;
const socket = net.createConnection({ host: '127.0.0.1', port }, () => {
requestWritten = true;
socket.write(`${JSON.stringify(req)}\n`);
});
let settled = false;
const timeoutHandle =
typeof timeoutMs === 'number'
? setTimeout(() => {
settled = true;
socket.destroy();
reject(
handleRequestTimeout({
info,
statePaths,
...timeoutRequestContext(req, false, timeoutMs),
}),
);
}, timeoutMs)
: undefined;
readDaemonSocketProgressResponse(socket, {
req,
onProgress: options.onProgress,
isSettled: () => settled,
clearTimeout: () => {
if (timeoutHandle) clearTimeout(timeoutHandle);
},
resolve: (response) => {
settled = true;
resolve(response);
},
reject: (error) => {
settled = true;
reject(error);
},
});
socket.on('error', (err) => {
if (settled) return;
settled = true;
if (timeoutHandle) clearTimeout(timeoutHandle);
reject(
handleTransportError(err, req.meta?.requestId, false, {
daemonSocketRequestWritten: requestWritten,
}),
);
});
});
}
// The fields a timed-out request is described by, read once so a socket and an HTTP timeout cannot
// describe the same request differently.
type TimeoutRequestFields = Omit<Parameters<typeof handleRequestTimeout>[0], 'info' | 'statePaths'>;
function timeoutRequestContext(
req: DaemonRequest,
remote: boolean,
timeoutMs: number,
): TimeoutRequestFields {
return {
remote,
timeoutMs,
requestId: req.meta?.requestId,
command: req.command,
platform: req.flags?.platform,
session: req.session,
action: req.positionals?.[0],
};
}
type RemoteInstanceHeaders = {
instanceId?: string;
upstreamInstanceId?: string;
};
function readRemoteInstanceHeaders(
headers: Record<string, string | string[] | undefined>,
): RemoteInstanceHeaders {
const instanceId = headers[DAEMON_HTTP_INSTANCE_HEADER];
const upstreamInstanceId = headers[DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER];
return {
instanceId: typeof instanceId === 'string' ? instanceId : undefined,
upstreamInstanceId: typeof upstreamInstanceId === 'string' ? upstreamInstanceId : undefined,
};
}
async function verifyRemoteInstance(
info: DaemonInfo,
headers: Record<string, string | string[] | undefined>,
onIdentityChange?: (health: RemoteDaemonHealth | undefined) => void,
): Promise<void> {
if (!info.baseUrl || !info.remoteInstanceId) return;
const observed = readRemoteInstanceHeaders(headers);
if (
observed.instanceId === info.remoteInstanceId &&
observed.upstreamInstanceId === info.remoteUpstreamInstanceId
)
return;
await recheckChangedRemoteInstance(info, observed, onIdentityChange);
}
function hasCompleteRemoteInstanceHeaders(
info: DaemonInfo,
observed: RemoteInstanceHeaders,
): boolean {
return (
Boolean(observed.instanceId) &&
(!info.remoteUpstreamInstanceId || Boolean(observed.upstreamInstanceId))
);
}
function healthMatchesRemoteInstance(
health: RemoteDaemonHealth,
observed: RemoteInstanceHeaders,
): boolean {
return (
health.instanceId === observed.instanceId &&
health.upstream?.instanceId === observed.upstreamInstanceId
);
}
async function recheckChangedRemoteInstance(
info: DaemonInfo,
observed: RemoteInstanceHeaders,
onIdentityChange?: (health: RemoteDaemonHealth | undefined) => void,
): Promise<void> {
const health = await readRemoteDaemonHealth(info);
if (!health.reachable) {
throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', {
daemonBaseUrl: info.baseUrl,
});
}
if (!hasCompleteRemoteInstanceHeaders(info, observed)) {
onIdentityChange?.(undefined);
return;
}
if (!healthMatchesRemoteInstance(health, observed)) {
throw new AppError('COMMAND_FAILED', 'Remote daemon identity changed during RPC', {
daemonBaseUrl: info.baseUrl,
});
}
onIdentityChange?.(health);
}
async function sendHttpRequest(
info: DaemonInfo,
req: DaemonRequest,
statePaths: DaemonPaths,
timeoutMs: number | undefined,
options: SendRequestOptions,
): Promise<DaemonResponse> {
const rpcUrl = info.baseUrl
? new URL(buildDaemonHttpUrl(info.baseUrl, 'rpc'))
: info.httpPort
? new URL(`http://127.0.0.1:${info.httpPort}/rpc`)
: null;
if (!rpcUrl) throw new AppError('COMMAND_FAILED', DAEMON_HTTP_ENDPOINT_UNAVAILABLE_MESSAGE);
const rpcPayload = JSON.stringify(buildHttpRpcPayload(req, { includeTokenParam: !info.baseUrl }));
const headers: Record<string, string | number> = {
'content-type': 'application/json',
'content-length': Buffer.byteLength(rpcPayload),
};
if (info.baseUrl) {
Object.assign(headers, buildDaemonHttpAuthHeaders(info.token));
}
const transport = await loadNodeHttpRequester(rpcUrl.protocol);
return await new Promise((resolve, reject) => {
const request = transport.request(
{
protocol: rpcUrl.protocol,
host: rpcUrl.hostname,
port: rpcUrl.port,
method: 'POST',
path: rpcUrl.pathname + rpcUrl.search,
headers,
},
(res) => {
const identityCheck = verifyRemoteInstance(
info,
res.headers ?? {},
options.onIdentityChange,
);
if (shouldReadDaemonProgressStream(req, res.headers?.['content-type'])) {
void identityCheck.catch((error: unknown) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
reject(error);
});
readDaemonHttpProgressResponse(res, {
req,
onProgress: options.onProgress,
reject,
clearTimeout: () => {
if (timeoutHandle) clearTimeout(timeoutHandle);
},
handleResponseBody: (body) => {
void identityCheck
.then(() =>
handleDaemonHttpResponseBody(body, {
info,
req,
stateDir: statePaths.baseDir,
resolve,
reject,
}),
)
.catch(reject);
},
});
return;
}
const responseBody = readNodeHttpResponseBody(res).catch((error: unknown) => {
throw new AppError(
'COMMAND_FAILED',
'Failed to read daemon response',
{ requestId: req.meta?.requestId },
error instanceof Error ? error : undefined,
);
});
void Promise.all([identityCheck, responseBody])
.then(([, body]) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
handleDaemonHttpResponseBody(body, {
info,
req,
stateDir: statePaths.baseDir,
resolve,
reject,
});
})
.catch((error: unknown) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
reject(error);
});
},
);
const remote = isRemoteDaemon(info);
const timeoutHandle =
typeof timeoutMs === 'number'
? setTimeout(() => {
request.destroy();
reject(
handleRequestTimeout({
info,
statePaths,
...timeoutRequestContext(req, remote, timeoutMs),
}),
);
}, timeoutMs)
: undefined;
request.on('error', (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
reject(handleTransportError(err, req.meta?.requestId, remote));
});
request.write(rpcPayload);
request.end();
});
}
type RemoteHealthCacheEntry = {
baseUrl: string;
token: string;
pid: number;
instanceId?: string;
health: Promise<RemoteDaemonHealth>;
};
let remoteHealthCache: RemoteHealthCacheEntry | undefined;
function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): boolean {
return (
entry.baseUrl === info.baseUrl &&
entry.token === info.token &&
entry.pid === info.pid &&
(!info.remoteInstanceId || !entry.instanceId || entry.instanceId === info.remoteInstanceId)
);
}
export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void {
if (!health.instanceId || (health.upstream && !health.upstream.instanceId)) return;
remoteHealthCache = {
baseUrl: info.baseUrl ?? '',
token: info.token,
pid: info.pid,
instanceId: health.instanceId,
health: Promise.resolve(health),
};
}
export function invalidateRemoteDaemonHealth(info: DaemonInfo): void {
if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) {
remoteHealthCache = undefined;
}
}
export async function cachedRemoteDaemonHealth(info: DaemonInfo): Promise<RemoteDaemonHealth> {
if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) {
return await remoteHealthCache.health;
}
const entry: RemoteHealthCacheEntry = {
baseUrl: info.baseUrl ?? '',
token: info.token,
pid: info.pid,
health: readRemoteDaemonHealth(info),
};
remoteHealthCache = entry;
try {
const health = await entry.health;
entry.instanceId = health.instanceId;
if (
(!health.reachable ||
!health.instanceId ||
(health.upstream && !health.upstream.instanceId)) &&
remoteHealthCache === entry
) {
remoteHealthCache = undefined;
}
return health;
} catch (error) {
if (remoteHealthCache === entry) remoteHealthCache = undefined;
throw error;
}
}