@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.
Files changed (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
package/lib/plugin.js ADDED
@@ -0,0 +1,1126 @@
1
+ /**
2
+ * dsh-maestro-core — host plugin for auto-resume inside DSH web.
3
+ * Runs inside the DSH host process (outside the daemon's tree) and
4
+ * auto-resumes sessions interrupted within the configured window after
5
+ * a restart. The standalone daemon (systemd) handles crash detection
6
+ * and web restart; this plugin handles the in-process resume.
7
+ */
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import * as os from 'node:os';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { findInterrupted as defaultFindInterrupted, findDanglingOpenTurns as defaultFindDanglingOpenTurns, resolveSessionLogPath } from './resume.js';
13
+ import { readIntent, consumeIntent } from './intents.js';
14
+ import { appendResumeLog } from './resume-log.js';
15
+ import { makeSkillProvider } from './skill-provider.js';
16
+ import { registerRestartTool } from './restart-tool.js';
17
+ import { makePreExecuteGuard } from './self-kill-guard.js';
18
+ import { runSessionHealthCheck } from './session-health.js';
19
+ import { notify } from './notifier.js';
20
+ import { warnCoreToolLoss, recordResumedSession, recordResumeProbe, recordResumeComposition, parkResumedSession, registerResumeToolHealthService, } from './resume-tools.js';
21
+ export * from './resume-tools.js';
22
+ import { probeToolView, defaultResolveToolScope, } from './tool-view.js';
23
+ export * from './tool-view.js';
24
+ import { resolveSessionPresetId, makePresetSetup, composedPresetId, repairAgentPreset, } from './preset.js';
25
+ export * from './preset.js';
26
+ import { SUPERVISOR_SOURCE_KIND } from './source.js';
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+ export const inject = ['sessions', 'agents', 'connection', 'tools', 'skills'];
29
+ function parseDuration(s) {
30
+ if (!s)
31
+ return undefined;
32
+ const m = s.trim().match(/^(\d+)(s|m|h)?$/);
33
+ if (!m)
34
+ return undefined;
35
+ const n = parseInt(m[1], 10);
36
+ const unit = m[2] ?? 's';
37
+ if (unit === 's')
38
+ return n * 1000;
39
+ if (unit === 'm')
40
+ return n * 60 * 1000;
41
+ if (unit === 'h')
42
+ return n * 60 * 60 * 1000;
43
+ return undefined;
44
+ }
45
+ function getAutoResumeEnabled(config) {
46
+ // The Cordis-supplied config (cordis.patch.yml's `config:` block, or whatever
47
+ // the caller passes to apply()) is the highest-precedence source — it is an
48
+ // explicit, per-install decision and must win over ambient env/files.
49
+ if (typeof config?.autoResumeEnabled === 'boolean')
50
+ return config.autoResumeEnabled;
51
+ const env = process.env.DSH_SUPERVISOR_AUTO_RESUME;
52
+ if (env !== undefined) {
53
+ const v = env.trim().toLowerCase();
54
+ if (['1', 'true', 'yes', 'on', 'enabled'].includes(v))
55
+ return true;
56
+ if (['0', 'false', 'no', 'off', 'disabled'].includes(v))
57
+ return false;
58
+ }
59
+ try {
60
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
61
+ if (fs.existsSync(cfgPath)) {
62
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
63
+ const raw = cfg.autoResumeEnabled ?? cfg.autoResume;
64
+ if (typeof raw === 'boolean')
65
+ return raw;
66
+ if (typeof raw === 'string') {
67
+ const v = raw.trim().toLowerCase();
68
+ if (['1', 'true', 'yes', 'on'].includes(v))
69
+ return true;
70
+ if (['0', 'false', 'no', 'off'].includes(v))
71
+ return false;
72
+ }
73
+ }
74
+ const maestroPath = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'dsh-maestro-config', 'settings.json');
75
+ if (fs.existsSync(maestroPath)) {
76
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
77
+ const raw = j?.domains?.supervisor?.autoResumeEnabled ?? j?.supervisor?.autoResumeEnabled;
78
+ if (typeof raw === 'boolean')
79
+ return raw;
80
+ if (typeof raw === 'string') {
81
+ const v = raw.trim().toLowerCase();
82
+ if (['1', 'true', 'yes', 'on'].includes(v))
83
+ return true;
84
+ if (['0', 'false', 'no', 'off'].includes(v))
85
+ return false;
86
+ }
87
+ }
88
+ }
89
+ catch { }
90
+ return true;
91
+ }
92
+ /**
93
+ * C2 — resolve the mitigation policy with exactly the same precedence chain as
94
+ * getAutoResumeEnabled: (1) the Cordis-supplied plugin config (cordis.patch.yml
95
+ * `config:` block / whatever apply() receives — highest precedence), (2) env
96
+ * DSH_SUPERVISOR_RESUME_CORE_TOOL_POLICY, (3) ~/.dsh/.supervisor/config.json,
97
+ * (4) ~/.dsh/dsh-maestro-config/settings.json (domains.supervisor.resumeCoreToolPolicy),
98
+ * (5) 'warn'. Any other value falls through to the default 'warn'.
99
+ */
100
+ function getResumeCoreToolPolicy(config) {
101
+ if (config?.resumeCoreToolPolicy === 'warn' || config?.resumeCoreToolPolicy === 'park') {
102
+ return config.resumeCoreToolPolicy;
103
+ }
104
+ const env = process.env.DSH_SUPERVISOR_RESUME_CORE_TOOL_POLICY;
105
+ if (env) {
106
+ const v = env.trim().toLowerCase();
107
+ if (v === 'warn' || v === 'park')
108
+ return v;
109
+ }
110
+ try {
111
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
112
+ if (fs.existsSync(cfgPath)) {
113
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
114
+ const raw = cfg.resumeCoreToolPolicy;
115
+ if (raw === 'warn' || raw === 'park')
116
+ return raw;
117
+ }
118
+ const maestroPath = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'dsh-maestro-config', 'settings.json');
119
+ if (fs.existsSync(maestroPath)) {
120
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
121
+ const raw = j?.domains?.supervisor?.resumeCoreToolPolicy ?? j?.supervisor?.resumeCoreToolPolicy;
122
+ if (raw === 'warn' || raw === 'park')
123
+ return raw;
124
+ }
125
+ }
126
+ catch { }
127
+ return 'warn';
128
+ }
129
+ /**
130
+ * Whether the resume path may re-link a preset-less agent to its preset.
131
+ *
132
+ * Same precedence chain as `getResumeCoreToolPolicy`: (1) the Cordis-supplied
133
+ * plugin config, (2) env `DSH_SUPERVISOR_RESUME_AUTO_REPAIR`, (3)
134
+ * `~/.dsh/.supervisor/config.json`, (4)
135
+ * `~/.dsh/dsh-maestro-config/settings.json` (`domains.supervisor.resumeAutoRepair`),
136
+ * (5) `true`. Repair mutates a live agent's tool surface, so operators get a
137
+ * kill switch; the loss itself is still reported when it is off.
138
+ * @param config - the Cordis config handed to `apply()`.
139
+ * @returns whether an automatic repair may run.
140
+ */
141
+ function getResumeAutoRepair(config) {
142
+ if (typeof config?.resumeAutoRepair === 'boolean')
143
+ return config.resumeAutoRepair;
144
+ const parse = (raw) => {
145
+ if (typeof raw === 'boolean')
146
+ return raw;
147
+ if (typeof raw === 'string') {
148
+ const v = raw.trim().toLowerCase();
149
+ if (['1', 'true', 'yes', 'on'].includes(v))
150
+ return true;
151
+ if (['0', 'false', 'no', 'off'].includes(v))
152
+ return false;
153
+ }
154
+ return undefined;
155
+ };
156
+ const fromEnv = parse(process.env.DSH_SUPERVISOR_RESUME_AUTO_REPAIR);
157
+ if (fromEnv !== undefined)
158
+ return fromEnv;
159
+ try {
160
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
161
+ if (fs.existsSync(cfgPath)) {
162
+ const fromFile = parse(JSON.parse(fs.readFileSync(cfgPath, 'utf-8')).resumeAutoRepair);
163
+ if (fromFile !== undefined)
164
+ return fromFile;
165
+ }
166
+ const maestroPath = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'dsh-maestro-config', 'settings.json');
167
+ if (fs.existsSync(maestroPath)) {
168
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
169
+ const fromSettings = parse(j?.domains?.supervisor?.resumeAutoRepair ?? j?.supervisor?.resumeAutoRepair);
170
+ if (fromSettings !== undefined)
171
+ return fromSettings;
172
+ }
173
+ }
174
+ catch { }
175
+ return true;
176
+ }
177
+ function getResumeWithinMs(config) {
178
+ // Same precedence rule as getAutoResumeEnabled: explicit config wins first.
179
+ if (config?.autoResumeWithin !== undefined) {
180
+ const raw = config.autoResumeWithin;
181
+ if (typeof raw === 'number')
182
+ return raw * 60 * 1000;
183
+ if (typeof raw === 'string') {
184
+ if (/^\d+$/.test(raw.trim()))
185
+ return parseInt(raw.trim(), 10) * 60 * 1000;
186
+ const v = parseDuration(raw);
187
+ if (v !== undefined)
188
+ return v;
189
+ }
190
+ }
191
+ const env = process.env.DSH_SUPERVISOR_RESUME_WITHIN;
192
+ if (env) {
193
+ if (/^\d+$/.test(env.trim()))
194
+ return parseInt(env.trim(), 10) * 60 * 1000;
195
+ const v = parseDuration(env);
196
+ if (v !== undefined)
197
+ return v;
198
+ }
199
+ try {
200
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
201
+ if (fs.existsSync(cfgPath)) {
202
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
203
+ const raw = cfg.autoResumeWithin;
204
+ if (typeof raw === 'string') {
205
+ if (/^\d+$/.test(raw.trim()))
206
+ return parseInt(raw.trim(), 10) * 60 * 1000;
207
+ const v = parseDuration(raw);
208
+ if (v !== undefined)
209
+ return v;
210
+ }
211
+ else if (typeof raw === 'number')
212
+ return raw * 60 * 1000;
213
+ }
214
+ const maestroPath = path.join(process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'), 'dsh-maestro-config', 'settings.json');
215
+ if (fs.existsSync(maestroPath)) {
216
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
217
+ const raw = j?.domains?.supervisor?.autoResumeWithin ?? j?.supervisor?.autoResumeWithin;
218
+ if (typeof raw === 'string') {
219
+ if (/^\d+$/.test(raw.trim()))
220
+ return parseInt(raw.trim(), 10) * 60 * 1000;
221
+ const v = parseDuration(raw);
222
+ if (v !== undefined)
223
+ return v;
224
+ }
225
+ else if (typeof raw === 'number')
226
+ return raw * 60 * 1000;
227
+ }
228
+ }
229
+ catch { }
230
+ return 5 * 60 * 1000;
231
+ }
232
+ /**
233
+ * Whether `autoResumeEnabled` is pinned by an install-supplied Cordis `config:` value.
234
+ * Used by `dsh-maestro-config`'s UI to render a locked/disabled state instead of
235
+ * an interactive toggle that has no effect.
236
+ */
237
+ export function isAutoResumePinned(config) {
238
+ return typeof config?.autoResumeEnabled === 'boolean';
239
+ }
240
+ export function getAutoResumeEnabledExported(config) {
241
+ return getAutoResumeEnabled(config);
242
+ }
243
+ export async function runAutoResume(ctx, opts = {}) {
244
+ try {
245
+ const doFind = opts.findInterrupted ?? defaultFindInterrupted;
246
+ const doFindDangling = opts.findDanglingOpenTurns ?? defaultFindDanglingOpenTurns;
247
+ const doResume = opts.resumeInterrupted ?? resumeInterrupted;
248
+ const doLog = opts.logResume ?? ((entry) => { try {
249
+ appendResumeLog(entry);
250
+ }
251
+ catch { } });
252
+ if (!getAutoResumeEnabled(opts?.config)) {
253
+ ctx.logger?.info?.('[supervisor] auto-resume disabled — skip');
254
+ doLog({ ts: Date.now(), kind: 'scan', scanned: 0, interrupted: [], detail: 'auto-resume disabled' });
255
+ return;
256
+ }
257
+ const withinMs = getResumeWithinMs(opts?.config);
258
+ const { scanned, interrupted } = await doFind(undefined, { withinMs });
259
+ // Only safe to treat a dangling open turn as crashed right after a fresh
260
+ // boot, when this process is the sole live owner of these sessions —
261
+ // exactly the context runAutoResume runs in (called once, 8s after
262
+ // apply()). resumeInterrupted()'s own "already live" check additionally
263
+ // protects any id that happens to be live in *this* process already.
264
+ let dangling = [];
265
+ try {
266
+ dangling = (await doFindDangling(undefined, { withinMs })).interrupted;
267
+ }
268
+ catch (e) {
269
+ ctx.logger?.warn?.(`[supervisor] auto-resume: dangling-open-turn scan failed, continuing with closed-turn results only: ${e?.message ?? String(e)}`);
270
+ }
271
+ const merged = Array.from(new Set([...interrupted, ...dangling]));
272
+ doLog({ ts: Date.now(), kind: 'scan', scanned, interrupted: merged, detail: `withinMs=${withinMs}` });
273
+ if (!merged.length) {
274
+ ctx.logger?.info?.(`[supervisor] auto-resume: 0/${scanned} interrupted within ${withinMs}ms — nothing to do`);
275
+ return;
276
+ }
277
+ ctx.logger?.info?.(`[supervisor] auto-resume: ${merged.length}/${scanned} interrupted within ${withinMs}ms: ${merged.slice(0, 3).join(', ')}`);
278
+ await doResume(ctx, merged, {
279
+ ...(opts?.config !== undefined ? { config: opts.config } : {}),
280
+ ...(opts.logResume !== undefined ? { logResume: opts.logResume } : {}),
281
+ });
282
+ }
283
+ catch (e) {
284
+ try {
285
+ ctx.logger?.warn?.(`[supervisor] auto-resume error: ${e?.message ?? String(e)}`);
286
+ }
287
+ catch { }
288
+ }
289
+ }
290
+ function routeFromEvents(events) {
291
+ if (!Array.isArray(events))
292
+ return undefined;
293
+ const context = [...events].reverse().find((event) => event?.type === 'request/context')?.data;
294
+ if (typeof context?.provider === 'string' && typeof context?.model === 'string') {
295
+ return { provider: context.provider, model: context.model };
296
+ }
297
+ return undefined;
298
+ }
299
+ /**
300
+ * Route recovery through the handle seam (`open(id, 'read')` + `read(0)`).
301
+ * A `read` handle never takes ownership, so this works while another handle
302
+ * or process holds `write`. Replaces the removed `persistence.load(id)`
303
+ * API (gone since DSH's handle-based persistence seam) — calling `load`
304
+ * now resolves to `undefined` and every resumed agent would lose its
305
+ * provider/model.
306
+ */
307
+ async function readRouteFromHandle(persistence, sid) {
308
+ const handle = await persistence?.open?.(sid, 'read');
309
+ if (handle === undefined || handle === null)
310
+ return undefined;
311
+ try {
312
+ return routeFromEvents(await handle.read(0));
313
+ }
314
+ finally {
315
+ try {
316
+ await handle.close?.();
317
+ }
318
+ catch { }
319
+ }
320
+ }
321
+ /**
322
+ * Raw-log fallback when the backend cannot open the session: stream the
323
+ * stored log for the first `request/context` line. `grep -m1` stops at the
324
+ * first match so huge logs cost one streamed pass, not a full decode.
325
+ */
326
+ async function readRouteFromRawLog(sessionsRoot, group, sessionId) {
327
+ const logPath = resolveSessionLogPath(path.join(sessionsRoot, group, sessionId));
328
+ if (logPath === undefined)
329
+ return undefined;
330
+ try {
331
+ if (logPath.endsWith('.zstd')) {
332
+ const { execSync } = await import('node:child_process');
333
+ const out = execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null | grep -a -m1 '"type":"request/context"'`, { encoding: 'utf-8' });
334
+ const line = out.split('\n').find((l) => l.includes('request/context'));
335
+ if (line !== undefined) {
336
+ try {
337
+ return routeFromEvents([JSON.parse(line)]);
338
+ }
339
+ catch { }
340
+ }
341
+ return undefined;
342
+ }
343
+ const content = fs.readFileSync(logPath, 'utf-8');
344
+ for (const line of content.split('\n')) {
345
+ if (!line.includes('"request/context"'))
346
+ continue;
347
+ try {
348
+ const route = routeFromEvents([JSON.parse(line)]);
349
+ if (route !== undefined)
350
+ return route;
351
+ }
352
+ catch { }
353
+ }
354
+ }
355
+ catch { }
356
+ return undefined;
357
+ }
358
+ /**
359
+ * Recover the provider/model route a resumed agent needs for its
360
+ * `{{model}}` persona variable: handle seam first, raw session log as
361
+ * fallback. Returns `undefined` only for genuinely corrupt/routeless
362
+ * sessions, which the caller skips instead of resuming.
363
+ */
364
+ export async function recoverAgentOptions(input) {
365
+ try {
366
+ const viaHandle = await readRouteFromHandle(input.persistence, input.sid);
367
+ if (viaHandle !== undefined)
368
+ return viaHandle;
369
+ }
370
+ catch (e) {
371
+ input.logger?.warn?.(`[supervisor] auto-resume: could not recover route for ${input.id}: ${e?.message ?? String(e)}`);
372
+ }
373
+ try {
374
+ return await readRouteFromRawLog(input.sessionsRoot, input.group, input.sessionId);
375
+ }
376
+ catch (e) {
377
+ input.logger?.warn?.(`[supervisor] auto-resume: could not recover route for ${input.id}: ${e?.message ?? String(e)}`);
378
+ return undefined;
379
+ }
380
+ }
381
+ /**
382
+ * Recovery prompt for a turn the crash interrupted. A bare "continue" made the
383
+ * model answer with text instead of re-issuing its tool call (36646045…,
384
+ * 31ae53a2…), so the prompt names the synthesized TOOL_OUTCOME_UNKNOWN result
385
+ * (repair.ts:104) and asks for verification before any retry.
386
+ */
387
+ export const RECOVERY_PROMPT_IDLE = 'The previous turn was interrupted by a crash and the harness has synthesized a tool result with TOOL_OUTCOME_UNKNOWN / TOOL_NOT_STARTED. ' +
388
+ 'Outcome of the last tool call is unknown — it may or may not have had side effects. ' +
389
+ 'Verify external state with bash (e.g., ls, cat, git status) before retrying. ' +
390
+ 'Retry only if the operation is read-only or idempotent; if it may have side effects, verify first or ask the user. ' +
391
+ 'Then continue the original task from where it was interrupted — re-issue the next bash/tool call that the plan requires.';
392
+ /**
393
+ * Admit a recovery prompt into a session this host already has open. The
394
+ * reconnecting browser holds that session's write handle, so `agents.resume`
395
+ * cannot take ownership (`SessionAlreadyOwnedError`); `sessionController.prompt`
396
+ * is the Host API the UI itself uses, and it resolves the session's agent
397
+ * first. Returns false when the service is absent, the prompt was refused, or
398
+ * delivery failed — the caller then reports the original ownership failure.
399
+ *
400
+ * @param ctx - plugin context providing the optional `sessionController`.
401
+ * @param sessionId - session to continue.
402
+ * @param text - recovery prompt text.
403
+ */
404
+ export async function promptOwnedSession(ctx, sessionId, text) {
405
+ // Known attribution gap, recorded rather than hidden: `sessionController.prompt`
406
+ // hardcodes `source: { kind: 'user', rpcId, clientTimeZone }` and its request
407
+ // type carries no source field, so this delivery path cannot use
408
+ // SUPERVISOR_SOURCE_KIND. It fires when the reconnecting browser holds the
409
+ // write handle — the common post-crash case — so those recovery turns still
410
+ // look human to consumers that classify a turn by source kind, including
411
+ // dsh-maestro-memory's write guard. Closing it needs a harness change (or a
412
+ // controller API that accepts a source); see the spec's follow-ups.
413
+ try {
414
+ const controller = ctx.get?.('sessionController') ?? ctx.sessionController;
415
+ if (typeof controller?.prompt !== 'function')
416
+ return false;
417
+ const timeout = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(15_000) : undefined;
418
+ const ack = await controller.prompt({
419
+ requestId: `supervisor-resume-${sessionId}-${Date.now()}`,
420
+ sessionId,
421
+ mode: 'queue',
422
+ content: [{ type: 'text', text }],
423
+ }, timeout);
424
+ return ack?.accepted === true;
425
+ }
426
+ catch {
427
+ /* a delivery failure is reported as the original ownership failure */
428
+ return false;
429
+ }
430
+ }
431
+ /** Backoff for a resume blocked by a write handle another owner still holds. */
432
+ export const DEFAULT_OWNERSHIP_RETRY_DELAYS_MS = [2000, 4000, 8000];
433
+ /** True when the persistence backend refused a second write open. */
434
+ export function isSessionAlreadyOwned(error) {
435
+ return error?.name === 'SessionAlreadyOwnedError' || /already owned by an active write handle/.test(String(error?.message ?? ''));
436
+ }
437
+ /**
438
+ * `agents.resume` while the target session's write handle may still be held by
439
+ * the just-restarted host: the reconnecting browser re-opens the interrupted
440
+ * session and keeps that handle while it loads and repairs it, so the boot
441
+ * scan's resume loses the race with
442
+ * `session "<id>" is already owned by an active write handle`. That is
443
+ * transient — on 2026-09-13 the same session accepted an agent seconds later —
444
+ * so retry a bounded number of times instead of abandoning the session.
445
+ *
446
+ * A failure that is not an ownership conflict is rethrown immediately: it
447
+ * cannot be fixed by waiting.
448
+ *
449
+ * @param agents - the agents service (`resume`).
450
+ * @param options - the resume request handed to `agents.resume`.
451
+ * @param hooks.delaysMs - backoff before each retry; length = retry count.
452
+ * @param hooks.onRetry - called before each wait, for the audit trail.
453
+ * @param hooks.sleep - injectable wait, for tests.
454
+ * @returns the agent handle from the first successful resume.
455
+ */
456
+ export async function resumeAgentWithOwnershipRetry(agents, options, hooks = {}) {
457
+ const delays = hooks.delaysMs ?? DEFAULT_OWNERSHIP_RETRY_DELAYS_MS;
458
+ const sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
459
+ let attempt = 0;
460
+ for (;;) {
461
+ try {
462
+ return await agents?.resume?.(options);
463
+ }
464
+ catch (error) {
465
+ const delayMs = isSessionAlreadyOwned(error) ? delays[attempt] : undefined;
466
+ if (delayMs === undefined)
467
+ throw error;
468
+ attempt++;
469
+ hooks.onRetry?.(attempt, delayMs, error);
470
+ await sleep(delayMs);
471
+ }
472
+ }
473
+ }
474
+ /**
475
+ * A `setup` failure: the agent could not be joined to the preset the session
476
+ * records. Distinguished from a resume/ownership failure because this one must
477
+ * never degrade into a preset-less resume.
478
+ */
479
+ export class PresetComposeError extends Error {
480
+ presetId;
481
+ cause;
482
+ /**
483
+ * @param presetId - the preset that could not be composed.
484
+ * @param cause - the roster's own failure, kept for the message.
485
+ */
486
+ constructor(presetId, cause) {
487
+ super(`agent preset "${presetId}" could not be composed: ${cause?.message ?? String(cause)}`);
488
+ this.presetId = presetId;
489
+ this.cause = cause;
490
+ this.name = 'PresetComposeError';
491
+ }
492
+ }
493
+ /**
494
+ * Activate one session's agent through the single owner of agent activation.
495
+ *
496
+ * `sessionController.resolveAgent` is the entry point the Web API domain uses:
497
+ * it composes the session's preset, de-duplicates concurrent resumes for one
498
+ * session, and returns the live agent when the browser already re-opened it.
499
+ * Anything else — the service is absent, it throws, or it answers without an
500
+ * agent — falls back to `agents.resume` with the preset-composing `setup`,
501
+ * which still owns the write-handle retry and the owned-session prompt path.
502
+ *
503
+ * @param ctx - plugin context providing the optional `sessionController`.
504
+ * @param sessionId - the session to activate.
505
+ * @param deps.resolveSessionAgent - injectable controller call, for tests.
506
+ * @returns the resolved agent when the controller produced one, else `via: 'resume'`.
507
+ */
508
+ export async function activateSessionAgent(ctx, sessionId, deps = {}) {
509
+ const resolveViaController = deps.resolveSessionAgent ?? (async (c, id) => {
510
+ const controller = c?.get?.('sessionController') ?? c?.sessionController;
511
+ if (typeof controller?.resolveAgent !== 'function')
512
+ return undefined;
513
+ return controller.resolveAgent(id);
514
+ });
515
+ try {
516
+ const resolved = await resolveViaController(ctx, sessionId);
517
+ if (resolved?.agent !== undefined)
518
+ return { agent: resolved.agent, via: 'controller' };
519
+ }
520
+ catch {
521
+ /* fall through: the resume path owns the ownership retry and prompt delivery */
522
+ }
523
+ return { via: 'resume' };
524
+ }
525
+ export async function resumeInterrupted(ctx, ids, deps = {}) {
526
+ const doReadIntent = deps.readIntent ?? readIntent;
527
+ const doConsumeIntent = deps.consumeIntent ?? consumeIntent;
528
+ const doProbe = deps.probeToolView ?? probeToolView;
529
+ const doResolveToolScope = deps.resolveToolScope ?? defaultResolveToolScope;
530
+ const doLog = deps.logResume ?? ((entry) => { try {
531
+ appendResumeLog(entry);
532
+ }
533
+ catch { } });
534
+ const coreToolPolicy = getResumeCoreToolPolicy(deps.config);
535
+ const autoRepair = deps.config?.resumeAutoRepair ?? getResumeAutoRepair(deps.config);
536
+ const doRepairPreset = deps.repairPreset ?? repairAgentPreset;
537
+ const doReadPresetId = deps.readPresetId ?? ((id) => resolveSessionPresetId(ctx, id));
538
+ const resumed = [];
539
+ /**
540
+ * Recovery prompt for one session: a session that requested the dsh web
541
+ * restart has a durable intent sidecar (written by dsh_web_restart) and is
542
+ * resumed with a contextual message instead of the generic outcome-unknown
543
+ * one; the sidecar is consumed so it cannot re-trigger later.
544
+ */
545
+ /**
546
+ * Verify that the resumed agent is actually joined to a preset, and repair it
547
+ * when it is not. This is the authoritative check: the roster answers whether
548
+ * the binding exists (`composedPreset`), which no tool count can.
549
+ *
550
+ * Repair runs before the recovery prompt is delivered, so the turn the prompt
551
+ * starts already carries the preset's tools. A repair that fails is reported
552
+ * to the operator and parked, but the prompt is still delivered: the session
553
+ * would otherwise sit silently broken.
554
+ */
555
+ const verifyResumedComposition = async (sessionId, agent) => {
556
+ try {
557
+ // Never claim a loss that cannot be verified: without the roster service
558
+ // (a host that composes no presets) or without the agent's own context,
559
+ // there is nothing to check and nothing to report.
560
+ const presets = ctx.get?.('agentPresets') ?? ctx.agentPresets;
561
+ if (typeof presets?.composedPreset !== 'function')
562
+ return;
563
+ const live = agent ?? (ctx.get?.('agents') ?? ctx.agents)?.get?.(sessionId);
564
+ if (live === undefined || live.ctx === undefined)
565
+ return;
566
+ let composed = composedPresetId(ctx, live);
567
+ let repair;
568
+ if (composed === undefined && autoRepair) {
569
+ repair = await doRepairPreset(ctx, sessionId, { readPresetId: doReadPresetId });
570
+ composed = repair.composedAfter ?? composedPresetId(ctx, live);
571
+ }
572
+ recordResumeComposition({
573
+ sessionId,
574
+ composed: composed ?? null,
575
+ repaired: repair?.repaired === true,
576
+ reason: repair?.reason ?? (composed !== undefined ? 'already-composed' : 'not-composed'),
577
+ });
578
+ if (composed === undefined) {
579
+ try {
580
+ await (deps.notify ?? notify)(`[supervisor] resumed ${sessionId}: agent is NOT joined to an agent preset (${repair?.reason ?? 'resumeAutoRepair is off'}) — its tools will be missing; reopen the session`);
581
+ }
582
+ catch { }
583
+ if (coreToolPolicy === 'park')
584
+ parkResumedSession(sessionId);
585
+ }
586
+ else if (repair?.repaired === true) {
587
+ try {
588
+ await (deps.notify ?? notify)(`[supervisor] resumed ${sessionId}: repaired the missing agent preset (${repair.presetId})`);
589
+ }
590
+ catch { }
591
+ }
592
+ }
593
+ catch { }
594
+ };
595
+ /**
596
+ * C1/C2 after a delivery: probe the resumed session's SCOPED tool view,
597
+ * journal it, and on a CORE loss notify the operator + inject the tool
598
+ * inventory message (park policy also parks the id). Shared by the followup
599
+ * and the owned-session prompt path so neither delivers unobserved.
600
+ */
601
+ const observeResumedTools = async (sessionId) => {
602
+ try {
603
+ const probeTools = ctx.get?.('tools') ?? ctx.tools;
604
+ const scope = doResolveToolScope(ctx, sessionId);
605
+ const probe = doProbe(probeTools, scope, ctx.logger);
606
+ recordResumedSession(sessionId);
607
+ if (probe.missing.length) {
608
+ await warnCoreToolLoss(ctx, sessionId, scope, probe, coreToolPolicy, {
609
+ notify: deps.notify,
610
+ injectSessionMessage: deps.injectSessionMessage,
611
+ });
612
+ }
613
+ recordResumeProbe(probe);
614
+ }
615
+ catch { }
616
+ };
617
+ const recoveryPromptFor = (sessionId) => {
618
+ try {
619
+ const intent = doReadIntent(sessionId);
620
+ if (intent) {
621
+ const intentReason = intent.reason ?? '';
622
+ return {
623
+ text: `You requested a dsh web restart${intentReason ? ` (reason: ${intentReason})` : ''} and it completed. Do NOT call dsh_web_restart again. Verify current state if needed, then continue the original task.`,
624
+ intentReason,
625
+ };
626
+ }
627
+ }
628
+ catch { }
629
+ return { text: RECOVERY_PROMPT_IDLE, intentReason: '' };
630
+ };
631
+ for (const id of ids) {
632
+ try {
633
+ const sessionId = id.split('/').pop();
634
+ const agents = ctx.get?.('agents') ?? ctx.agents;
635
+ let agent = agents?.get?.(sessionId);
636
+ if (agent === undefined) {
637
+ // The activation owner runs FIRST and needs no recovered route: it
638
+ // resolves provider/model itself while composing the session's preset.
639
+ const activation = await activateSessionAgent(ctx, sessionId, {
640
+ ...(deps.resolveSessionAgent !== undefined ? { resolveSessionAgent: deps.resolveSessionAgent } : {}),
641
+ });
642
+ if (activation.agent !== undefined) {
643
+ agent = activation.agent;
644
+ ctx.logger?.info?.(`[supervisor] auto-resume: resolved the agent for ${id} through sessionController`);
645
+ }
646
+ else {
647
+ const { SessionId } = await import('@deepseek-ai/dsh-session').catch(() => ({ SessionId: (s) => s }));
648
+ const sid = SessionId ? SessionId(sessionId) : sessionId;
649
+ const persistence = ctx.get?.('sessionPersistence') ?? ctx.sessionPersistence;
650
+ const sessionsRoot = deps.config?.sessionLogRoot ?? path.join(os.homedir(), '.dsh', 'sessions');
651
+ const group = id.slice(0, Math.max(0, id.length - sessionId.length - 1));
652
+ const agentOptions = await recoverAgentOptions({ persistence, sid, sessionsRoot, group, sessionId, logger: ctx.logger, id });
653
+ if (agentOptions === undefined) {
654
+ // Resuming without a provider/model builds an agent whose
655
+ // {{model}} persona variable has no value, so the very next turn
656
+ // fails with `prompt variable "{{model}}" has no value for this
657
+ // assembly (section "deployment:persona")`. Skip corrupt/routeless
658
+ // sessions instead of triggering a continue that can only fail.
659
+ ctx.logger?.warn?.(`[supervisor] auto-resume: skipping ${id} — no provider/model recovered (corrupt or routeless session)`);
660
+ doLog({ ts: Date.now(), sessionId, kind: 'resume-failed', error: 'missing provider/model: persistence has no request/context route — skipping corrupt/routeless session' });
661
+ continue;
662
+ }
663
+ const presetId = deps.readPresetId !== undefined
664
+ ? await deps.readPresetId(sessionId)
665
+ : await resolveSessionPresetId(ctx, sessionId);
666
+ const rawSetup = deps.makeSetup !== undefined
667
+ ? deps.makeSetup(ctx, presetId)
668
+ : (presetId === undefined ? undefined : makePresetSetup(ctx, presetId));
669
+ // Tag a compose failure so the resume catch can tell it apart from an
670
+ // ownership conflict: the former must abort the session, the latter
671
+ // retries and falls back to the owned-session prompt.
672
+ const setup = rawSetup === undefined || presetId === undefined
673
+ ? rawSetup
674
+ : async (agentCtx, agentArg) => {
675
+ try {
676
+ await rawSetup(agentCtx, agentArg);
677
+ }
678
+ catch (error) {
679
+ throw new PresetComposeError(presetId, error);
680
+ }
681
+ };
682
+ if (presetId === undefined) {
683
+ ctx.logger?.warn?.(`[supervisor] auto-resume: ${id} records no agent preset — resuming a bare agent`);
684
+ }
685
+ let handle;
686
+ try {
687
+ handle = await resumeAgentWithOwnershipRetry(agents, { resumeSessionId: sid, agentOptions, ...(setup === undefined ? {} : { setup }) }, {
688
+ ...(deps.resumeOwnershipRetryDelaysMs !== undefined ? { delaysMs: deps.resumeOwnershipRetryDelaysMs } : {}),
689
+ onRetry: (attempt, delayMs, error) => {
690
+ ctx.logger?.warn?.(`[supervisor] auto-resume: ${id} write handle is still held — retry ${attempt} in ${delayMs}ms`);
691
+ doLog({ ts: Date.now(), sessionId, kind: 'resume-retry', detail: `attempt=${attempt} delayMs=${delayMs} reason=${error?.message ?? String(error)}` });
692
+ },
693
+ });
694
+ }
695
+ catch (error) {
696
+ if (error instanceof PresetComposeError) {
697
+ // Continuing would deliver a recovery prompt into an agent whose tool
698
+ // view is the deployment-global layer — the loss this path exists to
699
+ // prevent. Abort this session and say why.
700
+ ctx.logger?.warn?.(`[supervisor] auto-resume: refusing to continue ${id} without its agent preset — ${error.message}`);
701
+ doLog({ ts: Date.now(), sessionId, kind: 'resume-failed', error: error.message });
702
+ try {
703
+ await (deps.notify ?? notify)(`[supervisor] auto-resume: ${sessionId} was NOT continued — ${error.message}`);
704
+ }
705
+ catch { }
706
+ continue;
707
+ }
708
+ if (!isSessionAlreadyOwned(error))
709
+ throw error;
710
+ // The browser already re-opened this session in the restarted host and
711
+ // holds its write handle, so no amount of waiting lets `agents.resume`
712
+ // take it. Deliver the recovery prompt through the Host API the UI uses
713
+ // instead of abandoning the session that was just interrupted.
714
+ const { text, intentReason } = recoveryPromptFor(sessionId);
715
+ if (await promptOwnedSession(ctx, sessionId, text)) {
716
+ await verifyResumedComposition(sessionId, undefined);
717
+ if (text !== RECOVERY_PROMPT_IDLE) {
718
+ try {
719
+ doConsumeIntent(sessionId);
720
+ }
721
+ catch { }
722
+ }
723
+ resumed.push(id);
724
+ await observeResumedTools(sessionId);
725
+ ctx.logger?.info?.(`[supervisor] auto-resume: delivered the recovery prompt into the open session for ${id}`);
726
+ doLog({
727
+ ts: Date.now(),
728
+ sessionId,
729
+ kind: 'resumed',
730
+ detail: text === RECOVERY_PROMPT_IDLE ? 'owned-session-prompt' : `owned-session-prompt:${intentReason.slice(0, 100)}`,
731
+ });
732
+ continue;
733
+ }
734
+ throw error;
735
+ }
736
+ agent = handle?.agent;
737
+ if (agent !== undefined)
738
+ ctx.logger?.info?.(`[supervisor] auto-resume: re-attached agent for ${id}`);
739
+ }
740
+ }
741
+ if (typeof agent?.followup !== 'function') {
742
+ ctx.logger?.warn?.(`[supervisor] auto-resume: no live agent available for ${id}`);
743
+ doLog({ ts: Date.now(), sessionId, kind: 'no-agent', detail: 'agents.resume returned no followup-capable handle' });
744
+ continue;
745
+ }
746
+ await verifyResumedComposition(sessionId, agent);
747
+ const { createUserMessage } = await import('@deepseek-ai/dsh-llm').catch(() => ({
748
+ createUserMessage: (input) => ({ ...input, role: 'user', id: crypto.randomUUID() }),
749
+ }));
750
+ const { text: resumeMessage, intentReason } = recoveryPromptFor(sessionId);
751
+ agent.followup(createUserMessage({
752
+ content: [{ type: 'text', text: resumeMessage }],
753
+ source: { kind: SUPERVISOR_SOURCE_KIND },
754
+ }));
755
+ try {
756
+ if (resumeMessage !== RECOVERY_PROMPT_IDLE)
757
+ doConsumeIntent(sessionId);
758
+ }
759
+ catch { }
760
+ resumed.push(id);
761
+ ctx.logger?.info?.(`[supervisor] auto-resume: sent recovery continue for ${id}`);
762
+ doLog({
763
+ ts: Date.now(),
764
+ sessionId,
765
+ kind: 'resumed',
766
+ detail: resumeMessage === RECOVERY_PROMPT_IDLE ? 'idle-recovery-prompt' : `restart-intent:${intentReason.slice(0, 100)}`,
767
+ });
768
+ await observeResumedTools(sessionId);
769
+ }
770
+ catch (e) {
771
+ ctx.logger?.warn?.(`[supervisor] auto-resume failed ${id}: ${e?.message ?? String(e)}`);
772
+ doLog({ ts: Date.now(), sessionId: String(id).split('/').pop() ?? String(id), kind: 'resume-failed', error: e?.message ?? String(e) });
773
+ }
774
+ }
775
+ return resumed;
776
+ }
777
+ export function createResumeRpcHandler(ctx, opts = {}) {
778
+ const resume = opts.resumeInterrupted ?? resumeInterrupted;
779
+ return async (endpoint, payload, _signal) => {
780
+ if (endpoint === 'scan') {
781
+ const withinMs = typeof payload?.withinMs === 'number'
782
+ ? payload.withinMs
783
+ : getResumeWithinMs(opts.config);
784
+ return { ok: true, value: await defaultFindInterrupted(undefined, { withinMs }) };
785
+ }
786
+ if (endpoint === 'status') {
787
+ return { ok: true, value: { autoResumeEnabled: getAutoResumeEnabled(opts.config), autoResumePinned: isAutoResumePinned(opts.config), autoResumeWithinMs: getResumeWithinMs(opts.config) } };
788
+ }
789
+ if (endpoint !== 'resume') {
790
+ return { ok: false, error: { code: 'bad-request', message: `unsupported endpoint: ${endpoint}` } };
791
+ }
792
+ const ids = Array.isArray(payload?.ids)
793
+ ? payload.ids.filter((id) => typeof id === 'string' && id.length > 0)
794
+ : [];
795
+ if (!ids.length) {
796
+ return { ok: false, error: { code: 'bad-request', message: 'resume requires at least one session id' } };
797
+ }
798
+ // Forward the resume-relevant surface (config so resumeCoreToolPolicy
799
+ // resolves, plus the C2 injectable seams). Optional keys keep the deps
800
+ // object minimal — absent opts only yields `{}`.
801
+ const resumeDeps = {
802
+ ...(opts.config !== undefined ? { config: opts.config } : {}),
803
+ ...(opts.notify !== undefined ? { notify: opts.notify } : {}),
804
+ ...(opts.injectSessionMessage !== undefined ? { injectSessionMessage: opts.injectSessionMessage } : {}),
805
+ };
806
+ return { ok: true, value: { resumed: await resume(ctx, ids, resumeDeps) } };
807
+ };
808
+ }
809
+ /**
810
+ * Session-log root resolution shared with the safe-restart pre-flight script
811
+ * (skills/dsh-safe-restart/scripts/restart-dsh-web.sh): SESSIONS_ROOT wins,
812
+ * else DSH_HOME/sessions, else ~/.dsh/sessions. Kept in lockstep with the
813
+ * shell derivation so the RPC/tool and the pre-flight always scan the same
814
+ * store.
815
+ */
816
+ function defaultSessionsRoot() {
817
+ if (typeof process.env.SESSIONS_ROOT === 'string' && process.env.SESSIONS_ROOT)
818
+ return process.env.SESSIONS_ROOT;
819
+ return path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'sessions');
820
+ }
821
+ /** Extract a non-empty payload.root, else the resolved default session root. */
822
+ function resolveHealthRoot(payload, config) {
823
+ const root = payload?.root;
824
+ if (typeof root === 'string' && root)
825
+ return root;
826
+ return config?.sessionLogRoot ?? defaultSessionsRoot();
827
+ }
828
+ /**
829
+ * Loopback RPC handler for /dsh-maestro-supervisor-session-health. Runs the
830
+ * A1 session-log health check over the resolved root with repair on and
831
+ * quarantine off (mirrors the safe-restart pre-flight — single-frame logs get
832
+ * re-encoded, corrupt logs stay in place and are only counted). Same
833
+ * `{ ok, value | error }` envelope shape as the resume handler.
834
+ */
835
+ export function createSessionHealthRpcHandler(ctx, deps = {}) {
836
+ const run = deps.run ?? runSessionHealthCheck;
837
+ const config = deps.config ?? ctx.config;
838
+ return async (_endpoint, payload, _signal) => {
839
+ try {
840
+ return { ok: true, value: await run(resolveHealthRoot(payload, config), { repair: true, quarantine: false }) };
841
+ }
842
+ catch (e) {
843
+ return { ok: false, error: { code: 'session-health-failed', message: e?.message ?? String(e) } };
844
+ }
845
+ };
846
+ }
847
+ /** dsh.tools definition for the maestro_session_health host tool. */
848
+ function makeSessionHealthToolDef(config) {
849
+ return {
850
+ name: 'maestro_session_health',
851
+ description: 'Scan session logs under the operator DSH home sessions dir and report unhealthy shapes (single-frame whole logs, corrupt first frames). ' +
852
+ 'Single-frame logs are re-encoded into the canonical multi-frame form (with a backup); corrupt logs are only counted unless quarantine is enabled. ' +
853
+ 'Safe to run before or after a dsh web restart.',
854
+ parameters: {
855
+ type: 'object',
856
+ properties: {
857
+ root: { type: 'string', description: 'Session-log root to scan; defaults to the configured/operator DSH home sessions dir' },
858
+ repair: { type: 'boolean', description: 'Re-encode single-frame whole logs into canonical multi-frame form (default true)' },
859
+ quarantine: { type: 'boolean', description: 'Move corrupt-first-frame logs aside instead of leaving them in place (default false)' },
860
+ },
861
+ additionalProperties: false,
862
+ },
863
+ output: {
864
+ schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, counts: { type: 'object' } } },
865
+ render: (_args, value) => [{ type: 'text', text: `fixed=${value?.counts?.fixed ?? 0} quarantined=${value?.counts?.quarantined ?? 0} remaining=${value?.counts?.remaining ?? 0}` }],
866
+ },
867
+ execute: async (args) => {
868
+ const counts = await runSessionHealthCheck(resolveHealthRoot(args, config), {
869
+ repair: args?.repair !== false,
870
+ quarantine: args?.quarantine === true,
871
+ });
872
+ return { ok: true, counts };
873
+ },
874
+ };
875
+ }
876
+ /**
877
+ * Register the session-health RPC handle and the
878
+ * maestro_session_health host tool. Fail-safe like the other registrations:
879
+ * any registration error is logged, never thrown, and the returned disposer
880
+ * unregisters everything that did succeed.
881
+ */
882
+ export function registerSessionHealthService(ctx, config = {}) {
883
+ const disposers = [];
884
+ try {
885
+ const conn = ctx.connection ?? ctx.get?.('connection');
886
+ if (conn?.rpc?.handle) {
887
+ disposers.push(conn.rpc.handle('/dsh-maestro-supervisor-session-health', createSessionHealthRpcHandler(ctx, { config })));
888
+ }
889
+ }
890
+ catch (e) {
891
+ try {
892
+ ctx.logger?.warn?.(`[supervisor] session-health RPC registration failed: ${e?.message ?? String(e)}`);
893
+ }
894
+ catch { }
895
+ }
896
+ try {
897
+ if (typeof ctx.tools?.register === 'function') {
898
+ disposers.push(ctx.tools.register(makeSessionHealthToolDef(config)));
899
+ }
900
+ }
901
+ catch (e) {
902
+ try {
903
+ ctx.logger?.warn?.(`[supervisor] session-health tool registration failed: ${e?.message ?? String(e)}`);
904
+ }
905
+ catch { }
906
+ }
907
+ return () => { for (const d of disposers) {
908
+ try {
909
+ d();
910
+ }
911
+ catch { }
912
+ } };
913
+ }
914
+ /** Resolve the package-root skills/ dir regardless of module layout. The built
915
+ * host lib is flat (lib/plugin.js → ../skills), but under vitest the same
916
+ * module loads from src/host/ (→ ../../skills). Walking to the nearest
917
+ * package.json yields the same package-root skills/ in both layouts. */
918
+ function resolveSkillsDir(fromDir) {
919
+ let dir = fromDir;
920
+ for (let i = 0; i < 6; i++) {
921
+ try {
922
+ if (fs.existsSync(path.join(dir, 'package.json')))
923
+ return path.join(dir, 'skills');
924
+ }
925
+ catch { }
926
+ const parent = path.dirname(dir);
927
+ if (parent === dir)
928
+ break;
929
+ dir = parent;
930
+ }
931
+ return path.join(fromDir, '..', 'skills');
932
+ }
933
+ function ensureSystemdKeepalive(ctx) {
934
+ // Best-effort: ensure dsh-web-keepalive.service exists and is enabled, and linger is on.
935
+ // This is the user-level auto-fix for the 11:42:58 crash where manager session 97
936
+ // Removed caused user manager to exit despite Linger, killing dsh-web.
937
+ // Runs inside dsh web (as the current user) so systemctl --user bus is available when manager is alive.
938
+ // Failures are swallowed — never throw from apply().
939
+ try {
940
+ const home = os.homedir();
941
+ const systemdDir = path.join(home, '.config/systemd/user');
942
+ const keepalivePath = path.join(systemdDir, 'dsh-web-keepalive.service');
943
+ // Migrate old keepalive.service (pre-prefix) if present
944
+ const oldKeepalivePath = path.join(systemdDir, 'keepalive.service');
945
+ if (fs.existsSync(oldKeepalivePath) && !fs.existsSync(keepalivePath)) {
946
+ try {
947
+ fs.renameSync(oldKeepalivePath, keepalivePath);
948
+ ctx.logger?.info?.('[supervisor] migrated keepalive.service → dsh-web-keepalive.service');
949
+ }
950
+ catch {
951
+ try {
952
+ fs.copyFileSync(oldKeepalivePath, keepalivePath);
953
+ }
954
+ catch { }
955
+ }
956
+ }
957
+ if (!fs.existsSync(keepalivePath)) {
958
+ try {
959
+ fs.mkdirSync(systemdDir, { recursive: true });
960
+ // Inline template — avoids needing to resolve package's systemd/dsh-web-keepalive.service.template at runtime
961
+ const content = `[Unit]\nDescription=Keepalive for user manager linger — prevents systemd --user exit on manager session close\nAfter=default.target\n\n[Service]\nType=simple\nExecStart=/bin/sleep infinity\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n`;
962
+ fs.writeFileSync(keepalivePath, content, 'utf-8');
963
+ ctx.logger?.info?.('[supervisor] dsh-web-keepalive.service installed');
964
+ }
965
+ catch (e) {
966
+ ctx.logger?.warn?.(`[supervisor] keepalive install failed: ${e?.message ?? String(e)}`);
967
+ return;
968
+ }
969
+ }
970
+ // Try to enable linger + enable/start units best-effort (may need sudo for linger, ignore failure)
971
+ try {
972
+ const { execSync } = require('node:child_process');
973
+ const username = (() => { try {
974
+ return os.userInfo().username;
975
+ }
976
+ catch {
977
+ return process.env.USER || process.env.LOGNAME || '';
978
+ } })();
979
+ const lingerPath = username ? `/var/lib/systemd/linger/${username}` : '';
980
+ if (lingerPath && !fs.existsSync(lingerPath)) {
981
+ try {
982
+ execSync(`loginctl enable-linger ${username} 2>/dev/null || true`, { timeout: 3000, stdio: 'ignore' });
983
+ }
984
+ catch { }
985
+ }
986
+ try {
987
+ execSync('systemctl --user daemon-reload 2>/dev/null || true', { timeout: 3000, stdio: 'ignore' });
988
+ }
989
+ catch { }
990
+ try {
991
+ execSync('systemctl --user enable dsh-web-keepalive.service 2>/dev/null || true', { timeout: 3000, stdio: 'ignore' });
992
+ }
993
+ catch { }
994
+ try {
995
+ execSync('systemctl --user start dsh-web-keepalive.service 2>/dev/null || true', { timeout: 3000, stdio: 'ignore' });
996
+ }
997
+ catch { }
998
+ // Also ensure dsh-web + supervisor are enabled (in case user installed plugin but never ran install-systemd.sh)
999
+ try {
1000
+ execSync('systemctl --user enable dsh-web.service dsh-web-supervisor.service 2>/dev/null || true', { timeout: 3000, stdio: 'ignore' });
1001
+ }
1002
+ catch { }
1003
+ }
1004
+ catch { }
1005
+ }
1006
+ catch { }
1007
+ }
1008
+ export function apply(ctx, config = {}) {
1009
+ // The whole body is wrapped: per AGENTS.md, apply() must never throw
1010
+ // synchronously or let a rejected promise escape, no matter what fails
1011
+ // (ctx.effect missing/throwing, RPC registration throwing, or even the
1012
+ // error-reporting logger call itself throwing).
1013
+ try {
1014
+ try {
1015
+ ensureSystemdKeepalive(ctx);
1016
+ }
1017
+ catch { }
1018
+ try {
1019
+ const skills = ctx.get?.('skills');
1020
+ if (skills?.registerProvider) {
1021
+ ctx.effect(() => {
1022
+ let unregister;
1023
+ try {
1024
+ // Package-root skills/ is resolved at runtime by walking to the
1025
+ // nearest package.json (robust to lib/ vs src/host/ layouts).
1026
+ unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)));
1027
+ }
1028
+ catch (e) {
1029
+ ctx.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`);
1030
+ }
1031
+ return () => { try {
1032
+ unregister?.();
1033
+ }
1034
+ catch { } };
1035
+ }, 'supervisor:skill');
1036
+ }
1037
+ }
1038
+ catch { }
1039
+ try {
1040
+ ctx.effect(() => registerRestartTool(ctx), 'supervisor:restart-tool');
1041
+ }
1042
+ catch (e) {
1043
+ try {
1044
+ ctx.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`);
1045
+ }
1046
+ catch { }
1047
+ }
1048
+ try {
1049
+ ctx.effect(() => registerSessionHealthService(ctx, config), 'supervisor:session-health');
1050
+ }
1051
+ catch (e) {
1052
+ try {
1053
+ ctx.logger?.warn?.(`[supervisor] session-health effect failed: ${e?.message ?? String(e)}`);
1054
+ }
1055
+ catch { }
1056
+ }
1057
+ try {
1058
+ ctx.effect(() => registerResumeToolHealthService(ctx), 'supervisor:resume-tool-health');
1059
+ }
1060
+ catch (e) {
1061
+ try {
1062
+ ctx.logger?.warn?.(`[supervisor] resume-tool-health effect failed: ${e?.message ?? String(e)}`);
1063
+ }
1064
+ catch { }
1065
+ }
1066
+ ctx.effect(() => {
1067
+ let disposed = false;
1068
+ let timer = null;
1069
+ timer = setTimeout(() => {
1070
+ if (disposed)
1071
+ return;
1072
+ runAutoResume(ctx, { config }).catch(() => {
1073
+ // runAutoResume already never rejects, but guard the .catch itself is a no-op safety net
1074
+ });
1075
+ }, 8000);
1076
+ let disposeRpc;
1077
+ try {
1078
+ const conn = ctx.connection ?? ctx.get?.('connection');
1079
+ if (conn?.rpc?.handle) {
1080
+ disposeRpc = conn.rpc.handle('/dsh-maestro-supervisor-resume', createResumeRpcHandler(ctx, { config }));
1081
+ }
1082
+ }
1083
+ catch (e) {
1084
+ try {
1085
+ ctx.logger?.warn?.(`[supervisor] auto-resume RPC registration failed: ${e?.message ?? String(e)}`);
1086
+ }
1087
+ catch { }
1088
+ }
1089
+ return () => {
1090
+ disposed = true;
1091
+ if (timer)
1092
+ clearTimeout(timer);
1093
+ if (disposeRpc) {
1094
+ try {
1095
+ disposeRpc();
1096
+ }
1097
+ catch { }
1098
+ }
1099
+ };
1100
+ }, 'supervisor:auto-resume');
1101
+ try {
1102
+ // Deny bash/shell self-kill commands in-tree; the safe restart path is
1103
+ // dsh_web_restart (supervisor daemon owns the actual restart).
1104
+ const guard = makePreExecuteGuard();
1105
+ ctx.effect(() => {
1106
+ const un = ctx.on?.('tools/pre-execute', guard) ?? null;
1107
+ return () => { try {
1108
+ un?.();
1109
+ }
1110
+ catch { } };
1111
+ }, 'supervisor:self-kill-guard');
1112
+ }
1113
+ catch (e) {
1114
+ try {
1115
+ ctx.logger?.warn?.(`[supervisor] self-kill guard effect failed: ${e?.message ?? String(e)}`);
1116
+ }
1117
+ catch { }
1118
+ }
1119
+ }
1120
+ catch (e) {
1121
+ try {
1122
+ ctx.logger?.warn?.(`[supervisor] auto-resume apply() failed: ${e?.message ?? String(e)}`);
1123
+ }
1124
+ catch { }
1125
+ }
1126
+ }