-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathbroker-lifecycle.ts
More file actions
1535 lines (1397 loc) · 51.6 KB
/
Copy pathbroker-lifecycle.ts
File metadata and controls
1535 lines (1397 loc) · 51.6 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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs';
import path from 'node:path';
import { HarnessDriverClient } from '@agent-relay/harness-driver';
import { startServeNode, type FleetNodeDefinition, type RunningNode } from '@agent-relay/fleet';
import { createLogger } from '@agent-relay/utils';
import type { CoreDependencies, CoreProjectPaths, CoreRelay, SpawnedProcess } from '../commands/core.js';
import { track } from '../telemetry/index.js';
import { buildBundledAgentRelayMcpCommand } from './agent-relay-mcp-command.js';
import { errorClassName } from './telemetry-helpers.js';
import { createTriggerSyncClient, resolveNodeCapacityHarnesses } from './fleet-sidecar.js';
import {
discoverNodeConfigPath,
discoverPythonNodeConfigPath,
loadNodeDefinition,
} from './node-definition-loader.js';
import { startReflexCapture, type RunningReflexCapture } from './reflex-capture.js';
export type UpOptions = {
spawn?: boolean;
background?: boolean;
verbose?: boolean;
workspaceKey?: string;
stateDir?: string;
brokerName?: string;
config?: string;
/**
* Opt-in to auto-discovering an `agent-relay.*` node definition in the
* project root. Only `node up` sets this — the deprecated `local up` alias
* (and any other legacy caller) must keep its pre-`node` behavior of never
* touching such files.
*/
discoverConfig?: boolean;
/** Registered node name override (e.g. from a persisted Cloud enrollment). */
nodeName?: string;
/** Write structured node logs (capabilities, action invocations) to this file. */
logFile?: string;
/** Log verbosity floor: debug | info | warn | error. Defaults to info. */
logLevel?: string;
/** Emit logs as JSON lines instead of human-readable text. */
logJson?: boolean;
};
export type DownOptions = {
force?: boolean;
all?: boolean;
timeout?: string;
stateDir?: string;
};
const MAX_API_PORT_ATTEMPTS = 25;
const MAX_PORT = 65535;
const DEFAULT_BROKER_BASE_PORT = 3888;
/** The broker writes this file with URL, port, API key, and PID. */
const CONNECTION_FILENAME = 'connection.json';
const STATUS_POLL_INTERVAL_MS = 500;
const DETACHED_START_READY_TIMEOUT_MS = 10_000;
const NODE_DELIVERY_READY_TIMEOUT_MS = 10_000;
// Bounded wait for the broker's background-minted node token to surface on
// `/api/session` when serving a capability definition without an explicit
// RELAY_NODE_TOKEN.
const NODE_TOKEN_WAIT_MS = 15_000;
export type StatusOptions = { stateDir?: string; waitFor?: string };
export interface BrokerConnection {
url: string;
port: number;
api_key: string;
pid: number;
}
type BrokerStatusDetails = {
status: Awaited<ReturnType<HarnessDriverClient['getStatus']>>;
session: Awaited<ReturnType<HarnessDriverClient['getSession']>> | null;
};
type NodeDeliveryStatus = {
tokenPresent: boolean;
connected: boolean;
};
type BrokerReadiness =
| {
state: 'running';
conn: BrokerConnection;
statusDetails?: BrokerStatusDetails | null;
}
| {
state: 'starting';
conn: BrokerConnection;
}
| {
state: 'stopped';
};
type BrokerConnectionReader = {
readFileSync: (filePath: string, encoding: BufferEncoding) => string;
};
function parseBrokerConnection(raw: string): BrokerConnection | null {
try {
const conn = JSON.parse(raw);
if (
typeof conn.url === 'string' &&
typeof conn.port === 'number' &&
typeof conn.api_key === 'string' &&
typeof conn.pid === 'number' &&
conn.pid > 0
) {
return conn as BrokerConnection;
}
return null;
} catch {
return null;
}
}
function readBrokerConnectionFromFs(
fileSystem: BrokerConnectionReader,
dataDir: string
): BrokerConnection | null {
const connPath = path.join(dataDir, CONNECTION_FILENAME);
try {
const raw = fileSystem.readFileSync(connPath, 'utf-8');
return parseBrokerConnection(raw);
} catch {
return null;
}
}
/**
* Read the broker's connection.json file from the data directory.
* Returns null if the file doesn't exist or is invalid.
*/
export function readBrokerConnection(dataDir: string): BrokerConnection | null {
return readBrokerConnectionFromFs(fs, dataDir);
}
function toErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/** Emit a `[verbose]`-prefixed step marker via `deps.log` when `--verbose` is set. */
function vlog(deps: CoreDependencies, verbose: boolean | undefined, message: string): void {
if (verbose) {
deps.log(`[verbose] ${message}`);
}
}
/** True when any log flag (or `--verbose`) opts the node into structured logging. */
function nodeLoggingEnabled(options: UpOptions): boolean {
return Boolean(options.logFile || options.logLevel || options.logJson || options.verbose);
}
/**
* Translate the `--log-*` (and `--verbose`) flags into the `AGENT_RELAY_LOG_*`
* environment the shared `createLogger` reads. `--verbose` alone raises the
* floor to DEBUG so per-capability registration lines surface; an explicit
* `--log-level` always wins. Called before the fleet sidecar starts.
*/
function applyNodeLogEnv(options: UpOptions, deps: CoreDependencies): void {
if (options.logFile) {
deps.env.AGENT_RELAY_LOG_FILE = options.logFile;
}
const level = options.logLevel ?? (options.verbose ? 'debug' : undefined);
if (level) {
deps.env.AGENT_RELAY_LOG_LEVEL = level.toUpperCase();
}
if (options.logJson) {
deps.env.AGENT_RELAY_LOG_JSON = '1';
}
}
type ErrorWithCode = { code?: unknown };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
export function readNodeDeliveryStatus(status: unknown): NodeDeliveryStatus | null {
if (!isRecord(status)) {
return null;
}
const snake = isRecord(status.node_delivery) ? status.node_delivery : null;
const tokenPresent = typeof snake?.token_present === 'boolean' ? snake.token_present : false;
const connected =
typeof status.node_connected === 'boolean'
? status.node_connected
: typeof snake?.connected === 'boolean'
? snake.connected
: false;
return { tokenPresent, connected };
}
function nodeDeliveryReady(status: unknown): boolean {
const delivery = readNodeDeliveryStatus(status);
return Boolean(delivery?.tokenPresent && delivery.connected);
}
function formatNodeDeliveryStatus(status: unknown): string {
const delivery = readNodeDeliveryStatus(status);
if (!delivery) {
return 'unknown';
}
if (!delivery.tokenPresent) {
return 'DOWN (no node token)';
}
return delivery.connected ? 'CONNECTED' : 'DOWN (node websocket disconnected)';
}
function errorCode(err: unknown): string | undefined {
if (!err || typeof err !== 'object') return undefined;
const code = (err as ErrorWithCode).code;
return typeof code === 'string' ? code : undefined;
}
/**
* Extract a human-meaningful detail string from an error, walking `err.cause`.
*
* Node's native `fetch()` throws `TypeError: fetch failed` for any network
* problem and stuffs the real reason (ECONNREFUSED, ENOTFOUND, AbortError,
* UND_ERR_CONNECT_TIMEOUT, …) into `err.cause`. Without unwrapping, every
* outbound HTTP failure looks identical to the user.
*
* Exported for testing.
*/
export function describeError(err: unknown): string {
const top = toErrorMessage(err);
if (!(err instanceof Error) || !err.cause) return top;
// Walk the cause chain and collect the deepest message + any error codes.
const codes: string[] = [];
let detail: string | undefined;
let cursor: unknown = err.cause;
let depth = 0;
while (cursor && depth < 5) {
const code = errorCode(cursor);
if (code && !codes.includes(code)) codes.push(code);
if (cursor instanceof Error && cursor.message) {
detail = cursor.message;
}
cursor = cursor instanceof Error ? cursor.cause : undefined;
depth += 1;
}
const parts = [top];
if (detail && detail !== top) parts.push(detail);
if (codes.length > 0) parts.push(`[${codes.join(', ')}]`);
return parts.join(' — ');
}
/**
* Pick the best `error_class` for telemetry. Prefer a network-style code from
* `err.cause` (ECONNREFUSED etc.) over the generic constructor name (TypeError)
* — a code is more actionable in PostHog and matches the schema's example
* values for `BrokerStartFailedEvent.error_class`.
*
* Exported for testing.
*/
export function classifyBrokerStartError(err: unknown): string {
let cursor: unknown = err;
let depth = 0;
while (cursor && depth < 5) {
const code = errorCode(cursor);
if (code) return code;
cursor = cursor instanceof Error ? cursor.cause : undefined;
depth += 1;
}
return errorClassName(err) ?? 'Error';
}
/** Exported for testing. */
export function classifyBrokerStartStage(_err: unknown, message: string): string {
if (isBrokerAlreadyRunningError(message)) return 'already_running';
if (/fetch failed/i.test(message)) return 'connect';
if (/Broker did not report API port/i.test(message)) return 'spawn';
if (/Broker process exited with code/i.test(message)) return 'spawn';
if (/ENOENT/i.test(message) && /broker/i.test(message)) return 'resolve_binary';
return 'startup';
}
async function resolveApiPortWithFallback(
startApiPort: number,
maxAttempts: number,
deps: CoreDependencies
): Promise<number> {
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
const candidatePort = startApiPort + attempt;
if (candidatePort > MAX_PORT) {
break;
}
const inUse = await deps.isPortInUse(candidatePort);
if (!inUse) {
if (attempt > 0) {
deps.warn(`API port ${startApiPort} is already in use; trying ${candidatePort}`);
}
return candidatePort;
}
}
throw new Error(`Failed to find an available API port near ${startApiPort}.`);
}
/**
* The broker base port. `AGENT_RELAY_BROKER_PORT` overrides the default so
* multiple brokers can run side by side (e.g. in tests); the broker HTTP API
* binds near `basePort + 1` with fallback scanning.
*/
export function resolveBrokerBasePort(deps: Pick<CoreDependencies, 'env'>): number {
const raw = Number.parseInt(deps.env.AGENT_RELAY_BROKER_PORT ?? '', 10);
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_BROKER_BASE_PORT;
}
export async function startBrokerWithPortFallback(
paths: CoreProjectPaths,
basePort: number,
deps: CoreDependencies,
brokerName?: string,
verbose?: boolean
): Promise<{ relay: CoreRelay; apiPort: number }> {
// Resolve a free API port BEFORE spawning the broker. This avoids
// spawning (and flocking) multiple --persist brokers during retry,
// which caused stale-flock "already running" errors.
const startApiPort = basePort + 1;
vlog(deps, verbose, `Resolving a free API port starting near ${startApiPort}...`);
const apiPort = await resolveApiPortWithFallback(startApiPort, MAX_API_PORT_ATTEMPTS, deps);
vlog(deps, verbose, `API port resolved: ${apiPort}`);
vlog(deps, verbose, 'Creating broker client (spawns broker process, waits for handshake)...');
const candidate = await deps.createRelay(paths.projectRoot, apiPort, brokerName, verbose);
vlog(deps, verbose, 'Broker client created. Checking broker status...');
await candidate.getStatus();
vlog(deps, verbose, 'Broker status check passed.');
return { relay: candidate, apiPort };
}
/** A handle to stop the capability providers started alongside the broker. */
export interface RunningNodeProviders {
stop(): Promise<void>;
}
export interface BrokerNodeIdentity {
nodeId: string;
nodeName: string;
nodeToken?: string;
}
interface SessionSnapshot {
node_id?: string;
node_name?: string;
node_token?: string;
}
/** Reject if `promise` doesn't settle within `ms`, clearing the timer on settle. */
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('session read exceeded token-wait budget')), ms);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
(err) => {
clearTimeout(timer);
reject(err);
}
);
});
}
/**
* Resolve the broker's node identity from repeated `/api/session` reads.
*
* The broker publishes its node id as soon as the workspace handshake completes,
* but mints the node token off the API-readiness path (in the background), so a
* freshly started broker can report `node_id` before `node_token`. When
* `awaitTokenMs` is set, poll until the token appears (or the budget elapses) so
* a provider that needs the broker-minted token isn't skipped over a startup
* race. A transient session-read error yields the best identity seen so far
* (identity without token), or `null` if no `node_id` was ever read.
*/
export async function resolveNodeIdentityFromSession(
getSession: () => Promise<SessionSnapshot>,
options: { awaitTokenMs?: number; sleep?: (ms: number) => Promise<void> } = {}
): Promise<BrokerNodeIdentity | null> {
const awaitTokenMs = options.awaitTokenMs ?? 0;
const sleep = options.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
const deadline = Date.now() + awaitTokenMs;
let identity: BrokerNodeIdentity | null = null;
for (;;) {
let session: SessionSnapshot;
try {
// Bound each read to the remaining token-wait budget so a single stalled
// `/api/session` can't hold startup past `awaitTokenMs` (the transport's
// own request timeout is far longer). The non-await path issues one read
// and doesn't need the bound.
session =
awaitTokenMs > 0
? await withTimeout(getSession(), Math.max(0, deadline - Date.now()))
: await getSession();
} catch {
return identity;
}
if (!session.node_id) return identity;
identity = {
nodeId: session.node_id,
nodeName: session.node_name ?? session.node_id,
...(session.node_token ? { nodeToken: session.node_token } : {}),
};
if (session.node_token || awaitTokenMs <= 0 || Date.now() >= deadline) {
return identity;
}
await sleep(250);
}
}
/**
* Read the node id/name the broker registered as, from its HTTP session. The
* capability providers attach to this same node so they share its identity.
*/
async function readBrokerNodeIdentity(
conn: BrokerConnection,
options: { awaitTokenMs?: number; sleep?: (ms: number) => Promise<void> } = {}
): Promise<BrokerNodeIdentity | null> {
const client = new HarnessDriverClient({ baseUrl: conn.url, apiKey: conn.api_key });
try {
return await resolveNodeIdentityFromSession(() => client.getSession(), options);
} finally {
client.disconnect();
}
}
/**
* Serve the project's capability definitions as node providers connected
* directly to the engine, alongside the broker provider: an `agent-relay.{ts,…}`
* definition via {@link startServeNode}, and an `agent-relay.py` script spawned
* as a supervised `python` child with the node token in its env. When no
* definition exists, nothing is served — the broker's capacity already brings
* the node online. Best-effort: a provider setup failure never aborts `up`.
*/
async function startNodeCapabilityProviders(
paths: CoreProjectPaths,
relay: CoreRelay,
options: UpOptions,
deps: CoreDependencies,
nodeDefinition: FleetNodeDefinition | undefined
): Promise<RunningNodeProviders | undefined> {
// Definition discovery is opt-in (`node up` only), matching the TS config scan.
const pythonConfig =
options.discoverConfig === true ? discoverPythonNodeConfigPath(paths.projectRoot) : undefined;
if (!nodeDefinition && !pythonConfig) {
return undefined;
}
const conn = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
if (!conn) {
deps.warn('Capability providers skipped: broker connection file was not available.');
return undefined;
}
const baseUrl = deps.env.RELAY_BASE_URL?.trim();
// Serving a definition needs the node token. When no explicit RELAY_NODE_TOKEN
// is set we rely on the broker's background-minted token, which can lag its
// node id by a Relaycast round-trip — wait a bounded window for it rather than
// racing the mint and skipping the provider.
const awaitTokenMs = deps.env.RELAY_NODE_TOKEN?.trim() ? 0 : NODE_TOKEN_WAIT_MS;
const identity = await readBrokerNodeIdentity(conn, { awaitTokenMs });
if (!identity) {
deps.warn('Capability providers skipped: the broker did not report its node id yet.');
return undefined;
}
// The broker mints its own node token when RELAY_NODE_TOKEN is unset (local,
// un-enrolled); all providers on the node share that token, so fall back to
// the one it reports on its session rather than requiring pre-enrollment.
const nodeToken = deps.env.RELAY_NODE_TOKEN?.trim() || identity.nodeToken;
if (!nodeToken) {
deps.warn('Capability providers skipped: no node token available from the broker or environment.');
return undefined;
}
const served: RunningNode[] = [];
let pythonChild: SpawnedProcess | undefined;
if (nodeDefinition) {
try {
const workspaceKey = relay.workspaceKey;
served.push(
startServeNode({
definition: nodeDefinition,
connection: {
...(baseUrl ? { baseUrl } : {}),
nodeToken,
nodeId: identity.nodeId,
},
nameOverride: options.nodeName ?? identity.nodeName,
// The served definition attaches as its own provider, distinct from the
// broker ("broker") on the same node.
providerName: nodeDefinition.name,
...(workspaceKey ? { triggers: createTriggerSyncClient({ workspaceKey, baseUrl }) } : {}),
reconnect: true,
// With any --log-* flag (or --verbose), surface the node's full lifecycle
// — capabilities registered, every action invoked/completed — through the
// shared logger, which honors AGENT_RELAY_LOG_FILE/_LEVEL/_JSON. Without a
// flag, keep the prior behavior: the registration summary via log, warnings
// via warn.
...(nodeLoggingEnabled(options)
? { logger: deps.createNodeLogger?.('fleet') ?? createLogger('fleet') }
: { warn: (message) => deps.warn(message), log: (message) => deps.log(message) }),
})
);
} catch (err) {
deps.warn(`Capability provider skipped: ${toErrorMessage(err)}`);
}
}
if (pythonConfig) {
pythonChild = startPythonNodeProvider(
pythonConfig,
{
nodeToken,
baseUrl,
nodeId: identity.nodeId,
// Prefer the enrolled/override name so a Cloud-enrolled py provider
// registers under the same name as the TS provider, not the broker default.
nodeName: options.nodeName ?? identity.nodeName,
},
deps
);
}
if (served.length === 0 && !pythonChild) {
return undefined;
}
return {
stop: async () => {
await Promise.all(served.map((node) => node.stop().catch(() => undefined)));
if (pythonChild?.pid) {
try {
deps.killProcess(pythonChild.pid, 'SIGTERM');
} catch {
// Already exited.
}
}
},
};
}
/**
* Spawn `python agent-relay.py` as a supervised child with the node credentials
* in its environment. The child connects to the engine on its own via the SDK's
* `NodeProvider.from_enrollment()`.
*/
function startPythonNodeProvider(
configPath: string,
credentials: { nodeToken: string; baseUrl?: string; nodeId: string; nodeName: string },
deps: CoreDependencies
): SpawnedProcess | undefined {
const python = deps.env.AGENT_RELAY_PYTHON?.trim() || 'python3';
const env: NodeJS.ProcessEnv = {
...deps.env,
RELAY_NODE_TOKEN: credentials.nodeToken,
RELAY_NODE_ID: credentials.nodeId,
RELAY_NODE_NAME: credentials.nodeName,
...(credentials.baseUrl ? { RELAY_BASE_URL: credentials.baseUrl } : {}),
};
try {
const child = deps.spawnProcess(python, [configPath], {
stdio: deps.pythonProviderStdio ?? 'inherit',
env,
});
deps.log(
`Serving Python node provider: ${python} ${path.basename(configPath)} (pid: ${child.pid ?? 'unknown'}).`
);
return child;
} catch (err) {
deps.warn(`Python node provider skipped: ${toErrorMessage(err)}`);
return undefined;
}
}
function isBrokerAlreadyRunningError(message: string): boolean {
return /another broker instance is already running in this directory/i.test(message);
}
function extractBrokerLockDir(message: string): string | null {
const match = message.match(/another broker instance is already running in this directory \(([^)]+)\)/i);
return match?.[1] ?? null;
}
function reportAlreadyRunningError(message: string, dataDir: string, deps: CoreDependencies): void {
const pid = readBrokerPid(dataDir, deps);
if (pid !== null && isProcessRunning(pid, deps)) {
deps.error(`Broker already running for this project (pid: ${pid}).`);
} else {
const lockDir = extractBrokerLockDir(message);
if (lockDir) {
deps.error(`Broker already running for this project (lock: ${lockDir}).`);
} else {
deps.error('Broker already running for this project.');
}
}
deps.error('Run `agent-relay status` to inspect it, then `agent-relay down` to stop it.');
deps.error('If it still fails, run `agent-relay down --force` to clear stale runtime files.');
}
function safeUnlink(filePath: string, deps: CoreDependencies): void {
if (!deps.fs.existsSync(filePath)) return;
try {
deps.fs.unlinkSync(filePath);
} catch {
// Best-effort cleanup.
}
}
function readBrokerPid(dataDir: string, _deps: CoreDependencies): number | null {
const conn = readBrokerConnectionFromFs(_deps.fs, dataDir);
return conn?.pid ?? null;
}
function isProcessRunning(pid: number, deps: CoreDependencies): boolean {
try {
deps.killProcess(pid, 0);
return true;
} catch {
return false;
}
}
type ProcessInfo = {
pid: number;
command: string;
};
function parsePsAuxLine(line: string): ProcessInfo | null {
const fields = line.trim().split(/\s+/);
if (fields.length < 11 || fields[0] === 'USER') {
return null;
}
const pid = Number.parseInt(fields[1], 10);
if (Number.isNaN(pid) || pid <= 0) {
return null;
}
return {
pid,
command: fields.slice(10).join(' '),
};
}
function commandExecutableBasename(command: string): string {
const executable = command.trim().split(/\s+/)[0] ?? '';
return path.basename(executable.replace(/^["']|["']$/g, ''));
}
function isBrokerExecutableCommand(command: string): boolean {
const basename = commandExecutableBasename(command);
return basename === 'agent-relay-broker' || basename.startsWith('agent-relay-broker-');
}
function isAttachedBrokerCliCommand(command: string): boolean {
if (command.includes('agent-relay-mcp')) {
return false;
}
// The attached `up` process holds the broker. Skip the transient
// `up --background` launcher, which exits as soon as the child is ready.
if (!/(?:^|\s)up(?:\s|$)/.test(command) || /(?:^|\s)--background(?:\s|=|$)/.test(command)) {
return false;
}
return /(?:^|\s)(?:\S*agent-relay(?:\.js)?|\S*agent-relay-[^\s]+)(?:\s|$)/.test(command);
}
function isBrokerProcessCommand(command: string): boolean {
return isBrokerExecutableCommand(command) || isAttachedBrokerCliCommand(command);
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function commandHasBrokerName(command: string, brokerName: string): boolean {
const escapedName = escapeRegExp(brokerName);
return new RegExp(`(?:^|\\s)--name(?:\\s+|=)${escapedName}(?:\\s|$)`).test(command);
}
function commandHasProjectRoot(command: string, projectRoot: string): boolean {
const escapedRoot = escapeRegExp(path.resolve(projectRoot));
return new RegExp(`(?:^|\\s|=|["'])${escapedRoot}(?:$|\\s|["']|${escapeRegExp(path.sep)})`).test(command);
}
async function processCwdMatchesProjectRoot(
processInfo: ProcessInfo,
projectRoot: string,
deps: CoreDependencies
): Promise<boolean> {
try {
const cwdDetails = await deps.execCommand(`lsof -nP -a -p ${processInfo.pid} -d cwd -Fn`);
return cwdDetails.stdout
.split('\n')
.filter((line) => line.startsWith('n'))
.some((line) => path.resolve(line.slice(1)) === projectRoot);
} catch {
return false;
}
}
async function terminateProcess(pid: number, deps: CoreDependencies, force: boolean): Promise<boolean> {
try {
deps.killProcess(pid, 'SIGTERM');
} catch {
return false;
}
const exited = await waitForProcessExit(pid, force ? 500 : 300, deps);
if (exited || !force) {
return exited;
}
try {
deps.killProcess(pid, 'SIGKILL');
} catch {
return false;
}
return waitForProcessExit(pid, 500, deps);
}
async function killOrphanedBrokerProcesses(
projectRoot: string,
deps: CoreDependencies,
options?: { force?: boolean }
): Promise<{ matchedCount: number; killedCount: number }> {
let matchedCount = 0;
let killedCount = 0;
try {
const resolvedProjectRoot = path.resolve(projectRoot);
const brokerName = path.basename(resolvedProjectRoot) || 'project';
const candidates: ProcessInfo[] = [];
try {
const processList = await deps.execCommand('ps aux');
const relayProcesses = processList.stdout
.split('\n')
.map(parsePsAuxLine)
.filter((process): process is ProcessInfo => process !== null)
.filter((process) => isBrokerProcessCommand(process.command));
const matchedPids = new Set<number>();
for (const processInfo of relayProcesses) {
if (commandHasProjectRoot(processInfo.command, resolvedProjectRoot)) {
candidates.push(processInfo);
matchedPids.add(processInfo.pid);
}
}
for (const processInfo of relayProcesses) {
if (matchedPids.has(processInfo.pid)) {
continue;
}
const cwdMatches = await processCwdMatchesProjectRoot(processInfo, resolvedProjectRoot, deps);
if (!cwdMatches) continue;
if (
isBrokerExecutableCommand(processInfo.command) &&
!commandHasBrokerName(processInfo.command, brokerName)
) {
continue;
}
candidates.push(processInfo);
matchedPids.add(processInfo.pid);
}
} catch {
// Expected if ps is unavailable; fall through to no matches.
}
for (const { pid } of candidates) {
if (pid === deps.pid) {
continue;
}
matchedCount += 1;
deps.warn(`Killing orphaned broker process (pid: ${pid})`);
const killed = await terminateProcess(pid, deps, options?.force === true);
if (killed) {
killedCount += 1;
} else if (options?.force === true) {
deps.warn(`Broker orphan process may still be running (pid: ${pid})`);
}
}
} catch {
// Best-effort orphan cleanup.
}
return { matchedCount, killedCount };
}
function ensureBundledAgentRelayMcpCommand(deps: CoreDependencies): void {
if (deps.env.AGENT_RELAY_MCP_COMMAND?.trim()) {
return;
}
const command = buildBundledAgentRelayMcpCommand(deps.execPath, deps.cliScript, deps.fs.existsSync);
if (command) {
deps.env.AGENT_RELAY_MCP_COMMAND = command;
}
}
async function waitForProcessExit(pid: number, timeoutMs: number, deps: CoreDependencies): Promise<boolean> {
const startedAt = deps.now();
while (deps.now() - startedAt < timeoutMs) {
if (!isProcessRunning(pid, deps)) {
return true;
}
await deps.sleep(100);
}
return false;
}
async function recoverHalfStartedBroker(
paths: CoreProjectPaths,
deps: CoreDependencies
): Promise<'running' | 'recovered' | 'clear' | 'blocked'> {
deps.fs.mkdirSync(paths.dataDir, { recursive: true });
const readiness = await waitForBrokerReadiness(paths, deps, 0, true);
if (readiness.state === 'running') {
return 'running';
}
if (readiness.state === 'starting') {
deps.warn(
`Broker process is running but the API is not ready; killing half-started broker (pid: ${readiness.conn.pid}).`
);
const stopped = await terminateProcess(readiness.conn.pid, deps, true);
if (!stopped) {
deps.error(
`Failed to stop half-started broker process (pid: ${readiness.conn.pid}). ` +
'Run `agent-relay down --force` to retry cleanup, or remove `.agentworkforce/relay/` after stopping the process.'
);
return 'blocked';
}
cleanupBrokerFiles(paths, deps);
return 'recovered';
}
const orphanCleanup = await killOrphanedBrokerProcesses(paths.projectRoot, deps, { force: true });
if (orphanCleanup.matchedCount > 0) {
if (orphanCleanup.killedCount < orphanCleanup.matchedCount) {
deps.error(
'Failed to stop all half-started broker processes. ' +
'Run `agent-relay down --force` to retry cleanup, or remove `.agentworkforce/relay/` after stopping the processes.'
);
return 'blocked';
}
cleanupBrokerFiles(paths, deps);
return 'recovered';
}
cleanupBrokerFiles(paths, deps);
return 'clear';
}
function cleanupBrokerFiles(paths: CoreProjectPaths, deps: CoreDependencies): void {
const runtimePath = path.join(paths.dataDir, 'runtime.json');
const relaySockPath = path.join(paths.dataDir, 'relay.sock');
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
safeUnlink(relaySockPath, deps);
safeUnlink(runtimePath, deps);
// Clean up lock files and legacy pid files
try {
for (const file of deps.fs.readdirSync(paths.dataDir)) {
if (file.startsWith('broker-') && (file.endsWith('.lock') || file.endsWith('.pid'))) {
safeUnlink(path.join(paths.dataDir, file), deps);
continue;
}
if (!file.startsWith('mcp-identity-')) {
continue;
}
const pidMatch = file.match(/^mcp-identity-(\d+)/);
if (!pidMatch) {
continue;
}
const pid = Number.parseInt(pidMatch[1], 10);
if (!isProcessRunning(pid, deps)) {
safeUnlink(path.join(paths.dataDir, file), deps);
}
}
} catch {
// Ignore read errors while cleaning up.
}
}
function childUpArgsForDetachedStart(options: UpOptions, deps: CoreDependencies): string[] {
const args = cliUserArgs(deps).filter((arg) => !matchesCliOption(arg, '--background'));
if (options.stateDir && !hasCliOption(args, '--state-dir')) {
args.push('--state-dir', path.resolve(options.stateDir));
}
if (options.workspaceKey && !hasCliOption(args, '--workspace-key')) {
args.push('--workspace-key', options.workspaceKey);
}
if (options.brokerName && !hasCliOption(args, '--broker-name')) {
args.push('--broker-name', options.brokerName);
}
if (options.verbose === true && !args.includes('--verbose')) {
args.push('--verbose');
}
return args;
}
function cliUserArgs(deps: CoreDependencies): string[] {
return hasEntrypointArgvSlot(deps) ? deps.argv.slice(2) : deps.argv.slice(1);
}
function detachedCliInvocation(deps: CoreDependencies, args: string[]): { command: string; args: string[] } {
if (shouldReexecThroughScript(deps)) {
return { command: deps.execPath, args: [deps.cliScript, ...args] };
}
return { command: deps.execPath, args };
}
function hasEntrypointArgvSlot(deps: CoreDependencies): boolean {
return isBundledBunExecutableEntrypoint(deps) || isCliScriptEntrypoint(deps);
}
function shouldReexecThroughScript(deps: CoreDependencies): boolean {
return isCliScriptEntrypoint(deps) && !sameCliPath(deps.execPath, deps.cliScript);
}
function isCliScriptEntrypoint(deps: CoreDependencies): boolean {
const cliScript = deps.cliScript.trim();
if (!cliScript) {
return false;
}
if (isBundledBunExecutableEntrypoint(deps)) {
return false;
}
if (sameCliPath(deps.execPath, cliScript)) {
return true;
}
return (
path.isAbsolute(cliScript) ||
cliScript.includes('/') ||
cliScript.includes('\\') ||
/\.[cm]?js$/i.test(cliScript)
);
}
function isBundledBunExecutableEntrypoint(deps: CoreDependencies): boolean {
// Bun --compile exposes argv[1] as a virtual path for the embedded executable.
return deps.argv[0] === 'bun' && deps.cliScript.startsWith('/$bunfs/root/');
}
function sameCliPath(left: string, right: string): boolean {
return path.resolve(left) === path.resolve(right);
}
function hasCliOption(args: string[], name: string): boolean {
return args.some((arg) => matchesCliOption(arg, name));
}
function matchesCliOption(arg: string, name: string): boolean {
return arg === name || arg.startsWith(`${name}=`);
}
async function checkBrokerReadiness(
paths: CoreProjectPaths,
deps: CoreDependencies,
requireApi: boolean
): Promise<BrokerReadiness> {
const conn = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
if (!conn || conn.pid <= 0) {
return { state: 'stopped' };
}
if (!isProcessRunning(conn.pid, deps)) {
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
return { state: 'stopped' };
}
if (!requireApi) {
return { state: 'running', conn };
}
const statusDetails = await readBrokerStatusDetails(conn);
if (statusDetails) {
return { state: 'running', conn, statusDetails };
}
return { state: 'starting', conn };
}
async function waitForBrokerReadiness(
paths: CoreProjectPaths,
deps: CoreDependencies,
waitMs: number,
requireApi: boolean,
verbose?: boolean
): Promise<BrokerReadiness> {
const deadline = deps.now() + waitMs;
let latest = await checkBrokerReadiness(paths, deps, requireApi);
vlog(deps, verbose, `Broker readiness: ${latest.state}`);
while (latest.state !== 'running' && waitMs > 0 && deps.now() < deadline) {
await deps.sleep(Math.min(STATUS_POLL_INTERVAL_MS, Math.max(0, deadline - deps.now())));
const previousState = latest.state;
latest = await checkBrokerReadiness(paths, deps, requireApi);