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