@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,483 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh_web_restart tool — the safe restart path for the model running inside
|
|
3
|
+
* dsh web. Scheduling a restart through this tool instead of a raw kill keeps
|
|
4
|
+
* the restart inside the supervisor's ownership loop:
|
|
5
|
+
*
|
|
6
|
+
* 1. dry-boot gate — if the plugin tree changed since the latest LKG, boot a
|
|
7
|
+
* copy of the live profile on an ephemeral DSH_HOME first and only
|
|
8
|
+
* schedule when that boot serves HTTP.
|
|
9
|
+
* 2. intent sidecar — record the caller session + reason under
|
|
10
|
+
* ~/.dsh/.supervisor/intents/ for attribution.
|
|
11
|
+
* 3. hand-off — write the restart-request marker (planned-restart.json with
|
|
12
|
+
* callerSessionId) that the supervisor daemon owns and acts on
|
|
13
|
+
* (out-of-band). This tool NEVER restarts the host in-tree.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { join, dirname, resolve } from 'node:path'
|
|
17
|
+
import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs'
|
|
18
|
+
import { tmpdir, homedir } from 'node:os'
|
|
19
|
+
import { spawn, execFileSync } from 'node:child_process'
|
|
20
|
+
import { createRequire } from 'node:module'
|
|
21
|
+
import { writeRestartRequest, readRestartRequest } from './restart-guards.js'
|
|
22
|
+
import { intentPath, readIntent, readRestartOutcome } from './intents.js'
|
|
23
|
+
import { supervisorDaemonState, describeDaemonState, type DaemonState } from './daemon-freshness.js'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Copy a live profile tree for an isolated dry-boot. A naive recursive copy
|
|
27
|
+
* breaks `link:` installs: their node_modules entries are relative symlinks
|
|
28
|
+
* (e.g. `../../../shared/pkg`) that resolve against the copy location and
|
|
29
|
+
* dangle. Every symlink left dangling by the copy is rewritten to the
|
|
30
|
+
* absolute live target it pointed at, so the dry-boot loads the same code
|
|
31
|
+
* the live tree loads. Links already broken in the live tree are left alone
|
|
32
|
+
* (the dry-boot must stay faithful, not fix the live tree).
|
|
33
|
+
*/
|
|
34
|
+
export function copyProfileForDryBoot(srcDir: string, destDir: string): void {
|
|
35
|
+
cpSync(srcDir, destDir, { recursive: true, preserveTimestamps: true })
|
|
36
|
+
const repair = (dir: string, rel: string): void => {
|
|
37
|
+
for (const name of readdirSync(dir)) {
|
|
38
|
+
const p = join(dir, name)
|
|
39
|
+
const r = rel ? `${rel}/${name}` : name
|
|
40
|
+
const st = lstatSync(p)
|
|
41
|
+
if (st.isSymbolicLink()) {
|
|
42
|
+
if (!existsSync(p)) {
|
|
43
|
+
const liveTarget = resolve(srcDir, dirname(r), readlinkSync(p))
|
|
44
|
+
if (existsSync(liveTarget)) {
|
|
45
|
+
unlinkSync(p)
|
|
46
|
+
symlinkSync(liveTarget, p)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
} else if (st.isDirectory()) {
|
|
50
|
+
repair(p, r)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
repair(destDir, '')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A dry-boot orphan candidate: a `dsh web` process rooted at a temp DSH_HOME
|
|
59
|
+
* with an ephemeral-port listener. Ports 3080/3081/3082 are the live tree and
|
|
60
|
+
* can never be candidates.
|
|
61
|
+
*/
|
|
62
|
+
export interface DryBootCandidate { pid: number; port: number; dshHome: string }
|
|
63
|
+
|
|
64
|
+
const LIVE_PORTS = new Set([3080, 3081, 3082])
|
|
65
|
+
|
|
66
|
+
export interface GcReaders {
|
|
67
|
+
readProc?: () => Array<{ pid: number; cmd: string; env: string }>
|
|
68
|
+
ssPortsOf?: (pid: number) => number[]
|
|
69
|
+
selfPid?: number
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function defaultReadProc(): Array<{ pid: number; cmd: string; env: string }> {
|
|
73
|
+
const out: Array<{ pid: number; cmd: string; env: string }> = []
|
|
74
|
+
let names: string[] = []
|
|
75
|
+
try { names = readdirSync('/proc') } catch { return out }
|
|
76
|
+
for (const name of names) {
|
|
77
|
+
if (!/^\d+$/.test(name)) continue
|
|
78
|
+
try {
|
|
79
|
+
const cmd = readFileSync(`/proc/${name}/cmdline`, 'utf8').replace(/\0/g, ' ')
|
|
80
|
+
const env = readFileSync(`/proc/${name}/environ`, 'utf8')
|
|
81
|
+
out.push({ pid: Number(name), cmd, env })
|
|
82
|
+
} catch { /* process exited mid-scan — ignore */ }
|
|
83
|
+
}
|
|
84
|
+
return out
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function defaultSsPortsOf(pid: number): number[] {
|
|
88
|
+
try {
|
|
89
|
+
const out = execFileSync('ss', ['-tlnp'], { encoding: 'utf8' })
|
|
90
|
+
const ports: number[] = []
|
|
91
|
+
for (const line of out.split('\n')) {
|
|
92
|
+
if (!line.includes(`pid=${pid},`)) continue
|
|
93
|
+
const m = /:(\d+)\s/.exec(line)
|
|
94
|
+
if (m) ports.push(Number(m[1]))
|
|
95
|
+
}
|
|
96
|
+
return ports
|
|
97
|
+
} catch { return [] }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* List dry-boot orphans: `dsh web` processes on a temp DSH_HOME holding an
|
|
102
|
+
* ephemeral 9000-9999 listener. Conjunctive fingerprint + absolute exclusions
|
|
103
|
+
* (self PID, live ports, real-home DSH_HOME) — a process is returned only when
|
|
104
|
+
* every signal agrees it is a disposable dry-boot.
|
|
105
|
+
*/
|
|
106
|
+
export function listDryBootCandidates(readers: GcReaders = {}): DryBootCandidate[] {
|
|
107
|
+
const readProc = readers.readProc ?? defaultReadProc
|
|
108
|
+
const ssPortsOf = readers.ssPortsOf ?? defaultSsPortsOf
|
|
109
|
+
const selfPid = readers.selfPid ?? process.pid
|
|
110
|
+
const out: DryBootCandidate[] = []
|
|
111
|
+
for (const p of readProc()) {
|
|
112
|
+
if (p.pid === selfPid) continue
|
|
113
|
+
if (!/bin\.ts web/.test(p.cmd)) continue
|
|
114
|
+
const home = /^DSH_HOME=([^\0]*)/m.exec(p.env)?.[1] ?? ''
|
|
115
|
+
if (!home.startsWith(join(tmpdir(), 'dsh-dryboot-'))) continue
|
|
116
|
+
const ports = ssPortsOf(p.pid)
|
|
117
|
+
if (ports.some(port => LIVE_PORTS.has(port))) continue
|
|
118
|
+
const eph = ports.filter(port => port >= 9000 && port <= 9999)
|
|
119
|
+
if (eph.length === 0) continue
|
|
120
|
+
out.push({ pid: p.pid, port: eph[0], dshHome: home })
|
|
121
|
+
}
|
|
122
|
+
return out
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Boot a copy of the live web profile on an isolated DSH_HOME and verify the
|
|
127
|
+
* plugin tree loads and serves. Returns ok + a one-line detail for the tool
|
|
128
|
+
* message. The spawned tree is killed (best-effort) and the temp home removed.
|
|
129
|
+
* Unit tests mock this (never spawn a real node boot in tests).
|
|
130
|
+
*
|
|
131
|
+
* NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
|
|
132
|
+
* the web app's own commander program (no allowUnknownOption) rejects a stray
|
|
133
|
+
* `--profile` in its inner args — so the spawn passes only `web --no-open
|
|
134
|
+
* --port <port>`.
|
|
135
|
+
*/
|
|
136
|
+
export async function dryBootVerify(harnessRoot: string, opts: { timeoutMs?: number } = {}): Promise<{ ok: boolean; detail: string }> {
|
|
137
|
+
const timeoutMs = opts.timeoutMs ?? 60_000
|
|
138
|
+
const home = homedir()
|
|
139
|
+
const liveProfile = join(home, '.dsh', 'profiles', 'web')
|
|
140
|
+
if (!existsSync(liveProfile)) return { ok: true, detail: 'skipped (no live web profile)' }
|
|
141
|
+
const tmpHome = mkdtempSync(join(tmpdir(), 'dsh-dryboot-'))
|
|
142
|
+
const logs: string[] = []
|
|
143
|
+
let child: ReturnType<typeof spawn> | null = null
|
|
144
|
+
try {
|
|
145
|
+
copyProfileForDryBoot(liveProfile, join(tmpHome, 'profiles', 'web'))
|
|
146
|
+
const port = String(9000 + Math.floor(Math.random() * 1000))
|
|
147
|
+
const url = `http://127.0.0.1:${port}/`
|
|
148
|
+
child = spawn('node', ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web', '--no-open', '--port', port], {
|
|
149
|
+
cwd: harnessRoot, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
|
|
150
|
+
})
|
|
151
|
+
child.stdout?.on('data', (d: Buffer) => logs.push(d.toString()))
|
|
152
|
+
child.stderr?.on('data', (d: Buffer) => logs.push(d.toString()))
|
|
153
|
+
const deadline = Date.now() + timeoutMs
|
|
154
|
+
let code = -1
|
|
155
|
+
while (Date.now() < deadline) {
|
|
156
|
+
if (child.exitCode !== null) { code = child.exitCode; break }
|
|
157
|
+
try { const r = await fetch(url); if (r.status === 200 || r.status === 401) { code = 0; break } } catch {}
|
|
158
|
+
await new Promise(r => setTimeout(r, 500))
|
|
159
|
+
}
|
|
160
|
+
const tail = logs.join('').slice(-3000)
|
|
161
|
+
const loadErr = /ERR_MODULE_NOT_FOUND|assertChannel|must declare output|failed to apply loader entry/.exec(tail)
|
|
162
|
+
if (code === 0 && !loadErr) return { ok: true, detail: 'dry-boot ok' }
|
|
163
|
+
return { ok: false, detail: dryBootFailureDetail(tail, code) }
|
|
164
|
+
} catch (e: any) {
|
|
165
|
+
return { ok: false, detail: `dry-boot error: ${e?.message ?? String(e)}` }
|
|
166
|
+
} finally {
|
|
167
|
+
// Kill on every exit path — a successful boot included. The dry boot only
|
|
168
|
+
// exists to verify the tree; leaving the child up would orphan a dsh web
|
|
169
|
+
// on the ephemeral port whose temp DSH_HOME is removed below, and a stale
|
|
170
|
+
// orphan could later answer a port collision with a false-positive 200.
|
|
171
|
+
try { child?.kill('SIGKILL') } catch {}
|
|
172
|
+
try { rmSync(tmpHome, { recursive: true, force: true }) } catch {}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Classify a failed dry-boot's log tail into a precise one-line detail. The
|
|
178
|
+
* most common operator-actionable failure is an EADDRINUSE — the candidate
|
|
179
|
+
* collided with the live dsh web tree on :3000/:3080 or with another process
|
|
180
|
+
* on the ephemeral 9000-9999 port — so name the colliding port instead of
|
|
181
|
+
* reporting a generic boot failure. Plugin-tree load errors keep their stable
|
|
182
|
+
* codes (the caller's refused message reads `dry-boot failed — restart
|
|
183
|
+
* refused. <detail>`).
|
|
184
|
+
*/
|
|
185
|
+
export function dryBootFailureDetail(tail: string, exitCode: number): string {
|
|
186
|
+
const addrInUse = /EADDRINUSE[^]*?:(\d+)/.exec(tail)
|
|
187
|
+
if (addrInUse) {
|
|
188
|
+
const port = addrInUse[1]
|
|
189
|
+
return `dry-boot failed: port ${port} already in use (EADDRINUSE) — the live dsh web tree or another process holds it`
|
|
190
|
+
}
|
|
191
|
+
const loadErr = /ERR_MODULE_NOT_FOUND|assertChannel|must declare output|failed to apply loader entry/.exec(tail)
|
|
192
|
+
if (loadErr) return `dry-boot failed: ${loadErr[0]}`
|
|
193
|
+
return `dry-boot failed (exit ${exitCode})`
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Minimal file metadata the drift check reads; injectable for deterministic tests. */
|
|
197
|
+
export interface FileStat { mtimeMs: number }
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Whether the live plugin tree differs from the latest LKG snapshot. Three
|
|
201
|
+
* signals are combined:
|
|
202
|
+
*
|
|
203
|
+
* 1. manifest drift — the live profile's web `package.json` text vs baseline;
|
|
204
|
+
* 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
|
|
205
|
+
* baseline (a patch-only config edit changes the boot-time row wiring
|
|
206
|
+
* without touching the manifest — the manifest check alone misses it);
|
|
207
|
+
* 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
|
|
208
|
+
* snapshot moment. Link-installed plugins resolve to the same workspace
|
|
209
|
+
* files in both live and LKG, so the stored copies cannot be compared
|
|
210
|
+
* byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
|
|
211
|
+
* `lib/` bumps a file past it even when the manifest text is unchanged.
|
|
212
|
+
* writeLKG writes `manifest.json` LAST, so its FILE mtime is the
|
|
213
|
+
* authoritative snapshot moment; the snapshot dir mtime is only a
|
|
214
|
+
* fallback for legacy snapshots without a manifest.
|
|
215
|
+
*
|
|
216
|
+
* `statFile` (default `statSync`) reads the metadata so tests can inject a
|
|
217
|
+
* controlled reader instead of relying on filesystem utimes (which CI runners
|
|
218
|
+
* do not reliably reflect). No LKG baseline, a missing file on either side, or
|
|
219
|
+
* any stat/read error means "changed" — the caller falls back to the dry-boot
|
|
220
|
+
* gate.
|
|
221
|
+
*/
|
|
222
|
+
export function isPluginTreeChanged(
|
|
223
|
+
harnessRoot: string,
|
|
224
|
+
lkgDir = join(homedir(), '.dsh/.supervisor/lkg'),
|
|
225
|
+
opts: { statFile?: (p: string) => FileStat } = {},
|
|
226
|
+
): boolean {
|
|
227
|
+
void harnessRoot
|
|
228
|
+
const statFile = opts.statFile ?? ((p: string) => statSync(p))
|
|
229
|
+
try {
|
|
230
|
+
const entries = existsSync(lkgDir) ? readdirSync(lkgDir).sort() : []
|
|
231
|
+
const latest = entries[entries.length - 1]
|
|
232
|
+
if (!latest) return true // no baseline → assume changed
|
|
233
|
+
const lkgHome = join(lkgDir, latest, 'profiles', 'web')
|
|
234
|
+
const live = join(homedir(), '.dsh', 'profiles', 'web')
|
|
235
|
+
const lkgManifest = join(lkgHome, 'package.json')
|
|
236
|
+
const liveManifest = join(live, 'package.json')
|
|
237
|
+
if (!existsSync(lkgManifest) || !existsSync(liveManifest)) return true
|
|
238
|
+
if (readFileSync(liveManifest, 'utf8') !== readFileSync(lkgManifest, 'utf8')) return true
|
|
239
|
+
// cordis.patch.yml — compare only when at least one side has it (profiles
|
|
240
|
+
// without a patch are the baseline; a patch appearing on either side alone
|
|
241
|
+
// is drift). The text compare keeps the check cheap and hermetic.
|
|
242
|
+
const lkgPatch = join(lkgHome, 'cordis.patch.yml')
|
|
243
|
+
const livePatch = join(live, 'cordis.patch.yml')
|
|
244
|
+
if (existsSync(lkgPatch) || existsSync(livePatch)) {
|
|
245
|
+
if (!existsSync(lkgPatch) || !existsSync(livePatch)) return true
|
|
246
|
+
if (readFileSync(livePatch, 'utf8') !== readFileSync(lkgPatch, 'utf8')) return true
|
|
247
|
+
}
|
|
248
|
+
const snapshotManifest = join(lkgDir, latest, 'manifest.json')
|
|
249
|
+
const baseline = existsSync(snapshotManifest)
|
|
250
|
+
? statFile(snapshotManifest).mtimeMs
|
|
251
|
+
: statFile(join(lkgDir, latest)).mtimeMs
|
|
252
|
+
const livePlugins = join(live, 'node_modules', '@ddtcorex')
|
|
253
|
+
if (existsSync(livePlugins)) {
|
|
254
|
+
for (const name of readdirSync(livePlugins)) {
|
|
255
|
+
const libDir = join(livePlugins, name, 'lib')
|
|
256
|
+
if (!existsSync(libDir)) continue
|
|
257
|
+
if (newestFileMtime(libDir, statFile) > baseline) return true
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return false
|
|
261
|
+
} catch { return true }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Newest mtime under a directory; recursion threads the injected stat reader. */
|
|
265
|
+
function newestFileMtime(dir: string, statFile: (p: string) => FileStat): number {
|
|
266
|
+
let newest = 0
|
|
267
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
268
|
+
const p = join(dir, entry.name)
|
|
269
|
+
if (entry.isDirectory()) newest = Math.max(newest, newestFileMtime(p, statFile))
|
|
270
|
+
else newest = Math.max(newest, statFile(p).mtimeMs)
|
|
271
|
+
}
|
|
272
|
+
return newest
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function currentSessionId(exec: any, fallback?: (exec: any) => string | undefined): string | undefined {
|
|
276
|
+
// dsh-tools dispatch hands a ToolRunContext — the exec itself has no
|
|
277
|
+
// sessionId/session/caller fields; session identity lives on the agent
|
|
278
|
+
// (exec.agent.id is the branded SessionId, exec.agent.session.id also
|
|
279
|
+
// exists). Probe those first so production dispatches are identifiable.
|
|
280
|
+
return exec?.agent?.id ?? exec?.agent?.session?.id ?? exec?.sessionId ?? exec?.session?.id ?? exec?.caller?.sessionId ?? fallback?.(exec)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Register the dsh_web_restart tool. Registration is fail-safe (warns, never
|
|
285
|
+
* throws) and the returned function disposes the registration. `deps` are
|
|
286
|
+
* injectable for tests.
|
|
287
|
+
*/
|
|
288
|
+
export function registerRestartTool(ctx: any, deps: {
|
|
289
|
+
sessionIdOf?: (exec: any) => string | undefined
|
|
290
|
+
dryBoot?: typeof dryBootVerify
|
|
291
|
+
writeRestartRequest?: typeof writeRestartRequest
|
|
292
|
+
readRestartRequest?: typeof readRestartRequest
|
|
293
|
+
harnessRoot?: string
|
|
294
|
+
gcReaders?: GcReaders
|
|
295
|
+
killPid?: (pid: number, sig: string) => void
|
|
296
|
+
daemonState?: () => DaemonState
|
|
297
|
+
} = {}): () => void {
|
|
298
|
+
const doDryBoot = deps.dryBoot ?? dryBootVerify
|
|
299
|
+
const doWrite = deps.writeRestartRequest ?? writeRestartRequest
|
|
300
|
+
const doRead = deps.readRestartRequest ?? readRestartRequest
|
|
301
|
+
const doSessionId = deps.sessionIdOf ?? currentSessionId
|
|
302
|
+
const readDaemonState = deps.daemonState ?? supervisorDaemonState
|
|
303
|
+
let dispose: (() => void) | undefined
|
|
304
|
+
let disposeDryboot: (() => void) | undefined
|
|
305
|
+
let disposeGc: (() => void) | undefined
|
|
306
|
+
let disposeStatus: (() => void) | undefined
|
|
307
|
+
try {
|
|
308
|
+
dispose = ctx.tools.register({
|
|
309
|
+
name: 'dsh_web_restart',
|
|
310
|
+
description: 'Schedule a safe restart of the dsh web host: dry-boots the plugin tree when it changed, records an intent for the calling session, and hands the swap to the supervisor daemon (out-of-band — it never restarts in-tree). Returns immediately; the swap lands ~1-5 min later and kills the calling turn, so call this as the LAST action of the turn and verify with dsh_web_restart_status in the NEXT one (never sleep here). Do not call dsh_web_dryboot first — this tool already dry-boots. The result carries the supervisor daemon verdict: a "stale" line means run its `kill -TERM <pid>` before the swap lands.',
|
|
311
|
+
parameters: {
|
|
312
|
+
type: 'object',
|
|
313
|
+
properties: {
|
|
314
|
+
reason: { type: 'string', description: 'Why the restart is happening (recorded in the intent)' },
|
|
315
|
+
pluginChanged: { type: 'boolean', description: 'Override for the auto-detected plugin-tree change check' },
|
|
316
|
+
},
|
|
317
|
+
additionalProperties: false,
|
|
318
|
+
},
|
|
319
|
+
output: {
|
|
320
|
+
schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, detail: { type: 'string' } } },
|
|
321
|
+
render: (_args: any, value: any) => [{ type: 'text', text: value.detail }],
|
|
322
|
+
},
|
|
323
|
+
execute: async (args: any, exec: any) => {
|
|
324
|
+
// Serialize: a fresh restart-request marker means a restart is
|
|
325
|
+
// already in flight (another session, the daemon, or an earlier
|
|
326
|
+
// call of this tool). Scheduling another one overlaps the ~90s
|
|
327
|
+
// SIGTERM stop and crash-loops on EADDRINUSE — refuse fast, before
|
|
328
|
+
// the dry-boot gate, and point at the status tool instead.
|
|
329
|
+
let inflight: ReturnType<typeof readRestartRequest> | undefined
|
|
330
|
+
try {
|
|
331
|
+
inflight = doRead()
|
|
332
|
+
} catch {
|
|
333
|
+
inflight = undefined
|
|
334
|
+
}
|
|
335
|
+
if (inflight !== undefined) {
|
|
336
|
+
const by = inflight.callerSessionId ?? 'unknown session'
|
|
337
|
+
const why = inflight.reason ? `: ${inflight.reason.slice(0, 120)}` : ''
|
|
338
|
+
return { ok: false, detail: `restart already in progress (requested by ${by}${why}) — check dsh_web_restart_status instead of scheduling another` }
|
|
339
|
+
}
|
|
340
|
+
const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir()
|
|
341
|
+
const lkgDir = join(homedir(), '.dsh/.supervisor/lkg')
|
|
342
|
+
const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot, lkgDir))
|
|
343
|
+
if (changed) {
|
|
344
|
+
const gate = await doDryBoot(harnessRoot)
|
|
345
|
+
if (!gate.ok) return { ok: false, detail: `dry-boot failed — restart refused. ${gate.detail}` }
|
|
346
|
+
}
|
|
347
|
+
const callerSessionId = doSessionId(exec)
|
|
348
|
+
if (!callerSessionId) {
|
|
349
|
+
// The daemon's grace branch keys on callerSessionId — without it the
|
|
350
|
+
// marker would be written but no restart would ever be supervised.
|
|
351
|
+
return { ok: false, detail: 'cannot identify the calling session — restart not scheduled' }
|
|
352
|
+
}
|
|
353
|
+
doWrite({ callerSessionId, reason: typeof args.reason === 'string' ? args.reason : undefined, oldPid: process.pid }, 180_000)
|
|
354
|
+
writeIntentSidecar(callerSessionId, args.reason)
|
|
355
|
+
// A read-only probe, and it must never fail the swap: an unmeasurable
|
|
356
|
+
// daemon is reported as such, not treated as a blocker.
|
|
357
|
+
let daemon: DaemonState
|
|
358
|
+
try {
|
|
359
|
+
daemon = readDaemonState()
|
|
360
|
+
} catch {
|
|
361
|
+
daemon = { verdict: 'unknown' }
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
ok: true,
|
|
365
|
+
detail:
|
|
366
|
+
`restart scheduled — caller ${callerSessionId}. The swap lands ~1-5 min from now (measured 2026-10-02: 5m04s schedule→outcome; the dry-boot gate, the daemon's poll, the ~90s SIGTERM stop and the new boot all sit inside that window). THIS TURN ENDS AT THE SWAP: poll dsh_web_restart_status in the next turn, never sleep here. ${describeDaemonState(daemon)}`,
|
|
367
|
+
oldPid: process.pid,
|
|
368
|
+
intentPath: intentPath(callerSessionId),
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
})
|
|
372
|
+
} catch (e: any) {
|
|
373
|
+
try { ctx.logger?.warn?.(`[supervisor] dsh_web_restart tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
374
|
+
}
|
|
375
|
+
try {
|
|
376
|
+
disposeDryboot = ctx.tools.register({
|
|
377
|
+
name: 'dsh_web_dryboot',
|
|
378
|
+
description: 'Validate the plugin tree by booting a copy of the live profile on an ephemeral port. Never schedules or performs a restart; temp home removed afterwards.',
|
|
379
|
+
parameters: {
|
|
380
|
+
type: 'object',
|
|
381
|
+
properties: {
|
|
382
|
+
timeoutMs: { type: 'number', description: 'Gate timeout in ms (default 60000).' },
|
|
383
|
+
},
|
|
384
|
+
additionalProperties: false,
|
|
385
|
+
},
|
|
386
|
+
output: {
|
|
387
|
+
schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, detail: { type: 'string' } } },
|
|
388
|
+
render: (_args: any, value: any) => [{ type: 'text', text: value.detail }],
|
|
389
|
+
},
|
|
390
|
+
execute: async (args: any) => {
|
|
391
|
+
const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir()
|
|
392
|
+
const gate = await doDryBoot(harnessRoot, typeof args.timeoutMs === 'number' ? { timeoutMs: args.timeoutMs } : undefined)
|
|
393
|
+
return { ok: gate.ok, detail: gate.detail }
|
|
394
|
+
},
|
|
395
|
+
})
|
|
396
|
+
} catch (e: any) {
|
|
397
|
+
try { ctx.logger?.warn?.(`[supervisor] dsh_web_dryboot tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
398
|
+
}
|
|
399
|
+
try {
|
|
400
|
+
const doKill = deps.killPid ?? ((pid: number, sig: string) => process.kill(pid, sig as NodeJS.Signals))
|
|
401
|
+
disposeGc = ctx.tools.register({
|
|
402
|
+
name: 'dsh_web_gc',
|
|
403
|
+
description: 'Reap orphaned dry-boot dsh web processes (temp DSH_HOME + ephemeral port). Preview-first: returns candidates without killing unless confirm:true.',
|
|
404
|
+
parameters: {
|
|
405
|
+
type: 'object',
|
|
406
|
+
properties: {
|
|
407
|
+
confirm: { type: 'boolean', description: 'Actually SIGKILL the candidates and verify they are gone.' },
|
|
408
|
+
},
|
|
409
|
+
additionalProperties: false,
|
|
410
|
+
},
|
|
411
|
+
output: {
|
|
412
|
+
schema: { type: 'object', additionalProperties: true, properties: { killed: { type: 'array' }, candidates: { type: 'array' } } },
|
|
413
|
+
render: (_args: any, value: any) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
414
|
+
},
|
|
415
|
+
execute: async (args: any) => {
|
|
416
|
+
// INVARIANT: kill only conjunctive-fingerprint dry-boots (temp DSH_HOME
|
|
417
|
+
// + ephemeral listener), never self / live ports / real-home processes.
|
|
418
|
+
// Preview is the default; killing requires explicit confirm:true.
|
|
419
|
+
const found = listDryBootCandidates(deps.gcReaders)
|
|
420
|
+
if (args.confirm !== true) return { killed: [], candidates: found }
|
|
421
|
+
const killed: number[] = []
|
|
422
|
+
for (const c of found) {
|
|
423
|
+
try { doKill(c.pid, 'SIGKILL') } catch {}
|
|
424
|
+
}
|
|
425
|
+
const remaining = listDryBootCandidates(deps.gcReaders)
|
|
426
|
+
const alive = new Set(remaining.map(c => c.pid))
|
|
427
|
+
for (const c of found) {
|
|
428
|
+
if (!alive.has(c.pid)) killed.push(c.pid)
|
|
429
|
+
}
|
|
430
|
+
return { killed, candidates: remaining }
|
|
431
|
+
},
|
|
432
|
+
})
|
|
433
|
+
} catch (e: any) {
|
|
434
|
+
try { ctx.logger?.warn?.(`[supervisor] dsh_web_gc tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
disposeStatus = ctx.tools.register({
|
|
438
|
+
name: 'dsh_web_restart_status',
|
|
439
|
+
description: 'Read the outcome of the calling session\u2019s latest scheduled dsh web restart (pending until the daemon swaps and health-checks).',
|
|
440
|
+
parameters: {
|
|
441
|
+
type: 'object',
|
|
442
|
+
properties: {},
|
|
443
|
+
additionalProperties: false,
|
|
444
|
+
},
|
|
445
|
+
output: {
|
|
446
|
+
schema: { type: 'object', additionalProperties: true },
|
|
447
|
+
render: (_args: any, value: any) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
448
|
+
},
|
|
449
|
+
execute: async (_args: any, exec: any) => {
|
|
450
|
+
const callerSessionId = doSessionId(exec)
|
|
451
|
+
if (!callerSessionId) return { state: 'none', detail: 'cannot identify the calling session' }
|
|
452
|
+
const outcome = readRestartOutcome(callerSessionId)
|
|
453
|
+
if (outcome) return { ...outcome }
|
|
454
|
+
const intent = readIntent(callerSessionId)
|
|
455
|
+
if (intent) return { state: 'pending', detail: 'restart scheduled, daemon has not reported back yet' }
|
|
456
|
+
return { state: 'none', detail: 'no restart scheduled for this session' }
|
|
457
|
+
},
|
|
458
|
+
})
|
|
459
|
+
} catch (e: any) {
|
|
460
|
+
try { ctx.logger?.warn?.(`[supervisor] dsh_web_restart_status tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
461
|
+
}
|
|
462
|
+
return () => {
|
|
463
|
+
try { if (typeof dispose === 'function') dispose() } catch {}
|
|
464
|
+
try { if (typeof disposeDryboot === 'function') disposeDryboot() } catch {}
|
|
465
|
+
try { if (typeof disposeGc === 'function') disposeGc() } catch {}
|
|
466
|
+
try { if (typeof disposeStatus === 'function') disposeStatus() } catch {}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function writeIntentSidecar(sessionId: string | undefined, reason: string | undefined): void {
|
|
471
|
+
try {
|
|
472
|
+
if (!sessionId) return
|
|
473
|
+
const dir = join(homedir(), '.dsh/.supervisor/intents')
|
|
474
|
+
const require = createRequire(import.meta.url)
|
|
475
|
+
const { mkdirSync, writeFileSync, chmodSync } = require('node:fs') as typeof import('node:fs')
|
|
476
|
+
mkdirSync(dir, { recursive: true })
|
|
477
|
+
// Flatten slash-namespaced ids ('proj/abc' → 'proj_abc') so the sidecar is
|
|
478
|
+
// a single file under intents/ and never needs a nested intents/proj/ dir.
|
|
479
|
+
const safeId = sessionId.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
480
|
+
writeFileSync(join(dir, `${safeId}.json`), JSON.stringify({ ts: Date.now(), sessionId, reason: reason ?? '' }), 'utf8')
|
|
481
|
+
try { chmodSync(join(dir, `${safeId}.json`), 0o600) } catch {}
|
|
482
|
+
} catch {}
|
|
483
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import * as os from 'node:os'
|
|
2
|
+
import * as path from 'node:path'
|
|
3
|
+
import { buildKillStalePortsCommand, writePlannedRestart } from './restart-guards.js'
|
|
4
|
+
import { serializedSystemdRestart, shouldUseNohupFallback, systemdUnitExists } from './restart-exec.js'
|
|
5
|
+
import { withBootLock, type BootLockDeps } from './boot-lock.js'
|
|
6
|
+
import { resolveDeepseekHarnessDir } from './paths.js'
|
|
7
|
+
|
|
8
|
+
/** Boot budget: how long a boot may take before its failures are judged. */
|
|
9
|
+
export const DEFAULT_BOOT_GRACE_MS = 180_000
|
|
10
|
+
|
|
11
|
+
export interface RestartWebDeps {
|
|
12
|
+
exec?: (cmd: string, opts?: { timeout?: number }) => void
|
|
13
|
+
writeMarker?: (ttlMs?: number) => void
|
|
14
|
+
serializedRestart?: () => Promise<void>
|
|
15
|
+
startViaSystemd?: () => void
|
|
16
|
+
spawnNohup?: () => void | Promise<void>
|
|
17
|
+
unitExists?: () => boolean
|
|
18
|
+
bootGraceMs?: number
|
|
19
|
+
lock?: BootLockDeps
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface RestartWebResult {
|
|
23
|
+
restarted: boolean
|
|
24
|
+
reason?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The single implementation of a supervised dsh web restart. Single-flight:
|
|
29
|
+
* boot.lock is held from before the marker is written until the port answers,
|
|
30
|
+
* so a racing tick or a second rollback skips instead of producing the second
|
|
31
|
+
* systemd start that turned the incident's log tail toxic (2026-09-13).
|
|
32
|
+
*/
|
|
33
|
+
export async function performSingleBootRestart(deps: RestartWebDeps = {}): Promise<RestartWebResult> {
|
|
34
|
+
const grace = deps.bootGraceMs ?? DEFAULT_BOOT_GRACE_MS
|
|
35
|
+
const outcome = await withBootLock(async () => {
|
|
36
|
+
// Marker first, and inside the lock: every poll during the boot must know a
|
|
37
|
+
// restart is in flight, and the TTL is the boot budget — not 30 s (D5).
|
|
38
|
+
;(deps.writeMarker ?? writePlannedRestart)(grace)
|
|
39
|
+
const { execSync } = await import('node:child_process')
|
|
40
|
+
const exec = deps.exec ?? ((cmd: string, opts?: { timeout?: number }) => {
|
|
41
|
+
execSync(cmd, { timeout: opts?.timeout ?? 15_000, stdio: 'pipe' })
|
|
42
|
+
})
|
|
43
|
+
// A stale MainThread holding :3080/:3082 survives an EADDRINUSE crash with
|
|
44
|
+
// http 200 still served, so the new start would lose the race.
|
|
45
|
+
try { exec(buildKillStalePortsCommand(), { timeout: 5000 }) } catch {}
|
|
46
|
+
try {
|
|
47
|
+
await (deps.serializedRestart ?? (() => serializedSystemdRestart()))()
|
|
48
|
+
return
|
|
49
|
+
} catch {}
|
|
50
|
+
try {
|
|
51
|
+
;(deps.startViaSystemd ?? (() => exec('systemctl --user start dsh-web.service', { timeout: 15_000 })))()
|
|
52
|
+
return
|
|
53
|
+
} catch {}
|
|
54
|
+
const unitExists = (deps.unitExists ?? systemdUnitExists)()
|
|
55
|
+
if (!shouldUseNohupFallback(unitExists)) {
|
|
56
|
+
throw new Error('systemd manages dsh-web.service but start failed — refusing the direct-node fallback (it would create a second boot)')
|
|
57
|
+
}
|
|
58
|
+
await (deps.spawnNohup ?? defaultNohup)()
|
|
59
|
+
}, deps.lock ?? {})
|
|
60
|
+
if (!outcome.acquired) return { restarted: false, reason: 'another boot already holds boot.lock' }
|
|
61
|
+
return { restarted: true }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function defaultNohup(): Promise<void> {
|
|
65
|
+
const { execSync } = await import('node:child_process')
|
|
66
|
+
const harnessRoot = resolveDeepseekHarnessDir()
|
|
67
|
+
const logPath = path.join(os.homedir(), '.dsh/dsh-web.log')
|
|
68
|
+
execSync(
|
|
69
|
+
`setsid nohup bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; cd ${JSON.stringify(harnessRoot)} && exec node --import tsx/esm apps/cli/src/bin.ts web --no-open >> ${JSON.stringify(logPath)} 2>&1' &`,
|
|
70
|
+
{ timeout: 5000 },
|
|
71
|
+
)
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, chmodSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Durable out-of-band resume log (`~/.dsh/.supervisor/resume.log.jsonl`).
|
|
7
|
+
*
|
|
8
|
+
* The in-tree supervisor's `ctx.logger` output does not reach `dsh-web.log`
|
|
9
|
+
* (it goes to the per-session console), which made every `agents.resume`
|
|
10
|
+
* failure invisible on real machines — the 2026-09-02 investigation only
|
|
11
|
+
* recovered the pattern ("last successful continue 12:00Z, then 5 restarts
|
|
12
|
+
* with none", `lastResumeProbe: null`, unconsumed intents) by scanning the
|
|
13
|
+
* session logs. This append-only JSONL sidecar gives a machine-local audit
|
|
14
|
+
* trail of resume outcomes that survives no matter where plugin logs land.
|
|
15
|
+
* Never throws: a write failure must not break the resume path.
|
|
16
|
+
*/
|
|
17
|
+
export interface ResumeLogEntry {
|
|
18
|
+
ts: number
|
|
19
|
+
sessionId?: string
|
|
20
|
+
/** `resume-retry`: a resume blocked by another owner's write handle, retried. */
|
|
21
|
+
kind: 'scan' | 'resume-failed' | 'resumed' | 'no-agent' | 'resume-retry'
|
|
22
|
+
error?: string
|
|
23
|
+
detail?: string
|
|
24
|
+
scanned?: number
|
|
25
|
+
interrupted?: string[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function resumeLogPath(): string {
|
|
29
|
+
return join(homedir(), '.dsh', '.supervisor', 'resume.log.jsonl')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function appendResumeLog(entry: ResumeLogEntry): void {
|
|
33
|
+
try {
|
|
34
|
+
const p = resumeLogPath()
|
|
35
|
+
mkdirSync(join(homedir(), '.dsh', '.supervisor'), { recursive: true })
|
|
36
|
+
appendFileSync(p, JSON.stringify(entry) + '\n', 'utf8')
|
|
37
|
+
try { chmodSync(p, 0o600) } catch {}
|
|
38
|
+
} catch {}
|
|
39
|
+
}
|