Repository navigation
Expand file tree
/
Copy pathmonitor.ts
More file actions
357 lines (324 loc) · 10.7 KB
/
Copy pathmonitor.ts
File metadata and controls
357 lines (324 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { spawn } from "node:child_process";
import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { constants as osConstants, homedir, tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import type { TaskEvent, TaskRecord } from "@monitor/contracts";
import { buildClaudeSettings } from "../lib/adapters/claude.js";
import { isDirectExecution } from "../lib/bin-entry.js";
import { ensureDaemonRunning } from "../lib/daemon.js";
import { DaemonClient } from "../lib/http-client.js";
import {
ensureCursorBridgeInstalled,
installCursorBridge
} from "../lib/install/cursor-bridge.js";
import { buildCodexCommand, detectCodexWaitState } from "../lib/adapters/codex.js";
import { detectHostMetadata } from "../lib/host-metadata.js";
import { buildCursorBridgeUri } from "../lib/focus/cursor-bridge.js";
import { wrapCommandWithPty } from "../lib/pty.js";
const DEFAULT_DAEMON_URL = "http://127.0.0.1:45731";
const CURSOR_DEBUG_LOG_FILE = "cursor-focus-debug.jsonl";
function appendCursorDebugLog(event: string, payload: Record<string, unknown>): void {
try {
const dataDir = process.env.MONITOR_DATA_DIR ?? join(homedir(), ".monitor-data");
mkdirSync(dataDir, { recursive: true });
appendFileSync(
join(dataDir, CURSOR_DEBUG_LOG_FILE),
`${JSON.stringify({
ts: new Date().toISOString(),
scope: "monitor-cli",
pid: process.pid,
event,
...payload
})}\n`,
"utf8"
);
} catch {
// Debug logging is best-effort only.
}
}
export function parseNameArg(args: string[]): { name: string; remainingArgs: string[] } {
const nameIndex = args.indexOf("--name");
if (nameIndex < 0) return { name: "", remainingArgs: [...args] };
const candidateName = args[nameIndex + 1] ?? "";
const name = candidateName.startsWith("-") ? "" : candidateName;
const remainingArgs = [...args];
remainingArgs.splice(nameIndex, name ? 2 : 1);
return { name, remainingArgs };
}
export function resolveProcessExitCode(
code: number | null,
signal: NodeJS.Signals | null
): number {
if (typeof code === "number") return code;
if (!signal) return 0;
const signalCode = osConstants.signals[signal];
return typeof signalCode === "number" ? 128 + signalCode : 1;
}
export function buildStreamEvents(
taskId: string,
chunk: string,
carryover: string,
runner: TaskRecord["runnerType"] = "codex"
): { events: TaskEvent[]; carryover: string } {
const at = new Date().toISOString();
const events: TaskEvent[] = [{ type: "task.output", taskId, at, payload: { chunk } }];
const combined = `${carryover}${chunk}`.slice(-512);
const waitState = runner === "codex" ? detectCodexWaitState(combined) : null;
if (waitState) {
events.push({ type: `task.${waitState}`, taskId, at } as TaskEvent);
return { events, carryover: "" };
}
return { events, carryover: combined };
}
export function buildCloseEvents(
taskId: string,
code: number | null,
signal: NodeJS.Signals | null,
runner: TaskRecord["runnerType"] = "codex"
): { exitCode: number; events: TaskEvent[] } {
const exitCode = resolveProcessExitCode(code, signal);
if (exitCode === 0) {
return {
exitCode,
events: [{ type: "task.finished", taskId, at: new Date().toISOString() }]
};
}
const detail =
signal && code === null
? `signal ${signal}`
: `code ${typeof code === "number" ? code : exitCode}`;
return {
exitCode,
events: [
{
type: "task.error",
taskId,
at: new Date().toISOString(),
payload: { message: `${runner} exited with ${detail}` }
}
]
};
}
export function createEventQueue(
postEvent: (event: TaskEvent) => Promise<void>,
onError: (error: unknown) => void
): { enqueue: (event: TaskEvent) => void; drain: () => Promise<void> } {
let eventQueue = Promise.resolve();
const enqueue = (event: TaskEvent): void => {
eventQueue = eventQueue
.then(() => postEvent(event))
.catch((error) => onError(error));
};
return { enqueue, drain: () => eventQueue };
}
function openUriDetached(uri: string): void {
const child = spawn("open", [uri], {
detached: true,
stdio: "ignore"
});
child.unref();
}
function printUsage(): void {
process.stdout.write("用法:\n");
process.stdout.write(" monitor <codex|claude> [args...]\n");
process.stdout.write(" monitor install-cursor-bridge\n");
}
export function handleUtilityCommand(args: string[]): boolean {
const [command, ...restArgs] = args;
if (command === "install-cursor-bridge") {
if (restArgs.length > 0) {
throw new Error("install-cursor-bridge does not accept extra arguments");
}
const { targetDir } = installCursorBridge({
moduleUrl: import.meta.url
});
process.stdout.write(`Cursor bridge 已安装到:\n ${targetDir}\n`);
process.stdout.write("如果 Cursor 正在运行,重启一次 Cursor,确保 bridge 扩展被加载。\n");
return true;
}
if (command === "--help" || command === "-h" || command === "help") {
printUsage();
return true;
}
return false;
}
export async function main(): Promise<void> {
const daemonUrl = process.env.MONITOR_DAEMON_URL ?? DEFAULT_DAEMON_URL;
const forwardedArgs = process.argv.slice(2);
if (handleUtilityCommand(forwardedArgs)) {
return;
}
const [runner, ...runnerArgs] = forwardedArgs;
if (runner !== "codex" && runner !== "claude") {
printUsage();
throw new Error(`unsupported runner: ${runner ?? ""}`);
}
const runnerType: TaskRecord["runnerType"] = runner;
const host = detectHostMetadata();
if (host.hostApp === "cursor") {
try {
const result = ensureCursorBridgeInstalled({
moduleUrl: import.meta.url
});
if (result.installed) {
const actionText = result.reason === "outdated" ? "更新" : "安装";
process.stderr.write(
`monitor: 已自动${actionText} Cursor bridge 到 ${result.targetDir},请重启一次 Cursor。\n`
);
}
} catch (error) {
process.stderr.write(
`monitor: 自动安装 Cursor bridge 失败,可稍后手动执行 monitor install-cursor-bridge: ${String(error)}\n`
);
}
}
await ensureDaemonRunning({
baseUrl: daemonUrl,
moduleUrl: import.meta.url
});
const { name, remainingArgs } = parseNameArg(runnerArgs);
const taskId = randomUUID();
const displayName = name || `${runnerType}-${taskId.slice(0, 8)}`;
const hookPath = join(dirname(fileURLToPath(import.meta.url)), "monitor-hook.js");
const baseHookCommand = [process.execPath, hookPath];
let command: string[];
if (runnerType === "codex") {
command = buildCodexCommand({
taskId,
daemonUrl,
hookCommand: baseHookCommand,
forwardedArgs: ["codex", ...remainingArgs]
});
} else {
const settings = buildClaudeSettings({
taskId,
daemonUrl,
hookCommand: baseHookCommand
});
const settingsDir = mkdtempSync(join(tmpdir(), "monitor-claude-"));
const settingsPath = join(settingsDir, "settings.json");
writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
command = [
"claude",
"--settings",
settingsPath,
...(name ? ["-n", name] : []),
...remainingArgs
];
}
const spawnCommand = wrapCommandWithPty(command);
const child = spawn(spawnCommand[0], spawnCommand.slice(1), {
stdio: ["inherit", "pipe", "pipe"]
});
const client = new DaemonClient(daemonUrl);
const eventQueue = createEventQueue((event) => client.postEvent(event), (error) => {
process.stderr.write(`failed to post task event: ${String(error)}\n`);
});
const enqueueEvent = eventQueue.enqueue;
let didSpawn = false;
let hasExited = false;
let stdoutCarryover = "";
let stderrCarryover = "";
const flushAndExit = (exitCode: number): void => {
if (hasExited) return;
hasExited = true;
void eventQueue
.drain()
.then(() => process.exit(exitCode))
.catch(() => process.exit(1));
};
child.on("spawn", () => {
didSpawn = true;
const startedAt = new Date().toISOString();
if (host.hostApp === "cursor") {
appendCursorDebugLog("cursor-task-spawned", {
taskId,
name: displayName,
cwd: process.cwd(),
hostWindowRef: host.hostWindowRef,
hostSessionRef: host.hostSessionRef,
env: {
TERM_PROGRAM: process.env.TERM_PROGRAM ?? null,
TERM_PROGRAM_VERSION: process.env.TERM_PROGRAM_VERSION ?? null,
CURSOR_TRACE_ID: process.env.CURSOR_TRACE_ID ?? null,
CURSOR_AGENT: process.env.CURSOR_AGENT ?? null,
WINDOWID: process.env.WINDOWID ?? null
}
});
openUriDetached(
buildCursorBridgeUri("register", {
taskId,
name: displayName,
cwd: process.cwd(),
monitorPid: String(process.pid)
})
);
}
const task: TaskRecord = {
taskId,
name: displayName,
runnerType,
rawCommand: command,
cwd: process.cwd(),
pid: child.pid ?? -1,
hostApp: host.hostApp,
hostWindowRef: host.hostWindowRef,
hostSessionRef: host.hostSessionRef,
startedAt,
lastEventAt: startedAt,
status: "running",
lastOutputExcerpt: ""
};
enqueueEvent({
type: "task.started",
taskId,
at: startedAt,
payload: task
});
});
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
process.stdout.write(chunk);
const result = buildStreamEvents(taskId, chunk, stdoutCarryover, runnerType);
stdoutCarryover = result.carryover;
for (const event of result.events) {
enqueueEvent(event);
}
});
child.stderr?.setEncoding("utf8");
child.stderr?.on("data", (chunk: string) => {
process.stderr.write(chunk);
const result = buildStreamEvents(taskId, chunk, stderrCarryover, runnerType);
stderrCarryover = result.carryover;
for (const event of result.events) {
enqueueEvent(event);
}
});
child.on("error", (error) => {
enqueueEvent({
type: "task.error",
taskId,
at: new Date().toISOString(),
payload: { message: `failed to spawn ${runnerType}: ${String(error)}` }
});
if (!didSpawn) {
flushAndExit(1);
}
});
child.on("close", (code, signal) => {
const result = buildCloseEvents(taskId, code, signal, runnerType);
for (const event of result.events) {
enqueueEvent(event);
}
flushAndExit(result.exitCode);
});
}
if (isDirectExecution(fileURLToPath(import.meta.url), process.argv[1])) {
main().catch((error) => {
process.stderr.write(String(error) + "\n");
process.exit(1);
});
}