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.
- package/.claude-plugin/marketplace.json +21 -0
- package/.claude-plugin/plugin.json +19 -0
- package/CHANGELOG.md +138 -0
- package/LICENSE +21 -0
- package/README.md +660 -2
- package/README.pt.md +616 -0
- package/bin/entry.d.mts +2 -0
- package/bin/entry.mjs +19 -0
- package/bin/t3sm.mjs +44 -0
- package/commands/import.md +30 -0
- package/commands/organize.md +36 -0
- package/commands/status.md +24 -0
- package/commands/sync.md +26 -0
- package/dist/apply/apply.js +993 -0
- package/dist/apply/claudeWriter.js +168 -0
- package/dist/apply/copyTranscript.js +116 -0
- package/dist/apply/importer.js +697 -0
- package/dist/apply/materialize.js +335 -0
- package/dist/apply/waves.js +108 -0
- package/dist/assistant/core.js +295 -0
- package/dist/assistant/deps.js +256 -0
- package/dist/assistant/i18n.js +38 -0
- package/dist/assistant/messages.en.js +494 -0
- package/dist/assistant/messages.pt.js +495 -0
- package/dist/assistant/runner.js +64 -0
- package/dist/assistant/steps.js +1362 -0
- package/dist/build.json +1 -0
- package/dist/cli/applyScreen.js +158 -0
- package/dist/cli/commands/accounts.js +254 -0
- package/dist/cli/commands/apply.js +199 -0
- package/dist/cli/commands/changelog.js +61 -0
- package/dist/cli/commands/doctor.js +105 -0
- package/dist/cli/commands/help.js +158 -0
- package/dist/cli/commands/merge.js +224 -0
- package/dist/cli/commands/organize.js +872 -0
- package/dist/cli/commands/plan.js +161 -0
- package/dist/cli/commands/projects.js +430 -0
- package/dist/cli/commands/quarantine.js +203 -0
- package/dist/cli/commands/recover.js +230 -0
- package/dist/cli/commands/rollback.js +281 -0
- package/dist/cli/commands/scan.js +117 -0
- package/dist/cli/commands/schedule.js +288 -0
- package/dist/cli/commands/start.js +45 -0
- package/dist/cli/commands/status.js +615 -0
- package/dist/cli/commands/sync.js +336 -0
- package/dist/cli/commands/update.js +398 -0
- package/dist/cli/errors.js +53 -0
- package/dist/cli/failures.js +91 -0
- package/dist/cli/flags.js +53 -0
- package/dist/cli/help.en.js +549 -0
- package/dist/cli/help.pt.js +566 -0
- package/dist/cli/helpText.js +211 -0
- package/dist/cli/helpTopics.js +58 -0
- package/dist/cli/locked.js +12 -0
- package/dist/cli/main.js +155 -0
- package/dist/cli/screen.js +3 -0
- package/dist/cli/ui.js +111 -0
- package/dist/cli/words.js +2 -0
- package/dist/core/activity.js +16 -0
- package/dist/core/changelog.js +47 -0
- package/dist/core/config.js +530 -0
- package/dist/core/fsutil.js +171 -0
- package/dist/core/glob.js +34 -0
- package/dist/core/history.js +32 -0
- package/dist/core/journal.js +274 -0
- package/dist/core/lock.js +337 -0
- package/dist/core/mask.js +31 -0
- package/dist/core/paths.js +68 -0
- package/dist/core/pid.js +101 -0
- package/dist/core/run.js +4 -0
- package/dist/core/semver.js +18 -0
- package/dist/core/sysroot.js +29 -0
- package/dist/core/types.js +229 -0
- package/dist/core/uuid.js +29 -0
- package/dist/core/version.js +72 -0
- package/dist/help/convert.md +20 -0
- package/dist/help/convert.pt.md +21 -0
- package/dist/help/cwd-unreadable.md +22 -0
- package/dist/help/cwd-unreadable.pt.md +22 -0
- package/dist/help/decisions.md +20 -0
- package/dist/help/decisions.pt.md +20 -0
- package/dist/help/errors.md +20 -0
- package/dist/help/errors.pt.md +22 -0
- package/dist/help/held.md +20 -0
- package/dist/help/held.pt.md +20 -0
- package/dist/help/history.md +27 -0
- package/dist/help/history.pt.md +29 -0
- package/dist/help/instance-unavailable.md +18 -0
- package/dist/help/instance-unavailable.pt.md +19 -0
- package/dist/help/not-imported.md +19 -0
- package/dist/help/not-imported.pt.md +19 -0
- package/dist/help/orphaned.md +19 -0
- package/dist/help/orphaned.pt.md +19 -0
- package/dist/help/project-mismatch.md +15 -0
- package/dist/help/project-mismatch.pt.md +15 -0
- package/dist/help/t3-native.md +22 -0
- package/dist/help/t3-native.pt.md +22 -0
- package/dist/help/updates.md +26 -0
- package/dist/help/updates.pt.md +28 -0
- package/dist/help/watcher.md +24 -0
- package/dist/help/watcher.pt.md +25 -0
- package/dist/i18n/cli.js +41 -0
- package/dist/i18n/lang.js +55 -0
- package/dist/i18n/messages.en.js +1140 -0
- package/dist/i18n/messages.pt.js +1149 -0
- package/dist/i18n/words.js +12 -0
- package/dist/ops/accounts.js +170 -0
- package/dist/ops/autoUpdate.js +223 -0
- package/dist/ops/discoverAccounts.js +343 -0
- package/dist/ops/doctor.js +811 -0
- package/dist/ops/elevated.js +47 -0
- package/dist/ops/errorCodes.js +39 -0
- package/dist/ops/follow.js +558 -0
- package/dist/ops/merge.js +830 -0
- package/dist/ops/notify.js +249 -0
- package/dist/ops/plugin.js +92 -0
- package/dist/ops/projects.js +113 -0
- package/dist/ops/quarantine.js +415 -0
- package/dist/ops/rollback.js +868 -0
- package/dist/ops/schedule.js +464 -0
- package/dist/ops/successor.js +51 -0
- package/dist/ops/sync.js +859 -0
- package/dist/ops/syncStatus.js +290 -0
- package/dist/ops/update.js +273 -0
- package/dist/ops/updater.js +641 -0
- package/dist/ops/watch.js +676 -0
- package/dist/ops/watcherControl.js +212 -0
- package/dist/ops/watcherHealth.js +75 -0
- package/dist/organize/apply.js +495 -0
- package/dist/organize/history.js +192 -0
- package/dist/organize/plan.js +283 -0
- package/dist/organize/rename.js +58 -0
- package/dist/organize/sessions.js +100 -0
- package/dist/organize/titles.js +70 -0
- package/dist/organize/types.js +73 -0
- package/dist/plan/categories.js +104 -0
- package/dist/plan/dedupe.js +137 -0
- package/dist/plan/folders.js +82 -0
- package/dist/plan/names.js +93 -0
- package/dist/plan/ownership.js +316 -0
- package/dist/plan/planner.js +669 -0
- package/dist/plan/rehome.js +101 -0
- package/dist/plan/report.js +407 -0
- package/dist/sources/cache.js +89 -0
- package/dist/sources/claude.js +297 -0
- package/dist/sources/codex.js +496 -0
- package/dist/sources/flatten.js +23 -0
- package/dist/sources/jsonl.js +169 -0
- package/dist/sources/native.js +233 -0
- package/dist/sources/opencode.js +483 -0
- package/dist/sources/pi.js +133 -0
- package/dist/sources/registry.js +67 -0
- package/dist/sources/types.js +80 -0
- package/dist/t3/api.js +492 -0
- package/dist/t3/auth.js +248 -0
- package/dist/t3/compat.js +62 -0
- package/dist/t3/decode.js +408 -0
- package/dist/t3/errors.js +185 -0
- package/dist/t3/rpc.js +185 -0
- package/dist/t3/runtime.js +80 -0
- package/dist/ui/caps.js +56 -0
- package/dist/ui/components.js +202 -0
- package/dist/ui/layout.js +205 -0
- package/dist/ui/list.js +423 -0
- package/dist/ui/locale.js +73 -0
- package/dist/ui/organizePreview.js +72 -0
- package/dist/ui/progress.js +237 -0
- package/dist/ui/style.js +32 -0
- package/dist/ui/terminal.js +126 -0
- package/dist/ui/text.js +186 -0
- package/package.json +58 -4
- package/skills/t3code-sessions/SKILL.md +183 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { link, mkdir, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { hostname, uptime } from "node:os";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { basename, dirname, join } from "node:path";
|
|
6
|
+
import { pidAlive } from "./pid.js";
|
|
7
|
+
|
|
8
|
+
const UNPARSEABLE_STALE_MS = 3600_000;
|
|
9
|
+
const STEAL_MUTEX_STALE_MS = 30_000;
|
|
10
|
+
const LINK_UNSUPPORTED = new Set(["EPERM", "ENOTSUP", "EXDEV", "ENOSYS", "EOPNOTSUPP"]);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The lock owner cannot have survived a reboot: the machine's uptime now is below the uptime recorded in the lock
|
|
14
|
+
* (uptime only grows within one boot, whatever the wall clock does). Its pid may since belong to an unrelated live
|
|
15
|
+
* process, so this check wins over the pid check. A lock without a recorded uptime (older t3sm): false (pid check only).
|
|
16
|
+
*/
|
|
17
|
+
export function rebootedSince(lockUptimeSec , currentUptimeSec ) {
|
|
18
|
+
return typeof lockUptimeSec === "number" && Number.isFinite(lockUptimeSec) && currentUptimeSec < lockUptimeSec;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Linux only: this boot's id (diagnostic hint in the lock body; staleness is judged by uptime). */
|
|
22
|
+
function bootIdHint() {
|
|
23
|
+
if (process.platform !== "linux") return undefined;
|
|
24
|
+
try { return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() || undefined; } catch { return undefined; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
function parseBody(raw ) {
|
|
60
|
+
try {
|
|
61
|
+
const v = JSON.parse(raw) ;
|
|
62
|
+
if (v && typeof v.pid === "number" && Number.isInteger(v.pid) && v.pid > 0 && typeof v.startedAt === "string" && typeof v.hostname === "string") {
|
|
63
|
+
const b = { pid: v.pid, startedAt: v.startedAt, hostname: v.hostname };
|
|
64
|
+
if (typeof v.uptimeSec === "number" && Number.isFinite(v.uptimeSec)) b.uptimeSec = v.uptimeSec;
|
|
65
|
+
if (typeof v.bootId === "string") b.bootId = v.bootId;
|
|
66
|
+
return b;
|
|
67
|
+
}
|
|
68
|
+
} catch { /* fall through */ }
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Create `file` atomically WITH its content: write a temp file, fsync, hard-link it to
|
|
75
|
+
* `file` (EEXIST => held), unlink the temp. No reader can ever see an empty lock.
|
|
76
|
+
* If the filesystem cannot hard-link (EPERM/ENOTSUP/EXDEV/...), fall back to an
|
|
77
|
+
* exclusive `wx` create followed by a write; that fallback has a brief window in which
|
|
78
|
+
* the lock file is empty (readers treat an empty/unparseable lock younger than 1 h as held).
|
|
79
|
+
*/
|
|
80
|
+
async function tryCreate(file , body ) {
|
|
81
|
+
const tmp = `${file}.tmp-${randomBytes(6).toString("hex")}`;
|
|
82
|
+
const fh = await open(tmp, "wx");
|
|
83
|
+
try {
|
|
84
|
+
try {
|
|
85
|
+
await fh.writeFile(JSON.stringify(body), "utf8");
|
|
86
|
+
await fh.sync();
|
|
87
|
+
} finally {
|
|
88
|
+
await fh.close();
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
await link(tmp, file);
|
|
92
|
+
return true;
|
|
93
|
+
} catch (e) {
|
|
94
|
+
const code = (e ).code ?? "";
|
|
95
|
+
if (code === "EEXIST") return false;
|
|
96
|
+
if (!LINK_UNSUPPORTED.has(code)) throw e;
|
|
97
|
+
}
|
|
98
|
+
let lf;
|
|
99
|
+
try {
|
|
100
|
+
lf = await open(file, "wx");
|
|
101
|
+
} catch (e) {
|
|
102
|
+
const code = (e ).code ?? "";
|
|
103
|
+
if (code === "EEXIST" || TRANSIENT.has(code)) return false; // held, or being deleted right now
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
await lf.writeFile(JSON.stringify(body), "utf8");
|
|
108
|
+
await lf.sync();
|
|
109
|
+
} finally {
|
|
110
|
+
await lf.close();
|
|
111
|
+
}
|
|
112
|
+
return true;
|
|
113
|
+
} finally {
|
|
114
|
+
await rmForce(tmp);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const TRANSIENT = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
119
|
+
|
|
120
|
+
/** Read a file; null if absent. On Windows a file being deleted by another process reports
|
|
121
|
+
* EPERM/EBUSY for a moment, so those are retried briefly and then rethrown. */
|
|
122
|
+
async function readIfExists(file ) {
|
|
123
|
+
for (let attempt = 0; ; attempt++) {
|
|
124
|
+
try {
|
|
125
|
+
return await readFile(file, "utf8");
|
|
126
|
+
} catch (e) {
|
|
127
|
+
const code = (e ).code ?? "";
|
|
128
|
+
if (code === "ENOENT") return null;
|
|
129
|
+
if (!TRANSIENT.has(code) || attempt >= 8) throw e;
|
|
130
|
+
await new Promise((r) => setTimeout(r, 5 * (attempt + 1)));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const rmForce = (p ) => rm(p, { force: true, maxRetries: 8, retryDelay: 10 });
|
|
136
|
+
|
|
137
|
+
async function isStale(file , raw , kill , upNow ) {
|
|
138
|
+
const b = parseBody(raw);
|
|
139
|
+
if (b) {
|
|
140
|
+
if (b.hostname !== hostname()) return false; // shared state dir: never steal
|
|
141
|
+
if (rebootedSince(b.uptimeSec, upNow())) return true; // its owner died with the last shutdown
|
|
142
|
+
return !pidAlive(b.pid, kill);
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
const s = await stat(file);
|
|
146
|
+
return Date.now() - s.mtimeMs > UNPARSEABLE_STALE_MS;
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Test hooks (deterministic interleavings). */
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Take the steal mutex (`lock.steal`, wx) holding a random token; returns the token or null.
|
|
162
|
+
*
|
|
163
|
+
* Guarantee: exclusivity comes from the exclusive `wx` create, never from rename (on Windows
|
|
164
|
+
* concurrent renames of the same file can all report success). A mutex older than 30 s is
|
|
165
|
+
* stale: we move it aside to `lock.steal.broken-<rand>`, delete that, and `wx`-create a new
|
|
166
|
+
* one; only one creator can succeed. If the moved-aside file turns out to be fresh (its
|
|
167
|
+
* owner replaced the stale one between our stat and rename) it is a live holder's mutex:
|
|
168
|
+
* it is put back with `link` (EEXIST means someone recreated it, which is fine; never
|
|
169
|
+
* `rename` back, that overwrites on POSIX), then the aside name is unlinked, and we return null.
|
|
170
|
+
*/
|
|
171
|
+
export async function takeStealMutex(path , hooks = {}) {
|
|
172
|
+
const token = randomBytes(8).toString("hex");
|
|
173
|
+
const create = async () => {
|
|
174
|
+
let fh;
|
|
175
|
+
try {
|
|
176
|
+
fh = await open(path, "wx");
|
|
177
|
+
} catch (e) {
|
|
178
|
+
if ((e ).code === "EEXIST") return false;
|
|
179
|
+
throw e;
|
|
180
|
+
}
|
|
181
|
+
try { await fh.writeFile(token, "utf8"); } finally { await fh.close(); }
|
|
182
|
+
return true;
|
|
183
|
+
};
|
|
184
|
+
if (await create()) return token;
|
|
185
|
+
let age ;
|
|
186
|
+
try {
|
|
187
|
+
age = Date.now() - (await stat(path)).mtimeMs;
|
|
188
|
+
} catch (e) {
|
|
189
|
+
if ((e ).code === "ENOENT") return (await create()) ? token : null;
|
|
190
|
+
throw e;
|
|
191
|
+
}
|
|
192
|
+
if (age <= STEAL_MUTEX_STALE_MS) return null;
|
|
193
|
+
if (hooks.afterStatBeforeBreak) await hooks.afterStatBeforeBreak();
|
|
194
|
+
const broken = `${path}.broken-${randomBytes(4).toString("hex")}`;
|
|
195
|
+
try {
|
|
196
|
+
await rename(path, broken);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
const code = (e ).code ?? "";
|
|
199
|
+
if (code === "ENOENT" || TRANSIENT.has(code)) return null; // lost the break race
|
|
200
|
+
throw e;
|
|
201
|
+
}
|
|
202
|
+
let fresh = false;
|
|
203
|
+
try {
|
|
204
|
+
fresh = Date.now() - (await stat(broken)).mtimeMs <= STEAL_MUTEX_STALE_MS;
|
|
205
|
+
} catch { /* gone: treat as stale */ }
|
|
206
|
+
if (fresh) {
|
|
207
|
+
if (hooks.afterBreakBeforePutBack) await hooks.afterBreakBeforePutBack();
|
|
208
|
+
try {
|
|
209
|
+
await link(broken, path);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
const code = (e ).code ?? "";
|
|
212
|
+
if (code !== "EEXIST") {
|
|
213
|
+
// No hard links here: recreate the mutex with the same content (best effort).
|
|
214
|
+
try {
|
|
215
|
+
const content = await readFile(broken, "utf8");
|
|
216
|
+
const fh = await open(path, "wx");
|
|
217
|
+
try { await fh.writeFile(content, "utf8"); } finally { await fh.close(); }
|
|
218
|
+
} catch { /* someone recreated it, or unrecoverable: the holder's finally tolerates a missing mutex */ }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
await rmForce(broken);
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
await rmForce(broken);
|
|
225
|
+
return (await create()) ? token : null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Take the state-dir lock at `<dir>/lock`. Returns null when held by a live owner on this machine (started after the
|
|
230
|
+
* last boot, pid alive) or by an owner on another host. Callers MUST hold this lock around any journal-mutating work
|
|
231
|
+
* (including `recoverPendingMtimes`) and `release()` it afterwards.
|
|
232
|
+
*
|
|
233
|
+
* Stealing a stale lock is serialized by a `lock.steal` mutex: inside it the lock is re-read and removed only if it
|
|
234
|
+
* still equals the content judged stale, then the exclusive create is retried once and verified by a re-read. Nothing
|
|
235
|
+
* is ever put back. A stale (>30 s) mutex is moved aside by rename and replaced by an exclusive `wx` create, so only
|
|
236
|
+
* one stealer can win (see takeStealMutex). Residual risk: a mutex holder stalled for more than 30 s combined with an
|
|
237
|
+
* exact interleaving of a second stealer could still yield two owners; accepted as practically unreachable.
|
|
238
|
+
*/
|
|
239
|
+
export async function acquireLock(dir , opts = {}) {
|
|
240
|
+
const kill = opts.kill ?? ((pid , sig ) => { process.kill(pid, sig); });
|
|
241
|
+
await mkdir(dir, { recursive: true });
|
|
242
|
+
const file = join(dir, "lock");
|
|
243
|
+
const upNow = opts.uptime ?? uptime;
|
|
244
|
+
const body = { pid: process.pid, startedAt: new Date().toISOString(), hostname: hostname(), uptimeSec: upNow() };
|
|
245
|
+
const bootId = bootIdHint();
|
|
246
|
+
if (bootId !== undefined) body.bootId = bootId;
|
|
247
|
+
|
|
248
|
+
if (await tryCreate(file, body)) return makeLock(file, body);
|
|
249
|
+
|
|
250
|
+
let raw ;
|
|
251
|
+
try {
|
|
252
|
+
raw = await readIfExists(file);
|
|
253
|
+
} catch (e) {
|
|
254
|
+
if (TRANSIENT.has((e ).code ?? "")) return null; // contended: report held
|
|
255
|
+
throw e;
|
|
256
|
+
}
|
|
257
|
+
if (raw === null) return (await tryCreate(file, body)) ? makeLock(file, body) : null; // vanished
|
|
258
|
+
if (!(await isStale(file, raw, kill, upNow))) return null;
|
|
259
|
+
|
|
260
|
+
const mutex = `${file}.steal`;
|
|
261
|
+
const token = await takeStealMutex(mutex, opts.stealHooks);
|
|
262
|
+
if (token === null) return null;
|
|
263
|
+
try {
|
|
264
|
+
const cur = await readIfExists(file);
|
|
265
|
+
if (cur !== null) {
|
|
266
|
+
if (cur !== raw) return null; // someone else already replaced it
|
|
267
|
+
await rmForce(file);
|
|
268
|
+
}
|
|
269
|
+
if (!(await tryCreate(file, body))) return null;
|
|
270
|
+
// Verify we still own it; if not, remove nothing and yield.
|
|
271
|
+
const after = await readIfExists(file).catch(() => null);
|
|
272
|
+
const mine = after !== null ? parseBody(after) : null;
|
|
273
|
+
if (!mine || mine.pid !== body.pid || mine.startedAt !== body.startedAt) return null;
|
|
274
|
+
return makeLock(file, body);
|
|
275
|
+
} finally {
|
|
276
|
+
await releaseStealMutex(mutex, token);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Release the steal mutex taken by takeStealMutex: delete every copy that still holds our token, never anyone else's.
|
|
282
|
+
*
|
|
283
|
+
* A stealer that judged the mutex stale just before we replaced it may have moved OUR fresh mutex aside
|
|
284
|
+
* (`<path>.broken-<rand>`) and be about to put it back (takeStealMutex links it back for a live holder). Deleting only
|
|
285
|
+
* `<path>` would then leave our mutex behind once it is put back, blocking steals until it goes stale (30 s). So we
|
|
286
|
+
* also delete aside copies holding our token: the stealer's put-back then finds nothing (ENOENT) and gives up, and a
|
|
287
|
+
* copy it already put back is caught on the next pass at `<path>`. A copy can only reach `<path>` from an aside name
|
|
288
|
+
* and only leave it by being moved aside, so passes repeat until two in a row find no copy of ours. Aside names are
|
|
289
|
+
* unique per stealer and never replaced, so deleting one of ours is safe; `<path>` keeps the read-then-delete of
|
|
290
|
+
* before (see the residual risk on acquireLock).
|
|
291
|
+
*/
|
|
292
|
+
export async function releaseStealMutex(path , token ) {
|
|
293
|
+
const dir = dirname(path);
|
|
294
|
+
const aside = `${basename(path)}.broken-`;
|
|
295
|
+
const ours = async (p ) => {
|
|
296
|
+
try { return (await readIfExists(p)) === token; } catch { return false; } // unreadable: not provably ours
|
|
297
|
+
};
|
|
298
|
+
for (let pass = 0, clean = 0; pass < 10 && clean < 2; pass++) {
|
|
299
|
+
let found = false;
|
|
300
|
+
if (await ours(path)) { await rmForce(path); found = true; }
|
|
301
|
+
let names = [];
|
|
302
|
+
try { names = await readdir(dir); } catch { /* dir gone: nothing left */ }
|
|
303
|
+
for (const n of names) {
|
|
304
|
+
if (n.startsWith(aside) && await ours(join(dir, n))) { await rmForce(join(dir, n)); found = true; }
|
|
305
|
+
}
|
|
306
|
+
clean = found ? 0 : clean + 1;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Parse the current lock for diagnostics (`doctor`): null if absent or unparseable. Never steals. */
|
|
311
|
+
export async function lockInfo(dir ) {
|
|
312
|
+
const file = join(dir, "lock");
|
|
313
|
+
const raw = await readIfExists(file);
|
|
314
|
+
if (raw === null) return null;
|
|
315
|
+
const b = parseBody(raw);
|
|
316
|
+
if (!b) return null;
|
|
317
|
+
const started = Date.parse(b.startedAt);
|
|
318
|
+
let ageMs ;
|
|
319
|
+
if (Number.isFinite(started)) ageMs = Date.now() - started;
|
|
320
|
+
else {
|
|
321
|
+
try { ageMs = Date.now() - (await stat(file)).mtimeMs; } catch { return null; }
|
|
322
|
+
}
|
|
323
|
+
return { pid: b.pid, startedAt: b.startedAt, hostname: b.hostname, ageMs, uptimeSec: b.uptimeSec ?? null };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function makeLock(file , body ) {
|
|
327
|
+
let released = false;
|
|
328
|
+
return {
|
|
329
|
+
async release() {
|
|
330
|
+
if (released) return;
|
|
331
|
+
released = true;
|
|
332
|
+
const raw = await readIfExists(file);
|
|
333
|
+
const cur = raw === null ? null : parseBody(raw);
|
|
334
|
+
if (cur && cur.pid === body.pid && cur.startedAt === body.startedAt) await rmForce(file);
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Email masking for everything t3sm prints or writes for people to read (screens, --json, diagnostics that users paste
|
|
2
|
+
// into issues): "demo@example.com" becomes "d***@example.com". Pure; no imports.
|
|
3
|
+
|
|
4
|
+
/** One email address, masked: its first character, then ***@ and the domain. Anything without a local part: "***". */
|
|
5
|
+
export function maskEmail(email ) {
|
|
6
|
+
const at = email.lastIndexOf("@");
|
|
7
|
+
if (at < 1) return "***";
|
|
8
|
+
return `${email[0]}***@${email.slice(at + 1)}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* An email address inside free text (Unicode local part and IDN domain; the domain needs a dot and a letter TLD, so a
|
|
13
|
+
* package spec such as `t3sm@t3code-session-manager` or `node@22` in a command is left as it is).
|
|
14
|
+
*/
|
|
15
|
+
export const EMAIL_RE = /([\p{L}\p{N}])[\p{L}\p{N}\p{M}._%+-]*@([\p{L}\p{N}\p{M}-]+(?:\.[\p{L}\p{N}\p{M}-]+)*\.[\p{L}\p{M}]{2,})/gu;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Any token holding an "@" after a non-empty local part: the broad form, for account names. The domain may be a
|
|
19
|
+
* single label ("user@localhost", "a@b") or an IP literal ("user@[10.0.0.5]").
|
|
20
|
+
*/
|
|
21
|
+
const ADDRESS_RE = /([\p{L}\p{N}])[^\s@,;:<>()[\]"]*@(\[[^\]\s]*\]|[^\s@,;:<>()[\]"]+)/gu;
|
|
22
|
+
|
|
23
|
+
/** Every email address inside free text masked (EMAIL_RE); the rest unchanged. */
|
|
24
|
+
export function maskEmailsIn(text ) {
|
|
25
|
+
return text.replace(EMAIL_RE, (_m, a , d ) => `${a}***@${d}`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Every token that looks like an address ("x@y", with or without a dot) masked: for names, where no command lives. */
|
|
29
|
+
export function maskAddressesIn(text ) {
|
|
30
|
+
return text.replace(ADDRESS_RE, (_m, a , d ) => `${a}***@${d}`);
|
|
31
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Canonical form of a working directory: forward slashes, no trailing slash,
|
|
5
|
+
* upper-case drive letter, `\\?\` prefix stripped, `.`/`..` resolved.
|
|
6
|
+
* Pure string function: never touches the filesystem. Case is preserved
|
|
7
|
+
* (compare with `sameCwd`).
|
|
8
|
+
*/
|
|
9
|
+
export function normalizeCwd(p , platform = process.platform) {
|
|
10
|
+
if (p === "") return p;
|
|
11
|
+
let out ;
|
|
12
|
+
if (platform === "win32") {
|
|
13
|
+
let s = p;
|
|
14
|
+
if (/^\\\\\?\\UNC\\/i.test(s)) s = "\\\\" + s.slice(8);
|
|
15
|
+
else if (s.startsWith("\\\\?\\")) s = s.slice(4);
|
|
16
|
+
out = path.win32.normalize(s).replace(/\\/g, "/");
|
|
17
|
+
out = out.replace(/^([A-Za-z]):\.$/, "$1:/"); // bare drive "D:" normalizes to "D:."
|
|
18
|
+
out = out.replace(/^([a-z]):/, (_m, d ) => d.toUpperCase() + ":");
|
|
19
|
+
} else {
|
|
20
|
+
out = path.posix.normalize(p);
|
|
21
|
+
}
|
|
22
|
+
if (out.length > 1 && out.endsWith("/") && !/^[A-Za-z]:\/$/.test(out)) out = out.replace(/\/+$/, "");
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Path identity for maps and sets: normalizeCwd, case-folded on Windows and macOS. One definition for every caller. */
|
|
27
|
+
export function pathKey(p , platform = process.platform) {
|
|
28
|
+
const n = normalizeCwd(p, platform);
|
|
29
|
+
return platform === "win32" || platform === "darwin" ? n.toLowerCase() : n;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function sameCwd(a , b , platform = process.platform) {
|
|
33
|
+
const na = normalizeCwd(a, platform);
|
|
34
|
+
const nb = normalizeCwd(b, platform);
|
|
35
|
+
if (platform === "win32" || platform === "darwin") return na.toLowerCase() === nb.toLowerCase();
|
|
36
|
+
return na === nb;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Claude Code's own project-directory rule: every char outside [A-Za-z0-9] becomes "-". */
|
|
40
|
+
export function encodeClaudeProjectDir(cwd ) {
|
|
41
|
+
return cwd.replace(/[^A-Za-z0-9]/g, "-");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function trimTrailingSeps(s ) {
|
|
45
|
+
return s.replace(/[\\/]+$/, "");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function expandHome(p , home ) {
|
|
49
|
+
if (p === "~") return home;
|
|
50
|
+
if (p.startsWith("~/") || p.startsWith("~\\")) return trimTrailingSeps(home) + "/" + p.slice(2);
|
|
51
|
+
return p;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `p` relative to the user home as `~/...` (forward slashes) when it lies inside it; else its normalized form. */
|
|
55
|
+
export function tildePath(p , home , platform = process.platform) {
|
|
56
|
+
const n = normalizeCwd(p, platform), h = normalizeCwd(home, platform);
|
|
57
|
+
const fold = platform === "win32" || platform === "darwin";
|
|
58
|
+
const k = (s ) => (fold ? s.toLowerCase() : s);
|
|
59
|
+
if (k(n) === k(h)) return "~";
|
|
60
|
+
const pre = h.endsWith("/") ? h : h + "/";
|
|
61
|
+
return k(n).startsWith(k(pre)) ? "~/" + n.slice(pre.length) : n;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function stateDir(env , home ) {
|
|
65
|
+
const override = env["T3SM_HOME"];
|
|
66
|
+
if (override) return override;
|
|
67
|
+
return trimTrailingSeps(home) + "/.t3code-session-manager";
|
|
68
|
+
}
|
package/dist/core/pid.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
|
|
4
|
+
import { system32 } from "./sysroot.js";
|
|
5
|
+
|
|
6
|
+
const MAX_PID = 2 ** 31 - 1;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Is process `pid` alive? Signal 0 only probes; nothing is ever sent. ESRCH = gone; any other error (EPERM: another
|
|
10
|
+
* user's process) counts as alive, so a lock or a watcher is never taken over on a doubtful answer. `kill`: test hook.
|
|
11
|
+
* A pid outside 1..2^31-1 (or not an integer) names no process: not alive, never probed (`kill(0)` would signal our
|
|
12
|
+
* own process group, and an out-of-range pid throws a non-ESRCH error that would read as alive forever).
|
|
13
|
+
*/
|
|
14
|
+
export function pidAlive(pid , kill = (p, s) => { process.kill(p, s); }) {
|
|
15
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) return false;
|
|
16
|
+
if (pid === process.pid) return true;
|
|
17
|
+
try {
|
|
18
|
+
kill(pid, 0);
|
|
19
|
+
return true;
|
|
20
|
+
} catch (e) {
|
|
21
|
+
return (e ).code !== "ESRCH";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What identifies a process before it is killed: its command line (and argv where the OS keeps it) and start time. */
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
const CLK_TCK = 100; // USER_HZ: 100 on every mainstream Linux build
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* How long reading a process's command line and start time may take. A cold powershell.exe with a CIM query at sign-in
|
|
47
|
+
* can take several seconds on a loaded machine, and a timeout means "cannot verify" (the watcher is then not stopped).
|
|
48
|
+
*/
|
|
49
|
+
export const PROCESS_INFO_TIMEOUT_MS = 15_000;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Command line and start time of process `pid`, or null when it is gone, unreadable or the answer is unusable (the
|
|
53
|
+
* caller then does not kill). The pid is validated (integer, 1..2^31-1) before any command is built: nothing else is
|
|
54
|
+
* ever interpolated. Tools are resolved to absolute paths (never PATH / CWD): win32 powershell.exe under SystemRoot
|
|
55
|
+
* (one CIM call -> JSON), POSIX /bin/ps; Linux reads /proc/<pid>/{cmdline,stat} and /proc/stat btime without a
|
|
56
|
+
* command. The whole read is bounded by `timeoutMs` (default PROCESS_INFO_TIMEOUT_MS), and so is each command, which
|
|
57
|
+
* the runner then kills: a timed-out reader is never left running.
|
|
58
|
+
*/
|
|
59
|
+
export async function processInfo(pid , platform , run , o = {}) {
|
|
60
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) return null;
|
|
61
|
+
let timer ;
|
|
62
|
+
const timeout = new Promise ((ok) => { timer = setTimeout(() => ok(null), o.timeoutMs ?? PROCESS_INFO_TIMEOUT_MS); timer.unref?.(); });
|
|
63
|
+
try {
|
|
64
|
+
return await Promise.race([read(pid, platform, run, o), timeout]);
|
|
65
|
+
} catch { return null; } finally { clearTimeout(timer); }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function read(pid , platform , run , o ) {
|
|
69
|
+
const cwd = o.cwd ?? tmpdir();
|
|
70
|
+
if (platform === "linux") {
|
|
71
|
+
const rd = o.readProc ?? ((p ) => readFile(p, "utf8"));
|
|
72
|
+
const argv = (await rd(`/proc/${pid}/cmdline`)).split("\0");
|
|
73
|
+
while (argv.length > 0 && argv[argv.length - 1] === "") argv.pop();
|
|
74
|
+
if (argv.length === 0) return null;
|
|
75
|
+
const stat = await rd(`/proc/${pid}/stat`);
|
|
76
|
+
const rest = stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/); // rest[0] is field 3
|
|
77
|
+
const ticks = Number(rest[19]); // field 22: starttime
|
|
78
|
+
const btime = Number(/^btime\s+(\d+)/m.exec(await rd("/proc/stat"))?.[1]);
|
|
79
|
+
if (!Number.isFinite(ticks) || !Number.isFinite(btime)) return null;
|
|
80
|
+
return { argv, commandLine: argv.join(" "), startedAt: (btime + ticks / CLK_TCK) * 1000 };
|
|
81
|
+
}
|
|
82
|
+
if (platform === "win32") {
|
|
83
|
+
const env = o.env ?? process.env;
|
|
84
|
+
const ps = system32(env, "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
85
|
+
const script = `Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' | Select-Object CommandLine, @{n='S';e={$_.CreationDate.ToUniversalTime().ToString('o')}} | ConvertTo-Json -Compress`;
|
|
86
|
+
const r = await run(ps, ["-NoProfile", "-NonInteractive", "-Command", script], { cwd, timeoutMs: o.timeoutMs ?? PROCESS_INFO_TIMEOUT_MS });
|
|
87
|
+
if (r.code !== 0 || r.stdout.trim() === "") return null;
|
|
88
|
+
const j = JSON.parse(r.stdout.trim()) ;
|
|
89
|
+
const startedAt = typeof j.S === "string" ? Date.parse(j.S) : Number.NaN;
|
|
90
|
+
if (typeof j.CommandLine !== "string" || j.CommandLine.trim() === "" || !Number.isFinite(startedAt)) return null;
|
|
91
|
+
return { argv: null, commandLine: j.CommandLine.trim(), startedAt };
|
|
92
|
+
}
|
|
93
|
+
const ps = async (field ) => {
|
|
94
|
+
const r = await run("/bin/ps", ["-o", field, "-p", String(pid)], { cwd, timeoutMs: o.timeoutMs ?? PROCESS_INFO_TIMEOUT_MS });
|
|
95
|
+
return r.code === 0 && r.stdout.trim() !== "" ? r.stdout.trim() : null;
|
|
96
|
+
};
|
|
97
|
+
const lstart = await ps("lstart=");
|
|
98
|
+
const commandLine = lstart === null ? null : await ps("command=");
|
|
99
|
+
const startedAt = lstart === null ? Number.NaN : Date.parse(lstart);
|
|
100
|
+
return commandLine === null || !Number.isFinite(startedAt) ? null : { argv: null, commandLine, startedAt };
|
|
101
|
+
}
|
package/dist/core/run.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Release versions: `X.Y.Z` with an optional `v` (tags are `vX.Y.Z`). Prereleases (`v0.3.1-rc1`), build metadata,
|
|
2
|
+
// partial versions and leading zeros are not releases: parseSemver returns null, so they are never installed.
|
|
3
|
+
|
|
4
|
+
const RE = /^v?(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/;
|
|
5
|
+
|
|
6
|
+
/** `[major, minor, patch]` of "v0.3.1" or "0.3.1"; null for anything that is not a release version. */
|
|
7
|
+
export function parseSemver(v ) {
|
|
8
|
+
const m = RE.exec(v);
|
|
9
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Negative, zero or positive as `a` is older than, the same as or newer than `b`. Throws for a non-release version. */
|
|
13
|
+
export function compareSemver(a , b ) {
|
|
14
|
+
const x = parseSemver(a);
|
|
15
|
+
const y = parseSemver(b);
|
|
16
|
+
if (x === null || y === null) throw new Error(`not a release version: ${JSON.stringify(x === null ? a : b)}`);
|
|
17
|
+
return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
18
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Where Windows' own programs live. t3sm starts powershell.exe, taskkill.exe, schtasks.exe, conhost.exe, cmd.exe and
|
|
2
|
+
// net.exe by their absolute path under %SystemRoot%\System32, never by bare name: without a shell, Windows resolves a
|
|
3
|
+
// bare name in the current folder before PATH, so a planted `powershell.exe` there would run instead.
|
|
4
|
+
|
|
5
|
+
import { win32 } from "node:path";
|
|
6
|
+
|
|
7
|
+
/** The Windows folder when no environment variable names one. */
|
|
8
|
+
export const DEFAULT_SYSTEM_ROOT = "C:\\Windows";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* %SystemRoot% (else %windir%) when it is a drive path such as `C:\Windows`; null when it is set to anything else (a
|
|
12
|
+
* relative folder, a drive-less `\Windows`, a network share or a device path would choose where the program comes
|
|
13
|
+
* from). Neither set: DEFAULT_SYSTEM_ROOT. A trailing separator is dropped.
|
|
14
|
+
*/
|
|
15
|
+
export function driveSystemRoot(env ) {
|
|
16
|
+
const v = env["SystemRoot"] || env["windir"];
|
|
17
|
+
if (v === undefined || v === "") return DEFAULT_SYSTEM_ROOT;
|
|
18
|
+
return /^[A-Za-z]:\\/.test(v) ? v.replace(/[\\/]+$/, "") : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** driveSystemRoot, or DEFAULT_SYSTEM_ROOT when the environment's value is not a drive path. */
|
|
22
|
+
export function systemRoot(env ) {
|
|
23
|
+
return driveSystemRoot(env) ?? DEFAULT_SYSTEM_ROOT;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `<systemRoot>\System32\<parts...>`: the absolute path of a Windows program. */
|
|
27
|
+
export function system32(env , ...parts ) {
|
|
28
|
+
return win32.join(systemRoot(env), "System32", ...parts);
|
|
29
|
+
}
|