@aiwayds/dsh-opentui 0.27.2 → 0.28.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.
@@ -1,173 +0,0 @@
1
- // Idle-exit reaper (ADR-0005 decision 5, entry-side companion of
2
- // lifecycle.ts): the lifecycle's idle-exit timer is unref()ed — a
3
- // refcount-0 manager must stay free to exit — so a cleanly quitting TUI
4
- // cannot deliver "the host exits after DSH_OPENTUI_HOST_IDLE_MS of
5
- // idleness" with an in-process timer. The quitting client spawns this
6
- // script DETACHED instead (spawnIdleReaper in src/client/boot-shared.ts):
7
- //
8
- // node idle-reaper.mjs <pid> <port> <lockfilePath> <idleMs>
9
- //
10
- // It owns the idle window after the last client disconnected. During the
11
- // window it polls the port and the lockfile; a client coming back CANCELS
12
- // the timer (exit 0, the host stays — that client's own quit arms the next
13
- // reaper). It never touches a host it does not own:
14
- //
15
- // - the lockfile now describes a DIFFERENT pid (a fresh boot — or
16
- // lifecycle's `booting` placeholder, pid = the booting client — replaced
17
- // the host): exit without killing;
18
- // - the lockfile GENERATION moved since the window started (lifecycle's
19
- // adoptHost bumps startedAt/mtime): a client adopted the host and may
20
- // still be minting its cookie (up to ~15s) before its first ESTABLISHED
21
- // connection — spare it;
22
- // - an ESTABLISHED TCP connection to the host port (the adoption path's
23
- // liveness marker): a client re-attached, spare it;
24
- // - the lockfile cannot be read: never kill what we cannot verify.
25
- //
26
- // After the window with none of the above, it appends one line to
27
- // `<dshHome>/opentui-host.idle.log`
28
- // <iso> reason=idle idleMs=<n> lastClientAt=<iso> host=<pid> port=<n>
29
- // then SIGTERMs the host, escalates to SIGKILL after 2s, and clears the
30
- // lockfile only while it still describes this host.
31
- //
32
- // The probe is `lsof -sTCP:ESTABLISHED`; when the tool is unavailable the
33
- // reaper falls back to the plain lifecycle semantics (idle exit).
34
- //
35
- // Idempotent and leak-free: no sockets are opened (lsof is a child
36
- // process), the process exits by itself, and a replacement host's lock is
37
- // never removed.
38
- import { appendFileSync, readFileSync, rmSync, statSync } from 'node:fs'
39
- import { spawnSync } from 'node:child_process'
40
- import { dirname, join } from 'node:path'
41
-
42
- const [pidArg, portArg, lockPath, idleMsArg] = process.argv.slice(2)
43
- const pid = Number(pidArg)
44
- const port = Number(portArg)
45
- const idleMs = Number(idleMsArg)
46
-
47
- // Defensive argument handling: the spawner always passes valid values, but
48
- // a stray manual invocation must exit quietly instead of throwing.
49
- if (!lockPath || !Number.isFinite(pid) || pid <= 0 || !Number.isFinite(idleMs) || idleMs < 0) {
50
- process.exit(2)
51
- }
52
-
53
- const startedAt = Date.now()
54
- /** Poll cadence inside the window: fine enough to notice a re-attach well
55
- * before the deadline, coarse enough to keep `lsof` cheap. */
56
- const POLL_MS = Math.max(50, Math.min(500, Math.round(idleMs / 10) || 50))
57
-
58
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
59
-
60
- const pidAlive = (target) => {
61
- try {
62
- process.kill(target, 0)
63
- } catch (err) {
64
- return err?.code === 'EPERM'
65
- }
66
- // kill(0) succeeds for an unreaped zombie; confirm via ps (fall back to
67
- // the kill(0) verdict when ps is unavailable).
68
- try {
69
- const res = spawnSync('ps', ['-p', String(target), '-o', 'stat='], { encoding: 'utf8' })
70
- if (!res.error && res.status === 0) return !(res.stdout ?? '').trim().startsWith('Z')
71
- } catch {}
72
- return true
73
- }
74
-
75
- /** Established TCP connections involving the host port (0 = none, -1 =
76
- * the probe tool is unavailable). lsof exits 1 with no output when the
77
- * filter matches nothing — that IS the zero case. */
78
- function establishedTo(targetPort) {
79
- const res = spawnSync('lsof', ['-nP', `-iTCP:${targetPort}`, '-sTCP:ESTABLISHED'], { encoding: 'utf8' })
80
- if (res.error) return -1
81
- if (res.status === 1) return 0
82
- const lines = String(res.stdout ?? '').split('\n')
83
- return Math.max(0, lines.slice(1).filter((l) => l.trim().length > 0).length)
84
- }
85
-
86
- /** Lockfile snapshot: the ownership fields plus the mtime used as the
87
- * generation token. null when the lock is missing or unreadable. */
88
- function readLock() {
89
- try {
90
- const raw = JSON.parse(readFileSync(lockPath, 'utf8'))
91
- if (typeof raw?.pid !== 'number') return null
92
- let mtimeMs = 0
93
- try {
94
- mtimeMs = statSync(lockPath).mtimeMs
95
- } catch {
96
- mtimeMs = 0
97
- }
98
- return { pid: raw.pid, port: raw.port, startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '', mtimeMs }
99
- } catch {
100
- return null
101
- }
102
- }
103
-
104
- /** Has this lockfile moved to a new generation since `base`? Adoption
105
- * rewrites `startedAt`; the mtime comparison is the belt-and-braces for a
106
- * writer that keeps the field identical. */
107
- function generationMoved(base, current) {
108
- if (!base || !current) return false
109
- if (current.startedAt !== base.startedAt) return true
110
- return current.mtimeMs > base.mtimeMs + 1
111
- }
112
-
113
- const logPath = join(dirname(lockPath), 'opentui-host.idle.log')
114
- function logIdleExit(hostPort) {
115
- const line =
116
- `${new Date().toISOString()} reason=idle idleMs=${idleMs} ` +
117
- `lastClientAt=${new Date(startedAt).toISOString()} host=${pid} port=${hostPort}\n`
118
- try {
119
- appendFileSync(logPath, line)
120
- } catch {}
121
- try {
122
- process.stderr.write(line) // usually /dev/null (detached, stdio ignore)
123
- } catch {}
124
- }
125
-
126
- const initial = readLock()
127
- if (!initial || initial.pid !== pid) process.exit(0) // nothing of ours to reap
128
-
129
- const deadline = startedAt + idleMs
130
- for (;;) {
131
- const remaining = deadline - Date.now()
132
- if (remaining <= 0) break
133
- await sleep(Math.min(POLL_MS, remaining))
134
-
135
- const current = readLock()
136
- if (!current) continue // mid-rewrite or vanished: re-check at the deadline
137
- if (current.pid !== pid) process.exit(0) // replaced by a fresh boot — not ours
138
- if (generationMoved(initial, current)) process.exit(0) // adopted mid-window — a client is coming
139
- if (establishedTo(port) > 0) process.exit(0) // a client re-attached — cancel the idle exit
140
- }
141
-
142
- // Final gate: re-verify everything we saw during the window. Anything
143
- // ambiguous (unreadable lock) means "do not kill".
144
- const finalLock = readLock()
145
- if (!finalLock) process.exit(0)
146
- if (finalLock.pid !== pid) process.exit(0)
147
- if (generationMoved(initial, finalLock)) process.exit(0)
148
- if (establishedTo(port) > 0) process.exit(0)
149
-
150
- logIdleExit(finalLock.port ?? port)
151
- try {
152
- process.kill(pid, 'SIGTERM')
153
- } catch {}
154
- // Graceful window for the host's own SIGTERM disposer; escalate only when
155
- // it is still alive afterwards. Polling (not a flat sleep) lets the lockfile
156
- // cleanup happen as soon as the host is gone, so a new client booting right
157
- // after the exit does not see a stale lock.
158
- const killDeadline = Date.now() + 2000
159
- while (Date.now() < killDeadline && pidAlive(pid)) await sleep(50)
160
- if (pidAlive(pid)) {
161
- try {
162
- process.kill(pid, 'SIGKILL')
163
- } catch {}
164
- const hardDeadline = Date.now() + 500
165
- while (Date.now() < hardDeadline && pidAlive(pid)) await sleep(25)
166
- }
167
- // Clear the lockfile only if it still describes THIS host (never clobber
168
- // a newer host's lock — lifecycle parity).
169
- try {
170
- const now = readLock()
171
- if (now && now.pid === pid && now.port === finalLock.port) rmSync(lockPath, { force: true })
172
- } catch {}
173
- process.exit(0)