opencode-github-sync 3.1.0 → 3.2.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 (104) hide show
  1. package/README.md +340 -219
  2. package/README.zh-CN.md +242 -198
  3. package/dist/cli/app.d.ts +39 -0
  4. package/dist/cli/app.d.ts.map +1 -0
  5. package/dist/cli/app.js +179 -0
  6. package/dist/cli/app.js.map +1 -0
  7. package/dist/cli/args.d.ts +10 -0
  8. package/dist/cli/args.d.ts.map +1 -0
  9. package/dist/cli/args.js +39 -0
  10. package/dist/cli/args.js.map +1 -0
  11. package/dist/cli/i18n.d.ts +368 -0
  12. package/dist/cli/i18n.d.ts.map +1 -0
  13. package/dist/cli/i18n.js +773 -0
  14. package/dist/cli/i18n.js.map +1 -0
  15. package/dist/cli/index.js +312 -114
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/cli/menu.d.ts +52 -0
  18. package/dist/cli/menu.d.ts.map +1 -0
  19. package/dist/cli/menu.js +1126 -0
  20. package/dist/cli/menu.js.map +1 -0
  21. package/dist/cli/render.d.ts +3 -0
  22. package/dist/cli/render.d.ts.map +1 -1
  23. package/dist/cli/render.js +6 -1
  24. package/dist/cli/render.js.map +1 -1
  25. package/dist/cli/ui.d.ts +62 -0
  26. package/dist/cli/ui.d.ts.map +1 -0
  27. package/dist/cli/ui.js +383 -0
  28. package/dist/cli/ui.js.map +1 -0
  29. package/dist/core/autosync.d.ts +134 -0
  30. package/dist/core/autosync.d.ts.map +1 -0
  31. package/dist/core/autosync.js +507 -0
  32. package/dist/core/autosync.js.map +1 -0
  33. package/dist/core/bundle.d.ts +11 -0
  34. package/dist/core/bundle.d.ts.map +1 -0
  35. package/dist/core/bundle.js +87 -0
  36. package/dist/core/bundle.js.map +1 -0
  37. package/dist/core/categories.d.ts +37 -0
  38. package/dist/core/categories.d.ts.map +1 -0
  39. package/dist/core/categories.js +115 -0
  40. package/dist/core/categories.js.map +1 -0
  41. package/dist/core/compare.d.ts +21 -0
  42. package/dist/core/compare.d.ts.map +1 -0
  43. package/dist/core/compare.js +124 -0
  44. package/dist/core/compare.js.map +1 -0
  45. package/dist/core/env.d.ts +16 -0
  46. package/dist/core/env.d.ts.map +1 -0
  47. package/dist/core/env.js +47 -0
  48. package/dist/core/env.js.map +1 -0
  49. package/dist/core/git.d.ts +6 -0
  50. package/dist/core/git.d.ts.map +1 -1
  51. package/dist/core/git.js +44 -4
  52. package/dist/core/git.js.map +1 -1
  53. package/dist/core/guard.d.ts +36 -0
  54. package/dist/core/guard.d.ts.map +1 -0
  55. package/dist/core/guard.js +65 -0
  56. package/dist/core/guard.js.map +1 -0
  57. package/dist/core/history.d.ts +38 -0
  58. package/dist/core/history.d.ts.map +1 -0
  59. package/dist/core/history.js +98 -0
  60. package/dist/core/history.js.map +1 -0
  61. package/dist/core/index.d.ts +11 -0
  62. package/dist/core/index.d.ts.map +1 -1
  63. package/dist/core/index.js +11 -0
  64. package/dist/core/index.js.map +1 -1
  65. package/dist/core/notify.d.ts +9 -0
  66. package/dist/core/notify.d.ts.map +1 -0
  67. package/dist/core/notify.js +69 -0
  68. package/dist/core/notify.js.map +1 -0
  69. package/dist/core/recovery.d.ts +26 -0
  70. package/dist/core/recovery.d.ts.map +1 -0
  71. package/dist/core/recovery.js +56 -0
  72. package/dist/core/recovery.js.map +1 -0
  73. package/dist/core/repo.d.ts +19 -1
  74. package/dist/core/repo.d.ts.map +1 -1
  75. package/dist/core/repo.js +61 -2
  76. package/dist/core/repo.js.map +1 -1
  77. package/dist/core/scheduler.d.ts +138 -0
  78. package/dist/core/scheduler.d.ts.map +1 -0
  79. package/dist/core/scheduler.js +531 -0
  80. package/dist/core/scheduler.js.map +1 -0
  81. package/dist/core/settings.d.ts +61 -0
  82. package/dist/core/settings.d.ts.map +1 -1
  83. package/dist/core/settings.js +44 -2
  84. package/dist/core/settings.js.map +1 -1
  85. package/dist/core/setup.d.ts +20 -0
  86. package/dist/core/setup.d.ts.map +1 -1
  87. package/dist/core/setup.js +87 -4
  88. package/dist/core/setup.js.map +1 -1
  89. package/dist/core/stage.d.ts +5 -0
  90. package/dist/core/stage.d.ts.map +1 -1
  91. package/dist/core/stage.js +94 -8
  92. package/dist/core/stage.js.map +1 -1
  93. package/dist/core/sync.d.ts +25 -0
  94. package/dist/core/sync.d.ts.map +1 -1
  95. package/dist/core/sync.js +295 -37
  96. package/dist/core/sync.js.map +1 -1
  97. package/dist/core/update.d.ts +21 -0
  98. package/dist/core/update.d.ts.map +1 -0
  99. package/dist/core/update.js +75 -0
  100. package/dist/core/update.js.map +1 -0
  101. package/dist/plugin/index.d.ts.map +1 -1
  102. package/dist/plugin/index.js +4 -3
  103. package/dist/plugin/index.js.map +1 -1
  104. package/package.json +1 -1
