agent-relay 17.2.0 → 18.0.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/README.md +45 -270
- package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
- package/dist/cli/agent-relay-mcp.js +6 -5
- package/dist/cli/agent-relay-mcp.js.map +1 -1
- package/dist/cli/bootstrap.d.ts +1 -1
- package/dist/cli/bootstrap.d.ts.map +1 -1
- package/dist/cli/bootstrap.js +11 -29
- package/dist/cli/bootstrap.js.map +1 -1
- package/dist/cli/commands/agent.d.ts.map +1 -1
- package/dist/cli/commands/agent.js +3 -2
- package/dist/cli/commands/agent.js.map +1 -1
- package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
- package/dist/cli/commands/cloud-integration.js +2 -1
- package/dist/cli/commands/cloud-integration.js.map +1 -1
- package/dist/cli/commands/cloud-room.d.ts.map +1 -1
- package/dist/cli/commands/cloud-room.js +2 -1
- package/dist/cli/commands/cloud-room.js.map +1 -1
- package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
- package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
- package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
- package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
- package/dist/cli/commands/cloud-worker.d.ts +1 -1
- package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
- package/dist/cli/commands/cloud-worker.js +42 -31
- package/dist/cli/commands/cloud-worker.js.map +1 -1
- package/dist/cli/commands/cloud.d.ts.map +1 -1
- package/dist/cli/commands/cloud.js +6 -7
- package/dist/cli/commands/cloud.js.map +1 -1
- package/dist/cli/commands/core.d.ts +3 -91
- package/dist/cli/commands/core.d.ts.map +1 -1
- package/dist/cli/commands/core.js +5 -254
- package/dist/cli/commands/core.js.map +1 -1
- package/dist/cli/commands/fleet-agent.d.ts +9 -54
- package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
- package/dist/cli/commands/fleet-agent.js +105 -314
- package/dist/cli/commands/fleet-agent.js.map +1 -1
- package/dist/cli/commands/fleet.d.ts +0 -3
- package/dist/cli/commands/fleet.d.ts.map +1 -1
- package/dist/cli/commands/fleet.js +48 -267
- package/dist/cli/commands/fleet.js.map +1 -1
- package/dist/cli/commands/init.js +1 -1
- package/dist/cli/commands/init.js.map +1 -1
- package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
- package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
- package/dist/cli/commands/integration-cleanup-journal.js +611 -134
- package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
- package/dist/cli/commands/integration-recipient.d.ts +0 -17
- package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
- package/dist/cli/commands/integration-recipient.js +1 -104
- package/dist/cli/commands/integration-recipient.js.map +1 -1
- package/dist/cli/commands/integration.d.ts +7 -3
- package/dist/cli/commands/integration.d.ts.map +1 -1
- package/dist/cli/commands/integration.js +37 -82
- package/dist/cli/commands/integration.js.map +1 -1
- package/dist/cli/commands/local-workflow.d.ts +1 -1
- package/dist/cli/commands/local-workflow.d.ts.map +1 -1
- package/dist/cli/commands/local-workflow.js +20 -6
- package/dist/cli/commands/local-workflow.js.map +1 -1
- package/dist/cli/commands/node.d.ts +18 -20
- package/dist/cli/commands/node.d.ts.map +1 -1
- package/dist/cli/commands/node.js +42 -272
- package/dist/cli/commands/node.js.map +1 -1
- package/dist/cli/commands/product-surfaces.js +4 -4
- package/dist/cli/commands/product-surfaces.js.map +1 -1
- package/dist/cli/commands/session.d.ts.map +1 -1
- package/dist/cli/commands/session.js +2 -1
- package/dist/cli/commands/session.js.map +1 -1
- package/dist/cli/commands/skills.d.ts.map +1 -1
- package/dist/cli/commands/skills.js +2 -1
- package/dist/cli/commands/skills.js.map +1 -1
- package/dist/cli/commands/status.d.ts +1 -7
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +2 -28
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/commands/workspace.d.ts.map +1 -1
- package/dist/cli/commands/workspace.js +2 -2
- package/dist/cli/commands/workspace.js.map +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +1 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/lib/agent-relay-cli-reentry.d.ts +37 -0
- package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
- package/dist/cli/lib/agent-relay-cli-reentry.js +40 -0
- package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
- package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
- package/dist/cli/lib/agent-tools-mcp.js +3 -2
- package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
- package/dist/cli/lib/core-maintenance.d.ts +2 -3
- package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
- package/dist/cli/lib/core-maintenance.js +3 -37
- package/dist/cli/lib/core-maintenance.js.map +1 -1
- package/dist/cli/lib/desktop-presence.js +1 -1
- package/dist/cli/lib/desktop-presence.js.map +1 -1
- package/dist/cli/lib/install-paths.d.ts +100 -0
- package/dist/cli/lib/install-paths.d.ts.map +1 -0
- package/dist/cli/lib/install-paths.js +157 -0
- package/dist/cli/lib/install-paths.js.map +1 -0
- package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
- package/dist/cli/lib/product-surface-store.js +4 -1
- package/dist/cli/lib/product-surface-store.js.map +1 -1
- package/dist/cli/lib/relay-node.d.ts +7 -34
- package/dist/cli/lib/relay-node.d.ts.map +1 -1
- package/dist/cli/lib/relay-node.js +7 -182
- package/dist/cli/lib/relay-node.js.map +1 -1
- package/dist/cli/lib/removed-broker-command.d.ts +7 -0
- package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
- package/dist/cli/lib/removed-broker-command.js +13 -0
- package/dist/cli/lib/removed-broker-command.js.map +1 -0
- package/dist/cli/lib/sdk-client.d.ts +4 -4
- package/dist/cli/lib/sdk-client.js +4 -4
- package/dist/cli/lib/self-update.d.ts +8 -19
- package/dist/cli/lib/self-update.d.ts.map +1 -1
- package/dist/cli/lib/self-update.js +14 -28
- package/dist/cli/lib/self-update.js.map +1 -1
- package/dist/cli/lib/skills-install.d.ts.map +1 -1
- package/dist/cli/lib/skills-install.js +3 -2
- package/dist/cli/lib/skills-install.js.map +1 -1
- package/dist/cli/telemetry/events.d.ts +4 -1
- package/dist/cli/telemetry/events.d.ts.map +1 -1
- package/package.json +10 -15
- package/dist/auto/classifier.d.ts +0 -29
- package/dist/auto/classifier.d.ts.map +0 -1
- package/dist/auto/classifier.js +0 -126
- package/dist/auto/classifier.js.map +0 -1
- package/dist/auto/composer.d.ts +0 -105
- package/dist/auto/composer.d.ts.map +0 -1
- package/dist/auto/composer.js +0 -454
- package/dist/auto/composer.js.map +0 -1
- package/dist/auto/director-prompt.d.ts +0 -25
- package/dist/auto/director-prompt.d.ts.map +0 -1
- package/dist/auto/director-prompt.js +0 -53
- package/dist/auto/director-prompt.js.map +0 -1
- package/dist/auto/index.d.ts +0 -15
- package/dist/auto/index.d.ts.map +0 -1
- package/dist/auto/index.js +0 -13
- package/dist/auto/index.js.map +0 -1
- package/dist/cli/commands/local-agent.d.ts +0 -74
- package/dist/cli/commands/local-agent.d.ts.map +0 -1
- package/dist/cli/commands/local-agent.js +0 -969
- package/dist/cli/commands/local-agent.js.map +0 -1
- package/dist/cli/lib/attach-broker.d.ts +0 -17
- package/dist/cli/lib/attach-broker.d.ts.map +0 -1
- package/dist/cli/lib/attach-broker.js +0 -27
- package/dist/cli/lib/attach-broker.js.map +0 -1
- package/dist/cli/lib/attach-drive.d.ts +0 -376
- package/dist/cli/lib/attach-drive.d.ts.map +0 -1
- package/dist/cli/lib/attach-drive.js +0 -1212
- package/dist/cli/lib/attach-drive.js.map +0 -1
- package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
- package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
- package/dist/cli/lib/attach-fleet-node.js +0 -1347
- package/dist/cli/lib/attach-fleet-node.js.map +0 -1
- package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
- package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
- package/dist/cli/lib/attach-input-recovery.js +0 -559
- package/dist/cli/lib/attach-input-recovery.js.map +0 -1
- package/dist/cli/lib/attach-mode.d.ts +0 -2
- package/dist/cli/lib/attach-mode.d.ts.map +0 -1
- package/dist/cli/lib/attach-mode.js +0 -2
- package/dist/cli/lib/attach-mode.js.map +0 -1
- package/dist/cli/lib/attach-native.d.ts +0 -27
- package/dist/cli/lib/attach-native.d.ts.map +0 -1
- package/dist/cli/lib/attach-native.js +0 -267
- package/dist/cli/lib/attach-native.js.map +0 -1
- package/dist/cli/lib/attach-passthrough.d.ts +0 -193
- package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
- package/dist/cli/lib/attach-passthrough.js +0 -778
- package/dist/cli/lib/attach-passthrough.js.map +0 -1
- package/dist/cli/lib/attach-remote-node.d.ts +0 -21
- package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
- package/dist/cli/lib/attach-remote-node.js +0 -133
- package/dist/cli/lib/attach-remote-node.js.map +0 -1
- package/dist/cli/lib/attach-view.d.ts +0 -177
- package/dist/cli/lib/attach-view.d.ts.map +0 -1
- package/dist/cli/lib/attach-view.js +0 -455
- package/dist/cli/lib/attach-view.js.map +0 -1
- package/dist/cli/lib/attach.d.ts +0 -555
- package/dist/cli/lib/attach.d.ts.map +0 -1
- package/dist/cli/lib/attach.js +0 -1180
- package/dist/cli/lib/attach.js.map +0 -1
- package/dist/cli/lib/broker-connection.d.ts +0 -65
- package/dist/cli/lib/broker-connection.d.ts.map +0 -1
- package/dist/cli/lib/broker-connection.js +0 -144
- package/dist/cli/lib/broker-connection.js.map +0 -1
- package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
- package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
- package/dist/cli/lib/broker-lifecycle.js +0 -2290
- package/dist/cli/lib/broker-lifecycle.js.map +0 -1
- package/dist/cli/lib/broker-process-identity.d.ts +0 -38
- package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
- package/dist/cli/lib/broker-process-identity.js +0 -304
- package/dist/cli/lib/broker-process-identity.js.map +0 -1
- package/dist/cli/lib/client-factory.d.ts +0 -44
- package/dist/cli/lib/client-factory.d.ts.map +0 -1
- package/dist/cli/lib/client-factory.js +0 -64
- package/dist/cli/lib/client-factory.js.map +0 -1
- package/dist/cli/lib/collect-with-retry.d.ts +0 -24
- package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
- package/dist/cli/lib/collect-with-retry.js +0 -33
- package/dist/cli/lib/collect-with-retry.js.map +0 -1
- package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
- package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
- package/dist/cli/lib/fleet-attach-target.js +0 -57
- package/dist/cli/lib/fleet-attach-target.js.map +0 -1
- package/dist/cli/lib/fleet-hint.d.ts +0 -49
- package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
- package/dist/cli/lib/fleet-hint.js +0 -113
- package/dist/cli/lib/fleet-hint.js.map +0 -1
- package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
- package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
- package/dist/cli/lib/fleet-sidecar.js +0 -84
- package/dist/cli/lib/fleet-sidecar.js.map +0 -1
- package/dist/cli/lib/join-ticket.d.ts +0 -22
- package/dist/cli/lib/join-ticket.d.ts.map +0 -1
- package/dist/cli/lib/join-ticket.js +0 -96
- package/dist/cli/lib/join-ticket.js.map +0 -1
- package/dist/cli/lib/node-claim.d.ts +0 -468
- package/dist/cli/lib/node-claim.d.ts.map +0 -1
- package/dist/cli/lib/node-claim.js +0 -1349
- package/dist/cli/lib/node-claim.js.map +0 -1
- package/dist/cli/lib/node-definition-loader.d.ts +0 -19
- package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
- package/dist/cli/lib/node-definition-loader.js +0 -143
- package/dist/cli/lib/node-definition-loader.js.map +0 -1
- package/dist/cli/lib/node-provider-child.d.ts +0 -129
- package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
- package/dist/cli/lib/node-provider-child.js +0 -755
- package/dist/cli/lib/node-provider-child.js.map +0 -1
- package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
- package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
- package/dist/cli/lib/predictive-echo-screen.js +0 -74
- package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
- package/dist/cli/lib/project-broker-client.d.ts +0 -4
- package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
- package/dist/cli/lib/project-broker-client.js +0 -12
- package/dist/cli/lib/project-broker-client.js.map +0 -1
- package/dist/cli/lib/reflex-capture.d.ts +0 -41
- package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
- package/dist/cli/lib/reflex-capture.js +0 -128
- package/dist/cli/lib/reflex-capture.js.map +0 -1
- package/dist/cli/lib/workspace-env.d.ts +0 -8
- package/dist/cli/lib/workspace-env.d.ts.map +0 -1
- package/dist/cli/lib/workspace-env.js +0 -16
- package/dist/cli/lib/workspace-env.js.map +0 -1
|
@@ -1,2290 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { HarnessDriverClient } from '@agent-relay/harness-driver';
|
|
5
|
-
import { getBrokerBinaryPath } from '@agent-relay/harness-driver/broker-path';
|
|
6
|
-
import { startServeNode } from '@agent-relay/fleet';
|
|
7
|
-
import { createLogger } from '@agent-relay/utils';
|
|
8
|
-
import { redactCredentialValues } from '@agent-relay/cloud/redact';
|
|
9
|
-
import { brokerIdentityDirectory, locateBrokerIdentityFile, matchesBrokerIdentity, persistBrokerIdentity, readBrokerIdentities, removeBrokerIdentity, } from './broker-process-identity.js';
|
|
10
|
-
import { track } from '../telemetry/index.js';
|
|
11
|
-
import { buildBundledAgentRelayMcpCommand, isBundledBunEntrypointPath } from './agent-relay-mcp-command.js';
|
|
12
|
-
import { errorClassName } from './telemetry-helpers.js';
|
|
13
|
-
import { runSignalHandler } from './exit.js';
|
|
14
|
-
import { createTriggerSyncClient, resolveNodeCapacityHarnesses, resolveNodeMaxAgents, } from './fleet-sidecar.js';
|
|
15
|
-
import { discoverNodeConfigPath, loadNodeDefinition } from './node-definition-loader.js';
|
|
16
|
-
import { describeNodeDefinitionViaNode, descriptorCapacitySource, startNodeJsNodeProvider, } from './node-provider-child.js';
|
|
17
|
-
import { describeError } from './describe-error.js';
|
|
18
|
-
import { acquireNodeClaim, adoptNodeClaim, closeNodeClaimHold, describeNodeClaimHolder, enrolledNodeIdForClaim, findLiveStateDirBroker, inspectNodeClaimHold, listHeldNodeClaims, normalizeClaimStateDir, openNodeClaimHold, recordSpawnedBrokerChild, releaseNodeClaim, releaseNodeClaimsForBroker, } from './node-claim.js';
|
|
19
|
-
import { maskSecret } from './redact.js';
|
|
20
|
-
import { startReflexCapture } from './reflex-capture.js';
|
|
21
|
-
import { readProjectWorkspaceSession, resolveWorkspaceSelection, writeProjectWorkspaceKeyPreservingSession, } from './project-workspace-key.js';
|
|
22
|
-
const MAX_API_PORT_ATTEMPTS = 25;
|
|
23
|
-
const MAX_PORT = 65535;
|
|
24
|
-
const DEFAULT_BROKER_BASE_PORT = 3888;
|
|
25
|
-
/** The broker writes this file with URL, port, API key, and PID. */
|
|
26
|
-
const CONNECTION_FILENAME = 'connection.json';
|
|
27
|
-
const BACKGROUND_START_ERROR_FILENAME = 'background-start-error.log';
|
|
28
|
-
export const WORKSPACE_BINDING_SOURCE_ENV = 'AGENT_RELAY_WORKSPACE_SOURCE';
|
|
29
|
-
const STATUS_POLL_INTERVAL_MS = 500;
|
|
30
|
-
/**
|
|
31
|
-
* The broker's initial Relaycast handshake is bounded at 44s. Keep detached
|
|
32
|
-
* readiness above that budget with explicit setup/observation margin so a
|
|
33
|
-
* valid broker is not killed while its startup handshake is still in flight.
|
|
34
|
-
*/
|
|
35
|
-
export const DETACHED_START_READY_TIMEOUT_MS = 60_000;
|
|
36
|
-
const NODE_DELIVERY_READY_TIMEOUT_MS = 10_000;
|
|
37
|
-
// Bounded wait for the broker's background-minted node token to surface on
|
|
38
|
-
// `/api/session` when serving a capability definition without an explicit
|
|
39
|
-
// RELAY_NODE_TOKEN.
|
|
40
|
-
const NODE_TOKEN_WAIT_MS = 15_000;
|
|
41
|
-
function parseBrokerConnection(raw) {
|
|
42
|
-
try {
|
|
43
|
-
const conn = JSON.parse(raw);
|
|
44
|
-
if (typeof conn.url === 'string' &&
|
|
45
|
-
typeof conn.port === 'number' &&
|
|
46
|
-
typeof conn.api_key === 'string' &&
|
|
47
|
-
typeof conn.pid === 'number' &&
|
|
48
|
-
conn.pid > 0) {
|
|
49
|
-
return conn;
|
|
50
|
-
}
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
catch {
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
function readBrokerConnectionFromFs(fileSystem, dataDir) {
|
|
58
|
-
const connPath = path.join(dataDir, CONNECTION_FILENAME);
|
|
59
|
-
try {
|
|
60
|
-
const raw = fileSystem.readFileSync(connPath, 'utf-8');
|
|
61
|
-
return parseBrokerConnection(raw);
|
|
62
|
-
}
|
|
63
|
-
catch {
|
|
64
|
-
return null;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Read the broker's connection.json file from the data directory.
|
|
69
|
-
* Returns null if the file doesn't exist or is invalid.
|
|
70
|
-
*/
|
|
71
|
-
export function readBrokerConnection(dataDir) {
|
|
72
|
-
return readBrokerConnectionFromFs(fs, dataDir);
|
|
73
|
-
}
|
|
74
|
-
function toErrorMessage(err) {
|
|
75
|
-
return describeError(err);
|
|
76
|
-
}
|
|
77
|
-
/** Emit a `[verbose]`-prefixed step marker via `deps.log` when `--verbose` is set. */
|
|
78
|
-
function vlog(deps, verbose, message) {
|
|
79
|
-
if (verbose) {
|
|
80
|
-
deps.log(`[verbose] ${message}`);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
/** True when any log flag (or `--verbose`) opts the node into structured logging. */
|
|
84
|
-
function nodeLoggingEnabled(options) {
|
|
85
|
-
return Boolean(options.logFile || options.logLevel || options.logJson || options.verbose);
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Translate the `--log-*` (and `--verbose`) flags into the `AGENT_RELAY_LOG_*`
|
|
89
|
-
* environment the shared `createLogger` reads. `--verbose` alone raises the
|
|
90
|
-
* floor to DEBUG so per-capability registration lines surface; an explicit
|
|
91
|
-
* `--log-level` always wins. Called before the fleet sidecar starts.
|
|
92
|
-
*/
|
|
93
|
-
function applyNodeLogEnv(options, deps) {
|
|
94
|
-
if (options.logFile) {
|
|
95
|
-
deps.env.AGENT_RELAY_LOG_FILE = options.logFile;
|
|
96
|
-
}
|
|
97
|
-
const level = options.logLevel ?? (options.verbose ? 'debug' : undefined);
|
|
98
|
-
if (level) {
|
|
99
|
-
deps.env.AGENT_RELAY_LOG_LEVEL = level.toUpperCase();
|
|
100
|
-
}
|
|
101
|
-
if (options.logJson) {
|
|
102
|
-
deps.env.AGENT_RELAY_LOG_JSON = '1';
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Keep background Reflex maintenance out of the broker's normal startup
|
|
107
|
-
* output. When a node log file is configured, preserve those diagnostics in
|
|
108
|
-
* the same structured log stream as the other long-running node work; when
|
|
109
|
-
* `--verbose` is requested, surface them to the interactive terminal too.
|
|
110
|
-
*/
|
|
111
|
-
function createReflexDiagnosticLog(options, deps) {
|
|
112
|
-
const logger = options.logFile ? createLogger('reflex') : undefined;
|
|
113
|
-
return (message) => {
|
|
114
|
-
if (options.verbose) {
|
|
115
|
-
vlog(deps, true, message);
|
|
116
|
-
}
|
|
117
|
-
if (!logger)
|
|
118
|
-
return;
|
|
119
|
-
// The logger already scopes lines with [reflex]; drop the message's own
|
|
120
|
-
// prefix so the file does not read "[reflex] [reflex] ...".
|
|
121
|
-
const unscoped = message.startsWith('[reflex] ') ? message.slice('[reflex] '.length) : message;
|
|
122
|
-
if (message.startsWith('[reflex] cloud sync failed:')) {
|
|
123
|
-
logger.warn(unscoped);
|
|
124
|
-
}
|
|
125
|
-
else {
|
|
126
|
-
logger.info(unscoped);
|
|
127
|
-
}
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
function isRecord(value) {
|
|
131
|
-
return typeof value === 'object' && value !== null;
|
|
132
|
-
}
|
|
133
|
-
export function readNodeDeliveryStatus(status) {
|
|
134
|
-
if (!isRecord(status)) {
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
const snake = isRecord(status.node_delivery) ? status.node_delivery : null;
|
|
138
|
-
const tokenPresent = typeof snake?.token_present === 'boolean' ? snake.token_present : false;
|
|
139
|
-
const connected = typeof status.node_connected === 'boolean'
|
|
140
|
-
? status.node_connected
|
|
141
|
-
: typeof snake?.connected === 'boolean'
|
|
142
|
-
? snake.connected
|
|
143
|
-
: false;
|
|
144
|
-
return { tokenPresent, connected };
|
|
145
|
-
}
|
|
146
|
-
function nodeDeliveryReady(status) {
|
|
147
|
-
const delivery = readNodeDeliveryStatus(status);
|
|
148
|
-
return Boolean(delivery?.tokenPresent && delivery.connected);
|
|
149
|
-
}
|
|
150
|
-
function formatNodeDeliveryStatus(status) {
|
|
151
|
-
const delivery = readNodeDeliveryStatus(status);
|
|
152
|
-
if (!delivery) {
|
|
153
|
-
return 'unknown';
|
|
154
|
-
}
|
|
155
|
-
if (!delivery.tokenPresent) {
|
|
156
|
-
return 'DOWN (no node token)';
|
|
157
|
-
}
|
|
158
|
-
return delivery.connected ? 'CONNECTED' : 'DOWN (node websocket disconnected)';
|
|
159
|
-
}
|
|
160
|
-
function errorCode(err) {
|
|
161
|
-
if (!err || typeof err !== 'object')
|
|
162
|
-
return undefined;
|
|
163
|
-
const code = err.code;
|
|
164
|
-
return typeof code === 'string' ? code : undefined;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Extract a human-meaningful detail string from an error, walking `err.cause`.
|
|
168
|
-
*
|
|
169
|
-
* The broker-start specialization of {@link describeError}: it starts from the
|
|
170
|
-
* shared description and appends the cause chain's detail and error codes.
|
|
171
|
-
*
|
|
172
|
-
* Node's native `fetch()` throws `TypeError: fetch failed` for any network
|
|
173
|
-
* problem and stuffs the real reason (ECONNREFUSED, ENOTFOUND, AbortError,
|
|
174
|
-
* UND_ERR_CONNECT_TIMEOUT, …) into `err.cause`. Without unwrapping, every
|
|
175
|
-
* outbound HTTP failure looks identical to the user.
|
|
176
|
-
*
|
|
177
|
-
* Exported for testing.
|
|
178
|
-
*/
|
|
179
|
-
export function describeErrorWithCause(err) {
|
|
180
|
-
const top = toErrorMessage(err);
|
|
181
|
-
if (!(err instanceof Error) || !err.cause)
|
|
182
|
-
return top;
|
|
183
|
-
// Walk the cause chain and collect the deepest message + any error codes.
|
|
184
|
-
const codes = [];
|
|
185
|
-
let detail;
|
|
186
|
-
let cursor = err.cause;
|
|
187
|
-
let depth = 0;
|
|
188
|
-
while (cursor && depth < 5) {
|
|
189
|
-
const code = errorCode(cursor);
|
|
190
|
-
if (code && !codes.includes(code))
|
|
191
|
-
codes.push(code);
|
|
192
|
-
if (cursor instanceof Error && cursor.message) {
|
|
193
|
-
detail = cursor.message;
|
|
194
|
-
}
|
|
195
|
-
cursor = cursor instanceof Error ? cursor.cause : undefined;
|
|
196
|
-
depth += 1;
|
|
197
|
-
}
|
|
198
|
-
const parts = [top];
|
|
199
|
-
if (detail && detail !== top)
|
|
200
|
-
parts.push(detail);
|
|
201
|
-
if (codes.length > 0)
|
|
202
|
-
parts.push(`[${codes.join(', ')}]`);
|
|
203
|
-
return redactCredentialValues(parts.join(' — '));
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Pick the best `error_class` for telemetry. Prefer a network-style code from
|
|
207
|
-
* `err.cause` (ECONNREFUSED etc.) over the generic constructor name (TypeError)
|
|
208
|
-
* — a code is more actionable in PostHog and matches the schema's example
|
|
209
|
-
* values for `BrokerStartFailedEvent.error_class`.
|
|
210
|
-
*
|
|
211
|
-
* Exported for testing.
|
|
212
|
-
*/
|
|
213
|
-
export function classifyBrokerStartError(err) {
|
|
214
|
-
let cursor = err;
|
|
215
|
-
let depth = 0;
|
|
216
|
-
while (cursor && depth < 5) {
|
|
217
|
-
const code = errorCode(cursor);
|
|
218
|
-
if (code)
|
|
219
|
-
return code;
|
|
220
|
-
cursor = cursor instanceof Error ? cursor.cause : undefined;
|
|
221
|
-
depth += 1;
|
|
222
|
-
}
|
|
223
|
-
return errorClassName(err) ?? 'Error';
|
|
224
|
-
}
|
|
225
|
-
/** Exported for testing. */
|
|
226
|
-
export function classifyBrokerStartStage(_err, message) {
|
|
227
|
-
if (isBrokerAlreadyRunningError(message))
|
|
228
|
-
return 'already_running';
|
|
229
|
-
// Node's native fetch() throws "fetch failed"; the CLI's Bun-compiled
|
|
230
|
-
// binaries throw Bun's own connect-failure text instead ("Unable to
|
|
231
|
-
// connect. Is the computer able to access the url?"). Recognize both so
|
|
232
|
-
// the shipped binary doesn't misclassify every connect failure as generic
|
|
233
|
-
// 'startup'.
|
|
234
|
-
if (/fetch failed/i.test(message) || /unable to connect/i.test(message))
|
|
235
|
-
return 'connect';
|
|
236
|
-
if (/Broker did not report API port/i.test(message))
|
|
237
|
-
return 'spawn';
|
|
238
|
-
if (/Broker process exited with code/i.test(message))
|
|
239
|
-
return 'spawn';
|
|
240
|
-
if (/ENOENT/i.test(message) && /broker/i.test(message))
|
|
241
|
-
return 'resolve_binary';
|
|
242
|
-
return 'startup';
|
|
243
|
-
}
|
|
244
|
-
/**
|
|
245
|
-
* Render the same "Failed to start broker" diagnostic + telemetry the
|
|
246
|
-
* `runUpCommand` catch block has always used. Extracted so the process-level
|
|
247
|
-
* crash guard (below) can report an unhandled rejection/exception the exact
|
|
248
|
-
* same way as an ordinary caught startup failure.
|
|
249
|
-
*/
|
|
250
|
-
function reportBrokerStartFailure(err, deps, paths, options) {
|
|
251
|
-
const message = toErrorMessage(err);
|
|
252
|
-
const stage = classifyBrokerStartStage(err, message);
|
|
253
|
-
track('broker_start_failed', {
|
|
254
|
-
stage,
|
|
255
|
-
error_class: classifyBrokerStartError(err),
|
|
256
|
-
});
|
|
257
|
-
const detailedMessage = describeErrorWithCause(err);
|
|
258
|
-
recordBackgroundStartError(detailedMessage, paths.dataDir, options.backgroundChild === true, deps);
|
|
259
|
-
if (isBrokerAlreadyRunningError(message)) {
|
|
260
|
-
reportAlreadyRunningError(message, paths.dataDir, deps);
|
|
261
|
-
}
|
|
262
|
-
else {
|
|
263
|
-
deps.error(`Failed to start broker: ${detailedMessage}`);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* `runUpCommand`'s startup try/catch only sees rejections it actually
|
|
268
|
-
* `await`s. Anything that rejects off to the side — a fire-and-forget
|
|
269
|
-
* background task inside a capability provider, an addon's internal promise
|
|
270
|
-
* chain, etc. — crashes the process via Node's bare default
|
|
271
|
-
* uncaughtException/unhandledRejection handler instead, which prints no
|
|
272
|
-
* "Failed to start broker" line and never records `broker_start_failed`
|
|
273
|
-
* telemetry. Observed in the wild as a `node up` that printed "Broker
|
|
274
|
-
* started." and then died with nothing further logged.
|
|
275
|
-
*
|
|
276
|
-
* This guard is armed for the lifetime of the foreground startup + hold-open
|
|
277
|
-
* phase so that class of crash gets the same diagnostic + telemetry + cleanup
|
|
278
|
-
* treatment as an ordinary caught failure, instead of vanishing into Node's
|
|
279
|
-
* default handler. `dispose()` must be called (via `finally`) so the
|
|
280
|
-
* listeners don't outlive this command invocation.
|
|
281
|
-
*/
|
|
282
|
-
function installStartupCrashGuard(deps, paths, options, shutdownOnce) {
|
|
283
|
-
let handled = false;
|
|
284
|
-
const handleCrash = (err) => {
|
|
285
|
-
if (handled)
|
|
286
|
-
return;
|
|
287
|
-
handled = true;
|
|
288
|
-
// `deps.exit(1)` throws `CliExit` (see `defaultExit`) rather than really
|
|
289
|
-
// exiting. Run this body through `runSignalHandler` -- the same wrapper
|
|
290
|
-
// `deps.onSignal` uses -- so that throw becomes a real, telemetry-flushed
|
|
291
|
-
// `process.exit`. Without it, the throw rejects this detached body with
|
|
292
|
-
// no awaiter; the `unhandledRejection` it produces hits `handleCrash`
|
|
293
|
-
// again, sees `handled` already true, and is silently dropped, leaving
|
|
294
|
-
// `runUpCommand` stuck in `holdOpen` instead of exiting.
|
|
295
|
-
runSignalHandler(async () => {
|
|
296
|
-
await shutdownOnce().catch(() => undefined);
|
|
297
|
-
reportBrokerStartFailure(err, deps, paths, options);
|
|
298
|
-
deps.exit(1);
|
|
299
|
-
});
|
|
300
|
-
};
|
|
301
|
-
process.on('uncaughtException', handleCrash);
|
|
302
|
-
process.on('unhandledRejection', handleCrash);
|
|
303
|
-
return {
|
|
304
|
-
dispose: () => {
|
|
305
|
-
process.off('uncaughtException', handleCrash);
|
|
306
|
-
process.off('unhandledRejection', handleCrash);
|
|
307
|
-
},
|
|
308
|
-
// Called from the normal catch block so a straggler process-level event
|
|
309
|
-
// for the same failure can't fire a second, duplicate report after this
|
|
310
|
-
// function has already handled it and moved on.
|
|
311
|
-
markHandled: () => {
|
|
312
|
-
handled = true;
|
|
313
|
-
},
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
async function resolveApiPortWithFallback(startApiPort, maxAttempts, deps) {
|
|
317
|
-
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
318
|
-
const candidatePort = startApiPort + attempt;
|
|
319
|
-
if (candidatePort > MAX_PORT) {
|
|
320
|
-
break;
|
|
321
|
-
}
|
|
322
|
-
const inUse = await deps.isPortInUse(candidatePort);
|
|
323
|
-
if (!inUse) {
|
|
324
|
-
if (attempt > 0) {
|
|
325
|
-
deps.warn(`API port ${startApiPort} is already in use; trying ${candidatePort}`);
|
|
326
|
-
}
|
|
327
|
-
return candidatePort;
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
throw new Error(`Failed to find an available API port near ${startApiPort}.`);
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* The broker base port. `AGENT_RELAY_BROKER_PORT` overrides the default so
|
|
334
|
-
* multiple brokers can run side by side. A value of `0` asks the OS to assign
|
|
335
|
-
* the API port atomically during broker bind, which avoids probe-then-bind
|
|
336
|
-
* races in concurrent test stacks.
|
|
337
|
-
*/
|
|
338
|
-
export function resolveBrokerBasePort(deps) {
|
|
339
|
-
const raw = Number.parseInt(deps.env.AGENT_RELAY_BROKER_PORT ?? '', 10);
|
|
340
|
-
return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_BROKER_BASE_PORT;
|
|
341
|
-
}
|
|
342
|
-
/** Bounded attempts for {@link getBrokerStatusWithRetry}'s post-handshake status check. */
|
|
343
|
-
const STATUS_CHECK_MAX_ATTEMPTS = 4;
|
|
344
|
-
/** Fixed delay between status-check retries, in ms. */
|
|
345
|
-
const STATUS_CHECK_RETRY_DELAY_MS = 300;
|
|
346
|
-
/**
|
|
347
|
-
* `candidate.getStatus()` is the first request made against a broker that
|
|
348
|
-
* just finished a successful handshake -- `HarnessDriverClient.spawn()`'s own
|
|
349
|
-
* `getSession()` poll already confirmed the broker was reachable moments
|
|
350
|
-
* earlier. Under load, the broker can be transiently preempted between that
|
|
351
|
-
* handshake and this immediate follow-up request, surfacing as a bare
|
|
352
|
-
* connect failure (Node's `TypeError: fetch failed` / Bun's "Unable to
|
|
353
|
-
* connect. Is the computer able to access the url?"), which previously had
|
|
354
|
-
* zero tolerance: one bad request and the whole `up` was reported failed
|
|
355
|
-
* even though the broker was (and remained) healthy.
|
|
356
|
-
*
|
|
357
|
-
* A handful of short, fixed-delay retries absorb that hiccup. This mirrors
|
|
358
|
-
* the *spirit* of the 503-retry loop `HarnessDriverClient.spawn()` runs
|
|
359
|
-
* during the handshake, not its duration -- that loop waits out a possibly
|
|
360
|
-
* slow cold start; this one is only smoothing a momentary preemption right
|
|
361
|
-
* after a broker we already know is up, so the total budget is much
|
|
362
|
-
* shorter (under 1s across all retries).
|
|
363
|
-
*
|
|
364
|
-
* Exported for testing.
|
|
365
|
-
*/
|
|
366
|
-
export async function getBrokerStatusWithRetry(candidate, deps, verbose) {
|
|
367
|
-
let lastError;
|
|
368
|
-
for (let attempt = 1; attempt <= STATUS_CHECK_MAX_ATTEMPTS; attempt += 1) {
|
|
369
|
-
try {
|
|
370
|
-
return await candidate.getStatus();
|
|
371
|
-
}
|
|
372
|
-
catch (err) {
|
|
373
|
-
lastError = err;
|
|
374
|
-
const isConnectFailure = classifyBrokerStartStage(err, toErrorMessage(err)) === 'connect';
|
|
375
|
-
if (!isConnectFailure || attempt >= STATUS_CHECK_MAX_ATTEMPTS)
|
|
376
|
-
break;
|
|
377
|
-
vlog(deps, verbose, `Broker status check failed (attempt ${attempt}/${STATUS_CHECK_MAX_ATTEMPTS}), retrying in ${STATUS_CHECK_RETRY_DELAY_MS}ms...`);
|
|
378
|
-
await deps.sleep(STATUS_CHECK_RETRY_DELAY_MS);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
throw lastError;
|
|
382
|
-
}
|
|
383
|
-
export async function startBrokerWithPortFallback(paths, basePort, deps, brokerName, verbose,
|
|
384
|
-
/**
|
|
385
|
-
* Invoked as soon as the broker child process has been spawned and its
|
|
386
|
-
* client handle exists, well before the handshake/status-check retries
|
|
387
|
-
* below resolve. Lets the caller wire up cleanup (e.g. a SIGTERM handler)
|
|
388
|
-
* against the real process immediately, instead of only after this whole
|
|
389
|
-
* function returns -- a signal arriving during the status check would
|
|
390
|
-
* otherwise find no handle to shut down and leak the broker child.
|
|
391
|
-
*/
|
|
392
|
-
onCandidateReady,
|
|
393
|
-
/**
|
|
394
|
-
* Descriptors every spawn attempt must hand the broker child. `node up`
|
|
395
|
-
* passes its node claim's hold descriptor, which the child inherits across
|
|
396
|
-
* `fork` — so the claim reads as held from the instant a broker exists,
|
|
397
|
-
* rather than from the moment one of them manages to write something down.
|
|
398
|
-
*/
|
|
399
|
-
inheritFds = [],
|
|
400
|
-
/**
|
|
401
|
-
* Invoked with the broker child's pid in the same turn `spawn()` returns it
|
|
402
|
-
* — before the handshake, and before a launcher script can `exec` into the
|
|
403
|
-
* real broker. `node up` writes it onto the node claim, so the process the
|
|
404
|
-
* inherited descriptor fences stays identifiable whatever executable it ends
|
|
405
|
-
* up running.
|
|
406
|
-
*/
|
|
407
|
-
onBrokerSpawn) {
|
|
408
|
-
if (basePort === 0) {
|
|
409
|
-
vlog(deps, verbose, 'Asking the OS to assign the broker API port...');
|
|
410
|
-
const candidate = await deps.createRelay(paths.projectRoot, 0, brokerName, verbose, inheritFds, onBrokerSpawn);
|
|
411
|
-
onCandidateReady?.(candidate);
|
|
412
|
-
try {
|
|
413
|
-
await getBrokerStatusWithRetry(candidate, deps, verbose);
|
|
414
|
-
if (!candidate.apiPort) {
|
|
415
|
-
throw new Error('Broker started without reporting its OS-assigned API port.');
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
catch (startupError) {
|
|
419
|
-
try {
|
|
420
|
-
await candidate.shutdown();
|
|
421
|
-
}
|
|
422
|
-
catch (cleanupError) {
|
|
423
|
-
throw new AggregateError([startupError, cleanupError], 'Broker startup validation failed and cleanup also failed.', { cause: startupError });
|
|
424
|
-
}
|
|
425
|
-
throw startupError;
|
|
426
|
-
}
|
|
427
|
-
vlog(deps, verbose, `API port assigned: ${candidate.apiPort}`);
|
|
428
|
-
return { relay: candidate, apiPort: candidate.apiPort };
|
|
429
|
-
}
|
|
430
|
-
// Resolve a free API port BEFORE spawning the broker. This avoids
|
|
431
|
-
// spawning (and flocking) multiple --persist brokers during retry,
|
|
432
|
-
// which caused stale-flock "already running" errors.
|
|
433
|
-
const startApiPort = basePort + 1;
|
|
434
|
-
vlog(deps, verbose, `Resolving a free API port starting near ${startApiPort}...`);
|
|
435
|
-
const apiPort = await resolveApiPortWithFallback(startApiPort, MAX_API_PORT_ATTEMPTS, deps);
|
|
436
|
-
vlog(deps, verbose, `API port resolved: ${apiPort}`);
|
|
437
|
-
vlog(deps, verbose, 'Creating broker client (spawns broker process, waits for handshake)...');
|
|
438
|
-
const candidate = await deps.createRelay(paths.projectRoot, apiPort, brokerName, verbose, inheritFds, onBrokerSpawn);
|
|
439
|
-
onCandidateReady?.(candidate);
|
|
440
|
-
vlog(deps, verbose, 'Broker client created. Checking broker status...');
|
|
441
|
-
try {
|
|
442
|
-
await getBrokerStatusWithRetry(candidate, deps, verbose);
|
|
443
|
-
}
|
|
444
|
-
catch (startupError) {
|
|
445
|
-
try {
|
|
446
|
-
await candidate.shutdown();
|
|
447
|
-
}
|
|
448
|
-
catch (cleanupError) {
|
|
449
|
-
throw new AggregateError([startupError, cleanupError], 'Broker startup validation failed and cleanup also failed.', { cause: startupError });
|
|
450
|
-
}
|
|
451
|
-
throw startupError;
|
|
452
|
-
}
|
|
453
|
-
vlog(deps, verbose, 'Broker status check passed.');
|
|
454
|
-
return { relay: candidate, apiPort };
|
|
455
|
-
}
|
|
456
|
-
/** Reject if `promise` doesn't settle within `ms`, clearing the timer on settle. */
|
|
457
|
-
function withTimeout(promise, ms) {
|
|
458
|
-
return new Promise((resolve, reject) => {
|
|
459
|
-
const timer = setTimeout(() => reject(new Error('session read exceeded token-wait budget')), ms);
|
|
460
|
-
promise.then((value) => {
|
|
461
|
-
clearTimeout(timer);
|
|
462
|
-
resolve(value);
|
|
463
|
-
}, (err) => {
|
|
464
|
-
clearTimeout(timer);
|
|
465
|
-
reject(err);
|
|
466
|
-
});
|
|
467
|
-
});
|
|
468
|
-
}
|
|
469
|
-
/**
|
|
470
|
-
* Resolve the broker's node identity from repeated `/api/session` reads.
|
|
471
|
-
*
|
|
472
|
-
* The broker publishes its node id as soon as the workspace handshake completes,
|
|
473
|
-
* but mints the node token off the API-readiness path (in the background), so a
|
|
474
|
-
* freshly started broker can report `node_id` before `node_token`. When
|
|
475
|
-
* `awaitTokenMs` is set, poll until the token appears (or the budget elapses) so
|
|
476
|
-
* a provider that needs the broker-minted token isn't skipped over a startup
|
|
477
|
-
* race. A transient session-read error yields the best identity seen so far
|
|
478
|
-
* (identity without token), or `null` if no `node_id` was ever read.
|
|
479
|
-
*/
|
|
480
|
-
export async function resolveNodeIdentityFromSession(getSession, options = {}) {
|
|
481
|
-
const awaitTokenMs = options.awaitTokenMs ?? 0;
|
|
482
|
-
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
483
|
-
const deadline = Date.now() + awaitTokenMs;
|
|
484
|
-
let identity = null;
|
|
485
|
-
for (;;) {
|
|
486
|
-
let session;
|
|
487
|
-
try {
|
|
488
|
-
// Bound each read to the remaining token-wait budget so a single stalled
|
|
489
|
-
// `/api/session` can't hold startup past `awaitTokenMs` (the transport's
|
|
490
|
-
// own request timeout is far longer). The non-await path issues one read
|
|
491
|
-
// and doesn't need the bound.
|
|
492
|
-
session =
|
|
493
|
-
awaitTokenMs > 0
|
|
494
|
-
? await withTimeout(getSession(), Math.max(0, deadline - Date.now()))
|
|
495
|
-
: await getSession();
|
|
496
|
-
}
|
|
497
|
-
catch {
|
|
498
|
-
return identity;
|
|
499
|
-
}
|
|
500
|
-
if (!session.node_id)
|
|
501
|
-
return identity;
|
|
502
|
-
identity = {
|
|
503
|
-
nodeId: session.node_id,
|
|
504
|
-
nodeName: session.node_name ?? session.node_id,
|
|
505
|
-
...(session.node_token ? { nodeToken: session.node_token } : {}),
|
|
506
|
-
};
|
|
507
|
-
if (session.node_token || awaitTokenMs <= 0 || Date.now() >= deadline) {
|
|
508
|
-
return identity;
|
|
509
|
-
}
|
|
510
|
-
await sleep(250);
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
/**
|
|
514
|
-
* Read the node id/name the broker registered as, from its HTTP session. The
|
|
515
|
-
* capability providers attach to this same node so they share its identity.
|
|
516
|
-
*/
|
|
517
|
-
async function readBrokerNodeIdentity(conn, options = {}) {
|
|
518
|
-
const client = new HarnessDriverClient({ baseUrl: conn.url, apiKey: conn.api_key });
|
|
519
|
-
try {
|
|
520
|
-
return await resolveNodeIdentityFromSession(() => client.getSession(), options);
|
|
521
|
-
}
|
|
522
|
-
finally {
|
|
523
|
-
client.disconnect();
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Serve the project's capability definitions as node providers connected
|
|
528
|
-
* directly to the engine, alongside the broker provider: an `agent-relay.{ts,…}`
|
|
529
|
-
* definition via {@link startServeNode}. When no definition exists, nothing is
|
|
530
|
-
* served — the broker's capacity already brings the node online. Best-effort:
|
|
531
|
-
* a provider setup failure never aborts `up`.
|
|
532
|
-
*/
|
|
533
|
-
async function startNodeCapabilityProviders(paths, relay, options, deps, nodePlan) {
|
|
534
|
-
if (!nodePlan) {
|
|
535
|
-
return undefined;
|
|
536
|
-
}
|
|
537
|
-
const conn = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
|
|
538
|
-
if (!conn) {
|
|
539
|
-
deps.warn('Capability providers skipped: broker connection file was not available.');
|
|
540
|
-
return undefined;
|
|
541
|
-
}
|
|
542
|
-
const baseUrl = deps.env.RELAY_BASE_URL?.trim();
|
|
543
|
-
// Serving a definition needs the node token. When no explicit RELAY_NODE_TOKEN
|
|
544
|
-
// is set we rely on the broker's background-minted token, which can lag its
|
|
545
|
-
// node id by a Relaycast round-trip — wait a bounded window for it rather than
|
|
546
|
-
// racing the mint and skipping the provider.
|
|
547
|
-
const awaitTokenMs = deps.env.RELAY_NODE_TOKEN?.trim() ? 0 : NODE_TOKEN_WAIT_MS;
|
|
548
|
-
const identity = await readBrokerNodeIdentity(conn, { awaitTokenMs });
|
|
549
|
-
if (!identity) {
|
|
550
|
-
deps.warn('Capability providers skipped: the broker did not report its node id yet.');
|
|
551
|
-
return undefined;
|
|
552
|
-
}
|
|
553
|
-
// The broker mints its own node token when RELAY_NODE_TOKEN is unset (local,
|
|
554
|
-
// un-enrolled); all providers on the node share that token, so fall back to
|
|
555
|
-
// the one it reports on its session rather than requiring pre-enrollment.
|
|
556
|
-
const nodeToken = deps.env.RELAY_NODE_TOKEN?.trim() || identity.nodeToken;
|
|
557
|
-
if (!nodeToken) {
|
|
558
|
-
deps.warn('Capability providers skipped: no node token available from the broker or environment.');
|
|
559
|
-
return undefined;
|
|
560
|
-
}
|
|
561
|
-
const served = [];
|
|
562
|
-
let nodeJsChild;
|
|
563
|
-
if (nodePlan?.mode === 'in-process') {
|
|
564
|
-
const nodeDefinition = nodePlan.definition;
|
|
565
|
-
try {
|
|
566
|
-
const workspaceKey = relay.workspaceKey;
|
|
567
|
-
served.push(startServeNode({
|
|
568
|
-
definition: nodeDefinition,
|
|
569
|
-
connection: {
|
|
570
|
-
...(baseUrl ? { baseUrl } : {}),
|
|
571
|
-
nodeToken,
|
|
572
|
-
nodeId: identity.nodeId,
|
|
573
|
-
},
|
|
574
|
-
nameOverride: options.nodeName ?? identity.nodeName,
|
|
575
|
-
// The served definition attaches as its own provider, distinct from the
|
|
576
|
-
// broker ("broker") on the same node.
|
|
577
|
-
providerName: nodeDefinition.name,
|
|
578
|
-
...(workspaceKey ? { triggers: createTriggerSyncClient({ workspaceKey, baseUrl }) } : {}),
|
|
579
|
-
reconnect: true,
|
|
580
|
-
// With any --log-* flag (or --verbose), surface the node's full lifecycle
|
|
581
|
-
// — capabilities registered, every action invoked/completed — through the
|
|
582
|
-
// shared logger, which honors AGENT_RELAY_LOG_FILE/_LEVEL/_JSON. Without a
|
|
583
|
-
// flag, keep the prior behavior: the registration summary via log, warnings
|
|
584
|
-
// via warn.
|
|
585
|
-
...(nodeLoggingEnabled(options)
|
|
586
|
-
? { logger: createLogger('fleet') }
|
|
587
|
-
: { warn: (message) => deps.warn(message), log: (message) => deps.log(message) }),
|
|
588
|
-
}));
|
|
589
|
-
}
|
|
590
|
-
catch (err) {
|
|
591
|
-
deps.warn(`Capability provider skipped: ${toErrorMessage(err)}`);
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
if (nodePlan?.mode === 'child-node') {
|
|
595
|
-
nodeJsChild = await startNodeJsNodeProvider(nodePlan.configPath, {
|
|
596
|
-
nodeToken,
|
|
597
|
-
baseUrl,
|
|
598
|
-
nodeId: identity.nodeId,
|
|
599
|
-
nodeName: options.nodeName ?? identity.nodeName,
|
|
600
|
-
...(relay.workspaceKey ? { workspaceKey: relay.workspaceKey } : {}),
|
|
601
|
-
}, deps);
|
|
602
|
-
}
|
|
603
|
-
if (served.length === 0 && !nodeJsChild) {
|
|
604
|
-
return undefined;
|
|
605
|
-
}
|
|
606
|
-
return {
|
|
607
|
-
...(nodeJsChild ? { done: nodeJsChild.done } : {}),
|
|
608
|
-
stop: async () => {
|
|
609
|
-
await Promise.all([...served.map((node) => node.stop().catch(() => undefined)), nodeJsChild?.stop()]);
|
|
610
|
-
},
|
|
611
|
-
};
|
|
612
|
-
}
|
|
613
|
-
function isBrokerAlreadyRunningError(message) {
|
|
614
|
-
return /another broker instance is already running in this directory/i.test(message);
|
|
615
|
-
}
|
|
616
|
-
function extractBrokerLockDir(message) {
|
|
617
|
-
const match = message.match(/another broker instance is already running in this directory \(([^)]+)\)/i);
|
|
618
|
-
return match?.[1] ?? null;
|
|
619
|
-
}
|
|
620
|
-
function reportAlreadyRunningError(message, dataDir, deps) {
|
|
621
|
-
const pid = readBrokerPid(dataDir, deps);
|
|
622
|
-
if (pid !== null && isProcessRunning(pid, deps)) {
|
|
623
|
-
deps.error(`Broker already running for this project (pid: ${pid}).`);
|
|
624
|
-
}
|
|
625
|
-
else {
|
|
626
|
-
const lockDir = extractBrokerLockDir(message);
|
|
627
|
-
if (lockDir) {
|
|
628
|
-
deps.error(`Broker already running for this project (lock: ${lockDir}).`);
|
|
629
|
-
}
|
|
630
|
-
else {
|
|
631
|
-
deps.error('Broker already running for this project.');
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
deps.error('Run `agent-relay status` to inspect it, then `agent-relay down` to stop it.');
|
|
635
|
-
deps.error('If it still fails, run `agent-relay down --force` to clear stale runtime files.');
|
|
636
|
-
}
|
|
637
|
-
function safeUnlink(filePath, deps) {
|
|
638
|
-
if (!deps.fs.existsSync(filePath))
|
|
639
|
-
return;
|
|
640
|
-
try {
|
|
641
|
-
deps.fs.unlinkSync(filePath);
|
|
642
|
-
}
|
|
643
|
-
catch {
|
|
644
|
-
// Best-effort cleanup.
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
function workspaceBindingSource(value) {
|
|
648
|
-
return value === 'flag' ||
|
|
649
|
-
value === 'env' ||
|
|
650
|
-
value === 'project' ||
|
|
651
|
-
value === 'store' ||
|
|
652
|
-
value === 'created' ||
|
|
653
|
-
value === 'multi-workspace'
|
|
654
|
-
? value
|
|
655
|
-
: undefined;
|
|
656
|
-
}
|
|
657
|
-
function workspaceBindingSourceLabel(source) {
|
|
658
|
-
switch (source) {
|
|
659
|
-
case 'flag':
|
|
660
|
-
return 'command-line flag (--workspace-key / --wk)';
|
|
661
|
-
case 'env':
|
|
662
|
-
return 'environment (RELAY_WORKSPACE_KEY > AGENT_RELAY_WORKSPACE_KEY > RELAY_API_KEY)';
|
|
663
|
-
case 'project':
|
|
664
|
-
return 'repository pin (.agentworkforce/relay/workspace-key.json)';
|
|
665
|
-
case 'store':
|
|
666
|
-
return 'machine-global active workspace (~/.agentworkforce/relay/workspaces.json)';
|
|
667
|
-
case 'created':
|
|
668
|
-
return 'created (no configured workspace resolved)';
|
|
669
|
-
case 'multi-workspace':
|
|
670
|
-
return 'multi-workspace session ($RELAY_WORKSPACES_JSON)';
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
/** True when `RELAY_WORKSPACES_JSON` carries at least one membership. The broker's
|
|
674
|
-
* `startup_session_set_with_options` checks this env var before any single
|
|
675
|
-
* workspace key (flag, env, repository pin, or machine-global store), so the
|
|
676
|
-
* CLI's precedence ladder must defer to it for provenance too — otherwise
|
|
677
|
-
* `node up` / `node status` can report a source the broker never used. */
|
|
678
|
-
function usesMultiWorkspaceEnv(env) {
|
|
679
|
-
return Boolean(env.RELAY_WORKSPACES_JSON?.trim());
|
|
680
|
-
}
|
|
681
|
-
function writeBrokerBindingSource(dataDir, source, deps) {
|
|
682
|
-
const connectionPath = path.join(dataDir, CONNECTION_FILENAME);
|
|
683
|
-
const connection = readBrokerConnectionFromFs(deps.fs, dataDir);
|
|
684
|
-
if (!connection)
|
|
685
|
-
return;
|
|
686
|
-
// Every CLI invocation resolves the broker through this file, so a
|
|
687
|
-
// concurrent writer must never observe a partial or clobbered write.
|
|
688
|
-
// Write to a private tmp file and rename it into place, which is atomic
|
|
689
|
-
// on the same filesystem.
|
|
690
|
-
const tmpPath = `${connectionPath}.tmp-${process.pid}-${randomUUID()}`;
|
|
691
|
-
deps.fs.writeFileSync(tmpPath, `${JSON.stringify({ ...connection, workspace_source: source }, null, 2)}\n`, 'utf-8');
|
|
692
|
-
deps.fs.renameSync(tmpPath, connectionPath);
|
|
693
|
-
}
|
|
694
|
-
function backgroundStartErrorPath(dataDir) {
|
|
695
|
-
return path.join(dataDir, BACKGROUND_START_ERROR_FILENAME);
|
|
696
|
-
}
|
|
697
|
-
function readBackgroundStartError(dataDir, deps) {
|
|
698
|
-
try {
|
|
699
|
-
return deps.fs.readFileSync(backgroundStartErrorPath(dataDir), 'utf-8').trim() || undefined;
|
|
700
|
-
}
|
|
701
|
-
catch {
|
|
702
|
-
return undefined;
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
function recordBackgroundStartError(message, dataDir, isDetachedChild, deps) {
|
|
706
|
-
if (!isDetachedChild)
|
|
707
|
-
return;
|
|
708
|
-
try {
|
|
709
|
-
// Never trust a project-loaded environment variable as a filesystem path.
|
|
710
|
-
// Detached startup owns one fixed diagnostic file inside its resolved
|
|
711
|
-
// broker state directory; foreground failures do not write it at all.
|
|
712
|
-
deps.fs.writeFileSync(backgroundStartErrorPath(dataDir), `${message}\n`, 'utf-8');
|
|
713
|
-
}
|
|
714
|
-
catch {
|
|
715
|
-
// Diagnostics must never replace the original startup error.
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
function readBrokerPid(dataDir, _deps) {
|
|
719
|
-
const conn = readBrokerConnectionFromFs(_deps.fs, dataDir);
|
|
720
|
-
return conn?.pid ?? null;
|
|
721
|
-
}
|
|
722
|
-
function isProcessRunning(pid, deps) {
|
|
723
|
-
try {
|
|
724
|
-
deps.killProcess(pid, 0);
|
|
725
|
-
return true;
|
|
726
|
-
}
|
|
727
|
-
catch (error) {
|
|
728
|
-
// Permission denial proves no exit and must never authorize record deletion.
|
|
729
|
-
return error?.code === 'EPERM';
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
async function terminateProcess(pid, deps, force) {
|
|
733
|
-
try {
|
|
734
|
-
deps.killProcess(pid, 'SIGTERM');
|
|
735
|
-
}
|
|
736
|
-
catch {
|
|
737
|
-
return false;
|
|
738
|
-
}
|
|
739
|
-
const exited = await waitForProcessExit(pid, force ? 500 : 300, deps);
|
|
740
|
-
if (exited || !force) {
|
|
741
|
-
return exited;
|
|
742
|
-
}
|
|
743
|
-
try {
|
|
744
|
-
deps.killProcess(pid, 'SIGKILL');
|
|
745
|
-
}
|
|
746
|
-
catch {
|
|
747
|
-
return false;
|
|
748
|
-
}
|
|
749
|
-
return waitForProcessExit(pid, 500, deps);
|
|
750
|
-
}
|
|
751
|
-
async function killOrphanedBrokerProcesses(paths, deps, options) {
|
|
752
|
-
const identities = readBrokerIdentities(paths, deps);
|
|
753
|
-
if (!identities) {
|
|
754
|
-
deps.warn(`Broker identities could not be read in ${brokerIdentityDirectory(paths, deps)}. State retained; inspect the records and verify process ownership before manual recovery.`);
|
|
755
|
-
return { matchedCount: 1, killedCount: 0 };
|
|
756
|
-
}
|
|
757
|
-
const brokerName = options?.brokerName?.trim() ||
|
|
758
|
-
deps.env.AGENT_RELAY_BROKER_NAME?.trim() ||
|
|
759
|
-
path.basename(paths.projectRoot) ||
|
|
760
|
-
'project';
|
|
761
|
-
const result = { matchedCount: 0, killedCount: 0 };
|
|
762
|
-
for (const identity of identities) {
|
|
763
|
-
if (options?.matchBrokerName && identity.brokerName !== brokerName)
|
|
764
|
-
continue;
|
|
765
|
-
if (!isProcessRunning(identity.pid, deps)) {
|
|
766
|
-
if (options?.matchBrokerName) {
|
|
767
|
-
result.matchedCount++;
|
|
768
|
-
deps.warn(`Recorded broker has already exited; its identity was retained because no matched exit was observed. Verify ownership before removing ${locateBrokerIdentityFile(paths, deps, identity.brokerName)} and restarting.`);
|
|
769
|
-
}
|
|
770
|
-
continue;
|
|
771
|
-
}
|
|
772
|
-
result.matchedCount++;
|
|
773
|
-
if (await stopRecordedBroker(paths, identity, deps, options?.force === true))
|
|
774
|
-
result.killedCount++;
|
|
775
|
-
}
|
|
776
|
-
return result;
|
|
777
|
-
}
|
|
778
|
-
async function stopRecordedBroker(paths, identity, deps, force) {
|
|
779
|
-
// Check the persisted instance immediately before EVERY signal, including
|
|
780
|
-
// escalation after a wait. Never rediscover ownership from rendered argv.
|
|
781
|
-
if (!(await matchesBrokerIdentity(identity, paths, deps))) {
|
|
782
|
-
deps.warn(`Broker identity could not be verified (pid: ${identity.pid}). State retained; verify process ownership before stopping it manually. If the recorded broker has exited, remove its stale identity file: ${locateBrokerIdentityFile(paths, deps, identity.brokerName)}`);
|
|
783
|
-
return false;
|
|
784
|
-
}
|
|
785
|
-
deps.warn(`Killing orphaned broker process (pid: ${identity.pid})`);
|
|
786
|
-
try {
|
|
787
|
-
deps.killProcess(identity.pid, 'SIGTERM');
|
|
788
|
-
// Native graceful shutdown may drain identity/presence work for 3.5s.
|
|
789
|
-
let exited = await waitForProcessExit(identity.pid, force ? 500 : 5000, deps);
|
|
790
|
-
if (!exited && force && (await matchesBrokerIdentity(identity, paths, deps))) {
|
|
791
|
-
deps.killProcess(identity.pid, 'SIGKILL');
|
|
792
|
-
exited = await waitForProcessExit(identity.pid, 500, deps);
|
|
793
|
-
}
|
|
794
|
-
if (exited) {
|
|
795
|
-
removeBrokerIdentity(paths, identity, deps);
|
|
796
|
-
return true;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
catch (error) {
|
|
800
|
-
if (error?.code === 'ESRCH') {
|
|
801
|
-
// The kernel observed absence after this exact instance was verified.
|
|
802
|
-
removeBrokerIdentity(paths, identity, deps);
|
|
803
|
-
return true;
|
|
804
|
-
}
|
|
805
|
-
// Retain the record when a matched exit was not observed.
|
|
806
|
-
}
|
|
807
|
-
deps.warn(`Broker orphan process may still be running (pid: ${identity.pid})`);
|
|
808
|
-
return false;
|
|
809
|
-
}
|
|
810
|
-
function ensureBundledAgentRelayMcpCommand(deps) {
|
|
811
|
-
if (deps.env.AGENT_RELAY_MCP_COMMAND?.trim()) {
|
|
812
|
-
return;
|
|
813
|
-
}
|
|
814
|
-
const command = buildBundledAgentRelayMcpCommand(deps.execPath, deps.cliScript, deps.fs.existsSync);
|
|
815
|
-
if (command) {
|
|
816
|
-
deps.env.AGENT_RELAY_MCP_COMMAND = command;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
async function waitForProcessExit(pid, timeoutMs, deps) {
|
|
820
|
-
const startedAt = deps.now();
|
|
821
|
-
while (deps.now() - startedAt < timeoutMs) {
|
|
822
|
-
if (!isProcessRunning(pid, deps)) {
|
|
823
|
-
return true;
|
|
824
|
-
}
|
|
825
|
-
await deps.sleep(100);
|
|
826
|
-
}
|
|
827
|
-
return false;
|
|
828
|
-
}
|
|
829
|
-
async function recoverHalfStartedBroker(paths, deps, brokerName) {
|
|
830
|
-
deps.fs.mkdirSync(paths.dataDir, { recursive: true });
|
|
831
|
-
const readiness = await waitForBrokerReadiness(paths, deps, 0, true);
|
|
832
|
-
if (readiness.state === 'running') {
|
|
833
|
-
return 'running';
|
|
834
|
-
}
|
|
835
|
-
if (readiness.state === 'starting') {
|
|
836
|
-
deps.warn(`Broker process is running but the API is not ready; verifying half-started broker ownership (pid: ${readiness.conn.pid}).`);
|
|
837
|
-
const identities = readBrokerIdentities(paths, deps);
|
|
838
|
-
const identity = identities?.find((record) => record.pid === readiness.conn.pid);
|
|
839
|
-
const stopped = identity && (await stopRecordedBroker(paths, identity, deps, true));
|
|
840
|
-
if (!stopped) {
|
|
841
|
-
deps.error(`Failed to stop half-started broker process (pid: ${readiness.conn.pid}). ` +
|
|
842
|
-
`Verify process ownership manually before stopping it; inspect identities in ${brokerIdentityDirectory(paths, deps)}. Connection metadata alone cannot authorize a signal.`);
|
|
843
|
-
return 'blocked';
|
|
844
|
-
}
|
|
845
|
-
cleanupBrokerFiles(paths, deps);
|
|
846
|
-
return 'recovered';
|
|
847
|
-
}
|
|
848
|
-
const orphanCleanup = await killOrphanedBrokerProcesses(paths, deps, {
|
|
849
|
-
force: true,
|
|
850
|
-
brokerName,
|
|
851
|
-
matchBrokerName: true,
|
|
852
|
-
});
|
|
853
|
-
if (orphanCleanup.matchedCount > 0) {
|
|
854
|
-
if (orphanCleanup.killedCount < orphanCleanup.matchedCount) {
|
|
855
|
-
deps.error('Failed to stop all half-started broker processes. ' +
|
|
856
|
-
'Run `agent-relay down --force` to retry cleanup, or remove `.agentworkforce/relay/` after stopping the processes.');
|
|
857
|
-
return 'blocked';
|
|
858
|
-
}
|
|
859
|
-
cleanupBrokerFiles(paths, deps);
|
|
860
|
-
return 'recovered';
|
|
861
|
-
}
|
|
862
|
-
return 'clear';
|
|
863
|
-
}
|
|
864
|
-
function cleanupBrokerFiles(paths, deps) {
|
|
865
|
-
// A concurrent replacement or another named broker still owns discovery
|
|
866
|
-
// state. Unreadable records are likewise not permission to remove it.
|
|
867
|
-
if (readBrokerIdentities(paths, deps)?.length !== 0)
|
|
868
|
-
return;
|
|
869
|
-
// A replacement can publish connection.json before its identity is captured.
|
|
870
|
-
const connection = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
|
|
871
|
-
if (connection?.pid && isProcessRunning(connection.pid, deps))
|
|
872
|
-
return;
|
|
873
|
-
const runtimePath = path.join(paths.dataDir, 'runtime.json');
|
|
874
|
-
const relaySockPath = path.join(paths.dataDir, 'relay.sock');
|
|
875
|
-
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
|
|
876
|
-
safeUnlink(relaySockPath, deps);
|
|
877
|
-
safeUnlink(runtimePath, deps);
|
|
878
|
-
safeUnlink(backgroundStartErrorPath(paths.dataDir), deps);
|
|
879
|
-
// A lock pathname may still belong to an unverifiable or differently named
|
|
880
|
-
// live broker. Reusing the existing inode preserves its flock protection.
|
|
881
|
-
// Only legacy pid files are disposable here.
|
|
882
|
-
try {
|
|
883
|
-
for (const file of deps.fs.readdirSync(paths.dataDir)) {
|
|
884
|
-
if (file.startsWith('broker-') && file.endsWith('.pid')) {
|
|
885
|
-
safeUnlink(path.join(paths.dataDir, file), deps);
|
|
886
|
-
continue;
|
|
887
|
-
}
|
|
888
|
-
if (!file.startsWith('mcp-identity-')) {
|
|
889
|
-
continue;
|
|
890
|
-
}
|
|
891
|
-
const pidMatch = file.match(/^mcp-identity-(\d+)/);
|
|
892
|
-
if (!pidMatch) {
|
|
893
|
-
continue;
|
|
894
|
-
}
|
|
895
|
-
const pid = Number.parseInt(pidMatch[1], 10);
|
|
896
|
-
if (!isProcessRunning(pid, deps)) {
|
|
897
|
-
safeUnlink(path.join(paths.dataDir, file), deps);
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
catch {
|
|
902
|
-
// Ignore read errors while cleaning up.
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
function childUpArgsForDetachedStart(options, deps) {
|
|
906
|
-
// The workspace key travels to the detached child via env only (set on
|
|
907
|
-
// deps.env before the spawn): strip every argv spelling so the daemon's
|
|
908
|
-
// command line never carries it into `ps` output.
|
|
909
|
-
const args = stripCliOptionsWithValue(cliUserArgs(deps).filter((arg) => !matchesCliOption(arg, '--background')), ['--workspace-key', '--wk']);
|
|
910
|
-
if (options.stateDir && !hasCliOption(args, '--state-dir')) {
|
|
911
|
-
args.push('--state-dir', path.resolve(options.stateDir));
|
|
912
|
-
}
|
|
913
|
-
if (options.brokerName && !hasCliOption(args, '--broker-name')) {
|
|
914
|
-
args.push('--broker-name', options.brokerName);
|
|
915
|
-
}
|
|
916
|
-
if (options.verbose === true && !args.includes('--verbose')) {
|
|
917
|
-
args.push('--verbose');
|
|
918
|
-
}
|
|
919
|
-
if (!args.includes('--background-child')) {
|
|
920
|
-
args.push('--background-child');
|
|
921
|
-
}
|
|
922
|
-
return args;
|
|
923
|
-
}
|
|
924
|
-
/** Drop each named option and, for the space-separated form, its value token. */
|
|
925
|
-
function stripCliOptionsWithValue(args, names) {
|
|
926
|
-
const result = [];
|
|
927
|
-
for (let i = 0; i < args.length; i++) {
|
|
928
|
-
const arg = args[i];
|
|
929
|
-
if (names.includes(arg)) {
|
|
930
|
-
i++;
|
|
931
|
-
continue;
|
|
932
|
-
}
|
|
933
|
-
if (names.some((name) => arg.startsWith(`${name}=`))) {
|
|
934
|
-
continue;
|
|
935
|
-
}
|
|
936
|
-
result.push(arg);
|
|
937
|
-
}
|
|
938
|
-
return result;
|
|
939
|
-
}
|
|
940
|
-
function cliUserArgs(deps) {
|
|
941
|
-
return hasEntrypointArgvSlot(deps) ? deps.argv.slice(2) : deps.argv.slice(1);
|
|
942
|
-
}
|
|
943
|
-
function detachedCliInvocation(deps, args) {
|
|
944
|
-
if (shouldReexecThroughScript(deps)) {
|
|
945
|
-
return { command: deps.execPath, args: [deps.cliScript, ...args] };
|
|
946
|
-
}
|
|
947
|
-
return { command: deps.execPath, args };
|
|
948
|
-
}
|
|
949
|
-
function hasEntrypointArgvSlot(deps) {
|
|
950
|
-
return isBundledBunExecutableEntrypoint(deps) || isCliScriptEntrypoint(deps);
|
|
951
|
-
}
|
|
952
|
-
function shouldReexecThroughScript(deps) {
|
|
953
|
-
return isCliScriptEntrypoint(deps) && !sameCliPath(deps.execPath, deps.cliScript);
|
|
954
|
-
}
|
|
955
|
-
function isCliScriptEntrypoint(deps) {
|
|
956
|
-
const cliScript = deps.cliScript.trim();
|
|
957
|
-
if (!cliScript) {
|
|
958
|
-
return false;
|
|
959
|
-
}
|
|
960
|
-
if (isBundledBunExecutableEntrypoint(deps)) {
|
|
961
|
-
return false;
|
|
962
|
-
}
|
|
963
|
-
if (sameCliPath(deps.execPath, cliScript)) {
|
|
964
|
-
return true;
|
|
965
|
-
}
|
|
966
|
-
return (path.isAbsolute(cliScript) ||
|
|
967
|
-
cliScript.includes('/') ||
|
|
968
|
-
cliScript.includes('\\') ||
|
|
969
|
-
/\.[cm]?js$/i.test(cliScript));
|
|
970
|
-
}
|
|
971
|
-
export function isBundledBunExecutableEntrypoint(deps) {
|
|
972
|
-
return deps.argv[0] === 'bun' && isBundledBunEntrypointPath(deps.cliScript);
|
|
973
|
-
}
|
|
974
|
-
function sameCliPath(left, right) {
|
|
975
|
-
return path.resolve(left) === path.resolve(right);
|
|
976
|
-
}
|
|
977
|
-
function hasCliOption(args, name) {
|
|
978
|
-
return args.some((arg) => matchesCliOption(arg, name));
|
|
979
|
-
}
|
|
980
|
-
function matchesCliOption(arg, name) {
|
|
981
|
-
return arg === name || arg.startsWith(`${name}=`);
|
|
982
|
-
}
|
|
983
|
-
async function checkBrokerReadiness(paths, deps, requireApi) {
|
|
984
|
-
const conn = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
|
|
985
|
-
if (!conn || conn.pid <= 0) {
|
|
986
|
-
return { state: 'stopped' };
|
|
987
|
-
}
|
|
988
|
-
if (!isProcessRunning(conn.pid, deps)) {
|
|
989
|
-
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
|
|
990
|
-
return { state: 'stopped' };
|
|
991
|
-
}
|
|
992
|
-
if (!requireApi) {
|
|
993
|
-
return { state: 'running', conn };
|
|
994
|
-
}
|
|
995
|
-
const statusDetails = await readBrokerStatusDetails(conn);
|
|
996
|
-
if (statusDetails) {
|
|
997
|
-
return { state: 'running', conn, statusDetails };
|
|
998
|
-
}
|
|
999
|
-
return { state: 'starting', conn };
|
|
1000
|
-
}
|
|
1001
|
-
async function waitForBrokerReadiness(paths, deps, waitMs, requireApi, verbose, stopWhenPidExits) {
|
|
1002
|
-
const deadline = deps.now() + waitMs;
|
|
1003
|
-
let latest = await checkBrokerReadiness(paths, deps, requireApi);
|
|
1004
|
-
vlog(deps, verbose, `Broker readiness: ${latest.state}`);
|
|
1005
|
-
while (latest.state !== 'running' && waitMs > 0 && deps.now() < deadline) {
|
|
1006
|
-
if (stopWhenPidExits && !isProcessRunning(stopWhenPidExits, deps)) {
|
|
1007
|
-
return latest;
|
|
1008
|
-
}
|
|
1009
|
-
await deps.sleep(Math.min(STATUS_POLL_INTERVAL_MS, Math.max(0, deadline - deps.now())));
|
|
1010
|
-
const previousState = latest.state;
|
|
1011
|
-
latest = await checkBrokerReadiness(paths, deps, requireApi);
|
|
1012
|
-
if (latest.state !== previousState) {
|
|
1013
|
-
vlog(deps, verbose, `Broker readiness: ${latest.state}`);
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
return latest;
|
|
1017
|
-
}
|
|
1018
|
-
async function waitForEnrolledNodeReadiness(conn, deps, expected, initialDetails) {
|
|
1019
|
-
const deadline = deps.now() + DETACHED_START_READY_TIMEOUT_MS;
|
|
1020
|
-
let details = initialDetails ?? null;
|
|
1021
|
-
for (;;) {
|
|
1022
|
-
details ??= await readBrokerStatusDetails(conn);
|
|
1023
|
-
const actualNodeId = details?.session?.node_id?.trim();
|
|
1024
|
-
const actualNodeName = details?.session?.node_name?.trim();
|
|
1025
|
-
if (actualNodeId && actualNodeId !== expected.nodeId) {
|
|
1026
|
-
return {
|
|
1027
|
-
ready: false,
|
|
1028
|
-
reason: `Cloud enrollment identity mismatch: expected node id "${expected.nodeId}", got "${actualNodeId}".`,
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
if (expected.nodeName && actualNodeName && actualNodeName !== expected.nodeName) {
|
|
1032
|
-
return {
|
|
1033
|
-
ready: false,
|
|
1034
|
-
reason: `Cloud enrollment identity mismatch: expected node name "${expected.nodeName}", got "${actualNodeName}".`,
|
|
1035
|
-
};
|
|
1036
|
-
}
|
|
1037
|
-
if (actualNodeId === expected.nodeId &&
|
|
1038
|
-
(!expected.nodeName || actualNodeName === expected.nodeName) &&
|
|
1039
|
-
nodeDeliveryReady(details?.status)) {
|
|
1040
|
-
return { ready: true };
|
|
1041
|
-
}
|
|
1042
|
-
if (deps.now() >= deadline) {
|
|
1043
|
-
return {
|
|
1044
|
-
ready: false,
|
|
1045
|
-
reason: `Cloud enrollment for node "${expected.nodeName ?? expected.nodeId}" did not become ready. ` +
|
|
1046
|
-
`Node delivery: ${formatNodeDeliveryStatus(details?.status)}`,
|
|
1047
|
-
};
|
|
1048
|
-
}
|
|
1049
|
-
await deps.sleep(Math.min(STATUS_POLL_INTERVAL_MS, Math.max(0, deadline - deps.now())));
|
|
1050
|
-
details = null;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
export async function waitForNodeDelivery(relay, deps, waitMs = NODE_DELIVERY_READY_TIMEOUT_MS) {
|
|
1054
|
-
const deadline = deps.now() + waitMs;
|
|
1055
|
-
let latest = null;
|
|
1056
|
-
while (true) {
|
|
1057
|
-
try {
|
|
1058
|
-
latest = await relay.getStatus();
|
|
1059
|
-
}
|
|
1060
|
-
catch {
|
|
1061
|
-
latest = null;
|
|
1062
|
-
}
|
|
1063
|
-
if (nodeDeliveryReady(latest)) {
|
|
1064
|
-
return { ready: true, status: latest };
|
|
1065
|
-
}
|
|
1066
|
-
if (waitMs <= 0 || deps.now() >= deadline) {
|
|
1067
|
-
return { ready: false, status: latest };
|
|
1068
|
-
}
|
|
1069
|
-
await deps.sleep(Math.min(STATUS_POLL_INTERVAL_MS, Math.max(0, deadline - deps.now())));
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
async function shutdownUpResources(relay, paths, deps, observedChildExit) {
|
|
1073
|
-
// The SDK clears its child handle on exit/shutdown, so preserve the owned
|
|
1074
|
-
// PID before awaiting shutdown or use the exact observed-child snapshot.
|
|
1075
|
-
const brokerPid = observedChildExit?.pid ?? relay.brokerPid;
|
|
1076
|
-
const identity = readBrokerIdentities(paths, deps)?.find((record) => record.pid === brokerPid);
|
|
1077
|
-
const owned = identity !== undefined && (await matchesBrokerIdentity(identity, paths, deps));
|
|
1078
|
-
await relay.shutdown().catch(() => undefined);
|
|
1079
|
-
if (observedChildExit && observedChildExit.pid === brokerPid)
|
|
1080
|
-
removeBrokerIdentity(paths, observedChildExit, deps);
|
|
1081
|
-
if (identity && owned && !isProcessRunning(identity.pid, deps))
|
|
1082
|
-
removeBrokerIdentity(paths, identity, deps);
|
|
1083
|
-
if (brokerPid && readBrokerPid(paths.dataDir, deps) === brokerPid) {
|
|
1084
|
-
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
// eslint-disable-next-line complexity
|
|
1088
|
-
/**
|
|
1089
|
-
* Resolve the node definition `up` should serve, if any.
|
|
1090
|
-
*
|
|
1091
|
-
* A discovered (or explicit --config) node definition takes over from the
|
|
1092
|
-
* implicit teams.json-derived node. Discovery is opt-in (`node up` only): the
|
|
1093
|
-
* deprecated `local up` alias never scanned for agent-relay.* files and must
|
|
1094
|
-
* not start importing arbitrary modules from the project root. An explicit
|
|
1095
|
-
* --config resolves against the invocation cwd and fails hard; implicit
|
|
1096
|
-
* discovery scans the project root and merely warns on a file that doesn't
|
|
1097
|
-
* load as defineNode(...) — a stray agent-relay.ts must not brick startup.
|
|
1098
|
-
* When the implicit fleet node is disabled the sidecar never starts, so
|
|
1099
|
-
* loading a config would be pointless — skip it entirely.
|
|
1100
|
-
*/
|
|
1101
|
-
async function resolveNodeDefinitionForUp(paths, options, deps) {
|
|
1102
|
-
const fleetNodeDisabled = deps.env.AGENT_RELAY_DISABLE_IMPLICIT_FLEET_NODE === '1';
|
|
1103
|
-
if (fleetNodeDisabled || (!options.config && options.discoverConfig !== true)) {
|
|
1104
|
-
return undefined;
|
|
1105
|
-
}
|
|
1106
|
-
const explicitConfig = options.config ? path.resolve(process.cwd(), options.config) : undefined;
|
|
1107
|
-
const configPath = discoverNodeConfigPath(paths.projectRoot, explicitConfig);
|
|
1108
|
-
if (!configPath) {
|
|
1109
|
-
return undefined;
|
|
1110
|
-
}
|
|
1111
|
-
vlog(deps, options.verbose, `Loading fleet node definition from ${configPath}...`);
|
|
1112
|
-
if (explicitConfig) {
|
|
1113
|
-
return loadNodeDefinitionPlan(configPath, deps);
|
|
1114
|
-
}
|
|
1115
|
-
try {
|
|
1116
|
-
return await loadNodeDefinitionPlan(configPath, deps);
|
|
1117
|
-
}
|
|
1118
|
-
catch (err) {
|
|
1119
|
-
deps.warn(`Ignoring discovered node config ${configPath}: ${toErrorMessage(err)}. ` +
|
|
1120
|
-
'Serving the implicit local node instead; pass --config to fail hard on this file.');
|
|
1121
|
-
return undefined;
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
/**
|
|
1125
|
-
* Decide how to serve `configPath` and gather what the broker needs before it
|
|
1126
|
-
* starts (capacity, and a hard failure on a bad explicit --config).
|
|
1127
|
-
* @param configPath - Absolute path to the node definition file.
|
|
1128
|
-
* @param deps - Core dependencies.
|
|
1129
|
-
*/
|
|
1130
|
-
export async function loadNodeDefinitionPlan(configPath, deps) {
|
|
1131
|
-
if (!isBundledBunExecutableEntrypoint(deps)) {
|
|
1132
|
-
return { mode: 'in-process', definition: await loadNodeDefinition(configPath) };
|
|
1133
|
-
}
|
|
1134
|
-
const descriptor = await describeNodeDefinitionViaNode(configPath, deps);
|
|
1135
|
-
return { mode: 'child-node', configPath, descriptor };
|
|
1136
|
-
}
|
|
1137
|
-
/** The capacity a plan contributes to the broker's advertised capacity. */
|
|
1138
|
-
function planCapacitySource(plan) {
|
|
1139
|
-
if (!plan) {
|
|
1140
|
-
return undefined;
|
|
1141
|
-
}
|
|
1142
|
-
return plan.mode === 'in-process' ? plan.definition : descriptorCapacitySource(plan.descriptor);
|
|
1143
|
-
}
|
|
1144
|
-
/**
|
|
1145
|
-
* Apply the resolved workspace to the environment the broker (and any detached
|
|
1146
|
-
* child) inherits, and report which source won. Returns the pinned project
|
|
1147
|
-
* session when the repository pin supplied the selection.
|
|
1148
|
-
*/
|
|
1149
|
-
function applyWorkspaceSelection(selection, deps, projectDataDir) {
|
|
1150
|
-
if (!selection) {
|
|
1151
|
-
deps.log('Workspace: none selected (no --workspace-key, no RELAY_WORKSPACE_KEY, no repository pin, ' +
|
|
1152
|
-
'no active workspace in the machine-global store). A new workspace will be created.');
|
|
1153
|
-
return undefined;
|
|
1154
|
-
}
|
|
1155
|
-
deps.log(`Workspace source: ${describeWorkspaceSource(selection.source)} (${selection.origin})`);
|
|
1156
|
-
// Normalize every winning source to the primary env var inherited by the
|
|
1157
|
-
// broker and any detached child. Keep a caller-supplied RELAY_API_KEY intact
|
|
1158
|
-
// when an explicit flag or environment variable won.
|
|
1159
|
-
deps.env.RELAY_WORKSPACE_KEY = selection.key;
|
|
1160
|
-
if (selection.source === 'project' || selection.source === 'store') {
|
|
1161
|
-
deps.env.RELAY_API_KEY = selection.key;
|
|
1162
|
-
}
|
|
1163
|
-
if (selection.source !== 'project') {
|
|
1164
|
-
return undefined;
|
|
1165
|
-
}
|
|
1166
|
-
const pinned = readProjectWorkspaceSession(projectDataDir, deps.fs);
|
|
1167
|
-
if (pinned?.enrolledNodeId) {
|
|
1168
|
-
deps.env.AGENT_RELAY_ENROLLED_NODE_ID = pinned.enrolledNodeId;
|
|
1169
|
-
}
|
|
1170
|
-
return pinned;
|
|
1171
|
-
}
|
|
1172
|
-
/** Human-readable name for a precedence-ladder step, for the startup line. */
|
|
1173
|
-
function describeWorkspaceSource(source) {
|
|
1174
|
-
switch (source) {
|
|
1175
|
-
case 'flag':
|
|
1176
|
-
return 'command-line flag';
|
|
1177
|
-
case 'env':
|
|
1178
|
-
return 'environment';
|
|
1179
|
-
case 'project':
|
|
1180
|
-
return 'repository pin';
|
|
1181
|
-
case 'store':
|
|
1182
|
-
return 'machine-global active workspace';
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
/**
|
|
1186
|
-
* Preserve the original source across `--background` re-exec. The detached
|
|
1187
|
-
* child sees the normalized RELAY_WORKSPACE_KEY as an env selection, so this
|
|
1188
|
-
* marker carries only provenance; it never participates in resolution.
|
|
1189
|
-
*/
|
|
1190
|
-
function recordWorkspaceBindingSource(selection, deps, overrideSource) {
|
|
1191
|
-
const inheritedSource = workspaceBindingSource(deps.env[WORKSPACE_BINDING_SOURCE_ENV]);
|
|
1192
|
-
const source = overrideSource ??
|
|
1193
|
-
(selection?.source === 'env' && inheritedSource ? inheritedSource : (selection?.source ?? 'created'));
|
|
1194
|
-
deps.env[WORKSPACE_BINDING_SOURCE_ENV] = source;
|
|
1195
|
-
return source;
|
|
1196
|
-
}
|
|
1197
|
-
function resolveBrokerName(options, deps, projectRoot) {
|
|
1198
|
-
return (options.brokerName?.trim() ||
|
|
1199
|
-
deps.env.AGENT_RELAY_BROKER_NAME?.trim() ||
|
|
1200
|
-
path.basename(projectRoot) ||
|
|
1201
|
-
'project');
|
|
1202
|
-
}
|
|
1203
|
-
/**
|
|
1204
|
-
* Take machine-local ownership of the enrolled node id this start will register
|
|
1205
|
-
* as, if any — BEFORE anything that can register is spawned.
|
|
1206
|
-
*
|
|
1207
|
-
* The broker queues `node.register` from its own initialization
|
|
1208
|
-
* (`crates/broker/src/runtime/init.rs`), so by the time the CLI can verify the
|
|
1209
|
-
* child and write a claim the engine may already have moved the node's delivery
|
|
1210
|
-
* socket. Claiming after the spawn therefore could not deliver the guarantee it
|
|
1211
|
-
* was written for: a loser that is correctly refused had already evicted the
|
|
1212
|
-
* incumbent. The reservation names this supervising CLI, is exclusive against
|
|
1213
|
-
* every other start on the machine, and is handed to the broker by
|
|
1214
|
-
* {@link adoptEnrolledNodeClaim} once a verified process owns the state dir.
|
|
1215
|
-
*
|
|
1216
|
-
* `node up` also refuses a conflicting node id in its own preflight so the
|
|
1217
|
-
* operator gets remedies instead of a startup failure; this is what guards the
|
|
1218
|
-
* plain `up` / `local up` aliases, which have no preflight, and what serializes
|
|
1219
|
-
* two starts that raced past one.
|
|
1220
|
-
*
|
|
1221
|
-
* @throws NodeClaimConflictError when a live local broker holds the node id.
|
|
1222
|
-
* @throws NodeClaimContentionError when exclusion could not be established.
|
|
1223
|
-
*/
|
|
1224
|
-
/**
|
|
1225
|
-
* The executable this start will run as its broker.
|
|
1226
|
-
*
|
|
1227
|
-
* Recorded in the claim so a later start recognises that process by executable
|
|
1228
|
-
* identity rather than by its filename: `AGENT_RELAY_BIN` /
|
|
1229
|
-
* `BROKER_BINARY_PATH` let a supported deployment run the broker under any
|
|
1230
|
-
* name, and such a broker orphaned by a dead supervisor used to read as an
|
|
1231
|
-
* unrelated process — the "node id free" verdict that evicts a live broker.
|
|
1232
|
-
*
|
|
1233
|
-
* Resolution mirrors `getBrokerBinaryPath`, which reads the override from the
|
|
1234
|
-
* real environment; `deps.env` is consulted first so a start whose environment
|
|
1235
|
-
* was overridden records the binary it is actually going to spawn.
|
|
1236
|
-
*/
|
|
1237
|
-
function resolveBrokerBinary(deps) {
|
|
1238
|
-
const override = (deps.env.BROKER_BINARY_PATH ?? deps.env.AGENT_RELAY_BIN)?.trim();
|
|
1239
|
-
if (override) {
|
|
1240
|
-
const resolved = path.resolve(override);
|
|
1241
|
-
if (fs.existsSync(resolved))
|
|
1242
|
-
return resolved;
|
|
1243
|
-
}
|
|
1244
|
-
try {
|
|
1245
|
-
return getBrokerBinaryPath() ?? undefined;
|
|
1246
|
-
}
|
|
1247
|
-
catch {
|
|
1248
|
-
return undefined;
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
async function reserveEnrolledNode(paths, options, deps, localOnly) {
|
|
1252
|
-
const nodeId = localOnly ? undefined : enrolledNodeIdForClaim(deps.env);
|
|
1253
|
-
if (!nodeId) {
|
|
1254
|
-
return undefined;
|
|
1255
|
-
}
|
|
1256
|
-
const brokerBinary = resolveBrokerBinary(deps);
|
|
1257
|
-
return acquireNodeClaim({
|
|
1258
|
-
nodeId,
|
|
1259
|
-
pid: deps.pid,
|
|
1260
|
-
stateDir: paths.dataDir,
|
|
1261
|
-
...(brokerBinary ? { brokerBinary } : {}),
|
|
1262
|
-
status: 'reserved',
|
|
1263
|
-
force: options.force === true,
|
|
1264
|
-
env: deps.env,
|
|
1265
|
-
killProcess: deps.killProcess,
|
|
1266
|
-
execCommand: deps.execCommand,
|
|
1267
|
-
});
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Move the reservation onto the verified broker process.
|
|
1271
|
-
*
|
|
1272
|
-
* Conditional on the reservation still being the claim on disk: a `--force`
|
|
1273
|
-
* takeover that landed while this broker was starting has already won the node
|
|
1274
|
-
* id, and overwriting it would put two brokers back on one delivery socket.
|
|
1275
|
-
* Losing here fails startup, which tears this broker down.
|
|
1276
|
-
*/
|
|
1277
|
-
async function adoptEnrolledNodeClaim(reservation, broker, deps) {
|
|
1278
|
-
return adoptNodeClaim({
|
|
1279
|
-
reservation,
|
|
1280
|
-
pid: broker.pid,
|
|
1281
|
-
...(broker.apiPort !== undefined ? { apiPort: broker.apiPort } : {}),
|
|
1282
|
-
brokerName: broker.brokerName,
|
|
1283
|
-
env: deps.env,
|
|
1284
|
-
killProcess: deps.killProcess,
|
|
1285
|
-
execCommand: deps.execCommand,
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
/** Polls before giving up on observing a shut-down broker actually exit. */
|
|
1289
|
-
const NODE_CLAIM_EXIT_POLL_ATTEMPTS = 50;
|
|
1290
|
-
const NODE_CLAIM_EXIT_POLL_MS = 100;
|
|
1291
|
-
/**
|
|
1292
|
-
* Wait for a claimed pid to disappear.
|
|
1293
|
-
*
|
|
1294
|
-
* Bounded by attempts rather than a deadline read from `deps.now()`: a frozen
|
|
1295
|
-
* clock must not turn this into an unbounded loop.
|
|
1296
|
-
*/
|
|
1297
|
-
async function waitForClaimedProcessExit(pid, deps) {
|
|
1298
|
-
for (let attempt = 0; attempt < NODE_CLAIM_EXIT_POLL_ATTEMPTS; attempt += 1) {
|
|
1299
|
-
if (!isProcessRunning(pid, deps)) {
|
|
1300
|
-
return true;
|
|
1301
|
-
}
|
|
1302
|
-
await deps.sleep(NODE_CLAIM_EXIT_POLL_MS);
|
|
1303
|
-
}
|
|
1304
|
-
return !isProcessRunning(pid, deps);
|
|
1305
|
-
}
|
|
1306
|
-
/**
|
|
1307
|
-
* Polls before giving up on a fenced child that has not dropped the claim's
|
|
1308
|
-
* hold descriptor. Shorter than the pid wait above: every attempt runs `lsof`,
|
|
1309
|
-
* and a holder this start never captured is either exiting right now or is not
|
|
1310
|
-
* going to.
|
|
1311
|
-
*/
|
|
1312
|
-
const NODE_CLAIM_HOLD_POLL_ATTEMPTS = 10;
|
|
1313
|
-
/**
|
|
1314
|
-
* Wait for every holder of the claim's hold descriptor other than this
|
|
1315
|
-
* supervisor to exit.
|
|
1316
|
-
*
|
|
1317
|
-
* This is the release-side half of the spawn-to-publication fence. `claim.pid`,
|
|
1318
|
-
* `supervisor_pid` and `spawnedPids` only ever name a child some part of this
|
|
1319
|
-
* start managed to capture, and `onCandidateReady` cannot fire until
|
|
1320
|
-
* `createRelay` RESOLVES: a spawn that rejects (a handshake that never
|
|
1321
|
-
* completed, a startup SIGTERM the child outlived) leaves a broker child that no
|
|
1322
|
-
* pid anywhere names and no `connection.json` either. Releasing then would
|
|
1323
|
-
* tombstone the claim and unlink the hold file out from under a live process
|
|
1324
|
-
* that is still fenced by it, and the next start would read the node id as free
|
|
1325
|
-
* while that child can still register — the eviction this lane exists to
|
|
1326
|
-
* prevent.
|
|
1327
|
-
*
|
|
1328
|
-
* This process's own descriptor is excluded: it is dropped only after the
|
|
1329
|
-
* release decision, and it is never evidence that somebody else owns the node.
|
|
1330
|
-
*/
|
|
1331
|
-
async function waitForClaimHoldRelease(claim, deps) {
|
|
1332
|
-
const claimDeps = { env: deps.env, killProcess: deps.killProcess, execCommand: deps.execCommand };
|
|
1333
|
-
// `deps.pid` is the supervisor of record; `process.pid` is who actually holds
|
|
1334
|
-
// the descriptor. They are the same process in production and can differ in
|
|
1335
|
-
// tests, so neither may read as a rival holder.
|
|
1336
|
-
const selfPids = new Set([deps.pid, process.pid]);
|
|
1337
|
-
let status = await inspectNodeClaimHold(claim, claimDeps, selfPids);
|
|
1338
|
-
for (let attempt = 0; status.held && attempt < NODE_CLAIM_HOLD_POLL_ATTEMPTS; attempt += 1) {
|
|
1339
|
-
await deps.sleep(NODE_CLAIM_EXIT_POLL_MS);
|
|
1340
|
-
status = await inspectNodeClaimHold(claim, claimDeps, selfPids);
|
|
1341
|
-
}
|
|
1342
|
-
return status;
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Release the node claim only once every process it protects is provably gone.
|
|
1346
|
-
*
|
|
1347
|
-
* "shutdown returned" is not evidence of exit: `shutdownUpResources` swallows
|
|
1348
|
-
* shutdown errors, and the SDK's `waitForExit` gives up after its timeout.
|
|
1349
|
-
* Releasing on that signal alone opened the node id while the old broker still
|
|
1350
|
-
* held its node-control socket — the eviction this claim exists to prevent.
|
|
1351
|
-
* Keeping a claim costs nothing: once the pids really die it reads as stale and
|
|
1352
|
-
* the next start takes it over, and `node down` releases it by verified pid.
|
|
1353
|
-
*
|
|
1354
|
-
* Before adoption the claim names only this supervising CLI, so its pids alone
|
|
1355
|
-
* do not cover the broker this start spawned. `spawnedPids` carries every child
|
|
1356
|
-
* pid this start ever saw — kept across the failure paths that clear `relay` —
|
|
1357
|
-
* the claim's hold descriptor answers for a child that was never captured at
|
|
1358
|
-
* all, and the state dir's own connection file is consulted last, for a broker
|
|
1359
|
-
* that published but was never fenced by this start.
|
|
1360
|
-
*
|
|
1361
|
-
* @returns Whether the claim was released.
|
|
1362
|
-
*/
|
|
1363
|
-
async function releaseNodeClaimAfterExit(claim, deps, spawnedPids = []) {
|
|
1364
|
-
const protectedPids = [...new Set([claim.pid, claim.supervisor_pid, ...spawnedPids])].filter((pid) => typeof pid === 'number' && pid > 0 && pid !== deps.pid);
|
|
1365
|
-
for (const pid of protectedPids) {
|
|
1366
|
-
if (!(await waitForClaimedProcessExit(pid, deps))) {
|
|
1367
|
-
deps.warn(`Broker pid ${pid} is still running after shutdown; keeping this machine's claim on node ${claim.node_id}. ` +
|
|
1368
|
-
`Stop it with: agent-relay node down --state-dir ${claim.state_dir} --force`);
|
|
1369
|
-
return false;
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
// Checked before the connection file, exactly as `inspectNodeClaim` orders
|
|
1373
|
-
// them: the descriptor is the only evidence that covers a child's whole life,
|
|
1374
|
-
// including the window before it has published anything at all.
|
|
1375
|
-
const fence = await waitForClaimHoldRelease(claim, deps);
|
|
1376
|
-
if (fence.held) {
|
|
1377
|
-
deps.warn(`${fence.reason}; keeping this machine's claim on node ${claim.node_id}. ` +
|
|
1378
|
-
`Stop it with: agent-relay node down --state-dir ${claim.state_dir} --force`);
|
|
1379
|
-
return false;
|
|
1380
|
-
}
|
|
1381
|
-
const occupant = await findLiveStateDirBroker(claim.state_dir, { env: deps.env, killProcess: deps.killProcess, execCommand: deps.execCommand }, { binary: claim.broker_binary, object: claim.broker_executable });
|
|
1382
|
-
if (occupant) {
|
|
1383
|
-
deps.warn(`A broker (pid ${occupant.pid}) is still serving ${claim.state_dir}; keeping this machine's claim on node ${claim.node_id}. ` +
|
|
1384
|
-
`Stop it with: agent-relay node down --state-dir ${claim.state_dir} --force`);
|
|
1385
|
-
return false;
|
|
1386
|
-
}
|
|
1387
|
-
await releaseNodeClaim(claim, deps.env);
|
|
1388
|
-
return true;
|
|
1389
|
-
}
|
|
1390
|
-
export async function runUpCommand(options, deps) {
|
|
1391
|
-
if (!['darwin', 'linux'].includes(process.platform)) {
|
|
1392
|
-
deps.error(`Broker lifecycle identity verification is supported only on macOS and Linux; refusing to start on ${process.platform}.`);
|
|
1393
|
-
deps.exit(1);
|
|
1394
|
-
return;
|
|
1395
|
-
}
|
|
1396
|
-
const localOnly = options.localOnly || deps.env.AGENT_RELAY_LOCAL_ONLY === '1';
|
|
1397
|
-
if (localOnly) {
|
|
1398
|
-
deps.env.AGENT_RELAY_LOCAL_ONLY = '1';
|
|
1399
|
-
deps.warn('DEGRADED — LOCAL ONLY: fleet routing, worker presence, remote delivery and remote attachment are disabled.');
|
|
1400
|
-
}
|
|
1401
|
-
ensureBundledAgentRelayMcpCommand(deps);
|
|
1402
|
-
const paths = deps.getProjectPaths();
|
|
1403
|
-
// The stable, default project data dir (`.agentworkforce/relay/`) captured
|
|
1404
|
-
// BEFORE any --state-dir override below. SDK-backed commands resolve the
|
|
1405
|
-
// recorded workspace key from this default location (they don't accept
|
|
1406
|
-
// --state-dir), so the key must be persisted here even when broker state is
|
|
1407
|
-
// redirected elsewhere.
|
|
1408
|
-
const projectWorkspaceKeyDataDir = paths.dataDir;
|
|
1409
|
-
// The broker's startup_session_set_with_options() checks RELAY_WORKSPACES_JSON
|
|
1410
|
-
// before any single workspace key, so a flag/env/pin/store resolution here
|
|
1411
|
-
// would report provenance the broker never actually used.
|
|
1412
|
-
const joinsMultiWorkspaceSession = usesMultiWorkspaceEnv(deps.env);
|
|
1413
|
-
const workspaceSelection = joinsMultiWorkspaceSession
|
|
1414
|
-
? undefined
|
|
1415
|
-
: resolveWorkspaceSelection({
|
|
1416
|
-
workspaceKey: options.workspaceKey,
|
|
1417
|
-
env: deps.env,
|
|
1418
|
-
projectDataDir: projectWorkspaceKeyDataDir,
|
|
1419
|
-
fileSystem: deps.fs,
|
|
1420
|
-
});
|
|
1421
|
-
const workspaceBindingSource = recordWorkspaceBindingSource(workspaceSelection, deps, joinsMultiWorkspaceSession ? 'multi-workspace' : undefined);
|
|
1422
|
-
const resumedProjectSession = joinsMultiWorkspaceSession
|
|
1423
|
-
? undefined
|
|
1424
|
-
: applyWorkspaceSelection(workspaceSelection, deps, projectWorkspaceKeyDataDir);
|
|
1425
|
-
if (joinsMultiWorkspaceSession) {
|
|
1426
|
-
deps.log(`Workspace source: ${workspaceBindingSourceLabel('multi-workspace')}`);
|
|
1427
|
-
}
|
|
1428
|
-
// --state-dir overrides where the broker writes state / connection files
|
|
1429
|
-
if (options.stateDir) {
|
|
1430
|
-
const resolved = path.resolve(options.stateDir);
|
|
1431
|
-
paths.dataDir = resolved;
|
|
1432
|
-
deps.env.AGENT_RELAY_STATE_DIR = resolved;
|
|
1433
|
-
}
|
|
1434
|
-
// If a workspace key was explicitly provided, inject it into the environment
|
|
1435
|
-
// for both current tools and older compatibility paths. This must happen
|
|
1436
|
-
// before the --background spawn: the detached child inherits deps.env, and
|
|
1437
|
-
// env is the key's only channel — it never rides on argv, where `ps` would
|
|
1438
|
-
// expose it for the daemon's whole lifetime.
|
|
1439
|
-
if (options.workspaceKey) {
|
|
1440
|
-
deps.env.RELAY_WORKSPACE_KEY = options.workspaceKey;
|
|
1441
|
-
deps.env.RELAY_API_KEY = options.workspaceKey;
|
|
1442
|
-
}
|
|
1443
|
-
if (options.background) {
|
|
1444
|
-
const preflight = await recoverHalfStartedBroker(paths, deps, options.brokerName);
|
|
1445
|
-
if (preflight === 'running') {
|
|
1446
|
-
const pid = readBrokerPid(paths.dataDir, deps);
|
|
1447
|
-
deps.error(pid
|
|
1448
|
-
? `Broker already running for this project (pid: ${pid}).`
|
|
1449
|
-
: 'Broker already running for this project.');
|
|
1450
|
-
deps.error('Run `agent-relay status` to inspect it, then `agent-relay down` to stop it.');
|
|
1451
|
-
deps.exit(1);
|
|
1452
|
-
return;
|
|
1453
|
-
}
|
|
1454
|
-
if (preflight === 'blocked') {
|
|
1455
|
-
deps.exit(1);
|
|
1456
|
-
return;
|
|
1457
|
-
}
|
|
1458
|
-
const startErrorPath = backgroundStartErrorPath(paths.dataDir);
|
|
1459
|
-
safeUnlink(startErrorPath, deps);
|
|
1460
|
-
const args = childUpArgsForDetachedStart(options, deps);
|
|
1461
|
-
const invocation = detachedCliInvocation(deps, args);
|
|
1462
|
-
let child;
|
|
1463
|
-
try {
|
|
1464
|
-
child = deps.spawnProcess(invocation.command, invocation.args, {
|
|
1465
|
-
detached: true,
|
|
1466
|
-
stdio: 'ignore',
|
|
1467
|
-
env: deps.env,
|
|
1468
|
-
});
|
|
1469
|
-
}
|
|
1470
|
-
catch (err) {
|
|
1471
|
-
deps.error(`Failed to start broker in background: ${describeErrorWithCause(err)}`);
|
|
1472
|
-
deps.exit(1);
|
|
1473
|
-
return;
|
|
1474
|
-
}
|
|
1475
|
-
child.unref?.();
|
|
1476
|
-
vlog(deps, options.verbose, `Spawned detached broker child (pid: ${child.pid ?? 'unknown'}), waiting for readiness...`);
|
|
1477
|
-
const readiness = await waitForBrokerReadiness(paths, deps, DETACHED_START_READY_TIMEOUT_MS, true, options.verbose, child.pid);
|
|
1478
|
-
if (readiness.state !== 'running') {
|
|
1479
|
-
const pid = readiness.state === 'starting' ? readiness.conn.pid : child.pid;
|
|
1480
|
-
const childExited = typeof child.pid === 'number' && child.pid > 0 && !isProcessRunning(child.pid, deps);
|
|
1481
|
-
if (childExited) {
|
|
1482
|
-
deps.error(`Broker background child exited before becoming ready (pid: ${child.pid}).`);
|
|
1483
|
-
}
|
|
1484
|
-
else {
|
|
1485
|
-
deps.error(pid
|
|
1486
|
-
? `Broker background start did not become ready within ${DETACHED_START_READY_TIMEOUT_MS / 1000}s (pid: ${pid}).`
|
|
1487
|
-
: `Broker background start did not become ready within ${DETACHED_START_READY_TIMEOUT_MS / 1000}s.`);
|
|
1488
|
-
}
|
|
1489
|
-
if (readiness.state === 'starting') {
|
|
1490
|
-
deps.error('Broker process is running, but the API did not become ready.');
|
|
1491
|
-
}
|
|
1492
|
-
const detachedError = readBackgroundStartError(paths.dataDir, deps);
|
|
1493
|
-
if (detachedError) {
|
|
1494
|
-
deps.error(`Detached broker error: ${detachedError}`);
|
|
1495
|
-
}
|
|
1496
|
-
else if (childExited) {
|
|
1497
|
-
deps.error('Retry without --background to see the broker startup error.');
|
|
1498
|
-
}
|
|
1499
|
-
deps.error('Run `agent-relay status --wait-for=10` for details, or `agent-relay down --force` to clean up.');
|
|
1500
|
-
const cleanupPids = new Set();
|
|
1501
|
-
if (typeof child.pid === 'number' && child.pid > 0 && isProcessRunning(child.pid, deps)) {
|
|
1502
|
-
cleanupPids.add(child.pid);
|
|
1503
|
-
}
|
|
1504
|
-
if (readiness.state === 'starting') {
|
|
1505
|
-
cleanupPids.add(readiness.conn.pid);
|
|
1506
|
-
}
|
|
1507
|
-
for (const cleanupPid of cleanupPids) {
|
|
1508
|
-
deps.warn(`Cleaning up failed broker start (pid: ${cleanupPid})`);
|
|
1509
|
-
const identity = readBrokerIdentities(paths, deps)?.find((record) => record.pid === cleanupPid);
|
|
1510
|
-
const stopped = cleanupPid === child.pid
|
|
1511
|
-
? await terminateProcess(cleanupPid, deps, true)
|
|
1512
|
-
: identity && (await stopRecordedBroker(paths, identity, deps, true));
|
|
1513
|
-
if (!stopped) {
|
|
1514
|
-
deps.error(`Failed to stop half-started broker process (pid: ${cleanupPid}). ` +
|
|
1515
|
-
`Verify process ownership before stopping it manually; inspect identities in ${brokerIdentityDirectory(paths, deps)}.`);
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
cleanupBrokerFiles(paths, deps);
|
|
1519
|
-
deps.exit(1);
|
|
1520
|
-
return;
|
|
1521
|
-
}
|
|
1522
|
-
const enrolledNodeToken = localOnly ? undefined : deps.env.RELAY_NODE_TOKEN?.trim();
|
|
1523
|
-
const enrolledNodeId = enrolledNodeToken ? deps.env.RELAY_NODE_ID?.trim() : undefined;
|
|
1524
|
-
let enrollmentFailureReason;
|
|
1525
|
-
if (enrolledNodeToken && !enrolledNodeId) {
|
|
1526
|
-
enrollmentFailureReason =
|
|
1527
|
-
'Cloud enrollment credentials are incomplete: RELAY_NODE_ID is required when RELAY_NODE_TOKEN is set.';
|
|
1528
|
-
}
|
|
1529
|
-
else if (enrolledNodeId) {
|
|
1530
|
-
const enrolledReadiness = await waitForEnrolledNodeReadiness(readiness.conn, deps, {
|
|
1531
|
-
nodeId: enrolledNodeId,
|
|
1532
|
-
...(options.brokerName?.trim() ? { nodeName: options.brokerName.trim() } : {}),
|
|
1533
|
-
}, readiness.statusDetails);
|
|
1534
|
-
if (!enrolledReadiness.ready) {
|
|
1535
|
-
enrollmentFailureReason = enrolledReadiness.reason ?? 'Cloud enrollment did not become ready.';
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
if (enrollmentFailureReason) {
|
|
1539
|
-
deps.error(enrollmentFailureReason);
|
|
1540
|
-
const cleanupPids = new Set();
|
|
1541
|
-
if (typeof child.pid === 'number' && child.pid > 0) {
|
|
1542
|
-
cleanupPids.add(child.pid);
|
|
1543
|
-
}
|
|
1544
|
-
cleanupPids.add(readiness.conn.pid);
|
|
1545
|
-
let allStopped = true;
|
|
1546
|
-
for (const cleanupPid of cleanupPids) {
|
|
1547
|
-
deps.warn(`Cleaning up failed broker start (pid: ${cleanupPid})`);
|
|
1548
|
-
const identity = readBrokerIdentities(paths, deps)?.find((record) => record.pid === cleanupPid);
|
|
1549
|
-
const stopped = cleanupPid === child.pid
|
|
1550
|
-
? await terminateProcess(cleanupPid, deps, true)
|
|
1551
|
-
: identity && (await stopRecordedBroker(paths, identity, deps, true));
|
|
1552
|
-
if (!stopped) {
|
|
1553
|
-
allStopped = false;
|
|
1554
|
-
deps.error(`Failed to stop broker process after Cloud enrollment startup failed (pid: ${cleanupPid}). ` +
|
|
1555
|
-
`Verify process ownership before stopping it manually; inspect identities in ${brokerIdentityDirectory(paths, deps)}.`);
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
if (allStopped) {
|
|
1559
|
-
cleanupBrokerFiles(paths, deps);
|
|
1560
|
-
}
|
|
1561
|
-
deps.exit(1);
|
|
1562
|
-
return;
|
|
1563
|
-
}
|
|
1564
|
-
const identityDeadline = deps.now() + DETACHED_START_READY_TIMEOUT_MS;
|
|
1565
|
-
let identityReady = false;
|
|
1566
|
-
while (deps.now() < identityDeadline && isProcessRunning(readiness.conn.pid, deps)) {
|
|
1567
|
-
const record = readBrokerIdentities(paths, deps)?.find((entry) => entry.pid === readiness.conn.pid);
|
|
1568
|
-
if (record && (await matchesBrokerIdentity(record, paths, deps))) {
|
|
1569
|
-
identityReady = true;
|
|
1570
|
-
break;
|
|
1571
|
-
}
|
|
1572
|
-
await deps.sleep(100);
|
|
1573
|
-
}
|
|
1574
|
-
if (!identityReady) {
|
|
1575
|
-
deps.error(`Broker API is ready but process identity was not confirmed (pid: ${readiness.conn.pid}). State retained; verify ownership manually and inspect identities in ${brokerIdentityDirectory(paths, deps)}.`);
|
|
1576
|
-
deps.exit(1);
|
|
1577
|
-
return;
|
|
1578
|
-
}
|
|
1579
|
-
deps.log('Broker started.');
|
|
1580
|
-
deps.log(`Broker PID: ${readiness.conn.pid}`);
|
|
1581
|
-
deps.log('Stop with: agent-relay down');
|
|
1582
|
-
safeUnlink(startErrorPath, deps);
|
|
1583
|
-
deps.exit(0);
|
|
1584
|
-
return;
|
|
1585
|
-
}
|
|
1586
|
-
const basePort = resolveBrokerBasePort(deps);
|
|
1587
|
-
deps.fs.mkdirSync(paths.dataDir, { recursive: true });
|
|
1588
|
-
const existingPid = readBrokerPid(paths.dataDir, deps);
|
|
1589
|
-
const brokerName = resolveBrokerName(options, deps, paths.projectRoot);
|
|
1590
|
-
let relay = null;
|
|
1591
|
-
let nodeProviders;
|
|
1592
|
-
let reflexCapture;
|
|
1593
|
-
let shuttingDown = false;
|
|
1594
|
-
let sigintCount = 0;
|
|
1595
|
-
let shutdownPromise;
|
|
1596
|
-
let stopWatchingBrokerExit;
|
|
1597
|
-
let managedIdentity;
|
|
1598
|
-
/** Machine-global claim on this broker's enrolled node id, once registered. */
|
|
1599
|
-
let nodeClaim;
|
|
1600
|
-
/**
|
|
1601
|
-
* Descriptor on the claim's hold file, opened before the broker is spawned
|
|
1602
|
-
* and inherited by it.
|
|
1603
|
-
*
|
|
1604
|
-
* This is the ownership fence that does not depend on either process living
|
|
1605
|
-
* long enough to write anything down. A supervisor SIGKILLed between the
|
|
1606
|
-
* spawn and the broker's first write used to leave a reservation whose pids
|
|
1607
|
-
* were all dead and a state dir with no `connection.json`: a competing start
|
|
1608
|
-
* read that as stale, began a second broker, and the orphaned child then
|
|
1609
|
-
* registered against the same node id with nobody left to adopt or stop it.
|
|
1610
|
-
* The child inherits this descriptor across `fork`, so from the instant it
|
|
1611
|
-
* exists the kernel answers for it, and it stops answering the instant it
|
|
1612
|
-
* dies.
|
|
1613
|
-
*/
|
|
1614
|
-
let nodeClaimHoldFd;
|
|
1615
|
-
/**
|
|
1616
|
-
* Every broker pid this start spawned, remembered independently of `relay`.
|
|
1617
|
-
*
|
|
1618
|
-
* The startup failure paths null `relay` out (to avoid a double `shutdown()`)
|
|
1619
|
-
* while the child can still be alive — a `shutdown()` that rejected, a status
|
|
1620
|
-
* check that failed with cleanup failing too. Releasing the node claim then
|
|
1621
|
-
* would open the node id for a broker that is still registered, so the pids
|
|
1622
|
-
* stay here and every release waits on them.
|
|
1623
|
-
*/
|
|
1624
|
-
const spawnedBrokerPids = new Set();
|
|
1625
|
-
let ownedBrokerExited = false;
|
|
1626
|
-
let rejectBrokerExit;
|
|
1627
|
-
const brokerExit = new Promise((_resolve, reject) => {
|
|
1628
|
-
rejectBrokerExit = reject;
|
|
1629
|
-
});
|
|
1630
|
-
// The child can exit during startup before holdOpen begins racing this promise.
|
|
1631
|
-
void brokerExit.catch(() => undefined);
|
|
1632
|
-
const shutdownOnce = async () => {
|
|
1633
|
-
if (!shutdownPromise) {
|
|
1634
|
-
shuttingDown = true;
|
|
1635
|
-
if (relay === null) {
|
|
1636
|
-
// A reservation taken before the broker spawned protects nothing once
|
|
1637
|
-
// this start gives up. Drop it here so the node id frees immediately
|
|
1638
|
-
// instead of staying held until this supervisor's pid disappears.
|
|
1639
|
-
shutdownPromise = (async () => {
|
|
1640
|
-
if (nodeClaim && (await releaseNodeClaimAfterExit(nodeClaim, deps, spawnedBrokerPids))) {
|
|
1641
|
-
nodeClaim = undefined;
|
|
1642
|
-
}
|
|
1643
|
-
// Dropped last: while this descriptor is open, this start is still
|
|
1644
|
-
// one of the live processes the claim's hold answers for.
|
|
1645
|
-
closeNodeClaimHold(nodeClaimHoldFd);
|
|
1646
|
-
nodeClaimHoldFd = undefined;
|
|
1647
|
-
})();
|
|
1648
|
-
}
|
|
1649
|
-
else {
|
|
1650
|
-
shutdownPromise = (async () => {
|
|
1651
|
-
await reflexCapture?.stop();
|
|
1652
|
-
await nodeProviders?.stop();
|
|
1653
|
-
await shutdownUpResources(relay, paths, deps, ownedBrokerExited ? managedIdentity : undefined);
|
|
1654
|
-
// Released only after the broker's exit is OBSERVED: dropping the
|
|
1655
|
-
// claim while its node-control socket is still connected would wave a
|
|
1656
|
-
// second `node up` straight through to evict it, and shutdown can
|
|
1657
|
-
// return without the process being gone.
|
|
1658
|
-
if (nodeClaim && (await releaseNodeClaimAfterExit(nodeClaim, deps, spawnedBrokerPids))) {
|
|
1659
|
-
nodeClaim = undefined;
|
|
1660
|
-
}
|
|
1661
|
-
closeNodeClaimHold(nodeClaimHoldFd);
|
|
1662
|
-
nodeClaimHoldFd = undefined;
|
|
1663
|
-
})();
|
|
1664
|
-
}
|
|
1665
|
-
}
|
|
1666
|
-
await shutdownPromise;
|
|
1667
|
-
};
|
|
1668
|
-
const crashGuard = installStartupCrashGuard(deps, paths, options, shutdownOnce);
|
|
1669
|
-
// Registered before any async startup work (broker spawn, capability
|
|
1670
|
-
// providers, Reflex capture, node delivery wait) so a signal arriving
|
|
1671
|
-
// during that window gets the same graceful, logged shutdown as one that
|
|
1672
|
-
// arrives later during hold-open. Previously these were registered just
|
|
1673
|
-
// before hold-open — a SIGTERM in that earlier window hit Node's bare
|
|
1674
|
-
// default disposition (silent immediate termination) instead, which is
|
|
1675
|
-
// indistinguishable from a genuine crash when observed from outside.
|
|
1676
|
-
deps.onSignal('SIGINT', async () => {
|
|
1677
|
-
sigintCount += 1;
|
|
1678
|
-
if (shuttingDown) {
|
|
1679
|
-
if (sigintCount >= 2) {
|
|
1680
|
-
deps.warn('Force exiting...');
|
|
1681
|
-
deps.exit(130);
|
|
1682
|
-
}
|
|
1683
|
-
return;
|
|
1684
|
-
}
|
|
1685
|
-
deps.log('\nStopping...');
|
|
1686
|
-
await shutdownOnce();
|
|
1687
|
-
deps.exit(0);
|
|
1688
|
-
});
|
|
1689
|
-
deps.onSignal('SIGTERM', async () => {
|
|
1690
|
-
if (shuttingDown) {
|
|
1691
|
-
return;
|
|
1692
|
-
}
|
|
1693
|
-
deps.log('\nStopping (SIGTERM)...');
|
|
1694
|
-
await shutdownOnce();
|
|
1695
|
-
deps.exit(0);
|
|
1696
|
-
});
|
|
1697
|
-
try {
|
|
1698
|
-
if (existingPid !== null) {
|
|
1699
|
-
if (isProcessRunning(existingPid, deps)) {
|
|
1700
|
-
deps.error(`Broker already running for this project (pid: ${existingPid}).`);
|
|
1701
|
-
deps.error('Run `agent-relay status` to inspect it, then `agent-relay down` to stop it.');
|
|
1702
|
-
deps.exit(1);
|
|
1703
|
-
return;
|
|
1704
|
-
}
|
|
1705
|
-
safeUnlink(path.join(paths.dataDir, CONNECTION_FILENAME), deps);
|
|
1706
|
-
}
|
|
1707
|
-
// Point the shared logger at a file / level / format before the fleet
|
|
1708
|
-
// sidecar (which reads this env when it builds its logger) starts.
|
|
1709
|
-
applyNodeLogEnv(options, deps);
|
|
1710
|
-
// Resolved BEFORE the broker starts so an explicit bad --config fails
|
|
1711
|
-
// fast instead of tearing down a broker that just came up.
|
|
1712
|
-
const nodePlan = localOnly ? undefined : await resolveNodeDefinitionForUp(paths, options, deps);
|
|
1713
|
-
const teamsConfig = deps.loadTeamsConfig(paths.projectRoot);
|
|
1714
|
-
// The broker advertises spawn:<harness> capacity for this set. A pre-set
|
|
1715
|
-
// AGENT_RELAY_NODE_HARNESSES is the operator's authoritative declaration of the
|
|
1716
|
-
// node's real capacity and is used verbatim; otherwise the CLI computes it from
|
|
1717
|
-
// the project's runnable harnesses (built-in defaults plus teams.json clis and
|
|
1718
|
-
// any spawn:<harness> definitions) and passes it to the broker before it registers.
|
|
1719
|
-
const capacitySource = planCapacitySource(nodePlan);
|
|
1720
|
-
deps.env.AGENT_RELAY_NODE_HARNESSES = resolveNodeCapacityHarnesses(deps.env.AGENT_RELAY_NODE_HARNESSES, teamsConfig, capacitySource);
|
|
1721
|
-
// The broker reports this provider-level agent cap in its register and
|
|
1722
|
-
// heartbeat frames. A pre-set AGENT_RELAY_NODE_MAX_AGENTS is the
|
|
1723
|
-
// operator's authoritative declaration and wins verbatim; otherwise the
|
|
1724
|
-
// node definition's `maxAgents` is forwarded so the roster reports the
|
|
1725
|
-
// configured cap instead of 0 (unlimited). Without either, the broker
|
|
1726
|
-
// keeps its historically unbounded capacity.
|
|
1727
|
-
const nodeMaxAgents = resolveNodeMaxAgents(deps.env.AGENT_RELAY_NODE_MAX_AGENTS, capacitySource);
|
|
1728
|
-
if (nodeMaxAgents !== undefined) {
|
|
1729
|
-
deps.env.AGENT_RELAY_NODE_MAX_AGENTS = nodeMaxAgents;
|
|
1730
|
-
}
|
|
1731
|
-
// Recover a broker whose discovery files were lost only while its persisted
|
|
1732
|
-
// process identity and original runtime lock still prove ownership.
|
|
1733
|
-
vlog(deps, options.verbose, 'Checking for orphaned broker processes...');
|
|
1734
|
-
const orphanCleanup = await killOrphanedBrokerProcesses(paths, deps, {
|
|
1735
|
-
brokerName,
|
|
1736
|
-
matchBrokerName: true,
|
|
1737
|
-
});
|
|
1738
|
-
if (orphanCleanup.matchedCount > orphanCleanup.killedCount) {
|
|
1739
|
-
throw new Error('Could not verify orphan broker exit; retained its state for a later cleanup.');
|
|
1740
|
-
}
|
|
1741
|
-
// Ownership is taken BEFORE the broker exists, because the broker registers
|
|
1742
|
-
// with the engine on its own initialization path. A start that loses here
|
|
1743
|
-
// has spawned nothing, so it cannot have moved the node's delivery socket.
|
|
1744
|
-
nodeClaim = await reserveEnrolledNode(paths, options, deps, localOnly);
|
|
1745
|
-
if (nodeClaim) {
|
|
1746
|
-
// Opened BEFORE the spawn: a fence established afterwards would leave
|
|
1747
|
-
// exactly the window it exists to close. A failure here throws, so the
|
|
1748
|
-
// spawn below is unreachable without the fence in place -- warning and
|
|
1749
|
-
// continuing would have started a broker whose claim silently loses its
|
|
1750
|
-
// crash safety, which is the failure this whole path exists to prevent.
|
|
1751
|
-
// The outer catch releases the reservation on the way out.
|
|
1752
|
-
nodeClaimHoldFd = openNodeClaimHold(nodeClaim, deps.env);
|
|
1753
|
-
}
|
|
1754
|
-
const started = await startBrokerWithPortFallback(paths, basePort, deps, brokerName, options.verbose,
|
|
1755
|
-
// Assign `relay` as soon as the broker child process exists, not only
|
|
1756
|
-
// once the handshake/status-check retries above also succeed. A
|
|
1757
|
-
// SIGTERM/SIGINT arriving during that check window otherwise finds
|
|
1758
|
-
// `relay` still null, so `shutdownOnce()` no-ops and leaks the broker
|
|
1759
|
-
// child instead of shutting it down.
|
|
1760
|
-
(candidate) => {
|
|
1761
|
-
relay = candidate;
|
|
1762
|
-
// Remembered here and never cleared: the catch below nulls `relay` out
|
|
1763
|
-
// while this process can still be running, and the node claim must not
|
|
1764
|
-
// be released while it is.
|
|
1765
|
-
if (typeof candidate.brokerPid === 'number' && candidate.brokerPid > 0) {
|
|
1766
|
-
spawnedBrokerPids.add(candidate.brokerPid);
|
|
1767
|
-
}
|
|
1768
|
-
}, nodeClaimHoldFd === undefined ? [] : [nodeClaimHoldFd],
|
|
1769
|
-
// Written to the claim in the same turn the child exists, because the
|
|
1770
|
-
// executable identity recorded before the spawn describes the file this
|
|
1771
|
-
// start MEANT to run, not the one the process ends up mapping: a shebang
|
|
1772
|
-
// launcher runs as its interpreter, and a launcher that `exec`s the real
|
|
1773
|
-
// broker maps that instead. Both kept their pid, and without it such a
|
|
1774
|
-
// live, fenced child read as an unrelated process and the next start took
|
|
1775
|
-
// its node id. Tracked for the release path too, which must not free a
|
|
1776
|
-
// claim while a child this start spawned can still register under it.
|
|
1777
|
-
(pid) => {
|
|
1778
|
-
if (pid > 0)
|
|
1779
|
-
spawnedBrokerPids.add(pid);
|
|
1780
|
-
if (nodeClaim)
|
|
1781
|
-
nodeClaim = recordSpawnedBrokerChild(nodeClaim, pid, deps.env);
|
|
1782
|
-
}).catch((err) => {
|
|
1783
|
-
// On failure, `startBrokerWithPortFallback` has already shut down any
|
|
1784
|
-
// candidate it created before rethrowing. Clear the early handle too
|
|
1785
|
-
// so the outer catch's `shutdownOnce()` does not call `shutdown()` a
|
|
1786
|
-
// second time on it.
|
|
1787
|
-
relay = null;
|
|
1788
|
-
throw err;
|
|
1789
|
-
});
|
|
1790
|
-
relay = started.relay;
|
|
1791
|
-
stopWatchingBrokerExit = relay.onBrokerExit?.(() => {
|
|
1792
|
-
ownedBrokerExited = true;
|
|
1793
|
-
if (!shuttingDown)
|
|
1794
|
-
rejectBrokerExit(new Error('Broker exited; stopping the node supervisor.'));
|
|
1795
|
-
});
|
|
1796
|
-
if (relay.brokerPid)
|
|
1797
|
-
managedIdentity = await persistBrokerIdentity(paths, relay.brokerPid, brokerName, deps);
|
|
1798
|
-
if (!managedIdentity) {
|
|
1799
|
-
throw new Error('Could not persist a verified broker process identity. Startup was stopped; ensure ps and lsof are available, process inspection is permitted, and the project identity directory is writable.');
|
|
1800
|
-
}
|
|
1801
|
-
// Hand the reservation to the verified broker process that now owns the
|
|
1802
|
-
// state dir, so the claim survives this supervisor and `node down` can
|
|
1803
|
-
// release it by the pid it verifies.
|
|
1804
|
-
if (nodeClaim) {
|
|
1805
|
-
nodeClaim = await adoptEnrolledNodeClaim(nodeClaim, { pid: managedIdentity.pid, brokerName, apiPort: started.apiPort }, deps);
|
|
1806
|
-
}
|
|
1807
|
-
try {
|
|
1808
|
-
writeBrokerBindingSource(paths.dataDir, workspaceBindingSource, deps);
|
|
1809
|
-
}
|
|
1810
|
-
catch {
|
|
1811
|
-
// Provenance is diagnostic metadata; a broker that came up stays up.
|
|
1812
|
-
}
|
|
1813
|
-
safeUnlink(backgroundStartErrorPath(paths.dataDir), deps);
|
|
1814
|
-
deps.log(`Relay API: http://localhost:${started.apiPort}`);
|
|
1815
|
-
deps.log(`Project: ${paths.projectRoot}`);
|
|
1816
|
-
deps.log('Mode: broker (stdio)');
|
|
1817
|
-
deps.log(`Workspace Key: ${relay.workspaceKey ? maskSecret(relay.workspaceKey) : 'unknown'}`);
|
|
1818
|
-
// Minting must be observable: without this line "created a workspace" and
|
|
1819
|
-
// "joined the pinned workspace" print identically.
|
|
1820
|
-
const joinedWorkspaceId = relay.workspaceId ?? 'unknown';
|
|
1821
|
-
// The multi-workspace session always joins a configured membership; it
|
|
1822
|
-
// never mints a new workspace the way an unresolved single key does.
|
|
1823
|
-
if (localOnly) {
|
|
1824
|
-
deps.log('Workspace: local only; configured credentials are used only for delivery-record reconciliation');
|
|
1825
|
-
}
|
|
1826
|
-
else if (workspaceSelection || joinsMultiWorkspaceSession) {
|
|
1827
|
-
deps.log(`Workspace: joined ${joinedWorkspaceId}`);
|
|
1828
|
-
}
|
|
1829
|
-
else {
|
|
1830
|
-
deps.log(`Workspace: created new workspace ${joinedWorkspaceId}`);
|
|
1831
|
-
deps.log('Pin a workspace for this repository with `agent-relay up --workspace-key <key>`, ' +
|
|
1832
|
-
'or select one machine-wide with `agent-relay workspace switch <name>`.');
|
|
1833
|
-
}
|
|
1834
|
-
deps.log('Broker started.');
|
|
1835
|
-
// Record the workspace this broker joined (explicitly passed or auto-minted)
|
|
1836
|
-
// in the DEFAULT project data dir (not any --state-dir override), so later
|
|
1837
|
-
// SDK commands in this CWD resolve it instead of the machine-global active
|
|
1838
|
-
// workspace. Persistence must never abort startup, so a write failure is
|
|
1839
|
-
// swallowed.
|
|
1840
|
-
try {
|
|
1841
|
-
const relayWorkspaceKey = relay.workspaceKey ?? undefined;
|
|
1842
|
-
const sameWorkspace = resumedProjectSession?.workspaceKey === relayWorkspaceKey;
|
|
1843
|
-
writeProjectWorkspaceKeyPreservingSession(projectWorkspaceKeyDataDir, relayWorkspaceKey, {
|
|
1844
|
-
enrolledNodeId: deps.env.AGENT_RELAY_ENROLLED_NODE_ID ?? resumedProjectSession?.enrolledNodeId,
|
|
1845
|
-
// Recording the resolved workspace id lets the NEXT start detect a
|
|
1846
|
-
// conflicting source (a stored enrollment in another workspace) before
|
|
1847
|
-
// the broker comes up, instead of after agents land in the wrong place.
|
|
1848
|
-
...((relay.workspaceId ?? (sameWorkspace ? resumedProjectSession?.workspaceId : undefined))
|
|
1849
|
-
? { workspaceId: relay.workspaceId ?? resumedProjectSession?.workspaceId }
|
|
1850
|
-
: {}),
|
|
1851
|
-
});
|
|
1852
|
-
}
|
|
1853
|
-
catch {
|
|
1854
|
-
// best-effort: a broker that came up should stay up even if the key file
|
|
1855
|
-
// can't be written (read-only dir, etc.).
|
|
1856
|
-
}
|
|
1857
|
-
vlog(deps, options.verbose, 'Starting node capability providers (if any)...');
|
|
1858
|
-
nodeProviders = localOnly
|
|
1859
|
-
? undefined
|
|
1860
|
-
: await startNodeCapabilityProviders(paths, relay, options, deps, nodePlan);
|
|
1861
|
-
// When Reflex is enabled, periodically sync + push local session history to
|
|
1862
|
-
// relayhistory-cloud in-process via the ai-hist-native addon (no subprocess).
|
|
1863
|
-
// No-op when disabled or the addon isn't available.
|
|
1864
|
-
reflexCapture = startReflexCapture({ log: createReflexDiagnosticLog(options, deps) });
|
|
1865
|
-
const shouldSpawn = options.spawn === true ? true : options.spawn === false ? false : Boolean(teamsConfig?.autoSpawn);
|
|
1866
|
-
if (shouldSpawn && teamsConfig && teamsConfig.agents.length > 0) {
|
|
1867
|
-
vlog(deps, options.verbose, 'Waiting for broker node delivery (/v1/node/ws) before auto-spawning...');
|
|
1868
|
-
// Node delivery can't connect until the broker mints its node token, which
|
|
1869
|
-
// now happens in the background after `Broker started.`. Budget for that
|
|
1870
|
-
// mint window plus the connect so a slow mint doesn't abort auto-spawn.
|
|
1871
|
-
const delivery = localOnly
|
|
1872
|
-
? { ready: true, status: null }
|
|
1873
|
-
: await waitForNodeDelivery(relay, deps, NODE_TOKEN_WAIT_MS + NODE_DELIVERY_READY_TIMEOUT_MS);
|
|
1874
|
-
if (!delivery.ready) {
|
|
1875
|
-
deps.error('Refusing to auto-spawn agents because broker node delivery is not connected.');
|
|
1876
|
-
deps.error(`Node delivery: ${formatNodeDeliveryStatus(delivery.status)}`);
|
|
1877
|
-
deps.error('Realtime injection depends on /v1/node/ws. Check broker logs for create_node/node token errors, then retry `agent-relay up --spawn`.');
|
|
1878
|
-
await shutdownOnce();
|
|
1879
|
-
deps.exit(1);
|
|
1880
|
-
return;
|
|
1881
|
-
}
|
|
1882
|
-
for (const agent of teamsConfig.agents) {
|
|
1883
|
-
vlog(deps, options.verbose, `Spawning agent '${agent.name}' (cli: ${agent.cli})...`);
|
|
1884
|
-
await relay.spawn({
|
|
1885
|
-
name: agent.name,
|
|
1886
|
-
cli: agent.cli,
|
|
1887
|
-
...(agent.model ? { model: agent.model } : {}),
|
|
1888
|
-
channels: ['general'],
|
|
1889
|
-
task: agent.task ?? '',
|
|
1890
|
-
team: teamsConfig.team,
|
|
1891
|
-
});
|
|
1892
|
-
}
|
|
1893
|
-
}
|
|
1894
|
-
else if (options.spawn === true && !teamsConfig) {
|
|
1895
|
-
deps.warn('Warning: --spawn specified but no teams.json found');
|
|
1896
|
-
}
|
|
1897
|
-
const holdOpen = Promise.race([deps.holdOpen(), brokerExit]);
|
|
1898
|
-
if (nodeProviders?.done) {
|
|
1899
|
-
await Promise.race([holdOpen, nodeProviders.done]);
|
|
1900
|
-
}
|
|
1901
|
-
else {
|
|
1902
|
-
await holdOpen;
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
catch (err) {
|
|
1906
|
-
// A rejection from cleanup must not swallow the original startup
|
|
1907
|
-
// failure -- without this, `deps.exit(1)` below would never run and the
|
|
1908
|
-
// startup error would go unreported.
|
|
1909
|
-
try {
|
|
1910
|
-
await shutdownOnce();
|
|
1911
|
-
}
|
|
1912
|
-
catch (cleanupError) {
|
|
1913
|
-
deps.warn(`Failed to clean up after broker startup failure: ${describeErrorWithCause(cleanupError)}`);
|
|
1914
|
-
}
|
|
1915
|
-
// A straggler process-level crash event for this same failure must not
|
|
1916
|
-
// also fire and duplicate the report below. Marked here -- after
|
|
1917
|
-
// cleanup, right before reporting -- rather than at catch-entry, so an
|
|
1918
|
-
// unrelated crash during the shutdownOnce() cleanup above is not
|
|
1919
|
-
// silently swallowed by this guard too.
|
|
1920
|
-
crashGuard.markHandled();
|
|
1921
|
-
reportBrokerStartFailure(err, deps, paths, options);
|
|
1922
|
-
deps.exit(1);
|
|
1923
|
-
}
|
|
1924
|
-
finally {
|
|
1925
|
-
stopWatchingBrokerExit?.();
|
|
1926
|
-
crashGuard.dispose();
|
|
1927
|
-
}
|
|
1928
|
-
}
|
|
1929
|
-
/**
|
|
1930
|
-
* Point `down` at live brokers serving other state directories.
|
|
1931
|
-
*
|
|
1932
|
-
* `down` resolves its state dir from the cwd (or `--state-dir`), so running it
|
|
1933
|
-
* from the wrong directory reports "Not running" while the broker it was meant
|
|
1934
|
-
* to stop keeps serving. The machine-global node claims are the one index that
|
|
1935
|
-
* spans state dirs, so use them to name the live brokers instead.
|
|
1936
|
-
*/
|
|
1937
|
-
async function reportNodeClaimsElsewhere(paths, deps) {
|
|
1938
|
-
let held;
|
|
1939
|
-
try {
|
|
1940
|
-
held = await listHeldNodeClaims({
|
|
1941
|
-
env: deps.env,
|
|
1942
|
-
killProcess: deps.killProcess,
|
|
1943
|
-
execCommand: deps.execCommand,
|
|
1944
|
-
});
|
|
1945
|
-
}
|
|
1946
|
-
catch {
|
|
1947
|
-
// Diagnostics only — an unreadable claims directory changes nothing here.
|
|
1948
|
-
return;
|
|
1949
|
-
}
|
|
1950
|
-
const stateDir = normalizeClaimStateDir(paths.dataDir);
|
|
1951
|
-
const elsewhere = held.filter((claim) => claim.state_dir !== stateDir);
|
|
1952
|
-
if (elsewhere.length === 0) {
|
|
1953
|
-
return;
|
|
1954
|
-
}
|
|
1955
|
-
deps.log('Live relay nodes on this machine are serving other state directories:');
|
|
1956
|
-
for (const claim of elsewhere) {
|
|
1957
|
-
deps.log(` node ${claim.node_id} — ${describeNodeClaimHolder(claim)}`);
|
|
1958
|
-
}
|
|
1959
|
-
deps.log('Stop one with: agent-relay node down --state-dir <state dir>');
|
|
1960
|
-
}
|
|
1961
|
-
/**
|
|
1962
|
-
* Resolve `--state-dir` for commands that inspect an existing broker. A fleet
|
|
1963
|
-
* node directory holds its broker state in `state/`, so accept the node
|
|
1964
|
-
* directory too when the nested one holds the broker (relay#1575).
|
|
1965
|
-
*
|
|
1966
|
-
* Evidence is ranked, checking the exact directory before `state/` at each
|
|
1967
|
-
* rank: an identity record verified against its running process (start
|
|
1968
|
-
* time, executable and held lock, as `down` requires before signalling),
|
|
1969
|
-
* then a `connection.json` whose pid is running, then any `connection.json`,
|
|
1970
|
-
* then any broker lock or record. Leftover files in the node directory —
|
|
1971
|
-
* including a connection file whose pid was reused by another process —
|
|
1972
|
-
* therefore cannot shadow a verified nested broker, and `down --force` can
|
|
1973
|
-
* still recover a broker whose connection file is gone.
|
|
1974
|
-
*/
|
|
1975
|
-
async function resolveExistingStateDir(stateDir, deps) {
|
|
1976
|
-
const exact = path.resolve(stateDir);
|
|
1977
|
-
const candidates = [exact, path.join(exact, 'state')];
|
|
1978
|
-
const ranks = [
|
|
1979
|
-
(dir) => hasVerifiedBrokerIdentity(dir, deps),
|
|
1980
|
-
(dir) => hasLiveConnection(dir, deps),
|
|
1981
|
-
(dir) => deps.fs.existsSync(path.join(dir, CONNECTION_FILENAME)),
|
|
1982
|
-
(dir) => hasBrokerStateFiles(dir, deps),
|
|
1983
|
-
];
|
|
1984
|
-
for (const matches of ranks) {
|
|
1985
|
-
for (const candidate of candidates) {
|
|
1986
|
-
if (await matches(candidate))
|
|
1987
|
-
return candidate;
|
|
1988
|
-
}
|
|
1989
|
-
}
|
|
1990
|
-
return exact;
|
|
1991
|
-
}
|
|
1992
|
-
function brokerStateFiles(dir, deps) {
|
|
1993
|
-
try {
|
|
1994
|
-
return deps.fs
|
|
1995
|
-
.readdirSync(dir)
|
|
1996
|
-
.filter((file) => file.startsWith('broker-') && (file.endsWith('.lock') || file.endsWith('.json')));
|
|
1997
|
-
}
|
|
1998
|
-
catch {
|
|
1999
|
-
return [];
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
2002
|
-
function hasBrokerStateFiles(dir, deps) {
|
|
2003
|
-
return brokerStateFiles(dir, deps).length > 0;
|
|
2004
|
-
}
|
|
2005
|
-
/** A connection file only proves a live broker while its pid is running. */
|
|
2006
|
-
function hasLiveConnection(dir, deps) {
|
|
2007
|
-
const pid = readBrokerConnectionFromFs(deps.fs, dir)?.pid;
|
|
2008
|
-
return typeof pid === 'number' && pid > 0 && isProcessRunning(pid, deps);
|
|
2009
|
-
}
|
|
2010
|
-
/**
|
|
2011
|
-
* Whether `dir` holds an identity record that still matches its process. A
|
|
2012
|
-
* bare pid check would trust a stale record whose pid has been reused.
|
|
2013
|
-
*/
|
|
2014
|
-
async function hasVerifiedBrokerIdentity(dir, deps) {
|
|
2015
|
-
const paths = { ...deps.getProjectPaths(), dataDir: dir };
|
|
2016
|
-
for (const identity of readBrokerIdentities(paths, deps) ?? []) {
|
|
2017
|
-
if (await matchesBrokerIdentity(identity, paths, deps))
|
|
2018
|
-
return true;
|
|
2019
|
-
}
|
|
2020
|
-
return false;
|
|
2021
|
-
}
|
|
2022
|
-
// eslint-disable-next-line complexity, max-depth
|
|
2023
|
-
export async function runDownCommand(options, deps) {
|
|
2024
|
-
const paths = deps.getProjectPaths();
|
|
2025
|
-
if (options.stateDir) {
|
|
2026
|
-
paths.dataDir = await resolveExistingStateDir(options.stateDir, deps);
|
|
2027
|
-
}
|
|
2028
|
-
const timeout = Number.parseInt(options.timeout ?? '5000', 10) || 5000;
|
|
2029
|
-
if (options.all) {
|
|
2030
|
-
deps.log('Stopping all agent-relay processes...');
|
|
2031
|
-
try {
|
|
2032
|
-
const { stdout } = await deps.execCommand('ps aux');
|
|
2033
|
-
const pids = [];
|
|
2034
|
-
for (const line of stdout.split('\n')) {
|
|
2035
|
-
if (!line.includes('agent-relay') || !line.includes(' up') || line.includes('agent-relay-mcp')) {
|
|
2036
|
-
continue;
|
|
2037
|
-
}
|
|
2038
|
-
const fields = line.trim().split(/\s+/);
|
|
2039
|
-
const pid = Number.parseInt(fields[1], 10);
|
|
2040
|
-
if (!Number.isNaN(pid) && pid > 0 && pid !== deps.pid) {
|
|
2041
|
-
pids.push(pid);
|
|
2042
|
-
}
|
|
2043
|
-
}
|
|
2044
|
-
for (const pid of pids) {
|
|
2045
|
-
try {
|
|
2046
|
-
deps.killProcess(pid, 'SIGTERM');
|
|
2047
|
-
}
|
|
2048
|
-
catch {
|
|
2049
|
-
// Ignore dead pids.
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
if (options.force) {
|
|
2053
|
-
await deps.sleep(2000);
|
|
2054
|
-
for (const pid of pids) {
|
|
2055
|
-
// eslint-disable-next-line max-depth
|
|
2056
|
-
if (isProcessRunning(pid, deps)) {
|
|
2057
|
-
// eslint-disable-next-line max-depth
|
|
2058
|
-
try {
|
|
2059
|
-
deps.killProcess(pid, 'SIGKILL');
|
|
2060
|
-
}
|
|
2061
|
-
catch {
|
|
2062
|
-
// Ignore dead pids.
|
|
2063
|
-
}
|
|
2064
|
-
}
|
|
2065
|
-
}
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
catch (err) {
|
|
2069
|
-
deps.error(`Error finding processes: ${toErrorMessage(err)}`);
|
|
2070
|
-
}
|
|
2071
|
-
cleanupBrokerFiles(paths, deps);
|
|
2072
|
-
deps.log('Done');
|
|
2073
|
-
return;
|
|
2074
|
-
}
|
|
2075
|
-
const conn = readBrokerConnectionFromFs(deps.fs, paths.dataDir);
|
|
2076
|
-
if (!conn) {
|
|
2077
|
-
if (options.force) {
|
|
2078
|
-
const result = await killOrphanedBrokerProcesses(paths, deps, { force: true });
|
|
2079
|
-
if (result.matchedCount > result.killedCount) {
|
|
2080
|
-
deps.error('Could not verify broker exit; retained its state for a later cleanup.');
|
|
2081
|
-
deps.exit(1);
|
|
2082
|
-
return;
|
|
2083
|
-
}
|
|
2084
|
-
if (result.matchedCount === 0) {
|
|
2085
|
-
deps.log('No verified orphan broker found; retained existing state.');
|
|
2086
|
-
await reportNodeClaimsElsewhere(paths, deps);
|
|
2087
|
-
return;
|
|
2088
|
-
}
|
|
2089
|
-
cleanupBrokerFiles(paths, deps);
|
|
2090
|
-
deps.log('Cleaned up (was not running)');
|
|
2091
|
-
}
|
|
2092
|
-
else {
|
|
2093
|
-
deps.log('Not running');
|
|
2094
|
-
await reportNodeClaimsElsewhere(paths, deps);
|
|
2095
|
-
}
|
|
2096
|
-
return;
|
|
2097
|
-
}
|
|
2098
|
-
const pid = conn.pid;
|
|
2099
|
-
if (!pid || pid <= 0) {
|
|
2100
|
-
cleanupBrokerFiles(paths, deps);
|
|
2101
|
-
deps.log('Cleaned up stale state (invalid connection file)');
|
|
2102
|
-
return;
|
|
2103
|
-
}
|
|
2104
|
-
if (!isProcessRunning(pid, deps)) {
|
|
2105
|
-
cleanupBrokerFiles(paths, deps);
|
|
2106
|
-
await releaseNodeClaimsForBroker({
|
|
2107
|
-
pid,
|
|
2108
|
-
stateDir: paths.dataDir,
|
|
2109
|
-
env: deps.env,
|
|
2110
|
-
killProcess: deps.killProcess,
|
|
2111
|
-
execCommand: deps.execCommand,
|
|
2112
|
-
});
|
|
2113
|
-
deps.log('Cleaned up stale state (process was not running)');
|
|
2114
|
-
return;
|
|
2115
|
-
}
|
|
2116
|
-
const identities = readBrokerIdentities(paths, deps);
|
|
2117
|
-
const identity = identities?.find((record) => record.pid === pid);
|
|
2118
|
-
if (identities && !identity) {
|
|
2119
|
-
deps.error(`No identity record for the running broker (pid: ${pid}) in ${brokerIdentityDirectory(paths, deps)}; retained its state. ` +
|
|
2120
|
-
'It was started by an older CLI or directly with `agent-relay-broker init`, which record none. ' +
|
|
2121
|
-
`Verify ownership and stop it manually once, then start it with \`agent-relay node up --state-dir ${paths.dataDir}\` ` +
|
|
2122
|
-
'so later `node down` calls can verify it. Connection metadata alone cannot authorize a signal.');
|
|
2123
|
-
deps.exit(1);
|
|
2124
|
-
return;
|
|
2125
|
-
}
|
|
2126
|
-
if (!identity || !(await matchesBrokerIdentity(identity, paths, deps))) {
|
|
2127
|
-
deps.error(`Broker identity could not be verified (pid: ${pid}); retained its state. Verify ownership before stopping the process manually; inspect identities in ${brokerIdentityDirectory(paths, deps)}. Connection metadata alone cannot authorize a signal.`);
|
|
2128
|
-
deps.exit(1);
|
|
2129
|
-
return;
|
|
2130
|
-
}
|
|
2131
|
-
try {
|
|
2132
|
-
deps.log(`Stopping broker (pid: ${pid})...`);
|
|
2133
|
-
deps.killProcess(pid, 'SIGTERM');
|
|
2134
|
-
let exited = await waitForProcessExit(pid, timeout, deps);
|
|
2135
|
-
if (!exited) {
|
|
2136
|
-
// eslint-disable-next-line max-depth
|
|
2137
|
-
if (options.force) {
|
|
2138
|
-
deps.log('Graceful shutdown timed out, forcing...');
|
|
2139
|
-
if (identity && !(await matchesBrokerIdentity(identity, paths, deps))) {
|
|
2140
|
-
throw new Error('Broker identity changed before escalation; retained its state.');
|
|
2141
|
-
}
|
|
2142
|
-
deps.killProcess(pid, 'SIGKILL');
|
|
2143
|
-
exited = await waitForProcessExit(pid, 2000, deps);
|
|
2144
|
-
}
|
|
2145
|
-
else {
|
|
2146
|
-
deps.log(`Graceful shutdown timed out after ${timeout}ms. Use --force to kill.`);
|
|
2147
|
-
return;
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
if (!exited) {
|
|
2151
|
-
throw new Error('Could not verify broker exit; retained its state for a later cleanup.');
|
|
2152
|
-
}
|
|
2153
|
-
if (identity)
|
|
2154
|
-
removeBrokerIdentity(paths, identity, deps);
|
|
2155
|
-
cleanupBrokerFiles(paths, deps);
|
|
2156
|
-
// The supervising CLI releases its own claim on a graceful exit, but `down`
|
|
2157
|
-
// can outlive it (or kill it with --force), so release by the pid and state
|
|
2158
|
-
// dir it just verified. Only a claim naming both is removed.
|
|
2159
|
-
for (const claim of await releaseNodeClaimsForBroker({
|
|
2160
|
-
pid,
|
|
2161
|
-
stateDir: paths.dataDir,
|
|
2162
|
-
env: deps.env,
|
|
2163
|
-
killProcess: deps.killProcess,
|
|
2164
|
-
execCommand: deps.execCommand,
|
|
2165
|
-
})) {
|
|
2166
|
-
deps.log(`Released this machine's claim on node ${claim.node_id}.`);
|
|
2167
|
-
}
|
|
2168
|
-
deps.log('Stopped');
|
|
2169
|
-
return;
|
|
2170
|
-
}
|
|
2171
|
-
catch (err) {
|
|
2172
|
-
const withCode = err;
|
|
2173
|
-
if (withCode.code === 'ESRCH') {
|
|
2174
|
-
removeBrokerIdentity(paths, identity, deps);
|
|
2175
|
-
cleanupBrokerFiles(paths, deps);
|
|
2176
|
-
await releaseNodeClaimsForBroker({
|
|
2177
|
-
pid,
|
|
2178
|
-
stateDir: paths.dataDir,
|
|
2179
|
-
env: deps.env,
|
|
2180
|
-
killProcess: deps.killProcess,
|
|
2181
|
-
execCommand: deps.execCommand,
|
|
2182
|
-
});
|
|
2183
|
-
deps.log('Cleaned up stale state');
|
|
2184
|
-
return;
|
|
2185
|
-
}
|
|
2186
|
-
deps.error(`Error stopping broker: ${toErrorMessage(err)}`);
|
|
2187
|
-
}
|
|
2188
|
-
deps.exit(1);
|
|
2189
|
-
}
|
|
2190
|
-
export async function runStatusCommand(deps, options) {
|
|
2191
|
-
const paths = deps.getProjectPaths();
|
|
2192
|
-
if (options?.stateDir) {
|
|
2193
|
-
paths.dataDir = await resolveExistingStateDir(options.stateDir, deps);
|
|
2194
|
-
}
|
|
2195
|
-
const waitMs = parseWaitForMs(options?.waitFor, deps);
|
|
2196
|
-
if (waitMs === null) {
|
|
2197
|
-
return;
|
|
2198
|
-
}
|
|
2199
|
-
const readiness = await waitForBrokerReadiness(paths, deps, waitMs, waitMs > 0);
|
|
2200
|
-
if (readiness.state === 'stopped') {
|
|
2201
|
-
deps.log('Status: STOPPED');
|
|
2202
|
-
if (waitMs > 0) {
|
|
2203
|
-
deps.exit(1);
|
|
2204
|
-
}
|
|
2205
|
-
return;
|
|
2206
|
-
}
|
|
2207
|
-
if (readiness.state === 'starting') {
|
|
2208
|
-
deps.log('Status: STARTING');
|
|
2209
|
-
deps.log('Mode: broker (stdio)');
|
|
2210
|
-
deps.log(`PID: ${readiness.conn.pid}`);
|
|
2211
|
-
deps.log(`Project: ${paths.projectRoot}`);
|
|
2212
|
-
deps.warn('Broker process is running, but the API did not become ready before timeout.');
|
|
2213
|
-
deps.exit(1);
|
|
2214
|
-
return;
|
|
2215
|
-
}
|
|
2216
|
-
const statusDetails = readiness.statusDetails ?? (waitMs > 0 ? null : await readBrokerStatusDetails(readiness.conn));
|
|
2217
|
-
const localOnly = statusDetails?.status.mode === 'local_only' || readiness.conn.operation_mode === 'local_only';
|
|
2218
|
-
deps.log(localOnly ? 'Status: DEGRADED (LOCAL ONLY)' : 'Status: RUNNING');
|
|
2219
|
-
deps.log(localOnly ? 'Mode: local only' : 'Mode: broker (stdio)');
|
|
2220
|
-
if (localOnly) {
|
|
2221
|
-
deps.warn('Cross-machine routing, worker presence, remote delivery and remote attachment: DISABLED');
|
|
2222
|
-
const reconciliation = statusDetails?.status.degraded?.reconciliation;
|
|
2223
|
-
if (reconciliation) {
|
|
2224
|
-
deps.log(`Reconciliation: ${reconciliation.connected ? 'connected (audit only)' : reconciliation.configured ? 'disconnected' : 'not configured'}; pending records: ${reconciliation.pending_records}`);
|
|
2225
|
-
}
|
|
2226
|
-
}
|
|
2227
|
-
deps.log(`PID: ${readiness.conn.pid}`);
|
|
2228
|
-
deps.log(`Project: ${paths.projectRoot}`);
|
|
2229
|
-
const identities = readBrokerIdentities(paths, deps);
|
|
2230
|
-
if (identities && !identities.some((record) => record.pid === readiness.conn.pid)) {
|
|
2231
|
-
// Surface this before an outage: without a record `node down` refuses to signal.
|
|
2232
|
-
deps.warn(`Broker identity: not recorded in ${brokerIdentityDirectory(paths, deps)}; \`node down\` cannot verify this broker. ` +
|
|
2233
|
-
`Restart it once with \`agent-relay node up --state-dir ${paths.dataDir}\` to record one.`);
|
|
2234
|
-
}
|
|
2235
|
-
const source = workspaceBindingSource(readiness.conn.workspace_source);
|
|
2236
|
-
deps.log(source
|
|
2237
|
-
? `Workspace source: ${workspaceBindingSourceLabel(source)}`
|
|
2238
|
-
: 'Workspace source: unknown (startup provenance was not recorded)');
|
|
2239
|
-
// Additional runtime details use the same bounded snapshot as the mode above.
|
|
2240
|
-
if (!statusDetails || statusDetails.session === null) {
|
|
2241
|
-
deps.warn('Broker API details unavailable (request failed or exceeded the 2s limit).');
|
|
2242
|
-
}
|
|
2243
|
-
if (statusDetails) {
|
|
2244
|
-
const { status, session } = statusDetails;
|
|
2245
|
-
if (typeof status.agent_count === 'number') {
|
|
2246
|
-
deps.log(`Agents: ${status.agent_count}`);
|
|
2247
|
-
}
|
|
2248
|
-
if (typeof status.pending_delivery_count === 'number' && status.pending_delivery_count > 0) {
|
|
2249
|
-
deps.log(`Pending deliveries: ${status.pending_delivery_count}`);
|
|
2250
|
-
}
|
|
2251
|
-
deps.log(`Node delivery: ${formatNodeDeliveryStatus(status)}`);
|
|
2252
|
-
if (session?.node_id) {
|
|
2253
|
-
deps.log(`Node: ${session.node_name?.trim() || session.node_id} (${session.node_id})`);
|
|
2254
|
-
}
|
|
2255
|
-
if (session?.workspace_key) {
|
|
2256
|
-
deps.log(`Workspace Key: ${maskSecret(session.workspace_key)}`);
|
|
2257
|
-
}
|
|
2258
|
-
}
|
|
2259
|
-
}
|
|
2260
|
-
function parseWaitForMs(rawValue, deps) {
|
|
2261
|
-
const rawWaitFor = rawValue?.trim();
|
|
2262
|
-
if (rawWaitFor !== undefined && !/^\d+(?:\.\d+)?$/.test(rawWaitFor)) {
|
|
2263
|
-
deps.error('--wait-for must be a non-negative number of seconds.');
|
|
2264
|
-
deps.exit(1);
|
|
2265
|
-
return null;
|
|
2266
|
-
}
|
|
2267
|
-
const waitSeconds = rawWaitFor === undefined ? 0 : Number.parseFloat(rawWaitFor);
|
|
2268
|
-
return waitSeconds > 0 ? waitSeconds * 1000 : 0;
|
|
2269
|
-
}
|
|
2270
|
-
async function readBrokerStatusDetails(conn) {
|
|
2271
|
-
// Status is a local liveness probe. The driver's 30s mutation timeout would
|
|
2272
|
-
// make a live but stalled broker hang CLI status and readiness polling.
|
|
2273
|
-
const client = new HarnessDriverClient({
|
|
2274
|
-
baseUrl: conn.url,
|
|
2275
|
-
apiKey: conn.api_key,
|
|
2276
|
-
requestTimeoutMs: 2000,
|
|
2277
|
-
});
|
|
2278
|
-
try {
|
|
2279
|
-
const status = await client.getStatus();
|
|
2280
|
-
const session = await client.getSession().catch(() => null);
|
|
2281
|
-
return { status, session };
|
|
2282
|
-
}
|
|
2283
|
-
catch {
|
|
2284
|
-
return null;
|
|
2285
|
-
}
|
|
2286
|
-
finally {
|
|
2287
|
-
client.disconnect();
|
|
2288
|
-
}
|
|
2289
|
-
}
|
|
2290
|
-
//# sourceMappingURL=broker-lifecycle.js.map
|