Repository navigation
Expand file tree
/
Copy pathdaemon-client-metadata.ts
More file actions
323 lines (290 loc) · 10.8 KB
/
Copy pathdaemon-client-metadata.ts
File metadata and controls
323 lines (290 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import fs from 'node:fs';
import { AppError } from '@agent-device/kernel/errors';
import { shellQuote } from '@agent-device/kernel/device-shell';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import {
isAgentDeviceDaemonProcess,
stopDaemonProcess,
type DaemonTerminationResult,
} from '../daemon-process.ts';
import type { DaemonCodeOrigin } from '@agent-device/host-kit/code-signature';
import {
resolveDaemonPaths,
type DaemonPaths,
type DaemonServerMode,
} from '../daemon-resolution.ts';
export type DaemonInfo = {
port?: number;
httpPort?: number;
transport?: DaemonServerMode;
token: string;
pid: number;
version?: string;
codeOrigin?: DaemonCodeOrigin;
codeSignature?: string;
processStartTime?: string;
/** ADR 0029: digest of the daemon policy the daemon enforces; absent when it has none. */
policyDigest?: string;
baseUrl?: string;
remoteInstanceId?: string;
remoteUpstreamInstanceId?: string;
};
type DaemonLockInfo = {
pid: number;
processStartTime?: string;
startedAt?: number;
};
export type DaemonMetadataState = {
hasInfo: boolean;
hasLock: boolean;
};
type DaemonStartupCleanupReason = 'start_error' | 'startup_timeout';
export type DaemonStartupCleanupResult = {
reason: DaemonStartupCleanupReason;
removedInfo: boolean;
removedLock: boolean;
stoppedInfoProcess: boolean;
stoppedLockProcess: boolean;
retainedInfoProcess?: boolean;
retainedLockProcess?: boolean;
error?: string;
};
const DAEMON_TAKEOVER_TERM_TIMEOUT_MS = 3000;
const DAEMON_TAKEOVER_KILL_TIMEOUT_MS = 1000;
export function readDaemonInfo(infoPath: string): DaemonInfo | null {
const data = readJsonFile(infoPath);
if (!data || typeof data !== 'object') return null;
const parsed = data as Partial<DaemonInfo>;
const token = readRequiredDaemonToken(parsed);
if (!token) return null;
const ports = readDaemonInfoPorts(parsed);
if (!ports) return null;
return {
token,
...ports,
transport: readDaemonInfoTransport(parsed.transport),
pid: readPositiveInteger(parsed.pid) ?? 0,
version: readOptionalString(parsed.version),
codeOrigin: readDaemonInfoCodeOrigin(parsed.codeOrigin),
codeSignature: readOptionalString(parsed.codeSignature),
processStartTime: readOptionalString(parsed.processStartTime),
policyDigest: readOptionalString(parsed.policyDigest),
};
}
function readRequiredDaemonToken(parsed: Partial<DaemonInfo>): string | null {
return typeof parsed.token === 'string' && parsed.token.length > 0 ? parsed.token : null;
}
function readDaemonInfoPorts(
parsed: Partial<DaemonInfo>,
): Pick<DaemonInfo, 'port' | 'httpPort'> | null {
const port = readPositiveInteger(parsed.port);
const httpPort = readPositiveInteger(parsed.httpPort);
if (port === undefined && httpPort === undefined) return null;
return { port, httpPort };
}
function readDaemonInfoCodeOrigin(value: unknown): DaemonInfo['codeOrigin'] {
return value === 'installed' || value === 'checkout' ? value : undefined;
}
function readDaemonInfoTransport(value: unknown): DaemonInfo['transport'] {
return value === 'socket' || value === 'http' || value === 'dual' ? value : undefined;
}
function readOptionalString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined;
}
function readPositiveInteger(value: unknown): number | undefined {
return Number.isInteger(value) && Number(value) > 0 ? Number(value) : undefined;
}
function readDaemonLockInfo(lockPath: string): DaemonLockInfo | null {
const data = readJsonFile(lockPath);
if (!data || typeof data !== 'object') return null;
const parsed = data as Partial<DaemonLockInfo>;
const hasPid = Number.isInteger(parsed.pid) && Number(parsed.pid) > 0;
if (!hasPid) {
return null;
}
return {
pid: Number(parsed.pid),
processStartTime:
typeof parsed.processStartTime === 'string' ? parsed.processStartTime : undefined,
startedAt: typeof parsed.startedAt === 'number' ? parsed.startedAt : undefined,
};
}
/**
* Whether a live daemon other than `pid` holds the startup lock: another client's daemon won the
* start, and the daemon at `pid` exited because it lost the lock.
*/
export function isDaemonLockHeldByAnotherDaemon(paths: DaemonPaths, pid: number): boolean {
const lockInfo = readDaemonLockInfo(paths.lockPath);
return (
lockInfo !== null &&
lockInfo.pid !== pid &&
isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime)
);
}
export function removeDaemonInfo(infoPath: string): void {
removeFileIfExists(infoPath);
}
export function removeDaemonLock(lockPath: string): void {
removeFileIfExists(lockPath);
}
export function cleanupStaleDaemonLockIfSafe(paths: DaemonPaths): void {
const state = getDaemonMetadataState(paths);
if (!state.hasLock || state.hasInfo) return;
const lockInfo = readDaemonLockInfo(paths.lockPath);
if (!lockInfo) {
removeDaemonLock(paths.lockPath);
return;
}
if (isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime)) {
return;
}
removeDaemonLock(paths.lockPath);
}
export async function cleanupFailedDaemonStartupMetadata(
paths: DaemonPaths,
reason: DaemonStartupCleanupReason,
options: { stopLiveProcesses?: boolean } = {},
): Promise<DaemonStartupCleanupResult> {
const stopLiveProcesses = options.stopLiveProcesses ?? true;
const result: DaemonStartupCleanupResult = {
reason,
removedInfo: false,
removedLock: false,
stoppedInfoProcess: false,
stoppedLockProcess: false,
};
try {
const infoExists = fs.existsSync(paths.infoPath);
const info = readDaemonInfo(paths.infoPath);
if (info) {
const liveInfoProcess = isAgentDeviceDaemonProcess(info.pid, info.processStartTime);
if (liveInfoProcess && !stopLiveProcesses) {
result.retainedInfoProcess = true;
} else {
if (liveInfoProcess) {
await stopDaemonProcessForTakeover(info);
result.stoppedInfoProcess = true;
}
removeDaemonInfo(paths.infoPath);
result.removedInfo = true;
}
} else if (infoExists) {
removeDaemonInfo(paths.infoPath);
result.removedInfo = true;
}
const lockExists = fs.existsSync(paths.lockPath);
const lockInfo = readDaemonLockInfo(paths.lockPath);
if (lockInfo) {
const liveLockProcess = isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime);
if (liveLockProcess && !stopLiveProcesses) {
result.retainedLockProcess = true;
} else {
if (liveLockProcess) {
const termination = await stopDaemonProcess(
{ pid: lockInfo.pid, startTime: lockInfo.processStartTime ?? null },
{
mode: 'graceful',
termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
},
);
requireDaemonExit(termination);
result.stoppedLockProcess = true;
}
removeDaemonLock(paths.lockPath);
result.removedLock = true;
}
} else if (lockExists) {
removeDaemonLock(paths.lockPath);
result.removedLock = true;
}
} catch (error) {
result.error = error instanceof Error ? error.message : String(error);
}
emitDiagnostic({
level: result.error ? 'warn' : 'info',
phase: 'daemon_startup_metadata_cleanup',
data: result,
});
return result;
}
export function getDaemonMetadataState(paths: DaemonPaths): DaemonMetadataState {
return {
hasInfo: fs.existsSync(paths.infoPath),
hasLock: fs.existsSync(paths.lockPath),
};
}
export async function recoverDaemonLockHolder(paths: DaemonPaths): Promise<boolean> {
const state = getDaemonMetadataState(paths);
if (!state.hasLock || state.hasInfo) return false;
const lockInfo = readDaemonLockInfo(paths.lockPath);
if (!lockInfo) {
removeDaemonLock(paths.lockPath);
return true;
}
if (!isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime)) {
removeDaemonLock(paths.lockPath);
return true;
}
return false;
}
export async function stopDaemonProcessForTakeover(
info: DaemonInfo,
): Promise<DaemonTerminationResult> {
const termination = await stopDaemonProcess(
{ pid: info.pid, startTime: info.processStartTime ?? null },
{
mode: 'graceful',
termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
},
);
requireDaemonExit(termination);
return termination;
}
function requireDaemonExit(termination: DaemonTerminationResult): void {
if (termination.status !== 'retained') return;
throw new AppError('COMMAND_FAILED', 'Daemon exit could not be confirmed.', {
reason: 'daemon_exit_unconfirmed',
termination,
});
}
export function isRemoteDaemon(info: DaemonInfo): boolean {
return typeof info.baseUrl === 'string' && info.baseUrl.length > 0;
}
export function resolveDaemonStartupHint(
state: { hasInfo: boolean; hasLock: boolean },
paths: Pick<DaemonPaths, 'infoPath' | 'lockPath'> = resolveDaemonPaths(
process.env.AGENT_DEVICE_STATE_DIR,
),
): string {
const cleanupCommand = buildDaemonMetadataCleanupCommand(paths);
if (state.hasLock && !state.hasInfo) {
return `agent-device attempted to clean stale daemon metadata automatically, but ${paths.lockPath} still exists without ${paths.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${cleanupCommand}`;
}
if (state.hasLock && state.hasInfo) {
return `agent-device attempted to clean stale daemon metadata automatically, but ${paths.infoPath} and ${paths.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${cleanupCommand}`;
}
if (state.hasInfo) {
return `agent-device did not observe reachable daemon metadata after retrying, and ${paths.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${cleanupCommand}`;
}
return `agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${cleanupCommand}`;
}
function buildDaemonMetadataCleanupCommand(paths: Pick<DaemonPaths, 'infoPath' | 'lockPath'>) {
return `rm -f ${shellQuote(paths.infoPath)} ${shellQuote(paths.lockPath)}`;
}
function readJsonFile(filePath: string): unknown | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown;
} catch {
return null;
}
}
function removeFileIfExists(filePath: string): void {
try {
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
} catch {
// Best-effort cleanup only.
}
}