opencode-windows-scheduler 1.2.1 → 1.2.2

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/src/server.ts CHANGED
@@ -39,8 +39,13 @@ const FALLBACK_PORT = 4782;
39
39
  /** Дополнительный порт, если и 3782, и 4782 заняты чужими процессами. */
40
40
  const EXTRA_PORTS = [5782];
41
41
 
42
- /** Имена процессов, которые считаем «зомби» от прошлых запусков плагина. */
43
- const ZOMBIE_IMAGE_NAMES = new Set(["node.exe", "bun.exe"]);
42
+ const IS_WINDOWS = process.platform === "win32";
43
+
44
+ /**
45
+ * Имена процессов, которые считаем «зомби» от прошлых запусков плагина.
46
+ * На Windows процессы называются node.exe / bun.exe, на POSIX — node / bun.
47
+ */
48
+ const ZOMBIE_IMAGE_NAMES = new Set(["node", "nodejs", "node.exe", "bun", "bun.exe"]);
44
49
 
45
50
  /** Маркер-заголовок: по нему узнаём «свой» дашборд, уже слушающий порт. */
46
51
  const DASHBOARD_HEADER = "x-plugin-dashboard";
@@ -304,15 +309,20 @@ export async function startDashboardServer(
304
309
  }
305
310
 
306
311
  // Порт занят чужим или старым процессом: пробуем снять зомби
307
- // (только node/bun этого плагина) и один раз повторить bind.
312
+ // (только node/bun этого плагина) и повторить bind.
308
313
  if (port !== 0 && (await tryFreeZombiePort(port))) {
309
- try {
310
- const server = await listenOn(port, deps);
311
- running = { server, port };
312
- console.log(`[windows-scheduler] Веб-дашборд запущен: http://localhost:${port}`);
313
- return { port };
314
- } catch {
315
- // Не вышло — идём к следующему порту.
314
+ // SIGKILL асинхронный: на POSIX процесс может ещё какое-то время
315
+ // держать сокет, поэтому сначала ждём освобождения порта.
316
+ const freed = await waitForPortFree(port, 3000);
317
+ if (freed) {
318
+ try {
319
+ const server = await listenOn(port, deps);
320
+ running = { server, port };
321
+ console.log(`[windows-scheduler] Веб-дашборд запущен: http://localhost:${port}`);
322
+ return { port };
323
+ } catch {
324
+ // Не вышло — идём к следующему порту.
325
+ }
316
326
  }
317
327
  }
318
328
  // Чужой сервис — пробуем запасной порт.
@@ -370,7 +380,11 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
370
380
  }
371
381
 
372
382
  try {
373
- await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
383
+ if (IS_WINDOWS) {
384
+ await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
385
+ } else {
386
+ process.kill(pid, "SIGKILL");
387
+ }
374
388
  console.log(
375
389
  `[windows-scheduler] Снят зомби-процесс ${info.name} (PID ${pid}), державший порт ${port}.`
376
390
  );
@@ -387,8 +401,25 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
387
401
  return killed;
388
402
  }
389
403
 
