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,464 @@
|
|
|
1
|
+
// Scheduler integration for `t3sm sync`: Windows Task Scheduler (schtasks /XML), macOS LaunchAgent (launchctl), cron.
|
|
2
|
+
// Every command is an argument array run without a shell. The only command strings built here are the task XML's
|
|
3
|
+
// <Arguments> and the crontab line, each quoted for its own parser; node/bin paths holding %, CR or LF are refused
|
|
4
|
+
// (cron and the Windows command line would expand or split them).
|
|
5
|
+
//
|
|
6
|
+
// Windows: a task XML is written to <state>/schedule/t3sm-task.xml (UTF-16LE with BOM, as schtasks requires) and
|
|
7
|
+
// registered with %SystemRoot%\System32\schtasks.exe /Create /XML <file> /TN <name> /F. The principal is the current
|
|
8
|
+
// user with LogonType InteractiveToken (runs only while that user is logged on, in their session) and RunLevel
|
|
9
|
+
// LeastPrivilege (no elevation). Interval: TimeTrigger with an indefinite Repetition; --watch: LogonTrigger for that
|
|
10
|
+
// user only, started at once with /Run, plus a keep-alive TimeTrigger repeating every KEEPALIVE_MINUTES: while the
|
|
11
|
+
// watcher runs, IgnoreNew drops it (and a run that finds the watcher's pipe taken exits 0 at once); after a crash, or
|
|
12
|
+
// when a self-restarting watcher's successor (which runs outside the task) failed to start, it brings one back. Settings: IgnoreNew (never two at once), runs on battery, StartWhenAvailable
|
|
13
|
+
// (a missed run starts at logon/wake), ExecutionTimeLimit PT2H for the interval job (generous on purpose: a hard
|
|
14
|
+
// terminate in the middle of a wave is exactly what the journal has to repair) / PT0S (unlimited) for the watcher.
|
|
15
|
+
// No <Hidden>: that flag hides the task from the Task Scheduler library, not its window; the window is hidden by
|
|
16
|
+
// running the action through `conhost.exe --headless "<node>" "<bin>" sync ...` (Windows
|
|
17
|
+
// 10 1809+; verified on build 26300). conhost does not forward the child's exit code (Task Scheduler's "Last Run
|
|
18
|
+
// Result" is always 0); the outcome lives in <state>/logs/sync.log. Without conhost: `cmd.exe /c start "" /min ...`.
|
|
19
|
+
|
|
20
|
+
import { existsSync } from "node:fs";
|
|
21
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
22
|
+
import { randomBytes } from "node:crypto";
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import { homedir, release, userInfo } from "node:os";
|
|
25
|
+
import path from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
|
|
28
|
+
import { atomicWrite, renameRetrying, } from "../core/fsutil.js";
|
|
29
|
+
import { ConfigError } from "../core/config.js";
|
|
30
|
+
import { system32, systemRoot as envSystemRoot } from "../core/sysroot.js";
|
|
31
|
+
import { npmEnv } from "./update.js";
|
|
32
|
+
|
|
33
|
+
export const TASK_NAME = "t3code-session-manager sync";
|
|
34
|
+
export const LAUNCHD_LABEL = "dev.t3sm.sync";
|
|
35
|
+
export const CRON_TAG = "# t3sm";
|
|
36
|
+
/** The watcher's keep-alive: a `sync --watch` started this often exits at once while one runs (cron, Task Scheduler). */
|
|
37
|
+
export const KEEPALIVE_MINUTES = 15;
|
|
38
|
+
/** Fixed StartBoundary: the repetition grid only; StartWhenAvailable covers the first run. */
|
|
39
|
+
const START_BOUNDARY = "2026-01-01T00:00:00";
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
function checkEvery(n ) {
|
|
77
|
+
if (!Number.isInteger(n) || n < 1 || n > 1440) throw new ConfigError(`schedule.everyMinutes must be an integer 1..1440 (got ${n}).`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function checkPath(p , what ) {
|
|
81
|
+
if (/[%\r\n]/.test(p)) throw new ConfigError(`The ${what} path cannot contain %, CR or LF (the scheduler would expand or split it): ${JSON.stringify(p)}. Install t3sm in another folder.`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const xml = (s ) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
85
|
+
|
|
86
|
+
/** Double-quoted for /bin/sh inside a crontab: \ " $ ` escaped for the shell (% is refused by checkPath). */
|
|
87
|
+
function cronQuote(p ) {
|
|
88
|
+
return `"${p.replace(/([\\"$`])/g, "\\$1")}"`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function cronWhen(n ) {
|
|
92
|
+
if (n < 60) return `*/${n} * * * *`;
|
|
93
|
+
if (n === 1440) return "0 0 * * *";
|
|
94
|
+
if (n % 60 === 0) return `0 */${n / 60} * * *`;
|
|
95
|
+
throw new ConfigError(`schedule.everyMinutes = ${n} cannot be expressed in cron: use a value below 60 or a multiple of 60.`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** conhost.exe with --headless (Windows 10 1809 = build 17763 or later), else null. */
|
|
99
|
+
export function detectConhost(env = process.env, osRelease = release(), exists = existsSync) {
|
|
100
|
+
const build = Number(osRelease.split(".")[2] ?? 0);
|
|
101
|
+
if (!(build >= 17763)) return null;
|
|
102
|
+
const p = system32(env, "conhost.exe");
|
|
103
|
+
return exists(p) ? p : null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Absolute path of bin/t3sm.mjs in this checkout or install. */
|
|
107
|
+
export function defaultBinPath() {
|
|
108
|
+
return fileURLToPath(new URL("../../bin/t3sm.mjs", import.meta.url));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
/** The Task Scheduler 1.2 definition (see the header). Every value is XML-escaped. */
|
|
117
|
+
export function taskXml(i ) {
|
|
118
|
+
const cmd = `"${i.nodePath}" "${i.binPath}" ${i.args.join(" ")}`;
|
|
119
|
+
const command = i.conhost ?? path.win32.join(i.systemRoot, "System32", "cmd.exe");
|
|
120
|
+
const args = i.conhost ? `--headless ${cmd}` : `/c start "" /min ${cmd}`;
|
|
121
|
+
const repeating = (minutes ) => ` <TimeTrigger>
|
|
122
|
+
<Repetition>
|
|
123
|
+
<Interval>PT${minutes}M</Interval>
|
|
124
|
+
<StopAtDurationEnd>false</StopAtDurationEnd>
|
|
125
|
+
</Repetition>
|
|
126
|
+
<StartBoundary>${START_BOUNDARY}</StartBoundary>
|
|
127
|
+
<Enabled>true</Enabled>
|
|
128
|
+
</TimeTrigger>`;
|
|
129
|
+
const trigger = i.watch
|
|
130
|
+
? ` <LogonTrigger>
|
|
131
|
+
<Enabled>true</Enabled>
|
|
132
|
+
<UserId>${xml(i.userId)}</UserId>
|
|
133
|
+
</LogonTrigger>
|
|
134
|
+
${repeating(KEEPALIVE_MINUTES)}`
|
|
135
|
+
: repeating(i.everyMinutes);
|
|
136
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
137
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
138
|
+
<RegistrationInfo>
|
|
139
|
+
<Description>t3code-session-manager: import new agent sessions into T3 Code (t3sm sync).</Description>
|
|
140
|
+
</RegistrationInfo>
|
|
141
|
+
<Triggers>
|
|
142
|
+
${trigger}
|
|
143
|
+
</Triggers>
|
|
144
|
+
<Principals>
|
|
145
|
+
<Principal id="Author">
|
|
146
|
+
<UserId>${xml(i.userId)}</UserId>
|
|
147
|
+
<LogonType>InteractiveToken</LogonType>
|
|
148
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
149
|
+
</Principal>
|
|
150
|
+
</Principals>
|
|
151
|
+
<Settings>
|
|
152
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
153
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
154
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
155
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
156
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
157
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
158
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
159
|
+
<Enabled>true</Enabled>
|
|
160
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
161
|
+
<WakeToRun>false</WakeToRun>
|
|
162
|
+
<ExecutionTimeLimit>${i.watch ? "PT0S" : "PT2H"}</ExecutionTimeLimit>
|
|
163
|
+
<Priority>7</Priority>
|
|
164
|
+
</Settings>
|
|
165
|
+
<Actions Context="Author">
|
|
166
|
+
<Exec>
|
|
167
|
+
<Command>${xml(command)}</Command>
|
|
168
|
+
<Arguments>${xml(args)}</Arguments>
|
|
169
|
+
</Exec>
|
|
170
|
+
</Actions>
|
|
171
|
+
</Task>
|
|
172
|
+
`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function scheduleSpec(platform , nodePath , binPath , everyMinutes , opts = {}) {
|
|
176
|
+
checkEvery(everyMinutes);
|
|
177
|
+
checkPath(nodePath, "node");
|
|
178
|
+
checkPath(binPath, "t3sm");
|
|
179
|
+
const watch = opts.watch ?? false;
|
|
180
|
+
const args = watch ? ["sync", "--watch", "--quiet"] : ["sync", "--quiet"];
|
|
181
|
+
if (platform === "win32") {
|
|
182
|
+
const systemRoot = envSystemRoot(opts.systemRoot !== undefined ? { SystemRoot: opts.systemRoot } : process.env);
|
|
183
|
+
const schtasks = path.win32.join(systemRoot, "System32", "schtasks.exe");
|
|
184
|
+
const conhost = opts.conhost === undefined ? detectConhost() : opts.conhost;
|
|
185
|
+
const userId = opts.userId ?? (process.env["USERDOMAIN"] ? `${process.env["USERDOMAIN"]}\\${process.env["USERNAME"] ?? userInfo().username}` : userInfo().username);
|
|
186
|
+
if (!opts.stateDir) throw new ConfigError("scheduleSpec(win32) needs the state dir for the task XML.");
|
|
187
|
+
const xmlPath = path.win32.join(opts.stateDir, "schedule", "t3sm-task.xml");
|
|
188
|
+
const create = [schtasks, "/Create", "/XML", xmlPath, "/TN", TASK_NAME, "/F"];
|
|
189
|
+
return {
|
|
190
|
+
kind: "schtasks", watch,
|
|
191
|
+
install: watch ? [create, [schtasks, "/Run", "/TN", TASK_NAME]] : [create],
|
|
192
|
+
remove: [[schtasks, "/Delete", "/F", "/TN", TASK_NAME]],
|
|
193
|
+
query: [schtasks, "/Query", "/TN", TASK_NAME, "/FO", "CSV", "/NH"],
|
|
194
|
+
files: [{ path: xmlPath, content: taskXml({ nodePath, binPath, args, everyMinutes, watch, userId, conhost, systemRoot }), encoding: "utf16le-bom" }],
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (platform === "darwin") {
|
|
198
|
+
const home = opts.home ?? homedir();
|
|
199
|
+
const uid = opts.uid ?? userInfo().uid;
|
|
200
|
+
const plist = path.posix.join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
201
|
+
const prog = [nodePath, binPath, ...args].map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
202
|
+
// KeepAlive only after a failed exit (a second watcher exits 0 and stays down), at most one restart a minute.
|
|
203
|
+
const when = watch
|
|
204
|
+
? " <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key>\n <false/>\n </dict>\n <key>ThrottleInterval</key>\n <integer>60</integer>"
|
|
205
|
+
: ` <key>StartInterval</key>\n <integer>${everyMinutes * 60}</integer>`;
|
|
206
|
+
const content = `<?xml version="1.0" encoding="UTF-8"?>
|
|
207
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
208
|
+
<plist version="1.0">
|
|
209
|
+
<dict>
|
|
210
|
+
<key>Label</key>
|
|
211
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
212
|
+
<key>ProgramArguments</key>
|
|
213
|
+
<array>
|
|
214
|
+
${prog}
|
|
215
|
+
</array>
|
|
216
|
+
${when}
|
|
217
|
+
<key>ProcessType</key>
|
|
218
|
+
<string>Background</string>
|
|
219
|
+
</dict>
|
|
220
|
+
</plist>
|
|
221
|
+
`;
|
|
222
|
+
return {
|
|
223
|
+
kind: "launchd", watch,
|
|
224
|
+
install: [["launchctl", "bootstrap", `gui/${uid}`, plist]],
|
|
225
|
+
remove: [["launchctl", "bootout", `gui/${uid}/${LAUNCHD_LABEL}`]],
|
|
226
|
+
query: ["launchctl", "print", `gui/${uid}/${LAUNCHD_LABEL}`],
|
|
227
|
+
files: [{ path: plist, content }],
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const body = `${cronQuote(nodePath)} ${cronQuote(binPath)} ${args.join(" ")} ${CRON_TAG}`;
|
|
231
|
+
const line = `${watch ? "@reboot" : cronWhen(everyMinutes)} ${body}`;
|
|
232
|
+
const lines = watch ? [line, `${cronWhen(KEEPALIVE_MINUTES)} ${body}`] : [line];
|
|
233
|
+
return { kind: "cron", watch, install: [["crontab", "-"]], remove: [["crontab", "-"]], query: ["crontab", "-l"], cronLine: line, cronLines: lines };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------- running the spec ----------
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
/** schtasks /XML prints UTF-16 when redirected on some builds: decode by BOM / NUL pattern, else UTF-8. */
|
|
241
|
+
function decodeOutput(b ) {
|
|
242
|
+
if (b.length >= 2 && b[0] === 0xff && b[1] === 0xfe) return b.subarray(2).toString("utf16le");
|
|
243
|
+
if (b.length >= 4 && b[1] === 0 && b[3] === 0) return b.toString("utf16le");
|
|
244
|
+
return b.toString("utf8");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** realRunner's time limit when the call names none: no scheduler or pid-reader call takes anywhere near it. */
|
|
248
|
+
export const REAL_RUNNER_TIMEOUT_MS = 60_000;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* spawn without a shell; ENOENT and other spawn errors come back as code 127. The child never inherits
|
|
252
|
+
* CLAUDE_CONFIG_DIR (invariant 11), and every call has a time limit (`timeoutMs`, default REAL_RUNNER_TIMEOUT_MS):
|
|
253
|
+
* past it the child is killed by its own handle and the result is exit 124, so a hung schtasks.exe, launchctl or
|
|
254
|
+
* crontab never holds the state lock (schedule commands, the update) forever.
|
|
255
|
+
*/
|
|
256
|
+
export const realRunner = (cmd, args, opts) => new Promise((resolve) => {
|
|
257
|
+
const out = [];
|
|
258
|
+
const err = [];
|
|
259
|
+
let done = false;
|
|
260
|
+
let timer ;
|
|
261
|
+
const finish = (code , fallbackErr = "") => {
|
|
262
|
+
if (done) return;
|
|
263
|
+
done = true;
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
resolve({ code, stdout: decodeOutput(Buffer.concat(out)), stderr: decodeOutput(Buffer.concat(err)) || fallbackErr });
|
|
266
|
+
};
|
|
267
|
+
let child;
|
|
268
|
+
try {
|
|
269
|
+
child = spawn(cmd, args, { shell: false, windowsHide: true, cwd: opts?.cwd, env: npmEnv(process.env), stdio: ["pipe", "pipe", "pipe"] });
|
|
270
|
+
} catch (e) {
|
|
271
|
+
finish(127, (e ).message);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const c = child;
|
|
275
|
+
const ms = opts?.timeoutMs ?? REAL_RUNNER_TIMEOUT_MS;
|
|
276
|
+
timer = setTimeout(() => {
|
|
277
|
+
if (c.exitCode === null && c.signalCode === null) { try { c.kill(); } catch { /* gone */ } }
|
|
278
|
+
for (const st of [c.stdout, c.stderr]) { try { st.destroy(); } catch { /* closed */ } }
|
|
279
|
+
finish(124, `timed out after ${Math.round(ms / 1000)} s`);
|
|
280
|
+
}, ms);
|
|
281
|
+
timer.unref();
|
|
282
|
+
child.stdout.on("data", (d ) => void out.push(d));
|
|
283
|
+
child.stderr.on("data", (d ) => void err.push(d));
|
|
284
|
+
child.on("error", (e) => finish(127, e.message));
|
|
285
|
+
child.on("close", (code) => finish(code ?? 1));
|
|
286
|
+
child.stdin.on("error", () => {});
|
|
287
|
+
child.stdin.end(opts?.input ?? "");
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
export class ScheduleError extends Error {
|
|
291
|
+
name = "ScheduleError";
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function must(run , argv , input ) {
|
|
295
|
+
const r = await run(argv[0] , argv.slice(1), input === undefined ? undefined : { input });
|
|
296
|
+
if (r.code !== 0) {
|
|
297
|
+
const why = (r.stderr || r.stdout).trim().split(/\r?\n/)[0] || `exit ${r.code}`;
|
|
298
|
+
throw new ScheduleError(`${path.basename(argv[0] )} ${argv[1] ?? ""} failed: ${why}`);
|
|
299
|
+
}
|
|
300
|
+
return r;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The current crontab, "" when the user has none. Any other failure throws: never overwrite a crontab we could not read. */
|
|
304
|
+
async function readCrontab(run ) {
|
|
305
|
+
const r = await run("crontab", ["-l"]);
|
|
306
|
+
if (r.code === 0) return r.stdout;
|
|
307
|
+
if (/no crontab/i.test(r.stderr)) return "";
|
|
308
|
+
throw new ScheduleError(`crontab -l failed: ${(r.stderr || r.stdout).trim() || `exit ${r.code}`}`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function withoutTagged(crontab ) {
|
|
312
|
+
return crontab.split(/\r?\n/).filter((l) => l !== "" && !l.trimEnd().endsWith(CRON_TAG));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** The bytes of a schedule file: UTF-16LE with a BOM for the task XML (schtasks /XML requires it), else UTF-8. */
|
|
316
|
+
export function scheduleFileBytes(f ) {
|
|
317
|
+
return f.encoding === "utf16le-bom" ? Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(f.content, "utf16le")]) : Buffer.from(f.content, "utf8");
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The file operations install and remove need. A spec's file paths are written for the spec's platform (a win32 spec
|
|
322
|
+
* holds Windows paths), so they are real files only on that platform: tests of another platform's spec inject a fake.
|
|
323
|
+
*/
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Writes a schedule file: UTF-8 through atomicWrite; the task XML (UTF-16LE, which atomicWrite does not write) to a temp
|
|
334
|
+
* file in the same directory, then renamed over the old one with atomicWrite's retries (renameRetrying: the antivirus
|
|
335
|
+
* or the indexer holding the old XML must not fail `schedule install` or an update's re-registration).
|
|
336
|
+
*/
|
|
337
|
+
export async function writeScheduleFile(f , deps = {}) {
|
|
338
|
+
if (f.encoding !== "utf16le-bom") return atomicWrite(f.path, f.content, deps);
|
|
339
|
+
await mkdir(path.dirname(f.path), { recursive: true });
|
|
340
|
+
const tmp = `${f.path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
341
|
+
await writeFile(tmp, scheduleFileBytes(f));
|
|
342
|
+
try { await renameRetrying(tmp, f.path, deps); } catch (e) { await rm(tmp, { force: true }); throw e; }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export const realScheduleFs = {
|
|
346
|
+
write: (f) => writeScheduleFile(f),
|
|
347
|
+
remove: (p) => rm(p, { force: true }),
|
|
348
|
+
exists: existsSync,
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Idempotent: schtasks /F replaces; launchd is booted out (failure ignored) and bootstrapped, with one more
|
|
353
|
+
* bootout + bootstrap if the first bootstrap fails (a stale registration); cron replaces the tagged lines (all of them,
|
|
354
|
+
* so the keep-alive line is there once however often install runs).
|
|
355
|
+
*/
|
|
356
|
+
export async function installSchedule(spec , run , fs = realScheduleFs) {
|
|
357
|
+
if (spec.kind === "cron") {
|
|
358
|
+
const lines = withoutTagged(await readCrontab(run));
|
|
359
|
+
await must(run, spec.install[0] , [...lines, ...(spec.cronLines ?? [spec.cronLine ])].join("\n") + "\n");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
for (const f of spec.files ?? []) await fs.write(f);
|
|
363
|
+
if (spec.kind === "launchd") {
|
|
364
|
+
const bootout = async () => { for (const c of spec.remove) await run(c[0] , c.slice(1)); };
|
|
365
|
+
await bootout(); // not loaded yet: fine
|
|
366
|
+
const c = spec.install[0] ;
|
|
367
|
+
const first = await run(c[0] , c.slice(1));
|
|
368
|
+
if (first.code !== 0) {
|
|
369
|
+
await bootout();
|
|
370
|
+
await must(run, c);
|
|
371
|
+
}
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
for (const c of spec.install) await must(run, c);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export async function removeSchedule(spec , run , fs = realScheduleFs) {
|
|
378
|
+
if (spec.kind === "cron") {
|
|
379
|
+
const cur = await readCrontab(run);
|
|
380
|
+
const kept = withoutTagged(cur);
|
|
381
|
+
if (kept.length === cur.split(/\r?\n/).filter((l) => l !== "").length) return { removed: false };
|
|
382
|
+
await must(run, spec.remove[0] , kept.length ? kept.join("\n") + "\n" : "");
|
|
383
|
+
return { removed: true };
|
|
384
|
+
}
|
|
385
|
+
const status = await scheduleStatus(spec, run);
|
|
386
|
+
const hasFiles = (spec.files ?? []).some((f) => fs.exists(f.path));
|
|
387
|
+
if (!status.installed && !hasFiles) return { removed: false };
|
|
388
|
+
if (spec.kind === "launchd") {
|
|
389
|
+
for (const c of spec.remove) await run(c[0] , c.slice(1));
|
|
390
|
+
} else if (status.installed) {
|
|
391
|
+
for (const c of spec.remove) await must(run, c);
|
|
392
|
+
}
|
|
393
|
+
for (const f of spec.files ?? []) await fs.remove(f.path);
|
|
394
|
+
return { removed: status.installed || hasFiles };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** First CSV row of `schtasks /Query /FO CSV /NH`: TaskName, Next Run Time, Status (values localized, columns fixed). */
|
|
398
|
+
function csvRow(s ) {
|
|
399
|
+
const line = s.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
|
|
400
|
+
return [...line.matchAll(/"((?:[^"]|"")*)"/g)].map((m) => m[1] .replace(/""/g, '"'));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const unxml = (s ) => s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
404
|
+
const quoted = (s ) => [...s.matchAll(/"((?:\\.|[^"\\])*)"/g)].map((m) => m[1] .replace(/\\(.)/g, "$1")).filter((p) => p !== "");
|
|
405
|
+
|
|
406
|
+
/** The installed command line and the node/bin paths it runs, read back from the scheduler (or the plist). */
|
|
407
|
+
async function installedCommand(spec , run , cronLine ) {
|
|
408
|
+
try {
|
|
409
|
+
if (spec.kind === "cron") {
|
|
410
|
+
if (!cronLine) return { command: null, paths: [] };
|
|
411
|
+
const body = cronLine.replace(/^(@\w+|\S+ \S+ \S+ \S+ \S+)\s+/, "").replace(/\s*# t3sm\s*$/, "");
|
|
412
|
+
return { command: body, paths: quoted(body).slice(0, 2) };
|
|
413
|
+
}
|
|
414
|
+
if (spec.kind === "launchd") {
|
|
415
|
+
const plist = await readFile(spec.files [0] .path, "utf8");
|
|
416
|
+
const strings = [...(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(plist)?.[1] ?? "").matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => unxml(m[1] ));
|
|
417
|
+
return strings.length ? { command: strings.join(" "), paths: strings.slice(0, 2) } : { command: null, paths: [] };
|
|
418
|
+
}
|
|
419
|
+
const r = await run(spec.query[0] , ["/Query", "/TN", TASK_NAME, "/XML"]);
|
|
420
|
+
if (r.code !== 0) return { command: null, paths: [] };
|
|
421
|
+
const cmd = /<Command>([\s\S]*?)<\/Command>/.exec(r.stdout)?.[1];
|
|
422
|
+
const args = /<Arguments>([\s\S]*?)<\/Arguments>/.exec(r.stdout)?.[1];
|
|
423
|
+
if (cmd === undefined || args === undefined) return { command: null, paths: [] };
|
|
424
|
+
const a = unxml(args);
|
|
425
|
+
// Windows command line: backslashes are path separators, not escapes; the "" title of `start` is skipped.
|
|
426
|
+
const ps = [...a.matchAll(/"([^"]*)"/g)].map((m) => m[1] ).filter((p) => /[\\/]/.test(p));
|
|
427
|
+
return { command: `${unxml(cmd)} ${a}`, paths: ps.slice(0, 2) };
|
|
428
|
+
} catch {
|
|
429
|
+
return { command: null, paths: [] };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
export async function scheduleStatus(spec , run , o = {}) {
|
|
444
|
+
const exists = o.exists ?? existsSync;
|
|
445
|
+
const none = { installed: false, nextRun: null, detail: null, command: null, missing: [] };
|
|
446
|
+
let base ;
|
|
447
|
+
let cronLine = null;
|
|
448
|
+
if (spec.kind === "cron") {
|
|
449
|
+
cronLine = (await readCrontab(run)).split(/\r?\n/).find((l) => l.trimEnd().endsWith(CRON_TAG)) ?? null;
|
|
450
|
+
if (cronLine === null) return none;
|
|
451
|
+
base = { installed: true, nextRun: null, detail: cronLine };
|
|
452
|
+
} else {
|
|
453
|
+
const r = await run(spec.query[0] , spec.query.slice(1));
|
|
454
|
+
if (r.code !== 0) return none;
|
|
455
|
+
if (spec.kind === "schtasks") {
|
|
456
|
+
const row = csvRow(r.stdout);
|
|
457
|
+
base = { installed: true, nextRun: row[1] ?? null, detail: row[2] ?? null };
|
|
458
|
+
} else {
|
|
459
|
+
base = { installed: true, nextRun: null, detail: /^\s*state = (.+)$/m.exec(r.stdout)?.[1] ?? null };
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const ic = await installedCommand(spec, run, cronLine);
|
|
463
|
+
return { ...base, command: ic.command, missing: ic.paths.filter((p) => !exists(p)) };
|
|
464
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Starting the next background watcher (`sync --watch --quiet`) detached and hidden: used by a watcher that restarts
|
|
2
|
+
// into a newer install (src/cli/commands/sync.ts), by `t3sm schedule` where the scheduler cannot start one (cron), and
|
|
3
|
+
// by the update engine (src/ops/updater.ts). The watcher's daily update check starts `update --auto-run --yes` the same
|
|
4
|
+
// way (src/ops/autoUpdate.ts): the update stops the watcher, so it never runs inside the watcher's own process.
|
|
5
|
+
|
|
6
|
+
import { system32 } from "../core/sysroot.js";
|
|
7
|
+
|
|
8
|
+
/** The slice of child_process.spawn spawnSuccessor uses. */
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Starts the next watcher (`sync --watch --quiet` from the new install) detached, hidden, with stdio ignored and
|
|
30
|
+
* without CLAUDE_CONFIG_DIR, and lets it go (unref). Called after the singleton is released, so the successor finds the
|
|
31
|
+
* pipe free; if it still loses a race, or fails to start, the keep-alive trigger (every 15 min) or the next logon
|
|
32
|
+
* starts one.
|
|
33
|
+
*/
|
|
34
|
+
export function spawnSuccessor(o ) {
|
|
35
|
+
const env = {};
|
|
36
|
+
for (const [k, v] of Object.entries(o.env ?? process.env)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") env[k] = v;
|
|
37
|
+
const opts = { detached: true, stdio: "ignore" , windowsHide: true, env };
|
|
38
|
+
const argv = o.argv ?? ["sync", "--watch", "--quiet"];
|
|
39
|
+
let child ;
|
|
40
|
+
if (o.platform === "win32" && o.conhost) {
|
|
41
|
+
child = o.spawn(o.conhost, ["--headless", o.nodePath, o.binPath, ...argv], opts);
|
|
42
|
+
} else if (o.platform === "win32" && !/[%"\r\n]/.test(o.nodePath + o.binPath)) {
|
|
43
|
+
// cmd.exe parses its own command line: built verbatim, quoted as the scheduled task's (src/ops/schedule.ts).
|
|
44
|
+
const cmd = system32(o.systemRoot !== undefined ? { SystemRoot: o.systemRoot } : env, "cmd.exe");
|
|
45
|
+
child = o.spawn(cmd, ["/c", "start", '""', "/min", `"${o.nodePath}"`, `"${o.binPath}"`, ...argv], { ...opts, windowsVerbatimArguments: true });
|
|
46
|
+
} else {
|
|
47
|
+
child = o.spawn(o.nodePath, [o.binPath, ...argv], opts);
|
|
48
|
+
}
|
|
49
|
+
child.on?.("error", () => { /* the keep-alive trigger starts one */ });
|
|
50
|
+
child.unref();
|
|
51
|
+
}
|