@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,1037 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { resolve as resolvePath } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
AGENT_INSPECTOR_BASE_PATH_ENV,
|
|
5
|
+
appendBasePathToOrigin,
|
|
6
|
+
getConfiguredBasePath,
|
|
7
|
+
normalizeBasePath,
|
|
8
|
+
} from "../lib/basePath";
|
|
9
|
+
import {
|
|
10
|
+
type InstanceConnectionOutput,
|
|
11
|
+
type InstanceOperationOutcome,
|
|
12
|
+
type InstanceOperationOutput,
|
|
13
|
+
type InstanceStartRequest,
|
|
14
|
+
type InstanceStatusOutput,
|
|
15
|
+
INSTANCE_API_SCHEMA_VERSION,
|
|
16
|
+
isRetryableInstanceError,
|
|
17
|
+
} from "../lib/instanceContract";
|
|
18
|
+
import { AGENT_INSPECTOR_CLI_ENTRY_ENV, MANAGED_INSTANCE_ENV } from "../lib/managedInstance";
|
|
19
|
+
import { resolveDataDir } from "../proxy/dataDir";
|
|
20
|
+
import { openUrlCommand } from "../proxy/platformCommands";
|
|
21
|
+
import { type InstanceAction, instanceHelp, parseInstanceArgs } from "./instanceArgs";
|
|
22
|
+
import {
|
|
23
|
+
type ExpectedInstanceControlIdentity,
|
|
24
|
+
type InstanceControlFetch,
|
|
25
|
+
probeInstanceControl,
|
|
26
|
+
requestInstanceShutdown,
|
|
27
|
+
} from "./instanceControl";
|
|
28
|
+
import {
|
|
29
|
+
acquireInstanceLock,
|
|
30
|
+
acquireRegistryLock,
|
|
31
|
+
canonicalizeDataDirectory,
|
|
32
|
+
createInstanceRecord,
|
|
33
|
+
getInstancePaths,
|
|
34
|
+
getInstancesRoot,
|
|
35
|
+
instanceRegistrySuccess,
|
|
36
|
+
isPortAvailableByBinding,
|
|
37
|
+
listInstanceRecords,
|
|
38
|
+
planInstancePorts,
|
|
39
|
+
readInstanceRecord,
|
|
40
|
+
rotateInstanceLaunch,
|
|
41
|
+
type InstanceLockHandle,
|
|
42
|
+
type InstancePortPair,
|
|
43
|
+
type InstanceRecord,
|
|
44
|
+
type InstanceRegistryErrorCode,
|
|
45
|
+
type InstanceRegistryResult,
|
|
46
|
+
validateDataDirectoryAssignment,
|
|
47
|
+
validateInstanceName,
|
|
48
|
+
writeInstanceRecord,
|
|
49
|
+
InstanceRecordSchema,
|
|
50
|
+
type PortAvailabilityCheck,
|
|
51
|
+
} from "./instanceRegistry";
|
|
52
|
+
import { probeHostForBindHost, urlForHost } from "./networkHints";
|
|
53
|
+
|
|
54
|
+
const DEFAULT_INSTANCE_HOST = "127.0.0.1";
|
|
55
|
+
const DEFAULT_INSTANCE_CAPTURE_MODE = "simple";
|
|
56
|
+
const INSTANCE_READY_TIMEOUT_MS = 15_000;
|
|
57
|
+
const INSTANCE_STOP_TIMEOUT_MS = 20_000;
|
|
58
|
+
const INSTANCE_POLL_INTERVAL_MS = 200;
|
|
59
|
+
|
|
60
|
+
export type InstanceLifecycleErrorCode =
|
|
61
|
+
| InstanceRegistryErrorCode
|
|
62
|
+
| "argument_invalid"
|
|
63
|
+
| "config_mismatch"
|
|
64
|
+
| "identity_mismatch"
|
|
65
|
+
| "instance_not_found"
|
|
66
|
+
| "launch_failed"
|
|
67
|
+
| "launch_unavailable"
|
|
68
|
+
| "restart_failed_degraded"
|
|
69
|
+
| "restart_failed_rolled_back"
|
|
70
|
+
| "self_lifecycle_unsupported"
|
|
71
|
+
| "shutdown_failed";
|
|
72
|
+
|
|
73
|
+
export type InstanceLifecycleError = {
|
|
74
|
+
code: InstanceLifecycleErrorCode;
|
|
75
|
+
message: string;
|
|
76
|
+
retryable: boolean;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type InstanceLifecycleResult<T> =
|
|
80
|
+
| { kind: "success"; value: T }
|
|
81
|
+
| { kind: "error"; error: InstanceLifecycleError };
|
|
82
|
+
|
|
83
|
+
type InstanceLiveState =
|
|
84
|
+
| { state: "running"; supervisorPid: number }
|
|
85
|
+
| { state: "stopped"; supervisorPid: null }
|
|
86
|
+
| {
|
|
87
|
+
state: "conflict";
|
|
88
|
+
supervisorPid: null;
|
|
89
|
+
code: "identity_mismatch" | "port_conflict";
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type InstanceIo = {
|
|
93
|
+
stdout: (text: string) => void;
|
|
94
|
+
stderr: (text: string) => void;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export type InstanceLifecycleDependencies = {
|
|
98
|
+
root?: string;
|
|
99
|
+
cliEntry?: string;
|
|
100
|
+
fetchImpl?: InstanceControlFetch;
|
|
101
|
+
isPortAvailable?: PortAvailabilityCheck;
|
|
102
|
+
launch?: (record: InstanceRecord, open: boolean) => Promise<boolean>;
|
|
103
|
+
openUrl?: (url: string) => void;
|
|
104
|
+
sleep?: (milliseconds: number) => Promise<void>;
|
|
105
|
+
readyTimeoutMs?: number;
|
|
106
|
+
stopTimeoutMs?: number;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const processIo: InstanceIo = {
|
|
110
|
+
stdout: (text) => process.stdout.write(text),
|
|
111
|
+
stderr: (text) => process.stderr.write(text),
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
function success<T>(value: T): InstanceLifecycleResult<T> {
|
|
115
|
+
return { kind: "success", value };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function failure<T>(code: InstanceLifecycleErrorCode, message: string): InstanceLifecycleResult<T> {
|
|
119
|
+
return {
|
|
120
|
+
kind: "error",
|
|
121
|
+
error: { code, message, retryable: isRetryableInstanceError(code) },
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function fromRegistry<T>(result: InstanceRegistryResult<T>): InstanceLifecycleResult<T> {
|
|
126
|
+
return result.kind === "success"
|
|
127
|
+
? success(result.value)
|
|
128
|
+
: failure(result.error.code, result.error.message);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function sleep(milliseconds: number): Promise<void> {
|
|
132
|
+
return new Promise((resolveSleep) => setTimeout(resolveSleep, milliseconds));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function displayBasePath(basePath: string): string {
|
|
136
|
+
return basePath.length === 0 ? "/" : basePath;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function recordUrls(record: InstanceRecord): InstanceStatusOutput["urls"] {
|
|
140
|
+
const origin = urlForHost(record.publicPort, record.host);
|
|
141
|
+
return {
|
|
142
|
+
ui: appendBasePathToOrigin(origin, "/", record.basePath),
|
|
143
|
+
api: appendBasePathToOrigin(origin, "/api", record.basePath),
|
|
144
|
+
health: appendBasePathToOrigin(origin, "/api/health", record.basePath),
|
|
145
|
+
proxy: appendBasePathToOrigin(origin, "/proxy", record.basePath),
|
|
146
|
+
openai: appendBasePathToOrigin(origin, "/proxy/v1", record.basePath),
|
|
147
|
+
mcp: appendBasePathToOrigin(origin, "/api/mcp", record.basePath),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function statusOutput(
|
|
152
|
+
record: InstanceRecord,
|
|
153
|
+
live: InstanceLiveState,
|
|
154
|
+
checkedAt = new Date(),
|
|
155
|
+
): InstanceStatusOutput {
|
|
156
|
+
return {
|
|
157
|
+
schemaVersion: INSTANCE_API_SCHEMA_VERSION,
|
|
158
|
+
name: record.name,
|
|
159
|
+
instanceId: record.instanceId,
|
|
160
|
+
state: live.state,
|
|
161
|
+
stateReason: live.state === "conflict" ? live.code : null,
|
|
162
|
+
checkedAt: checkedAt.toISOString(),
|
|
163
|
+
createdAt: record.createdAt,
|
|
164
|
+
updatedAt: record.updatedAt,
|
|
165
|
+
launch: {
|
|
166
|
+
launchId: record.launch.launchId,
|
|
167
|
+
startedAt: record.launch.startedAt,
|
|
168
|
+
},
|
|
169
|
+
host: record.host,
|
|
170
|
+
publicPort: record.publicPort,
|
|
171
|
+
upstreamPort: record.upstreamPort,
|
|
172
|
+
basePath: displayBasePath(record.basePath),
|
|
173
|
+
captureMode: record.captureMode,
|
|
174
|
+
dataDir: record.dataDir,
|
|
175
|
+
supervisorPid: live.supervisorPid,
|
|
176
|
+
urls: recordUrls(record),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function operationOutput(
|
|
181
|
+
operation: InstanceOperationOutput["operation"],
|
|
182
|
+
outcome: InstanceOperationOutcome,
|
|
183
|
+
instance: InstanceStatusOutput,
|
|
184
|
+
): InstanceOperationOutput {
|
|
185
|
+
return {
|
|
186
|
+
schemaVersion: INSTANCE_API_SCHEMA_VERSION,
|
|
187
|
+
operation,
|
|
188
|
+
outcome,
|
|
189
|
+
instance,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function connectionOutput(instance: InstanceStatusOutput): InstanceConnectionOutput {
|
|
194
|
+
const serverName = `agent-inspector-${instance.name}`;
|
|
195
|
+
return {
|
|
196
|
+
schemaVersion: INSTANCE_API_SCHEMA_VERSION,
|
|
197
|
+
instance,
|
|
198
|
+
baseUrl: instance.urls.ui,
|
|
199
|
+
endpoints: instance.urls,
|
|
200
|
+
environment: {
|
|
201
|
+
ANTHROPIC_BASE_URL: instance.urls.proxy,
|
|
202
|
+
LLM_BASE_URL: instance.urls.proxy,
|
|
203
|
+
OPENAI_BASE_URL: instance.urls.openai,
|
|
204
|
+
AGENT_INSPECTOR_MCP_URL: instance.urls.mcp,
|
|
205
|
+
},
|
|
206
|
+
mcp: {
|
|
207
|
+
serverName,
|
|
208
|
+
transport: "streamable-http",
|
|
209
|
+
url: instance.urls.mcp,
|
|
210
|
+
},
|
|
211
|
+
codex: {
|
|
212
|
+
providerName: serverName,
|
|
213
|
+
baseUrl: instance.urls.openai,
|
|
214
|
+
wireApi: "responses",
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function expectedIdentity(record: InstanceRecord): ExpectedInstanceControlIdentity {
|
|
220
|
+
return {
|
|
221
|
+
instanceId: record.instanceId,
|
|
222
|
+
launchId: record.launch.launchId,
|
|
223
|
+
controlToken: record.launch.controlToken,
|
|
224
|
+
host: probeHostForBindHost(record.host),
|
|
225
|
+
publicPort: record.publicPort,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function classifyRecord(
|
|
230
|
+
record: InstanceRecord,
|
|
231
|
+
deps: InstanceLifecycleDependencies,
|
|
232
|
+
): Promise<InstanceLiveState> {
|
|
233
|
+
const probe = await probeInstanceControl(expectedIdentity(record), deps.fetchImpl);
|
|
234
|
+
if (probe.kind === "running") {
|
|
235
|
+
return { state: "running", supervisorPid: probe.identity.supervisorPid };
|
|
236
|
+
}
|
|
237
|
+
if (probe.kind === "identity-mismatch" || probe.kind === "invalid-response") {
|
|
238
|
+
return { state: "conflict", supervisorPid: null, code: "identity_mismatch" };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const check = deps.isPortAvailable ?? isPortAvailableByBinding;
|
|
242
|
+
const publicAvailable = await check(record.publicPort, record.host);
|
|
243
|
+
const upstreamAvailable = await check(record.upstreamPort, DEFAULT_INSTANCE_HOST);
|
|
244
|
+
return publicAvailable && upstreamAvailable
|
|
245
|
+
? { state: "stopped", supervisorPid: null }
|
|
246
|
+
: { state: "conflict", supervisorPid: null, code: "port_conflict" };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function waitForProcess(child: ChildProcess): Promise<number> {
|
|
250
|
+
return new Promise((resolveExit) => {
|
|
251
|
+
let settled = false;
|
|
252
|
+
const finish = (code: number): void => {
|
|
253
|
+
if (settled) return;
|
|
254
|
+
settled = true;
|
|
255
|
+
resolveExit(code);
|
|
256
|
+
};
|
|
257
|
+
child.once("exit", (code) => finish(code ?? 1));
|
|
258
|
+
child.once("error", () => finish(1));
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function defaultOpenUrl(targetUrl: string): void {
|
|
263
|
+
const command = openUrlCommand(targetUrl);
|
|
264
|
+
if (command === null) return;
|
|
265
|
+
const child = spawn(command.command, command.args, {
|
|
266
|
+
stdio: "ignore",
|
|
267
|
+
detached: true,
|
|
268
|
+
windowsHide: true,
|
|
269
|
+
});
|
|
270
|
+
child.once("error", () => undefined);
|
|
271
|
+
child.unref();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function launchArgs(record: InstanceRecord, open: boolean): string[] {
|
|
275
|
+
const args = [
|
|
276
|
+
"--background",
|
|
277
|
+
"--no-open",
|
|
278
|
+
"--port",
|
|
279
|
+
String(record.publicPort),
|
|
280
|
+
"--host",
|
|
281
|
+
record.host,
|
|
282
|
+
"--mode",
|
|
283
|
+
record.captureMode,
|
|
284
|
+
];
|
|
285
|
+
if (open) args.push("--open");
|
|
286
|
+
return args;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function defaultLaunch(
|
|
290
|
+
record: InstanceRecord,
|
|
291
|
+
open: boolean,
|
|
292
|
+
cliEntry: string,
|
|
293
|
+
): Promise<boolean> {
|
|
294
|
+
const child = spawn(process.execPath, [cliEntry, ...launchArgs(record, open)], {
|
|
295
|
+
stdio: "ignore",
|
|
296
|
+
windowsHide: true,
|
|
297
|
+
env: {
|
|
298
|
+
...process.env,
|
|
299
|
+
[AGENT_INSPECTOR_CLI_ENTRY_ENV]: cliEntry,
|
|
300
|
+
AGENT_INSPECTOR_DATA_DIR: record.dataDir,
|
|
301
|
+
[AGENT_INSPECTOR_BASE_PATH_ENV]: displayBasePath(record.basePath),
|
|
302
|
+
[MANAGED_INSTANCE_ENV.name]: record.name,
|
|
303
|
+
[MANAGED_INSTANCE_ENV.instanceId]: record.instanceId,
|
|
304
|
+
[MANAGED_INSTANCE_ENV.launchId]: record.launch.launchId,
|
|
305
|
+
[MANAGED_INSTANCE_ENV.controlToken]: record.launch.controlToken,
|
|
306
|
+
[MANAGED_INSTANCE_ENV.startedAt]: record.launch.startedAt,
|
|
307
|
+
[MANAGED_INSTANCE_ENV.upstreamPort]: String(record.upstreamPort),
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
return (await waitForProcess(child)) === 0;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function launchRecord(
|
|
314
|
+
record: InstanceRecord,
|
|
315
|
+
open: boolean,
|
|
316
|
+
deps: InstanceLifecycleDependencies,
|
|
317
|
+
): Promise<InstanceLifecycleResult<InstanceLiveState>> {
|
|
318
|
+
const cliEntry = deps.cliEntry ?? process.env[AGENT_INSPECTOR_CLI_ENTRY_ENV] ?? process.argv[1];
|
|
319
|
+
if (deps.launch === undefined && (cliEntry === undefined || cliEntry.length === 0)) {
|
|
320
|
+
return failure("launch_unavailable", "Cannot resolve the packaged Agent Inspector CLI entry.");
|
|
321
|
+
}
|
|
322
|
+
const launched =
|
|
323
|
+
deps.launch === undefined
|
|
324
|
+
? await defaultLaunch(record, open, cliEntry ?? "")
|
|
325
|
+
: await deps.launch(record, open);
|
|
326
|
+
if (!launched) {
|
|
327
|
+
return failure(
|
|
328
|
+
"launch_failed",
|
|
329
|
+
`Instance ${record.name} did not become ready; its saved configuration is retained for retry.`,
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const wait = deps.sleep ?? sleep;
|
|
334
|
+
const deadline = Date.now() + (deps.readyTimeoutMs ?? INSTANCE_READY_TIMEOUT_MS);
|
|
335
|
+
while (Date.now() <= deadline) {
|
|
336
|
+
const live = await classifyRecord(record, deps);
|
|
337
|
+
if (live.state === "running") return success(live);
|
|
338
|
+
if (live.state === "conflict") {
|
|
339
|
+
return failure(
|
|
340
|
+
live.code,
|
|
341
|
+
`Instance ${record.name} launch identity does not own its saved port pair; no process was terminated.`,
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
await wait(INSTANCE_POLL_INTERVAL_MS);
|
|
345
|
+
}
|
|
346
|
+
return failure(
|
|
347
|
+
"launch_failed",
|
|
348
|
+
`Instance ${record.name} launch timed out; its saved configuration is retained for retry.`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function waitForPortsToClose(
|
|
353
|
+
record: InstanceRecord,
|
|
354
|
+
deps: InstanceLifecycleDependencies,
|
|
355
|
+
): Promise<boolean> {
|
|
356
|
+
const check = deps.isPortAvailable ?? isPortAvailableByBinding;
|
|
357
|
+
const wait = deps.sleep ?? sleep;
|
|
358
|
+
const deadline = Date.now() + (deps.stopTimeoutMs ?? INSTANCE_STOP_TIMEOUT_MS);
|
|
359
|
+
while (Date.now() <= deadline) {
|
|
360
|
+
const publicAvailable = await check(record.publicPort, record.host);
|
|
361
|
+
const upstreamAvailable = await check(record.upstreamPort, DEFAULT_INSTANCE_HOST);
|
|
362
|
+
if (publicAvailable && upstreamAvailable) return true;
|
|
363
|
+
await wait(INSTANCE_POLL_INTERVAL_MS);
|
|
364
|
+
}
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
type StoppedRecord = {
|
|
369
|
+
live: Extract<InstanceLiveState, { state: "stopped" }>;
|
|
370
|
+
outcome: "stopped" | "already_stopped";
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
async function stopRecord(
|
|
374
|
+
record: InstanceRecord,
|
|
375
|
+
deps: InstanceLifecycleDependencies,
|
|
376
|
+
): Promise<InstanceLifecycleResult<StoppedRecord>> {
|
|
377
|
+
const live = await classifyRecord(record, deps);
|
|
378
|
+
if (live.state === "stopped") return success({ live, outcome: "already_stopped" });
|
|
379
|
+
if (live.state === "conflict") {
|
|
380
|
+
return failure(
|
|
381
|
+
live.code,
|
|
382
|
+
`Instance ${record.name} does not own its saved port pair; refusing to stop another process.`,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
const requested = await requestInstanceShutdown(expectedIdentity(record), deps.fetchImpl);
|
|
386
|
+
if (requested.kind === "identity-mismatch") {
|
|
387
|
+
return failure(
|
|
388
|
+
"identity_mismatch",
|
|
389
|
+
`Instance ${record.name} changed identity before shutdown; no process was terminated.`,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
if (requested.kind !== "accepted") {
|
|
393
|
+
return failure("shutdown_failed", `Instance ${record.name} rejected the shutdown request.`);
|
|
394
|
+
}
|
|
395
|
+
return (await waitForPortsToClose(record, deps))
|
|
396
|
+
? success({
|
|
397
|
+
live: { state: "stopped", supervisorPid: null },
|
|
398
|
+
outcome: "stopped",
|
|
399
|
+
})
|
|
400
|
+
: failure(
|
|
401
|
+
"shutdown_failed",
|
|
402
|
+
`Instance ${record.name} did not stop before the shutdown deadline.`,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
type AcquiredLocks = {
|
|
407
|
+
registry: InstanceLockHandle | null;
|
|
408
|
+
instance: InstanceLockHandle;
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
async function acquireLocks(
|
|
412
|
+
root: string,
|
|
413
|
+
name: string,
|
|
414
|
+
includeRegistry: boolean,
|
|
415
|
+
): Promise<InstanceLifecycleResult<AcquiredLocks>> {
|
|
416
|
+
const registryResult = includeRegistry ? await acquireRegistryLock(root) : null;
|
|
417
|
+
if (registryResult !== null && registryResult.kind === "error") {
|
|
418
|
+
return fromRegistry(registryResult);
|
|
419
|
+
}
|
|
420
|
+
const registry = registryResult?.kind === "success" ? registryResult.value : null;
|
|
421
|
+
const instanceResult = await acquireInstanceLock(root, name);
|
|
422
|
+
if (instanceResult.kind === "error") {
|
|
423
|
+
registry?.release();
|
|
424
|
+
return fromRegistry(instanceResult);
|
|
425
|
+
}
|
|
426
|
+
return success({ registry, instance: instanceResult.value });
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function releaseLocks(locks: AcquiredLocks): InstanceLifecycleResult<void> {
|
|
430
|
+
const instanceReleased = locks.instance.release();
|
|
431
|
+
const registryReleased = locks.registry?.release() ?? instanceRegistrySuccess(undefined);
|
|
432
|
+
if (instanceReleased.kind === "error") return fromRegistry(instanceReleased);
|
|
433
|
+
return fromRegistry(registryReleased);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function withLocks<T>(
|
|
437
|
+
root: string,
|
|
438
|
+
name: string,
|
|
439
|
+
includeRegistry: boolean,
|
|
440
|
+
operation: () => Promise<InstanceLifecycleResult<T>>,
|
|
441
|
+
): Promise<InstanceLifecycleResult<T>> {
|
|
442
|
+
const locks = await acquireLocks(root, name, includeRegistry);
|
|
443
|
+
if (locks.kind === "error") return locks;
|
|
444
|
+
let result: InstanceLifecycleResult<T>;
|
|
445
|
+
try {
|
|
446
|
+
result = await operation();
|
|
447
|
+
} catch {
|
|
448
|
+
result = failure("registry_io", "The named-instance lifecycle operation failed.");
|
|
449
|
+
}
|
|
450
|
+
const released = releaseLocks(locks.value);
|
|
451
|
+
return result.kind === "success" && released.kind === "error" ? released : result;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function readRequiredRecord(root: string, name: string): InstanceLifecycleResult<InstanceRecord> {
|
|
455
|
+
const read = readInstanceRecord(root, name);
|
|
456
|
+
if (read.kind === "error") return fromRegistry(read);
|
|
457
|
+
return read.value === null
|
|
458
|
+
? failure("instance_not_found", `Named instance ${name} does not exist.`)
|
|
459
|
+
: success(read.value);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function overridesDiffer(
|
|
463
|
+
record: InstanceRecord,
|
|
464
|
+
action: Extract<InstanceAction, { kind: "start" | "restart" }>,
|
|
465
|
+
): boolean {
|
|
466
|
+
const { overrides } = action;
|
|
467
|
+
if (overrides.port !== null && overrides.port !== record.publicPort) return true;
|
|
468
|
+
if (overrides.basePath !== null && overrides.basePath !== record.basePath) return true;
|
|
469
|
+
if (overrides.host !== null && overrides.host !== record.host) return true;
|
|
470
|
+
if (overrides.captureMode !== null && overrides.captureMode !== record.captureMode) return true;
|
|
471
|
+
if (overrides.dataDir !== null) {
|
|
472
|
+
const requested = canonicalizeDataDirectory(overrides.dataDir);
|
|
473
|
+
const saved = canonicalizeDataDirectory(record.dataDir);
|
|
474
|
+
if (
|
|
475
|
+
requested.kind === "error" ||
|
|
476
|
+
saved.kind === "error" ||
|
|
477
|
+
requested.value.comparisonKey !== saved.value.comparisonKey
|
|
478
|
+
) {
|
|
479
|
+
return true;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function updatedRecord(
|
|
486
|
+
record: InstanceRecord,
|
|
487
|
+
action: Extract<InstanceAction, { kind: "restart" }>,
|
|
488
|
+
pair: InstancePortPair,
|
|
489
|
+
dataDir: string,
|
|
490
|
+
): InstanceLifecycleResult<InstanceRecord> {
|
|
491
|
+
const candidate: unknown = {
|
|
492
|
+
...record,
|
|
493
|
+
host: action.overrides.host ?? record.host,
|
|
494
|
+
publicPort: pair.publicPort,
|
|
495
|
+
upstreamPort: pair.upstreamPort,
|
|
496
|
+
basePath: action.overrides.basePath ?? record.basePath,
|
|
497
|
+
captureMode: action.overrides.captureMode ?? record.captureMode,
|
|
498
|
+
dataDir,
|
|
499
|
+
};
|
|
500
|
+
const parsed = InstanceRecordSchema.safeParse(candidate);
|
|
501
|
+
if (!parsed.success) {
|
|
502
|
+
return failure(
|
|
503
|
+
"record_invalid",
|
|
504
|
+
`Cannot update instance ${record.name}: ${parsed.error.issues[0]?.message ?? "invalid configuration"}.`,
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
return fromRegistry(rotateInstanceLaunch(parsed.data));
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function saveRecord(root: string, record: InstanceRecord): InstanceLifecycleResult<InstanceRecord> {
|
|
511
|
+
return fromRegistry(writeInstanceRecord(root, record));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function validateInstanceDataDirectory(
|
|
515
|
+
rawPath: string,
|
|
516
|
+
records: readonly InstanceRecord[],
|
|
517
|
+
excludeName?: string,
|
|
518
|
+
): InstanceLifecycleResult<string> {
|
|
519
|
+
const assigned = validateDataDirectoryAssignment(rawPath, records, excludeName);
|
|
520
|
+
if (assigned.kind === "error") return fromRegistry(assigned);
|
|
521
|
+
const defaultDirectory = canonicalizeDataDirectory(resolveDataDir(() => false));
|
|
522
|
+
if (defaultDirectory.kind === "error") return fromRegistry(defaultDirectory);
|
|
523
|
+
if (assigned.value.comparisonKey === defaultDirectory.value.comparisonKey) {
|
|
524
|
+
return failure(
|
|
525
|
+
"data_dir_conflict",
|
|
526
|
+
`Data directory ${assigned.value.path} belongs to the unmanaged default instance; named instances cannot share it.`,
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
return success(assigned.value.path);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function createNewRecord(
|
|
533
|
+
root: string,
|
|
534
|
+
action: Extract<InstanceAction, { kind: "start" }>,
|
|
535
|
+
deps: InstanceLifecycleDependencies,
|
|
536
|
+
): Promise<InstanceLifecycleResult<InstanceRecord>> {
|
|
537
|
+
const recordsResult = listInstanceRecords(root);
|
|
538
|
+
if (recordsResult.kind === "error") return fromRegistry(recordsResult);
|
|
539
|
+
const pathsResult = getInstancePaths(root, action.name);
|
|
540
|
+
if (pathsResult.kind === "error") return fromRegistry(pathsResult);
|
|
541
|
+
const host = action.overrides.host ?? DEFAULT_INSTANCE_HOST;
|
|
542
|
+
const pairResult = await planInstancePorts({
|
|
543
|
+
records: recordsResult.value,
|
|
544
|
+
requestedPublicPort: action.overrides.port ?? undefined,
|
|
545
|
+
publicHost: host,
|
|
546
|
+
isPortAvailable: deps.isPortAvailable,
|
|
547
|
+
});
|
|
548
|
+
if (pairResult.kind === "error") return fromRegistry(pairResult);
|
|
549
|
+
const requestedDataDir = action.overrides.dataDir ?? pathsResult.value.dataDir;
|
|
550
|
+
const dataDirResult = validateInstanceDataDirectory(requestedDataDir, recordsResult.value);
|
|
551
|
+
if (dataDirResult.kind === "error") return dataDirResult;
|
|
552
|
+
const created = createInstanceRecord({
|
|
553
|
+
name: action.name,
|
|
554
|
+
host,
|
|
555
|
+
publicPort: pairResult.value.publicPort,
|
|
556
|
+
upstreamPort: pairResult.value.upstreamPort,
|
|
557
|
+
basePath: action.overrides.basePath ?? getConfiguredBasePath(process.env),
|
|
558
|
+
captureMode: action.overrides.captureMode ?? DEFAULT_INSTANCE_CAPTURE_MODE,
|
|
559
|
+
dataDir: dataDirResult.value,
|
|
560
|
+
});
|
|
561
|
+
return created.kind === "error" ? fromRegistry(created) : saveRecord(root, created.value);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
async function prepareStoppedStart(
|
|
565
|
+
root: string,
|
|
566
|
+
record: InstanceRecord,
|
|
567
|
+
deps: InstanceLifecycleDependencies,
|
|
568
|
+
): Promise<InstanceLifecycleResult<InstanceRecord>> {
|
|
569
|
+
const records = listInstanceRecords(root);
|
|
570
|
+
if (records.kind === "error") return fromRegistry(records);
|
|
571
|
+
const pair = await planInstancePorts({
|
|
572
|
+
records: records.value,
|
|
573
|
+
requestedPublicPort: record.publicPort,
|
|
574
|
+
requestedUpstreamPort: record.upstreamPort,
|
|
575
|
+
excludeName: record.name,
|
|
576
|
+
publicHost: record.host,
|
|
577
|
+
isPortAvailable: deps.isPortAvailable,
|
|
578
|
+
});
|
|
579
|
+
if (pair.kind === "error") return fromRegistry(pair);
|
|
580
|
+
const dataDir = validateInstanceDataDirectory(record.dataDir, records.value, record.name);
|
|
581
|
+
if (dataDir.kind === "error") return dataDir;
|
|
582
|
+
const rotated = rotateInstanceLaunch({ ...record, dataDir: dataDir.value });
|
|
583
|
+
return rotated.kind === "error" ? fromRegistry(rotated) : saveRecord(root, rotated.value);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async function startAction(
|
|
587
|
+
root: string,
|
|
588
|
+
action: Extract<InstanceAction, { kind: "start" }>,
|
|
589
|
+
deps: InstanceLifecycleDependencies,
|
|
590
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
591
|
+
return withLocks(root, action.name, true, async () => {
|
|
592
|
+
const read = readInstanceRecord(root, action.name);
|
|
593
|
+
if (read.kind === "error") return fromRegistry(read);
|
|
594
|
+
if (read.value === null) {
|
|
595
|
+
const created = await createNewRecord(root, action, deps);
|
|
596
|
+
if (created.kind === "error") return created;
|
|
597
|
+
const launched = await launchRecord(created.value, action.overrides.open, deps);
|
|
598
|
+
return launched.kind === "error"
|
|
599
|
+
? launched
|
|
600
|
+
: success(operationOutput("start", "created", statusOutput(created.value, launched.value)));
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const record = read.value;
|
|
604
|
+
if (overridesDiffer(record, action)) {
|
|
605
|
+
return failure(
|
|
606
|
+
"config_mismatch",
|
|
607
|
+
`Instance ${record.name} already has saved configuration; use "agent-inspector instance restart ${record.name}" with overrides to change it.`,
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
const live = await classifyRecord(record, deps);
|
|
611
|
+
if (live.state === "running") {
|
|
612
|
+
if (action.overrides.open) (deps.openUrl ?? defaultOpenUrl)(recordUrls(record).ui);
|
|
613
|
+
return success(operationOutput("start", "already_running", statusOutput(record, live)));
|
|
614
|
+
}
|
|
615
|
+
if (live.state === "conflict") {
|
|
616
|
+
return failure(
|
|
617
|
+
live.code,
|
|
618
|
+
`Instance ${record.name} does not own its saved port pair; no process was terminated.`,
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
const prepared = await prepareStoppedStart(root, record, deps);
|
|
622
|
+
if (prepared.kind === "error") return prepared;
|
|
623
|
+
const launched = await launchRecord(prepared.value, action.overrides.open, deps);
|
|
624
|
+
return launched.kind === "error"
|
|
625
|
+
? launched
|
|
626
|
+
: success(operationOutput("start", "started", statusOutput(prepared.value, launched.value)));
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async function planRestartRecord(
|
|
631
|
+
root: string,
|
|
632
|
+
record: InstanceRecord,
|
|
633
|
+
action: Extract<InstanceAction, { kind: "restart" }>,
|
|
634
|
+
wasRunning: boolean,
|
|
635
|
+
deps: InstanceLifecycleDependencies,
|
|
636
|
+
): Promise<InstanceLifecycleResult<InstanceRecord>> {
|
|
637
|
+
const records = listInstanceRecords(root);
|
|
638
|
+
if (records.kind === "error") return fromRegistry(records);
|
|
639
|
+
const desiredPublicPort = action.overrides.port ?? record.publicPort;
|
|
640
|
+
const desiredUpstreamPort = desiredPublicPort + 2;
|
|
641
|
+
const sameLivePair =
|
|
642
|
+
wasRunning &&
|
|
643
|
+
desiredPublicPort === record.publicPort &&
|
|
644
|
+
desiredUpstreamPort === record.upstreamPort;
|
|
645
|
+
let pair: InstancePortPair;
|
|
646
|
+
if (sameLivePair) {
|
|
647
|
+
pair = { publicPort: record.publicPort, upstreamPort: record.upstreamPort };
|
|
648
|
+
} else {
|
|
649
|
+
const planned = await planInstancePorts({
|
|
650
|
+
records: records.value,
|
|
651
|
+
requestedPublicPort: desiredPublicPort,
|
|
652
|
+
requestedUpstreamPort: desiredUpstreamPort,
|
|
653
|
+
excludeName: record.name,
|
|
654
|
+
publicHost: action.overrides.host ?? record.host,
|
|
655
|
+
isPortAvailable: deps.isPortAvailable,
|
|
656
|
+
});
|
|
657
|
+
if (planned.kind === "error") return fromRegistry(planned);
|
|
658
|
+
pair = planned.value;
|
|
659
|
+
}
|
|
660
|
+
const requestedDataDir = action.overrides.dataDir ?? record.dataDir;
|
|
661
|
+
const dataDir = validateInstanceDataDirectory(requestedDataDir, records.value, record.name);
|
|
662
|
+
if (dataDir.kind === "error") return dataDir;
|
|
663
|
+
return updatedRecord(record, action, pair, dataDir.value);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async function rollbackRestart(
|
|
667
|
+
root: string,
|
|
668
|
+
previous: InstanceRecord,
|
|
669
|
+
deps: InstanceLifecycleDependencies,
|
|
670
|
+
): Promise<boolean> {
|
|
671
|
+
const rotated = rotateInstanceLaunch(previous);
|
|
672
|
+
if (rotated.kind === "error") return false;
|
|
673
|
+
const saved = saveRecord(root, rotated.value);
|
|
674
|
+
if (saved.kind === "error") return false;
|
|
675
|
+
const launched = await launchRecord(saved.value, false, deps);
|
|
676
|
+
return launched.kind === "success";
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async function restartFailureAfterStop<T>(
|
|
680
|
+
root: string,
|
|
681
|
+
previous: InstanceRecord,
|
|
682
|
+
deps: InstanceLifecycleDependencies,
|
|
683
|
+
): Promise<InstanceLifecycleResult<T>> {
|
|
684
|
+
const rolledBack = await rollbackRestart(root, previous, deps);
|
|
685
|
+
return rolledBack
|
|
686
|
+
? failure(
|
|
687
|
+
"restart_failed_rolled_back",
|
|
688
|
+
`Instance ${previous.name} replacement failed; the previous configuration was restored with a fresh launch.`,
|
|
689
|
+
)
|
|
690
|
+
: failure(
|
|
691
|
+
"restart_failed_degraded",
|
|
692
|
+
`Instance ${previous.name} replacement and rollback both failed; its saved configuration remains recoverable for a later start.`,
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async function restartAction(
|
|
697
|
+
root: string,
|
|
698
|
+
action: Extract<InstanceAction, { kind: "restart" }>,
|
|
699
|
+
deps: InstanceLifecycleDependencies,
|
|
700
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
701
|
+
return withLocks(root, action.name, true, async () => {
|
|
702
|
+
const required = readRequiredRecord(root, action.name);
|
|
703
|
+
if (required.kind === "error") return required;
|
|
704
|
+
const current = required.value;
|
|
705
|
+
const live = await classifyRecord(current, deps);
|
|
706
|
+
if (live.state === "conflict") {
|
|
707
|
+
return failure(
|
|
708
|
+
live.code,
|
|
709
|
+
`Instance ${current.name} does not own its saved port pair; refusing to replace another process.`,
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
const planned = await planRestartRecord(root, current, action, live.state === "running", deps);
|
|
713
|
+
if (planned.kind === "error") return planned;
|
|
714
|
+
if (live.state === "running") {
|
|
715
|
+
const stopped = await stopRecord(current, deps);
|
|
716
|
+
if (stopped.kind === "error") return stopped;
|
|
717
|
+
if (
|
|
718
|
+
planned.value.publicPort === current.publicPort &&
|
|
719
|
+
planned.value.upstreamPort === current.upstreamPort
|
|
720
|
+
) {
|
|
721
|
+
const check = deps.isPortAvailable ?? isPortAvailableByBinding;
|
|
722
|
+
if (
|
|
723
|
+
!(await check(current.publicPort, current.host)) ||
|
|
724
|
+
!(await check(current.upstreamPort, DEFAULT_INSTANCE_HOST))
|
|
725
|
+
) {
|
|
726
|
+
return failure(
|
|
727
|
+
"port_conflict",
|
|
728
|
+
`Instance ${current.name} ports did not become available after shutdown.`,
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const saved = saveRecord(root, planned.value);
|
|
734
|
+
if (saved.kind === "error") {
|
|
735
|
+
return live.state === "running" ? restartFailureAfterStop(root, current, deps) : saved;
|
|
736
|
+
}
|
|
737
|
+
const launched = await launchRecord(saved.value, action.overrides.open, deps);
|
|
738
|
+
if (launched.kind === "error") {
|
|
739
|
+
return live.state === "running" ? restartFailureAfterStop(root, current, deps) : launched;
|
|
740
|
+
}
|
|
741
|
+
return success(
|
|
742
|
+
operationOutput("restart", "restarted", statusOutput(saved.value, launched.value)),
|
|
743
|
+
);
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
async function stopAction(
|
|
748
|
+
root: string,
|
|
749
|
+
action: Extract<InstanceAction, { kind: "stop" }>,
|
|
750
|
+
deps: InstanceLifecycleDependencies,
|
|
751
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
752
|
+
return withLocks(root, action.name, false, async () => {
|
|
753
|
+
const required = readRequiredRecord(root, action.name);
|
|
754
|
+
if (required.kind === "error") return required;
|
|
755
|
+
const stopped = await stopRecord(required.value, deps);
|
|
756
|
+
return stopped.kind === "error"
|
|
757
|
+
? stopped
|
|
758
|
+
: success(
|
|
759
|
+
operationOutput(
|
|
760
|
+
"stop",
|
|
761
|
+
stopped.value.outcome,
|
|
762
|
+
statusOutput(required.value, stopped.value.live),
|
|
763
|
+
),
|
|
764
|
+
);
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
async function statusAction(
|
|
769
|
+
root: string,
|
|
770
|
+
name: string,
|
|
771
|
+
deps: InstanceLifecycleDependencies,
|
|
772
|
+
): Promise<InstanceLifecycleResult<InstanceStatusOutput>> {
|
|
773
|
+
const required = readRequiredRecord(root, name);
|
|
774
|
+
if (required.kind === "error") return required;
|
|
775
|
+
const live = await classifyRecord(required.value, deps);
|
|
776
|
+
return success(statusOutput(required.value, live));
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
async function listAction(
|
|
780
|
+
root: string,
|
|
781
|
+
deps: InstanceLifecycleDependencies,
|
|
782
|
+
): Promise<InstanceLifecycleResult<readonly InstanceStatusOutput[]>> {
|
|
783
|
+
const records = listInstanceRecords(root);
|
|
784
|
+
if (records.kind === "error") return fromRegistry(records);
|
|
785
|
+
const outputs = await Promise.all(
|
|
786
|
+
records.value.map(async (record) => statusOutput(record, await classifyRecord(record, deps))),
|
|
787
|
+
);
|
|
788
|
+
return success(outputs);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function requestActionOverrides(
|
|
792
|
+
input: InstanceStartRequest,
|
|
793
|
+
): Extract<InstanceAction, { kind: "start" }>["overrides"] {
|
|
794
|
+
return {
|
|
795
|
+
port: input.port ?? null,
|
|
796
|
+
basePath: input.basePath === undefined ? null : normalizeBasePath(input.basePath),
|
|
797
|
+
host: input.host ?? null,
|
|
798
|
+
captureMode: input.captureMode ?? null,
|
|
799
|
+
dataDir: input.dataDir ?? null,
|
|
800
|
+
open: false,
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function lifecycleRoot(deps: InstanceLifecycleDependencies): string {
|
|
805
|
+
return resolvePath(deps.root ?? getInstancesRoot());
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function normalizedServiceName(rawName: string): InstanceLifecycleResult<string> {
|
|
809
|
+
const validated = validateInstanceName(rawName);
|
|
810
|
+
return validated.kind === "error" ? fromRegistry(validated) : success(validated.value);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
export async function startNamedInstance(
|
|
814
|
+
rawName: string,
|
|
815
|
+
input: InstanceStartRequest = {},
|
|
816
|
+
deps: InstanceLifecycleDependencies = {},
|
|
817
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
818
|
+
const name = normalizedServiceName(rawName);
|
|
819
|
+
if (name.kind === "error") return name;
|
|
820
|
+
return startAction(
|
|
821
|
+
lifecycleRoot(deps),
|
|
822
|
+
{ kind: "start", name: name.value, overrides: requestActionOverrides(input), json: true },
|
|
823
|
+
deps,
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export async function restartNamedInstance(
|
|
828
|
+
rawName: string,
|
|
829
|
+
input: InstanceStartRequest = {},
|
|
830
|
+
deps: InstanceLifecycleDependencies = {},
|
|
831
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
832
|
+
const name = normalizedServiceName(rawName);
|
|
833
|
+
if (name.kind === "error") return name;
|
|
834
|
+
return restartAction(
|
|
835
|
+
lifecycleRoot(deps),
|
|
836
|
+
{ kind: "restart", name: name.value, overrides: requestActionOverrides(input), json: true },
|
|
837
|
+
deps,
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
export async function stopNamedInstance(
|
|
842
|
+
rawName: string,
|
|
843
|
+
deps: InstanceLifecycleDependencies = {},
|
|
844
|
+
): Promise<InstanceLifecycleResult<InstanceOperationOutput>> {
|
|
845
|
+
const name = normalizedServiceName(rawName);
|
|
846
|
+
if (name.kind === "error") return name;
|
|
847
|
+
return stopAction(lifecycleRoot(deps), { kind: "stop", name: name.value, json: true }, deps);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
export async function getNamedInstance(
|
|
851
|
+
rawName: string,
|
|
852
|
+
deps: InstanceLifecycleDependencies = {},
|
|
853
|
+
): Promise<InstanceLifecycleResult<InstanceStatusOutput>> {
|
|
854
|
+
const name = normalizedServiceName(rawName);
|
|
855
|
+
if (name.kind === "error") return name;
|
|
856
|
+
return statusAction(lifecycleRoot(deps), name.value, deps);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export async function getNamedInstanceConnection(
|
|
860
|
+
rawName: string,
|
|
861
|
+
deps: InstanceLifecycleDependencies = {},
|
|
862
|
+
): Promise<InstanceLifecycleResult<InstanceConnectionOutput>> {
|
|
863
|
+
const instance = await getNamedInstance(rawName, deps);
|
|
864
|
+
return instance.kind === "error" ? instance : success(connectionOutput(instance.value));
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export async function listNamedInstances(
|
|
868
|
+
deps: InstanceLifecycleDependencies = {},
|
|
869
|
+
): Promise<InstanceLifecycleResult<readonly InstanceStatusOutput[]>> {
|
|
870
|
+
return listAction(lifecycleRoot(deps), deps);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function formatStatus(output: InstanceStatusOutput): string {
|
|
874
|
+
const pid = output.supervisorPid === null ? "-" : String(output.supervisorPid);
|
|
875
|
+
const reason = output.stateReason === null ? "-" : output.stateReason;
|
|
876
|
+
return `Instance ${output.name}: ${output.state}
|
|
877
|
+
UI: ${output.urls.ui}
|
|
878
|
+
Proxy: ${output.urls.proxy}
|
|
879
|
+
OpenAI /v1: ${output.urls.openai}
|
|
880
|
+
MCP: ${output.urls.mcp}
|
|
881
|
+
Health: ${output.urls.health}
|
|
882
|
+
Port pair: ${String(output.publicPort)} / ${String(output.upstreamPort)} (private)
|
|
883
|
+
Base Path: ${output.basePath}
|
|
884
|
+
Capture mode: ${output.captureMode}
|
|
885
|
+
Data directory: ${output.dataDir}
|
|
886
|
+
Supervisor PID: ${pid}
|
|
887
|
+
State reason: ${reason}
|
|
888
|
+
`;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function formatConnection(output: InstanceConnectionOutput): string {
|
|
892
|
+
return `${formatStatus(output.instance)}
|
|
893
|
+
Coding Agent connection:
|
|
894
|
+
ANTHROPIC_BASE_URL=${output.environment.ANTHROPIC_BASE_URL}
|
|
895
|
+
LLM_BASE_URL=${output.environment.LLM_BASE_URL}
|
|
896
|
+
OPENAI_BASE_URL=${output.environment.OPENAI_BASE_URL}
|
|
897
|
+
AGENT_INSPECTOR_MCP_URL=${output.environment.AGENT_INSPECTOR_MCP_URL}
|
|
898
|
+
MCP server name: ${output.mcp.serverName}
|
|
899
|
+
Codex provider: ${output.codex.providerName} (${output.codex.wireApi})
|
|
900
|
+
`;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function writeError(io: InstanceIo, json: boolean, error: InstanceLifecycleError): void {
|
|
904
|
+
if (json) {
|
|
905
|
+
io.stderr(`${JSON.stringify({ schemaVersion: INSTANCE_API_SCHEMA_VERSION, error })}\n`);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
io.stderr(`agent-inspector instance: ${error.message} (${error.code})\n`);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function writeConnectionOutput(
|
|
912
|
+
io: InstanceIo,
|
|
913
|
+
json: boolean,
|
|
914
|
+
output: InstanceConnectionOutput,
|
|
915
|
+
): void {
|
|
916
|
+
io.stdout(json ? `${JSON.stringify(output, null, 2)}\n` : formatConnection(output));
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function writeSingleOutput(io: InstanceIo, json: boolean, output: InstanceStatusOutput): void {
|
|
920
|
+
io.stdout(json ? `${JSON.stringify(output, null, 2)}\n` : formatStatus(output));
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function writeListOutput(
|
|
924
|
+
io: InstanceIo,
|
|
925
|
+
json: boolean,
|
|
926
|
+
outputs: readonly InstanceStatusOutput[],
|
|
927
|
+
): void {
|
|
928
|
+
if (json) {
|
|
929
|
+
io.stdout(`${JSON.stringify({ schemaVersion: 1, instances: outputs }, null, 2)}\n`);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
io.stdout(
|
|
933
|
+
outputs.length === 0
|
|
934
|
+
? "No named Agent Inspector instances are registered.\n"
|
|
935
|
+
: outputs.map(formatStatus).join("\n"),
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function normalizeActionName(action: InstanceAction): InstanceLifecycleResult<InstanceAction> {
|
|
940
|
+
if (action.kind === "list") return success(action);
|
|
941
|
+
const validated = validateInstanceName(action.name);
|
|
942
|
+
if (validated.kind === "error") return fromRegistry(validated);
|
|
943
|
+
return success({ ...action, name: validated.value });
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
export async function runInstance(
|
|
947
|
+
argv: readonly string[],
|
|
948
|
+
deps: InstanceLifecycleDependencies = {},
|
|
949
|
+
io: InstanceIo = processIo,
|
|
950
|
+
): Promise<number> {
|
|
951
|
+
const parsed = parseInstanceArgs(argv);
|
|
952
|
+
if (parsed.kind === "help") {
|
|
953
|
+
io.stdout(instanceHelp());
|
|
954
|
+
return 0;
|
|
955
|
+
}
|
|
956
|
+
if (parsed.kind === "error") {
|
|
957
|
+
if (argv.includes("--json")) {
|
|
958
|
+
writeError(io, true, {
|
|
959
|
+
code: "argument_invalid",
|
|
960
|
+
message: parsed.message,
|
|
961
|
+
retryable: false,
|
|
962
|
+
});
|
|
963
|
+
} else {
|
|
964
|
+
io.stderr(`${parsed.message}\n\n${instanceHelp()}`);
|
|
965
|
+
}
|
|
966
|
+
return 2;
|
|
967
|
+
}
|
|
968
|
+
const normalized = normalizeActionName(parsed.action);
|
|
969
|
+
if (normalized.kind === "error") {
|
|
970
|
+
writeError(io, parsed.action.json, normalized.error);
|
|
971
|
+
return 2;
|
|
972
|
+
}
|
|
973
|
+
const root = resolvePath(deps.root ?? getInstancesRoot());
|
|
974
|
+
const action = normalized.value;
|
|
975
|
+
switch (action.kind) {
|
|
976
|
+
case "start": {
|
|
977
|
+
const result = await startAction(root, action, deps);
|
|
978
|
+
if (result.kind === "error") {
|
|
979
|
+
writeError(io, action.json, result.error);
|
|
980
|
+
return 1;
|
|
981
|
+
}
|
|
982
|
+
writeSingleOutput(io, action.json, result.value.instance);
|
|
983
|
+
return 0;
|
|
984
|
+
}
|
|
985
|
+
case "restart": {
|
|
986
|
+
const result = await restartAction(root, action, deps);
|
|
987
|
+
if (result.kind === "error") {
|
|
988
|
+
writeError(io, action.json, result.error);
|
|
989
|
+
return 1;
|
|
990
|
+
}
|
|
991
|
+
writeSingleOutput(io, action.json, result.value.instance);
|
|
992
|
+
return 0;
|
|
993
|
+
}
|
|
994
|
+
case "stop": {
|
|
995
|
+
const result = await stopAction(root, action, deps);
|
|
996
|
+
if (result.kind === "error") {
|
|
997
|
+
writeError(io, action.json, result.error);
|
|
998
|
+
return 1;
|
|
999
|
+
}
|
|
1000
|
+
writeSingleOutput(io, action.json, result.value.instance);
|
|
1001
|
+
return 0;
|
|
1002
|
+
}
|
|
1003
|
+
case "status": {
|
|
1004
|
+
const result = await statusAction(root, action.name, deps);
|
|
1005
|
+
if (result.kind === "error") {
|
|
1006
|
+
writeError(io, action.json, result.error);
|
|
1007
|
+
return 1;
|
|
1008
|
+
}
|
|
1009
|
+
writeSingleOutput(io, action.json, result.value);
|
|
1010
|
+
return result.value.state === "conflict" ? 1 : 0;
|
|
1011
|
+
}
|
|
1012
|
+
case "connect": {
|
|
1013
|
+
const result = await getNamedInstanceConnection(action.name, { ...deps, root });
|
|
1014
|
+
if (result.kind === "error") {
|
|
1015
|
+
writeError(io, action.json, result.error);
|
|
1016
|
+
return 1;
|
|
1017
|
+
}
|
|
1018
|
+
writeConnectionOutput(io, action.json, result.value);
|
|
1019
|
+
return result.value.instance.state === "conflict" ? 1 : 0;
|
|
1020
|
+
}
|
|
1021
|
+
case "list": {
|
|
1022
|
+
const result = await listAction(root, deps);
|
|
1023
|
+
if (result.kind === "error") {
|
|
1024
|
+
writeError(io, action.json, result.error);
|
|
1025
|
+
return 1;
|
|
1026
|
+
}
|
|
1027
|
+
writeListOutput(io, action.json, result.value);
|
|
1028
|
+
return 0;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
export const instanceLifecycleForTests = {
|
|
1034
|
+
classifyRecord,
|
|
1035
|
+
launchArgs,
|
|
1036
|
+
statusOutput,
|
|
1037
|
+
};
|