@@ -0,0 +1,1126 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { appendLog, readState, tailLog, writeState } from "../core/autosync.js";
5
+ import { redactValue, writeBundle } from "../core/bundle.js";
6
+ import { compareWithRemote } from "../core/compare.js";
7
+ import { setChildProxy } from "../core/env.js";
8
+ import { git } from "../core/git.js";
9
+ import { fileHistory, listDevices, restoreFile, trackedFiles } from "../core/history.js";
10
+ import { hostAlias, sanitizeAlias } from "../core/host.js";
11
+ import { parseJsonc } from "../core/jsonc.js";
12
+ import { withSyncLock } from "../core/lock.js";
13
+ import { findConfigFile, loadOverrides } from "../core/overrides.js";
14
+ import { getRoots } from "../core/paths.js";
15
+ import { listRecovery } from "../core/recovery.js";
16
+ import { CollectingReporter } from "../core/reporter.js";
17
+ import { MIN_AUTOSYNC_INTERVAL, OVERRIDES_TEMPLATE, loadSettings, overridesPath, repoBranch, repoUrl, saveSettings, settingsPath, } from "../core/settings.js";
18
+ import { SetupError, discoverSyncRepos, ghAvailable, githubTargetFromUrl, initSync, isRepoUrl, linkByUrl, linkSync, repoIsPrivate, repoLabel, unlinkSync, } from "../core/setup.js";
19
+ import { sqliteAvailable } from "../core/sqlite.js";
20
+ import { formatBytes, pull, push } from "../core/sync.js";
21
+ import { applyLocalSettings, formatTime, isValidProxy, lastCommitTime, nextRunEstimate, realScheduler, realUpdater, tomorrowMorning, } from "./app.js";
22
+ import { ago, getLang, setLang, t } from "./i18n.js";
23
+ import { banner, changeList, createCliReporter, detail, fail, heading, info, keyValue, ok, outcome, summaryLine, warn, write, } from "./render.js";
24
+ import { paint, style } from "./theme.js";
25
+ // ── Entry ───────────────────────────────────────────────────────────────────
26
+ export async function runMenu(deps) {
27
+ const ctx = {
28
+ ui: deps.ui,
29
+ roots: deps.roots ?? getRoots(),
30
+ scheduler: deps.scheduler ?? realScheduler,
31
+ updater: deps.updater ?? realUpdater,
32
+ openEditor: deps.openEditor ?? defaultEditor,
33
+ now: deps.now ?? Date.now,
34
+ cwd: deps.cwd ?? process.cwd(),
35
+ discover: deps.discover ?? defaultDiscover,
36
+ };
37
+ if (!repoUrl(settings(ctx))) {
38
+ const next = await firstRun(ctx);
39
+ if (next === "exit")
40
+ return;
41
+ }
42
+ for (;;) {
43
+ const s = settings(ctx);
44
+ header(ctx, s);
45
+ const choice = await ctx.ui.select("", [
46
+ { value: "sync", label: t("menuSync"), key: "1" },
47
+ { value: "what", label: t("menuWhat"), key: "2" },
48
+ { value: "auto", label: t("menuAutosync"), key: "3" },
49
+ { value: "update", label: t("menuUpdate"), key: "4" },
50
+ { value: "overrides", label: t("menuOverrides"), key: "5" },
51
+ { value: "diag", label: t("menuDiagnostics"), key: "6" },
52
+ { value: "danger", label: t("menuDanger"), key: "7" },
53
+ { value: "uninstall", label: t("menuUninstall"), key: "8" },
54
+ { value: "proxy", label: t("menuProxy"), key: "p" },
55
+ { value: "restore", label: t("menuRestore"), key: "r" },
56
+ { value: "devices", label: t("menuDevices"), key: "d" },
57
+ { value: "guard", label: t("menuGuard"), key: "g" },
58
+ { value: "lang", label: t("menuLanguage"), key: "l" },
59
+ { value: "quit", label: t("quit"), key: "q" },
60
+ ]);
61
+ if (choice === undefined || choice === "quit")
62
+ return;
63
+ const next = await dispatch(ctx, choice);
64
+ if (next === "exit")
65
+ return;
66
+ }
67
+ }
68
+ async function dispatch(ctx, choice) {
69
+ try {
70
+ switch (choice) {
71
+ case "sync":
72
+ return await syncMenu(ctx);
73
+ case "what":
74
+ return await whatMenu(ctx);
75
+ case "auto":
76
+ return await autosyncMenu(ctx);
77
+ case "update":
78
+ return await updateMenu(ctx);
79
+ case "overrides":
80
+ return await overridesMenu(ctx);
81
+ case "diag":
82
+ return await diagnosticsMenu(ctx);
83
+ case "danger":
84
+ return await dangerMenu(ctx);
85
+ case "uninstall":
86
+ return await uninstallMenu(ctx);
87
+ case "proxy":
88
+ return await proxyMenu(ctx);
89
+ case "restore":
90
+ return await restoreMenu(ctx);
91
+ case "devices":
92
+ return await devicesMenu(ctx);
93
+ case "guard":
94
+ return await guardMenu(ctx);
95
+ case "lang":
96
+ return await languageMenu(ctx);
97
+ }
98
+ }
99
+ catch (error) {
100
+ write();
101
+ fail(error.message);
102
+ write();
103
+ await ctx.ui.pause(t("pressKey"));
104
+ }
105
+ return "stay";
106
+ }
107
+ function settings(ctx) {
108
+ return loadSettings(ctx.roots.config);
109
+ }
110
+ function save(ctx, mutate) {
111
+ const s = settings(ctx);
112
+ mutate(s);
113
+ saveSettings(s, ctx.roots.config);
114
+ return s;
115
+ }
116
+ function onOff(value) {
117
+ return value ? paint(t("on"), style.green) : paint(t("off"), style.muted);
118
+ }
119
+ // ── Header ──────────────────────────────────────────────────────────────────
120
+ function header(ctx, s) {
121
+ banner();
122
+ keyValue(t("hdrRepo"), paint(repoLabel(s) ?? "-", style.text));
123
+ keyValue(t("hdrMachine"), paint(hostAlias(s.machineAlias), style.text));
124
+ const last = lastCommitTime(ctx.roots);
125
+ keyValue(t("hdrLastSync"), last ? `${formatTime(last)} ${paint(ago(last, ctx.now()), style.faint)}` : t("never"));
126
+ const now = ctx.now();
127
+ let auto = paint(t("off"), style.muted);
128
+ if (s.autosync.enabled) {
129
+ if (s.autosync.pausedUntil > now) {
130
+ auto = paint(t("hdrAutosyncPaused", { time: formatTime(s.autosync.pausedUntil) }), style.yellow);
131
+ }
132
+ else {
133
+ const next = nextRunEstimate(ctx.roots, s, now);
134
+ const nextText = next
135
+ ? t("inMinutes", { n: Math.max(1, Math.round((next - now) / 60000)) })
136
+ : t("soon");
137
+ auto = paint(t("hdrAutosyncOn", { n: s.autosync.intervalMinutes, next: nextText }), style.green);
138
+ }
139
+ }
140
+ keyValue(t("hdrAutosync"), auto);
141
+ const state = readState(ctx.roots);
142
+ if (state.lastError && state.lastFailureAt) {
143
+ const failures = state.consecutiveFailures ?? 0;
144
+ keyValue(t("hdrLastFailure"), paint(`${ago(state.lastFailureAt, now)} · ${t("hdrFailures", { n: failures, error: truncate(state.lastError, 60) })}`, style.red));
145
+ }
146
+ write();
147
+ }
148
+ function truncate(text, max) {
149
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
150
+ }
151
+ // ── First run ───────────────────────────────────────────────────────────────
152
+ async function firstRun(ctx) {
153
+ banner();
154
+ info(t("firstTitle"));
155
+ write();
156
+ const mode = await ctx.ui.select("", [
157
+ { value: "cli", label: t("firstInstallOnly"), key: "1" },
158
+ { value: "link", label: t("firstLink"), key: "2" },
159
+ { value: "primary", label: t("firstPrimary"), key: "3", hint: t("recommended") },
160
+ { value: "quit", label: t("quit"), key: "q" },
161
+ ]);
162
+ if (mode === undefined || mode === "quit")
163
+ return "exit";
164
+ if (mode === "cli") {
165
+ ok(t("installOnlyDone"));
166
+ write();
167
+ return "exit";
168
+ }
169
+ const linked = await linkFlow(ctx);
170
+ if (!linked)
171
+ return "exit";
172
+ const resolved = await resolveFirstSync(ctx);
173
+ if (!resolved)
174
+ return "exit";
175
+ if (mode === "primary")
176
+ await enableAutosync(ctx);
177
+ return "stay";
178
+ }
179
+ async function linkFlow(ctx) {
180
+ const how = await ctx.ui.select(t("linkTitle"), [
181
+ { value: "create", label: t("linkCreate"), key: "1" },
182
+ { value: "existing", label: t("linkExisting"), key: "2" },
183
+ { value: "back", label: t("back"), key: "b" },
184
+ ]);
185
+ if (how === undefined || how === "back")
186
+ return false;
187
+ const reporter = createCliReporter();
188
+ if (how === "create") {
189
+ if (!ghAvailable()) {
190
+ warn(t("linkNeedGh"));
191
+ return false;
192
+ }
193
+ const name = await ctx.ui.text(t("linkAskName"), "my-opencode-config");
194
+ if (name === undefined)
195
+ return false;
196
+ const result = initSync({ repo: name, reporter, roots: ctx.roots });
197
+ ok(t("linkDone", { repo: `${result.target.owner}/${result.target.name}` }));
198
+ return true;
199
+ }
200
+ let target;
201
+ const found = safe(() => ctx.discover(), []);
202
+ if (found.length > 0) {
203
+ const choices = found.slice(0, 9).map((r, i) => ({
204
+ value: r,
205
+ label: r,
206
+ key: String(i + 1),
207
+ }));
208
+ choices.push({ value: "", label: t("linkOther"), key: "o" });
209
+ target = await ctx.ui.select(t("linkFound"), choices);
210
+ if (target === undefined)
211
+ return false;
212
+ }
213
+ if (!target) {
214
+ target = await ctx.ui.text(t("linkAskExisting"));
215
+ if (!target)
216
+ return false;
217
+ }
218
+ const result = isRepoUrl(target)
219
+ ? linkByUrl({ url: target, reporter, roots: ctx.roots })
220
+ : linkSync({ repo: target, reporter, roots: ctx.roots });
221
+ ok(t("linkDone", {
222
+ repo: result.target.owner ? `${result.target.owner}/${result.target.name}` : target,
223
+ }));
224
+ return true;
225
+ }
226
+ function safe(fn, fallback) {
227
+ try {
228
+ return fn();
229
+ }
230
+ catch {
231
+ return fallback;
232
+ }
233
+ }
234
+ function defaultDiscover() {
235
+ return ghAvailable() ? discoverSyncRepos() : [];
236
+ }
237
+ /**
238
+ * The first sync on a newly linked machine. When the repository and the
239
+ * machine differ the user picks a side; nothing is replaced silently.
240
+ */
241
+ async function resolveFirstSync(ctx, prefer) {
242
+ const s = settings(ctx);
243
+ const remote = repoUrl(s);
244
+ if (fs.existsSync(path.join(ctx.roots.config, ".git"))) {
245
+ // Already a working copy (re-link): an ordinary sync handles it.
246
+ await runSync(ctx, "both");
247
+ return true;
248
+ }
249
+ const comparison = compareWithRemote(ctx.roots.config, remote, repoBranch(s), s.guard.skipDirs);
250
+ if (comparison.empty) {
251
+ info(t("resolveEmpty"));
252
+ await runSync(ctx, "push");
253
+ return true;
254
+ }
255
+ if (comparison.differences.length === 0) {
256
+ info(t("resolveSame"));
257
+ await runSync(ctx, "receive");
258
+ return true;
259
+ }
260
+ for (;;) {
261
+ let choice = prefer;
262
+ if (!choice) {
263
+ write();
264
+ warn(t("resolveTitle", { n: comparison.differences.length }));
265
+ choice = await ctx.ui.select("", [
266
+ { value: "repo", label: t("resolveRepo"), key: "1" },
267
+ { value: "local", label: t("resolveLocal"), key: "2" },
268
+ { value: "diff", label: t("resolveDiff"), key: "3" },
269
+ { value: "back", label: t("back"), key: "b" },
270
+ ]);
271
+ }
272
+ if (choice === undefined || choice === "back")
273
+ return false;
274
+ if (choice === "diff") {
275
+ const labels = {
276
+ onlyLocal: "diffOnlyHere",
277
+ different: "diffDifferent",
278
+ onlyRemote: "diffOnlyRepo",
279
+ };
280
+ for (const d of comparison.differences.slice(0, 40)) {
281
+ detail(`${paint(t(labels[d.kind]).padEnd(12), style.yellow)} ${d.path}`);
282
+ }
283
+ if (comparison.differences.length > 40) {
284
+ detail(t("diffMore", { n: comparison.differences.length - 40 }));
285
+ }
286
+ continue;
287
+ }
288
+ if (choice === "repo") {
289
+ await runSync(ctx, "receive");
290
+ const latest = listRecovery(ctx.roots)[0];
291
+ if (latest)
292
+ info(t("recoverySaved", { dir: latest }));
293
+ return true;
294
+ }
295
+ await runSync(ctx, "push", { adopt: "local" });
296
+ return true;
297
+ }
298
+ }
299
+ // ── Sync ────────────────────────────────────────────────────────────────────
300
+ async function syncMenu(ctx) {
301
+ const choice = await ctx.ui.select(t("syncTitle"), [
302
+ { value: "both", label: t("syncBoth"), key: "1" },
303
+ { value: "receive", label: t("syncReceive"), key: "2" },
304
+ { value: "push", label: t("syncPush"), key: "3" },
305
+ { value: "preview", label: t("syncPreview"), key: "4" },
306
+ { value: "back", label: t("back"), key: "b" },
307
+ ]);
308
+ if (choice === undefined || choice === "back")
309
+ return "stay";
310
+ if (choice === "preview") {
311
+ const go = await preview(ctx);
312
+ if (go)
313
+ await runSync(ctx, "both");
314
+ }
315
+ else {
316
+ await runSync(ctx, choice);
317
+ }
318
+ await ctx.ui.pause(t("pressKey"));
319
+ return "stay";
320
+ }
321
+ async function confirmLarge(ctx, report) {
322
+ const limits = settings(ctx).guard;
323
+ write();
324
+ warn(t("largeTitle"));
325
+ if (report.reasons.includes("files"))
326
+ detail(t("largeFiles", { n: report.addedFiles, limit: limits.maxFiles }));
327
+ if (report.reasons.includes("bytes")) {
328
+ detail(t("largeBytes", {
329
+ size: formatBytes(report.totalBytes),
330
+ limit: formatBytes(limits.maxBytes),
331
+ }));
332
+ }
333
+ for (const f of report.oversized.slice(0, 5)) {
334
+ detail(t("largeFile", {
335
+ path: f.path,
336
+ size: formatBytes(f.bytes),
337
+ limit: formatBytes(limits.maxFileBytes),
338
+ }));
339
+ }
340
+ return ctx.ui.confirm(t("largeConfirm"), false);
341
+ }
342
+ async function runSync(ctx, mode, extra = {}) {
343
+ const results = [];
344
+ const reporter = createCliReporter();
345
+ await withSyncLock(ctx.roots.config, { waitMs: 60_000 }, async () => {
346
+ if (mode !== "receive") {
347
+ try {
348
+ results.push(await push({
349
+ roots: ctx.roots,
350
+ reporter,
351
+ force: extra.force,
352
+ adopt: extra.adopt,
353
+ confirmLarge: (r) => confirmLarge(ctx, r),
354
+ }));
355
+ }
356
+ catch (error) {
357
+ if (error.name === "LargeChangeError") {
358
+ warn(t("largeRefused"));
359
+ return;
360
+ }
361
+ throw error;
362
+ }
363
+ }
364
+ if (mode !== "push") {
365
+ results.push(await pull({ roots: ctx.roots, reporter, force: mode === "receive" && extra.force }));
366
+ }
367
+ });
368
+ for (const r of results)
369
+ outcome(r.message, r.changed);
370
+ if (results.some((r) => r.restartRequired && r.changed))
371
+ info(t("restartHint"));
372
+ return results;
373
+ }
374
+ async function preview(ctx) {
375
+ const reporter = new CollectingReporter();
376
+ const out = await withSyncLock(ctx.roots.config, { waitMs: 60_000 }, () => push({ roots: ctx.roots, reporter, dryRun: true }));
377
+ let incoming;
378
+ try {
379
+ incoming = await withSyncLock(ctx.roots.config, { waitMs: 60_000 }, () => pull({ roots: ctx.roots, reporter, dryRun: true }));
380
+ }
381
+ catch {
382
+ incoming = undefined;
383
+ }
384
+ const outFiles = out.files;
385
+ const inFiles = incoming?.files ?? [];
386
+ if (outFiles.length === 0 && inFiles.length === 0) {
387
+ ok(t("previewNothing"));
388
+ return false;
389
+ }
390
+ if (outFiles.length > 0) {
391
+ heading(t("previewOutgoing", { n: outFiles.length }));
392
+ write(` ${summaryLine(out.summary)}`);
393
+ changeList(outFiles);
394
+ }
395
+ if (inFiles.length > 0 && incoming) {
396
+ heading(t("previewIncoming", { n: inFiles.length }));
397
+ write(` ${summaryLine(incoming.summary)}`);
398
+ changeList(inFiles);
399
+ }
400
+ write();
401
+ return ctx.ui.confirm(t("previewConfirm"), true);
402
+ }
403
+ async function whatMenu(ctx) {
404
+ for (;;) {
405
+ const choice = await ctx.ui.select(t("whatTitle"), [
406
+ { value: "cats", label: t("whatCategories"), key: "1" },
407
+ { value: "sessions", label: t("whatSessions"), key: "2" },
408
+ { value: "extra", label: t("whatExtra"), key: "3" },
409
+ { value: "back", label: t("back"), key: "b" },
410
+ ]);
411
+ if (choice === undefined || choice === "back")
412
+ return "stay";
413
+ if (choice === "cats")
414
+ await categoriesMenu(ctx);
415
+ if (choice === "sessions")
416
+ await sessionSettings(ctx);
417
+ if (choice === "extra")
418
+ await extraPathsMenu(ctx);
419
+ }
420
+ }
421
+ /** Whether the linked repository is confirmed private, public, or unknown. */
422
+ function repoVisibility(s) {
423
+ const target = s.repo.owner && s.repo.name
424
+ ? { owner: s.repo.owner, name: s.repo.name }
425
+ : s.repo.url
426
+ ? githubTargetFromUrl(s.repo.url)
427
+ : undefined;
428
+ if (!target || !ghAvailable())
429
+ return "unknown";
430
+ return repoIsPrivate(target) ? "private" : "public";
431
+ }
432
+ async function categoriesMenu(ctx) {
433
+ const s = settings(ctx);
434
+ const choices = [
435
+ { value: "config", label: t("catConfig") },
436
+ { value: "instructions", label: t("catInstructions") },
437
+ { value: "agents", label: t("catAgents") },
438
+ { value: "commands", label: t("catCommands") },
439
+ { value: "plugins", label: t("catPlugins") },
440
+ { value: "skills", label: t("catSkills") },
441
+ { value: "credentials", label: t("catCredentials") },
442
+ { value: "sessions", label: t("catSessions") },
443
+ ];
444
+ const selected = new Set();
445
+ for (const key of ["config", "instructions", "agents", "commands", "plugins"]) {
446
+ if (s.categories[key])
447
+ selected.add(key);
448
+ }
449
+ if (s.includeSkills)
450
+ selected.add("skills");
451
+ if (s.includeCredentials)
452
+ selected.add("credentials");
453
+ if (s.sessions.enabled)
454
+ selected.add("sessions");
455
+ const footer = ctx.ui.io.interactive ? t("checkboxKeys") : t("checkboxLines");
456
+ const result = await ctx.ui.checkbox(t("whatCategories"), choices, selected, footer);
457
+ if (!result) {
458
+ info(t("cancelled"));
459
+ return;
460
+ }
461
+ // Credentials and sessions are private data: never to a public repository.
462
+ for (const sensitive of ["credentials", "sessions"]) {
463
+ if (!result.has(sensitive) || selected.has(sensitive))
464
+ continue;
465
+ const visibility = repoVisibility(s);
466
+ if (visibility === "public") {
467
+ fail(t("credPublic"));
468
+ result.delete(sensitive);
469
+ continue;
470
+ }
471
+ if (visibility === "unknown") {
472
+ warn(t("credUnverified"));
473
+ if (!(await ctx.ui.confirm(t("credConfirm"), false)))
474
+ result.delete(sensitive);
475
+ }
476
+ if (sensitive === "sessions" && result.has("sessions")) {
477
+ warn(t("sessionsWarn"));
478
+ if (!(await sqliteAvailable()))
479
+ warn(t("sessionsNeedNode"));
480
+ }
481
+ }
482
+ save(ctx, (n) => {
483
+ for (const key of ["config", "instructions", "agents", "commands", "plugins"]) {
484
+ n.categories[key] = result.has(key);
485
+ }
486
+ n.includeSkills = result.has("skills");
487
+ n.includeCredentials = result.has("credentials");
488
+ n.sessions.enabled = result.has("sessions");
489
+ });
490
+ ok(t("saved"));
491
+ }
492
+ async function askNumber(ctx, question, current, min = 1) {
493
+ const answer = await ctx.ui.text(question, String(current));
494
+ if (answer === undefined)
495
+ return undefined;
496
+ const value = Number(answer);
497
+ if (!Number.isFinite(value) || value < min) {
498
+ warn(t("invalidValue", { value: answer }));
499
+ return undefined;
500
+ }
501
+ return value;
502
+ }
503
+ async function sessionSettings(ctx) {
504
+ const s = settings(ctx);
505
+ warn(t("sessionsWarn"));
506
+ const days = await askNumber(ctx, t("sessionsDays"), s.sessions.days);
507
+ if (days === undefined)
508
+ return;
509
+ const max = await askNumber(ctx, t("sessionsMax"), s.sessions.maxSessions);
510
+ if (max === undefined)
511
+ return;
512
+ const mb = await askNumber(ctx, t("sessionsMb"), Math.round(s.sessions.maxSessionBytes / 1048576));
513
+ if (mb === undefined)
514
+ return;
515
+ save(ctx, (n) => {
516
+ n.sessions.days = Math.floor(days);
517
+ n.sessions.maxSessions = Math.floor(max);
518
+ n.sessions.maxSessionBytes = Math.floor(mb * 1048576);
519
+ });
520
+ ok(t("saved"));
521
+ }
522
+ async function extraPathsMenu(ctx) {
523
+ for (;;) {
524
+ const s = settings(ctx);
525
+ if (s.extraPaths.length === 0)
526
+ detail(t("extraEmpty"));
527
+ const choices = [{ value: "+add", label: t("extraAdd"), key: "a" }];
528
+ s.extraPaths.forEach((p, i) => choices.push({ value: p, label: t("extraRemove", { path: p }), key: String(i + 1) }));
529
+ choices.push({ value: "+back", label: t("back"), key: "b" });
530
+ const choice = await ctx.ui.select(t("extraTitle"), choices);
531
+ if (choice === undefined || choice === "+back")
532
+ return;
533
+ if (choice === "+add") {
534
+ const value = await ctx.ui.text(t("extraAsk"));
535
+ if (!value)
536
+ continue;
537
+ save(ctx, (n) => {
538
+ if (!n.extraPaths.includes(value))
539
+ n.extraPaths.push(value);
540
+ });
541
+ ok(t("saved"));
542
+ }
543
+ else {
544
+ save(ctx, (n) => {
545
+ n.extraPaths = n.extraPaths.filter((p) => p !== choice);
546
+ });
547
+ ok(t("saved"));
548
+ }
549
+ }
550
+ }
551
+ // ── Autosync ────────────────────────────────────────────────────────────────
552
+ export async function enableAutosync(ctx) {
553
+ const s = loadSettings(ctx.roots.config);
554
+ s.autosync.enabled = true;
555
+ saveSettings(s, ctx.roots.config);
556
+ const result = ctx.scheduler.install(ctx.roots, s);
557
+ if (!result.ok) {
558
+ fail(t("autoInstallFailed", { error: result.detail.join("; ") }));
559
+ return false;
560
+ }
561
+ for (const w of result.warnings)
562
+ warn(t("autoWarning", { text: w }));
563
+ ok(t("autoOn", { n: s.autosync.intervalMinutes }));
564
+ return true;
565
+ }
566
+ export function disableAutosync(ctx) {
567
+ const s = loadSettings(ctx.roots.config);
568
+ s.autosync.enabled = false;
569
+ saveSettings(s, ctx.roots.config);
570
+ ctx.scheduler.uninstall(ctx.roots);
571
+ ok(t("autoOff"));
572
+ }
573
+ async function autosyncMenu(ctx) {
574
+ for (;;) {
575
+ const s = settings(ctx);
576
+ const choice = await ctx.ui.select(t("autoTitle"), [
577
+ s.autosync.enabled
578
+ ? { value: "off", label: t("autoTurnOff"), key: "1" }
579
+ : { value: "on", label: t("autoTurnOn"), key: "1" },
580
+ { value: "interval", label: t("autoInterval", { n: s.autosync.intervalMinutes }), key: "2" },
581
+ {
582
+ value: "loggedoff",
583
+ label: t("autoLoggedOff", { state: onOff(s.autosync.runWhenLoggedOff) }),
584
+ key: "3",
585
+ },
586
+ { value: "pause", label: t("autoPause"), key: "4" },
587
+ {
588
+ value: "notify",
589
+ label: t("autoNotifications", { state: onOff(s.notifications) }),
590
+ key: "5",
591
+ },
592
+ { value: "reset", label: t("autoReset"), key: "6" },
593
+ { value: "back", label: t("back"), key: "b" },
594
+ ]);
595
+ if (choice === undefined || choice === "back")
596
+ return "stay";
597
+ if (choice === "on")
598
+ await enableAutosync(ctx);
599
+ if (choice === "off")
600
+ disableAutosync(ctx);
601
+ if (choice === "interval")
602
+ await intervalMenu(ctx);
603
+ if (choice === "loggedoff")
604
+ await loggedOffMenu(ctx);
605
+ if (choice === "pause")
606
+ await pauseMenu(ctx);
607
+ if (choice === "notify") {
608
+ save(ctx, (n) => {
609
+ n.notifications = !n.notifications;
610
+ });
611
+ ok(t("saved"));
612
+ }
613
+ if (choice === "reset") {
614
+ const before = readState(ctx.roots).consecutiveFailures ?? 0;
615
+ writeState(ctx.roots, {
616
+ consecutiveFailures: 0,
617
+ lastError: null,
618
+ failureNotifiedAt: null,
619
+ lastAttemptAt: 0,
620
+ });
621
+ ok(t("resetDone", { n: before }));
622
+ }
623
+ }
624
+ }
625
+ async function intervalMenu(ctx) {
626
+ const presets = [5, 10, 15, 30, 60];
627
+ const choices = presets.map((n, i) => ({
628
+ value: n,
629
+ label: t("intervalMinutes", { n }),
630
+ key: String(i + 1),
631
+ }));
632
+ choices.push({ value: -1, label: t("intervalCustom"), key: "c" });
633
+ let minutes = await ctx.ui.select(t("intervalAsk"), choices);
634
+ if (minutes === undefined)
635
+ return;
636
+ if (minutes === -1) {
637
+ const custom = await askNumber(ctx, t("intervalAsk"), settings(ctx).autosync.intervalMinutes, MIN_AUTOSYNC_INTERVAL);
638
+ if (custom === undefined)
639
+ return;
640
+ minutes = Math.floor(custom);
641
+ }
642
+ const s = save(ctx, (n) => {
643
+ n.autosync.intervalMinutes = minutes;
644
+ });
645
+ if (s.autosync.enabled)
646
+ await enableAutosync(ctx);
647
+ else
648
+ ok(t("saved"));
649
+ }
650
+ async function loggedOffMenu(ctx) {
651
+ if (process.platform !== "win32") {
652
+ info(t("notWindows"));
653
+ }
654
+ info(t("loggedOffExplain"));
655
+ const s = save(ctx, (n) => {
656
+ n.autosync.runWhenLoggedOff = !n.autosync.runWhenLoggedOff;
657
+ });
658
+ ok(t("autoLoggedOff", { state: onOff(s.autosync.runWhenLoggedOff) }));
659
+ if (s.autosync.runWhenLoggedOff && process.platform === "win32" && !ctx.scheduler.elevated()) {
660
+ warn(t("loggedOffNeedAdmin"));
661
+ return;
662
+ }
663
+ if (s.autosync.enabled)
664
+ await enableAutosync(ctx);
665
+ }
666
+ async function pauseMenu(ctx) {
667
+ const now = ctx.now();
668
+ const choice = await ctx.ui.select(t("autoPause"), [
669
+ { value: now + 3600_000, label: t("pause1h"), key: "1" },
670
+ { value: now + 4 * 3600_000, label: t("pause4h"), key: "2" },
671
+ { value: tomorrowMorning(now), label: t("pauseTomorrow"), key: "3" },
672
+ { value: 0, label: t("pauseResume"), key: "4" },
673
+ ]);
674
+ if (choice === undefined)
675
+ return;
676
+ save(ctx, (n) => {
677
+ n.autosync.pausedUntil = choice;
678
+ });
679
+ ok(choice ? t("pausedUntil", { time: formatTime(choice) }) : t("resumed"));
680
+ }
681
+ // ── Update ──────────────────────────────────────────────────────────────────
682
+ async function updateMenu(ctx) {
683
+ for (;;) {
684
+ const s = settings(ctx);
685
+ const choice = await ctx.ui.select(t("updTitle"), [
686
+ { value: "check", label: t("updCheck"), key: "1" },
687
+ { value: "upgrade", label: t("updUpgrade"), key: "2" },
688
+ { value: "auto", label: t("updAuto", { state: onOff(s.autosync.autoUpdate) }), key: "3" },
689
+ { value: "back", label: t("back"), key: "b" },
690
+ ]);
691
+ if (choice === undefined || choice === "back")
692
+ return "stay";
693
+ if (choice === "check") {
694
+ const result = ctx.updater.check();
695
+ if (result.error)
696
+ fail(t("updFailed", { error: result.error }));
697
+ else {
698
+ info(t("updVersions", { current: result.current, latest: result.latest ?? "?" }));
699
+ ok(result.newer ? t("updNewer") : t("updLatest"));
700
+ }
701
+ }
702
+ if (choice === "upgrade") {
703
+ info(t("updRunning"));
704
+ ctx.updater.install();
705
+ ok(t("updDone"));
706
+ return "exit";
707
+ }
708
+ if (choice === "auto") {
709
+ save(ctx, (n) => {
710
+ n.autosync.autoUpdate = !n.autosync.autoUpdate;
711
+ });
712
+ ok(t("saved"));
713
+ }
714
+ }
715
+ }
716
+ // ── Overrides ───────────────────────────────────────────────────────────────
717
+ function defaultEditor(file) {
718
+ const editor = process.env.VISUAL || process.env.EDITOR || (process.platform === "win32" ? "notepad.exe" : "");
719
+ if (editor) {
720
+ const result = spawnSync(editor, [file], {
721
+ stdio: "inherit",
722
+ shell: !path.isAbsolute(editor) && /\s/.test(editor),
723
+ });
724
+ return !result.error;
725
+ }
726
+ const opener = process.platform === "darwin" ? "open" : "xdg-open";
727
+ return !spawnSync(opener, [file], { stdio: "ignore" }).error;
728
+ }
729
+ function flatten(value, prefix = "") {
730
+ if (value && typeof value === "object" && !Array.isArray(value)) {
731
+ const entries = Object.entries(value);
732
+ if (entries.length === 0)
733
+ return [[prefix, value]];
734
+ return entries.flatMap(([k, v]) => flatten(v, prefix ? `${prefix}.${k}` : k));
735
+ }
736
+ return [[prefix, value]];
737
+ }
738
+ function lookup(obj, dotted) {
739
+ return dotted
740
+ .split(".")
741
+ .reduce((acc, k) => acc && typeof acc === "object" ? acc[k] : undefined, obj);
742
+ }
743
+ async function overridesMenu(ctx) {
744
+ const file = overridesPath(ctx.roots.config);
745
+ for (;;) {
746
+ const choice = await ctx.ui.select(t("ovTitle"), [
747
+ { value: "open", label: t("ovOpen"), key: "1" },
748
+ { value: "show", label: t("ovShow"), key: "2" },
749
+ { value: "back", label: t("back"), key: "b" },
750
+ ]);
751
+ if (choice === undefined || choice === "back")
752
+ return "stay";
753
+ if (choice === "open") {
754
+ if (!fs.existsSync(file)) {
755
+ fs.mkdirSync(path.dirname(file), { recursive: true });
756
+ fs.writeFileSync(file, OVERRIDES_TEMPLATE);
757
+ }
758
+ if (!ctx.openEditor(file))
759
+ warn(t("ovEditorFailed", { file }));
760
+ }
761
+ if (choice === "show")
762
+ showOverrides(ctx, file);
763
+ }
764
+ }
765
+ function showOverrides(ctx, file) {
766
+ detail(t("ovFile", { file }));
767
+ const overrides = loadOverrides(ctx.roots.config);
768
+ if (Object.keys(overrides).length === 0) {
769
+ info(t("ovNone"));
770
+ return;
771
+ }
772
+ let shared;
773
+ const configFile = findConfigFile(ctx.roots.config);
774
+ if (configFile) {
775
+ const rel = path.relative(ctx.roots.config, configFile).split(path.sep).join("/");
776
+ const head = git(["show", `HEAD:${rel}`], { cwd: ctx.roots.config });
777
+ if (head.ok)
778
+ shared = safe(() => parseJsonc(head.stdout), undefined);
779
+ }
780
+ for (const [key, value] of flatten(overrides)) {
781
+ const before = lookup(shared, key);
782
+ const after = value === null ? paint(t("ovRemoved"), style.red) : paint(JSON.stringify(value), style.green);
783
+ write(` ${paint(key, style.cyan)} ${paint(JSON.stringify(before) ?? "-", style.faint)} → ${after}`);
784
+ }
785
+ }
786
+ // ── Diagnostics ─────────────────────────────────────────────────────────────
787
+ function toolVersion(cmd, args) {
788
+ const result = spawnSync(cmd, args, { encoding: "utf8", timeout: 20_000, windowsHide: true });
789
+ if (result.error || result.status !== 0)
790
+ return undefined;
791
+ return String(result.stdout).split(/\r?\n/)[0]?.trim();
792
+ }
793
+ export function collectDiagnostics(ctx) {
794
+ const rows = [];
795
+ rows.push([t("diagNode"), process.version]);
796
+ const major = Number(process.versions.node.split(".")[0]);
797
+ const minor = Number(process.versions.node.split(".")[1]);
798
+ if (major < 22 || (major === 22 && minor < 5))
799
+ rows.push(["", t("diagSessionsNode")]);
800
+ rows.push([t("diagGit"), toolVersion("git", ["--version"]) ?? t("diagMissing")]);
801
+ rows.push([t("diagGh"), toolVersion("gh", ["--version"]) ?? t("diagMissing")]);
802
+ const s = safe(() => loadSettings(ctx.roots.config), undefined);
803
+ const remote = s ? repoUrl(s) : undefined;
804
+ if (remote) {
805
+ const probe = git(["ls-remote", "--heads", remote], {
806
+ cwd: ctx.roots.config,
807
+ timeoutMs: 60_000,
808
+ });
809
+ rows.push([
810
+ t("diagNetwork"),
811
+ probe.ok
812
+ ? t("diagOk")
813
+ : t("diagFail", { error: (probe.stderr.split("\n")[0] ?? "").slice(0, 120) }),
814
+ ]);
815
+ }
816
+ const sched = safe(() => ctx.scheduler.status(), { installed: false, kind: "none" });
817
+ rows.push([
818
+ t("diagScheduler"),
819
+ sched.installed
820
+ ? `${t("diagRegistered", { kind: sched.kind })}${sched.nextRun ? ` · ${sched.nextRun}` : ""}`
821
+ : t("diagNotRegistered"),
822
+ ]);
823
+ if (fs.existsSync(path.join(ctx.roots.config, ".git"))) {
824
+ const ignored = git(["check-ignore", "-q", "opencode-sync.jsonc"], { cwd: ctx.roots.config });
825
+ rows.push([t("diagSettings"), ignored.ok ? t("diagIgnored") : t("diagNotIgnored")]);
826
+ }
827
+ return rows;
828
+ }
829
+ async function diagnosticsMenu(ctx) {
830
+ heading(t("diagTitle"));
831
+ for (const [k, v] of collectDiagnostics(ctx))
832
+ keyValue(k, v, 20);
833
+ heading(t("diagLog"));
834
+ for (const line of tailLog(ctx.roots, 15))
835
+ detail(line);
836
+ write();
837
+ const choice = await ctx.ui.select("", [
838
+ { value: "bundle", label: t("diagBundle"), key: "1" },
839
+ { value: "back", label: t("back"), key: "b" },
840
+ ]);
841
+ if (choice === "bundle") {
842
+ const file = exportBundle(ctx);
843
+ ok(t("bundleWritten", { file }));
844
+ }
845
+ return "stay";
846
+ }
847
+ export function exportBundle(ctx) {
848
+ const s = safe(() => loadSettings(ctx.roots.config), undefined);
849
+ const entries = [
850
+ {
851
+ name: "diagnostics.txt",
852
+ content: collectDiagnostics(ctx)
853
+ .map(([k, v]) => `${k.padEnd(20)} ${v}`)
854
+ .concat([
855
+ `platform ${process.platform} ${process.arch}`,
856
+ `lang ${getLang()}`,
857
+ ])
858
+ .join("\n"),
859
+ },
860
+ { name: "settings.json", content: JSON.stringify(redactValue(s ?? {}), null, 2) },
861
+ {
862
+ name: "autosync-state.json",
863
+ content: JSON.stringify(redactValue(readState(ctx.roots)), null, 2),
864
+ },
865
+ { name: "autosync.log", content: tailLog(ctx.roots, 400).join("\n") },
866
+ ];
867
+ const gitLog = git(["log", "-20", "--format=%h %cI %s"], { cwd: ctx.roots.config });
868
+ if (gitLog.ok)
869
+ entries.push({ name: "git-log.txt", content: gitLog.stdout });
870
+ const status = git(["status", "--short"], { cwd: ctx.roots.config });
871
+ if (status.ok)
872
+ entries.push({ name: "git-status.txt", content: status.stdout });
873
+ return writeBundle(ctx.cwd, entries);
874
+ }
875
+ // ── Danger zone ─────────────────────────────────────────────────────────────
876
+ const CONFIRM_WORD = "overwrite";
877
+ async function dangerMenu(ctx) {
878
+ const choice = await ctx.ui.select(t("dangerTitle"), [
879
+ { value: "pull", label: t("dangerPull"), key: "1" },
880
+ { value: "push", label: t("dangerPush"), key: "2" },
881
+ { value: "back", label: t("back"), key: "b" },
882
+ ]);
883
+ if (choice === undefined || choice === "back")
884
+ return "stay";
885
+ warn(choice === "pull" ? t("dangerWarnPull") : t("dangerWarnPush"));
886
+ if (!(await ctx.ui.confirmWord(t("dangerType"), CONFIRM_WORD))) {
887
+ info(t("cancelled"));
888
+ return "stay";
889
+ }
890
+ await runSync(ctx, choice === "pull" ? "receive" : "push", { force: true });
891
+ await ctx.ui.pause(t("pressKey"));
892
+ return "stay";
893
+ }
894
+ // ── Uninstall ───────────────────────────────────────────────────────────────
895
+ async function uninstallMenu(ctx) {
896
+ heading(t("unTitle"));
897
+ info(t("unKeep"));
898
+ const removed = ctx.scheduler.uninstall(ctx.roots);
899
+ ok(removed.removed ? t("unSchedulerRemoved") : t("unSchedulerNone"));
900
+ save(ctx, (n) => {
901
+ n.autosync.enabled = false;
902
+ });
903
+ if (await ctx.ui.confirm(t("unUnlink"), false)) {
904
+ unlinkSync(ctx.roots);
905
+ ok(t("unUnlinked"));
906
+ }
907
+ if (await ctx.ui.confirm(t("unNpm"), false)) {
908
+ ctx.updater.uninstall();
909
+ ok(t("unNpmDone"));
910
+ return "exit";
911
+ }
912
+ return repoUrl(settings(ctx)) ? "stay" : "exit";
913
+ }
914
+ // ── Extras ──────────────────────────────────────────────────────────────────
915
+ async function proxyMenu(ctx) {
916
+ const s = settings(ctx);
917
+ info(t("proxyCurrent", { proxy: s.proxy || t("none") }));
918
+ const value = await ctx.ui.text(t("proxyAsk"));
919
+ if (value === undefined)
920
+ return "stay";
921
+ if (value && !isValidProxy(value)) {
922
+ fail(t("proxyInvalid", { value }));
923
+ return "stay";
924
+ }
925
+ const saved = save(ctx, (n) => {
926
+ n.proxy = value;
927
+ });
928
+ applyLocalSettings(saved);
929
+ ok(value ? t("proxySet") : t("proxyCleared"));
930
+ return "stay";
931
+ }
932
+ async function restoreMenu(ctx) {
933
+ const filter = await ctx.ui.text(t("rsAsk"));
934
+ if (filter === undefined)
935
+ return "stay";
936
+ const files = trackedFiles(ctx.roots.config, filter).slice(0, 30);
937
+ if (files.length === 0) {
938
+ warn(t("rsNoMatch"));
939
+ return "stay";
940
+ }
941
+ const file = await ctx.ui.select(t("rsPickFile"), files.map((f, i) => ({ value: f, label: f, key: String(i + 1) })));
942
+ if (!file)
943
+ return "stay";
944
+ const versions = fileHistory(ctx.roots.config, file, 20);
945
+ if (versions.length === 0) {
946
+ warn(t("rsNoHistory"));
947
+ return "stay";
948
+ }
949
+ const commit = await ctx.ui.select(t("rsPickVersion"), versions.map((v, i) => ({
950
+ value: v.commit,
951
+ label: `${formatTime(Date.parse(v.date))} ${v.commit.slice(0, 8)}`,
952
+ hint: v.subject,
953
+ key: String(i + 1),
954
+ })));
955
+ if (!commit)
956
+ return "stay";
957
+ const version = versions.find((v) => v.commit === commit);
958
+ if (!(await ctx.ui.confirm(t("rsConfirm", { file, date: formatTime(Date.parse(version.date)) }), false))) {
959
+ info(t("cancelled"));
960
+ return "stay";
961
+ }
962
+ const result = restoreFile(ctx.roots, file, commit);
963
+ ok(t("rsDone", { file }));
964
+ if (result.recovery)
965
+ info(t("recoverySaved", { dir: result.recovery }));
966
+ if (await ctx.ui.confirm(t("rsPushNow"), false))
967
+ await runSync(ctx, "push");
968
+ return "stay";
969
+ }
970
+ async function devicesMenu(ctx) {
971
+ const s = settings(ctx);
972
+ const me = hostAlias(s.machineAlias);
973
+ const devices = listDevices(ctx.roots.config);
974
+ heading(t("devTitle"));
975
+ if (devices.length === 0)
976
+ detail(t("devNone"));
977
+ for (const d of devices) {
978
+ const when = ago(Date.parse(d.lastSync), ctx.now());
979
+ const tag = d.alias === me ? paint(` (${t("devThis")})`, style.accent) : "";
980
+ write(` ${paint(d.alias.padEnd(24), style.text)} ${paint(t("devRow", { when, n: d.commits }), style.muted)}${tag}`);
981
+ }
982
+ write();
983
+ const choice = await ctx.ui.select("", [
984
+ { value: "rename", label: t("devRename"), key: "1" },
985
+ { value: "back", label: t("back"), key: "b" },
986
+ ]);
987
+ if (choice === "rename") {
988
+ const name = await ctx.ui.text(t("devAsk"), me);
989
+ if (!name)
990
+ return "stay";
991
+ const alias = sanitizeAlias(name);
992
+ save(ctx, (n) => {
993
+ n.machineAlias = alias;
994
+ });
995
+ ok(t("devRenamed", { alias }));
996
+ }
997
+ return "stay";
998
+ }
999
+ async function guardMenu(ctx) {
1000
+ for (;;) {
1001
+ const g = settings(ctx).guard;
1002
+ const choice = await ctx.ui.select(t("guardTitle"), [
1003
+ { value: "files", label: t("guardFiles", { n: g.maxFiles }), key: "1" },
1004
+ { value: "bytes", label: t("guardBytes", { size: formatBytes(g.maxBytes) }), key: "2" },
1005
+ { value: "file", label: t("guardFile", { size: formatBytes(g.maxFileBytes) }), key: "3" },
1006
+ { value: "skip", label: t("guardSkip", { dirs: g.skipDirs.join(", ") }), key: "4" },
1007
+ { value: "back", label: t("back"), key: "b" },
1008
+ ]);
1009
+ if (choice === undefined || choice === "back")
1010
+ return "stay";
1011
+ if (choice === "files") {
1012
+ const n = await askNumber(ctx, t("guardAskNumber"), g.maxFiles);
1013
+ if (n !== undefined) {
1014
+ save(ctx, (s) => {
1015
+ s.guard.maxFiles = Math.floor(n);
1016
+ });
1017
+ }
1018
+ }
1019
+ if (choice === "bytes" || choice === "file") {
1020
+ const key = choice === "bytes" ? "maxBytes" : "maxFileBytes";
1021
+ const n = await askNumber(ctx, t("guardAskMb"), Math.round(g[key] / 1048576));
1022
+ if (n !== undefined) {
1023
+ save(ctx, (s) => {
1024
+ s.guard[key] = Math.floor(n * 1048576);
1025
+ });
1026
+ }
1027
+ }
1028
+ if (choice === "skip") {
1029
+ const value = await ctx.ui.text(t("guardAskSkip"), g.skipDirs.join(", "));
1030
+ if (value !== undefined) {
1031
+ const dirs = value
1032
+ .split(",")
1033
+ .map((d) => d.trim())
1034
+ .filter(Boolean);
1035
+ save(ctx, (s) => {
1036
+ s.guard.skipDirs = dirs;
1037
+ });
1038
+ }
1039
+ }
1040
+ }
1041
+ }
1042
+ async function languageMenu(ctx) {
1043
+ const choice = await ctx.ui.select(t("langTitle"), [
1044
+ { value: "", label: t("langAuto"), key: "1" },
1045
+ { value: "en", label: "English", key: "2" },
1046
+ { value: "zh-CN", label: "简体中文", key: "3" },
1047
+ ]);
1048
+ if (choice === undefined)
1049
+ return "stay";
1050
+ const s = save(ctx, (n) => {
1051
+ n.language = choice;
1052
+ });
1053
+ applyLocalSettings(s);
1054
+ if (choice)
1055
+ setLang(choice);
1056
+ ok(t("langSet"));
1057
+ return "stay";
1058
+ }
1059
+ /**
1060
+ * The non-interactive path the installers call with `--mode`. Mirrors the
1061
+ * first-run menu: link (creating the repository when `gh` can and it does not
1062
+ * exist), resolve the first sync by `prefer`, and with `auto` turn autosync on.
1063
+ */
1064
+ export async function runSetup(flags, deps) {
1065
+ const ctx = {
1066
+ ui: deps.ui,
1067
+ roots: deps.roots ?? getRoots(),
1068
+ scheduler: deps.scheduler ?? realScheduler,
1069
+ updater: deps.updater ?? realUpdater,
1070
+ openEditor: defaultEditor,
1071
+ now: Date.now,
1072
+ cwd: process.cwd(),
1073
+ discover: () => [],
1074
+ };
1075
+ banner();
1076
+ // Local-only preferences go into the settings file once it exists (after
1077
+ // linking); before that they only apply to this process.
1078
+ const applyFlags = () => {
1079
+ if (!fs.existsSync(settingsPath(ctx.roots.config)))
1080
+ return;
1081
+ save(ctx, (s) => {
1082
+ if (flags.lang)
1083
+ s.language = flags.lang;
1084
+ if (flags.proxy !== undefined)
1085
+ s.proxy = flags.proxy;
1086
+ if (flags.interval) {
1087
+ s.autosync.intervalMinutes = Math.max(MIN_AUTOSYNC_INTERVAL, Math.floor(flags.interval));
1088
+ }
1089
+ });
1090
+ };
1091
+ const current = safe(() => settings(ctx), undefined);
1092
+ applyLocalSettings(current && flags.proxy !== undefined ? { ...current, proxy: flags.proxy } : current, flags.lang);
1093
+ if (flags.proxy)
1094
+ setChildProxy(flags.proxy);
1095
+ if (flags.mode === "cli") {
1096
+ applyFlags();
1097
+ ok(t("setupCliOnly"));
1098
+ return;
1099
+ }
1100
+ if (!flags.repo)
1101
+ throw new SetupError(t("setupNeedRepo", { mode: flags.mode }));
1102
+ const reporter = createCliReporter();
1103
+ if (isRepoUrl(flags.repo))
1104
+ linkByUrl({ url: flags.repo, reporter, roots: ctx.roots });
1105
+ else {
1106
+ try {
1107
+ linkSync({ repo: flags.repo, reporter, roots: ctx.roots });
1108
+ }
1109
+ catch (error) {
1110
+ if (!/was not found/.test(error.message))
1111
+ throw error;
1112
+ initSync({ repo: flags.repo, reporter, roots: ctx.roots });
1113
+ }
1114
+ }
1115
+ applyFlags();
1116
+ ok(t("linkDone", { repo: repoLabel(settings(ctx)) ?? flags.repo }));
1117
+ await resolveFirstSync(ctx, flags.prefer ?? "repo");
1118
+ if (flags.mode === "auto") {
1119
+ const enabled = await enableAutosync(ctx);
1120
+ if (!enabled)
1121
+ process.exitCode = 1;
1122
+ }
1123
+ appendLog(ctx.roots, `setup: mode=${flags.mode}`);
1124
+ ok(t("setupDone"));
1125
+ }
1126
+ //# sourceMappingURL=menu.js.map