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