@ddtcorex/dsh-maestro-core 0.10.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/LICENSE +21 -0
- package/README.md +209 -0
- package/cordis.patch.yml +43 -0
- package/lib/bin.d.ts +2 -0
- package/lib/bin.js +3 -0
- package/lib/boot-guard.d.ts +33 -0
- package/lib/boot-guard.js +68 -0
- package/lib/boot-lock.d.ts +56 -0
- package/lib/boot-lock.js +155 -0
- package/lib/cli.d.ts +31 -0
- package/lib/cli.js +336 -0
- package/lib/client.js +2901 -0
- package/lib/config/index.d.ts +34 -0
- package/lib/config/index.js +62 -0
- package/lib/config/service.d.ts +18 -0
- package/lib/config/service.js +28 -0
- package/lib/config.d.ts +1 -0
- package/lib/config.js +19 -0
- package/lib/daemon-freshness.d.ts +48 -0
- package/lib/daemon-freshness.js +122 -0
- package/lib/debug-agent.d.ts +17 -0
- package/lib/debug-agent.js +144 -0
- package/lib/dsh-session.d.ts +26 -0
- package/lib/dsh-session.js +45 -0
- package/lib/guard/config.d.ts +82 -0
- package/lib/guard/config.js +211 -0
- package/lib/guard/decide.d.ts +30 -0
- package/lib/guard/decide.js +38 -0
- package/lib/guard/full-scan-tool.d.ts +6 -0
- package/lib/guard/full-scan-tool.js +65 -0
- package/lib/guard/index.d.ts +85 -0
- package/lib/guard/index.js +254 -0
- package/lib/guard/journal.d.ts +146 -0
- package/lib/guard/journal.js +398 -0
- package/lib/guard/migrate.d.ts +15 -0
- package/lib/guard/migrate.js +42 -0
- package/lib/guard/parse.d.ts +193 -0
- package/lib/guard/parse.js +1103 -0
- package/lib/guard/paths.d.ts +104 -0
- package/lib/guard/paths.js +254 -0
- package/lib/guard/permission-policy.d.ts +10 -0
- package/lib/guard/permission-policy.js +21 -0
- package/lib/guard/redact.d.ts +25 -0
- package/lib/guard/redact.js +52 -0
- package/lib/guard/rules.d.ts +65 -0
- package/lib/guard/rules.js +832 -0
- package/lib/guard/status-tool.d.ts +54 -0
- package/lib/guard/status-tool.js +195 -0
- package/lib/guard/tiers.d.ts +2 -0
- package/lib/guard/tiers.js +1 -0
- package/lib/guard/validators.d.ts +4 -0
- package/lib/guard/validators.js +45 -0
- package/lib/health-poller.d.ts +90 -0
- package/lib/health-poller.js +430 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +7 -0
- package/lib/intents.d.ts +32 -0
- package/lib/intents.js +49 -0
- package/lib/notifier.d.ts +12 -0
- package/lib/notifier.js +62 -0
- package/lib/paths.d.ts +13 -0
- package/lib/paths.js +70 -0
- package/lib/plugin.d.ts +250 -0
- package/lib/plugin.js +1126 -0
- package/lib/preset.d.ts +73 -0
- package/lib/preset.js +158 -0
- package/lib/report.d.ts +11 -0
- package/lib/report.js +58 -0
- package/lib/restart-exec.d.ts +35 -0
- package/lib/restart-exec.js +60 -0
- package/lib/restart-guards.d.ts +39 -0
- package/lib/restart-guards.js +150 -0
- package/lib/restart-tool.d.ts +124 -0
- package/lib/restart-tool.js +539 -0
- package/lib/restart-web.d.ts +26 -0
- package/lib/restart-web.js +58 -0
- package/lib/resume-log.d.ts +24 -0
- package/lib/resume-log.js +18 -0
- package/lib/resume-tools.d.ts +131 -0
- package/lib/resume-tools.js +337 -0
- package/lib/resume.d.ts +33 -0
- package/lib/resume.js +221 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +81 -0
- package/lib/self-kill-guard.js +208 -0
- package/lib/session-health.d.ts +89 -0
- package/lib/session-health.js +274 -0
- package/lib/session-log-file.d.ts +22 -0
- package/lib/session-log-file.js +74 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +73 -0
- package/lib/snapshot.d.ts +59 -0
- package/lib/snapshot.js +358 -0
- package/lib/source.d.ts +19 -0
- package/lib/source.js +19 -0
- package/lib/store/index.d.ts +42 -0
- package/lib/store/index.js +340 -0
- package/lib/store/legacy.d.ts +17 -0
- package/lib/store/legacy.js +85 -0
- package/lib/supervisor.d.ts +119 -0
- package/lib/supervisor.js +741 -0
- package/lib/sync/backup-config.d.ts +55 -0
- package/lib/sync/backup-config.js +119 -0
- package/lib/sync/backup-service.d.ts +110 -0
- package/lib/sync/backup-service.js +440 -0
- package/lib/sync/bidirectional.d.ts +39 -0
- package/lib/sync/bidirectional.js +25 -0
- package/lib/sync/cli.d.ts +38 -0
- package/lib/sync/cli.js +536 -0
- package/lib/sync/config.d.ts +77 -0
- package/lib/sync/config.js +90 -0
- package/lib/sync/fingerprint.d.ts +29 -0
- package/lib/sync/fingerprint.js +65 -0
- package/lib/sync/hashing.d.ts +9 -0
- package/lib/sync/hashing.js +47 -0
- package/lib/sync/index.d.ts +6 -0
- package/lib/sync/index.js +634 -0
- package/lib/sync/machine-id.d.ts +29 -0
- package/lib/sync/machine-id.js +66 -0
- package/lib/sync/merge.d.ts +33 -0
- package/lib/sync/merge.js +88 -0
- package/lib/sync/peer-host.d.ts +22 -0
- package/lib/sync/peer-host.js +62 -0
- package/lib/sync/process-runner.d.ts +31 -0
- package/lib/sync/process-runner.js +161 -0
- package/lib/sync/remote-agent.d.ts +42 -0
- package/lib/sync/remote-agent.js +217 -0
- package/lib/sync/remote-cache.d.ts +18 -0
- package/lib/sync/remote-cache.js +60 -0
- package/lib/sync/remote-manifest.d.ts +8 -0
- package/lib/sync/remote-manifest.js +64 -0
- package/lib/sync/s3-object-store.d.ts +38 -0
- package/lib/sync/s3-object-store.js +126 -0
- package/lib/sync/session-merge.d.ts +18 -0
- package/lib/sync/session-merge.js +191 -0
- package/lib/sync/session-plan.d.ts +29 -0
- package/lib/sync/session-plan.js +213 -0
- package/lib/sync/sigv4.d.ts +20 -0
- package/lib/sync/sigv4.js +57 -0
- package/lib/sync/snapshot.d.ts +21 -0
- package/lib/sync/snapshot.js +176 -0
- package/lib/sync/ssh-mux.d.ts +12 -0
- package/lib/sync/ssh-mux.js +48 -0
- package/lib/sync/sync-plan.d.ts +24 -0
- package/lib/sync/sync-plan.js +366 -0
- package/lib/sync/sync-service.d.ts +177 -0
- package/lib/sync/sync-service.js +819 -0
- package/lib/sync/sync-types.d.ts +87 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/transport.d.ts +75 -0
- package/lib/sync/transport.js +200 -0
- package/lib/sync/tunnel-restore.d.ts +77 -0
- package/lib/sync/tunnel-restore.js +142 -0
- package/lib/sync/validation.d.ts +10 -0
- package/lib/sync/validation.js +83 -0
- package/lib/tool-view.d.ts +62 -0
- package/lib/tool-view.js +70 -0
- package/lib/types/client/auto-reload.d.ts +8 -0
- package/lib/types/client/auto-reload.d.ts.map +1 -0
- package/lib/types/client/config/MaestroSettings.d.ts +25 -0
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
- package/lib/types/client/config/components/BrandMark.d.ts +50 -0
- package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
- package/lib/types/client/config/guard-view.d.ts +83 -0
- package/lib/types/client/config/guard-view.d.ts.map +1 -0
- package/lib/types/client/config/index.d.ts +20 -0
- package/lib/types/client/config/index.d.ts.map +1 -0
- package/lib/types/client/config/maestro-mark.d.ts +29 -0
- package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
- package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
- package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +16 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/SyncPanel.d.ts +12 -0
- package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
- package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
- package/lib/types/client/sync/index.d.ts +10 -0
- package/lib/types/client/sync/index.d.ts.map +1 -0
- package/lib/types/client/sync/ui.d.ts +79 -0
- package/lib/types/client/sync/ui.d.ts.map +1 -0
- package/lib/types/client/sync/use-backup.d.ts +50 -0
- package/lib/types/client/sync/use-backup.d.ts.map +1 -0
- package/lib/types/client/sync/use-sync.d.ts +88 -0
- package/lib/types/client/sync/use-sync.d.ts.map +1 -0
- package/package.json +89 -0
- package/skills/dsh-safe-restart/SKILL.md +206 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
- package/src/client/auto-reload.ts +104 -0
- package/src/client/config/MaestroSettings.tsx +892 -0
- package/src/client/config/components/BrandMark.tsx +94 -0
- package/src/client/config/guard-view.ts +187 -0
- package/src/client/config/index.tsx +109 -0
- package/src/client/config/maestro-mark.ts +37 -0
- package/src/client/config/settings-nav-icon.ts +68 -0
- package/src/client/index.tsx +33 -0
- package/src/client/sync/R2SyncPanel.tsx +260 -0
- package/src/client/sync/SyncPanel.tsx +422 -0
- package/src/client/sync/confirm-dialog.tsx +202 -0
- package/src/client/sync/index.tsx +336 -0
- package/src/client/sync/ui.tsx +313 -0
- package/src/client/sync/use-backup.ts +207 -0
- package/src/client/sync/use-sync.ts +502 -0
- package/src/host/bin.ts +3 -0
- package/src/host/boot-guard.ts +76 -0
- package/src/host/boot-lock.ts +155 -0
- package/src/host/cli.ts +288 -0
- package/src/host/config/index.ts +78 -0
- package/src/host/config/service.ts +40 -0
- package/src/host/config.ts +18 -0
- package/src/host/daemon-freshness.ts +143 -0
- package/src/host/debug-agent.ts +145 -0
- package/src/host/dsh-session.ts +56 -0
- package/src/host/dsh-skill.d.ts +44 -0
- package/src/host/guard/augment.d.ts +33 -0
- package/src/host/guard/config.ts +244 -0
- package/src/host/guard/decide.ts +40 -0
- package/src/host/guard/full-scan-tool.ts +61 -0
- package/src/host/guard/index.ts +281 -0
- package/src/host/guard/journal.ts +440 -0
- package/src/host/guard/migrate.ts +41 -0
- package/src/host/guard/parse.ts +1150 -0
- package/src/host/guard/paths.ts +239 -0
- package/src/host/guard/permission-policy.ts +15 -0
- package/src/host/guard/redact.ts +64 -0
- package/src/host/guard/rules.ts +891 -0
- package/src/host/guard/status-tool.ts +229 -0
- package/src/host/guard/tiers.ts +2 -0
- package/src/host/guard/validators.ts +29 -0
- package/src/host/health-poller.ts +446 -0
- package/src/host/index.ts +7 -0
- package/src/host/intents.ts +67 -0
- package/src/host/notifier.ts +71 -0
- package/src/host/paths.ts +70 -0
- package/src/host/plugin.ts +1097 -0
- package/src/host/preset.ts +170 -0
- package/src/host/report.ts +71 -0
- package/src/host/restart-exec.ts +81 -0
- package/src/host/restart-guards.ts +150 -0
- package/src/host/restart-tool.ts +483 -0
- package/src/host/restart-web.ts +72 -0
- package/src/host/resume-log.ts +39 -0
- package/src/host/resume-tools.ts +385 -0
- package/src/host/resume.ts +204 -0
- package/src/host/scan.ts +61 -0
- package/src/host/self-kill-guard.ts +216 -0
- package/src/host/session-health.ts +236 -0
- package/src/host/session-log-file.ts +77 -0
- package/src/host/skill-provider.ts +69 -0
- package/src/host/snapshot.ts +337 -0
- package/src/host/source.ts +19 -0
- package/src/host/store/index.ts +348 -0
- package/src/host/store/legacy.ts +96 -0
- package/src/host/supervisor.ts +720 -0
- package/src/host/sync/backup-config.ts +159 -0
- package/src/host/sync/backup-service.ts +453 -0
- package/src/host/sync/bidirectional.ts +66 -0
- package/src/host/sync/cli.ts +539 -0
- package/src/host/sync/config.ts +119 -0
- package/src/host/sync/fingerprint.ts +83 -0
- package/src/host/sync/hashing.ts +58 -0
- package/src/host/sync/index.ts +737 -0
- package/src/host/sync/machine-id.ts +81 -0
- package/src/host/sync/merge.ts +102 -0
- package/src/host/sync/peer-host.ts +65 -0
- package/src/host/sync/process-runner.ts +177 -0
- package/src/host/sync/remote-agent.ts +213 -0
- package/src/host/sync/remote-cache.ts +68 -0
- package/src/host/sync/remote-manifest.ts +70 -0
- package/src/host/sync/s3-object-store.ts +144 -0
- package/src/host/sync/session-merge.ts +220 -0
- package/src/host/sync/session-plan.ts +237 -0
- package/src/host/sync/sigv4.ts +81 -0
- package/src/host/sync/snapshot.ts +162 -0
- package/src/host/sync/ssh-mux.ts +56 -0
- package/src/host/sync/sync-plan.ts +366 -0
- package/src/host/sync/sync-service.ts +855 -0
- package/src/host/sync/sync-types.ts +102 -0
- package/src/host/sync/transport.ts +261 -0
- package/src/host/sync/tunnel-restore.ts +160 -0
- package/src/host/sync/validation.ts +91 -0
- package/src/host/tool-view.ts +98 -0
package/lib/resume.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import { resolveSessionLogPath } from './session-log-file.js';
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the readable session log inside one session directory. Owned by
|
|
7
|
+
* `session-log-file.ts` — the single owner of "which file is the log":
|
|
8
|
+
* generations are discovered, never listed, because enumerating them went
|
|
9
|
+
* blind twice (v3 on 2026-09-11, v4 on 2026-09-23). Re-exported here because
|
|
10
|
+
* `plugin.ts` and `preset.ts` already import it from this module.
|
|
11
|
+
*/
|
|
12
|
+
export { resolveSessionLogPath };
|
|
13
|
+
/**
|
|
14
|
+
* Read the last ~100 lines of one session's raw log, applying the mtime
|
|
15
|
+
* pre-filter before any (potentially expensive) zstd decompression: a
|
|
16
|
+
* session log's mtime only advances when something is appended to it, so a
|
|
17
|
+
* file older than `sinceMs` cannot contain anything within the window.
|
|
18
|
+
* Shared by every raw-log scan below so the pre-filter (Critical: this
|
|
19
|
+
* scan previously blocked the host event loop ~5.5s across 412 sessions on
|
|
20
|
+
* a real machine before this filter existed) can't be accidentally
|
|
21
|
+
* bypassed by a future scan variant.
|
|
22
|
+
* @returns `undefined` when the session has no log file, or is filtered
|
|
23
|
+
* out by `sinceMs` — callers must treat that the same as "nothing found".
|
|
24
|
+
*/
|
|
25
|
+
async function readSessionTailLines(logPath, sinceMs) {
|
|
26
|
+
if (logPath === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
if (sinceMs !== undefined) {
|
|
29
|
+
try {
|
|
30
|
+
if (fs.statSync(logPath).mtimeMs < sinceMs)
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
catch { }
|
|
34
|
+
}
|
|
35
|
+
if (logPath.endsWith('.zstd')) {
|
|
36
|
+
const { execSync } = await import('node:child_process');
|
|
37
|
+
const out = execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null | tail -100`, { encoding: 'utf-8' });
|
|
38
|
+
return out.split('\n').filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const content = fs.readFileSync(logPath, 'utf-8');
|
|
42
|
+
return content.trim().split('\n').slice(-100);
|
|
43
|
+
}
|
|
44
|
+
catch { }
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
export async function findInterrupted(dshHome, opts) {
|
|
48
|
+
const home = dshHome ?? path.join(os.homedir(), '.dsh');
|
|
49
|
+
const sessionsRoot = path.join(home, 'sessions');
|
|
50
|
+
let scanned = 0;
|
|
51
|
+
const interrupted = [];
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
const withinMs = opts?.withinMs;
|
|
54
|
+
const sinceMs = opts?.sinceMs ?? (withinMs !== undefined ? now - withinMs : undefined);
|
|
55
|
+
try {
|
|
56
|
+
const groups = fs.readdirSync(sessionsRoot, { withFileTypes: true });
|
|
57
|
+
for (const g of groups) {
|
|
58
|
+
if (!g.isDirectory())
|
|
59
|
+
continue;
|
|
60
|
+
const groupPath = path.join(sessionsRoot, g.name);
|
|
61
|
+
const sessions = fs.readdirSync(groupPath, { withFileTypes: true });
|
|
62
|
+
for (const s of sessions) {
|
|
63
|
+
if (!s.isDirectory())
|
|
64
|
+
continue;
|
|
65
|
+
scanned++;
|
|
66
|
+
const logPath = resolveSessionLogPath(path.join(groupPath, s.name));
|
|
67
|
+
try {
|
|
68
|
+
const lines = await readSessionTailLines(logPath, sinceMs);
|
|
69
|
+
if (lines === undefined)
|
|
70
|
+
continue;
|
|
71
|
+
let found = false;
|
|
72
|
+
let foundTime;
|
|
73
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
74
|
+
const line = lines[i];
|
|
75
|
+
try {
|
|
76
|
+
const obj = JSON.parse(line);
|
|
77
|
+
foundTime = typeof obj.time === 'number' ? obj.time : undefined;
|
|
78
|
+
if (obj.type === 'turn/end' && obj.data?.reason?.kind === 'interrupted') {
|
|
79
|
+
found = true;
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch { }
|
|
84
|
+
}
|
|
85
|
+
if (!found)
|
|
86
|
+
continue;
|
|
87
|
+
if (sinceMs !== undefined && foundTime !== undefined) {
|
|
88
|
+
if (foundTime < sinceMs)
|
|
89
|
+
continue; // too old
|
|
90
|
+
}
|
|
91
|
+
else if (sinceMs !== undefined && foundTime === undefined) {
|
|
92
|
+
// no timestamp, skip when filtering by time
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
interrupted.push(`${g.name}/${s.name}`);
|
|
96
|
+
}
|
|
97
|
+
catch { }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch { }
|
|
102
|
+
return { scanned, interrupted };
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Read the entire log for a recent session (mtime within window) to find an
|
|
106
|
+
* open turn that may be far from the tail. Used only by
|
|
107
|
+
* {@link findDanglingOpenTurns}, which must see the last `turn/start`
|
|
108
|
+
* even when the file is 1906 lines and the open turn is at line 2 (subagent
|
|
109
|
+
* `b6487e33` had its only `turn/start` at seq 6, missed by `tail -100`).
|
|
110
|
+
* The mtime pre-filter ensures this full decompression runs only for
|
|
111
|
+
* recent sessions (within 5m, typically 1-2 files), not for all 425.
|
|
112
|
+
*/
|
|
113
|
+
async function readSessionAllLines(logPath, sinceMs) {
|
|
114
|
+
if (logPath === undefined)
|
|
115
|
+
return undefined;
|
|
116
|
+
if (sinceMs !== undefined) {
|
|
117
|
+
try {
|
|
118
|
+
if (fs.statSync(logPath).mtimeMs < sinceMs)
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
catch { }
|
|
122
|
+
}
|
|
123
|
+
if (logPath.endsWith('.zstd')) {
|
|
124
|
+
const { execSync } = await import('node:child_process');
|
|
125
|
+
// maxBuffer must exceed the decompressed size of any real session log —
|
|
126
|
+
// worker sessions decode to 8-23MB while execSync's default 1MB would
|
|
127
|
+
// throw ENOBUFS and silently drop the session from every scan that needs
|
|
128
|
+
// the full file (findDanglingOpenTurns). Use 64MB to leave headroom.
|
|
129
|
+
const out = execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null`, { encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 });
|
|
130
|
+
return out.split('\n').filter(Boolean);
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const content = fs.readFileSync(logPath, 'utf-8');
|
|
134
|
+
return content.trim().split('\n').filter(Boolean);
|
|
135
|
+
}
|
|
136
|
+
catch { }
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Detect sessions whose raw log ends with a `turn/start` that has no
|
|
141
|
+
* matching `turn/end` anywhere later in the scanned log — a dangling open
|
|
142
|
+
* turn. Unlike {@link findInterrupted}, this needs no prior `persistence.load()`
|
|
143
|
+
* call to have already synthesized a `turn/end interrupted` closer (DSH core
|
|
144
|
+
* only writes that closer when something loads/prepares the specific
|
|
145
|
+
* session — a genuinely fresh crash's raw log has no closer at all, only an
|
|
146
|
+
* open turn). Safe to call ONLY right after a fresh `dsh web` boot, when
|
|
147
|
+
* `dsh web` is the sole live process for these sessions — an open turn found
|
|
148
|
+
* at that moment cannot belong to a still-running generation anywhere else.
|
|
149
|
+
* Callers MUST additionally skip any id that is live in their own current
|
|
150
|
+
* process (e.g. `ctx.sessions.get(id)`) before treating a match as crashed.
|
|
151
|
+
*/
|
|
152
|
+
export async function findDanglingOpenTurns(dshHome, opts) {
|
|
153
|
+
const home = dshHome ?? path.join(os.homedir(), '.dsh');
|
|
154
|
+
const sessionsRoot = path.join(home, 'sessions');
|
|
155
|
+
let scanned = 0;
|
|
156
|
+
const interrupted = [];
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
const withinMs = opts?.withinMs;
|
|
159
|
+
const sinceMs = opts?.sinceMs ?? (withinMs !== undefined ? now - withinMs : undefined);
|
|
160
|
+
try {
|
|
161
|
+
const groups = fs.readdirSync(sessionsRoot, { withFileTypes: true });
|
|
162
|
+
for (const g of groups) {
|
|
163
|
+
if (!g.isDirectory())
|
|
164
|
+
continue;
|
|
165
|
+
const groupPath = path.join(sessionsRoot, g.name);
|
|
166
|
+
const sessions = fs.readdirSync(groupPath, { withFileTypes: true });
|
|
167
|
+
for (const s of sessions) {
|
|
168
|
+
if (!s.isDirectory())
|
|
169
|
+
continue;
|
|
170
|
+
scanned++;
|
|
171
|
+
const logPath = resolveSessionLogPath(path.join(groupPath, s.name));
|
|
172
|
+
try {
|
|
173
|
+
const lines = await readSessionAllLines(logPath, sinceMs);
|
|
174
|
+
if (lines === undefined)
|
|
175
|
+
continue;
|
|
176
|
+
let openTurn;
|
|
177
|
+
for (const line of lines) {
|
|
178
|
+
try {
|
|
179
|
+
const obj = JSON.parse(line);
|
|
180
|
+
if (obj.type === 'turn/start' && typeof obj.data?.turn === 'number') {
|
|
181
|
+
openTurn = obj.data.turn;
|
|
182
|
+
}
|
|
183
|
+
else if (obj.type === 'turn/end' && obj.data?.turn === openTurn) {
|
|
184
|
+
openTurn = undefined;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch { }
|
|
188
|
+
}
|
|
189
|
+
if (openTurn === undefined)
|
|
190
|
+
continue;
|
|
191
|
+
// The requested window is enforced by the log's mtime in
|
|
192
|
+
// readSessionAllLines: a file appended to within the window may hold
|
|
193
|
+
// a fresh crash. It must NOT be re-checked against the open turn's
|
|
194
|
+
// own start time — a turn that ran longer than the window (a real
|
|
195
|
+
// 21-minute turn on 2026-09-13) then looked old and was skipped, so a
|
|
196
|
+
// restart mid-turn triggered no auto-continue.
|
|
197
|
+
interrupted.push(`${g.name}/${s.name}`);
|
|
198
|
+
}
|
|
199
|
+
catch { }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch { }
|
|
204
|
+
return { scanned, interrupted };
|
|
205
|
+
}
|
|
206
|
+
export function parseDuration(s) {
|
|
207
|
+
if (!s)
|
|
208
|
+
return undefined;
|
|
209
|
+
const m = s.trim().match(/^(\d+)(s|m|h)?$/);
|
|
210
|
+
if (!m)
|
|
211
|
+
return undefined;
|
|
212
|
+
const n = parseInt(m[1], 10);
|
|
213
|
+
const unit = m[2] ?? 's';
|
|
214
|
+
if (unit === 's')
|
|
215
|
+
return n * 1000;
|
|
216
|
+
if (unit === 'm')
|
|
217
|
+
return n * 60 * 1000;
|
|
218
|
+
if (unit === 'h')
|
|
219
|
+
return n * 60 * 60 * 1000;
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
package/lib/scan.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Post-restart session scan: walk recent session logs under
|
|
3
|
+
* <dshHome>/sessions/<project>/<session>/ and flag torn tails (a zstd frame
|
|
4
|
+
* that fails to decode, or a plain-text log that is unreadable). Runs after
|
|
5
|
+
* an intentional dsh-web restart so the supervisor can report whether any
|
|
6
|
+
* in-flight session log was left truncated by the restart.
|
|
7
|
+
*/
|
|
8
|
+
interface ScanOptions {
|
|
9
|
+
withinMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Scan session logs whose mtime falls within the window. A file whose decode
|
|
13
|
+
* fails (torn zstd frame or unreadable plain text) is reported as torn. A
|
|
14
|
+
* missing sessions root yields an empty scan, never an error.
|
|
15
|
+
*/
|
|
16
|
+
export declare function scanSessions(dshHome: string, opts?: ScanOptions): Promise<{
|
|
17
|
+
scanned: number;
|
|
18
|
+
torn: string[];
|
|
19
|
+
}>;
|
|
20
|
+
export {};
|
package/lib/scan.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Post-restart session scan: walk recent session logs under
|
|
3
|
+
* <dshHome>/sessions/<project>/<session>/ and flag torn tails (a zstd frame
|
|
4
|
+
* that fails to decode, or a plain-text log that is unreadable). Runs after
|
|
5
|
+
* an intentional dsh-web restart so the supervisor can report whether any
|
|
6
|
+
* in-flight session log was left truncated by the restart.
|
|
7
|
+
*/
|
|
8
|
+
import { readdirSync, statSync } from 'node:fs';
|
|
9
|
+
import { join, extname, basename } from 'node:path';
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
async function decodeOk(file) {
|
|
12
|
+
try {
|
|
13
|
+
if (extname(file) === '.zstd') {
|
|
14
|
+
execFileSync('zstd', ['-d', '-c', file], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
const { readFileSync } = await import('node:fs');
|
|
18
|
+
readFileSync(file, 'utf8');
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Scan session logs whose mtime falls within the window. A file whose decode
|
|
28
|
+
* fails (torn zstd frame or unreadable plain text) is reported as torn. A
|
|
29
|
+
* missing sessions root yields an empty scan, never an error.
|
|
30
|
+
*/
|
|
31
|
+
export async function scanSessions(dshHome, opts = {}) {
|
|
32
|
+
const sessionsRoot = join(dshHome, 'sessions');
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const withinMs = opts.withinMs ?? 10 * 60 * 1000;
|
|
35
|
+
const files = [];
|
|
36
|
+
try {
|
|
37
|
+
for (const proj of readdirSync(sessionsRoot)) {
|
|
38
|
+
const projDir = join(sessionsRoot, proj);
|
|
39
|
+
if (!statSync(projDir).isDirectory())
|
|
40
|
+
continue;
|
|
41
|
+
for (const sess of readdirSync(projDir)) {
|
|
42
|
+
const sessDir = join(projDir, sess);
|
|
43
|
+
if (!statSync(sessDir).isDirectory())
|
|
44
|
+
continue;
|
|
45
|
+
for (const f of readdirSync(sessDir)) {
|
|
46
|
+
const name = basename(f);
|
|
47
|
+
if (!name.endsWith('.zstd') && !name.endsWith('.jsonl'))
|
|
48
|
+
continue;
|
|
49
|
+
const fp = join(sessDir, f);
|
|
50
|
+
let mtime = 0;
|
|
51
|
+
try {
|
|
52
|
+
mtime = statSync(fp).mtimeMs;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (now - mtime > withinMs)
|
|
58
|
+
continue;
|
|
59
|
+
files.push(fp);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch { /* sessions root absent */ }
|
|
65
|
+
const torn = [];
|
|
66
|
+
for (const f of files) {
|
|
67
|
+
if (!(await decodeOk(f)))
|
|
68
|
+
torn.push(f);
|
|
69
|
+
}
|
|
70
|
+
return { scanned: files.length, torn };
|
|
71
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-kill guard for `tools/pre-execute`: deny bash/shell commands that would
|
|
3
|
+
* kill or restart the very dsh web process the agent is running inside. The
|
|
4
|
+
* model must route restarts through the supervisor's dsh_web_restart tool, not
|
|
5
|
+
* by killing the host.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Remove data spans (quoted strings and heredoc bodies) from a command before
|
|
9
|
+
* self-kill matching. Text inside quotes or a heredoc is content — an echo,
|
|
10
|
+
* printf, node -e script or cat <<'EOF' body can legitimately discuss kill
|
|
11
|
+
* commands without executing one.
|
|
12
|
+
*/
|
|
13
|
+
export declare function stripDataSpans(cmd: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* The dsh web MainThread owns both ports (3000 = gitlab-webhook, 3080 = web).
|
|
16
|
+
* Only listeners on these ports can be dsh web; every other listening process
|
|
17
|
+
* on the host (mysql, sshd, nginx, redis, ...) is explicitly NOT protected.
|
|
18
|
+
*/
|
|
19
|
+
export declare const DSH_WEB_PORTS: number[];
|
|
20
|
+
export type TreeBoundaryKind = 'none' | 'launcher' | 'service-manager';
|
|
21
|
+
/**
|
|
22
|
+
* Boundary classification for the ancestor walk — mirrors
|
|
23
|
+
* `skills/dsh-safe-restart/scripts/restart-dsh-web.sh`'s `resolve_tree()`:
|
|
24
|
+
* the walk stops at `pnpm` (the launcher — everything above it is the
|
|
25
|
+
* launching shell, not dsh web) and never walks into a `systemd --user`
|
|
26
|
+
* manager (it owns every user unit on the box). `launcher` pids stay in the
|
|
27
|
+
* forest; `service-manager` pids are never included.
|
|
28
|
+
*/
|
|
29
|
+
export declare function treeBoundaryKind(commandLine: string): TreeBoundaryKind;
|
|
30
|
+
/** Convenience boolean form of {@link treeBoundaryKind}. */
|
|
31
|
+
export declare function isTreeBoundary(commandLine: string): boolean;
|
|
32
|
+
export interface ProcessRow {
|
|
33
|
+
pid: number;
|
|
34
|
+
ppid: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Resolve the pids that belong to the dsh web process forest. `listeners` are
|
|
38
|
+
* the pids owning the dsh-web ports (already narrowed by the caller). A pid is
|
|
39
|
+
* protected iff its upward ancestor chain reaches the forest before pid 1:
|
|
40
|
+
*
|
|
41
|
+
* - the forest roots are the listeners plus every ancestor up to the
|
|
42
|
+
* `launcher` boundary (pnpm stays inside the forest; systemd --user and
|
|
43
|
+
* the launching shell stay out);
|
|
44
|
+
* - the descendant closure then protects the whole owned subtree — the dsh
|
|
45
|
+
* web node processes AND their bash-tool/browser children — while never
|
|
46
|
+
* climbing into unrelated ancestors.
|
|
47
|
+
*
|
|
48
|
+
* `boundary(pid)` classifies the command line of a walked pid; it is only
|
|
49
|
+
* invoked for the handful of listener + ancestor pids, never for the full
|
|
50
|
+
* table.
|
|
51
|
+
*/
|
|
52
|
+
export declare function resolveDshWebTreePids(listeners: number[], rows: ProcessRow[], boundary?: (pid: number) => TreeBoundaryKind): number[];
|
|
53
|
+
/**
|
|
54
|
+
* Whether a shell command is a self-kill. `livePids` are the pids of the dsh
|
|
55
|
+
* web process forest; a `kill <pid>` whose pid is one of ours is a self-kill
|
|
56
|
+
* regardless of anything else in the command. The kill parser accepts flag
|
|
57
|
+
* forms (`kill -9 <pid>`, `kill -TERM <pid>`). A command that is essentially
|
|
58
|
+
* JUST a `kill <unrelated-pid>` is allowed (idempotent cleanups are common),
|
|
59
|
+
* as are kill attempts whose output reports "not found"/"done" — but any
|
|
60
|
+
* compound that chains a restart/kill after it (or before the end) stays
|
|
61
|
+
* denied.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isSelfKillCommand(cmd: string, livePids: number[]): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Live pids of the dsh web OWN forest: pids owning the dsh-web ports
|
|
66
|
+
* (3000/3080) plus their ancestor chain up to the pnpm/systemd boundary and
|
|
67
|
+
* the owned subtree. A kill of an unrelated listener (mysql/sshd/nginx) is
|
|
68
|
+
* therefore allowed — before this scoping the guard denied `kill <pid>` of ANY
|
|
69
|
+
* pid holding a listening socket as a "restart dsh web".
|
|
70
|
+
*/
|
|
71
|
+
export declare function dshWebTreeLivePids(): number[];
|
|
72
|
+
/**
|
|
73
|
+
* Build a `tools/pre-execute` waterfall listener: deny matching
|
|
74
|
+
* bash/shell/exec commands, otherwise delegate to `next()`. Live pids default
|
|
75
|
+
* to the dsh web process forest (see `dshWebTreeLivePids`) so `kill <pid>` of
|
|
76
|
+
* a live host process is caught even when the command names no tool, while a
|
|
77
|
+
* kill of an unrelated service is not.
|
|
78
|
+
*/
|
|
79
|
+
export declare function makePreExecuteGuard(opts?: {
|
|
80
|
+
livePids?: () => number[];
|
|
81
|
+
}): (exec: any, next: () => Promise<any>) => Promise<any>;
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-kill guard for `tools/pre-execute`: deny bash/shell commands that would
|
|
3
|
+
* kill or restart the very dsh web process the agent is running inside. The
|
|
4
|
+
* model must route restarts through the supervisor's dsh_web_restart tool, not
|
|
5
|
+
* by killing the host.
|
|
6
|
+
*/
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
// Patterns that restart/stop/start or kill dsh web (systemctl --user units,
|
|
10
|
+
// pkill/killall over the dsh tree, killing holders of :3080, and the
|
|
11
|
+
// dsh-safe-web-update helper itself). Matched — like dsh-maestro-guard —
|
|
12
|
+
// against the executed command surface with quoted/heredoc spans stripped, so
|
|
13
|
+
// text that merely MENTIONS these words (echo/printf/script bodies) is data,
|
|
14
|
+
// not argv.
|
|
15
|
+
const SELF_KILL_RE = /(systemctl\s+--?user\s+.*(restart|stop|start).*dsh-web|pkill\s+.*dsh|killall\s+.*dsh|ss\s+.*3080.*kill|restart-dsh-web)/i;
|
|
16
|
+
// A segment whose command position is one of these verbs is a real kill-family
|
|
17
|
+
// invocation: blanket-denied even when its target lives inside quotes
|
|
18
|
+
// (`pkill -f "dsh web"` must still be caught). `sudo`/`env VAR=` prefixes are
|
|
19
|
+
// stripped before the verb is read.
|
|
20
|
+
const DANGEROUS_KILL_VERB = /^(?:sudo\s+|env\s+\S+\s+)*(pkill|killall|kill|systemctl)\b/i;
|
|
21
|
+
/**
|
|
22
|
+
* Remove data spans (quoted strings and heredoc bodies) from a command before
|
|
23
|
+
* self-kill matching. Text inside quotes or a heredoc is content — an echo,
|
|
24
|
+
* printf, node -e script or cat <<'EOF' body can legitimately discuss kill
|
|
25
|
+
* commands without executing one.
|
|
26
|
+
*/
|
|
27
|
+
export function stripDataSpans(cmd) {
|
|
28
|
+
let out = cmd;
|
|
29
|
+
let prev = '';
|
|
30
|
+
while (out !== prev) {
|
|
31
|
+
prev = out;
|
|
32
|
+
// heredoc FIRST: the `<<'EOF'` delimiter quotes would otherwise be eaten by
|
|
33
|
+
// the generic quote-strip below and the body would survive as unquoted text
|
|
34
|
+
out = out.replace(/<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?[^\r\n]*\r?\n[\s\S]*?^\1\s*$/gm, ' ');
|
|
35
|
+
// quote spans respect backslash escapes (`\"` inside a double-quoted
|
|
36
|
+
// node -e body is content, not a delimiter) so nested literals stay stripped
|
|
37
|
+
out = out.replace(/"(?:[^"\\]|\\.)*"/g, ' ').replace(/'(?:[^'\\]|\\.)*'/g, ' ');
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The dsh web MainThread owns both ports (3000 = gitlab-webhook, 3080 = web).
|
|
43
|
+
* Only listeners on these ports can be dsh web; every other listening process
|
|
44
|
+
* on the host (mysql, sshd, nginx, redis, ...) is explicitly NOT protected.
|
|
45
|
+
*/
|
|
46
|
+
export const DSH_WEB_PORTS = [3000, 3080];
|
|
47
|
+
/**
|
|
48
|
+
* Boundary classification for the ancestor walk — mirrors
|
|
49
|
+
* `skills/dsh-safe-restart/scripts/restart-dsh-web.sh`'s `resolve_tree()`:
|
|
50
|
+
* the walk stops at `pnpm` (the launcher — everything above it is the
|
|
51
|
+
* launching shell, not dsh web) and never walks into a `systemd --user`
|
|
52
|
+
* manager (it owns every user unit on the box). `launcher` pids stay in the
|
|
53
|
+
* forest; `service-manager` pids are never included.
|
|
54
|
+
*/
|
|
55
|
+
export function treeBoundaryKind(commandLine) {
|
|
56
|
+
if (commandLine.includes('pnpm'))
|
|
57
|
+
return 'launcher';
|
|
58
|
+
if (commandLine.includes('systemd --user'))
|
|
59
|
+
return 'service-manager';
|
|
60
|
+
return 'none';
|
|
61
|
+
}
|
|
62
|
+
/** Convenience boolean form of {@link treeBoundaryKind}. */
|
|
63
|
+
export function isTreeBoundary(commandLine) {
|
|
64
|
+
return treeBoundaryKind(commandLine) !== 'none';
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Resolve the pids that belong to the dsh web process forest. `listeners` are
|
|
68
|
+
* the pids owning the dsh-web ports (already narrowed by the caller). A pid is
|
|
69
|
+
* protected iff its upward ancestor chain reaches the forest before pid 1:
|
|
70
|
+
*
|
|
71
|
+
* - the forest roots are the listeners plus every ancestor up to the
|
|
72
|
+
* `launcher` boundary (pnpm stays inside the forest; systemd --user and
|
|
73
|
+
* the launching shell stay out);
|
|
74
|
+
* - the descendant closure then protects the whole owned subtree — the dsh
|
|
75
|
+
* web node processes AND their bash-tool/browser children — while never
|
|
76
|
+
* climbing into unrelated ancestors.
|
|
77
|
+
*
|
|
78
|
+
* `boundary(pid)` classifies the command line of a walked pid; it is only
|
|
79
|
+
* invoked for the handful of listener + ancestor pids, never for the full
|
|
80
|
+
* table.
|
|
81
|
+
*/
|
|
82
|
+
export function resolveDshWebTreePids(listeners, rows, boundary = () => 'launcher') {
|
|
83
|
+
const byPid = new Map(rows.map(r => [r.pid, r]));
|
|
84
|
+
const roots = new Set();
|
|
85
|
+
for (const pid of listeners) {
|
|
86
|
+
let cur = pid;
|
|
87
|
+
for (let depth = 0; cur && cur !== 1 && depth < 100 && !roots.has(cur); depth++) {
|
|
88
|
+
const row = byPid.get(cur);
|
|
89
|
+
if (!row)
|
|
90
|
+
break;
|
|
91
|
+
const kind = boundary(cur);
|
|
92
|
+
if (kind === 'service-manager')
|
|
93
|
+
break; // never climb into systemd --user
|
|
94
|
+
roots.add(cur);
|
|
95
|
+
if (kind === 'launcher')
|
|
96
|
+
break; // pnpm is the ceiling of the forest
|
|
97
|
+
if (row.ppid === cur || row.ppid <= 0)
|
|
98
|
+
break;
|
|
99
|
+
cur = row.ppid;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const protectedSet = new Set(roots);
|
|
103
|
+
for (const row of rows) {
|
|
104
|
+
let cur = row.pid;
|
|
105
|
+
for (let depth = 0; cur && cur !== 1 && depth < 100; depth++) {
|
|
106
|
+
if (roots.has(cur)) {
|
|
107
|
+
protectedSet.add(row.pid);
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
const next = byPid.get(cur);
|
|
111
|
+
if (!next || next.ppid === cur || next.ppid <= 0)
|
|
112
|
+
break;
|
|
113
|
+
cur = next.ppid;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return [...protectedSet].sort((a, b) => a - b);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Whether a shell command is a self-kill. `livePids` are the pids of the dsh
|
|
120
|
+
* web process forest; a `kill <pid>` whose pid is one of ours is a self-kill
|
|
121
|
+
* regardless of anything else in the command. The kill parser accepts flag
|
|
122
|
+
* forms (`kill -9 <pid>`, `kill -TERM <pid>`). A command that is essentially
|
|
123
|
+
* JUST a `kill <unrelated-pid>` is allowed (idempotent cleanups are common),
|
|
124
|
+
* as are kill attempts whose output reports "not found"/"done" — but any
|
|
125
|
+
* compound that chains a restart/kill after it (or before the end) stays
|
|
126
|
+
* denied.
|
|
127
|
+
*/
|
|
128
|
+
export function isSelfKillCommand(cmd, livePids) {
|
|
129
|
+
// pid-targeted kill: an exact live pid is a self-kill regardless of context
|
|
130
|
+
if (/kill\s+(?:-\S+\s+)?(\d+)/i.test(cmd)) {
|
|
131
|
+
const pid = Number(cmd.match(/kill\s+(?:-\S+\s+)?(\d+)/i)?.[1]);
|
|
132
|
+
if (livePids.includes(pid))
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
// Targeted patterns may span segments (`ss ... | grep 3080 | xargs kill`),
|
|
136
|
+
// so test the stripped full text once, then verbs per segment.
|
|
137
|
+
const stripped = stripDataSpans(cmd);
|
|
138
|
+
if (SELF_KILL_RE.test(stripped))
|
|
139
|
+
return true;
|
|
140
|
+
for (const seg of stripped.split(/\s*(?:&&|\|\||;|\||\r?\n)+\s*/)) {
|
|
141
|
+
// Exclude ONLY a command that is JUST `kill [flags] <unrelated pid>` —
|
|
142
|
+
// anchored end-to-end so `kill 1234 && systemctl restart dsh-web` cannot
|
|
143
|
+
// whitelist the compound through its prefix.
|
|
144
|
+
if (/^kill\s+(?:-\S+\s+)?\d+\s*$/i.test(seg.trim()))
|
|
145
|
+
continue;
|
|
146
|
+
if (/kill\s+(?:-\S+\s+)?(\d+)\s+.*(not found|done)/i.test(seg))
|
|
147
|
+
continue;
|
|
148
|
+
if (DANGEROUS_KILL_VERB.test(seg))
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Live pids of the dsh web OWN forest: pids owning the dsh-web ports
|
|
155
|
+
* (3000/3080) plus their ancestor chain up to the pnpm/systemd boundary and
|
|
156
|
+
* the owned subtree. A kill of an unrelated listener (mysql/sshd/nginx) is
|
|
157
|
+
* therefore allowed — before this scoping the guard denied `kill <pid>` of ANY
|
|
158
|
+
* pid holding a listening socket as a "restart dsh web".
|
|
159
|
+
*/
|
|
160
|
+
export function dshWebTreeLivePids() {
|
|
161
|
+
try {
|
|
162
|
+
const { execSync } = require('node:child_process');
|
|
163
|
+
const filter = DSH_WEB_PORTS.map(p => `sport = :${p}`).join(' or ');
|
|
164
|
+
const out = execSync(`ss -tlnp '( ${filter} )' 2>/dev/null | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | sort -u`, { encoding: 'utf8' });
|
|
165
|
+
const listeners = out.trim().split('\n').filter(Boolean).map(Number);
|
|
166
|
+
if (listeners.length === 0)
|
|
167
|
+
return [];
|
|
168
|
+
const psOut = execSync(`ps -eo pid=,ppid=`, { encoding: 'utf8' });
|
|
169
|
+
const rows = psOut.trim().split('\n')
|
|
170
|
+
.map(line => line.trim().split(/\s+/))
|
|
171
|
+
.filter(p => p.length >= 2 && /^\d+$/.test(p[0]) && /^\d+$/.test(p[1]))
|
|
172
|
+
.map(([pid, ppid]) => ({ pid: Number(pid), ppid: Number(ppid) }));
|
|
173
|
+
// Command lines are only fetched for the walked listener/ancestor pids
|
|
174
|
+
// (a handful of subprocess calls), never for the whole process table.
|
|
175
|
+
const boundary = (pid) => {
|
|
176
|
+
try {
|
|
177
|
+
const args = execSync(`ps -o args= -p ${pid}`, { encoding: 'utf8' });
|
|
178
|
+
return treeBoundaryKind(args);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return 'launcher'; // gone or unreadable → stop walking right here
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
return resolveDshWebTreePids(listeners, rows, boundary);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Build a `tools/pre-execute` waterfall listener: deny matching
|
|
192
|
+
* bash/shell/exec commands, otherwise delegate to `next()`. Live pids default
|
|
193
|
+
* to the dsh web process forest (see `dshWebTreeLivePids`) so `kill <pid>` of
|
|
194
|
+
* a live host process is caught even when the command names no tool, while a
|
|
195
|
+
* kill of an unrelated service is not.
|
|
196
|
+
*/
|
|
197
|
+
export function makePreExecuteGuard(opts = {}) {
|
|
198
|
+
const livePids = opts.livePids ?? dshWebTreeLivePids;
|
|
199
|
+
return async (exec, next) => {
|
|
200
|
+
// dsh-tools hands the frozen ToolExecution (name + arguments); the guard
|
|
201
|
+
// also accepts the `args` shape for tests/embedded hosts.
|
|
202
|
+
const cmd = String(exec?.args?.command ?? exec?.args?.input ?? exec?.arguments?.command ?? exec?.arguments?.input ?? '');
|
|
203
|
+
if ((exec?.name === 'bash' || exec?.name === 'shell' || exec?.name === 'exec') && isSelfKillCommand(cmd, livePids())) {
|
|
204
|
+
return { kind: 'deny', reason: 'DENIED — this command restarts the dsh web process you are running inside. Use the dsh_web_restart tool (supervisor) for a safe restart.' };
|
|
205
|
+
}
|
|
206
|
+
return next();
|
|
207
|
+
};
|
|
208
|
+
}
|