@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,385 @@
1
+ /**
2
+ * C2 — deterministic plugin-layer mitigation for resumed sessions that lose
3
+ * core tools after a dsh web restart (`Error: unknown tool "bash"`).
4
+ *
5
+ * The supervisor cannot edit the harness tool layer (hard workspace rule) and
6
+ * the exact layer-rebuild root cause is only observable on the live system
7
+ * (Part D). So when the post-resume probe (C1) reports a core tool missing
8
+ * from the resumed session's SCOPED view, this module runs a host-side
9
+ * mitigation:
10
+ *
11
+ * 1. a short notifier line so the operator sees the loss immediately;
12
+ * 2. a "System:"-prefixed inventory user-message injected into the session
13
+ * (same createUserMessage/followup pattern as the resume-intent message),
14
+ * so the model stops calling the lost tool and uses what remains;
15
+ * 3. optionally (resumeCoreToolPolicy: 'park') records the session id in a
16
+ * module-level parked set exposed through the `maestro_resume_tool_health`
17
+ * host tool + loopback RPC, marking it for manual reopen.
18
+ *
19
+ * The module-level state (`parkedCoreToolLossIds`, `lastResumeProbe`,
20
+ * `resumedSessions`) is per-`dsh web`-process: a host restart clears it, which
21
+ * is exactly right — these are per-boot facts.
22
+ */
23
+
24
+ import { notify } from './notifier.js'
25
+ import { repairAgentPreset, type RepairOutcome } from './preset.js'
26
+ import { SUPERVISOR_SOURCE_KIND } from './source.js'
27
+ import {
28
+ probeToolView,
29
+ defaultResolveToolScope,
30
+ CRITICAL_TOOLS,
31
+ type ToolViewProbe,
32
+ type ToolViewProbeFn,
33
+ type ToolScopeResolver,
34
+ type ToolsLike,
35
+ type ResumeCoreToolPolicy,
36
+ } from './plugin.js'
37
+
38
+ // --- module-level mitigation state ---------------------------------------------
39
+
40
+ let lastResumeProbe: ToolViewProbe | null = null
41
+ let lastComposition: ResumeComposition | null = null
42
+ const parkedCoreToolLossIds = new Set<string>()
43
+ const resumedSessions = new Set<string>()
44
+
45
+ /** Reset the per-process mitigation state — tests + fresh boot reuse. */
46
+ export function resetResumeToolHealthState(): void {
47
+ lastResumeProbe = null
48
+ lastComposition = null
49
+ parkedCoreToolLossIds.clear()
50
+ resumedSessions.clear()
51
+ }
52
+
53
+ /**
54
+ * The composition outcome of the most recent resumed session. A host with a
55
+ * preset-less agent is the one an operator must act on, so this is reported
56
+ * beside the tool view rather than only journalled.
57
+ */
58
+ export interface ResumeComposition {
59
+ sessionId: string
60
+ /** The preset the agent is joined to after verification, or null when it is joined to none. */
61
+ composed: string | null
62
+ /** Whether the resume path had to re-link the agent to its preset. */
63
+ repaired: boolean
64
+ /** Repair classification: `already-composed`, `repaired`, `no-preset-recorded`, … */
65
+ reason: string
66
+ }
67
+
68
+ /** Record the composition outcome of one resumed session. */
69
+ export function recordResumeComposition(composition: ResumeComposition): void {
70
+ lastComposition = composition
71
+ }
72
+
73
+ /** Park a session for manual reopen — the operator must reopen it fresh. */
74
+ export function parkResumedSession(sessionId: string): void {
75
+ parkedCoreToolLossIds.add(sessionId)
76
+ }
77
+
78
+ /** Record a session the auto-resume confirmed as resumed (on-demand probe target). */
79
+ export function recordResumedSession(sessionId: string): void {
80
+ resumedSessions.add(sessionId)
81
+ }
82
+
83
+ /** Record the last REAL post-resume tool-view observation ({ missing, visible }). */
84
+ export function recordResumeProbe(probe: ToolViewProbe): void {
85
+ lastResumeProbe = probe
86
+ }
87
+
88
+ // --- message builders -----------------------------------------------------------
89
+
90
+ /**
91
+ * Operator-facing notify line. The park variant appends the manual-reopen
92
+ * marker so the operator knows the session was NOT auto-continued for tools.
93
+ */
94
+ export function buildCoreToolLossNotifyLine(sessionId: string, missing: string[], policy: ResumeCoreToolPolicy): string {
95
+ const base = `[supervisor] resumed ${sessionId}: core tool lost [${missing.join(',')}] — tool view incomplete; reopen session if it persists`
96
+ return policy === 'park' ? `${base} (manual reopen required)` : base
97
+ }
98
+
99
+ /**
100
+ * The SYSTEM message injected into the resumed session. Tells the model the
101
+ * CURRENT inventory (scoped `schemas()` — the tools the session can actually
102
+ * call) so it stops issuing the lost tool instead of looping on unknown-tool
103
+ * errors. Names joined with ', '.
104
+ */
105
+ export function buildToolInventoryMessage(missing: string[], available: string[]): string {
106
+ const names = missing.join(', ')
107
+ const verb = missing.length === 1 ? 'tool is' : 'tools are'
108
+ return `System: the ${names} ${verb} unavailable in this session's restored tool view. Available tools: ${available.join(', ')}. Do not call ${names}; use the available tools.`
109
+ }
110
+
111
+ /** Scoped schemas() = exactly what the session can still call; never the global view. */
112
+ function resolveAvailableToolNames(tools: ToolsLike | undefined, scope: unknown): string[] {
113
+ try {
114
+ const schemas = typeof tools?.schemas === 'function' ? tools.schemas : undefined
115
+ if (!schemas) return []
116
+ const list = schemas(scope)
117
+ if (!Array.isArray(list)) return []
118
+ return list.map((t) => (t && typeof t.name === 'string' ? t.name : '')).filter((n) => n.length > 0)
119
+ } catch {
120
+ return []
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Default session-message injection: mirrors the resume-intent push in
126
+ * plugin.ts `resumeInterrupted` — `createUserMessage` (dynamic import so the
127
+ * plugin loads without the LLM package ever installed) + `agent.followup`.
128
+ * Never throws; a missing agent just no-ops.
129
+ */
130
+ function makeDefaultSessionMessageInjector(ctx: any): (sessionId: string, content: string) => unknown {
131
+ return async (sessionId: string, content: string) => {
132
+ try {
133
+ const agents = (ctx.get?.('agents') as any) ?? (ctx as any).agents
134
+ const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined
135
+ if (typeof agent?.followup !== 'function') return
136
+ const { createUserMessage } = await import('@deepseek-ai/dsh-llm' as any).catch(() => ({
137
+ createUserMessage: (input: any) => ({ ...input, role: 'user', id: crypto.randomUUID() }),
138
+ }))
139
+ agent.followup(createUserMessage({
140
+ content: [{ type: 'text', text: content }],
141
+ source: { kind: SUPERVISOR_SOURCE_KIND },
142
+ }))
143
+ } catch {}
144
+ }
145
+ }
146
+
147
+ export interface WarnCoreToolLossDeps {
148
+ /** Loose notifier — default wires to the package notifier (swallows errors). */
149
+ notify?: (line: string) => Promise<void>
150
+ /** Push a message into the resumed session — default follows the createUserMessage / followup pattern. */
151
+ injectSessionMessage?: (sessionId: string, content: string) => unknown
152
+ /** Tool registry whose SCOPED schemas() yields the available-tool inventory. Defaults to ctx.tools. */
153
+ tools?: ToolsLike
154
+ }
155
+
156
+ /**
157
+ * C2 mitigation entry: called by the resume flow when the post-resume probe
158
+ * found a core tool missing. Notifies, injects the inventory message, and —
159
+ * under 'park' policy — records the session id. Only fires on an actual
160
+ * CRITICAL_TOOLS loss; a non-core missing name (e.g. cordis_inspect_query)
161
+ * is a no-op. All seams are injectable for tests; every step is defensive.
162
+ */
163
+ export async function warnCoreToolLoss(
164
+ ctx: any,
165
+ sessionId: string,
166
+ scope: unknown,
167
+ probe: ToolViewProbe,
168
+ policy: ResumeCoreToolPolicy,
169
+ opts: WarnCoreToolLossDeps = {},
170
+ ): Promise<void> {
171
+ const lostCore = probe.missing.filter((n) => (CRITICAL_TOOLS as readonly string[]).includes(n))
172
+ if (!lostCore.length) return
173
+ const doNotify = opts.notify ?? ((line: string) => notify(line))
174
+ try {
175
+ await doNotify(buildCoreToolLossNotifyLine(sessionId, lostCore, policy))
176
+ } catch {}
177
+ try {
178
+ const tools = opts.tools ?? ((ctx.get?.('tools') as any) ?? (ctx as any).tools)
179
+ const doInject = opts.injectSessionMessage ?? makeDefaultSessionMessageInjector(ctx)
180
+ await doInject(sessionId, buildToolInventoryMessage(lostCore, resolveAvailableToolNames(tools, scope)))
181
+ } catch {}
182
+ if (policy === 'park') parkedCoreToolLossIds.add(sessionId)
183
+ }
184
+
185
+ // --- maestro_resume_tool_health: snapshot + on-demand probe ----------------------
186
+
187
+ export interface ResumeToolHealthSnapshot {
188
+ lastResumeProbe: ToolViewProbe | null
189
+ lastComposition: ResumeComposition | null
190
+ parked: string[]
191
+ }
192
+
193
+ function mergeResumeProbes(base: ToolViewProbe | null, next: ToolViewProbe): ToolViewProbe {
194
+ if (!base) return next
195
+ return {
196
+ missing: Array.from(new Set([...base.missing, ...next.missing])),
197
+ visible: base.visible + next.visible,
198
+ registry: base.registry === 'reachable' && next.registry === 'reachable' ? 'reachable' : 'unreachable',
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Build the RPC value. When the tool registry is reachable AND at least one
204
+ * current resumed session still lives, re-probes each session's SCOPED view
205
+ * on demand and records the aggregate as the freshest `lastResumeProbe`;
206
+ * otherwise returns the stored last observation unchanged ('tool registry
207
+ * unreachable -> lastResumeProbe' contract). Session ids whose agent is gone
208
+ * are skipped (they are no longer "current resumed sessions").
209
+ */
210
+ export function snapshotResumeToolHealth(
211
+ ctx: any,
212
+ deps: { probeToolView?: ToolViewProbeFn; resolveToolScope?: ToolScopeResolver } = {},
213
+ ): ResumeToolHealthSnapshot {
214
+ const doProbe = deps.probeToolView ?? probeToolView
215
+ const doResolve = deps.resolveToolScope ?? defaultResolveToolScope
216
+ const tools = (ctx.get?.('tools') as any) ?? (ctx as any).tools
217
+ let reachable = false
218
+ let aggregated: ToolViewProbe | null = null
219
+ for (const id of resumedSessions) {
220
+ try {
221
+ const agents = (ctx.get?.('agents') as any) ?? (ctx as any).agents
222
+ if (typeof agents?.get === 'function' && agents.get(id) === undefined) continue
223
+ aggregated = mergeResumeProbes(aggregated, doProbe(tools, doResolve(ctx, id)))
224
+ reachable = true
225
+ } catch {}
226
+ }
227
+ if (reachable && aggregated) lastResumeProbe = aggregated
228
+ return { lastResumeProbe, lastComposition, parked: [...parkedCoreToolLossIds] }
229
+ }
230
+
231
+ /**
232
+ * Loopback RPC handler for /dsh-maestro-supervisor-resume-tool-health.
233
+ * Same `{ ok, value | error }` envelope shape as the other supervisor RPCs.
234
+ */
235
+ export function createResumeToolHealthRpcHandler(
236
+ ctx: any,
237
+ deps: { probeToolView?: ToolViewProbeFn; resolveToolScope?: ToolScopeResolver } = {},
238
+ ) {
239
+ return async (_endpoint: string, _payload: unknown, _signal: AbortSignal) => {
240
+ try {
241
+ return { ok: true, value: snapshotResumeToolHealth(ctx, deps) }
242
+ } catch (e: any) {
243
+ return { ok: false, error: { code: 'resume-tool-health-failed', message: e?.message ?? String(e) } }
244
+ }
245
+ }
246
+ }
247
+
248
+ /** dsh.tools definition for the maestro_resume_tool_health host tool. */
249
+ export function makeResumeToolHealthToolDef(ctx: any): any {
250
+ return {
251
+ name: 'maestro_resume_tool_health',
252
+ description:
253
+ 'Report the tool-view health of sessions auto-resumed after a dsh web restart. ' +
254
+ 'Returns the last post-resume probe (missing core tools, visible count) plus the sessions ' +
255
+ 'parked for manual reopen under resumeCoreToolPolicy: park. The probe is refreshed on demand ' +
256
+ 'against the currently resumed sessions when the tool registry is reachable.',
257
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
258
+ output: {
259
+ schema: {
260
+ type: 'object',
261
+ additionalProperties: true,
262
+ properties: {
263
+ // Null until the first probe of this process (a fresh boot has none),
264
+ // which the validator accepts only as a oneOf branch — it rejects
265
+ // `type` arrays and refuses `type` beside `oneOf`.
266
+ lastResumeProbe: {
267
+ oneOf: [
268
+ {
269
+ type: 'object',
270
+ properties: {
271
+ missing: { type: 'array', items: { type: 'string' } },
272
+ visible: { type: 'number' },
273
+ },
274
+ },
275
+ { type: 'null' },
276
+ ],
277
+ },
278
+ parked: { type: 'array', items: { type: 'string' } },
279
+ },
280
+ },
281
+ render: (_args: any, value: any) => {
282
+ const probe = value?.lastResumeProbe
283
+ const missing = Array.isArray(probe?.missing) && probe.missing.length ? probe.missing.join(',') : 'none'
284
+ const visible = typeof probe?.visible === 'number' ? probe.visible : 'n/a'
285
+ const registry = typeof probe?.registry === 'string' ? probe.registry : 'n/a'
286
+ const composition = value?.lastComposition
287
+ const composed = composition === null || composition === undefined ? 'unknown' : (composition.composed ?? 'none')
288
+ const repaired = composition?.repaired === true ? 'yes' : 'no'
289
+ return [{
290
+ type: 'text',
291
+ text: `missing=${missing} visible=${visible} registry=${registry} composed=${composed} repaired=${repaired} parked=${Array.isArray(value?.parked) ? value.parked.length : 0}`,
292
+ }]
293
+ },
294
+ },
295
+ execute: async () => snapshotResumeToolHealth(ctx),
296
+ }
297
+ }
298
+
299
+ /**
300
+ * dsh.tools definition for the `maestro_repair_session_preset` host tool.
301
+ *
302
+ * The resume path repairs automatically; this tool is the operator's manual
303
+ * handle on the same capability: an agent that already lost its preset (a
304
+ * session resumed before this fix existed, for example) can be re-linked without
305
+ * waiting for the next restart.
306
+ * @param ctx - plugin context providing `agents`, `agentPresets` and the session readers.
307
+ * @returns the tool definition handed to `ctx.tools.register`.
308
+ */
309
+ export function makeRepairPresetToolDef(ctx: any): any {
310
+ return {
311
+ name: 'maestro_repair_session_preset',
312
+ description:
313
+ "Re-link one live session's agent to the agent preset it records. Use when a resumed session lost its " +
314
+ 'tools (every preset tool answers UNKNOWN_TOOL): the agent was published without joining a preset, and ' +
315
+ 'recompose restores the full tool set for its next request. Reports whether the agent was repaired, ' +
316
+ 'already composed, or could not be (no recorded preset, no live agent, recompose failed).',
317
+ parameters: {
318
+ type: 'object',
319
+ properties: {
320
+ sessionId: { type: 'string', description: 'The session whose live agent should be re-linked to its preset.' },
321
+ },
322
+ required: ['sessionId'],
323
+ additionalProperties: false,
324
+ },
325
+ output: {
326
+ schema: {
327
+ type: 'object',
328
+ additionalProperties: true,
329
+ properties: {
330
+ repaired: { type: 'boolean' },
331
+ presetId: { type: 'string' },
332
+ reason: { type: 'string' },
333
+ composedAfter: { type: 'string' },
334
+ },
335
+ },
336
+ render: (_args: any, value: any) =>
337
+ [{
338
+ type: 'text',
339
+ text: `repaired=${value?.repaired === true ? 'yes' : 'no'} reason=${value?.reason ?? 'unknown'} preset=${value?.presetId ?? 'none'}`,
340
+ }],
341
+ },
342
+ execute: async (args: any): Promise<RepairOutcome & { ok: boolean }> => {
343
+ const sessionId = typeof args?.sessionId === 'string' ? args.sessionId : ''
344
+ if (!sessionId) return { ok: false, repaired: false, reason: 'no-preset-recorded' }
345
+ const outcome = await repairAgentPreset(ctx, sessionId)
346
+ return { ok: true, ...outcome }
347
+ },
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Register the resume-tool-health RPC handle and the
353
+ * maestro_resume_tool_health host tool. Fail-safe like the other
354
+ * registrations: any registration error is logged, never thrown, and the
355
+ * returned disposer unregisters everything that did succeed.
356
+ */
357
+ export function registerResumeToolHealthService(ctx: any): () => void {
358
+ const disposers: (() => void)[] = []
359
+ try {
360
+ const conn = ctx.connection ?? ctx.get?.('connection')
361
+ if (conn?.rpc?.handle) {
362
+ disposers.push(conn.rpc.handle(
363
+ '/dsh-maestro-supervisor-resume-tool-health',
364
+ createResumeToolHealthRpcHandler(ctx),
365
+ ))
366
+ }
367
+ } catch (e: any) {
368
+ try { ctx.logger?.warn?.(`[supervisor] resume-tool-health RPC registration failed: ${e?.message ?? String(e)}`) } catch {}
369
+ }
370
+ try {
371
+ if (typeof ctx.tools?.register === 'function') {
372
+ disposers.push(ctx.tools.register(makeResumeToolHealthToolDef(ctx)))
373
+ }
374
+ } catch (e: any) {
375
+ try { ctx.logger?.warn?.(`[supervisor] resume-tool-health tool registration failed: ${e?.message ?? String(e)}`) } catch {}
376
+ }
377
+ try {
378
+ if (typeof ctx.tools?.register === 'function') {
379
+ disposers.push(ctx.tools.register(makeRepairPresetToolDef(ctx)))
380
+ }
381
+ } catch (e: any) {
382
+ try { ctx.logger?.warn?.(`[supervisor] repair-preset tool registration failed: ${e?.message ?? String(e)}`) } catch {}
383
+ }
384
+ return () => { for (const d of disposers) { try { d() } catch {} } }
385
+ }
@@ -0,0 +1,204 @@
1
+ import * as fs from 'node:fs'
2
+ import * as path from 'node:path'
3
+ import * as os from 'node:os'
4
+ import { resolveSessionLogPath } from './session-log-file.js'
5
+
6
+ export interface ResumeResult {
7
+ scanned: number
8
+ interrupted: string[]
9
+ }
10
+
11
+ export interface FindInterruptedOpts {
12
+ withinMs?: number // only sessions interrupted within this window from now
13
+ sinceMs?: number // or since this absolute epoch ms
14
+ }
15
+
16
+ /**
17
+ * Resolve the readable session log inside one session directory. Owned by
18
+ * `session-log-file.ts` — the single owner of "which file is the log":
19
+ * generations are discovered, never listed, because enumerating them went
20
+ * blind twice (v3 on 2026-09-11, v4 on 2026-09-23). Re-exported here because
21
+ * `plugin.ts` and `preset.ts` already import it from this module.
22
+ */
23
+ export { resolveSessionLogPath }
24
+
25
+ /**
26
+ * Read the last ~100 lines of one session's raw log, applying the mtime
27
+ * pre-filter before any (potentially expensive) zstd decompression: a
28
+ * session log's mtime only advances when something is appended to it, so a
29
+ * file older than `sinceMs` cannot contain anything within the window.
30
+ * Shared by every raw-log scan below so the pre-filter (Critical: this
31
+ * scan previously blocked the host event loop ~5.5s across 412 sessions on
32
+ * a real machine before this filter existed) can't be accidentally
33
+ * bypassed by a future scan variant.
34
+ * @returns `undefined` when the session has no log file, or is filtered
35
+ * out by `sinceMs` — callers must treat that the same as "nothing found".
36
+ */
37
+ async function readSessionTailLines(logPath: string | undefined, sinceMs: number | undefined): Promise<string[] | undefined> {
38
+ if (logPath === undefined) return undefined
39
+ if (sinceMs !== undefined) {
40
+ try {
41
+ if (fs.statSync(logPath).mtimeMs < sinceMs) return undefined
42
+ } catch {}
43
+ }
44
+ if (logPath.endsWith('.zstd')) {
45
+ const { execSync } = await import('node:child_process')
46
+ const out = execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null | tail -100`, { encoding: 'utf-8' })
47
+ return out.split('\n').filter(Boolean)
48
+ }
49
+ try {
50
+ const content = fs.readFileSync(logPath, 'utf-8')
51
+ return content.trim().split('\n').slice(-100)
52
+ } catch {}
53
+ return undefined
54
+ }
55
+
56
+ export async function findInterrupted(dshHome?: string, opts?: FindInterruptedOpts): Promise<ResumeResult> {
57
+ const home = dshHome ?? path.join(os.homedir(), '.dsh')
58
+ const sessionsRoot = path.join(home, 'sessions')
59
+ let scanned = 0
60
+ const interrupted: string[] = []
61
+ const now = Date.now()
62
+ const withinMs = opts?.withinMs
63
+ const sinceMs = opts?.sinceMs ?? (withinMs !== undefined ? now - withinMs : undefined)
64
+ try {
65
+ const groups = fs.readdirSync(sessionsRoot, { withFileTypes: true })
66
+ for (const g of groups) {
67
+ if (!g.isDirectory()) continue
68
+ const groupPath = path.join(sessionsRoot, g.name)
69
+ const sessions = fs.readdirSync(groupPath, { withFileTypes: true })
70
+ for (const s of sessions) {
71
+ if (!s.isDirectory()) continue
72
+ scanned++
73
+ const logPath = resolveSessionLogPath(path.join(groupPath, s.name))
74
+ try {
75
+ const lines = await readSessionTailLines(logPath, sinceMs)
76
+ if (lines === undefined) continue
77
+ let found = false
78
+ let foundTime: number | undefined
79
+ for (let i = lines.length - 1; i >= 0; i--) {
80
+ const line = lines[i]
81
+ try {
82
+ const obj = JSON.parse(line)
83
+ foundTime = typeof obj.time === 'number' ? obj.time : undefined
84
+ if (obj.type === 'turn/end' && obj.data?.reason?.kind === 'interrupted') { found = true; break }
85
+ } catch {}
86
+ }
87
+ if (!found) continue
88
+ if (sinceMs !== undefined && foundTime !== undefined) {
89
+ if (foundTime < sinceMs) continue // too old
90
+ } else if (sinceMs !== undefined && foundTime === undefined) {
91
+ // no timestamp, skip when filtering by time
92
+ continue
93
+ }
94
+ interrupted.push(`${g.name}/${s.name}`)
95
+ } catch {}
96
+ }
97
+ }
98
+ } catch {}
99
+ return { scanned, interrupted }
100
+ }
101
+
102
+ /**
103
+ * Read the entire log for a recent session (mtime within window) to find an
104
+ * open turn that may be far from the tail. Used only by
105
+ * {@link findDanglingOpenTurns}, which must see the last `turn/start`
106
+ * even when the file is 1906 lines and the open turn is at line 2 (subagent
107
+ * `b6487e33` had its only `turn/start` at seq 6, missed by `tail -100`).
108
+ * The mtime pre-filter ensures this full decompression runs only for
109
+ * recent sessions (within 5m, typically 1-2 files), not for all 425.
110
+ */
111
+ async function readSessionAllLines(logPath: string | undefined, sinceMs: number | undefined): Promise<string[] | undefined> {
112
+ if (logPath === undefined) return undefined
113
+ if (sinceMs !== undefined) {
114
+ try {
115
+ if (fs.statSync(logPath).mtimeMs < sinceMs) return undefined
116
+ } catch {}
117
+ }
118
+ if (logPath.endsWith('.zstd')) {
119
+ const { execSync } = await import('node:child_process')
120
+ // maxBuffer must exceed the decompressed size of any real session log —
121
+ // worker sessions decode to 8-23MB while execSync's default 1MB would
122
+ // throw ENOBUFS and silently drop the session from every scan that needs
123
+ // the full file (findDanglingOpenTurns). Use 64MB to leave headroom.
124
+ const out = execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null`, { encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 })
125
+ return out.split('\n').filter(Boolean)
126
+ }
127
+ try {
128
+ const content = fs.readFileSync(logPath, 'utf-8')
129
+ return content.trim().split('\n').filter(Boolean)
130
+ } catch {}
131
+ return undefined
132
+ }
133
+
134
+ /**
135
+ * Detect sessions whose raw log ends with a `turn/start` that has no
136
+ * matching `turn/end` anywhere later in the scanned log — a dangling open
137
+ * turn. Unlike {@link findInterrupted}, this needs no prior `persistence.load()`
138
+ * call to have already synthesized a `turn/end interrupted` closer (DSH core
139
+ * only writes that closer when something loads/prepares the specific
140
+ * session — a genuinely fresh crash's raw log has no closer at all, only an
141
+ * open turn). Safe to call ONLY right after a fresh `dsh web` boot, when
142
+ * `dsh web` is the sole live process for these sessions — an open turn found
143
+ * at that moment cannot belong to a still-running generation anywhere else.
144
+ * Callers MUST additionally skip any id that is live in their own current
145
+ * process (e.g. `ctx.sessions.get(id)`) before treating a match as crashed.
146
+ */
147
+ export async function findDanglingOpenTurns(dshHome?: string, opts?: FindInterruptedOpts): Promise<ResumeResult> {
148
+ const home = dshHome ?? path.join(os.homedir(), '.dsh')
149
+ const sessionsRoot = path.join(home, 'sessions')
150
+ let scanned = 0
151
+ const interrupted: string[] = []
152
+ const now = Date.now()
153
+ const withinMs = opts?.withinMs
154
+ const sinceMs = opts?.sinceMs ?? (withinMs !== undefined ? now - withinMs : undefined)
155
+ try {
156
+ const groups = fs.readdirSync(sessionsRoot, { withFileTypes: true })
157
+ for (const g of groups) {
158
+ if (!g.isDirectory()) continue
159
+ const groupPath = path.join(sessionsRoot, g.name)
160
+ const sessions = fs.readdirSync(groupPath, { withFileTypes: true })
161
+ for (const s of sessions) {
162
+ if (!s.isDirectory()) continue
163
+ scanned++
164
+ const logPath = resolveSessionLogPath(path.join(groupPath, s.name))
165
+ try {
166
+ const lines = await readSessionAllLines(logPath, sinceMs)
167
+ if (lines === undefined) continue
168
+ let openTurn: number | undefined
169
+ for (const line of lines) {
170
+ try {
171
+ const obj = JSON.parse(line)
172
+ if (obj.type === 'turn/start' && typeof obj.data?.turn === 'number') {
173
+ openTurn = obj.data.turn
174
+ } else if (obj.type === 'turn/end' && obj.data?.turn === openTurn) {
175
+ openTurn = undefined
176
+ }
177
+ } catch {}
178
+ }
179
+ if (openTurn === undefined) continue
180
+ // The requested window is enforced by the log's mtime in
181
+ // readSessionAllLines: a file appended to within the window may hold
182
+ // a fresh crash. It must NOT be re-checked against the open turn's
183
+ // own start time — a turn that ran longer than the window (a real
184
+ // 21-minute turn on 2026-09-13) then looked old and was skipped, so a
185
+ // restart mid-turn triggered no auto-continue.
186
+ interrupted.push(`${g.name}/${s.name}`)
187
+ } catch {}
188
+ }
189
+ }
190
+ } catch {}
191
+ return { scanned, interrupted }
192
+ }
193
+
194
+ export function parseDuration(s: string): number | undefined {
195
+ if (!s) return undefined
196
+ const m = s.trim().match(/^(\d+)(s|m|h)?$/)
197
+ if (!m) return undefined
198
+ const n = parseInt(m[1], 10)
199
+ const unit = m[2] ?? 's'
200
+ if (unit === 's') return n * 1000
201
+ if (unit === 'm') return n * 60 * 1000
202
+ if (unit === 'h') return n * 60 * 60 * 1000
203
+ return undefined
204
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Post-restart session scan: walk recent session logs under
3
+ * <dshHome>/sessions/<project>/<session>/ and flag torn tails (a zstd frame
4
+ * that fails to decode, or a plain-text log that is unreadable). Runs after
5
+ * an intentional dsh-web restart so the supervisor can report whether any
6
+ * in-flight session log was left truncated by the restart.
7
+ */
8
+
9
+ import { readdirSync, statSync } from 'node:fs'
10
+ import { join, extname, basename } from 'node:path'
11
+ import { execFileSync } from 'node:child_process'
12
+
13
+ interface ScanOptions { withinMs?: number }
14
+
15
+ async function decodeOk(file: string): Promise<boolean> {
16
+ try {
17
+ if (extname(file) === '.zstd') {
18
+ execFileSync('zstd', ['-d', '-c', file], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 30_000 })
19
+ } else {
20
+ const { readFileSync } = await import('node:fs')
21
+ readFileSync(file, 'utf8')
22
+ }
23
+ return true
24
+ } catch { return false }
25
+ }
26
+
27
+ /**
28
+ * Scan session logs whose mtime falls within the window. A file whose decode
29
+ * fails (torn zstd frame or unreadable plain text) is reported as torn. A
30
+ * missing sessions root yields an empty scan, never an error.
31
+ */
32
+ export async function scanSessions(dshHome: string, opts: ScanOptions = {}): Promise<{ scanned: number; torn: string[] }> {
33
+ const sessionsRoot = join(dshHome, 'sessions')
34
+ const now = Date.now()
35
+ const withinMs = opts.withinMs ?? 10 * 60 * 1000
36
+ const files: string[] = []
37
+ try {
38
+ for (const proj of readdirSync(sessionsRoot)) {
39
+ const projDir = join(sessionsRoot, proj)
40
+ if (!statSync(projDir).isDirectory()) continue
41
+ for (const sess of readdirSync(projDir)) {
42
+ const sessDir = join(projDir, sess)
43
+ if (!statSync(sessDir).isDirectory()) continue
44
+ for (const f of readdirSync(sessDir)) {
45
+ const name = basename(f)
46
+ if (!name.endsWith('.zstd') && !name.endsWith('.jsonl')) continue
47
+ const fp = join(sessDir, f)
48
+ let mtime = 0
49
+ try { mtime = statSync(fp).mtimeMs } catch { continue }
50
+ if (now - mtime > withinMs) continue
51
+ files.push(fp)
52
+ }
53
+ }
54
+ }
55
+ } catch { /* sessions root absent */ }
56
+ const torn: string[] = []
57
+ for (const f of files) {
58
+ if (!(await decodeOk(f))) torn.push(f)
59
+ }
60
+ return { scanned: files.length, torn }
61
+ }