@moberg_hr/work-tree 1.16.0 → 2.0.1
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/README.md +56 -142
- package/dist/answer-2J4XLIP7.js +63 -0
- package/dist/answer-2J4XLIP7.js.map +1 -0
- package/dist/attach-CZKRNPAJ.js +59 -0
- package/dist/attach-CZKRNPAJ.js.map +1 -0
- package/dist/bin.js +26 -11924
- package/dist/bin.js.map +1 -1
- package/dist/block-RAIDCJ4F.js +84 -0
- package/dist/block-RAIDCJ4F.js.map +1 -0
- package/dist/broadcast-BSI5NDDB.js +104 -0
- package/dist/broadcast-BSI5NDDB.js.map +1 -0
- package/dist/catchup-VVOPL2S5.js +51 -0
- package/dist/catchup-VVOPL2S5.js.map +1 -0
- package/dist/chunk-3JWTO5VZ.js +135 -0
- package/dist/chunk-3JWTO5VZ.js.map +1 -0
- package/dist/chunk-4BOK2GXL.js +210 -0
- package/dist/chunk-4BOK2GXL.js.map +1 -0
- package/dist/chunk-5QK7GB5K.js +112 -0
- package/dist/chunk-5QK7GB5K.js.map +1 -0
- package/dist/chunk-6AQRYLOB.js +16 -0
- package/dist/chunk-6AQRYLOB.js.map +1 -0
- package/dist/chunk-6FTIY5M6.js +120 -0
- package/dist/chunk-6FTIY5M6.js.map +1 -0
- package/dist/chunk-6H3MLDGG.js +48 -0
- package/dist/chunk-6H3MLDGG.js.map +1 -0
- package/dist/chunk-77XFJQGC.js +103 -0
- package/dist/chunk-77XFJQGC.js.map +1 -0
- package/dist/chunk-7HEB6SQS.js +257 -0
- package/dist/chunk-7HEB6SQS.js.map +1 -0
- package/dist/chunk-7NAXFBFI.js +206 -0
- package/dist/chunk-7NAXFBFI.js.map +1 -0
- package/dist/chunk-7NCW3LUT.js +358 -0
- package/dist/chunk-7NCW3LUT.js.map +1 -0
- package/dist/chunk-7OLPI334.js +537 -0
- package/dist/chunk-7OLPI334.js.map +1 -0
- package/dist/chunk-ABQYKTG4.js +38 -0
- package/dist/chunk-ABQYKTG4.js.map +1 -0
- package/dist/chunk-AH5TM3NB.js +21 -0
- package/dist/chunk-AH5TM3NB.js.map +1 -0
- package/dist/chunk-AKMPF72Y.js +274 -0
- package/dist/chunk-AKMPF72Y.js.map +1 -0
- package/dist/chunk-BR6OPEE4.js +162 -0
- package/dist/chunk-BR6OPEE4.js.map +1 -0
- package/dist/chunk-C2BK6EBN.js +162 -0
- package/dist/chunk-C2BK6EBN.js.map +1 -0
- package/dist/chunk-C2THFSXA.js +37 -0
- package/dist/chunk-C2THFSXA.js.map +1 -0
- package/dist/chunk-C7W5TMFB.js +308 -0
- package/dist/chunk-C7W5TMFB.js.map +1 -0
- package/dist/chunk-CLGVSX36.js +668 -0
- package/dist/chunk-CLGVSX36.js.map +1 -0
- package/dist/chunk-CVAVYDXO.js +295 -0
- package/dist/chunk-CVAVYDXO.js.map +1 -0
- package/dist/chunk-DW4JPVXB.js +41 -0
- package/dist/chunk-DW4JPVXB.js.map +1 -0
- package/dist/chunk-FPKERDK7.js +142 -0
- package/dist/chunk-FPKERDK7.js.map +1 -0
- package/dist/chunk-FR3EWVXI.js +188 -0
- package/dist/chunk-FR3EWVXI.js.map +1 -0
- package/dist/chunk-H5LKMR45.js +117 -0
- package/dist/chunk-H5LKMR45.js.map +1 -0
- package/dist/chunk-HIZBWYPL.js +267 -0
- package/dist/chunk-HIZBWYPL.js.map +1 -0
- package/dist/chunk-HSICXDMZ.js +41 -0
- package/dist/chunk-HSICXDMZ.js.map +1 -0
- package/dist/chunk-HUXS3VAI.js +90 -0
- package/dist/chunk-HUXS3VAI.js.map +1 -0
- package/dist/chunk-HWUINPIL.js +151 -0
- package/dist/chunk-HWUINPIL.js.map +1 -0
- package/dist/chunk-IXKVCR4Y.js +487 -0
- package/dist/chunk-IXKVCR4Y.js.map +1 -0
- package/dist/chunk-JNBYNRFS.js +54 -0
- package/dist/chunk-JNBYNRFS.js.map +1 -0
- package/dist/chunk-JYTMT5DF.js +421 -0
- package/dist/chunk-JYTMT5DF.js.map +1 -0
- package/dist/chunk-KGZ6OZ2T.js +102 -0
- package/dist/chunk-KGZ6OZ2T.js.map +1 -0
- package/dist/chunk-LMIEEDDC.js +9 -0
- package/dist/chunk-LMIEEDDC.js.map +1 -0
- package/dist/chunk-LNHSBM4L.js +26 -0
- package/dist/chunk-LNHSBM4L.js.map +1 -0
- package/dist/chunk-M4FVCAT6.js +2406 -0
- package/dist/chunk-M4FVCAT6.js.map +1 -0
- package/dist/chunk-N4EYQKSM.js +104 -0
- package/dist/chunk-N4EYQKSM.js.map +1 -0
- package/dist/chunk-NDWSLQPB.js +112 -0
- package/dist/chunk-NDWSLQPB.js.map +1 -0
- package/dist/chunk-O3QTWVSK.js +323 -0
- package/dist/chunk-O3QTWVSK.js.map +1 -0
- package/dist/chunk-P3BL4EOP.js +37 -0
- package/dist/chunk-P3BL4EOP.js.map +1 -0
- package/dist/chunk-PN44M5EE.js +887 -0
- package/dist/chunk-PN44M5EE.js.map +1 -0
- package/dist/chunk-Q6WZCO45.js +47 -0
- package/dist/chunk-Q6WZCO45.js.map +1 -0
- package/dist/chunk-QBAZG4CY.js +230 -0
- package/dist/chunk-QBAZG4CY.js.map +1 -0
- package/dist/chunk-R2LN3JJJ.js +132 -0
- package/dist/chunk-R2LN3JJJ.js.map +1 -0
- package/dist/chunk-RCYI7SRA.js +15 -0
- package/dist/chunk-RCYI7SRA.js.map +1 -0
- package/dist/chunk-RYNBBSLY.js +67 -0
- package/dist/chunk-RYNBBSLY.js.map +1 -0
- package/dist/chunk-S5HJT7CM.js +30 -0
- package/dist/chunk-S5HJT7CM.js.map +1 -0
- package/dist/chunk-SNAQOHNL.js +285 -0
- package/dist/chunk-SNAQOHNL.js.map +1 -0
- package/dist/chunk-SOCPIHCS.js +181 -0
- package/dist/chunk-SOCPIHCS.js.map +1 -0
- package/dist/chunk-TUC4QY4O.js +147 -0
- package/dist/chunk-TUC4QY4O.js.map +1 -0
- package/dist/chunk-TUFQJXXO.js +19 -0
- package/dist/chunk-TUFQJXXO.js.map +1 -0
- package/dist/chunk-UFY7C5PP.js +90 -0
- package/dist/chunk-UFY7C5PP.js.map +1 -0
- package/dist/chunk-UQ35KLHH.js +34 -0
- package/dist/chunk-UQ35KLHH.js.map +1 -0
- package/dist/chunk-VJ7SVDED.js +177 -0
- package/dist/chunk-VJ7SVDED.js.map +1 -0
- package/dist/chunk-VJNSIDOA.js +23 -0
- package/dist/chunk-VJNSIDOA.js.map +1 -0
- package/dist/chunk-WF5SBVPZ.js +190 -0
- package/dist/chunk-WF5SBVPZ.js.map +1 -0
- package/dist/chunk-WMJIU3YW.js +29 -0
- package/dist/chunk-WMJIU3YW.js.map +1 -0
- package/dist/chunk-XJDEROHY.js +19 -0
- package/dist/chunk-XJDEROHY.js.map +1 -0
- package/dist/chunk-YKODIG22.js +221 -0
- package/dist/chunk-YKODIG22.js.map +1 -0
- package/dist/chunk-YNKWLC45.js +122 -0
- package/dist/chunk-YNKWLC45.js.map +1 -0
- package/dist/chunk-YZDD5YGE.js +165 -0
- package/dist/chunk-YZDD5YGE.js.map +1 -0
- package/dist/chunk-YZWADOEW.js +151 -0
- package/dist/chunk-YZWADOEW.js.map +1 -0
- package/dist/chunk-ZJN5RWZD.js +76 -0
- package/dist/chunk-ZJN5RWZD.js.map +1 -0
- package/dist/chunk-ZSHWP2VS.js +22 -0
- package/dist/chunk-ZSHWP2VS.js.map +1 -0
- package/dist/chunk-ZXPYWZL5.js +307 -0
- package/dist/chunk-ZXPYWZL5.js.map +1 -0
- package/dist/cleanup-LDBGWEKZ.js +192 -0
- package/dist/cleanup-LDBGWEKZ.js.map +1 -0
- package/dist/cli-UATB4RM2.js +18 -0
- package/dist/cli-UATB4RM2.js.map +1 -0
- package/dist/command-hook-installer-SGEJTZ2Y.js +204 -0
- package/dist/command-hook-installer-SGEJTZ2Y.js.map +1 -0
- package/dist/completion-MXX5TRIV.js +118 -0
- package/dist/completion-MXX5TRIV.js.map +1 -0
- package/dist/config-IEIU7A66.js +410 -0
- package/dist/config-IEIU7A66.js.map +1 -0
- package/dist/console-reporter-XU6VFUZE.js +10 -0
- package/dist/console-reporter-XU6VFUZE.js.map +1 -0
- package/dist/diff-K47HB6SA.js +582 -0
- package/dist/diff-K47HB6SA.js.map +1 -0
- package/dist/digest-FBZTBXQO.js +100 -0
- package/dist/digest-FBZTBXQO.js.map +1 -0
- package/dist/fork-BKI5UNNS.js +120 -0
- package/dist/fork-BKI5UNNS.js.map +1 -0
- package/dist/hook-SLMZT5OV.js +220 -0
- package/dist/hook-SLMZT5OV.js.map +1 -0
- package/dist/hydrate-Y2AAMZTA.js +121 -0
- package/dist/hydrate-Y2AAMZTA.js.map +1 -0
- package/dist/init-7ESFTYZC.js +187 -0
- package/dist/init-7ESFTYZC.js.map +1 -0
- package/dist/install-skills-O34BHFHD.js +14 -0
- package/dist/install-skills-O34BHFHD.js.map +1 -0
- package/dist/install-skills-bin.js +12 -0
- package/dist/install-skills-bin.js.map +1 -0
- package/dist/list-KEF73NLQ.js +126 -0
- package/dist/list-KEF73NLQ.js.map +1 -0
- package/dist/move-FKT2P5LY.js +313 -0
- package/dist/move-FKT2P5LY.js.map +1 -0
- package/dist/note-WGM6LCP2.js +78 -0
- package/dist/note-WGM6LCP2.js.map +1 -0
- package/dist/overlaps-FRLMMIGC.js +56 -0
- package/dist/overlaps-FRLMMIGC.js.map +1 -0
- package/dist/pin-MQ5ZE37R.js +45 -0
- package/dist/pin-MQ5ZE37R.js.map +1 -0
- package/dist/pr-527S5HXB.js +122 -0
- package/dist/pr-527S5HXB.js.map +1 -0
- package/dist/prune-AIS5YEXP.js +92 -0
- package/dist/prune-AIS5YEXP.js.map +1 -0
- package/dist/pty-host-RWIS55N4.js +826 -0
- package/dist/pty-host-RWIS55N4.js.map +1 -0
- package/dist/read-AP6T3ZGN.js +57 -0
- package/dist/read-AP6T3ZGN.js.map +1 -0
- package/dist/recent-IE3LYQ65.js +111 -0
- package/dist/recent-IE3LYQ65.js.map +1 -0
- package/dist/remove-YGUTSKZP.js +108 -0
- package/dist/remove-YGUTSKZP.js.map +1 -0
- package/dist/report-KM4OZCZB.js +16 -0
- package/dist/report-KM4OZCZB.js.map +1 -0
- package/dist/resume-UUP6R2IE.js +81 -0
- package/dist/resume-UUP6R2IE.js.map +1 -0
- package/dist/run-V4755W7C.js +263 -0
- package/dist/run-V4755W7C.js.map +1 -0
- package/dist/screen-DNX4K23V.js +58 -0
- package/dist/screen-DNX4K23V.js.map +1 -0
- package/dist/search-3JZXLCR2.js +46 -0
- package/dist/search-3JZXLCR2.js.map +1 -0
- package/dist/section-TXLC5XO3.js +79 -0
- package/dist/section-TXLC5XO3.js.map +1 -0
- package/dist/send-6X46WZLC.js +87 -0
- package/dist/send-6X46WZLC.js.map +1 -0
- package/dist/sessions-T3QDTNP7.js +135 -0
- package/dist/sessions-T3QDTNP7.js.map +1 -0
- package/dist/snooze-KYSFXLPY.js +65 -0
- package/dist/snooze-KYSFXLPY.js.map +1 -0
- package/dist/start-SQSDQK4F.js +56 -0
- package/dist/start-SQSDQK4F.js.map +1 -0
- package/dist/state-4DFV6SHG.js +147 -0
- package/dist/state-4DFV6SHG.js.map +1 -0
- package/dist/status-H5OW4LYE.js +118 -0
- package/dist/status-H5OW4LYE.js.map +1 -0
- package/dist/stop-HC7XPSSP.js +45 -0
- package/dist/stop-HC7XPSSP.js.map +1 -0
- package/dist/sync-ITK5UYGM.js +96 -0
- package/dist/sync-ITK5UYGM.js.map +1 -0
- package/dist/time-GN6B4QD6.js +111 -0
- package/dist/time-GN6B4QD6.js.map +1 -0
- package/dist/todo-LWMQY6XW.js +152 -0
- package/dist/todo-LWMQY6XW.js.map +1 -0
- package/dist/tree-7BMORJ6J.js +235 -0
- package/dist/tree-7BMORJ6J.js.map +1 -0
- package/dist/update-6LQNLRA4.js +57 -0
- package/dist/update-6LQNLRA4.js.map +1 -0
- package/dist/wait-MZOZQ3CI.js +57 -0
- package/dist/wait-MZOZQ3CI.js.map +1 -0
- package/dist/wd-bin.js +21 -11912
- package/dist/wd-bin.js.map +1 -1
- package/dist/web/assets/PtyView-BrP-ENHg.css +1 -0
- package/dist/web/assets/PtyView-DYvawzWb.js +90 -0
- package/dist/web/assets/PtyView-DYvawzWb.js.map +1 -0
- package/dist/web/assets/index-C5lJhIwK.js +116 -0
- package/dist/web/assets/index-C5lJhIwK.js.map +1 -0
- package/dist/web/assets/index-L8mjakHP.css +1 -0
- package/dist/web/index.html +3 -5
- package/dist/web-IC3P7EHZ.js +7689 -0
- package/dist/web-IC3P7EHZ.js.map +1 -0
- package/npm-shrinkwrap.json +6947 -0
- package/package.json +52 -34
- package/plugins/work-tree/.claude-plugin/plugin.json +1 -1
- package/plugins/work-tree/skills/wd-review/SKILL.md +4 -4
- package/plugins/work-tree/skills/work-sessions/SKILL.md +62 -0
- package/scripts/postinstall.mjs +15 -45
- package/dist/web/assets/index-B9H3vCtL.js +0 -107
- package/dist/web/assets/index-B9H3vCtL.js.map +0 -1
- package/dist/web/assets/index-BseMpW5i.css +0 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
getConfigDir
|
|
4
|
+
} from "./chunk-7HEB6SQS.js";
|
|
5
|
+
|
|
6
|
+
// src/core/platform/logger.ts
|
|
7
|
+
import fs from "fs";
|
|
8
|
+
import path from "path";
|
|
9
|
+
var maxLogSize = 5 * 1024 * 1024;
|
|
10
|
+
var logPath = null;
|
|
11
|
+
var logFd = null;
|
|
12
|
+
var logBytes = 0;
|
|
13
|
+
function rotate(file) {
|
|
14
|
+
const prev = file + ".1";
|
|
15
|
+
try {
|
|
16
|
+
fs.unlinkSync(prev);
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
fs.renameSync(file, prev);
|
|
21
|
+
} catch {
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function ensureLog() {
|
|
25
|
+
if (logFd !== null) return logFd;
|
|
26
|
+
try {
|
|
27
|
+
const dir = getConfigDir();
|
|
28
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
29
|
+
logPath = path.join(dir, "debug.log");
|
|
30
|
+
let size = 0;
|
|
31
|
+
try {
|
|
32
|
+
size = fs.statSync(logPath).size;
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
if (size > maxLogSize) {
|
|
36
|
+
rotate(logPath);
|
|
37
|
+
size = 0;
|
|
38
|
+
}
|
|
39
|
+
logFd = fs.openSync(logPath, "a");
|
|
40
|
+
logBytes = size;
|
|
41
|
+
return logFd;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function timestamp() {
|
|
47
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
48
|
+
}
|
|
49
|
+
function stripAnsi(str) {
|
|
50
|
+
return str.replace(/\x1b\[[0-9;]*m/g, "");
|
|
51
|
+
}
|
|
52
|
+
function debugLog(level, ...args) {
|
|
53
|
+
const fd = ensureLog();
|
|
54
|
+
if (fd === null) return;
|
|
55
|
+
const msg = args.map((a) => typeof a === "string" ? stripAnsi(a) : JSON.stringify(a)).join(" ");
|
|
56
|
+
const line = `${timestamp()} [${level}] ${msg}
|
|
57
|
+
`;
|
|
58
|
+
try {
|
|
59
|
+
fs.writeSync(fd, line);
|
|
60
|
+
} catch {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
logBytes += Buffer.byteLength(line);
|
|
64
|
+
if (logBytes > maxLogSize && logPath) {
|
|
65
|
+
closeLog();
|
|
66
|
+
rotate(logPath);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function installConsoleLogger() {
|
|
70
|
+
const origLog = console.log.bind(console);
|
|
71
|
+
const origError = console.error.bind(console);
|
|
72
|
+
const origWarn = console.warn.bind(console);
|
|
73
|
+
console.log = (...args) => {
|
|
74
|
+
origLog(...args);
|
|
75
|
+
debugLog("INFO", ...args);
|
|
76
|
+
};
|
|
77
|
+
console.error = (...args) => {
|
|
78
|
+
origError(...args);
|
|
79
|
+
debugLog("ERROR", ...args);
|
|
80
|
+
};
|
|
81
|
+
console.warn = (...args) => {
|
|
82
|
+
origWarn(...args);
|
|
83
|
+
debugLog("WARN", ...args);
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function debug(...args) {
|
|
87
|
+
debugLog("DEBUG", ...args);
|
|
88
|
+
}
|
|
89
|
+
function closeLog() {
|
|
90
|
+
if (logFd !== null) {
|
|
91
|
+
try {
|
|
92
|
+
fs.closeSync(logFd);
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
95
|
+
logFd = null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export {
|
|
100
|
+
debugLog,
|
|
101
|
+
installConsoleLogger,
|
|
102
|
+
debug
|
|
103
|
+
};
|
|
104
|
+
//# sourceMappingURL=chunk-N4EYQKSM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/platform/logger.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from './config.js';\n\nlet maxLogSize = 5 * 1024 * 1024; // 5MB, then debug.log → debug.log.1\n\nlet logPath: string | null = null;\n/** A plain file descriptor, written synchronously: a line is on disk when\n * debugLog returns (a buffered stream lost the last lines on exit), and\n * rotation can close the file before renaming it — Windows refuses to\n * rename a file that is still open. */\nlet logFd: number | null = null;\n/** Bytes in the current file: its size at open plus what we wrote since. */\nlet logBytes = 0;\n\n/** Tests shrink the cap to exercise rotation. */\nexport function setMaxLogSizeForTests(bytes: number): void {\n maxLogSize = bytes;\n}\n\nfunction rotate(file: string): void {\n const prev = file + '.1';\n try {\n fs.unlinkSync(prev);\n } catch {\n /* */\n }\n try {\n fs.renameSync(file, prev);\n } catch {\n /* another process has it open; next time */\n }\n}\n\nfunction ensureLog(): number | null {\n if (logFd !== null) return logFd;\n try {\n const dir = getConfigDir();\n fs.mkdirSync(dir, { recursive: true });\n logPath = path.join(dir, 'debug.log');\n let size = 0;\n try {\n size = fs.statSync(logPath).size;\n } catch {\n /* file doesn't exist yet */\n }\n if (size > maxLogSize) {\n rotate(logPath);\n size = 0;\n }\n logFd = fs.openSync(logPath, 'a');\n logBytes = size;\n return logFd;\n } catch {\n return null;\n }\n}\n\nfunction timestamp(): string {\n return new Date().toISOString();\n}\n\n// Strip ANSI escape codes for clean log output\nfunction stripAnsi(str: string): string {\n return str.replace(/\\x1b\\[[0-9;]*m/g, '');\n}\n\nexport function debugLog(level: 'INFO' | 'ERROR' | 'DEBUG' | 'WARN', ...args: unknown[]): void {\n const fd = ensureLog();\n if (fd === null) return;\n const msg = args.map((a) => (typeof a === 'string' ? stripAnsi(a) : JSON.stringify(a))).join(' ');\n const line = `${timestamp()} [${level}] ${msg}\\n`;\n try {\n fs.writeSync(fd, line);\n } catch {\n return; // best effort: logging must never break the host\n }\n logBytes += Buffer.byteLength(line);\n // Rotate while running too: work web and the PTY host run for days, and\n // the cap used to be checked only when a process opened the log.\n if (logBytes > maxLogSize && logPath) {\n closeLog();\n rotate(logPath);\n }\n}\n\n/**\n * Patch console.log and console.error to also write to the debug log.\n * Call once at startup.\n */\nexport function installConsoleLogger(): void {\n const origLog = console.log.bind(console);\n const origError = console.error.bind(console);\n const origWarn = console.warn.bind(console);\n\n console.log = (...args: unknown[]) => {\n origLog(...args);\n debugLog('INFO', ...args);\n };\n\n console.error = (...args: unknown[]) => {\n origError(...args);\n debugLog('ERROR', ...args);\n };\n\n console.warn = (...args: unknown[]) => {\n origWarn(...args);\n debugLog('WARN', ...args);\n };\n}\n\n/** Write a debug-only message (not shown to user). */\nexport function debug(...args: unknown[]): void {\n debugLog('DEBUG', ...args);\n}\n\n/** Get the log file path. */\nexport function getLogPath(): string {\n ensureLog();\n return logPath ?? path.join(getConfigDir(), 'debug.log');\n}\n\n/** Flush and close the log stream. */\nexport function closeLog(): void {\n if (logFd !== null) {\n try {\n fs.closeSync(logFd);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U,IAAI,IAAI;AAAA,EACvB,QAAQ;AACN;AAAA,EACF;AACA,cAAY,OAAO,WAAW,IAAI;AAGlC,MAAI,WAAW,cAAc,SAAS;AACpC,aAAS;AACT,WAAO,OAAO;AAAA,EAChB;AACF;AAMO,SAAS,uBAA6B;AAC3C,QAAM,UAAU,QAAQ,IAAI,KAAK,OAAO;AACxC,QAAM,YAAY,QAAQ,MAAM,KAAK,OAAO;AAC5C,QAAM,WAAW,QAAQ,KAAK,KAAK,OAAO;AAE1C,UAAQ,MAAM,IAAI,SAAoB;AACpC,YAAQ,GAAG,IAAI;AACf,aAAS,QAAQ,GAAG,IAAI;AAAA,EAC1B;AAEA,UAAQ,QAAQ,IAAI,SAAoB;AACtC,cAAU,GAAG,IAAI;AACjB,aAAS,SAAS,GAAG,IAAI;AAAA,EAC3B;AAEA,UAAQ,OAAO,IAAI,SAAoB;AACrC,aAAS,GAAG,IAAI;AAChB,aAAS,QAAQ,GAAG,IAAI;AAAA,EAC1B;AACF;AAGO,SAAS,SAAS,MAAuB;AAC9C,WAAS,SAAS,GAAG,IAAI;AAC3B;AASO,SAAS,WAAiB;AAC/B,MAAI,UAAU,MAAM;AAClB,QAAI;AACF,SAAG,UAAU,KAAK;AAAA,IACpB,QAAQ;AAAA,IAER;AACA,YAAQ;AAAA,EACV;AACF;","names":[]}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
defaultRunner
|
|
4
|
+
} from "./chunk-ZXPYWZL5.js";
|
|
5
|
+
|
|
6
|
+
// src/core/cleanup/build-folders.ts
|
|
7
|
+
import fs from "fs";
|
|
8
|
+
import path from "path";
|
|
9
|
+
var BUILD_DIR_NAMES = /* @__PURE__ */ new Set([
|
|
10
|
+
"node_modules",
|
|
11
|
+
"bin",
|
|
12
|
+
"obj",
|
|
13
|
+
"dist",
|
|
14
|
+
"build",
|
|
15
|
+
"out",
|
|
16
|
+
"target",
|
|
17
|
+
"coverage",
|
|
18
|
+
".next",
|
|
19
|
+
".nuxt",
|
|
20
|
+
".turbo",
|
|
21
|
+
".vite",
|
|
22
|
+
".angular",
|
|
23
|
+
".parcel-cache",
|
|
24
|
+
".svelte-kit",
|
|
25
|
+
".gradle",
|
|
26
|
+
".pytest_cache",
|
|
27
|
+
"__pycache__"
|
|
28
|
+
]);
|
|
29
|
+
var SKIP = /* @__PURE__ */ new Set([".git"]);
|
|
30
|
+
async function candidateBuildDirs(root, maxDepth = 4) {
|
|
31
|
+
const found = [];
|
|
32
|
+
const walk = async (dir, depth) => {
|
|
33
|
+
let entries;
|
|
34
|
+
try {
|
|
35
|
+
entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
36
|
+
} catch {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (depth > 0 && entries.some((e) => e.name === ".git")) return;
|
|
40
|
+
for (const e of entries) {
|
|
41
|
+
if (!e.isDirectory() || SKIP.has(e.name)) continue;
|
|
42
|
+
const full = path.join(dir, e.name);
|
|
43
|
+
if (BUILD_DIR_NAMES.has(e.name)) found.push(full);
|
|
44
|
+
else if (depth < maxDepth) await walk(full, depth + 1);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
await walk(root, 0);
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
async function ignoredByGit(root, dirs, run = defaultRunner) {
|
|
51
|
+
if (dirs.length === 0) return /* @__PURE__ */ new Set();
|
|
52
|
+
const rel = dirs.map((d) => path.relative(root, d).replace(/\\/g, "/"));
|
|
53
|
+
const r = await run("git", ["-C", root, "check-ignore", "--", ...rel], root);
|
|
54
|
+
if (r.code !== 0) return /* @__PURE__ */ new Set();
|
|
55
|
+
const ignored = new Set(
|
|
56
|
+
r.stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
|
|
57
|
+
);
|
|
58
|
+
return new Set(dirs.filter((_, i) => ignored.has(rel[i])));
|
|
59
|
+
}
|
|
60
|
+
async function folderBytes(dir) {
|
|
61
|
+
let total = 0;
|
|
62
|
+
const stack = [dir];
|
|
63
|
+
while (stack.length) {
|
|
64
|
+
const d = stack.pop();
|
|
65
|
+
let entries;
|
|
66
|
+
try {
|
|
67
|
+
entries = await fs.promises.readdir(d, { withFileTypes: true });
|
|
68
|
+
} catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
await Promise.all(
|
|
72
|
+
entries.map(async (e) => {
|
|
73
|
+
const full = path.join(d, e.name);
|
|
74
|
+
if (e.isDirectory()) stack.push(full);
|
|
75
|
+
else if (e.isFile()) {
|
|
76
|
+
try {
|
|
77
|
+
total += (await fs.promises.lstat(full)).size;
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return total;
|
|
85
|
+
}
|
|
86
|
+
async function buildFoldersOf(root, run) {
|
|
87
|
+
const dirs = await ignoredByGit(root, await candidateBuildDirs(root), run);
|
|
88
|
+
const out = [];
|
|
89
|
+
for (const d of dirs) out.push({ path: d, bytes: await folderBytes(d) });
|
|
90
|
+
return out.sort((a, b) => b.bytes - a.bytes);
|
|
91
|
+
}
|
|
92
|
+
async function clearBuildFolders(root, run) {
|
|
93
|
+
const dirs = await ignoredByGit(root, await candidateBuildDirs(root), run);
|
|
94
|
+
const removed = [];
|
|
95
|
+
const failed = [];
|
|
96
|
+
for (const d of dirs) {
|
|
97
|
+
try {
|
|
98
|
+
await fs.promises.rm(d, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
|
|
99
|
+
removed.push(d);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
failed.push({ path: d, error: err.message });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { removed, failed };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export {
|
|
108
|
+
BUILD_DIR_NAMES,
|
|
109
|
+
buildFoldersOf,
|
|
110
|
+
clearBuildFolders
|
|
111
|
+
};
|
|
112
|
+
//# sourceMappingURL=chunk-NDWSLQPB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/cleanup/build-folders.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { defaultRunner, type CommandRunner } from '../pr/ship.js';\n\n/**\n * Build output inside worktrees: node_modules, bin/obj, .next, target, … —\n * most of a worktree's disk, and all of it regenerated by the next install\n * or build. Clearing it in sessions you haven't used for a while gives the\n * space back without archiving them.\n *\n * Safety: a folder is only ever counted or deleted when git IGNORES it\n * (`git check-ignore`: tracked content is never reported as ignored), and\n * the check runs again right before deleting. Symlinks and junctions (pnpm)\n * are neither followed nor sized; deleting removes the link, not its target.\n * A nested repository or worktree (a folder with its own `.git`, such as\n * `.claude/worktrees/<agent>`) is never entered: the outer repo's\n * check-ignore calls its node_modules ignored, but that tree is someone\n * else's, maybe in use right now.\n */\n\nexport const BUILD_DIR_NAMES = new Set([\n 'node_modules',\n 'bin',\n 'obj',\n 'dist',\n 'build',\n 'out',\n 'target',\n 'coverage',\n '.next',\n '.nuxt',\n '.turbo',\n '.vite',\n '.angular',\n '.parcel-cache',\n '.svelte-kit',\n '.gradle',\n '.pytest_cache',\n '__pycache__',\n]);\nconst SKIP = new Set(['.git']);\n\n/** Folders under `root` whose name is a build-output name (not descending into them, nor into nested repos). */\nexport async function candidateBuildDirs(root: string, maxDepth = 4): Promise<string[]> {\n const found: string[] = [];\n const walk = async (dir: string, depth: number): Promise<void> => {\n let entries: fs.Dirent[];\n try {\n entries = await fs.promises.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n if (depth > 0 && entries.some((e) => e.name === '.git')) return; // another repo or worktree\n for (const e of entries) {\n if (!e.isDirectory() || SKIP.has(e.name)) continue; // a symlink/junction is not a Dirent directory\n const full = path.join(dir, e.name);\n if (BUILD_DIR_NAMES.has(e.name)) found.push(full);\n else if (depth < maxDepth) await walk(full, depth + 1);\n }\n };\n await walk(root, 0);\n return found;\n}\n\n/** Of `dirs` (inside the repo at `root`), the ones git ignores. */\nexport async function ignoredByGit(root: string, dirs: string[], run: CommandRunner = defaultRunner): Promise<Set<string>> {\n if (dirs.length === 0) return new Set();\n const rel = dirs.map((d) => path.relative(root, d).replace(/\\\\/g, '/'));\n // Exit 0: some ignored (listed); 1: none; anything else: we can't tell — nothing counts.\n const r = await run('git', ['-C', root, 'check-ignore', '--', ...rel], root);\n if (r.code !== 0) return new Set();\n const ignored = new Set(\n r.stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter(Boolean),\n );\n return new Set(dirs.filter((_, i) => ignored.has(rel[i])));\n}\n\n/** Bytes in a folder (not following links), without blocking the event loop. */\nexport async function folderBytes(dir: string): Promise<number> {\n let total = 0;\n const stack = [dir];\n while (stack.length) {\n const d = stack.pop()!;\n let entries: fs.Dirent[];\n try {\n entries = await fs.promises.readdir(d, { withFileTypes: true });\n } catch {\n continue;\n }\n await Promise.all(\n entries.map(async (e) => {\n const full = path.join(d, e.name);\n if (e.isDirectory()) stack.push(full);\n else if (e.isFile()) {\n try {\n total += (await fs.promises.lstat(full)).size;\n } catch {\n /* vanished */\n }\n }\n }),\n );\n }\n return total;\n}\n\nexport type { BuildFolder } from '../api-types.js';\nimport type { BuildFolder } from '../api-types.js';\n\n/** A worktree's ignored build folders, sized. */\nexport async function buildFoldersOf(root: string, run?: CommandRunner): Promise<BuildFolder[]> {\n const dirs = await ignoredByGit(root, await candidateBuildDirs(root), run);\n const out: BuildFolder[] = [];\n for (const d of dirs) out.push({ path: d, bytes: await folderBytes(d) });\n return out.sort((a, b) => b.bytes - a.bytes);\n}\n\n/**\n * Delete a worktree's build folders: the ones git ignores RIGHT NOW (checked\n * again here), never anything tracked. Returns what went.\n */\nexport async function clearBuildFolders(\n root: string,\n run?: CommandRunner,\n): Promise<{ removed: string[]; failed: Array<{ path: string; error: string }> }> {\n const dirs = await ignoredByGit(root, await candidateBuildDirs(root), run);\n const removed: string[] = [];\n const failed: Array<{ path: string; error: string }> = [];\n for (const d of dirs) {\n try {\n await fs.promises.rm(d, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });\n removed.push(d);\n } catch (err) {\n failed.push({ path: d, error: (err as Error).message });\n }\n }\n return { removed, failed };\n}\n"],"mappings":";;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAmBV,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,OAAO,oBAAI,IAAI,CAAC,MAAM,CAAC;AAG7B,eAAsB,mBAAmB,MAAc,WAAW,GAAsB;AACtF,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,OAAO,KAAa,UAAiC;AAChE,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,GAAG,SAAS,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IAClE,QAAQ;AACN;AAAA,IACF;AACA,QAAI,QAAQ,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG;AACzD,eAAW,KAAK,SAAS;AACvB,UAAI,CAAC,EAAE,YAAY,KAAK,KAAK,IAAI,EAAE,IAAI,EAAG;AAC1C,YAAM,OAAO,KAAK,KAAK,KAAK,EAAE,IAAI;AAClC,UAAI,gBAAgB,IAAI,EAAE,IAAI,EAAG,OAAM,KAAK,IAAI;AAAA,eACvC,QAAQ,SAAU,OAAM,KAAK,MAAM,QAAQ,CAAC;AAAA,IACvD;AAAA,EACF;AACA,QAAM,KAAK,MAAM,CAAC;AAClB,SAAO;AACT;AAGA,eAAsB,aAAa,MAAc,MAAgB,MAAqB,eAAqC;AACzH,MAAI,KAAK,WAAW,EAAG,QAAO,oBAAI,IAAI;AACtC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AK,EAAE,MAAM,GAAG,OAAO,MAAM,YAAY,CAAC,EAAE,CAAC;AACvE,SAAO,IAAI,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC7C;AAMA,eAAsB,kBACpB,MACA,KACgF;AAChF,QAAM,OAAO,MAAM,aAAa,MAAM,MAAM,mBAAmB,IAAI,GAAG,GAAG;AACzE,QAAM,UAAoB,CAAC;AAC3B,QAAM,SAAiD,CAAC;AACxD,aAAW,KAAK,MAAM;AACpB,QAAI;AACF,YAAM,GAAG,SAAS,GAAG,GAAG,EAAE,WAAW,MAAM,OAAO,MAAM,YAAY,GAAG,YAAY,IAAI,CAAC;AACxF,cAAQ,KAAK,CAAC;AAAA,IAChB,SAAS,KAAK;AACZ,aAAO,KAAK,EAAE,MAAM,GAAG,OAAQ,IAAc,QAAQ,CAAC;AAAA,IACxD;AAAA,EACF;AACA,SAAO,EAAE,SAAS,OAAO;AAC3B;","names":[]}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
dbPtySessions,
|
|
4
|
+
forgetPersistedSession
|
|
5
|
+
} from "./chunk-ZJN5RWZD.js";
|
|
6
|
+
import {
|
|
7
|
+
PtyHostBusyError,
|
|
8
|
+
PtyHostClient,
|
|
9
|
+
PtyHostVersionError,
|
|
10
|
+
ensureHost,
|
|
11
|
+
findHost,
|
|
12
|
+
findHostPatient,
|
|
13
|
+
hostStartLockPath
|
|
14
|
+
} from "./chunk-QBAZG4CY.js";
|
|
15
|
+
import {
|
|
16
|
+
ASSISTANT_ID,
|
|
17
|
+
prepareAssistantDir
|
|
18
|
+
} from "./chunk-SOCPIHCS.js";
|
|
19
|
+
import {
|
|
20
|
+
createFsWatcher,
|
|
21
|
+
findSessionById,
|
|
22
|
+
logSwallowed,
|
|
23
|
+
noClaudeBecause,
|
|
24
|
+
swallow
|
|
25
|
+
} from "./chunk-M4FVCAT6.js";
|
|
26
|
+
import {
|
|
27
|
+
sessionIdFor
|
|
28
|
+
} from "./chunk-7NCW3LUT.js";
|
|
29
|
+
import {
|
|
30
|
+
agentFor,
|
|
31
|
+
agentSettings,
|
|
32
|
+
assistantAgent
|
|
33
|
+
} from "./chunk-PN44M5EE.js";
|
|
34
|
+
import {
|
|
35
|
+
ensureFile,
|
|
36
|
+
loadConfig,
|
|
37
|
+
withFileLock
|
|
38
|
+
} from "./chunk-7HEB6SQS.js";
|
|
39
|
+
|
|
40
|
+
// src/core/pty/output-status.ts
|
|
41
|
+
var OUTPUT_WORKING_MS = 1e4;
|
|
42
|
+
function statusFromOutput(p, now) {
|
|
43
|
+
if (!p.tool || p.tool === "claude" || !p.lastOutputAt) return null;
|
|
44
|
+
const at = Date.parse(p.lastOutputAt);
|
|
45
|
+
if (!Number.isFinite(at)) return null;
|
|
46
|
+
const working = now - at < OUTPUT_WORKING_MS;
|
|
47
|
+
return {
|
|
48
|
+
state: working ? "working" : "idle",
|
|
49
|
+
seen: true,
|
|
50
|
+
since: p.lastOutputAt,
|
|
51
|
+
updatedAt: p.lastOutputAt,
|
|
52
|
+
stale: false,
|
|
53
|
+
summary: `${working ? "Printing" : "Quiet"} \u2014 from its terminal output (${p.tool} has no status hooks)`
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/core/pty/pty-pool.ts
|
|
58
|
+
import path from "path";
|
|
59
|
+
|
|
60
|
+
// src/core/sessions/web-state.ts
|
|
61
|
+
function findSession(sessionId) {
|
|
62
|
+
return findSessionById(sessionId);
|
|
63
|
+
}
|
|
64
|
+
var sessionWatchers = /* @__PURE__ */ new Map();
|
|
65
|
+
var DEBOUNCE_MS = 150;
|
|
66
|
+
function subscribeSession(sessionId, onChange) {
|
|
67
|
+
const session = findSession(sessionId);
|
|
68
|
+
if (!session)
|
|
69
|
+
return () => {
|
|
70
|
+
};
|
|
71
|
+
let entry = sessionWatchers.get(sessionId);
|
|
72
|
+
if (!entry) {
|
|
73
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
74
|
+
const newEntry = {
|
|
75
|
+
subscribers,
|
|
76
|
+
watcher: createFsWatcher({
|
|
77
|
+
roots: session.paths,
|
|
78
|
+
debounceMs: DEBOUNCE_MS,
|
|
79
|
+
onChange: () => {
|
|
80
|
+
for (const cb of subscribers) {
|
|
81
|
+
try {
|
|
82
|
+
cb();
|
|
83
|
+
} catch {
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
};
|
|
89
|
+
sessionWatchers.set(sessionId, newEntry);
|
|
90
|
+
entry = newEntry;
|
|
91
|
+
}
|
|
92
|
+
entry.subscribers.add(onChange);
|
|
93
|
+
let released = false;
|
|
94
|
+
return () => {
|
|
95
|
+
if (released) return;
|
|
96
|
+
released = true;
|
|
97
|
+
entry.subscribers.delete(onChange);
|
|
98
|
+
if (entry.subscribers.size === 0) {
|
|
99
|
+
entry.watcher.stop();
|
|
100
|
+
if (sessionWatchers.get(sessionId) === entry) {
|
|
101
|
+
sessionWatchers.delete(sessionId);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
async function disposeSessionWatcher(sessionId) {
|
|
107
|
+
const entry = sessionWatchers.get(sessionId);
|
|
108
|
+
if (!entry) return;
|
|
109
|
+
sessionWatchers.delete(sessionId);
|
|
110
|
+
entry.subscribers.clear();
|
|
111
|
+
entry.watcher.stop();
|
|
112
|
+
}
|
|
113
|
+
function disposeAllWatchers() {
|
|
114
|
+
for (const [, entry] of sessionWatchers) entry.watcher.stop();
|
|
115
|
+
sessionWatchers.clear();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/core/pty/pty-pool.ts
|
|
119
|
+
var workBin = process.argv[1] ?? "";
|
|
120
|
+
var client = null;
|
|
121
|
+
var live = /* @__PURE__ */ new Set();
|
|
122
|
+
var livePids = /* @__PURE__ */ new Set();
|
|
123
|
+
var outputs = /* @__PURE__ */ new Map();
|
|
124
|
+
var refreshTimer = null;
|
|
125
|
+
var beat = { known: false, lastOkAt: null, latencyMs: null, lastError: null };
|
|
126
|
+
function hostBeat() {
|
|
127
|
+
return { ...beat };
|
|
128
|
+
}
|
|
129
|
+
var REFRESH_MS = 2e3;
|
|
130
|
+
function configurePtyPool(opts) {
|
|
131
|
+
workBin = opts.workBin;
|
|
132
|
+
}
|
|
133
|
+
function getWorkBin() {
|
|
134
|
+
return workBin;
|
|
135
|
+
}
|
|
136
|
+
async function getClient(spawnIfMissing) {
|
|
137
|
+
if (client) {
|
|
138
|
+
return client;
|
|
139
|
+
}
|
|
140
|
+
const info = spawnIfMissing ? await ensureHost(workBin) : await findHost();
|
|
141
|
+
if (!info) return null;
|
|
142
|
+
client = new PtyHostClient(info);
|
|
143
|
+
startRefresh();
|
|
144
|
+
return client;
|
|
145
|
+
}
|
|
146
|
+
async function refresh() {
|
|
147
|
+
const t0 = Date.now();
|
|
148
|
+
try {
|
|
149
|
+
const c = await getClient(false);
|
|
150
|
+
if (!c) {
|
|
151
|
+
beat.known = false;
|
|
152
|
+
live = /* @__PURE__ */ new Set();
|
|
153
|
+
livePids = /* @__PURE__ */ new Set();
|
|
154
|
+
outputs = /* @__PURE__ */ new Map();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
beat.known = true;
|
|
158
|
+
const ptys = await c.list();
|
|
159
|
+
beat.lastOkAt = Date.now();
|
|
160
|
+
beat.latencyMs = beat.lastOkAt - t0;
|
|
161
|
+
beat.lastError = null;
|
|
162
|
+
live = new Set(ptys.filter((p) => !p.exited).map((p) => p.id));
|
|
163
|
+
livePids = new Set(ptys.filter((p) => !p.exited).map((p) => p.pid));
|
|
164
|
+
outputs = new Map(
|
|
165
|
+
ptys.filter((p) => !p.exited).map((p) => [p.id, { tool: p.tool, lastOutputAt: p.lastOutputAt, startedAt: p.startedAt }])
|
|
166
|
+
);
|
|
167
|
+
} catch (err) {
|
|
168
|
+
beat.known = beat.known || err instanceof PtyHostBusyError;
|
|
169
|
+
beat.lastError = err.message;
|
|
170
|
+
client = null;
|
|
171
|
+
live = /* @__PURE__ */ new Set();
|
|
172
|
+
livePids = /* @__PURE__ */ new Set();
|
|
173
|
+
outputs = /* @__PURE__ */ new Map();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function startRefresh() {
|
|
177
|
+
if (refreshTimer) return;
|
|
178
|
+
refreshTimer = setInterval(() => void refresh(), REFRESH_MS);
|
|
179
|
+
refreshTimer.unref?.();
|
|
180
|
+
}
|
|
181
|
+
async function syncPtyPool() {
|
|
182
|
+
await refresh();
|
|
183
|
+
}
|
|
184
|
+
async function initPtyPool() {
|
|
185
|
+
await refresh().catch(() => {
|
|
186
|
+
});
|
|
187
|
+
startRefresh();
|
|
188
|
+
}
|
|
189
|
+
async function resumePersistedSessions() {
|
|
190
|
+
let count;
|
|
191
|
+
try {
|
|
192
|
+
count = Object.keys(dbPtySessions.read()).length;
|
|
193
|
+
} catch {
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
if (count === 0) return 0;
|
|
197
|
+
if (await findHost().catch(() => true)) return 0;
|
|
198
|
+
await getClient(true);
|
|
199
|
+
await refresh();
|
|
200
|
+
return count;
|
|
201
|
+
}
|
|
202
|
+
function assistantSpec() {
|
|
203
|
+
const settings = agentSettings();
|
|
204
|
+
const agent = assistantAgent(settings);
|
|
205
|
+
return { cwd: prepareAssistantDir(agent), tool: agent.launch.tool(settings) };
|
|
206
|
+
}
|
|
207
|
+
function spawnSpecFor(session) {
|
|
208
|
+
const first = session.paths[0];
|
|
209
|
+
if (!first) return null;
|
|
210
|
+
const cwd = session.isGroup ? path.dirname(first) : first;
|
|
211
|
+
const config = loadConfig();
|
|
212
|
+
return { cwd, tool: agentFor(config, session).launch.tool(config), port: session.port };
|
|
213
|
+
}
|
|
214
|
+
async function ensurePty(sessionId, extra = {}) {
|
|
215
|
+
const session = sessionId === ASSISTANT_ID ? null : findSession(sessionId);
|
|
216
|
+
const refused = sessionId === ASSISTANT_ID ? null : noClaudeBecause(session, sessionId);
|
|
217
|
+
if (refused) throw new Error(refused);
|
|
218
|
+
const base = sessionId === ASSISTANT_ID ? assistantSpec() : session ? spawnSpecFor(session) : null;
|
|
219
|
+
if (!base) return null;
|
|
220
|
+
const spec = extra.initialPrompt ? { ...base, initialPrompt: extra.initialPrompt } : base;
|
|
221
|
+
let c = await getClient(true);
|
|
222
|
+
if (!c) return null;
|
|
223
|
+
try {
|
|
224
|
+
await c.spawn(sessionId, spec);
|
|
225
|
+
} catch (err) {
|
|
226
|
+
client = null;
|
|
227
|
+
c = await getClient(true);
|
|
228
|
+
if (!c) throw err;
|
|
229
|
+
await c.spawn(sessionId, spec);
|
|
230
|
+
}
|
|
231
|
+
live.add(sessionId);
|
|
232
|
+
return c.attachUrl(sessionId);
|
|
233
|
+
}
|
|
234
|
+
async function listHostPtys() {
|
|
235
|
+
const c = await getClient(false);
|
|
236
|
+
return c ? c.list() : [];
|
|
237
|
+
}
|
|
238
|
+
function ptyPids() {
|
|
239
|
+
return livePids;
|
|
240
|
+
}
|
|
241
|
+
function outputStatus(sessionId, now = Date.now()) {
|
|
242
|
+
const o = outputs.get(sessionId);
|
|
243
|
+
return o ? statusFromOutput(o, now) : null;
|
|
244
|
+
}
|
|
245
|
+
function peekPty(sessionId) {
|
|
246
|
+
return live.has(sessionId);
|
|
247
|
+
}
|
|
248
|
+
async function readPtyScreen(sessionId) {
|
|
249
|
+
if (!live.has(sessionId)) return null;
|
|
250
|
+
const c = await getClient(false);
|
|
251
|
+
return c ? c.screen(sessionId) : null;
|
|
252
|
+
}
|
|
253
|
+
async function writeToPty(sessionId, data) {
|
|
254
|
+
if (!live.has(sessionId)) return false;
|
|
255
|
+
const c = await getClient(false);
|
|
256
|
+
return c ? c.write(sessionId, data) : false;
|
|
257
|
+
}
|
|
258
|
+
async function disposePty(sessionId) {
|
|
259
|
+
live.delete(sessionId);
|
|
260
|
+
let c = client;
|
|
261
|
+
if (!c) {
|
|
262
|
+
let info;
|
|
263
|
+
try {
|
|
264
|
+
info = await findHostPatient();
|
|
265
|
+
} catch (err) {
|
|
266
|
+
if (err instanceof PtyHostVersionError) return;
|
|
267
|
+
throw err;
|
|
268
|
+
}
|
|
269
|
+
if (!info) return;
|
|
270
|
+
c = new PtyHostClient(info);
|
|
271
|
+
}
|
|
272
|
+
await c.kill(sessionId).catch(swallow(`stop session ${sessionId} in the PTY host`));
|
|
273
|
+
}
|
|
274
|
+
async function stopSessionPty(target, branch) {
|
|
275
|
+
const id = sessionIdFor({ target, branch });
|
|
276
|
+
live.delete(id);
|
|
277
|
+
const lock = hostStartLockPath();
|
|
278
|
+
ensureFile(lock, "");
|
|
279
|
+
await withFileLock(lock, async () => {
|
|
280
|
+
let info;
|
|
281
|
+
try {
|
|
282
|
+
info = await findHostPatient();
|
|
283
|
+
} catch (err) {
|
|
284
|
+
logSwallowed(`stop session ${id}: PTY host`, err);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (info) await new PtyHostClient(info).kill(id).catch(swallow(`stop session ${id} in the PTY host`));
|
|
288
|
+
else await forgetPersistedSession(id).catch(swallow(`forget saved session ${id}`));
|
|
289
|
+
}).catch(swallow(`stop session ${id}: host start lock`));
|
|
290
|
+
}
|
|
291
|
+
function detachPtyPool() {
|
|
292
|
+
if (refreshTimer) clearInterval(refreshTimer);
|
|
293
|
+
refreshTimer = null;
|
|
294
|
+
client = null;
|
|
295
|
+
live = /* @__PURE__ */ new Set();
|
|
296
|
+
livePids = /* @__PURE__ */ new Set();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export {
|
|
300
|
+
findSession,
|
|
301
|
+
subscribeSession,
|
|
302
|
+
disposeSessionWatcher,
|
|
303
|
+
disposeAllWatchers,
|
|
304
|
+
statusFromOutput,
|
|
305
|
+
hostBeat,
|
|
306
|
+
configurePtyPool,
|
|
307
|
+
getWorkBin,
|
|
308
|
+
syncPtyPool,
|
|
309
|
+
initPtyPool,
|
|
310
|
+
resumePersistedSessions,
|
|
311
|
+
spawnSpecFor,
|
|
312
|
+
ensurePty,
|
|
313
|
+
listHostPtys,
|
|
314
|
+
ptyPids,
|
|
315
|
+
outputStatus,
|
|
316
|
+
peekPty,
|
|
317
|
+
readPtyScreen,
|
|
318
|
+
writeToPty,
|
|
319
|
+
disposePty,
|
|
320
|
+
stopSessionPty,
|
|
321
|
+
detachPtyPool
|
|
322
|
+
};
|
|
323
|
+
//# sourceMappingURL=chunk-O3QTWVSK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/pty/output-status.ts","../src/core/pty/pty-pool.ts","../src/core/sessions/web-state.ts"],"sourcesContent":["import type { SessionAttention } from '../api-types.js';\n\n/**\n * A status for a session whose tool isn't Claude Code (config `aiCommand`,\n * e.g. opencode): no hooks report its turns, so the PTY host's \"last printed\n * anything\" stands in — a working agent redraws its spinner, an idle one\n * prints nothing. Working while it printed in the last `OUTPUT_WORKING_MS`,\n * idle after; never \"done, unseen\" or \"needs input\" (output can't tell a\n * finished turn from a question). Pure.\n */\n\nexport const OUTPUT_WORKING_MS = 10_000;\n\nexport interface PtyOutput {\n /** The tool's binary (the host's spawn spec). */\n tool?: string;\n /** When it last printed (ISO). */\n lastOutputAt?: string;\n startedAt: string;\n}\n\nexport function statusFromOutput(p: PtyOutput, now: number): SessionAttention | null {\n if (!p.tool || p.tool === 'claude' || !p.lastOutputAt) return null;\n const at = Date.parse(p.lastOutputAt);\n if (!Number.isFinite(at)) return null;\n const working = now - at < OUTPUT_WORKING_MS;\n return {\n state: working ? 'working' : 'idle',\n seen: true,\n since: p.lastOutputAt,\n updatedAt: p.lastOutputAt,\n stale: false,\n summary: `${working ? 'Printing' : 'Quiet'} — from its terminal output (${p.tool} has no status hooks)`,\n };\n}\n","import path from 'node:path';\nimport type { AgentAdapter } from '../agents/types.js';\nimport { agentFor, agentSettings, assistantAgent } from '../agents/index.js';\nimport { statusFromOutput, type PtyOutput } from './output-status.js';\nimport type { SessionAttention } from '../api-types.js';\nimport type { HostBeat } from './host-health.js';\nimport { PtyHostBusyError } from './pty-host-client.js';\nimport { noClaudeBecause } from '../archive/archiving.js';\nimport { findSession, sessionIdFor } from '../sessions/web-state.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport { hostStartLockPath, type SpawnSpec, type HostInfo, type PtyInfo } from './pty-host-protocol.js';\nimport { dbPtySessions } from './pty-sessions-file.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { forgetPersistedSession } from './pty-sessions-file.js';\nimport { loadConfig } from '../platform/config.js';\nimport { ensureHost, findHost, PtyHostClient, findHostPatient, PtyHostVersionError } from './pty-host-client.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\nimport { ASSISTANT_ID, prepareAssistantDir } from '../agents/assistant.js';\n\n/**\n * `work web`'s view of the Claude PTYs. The PTYs themselves live in the\n * PTY host (`work pty-host`, see core/pty-host.ts), a separate long-lived\n * process — so restarting or rebuilding `work web` never kills an agent,\n * and a real terminal (`work attach`) can share the same session.\n *\n * This module resolves a dashboard session to a spawn spec, asks the host\n * to spawn it on first attach, and keeps a small cache of which sessions\n * have a live PTY for the synchronous badge path (`peekPty`).\n */\n\nlet workBin = process.argv[1] ?? '';\nlet client: PtyHostClient | null = null;\nlet live = new Set<string>();\n/** The pids of those PTYs' processes (the Claudes the app runs). */\nlet livePids = new Set<number>();\n/** Each live PTY's tool and last output (for output-status.ts). */\nlet outputs = new Map<string, PtyOutput>();\nlet refreshTimer: NodeJS.Timeout | null = null;\n/** The heartbeat (host-health.ts): each list request is one. */\nconst beat: HostBeat = { known: false, lastOkAt: null, latencyMs: null, lastError: null };\n\n/** How the host answered lately (for GET /api/pty-host/health). */\nexport function hostBeat(): HostBeat {\n return { ...beat };\n}\nconst REFRESH_MS = 2000;\n\n/** Called by `work web` at startup with the resolved `work` binary path,\n * which is what the host is spawned from. */\nexport function configurePtyPool(opts: { workBin: string }): void {\n workBin = opts.workBin;\n}\n\n/** The `work` binary path, for routes that launch `work attach`. */\nexport function getWorkBin(): string {\n return workBin;\n}\n\nasync function getClient(spawnIfMissing: boolean): Promise<PtyHostClient | null> {\n if (client) {\n // Cheap liveness re-check happens in refresh(); a dead host surfaces\n // as a failed call, which resets `client` below.\n return client;\n }\n const info = spawnIfMissing ? await ensureHost(workBin) : await findHost();\n if (!info) return null;\n client = new PtyHostClient(info);\n startRefresh();\n return client;\n}\n\nasync function refresh(): Promise<void> {\n const t0 = Date.now();\n try {\n const c = await getClient(false);\n if (!c) {\n beat.known = false;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n return;\n }\n beat.known = true;\n const ptys = await c.list();\n beat.lastOkAt = Date.now();\n beat.latencyMs = beat.lastOkAt - t0;\n beat.lastError = null;\n live = new Set(ptys.filter((p) => !p.exited).map((p) => p.id));\n livePids = new Set(ptys.filter((p) => !p.exited).map((p) => p.pid));\n outputs = new Map(\n ptys.filter((p) => !p.exited).map((p) => [p.id, { tool: p.tool, lastOutputAt: p.lastOutputAt, startedAt: p.startedAt }]),\n );\n } catch (err) {\n // Host went away (or was restarted on a new port) — rediscover next tick.\n // A busy host is still a host (it is there, just not answering).\n beat.known = beat.known || err instanceof PtyHostBusyError;\n beat.lastError = (err as Error).message;\n client = null;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n }\n}\n\nfunction startRefresh(): void {\n if (refreshTimer) return;\n refreshTimer = setInterval(() => void refresh(), REFRESH_MS);\n refreshTimer.unref?.();\n}\n\n/** Connect to an already-running host at `work web` startup so badges for\n * PTYs that survived a web restart show immediately. Never spawns. */\n/** Re-read the host's PTY list now (the periodic refresh can be seconds old,\n * or not have run at all right after `work web` started). */\nexport async function syncPtyPool(): Promise<void> {\n await refresh();\n}\n\nexport async function initPtyPool(): Promise<void> {\n await refresh().catch(() => {});\n startRefresh();\n}\n\n/**\n * After a reboot (or a host crash) nothing is running but\n * `pty-sessions.json` still lists the sessions that were live. Starting the\n * host restores them; do that when there's something to restore, so\n * reopening `work web` picks up where you left off. Returns how many\n * sessions the host will bring back (0 = nothing to do).\n */\nexport async function resumePersistedSessions(): Promise<number> {\n let count: number;\n try {\n count = Object.keys(dbPtySessions.read()).length;\n } catch {\n return 0;\n }\n if (count === 0) return 0;\n if (await findHost().catch(() => true)) return 0; // already running\n await getClient(true);\n await refresh();\n return count;\n}\n\n/**\n * Where Claude runs for a session — the same directory `work tree` launches\n * in: the worktree for a single repo, the group root (parent of the\n * sub-repos) for a group.\n */\nexport { ASSISTANT_ID };\n\n/** The assistant runs config `assistantAgent` (Claude Code by default), in its folder written for that agent. */\nexport function assistantSpec(): { cwd: string; tool: ReturnType<AgentAdapter['launch']['tool']> } {\n const settings = agentSettings();\n const agent = assistantAgent(settings);\n return { cwd: prepareAssistantDir(agent), tool: agent.launch.tool(settings) };\n}\n\nexport function spawnSpecFor(session: WorktreeSession): SpawnSpec | null {\n const first = session.paths[0];\n if (!first) return null;\n const cwd = session.isGroup ? path.dirname(first) : first;\n const config = loadConfig();\n return { cwd, tool: agentFor(config, session).launch.tool(config), port: session.port };\n}\n\n/**\n * Ensure a live PTY exists for the session (spawning Claude in the host if\n * needed) and return the host WebSocket URL to attach to. Null for an\n * unknown session.\n */\nexport async function ensurePty(sessionId: string, extra: { initialPrompt?: string } = {}): Promise<string | null> {\n // The dashboard assistant (Ctrl+K) is not a worktree: it runs in its own\n // folder, which is (re)written first (assistant.ts).\n const session = sessionId === ASSISTANT_ID ? null : findSession(sessionId);\n // Not for a session being archived, or archived: its Claude was stopped on\n // purpose (a Terminal tab still open on it reconnects and would start it).\n const refused = sessionId === ASSISTANT_ID ? null : noClaudeBecause(session, sessionId);\n if (refused) throw new Error(refused);\n const base = sessionId === ASSISTANT_ID ? assistantSpec() : session ? spawnSpecFor(session) : null;\n if (!base) return null;\n // The first prompt only applies to a fresh spawn (the host ignores the\n // spec when the session's PTY is already running).\n const spec = extra.initialPrompt ? { ...base, initialPrompt: extra.initialPrompt } : base;\n\n let c = await getClient(true);\n if (!c) return null;\n try {\n await c.spawn(sessionId, spec);\n } catch (err) {\n // Stale client (host restarted on a new port) — retry once, fresh.\n client = null;\n c = await getClient(true);\n if (!c) throw err;\n await c.spawn(sessionId, spec);\n }\n live.add(sessionId);\n return c.attachUrl(sessionId);\n}\n\n/** Side-effect-free check: does an active (non-exited) PTY exist for this\n * session? Served from the refresh cache — used by session-meta for the\n * \"running/idle\" badge, which must stay synchronous. */\n/** Every PTY in the host, fresh (never starts a host; [] without one). */\nexport async function listHostPtys(): Promise<PtyInfo[]> {\n const c = await getClient(false);\n return c ? c.list() : [];\n}\n\n/** Pids of the Claudes running in the PTY host (from the refresh cache). */\nexport function ptyPids(): ReadonlySet<number> {\n return livePids;\n}\n\n/** A status from its terminal output, for a session whose tool has no hooks (output-status.ts); null for Claude or no PTY. */\nexport function outputStatus(sessionId: string, now = Date.now()): SessionAttention | null {\n const o = outputs.get(sessionId);\n return o ? statusFromOutput(o, now) : null;\n}\n\nexport function peekPty(sessionId: string): boolean {\n return live.has(sessionId);\n}\n\n/** A session's live PTY screen as text; null when there is none (never spawns). */\nexport async function readPtyScreen(sessionId: string): Promise<string | null> {\n if (!live.has(sessionId)) return null;\n const c = await getClient(false);\n return c ? c.screen(sessionId) : null;\n}\n\n/** Write to a session's live PTY. False when there is none (never spawns). */\nexport async function writeToPty(sessionId: string, data: string): Promise<boolean> {\n if (!live.has(sessionId)) return false;\n const c = await getClient(false);\n return c ? c.write(sessionId, data) : false;\n}\n\n/** Kill one session's PTY (if any). Called before removing a worktree so\n * the Claude process doesn't hold its cwd open (Windows refuses to delete\n * a directory that is some process's working directory). */\nexport async function disposePty(sessionId: string): Promise<void> {\n live.delete(sessionId);\n let c = client;\n if (!c) {\n // A busy host (mid-restore) is waited for, not skipped: skipping left\n // Claude running inside the worktree about to be deleted. A host from\n // another build can't be talked to — nothing to do but proceed.\n let info: HostInfo | null;\n try {\n info = await findHostPatient();\n } catch (err) {\n if (err instanceof PtyHostVersionError) return;\n throw err; // still busy after waiting: let the caller report it\n }\n if (!info) return;\n c = new PtyHostClient(info);\n }\n await c.kill(sessionId).catch(swallow(`stop session ${sessionId} in the PTY host`));\n}\n\n/**\n * Stop a session's Claude in the PTY host before its worktree is deleted —\n * from any caller, including the CLI (`work remove` / prune / sync), which\n * doesn't run a pool. Never starts a host; waits for the process to exit\n * (the host's kill does) so Windows can then delete the directory.\n * Best-effort: no host, or a host that can't be reached, is a no-op.\n */\nexport async function stopSessionPty(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch } as WorktreeSession);\n live.delete(id);\n // Under the host START lock: a host that's starting holds it until it has\n // restored, so we either see it running (and kill the session) or know\n // none is — and then drop the session from the saved list so a later\n // start doesn't restore Claude into a worktree that's being deleted.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n await withFileLock(lock, async () => {\n let info;\n try {\n info = await findHostPatient();\n } catch (err) {\n // A host from another build can't be talked to; one still busy after\n // waiting is running and owns the session — leave both alone (and\n // never drop the saved entry: the host is what it belongs to).\n logSwallowed(`stop session ${id}: PTY host`, err);\n return;\n }\n if (info) await new PtyHostClient(info).kill(id).catch(swallow(`stop session ${id} in the PTY host`));\n else await forgetPersistedSession(id).catch(swallow(`forget saved session ${id}`));\n }).catch(swallow(`stop session ${id}: host start lock`));\n}\n\n/** `work web` shutdown. Deliberately does NOT kill anything: the PTYs belong\n * to the host and outlive the dashboard. Just stops polling. */\nexport function detachPtyPool(): void {\n if (refreshTimer) clearInterval(refreshTimer);\n refreshTimer = null;\n client = null;\n live = new Set();\n livePids = new Set();\n}\n","import { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { findSessionById, type WorktreeSession } from './history.js';\n\nexport { sessionIdFor } from './session-id.js';\n\n/** A session by id — a primary-key lookup (every /api/sessions/:id/*\n * request does one; it used to load and hash every row). */\nexport function findSession(sessionId: string): WorktreeSession | null {\n return findSessionById(sessionId);\n}\n\ninterface WatcherEntry {\n watcher: FsWatcher;\n subscribers: Set<() => void>;\n}\n\nconst sessionWatchers = new Map<string, WatcherEntry>();\nconst DEBOUNCE_MS = 150;\n\n/**\n * Subscribe to filesystem changes for a session's worktree(s). The watch is\n * started on first subscriber and stopped when the last one leaves —\n * reference-counted so the cost stays proportional to what's actually being\n * viewed in the browser. It is the shared fs-watcher: dependency and build\n * folders (node_modules, bin/obj, dist, …) are left out, and on Windows and\n * macOS it is one recursive OS watch per root. A chokidar watch over the\n * whole worktree used to open one watch per folder, node_modules included.\n *\n * Returns an unsubscribe function. Safe to call multiple times.\n */\nexport function subscribeSession(sessionId: string, onChange: () => void): () => void {\n const session = findSession(sessionId);\n if (!session)\n return () => {\n /* unknown session */\n };\n\n let entry = sessionWatchers.get(sessionId);\n if (!entry) {\n const subscribers = new Set<() => void>();\n const newEntry: WatcherEntry = {\n subscribers,\n watcher: createFsWatcher({\n roots: session.paths,\n debounceMs: DEBOUNCE_MS,\n onChange: () => {\n for (const cb of subscribers) {\n try {\n cb();\n } catch {\n /* swallow */\n }\n }\n },\n }),\n };\n sessionWatchers.set(sessionId, newEntry);\n entry = newEntry;\n }\n\n entry.subscribers.add(onChange);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry!.subscribers.delete(onChange);\n if (entry!.subscribers.size === 0) {\n entry!.watcher.stop();\n if (sessionWatchers.get(sessionId) === entry) {\n sessionWatchers.delete(sessionId);\n }\n }\n };\n}\n\n/**\n * Force-stop one session's watcher regardless of subscribers. Used before\n * removing a worktree: on Windows an open directory watch keeps a handle\n * on the tree and makes `git worktree remove` fail. Late unsubscribes from\n * the orphaned entry are harmless (see the identity check above).\n */\nexport async function disposeSessionWatcher(sessionId: string): Promise<void> {\n const entry = sessionWatchers.get(sessionId);\n if (!entry) return;\n sessionWatchers.delete(sessionId);\n entry.subscribers.clear();\n entry.watcher.stop();\n}\n\n/** Stop every active session watcher. Called on server shutdown. */\nexport function disposeAllWatchers(): void {\n for (const [, entry] of sessionWatchers) entry.watcher.stop();\n sessionWatchers.clear();\n}\n"],"mapp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AAK,OAAO,EAAE;AAKd,QAAM,OAAO,kBAAkB;AAC/B,aAAW,MAAM,EAAE;AACnB,QAAM,aAAa,MAAM,YAAY;AACnC,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,gBAAgB;AAAA,IAC/B,SAAS,KAAK;AAIZ,mBAAa,gBAAgB,EAAE,cAAc,GAAG;AAChD;AAAA,IACF;AACA,QAAI,KAAM,OAAM,IAAI,cAAc,IAAI,EAAE,KAAK,EAAE,EAAE,MAAM,QAAQ,gBAAgB,EAAE,kBAAkB,CAAC;AAAA,QAC/F,OAAM,uBAAuB,EAAE,EAAE,MAAM,QAAQ,wBAAwB,EAAE,EAAE,CAAC;AAAA,EACnF,CAAC,EAAE,MAAM,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC;AACzD;AAIO,SAAS,gBAAsB;AACpC,MAAI,aAAc,eAAc,YAAY;AAC5C,iBAAe;AACf,WAAS;AACT,SAAO,oBAAI,IAAI;AACf,aAAW,oBAAI,IAAI;AACrB;","names":[]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
buildAiLaunchArgs
|
|
4
|
+
} from "./chunk-PN44M5EE.js";
|
|
5
|
+
import {
|
|
6
|
+
spawn_default
|
|
7
|
+
} from "./chunk-RCYI7SRA.js";
|
|
8
|
+
|
|
9
|
+
// src/core/platform/launch.ts
|
|
10
|
+
function getEditor() {
|
|
11
|
+
return process.env.EDITOR ?? process.env.VISUAL ?? (process.platform === "win32" ? "notepad" : "vi");
|
|
12
|
+
}
|
|
13
|
+
function openInEditor(filePath) {
|
|
14
|
+
const editor = getEditor();
|
|
15
|
+
spawn_default.sync(editor, [filePath], { stdio: "inherit" });
|
|
16
|
+
}
|
|
17
|
+
function openUrl(url) {
|
|
18
|
+
const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
|
|
19
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
20
|
+
spawn_default(cmd, args, { stdio: "ignore", detached: true }).unref();
|
|
21
|
+
}
|
|
22
|
+
function openVSCode(dir) {
|
|
23
|
+
spawn_default.sync("code", ["."], { cwd: dir, stdio: "inherit" });
|
|
24
|
+
}
|
|
25
|
+
function launchAi(cwd, tool, opts = {}, port) {
|
|
26
|
+
const { cmd, args } = buildAiLaunchArgs(tool, opts);
|
|
27
|
+
const spawnOpts = port !== void 0 ? { cwd, stdio: "inherit", env: { ...process.env, PORT: String(port) } } : { cwd, stdio: "inherit" };
|
|
28
|
+
spawn_default.sync(cmd, args, spawnOpts);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
openInEditor,
|
|
33
|
+
openUrl,
|
|
34
|
+
openVSCode,
|
|
35
|
+
launchAi
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=chunk-P3BL4EOP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/platform/launch.ts"],"sourcesContent":["import spawn from './spawn.js';\nimport { buildAiLaunchArgs, type AiLaunchOpts, type AiToolSpec } from './ai-launcher.js';\n\n/** Get the platform-appropriate default editor. */\nexport function getEditor(): string {\n return process.env.EDITOR ?? process.env.VISUAL ?? (process.platform === 'win32' ? 'notepad' : 'vi');\n}\n\n/** Open a file in the user's editor. */\nexport function openInEditor(filePath: string): void {\n const editor = getEditor();\n spawn.sync(editor, [filePath], { stdio: 'inherit' });\n}\n\n/** Open a URL in the default browser. */\nexport function openUrl(url: string): void {\n const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';\n const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n}\n\n/** Open VS Code in the given directory. */\nexport function openVSCode(dir: string): void {\n spawn.sync('code', ['.'], { cwd: dir, stdio: 'inherit' });\n}\n\n/**\n * Launch the configured AI tool in the given directory.\n *\n * When `port` is provided it is injected as `$PORT` into the launched process\n * so dev servers started by parallel agent sessions don't collide.\n */\nexport function launchAi(cwd: string, tool: AiToolSpec, opts: AiLaunchOpts = {}, port?: number): void {\n const { cmd, args } = buildAiLaunchArgs(tool, opts);\n const spawnOpts: Parameters<typeof spawn.sync>[2] =\n port !== undefined ? { cwd, stdio: 'inherit', env: { ...process.env, PORT: String(port) } } : { cwd, stdio: 'inherit' };\n spawn.sync(cmd, args, spawnOpts);\n}\n"],"mappings":";;;;;;;;;AAIO,SAAS,YAAoB;AAClC,SAAO,QAAQ,IAAI,UAAU,QAAQ,IAAI,WAAW,QAAQ,aAAa,UAAU,YAAY;AACjG;AAGO,SAAS,aAAa,UAAwB;AACnD,QAAM,SAAS,UAAU;AACzB,gBAAM,KAAK,QAAQ,CAAC,QAAQ,GAAG,EAAE,OAAO,UAAU,CAAC;AACrD;AAGO,SAAS,QAAQ,KAAmB;AACzC,QAAM,MAAM,QAAQ,aAAa,UAAU,QAAQ,QAAQ,aAAa,WAAW,SAAS;AAC5F,QAAM,OAAO,QAAQ,aAAa,UAAU,CAAC,MAAM,SAAS,IAAI,GAAG,IAAI,CAAC,GAAG;AAC3E,gBAAM,KAAK,MAAM,EAAE,OAAO,UAAU,UAAU,KAAK,CAAC,EAAE,MAAM;AAC9D;AAGO,SAAS,WAAW,KAAmB;AAC5C,gBAAM,KAAK,QAAQ,CAAC,GAAG,GAAG,EAAE,KAAK,KAAK,OAAO,UAAU,CAAC;AAC1D;AAQO,SAAS,SAAS,KAAa,MAAkB,OAAqB,CAAC,GAAG,MAAqB;AACpG,QAAM,EAAE,KAAK,KAAK,IAAI,kBAAkB,MAAM,IAAI;AAClD,QAAM,YACJ,SAAS,SAAY,EAAE,KAAK,OAAO,WAAW,KAAK,EAAE,GAAG,QAAQ,KAAK,MAAM,OAAO,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,OAAO,UAAU;AACxH,gBAAM,KAAK,KAAK,MAAM,SAAS;AACjC;","names":[]}
|