u-foo 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ufoo.js +15 -7
- package/package.json +3 -2
- package/scripts/global-chat-switch-benchmark.js +406 -0
- package/src/chat/chatLogController.js +28 -5
- package/src/chat/commandExecutor.js +127 -3
- package/src/chat/commands.js +8 -0
- package/src/chat/daemonConnection.js +36 -1
- package/src/chat/daemonCoordinator.js +36 -0
- package/src/chat/daemonTransport.js +36 -5
- package/src/chat/dashboardKeyController.js +80 -1
- package/src/chat/dashboardView.js +289 -93
- package/src/chat/index.js +537 -37
- package/src/chat/inputHistoryController.js +33 -3
- package/src/chat/inputListenerController.js +22 -12
- package/src/chat/layout.js +12 -7
- package/src/chat/streamTracker.js +6 -0
- package/src/cli.js +167 -4
- package/src/daemon/index.js +42 -2
- package/src/daemon/ops.js +199 -23
- package/src/projects/projectId.js +29 -0
- package/src/projects/registry.js +279 -0
package/src/daemon/ops.js
CHANGED
|
@@ -37,6 +37,44 @@ function toTmuxBinary(agent = "") {
|
|
|
37
37
|
return "";
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
function normalizeLaunchScope(value, fallback = "inplace") {
|
|
41
|
+
const raw = String(value || "").trim().toLowerCase();
|
|
42
|
+
if (!raw) return fallback;
|
|
43
|
+
if (raw === "inplace" || raw === "same" || raw === "current" || raw === "tab" || raw === "pane") {
|
|
44
|
+
return "inplace";
|
|
45
|
+
}
|
|
46
|
+
if (
|
|
47
|
+
raw === "window"
|
|
48
|
+
|| raw === "separate"
|
|
49
|
+
|| raw === "new"
|
|
50
|
+
|| raw === "new-window"
|
|
51
|
+
|| raw === "external"
|
|
52
|
+
|| raw === "1"
|
|
53
|
+
|| raw === "true"
|
|
54
|
+
|| raw === "yes"
|
|
55
|
+
|| raw === "y"
|
|
56
|
+
|| raw === "on"
|
|
57
|
+
) {
|
|
58
|
+
return "window";
|
|
59
|
+
}
|
|
60
|
+
if (raw === "0" || raw === "false" || raw === "no" || raw === "n" || raw === "off") {
|
|
61
|
+
return "inplace";
|
|
62
|
+
}
|
|
63
|
+
return fallback;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function normalizeTerminalAppPreference(value = "") {
|
|
67
|
+
const raw = String(value || "").trim().toLowerCase();
|
|
68
|
+
if (!raw) return "";
|
|
69
|
+
if (raw === "terminal" || raw === "apple_terminal" || raw === "apple-terminal") {
|
|
70
|
+
return "terminal";
|
|
71
|
+
}
|
|
72
|
+
if (raw === "iterm2" || raw === "iterm" || raw === "iterm.app") {
|
|
73
|
+
return "iterm2";
|
|
74
|
+
}
|
|
75
|
+
return "";
|
|
76
|
+
}
|
|
77
|
+
|
|
40
78
|
function resolveAgentId(projectRoot, agentId) {
|
|
41
79
|
if (!agentId) return agentId;
|
|
42
80
|
if (agentId.includes(":")) return agentId;
|
|
@@ -130,23 +168,40 @@ function runAppleScript(lines) {
|
|
|
130
168
|
});
|
|
131
169
|
}
|
|
132
170
|
|
|
133
|
-
async function openTerminalWindow(runCmd) {
|
|
171
|
+
async function openTerminalWindow(runCmd, options = {}) {
|
|
134
172
|
if (process.platform !== "darwin") {
|
|
135
173
|
throw new Error("Terminal mode is only supported on macOS");
|
|
136
174
|
}
|
|
137
175
|
|
|
176
|
+
const launchScope = normalizeLaunchScope(options.launchScope, "inplace");
|
|
177
|
+
const terminalApp = normalizeTerminalAppPreference(options.terminalApp);
|
|
178
|
+
const preferSeparateWindow = launchScope === "window";
|
|
138
179
|
const escaped = escapeAppleScriptString(runCmd);
|
|
180
|
+
const shouldTryITerm2 = terminalApp
|
|
181
|
+
? terminalApp === "iterm2"
|
|
182
|
+
: isITerm2();
|
|
139
183
|
|
|
140
|
-
if (
|
|
184
|
+
if (shouldTryITerm2) {
|
|
141
185
|
try {
|
|
142
|
-
const script =
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
186
|
+
const script = preferSeparateWindow
|
|
187
|
+
? [
|
|
188
|
+
'tell application "iTerm2"',
|
|
189
|
+
` create window with default profile command "${escaped}"`,
|
|
190
|
+
" activate",
|
|
191
|
+
"end tell",
|
|
192
|
+
]
|
|
193
|
+
: [
|
|
194
|
+
'tell application "iTerm2"',
|
|
195
|
+
" if (count of windows) is 0 then",
|
|
196
|
+
` create window with default profile command "${escaped}"`,
|
|
197
|
+
" else",
|
|
198
|
+
" tell current window",
|
|
199
|
+
` create tab with default profile command "${escaped}"`,
|
|
200
|
+
" end tell",
|
|
201
|
+
" end if",
|
|
202
|
+
" activate",
|
|
203
|
+
"end tell",
|
|
204
|
+
];
|
|
150
205
|
await runAppleScript(script);
|
|
151
206
|
return;
|
|
152
207
|
} catch {
|
|
@@ -154,13 +209,55 @@ async function openTerminalWindow(runCmd) {
|
|
|
154
209
|
}
|
|
155
210
|
}
|
|
156
211
|
|
|
157
|
-
|
|
212
|
+
if (preferSeparateWindow) {
|
|
213
|
+
const script = [
|
|
214
|
+
'tell application "Terminal"',
|
|
215
|
+
` do script "${escaped}"`,
|
|
216
|
+
" activate",
|
|
217
|
+
"end tell",
|
|
218
|
+
];
|
|
219
|
+
await runAppleScript(script);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const preferredScript = [
|
|
158
224
|
'tell application "Terminal"',
|
|
159
|
-
|
|
160
|
-
"
|
|
225
|
+
" activate",
|
|
226
|
+
" if (count of windows) is 0 then",
|
|
227
|
+
` do script "${escaped}"`,
|
|
228
|
+
" else",
|
|
229
|
+
' tell application "System Events"',
|
|
230
|
+
' tell process "Terminal"',
|
|
231
|
+
' keystroke "t" using command down',
|
|
232
|
+
" end tell",
|
|
233
|
+
" end tell",
|
|
234
|
+
" delay 0.08",
|
|
235
|
+
` do script "${escaped}" in selected tab of front window`,
|
|
236
|
+
" end if",
|
|
237
|
+
" activate",
|
|
161
238
|
"end tell",
|
|
162
239
|
];
|
|
163
|
-
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
await runAppleScript(preferredScript);
|
|
243
|
+
return;
|
|
244
|
+
} catch {
|
|
245
|
+
// Accessibility can block System Events key events; fall back to pure Terminal AppleScript.
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const fallbackScript = [
|
|
249
|
+
'tell application "Terminal"',
|
|
250
|
+
" activate",
|
|
251
|
+
" if (count of windows) is 0 then",
|
|
252
|
+
` do script "${escaped}"`,
|
|
253
|
+
" else",
|
|
254
|
+
" set newTab to (do script \"\" in front window)",
|
|
255
|
+
` do script "${escaped}" in newTab`,
|
|
256
|
+
" end if",
|
|
257
|
+
" activate",
|
|
258
|
+
"end tell",
|
|
259
|
+
];
|
|
260
|
+
await runAppleScript(fallbackScript);
|
|
164
261
|
}
|
|
165
262
|
|
|
166
263
|
async function closeTerminalWindowByTty(ttyPath, preferApp = "") {
|
|
@@ -262,7 +359,16 @@ async function tryReuseTerminal(projectRoot, subscriberId, meta, agent, sessionI
|
|
|
262
359
|
/**
|
|
263
360
|
* Spawn managed terminal agent - open a real Terminal session to run the agent
|
|
264
361
|
*/
|
|
265
|
-
async function spawnManagedTerminalAgent(
|
|
362
|
+
async function spawnManagedTerminalAgent(
|
|
363
|
+
projectRoot,
|
|
364
|
+
agent,
|
|
365
|
+
nickname = "",
|
|
366
|
+
processManager = null,
|
|
367
|
+
extraArgs = [],
|
|
368
|
+
extraEnv = "",
|
|
369
|
+
launchScope = "window",
|
|
370
|
+
terminalApp = ""
|
|
371
|
+
) {
|
|
266
372
|
const normalizedAgent = normalizeLaunchAgent(agent);
|
|
267
373
|
const binary = toTerminalBinary(normalizedAgent);
|
|
268
374
|
const agentType = toBusAgentType(normalizedAgent);
|
|
@@ -283,7 +389,7 @@ async function spawnManagedTerminalAgent(projectRoot, agent, nickname = "", proc
|
|
|
283
389
|
|
|
284
390
|
const runCmd = `cd ${shellEscape(projectRoot)} && ${prefix}${modeEnv}${nickEnv}${envPrefix}${binary}${argText}`;
|
|
285
391
|
|
|
286
|
-
await openTerminalWindow(runCmd);
|
|
392
|
+
await openTerminalWindow(runCmd, { launchScope, terminalApp });
|
|
287
393
|
|
|
288
394
|
const subscriberId = await waitForNewSubscriber(projectRoot, agentType, existing, 15000);
|
|
289
395
|
return { child: null, subscriberId: subscriberId || null };
|
|
@@ -455,9 +561,57 @@ function spawnTmuxWindow(projectRoot, agent, nickname = "", extraArgs = [], extr
|
|
|
455
561
|
});
|
|
456
562
|
}
|
|
457
563
|
|
|
458
|
-
|
|
564
|
+
function resolveTmuxPaneTarget() {
|
|
565
|
+
const explicit = String(process.env.UFOO_TMUX_TARGET || "").trim();
|
|
566
|
+
if (explicit) return explicit;
|
|
567
|
+
const preferredPane = String(process.env.UFOO_TMUX_PANE || "").trim();
|
|
568
|
+
if (preferredPane) return preferredPane;
|
|
569
|
+
const currentPane = String(process.env.TMUX_PANE || "").trim();
|
|
570
|
+
if (currentPane) return currentPane;
|
|
571
|
+
return "";
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function spawnTmuxPane(projectRoot, agent, nickname = "", extraArgs = [], extraEnv = "", target = "") {
|
|
575
|
+
return new Promise((resolve, reject) => {
|
|
576
|
+
const normalizedAgent = normalizeLaunchAgent(agent);
|
|
577
|
+
const binary = toTmuxBinary(normalizedAgent);
|
|
578
|
+
if (!binary) {
|
|
579
|
+
reject(new Error(`unsupported agent type: ${agent}`));
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const nickEnv = nickname ? `UFOO_NICKNAME=${shellEscape(nickname)} ` : "";
|
|
583
|
+
const modeEnv = "UFOO_LAUNCH_MODE=tmux ";
|
|
584
|
+
const ttyEnv = "UFOO_TTY_OVERRIDE=$(tty) ";
|
|
585
|
+
const args = Array.isArray(extraArgs) ? extraArgs : [];
|
|
586
|
+
const envPrefix = extraEnv ? `${String(extraEnv).trim()} ` : "";
|
|
587
|
+
const argText = args.length > 0 ? ` ${args.map(shellEscape).join(" ")}` : "";
|
|
588
|
+
const setPaneEnv = `export TMUX_PANE=$(tmux display-message -p '#{pane_id}'); `;
|
|
589
|
+
const runCmd = `cd ${shellEscape(projectRoot)} && ${setPaneEnv}${modeEnv}${nickEnv}${ttyEnv}${envPrefix}${binary}${argText}`;
|
|
590
|
+
|
|
591
|
+
const tmuxArgs = ["split-window", "-d"];
|
|
592
|
+
const normalizedTarget = String(target || "").trim();
|
|
593
|
+
if (normalizedTarget) {
|
|
594
|
+
tmuxArgs.push("-t", normalizedTarget);
|
|
595
|
+
}
|
|
596
|
+
tmuxArgs.push(runCmd);
|
|
597
|
+
|
|
598
|
+
const proc = spawn("tmux", tmuxArgs);
|
|
599
|
+
let stderr = "";
|
|
600
|
+
proc.stderr.on("data", (d) => {
|
|
601
|
+
stderr += d.toString("utf8");
|
|
602
|
+
});
|
|
603
|
+
proc.on("close", (code) => {
|
|
604
|
+
if (code === 0) resolve();
|
|
605
|
+
else reject(new Error(stderr || "tmux split-window failed"));
|
|
606
|
+
});
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function launchAgent(projectRoot, agent, count = 1, nickname = "", processManager = null, options = {}) {
|
|
459
611
|
const config = loadConfig(projectRoot);
|
|
460
612
|
const mode = config.launchMode || "terminal";
|
|
613
|
+
const launchScope = normalizeLaunchScope(options.launchScope, "inplace");
|
|
614
|
+
const terminalApp = normalizeTerminalAppPreference(options.terminalApp);
|
|
461
615
|
const normalizedAgent = normalizeLaunchAgent(agent);
|
|
462
616
|
if (!normalizedAgent) {
|
|
463
617
|
throw new Error(`unsupported agent type: ${agent}`);
|
|
@@ -465,7 +619,7 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
|
|
|
465
619
|
|
|
466
620
|
if (mode === "internal") {
|
|
467
621
|
const result = await spawnInternalAgent(projectRoot, normalizedAgent, count, nickname, processManager);
|
|
468
|
-
return { mode: "internal", subscriberIds: result.subscriberIds };
|
|
622
|
+
return { mode: "internal", launchScope, subscriberIds: result.subscriberIds };
|
|
469
623
|
}
|
|
470
624
|
if (mode === "tmux") {
|
|
471
625
|
// Check if tmux is available
|
|
@@ -489,14 +643,27 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
|
|
|
489
643
|
process.env.UFOO_TMUX_SESSION = firstSession;
|
|
490
644
|
}
|
|
491
645
|
}
|
|
646
|
+
const paneTarget = resolveTmuxPaneTarget();
|
|
647
|
+
const useSeparateWindow = launchScope === "window";
|
|
492
648
|
for (let i = 0; i < count; i += 1) {
|
|
493
649
|
// Use "ucode" as default nickname for ufoo/ucode agents
|
|
494
650
|
const defaultNick = normalizedAgent === "ufoo" ? "ucode" : normalizedAgent;
|
|
495
651
|
const nick = count > 1 ? `${nickname || defaultNick}-${i + 1}` : (nickname || "");
|
|
496
|
-
|
|
497
|
-
|
|
652
|
+
if (useSeparateWindow) {
|
|
653
|
+
// eslint-disable-next-line no-await-in-loop
|
|
654
|
+
await spawnTmuxWindow(projectRoot, normalizedAgent, nick);
|
|
655
|
+
} else {
|
|
656
|
+
try {
|
|
657
|
+
// eslint-disable-next-line no-await-in-loop
|
|
658
|
+
await spawnTmuxPane(projectRoot, normalizedAgent, nick, [], "", paneTarget);
|
|
659
|
+
} catch {
|
|
660
|
+
// Fallback to new window when current pane target cannot be resolved.
|
|
661
|
+
// eslint-disable-next-line no-await-in-loop
|
|
662
|
+
await spawnTmuxWindow(projectRoot, normalizedAgent, nick);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
498
665
|
}
|
|
499
|
-
return { mode: "tmux" };
|
|
666
|
+
return { mode: "tmux", launchScope, subscriberIds: [] };
|
|
500
667
|
}
|
|
501
668
|
// terminal mode - daemon 作为父进程,输出到终端窗口
|
|
502
669
|
if (process.platform !== "darwin") {
|
|
@@ -509,11 +676,20 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
|
|
|
509
676
|
const defaultNick = normalizedAgent === "ufoo" ? "ucode" : normalizedAgent;
|
|
510
677
|
const nick = count > 1 ? `${nickname || defaultNick}-${i + 1}` : (nickname || "");
|
|
511
678
|
// eslint-disable-next-line no-await-in-loop
|
|
512
|
-
const result = await spawnManagedTerminalAgent(
|
|
679
|
+
const result = await spawnManagedTerminalAgent(
|
|
680
|
+
projectRoot,
|
|
681
|
+
normalizedAgent,
|
|
682
|
+
nick,
|
|
683
|
+
processManager,
|
|
684
|
+
[],
|
|
685
|
+
"",
|
|
686
|
+
launchScope,
|
|
687
|
+
terminalApp
|
|
688
|
+
);
|
|
513
689
|
if (result.subscriberId) subscriberIds.push(result.subscriberId);
|
|
514
690
|
}
|
|
515
691
|
|
|
516
|
-
return { mode: "terminal", subscriberIds };
|
|
692
|
+
return { mode: "terminal", launchScope, subscriberIds };
|
|
517
693
|
}
|
|
518
694
|
|
|
519
695
|
function normalizeAgentType(agentType) {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const crypto = require("crypto");
|
|
2
|
+
const fs = require("fs");
|
|
3
|
+
const path = require("path");
|
|
4
|
+
|
|
5
|
+
function trimTrailingSlashes(value) {
|
|
6
|
+
if (!value) return value;
|
|
7
|
+
return value.replace(/\/+$/, "") || "/";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function canonicalProjectRoot(projectRoot) {
|
|
11
|
+
const input = String(projectRoot || "").trim();
|
|
12
|
+
if (!input) {
|
|
13
|
+
throw new Error("projectRoot is required");
|
|
14
|
+
}
|
|
15
|
+
const resolved = path.resolve(input);
|
|
16
|
+
const canonical = fs.realpathSync.native ? fs.realpathSync.native(resolved) : fs.realpathSync(resolved);
|
|
17
|
+
return trimTrailingSlashes(canonical);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function buildProjectId(projectRoot) {
|
|
21
|
+
const canonical = canonicalProjectRoot(projectRoot);
|
|
22
|
+
return crypto.createHash("sha1").update(canonical).digest("hex").slice(0, 12);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = {
|
|
26
|
+
trimTrailingSlashes,
|
|
27
|
+
canonicalProjectRoot,
|
|
28
|
+
buildProjectId,
|
|
29
|
+
};
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
const fs = require("fs");
|
|
2
|
+
const os = require("os");
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const { canonicalProjectRoot, buildProjectId, trimTrailingSlashes } = require("./projectId");
|
|
5
|
+
const { getUfooPaths } = require("../ufoo/paths");
|
|
6
|
+
|
|
7
|
+
const DEFAULT_STALE_TTL_MS = 30 * 1000;
|
|
8
|
+
const DEFAULT_TMP_CLEANUP_AGE_MS = 5 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
function ensureDir(dirPath) {
|
|
11
|
+
if (!fs.existsSync(dirPath)) {
|
|
12
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function canonicalizeForRecord(projectRoot) {
|
|
17
|
+
const input = String(projectRoot || "").trim();
|
|
18
|
+
if (!input) throw new Error("projectRoot is required");
|
|
19
|
+
try {
|
|
20
|
+
return canonicalProjectRoot(input);
|
|
21
|
+
} catch (err) {
|
|
22
|
+
if (!err || err.code === "ENOENT") {
|
|
23
|
+
// Keep stale records readable when project path was deleted or moved.
|
|
24
|
+
return trimTrailingSlashes(path.resolve(input));
|
|
25
|
+
}
|
|
26
|
+
// Unexpected IO errors should be visible, but keep fallback behavior.
|
|
27
|
+
// eslint-disable-next-line no-console
|
|
28
|
+
console.warn(`[projects] canonicalize fallback for ${input}: ${err.message || err}`);
|
|
29
|
+
// Keep stale records readable even when project path no longer exists.
|
|
30
|
+
return trimTrailingSlashes(path.resolve(input));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function resolveRuntimeDir(options = {}) {
|
|
35
|
+
if (options.runtimeDir) return options.runtimeDir;
|
|
36
|
+
return path.join(os.homedir(), ".ufoo", "projects", "runtime");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function normalizeIsoTimestamp(value, fallback = new Date().toISOString()) {
|
|
40
|
+
if (!value) return fallback;
|
|
41
|
+
const parsed = new Date(value);
|
|
42
|
+
if (Number.isNaN(parsed.getTime())) return fallback;
|
|
43
|
+
return parsed.toISOString();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function runtimeFilePathByProjectId(projectId, options = {}) {
|
|
47
|
+
const runtimeDir = resolveRuntimeDir(options);
|
|
48
|
+
return path.join(runtimeDir, `${projectId}.json`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function runtimeFilePathByProjectRoot(projectRoot, options = {}) {
|
|
52
|
+
return runtimeFilePathByProjectId(buildProjectId(projectRoot), options);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readJsonFileSafe(filePath) {
|
|
56
|
+
try {
|
|
57
|
+
const raw = fs.readFileSync(filePath, "utf8");
|
|
58
|
+
return JSON.parse(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function writeJsonAtomic(filePath, data) {
|
|
65
|
+
ensureDir(path.dirname(filePath));
|
|
66
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
67
|
+
fs.writeFileSync(tmpPath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
|
68
|
+
fs.renameSync(tmpPath, filePath);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function cleanupRuntimeTmpFiles(runtimeDir, options = {}) {
|
|
72
|
+
if (!fs.existsSync(runtimeDir)) return;
|
|
73
|
+
const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
|
|
74
|
+
const minAgeMs = Number.isFinite(options.tmpCleanupAgeMs)
|
|
75
|
+
? options.tmpCleanupAgeMs
|
|
76
|
+
: DEFAULT_TMP_CLEANUP_AGE_MS;
|
|
77
|
+
const files = fs.readdirSync(runtimeDir).filter((name) => name.endsWith(".tmp"));
|
|
78
|
+
for (const file of files) {
|
|
79
|
+
const target = path.join(runtimeDir, file);
|
|
80
|
+
try {
|
|
81
|
+
const stat = fs.statSync(target);
|
|
82
|
+
const ageMs = Math.max(0, nowMs - stat.mtimeMs);
|
|
83
|
+
if (ageMs < minAgeMs) continue;
|
|
84
|
+
fs.unlinkSync(target);
|
|
85
|
+
} catch {
|
|
86
|
+
// Ignore temp cleanup failures.
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function parseDaemonPid(value, fallback = null) {
|
|
92
|
+
if (value === null || value === undefined || value === "") return fallback;
|
|
93
|
+
const parsed = Number.parseInt(value, 10);
|
|
94
|
+
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
|
|
95
|
+
return parsed;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isPidAlive(pid) {
|
|
99
|
+
if (!Number.isFinite(pid) || pid <= 0) return false;
|
|
100
|
+
try {
|
|
101
|
+
process.kill(pid, 0);
|
|
102
|
+
return true;
|
|
103
|
+
} catch (err) {
|
|
104
|
+
if (err && err.code === "EPERM") return true;
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isSocketAlive(socketPath) {
|
|
110
|
+
if (!socketPath || typeof socketPath !== "string") return false;
|
|
111
|
+
if (!fs.existsSync(socketPath)) return false;
|
|
112
|
+
try {
|
|
113
|
+
const stat = fs.statSync(socketPath);
|
|
114
|
+
return stat.isSocket();
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function normalizeStatus(value, fallback = "running") {
|
|
121
|
+
const raw = String(value || "").trim().toLowerCase();
|
|
122
|
+
if (raw === "running" || raw === "stale" || raw === "stopped") return raw;
|
|
123
|
+
return fallback;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function normalizeRuntimeEntry(entry = {}, fallbackProjectRoot = "") {
|
|
127
|
+
const canonicalRoot = canonicalizeForRecord(entry.project_root || fallbackProjectRoot);
|
|
128
|
+
const knownProjectId = String(entry.project_id || "").trim();
|
|
129
|
+
const projectId = /^[a-f0-9]{12}$/.test(knownProjectId)
|
|
130
|
+
? knownProjectId
|
|
131
|
+
: buildProjectId(canonicalRoot);
|
|
132
|
+
const paths = getUfooPaths(canonicalRoot);
|
|
133
|
+
return {
|
|
134
|
+
version: 1,
|
|
135
|
+
project_id: projectId,
|
|
136
|
+
project_root: canonicalRoot,
|
|
137
|
+
project_name: String(entry.project_name || path.basename(canonicalRoot) || canonicalRoot),
|
|
138
|
+
daemon_pid: parseDaemonPid(entry.daemon_pid, null),
|
|
139
|
+
socket_path: String(entry.socket_path || paths.ufooSock),
|
|
140
|
+
status: normalizeStatus(entry.status, "running"),
|
|
141
|
+
last_seen: normalizeIsoTimestamp(entry.last_seen),
|
|
142
|
+
last_switch_at: entry.last_switch_at ? normalizeIsoTimestamp(entry.last_switch_at) : undefined,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function readProjectRuntimeByRoot(projectRoot, options = {}) {
|
|
147
|
+
const filePath = runtimeFilePathByProjectRoot(projectRoot, options);
|
|
148
|
+
if (!fs.existsSync(filePath)) return null;
|
|
149
|
+
const parsed = readJsonFileSafe(filePath);
|
|
150
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
151
|
+
try {
|
|
152
|
+
return normalizeRuntimeEntry(parsed, projectRoot);
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function upsertProjectRuntime(entry = {}, options = {}) {
|
|
159
|
+
const projectRoot = entry.projectRoot || entry.project_root;
|
|
160
|
+
if (!projectRoot) throw new Error("projectRoot is required");
|
|
161
|
+
|
|
162
|
+
const existing = readProjectRuntimeByRoot(projectRoot, options) || {};
|
|
163
|
+
const normalized = normalizeRuntimeEntry({
|
|
164
|
+
...existing,
|
|
165
|
+
...entry,
|
|
166
|
+
project_root: projectRoot,
|
|
167
|
+
project_name: entry.projectName || entry.project_name || existing.project_name,
|
|
168
|
+
daemon_pid: parseDaemonPid(entry.daemonPid ?? entry.daemon_pid, existing.daemon_pid),
|
|
169
|
+
socket_path: entry.socketPath || entry.socket_path || existing.socket_path,
|
|
170
|
+
status: normalizeStatus(entry.status, existing.status || "running"),
|
|
171
|
+
last_seen: normalizeIsoTimestamp(entry.lastSeen || entry.last_seen || new Date().toISOString()),
|
|
172
|
+
last_switch_at: entry.lastSwitchAt || entry.last_switch_at || existing.last_switch_at,
|
|
173
|
+
}, projectRoot);
|
|
174
|
+
|
|
175
|
+
const filePath = runtimeFilePathByProjectId(normalized.project_id, options);
|
|
176
|
+
writeJsonAtomic(filePath, normalized);
|
|
177
|
+
return normalized;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function markProjectStopped(projectRoot, options = {}) {
|
|
181
|
+
if (!projectRoot) return null;
|
|
182
|
+
const existing = readProjectRuntimeByRoot(projectRoot, options);
|
|
183
|
+
const paths = getUfooPaths(canonicalizeForRecord(projectRoot));
|
|
184
|
+
return upsertProjectRuntime({
|
|
185
|
+
projectRoot,
|
|
186
|
+
projectName: existing ? existing.project_name : path.basename(projectRoot),
|
|
187
|
+
daemonPid: existing ? existing.daemon_pid : null,
|
|
188
|
+
socketPath: existing ? existing.socket_path : paths.ufooSock,
|
|
189
|
+
status: "stopped",
|
|
190
|
+
lastSeen: new Date().toISOString(),
|
|
191
|
+
lastSwitchAt: existing ? existing.last_switch_at : undefined,
|
|
192
|
+
}, options);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function validateProjectRuntime(entry = {}, options = {}) {
|
|
196
|
+
if (!entry || typeof entry !== "object") return null;
|
|
197
|
+
const staleTtlMs = Number.isFinite(options.staleTtlMs) ? options.staleTtlMs : DEFAULT_STALE_TTL_MS;
|
|
198
|
+
const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
|
|
199
|
+
const pidAlive = isPidAlive(parseDaemonPid(entry.daemon_pid, null));
|
|
200
|
+
const socketAlive = isSocketAlive(entry.socket_path);
|
|
201
|
+
const running = pidAlive && socketAlive;
|
|
202
|
+
|
|
203
|
+
const parsedLastSeen = new Date(entry.last_seen);
|
|
204
|
+
const lastSeenMs = Number.isNaN(parsedLastSeen.getTime()) ? null : parsedLastSeen.getTime();
|
|
205
|
+
const ageMs = lastSeenMs === null ? null : Math.max(0, nowMs - lastSeenMs);
|
|
206
|
+
|
|
207
|
+
let status = normalizeStatus(entry.status, "running");
|
|
208
|
+
if (running) {
|
|
209
|
+
status = "running";
|
|
210
|
+
} else if (status === "stopped") {
|
|
211
|
+
// Respect explicit stop state even if pid/socket checks are unavailable.
|
|
212
|
+
status = "stopped";
|
|
213
|
+
} else if (ageMs === null || ageMs > staleTtlMs) {
|
|
214
|
+
status = "stale";
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
...entry,
|
|
219
|
+
status,
|
|
220
|
+
validation: {
|
|
221
|
+
pid_alive: pidAlive,
|
|
222
|
+
socket_alive: socketAlive,
|
|
223
|
+
stale_ttl_ms: staleTtlMs,
|
|
224
|
+
age_ms: ageMs,
|
|
225
|
+
validated_at: new Date(nowMs).toISOString(),
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function listProjectRuntimes(options = {}) {
|
|
231
|
+
const runtimeDir = resolveRuntimeDir(options);
|
|
232
|
+
if (!fs.existsSync(runtimeDir)) return [];
|
|
233
|
+
if (options.cleanupTmp === true) {
|
|
234
|
+
cleanupRuntimeTmpFiles(runtimeDir, options);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const files = fs.readdirSync(runtimeDir)
|
|
238
|
+
.filter((name) => name.endsWith(".json"))
|
|
239
|
+
.sort();
|
|
240
|
+
|
|
241
|
+
const rows = [];
|
|
242
|
+
for (const file of files) {
|
|
243
|
+
const parsed = readJsonFileSafe(path.join(runtimeDir, file));
|
|
244
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
245
|
+
try {
|
|
246
|
+
const normalized = normalizeRuntimeEntry(parsed);
|
|
247
|
+
rows.push(options.validate === false ? normalized : validateProjectRuntime(normalized, options));
|
|
248
|
+
} catch {
|
|
249
|
+
// Ignore malformed runtime entries.
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
rows.sort((a, b) => {
|
|
254
|
+
const aSeen = Date.parse(a.last_seen || 0) || 0;
|
|
255
|
+
const bSeen = Date.parse(b.last_seen || 0) || 0;
|
|
256
|
+
return bSeen - aSeen;
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
return rows;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function getCurrentProjectRuntime(projectRoot, options = {}) {
|
|
263
|
+
const runtime = readProjectRuntimeByRoot(projectRoot, options);
|
|
264
|
+
if (!runtime) return null;
|
|
265
|
+
if (options.validate === false) return runtime;
|
|
266
|
+
return validateProjectRuntime(runtime, options);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = {
|
|
270
|
+
DEFAULT_STALE_TTL_MS,
|
|
271
|
+
resolveRuntimeDir,
|
|
272
|
+
runtimeFilePathByProjectId,
|
|
273
|
+
runtimeFilePathByProjectRoot,
|
|
274
|
+
upsertProjectRuntime,
|
|
275
|
+
markProjectStopped,
|
|
276
|
+
listProjectRuntimes,
|
|
277
|
+
getCurrentProjectRuntime,
|
|
278
|
+
validateProjectRuntime,
|
|
279
|
+
};
|