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,12 @@
1
+ // Words several screens share: the organize questions by name, and a project folder by its last name.
2
+
3
+
4
+
5
+ /** The organize questions (organize.decided / decisionsPending keys) in words. */
6
+ export const DECISION_WORDS = {
7
+ home: "status.decision.home", "t3-refused": "status.decision.t3Refused", temp: "status.decision.temp",
8
+ system: "status.decision.system", automated: "status.decision.automated", orphaned: "status.decision.orphaned",
9
+ };
10
+
11
+ /** A project root's last folder name (what the user knows the project by). */
12
+ export const folderName = (root ) => root.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || root;
@@ -0,0 +1,170 @@
1
+ // Account instances and per-project default subscription in T3 Code.
2
+ // Writing functions here REQUIRE the caller to hold the state-dir lock (acquireLock) and to have run
3
+ // recoverPendingMtimes first; they never take the lock themselves.
4
+
5
+
6
+
7
+ import { sameCwd } from "../core/paths.js";
8
+
9
+ import { join } from "node:path";
10
+ import { ConfigError } from "../core/config.js";
11
+
12
+ /** claudeAgent (T3's default Claude instance) reads a home other than ~/.claude (inherited CLAUDE_CONFIG_DIR). Exit 2. */
13
+ export class InstanceHomeDrift extends Error {
14
+ name = "InstanceHomeDrift";
15
+ actualHome ;
16
+ constructor(actualHome ) {
17
+ super(`T3 Code's default Claude instance reads ${actualHome} instead of ~/.claude. Close T3 Code and open it from the Start menu, then retry.`);
18
+ this.actualHome = actualHome;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * claudeAgent has an EXPLICIT settings entry (T3 Code settings, Providers) for a home other than ~/.claude: restarting
24
+ * T3 Code does not change it, so the advice is to change the setting (or let `t3sm accounts --apply` re-pin it). Exit 2.
25
+ */
26
+ export class InstanceHomeConfigured extends InstanceHomeDrift {
27
+ name = "InstanceHomeConfigured";
28
+ constructor(configuredHome ) {
29
+ super(configuredHome);
30
+ this.message = `T3 Code's default Claude instance is configured to read ${configuredHome}. t3sm expects it to read ~/.claude. Change it in T3 Code settings (Providers) or run \`t3sm accounts --apply\`.`;
31
+ }
32
+ }
33
+
34
+ const isObj = (u ) => typeof u === "object" && u !== null && !Array.isArray(u);
35
+
36
+ /** The drift error for claudeAgent reading `effectiveHome`: configured (explicit settings entry) or inherited. */
37
+ export function driftError(settings , effectiveHome ) {
38
+ if (settings !== undefined && Object.hasOwn(settings, DEFAULT_ID)) return new InstanceHomeConfigured(entryHome(settings[DEFAULT_ID]) ?? effectiveHome);
39
+ return new InstanceHomeDrift(effectiveHome);
40
+ }
41
+
42
+ /** config.homePath of a provider settings entry, or null. Journals never carry anything else from an entry. */
43
+ export function entryHome(entry ) {
44
+ const c = isObj(entry) ? entry.config : undefined;
45
+ return isObj(c) && typeof c.homePath === "string" ? c.homePath : null;
46
+ }
47
+
48
+ /** The delta journaled for instance-updated: displayName/accentColor/homePath only (never environment or other config keys). */
49
+ export function appearanceDelta(entry ) {
50
+ const e = isObj(entry) ? entry : {};
51
+ return { displayName: typeof e.displayName === "string" ? e.displayName : null, accentColor: typeof e.accentColor === "string" ? e.accentColor : null, homePath: entryHome(entry) };
52
+ }
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+ export const DEFAULT_ID = "claudeAgent";
62
+
63
+ /** The home T3's default Claude instance must read: `<user home>/.claude`. */
64
+ export function defaultClaudeHome(home ) {
65
+ return join(home, ".claude");
66
+ }
67
+
68
+ /**
69
+ * T3's default Claude instance (claudeAgent) must read the config account whose home is ~/.claude, matched by HOME
70
+ * (the account may have any id). Its effective home anywhere else (e.g. T3 started with CLAUDE_CONFIG_DIR set) ->
71
+ * InstanceHomeDrift (InstanceHomeConfigured when `settings`, T3's providerInstances map, has an explicit entry for it).
72
+ * Nothing to check without such an account, or while T3 reports no home for the instance.
73
+ */
74
+ export function assertDefaultInstanceHome(
75
+ providers , accountHomes , home , platform = process.platform,
76
+ settings ,
77
+ ) {
78
+ const want = defaultClaudeHome(home);
79
+ const def = providers.find((p) => p.instanceId === DEFAULT_ID && p.driver === "claudeAgent");
80
+ if (!accountHomes.some((h) => sameCwd(h, want, platform))) {
81
+ // No ~/.claude account: the IMPLICIT default instance (inherited CLAUDE_CONFIG_DIR) must still never stand in for
82
+ // another configured account, or that account's sessions would be imported twice (once per instance). Settings
83
+ // unknown count as implicit; an explicit entry is the user's choice.
84
+ const implicit = settings === undefined || !Object.hasOwn(settings, DEFAULT_ID);
85
+ if (def && def.homePath !== null && implicit && accountHomes.some((h) => sameCwd(h, def.homePath , platform))) throw new InstanceHomeDrift(def.homePath);
86
+ return;
87
+ }
88
+ if (def && def.homePath !== null && !sameCwd(def.homePath, want, platform)) throw driftError(settings, def.homePath);
89
+ }
90
+
91
+ /**
92
+ * Read-only: decides what ensureInstances would do. The spec for T3's default instance is the one whose home is
93
+ * `defaultHome` (~/.claude; any id), or, without `defaultHome`, the spec with id claudeAgent. Throws InstanceHomeDrift
94
+ * before anything is written when claudeAgent's effective home is not that spec's home (InstanceHomeConfigured when it
95
+ * has an explicit settings entry), except that `repinExplicit` (`t3sm accounts --apply`) re-pins an explicit entry to
96
+ * the spec's home instead. "pin" lists claudeAgent whenever it exists; the write path asks pinInstanceHome, which
97
+ * reports changed:false when it is already pinned.
98
+ */
99
+ export async function planInstances(api , specs , defaultHome , opts = {}) {
100
+ const claude = (await api.providerInstances()).filter((i) => i.driver === "claudeAgent");
101
+ const plan = { create: [], pin: [], skipped: [] };
102
+ const def = specs.find((s) => (defaultHome !== undefined ? sameCwd(s.homePath, defaultHome) : s.id === DEFAULT_ID));
103
+ const defInst = claude.find((i) => i.instanceId === DEFAULT_ID);
104
+ if (def && defInst && defInst.homePath !== null && !sameCwd(defInst.homePath, def.homePath)) {
105
+ const settings = (await api.getConfig()).settings.providerInstances;
106
+ const err = driftError(settings, defInst.homePath);
107
+ if (!(err instanceof InstanceHomeConfigured && opts.repinExplicit)) throw err;
108
+ }
109
+ if (def && defInst) plan.pin.push({ ...def, id: DEFAULT_ID });
110
+ const taken = claude.map((i) => ({ instanceId: i.instanceId, homePath: i.homePath }));
111
+ for (const s of specs) {
112
+ if ((s === def && defInst) || s.id === DEFAULT_ID) continue; // served by claudeAgent: never a second instance for ~/.claude
113
+ const byId = taken.find((i) => i.instanceId === s.id);
114
+ const byHome = taken.find((i) => i.homePath !== null && sameCwd(i.homePath, s.homePath));
115
+ if (byId && (byId.homePath === null || sameCwd(byId.homePath, s.homePath))) { plan.skipped.push({ id: s.id, reason: "already present" }); continue; }
116
+ if (byId) { plan.skipped.push({ id: s.id, reason: `instance id already used with another home (${byId.homePath})` }); continue; }
117
+ if (byHome) { plan.skipped.push({ id: s.id, reason: `home already served by instance ${byHome.instanceId}` }); continue; }
118
+ plan.create.push(s);
119
+ taken.push({ instanceId: s.id, homePath: s.homePath });
120
+ }
121
+ return plan;
122
+ }
123
+
124
+ export async function ensureInstances(
125
+ api , specs , j , runId , defaultHome , opts = {},
126
+ ) {
127
+ const plan = await planInstances(api, specs, defaultHome, opts); // may throw InstanceHomeDrift: nothing written yet
128
+ const out = { created: [] , pinned: [] , skipped: plan.skipped };
129
+ for (const s of plan.pin) {
130
+ const r = await api.pinInstanceHome(s.id, s.homePath);
131
+ if (!r.changed) continue;
132
+ out.pinned.push(s.id);
133
+ await j.append({ t: "instance-pinned", runId, instanceId: s.id, previous: { homePath: entryHome(r.previous) }, next: { homePath: s.homePath } } );
134
+ }
135
+ for (const s of plan.create) {
136
+ await api.addInstance(s);
137
+ out.created.push(s.id);
138
+ await j.append({ t: "instance-created", runId, instanceId: s.id, homePath: s.homePath } );
139
+ }
140
+ return out;
141
+ }
142
+
143
+ export async function applyProjectDefaults(
144
+ api , defaults , j , runId ,
145
+ ) {
146
+ const projects = await api.listProjects();
147
+ const res = { set: [] , unchanged: [] };
148
+ for (const d of defaults) {
149
+ const p = projects.find((x) => x.id === d.projectId);
150
+ if (p && p.defaultModelSelection?.instanceId === d.instanceId) { res.unchanged.push(d.projectId); continue; }
151
+ const { previous } = await api.setProjectDefault(d.projectId, d.instanceId);
152
+ res.set.push(d.projectId);
153
+ await j.append({ t: "project-default-set", runId, projectId: d.projectId, previous, next: { instanceId: d.instanceId } });
154
+ }
155
+ return res;
156
+ }
157
+
158
+ /**
159
+ * Run before renaming an instance: the api pins an IMPLICIT instance's detected home in the same upsert, so a drifted
160
+ * home must never reach it. claudeAgent drifted -> InstanceHomeDrift; another implicit id -> only when its detected
161
+ * home equals the config account's home. Explicit entries are not pinned by a rename and pass.
162
+ */
163
+ export async function assertRenameSafe(api , instanceId , accountHome ) {
164
+ const cfg = await api.getConfig();
165
+ if (Object.hasOwn(cfg.settings.providerInstances, instanceId)) return null; // explicit entry: a rename pins nothing
166
+ const eff = (await api.providerInstances()).find((i) => i.instanceId === instanceId)?.homePath ?? null;
167
+ if (eff === null || sameCwd(eff, accountHome)) return eff; // the home an implicit instance will be pinned to
168
+ if (instanceId === DEFAULT_ID) throw new InstanceHomeDrift(eff);
169
+ throw new ConfigError(`Refusing to rename ${instanceId}: it has no settings entry and its detected home ${eff} differs from the configured ${accountHome}; renaming would pin the wrong home. Run \`t3sm accounts --apply\` first.`);
170
+ }
@@ -0,0 +1,223 @@
1
+ // The background watcher's daily update check (spec §5.3 point 3). After a cycle, at most once per 24 h
2
+ // (`lastCheckAt` in <state>/update.json), when `update.auto` is on (default) and this t3sm is a global npm install (a
3
+ // checkout is updated with git pull, the npx cache is not updated at all), it looks up the releases of the remembered
4
+ // source (or package.json's GitHub repository):
5
+ // - a newer patch or minor release (same major; 0.x minors included) is installed by a detached, hidden child
6
+ // `t3sm update --auto-run --yes`, started at most once per check: the update stops the watcher, so it must never
7
+ // run in the watcher's own process; the child takes the lock and runs runUpdate (src/ops/updater.ts). A child that
8
+ // finds the lock taken asks for another check within the hour (<state>/update.retry);
9
+ // - a newer major release is only announced: kept in update.json's `available`, one notification per version;
10
+ // - an answer counts as the day's check (no release at all included); offline (no answer): nothing is recorded, one
11
+ // line in logs/sync.log per streak, tried again in 1 h.
12
+ // The lookup (git ls-remote / npm view) is the only network call t3sm makes. Never throws for a lookup; a write error
13
+ // propagates (the watcher ignores it) but cannot repeat the check sooner than in an hour.
14
+
15
+ import { spawn as nodeSpawn } from "node:child_process";
16
+ import { readFile, rm } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+ import { loadConfig, updateAuto } from "../core/config.js";
19
+ import { atomicWrite } from "../core/fsutil.js";
20
+ import { acquireLock, } from "../core/lock.js";
21
+
22
+ import { compareSemver, parseSemver } from "../core/semver.js";
23
+
24
+ import { installRoot, packageVersion } from "../core/version.js";
25
+ import { notifyOnce, updateNotice, UPDATE_AVAILABLE_REASON, } from "./notify.js";
26
+ import { resolveLang } from "../assistant/i18n.js";
27
+ import { defaultBinPath, detectConhost } from "./schedule.js";
28
+ import { spawnSuccessor, } from "./successor.js";
29
+ import { appendSyncLog } from "./sync.js";
30
+ import { defaultUpdateSource, installKind, isRegistryInstall, ownPackageName, ownRepositoryUrl, updateRunner, } from "./update.js";
31
+ import { classify, newestRelease, readUpdateState, releaseVersions, writeUpdateState, } from "./updater.js";
32
+
33
+ export const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
34
+ /** A check that got no answer (or found the lock taken) is tried again after this long. */
35
+ export const UPDATE_CHECK_RETRY_MS = 60 * 60 * 1000;
36
+
37
+ // ---------- the retry request (an update child that found the lock taken) ----------
38
+
39
+ const RETRY_FILE = "update.retry";
40
+
41
+ /** Asks the watcher's next check to run at `at` even when the day's check already ran (best effort). */
42
+ export async function requestUpdateRetry(stateDir , at ) {
43
+ await atomicWrite(join(stateDir, RETRY_FILE), `${at.toISOString()}\n`).catch(() => { /* the next daily check comes anyway */ });
44
+ }
45
+
46
+ async function readRetry(stateDir ) {
47
+ try { const t = Date.parse((await readFile(join(stateDir, RETRY_FILE), "utf8")).trim()); return Number.isFinite(t) ? t : null; } catch { return null; }
48
+ }
49
+
50
+ /** update.json and the retry request (tests inject an in-memory one). */
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+ /**
60
+ * The release an automatic update installs: the newest one strictly newer than `installed` with the same major (a patch
61
+ * or a minor; 0.x minors included), leaving out `skip` (rolled back before). null: none.
62
+ */
63
+ export function autoTarget(installed , versions , skip = []) {
64
+ const cur = parseSemver(installed);
65
+ if (cur === null) return null;
66
+ const same = versions.filter((v) => parseSemver(v)?.[0] === cur[0] && compareSemver(v, installed) > 0);
67
+ return newestRelease(same, skip);
68
+ }
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+ /** The check, holding its own retry time and "logged once" streak for the life of the watcher. */
99
+ export function dailyUpdateCheck(d ) {
100
+ const store = d.store ?? {
101
+ read: () => readUpdateState(d.stateDir),
102
+ write: (s) => writeUpdateState(d.stateDir, s),
103
+ retryAt: () => readRetry(d.stateDir),
104
+ clearRetry: () => rm(join(d.stateDir, RETRY_FILE), { force: true }),
105
+ };
106
+ let notBefore = -Infinity; // in memory too: a failed update.json write never turns into a check (and a child) per cycle
107
+ let unavailableLogged = false;
108
+ return {
109
+ /** `stopped`: the watcher was asked to stop meanwhile (`schedule remove`, an update): no update child is started. */
110
+ async check(stopped ) {
111
+ if (d.kind !== "global") return { kind: "skipped", why: "not-installed" };
112
+ // A config.json that cannot be read: no automatic install (it may say `"auto": false`).
113
+ const config = await d.config().then((c) => c, () => undefined);
114
+ if (config === undefined || !updateAuto(config)) return { kind: "skipped", why: "auto-off" };
115
+ const now = d.now();
116
+ if (now < notBefore) return { kind: "skipped", why: "not-due" };
117
+ const state = await store.read();
118
+ const retry = (await store.retryAt?.().catch(() => null)) ?? null;
119
+ const last = Date.parse(state?.lastCheckAt ?? "");
120
+ const checkedToday = Number.isFinite(last) && now - last >= 0 && now - last < UPDATE_CHECK_INTERVAL_MS;
121
+ if (checkedToday && !(retry !== null && now >= retry)) return { kind: "skipped", why: "not-due" };
122
+ const source = state?.source ?? d.defaultSource;
123
+ if (source === null) return { kind: "skipped", why: "no-source" };
124
+ notBefore = now + UPDATE_CHECK_RETRY_MS;
125
+
126
+ const versions = await releaseVersions(source, d.run, d.platform);
127
+ if (versions === null) {
128
+ if (!unavailableLogged) { unavailableLogged = true; await d.log("update-check unavailable"); }
129
+ return { kind: "unavailable" };
130
+ }
131
+ unavailableLogged = false;
132
+ const skip = state?.skip ?? [];
133
+ const latest = newestRelease(versions, skip);
134
+ const installed = d.installed();
135
+ const install = autoTarget(installed, versions, skip);
136
+ const major = latest !== null && classify(installed, latest) === "major" ? latest : null;
137
+
138
+ const lock = await (d.lock ?? acquireLock)(d.stateDir);
139
+ if (!lock) return { kind: "skipped", why: "busy" }; // a manual update or a sync holds it: in an hour
140
+ let announcedBefore ;
141
+ try {
142
+ // Read again under the lock: an update that just ran may have changed the source or the previous version.
143
+ const cur = (await store.read()) ?? { source, lastCheckAt: null, previous: null, available: null, skip: [] };
144
+ announcedBefore = cur.available;
145
+ await store.write({ ...cur, lastCheckAt: new Date(now).toISOString(), available: major });
146
+ await store.clearRetry?.().catch(() => { /* asked again by the next busy child, if any */ });
147
+ } finally {
148
+ await lock.release();
149
+ }
150
+ if (major !== null && announcedBefore !== major) {
151
+ await d.log(`update-check available to=${major}`);
152
+ await d.announce?.(major).catch(() => { /* an announcement never fails the check */ });
153
+ }
154
+ if (install !== null && stopped?.() === true) return { kind: "skipped", why: "stopping" }; // the next watcher checks again
155
+ if (install !== null) {
156
+ await d.log(`update-check start to=${install}`);
157
+ d.spawnUpdate();
158
+ }
159
+ return { kind: "checked", latest, install, major };
160
+ },
161
+ };
162
+ }
163
+
164
+ // ---------- the watcher's real check ----------
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+ /**
185
+ * The daily check as the watcher runs it: this install's kind and version, config.json read fresh, the npm registry
186
+ * (an install that came from it) or package.json's GitHub repository as the default source, git and npm through
187
+ * updateRunner, the update child started like a successor
188
+ * (detached, hidden, without CLAUDE_CONFIG_DIR) from this install's bin, a major announced once per version, and the
189
+ * log lines in logs/sync.log.
190
+ */
191
+ /** The default source of this install: its npm package when npm installed it from the registry, else GitHub. */
192
+ function registryAwareDefault() {
193
+ const name = ownPackageName();
194
+ return defaultUpdateSource(ownRepositoryUrl(), { name, installed: isRegistryInstall(installRoot().replace(/[\\/]+$/, "")) });
195
+ }
196
+
197
+ export function watcherUpdateCheck(o ) {
198
+ const c = dailyUpdateCheck({
199
+ stateDir: o.stateDir,
200
+ installed: o.installed ?? packageVersion,
201
+ kind: o.kind ?? installKind(installRoot().replace(/[\\/]+$/, "")),
202
+ config: () => loadConfig(o.stateDir, o.home),
203
+ defaultSource: o.defaultSource !== undefined ? o.defaultSource : registryAwareDefault(),
204
+ run: o.run ?? updateRunner(o.platform, o.env),
205
+ platform: o.platform,
206
+ now: o.now,
207
+ spawnUpdate: () => spawnSuccessor({
208
+ platform: o.platform, nodePath: process.execPath, binPath: defaultBinPath(), env: o.env,
209
+ conhost: o.conhost !== undefined ? o.conhost : o.platform === "win32" ? detectConhost() : null,
210
+ spawn: o.spawn ?? (nodeSpawn ),
211
+ argv: ["update", "--auto-run", "--yes"],
212
+ }),
213
+ log: (line) => appendSyncLog(o.stateDir, `${new Date(o.now()).toISOString()} ${line}`).catch(() => { /* never fails the check */ }),
214
+ announce: async (v) => {
215
+ if (!o.notifier) return;
216
+ const config = await loadConfig(o.stateDir, o.home).catch(() => null);
217
+ // The watcher has no Io: the language is resolved as the cycle does (env, then config.json "language").
218
+ const { title, body } = updateNotice("available", { to: v }, resolveLang(null, o.env, config?.language ?? null));
219
+ await notifyOnce({ stateDir: o.stateDir, mode: config?.notify ?? "attention", notifier: o.notifier, now: o.now(), key: `${UPDATE_AVAILABLE_REASON}:${v}`, title, body });
220
+ },
221
+ });
222
+ return (stopped) => c.check(stopped);
223
+ }