@ddtcorex/dsh-maestro-core 0.15.1 → 0.16.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 (117) hide show
  1. package/README.md +7 -7
  2. package/assets/icon.svg +4 -0
  3. package/cordis.patch.yml +0 -12
  4. package/lib/client.js +3 -1744
  5. package/lib/health-poller.js +1 -1
  6. package/lib/self-kill-guard.d.ts +25 -8
  7. package/lib/self-kill-guard.js +81 -27
  8. package/lib/types/client/config/components/BrandMark.d.ts +3 -3
  9. package/lib/types/client/index.d.ts.map +1 -1
  10. package/locale/en.json +6 -0
  11. package/package.json +9 -5
  12. package/src/client/config/components/BrandMark.tsx +3 -3
  13. package/src/client/index.tsx +0 -2
  14. package/src/host/health-poller.ts +1 -1
  15. package/src/host/self-kill-guard.ts +84 -26
  16. package/lib/sync/backup-config.d.ts +0 -55
  17. package/lib/sync/backup-config.js +0 -119
  18. package/lib/sync/backup-service.d.ts +0 -123
  19. package/lib/sync/backup-service.js +0 -486
  20. package/lib/sync/bidirectional.d.ts +0 -39
  21. package/lib/sync/bidirectional.js +0 -25
  22. package/lib/sync/cli.d.ts +0 -38
  23. package/lib/sync/cli.js +0 -528
  24. package/lib/sync/config.d.ts +0 -59
  25. package/lib/sync/config.js +0 -72
  26. package/lib/sync/fingerprint.d.ts +0 -29
  27. package/lib/sync/fingerprint.js +0 -65
  28. package/lib/sync/hashing.d.ts +0 -22
  29. package/lib/sync/hashing.js +0 -77
  30. package/lib/sync/index.d.ts +0 -6
  31. package/lib/sync/index.js +0 -619
  32. package/lib/sync/machine-id.d.ts +0 -29
  33. package/lib/sync/machine-id.js +0 -66
  34. package/lib/sync/merge.d.ts +0 -31
  35. package/lib/sync/merge.js +0 -86
  36. package/lib/sync/peer-host.d.ts +0 -22
  37. package/lib/sync/peer-host.js +0 -62
  38. package/lib/sync/process-runner.d.ts +0 -31
  39. package/lib/sync/process-runner.js +0 -161
  40. package/lib/sync/remote-agent.d.ts +0 -41
  41. package/lib/sync/remote-agent.js +0 -216
  42. package/lib/sync/remote-cache.d.ts +0 -18
  43. package/lib/sync/remote-cache.js +0 -60
  44. package/lib/sync/remote-manifest.d.ts +0 -20
  45. package/lib/sync/remote-manifest.js +0 -86
  46. package/lib/sync/s3-object-store.d.ts +0 -38
  47. package/lib/sync/s3-object-store.js +0 -126
  48. package/lib/sync/session-plan.d.ts +0 -29
  49. package/lib/sync/session-plan.js +0 -213
  50. package/lib/sync/sigv4.d.ts +0 -20
  51. package/lib/sync/sigv4.js +0 -57
  52. package/lib/sync/snapshot.d.ts +0 -16
  53. package/lib/sync/snapshot.js +0 -143
  54. package/lib/sync/ssh-mux.d.ts +0 -12
  55. package/lib/sync/ssh-mux.js +0 -48
  56. package/lib/sync/store-root.d.ts +0 -44
  57. package/lib/sync/store-root.js +0 -67
  58. package/lib/sync/sync-plan.d.ts +0 -24
  59. package/lib/sync/sync-plan.js +0 -366
  60. package/lib/sync/sync-service.d.ts +0 -183
  61. package/lib/sync/sync-service.js +0 -926
  62. package/lib/sync/sync-types.d.ts +0 -87
  63. package/lib/sync/sync-types.js +0 -1
  64. package/lib/sync/transport.d.ts +0 -75
  65. package/lib/sync/transport.js +0 -196
  66. package/lib/sync/tunnel-restore.d.ts +0 -77
  67. package/lib/sync/tunnel-restore.js +0 -142
  68. package/lib/sync/validation.d.ts +0 -12
  69. package/lib/sync/validation.js +0 -96
  70. package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
  71. package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
  72. package/lib/types/client/sync/SyncPanel.d.ts +0 -12
  73. package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
  74. package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
  75. package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
  76. package/lib/types/client/sync/index.d.ts +0 -10
  77. package/lib/types/client/sync/index.d.ts.map +0 -1
  78. package/lib/types/client/sync/ui.d.ts +0 -75
  79. package/lib/types/client/sync/ui.d.ts.map +0 -1
  80. package/lib/types/client/sync/use-backup.d.ts +0 -50
  81. package/lib/types/client/sync/use-backup.d.ts.map +0 -1
  82. package/lib/types/client/sync/use-sync.d.ts +0 -88
  83. package/lib/types/client/sync/use-sync.d.ts.map +0 -1
  84. package/src/client/sync/R2SyncPanel.tsx +0 -260
  85. package/src/client/sync/SyncPanel.tsx +0 -422
  86. package/src/client/sync/confirm-dialog.tsx +0 -202
  87. package/src/client/sync/index.tsx +0 -286
  88. package/src/client/sync/ui.tsx +0 -297
  89. package/src/client/sync/use-backup.ts +0 -207
  90. package/src/client/sync/use-sync.ts +0 -502
  91. package/src/host/sync/backup-config.ts +0 -158
  92. package/src/host/sync/backup-service.ts +0 -506
  93. package/src/host/sync/bidirectional.ts +0 -66
  94. package/src/host/sync/cli.ts +0 -530
  95. package/src/host/sync/config.ts +0 -96
  96. package/src/host/sync/fingerprint.ts +0 -83
  97. package/src/host/sync/hashing.ts +0 -91
  98. package/src/host/sync/index.ts +0 -697
  99. package/src/host/sync/machine-id.ts +0 -81
  100. package/src/host/sync/merge.ts +0 -99
  101. package/src/host/sync/peer-host.ts +0 -65
  102. package/src/host/sync/process-runner.ts +0 -177
  103. package/src/host/sync/remote-agent.ts +0 -212
  104. package/src/host/sync/remote-cache.ts +0 -68
  105. package/src/host/sync/remote-manifest.ts +0 -91
  106. package/src/host/sync/s3-object-store.ts +0 -144
  107. package/src/host/sync/session-plan.ts +0 -237
  108. package/src/host/sync/sigv4.ts +0 -81
  109. package/src/host/sync/snapshot.ts +0 -132
  110. package/src/host/sync/ssh-mux.ts +0 -55
  111. package/src/host/sync/store-root.ts +0 -83
  112. package/src/host/sync/sync-plan.ts +0 -366
  113. package/src/host/sync/sync-service.ts +0 -960
  114. package/src/host/sync/sync-types.ts +0 -102
  115. package/src/host/sync/transport.ts +0 -256
  116. package/src/host/sync/tunnel-restore.ts +0 -160
  117. package/src/host/sync/validation.ts +0 -104