390
- /** Возвращает PID'ы процессов, слушающих указанный TCP-порт (netstat). */
404
+ /** Ждёт, пока порт освободится (POSIX: убитый процесс отпускает сокет не синхронно). */
405
+ async function waitForPortFree(port: number, timeoutMs: number): Promise<boolean> {
406
+ const deadline = Date.now() + timeoutMs;
407
+ while (Date.now() < deadline) {
408
+ const pids = await findListeningPids(port);
409
+ if (pids.length === 0) return true;
410
+ await new Promise((resolve) => setTimeout(resolve, 150));
411
+ }
412
+ return false;
413
+ }
414
+
415
+ /** Возвращает PID'ы процессов, слушающих указанный TCP-порт. */
391
416
  async function findListeningPids(port: number): Promise<number[]> {
417
+ if (IS_WINDOWS) return findListeningPidsWindows(port);
418
+ return findListeningPidsPosix(port);
419
+ }
420
+
421
+ /** Windows: netstat -ano, состояния LISTENING. */
422
+ async function findListeningPidsWindows(port: number): Promise<number[]> {
392
423
  try {
393
424
  const { stdout } = await execFileAsync("netstat", ["-ano", "-p", "TCP"], {
394
425
  windowsHide: true,
@@ -410,8 +441,55 @@ async function findListeningPids(port: number): Promise<number[]> {
410
441
  }
411
442
  }
412
443
 
413
- /** Имя процесса и командная строка через CIM (Windows PowerShell). */
444
+ /**
445
+ * macOS/Linux: lsof (есть в macOS и на большинстве Linux-образов),
446
+ * на Linux — запасной вариант через ss из iproute2.
447
+ */
448
+ async function findListeningPidsPosix(port: number): Promise<number[]> {
449
+ try {
450
+ const { stdout } = await execFileAsync(
451
+ "lsof",
452
+ ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"],
453
+ { windowsHide: true }
454
+ );
455
+ const pids = stdout
456
+ .split(/\s+/)
457
+ .map(Number)
458
+ .filter((pid) => Number.isInteger(pid) && pid > 0);
459
+ if (pids.length > 0) return Array.from(new Set(pids));
460
+ } catch {
461
+ // lsof может отсутствовать или не быть в PATH — пробуем ss.
462
+ }
463
+
464
+ if (process.platform === "linux") {
465
+ try {
466
+ const { stdout } = await execFileAsync("ss", ["-ltnp", `sport = :${port}`], {
467
+ windowsHide: true,
468
+ });
469
+ const pids = new Set<number>();
470
+ for (const match of stdout.matchAll(/pid=(\d+)/g)) {
471
+ const pid = Number(match[1]);
472
+ if (Number.isInteger(pid) && pid > 0) pids.add(pid);
473
+ }
474
+ return Array.from(pids);
475
+ } catch {
476
+ // ss тоже недоступен — считаем, что владельца порта не знаем.
477
+ }
478
+ }
479
+
480
+ return [];
481
+ }
482
+
483
+ /** Имя процесса и командная строка. */
414
484
  async function getProcessInfo(pid: number): Promise<{ name: string; commandLine: string } | null> {
485
+ if (IS_WINDOWS) return getProcessInfoWindows(pid);
486
+ return getProcessInfoPosix(pid);
487
+ }
488
+
489
+ /** Имя процесса и командная строка через CIM (Windows PowerShell). */
490
+ async function getProcessInfoWindows(
491
+ pid: number
492
+ ): Promise<{ name: string; commandLine: string } | null> {
415
493
  try {
416
494
  const script =
417
495
  '$p = Get-CimInstance Win32_Process -Filter "ProcessId=' +
@@ -432,6 +510,36 @@ async function getProcessInfo(pid: number): Promise<{ name: string; commandLine:
432
510
  }
433
511
  }
434
512
 
513
+ /** Имя процесса и командная строка через ps (macOS/Linux). */
514
+ async function getProcessInfoPosix(
515
+ pid: number
516
+ ): Promise<{ name: string; commandLine: string } | null> {
517
+ try {
518
+ // NOTE: на Linux у Node главный поток помечен как "MainThread", поэтому
519
+ // имя берём из argv[0] командной строки (это полный путь к бинарнику),
520
+ // а comm используем только как запасной вариант.
521
+ const { stdout: argsOut } = await execFileAsync("ps", ["-p", String(pid), "-o", "args="], {
522
+ windowsHide: true,
523
+ });
524
+ const args = argsOut.trim();
525
+ const argv0 = args.split(/\s+/)[0]?.replace(/^["']|["']$/g, "") ?? "";
526
+ let name = argv0.split(/[\\/]/).pop() ?? "";
527
+
528
+ if (!name) {
529
+ const { stdout: commOut } = await execFileAsync("ps", ["-p", String(pid), "-o", "comm="], {
530
+ windowsHide: true,
531
+ });
532
+ const comm = commOut.trim();
533
+ if (!comm) return null;
534
+ name = comm.split(/[\\/]/).pop() || comm;
535
+ }
536
+
537
+ return { name, commandLine: args };
538
+ } catch {
539
+ return null;
540
+ }
541
+ }
542
+
435
543
  /** Проверяет по маркер-заголовку, что на порту отвечает наш дашборд. */
436
544
  async function isOwnDashboardOn(port: number): Promise<boolean> {
437
545
  try {
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("solid-js/web"),m=require("solid-js"),a=require("@opencode/plugin/gui");function p(r){switch(r){case"running":return"●";case"error":return"✗";case"success":return"✓";default:return"?"}}async function _(r){return[]}var $=e.template("<div style=padding:8px><h4>Планировщик Windows"),g=e.template("<p>Задач пока нет"),v=e.template("<ul>"),f=e.template("<li> ");const h=a.Plugin.define({setup(r){const[u,i]=m.createSignal([]);return _().then(i).catch(()=>i([])),r.add(a.Panel,{id:"scheduler-jobs",region:"side",list:()=>[{id:"jobs",title:"Планировщик",pinned:!0}],render:()=>(()=>{var s=$();return s.firstChild,e.insert(s,(()=>{var c=e.memo(()=>u().length===0);return()=>c()?g():(()=>{var l=v();return e.insert(l,()=>u().map(n=>(()=>{var t=f(),o=t.firstChild;return e.insert(t,()=>p(n.status),o),e.insert(t,()=>n.name,null),e.insert(t,(()=>{var d=e.memo(()=>!!n.nextRun);return()=>d()?` → ${n.nextRun}`:""})(),null),t})())),l})()})(),null),s})()})}});exports.default=h;