@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
|
@@ -0,0 +1,216 @@
|
|
|
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
|
+
import { createRequire } from 'node:module'
|
|
9
|
+
|
|
10
|
+
const require = createRequire(import.meta.url)
|
|
11
|
+
|
|
12
|
+
// Patterns that restart/stop/start or kill dsh web (systemctl --user units,
|
|
13
|
+
// pkill/killall over the dsh tree, killing holders of :3080, and the
|
|
14
|
+
// dsh-safe-web-update helper itself). Matched — like dsh-maestro-guard —
|
|
15
|
+
// against the executed command surface with quoted/heredoc spans stripped, so
|
|
16
|
+
// text that merely MENTIONS these words (echo/printf/script bodies) is data,
|
|
17
|
+
// not argv.
|
|
18
|
+
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
|
|
19
|
+
|
|
20
|
+
// A segment whose command position is one of these verbs is a real kill-family
|
|
21
|
+
// invocation: blanket-denied even when its target lives inside quotes
|
|
22
|
+
// (`pkill -f "dsh web"` must still be caught). `sudo`/`env VAR=` prefixes are
|
|
23
|
+
// stripped before the verb is read.
|
|
24
|
+
const DANGEROUS_KILL_VERB = /^(?:sudo\s+|env\s+\S+\s+)*(pkill|killall|kill|systemctl)\b/i
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Remove data spans (quoted strings and heredoc bodies) from a command before
|
|
28
|
+
* self-kill matching. Text inside quotes or a heredoc is content — an echo,
|
|
29
|
+
* printf, node -e script or cat <<'EOF' body can legitimately discuss kill
|
|
30
|
+
* commands without executing one.
|
|
31
|
+
*/
|
|
32
|
+
export function stripDataSpans(cmd: string): string {
|
|
33
|
+
let out = cmd
|
|
34
|
+
let prev = ''
|
|
35
|
+
while (out !== prev) {
|
|
36
|
+
prev = out
|
|
37
|
+
// heredoc FIRST: the `<<'EOF'` delimiter quotes would otherwise be eaten by
|
|
38
|
+
// the generic quote-strip below and the body would survive as unquoted text
|
|
39
|
+
out = out.replace(/<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?[^\r\n]*\r?\n[\s\S]*?^\1\s*$/gm, ' ')
|
|
40
|
+
// quote spans respect backslash escapes (`\"` inside a double-quoted
|
|
41
|
+
// node -e body is content, not a delimiter) so nested literals stay stripped
|
|
42
|
+
out = out.replace(/"(?:[^"\\]|\\.)*"/g, ' ').replace(/'(?:[^'\\]|\\.)*'/g, ' ')
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The dsh web MainThread owns both ports (3000 = gitlab-webhook, 3080 = web).
|
|
49
|
+
* Only listeners on these ports can be dsh web; every other listening process
|
|
50
|
+
* on the host (mysql, sshd, nginx, redis, ...) is explicitly NOT protected.
|
|
51
|
+
*/
|
|
52
|
+
export const DSH_WEB_PORTS = [3000, 3080]
|
|
53
|
+
|
|
54
|
+
export type TreeBoundaryKind = 'none' | 'launcher' | 'service-manager'
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Boundary classification for the ancestor walk — mirrors
|
|
58
|
+
* `skills/dsh-safe-restart/scripts/restart-dsh-web.sh`'s `resolve_tree()`:
|
|
59
|
+
* the walk stops at `pnpm` (the launcher — everything above it is the
|
|
60
|
+
* launching shell, not dsh web) and never walks into a `systemd --user`
|
|
61
|
+
* manager (it owns every user unit on the box). `launcher` pids stay in the
|
|
62
|
+
* forest; `service-manager` pids are never included.
|
|
63
|
+
*/
|
|
64
|
+
export function treeBoundaryKind(commandLine: string): TreeBoundaryKind {
|
|
65
|
+
if (commandLine.includes('pnpm')) return 'launcher'
|
|
66
|
+
if (commandLine.includes('systemd --user')) return 'service-manager'
|
|
67
|
+
return 'none'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Convenience boolean form of {@link treeBoundaryKind}. */
|
|
71
|
+
export function isTreeBoundary(commandLine: string): boolean {
|
|
72
|
+
return treeBoundaryKind(commandLine) !== 'none'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ProcessRow { pid: number; ppid: number }
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Resolve the pids that belong to the dsh web process forest. `listeners` are
|
|
79
|
+
* the pids owning the dsh-web ports (already narrowed by the caller). A pid is
|
|
80
|
+
* protected iff its upward ancestor chain reaches the forest before pid 1:
|
|
81
|
+
*
|
|
82
|
+
* - the forest roots are the listeners plus every ancestor up to the
|
|
83
|
+
* `launcher` boundary (pnpm stays inside the forest; systemd --user and
|
|
84
|
+
* the launching shell stay out);
|
|
85
|
+
* - the descendant closure then protects the whole owned subtree — the dsh
|
|
86
|
+
* web node processes AND their bash-tool/browser children — while never
|
|
87
|
+
* climbing into unrelated ancestors.
|
|
88
|
+
*
|
|
89
|
+
* `boundary(pid)` classifies the command line of a walked pid; it is only
|
|
90
|
+
* invoked for the handful of listener + ancestor pids, never for the full
|
|
91
|
+
* table.
|
|
92
|
+
*/
|
|
93
|
+
export function resolveDshWebTreePids(
|
|
94
|
+
listeners: number[],
|
|
95
|
+
rows: ProcessRow[],
|
|
96
|
+
boundary: (pid: number) => TreeBoundaryKind = () => 'launcher',
|
|
97
|
+
): number[] {
|
|
98
|
+
const byPid = new Map(rows.map(r => [r.pid, r]))
|
|
99
|
+
const roots = new Set<number>()
|
|
100
|
+
for (const pid of listeners) {
|
|
101
|
+
let cur = pid
|
|
102
|
+
for (let depth = 0; cur && cur !== 1 && depth < 100 && !roots.has(cur); depth++) {
|
|
103
|
+
const row = byPid.get(cur)
|
|
104
|
+
if (!row) break
|
|
105
|
+
const kind = boundary(cur)
|
|
106
|
+
if (kind === 'service-manager') break // never climb into systemd --user
|
|
107
|
+
roots.add(cur)
|
|
108
|
+
if (kind === 'launcher') break // pnpm is the ceiling of the forest
|
|
109
|
+
if (row.ppid === cur || row.ppid <= 0) break
|
|
110
|
+
cur = row.ppid
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const protectedSet = new Set(roots)
|
|
114
|
+
for (const row of rows) {
|
|
115
|
+
let cur: number | undefined = row.pid
|
|
116
|
+
for (let depth = 0; cur && cur !== 1 && depth < 100; depth++) {
|
|
117
|
+
if (roots.has(cur)) {
|
|
118
|
+
protectedSet.add(row.pid)
|
|
119
|
+
break
|
|
120
|
+
}
|
|
121
|
+
const next = byPid.get(cur)
|
|
122
|
+
if (!next || next.ppid === cur || next.ppid <= 0) break
|
|
123
|
+
cur = next.ppid
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return [...protectedSet].sort((a, b) => a - b)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Whether a shell command is a self-kill. `livePids` are the pids of the dsh
|
|
131
|
+
* web process forest; a `kill <pid>` whose pid is one of ours is a self-kill
|
|
132
|
+
* regardless of anything else in the command. The kill parser accepts flag
|
|
133
|
+
* forms (`kill -9 <pid>`, `kill -TERM <pid>`). A command that is essentially
|
|
134
|
+
* JUST a `kill <unrelated-pid>` is allowed (idempotent cleanups are common),
|
|
135
|
+
* as are kill attempts whose output reports "not found"/"done" — but any
|
|
136
|
+
* compound that chains a restart/kill after it (or before the end) stays
|
|
137
|
+
* denied.
|
|
138
|
+
*/
|
|
139
|
+
export function isSelfKillCommand(cmd: string, livePids: number[]): boolean {
|
|
140
|
+
// pid-targeted kill: an exact live pid is a self-kill regardless of context
|
|
141
|
+
if (/kill\s+(?:-\S+\s+)?(\d+)/i.test(cmd)) {
|
|
142
|
+
const pid = Number(cmd.match(/kill\s+(?:-\S+\s+)?(\d+)/i)?.[1])
|
|
143
|
+
if (livePids.includes(pid)) return true
|
|
144
|
+
}
|
|
145
|
+
// Targeted patterns may span segments (`ss ... | grep 3080 | xargs kill`),
|
|
146
|
+
// so test the stripped full text once, then verbs per segment.
|
|
147
|
+
const stripped = stripDataSpans(cmd)
|
|
148
|
+
if (SELF_KILL_RE.test(stripped)) return true
|
|
149
|
+
for (const seg of stripped.split(/\s*(?:&&|\|\||;|\||\r?\n)+\s*/)) {
|
|
150
|
+
// Exclude ONLY a command that is JUST `kill [flags] <unrelated pid>` —
|
|
151
|
+
// anchored end-to-end so `kill 1234 && systemctl restart dsh-web` cannot
|
|
152
|
+
// whitelist the compound through its prefix.
|
|
153
|
+
if (/^kill\s+(?:-\S+\s+)?\d+\s*$/i.test(seg.trim())) continue
|
|
154
|
+
if (/kill\s+(?:-\S+\s+)?(\d+)\s+.*(not found|done)/i.test(seg)) continue
|
|
155
|
+
if (DANGEROUS_KILL_VERB.test(seg)) return true
|
|
156
|
+
}
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Live pids of the dsh web OWN forest: pids owning the dsh-web ports
|
|
162
|
+
* (3000/3080) plus their ancestor chain up to the pnpm/systemd boundary and
|
|
163
|
+
* the owned subtree. A kill of an unrelated listener (mysql/sshd/nginx) is
|
|
164
|
+
* therefore allowed — before this scoping the guard denied `kill <pid>` of ANY
|
|
165
|
+
* pid holding a listening socket as a "restart dsh web".
|
|
166
|
+
*/
|
|
167
|
+
export function dshWebTreeLivePids(): number[] {
|
|
168
|
+
try {
|
|
169
|
+
const { execSync } = require('node:child_process') as typeof import('node:child_process')
|
|
170
|
+
const filter = DSH_WEB_PORTS.map(p => `sport = :${p}`).join(' or ')
|
|
171
|
+
const out = execSync(
|
|
172
|
+
`ss -tlnp '( ${filter} )' 2>/dev/null | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | sort -u`,
|
|
173
|
+
{ encoding: 'utf8' },
|
|
174
|
+
)
|
|
175
|
+
const listeners = out.trim().split('\n').filter(Boolean).map(Number)
|
|
176
|
+
if (listeners.length === 0) return []
|
|
177
|
+
const psOut = execSync(`ps -eo pid=,ppid=`, { encoding: 'utf8' })
|
|
178
|
+
const rows: ProcessRow[] = psOut.trim().split('\n')
|
|
179
|
+
.map(line => line.trim().split(/\s+/))
|
|
180
|
+
.filter(p => p.length >= 2 && /^\d+$/.test(p[0]) && /^\d+$/.test(p[1]))
|
|
181
|
+
.map(([pid, ppid]) => ({ pid: Number(pid), ppid: Number(ppid) }))
|
|
182
|
+
// Command lines are only fetched for the walked listener/ancestor pids
|
|
183
|
+
// (a handful of subprocess calls), never for the whole process table.
|
|
184
|
+
const boundary = (pid: number): TreeBoundaryKind => {
|
|
185
|
+
try {
|
|
186
|
+
const args = execSync(`ps -o args= -p ${pid}`, { encoding: 'utf8' })
|
|
187
|
+
return treeBoundaryKind(args)
|
|
188
|
+
} catch {
|
|
189
|
+
return 'launcher' // gone or unreadable → stop walking right here
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return resolveDshWebTreePids(listeners, rows, boundary)
|
|
193
|
+
} catch {
|
|
194
|
+
return []
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Build a `tools/pre-execute` waterfall listener: deny matching
|
|
200
|
+
* bash/shell/exec commands, otherwise delegate to `next()`. Live pids default
|
|
201
|
+
* to the dsh web process forest (see `dshWebTreeLivePids`) so `kill <pid>` of
|
|
202
|
+
* a live host process is caught even when the command names no tool, while a
|
|
203
|
+
* kill of an unrelated service is not.
|
|
204
|
+
*/
|
|
205
|
+
export function makePreExecuteGuard(opts: { livePids?: () => number[] } = {}) {
|
|
206
|
+
const livePids = opts.livePids ?? dshWebTreeLivePids
|
|
207
|
+
return async (exec: any, next: () => Promise<any>) => {
|
|
208
|
+
// dsh-tools hands the frozen ToolExecution (name + arguments); the guard
|
|
209
|
+
// also accepts the `args` shape for tests/embedded hosts.
|
|
210
|
+
const cmd = String(exec?.args?.command ?? exec?.args?.input ?? exec?.arguments?.command ?? exec?.arguments?.input ?? '')
|
|
211
|
+
if ((exec?.name === 'bash' || exec?.name === 'shell' || exec?.name === 'exec') && isSelfKillCommand(cmd, livePids())) {
|
|
212
|
+
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.' }
|
|
213
|
+
}
|
|
214
|
+
return next()
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-log health scan.
|
|
3
|
+
*
|
|
4
|
+
* Deeper resilience for dsh-safe-restart pre-flight: after (or before) a
|
|
5
|
+
* restart, individual session logs under a project session dir can end up in
|
|
6
|
+
* three distinct shapes:
|
|
7
|
+
*
|
|
8
|
+
* 1. healthy multi-frame — one frame per line (a header-only first frame,
|
|
9
|
+
* then per-event frames). The DSH reader depends on
|
|
10
|
+
* this shape to fast-seek the session header.
|
|
11
|
+
* 2. single-frame whole-log — the entire log was written as ONE zstd frame.
|
|
12
|
+
* Data is fully intact (whole-file decode works) but
|
|
13
|
+
* the header cannot be located by a frame walk.
|
|
14
|
+
* 3. corrupt first frame — the first frame cannot be decoded at all.
|
|
15
|
+
*
|
|
16
|
+
* Classification uses fzstd's whole-file decode + streaming Decompress and
|
|
17
|
+
* avoids a hand-rolled zstd frame-header walker (empirically wrong on both
|
|
18
|
+
* real file shapes; fzstd whole-file decode already handles single and
|
|
19
|
+
* concatenated frames). The first-frame probe only ever feeds the streaming
|
|
20
|
+
* decoder a bounded 64 KiB head (log2 scans of ≤256-byte-prefix steps), so it
|
|
21
|
+
* is stack-safe even on long-running many-frame logs — feeding a whole file
|
|
22
|
+
* into the streaming decoder recurses per frame and overflows the V8 stack.
|
|
23
|
+
*
|
|
24
|
+
* Repair re-encodes a single-frame whole-log into the canonical multi-frame
|
|
25
|
+
* shape (frame #1 = exactly the header line, trailing line-batched frames),
|
|
26
|
+
* byte-preserving every event; the original file is kept as a sidecar backup
|
|
27
|
+
* and the replace is atomic (write temp + rename).
|
|
28
|
+
*
|
|
29
|
+
* NOTE: fzstd is a decode-only pure-JS zstd library; re-encoding uses Node's
|
|
30
|
+
* native zlib zstd encoder, whose frames fzstd (and the zstd CLI / DSH's
|
|
31
|
+
* reader) decode as standard concatenated frames.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { decompress, Decompress } from 'fzstd'
|
|
35
|
+
import { copyFileSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync, type Dirent } from 'node:fs'
|
|
36
|
+
import { zstdCompressSync } from 'node:zlib'
|
|
37
|
+
import { join } from 'node:path'
|
|
38
|
+
import { resolveSessionLogPath } from './session-log-file.js'
|
|
39
|
+
|
|
40
|
+
export type SessionLogClass = 'ok' | 'single-frame-whole-log' | 'corrupt-first-frame' | 'not-a-session-log'
|
|
41
|
+
export interface SessionHealthEntry { path: string; klass: SessionLogClass; remark?: string }
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Cap on the file head probed through the streaming decoder. Feeding a whole
|
|
45
|
+
* long-running log (thousands of concatenated zstd frames) into fzstd's
|
|
46
|
+
* streaming `Decompress` in one push recurses once per frame and overflows the
|
|
47
|
+
* V8 stack (RangeError: Maximum call stack size exceeded, seen on a real
|
|
48
|
+
* ~1.8 MB session log). Only the first frame matters for classification, so we
|
|
49
|
+
* never probe past 64 KiB — a canonical log's first frame is a few hundred
|
|
50
|
+
* bytes, and a frame can never legitimately straddle this cap.
|
|
51
|
+
*/
|
|
52
|
+
const FIRST_FRAME_CAP = 64 * 1024
|
|
53
|
+
|
|
54
|
+
/** Standard zstd frame encoder (node:zlib) — decode-compatible with fzstd. */
|
|
55
|
+
function compress(data: Buffer): Buffer {
|
|
56
|
+
return zstdCompressSync(data)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
type FrameHead = { found: true; end: number } | { found: false }
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Smallest head prefix at which the streaming decoder first emits output
|
|
63
|
+
* (≈ first-frame completion), searched only within FIRST_FRAME_CAP. Never
|
|
64
|
+
* pushes more than the cap into the decoder, so the probe is stack-safe on
|
|
65
|
+
* arbitrarily large many-frame logs. A push that throws on invalid bytes past
|
|
66
|
+
* the first decoded frame is harmless to the boundary search — once the first
|
|
67
|
+
* frame has emitted (`fired`), the boundary is already known, so the throw is
|
|
68
|
+
* swallowed. Only garbage that decodes nothing yields `{ found: false }`.
|
|
69
|
+
*/
|
|
70
|
+
function firstFrameHead(buf: Buffer): FrameHead {
|
|
71
|
+
const emits = (len: number): boolean => {
|
|
72
|
+
let fired = false
|
|
73
|
+
const d = new Decompress((chunk) => { if (chunk.length > 0) fired = true })
|
|
74
|
+
try {
|
|
75
|
+
d.push(buf.subarray(0, len))
|
|
76
|
+
} catch {
|
|
77
|
+
// Invalid bytes past the first frame (corrupt tail): the decoder had
|
|
78
|
+
// already emitted the first frame's output → keep `fired` as-is.
|
|
79
|
+
}
|
|
80
|
+
return fired
|
|
81
|
+
}
|
|
82
|
+
const cap = Math.min(buf.length, FIRST_FRAME_CAP)
|
|
83
|
+
let hi = cap
|
|
84
|
+
for (let l = 256; l <= cap; l += 256) if (emits(l)) { hi = l; break }
|
|
85
|
+
if (!emits(cap)) return { found: false } // no frame boundary within the cap
|
|
86
|
+
let lo = 0
|
|
87
|
+
while (lo + 1 < hi) { const mid = (lo + hi) >> 1; emits(mid) ? hi = mid : lo = mid }
|
|
88
|
+
return { found: true, end: hi }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isSingleHeaderLine(plain: Buffer): boolean {
|
|
92
|
+
if (plain.length === 0) return false
|
|
93
|
+
const nl = plain.indexOf(0x0a)
|
|
94
|
+
return nl === plain.length - 1 // exactly one line, terminated by '\n'
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Classify a single session log file per the validated algorithm.
|
|
99
|
+
*
|
|
100
|
+
* Fast path (dominant case): classify a healthy multi-frame log from its first
|
|
101
|
+
* frame alone — the bounded 64 KiB head probe finds the first-frame boundary,
|
|
102
|
+
* decodes just that frame, and a header-only first frame means `ok` WITHOUT
|
|
103
|
+
* ever decoding the whole file.
|
|
104
|
+
*
|
|
105
|
+
* Whole-file decode is ONLY the fallback corrupt gate:
|
|
106
|
+
* - first frame decodes but is multi-line (or the probe found no boundary
|
|
107
|
+
* within 64 KiB — a first frame bigger than the cap is never a canonical
|
|
108
|
+
* healthy log): whole decode throws → 'corrupt-first-frame', succeeds →
|
|
109
|
+
* 'single-frame-whole-log' (whole decodes to exactly one line → 'ok').
|
|
110
|
+
*
|
|
111
|
+
* Empty files are not session logs.
|
|
112
|
+
*/
|
|
113
|
+
export async function classifySessionLog(path: string): Promise<SessionHealthEntry> {
|
|
114
|
+
let buf: Buffer
|
|
115
|
+
try { buf = readFileSync(path) } catch { return { path, klass: 'not-a-session-log' } }
|
|
116
|
+
if (buf.length === 0) return { path, klass: 'not-a-session-log' }
|
|
117
|
+
const head = firstFrameHead(buf)
|
|
118
|
+
if (head.found) {
|
|
119
|
+
let first: Buffer | undefined
|
|
120
|
+
try { first = Buffer.from(decompress(buf.subarray(0, head.end))) } catch { /* prefix not a complete frame */ }
|
|
121
|
+
if (first?.byteLength !== undefined && isSingleHeaderLine(first)) return { path, klass: 'ok' }
|
|
122
|
+
// First frame decodes but is multi-line (or the prefix is not a complete
|
|
123
|
+
// frame): the whole file must still decode for this to be recoverable.
|
|
124
|
+
try { decompress(buf) } catch { return { path, klass: 'corrupt-first-frame' } }
|
|
125
|
+
return { path, klass: 'single-frame-whole-log' }
|
|
126
|
+
}
|
|
127
|
+
// No frame boundary within the cap — first frame is bigger than 64 KiB, never
|
|
128
|
+
// a canonical healthy log. The whole-file decode is authoritative.
|
|
129
|
+
let whole: Buffer
|
|
130
|
+
try { whole = Buffer.from(decompress(buf)) } catch { return { path, klass: 'corrupt-first-frame' } }
|
|
131
|
+
if (isSingleHeaderLine(whole)) return { path, klass: 'ok' }
|
|
132
|
+
return { path, klass: 'single-frame-whole-log' } // whole-file decodes; first frame isn't header-only → recoverable
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Re-encode a single-frame-whole-log into canonical multi-frame form:
|
|
137
|
+
* frame #1 = exactly the header line, then line-batched trailing frames.
|
|
138
|
+
* The original file is preserved as `path + backupSuffix` (first time only)
|
|
139
|
+
* and the replace is atomic (temp file + rename).
|
|
140
|
+
*/
|
|
141
|
+
export async function repairSingleFrameLog(path: string, backupSuffix = '.corrupt-singleframe.bak'): Promise<void> {
|
|
142
|
+
const buf = readFileSync(path)
|
|
143
|
+
const whole = Buffer.from(decompress(buf))
|
|
144
|
+
const nl = whole.indexOf(0x0a)
|
|
145
|
+
const header = whole.subarray(0, nl + 1)
|
|
146
|
+
const rest = whole.subarray(nl + 1)
|
|
147
|
+
if (!existsSync(path + backupSuffix)) copyFileSync(path, path + backupSuffix)
|
|
148
|
+
const frames: Buffer[] = [compress(header)]
|
|
149
|
+
let start = 0
|
|
150
|
+
for (let i = 0; i < rest.length; i++) {
|
|
151
|
+
if (rest[i] === 0x0a && i - start + 1 >= 64 * 1024) { frames.push(compress(rest.subarray(start, i + 1))); start = i + 1 }
|
|
152
|
+
}
|
|
153
|
+
if (start < rest.length) frames.push(compress(rest.subarray(start)))
|
|
154
|
+
const tmp = path + '.repair.tmp'
|
|
155
|
+
writeFileSync(tmp, Buffer.concat(frames))
|
|
156
|
+
renameSync(tmp, path)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Walk `root` recursively and classify the session log of every session
|
|
161
|
+
* directory found. One directory owns one log — the newest format generation
|
|
162
|
+
* in it (`session.v<N>.jsonl[.zstd]`, generation 0 without the `vN`) is exactly
|
|
163
|
+
* the file the harness reads, so a stale generation beside it is skipped.
|
|
164
|
+
* The process-write layout is <dshHome>/sessions/<project>/<session>/, but we
|
|
165
|
+
* recurse generically so tests and future layouts work unchanged. Resolving the
|
|
166
|
+
* generation by name is load-bearing: matching a literal went blind when the
|
|
167
|
+
* harness bumped it (v3 -> v4 on 2026-09-23), leaving this pre-flight with zero
|
|
168
|
+
* files to classify.
|
|
169
|
+
*/
|
|
170
|
+
export async function scanSessionLogs(root: string): Promise<SessionHealthEntry[]> {
|
|
171
|
+
const found: string[] = []
|
|
172
|
+
const walk = (dir: string): void => {
|
|
173
|
+
let entries: Dirent[]
|
|
174
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
175
|
+
const log = resolveSessionLogPath(dir)
|
|
176
|
+
if (log !== undefined) found.push(log)
|
|
177
|
+
for (const e of entries) if (e.isDirectory()) walk(join(dir, e.name))
|
|
178
|
+
}
|
|
179
|
+
walk(root)
|
|
180
|
+
const out: SessionHealthEntry[] = []
|
|
181
|
+
for (const p of found) {
|
|
182
|
+
try {
|
|
183
|
+
out.push(await classifySessionLog(p))
|
|
184
|
+
} catch (err) {
|
|
185
|
+
// One unreadable / unclassifiable file must never abort the whole scan.
|
|
186
|
+
out.push({ path: p, klass: 'corrupt-first-frame', remark: err instanceof Error ? err.message : String(err) })
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return out
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Health check over a session-log root: repair single-frame logs (atomic
|
|
194
|
+
* re-encode), optionally quarantine corrupt-first-frame logs aside, and
|
|
195
|
+
* report counts. `remaining` counts unhealthy entries left untouched
|
|
196
|
+
* (not-a-session-log, corrupt frames when quarantine is off, and
|
|
197
|
+
* single-frame logs when repair is off).
|
|
198
|
+
*/
|
|
199
|
+
export async function runSessionHealthCheck(
|
|
200
|
+
root: string,
|
|
201
|
+
opts: { repair?: boolean; quarantine?: boolean } = {},
|
|
202
|
+
): Promise<{ fixed: number; quarantined: number; remaining: number }> {
|
|
203
|
+
const repair = opts.repair ?? true
|
|
204
|
+
const quarantine = opts.quarantine ?? false
|
|
205
|
+
let fixed = 0
|
|
206
|
+
let quarantined = 0
|
|
207
|
+
let remaining = 0
|
|
208
|
+
for (const entry of await scanSessionLogs(root)) {
|
|
209
|
+
try {
|
|
210
|
+
switch (entry.klass) {
|
|
211
|
+
case 'single-frame-whole-log':
|
|
212
|
+
if (repair) { await repairSingleFrameLog(entry.path); fixed++ } else remaining++
|
|
213
|
+
break
|
|
214
|
+
case 'corrupt-first-frame':
|
|
215
|
+
if (quarantine) {
|
|
216
|
+
let aside = entry.path + '.corrupt-' + Date.now() + '.bak'
|
|
217
|
+
let n = 0
|
|
218
|
+
while (existsSync(aside)) aside = entry.path + '.corrupt-' + Date.now() + '-' + (++n) + '.bak'
|
|
219
|
+
renameSync(entry.path, aside)
|
|
220
|
+
quarantined++
|
|
221
|
+
} else remaining++
|
|
222
|
+
break
|
|
223
|
+
case 'not-a-session-log':
|
|
224
|
+
remaining++
|
|
225
|
+
break
|
|
226
|
+
default:
|
|
227
|
+
break
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
// Repair/quarantine of a single entry failed — it stays unhealthy and
|
|
231
|
+
// can never abort the whole pass. Counts always reconcile.
|
|
232
|
+
remaining++
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return { fixed, quarantined, remaining }
|
|
236
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Which file inside a session directory is that session's readable log.
|
|
6
|
+
*
|
|
7
|
+
* The harness names the artifact by Session format generation —
|
|
8
|
+
* `generationLogFilename(version, compression)`: version 0 keeps the
|
|
9
|
+
* suffix-only name (`session.jsonl[.zstd]`), and every later generation carries
|
|
10
|
+
* a lowercase numeric `vN` (`session.v4.jsonl.zstd`). Generations are
|
|
11
|
+
* unbounded, so this module PARSES the name and picks the newest generation
|
|
12
|
+
* instead of enumerating literal filenames.
|
|
13
|
+
*
|
|
14
|
+
* Why that matters: a hardcoded list goes blind at every generation bump, and
|
|
15
|
+
* the failure is silent — the scan simply finds no session. It happened on
|
|
16
|
+
* 2026-09-11 (v3 landed, auto-resume found nothing after a restart) and again
|
|
17
|
+
* on 2026-09-23 (v4 landed with DSH 0.1.7-rc.1: `findInterrupted` reported
|
|
18
|
+
* `0/N` interrupted, the boot pre-flight had nothing to classify, and session
|
|
19
|
+
* preset recovery read no header). Never reintroduce a literal generation list
|
|
20
|
+
* here.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** `session.jsonl[.zstd]` (generation 0) or `session.v<N>.jsonl[.zstd]`. */
|
|
24
|
+
const SESSION_LOG_NAME = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Session format generation encoded in a log filename.
|
|
28
|
+
* @param name - bare file name (no directory).
|
|
29
|
+
* @returns the generation number, or `undefined` when the name is not a session log.
|
|
30
|
+
*/
|
|
31
|
+
export function sessionLogGeneration(name: string): number | undefined {
|
|
32
|
+
const match = SESSION_LOG_NAME.exec(name)
|
|
33
|
+
if (match === null) return undefined
|
|
34
|
+
return match[1] === undefined ? 0 : Number(match[1])
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether a bare file name is a session log of any generation.
|
|
39
|
+
* @param name - bare file name (no directory).
|
|
40
|
+
*/
|
|
41
|
+
export function isSessionLogName(name: string): boolean {
|
|
42
|
+
return sessionLogGeneration(name) !== undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the readable session log inside one session directory across format
|
|
48
|
+
* generations. The newest generation wins — that is where a live session
|
|
49
|
+
* persists, while older generations stay behind as migration artifacts (a
|
|
50
|
+
* directory can hold several, and judging the session by a stale one both
|
|
51
|
+
* misses a recovery and can fire a false one). Within one generation the
|
|
52
|
+
* compressed `.jsonl.zstd` artifact wins over plaintext.
|
|
53
|
+
* @param dir - one session directory.
|
|
54
|
+
* @returns the absolute log path, or `undefined` when the directory holds no log.
|
|
55
|
+
*/
|
|
56
|
+
export function resolveSessionLogPath(dir: string): string | undefined {
|
|
57
|
+
let entries: string[]
|
|
58
|
+
try {
|
|
59
|
+
entries = fs.readdirSync(dir)
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
let bestName: string | undefined
|
|
64
|
+
let bestGeneration = -1
|
|
65
|
+
let bestCompressed = false
|
|
66
|
+
for (const name of entries) {
|
|
67
|
+
const generation = sessionLogGeneration(name)
|
|
68
|
+
if (generation === undefined) continue
|
|
69
|
+
const compressed = name.endsWith('.zstd')
|
|
70
|
+
if (generation > bestGeneration || (generation === bestGeneration && compressed && !bestCompressed)) {
|
|
71
|
+
bestName = name
|
|
72
|
+
bestGeneration = generation
|
|
73
|
+
bestCompressed = compressed
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return bestName === undefined ? undefined : join(dir, bestName)
|
|
77
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import type { SkillCandidate, SkillDefinition, SkillLookupOptions } from '@deepseek-ai/dsh-skill'
|
|
4
|
+
|
|
5
|
+
const SKILL_NAME = 'dsh-safe-restart'
|
|
6
|
+
|
|
7
|
+
/** Minimal frontmatter reader for our own SKILL.md — enough to serve the provider contract. */
|
|
8
|
+
function parseFrontmatter(raw: string): { name: string; description: string; body: string } {
|
|
9
|
+
// `\r?\n` on both delimiters and on the line split: a SKILL.md checked out
|
|
10
|
+
// with CRLF (git core.autocrlf, a Windows editor) otherwise parses to an
|
|
11
|
+
// empty description with no error at all.
|
|
12
|
+
const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/)
|
|
13
|
+
if (!m) return { name: SKILL_NAME, description: '', body: raw }
|
|
14
|
+
const fm = m[1].split(/\r?\n/).reduce<Record<string, string>>((acc, line) => {
|
|
15
|
+
const kv = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/)
|
|
16
|
+
if (kv) acc[kv[1]] = kv[2].replace(/^["']|["']$/g, '')
|
|
17
|
+
return acc
|
|
18
|
+
}, {})
|
|
19
|
+
return { name: fm.name || SKILL_NAME, description: fm.description || '', body: m[2] }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function makeSkillProvider(skillsDir: string) {
|
|
23
|
+
return {
|
|
24
|
+
// The dsh-skill service attributes candidates through the provider
|
|
25
|
+
// object's own `name` (maestro-skills returns `{ name, list, get }`); a
|
|
26
|
+
// missing name surfaces at runtime as `skill provider "undefined" returned
|
|
27
|
+
// skill ... for provider "maestro-supervisor"` and fails every turn.
|
|
28
|
+
name: 'maestro-supervisor',
|
|
29
|
+
async list(_options: SkillLookupOptions): Promise<SkillCandidate[]> {
|
|
30
|
+
const entry = join(skillsDir, SKILL_NAME)
|
|
31
|
+
const st = await stat(entry).catch(() => null)
|
|
32
|
+
if (!st?.isDirectory()) return []
|
|
33
|
+
const skillFilePath = join(entry, 'SKILL.md')
|
|
34
|
+
const fileSt = await stat(skillFilePath).catch(() => null)
|
|
35
|
+
if (!fileSt?.isFile()) return []
|
|
36
|
+
const raw = await readFile(skillFilePath, 'utf-8').catch(() => null)
|
|
37
|
+
if (raw === null) return []
|
|
38
|
+
const { name, description } = parseFrontmatter(raw)
|
|
39
|
+
return [{
|
|
40
|
+
name,
|
|
41
|
+
description,
|
|
42
|
+
invocation: { modelInvocable: true, userInvocable: true },
|
|
43
|
+
source: 'custom',
|
|
44
|
+
provider: 'maestro-supervisor',
|
|
45
|
+
rank: 360,
|
|
46
|
+
locator: skillFilePath,
|
|
47
|
+
path: skillFilePath,
|
|
48
|
+
resourceBase: { kind: 'directory', path: entry },
|
|
49
|
+
metadata: { name, description },
|
|
50
|
+
}]
|
|
51
|
+
},
|
|
52
|
+
async get(candidate: SkillCandidate, _options: SkillLookupOptions): Promise<SkillDefinition | undefined> {
|
|
53
|
+
try {
|
|
54
|
+
const raw = await readFile(candidate.path as string, 'utf-8')
|
|
55
|
+
const { name, description, body } = parseFrontmatter(raw)
|
|
56
|
+
return {
|
|
57
|
+
name, description,
|
|
58
|
+
invocation: candidate.invocation,
|
|
59
|
+
source: candidate.source,
|
|
60
|
+
provider: candidate.provider,
|
|
61
|
+
resourceBase: candidate.resourceBase,
|
|
62
|
+
path: candidate.path,
|
|
63
|
+
content: body,
|
|
64
|
+
metadata: candidate.metadata,
|
|
65
|
+
}
|
|
66
|
+
} catch { return undefined }
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
}
|