@@ -1,697 +0,0 @@
1
- // dsh-maestro-sync — Host index: preview/apply tools + loopback RPC (Task 6).
2
- // Mutation exists only through preview-bound apply(confirm:true).
3
- import * as path from 'node:path';
4
- import * as os from 'node:os';
5
- import { randomBytes } from 'node:crypto';
6
- import { defineTool } from '@deepseek-ai/dsh-tools';
7
- import { SyncService } from './sync-service.js';
8
- import { loadSyncConfig } from './config.js';
9
- import { defaultDshHome, readPeerHost, writePeerHost } from './peer-host.js';
10
- import { BackupService } from './backup-service.js';
11
- import { S3ObjectStore } from './s3-object-store.js';
12
- import { resolveBackupTarget, validateR2ConfigInput, type NormalizedR2Config } from './backup-config.js';
13
- import { load, set as saveDomain } from '../store/index.js';
14
- import { validateHost } from './validation.js';
15
- import type { PreviewJobState, RemoteTarget } from './sync-types.js';
16
- import { runBidirectionalApply, runBidirectionalPreview } from './bidirectional.js';
17
- import { readLocalTunnelProfile, restoreLocalTunnel } from './tunnel-restore.js';
18
- import { checkMachines, peerMachineId, readLocalMachineId } from './machine-id.js';
19
- import { restoreRemoteTunnel } from './tunnel-restore.js';
20
-
21
- export const RPC_CHANNEL = '/dsh-maestro-sync';
22
-
23
- // Async preview jobs: the UI polls previewStatus while the service hashes
24
- // sessions over ssh (count-only). Job state is process-local; the exact
25
- // preview is persisted to the sidecar store by the service itself, so a job
26
- // state loss on restart only loses the in-flight progress, never a preview.
27
- const previewJobs = new Map<string, PreviewJobState>();
28
- const MAX_PREVIEW_JOBS = 8;
29
- const PREVIEW_JOB_IDLE_MS = 120_000;
30
-
31
- /**
32
- * Tunnel-restore previews. `restoreLocalTunnel` rewrites `domains.tunnel` in
33
- * the shared store — the exact data class whose uncoordinated write took a
34
- * machine's tunnel down on 2026-08-26 and 2026-09-09 (HTTP 530). It therefore
35
- * follows the same contract as every other mutation in this package: a
36
- * read-only preview first, then a single-use, TTL-bounded id carried into the
37
- * confirmation dialog.
38
- */
39
- type TunnelPreview = { side: 'local'; profile: string; expiresAt: number; current: unknown; desired: unknown };
40
- const tunnelPreviews = new Map<string, TunnelPreview>();
41
- const TUNNEL_PREVIEW_TTL_MS = 60_000;
42
-
43
- function pruneTunnelPreviews(now = Date.now()): void {
44
- for (const [id, p] of tunnelPreviews) if (p.expiresAt <= now) tunnelPreviews.delete(id);
45
- }
46
-
47
- // Carrier helpers — dsh-client-connection decodes every RPC response as
48
- // { ok: true, value } | { ok: false, error: { code, message, details } }
49
- // (same shape as dsh-maestro-jobs rpc.ts). A handler MUST return this exact
50
- // shape; returning { ok: true, ...flatFields } yields value: undefined on the
51
- // browser side because the connection reads result.value.
52
- function okCarrier<T>(value: T): { ok: true; value: T } {
53
- return { ok: true, value };
54
- }
55
-
56
- function failCarrier(message: string, code = 'maestro-sync/rpc', details: Record<string, unknown> = {}): { ok: false; error: { code: string; message: string; details: object } } {
57
- return { ok: false, error: { code, message, details } };
58
- }
59
-
60
- /**
61
- * Best-effort tunnel profile restore after a confirmed apply.
62
- * Delegates to the shared tunnel-restore module (local side only here;
63
- * remote restore is an explicit tool/RPC, never implicit).
64
- * Never throws; profiles may not exist on CI.
65
- */
66
- async function restoreTunnelProfile(): Promise<void> {
67
- await restoreLocalTunnel();
68
- }
69
-
70
- function textTool(name: string, description: string, params: Record<string, any>, execute: (args: any) => Promise<string>) {
71
- return defineTool({
72
- name,
73
- description,
74
- parameters: params,
75
- output: {
76
- schema: {
77
- type: 'object',
78
- additionalProperties: false,
79
- properties: { text: { type: 'string', required: true } },
80
- },
81
- render: (_args, value) => [{ type: 'text', text: value.text }],
82
- },
83
- async execute(args: any) {
84
- return { text: await execute(args ?? {}) };
85
- },
86
- });
87
- }
88
-
89
- export default {
90
- inject: ['tools', 'connection'] as const,
91
- apply(ctx: any) {
92
- const makeBackupService = async () => {
93
- const doc = (await load().catch(() => ({ domains: {} as any }))) as any;
94
- const { config, secrets } = await resolveBackupTarget(doc, process.env as any);
95
- if (!config.endpoint) throw Object.assign(new Error('backup endpoint not configured'), { phase: 'validate', code: 'MISSING_ENDPOINT' });
96
- const store = new S3ObjectStore({ endpoint: config.endpoint, region: config.region, accessKeyId: secrets.accessKeyId, secretAccessKey: secrets.secretAccessKey });
97
- const dshHome = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
98
- return new BackupService({
99
- localDsh: dshHome,
100
- store,
101
- target: { provider: config.provider, bucket: config.bucket, prefix: config.prefix, hostId: config.prefix.split('/')[2] ?? 'host' },
102
- previewDir: path.join(dshHome, 'dsh-maestro-sync', 'previews'),
103
- cacheDir: path.join(dshHome, 'dsh-maestro-sync', 'cache'),
104
- });
105
- };
106
-
107
- const makeService = async () => {
108
- const cfg = await loadSyncConfig({ dshHome: defaultDshHome() });
109
- return new SyncService({ remote: cfg.remoteHost, remoteDsh: cfg.remoteDshPath });
110
- };
111
-
112
- // Shared lifecycle reads: local machine-id via the service fs, remote via
113
- // the service transport (fixed agent op). No new seams — tests stub the
114
- // service/transport methods.
115
- const lifecycleIds = async (svc: SyncService): Promise<{ localId: string | null; remoteId: string | null; target: RemoteTarget }> => {
116
- const localId = await readLocalMachineId(svc.fs, svc.localDsh);
117
- const target = await svc.resolveTarget();
118
- const remoteId = await svc.transport.readMachineId(target);
119
- return { localId, remoteId, target };
120
- };
121
-
122
- // maestro_sync_preview — read-only exact plan
123
- ctx.effect(() =>
124
- ctx.tools.register(
125
- textTool(
126
- 'maestro_sync_preview',
127
- 'Preview exact pull/push merge plan (read-only: copy/merge/skip/conflict + added counts)',
128
- { direction: { type: 'string', enum: ['pull', 'push'], description: 'plan direction' } },
129
- async ({ direction }) => {
130
- const svc = await makeService();
131
- const preview = await svc.preview({ direction: direction === 'push' ? 'push' : 'pull' });
132
- return JSON.stringify({
133
- ok: true,
134
- previewId: preview.previewId,
135
- revision: preview.revision,
136
- expiresAt: preview.expiresAt,
137
- summary: preview.summary,
138
- actions: preview.actions,
139
- });
140
- },
141
- ),
142
- ),
143
- );
144
-
145
- // maestro_sync_apply — the only mutation route (preview-bound, confirm required)
146
- ctx.effect(() =>
147
- ctx.tools.register(
148
- textTool(
149
- 'maestro_sync_apply',
150
- 'Apply a previously previewed plan. Requires previewId, direction and confirm:true.',
151
- {
152
- previewId: { type: 'string', description: 'preview id returned by preview' },
153
- direction: { type: 'string', enum: ['pull', 'push'], description: 'apply direction (must match preview)' },
154
- confirm: { type: 'boolean', description: 'must be true' },
155
- },
156
- async ({ previewId, direction, confirm }) => {
157
- if (confirm !== true) return JSON.stringify({ ok: false, error: 'apply requires confirm:true' });
158
- if (!previewId || typeof previewId !== 'string') return JSON.stringify({ ok: false, error: 'apply requires previewId' });
159
- const svc = await makeService();
160
- try {
161
- const r = await svc.apply({ previewId, direction: direction === 'push' ? 'push' : 'pull', confirm: true });
162
- if (r.ok) await restoreTunnelProfile();
163
- return JSON.stringify({ ok: r.ok, revision: r.revision, summary: r.summary, committed: r.committed, failures: r.failures });
164
- } catch (e: any) {
165
- return JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase });
166
- }
167
- },
168
- ),
169
- ),
170
- );
171
-
172
- // maestro_sync_bidirectional_preview — read-only combined plan (exact push + projected pull)
173
- ctx.effect(() =>
174
- ctx.tools.register(
175
- textTool(
176
- 'maestro_sync_bidirectional_preview',
177
- 'Preview a push-then-pull round trip (read-only: exact push plan + projected pull plan).',
178
- { includeSessions: { type: 'boolean', description: 'also sync sessions/ (default: memories only)' } },
179
- async (a) => {
180
- const svc = await makeService();
181
- const scope = a?.includeSessions === true ? 'all' : 'memory';
182
- const combined = await runBidirectionalPreview(svc, { scope });
183
- return JSON.stringify({
184
- ok: true,
185
- previewId: combined.previewId,
186
- expiresAt: combined.expiresAt,
187
- push: { summary: combined.push.summary, actions: combined.push.actions },
188
- pullProjected: { summary: combined.pullProjected.summary, actions: combined.pullProjected.actions },
189
- note: 'pull plan is projected; recomputed exact at apply time',
190
- });
191
- },
192
- ),
193
- ),
194
- );
195
-
196
- // maestro_sync_bidirectional_apply — the only bidirectional mutation route
197
- ctx.effect(() =>
198
- ctx.tools.register(
199
- textTool(
200
- 'maestro_sync_bidirectional_apply',
201
- 'Apply a previously previewed bidirectional plan. Requires previewId and confirm:true.',
202
- {
203
- previewId: { type: 'string', description: 'preview id returned by bidirectional preview' },
204
- confirm: { type: 'boolean', description: 'must be true' },
205
- includeSessions: { type: 'boolean', description: 'must match the preview scope' },
206
- },
207
- async (a) => {
208
- if (a?.confirm !== true) return JSON.stringify({ ok: false, error: 'bidirectional apply requires confirm:true' });
209
- if (!a?.previewId || typeof a.previewId !== 'string') return JSON.stringify({ ok: false, error: 'bidirectional apply requires previewId' });
210
- const svc = await makeService();
211
- try {
212
- const scope = a?.includeSessions === true ? 'all' : 'memory';
213
- const r = await runBidirectionalApply(svc, { previewId: a.previewId, confirm: true, scope });
214
- if (r.ok) await restoreTunnelProfile();
215
- return JSON.stringify({ ok: r.ok, push: r.push, pull: r.pull, verification: r.verification, committed: r.committed, failures: r.failures });
216
- } catch (e: any) {
217
- return JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase });
218
- }
219
- },
220
- ),
221
- ),
222
- );
223
-
224
- // maestro_sync_check_machines — read-only machine identity preflight
225
- ctx.effect(() =>
226
- ctx.tools.register(
227
- textTool(
228
- 'maestro_sync_check_machines',
229
- 'Check machine identity before sync (read-only): local/remote machine-id plus the from/to verdict.',
230
- {
231
- from: { type: 'string', description: 'absolute source machine (default: local machine-id)' },
232
- to: { type: 'string', description: 'absolute destination machine (default: peer of from)' },
233
- mode: { type: 'string', enum: ['pull', 'push', 'bidirectional'], description: 'operation the check guards (default: bidirectional)' },
234
- },
235
- async (a) => {
236
- const svc = await makeService();
237
- const mode = a?.mode === 'pull' || a?.mode === 'push' ? a.mode : 'bidirectional';
238
- try {
239
- const { localId, remoteId } = await lifecycleIds(svc);
240
- const from = typeof a?.from === 'string' ? a.from : (localId ?? undefined);
241
- const to = typeof a?.to === 'string' ? a.to : (from === undefined ? undefined : peerMachineId(from, localId, remoteId) ?? undefined);
242
- if (from === undefined || to === undefined) {
243
- return JSON.stringify({ ok: false, code: 'MACHINE_ID_UNRESOLVED', error: 'cannot resolve --from/--to from the machine ids; pass them explicitly', localId, remoteId });
244
- }
245
- const verdict = checkMachines({ mode, from, to, localId, remoteId });
246
- return verdict.ok
247
- ? JSON.stringify({ ok: true, mode, localId, remoteId, from, to })
248
- : JSON.stringify({ ok: false, code: verdict.code, error: verdict.message, localId, remoteId, from, to });
249
- } catch (e: any) {
250
- return JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code });
251
- }
252
- },
253
- ),
254
- ),
255
- );
256
-
257
- // maestro_sync_tunnel_restore — explicit identity restore (confirm-first, never implicit)
258
- ctx.effect(() =>
259
- ctx.tools.register(
260
- textTool(
261
- 'maestro_sync_tunnel_restore',
262
- 'Restore the tunnel identity (domains.tunnel only) from a machine profile. Requires confirm:true; remote side additionally requires profile.',
263
- {
264
- side: { type: 'string', enum: ['local', 'remote'], description: 'which side to restore (default: local)' },
265
- profile: { type: 'string', description: 'profile name (required for remote)' },
266
- confirm: { type: 'boolean', description: 'must be true' },
267
- },
268
- async (a) => {
269
- if (a?.confirm !== true) return JSON.stringify({ ok: false, error: 'tunnel restore requires confirm:true' });
270
- const side = a?.side === 'remote' ? 'remote' : 'local';
271
- const svc = await makeService();
272
- try {
273
- if (side === 'local') {
274
- const r = await restoreLocalTunnel({ dshHome: svc.localDsh, profileName: typeof a?.profile === 'string' ? a.profile : undefined });
275
- return r.ok
276
- ? JSON.stringify({ ok: true, side, profile: r.profile })
277
- : JSON.stringify({ ok: false, side, code: r.code });
278
- }
279
- if (typeof a?.profile !== 'string' || !a.profile) return JSON.stringify({ ok: false, side, error: 'tunnel restore --side remote requires profile' });
280
- const target = await svc.resolveTarget();
281
- await svc.transport.ensureAgent(target);
282
- const r = await restoreRemoteTunnel(svc.transport, target, a.profile);
283
- return r.ok
284
- ? JSON.stringify({ ok: true, side, profile: r.profile, changed: r.changed })
285
- : JSON.stringify({ ok: false, side, code: r.code });
286
- } catch (e: any) {
287
- return JSON.stringify({ ok: false, side, error: e?.message ?? String(e), code: e?.code });
288
- }
289
- },
290
- ),
291
- ),
292
- );
293
-
294
- // maestro_sync_status — bounded cursor-paged file status
295
- ctx.effect(() =>
296
- ctx.tools.register(
297
- textTool(
298
- 'maestro_sync_status', 'Sync status: counts of local/remote/both files (never implies same content)',
299
- {},
300
- async () => {
301
- const svc = await makeService();
302
- const st = await svc.status();
303
- return JSON.stringify({ ok: true, remoteHost: st.remoteHost, connection: st.connection, localOnly: st.localOnly, remoteOnly: st.remoteOnly, both: st.both });
304
- },
305
- ),
306
- ),
307
- );
308
-
309
- // Backup / restore / GC tools (R2 Sync tab; mutation routes are
310
- // preview-bound apply(confirm:true) — mirroring the sync tools).
311
- ctx.effect(() =>
312
- ctx.tools.register(
313
- textTool('maestro_backup_preview', 'Read-only backup preview: what a Backup Apply would upload (missing blobs + bytes).', { direction: { type: 'string' } }, async () => {
314
- const r = await (await makeBackupService()).preview();
315
- return JSON.stringify({ ok: true, previewId: r.previewId, summary: r.summary });
316
- }),
317
- ),
318
- );
319
- ctx.effect(() =>
320
- ctx.tools.register(
321
- textTool('maestro_backup_apply', 'Apply a backup preview (single-use): upload blobs, write the manifest, CAS-advance HEAD.', { previewId: { type: 'string' }, confirm: { type: 'boolean' } }, async (a) => {
322
- if (a.confirm !== true) return JSON.stringify({ ok: false, error: 'backup apply requires confirm:true' });
323
- const r = await (await makeBackupService()).apply({ previewId: a.previewId, confirm: true });
324
- return JSON.stringify({ ok: r.ok, committed: r.committed, failures: r.failures });
325
- }),
326
- ),
327
- );
328
- ctx.effect(() =>
329
- ctx.tools.register(
330
- textTool('maestro_restore_preview', 'Read-only restore preview from the backup HEAD manifest (new-dir or in-place).', { mode: { type: 'string' } }, async (a) => {
331
- const r = await (await makeBackupService()).restorePreview({ mode: a.mode === 'new-dir' ? 'new-dir' : 'in-place' });
332
- return JSON.stringify({ ok: true, previewId: r.previewId, summary: r.summary });
333
- }),
334
- ),
335
- );
336
- ctx.effect(() =>
337
- ctx.tools.register(
338
- textTool('maestro_restore_apply', 'Apply a restore preview: materialize under a new dir or in place (backups overwritten targets).', { previewId: { type: 'string' }, mode: { type: 'string' }, destDir: { type: 'string' }, confirm: { type: 'boolean' } }, async (a) => {
339
- if (a.confirm !== true) return JSON.stringify({ ok: false, error: 'restore apply requires confirm:true' });
340
- const r = await (await makeBackupService()).restoreApply({ previewId: a.previewId, mode: a.mode === 'new-dir' ? 'new-dir' : 'in-place', destDir: a.destDir, confirm: true });
341
- return JSON.stringify({ ok: r.ok, committed: r.committed, failures: r.failures });
342
- }),
343
- ),
344
- );
345
- ctx.effect(() =>
346
- ctx.tools.register(
347
- textTool('maestro_backup_gc_preview', 'Read-only retention GC preview: unreachable blobs + freed bytes.', {}, async () => {
348
- const r = await (await makeBackupService()).gcPreview({});
349
- return JSON.stringify({ ok: true, previewId: r.previewId, deletable: r.deletableBlobs.length, freedBytes: r.freedBytes });
350
- }),
351
- ),
352
- );
353
- ctx.effect(() =>
354
- ctx.tools.register(
355
- textTool('maestro_backup_gc_apply', 'Apply a GC preview: delete the listed unreachable blobs.', { previewId: { type: 'string' }, confirm: { type: 'boolean' } }, async (a) => {
356
- if (a.confirm !== true) return JSON.stringify({ ok: false, error: 'gc apply requires confirm:true' });
357
- const r = await (await makeBackupService()).gcApply({ previewId: a.previewId, confirm: true });
358
- return JSON.stringify({ ok: r.ok, deleted: r.deleted, freedBytes: r.freedBytes });
359
- }),
360
- ),
361
- );
362
-
363
- // RPC for the Settings UI. Reachability is loopback because the browser
364
- // dials the local host; registration cannot request it — handle() takes
365
- // exactly (channel, handler).
366
- ctx.effect(() =>
367
- ctx.connection.rpc.handle(
368
- RPC_CHANNEL,
369
- async (method: string, args: any) => {
370
- const svc = await makeService();
371
- try {
372
- switch (String(method)) {
373
- case 'status': {
374
- if (args && typeof args.bucket === 'string') {
375
- const page = await svc.statusPage({ bucket: args.bucket, cursor: args.cursor, limit: args.limit });
376
- return okCarrier({ total: page.total, offset: page.offset, limit: page.limit, files: page.files, nextCursor: page.nextCursor, connection: page.connection, remoteHost: page.remoteHost });
377
- }
378
- const r = await svc.status();
379
- return okCarrier({ remoteHost: r.remoteHost, connection: r.connection, localOnly: r.localOnly, remoteOnly: r.remoteOnly, both: r.both });
380
- }
381
- case 'check': {
382
- const r = await svc.checkConnection();
383
- return okCarrier({ connection: r, remoteHost: r.host });
384
- }
385
- case 'getRemoteConfig': {
386
- // Effective SSH target + where it came from (no auto-check;
387
- // the UI checks explicitly via 'check').
388
- const doc = await load();
389
- const stored = (doc.domains?.sync as Record<string, unknown> | undefined)?.remoteHost;
390
- const machineHost = readPeerHost(svc.localDsh);
391
- const cfg = await loadSyncConfig({ dshHome: svc.localDsh });
392
- const source = machineHost
393
- ? 'machine'
394
- : typeof stored === 'string' && stored.length > 0
395
- ? 'settings'
396
- : process.env.REMOTE_HOST || process.env.REMOTE
397
- ? 'env'
398
- : 'default';
399
- return okCarrier({ remoteHost: cfg.remoteHost, source });
400
- }
401
- case 'saveRemoteHost': {
402
- const raw = (args as any)?.host;
403
- let host: string;
404
- try {
405
- host = validateHost(typeof raw === 'string' ? raw.trim() : '');
406
- } catch (e: any) {
407
- return failCarrier(e?.message ?? 'invalid host', 'INVALID_HOST');
408
- }
409
- await saveDomain('sync', { remoteHost: host });
410
- // Also record it for THIS machine: the shared value above
411
- // travels, so a peer that belongs to the other machine (or to
412
- // this one) must not win here. See peer-host.ts.
413
- try {
414
- writePeerHost(svc.localDsh ?? defaultDshHome(), host);
415
- } catch (e: any) {
416
- return failCarrier(e?.message ?? 'could not record the machine-local peer', 'PEER_WRITE_FAILED');
417
- }
418
- return okCarrier({ remoteHost: host, scope: 'machine' });
419
- }
420
- case 'saveR2Config': {
421
- // Non-secret backup target only — secret material is never
422
- // accepted here (env or the 0600 sidecar).
423
- let cfg: NormalizedR2Config;
424
- try {
425
- cfg = validateR2ConfigInput((args ?? {}) as any);
426
- } catch (e: any) {
427
- return failCarrier(e?.message ?? 'invalid r2 config', 'INVALID_R2_CONFIG');
428
- }
429
- const doc = await load().catch(() => ({ domains: {} as any }));
430
- const stored = ((doc.domains?.sync as Record<string, unknown> | undefined)?.r2 ?? {}) as Record<string, unknown>;
431
- const merged: Record<string, unknown> = { ...stored };
432
- const put = (k: string, v: string) => {
433
- if (v) merged[k] = v;
434
- else delete merged[k];
435
- };
436
- put('provider', cfg.provider === 'aws' ? 'aws' : '');
437
- put('accountId', cfg.accountId);
438
- put('endpoint', cfg.endpoint);
439
- put('region', cfg.region);
440
- merged.bucket = cfg.bucket;
441
- merged.prefix = cfg.prefix;
442
- await saveDomain('sync', { r2: merged });
443
- return okCarrier({ r2: { provider: cfg.provider, endpoint: cfg.endpoint, region: cfg.region, bucket: cfg.bucket, prefix: cfg.prefix } });
444
- }
445
- case 'preview': {
446
- const dir = (args && (args as any).direction) === 'push' ? 'push' : 'pull';
447
- const r = await svc.preview({ direction: dir });
448
- return okCarrier({ previewId: r.previewId, revision: r.revision, expiresAt: r.expiresAt, actions: r.actions, summary: r.summary, sessionCounts: r.sessionCounts, connection: r.connection, remoteHost: r.remoteHost });
449
- }
450
- case 'previewStart': {
451
- // Count-only sessions (no content staged) + per-file progress;
452
- // returns a jobId immediately, the UI polls previewStatus.
453
- const dir = (args && (args as any).direction) === 'push' ? 'push' : 'pull';
454
- const jobId = randomBytes(8).toString('hex');
455
- const state: PreviewJobState = { status: 'running', progress: { phase: 'listing', current: 0, total: 1 } };
456
- (state as any).cancelled = false;
457
- (state as any).ts = Date.now();
458
- previewJobs.set(jobId, state);
459
- if (previewJobs.size > MAX_PREVIEW_JOBS) {
460
- const oldest = [...previewJobs.entries()].sort((a, b) => ((a[1] as any).ts ?? 0) - ((b[1] as any).ts ?? 0))[0];
461
- if (oldest) previewJobs.delete(oldest[0]);
462
- }
463
- void (async () => {
464
- try {
465
- const r = await svc.preview({
466
- direction: dir,
467
- sessionsCountOnly: true,
468
- onProgress: (p) => {
469
- const s = previewJobs.get(jobId);
470
- if (s && s.status !== 'cancelled') {
471
- s.progress = p;
472
- (s as any).ts = Date.now();
473
- }
474
- },
475
- shouldStop: () => {
476
- const s = previewJobs.get(jobId);
477
- return s !== undefined && (s as any).cancelled === true;
478
- },
479
- });
480
- const s = previewJobs.get(jobId);
481
- if (s) {
482
- s.status = 'done';
483
- s.preview = { previewId: r.previewId, revision: r.revision, expiresAt: r.expiresAt, actions: r.actions, summary: r.summary, sessionCounts: r.sessionCounts, connection: (r as any).connection, remoteHost: (r as any).remoteHost } as any;
484
- (s as any).ts = Date.now();
485
- }
486
- } catch (e: any) {
487
- const s = previewJobs.get(jobId);
488
- if (s) {
489
- if (s.status !== 'cancelled') {
490
- s.status = e?.code === 'CANCELLED' ? 'cancelled' : 'error';
491
- s.error = e?.message ?? String(e);
492
- }
493
- (s as any).ts = Date.now();
494
- }
495
- }
496
- })();
497
- return okCarrier({ jobId, status: 'running' });
498
- }
499
- case 'previewCancel': {
500
- const jobId = args && (args as any).jobId;
501
- const s = jobId && typeof jobId === 'string' ? previewJobs.get(jobId) : undefined;
502
- if (!s) return failCarrier('preview job not found', 'maestro-sync/preview-job');
503
- (s as any).cancelled = true;
504
- s.status = 'cancelled';
505
- (s as any).ts = Date.now();
506
- return okCarrier({ ok: true });
507
- }
508
- case 'previewStatus': {
509
- const jobId = args && (args as any).jobId;
510
- if (!jobId || typeof jobId !== 'string' || !previewJobs.has(jobId)) return failCarrier('preview job not found', 'maestro-sync/preview-job');
511
- const s = previewJobs.get(jobId)!;
512
- const idleMs = Date.now() - ((s as any).ts ?? Date.now());
513
- if (idleMs > PREVIEW_JOB_IDLE_MS) {
514
- previewJobs.delete(jobId);
515
- return failCarrier('preview job expired', 'maestro-sync/preview-job');
516
- }
517
- return okCarrier({
518
- status: s.status,
519
- progress: s.progress,
520
- preview: s.preview,
521
- error: s.error,
522
- });
523
- }
524
- case 'apply': {
525
- const previewId = args && (args as any).previewId;
526
- const direction = args && (args as any).direction === 'push' ? 'push' : 'pull';
527
- const confirm = args && (args as any).confirm;
528
- if (confirm !== true) return failCarrier('apply requires confirm:true');
529
- if (!previewId || typeof previewId !== 'string') return failCarrier('apply requires previewId');
530
- const r = await svc.apply({ previewId, direction, confirm: true });
531
- if (r.ok) await restoreTunnelProfile();
532
- return okCarrier({ revision: r.revision, summary: r.summary, committed: r.committed, failures: r.failures });
533
- }
534
- case 'bidirectionalPreview': {
535
- const scope = args && (args as any).includeSessions === true ? 'all' : 'memory';
536
- const combined = await runBidirectionalPreview(svc, { scope });
537
- return okCarrier({
538
- previewId: combined.previewId,
539
- expiresAt: combined.expiresAt,
540
- push: combined.push,
541
- pullProjected: combined.pullProjected,
542
- note: 'pull plan is projected; recomputed exact at apply time',
543
- });
544
- }
545
- case 'bidirectionalApply': {
546
- const { previewId, confirm } = (args ?? {}) as any;
547
- if (confirm !== true) return failCarrier('bidirectional apply requires confirm:true', 'maestro-sync/confirm');
548
- if (!previewId || typeof previewId !== 'string') return failCarrier('bidirectional apply requires previewId');
549
- const scope = args && (args as any).includeSessions === true ? 'all' : 'memory';
550
- const r = await runBidirectionalApply(svc, { previewId, confirm: true, scope });
551
- if (r.ok) await restoreTunnelProfile();
552
- return r.ok
553
- ? okCarrier({ ok: true, push: r.push, pull: r.pull, verification: r.verification, committed: r.committed, failures: r.failures })
554
- : failCarrier('bidirectional apply failed', 'maestro-sync/bidirectional', { failures: r.failures } as any);
555
- }
556
- case 'checkMachines': {
557
- const a = (args ?? {}) as any;
558
- const mode = a.mode === 'pull' || a.mode === 'push' ? a.mode : 'bidirectional';
559
- try {
560
- const { localId, remoteId } = await lifecycleIds(svc);
561
- const from = typeof a.from === 'string' ? a.from : (localId ?? undefined);
562
- const to = typeof a.to === 'string' ? a.to : (from === undefined ? undefined : peerMachineId(from, localId, remoteId) ?? undefined);
563
- if (from === undefined || to === undefined) {
564
- return okCarrier({ ok: false, reason: 'cannot resolve --from/--to from the machine ids; pass them explicitly', mode, localId, remoteId });
565
- }
566
- const verdict = checkMachines({ mode, from, to, localId, remoteId });
567
- return verdict.ok
568
- ? okCarrier({ ok: true, mode, localId, remoteId, from, to })
569
- : okCarrier({ ok: false, reason: verdict.message, mode, localId, remoteId, from, to });
570
- } catch (e: any) {
571
- return failCarrier(e?.message ?? String(e), e?.code ?? 'maestro-sync/machines');
572
- }
573
- }
574
- case 'tunnelRestorePreview': {
575
- const a = (args ?? {}) as any;
576
- const side = a.side === 'remote' ? 'remote' : 'local';
577
- if (side === 'remote') {
578
- return failCarrier('remote tunnel restore has no preview yet — run it from the CLI with an explicit profile', 'maestro-sync/tunnel', { side });
579
- }
580
- const found = readLocalTunnelProfile(typeof a.profile === 'string' && a.profile ? { profileName: a.profile } : undefined);
581
- if (!found.ok) {
582
- return failCarrier(
583
- found.code === 'INVALID_PROFILE' ? 'tunnel profile tunnel is not a named-tunnel object' : 'no tunnel profile found',
584
- 'maestro-sync/tunnel',
585
- { side },
586
- );
587
- }
588
- let current: unknown = null;
589
- try {
590
- const doc: any = await load();
591
- current = doc?.domains?.tunnel ?? null;
592
- } catch {}
593
- pruneTunnelPreviews();
594
- const previewId = randomBytes(12).toString('hex');
595
- const expiresAt = Date.now() + TUNNEL_PREVIEW_TTL_MS;
596
- tunnelPreviews.set(previewId, { side: 'local', profile: found.profile, expiresAt, current, desired: found.tunnel });
597
- return okCarrier({
598
- previewId,
599
- side,
600
- profile: found.profile,
601
- expiresAt,
602
- target: 'domains.tunnel',
603
- current,
604
- desired: found.tunnel,
605
- changed: JSON.stringify(current ?? null) !== JSON.stringify(found.tunnel),
606
- });
607
- }
608
- case 'tunnelRestore': {
609
- const a = (args ?? {}) as any;
610
- if (a.confirm !== true) return failCarrier('tunnel restore requires confirm:true', 'maestro-sync/confirm');
611
- const side = a.side === 'remote' ? 'remote' : 'local';
612
- if (side === 'local') {
613
- // The write is bound to a preview taken moments ago: one
614
- // click can no longer rewrite domains.tunnel on its own.
615
- pruneTunnelPreviews();
616
- const previewId = typeof a.previewId === 'string' ? a.previewId : '';
617
- const preview = previewId ? tunnelPreviews.get(previewId) : undefined;
618
- if (!preview) return failCarrier('tunnel restore requires a fresh previewId', 'maestro-sync/preview', { side });
619
- tunnelPreviews.delete(previewId);
620
- const r = await restoreLocalTunnel({ profileName: preview.profile });
621
- return r.ok
622
- ? okCarrier({ ok: true, side, profile: r.profile })
623
- : failCarrier(r.code === 'INVALID_PROFILE' ? 'tunnel profile tunnel is not a named-tunnel object' : 'no tunnel profile found', 'maestro-sync/tunnel', { side });
624
- }
625
- if (typeof a.profile !== 'string' || !a.profile) return failCarrier('tunnel restore --side remote requires profile', 'maestro-sync/tunnel');
626
- try {
627
- const target = await svc.resolveTarget();
628
- await svc.transport.ensureAgent(target);
629
- const r = await restoreRemoteTunnel(svc.transport, target, a.profile);
630
- if (!r.ok) return failCarrier(`tunnel restore rejected: ${r.code}`, 'maestro-sync/tunnel', { side });
631
- return okCarrier({ ok: true, side, profile: r.profile, changed: r.changed });
632
- } catch (e: any) {
633
- return failCarrier(e?.message ?? String(e), e?.code ?? 'maestro-sync/tunnel', { side });
634
- }
635
- }
636
- case 'backupStatus': { try {
637
- const bsvc = await makeBackupService();
638
- const head = await bsvc.readHeadManifest();
639
- const target = await resolveBackupTarget((await load().catch(() => ({ domains: {} as any }))) as any, process.env as any);
640
- return okCarrier({
641
- configured: true,
642
- source: target.source,
643
- bucket: target.config.bucket,
644
- prefix: target.config.prefix,
645
- // Non-secret snapshot for the config form (never secret material).
646
- r2: { provider: target.config.provider, endpoint: target.config.endpoint, region: target.config.region, bucket: target.config.bucket, prefix: target.config.prefix },
647
- lastManifest: head ? head.key : null,
648
- eligible: { md: bsvc.listEligibleFiles().filter((p: string) => p.endsWith('.md')).length, sessions: bsvc.listEligibleFiles().filter((p: string) => p.endsWith('.jsonl.zstd')).length },
649
- });
650
- } catch (e: any) {
651
- return okCarrier({ configured: false, source: 'none', bucket: '', prefix: '', lastManifest: null, eligible: { md: 0, sessions: 0 }, error: e?.message ?? String(e) });
652
- }
653
- }
654
- case 'backupPreview': {
655
- const r = await (await makeBackupService()).preview();
656
- return okCarrier({ previewId: r.previewId, revision: r.revision, expiresAt: r.expiresAt, summary: r.summary });
657
- }
658
- case 'backupApply': {
659
- const { previewId, confirm } = (args ?? {}) as any;
660
- if (confirm !== true) return failCarrier('backup apply requires confirm:true', 'maestro-sync/confirm');
661
- const r = await (await makeBackupService()).apply({ previewId, confirm: true });
662
- return r.ok ? okCarrier({ ok: true, committed: r.committed, failures: r.failures }) : failCarrier('backup apply failed', 'maestro-sync/backup', { failures: r.failures } as any);
663
- }
664
- case 'restorePreview': {
665
- const mode = (args as any)?.mode === 'new-dir' ? 'new-dir' : 'in-place';
666
- const r = await (await makeBackupService()).restorePreview({ mode });
667
- return okCarrier(r);
668
- }
669
- case 'restoreApply': {
670
- const { previewId, mode, destDir, confirm } = (args ?? {}) as any;
671
- if (confirm !== true) return failCarrier('restore apply requires confirm:true', 'maestro-sync/confirm');
672
- const r = await (await makeBackupService()).restoreApply({ previewId, mode, destDir, confirm: true });
673
- return r.ok ? okCarrier({ ok: true, committed: r.committed, failures: r.failures }) : failCarrier('restore apply failed', 'maestro-sync/restore', { failures: r.failures } as any);
674
- }
675
- case 'backupGcPreview': {
676
- const r = await (await makeBackupService()).gcPreview({});
677
- return okCarrier(r);
678
- }
679
- case 'backupGcApply': {
680
- const { previewId, confirm } = (args ?? {}) as any;
681
- if (confirm !== true) return failCarrier('gc apply requires confirm:true', 'maestro-sync/confirm');
682
- const r = await (await makeBackupService()).gcApply({ previewId, confirm: true });
683
- return okCarrier(r);
684
- }
685
- default:
686
- return failCarrier('unknown method: ' + String(method));
687
- }
688
- } catch (e: any) {
689
- const details: Record<string, unknown> = {};
690
- if (e?.phase) details.phase = e?.phase;
691
- return failCarrier(e?.message ?? String(e), e?.code ?? 'maestro-sync/rpc', details);
692
- }
693
- },
694
- ),
695
- );
696
- },
697
- };