t3code-session-manager 0.0.0-stage → 0.4.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 (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +138 -0
  4. package/LICENSE +21 -0
  5. package/README.md +660 -2
  6. package/README.pt.md +616 -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,249 @@
1
+ // Optional system notifications for an unattended `sync` (spec 4.8): one OS notification per reason per 24 h (a failed send is retried after 1 h) when t3sm
2
+ // needs a person (`needsAttention`, see syncStatus.ts), and with notify "all" a summary after a cycle that imported
3
+ // something. Both the watcher and the scheduled `sync --quiet` go through notifyAfterCycle (called by runSyncCycle).
4
+ // - text is in the user's language (the catalogues, src/i18n/cli.ts; the caller resolves the language from env and
5
+ // config.json as the cycle does) and holds counts and project names only (shownText, max 40 each), never session text;
6
+ // - the title and body reach the OS as DATA, never spliced into a script: Windows gets them base64-encoded in
7
+ // environment variables and decodes them inside the script; macOS gets them as osascript arguments; Linux as
8
+ // notify-send arguments after `--`;
9
+ // - nothing here throws: a missing notifier, a failing process or an unwritable status file just means "no notification".
10
+ // Rate limit: `lastNotified` (reason -> ISO time) lives in sync-status.json, written by markNotified. A reason is marked
11
+ // when a notification was ATTEMPTED (a platform without a notifier must not retry on every cycle). Updates notify once
12
+ // per version instead (notifyOnce): a major release found by the daily check (`update-available`), and an automatic
13
+ // update that failed or was rolled back (`update-failed`, which the cycles then leave alone).
14
+
15
+ import { accessSync, constants } from "node:fs";
16
+ import { delimiter, join } from "node:path";
17
+ import { defaultRunner, } from "../t3/auth.js";
18
+ import { system32 } from "../core/sysroot.js";
19
+ import { shownText } from "../plan/names.js";
20
+
21
+ import { cliT, } from "../i18n/cli.js";
22
+ import { markNotified, readLastNotified, } from "./syncStatus.js";
23
+
24
+
25
+
26
+
27
+ export const NOTIFY_TIMEOUT_MS = 10_000;
28
+ export const NOTIFY_INTERVAL_MS = 24 * 60 * 60 * 1000;
29
+ /** A send that failed is retried after this long (the stamp is back-dated by INTERVAL - RETRY). */
30
+ export const NOTIFY_RETRY_MS = 60 * 60 * 1000;
31
+ /** The reason key of the "all" summary. */
32
+ export const SUMMARY_REASON = "imported";
33
+ export const NOTIFY_TITLE = "t3sm needs attention";
34
+ export const SUMMARY_TITLE = "t3sm";
35
+ const NAME_MAX = 40;
36
+ const DETAIL_MAX = 160;
37
+ const POWERSHELL_APP_ID = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";
38
+
39
+ const WIN_SCRIPT = [
40
+ "$ErrorActionPreference = 'Stop'",
41
+ "$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:T3SM_NOTIFY_TITLE))",
42
+ "$b = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:T3SM_NOTIFY_BODY))",
43
+ "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
44
+ "[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",
45
+ "$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
46
+ "$n = $x.GetElementsByTagName('text')",
47
+ "$n.Item(0).AppendChild($x.CreateTextNode($t)) | Out-Null",
48
+ "$n.Item(1).AppendChild($x.CreateTextNode($b)) | Out-Null",
49
+ "$toast = [Windows.UI.Notifications.ToastNotification]::new($x)",
50
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${POWERSHELL_APP_ID}').Show($toast)`,
51
+ ].join("; ");
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+ function onPath(name , env ) {
60
+ for (const dir of (env["PATH"] ?? "").split(delimiter)) {
61
+ if (!dir) continue;
62
+ try { accessSync(join(dir, name), constants.X_OK); return true; } catch { /* next */ }
63
+ }
64
+ return false;
65
+ }
66
+
67
+ /** The environment a notifier child gets: ours, without an account home (CLAUDE_CONFIG_DIR never leaks into children). */
68
+ function childEnv(base , extra = {}) {
69
+ const env = {};
70
+ for (const [k, v] of Object.entries(base)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") env[k] = v;
71
+ return { ...env, ...extra };
72
+ }
73
+
74
+ /** notify-send renders Pango markup: & < > must be entities (Linux only). */
75
+ const pango = (s ) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
76
+
77
+ const b64 = (s ) => Buffer.from(s, "utf8").toString("base64");
78
+
79
+ export function systemNotifier(platform , run = defaultRunner, o = {}) {
80
+ const base = o.env ?? process.env;
81
+ const which = o.which ?? ((n ) => onPath(n, base));
82
+ return {
83
+ async notify(title, body) {
84
+ // Control and escape characters never reach an OS notification (and no argument can be empty or start a new option).
85
+ const t = shownText(title, 120), b = shownText(body, 400);
86
+ try {
87
+ if (platform === "win32") {
88
+ const r = await run(system32(base, "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WIN_SCRIPT],
89
+ { shell: false, timeoutMs: NOTIFY_TIMEOUT_MS, env: childEnv(base, { T3SM_NOTIFY_TITLE: b64(t), T3SM_NOTIFY_BODY: b64(b) }) });
90
+ return r.code === 0 && !r.timedOut;
91
+ }
92
+ if (platform === "darwin") {
93
+ const r = await run("osascript", ["-e", "on run argv", "-e", "display notification (item 2 of argv) with title (item 1 of argv)", "-e", "end run", t, b],
94
+ { shell: false, timeoutMs: NOTIFY_TIMEOUT_MS, env: childEnv(base) });
95
+ return r.code === 0 && !r.timedOut;
96
+ }
97
+ if (platform === "linux") {
98
+ if (!which("notify-send")) return false;
99
+ const r = await run("notify-send", ["--", pango(t), pango(b)], { shell: false, timeoutMs: NOTIFY_TIMEOUT_MS, env: childEnv(base) });
100
+ return r.code === 0 && !r.timedOut;
101
+ }
102
+ return false;
103
+ } catch { return false; }
104
+ },
105
+ };
106
+ }
107
+
108
+ /** One notification per reason per 24 h; mode "attention" never sends the import summary; "off" and --dry-run never send. */
109
+ export function shouldNotify(o ) {
110
+ if (o.dryRun === true || o.mode === "off") return false;
111
+ if (o.mode === "attention" && o.reason === SUMMARY_REASON) return false;
112
+ const last = Date.parse(o.lastNotified[o.reason] ?? "");
113
+ return !(Number.isFinite(last) && o.now - last >= 0 && o.now - last < NOTIFY_INTERVAL_MS);
114
+ }
115
+
116
+ /** The title of an attention notification, in `lang`. */
117
+ export function attentionTitle(lang = "en") {
118
+ return cliT(lang, "notify.attentionTitle");
119
+ }
120
+
121
+ /** The title of the import summary, in `lang`. */
122
+ export function summaryTitle(lang = "en") {
123
+ return cliT(lang, "notify.summaryTitle");
124
+ }
125
+
126
+ /** What an attention notification or a status item is told from: its reason, the recorded English detail and facts. */
127
+
128
+
129
+ /**
130
+ * What needs the user, in `lang`, worded from the facts the producer recorded (sync.ts attentionOf,
131
+ * incompatibleAttention; syncStatus.ts streakAttention, the update failure). A record without facts (written by an
132
+ * older t3sm) keeps its English detail in English, and gets a sentence without the numbers in any other language.
133
+ */
134
+ export function attentionText(a , lang ) {
135
+ const f = a.facts;
136
+ const t = (k , v = {}) => cliT(lang, k, v);
137
+ const num = (x ) => typeof x === "number";
138
+ const known = (() => {
139
+ if (!f) return null;
140
+ switch (a.reason) {
141
+ case "undecided": return num(f.n) && num(f.q) ? t("notify.undecided", { n: f.n , q: f.q }) : null;
142
+ case "signed-out": return num(f.n) ? t("notify.signedOut", { n: f.n }) : null;
143
+ case "over-limit": return num(f.n) && num(f.limit) ? t("notify.overLimit", { n: f.n , limit: f.limit }) : null;
144
+ case "t3-incompatible": return typeof f.version === "string" ? t("notify.incompatible", { version: shownText(f.version, 40) }) : null;
145
+ case "repeated-failures": return num(f.n) ? t("notify.failures", { n: f.n }) : null;
146
+ case "update-failed": {
147
+ if (typeof f.from !== "string" || typeof f.to !== "string") return null;
148
+ const v = { from: shownText(f.from, 40), to: shownText(f.to, 40) };
149
+ return t(f.outcome === "rolled-back" ? "status.update.rolledBack" : f.outcome === "interrupted" ? "status.update.interrupted" : "status.update.failed", v);
150
+ }
151
+ }
152
+ })();
153
+ if (known !== null) return known;
154
+ if (lang === "en") return a.detail;
155
+ const any = {
156
+ undecided: "notify.undecidedAny", "signed-out": "notify.signedOutAny", "over-limit": "notify.overLimitAny",
157
+ "t3-incompatible": "notify.incompatibleAny", "repeated-failures": "notify.failuresAny", "update-failed": "notify.updateAny",
158
+ };
159
+ return t(any[a.reason]);
160
+ }
161
+
162
+ /**
163
+ * The body of an attention notification: what needs the user, then where to see it, in `lang`. A plain string is an
164
+ * English detail (no facts): told as it is.
165
+ */
166
+ export function attentionBody(a , lang = "en") {
167
+ const text = typeof a === "string" ? a : attentionText(a, lang);
168
+ const d = shownText(text, DETAIL_MAX).trim();
169
+ return `${/[.!?]$/.test(d) ? d : `${d}.`} ${cliT(lang, "notify.howTo")}`;
170
+ }
171
+
172
+
173
+
174
+ export function summaryBody(s , lang = "en") {
175
+ const head = s.projects > 0 ? cliT(lang, "notify.importedIn", { n: s.imported, p: s.projects }) : cliT(lang, "notify.importedOnly", { n: s.imported });
176
+ const names = s.newProjects.map((n) => shownText(n, NAME_MAX)).filter((n) => n !== "");
177
+ if (names.length === 0) return head;
178
+ const shown = names.length > 3 ? cliT(lang, "notify.andMore", { names: names.slice(0, 3).join(", "), n: names.length - 3 }) : names.join(", ");
179
+ return `${head} ${cliT(lang, "notify.newProjects", { n: names.length, names: shown })}`;
180
+ }
181
+
182
+ /** What an update notification says (an automatic update that failed, was rolled back or interrupted; a major release). */
183
+ export function updateNotice(kind , v , lang = "en") {
184
+ const vars = { from: v.from ?? "?", to: v.to };
185
+ if (kind === "available") return { title: cliT(lang, "notify.update.availableTitle", vars), body: cliT(lang, "notify.update.available") };
186
+ const key = kind === "rolled-back" ? "notify.update.rolledBack" : kind === "failed" ? "notify.update.failed" : "notify.update.interrupted";
187
+ return { title: attentionTitle(lang), body: cliT(lang, key, vars) };
188
+ }
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+ /** After a cycle. Never throws. Returns the reasons a notification was attempted for. */
203
+ export async function notifyAfterCycle(i ) {
204
+ const sent = [];
205
+ try {
206
+ if (i.dryRun === true || i.mode === "off") return sent;
207
+ const last = await readLastNotified(i.stateDir);
208
+ const jobs = [];
209
+ // update-failed was announced once by the update itself (notifyOnce): the cycles never repeat it.
210
+ const lang = i.lang ?? "en";
211
+ if (i.attention && i.attention.reason !== "update-failed") jobs.push({ reason: i.attention.reason, title: attentionTitle(lang), body: attentionBody(i.attention, lang) });
212
+ if (i.summary && i.summary.imported > 0) jobs.push({ reason: SUMMARY_REASON, title: summaryTitle(lang), body: summaryBody(i.summary, lang) });
213
+ for (const j of jobs) {
214
+ if (!shouldNotify({ mode: i.mode, reason: j.reason, lastNotified: last, now: i.now })) continue;
215
+ // Marked before sending: even a crash or a timeout inside the OS call must not turn into one per cycle.
216
+ await markNotified(i.stateDir, j.reason, new Date(i.now));
217
+ sent.push(j.reason);
218
+ const ok = await i.notifier.notify(j.title, j.body).catch(() => false);
219
+ // A failed send is stamped as if sent 23 h ago: retried in 1 h, not silenced for a day and not every cycle.
220
+ if (!ok) await markNotified(i.stateDir, j.reason, new Date(i.now - (NOTIFY_INTERVAL_MS - NOTIFY_RETRY_MS)));
221
+ }
222
+ } catch { /* a notification never fails a cycle */ }
223
+ return sent;
224
+ }
225
+
226
+ /** The info reason of a major release announced by the daily update check (keys: `update-available:<version>`). */
227
+ export const UPDATE_AVAILABLE_REASON = "update-available";
228
+ /** A failed or rolled-back automatic update (keys: `update-failed:<version>`); also an attention reason (syncStatus.ts). */
229
+ export const UPDATE_FAILED_REASON = "update-failed";
230
+ /** An automatic update found interrupted at the watcher's start (keys: `update-interrupted:<version>`): its own key, so a
231
+ * later failure of the same version still notifies. */
232
+ export const UPDATE_INTERRUPTED_REASON = "update-interrupted";
233
+
234
+
235
+
236
+ /**
237
+ * One notification per key, ever (an update announcement or failure: the key names the version), unless mode is "off".
238
+ * The key is marked in lastNotified before sending, like the cycle notifications, so a crash or a failed send never
239
+ * turns into a repeat. Never throws. Returns whether a notification was attempted.
240
+ */
241
+ export async function notifyOnce(i ) {
242
+ try {
243
+ if (i.mode === "off") return false;
244
+ if ((await readLastNotified(i.stateDir))[i.key] !== undefined) return false;
245
+ await markNotified(i.stateDir, i.key, new Date(i.now));
246
+ await i.notifier.notify(i.title, i.body).catch(() => false);
247
+ return true;
248
+ } catch { return false; }
249
+ }
@@ -0,0 +1,92 @@
1
+ // The t3sm Claude Code plugin per Claude account: whether it is installed (read-only: <home>/plugins/installed_plugins.json)
2
+ // and how to install it (two `claude plugin` child processes, run only after the user's yes, each with CLAUDE_CONFIG_DIR
3
+ // set to that account's home and nothing inherited from the shell). Network access happens only in those children.
4
+
5
+
6
+ import { cliT } from "../i18n/cli.js";
7
+ import { readFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+
10
+ export const PLUGIN_NAME = "t3sm";
11
+ export const MARKETPLACE = "t3code-session-manager";
12
+ export const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE}`;
13
+ /** GitHub owner/name `claude plugin marketplace add` reads (the repository this plugin is published from). */
14
+ export const MARKETPLACE_SOURCE = "brunobola-portfolio/t3code-session-manager";
15
+ /** What removes it again. */
16
+ export const UNINSTALL_COMMAND = `claude plugin uninstall ${PLUGIN_ID}`;
17
+
18
+
19
+
20
+ const num = (v ) => v.split(".").map((p) => Number.parseInt(p, 10) || 0);
21
+ function older(a , b ) {
22
+ const x = num(a), y = num(b);
23
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0);
24
+ return false;
25
+ }
26
+
27
+ /**
28
+ * `<accountHome>/plugins/installed_plugins.json` (`{version, plugins: {"name@marketplace": [{version, ...}]}}`), read only.
29
+ * A missing or unreadable file, or any other shape, reads as "missing". `expected` is this t3sm's version: an older
30
+ * installed plugin is "outdated" (a newer one is fine).
31
+ */
32
+ export async function readPluginState(accountHome , expected ) {
33
+ let data ;
34
+ try { data = JSON.parse((await readFile(join(accountHome, "plugins", "installed_plugins.json"), "utf8")).replace(/^\uFEFF/, "")); } catch { return { state: "missing" }; }
35
+ const plugins = data && typeof data === "object" ? (data ).plugins : undefined;
36
+ const list = plugins && typeof plugins === "object" ? (plugins )[PLUGIN_ID] : undefined;
37
+ if (!Array.isArray(list) || list.length === 0) return { state: "missing" };
38
+ const first = list[0] ;
39
+ const version = first && typeof first.version === "string" && first.version !== "" ? first.version : "unknown";
40
+ return { state: version !== "unknown" && older(version, expected) ? "outdated" : "installed", version };
41
+ }
42
+
43
+ export function describePlugin(s , expected , lang = "en") {
44
+ if (s.state === "installed") return cliT(lang, "status.plugin.installed", { version: s.version });
45
+ if (s.state === "outdated") return cliT(lang, "status.plugin.outdated", { version: s.version, expected, id: PLUGIN_ID });
46
+ return cliT(lang, "status.plugin.missing");
47
+ }
48
+
49
+ /** Runs one child and resolves with its exit code and output; never throws for a failing child. */
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+ /** The environment for one account's child: the caller's, without any CLAUDE_CONFIG_DIR, plus the account's own. */
63
+ export function accountEnv(base , accountHome ) {
64
+ const env = {};
65
+ for (const [k, v] of Object.entries(base)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") env[k] = v;
66
+ env["CLAUDE_CONFIG_DIR"] = accountHome;
67
+ return env;
68
+ }
69
+
70
+ /**
71
+ * `claude plugin marketplace add <repo>` then `claude plugin install t3sm@<marketplace>`, both for this one account. A
72
+ * marketplace that is already added is fine; any other failure stops there and reports the child's output.
73
+ */
74
+ export async function installPlugin(accountHome , o ) {
75
+ if (o.claudeBin === null) return { ok: false, step: "claude", output: "claude was not found on PATH" };
76
+ const env = accountEnv(o.env, accountHome);
77
+ const steps = [
78
+ ["marketplace", ["plugin", "marketplace", "add", MARKETPLACE_SOURCE]],
79
+ ["install", ["plugin", "install", PLUGIN_ID]],
80
+ ];
81
+ let output = "";
82
+ for (const [step, args] of steps) {
83
+ let r ;
84
+ try { r = await o.exec(o.claudeBin, args, env); } catch (e) { return { ok: false, step, output: output + (e ).message }; }
85
+ output += r.output;
86
+ if (r.code !== 0 && !(step === "marketplace" && /already (been )?(added|exists?|installed)/i.test(r.output))) return { ok: false, step, output };
87
+ }
88
+ return { ok: true, output };
89
+ }
90
+
91
+ /** This install's version (src/core/version.ts). */
92
+ export { packageVersion } from "../core/version.js";
@@ -0,0 +1,113 @@
1
+ // Which account a project folder uses: exact-folder routes in config.json (t3sm projects set / unset) and the
2
+ // read-only project table (t3sm projects, the guided assistant). Pure functions; the CLI does the I/O.
3
+
4
+ import path from "node:path";
5
+ import { homedir } from "node:os";
6
+
7
+ import { expandHome, normalizeCwd, pathKey, sameCwd } from "../core/paths.js";
8
+ import { globToRegExp } from "../core/glob.js";
9
+ import { ConfigError, resolveRemap, routeAccount } from "../core/config.js";
10
+
11
+
12
+
13
+
14
+ /** A route whose match has a wildcard. Every other route names one exact folder. */
15
+ export function isGlob(match ) {
16
+ return /[*?]/.test(match);
17
+ }
18
+
19
+ /** A folder as the user typed it: `~` is `home`, then made absolute (against the current folder) and normalised. */
20
+ export function normalizeFolder(input , platform = process.platform, home = homedir()) {
21
+ const expanded = expandHome(input, home);
22
+ const abs = platform === "win32" ? path.win32.resolve(expanded) : path.posix.resolve(expanded);
23
+ return normalizeCwd(abs, platform);
24
+ }
25
+
26
+ /**
27
+ * Sets the exact-folder route of `folder` to `account`; the folder always ends on that account and no other folder's
28
+ * account changes. The folder's own route (in any spelling sameCwd accepts: trailing slash, `..`, backslashes, case
29
+ * where the system folds it) is rewritten as the normalised folder in its place, duplicates dropped; a new one goes
30
+ * right before the first wildcard route matching the folder, or at the end. If an earlier route still matches the
31
+ * folder, that one route moves to just before it (it matches only this folder, so nothing else changes).
32
+ * `previous`: the account of the folder's own route before (null: none); `before`: the account the folder had by routes
33
+ * (null: none matched); `changed`: false when config.json would stay as it is. Input not mutated. A folder whose name
34
+ * contains `*` or `?` (possible outside Windows) would become a wildcard route: ConfigError.
35
+ */
36
+ export function setRoute(c , folder , account , platform = process.platform) {
37
+ const f = normalizeCwd(folder, platform);
38
+ if (isGlob(f)) {
39
+ throw new ConfigError(`The folder ${f} contains * or ?, which routes in config.json read as wildcards, so t3sm cannot write a route for it. Rename the folder, or write the route in config.json by hand.`);
40
+ }
41
+ const same = (r ) => !isGlob(r.match) && sameCwd(r.match, f, platform);
42
+ const previous = c.routes.find(same)?.account ?? null;
43
+ const before = routeAccount(f, c, platform);
44
+ const routes = [];
45
+ let placed = false;
46
+ for (const r of c.routes) {
47
+ if (!same(r)) { routes.push(r); continue; }
48
+ if (!placed) { routes.push({ match: f, account }); placed = true; } // the normalised folder, so it matches
49
+ }
50
+ if (!placed) {
51
+ const at = routes.findIndex((r) => isGlob(r.match) && globToRegExp(r.match, platform).test(f));
52
+ routes.splice(at === -1 ? routes.length : at, 0, { match: f, account });
53
+ }
54
+ const mine = routes.findIndex((r) => r.match === f && r.account === account);
55
+ const first = routes.findIndex((r) => globToRegExp(r.match, platform).test(f));
56
+ if (first !== -1 && first < mine) routes.splice(first, 0, routes.splice(mine, 1)[0] );
57
+ const changed = JSON.stringify(routes) !== JSON.stringify(c.routes);
58
+ return { config: { ...c, routes }, previous, before, changed };
59
+ }
60
+
61
+ /** The folders of `roots` other than `folder` whose account (by routes alone) differs between `before` and `after`. */
62
+ export function otherFoldersChanged(before , after , roots , folder , platform = process.platform) {
63
+ return roots.filter((r) => !sameCwd(r, folder, platform) && routeAccount(r, before, platform) !== routeAccount(r, after, platform));
64
+ }
65
+
66
+ /** Removes the exact-folder route(s) of `folder` (never a glob). `removed`: the account it pointed at, or null. */
67
+ export function unsetRoute(c , folder , platform = process.platform) {
68
+ const f = normalizeCwd(folder, platform);
69
+ const hit = (r ) => !isGlob(r.match) && sameCwd(r.match, f, platform);
70
+ const removed = c.routes.find(hit)?.account ?? null;
71
+ return { config: { ...c, routes: c.routes.filter((r) => !hit(r)) }, removed };
72
+ }
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+ /**
88
+ * One row per project root of the plan (plan.projectAccounts, sorted by folder). `projects` null: T3 Code was not read
89
+ * (offline table). `names`: account id -> display name.
90
+ */
91
+ export function projectRows(plan , names , projects , config , platform = process.platform) {
92
+ const key = (p ) => pathKey(p, platform);
93
+ const pending = new Map ();
94
+ for (const it of plan.items) {
95
+ if (it.action.kind === "skip") continue;
96
+ const k = key(it.action.projectRoot);
97
+ pending.set(k, (pending.get(k) ?? 0) + 1);
98
+ }
99
+ const held = new Set ();
100
+ for (const it of plan.items) {
101
+ if (!it.session.flags.includes("active") || it.session.cwd === null) continue;
102
+ held.add(key(resolveRemap(it.session.cwd, config, platform).cwd));
103
+ }
104
+ return plan.projectAccounts.map((p) => {
105
+ const t = projects?.find((x) => !x.deleted && sameCwd(x.workspaceRoot, p.root, platform));
106
+ return {
107
+ folder: p.root, account: p.accountId, accountName: names[p.accountId] ?? p.accountId, reason: p.source,
108
+ pending: pending.get(key(p.root)) ?? 0,
109
+ inT3: projects === null ? null : t === undefined ? "no" : t.archived ? "archived" : "yes",
110
+ held: held.has(key(p.root)),
111
+ };
112
+ });
113
+ }