@ddtcorex/dsh-maestro-supervisor 0.6.8 → 0.7.1
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/lib/cli.d.ts +13 -0
- package/lib/cli.js +87 -55
- package/lib/intents.d.ts +15 -0
- package/lib/intents.js +27 -0
- package/lib/plugin.d.ts +6 -2
- package/lib/plugin.js +94 -3
- package/lib/restart-guards.d.ts +11 -0
- package/lib/restart-guards.js +23 -0
- package/lib/restart-tool.d.ts +83 -0
- package/lib/restart-tool.js +277 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +74 -0
- package/lib/self-kill-guard.js +169 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +70 -0
- package/lib/supervisor.d.ts +9 -0
- package/lib/supervisor.js +73 -1
- package/package.json +2 -1
- package/skills/dsh-safe-restart/SKILL.md +90 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +279 -0
package/lib/cli.d.ts
CHANGED
|
@@ -1 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
|
|
3
|
+
* tried newest-first, skipping any that still carry a failing plugin so a
|
|
4
|
+
* broken bundle is not restored. `sessions/` is deliberately NOT restored —
|
|
5
|
+
* session logs are append-only truth and rolling them back to a snapshot
|
|
6
|
+
* would drop every turn recorded after that snapshot.
|
|
7
|
+
* @returns the rolled-back snapshot id.
|
|
8
|
+
*/
|
|
9
|
+
export declare function rollbackLKG(opts: {
|
|
10
|
+
dshHome: string;
|
|
11
|
+
lkgRoot: string;
|
|
12
|
+
failingPlugin?: string;
|
|
13
|
+
}): Promise<string>;
|
|
1
14
|
export declare function runCli(args: string[]): Promise<void>;
|
package/lib/cli.js
CHANGED
|
@@ -5,7 +5,76 @@ import * as fs from 'node:fs';
|
|
|
5
5
|
import * as path from 'node:path';
|
|
6
6
|
import * as os from 'node:os';
|
|
7
7
|
import { resolveHarnessRoot, resolveDeepseekHarnessDir } from './paths.js';
|
|
8
|
-
import { buildKillStalePortsCommand, isSelfCopyError, checkPlannedRestart, writePlannedRestart } from './restart-guards.js';
|
|
8
|
+
import { buildKillStalePortsCommand, isSelfCopyError, checkPlannedRestart, writePlannedRestart, readRestartRequest, clearPlannedRestart } from './restart-guards.js';
|
|
9
|
+
/**
|
|
10
|
+
* Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
|
|
11
|
+
* tried newest-first, skipping any that still carry a failing plugin so a
|
|
12
|
+
* broken bundle is not restored. `sessions/` is deliberately NOT restored —
|
|
13
|
+
* session logs are append-only truth and rolling them back to a snapshot
|
|
14
|
+
* would drop every turn recorded after that snapshot.
|
|
15
|
+
* @returns the rolled-back snapshot id.
|
|
16
|
+
*/
|
|
17
|
+
export async function rollbackLKG(opts) {
|
|
18
|
+
const { dshHome, lkgRoot, failingPlugin } = opts;
|
|
19
|
+
const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : [];
|
|
20
|
+
if (!entries.length)
|
|
21
|
+
throw new Error('no LKG to rollback to');
|
|
22
|
+
const candidates = [...entries].reverse().slice(0, 3);
|
|
23
|
+
let chosen;
|
|
24
|
+
for (const cand of candidates) {
|
|
25
|
+
if (!failingPlugin) {
|
|
26
|
+
chosen = cand;
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json');
|
|
31
|
+
if (!fs.existsSync(pkgPath)) {
|
|
32
|
+
chosen = cand;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
36
|
+
const bundles = pkg?.dsh?.profile?.bundles ?? [];
|
|
37
|
+
const deps = pkg?.dependencies ?? {};
|
|
38
|
+
const hasFailing = bundles.some((b) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin));
|
|
39
|
+
if (!hasFailing) {
|
|
40
|
+
chosen = cand;
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
chosen = cand;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const target = chosen ?? entries[entries.length - 1];
|
|
51
|
+
const src = path.join(lkgRoot, target);
|
|
52
|
+
for (const entry of fs.readdirSync(src)) {
|
|
53
|
+
if (entry === 'manifest.json')
|
|
54
|
+
continue;
|
|
55
|
+
if (entry === 'sessions') {
|
|
56
|
+
console.log('[supervisor] rollback keeps live sessions (append-only truth) — skipping sessions/');
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const srcPath = path.join(src, entry);
|
|
60
|
+
const destPath = path.join(dshHome, entry);
|
|
61
|
+
try {
|
|
62
|
+
// Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
|
|
63
|
+
try {
|
|
64
|
+
if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath))
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
fs.cpSync(srcPath, destPath, { recursive: true, force: true });
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
if (isSelfCopyError(String(e?.message ?? '')))
|
|
72
|
+
continue;
|
|
73
|
+
throw e;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return target;
|
|
77
|
+
}
|
|
9
78
|
export async function runCli(args) {
|
|
10
79
|
const cmd = args[2] ?? '--help';
|
|
11
80
|
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
|
|
@@ -108,10 +177,6 @@ Commands:
|
|
|
108
177
|
},
|
|
109
178
|
rollback: async () => {
|
|
110
179
|
const { execSync } = await import('node:child_process');
|
|
111
|
-
const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : [];
|
|
112
|
-
if (!entries.length)
|
|
113
|
-
throw new Error('no LKG to rollback to');
|
|
114
|
-
// Try newest to oldest (up to 3) to find a clean LKG for plugin failures
|
|
115
180
|
// Extract failing plugin from current log tail if possible
|
|
116
181
|
let failingPlugin;
|
|
117
182
|
try {
|
|
@@ -121,56 +186,7 @@ Commands:
|
|
|
121
186
|
failingPlugin = m[0].replace(/^@ddtcorex\//, '');
|
|
122
187
|
}
|
|
123
188
|
catch { }
|
|
124
|
-
const
|
|
125
|
-
let chosen;
|
|
126
|
-
for (const cand of candidates) {
|
|
127
|
-
if (!failingPlugin) {
|
|
128
|
-
chosen = cand;
|
|
129
|
-
break;
|
|
130
|
-
}
|
|
131
|
-
try {
|
|
132
|
-
const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json');
|
|
133
|
-
if (!fs.existsSync(pkgPath)) {
|
|
134
|
-
chosen = cand;
|
|
135
|
-
break;
|
|
136
|
-
}
|
|
137
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
138
|
-
const bundles = pkg?.dsh?.profile?.bundles ?? [];
|
|
139
|
-
const deps = pkg?.dependencies ?? {};
|
|
140
|
-
const hasFailing = bundles.some((b) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin));
|
|
141
|
-
if (!hasFailing) {
|
|
142
|
-
chosen = cand;
|
|
143
|
-
break;
|
|
144
|
-
}
|
|
145
|
-
console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`);
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
chosen = cand;
|
|
149
|
-
break;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
const target = chosen ?? entries[entries.length - 1];
|
|
153
|
-
const src = path.join(lkgRoot, target);
|
|
154
|
-
for (const entry of fs.readdirSync(src)) {
|
|
155
|
-
if (entry === 'manifest.json')
|
|
156
|
-
continue;
|
|
157
|
-
const srcPath = path.join(src, entry);
|
|
158
|
-
const destPath = path.join(dshHome, entry);
|
|
159
|
-
try {
|
|
160
|
-
// Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
|
|
161
|
-
try {
|
|
162
|
-
if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath))
|
|
163
|
-
continue;
|
|
164
|
-
}
|
|
165
|
-
catch { }
|
|
166
|
-
fs.cpSync(srcPath, destPath, { recursive: true, force: true });
|
|
167
|
-
}
|
|
168
|
-
catch (e) {
|
|
169
|
-
if (isSelfCopyError(String(e?.message ?? '')))
|
|
170
|
-
continue;
|
|
171
|
-
throw e;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
189
|
+
const target = await rollbackLKG({ dshHome, lkgRoot, failingPlugin });
|
|
174
190
|
console.log(`[supervisor] rolled back to ${target}${failingPlugin ? ` (avoiding ${failingPlugin})` : ''}`);
|
|
175
191
|
// Reconcile node_modules from restored package.json (critical for link: deps)
|
|
176
192
|
try {
|
|
@@ -229,6 +245,22 @@ Commands:
|
|
|
229
245
|
},
|
|
230
246
|
notify: async (msg) => console.log(`[notify] ${msg}`),
|
|
231
247
|
isPlannedRestartActive: () => checkPlannedRestart(),
|
|
248
|
+
// dsh_web_restart marker ownership: the daemon acts on the marker. After
|
|
249
|
+
// the restart, scan recent session logs for torn tails (an in-flight
|
|
250
|
+
// session truncated by the restart) and report; the marker is cleared in
|
|
251
|
+
// the supervisor's own finally block and again here as a safety net.
|
|
252
|
+
readRestartRequest: () => readRestartRequest(),
|
|
253
|
+
onRestartRequestHandled: async () => {
|
|
254
|
+
const { scanSessions } = await import('./scan.js');
|
|
255
|
+
const res = await scanSessions(path.join(os.homedir(), '.dsh'), { withinMs: 10 * 60 * 1000 }).catch(() => ({ scanned: 0, torn: [] }));
|
|
256
|
+
if (res.torn.length) {
|
|
257
|
+
console.log(`[supervisor] post-self-restart scan: ${res.torn.length} torn session log(s)`);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
console.log('[supervisor] post-self-restart scan: clean');
|
|
261
|
+
}
|
|
262
|
+
void clearPlannedRestart();
|
|
263
|
+
},
|
|
232
264
|
});
|
|
233
265
|
await supervisor.start();
|
|
234
266
|
// keep process alive
|
package/lib/intents.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable self-restart intent sidecar written by `dsh_web_restart`
|
|
3
|
+
* (`~/.dsh/.supervisor/intents/<sessionId>.json`, mode 600). Consumed by
|
|
4
|
+
* auto-resume so a session that requested the restart is resumed with a
|
|
5
|
+
* contextual message instead of the generic "outcome unknown" recovery text.
|
|
6
|
+
*/
|
|
7
|
+
export interface RestartIntent {
|
|
8
|
+
ts: number;
|
|
9
|
+
sessionId?: string;
|
|
10
|
+
reason?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function intentsDir(): string;
|
|
13
|
+
export declare function intentPath(sessionId: string): string;
|
|
14
|
+
export declare function readIntent(sessionId: string): RestartIntent | undefined;
|
|
15
|
+
export declare function consumeIntent(sessionId: string): void;
|
package/lib/intents.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { existsSync, readFileSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
export function intentsDir() {
|
|
5
|
+
return join(homedir(), '.dsh', '.supervisor', 'intents');
|
|
6
|
+
}
|
|
7
|
+
export function intentPath(sessionId) {
|
|
8
|
+
const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
9
|
+
return join(intentsDir(), `${safe}.json`);
|
|
10
|
+
}
|
|
11
|
+
export function readIntent(sessionId) {
|
|
12
|
+
try {
|
|
13
|
+
const p = intentPath(sessionId);
|
|
14
|
+
if (!existsSync(p))
|
|
15
|
+
return undefined;
|
|
16
|
+
return JSON.parse(readFileSync(p, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function consumeIntent(sessionId) {
|
|
23
|
+
try {
|
|
24
|
+
unlinkSync(intentPath(sessionId));
|
|
25
|
+
}
|
|
26
|
+
catch { }
|
|
27
|
+
}
|
package/lib/plugin.d.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
* and web restart; this plugin handles the in-process resume.
|
|
7
7
|
*/
|
|
8
8
|
import { findInterrupted as defaultFindInterrupted, findDanglingOpenTurns as defaultFindDanglingOpenTurns } from './resume.js';
|
|
9
|
-
|
|
9
|
+
import type { RestartIntent } from './intents.js';
|
|
10
|
+
export declare const inject: readonly ["sessions", "agents", "connection", "tools", "skills"];
|
|
10
11
|
export interface SupervisorPluginConfig {
|
|
11
12
|
autoResumeWithin?: number | string;
|
|
12
13
|
autoResumeEnabled?: boolean;
|
|
@@ -17,7 +18,10 @@ export declare function runAutoResume(ctx: any, opts?: {
|
|
|
17
18
|
resumeInterrupted?: typeof resumeInterrupted;
|
|
18
19
|
config?: SupervisorPluginConfig;
|
|
19
20
|
}): Promise<void>;
|
|
20
|
-
export declare function resumeInterrupted(ctx: any, ids: string[]
|
|
21
|
+
export declare function resumeInterrupted(ctx: any, ids: string[], deps?: {
|
|
22
|
+
readIntent?: (id: string) => RestartIntent | undefined;
|
|
23
|
+
consumeIntent?: (id: string) => void;
|
|
24
|
+
}): Promise<string[]>;
|
|
21
25
|
export declare function createResumeRpcHandler(ctx: any, opts?: {
|
|
22
26
|
resumeInterrupted?: typeof resumeInterrupted;
|
|
23
27
|
config?: SupervisorPluginConfig;
|
package/lib/plugin.js
CHANGED
|
@@ -8,8 +8,14 @@
|
|
|
8
8
|
import * as fs from 'node:fs';
|
|
9
9
|
import * as path from 'node:path';
|
|
10
10
|
import * as os from 'node:os';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
11
12
|
import { findInterrupted as defaultFindInterrupted, findDanglingOpenTurns as defaultFindDanglingOpenTurns } from './resume.js';
|
|
12
|
-
|
|
13
|
+
import { readIntent, consumeIntent } from './intents.js';
|
|
14
|
+
import { makeSkillProvider } from './skill-provider.js';
|
|
15
|
+
import { registerRestartTool } from './restart-tool.js';
|
|
16
|
+
import { makePreExecuteGuard } from './self-kill-guard.js';
|
|
17
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
export const inject = ['sessions', 'agents', 'connection', 'tools', 'skills'];
|
|
13
19
|
function parseDuration(s) {
|
|
14
20
|
if (!s)
|
|
15
21
|
return undefined;
|
|
@@ -166,7 +172,9 @@ export async function runAutoResume(ctx, opts = {}) {
|
|
|
166
172
|
catch { }
|
|
167
173
|
}
|
|
168
174
|
}
|
|
169
|
-
export async function resumeInterrupted(ctx, ids) {
|
|
175
|
+
export async function resumeInterrupted(ctx, ids, deps = {}) {
|
|
176
|
+
const doReadIntent = deps.readIntent ?? readIntent;
|
|
177
|
+
const doConsumeIntent = deps.consumeIntent ?? consumeIntent;
|
|
170
178
|
const resumed = [];
|
|
171
179
|
for (const id of ids) {
|
|
172
180
|
try {
|
|
@@ -241,15 +249,31 @@ export async function resumeInterrupted(ctx, ids) {
|
|
|
241
249
|
// model to verify external state before retrying. A bare "continue" made
|
|
242
250
|
// the model reply with text instead of re-issuing bash, leaving the
|
|
243
251
|
// session stuck after every crash (36646045..., 31ae53a2...).
|
|
244
|
-
const
|
|
252
|
+
const idleMessage = 'The previous turn was interrupted by a crash and the harness has synthesized a tool result with TOOL_OUTCOME_UNKNOWN / TOOL_NOT_STARTED. ' +
|
|
245
253
|
'Outcome of the last tool call is unknown — it may or may not have had side effects. ' +
|
|
246
254
|
'Verify external state with bash (e.g., ls, cat, git status) before retrying. ' +
|
|
247
255
|
'Retry only if the operation is read-only or idempotent; if it may have side effects, verify first or ask the user. ' +
|
|
248
256
|
'Then continue the original task from where it was interrupted — re-issue the next bash/tool call that the plan requires.';
|
|
257
|
+
// A session that requested the dsh web restart has a durable intent
|
|
258
|
+
// sidecar (written by dsh_web_restart): resume it with a contextual
|
|
259
|
+
// message instead of the generic "outcome unknown" recovery prompt, then
|
|
260
|
+
// consume the sidecar so it cannot re-trigger on a later resume.
|
|
261
|
+
let resumeMessage = idleMessage;
|
|
262
|
+
try {
|
|
263
|
+
const intent = doReadIntent(sessionId);
|
|
264
|
+
if (intent)
|
|
265
|
+
resumeMessage = `You requested a dsh web restart${intent.reason ? ` (reason: ${intent.reason})` : ''} and it completed. Do NOT call dsh_web_restart again. Verify current state if needed, then continue the original task.`;
|
|
266
|
+
}
|
|
267
|
+
catch { }
|
|
249
268
|
agent.followup(createUserMessage({
|
|
250
269
|
content: [{ type: 'text', text: resumeMessage }],
|
|
251
270
|
source: { kind: 'user' },
|
|
252
271
|
}));
|
|
272
|
+
try {
|
|
273
|
+
if (resumeMessage !== idleMessage)
|
|
274
|
+
doConsumeIntent(sessionId);
|
|
275
|
+
}
|
|
276
|
+
catch { }
|
|
253
277
|
resumed.push(id);
|
|
254
278
|
ctx.logger?.info?.(`[supervisor] auto-resume: sent recovery continue for ${id}`);
|
|
255
279
|
}
|
|
@@ -280,6 +304,25 @@ export function createResumeRpcHandler(ctx, opts = {}) {
|
|
|
280
304
|
return { ok: true, value: { resumed: await resume(ctx, ids) } };
|
|
281
305
|
};
|
|
282
306
|
}
|
|
307
|
+
/** Resolve the package-root skills/ dir regardless of module layout. The built
|
|
308
|
+
* host lib is flat (lib/plugin.js → ../skills), but under vitest the same
|
|
309
|
+
* module loads from src/host/ (→ ../../skills). Walking to the nearest
|
|
310
|
+
* package.json yields the same package-root skills/ in both layouts. */
|
|
311
|
+
function resolveSkillsDir(fromDir) {
|
|
312
|
+
let dir = fromDir;
|
|
313
|
+
for (let i = 0; i < 6; i++) {
|
|
314
|
+
try {
|
|
315
|
+
if (fs.existsSync(path.join(dir, 'package.json')))
|
|
316
|
+
return path.join(dir, 'skills');
|
|
317
|
+
}
|
|
318
|
+
catch { }
|
|
319
|
+
const parent = path.dirname(dir);
|
|
320
|
+
if (parent === dir)
|
|
321
|
+
break;
|
|
322
|
+
dir = parent;
|
|
323
|
+
}
|
|
324
|
+
return path.join(fromDir, '..', 'skills');
|
|
325
|
+
}
|
|
283
326
|
function ensureSystemdKeepalive(ctx) {
|
|
284
327
|
// Best-effort: ensure dsh-web-keepalive.service exists and is enabled, and linger is on.
|
|
285
328
|
// This is the user-level auto-fix for the 11:42:58 crash where manager session 97
|
|
@@ -365,6 +408,36 @@ export function apply(ctx, config = {}) {
|
|
|
365
408
|
ensureSystemdKeepalive(ctx);
|
|
366
409
|
}
|
|
367
410
|
catch { }
|
|
411
|
+
try {
|
|
412
|
+
const skills = ctx.get?.('skills');
|
|
413
|
+
if (skills?.registerProvider) {
|
|
414
|
+
ctx.effect(() => {
|
|
415
|
+
let unregister;
|
|
416
|
+
try {
|
|
417
|
+
// Package-root skills/ is resolved at runtime by walking to the
|
|
418
|
+
// nearest package.json (robust to lib/ vs src/host/ layouts).
|
|
419
|
+
unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)));
|
|
420
|
+
}
|
|
421
|
+
catch (e) {
|
|
422
|
+
ctx.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`);
|
|
423
|
+
}
|
|
424
|
+
return () => { try {
|
|
425
|
+
unregister?.();
|
|
426
|
+
}
|
|
427
|
+
catch { } };
|
|
428
|
+
}, 'supervisor:skill');
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
catch { }
|
|
432
|
+
try {
|
|
433
|
+
ctx.effect(() => registerRestartTool(ctx), 'supervisor:restart-tool');
|
|
434
|
+
}
|
|
435
|
+
catch (e) {
|
|
436
|
+
try {
|
|
437
|
+
ctx.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`);
|
|
438
|
+
}
|
|
439
|
+
catch { }
|
|
440
|
+
}
|
|
368
441
|
ctx.effect(() => {
|
|
369
442
|
let disposed = false;
|
|
370
443
|
let timer = null;
|
|
@@ -400,6 +473,24 @@ export function apply(ctx, config = {}) {
|
|
|
400
473
|
}
|
|
401
474
|
};
|
|
402
475
|
}, 'supervisor:auto-resume');
|
|
476
|
+
try {
|
|
477
|
+
// Deny bash/shell self-kill commands in-tree; the safe restart path is
|
|
478
|
+
// dsh_web_restart (supervisor daemon owns the actual restart).
|
|
479
|
+
const guard = makePreExecuteGuard();
|
|
480
|
+
ctx.effect(() => {
|
|
481
|
+
const un = ctx.on?.('tools/pre-execute', guard) ?? null;
|
|
482
|
+
return () => { try {
|
|
483
|
+
un?.();
|
|
484
|
+
}
|
|
485
|
+
catch { } };
|
|
486
|
+
}, 'supervisor:self-kill-guard');
|
|
487
|
+
}
|
|
488
|
+
catch (e) {
|
|
489
|
+
try {
|
|
490
|
+
ctx.logger?.warn?.(`[supervisor] self-kill guard effect failed: ${e?.message ?? String(e)}`);
|
|
491
|
+
}
|
|
492
|
+
catch { }
|
|
493
|
+
}
|
|
403
494
|
}
|
|
404
495
|
catch (e) {
|
|
405
496
|
try {
|
package/lib/restart-guards.d.ts
CHANGED
|
@@ -6,3 +6,14 @@ export declare function plannedRestartPath(): string;
|
|
|
6
6
|
export declare function writePlannedRestart(ttlMs?: number): void;
|
|
7
7
|
export declare function checkPlannedRestart(markerPath?: string): boolean;
|
|
8
8
|
export declare function clearPlannedRestart(): void;
|
|
9
|
+
export interface RestartRequest {
|
|
10
|
+
ts: number;
|
|
11
|
+
ttl: number;
|
|
12
|
+
callerSessionId?: string;
|
|
13
|
+
reason?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function writeRestartRequest(caller: {
|
|
16
|
+
callerSessionId?: string;
|
|
17
|
+
reason?: string;
|
|
18
|
+
}, ttlMs?: number): void;
|
|
19
|
+
export declare function readRestartRequest(): RestartRequest | undefined;
|
package/lib/restart-guards.js
CHANGED
|
@@ -92,3 +92,26 @@ export function clearPlannedRestart() {
|
|
|
92
92
|
}
|
|
93
93
|
catch { }
|
|
94
94
|
}
|
|
95
|
+
export function writeRestartRequest(caller, ttlMs = 180_000) {
|
|
96
|
+
const p = plannedRestartPath();
|
|
97
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
98
|
+
const body = { ts: Date.now(), ttl: ttlMs, ...caller };
|
|
99
|
+
fs.writeFileSync(p, JSON.stringify(body), { mode: 0o600 });
|
|
100
|
+
try {
|
|
101
|
+
fs.chmodSync(p, 0o600);
|
|
102
|
+
}
|
|
103
|
+
catch { }
|
|
104
|
+
}
|
|
105
|
+
export function readRestartRequest() {
|
|
106
|
+
try {
|
|
107
|
+
const raw = fs.readFileSync(plannedRestartPath(), 'utf8');
|
|
108
|
+
const j = JSON.parse(raw);
|
|
109
|
+
if (typeof j.ts === 'number' && typeof j.ttl === 'number') {
|
|
110
|
+
if (Date.now() - j.ts >= j.ttl)
|
|
111
|
+
return undefined;
|
|
112
|
+
return { ts: j.ts, ttl: j.ttl, callerSessionId: j.callerSessionId, reason: j.reason };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch { }
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
import { writeRestartRequest } from './restart-guards.js';
|
|
16
|
+
/**
|
|
17
|
+
* Boot a copy of the live web profile on an isolated DSH_HOME and verify the
|
|
18
|
+
* plugin tree loads and serves. Returns ok + a one-line detail for the tool
|
|
19
|
+
* message. The spawned tree is killed (best-effort) and the temp home removed.
|
|
20
|
+
* Unit tests mock this (never spawn a real node boot in tests).
|
|
21
|
+
*
|
|
22
|
+
* NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
|
|
23
|
+
* the web app's own commander program (no allowUnknownOption) rejects a stray
|
|
24
|
+
* `--profile` in its inner args — so the spawn passes only `web --no-open
|
|
25
|
+
* --port <port>`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function dryBootVerify(harnessRoot: string, opts?: {
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
}): Promise<{
|
|
30
|
+
ok: boolean;
|
|
31
|
+
detail: string;
|
|
32
|
+
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Classify a failed dry-boot's log tail into a precise one-line detail. The
|
|
35
|
+
* most common operator-actionable failure is an EADDRINUSE — the candidate
|
|
36
|
+
* collided with the live dsh web tree on :3000/:3080 or with another process
|
|
37
|
+
* on the ephemeral 9000-9999 port — so name the colliding port instead of
|
|
38
|
+
* reporting a generic boot failure. Plugin-tree load errors keep their stable
|
|
39
|
+
* codes (the caller's refused message reads `dry-boot failed — restart
|
|
40
|
+
* refused. <detail>`).
|
|
41
|
+
*/
|
|
42
|
+
export declare function dryBootFailureDetail(tail: string, exitCode: number): string;
|
|
43
|
+
/** Minimal file metadata the drift check reads; injectable for deterministic tests. */
|
|
44
|
+
export interface FileStat {
|
|
45
|
+
mtimeMs: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Whether the live plugin tree differs from the latest LKG snapshot. Three
|
|
49
|
+
* signals are combined:
|
|
50
|
+
*
|
|
51
|
+
* 1. manifest drift — the live profile's web `package.json` text vs baseline;
|
|
52
|
+
* 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
|
|
53
|
+
* baseline (a patch-only config edit changes the boot-time row wiring
|
|
54
|
+
* without touching the manifest — the manifest check alone misses it);
|
|
55
|
+
* 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
|
|
56
|
+
* snapshot moment. Link-installed plugins resolve to the same workspace
|
|
57
|
+
* files in both live and LKG, so the stored copies cannot be compared
|
|
58
|
+
* byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
|
|
59
|
+
* `lib/` bumps a file past it even when the manifest text is unchanged.
|
|
60
|
+
* writeLKG writes `manifest.json` LAST, so its FILE mtime is the
|
|
61
|
+
* authoritative snapshot moment; the snapshot dir mtime is only a
|
|
62
|
+
* fallback for legacy snapshots without a manifest.
|
|
63
|
+
*
|
|
64
|
+
* `statFile` (default `statSync`) reads the metadata so tests can inject a
|
|
65
|
+
* controlled reader instead of relying on filesystem utimes (which CI runners
|
|
66
|
+
* do not reliably reflect). No LKG baseline, a missing file on either side, or
|
|
67
|
+
* any stat/read error means "changed" — the caller falls back to the dry-boot
|
|
68
|
+
* gate.
|
|
69
|
+
*/
|
|
70
|
+
export declare function isPluginTreeChanged(harnessRoot: string, lkgDir?: string, opts?: {
|
|
71
|
+
statFile?: (p: string) => FileStat;
|
|
72
|
+
}): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Register the dsh_web_restart tool. Registration is fail-safe (warns, never
|
|
75
|
+
* throws) and the returned function disposes the registration. `deps` are
|
|
76
|
+
* injectable for tests.
|
|
77
|
+
*/
|
|
78
|
+
export declare function registerRestartTool(ctx: any, deps?: {
|
|
79
|
+
sessionIdOf?: (exec: any) => string | undefined;
|
|
80
|
+
dryBoot?: typeof dryBootVerify;
|
|
81
|
+
writeRestartRequest?: typeof writeRestartRequest;
|
|
82
|
+
harnessRoot?: string;
|
|
83
|
+
}): () => void;
|