t3code-session-manager 0.0.0-stage → 0.4.1

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 (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +149 -0
  4. package/LICENSE +21 -0
  5. package/README.md +661 -2
  6. package/README.pt.md +617 -0
  7. package/bin/entry.d.mts +2 -0
  8. package/bin/entry.mjs +19 -0
  9. package/bin/t3sm.mjs +44 -0
  10. package/commands/import.md +30 -0
  11. package/commands/organize.md +36 -0
  12. package/commands/status.md +24 -0
  13. package/commands/sync.md +26 -0
  14. package/dist/apply/apply.js +993 -0
  15. package/dist/apply/claudeWriter.js +168 -0
  16. package/dist/apply/copyTranscript.js +116 -0
  17. package/dist/apply/importer.js +697 -0
  18. package/dist/apply/materialize.js +335 -0
  19. package/dist/apply/waves.js +108 -0
  20. package/dist/assistant/core.js +295 -0
  21. package/dist/assistant/deps.js +256 -0
  22. package/dist/assistant/i18n.js +38 -0
  23. package/dist/assistant/messages.en.js +494 -0
  24. package/dist/assistant/messages.pt.js +495 -0
  25. package/dist/assistant/runner.js +64 -0
  26. package/dist/assistant/steps.js +1362 -0
  27. package/dist/build.json +1 -0
  28. package/dist/cli/applyScreen.js +158 -0
  29. package/dist/cli/commands/accounts.js +254 -0
  30. package/dist/cli/commands/apply.js +199 -0
  31. package/dist/cli/commands/changelog.js +61 -0
  32. package/dist/cli/commands/doctor.js +105 -0
  33. package/dist/cli/commands/help.js +158 -0
  34. package/dist/cli/commands/merge.js +224 -0
  35. package/dist/cli/commands/organize.js +872 -0
  36. package/dist/cli/commands/plan.js +161 -0
  37. package/dist/cli/commands/projects.js +430 -0
  38. package/dist/cli/commands/quarantine.js +203 -0
  39. package/dist/cli/commands/recover.js +230 -0
  40. package/dist/cli/commands/rollback.js +281 -0
  41. package/dist/cli/commands/scan.js +117 -0
  42. package/dist/cli/commands/schedule.js +288 -0
  43. package/dist/cli/commands/start.js +45 -0
  44. package/dist/cli/commands/status.js +615 -0
  45. package/dist/cli/commands/sync.js +336 -0
  46. package/dist/cli/commands/update.js +398 -0
  47. package/dist/cli/errors.js +53 -0
  48. package/dist/cli/failures.js +91 -0
  49. package/dist/cli/flags.js +53 -0
  50. package/dist/cli/help.en.js +549 -0
  51. package/dist/cli/help.pt.js +566 -0
  52. package/dist/cli/helpText.js +211 -0
  53. package/dist/cli/helpTopics.js +58 -0
  54. package/dist/cli/locked.js +12 -0
  55. package/dist/cli/main.js +155 -0
  56. package/dist/cli/screen.js +3 -0
  57. package/dist/cli/ui.js +111 -0
  58. package/dist/cli/words.js +2 -0
  59. package/dist/core/activity.js +16 -0
  60. package/dist/core/changelog.js +47 -0
  61. package/dist/core/config.js +530 -0
  62. package/dist/core/fsutil.js +171 -0
  63. package/dist/core/glob.js +34 -0
  64. package/dist/core/history.js +32 -0
  65. package/dist/core/journal.js +274 -0
  66. package/dist/core/lock.js +337 -0
  67. package/dist/core/mask.js +31 -0
  68. package/dist/core/paths.js +68 -0
  69. package/dist/core/pid.js +101 -0
  70. package/dist/core/run.js +4 -0
  71. package/dist/core/semver.js +18 -0
  72. package/dist/core/sysroot.js +29 -0
  73. package/dist/core/types.js +229 -0
  74. package/dist/core/uuid.js +29 -0
  75. package/dist/core/version.js +72 -0
  76. package/dist/help/convert.md +20 -0
  77. package/dist/help/convert.pt.md +21 -0
  78. package/dist/help/cwd-unreadable.md +22 -0
  79. package/dist/help/cwd-unreadable.pt.md +22 -0
  80. package/dist/help/decisions.md +20 -0
  81. package/dist/help/decisions.pt.md +20 -0
  82. package/dist/help/errors.md +20 -0
  83. package/dist/help/errors.pt.md +22 -0
  84. package/dist/help/held.md +20 -0
  85. package/dist/help/held.pt.md +20 -0
  86. package/dist/help/history.md +27 -0
  87. package/dist/help/history.pt.md +29 -0
  88. package/dist/help/instance-unavailable.md +18 -0
  89. package/dist/help/instance-unavailable.pt.md +19 -0
  90. package/dist/help/not-imported.md +19 -0
  91. package/dist/help/not-imported.pt.md +19 -0
  92. package/dist/help/orphaned.md +19 -0
  93. package/dist/help/orphaned.pt.md +19 -0
  94. package/dist/help/project-mismatch.md +15 -0
  95. package/dist/help/project-mismatch.pt.md +15 -0
  96. package/dist/help/t3-native.md +22 -0
  97. package/dist/help/t3-native.pt.md +22 -0
  98. package/dist/help/updates.md +26 -0
  99. package/dist/help/updates.pt.md +28 -0
  100. package/dist/help/watcher.md +24 -0
  101. package/dist/help/watcher.pt.md +25 -0
  102. package/dist/i18n/cli.js +41 -0
  103. package/dist/i18n/lang.js +55 -0
  104. package/dist/i18n/messages.en.js +1140 -0
  105. package/dist/i18n/messages.pt.js +1149 -0
  106. package/dist/i18n/words.js +12 -0
  107. package/dist/ops/accounts.js +170 -0
  108. package/dist/ops/autoUpdate.js +223 -0
  109. package/dist/ops/discoverAccounts.js +343 -0
  110. package/dist/ops/doctor.js +811 -0
  111. package/dist/ops/elevated.js +47 -0
  112. package/dist/ops/errorCodes.js +39 -0
  113. package/dist/ops/follow.js +558 -0
  114. package/dist/ops/merge.js +830 -0
  115. package/dist/ops/notify.js +249 -0
  116. package/dist/ops/plugin.js +92 -0
  117. package/dist/ops/projects.js +113 -0
  118. package/dist/ops/quarantine.js +415 -0
  119. package/dist/ops/rollback.js +868 -0
  120. package/dist/ops/schedule.js +464 -0
  121. package/dist/ops/successor.js +51 -0
  122. package/dist/ops/sync.js +859 -0
  123. package/dist/ops/syncStatus.js +290 -0
  124. package/dist/ops/update.js +273 -0
  125. package/dist/ops/updater.js +641 -0
  126. package/dist/ops/watch.js +676 -0
  127. package/dist/ops/watcherControl.js +212 -0
  128. package/dist/ops/watcherHealth.js +75 -0
  129. package/dist/organize/apply.js +495 -0
  130. package/dist/organize/history.js +192 -0
  131. package/dist/organize/plan.js +283 -0
  132. package/dist/organize/rename.js +58 -0
  133. package/dist/organize/sessions.js +100 -0
  134. package/dist/organize/titles.js +70 -0
  135. package/dist/organize/types.js +73 -0
  136. package/dist/plan/categories.js +104 -0
  137. package/dist/plan/dedupe.js +137 -0
  138. package/dist/plan/folders.js +82 -0
  139. package/dist/plan/names.js +93 -0
  140. package/dist/plan/ownership.js +316 -0
  141. package/dist/plan/planner.js +669 -0
  142. package/dist/plan/rehome.js +101 -0
  143. package/dist/plan/report.js +407 -0
  144. package/dist/sources/cache.js +89 -0
  145. package/dist/sources/claude.js +297 -0
  146. package/dist/sources/codex.js +496 -0
  147. package/dist/sources/flatten.js +23 -0
  148. package/dist/sources/jsonl.js +169 -0
  149. package/dist/sources/native.js +233 -0
  150. package/dist/sources/opencode.js +483 -0
  151. package/dist/sources/pi.js +133 -0
  152. package/dist/sources/registry.js +67 -0
  153. package/dist/sources/types.js +80 -0
  154. package/dist/t3/api.js +492 -0
  155. package/dist/t3/auth.js +248 -0
  156. package/dist/t3/compat.js +62 -0
  157. package/dist/t3/decode.js +408 -0
  158. package/dist/t3/errors.js +185 -0
  159. package/dist/t3/rpc.js +185 -0
  160. package/dist/t3/runtime.js +80 -0
  161. package/dist/ui/caps.js +56 -0
  162. package/dist/ui/components.js +202 -0
  163. package/dist/ui/layout.js +205 -0
  164. package/dist/ui/list.js +423 -0
  165. package/dist/ui/locale.js +73 -0
  166. package/dist/ui/organizePreview.js +72 -0
  167. package/dist/ui/progress.js +237 -0
  168. package/dist/ui/style.js +32 -0
  169. package/dist/ui/terminal.js +126 -0
  170. package/dist/ui/text.js +186 -0
  171. package/package.json +58 -4
  172. package/skills/t3code-sessions/SKILL.md +183 -0
@@ -0,0 +1 @@
1
+ {"version":"0.4.1","builtAt":"2026-11-16T15:00:26.391Z","channel":"npm"}
@@ -0,0 +1,158 @@
1
+ // What `t3sm apply` and `t3sm sync` show while they import and when they finish: one progress bar for the whole import
2
+ // ("Importing 5 conversations · 4 projects"; the waves only with --verbose), the result as a panel, the conversations
3
+ // held because they are in use, and the failures as a table (src/cli/failures.ts).
4
+
5
+
6
+
7
+ import { shownText } from "../plan/names.js";
8
+ import { kv, panel } from "../ui/components.js";
9
+ import { progressBar, } from "../ui/progress.js";
10
+ import { padStart } from "../ui/text.js";
11
+ import { failureTable } from "./failures.js";
12
+
13
+ import { fitLine, snugWidth } from "./screen.js";
14
+ import { ioTerm, } from "./ui.js";
15
+ import { folderName } from "./words.js";
16
+
17
+ /** "Importing 5 conversations · 4 projects". */
18
+ export function importLabel(ui , n ) {
19
+ return ui.t("apply.importing", { n: n.sessions, p: n.projects, sep: ui.s.sym.sep });
20
+ }
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+ /**
35
+ * One progress bar for the waves of one import. `silent`: nothing at all (--quiet, --watch). `verbose`: every wave's line
36
+ * too (above the bar on a terminal).
37
+ */
38
+ export function importProgress(io , ui , clock , o ) {
39
+ let bar = null;
40
+ let total = 0;
41
+ let done = 0; // imported, failed or deferred: the bar's progress
42
+ let imported = 0;
43
+ let started = 0;
44
+ const live = () => bar !== null && (ui.s.caps.cursor ?? ui.s.caps.isTTY);
45
+ return {
46
+ onImportStart(n) {
47
+ if (o.silent || n.sessions === 0) return;
48
+ // The label already says how many: no "(5)" after it.
49
+ bar = progressBar(ioTerm(io, ui), ui.s, ui.f, clock, { words: { left: ui.t("progress.left") }, showTotal: false, ...(o.proc ? { proc: o.proc } : {}) });
50
+ total = n.sessions;
51
+ started = clock();
52
+ bar.start(total, importLabel(ui, n));
53
+ },
54
+ onWave(p) {
55
+ done += p.imported + p.failed + p.deferred;
56
+ imported += p.imported;
57
+ if (done > total) total = done;
58
+ bar?.tick(Math.min(done, total));
59
+ },
60
+ onProgress(line) {
61
+ if (o.silent || !o.verbose) return;
62
+ if (bar) bar.note(line);
63
+ else io.stdout(`${line}\n`);
64
+ },
65
+ note(line) {
66
+ if (!live()) return false;
67
+ bar .note(line);
68
+ return true;
69
+ },
70
+ end() {
71
+ if (!bar) return;
72
+ const dur = ui.f.dur(clock() - started);
73
+ // Only what was imported is called imported: the rest failed or waits (the result panel says which).
74
+ bar.end(imported === done ? ui.t("apply.importDone", { n: imported, total, dur })
75
+ : ui.t("apply.importDoneMixed", { done, total, dur, n: imported, sep: ui.s.sym.sep }));
76
+ },
77
+ dispose() { bar?.dispose(); },
78
+ };
79
+ }
80
+
81
+ /** Why a held project waits, in the user's language: "<project> waits: '<title>' is in use (written 3 min ago); ...". */
82
+ export function waitingLines(ui , held , width = ui.width) {
83
+ return held.flatMap((h) => {
84
+ const title = shownText(h.title ?? (h.file.split(/[\\/]/).pop() || h.file), 120);
85
+ return fitLine(`${ui.s("warn", ui.s.sym.warn)} ${ui.t("apply.waiting", { project: shownText(h.project, 120), title, ago: ui.f.ago(h.modifiedAt) })}`, width, 2);
86
+ });
87
+ }
88
+
89
+ /**
90
+ * The result panel's rows: the counts aligned, with what they mean, and the run with how to undo it. Held projects named
91
+ * under the panel (`heldNamed`) are only counted here: the lines under it say why.
92
+ */
93
+ function resultRows(ui , r ) {
94
+ const { s, t, f } = ui;
95
+ const rows = [[t("apply.label.imported"), r.imported, null]];
96
+ if (r.failed) rows.push([t("apply.label.failed"), r.failed, null]);
97
+ if (r.converted) rows.push([t("apply.label.converted"), r.converted, null]);
98
+ if (r.unverified) rows.push([t("apply.label.unverified"), r.unverified, null]);
99
+ if (r.alreadyInT3) rows.push([t("apply.label.already"), r.alreadyInT3, null]);
100
+ if (r.deferred) rows.push([t("apply.label.deferred"), r.deferred, "apply.value.deferred"]);
101
+ if (r.held) rows.push([t("apply.label.held"), r.held, r.heldNamed ? null : "apply.value.held"]);
102
+ const nw = Math.max(...rows.map(([, n]) => f.n(n).length));
103
+ const out = rows.map(([k, n, more]) => {
104
+ const num = s("num", padStart(f.n(n), nw));
105
+ return [k, more === null ? num : t(more , { n: num })];
106
+ });
107
+ if (r.runId) {
108
+ out.push([t("apply.label.run"), t("apply.value.run", { runId: shownText(r.runId, 60) })]);
109
+ if (r.imported > 0 || r.converted > 0) out.push([t("apply.label.undo"), s("key", `t3sm rollback --run ${shownText(r.runId, 60)} --archive-threads`)]);
110
+ }
111
+ return out;
112
+ }
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+ /** The result as a panel: the title says what happened, the rows the counts. */
127
+ export function resultPanel(ui , c , width = ui.width) {
128
+ const { t } = ui;
129
+ const tone = c.status === "aborted" || c.failed > 0 || c.unverified > 0 ? "warn" : "ok";
130
+ const title = c.status === "aborted" ? t("apply.title.aborted", { n: c.imported })
131
+ : c.failed > 0 ? t("apply.title.partial", { n: c.imported, failed: c.failed })
132
+ : c.unverified > 0 ? t("apply.title.unverified", { n: c.imported, u: c.unverified })
133
+ : c.imported === 0 && c.converted === 0 && c.held + c.deferred > 0 ? t("apply.title.waiting", { n: c.held + c.deferred })
134
+ : c.imported === 0 && c.converted === 0 ? t("apply.title.nothing")
135
+ : t("apply.title.ok", { n: c.imported });
136
+ const body = kv(ui.s, resultRows(ui, c), Math.max(1, width - 4));
137
+ return panel(ui.s, { tone, title, body }, snugWidth(title, body, width));
138
+ }
139
+
140
+ /**
141
+ * `t3sm apply`'s result: the panel, why each held project waits, held projects with no transcript to name, and the
142
+ * failures as a table.
143
+ */
144
+ export function renderApplyResult(ui , r , width = ui.width) {
145
+ const status = r.status === "aborted" ? "aborted" : r.status === "partial" ? "partial" : "ok";
146
+ const out = resultPanel(ui, {
147
+ status, imported: r.imported, failed: r.failed, converted: r.converted, unverified: r.unverified, alreadyInT3: r.alreadyInT3,
148
+ deferred: r.deferred - r.deferredInUse, held: r.deferredInUse, heldNamed: r.heldRoots.length > 0, runId: r.runId,
149
+ }, width);
150
+ // Each held project once, with why: the conversation in use, else (a file stayed locked) the project alone.
151
+ const unexplained = r.heldRoots.filter((x) => !r.held.some((h) => h.root === x));
152
+ const lines = [...waitingLines(ui, r.held, width),
153
+ ...unexplained.flatMap((x) => fitLine(`${ui.s("warn", ui.s.sym.warn)} ${ui.t("apply.heldHint", { project: shownText(folderName(x), 60) })}`, width, 2))];
154
+ if (lines.length > 0) out.push("", ...lines);
155
+ if (r.failures.length > 0) out.push("", ...failureTable(ui, r.failures, width));
156
+ return out;
157
+ }
158
+
@@ -0,0 +1,254 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+
4
+ import { expandHome, sameCwd, stateDir, tildePath } from "../../core/paths.js";
5
+ import { discoverAccountHomes, nodeDiscoveryEnv, resolveAccounts, } from "../../ops/discoverAccounts.js";
6
+ import { ConfigError, defaultConfig, detectAccounts, loadConfig, saveConfig } from "../../core/config.js";
7
+ import { Journal, newRunId, recoverPendingMtimes } from "../../core/journal.js";
8
+ import { acquireLock } from "../../core/lock.js";
9
+ import { connectT3, } from "../../t3/api.js";
10
+ import { appearanceDelta, assertRenameSafe, defaultClaudeHome, ensureInstances, planInstances } from "../../ops/accounts.js";
11
+ import { maskEmail } from "../../ops/doctor.js";
12
+ import { reportLockBusy } from "../locked.js";
13
+
14
+ import { cliUi, confirm, isCliKey, unknownOption, usageLine } from "../ui.js";
15
+ import { FLAG_SPECS } from "../flags.js";
16
+ import { callout } from "../../ui/components.js";
17
+ import { bulletLines, fitLine, homeAsTilde, noteLines, tableOrBlocks, textLines } from "../screen.js";
18
+ import { shownAccountName, shownText } from "../../plan/names.js";
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+ const COLOR_RE = /^#[0-9A-Fa-f]{6}$/;
27
+ const KNOWN = new Set ([...FLAG_SPECS.accounts.bool, ...FLAG_SPECS.accounts.valued]);
28
+
29
+ function specsFromConfig(c , home ) {
30
+ return c.accounts.map((a) => ({ id: a.id, driver: "claudeAgent" , displayName: a.displayName, accentColor: a.accentColor, homePath: expandHome(a.home, home), environment: [] }));
31
+ }
32
+
33
+ export async function accountsCommand(args , io , deps = {}) {
34
+ const flags = new Set ();
35
+ let rename = null;
36
+ let color = null;
37
+ for (let i = 0; i < args.length; i++) {
38
+ const a = args[i] ;
39
+ if (a === "--rename") {
40
+ const id = args[i + 1], name = args[i + 2];
41
+ if (id === undefined || name === undefined || id.startsWith("--") || name.startsWith("--")) {
42
+ usageLine(io, "usage.renameArgs");
43
+ return 2;
44
+ }
45
+ rename = { id, name }; i += 2; flags.add(a);
46
+ } else if (a === "--color") {
47
+ const v = args[i + 1];
48
+ if (v === undefined || v.startsWith("--")) { usageLine(io, "usage.colorValue"); return 2; }
49
+ color = v; i += 1; flags.add(a);
50
+ } else if (KNOWN.has(a)) flags.add(a);
51
+ else { unknownOption(io, a, "accounts"); return 2; }
52
+ }
53
+ const modes = ["--init", "--apply", "--rename"].filter((f) => flags.has(f));
54
+ if (modes.length > 1) { usageLine(io, "usage.onlyOneOf", { modes: modes.join(", ") }); return 2; }
55
+ if (color !== null && !COLOR_RE.test(color)) { usageLine(io, "usage.colorFormat", { value: JSON.stringify(color) }); return 2; }
56
+ if (color !== null && !rename) { usageLine(io, "usage.colorWithRename"); return 2; }
57
+ if ((flags.has("--force") && !flags.has("--init")) || (flags.has("--yes") && !flags.has("--apply"))) {
58
+ usageLine(io, "usage.forceYes");
59
+ return 2;
60
+ }
61
+ if (flags.has("--show-emails") && modes.length > 0) { usageLine(io, "usage.showEmails"); return 2; }
62
+
63
+ const home = deps.home ?? homedir();
64
+ const now = deps.now ?? Date.now;
65
+ const dir = stateDir(io.env, home);
66
+ const connect = deps.connect ?? connectT3;
67
+ const allowUntested = flags.has("--allow-untested");
68
+ const notice = (l ) => io.stderr(`${l}\n`);
69
+
70
+ if (flags.has("--init")) {
71
+ if ((await loadConfig(dir, home)) !== null && !flags.has("--force")) {
72
+ io.stderr(`${join(dir, "config.json")} already exists. Use --force to overwrite it.\n`);
73
+ return 2;
74
+ }
75
+ // Existing T3 instance ids are kept when T3 Code is running (read-only session); otherwise ids come from discovery.
76
+ let specs = [];
77
+ try {
78
+ const api = await connect(home, { allowUntested: true, manageProviders: false, onNotice: () => {} });
79
+ try {
80
+ specs = (await api.providerInstances()).filter((i) => i.driver === "claudeAgent" && i.homePath !== null)
81
+ .map((i) => ({ id: i.instanceId, driver: "claudeAgent" , displayName: i.displayName, accentColor: i.accentColor, homePath: i.homePath , environment: [] }));
82
+ } finally { await api.close(); }
83
+ } catch { /* T3 Code not running: ids from discovery */ }
84
+ const cfg = defaultConfig(await resolveAccounts(home, specs, io.env));
85
+ await saveConfig(dir, cfg, home);
86
+ const ui = cliUi(io);
87
+ io.stdout(noteLines(ui.s, "ok", ui.t("accounts.wrote", { path: join(dir, "config.json"), n: cfg.accounts.length, ids: cfg.accounts.map((a) => a.id).join(", ") || ui.t("accounts.noneIds") }), ui.width).join("\n") + "\n");
88
+ return 0;
89
+ }
90
+
91
+ if (flags.has("--apply") && !flags.has("--yes") && !io.isTTY) {
92
+ usageLine(io, "common.needsYesT3");
93
+ return 2;
94
+ }
95
+
96
+ const needsConfig = flags.has("--apply") || rename !== null;
97
+ const loaded = await loadConfig(dir, home);
98
+ if (needsConfig && loaded === null) throw new ConfigError(`${join(dir, "config.json")} not found. Run \`t3sm accounts --init\` first.`);
99
+
100
+ if (rename) return renameInstance(rename, color, loaded , { io, dir, home, now, connect, allowUntested, notice });
101
+ if (flags.has("--apply")) return applyAccounts(loaded , flags.has("--yes"), { io, dir, home, now, connect, allowUntested, notice });
102
+
103
+ const api = await connect(home, { allowUntested, manageProviders: false, onNotice: notice });
104
+ try {
105
+ const instances = (await api.providerInstances()).filter((i) => i.driver === "claudeAgent");
106
+ const found = await discoverAccountHomes(nodeDiscoveryEnv({ home, env: io.env, instanceHomes: instances.flatMap((i) => (i.homePath === null ? [] : [i.homePath])) }));
107
+ const config = loaded ?? defaultConfig(await detectAccounts(home, [], found.map((f) => ({ home: f.home, alias: f.alias }))));
108
+ io.stdout(renderAccounts(cliUi(io), instances, config, home, found, flags.has("--show-emails")).join("\n") + "\n");
109
+ return 0;
110
+ } finally {
111
+ await api.close();
112
+ }
113
+ }
114
+
115
+
116
+
117
+
118
+
119
+ /** Why planInstances leaves an account out, in the user's language (its reasons are English); an unknown one as it is. */
120
+ export function skipWhy(ui , reason , home ) {
121
+ const used = /^instance id already used with another home \((.*)\)$/.exec(reason);
122
+ if (used) return ui.t("accounts.apply.why.idUsed", { home: shownText(used[1] === "null" ? "?" : tildePath(used[1] , home), 200) });
123
+ const served = /^home already served by instance (.+)$/.exec(reason);
124
+ if (served) return ui.t("accounts.apply.why.homeServed", { id: shownText(served[1] , 60) });
125
+ return shownText(homeAsTilde(reason, home), 200);
126
+ }
127
+
128
+ /**
129
+ * The accounts against T3 Code's instances as a table (account, instance, display name, home, where it was found,
130
+ * signed-in email, sign-in, availability), then each problem as a warning with its command. showEmails false
131
+ * (default): emails masked like doctor (b***@domain); shared emails are still compared unmasked.
132
+ */
133
+ export function renderAccounts(ui , instances , config , home , found , showEmails = false, width = ui.width) {
134
+ const { s, t: tr } = ui;
135
+ const shown = (email ) => (showEmails ? email : maskEmail(email));
136
+ // A display name may hold an email: masked like the emails, whole with --show-emails.
137
+ const showName = (name ) => (showEmails ? shownText(name, 60) : shownAccountName(name));
138
+ const used = new Set ();
139
+ const rows = [];
140
+ const warnings = [];
141
+ const t = (p ) => tildePath(p, home);
142
+ // Where a home was found, whether it is signed in and usable: in words (the codes are discovery's and T3 Code's).
143
+ const word = (prefix , v ) => { const k = `${prefix}${v.replace(/-([a-z0-9])/g, (_m, c ) => c.toUpperCase())}`; return isCliKey(k) ? tr(k) : shownText(v, 40); };
144
+ const sources = (d ) =>
145
+ d.sources.map((x) => (x === "shell-profile" && d.alias ? tr("accounts.via.shellAlias", { alias: shownText(d.alias, 40) }) : word("accounts.via.", x))).join(", ");
146
+ const via = (p , fallback ) => {
147
+ const d = p === null ? undefined : found.find((f) => sameCwd(f.home, p));
148
+ return d ? sources(d) : word("accounts.via.", fallback);
149
+ };
150
+ const row = (acct , i , fallback ) => {
151
+ used.add(i.instanceId);
152
+ rows.push({ account: acct, instance: i.instanceId, name: showName(i.displayName), home: i.homePath === null ? "?" : t(i.homePath), via: via(i.homePath, fallback), email: i.email ? shown(i.email) : "-", auth: i.authStatus === null ? "-" : word("accounts.auth.", i.authStatus), availability: word("accounts.avail.", i.availability) });
153
+ if (i.authStatus === "unauthenticated") warnings.push({ title: tr("accounts.warn.signedOutTitle", { id: i.instanceId }), body: tr("accounts.warn.signedOut") });
154
+ };
155
+ for (const a of config.accounts) {
156
+ const h = expandHome(a.home, home);
157
+ const i = instances.find((x) => x.homePath !== null && sameCwd(x.homePath, h));
158
+ if (i) row(a.id, i, "config");
159
+ else {
160
+ rows.push({ account: a.id, instance: tr("accounts.noInstance"), name: showName(a.displayName), home: t(h), via: via(h, "config"), email: "-", auth: "-", availability: "-" });
161
+ warnings.push({ title: tr("accounts.warn.noInstanceTitle", { id: a.id, home: t(h) }), body: tr("accounts.warn.noInstance"), command: "t3sm accounts --apply" });
162
+ }
163
+ }
164
+ for (const i of instances) if (!used.has(i.instanceId)) row(tr("accounts.notInConfig"), i, "t3-instance");
165
+ for (const f of found) {
166
+ if (config.accounts.some((a) => sameCwd(expandHome(a.home, home), f.home))) continue;
167
+ warnings.push({ title: tr("accounts.warn.foundTitle", { home: t(f.home), via: sources(f) }), body: tr("accounts.warn.found"), command: "t3sm accounts --init --force" });
168
+ }
169
+ const byEmail = new Map ();
170
+ for (const i of instances) if (i.email) byEmail.set(i.email.toLowerCase(), [...(byEmail.get(i.email.toLowerCase()) ?? []), i.instanceId]);
171
+ for (const [email, ids] of byEmail) if (ids.length > 1) warnings.push({ title: tr("accounts.warn.sharedTitle", { ids: ids.join(", "), email: shown(email) }), body: tr("accounts.warn.shared") });
172
+ // Never cut and never a column left out: a table when every cell fits whole, else one block per account.
173
+ const col = (header , get ) => ({ header, get: (r ) => get(r ) });
174
+ // The instance column only when some instance id is not its account's id (it would repeat the first column).
175
+ const sameIds = rows.every((r) => r.instance === r.account);
176
+ const out = tableOrBlocks(s, [
177
+ col(tr("accounts.col.account"), (r) => r.account),
178
+ ...(sameIds ? [] : [col(tr("accounts.col.instance"), (r) => r.instance)]),
179
+ col(tr("accounts.col.name"), (r) => r.name),
180
+ col(tr("accounts.col.home"), (r) => r.home),
181
+ col(tr("accounts.col.via"), (r) => r.via),
182
+ col(tr("accounts.col.email"), (r) => r.email),
183
+ col(tr("accounts.col.auth"), (r) => r.auth),
184
+ col(tr("accounts.col.availability"), (r) => r.availability),
185
+ ], rows, width);
186
+ for (const w of warnings) out.push("", ...callout(s, { kind: "warn", title: w.title, body: textLines(s, w.body, Math.max(1, width - 2)), ...(w.command ? { command: w.command } : {}) }, width));
187
+ return out;
188
+ }
189
+
190
+ // Both writers take the lock and restore pending mtimes BEFORE connecting: a held lock must not create a T3 session.
191
+ async function applyAccounts(config , yes , c ) {
192
+ const specs = specsFromConfig(config, c.home);
193
+ const lock = await acquireLock(c.dir);
194
+ if (!lock) { reportLockBusy(c.io); return 0; }
195
+ try {
196
+ const j = new Journal(join(c.dir, "journal.jsonl"));
197
+ await recoverPendingMtimes(j);
198
+ const api = await c.connect(c.home, { allowUntested: c.allowUntested, manageProviders: true, onNotice: c.notice });
199
+ const ui = cliUi(c.io);
200
+ const say = (l ) => c.io.stdout(l.join("\n") + "\n");
201
+ try {
202
+ // Throws InstanceHomeDrift before any write; an explicit claudeAgent entry for another home is re-pinned instead.
203
+ const plan = await planInstances(api, specs, defaultClaudeHome(c.home), { repinExplicit: true });
204
+ const items = [...plan.create.map((x) => ui.t("accounts.apply.create", { id: x.id, home: tildePath(x.homePath, c.home) })), ...plan.pin.map((x) => ui.t("accounts.apply.pin", { id: x.id, home: tildePath(x.homePath, c.home) }))];
205
+ for (const x of plan.skipped) if (x.reason !== "already present") say(noteLines(ui.s, "warn", ui.t("accounts.apply.skip", { id: x.id, reason: skipWhy(ui, x.reason, c.home) }), ui.width));
206
+ if (plan.create.length === 0 && plan.pin.length === 0) { say(noteLines(ui.s, "ok", ui.t("accounts.apply.nothing"), ui.width)); return 0; }
207
+ if (!yes) {
208
+ say([...fitLine(ui.s("title", ui.t("accounts.apply.willDo")), ui.width), ...items.flatMap((x) => bulletLines(ui.s, x, ui.width)), ""]);
209
+ if (!(await confirm(c.io, ui.t("accounts.confirm")))) { c.io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
210
+ }
211
+ const r = await ensureInstances(api, specs, j, newRunId(new Date(c.now())), defaultClaudeHome(c.home), { repinExplicit: true });
212
+ const none = ui.t("accounts.noneIds");
213
+ say(noteLines(ui.s, "ok", ui.t("accounts.apply.done", { created: r.created.join(", ") || none, pinned: r.pinned.join(", ") || none }), ui.width));
214
+ return 0;
215
+ } finally {
216
+ await api.close();
217
+ }
218
+ } finally {
219
+ await lock.release();
220
+ }
221
+ }
222
+
223
+ async function renameInstance(r , color , config , c ) {
224
+ const acct = config.accounts.find((a) => a.id === r.id);
225
+ if (!acct) throw new ConfigError(`No account ${JSON.stringify(r.id)} in config.json (known: ${config.accounts.map((a) => a.id).join(", ") || "none"}).`);
226
+ if (r.name.trim() === "") throw new ConfigError("The display name must not be empty.");
227
+ const lock = await acquireLock(c.dir);
228
+ if (!lock) { reportLockBusy(c.io); return 0; }
229
+ try {
230
+ const j = new Journal(join(c.dir, "journal.jsonl"));
231
+ await recoverPendingMtimes(j);
232
+ const api = await c.connect(c.home, { allowUntested: c.allowUntested, manageProviders: true, onNotice: c.notice });
233
+ try {
234
+ if (!(await api.providerInstances()).some((i) => i.instanceId === r.id)) {
235
+ throw new ConfigError(`No T3 Code instance named ${r.id}. Run \`t3sm accounts\` to list them.`);
236
+ }
237
+ const pinnedHome = await assertRenameSafe(api, r.id, expandHome(acct.home, c.home));
238
+ const appearance = { displayName: r.name.trim() };
239
+ if (color !== null) appearance.accentColor = color.toUpperCase();
240
+ const res = await api.updateInstanceAppearance(r.id, appearance);
241
+ if (res.changed) await j.append({ t: "instance-updated", runId: newRunId(new Date(c.now())), instanceId: r.id, previous: appearanceDelta(res.previous), next: { ...appearanceDelta(res.previous), ...appearance, homePath: appearanceDelta(res.previous).homePath ?? pinnedHome } });
242
+ acct.displayName = appearance.displayName;
243
+ if (appearance.accentColor !== undefined) acct.accentColor = appearance.accentColor;
244
+ await saveConfig(c.dir, config, c.home);
245
+ const ui = cliUi(c.io);
246
+ c.io.stdout(noteLines(ui.s, "ok", res.changed ? ui.t("accounts.renamed", { id: r.id, name: JSON.stringify(shownAccountName(appearance.displayName, 200)) }) : ui.t("accounts.renamedSame", { id: r.id }), ui.width).join("\n") + "\n");
247
+ return 0;
248
+ } finally {
249
+ await api.close();
250
+ }
251
+ } finally {
252
+ await lock.release();
253
+ }
254
+ }
@@ -0,0 +1,199 @@
1
+ import { homedir, tmpdir } from "node:os";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+
5
+ import { expandHome, normalizeCwd, stateDir, tildePath } from "../../core/paths.js";
6
+
7
+ import { shownAccountName, shownText } from "../../plan/names.js";
8
+ import { ConfigError, NoPlanError, defaultConfig, loadConfig } from "../../core/config.js";
9
+ import { allAdapters } from "../../sources/registry.js";
10
+ import { discoverAll, makeEnv } from "./scan.js";
11
+ import { renderTerminalSummary } from "../../plan/report.js";
12
+ import { applyPlan, } from "../../apply/apply.js";
13
+
14
+ import { reportLockBusy } from "../locked.js";
15
+ import { FLAG_SPECS } from "../flags.js";
16
+
17
+ import { cliUi, confirm, unknownOption, usageLine } from "../ui.js";
18
+ import { importProgress, renderApplyResult, waitingLines } from "../applyScreen.js";
19
+ import { FAILURES_SHOWN, failureTable } from "../failures.js";
20
+ import { folderName } from "../words.js";
21
+ import { fitLine, snugWidth } from "../screen.js";
22
+ import { kv, panel } from "../../ui/components.js";
23
+ import { displayWidth, padEnd } from "../../ui/text.js";
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ const FLAGS = new Set (FLAG_SPECS.apply.bool);
37
+ const VALUED = new Set (FLAG_SPECS.apply.valued);
38
+
39
+
40
+ /** The planner's folder classification inputs for `platform` (T3 Code under ~/.t3). */
41
+ export function defaultFolderEnv(home , env , platform ) {
42
+ const t3Base = normalizeCwd(expandHome("~/.t3", home), platform);
43
+ return { platform, home, tmpdir: tmpdir(), env, t3BaseDir: t3Base, t3WorktreesDir: `${t3Base}/worktrees` };
44
+ }
45
+
46
+ /** Newest `runs/<runId>/plan.json` (run ids sort by time). */
47
+ export async function latestPlan(dir ) {
48
+ let names ;
49
+ try { names = await readdir(join(dir, "runs")); } catch { return null; }
50
+ for (const n of names.sort().reverse()) {
51
+ const p = join(dir, "runs", n, "plan.json");
52
+ try { await readFile(p); return p; } catch { /* incomplete run dir */ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ export async function readPlan(p ) {
58
+ let u ;
59
+ try { u = JSON.parse(await readFile(p, "utf8")); } catch (e) {
60
+ throw new ConfigError(`Could not read the plan ${p} (${(e ).code ?? "invalid JSON"}). Run \`t3sm plan\` again.`);
61
+ }
62
+ const o = u ;
63
+ if (!o || typeof o !== "object" || o.version !== 1 || !Array.isArray(o.items) || typeof o.createdAt !== "string" || typeof o.t3Version !== "string"
64
+ || !Array.isArray(o.projectsToCreate) || !Array.isArray(o.projectDefaults) || !Array.isArray(o.instancesToCreate) || !Array.isArray(o.mirrorCopies)) {
65
+ throw new ConfigError(`${p} is not a t3sm plan. Run \`t3sm plan\` again.`);
66
+ }
67
+ return o ;
68
+ }
69
+
70
+ /** One line per destination folder a run would create for rehome copies (home shown as ~). */
71
+ const folderLines = (ui , roots , home , platform ) =>
72
+ roots.map((r) => ui.t("apply.willCreateFolder", { path: shownText(tildePath(r, home, platform)) }));
73
+
74
+ /** The accounts by name (config.json's display names; the plan adds the instances it creates). */
75
+ export const accountNames = (config ) =>
76
+ Object.fromEntries((config?.accounts ?? []).map((a) => [a.id, shownAccountName(a.displayName)]));
77
+
78
+ /** `apply --dry-run`: the confirmation's summary, then what a run would do (`waiting` lines under the held row). */
79
+ export function renderDryRun(d , planPath , ui , waiting , folders , accounts = {}) {
80
+ const { s, t, f } = ui;
81
+ const width = Math.max(1, ui.width);
82
+ const L = [renderTerminalSummary(d.plan, { planPath, ui, names: accounts }).trimEnd()];
83
+ const names = (xs ) => (xs.length ? ` (${xs.map((x) => shownText(x, 60)).join(", ")})` : "");
84
+ const nameOf = (id ) => { const n = d.plan.instancesToCreate.find((i) => i.id === id)?.displayName; return n !== undefined ? shownAccountName(n) : accounts[id] ?? id; };
85
+ const held = d.held.roots.length > 0 ? ` (${d.held.roots.map((r) => shownText(folderName(r), 60)).join(", ")}; ${t("apply.notThisRun")})` : "";
86
+ const rows = [
87
+ [t("apply.dry.instances"), `${f.n(d.instancesToCreate.length)}${names(d.instancesToCreate.map(nameOf))}`],
88
+ [t("apply.dry.pin"), d.pinDefault ? `${shownText(nameOf("claudeAgent"), 60)} ${s.sym.arrow} ${shownText(d.pinDefault, 120)}` : t("apply.dry.none")],
89
+ [t("apply.dry.folders"), f.n(d.foldersToCreate.length)],
90
+ [t("apply.dry.projects"), `${f.n(d.projectsToCreate.length)}${names(d.projectsToCreate.map(folderName))}`],
91
+ [t("apply.dry.defaults"), f.n(d.defaultsToSet.length)],
92
+ [t("apply.dry.conversions"), f.n(d.conversions)],
93
+ [t("apply.dry.waves"), t("apply.dry.wavesValue", { n: d.waves, sessions: d.waveSessions })],
94
+ [t("apply.dry.already"), f.n(d.alreadyInT3)],
95
+ [t("apply.dry.held"), t("apply.dry.heldValue", { n: d.held.roots.length, sessions: d.held.sessions }) + held],
96
+ [t("apply.dry.failUpFront"), f.n(d.failUpFront.length)],
97
+ ];
98
+ // One kv call per row, every label padded to the widest: the rows stay aligned and the extra lines go under theirs.
99
+ const lw = Math.max(...rows.map(([k]) => displayWidth(k)));
100
+ const body = [];
101
+ for (const [k, v] of rows) {
102
+ body.push(...kv(s, [[padEnd(k, lw), v]], Math.max(1, width - 4)));
103
+ if (k === t("apply.dry.held")) for (const x of waiting) body.push(` ${x}`);
104
+ if (k === t("apply.dry.folders")) for (const x of folders) body.push(` ${x}`);
105
+ }
106
+ L.push("", ...panel(s, { title: t("apply.dry.title"), body }, snugWidth(t("apply.dry.title"), body, width)));
107
+ if (d.failUpFront.length > 0) L.push("", ...failureTable(ui, d.failUpFront, width, { dry: true }));
108
+ if (d.pendingRecovery.length > 0) L.push("", ...fitLine(`${s("warn", s.sym.warn)} ${t("apply.dry.pendingRecovery", { n: d.pendingRecovery.length })}`, width, 2));
109
+ L.push("", ...fitLine(t("apply.dry.done"), width));
110
+ return L.join("\n") + "\n";
111
+ }
112
+
113
+ export async function applyCommand(args , io , deps = {}) {
114
+ const flags = new Set ();
115
+ let planPath = null;
116
+ let only = null;
117
+ for (let i = 0; i < args.length; i++) {
118
+ const a = args[i] ;
119
+ if (VALUED.has(a)) {
120
+ const v = args[i + 1];
121
+ if (v === undefined || v.startsWith("--")) { usageLine(io, "common.needsValue", { option: a, help: "t3sm apply --help" }); return 2; }
122
+ if (a === "--plan") planPath = v; else only = resolve(v);
123
+ i++;
124
+ } else if (FLAGS.has(a)) flags.add(a);
125
+ else { unknownOption(io, a, "apply"); return 2; }
126
+ }
127
+ const yes = flags.has("--yes");
128
+ const quiet = flags.has("--quiet");
129
+ const dryRun = flags.has("--dry-run");
130
+ if (yes && dryRun) { usageLine(io, "common.eitherDryRunOrYes"); return 2; }
131
+ if (!yes && !dryRun && !io.isTTY) { usageLine(io, "common.needsYesT3"); return 2; }
132
+
133
+ const home = deps.home ?? homedir();
134
+ const now = deps.now ?? Date.now;
135
+ const platform = deps.platform ?? process.platform;
136
+ const dir = stateDir(io.env, home);
137
+ const ui = cliUi(io, { now });
138
+ let shownPath = "";
139
+ // Read under the lock (inside applyPlan): a held lock wins over a missing or stale plan (exit 0, nothing touched).
140
+ const load = async () => {
141
+ const p = planPath ?? (await latestPlan(dir));
142
+ if (p === null) throw new NoPlanError();
143
+ shownPath = p.replace(/plan\.json$/, "plan.md");
144
+ return readPlan(p);
145
+ };
146
+
147
+ const config = await loadConfig(dir, home);
148
+ const out = (s ) => { if (!quiet) io.stdout(s); };
149
+ const bar = importProgress(io, ui, now, { silent: quiet, verbose: flags.has("--verbose") });
150
+ const names = accountNames(config);
151
+ const applyDeps = {
152
+ stateDir: dir, home, now, connect: deps.connect, signals: deps.signals,
153
+ allowUntested: flags.has("--allow-untested"), only, dryRun,
154
+ // An interactive apply creates a missing General / override destination folder (never sync: invariant 13).
155
+ rehomeFolders: { env: deps.folderEnv ?? defaultFolderEnv(home, io.env, platform) }, platform,
156
+ batch: config?.batch,
157
+ // Titles are read only for the failures the screen shows (none with --quiet).
158
+ failureTitles: quiet ? 0 : FAILURES_SHOWN,
159
+ onImportStart: (n) => bar.onImportStart(n),
160
+ onWave: (p) => bar.onWave(p),
161
+ onProgress: (l) => bar.onProgress(l),
162
+ // Codex / Pi transcripts created after planning (Claude's are listed directly from the instance homes). A dry run
163
+ // reads them with the read-only env (no discovery cache written).
164
+ rediscover: async () => (await discoverAll(allAdapters().filter((a) => a.id !== "claude"), { ...makeEnv(io, home, config ?? defaultConfig([]), now), readOnly: dryRun })).sessions,
165
+ onNotice: (l) => { if (!bar.note(l)) io.stderr(`${l}\n`); }, lang: ui.lang,
166
+ accountHomes: () => Object.fromEntries((config?.accounts ?? []).map((a) => [a.id, expandHome(a.home, home)])),
167
+ confirm: yes || dryRun ? undefined : async (plan, held, extra) => {
168
+ io.stdout(renderTerminalSummary(plan, { planPath: shownPath, ui, names, held }));
169
+ for (const l of folderLines(ui, extra.foldersToCreate, home, platform)) io.stdout(`${l}\n`);
170
+ return confirm(io, ui.t("apply.confirm"));
171
+ },
172
+ };
173
+ let r ;
174
+ try {
175
+ r = await applyPlan(load, applyDeps);
176
+ bar.end();
177
+ } finally {
178
+ bar.dispose();
179
+ }
180
+ if (r.status === "locked") { reportLockBusy(io, quiet); return 0; } // --quiet: silent, like sync
181
+ if (r.status === "declined") { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
182
+ if (r.status === "dry-run" && r.dryRun) {
183
+ io.stdout(renderDryRun(r.dryRun, shownPath, ui, waitingLines(ui, r.held, Math.max(1, ui.width - 6)), folderLines(ui, r.dryRun.foldersToCreate, home, platform), names));
184
+ return 0;
185
+ }
186
+ const rec = r.recovered;
187
+ if (rec && rec.restored.length > 0) io.stderr(`${ui.t("apply.recovered", { n: rec.restored.length })}\n`);
188
+ if (rec && rec.failed.length > 0) io.stderr(`${ui.t("apply.recoverFailed", { n: rec.failed.length })}\n`);
189
+
190
+ if (r.status === "aborted" && r.runId === null) { io.stderr(`${ui.t("apply.interruptedBefore")}\n`); return 130; }
191
+
192
+ out(renderApplyResult(ui, r).join("\n") + "\n");
193
+ if (r.restoreErrors.length > 0) {
194
+ io.stderr(`${ui.t("apply.restoreWarning", { n: r.restoreErrors.length, path: r.restoreErrors[0] .path, error: r.restoreErrors[0] .error })}\n`);
195
+ }
196
+ if (r.unverified > 0) io.stderr(`${ui.t("apply.unverifiedStop")}\n`);
197
+ if (r.status === "aborted") { io.stderr(`${ui.t("apply.interrupted")}\n`); return 130; }
198
+ return r.failed > 0 || r.unverified > 0 || r.restoreErrors.length > 0 ? 5 : 0;
199
+ }