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