@tonyclaw/agent-inspector 3.0.44 → 3.0.45
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/.output/cli.js +20743 -16945
- package/.output/nitro.json +1 -1
- package/.output/public/assets/{CompareDrawer-DQHjxFO6.js → CompareDrawer-B3_TLTJh.js} +1 -1
- package/.output/public/assets/{InspectorPet-D1A4505B.js → InspectorPet-Cpn6hv4P.js} +1 -1
- package/.output/public/assets/{ProxyViewerContainer-BhpIgfBi.js → ProxyViewerContainer-BEAhuGOJ.js} +27 -27
- package/.output/public/assets/{ReplayDialog-C5vmbecv.js → ReplayDialog-B3EKVdJk.js} +1 -1
- package/.output/public/assets/{RequestAnatomy-CPGNB8lk.js → RequestAnatomy-COOQjyUC.js} +1 -1
- package/.output/public/assets/{ResponseView-DUfrajCm.js → ResponseView-DBCjkwye.js} +1 -1
- package/.output/public/assets/{StreamingChunkSequence-nbeCQqOz.js → StreamingChunkSequence-CuXhDgMo.js} +1 -1
- package/.output/public/assets/{_sessionId-mw3aA8Bp.js → _sessionId-BJlM3nmt.js} +1 -1
- package/.output/public/assets/{_sessionId-CDhRgzf6.js → _sessionId-zbgYl7ZJ.js} +1 -1
- package/.output/public/assets/{index-B2eoeT-Z.js → index-BIK4bPTv.js} +1 -1
- package/.output/public/assets/{index-C6qZwYlR.js → index-BZo_8koU.js} +15 -15
- package/.output/public/assets/{index-CX7_rf7o.js → index-D2Qw6Ri2.js} +1 -1
- package/.output/public/assets/{index-BWjeqxbk.css → index-ZWschkCh.css} +1 -1
- package/.output/public/assets/{index-BfRhTvOd.js → index-xF_NY8Yb.js} +5 -5
- package/.output/public/assets/{json-viewer-BLmF1sOZ.js → json-viewer-B-Ao6pwW.js} +1 -1
- package/.output/public/assets/{jszip.min-C9rCFoU3.js → jszip.min-B_rfAUCe.js} +1 -1
- package/.output/server/_libs/modelcontextprotocol__core.mjs +25 -25
- package/.output/server/_libs/modelcontextprotocol__server.mjs +2 -2
- package/.output/server/_libs/zod.mjs +6 -6
- package/.output/server/{_sessionId-U54BAqdp.mjs → _sessionId-CJ99gZFV.mjs} +3 -1
- package/.output/server/{_sessionId-E_Dmopc-.mjs → _sessionId-DEjScBpK.mjs} +5 -3
- package/.output/server/_ssr/{CompareDrawer-CksatPed.mjs → CompareDrawer-DtOIMeQB.mjs} +4 -2
- package/.output/server/_ssr/{InspectorPet-DNc4GQ7z.mjs → InspectorPet-CXc4oCBQ.mjs} +3 -1
- package/.output/server/_ssr/{ProxyViewerContainer-B02Ey0p_.mjs → ProxyViewerContainer-DVPlwfkt.mjs} +52 -27
- package/.output/server/_ssr/{ReplayDialog-DdMvHJF1.mjs → ReplayDialog-BQEA95qC.mjs} +6 -4
- package/.output/server/_ssr/{RequestAnatomy--vh2Z8__.mjs → RequestAnatomy-BMyd8B7Q.mjs} +4 -2
- package/.output/server/_ssr/{ResponseView-Dhxc-cKC.mjs → ResponseView-qrTaEIM8.mjs} +4 -2
- package/.output/server/_ssr/{StreamingChunkSequence-BG0EQmaD.mjs → StreamingChunkSequence-BFTL8mIy.mjs} +5 -3
- package/.output/server/_ssr/{index-lcfulIXa.mjs → index-Bcj1Hcy4.mjs} +4 -2
- package/.output/server/_ssr/{index-D0At9nfd.mjs → index-DW-M7XUG.mjs} +3 -1
- package/.output/server/_ssr/index.mjs +4 -3
- package/.output/server/_ssr/{json-viewer-My1J1_5R.mjs → json-viewer-DiI0Yjsn.mjs} +4 -2
- package/.output/server/_ssr/publicBasePathContext-5264L3rX.mjs +148 -0
- package/.output/server/_ssr/{router-DWcUFPR3.mjs → router-BJ_ltLim.mjs} +2432 -475
- package/.output/server/_ssr/start-C6MjPjxp.mjs +57 -0
- package/.output/server/_tanstack-start-manifest_v-C6pXXX9R.mjs +4 -0
- package/.output/server/index.mjs +92 -92
- package/.output/workers/logFinalizer.worker.js +4 -0
- package/.output/workers/sessionWorkerEntry.js +4 -0
- package/README.md +221 -25
- package/docs/instance-control.openapi.yaml +306 -0
- package/package.json +4 -1
- package/src/cli/alias.ts +440 -0
- package/src/cli/instance.ts +1037 -0
- package/src/cli/instanceArgs.ts +266 -0
- package/src/cli/instanceControl.ts +183 -0
- package/src/cli/instanceModel.ts +275 -0
- package/src/cli/instanceRegistry.ts +740 -0
- package/src/cli/onboard.ts +123 -35
- package/src/cli/onboardTarget.ts +179 -0
- package/src/cli/templates/codex-skill-onboard.ts +76 -28
- package/src/cli/templates/skill-onboard.ts +93 -59
- package/src/cli.ts +154 -16
- package/src/components/ProxyViewer.tsx +13 -5
- package/src/components/providers/SettingsDialog.tsx +13 -8
- package/src/lib/basePath.ts +8 -2
- package/src/lib/codingAgentEndpoints.ts +16 -0
- package/src/lib/instanceContract.ts +220 -0
- package/src/lib/managedInstance.ts +104 -0
- package/src/lib/publicBasePathContext.ts +107 -0
- package/src/mcp/instanceHandlers.ts +149 -0
- package/src/mcp/loopback.ts +16 -5
- package/src/mcp/mode.ts +25 -0
- package/src/mcp/server.ts +258 -18
- package/src/mcp/toolHandlers.ts +2 -2
- package/src/proxy/identityProxy.ts +655 -36
- package/src/proxy/runtimeShutdown.ts +73 -1
- package/src/proxy/sessionInfo.ts +5 -4
- package/src/routes/api/-instances.ts +109 -0
- package/src/routes/api/instances.$name.connection.ts +12 -0
- package/src/routes/api/instances.$name.restart.ts +23 -0
- package/src/routes/api/instances.$name.start.ts +18 -0
- package/src/routes/api/instances.$name.stop.ts +23 -0
- package/src/routes/api/instances.$name.ts +12 -0
- package/src/routes/api/instances.ts +16 -0
- package/src/start.ts +10 -0
- package/.output/server/_ssr/start-HYkvq4Ni.mjs +0 -4
- package/.output/server/_tanstack-start-manifest_v-B2chR8ef.mjs +0 -4
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
type Dirent,
|
|
5
|
+
existsSync,
|
|
6
|
+
mkdirSync,
|
|
7
|
+
openSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
realpathSync,
|
|
11
|
+
renameSync,
|
|
12
|
+
rmSync,
|
|
13
|
+
statSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from "node:fs";
|
|
16
|
+
import { createServer } from "node:net";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { join, posix, win32 } from "node:path";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import {
|
|
21
|
+
ensurePrivateDirectorySync,
|
|
22
|
+
PRIVATE_FILE_MODE,
|
|
23
|
+
securePrivateFileSync,
|
|
24
|
+
} from "../proxy/privateDataPath";
|
|
25
|
+
import {
|
|
26
|
+
InstanceRecordSchema,
|
|
27
|
+
instanceRegistryError,
|
|
28
|
+
instanceRegistrySuccess,
|
|
29
|
+
type InstanceRecord,
|
|
30
|
+
type InstanceRegistryResult,
|
|
31
|
+
validateInstanceName,
|
|
32
|
+
} from "./instanceModel";
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
createInstanceRecord,
|
|
36
|
+
INSTANCE_OUTPUT_SCHEMA_VERSION,
|
|
37
|
+
INSTANCE_RECORD_SCHEMA_VERSION,
|
|
38
|
+
InstanceLaunchSchema,
|
|
39
|
+
InstanceRecordSchema,
|
|
40
|
+
instanceRegistryError,
|
|
41
|
+
instanceRegistrySuccess,
|
|
42
|
+
MAX_INSTANCE_NAME_LENGTH,
|
|
43
|
+
normalizeInstanceBasePath,
|
|
44
|
+
rotateInstanceLaunch,
|
|
45
|
+
toInstanceRecordOutput,
|
|
46
|
+
validateInstanceName,
|
|
47
|
+
} from "./instanceModel";
|
|
48
|
+
export type {
|
|
49
|
+
CreateInstanceRecordInput,
|
|
50
|
+
InstanceIdentityFactory,
|
|
51
|
+
InstanceLaunch,
|
|
52
|
+
InstanceRecord,
|
|
53
|
+
InstanceRecordOutput,
|
|
54
|
+
InstanceRegistryError,
|
|
55
|
+
InstanceRegistryErrorCode,
|
|
56
|
+
InstanceRegistryResult,
|
|
57
|
+
} from "./instanceModel";
|
|
58
|
+
|
|
59
|
+
export const AGENT_INSPECTOR_INSTANCES_DIR_ENV = "AGENT_INSPECTOR_INSTANCES_DIR";
|
|
60
|
+
export const DEFAULT_NAMED_INSTANCE_PUBLIC_PORT = 9530;
|
|
61
|
+
export const NAMED_INSTANCE_PORT_STEP = 3;
|
|
62
|
+
export const NAMED_INSTANCE_UPSTREAM_OFFSET = 2;
|
|
63
|
+
export const DEFAULT_INSTANCE_LOCK_TIMEOUT_MS = 10_000;
|
|
64
|
+
export const DEFAULT_INSTANCE_LOCK_STALE_MS = 30_000;
|
|
65
|
+
|
|
66
|
+
const INSTANCE_RECORD_FILE_NAME = "instance.json";
|
|
67
|
+
const ROOT_LOCK_DIRECTORY_NAME = ".allocation.lock";
|
|
68
|
+
const INSTANCE_LOCK_DIRECTORY_NAME = ".mutation.lock";
|
|
69
|
+
const LOCK_OWNER_FILE_NAME = "owner.json";
|
|
70
|
+
const DEFAULT_LOCK_RETRY_MS = 50;
|
|
71
|
+
|
|
72
|
+
type InstanceRootEnv = Readonly<Record<string, string | undefined>>;
|
|
73
|
+
|
|
74
|
+
export type InstancePaths = {
|
|
75
|
+
root: string;
|
|
76
|
+
instanceDir: string;
|
|
77
|
+
dataDir: string;
|
|
78
|
+
recordPath: string;
|
|
79
|
+
lockPath: string;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
export function getInstancesRoot(
|
|
83
|
+
env: InstanceRootEnv = process.env,
|
|
84
|
+
platform: typeof process.platform = process.platform,
|
|
85
|
+
): string {
|
|
86
|
+
const pathApi = platform === "win32" ? win32 : posix;
|
|
87
|
+
const explicitRoot = env[AGENT_INSPECTOR_INSTANCES_DIR_ENV];
|
|
88
|
+
if (explicitRoot !== undefined && explicitRoot.trim().length > 0) {
|
|
89
|
+
return pathApi.isAbsolute(explicitRoot) ? explicitRoot : pathApi.resolve(explicitRoot);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (platform === "win32") {
|
|
93
|
+
const localAppData = env["LOCALAPPDATA"];
|
|
94
|
+
if (localAppData !== undefined && localAppData.trim().length > 0) {
|
|
95
|
+
return win32.join(localAppData, "agent-inspector", "instances");
|
|
96
|
+
}
|
|
97
|
+
const userProfile = env["USERPROFILE"];
|
|
98
|
+
const fallback =
|
|
99
|
+
userProfile !== undefined && userProfile.trim().length > 0 ? userProfile : homedir();
|
|
100
|
+
return win32.join(fallback, ".agent-inspector", "instances");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const home = env["HOME"];
|
|
104
|
+
const base = home !== undefined && home.trim().length > 0 ? home : homedir();
|
|
105
|
+
return posix.join(base, ".agent-inspector", "instances");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function getInstancePaths(
|
|
109
|
+
root: string,
|
|
110
|
+
rawName: string,
|
|
111
|
+
): InstanceRegistryResult<InstancePaths> {
|
|
112
|
+
const name = validateInstanceName(rawName);
|
|
113
|
+
if (name.kind === "error") return name;
|
|
114
|
+
const instanceDir = join(root, name.value);
|
|
115
|
+
return instanceRegistrySuccess({
|
|
116
|
+
root,
|
|
117
|
+
instanceDir,
|
|
118
|
+
dataDir: join(instanceDir, "data"),
|
|
119
|
+
recordPath: join(instanceDir, INSTANCE_RECORD_FILE_NAME),
|
|
120
|
+
lockPath: join(instanceDir, INSTANCE_LOCK_DIRECTORY_NAME),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function ensureInstancesRoot(root = getInstancesRoot()): InstanceRegistryResult<string> {
|
|
125
|
+
return ensurePrivateDirectorySync(root)
|
|
126
|
+
? instanceRegistrySuccess(root)
|
|
127
|
+
: instanceRegistryError(
|
|
128
|
+
"registry_io",
|
|
129
|
+
`Cannot create or secure the private instance registry at ${root}.`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function nodeErrorCode(error: unknown): string | null {
|
|
134
|
+
if (typeof error !== "object" || error === null) return null;
|
|
135
|
+
const descriptor = Object.getOwnPropertyDescriptor(error, "code");
|
|
136
|
+
return typeof descriptor?.value === "string" ? descriptor.value : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function readRecordFile(recordPath: string): InstanceRegistryResult<InstanceRecord> {
|
|
140
|
+
let parsedJson: unknown;
|
|
141
|
+
try {
|
|
142
|
+
parsedJson = JSON.parse(readFileSync(recordPath, "utf8"));
|
|
143
|
+
} catch {
|
|
144
|
+
return instanceRegistryError(
|
|
145
|
+
"record_invalid",
|
|
146
|
+
`Instance record ${recordPath} is unreadable or is not valid JSON.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const parsed = InstanceRecordSchema.safeParse(parsedJson);
|
|
151
|
+
return parsed.success
|
|
152
|
+
? instanceRegistrySuccess(parsed.data)
|
|
153
|
+
: instanceRegistryError(
|
|
154
|
+
"record_invalid",
|
|
155
|
+
`Instance record ${recordPath} does not match schema version 1: ${parsed.error.issues[0]?.message ?? "invalid record"}.`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function readInstanceRecord(
|
|
160
|
+
root: string,
|
|
161
|
+
rawName: string,
|
|
162
|
+
): InstanceRegistryResult<InstanceRecord | null> {
|
|
163
|
+
const paths = getInstancePaths(root, rawName);
|
|
164
|
+
if (paths.kind === "error") return paths;
|
|
165
|
+
if (!existsSync(paths.value.recordPath)) return instanceRegistrySuccess(null);
|
|
166
|
+
return readRecordFile(paths.value.recordPath);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function listInstanceRecords(
|
|
170
|
+
root: string,
|
|
171
|
+
): InstanceRegistryResult<readonly InstanceRecord[]> {
|
|
172
|
+
if (!existsSync(root)) return instanceRegistrySuccess([]);
|
|
173
|
+
|
|
174
|
+
let entries: Dirent<string>[];
|
|
175
|
+
try {
|
|
176
|
+
entries = readdirSync(root, { withFileTypes: true });
|
|
177
|
+
} catch {
|
|
178
|
+
return instanceRegistryError("registry_io", `Cannot read the instance registry at ${root}.`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const records: InstanceRecord[] = [];
|
|
182
|
+
const names = new Set<string>();
|
|
183
|
+
for (const entry of entries) {
|
|
184
|
+
if (!entry.isDirectory()) continue;
|
|
185
|
+
const recordPath = join(root, entry.name, INSTANCE_RECORD_FILE_NAME);
|
|
186
|
+
if (!existsSync(recordPath)) continue;
|
|
187
|
+
const record = readRecordFile(recordPath);
|
|
188
|
+
if (record.kind === "error") return record;
|
|
189
|
+
const expectedName = validateInstanceName(entry.name);
|
|
190
|
+
if (
|
|
191
|
+
expectedName.kind === "error" ||
|
|
192
|
+
record.value.name !== expectedName.value ||
|
|
193
|
+
names.has(record.value.name)
|
|
194
|
+
) {
|
|
195
|
+
return instanceRegistryError(
|
|
196
|
+
"record_invalid",
|
|
197
|
+
`Instance directory ${entry.name} does not uniquely match its saved normalized name.`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
names.add(record.value.name);
|
|
201
|
+
records.push(record.value);
|
|
202
|
+
}
|
|
203
|
+
records.sort((left, right) => left.name.localeCompare(right.name));
|
|
204
|
+
return instanceRegistrySuccess(records);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function cleanupFile(path: string): void {
|
|
208
|
+
try {
|
|
209
|
+
rmSync(path, { force: true });
|
|
210
|
+
} catch {
|
|
211
|
+
// Best effort: a failed atomic write must not hide the original error.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function writeInstanceRecord(
|
|
216
|
+
root: string,
|
|
217
|
+
record: InstanceRecord,
|
|
218
|
+
): InstanceRegistryResult<InstanceRecord> {
|
|
219
|
+
const validated = InstanceRecordSchema.safeParse(record);
|
|
220
|
+
if (!validated.success) {
|
|
221
|
+
return instanceRegistryError(
|
|
222
|
+
"record_invalid",
|
|
223
|
+
`Cannot save instance record: ${validated.error.issues[0]?.message ?? "invalid record"}.`,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
const paths = getInstancePaths(root, validated.data.name);
|
|
227
|
+
if (paths.kind === "error") return paths;
|
|
228
|
+
const rootResult = ensureInstancesRoot(root);
|
|
229
|
+
if (rootResult.kind === "error") return rootResult;
|
|
230
|
+
if (!ensurePrivateDirectorySync(paths.value.instanceDir)) {
|
|
231
|
+
return instanceRegistryError(
|
|
232
|
+
"registry_io",
|
|
233
|
+
`Cannot create or secure the private directory for instance ${validated.data.name}.`,
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
if (!ensurePrivateDirectorySync(validated.data.dataDir)) {
|
|
237
|
+
return instanceRegistryError(
|
|
238
|
+
"registry_io",
|
|
239
|
+
`Cannot create or secure the data directory for instance ${validated.data.name}.`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const temporaryPath = join(
|
|
244
|
+
paths.value.instanceDir,
|
|
245
|
+
`.${INSTANCE_RECORD_FILE_NAME}.${String(process.pid)}.${randomUUID()}.tmp`,
|
|
246
|
+
);
|
|
247
|
+
let descriptor: number | null = null;
|
|
248
|
+
try {
|
|
249
|
+
descriptor = openSync(temporaryPath, "wx", PRIVATE_FILE_MODE);
|
|
250
|
+
writeFileSync(descriptor, `${JSON.stringify(validated.data, null, 2)}\n`, "utf8");
|
|
251
|
+
closeSync(descriptor);
|
|
252
|
+
descriptor = null;
|
|
253
|
+
if (!securePrivateFileSync(temporaryPath)) {
|
|
254
|
+
cleanupFile(temporaryPath);
|
|
255
|
+
return instanceRegistryError(
|
|
256
|
+
"registry_io",
|
|
257
|
+
`Cannot secure the saved record for instance ${validated.data.name}.`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
renameSync(temporaryPath, paths.value.recordPath);
|
|
261
|
+
return instanceRegistrySuccess(validated.data);
|
|
262
|
+
} catch {
|
|
263
|
+
if (descriptor !== null) {
|
|
264
|
+
try {
|
|
265
|
+
closeSync(descriptor);
|
|
266
|
+
} catch {
|
|
267
|
+
// The original write error remains the actionable failure.
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
cleanupFile(temporaryPath);
|
|
271
|
+
return instanceRegistryError(
|
|
272
|
+
"registry_io",
|
|
273
|
+
`Cannot atomically save the record for instance ${validated.data.name}.`,
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const InstanceLockOwnerSchema = z
|
|
279
|
+
.object({
|
|
280
|
+
schemaVersion: z.literal(1),
|
|
281
|
+
pid: z.number().int().positive(),
|
|
282
|
+
token: z.string().min(8),
|
|
283
|
+
createdAt: z.string().datetime(),
|
|
284
|
+
})
|
|
285
|
+
.strict();
|
|
286
|
+
|
|
287
|
+
type InstanceLockOwner = z.infer<typeof InstanceLockOwnerSchema>;
|
|
288
|
+
|
|
289
|
+
export type InstanceLockHandle = {
|
|
290
|
+
path: string;
|
|
291
|
+
release: () => InstanceRegistryResult<void>;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
export type InstanceLockOptions = {
|
|
295
|
+
timeoutMs?: number;
|
|
296
|
+
retryDelayMs?: number;
|
|
297
|
+
staleAfterMs?: number;
|
|
298
|
+
pid?: number;
|
|
299
|
+
now?: () => number;
|
|
300
|
+
sleep?: (milliseconds: number) => Promise<void>;
|
|
301
|
+
isProcessAlive?: (pid: number) => boolean;
|
|
302
|
+
createToken?: () => string;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
function defaultSleep(milliseconds: number): Promise<void> {
|
|
306
|
+
return new Promise((resolveSleep) => {
|
|
307
|
+
setTimeout(resolveSleep, milliseconds);
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function defaultIsProcessAlive(pid: number): boolean {
|
|
312
|
+
if (pid === process.pid) return true;
|
|
313
|
+
try {
|
|
314
|
+
process.kill(pid, 0);
|
|
315
|
+
return true;
|
|
316
|
+
} catch (error) {
|
|
317
|
+
return nodeErrorCode(error) !== "ESRCH";
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function readLockOwner(lockPath: string): InstanceLockOwner | null {
|
|
322
|
+
try {
|
|
323
|
+
const raw: unknown = JSON.parse(readFileSync(join(lockPath, LOCK_OWNER_FILE_NAME), "utf8"));
|
|
324
|
+
const parsed = InstanceLockOwnerSchema.safeParse(raw);
|
|
325
|
+
return parsed.success ? parsed.data : null;
|
|
326
|
+
} catch {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function lockCreatedAt(lockPath: string, owner: InstanceLockOwner | null): number | null {
|
|
332
|
+
if (owner !== null) return Date.parse(owner.createdAt);
|
|
333
|
+
try {
|
|
334
|
+
return statSync(lockPath).mtimeMs;
|
|
335
|
+
} catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function recoverStaleLock(
|
|
341
|
+
lockPath: string,
|
|
342
|
+
staleAfterMs: number,
|
|
343
|
+
now: number,
|
|
344
|
+
isProcessAlive: (pid: number) => boolean,
|
|
345
|
+
): boolean {
|
|
346
|
+
const owner = readLockOwner(lockPath);
|
|
347
|
+
const createdAt = lockCreatedAt(lockPath, owner);
|
|
348
|
+
if (createdAt === null || now - createdAt < staleAfterMs) return false;
|
|
349
|
+
if (owner !== null && isProcessAlive(owner.pid)) return false;
|
|
350
|
+
|
|
351
|
+
const recoveredPath = `${lockPath}.stale-${randomUUID()}`;
|
|
352
|
+
try {
|
|
353
|
+
renameSync(lockPath, recoveredPath);
|
|
354
|
+
rmSync(recoveredPath, { recursive: true, force: true });
|
|
355
|
+
return true;
|
|
356
|
+
} catch {
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function releaseDirectoryLock(lockPath: string, token: string): InstanceRegistryResult<void> {
|
|
362
|
+
if (!existsSync(lockPath)) return instanceRegistrySuccess(undefined);
|
|
363
|
+
const owner = readLockOwner(lockPath);
|
|
364
|
+
if (owner === null || owner.token !== token) {
|
|
365
|
+
return instanceRegistryError(
|
|
366
|
+
"lock_not_owned",
|
|
367
|
+
`Lifecycle lock ${lockPath} is no longer owned by this command.`,
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
372
|
+
return instanceRegistrySuccess(undefined);
|
|
373
|
+
} catch {
|
|
374
|
+
return instanceRegistryError("registry_io", `Cannot release lifecycle lock ${lockPath}.`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function acquireDirectoryLock(
|
|
379
|
+
lockPath: string,
|
|
380
|
+
options: InstanceLockOptions,
|
|
381
|
+
): Promise<InstanceRegistryResult<InstanceLockHandle>> {
|
|
382
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_INSTANCE_LOCK_TIMEOUT_MS;
|
|
383
|
+
const retryDelayMs = options.retryDelayMs ?? DEFAULT_LOCK_RETRY_MS;
|
|
384
|
+
const staleAfterMs = options.staleAfterMs ?? DEFAULT_INSTANCE_LOCK_STALE_MS;
|
|
385
|
+
const pid = options.pid ?? process.pid;
|
|
386
|
+
const now = options.now ?? Date.now;
|
|
387
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
388
|
+
const isProcessAlive = options.isProcessAlive ?? defaultIsProcessAlive;
|
|
389
|
+
const createToken = options.createToken ?? randomUUID;
|
|
390
|
+
const startedAt = now();
|
|
391
|
+
|
|
392
|
+
while (now() - startedAt <= timeoutMs) {
|
|
393
|
+
const token = createToken();
|
|
394
|
+
try {
|
|
395
|
+
mkdirSync(lockPath, { mode: 0o700 });
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (nodeErrorCode(error) !== "EEXIST") {
|
|
398
|
+
return instanceRegistryError("registry_io", `Cannot acquire lifecycle lock ${lockPath}.`);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (recoverStaleLock(lockPath, staleAfterMs, now(), isProcessAlive)) continue;
|
|
402
|
+
if (now() - startedAt >= timeoutMs) break;
|
|
403
|
+
await sleep(retryDelayMs);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
try {
|
|
408
|
+
if (!ensurePrivateDirectorySync(lockPath)) {
|
|
409
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
410
|
+
return instanceRegistryError("registry_io", `Cannot secure lifecycle lock ${lockPath}.`);
|
|
411
|
+
}
|
|
412
|
+
const owner: InstanceLockOwner = {
|
|
413
|
+
schemaVersion: 1,
|
|
414
|
+
pid,
|
|
415
|
+
token,
|
|
416
|
+
createdAt: new Date(now()).toISOString(),
|
|
417
|
+
};
|
|
418
|
+
const ownerPath = join(lockPath, LOCK_OWNER_FILE_NAME);
|
|
419
|
+
writeFileSync(ownerPath, `${JSON.stringify(owner)}\n`, {
|
|
420
|
+
encoding: "utf8",
|
|
421
|
+
flag: "wx",
|
|
422
|
+
mode: PRIVATE_FILE_MODE,
|
|
423
|
+
});
|
|
424
|
+
if (!securePrivateFileSync(ownerPath)) {
|
|
425
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
426
|
+
return instanceRegistryError("registry_io", `Cannot secure lifecycle lock ${lockPath}.`);
|
|
427
|
+
}
|
|
428
|
+
return instanceRegistrySuccess({
|
|
429
|
+
path: lockPath,
|
|
430
|
+
release: () => releaseDirectoryLock(lockPath, token),
|
|
431
|
+
});
|
|
432
|
+
} catch {
|
|
433
|
+
try {
|
|
434
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
435
|
+
} catch {
|
|
436
|
+
// The registry error remains actionable even if cleanup is deferred.
|
|
437
|
+
}
|
|
438
|
+
return instanceRegistryError("registry_io", `Cannot acquire lifecycle lock ${lockPath}.`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return instanceRegistryError(
|
|
443
|
+
"lock_timeout",
|
|
444
|
+
`Timed out waiting for lifecycle lock ${lockPath}; retry after the other command finishes.`,
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export async function acquireRegistryLock(
|
|
449
|
+
root: string,
|
|
450
|
+
options: InstanceLockOptions = {},
|
|
451
|
+
): Promise<InstanceRegistryResult<InstanceLockHandle>> {
|
|
452
|
+
const ensured = ensureInstancesRoot(root);
|
|
453
|
+
return ensured.kind === "error"
|
|
454
|
+
? ensured
|
|
455
|
+
: acquireDirectoryLock(join(root, ROOT_LOCK_DIRECTORY_NAME), options);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export async function acquireInstanceLock(
|
|
459
|
+
root: string,
|
|
460
|
+
rawName: string,
|
|
461
|
+
options: InstanceLockOptions = {},
|
|
462
|
+
): Promise<InstanceRegistryResult<InstanceLockHandle>> {
|
|
463
|
+
const paths = getInstancePaths(root, rawName);
|
|
464
|
+
if (paths.kind === "error") return paths;
|
|
465
|
+
const ensured = ensureInstancesRoot(root);
|
|
466
|
+
if (ensured.kind === "error") return ensured;
|
|
467
|
+
if (!ensurePrivateDirectorySync(paths.value.instanceDir)) {
|
|
468
|
+
return instanceRegistryError(
|
|
469
|
+
"registry_io",
|
|
470
|
+
`Cannot create or secure the private directory for instance ${rawName}.`,
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
return acquireDirectoryLock(paths.value.lockPath, options);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
type LockedOperation<T> = () => InstanceRegistryResult<T> | Promise<InstanceRegistryResult<T>>;
|
|
477
|
+
|
|
478
|
+
async function runWithLock<T>(
|
|
479
|
+
acquired: Promise<InstanceRegistryResult<InstanceLockHandle>>,
|
|
480
|
+
operation: LockedOperation<T>,
|
|
481
|
+
): Promise<InstanceRegistryResult<T>> {
|
|
482
|
+
const lock = await acquired;
|
|
483
|
+
if (lock.kind === "error") return lock;
|
|
484
|
+
|
|
485
|
+
let result: InstanceRegistryResult<T>;
|
|
486
|
+
try {
|
|
487
|
+
result = await operation();
|
|
488
|
+
} catch {
|
|
489
|
+
result = instanceRegistryError("registry_io", "The lifecycle registry operation failed.");
|
|
490
|
+
}
|
|
491
|
+
const released = lock.value.release();
|
|
492
|
+
return released.kind === "error" && result.kind === "success" ? released : result;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export function withRegistryLock<T>(
|
|
496
|
+
root: string,
|
|
497
|
+
operation: LockedOperation<T>,
|
|
498
|
+
options: InstanceLockOptions = {},
|
|
499
|
+
): Promise<InstanceRegistryResult<T>> {
|
|
500
|
+
return runWithLock(acquireRegistryLock(root, options), operation);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
export function withInstanceLock<T>(
|
|
504
|
+
root: string,
|
|
505
|
+
rawName: string,
|
|
506
|
+
operation: LockedOperation<T>,
|
|
507
|
+
options: InstanceLockOptions = {},
|
|
508
|
+
): Promise<InstanceRegistryResult<T>> {
|
|
509
|
+
return runWithLock(acquireInstanceLock(root, rawName, options), operation);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
type PathApi = typeof win32;
|
|
513
|
+
|
|
514
|
+
export type CanonicalDataDirectory = {
|
|
515
|
+
path: string;
|
|
516
|
+
comparisonKey: string;
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
export type CanonicalizeDataDirectoryOptions = {
|
|
520
|
+
platform?: typeof process.platform;
|
|
521
|
+
cwd?: string;
|
|
522
|
+
realpath?: (path: string) => string;
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
function pathApiForPlatform(platform: typeof process.platform): PathApi {
|
|
526
|
+
return platform === "win32" ? win32 : posix;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function resolveRealPathWithMissingTail(
|
|
530
|
+
absolutePath: string,
|
|
531
|
+
pathApi: PathApi,
|
|
532
|
+
realpath: (path: string) => string,
|
|
533
|
+
): string {
|
|
534
|
+
let current = absolutePath;
|
|
535
|
+
const missingSegments: string[] = [];
|
|
536
|
+
while (true) {
|
|
537
|
+
try {
|
|
538
|
+
return pathApi.join(realpath(current), ...missingSegments.reverse());
|
|
539
|
+
} catch {
|
|
540
|
+
const parent = pathApi.dirname(current);
|
|
541
|
+
if (parent === current) return absolutePath;
|
|
542
|
+
missingSegments.push(pathApi.basename(current));
|
|
543
|
+
current = parent;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function canonicalizeDataDirectory(
|
|
549
|
+
rawPath: string,
|
|
550
|
+
options: CanonicalizeDataDirectoryOptions = {},
|
|
551
|
+
): InstanceRegistryResult<CanonicalDataDirectory> {
|
|
552
|
+
if (rawPath.trim().length === 0 || rawPath.includes("\u0000")) {
|
|
553
|
+
return instanceRegistryError("data_dir_invalid", "Instance data directory cannot be empty.");
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const platform = options.platform ?? process.platform;
|
|
557
|
+
const pathApi = pathApiForPlatform(platform);
|
|
558
|
+
const cwd = options.cwd ?? process.cwd();
|
|
559
|
+
const absolutePath = pathApi.resolve(cwd, rawPath);
|
|
560
|
+
const resolvedPath = resolveRealPathWithMissingTail(
|
|
561
|
+
absolutePath,
|
|
562
|
+
pathApi,
|
|
563
|
+
options.realpath ?? realpathSync.native,
|
|
564
|
+
);
|
|
565
|
+
const normalizedPath = pathApi.normalize(resolvedPath);
|
|
566
|
+
const root = pathApi.parse(normalizedPath).root;
|
|
567
|
+
const withoutTrailingSeparator =
|
|
568
|
+
normalizedPath === root ? normalizedPath : normalizedPath.replace(/[\\/]+$/u, "");
|
|
569
|
+
return instanceRegistrySuccess({
|
|
570
|
+
path: withoutTrailingSeparator,
|
|
571
|
+
comparisonKey:
|
|
572
|
+
platform === "win32" ? withoutTrailingSeparator.toLowerCase() : withoutTrailingSeparator,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export function validateDataDirectoryAssignment(
|
|
577
|
+
rawPath: string,
|
|
578
|
+
records: readonly InstanceRecord[],
|
|
579
|
+
excludeName?: string,
|
|
580
|
+
options: CanonicalizeDataDirectoryOptions = {},
|
|
581
|
+
): InstanceRegistryResult<CanonicalDataDirectory> {
|
|
582
|
+
const candidate = canonicalizeDataDirectory(rawPath, options);
|
|
583
|
+
if (candidate.kind === "error") return candidate;
|
|
584
|
+
const normalizedExcludedName = excludeName?.toLowerCase();
|
|
585
|
+
|
|
586
|
+
for (const record of records) {
|
|
587
|
+
if (record.name === normalizedExcludedName) continue;
|
|
588
|
+
const registered = canonicalizeDataDirectory(record.dataDir, options);
|
|
589
|
+
if (registered.kind === "error") {
|
|
590
|
+
return instanceRegistryError(
|
|
591
|
+
"data_dir_conflict",
|
|
592
|
+
`Cannot safely compare the data directory registered to instance ${record.name}.`,
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
if (registered.value.comparisonKey === candidate.value.comparisonKey) {
|
|
596
|
+
return instanceRegistryError(
|
|
597
|
+
"data_dir_conflict",
|
|
598
|
+
`Data directory ${candidate.value.path} is already assigned to instance ${record.name}; named instances cannot share data.`,
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return candidate;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export type InstancePortPair = {
|
|
606
|
+
publicPort: number;
|
|
607
|
+
upstreamPort: number;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
export type PortAvailabilityCheck = (port: number, host: string) => boolean | Promise<boolean>;
|
|
611
|
+
|
|
612
|
+
export type PlanInstancePortsOptions = {
|
|
613
|
+
records: readonly InstanceRecord[];
|
|
614
|
+
requestedPublicPort?: number;
|
|
615
|
+
requestedUpstreamPort?: number;
|
|
616
|
+
excludeName?: string;
|
|
617
|
+
publicHost?: string;
|
|
618
|
+
isPortAvailable?: PortAvailabilityCheck;
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
function validPort(port: number): boolean {
|
|
622
|
+
return Number.isInteger(port) && port >= 1 && port <= 65_535;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function registeredPortOwner(
|
|
626
|
+
pair: InstancePortPair,
|
|
627
|
+
records: readonly InstanceRecord[],
|
|
628
|
+
excludeName: string | undefined,
|
|
629
|
+
): string | null {
|
|
630
|
+
const excluded = excludeName?.toLowerCase();
|
|
631
|
+
for (const record of records) {
|
|
632
|
+
if (record.name === excluded) continue;
|
|
633
|
+
const occupied = new Set([record.publicPort, record.upstreamPort]);
|
|
634
|
+
if (occupied.has(pair.publicPort) || occupied.has(pair.upstreamPort)) return record.name;
|
|
635
|
+
}
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
export function isPortAvailableByBinding(port: number, host: string): Promise<boolean> {
|
|
640
|
+
return new Promise((resolveAvailability) => {
|
|
641
|
+
const server = createServer();
|
|
642
|
+
let settled = false;
|
|
643
|
+
const finish = (available: boolean): void => {
|
|
644
|
+
if (settled) return;
|
|
645
|
+
settled = true;
|
|
646
|
+
server.removeAllListeners();
|
|
647
|
+
resolveAvailability(available);
|
|
648
|
+
};
|
|
649
|
+
server.once("error", () => finish(false));
|
|
650
|
+
server.once("listening", () => {
|
|
651
|
+
server.close((error) => finish(error === undefined));
|
|
652
|
+
});
|
|
653
|
+
server.unref();
|
|
654
|
+
try {
|
|
655
|
+
server.listen({ port, host, exclusive: true });
|
|
656
|
+
} catch {
|
|
657
|
+
finish(false);
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async function pairIsAvailable(
|
|
663
|
+
pair: InstancePortPair,
|
|
664
|
+
publicHost: string,
|
|
665
|
+
check: PortAvailabilityCheck,
|
|
666
|
+
): Promise<{ available: boolean; conflictingPort: number | null }> {
|
|
667
|
+
if (!(await check(pair.publicPort, publicHost))) {
|
|
668
|
+
return { available: false, conflictingPort: pair.publicPort };
|
|
669
|
+
}
|
|
670
|
+
if (!(await check(pair.upstreamPort, "127.0.0.1"))) {
|
|
671
|
+
return { available: false, conflictingPort: pair.upstreamPort };
|
|
672
|
+
}
|
|
673
|
+
return { available: true, conflictingPort: null };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export async function planInstancePorts(
|
|
677
|
+
options: PlanInstancePortsOptions,
|
|
678
|
+
): Promise<InstanceRegistryResult<InstancePortPair>> {
|
|
679
|
+
const check = options.isPortAvailable ?? isPortAvailableByBinding;
|
|
680
|
+
const publicHost = options.publicHost ?? "127.0.0.1";
|
|
681
|
+
|
|
682
|
+
if (options.requestedPublicPort === undefined && options.requestedUpstreamPort !== undefined) {
|
|
683
|
+
return instanceRegistryError(
|
|
684
|
+
"port_invalid",
|
|
685
|
+
"An explicit upstream port requires an explicit public port.",
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (options.requestedPublicPort !== undefined) {
|
|
690
|
+
const pair = {
|
|
691
|
+
publicPort: options.requestedPublicPort,
|
|
692
|
+
upstreamPort:
|
|
693
|
+
options.requestedUpstreamPort ??
|
|
694
|
+
options.requestedPublicPort + NAMED_INSTANCE_UPSTREAM_OFFSET,
|
|
695
|
+
};
|
|
696
|
+
if (
|
|
697
|
+
!validPort(pair.publicPort) ||
|
|
698
|
+
!validPort(pair.upstreamPort) ||
|
|
699
|
+
pair.publicPort === pair.upstreamPort
|
|
700
|
+
) {
|
|
701
|
+
return instanceRegistryError(
|
|
702
|
+
"port_invalid",
|
|
703
|
+
"Public and upstream ports must be different integers from 1 to 65535.",
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
const owner = registeredPortOwner(pair, options.records, options.excludeName);
|
|
707
|
+
if (owner !== null) {
|
|
708
|
+
return instanceRegistryError(
|
|
709
|
+
"port_conflict",
|
|
710
|
+
`Requested port pair ${String(pair.publicPort)}/${String(pair.upstreamPort)} overlaps instance ${owner}.`,
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
const availability = await pairIsAvailable(pair, publicHost, check);
|
|
714
|
+
return availability.available
|
|
715
|
+
? instanceRegistrySuccess(pair)
|
|
716
|
+
: instanceRegistryError(
|
|
717
|
+
"port_conflict",
|
|
718
|
+
`Port ${String(availability.conflictingPort)} already has a listener; no process was terminated.`,
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
for (
|
|
723
|
+
let publicPort = DEFAULT_NAMED_INSTANCE_PUBLIC_PORT;
|
|
724
|
+
publicPort + NAMED_INSTANCE_UPSTREAM_OFFSET <= 65_535;
|
|
725
|
+
publicPort += NAMED_INSTANCE_PORT_STEP
|
|
726
|
+
) {
|
|
727
|
+
const pair = {
|
|
728
|
+
publicPort,
|
|
729
|
+
upstreamPort: publicPort + NAMED_INSTANCE_UPSTREAM_OFFSET,
|
|
730
|
+
};
|
|
731
|
+
if (registeredPortOwner(pair, options.records, options.excludeName) !== null) continue;
|
|
732
|
+
const availability = await pairIsAvailable(pair, publicHost, check);
|
|
733
|
+
if (availability.available) return instanceRegistrySuccess(pair);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
return instanceRegistryError(
|
|
737
|
+
"port_exhausted",
|
|
738
|
+
`No available named-instance port pair was found from ${String(DEFAULT_NAMED_INSTANCE_PUBLIC_PORT)} through 65535.`,
|
|
739
|
+
);
|
|
740
|
+
}
|