tencil 0.7.0 → 0.8.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/README.md +12 -1
- package/dist/cli.mjs +19 -467
- package/dist/{cloud-jOobzTY9.d.mts → cloud-DPNrsIER.d.mts} +1 -1
- package/dist/{index-BRcZL2Ov.d.mts → index-C4SmNUQW.d.mts} +22 -1
- package/dist/index.d.mts +53 -5
- package/dist/index.mjs +1 -1
- package/dist/{loader-BevujQ44.mjs → loader-th3V-C7L.mjs} +7 -2
- package/dist/next.d.mts +6 -3
- package/dist/next.mjs +17 -3
- package/dist/overlay.global.js +44 -23
- package/dist/react.d.mts +1 -1
- package/dist/react.mjs +2 -2
- package/dist/{server-1L4Fi2wN.mjs → server-Cbvie3Om.mjs} +882 -13
- package/dist/source-attributes-Cs2NvuxG.mjs +151 -0
- package/dist/vite.d.mts +1 -1
- package/dist/vite.mjs +3 -151
- package/package.json +5 -5
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { execFile } from "node:child_process";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
2
|
+
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { access, chmod, mkdir, readFile, readlink, realpath, rename, writeFile } from "node:fs/promises";
|
|
5
5
|
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
6
|
import { promisify } from "node:util";
|
|
@@ -116,6 +116,8 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
116
116
|
type: z.literal("hello"),
|
|
117
117
|
protocol: z.literal(1),
|
|
118
118
|
pageUrl: z.string(),
|
|
119
|
+
/** Repository root the page's dev server runs in (Vite and Next integrations). */
|
|
120
|
+
root: z.string().max(4096).optional(),
|
|
119
121
|
build: BuildInfo.optional(),
|
|
120
122
|
/** Tencil Cloud access token; the local daemon has no sign-in. */
|
|
121
123
|
token: z.string().min(1).max(4096).optional()
|
|
@@ -193,7 +195,8 @@ const ClientMessage = z.discriminatedUnion("type", [
|
|
|
193
195
|
z.object({
|
|
194
196
|
type: z.literal("model.select"),
|
|
195
197
|
model: z.string().min(1).nullable()
|
|
196
|
-
})
|
|
198
|
+
}),
|
|
199
|
+
z.object({ type: z.literal("update.start") })
|
|
197
200
|
]);
|
|
198
201
|
z.object({
|
|
199
202
|
id: z.string(),
|
|
@@ -562,7 +565,8 @@ var Bridge = class {
|
|
|
562
565
|
provider: this.#provider().info(),
|
|
563
566
|
settings: this.#settings(),
|
|
564
567
|
threads: this.#options.store.list(),
|
|
565
|
-
...client.viewer && { viewer: client.viewer }
|
|
568
|
+
...client.viewer && { viewer: client.viewer },
|
|
569
|
+
...this.#options.update && { update: this.#options.update() }
|
|
566
570
|
});
|
|
567
571
|
return;
|
|
568
572
|
case "thread.create":
|
|
@@ -650,6 +654,7 @@ var Bridge = class {
|
|
|
650
654
|
if (provider?.threadId) this.#release(provider.id, provider.threadId);
|
|
651
655
|
return;
|
|
652
656
|
}
|
|
657
|
+
case "update.start": throw new Error("Tencil can't update itself here");
|
|
653
658
|
}
|
|
654
659
|
} catch (error) {
|
|
655
660
|
const threadId = "threadId" in message ? message.threadId : void 0;
|
|
@@ -1215,7 +1220,8 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
|
|
|
1215
1220
|
/**
|
|
1216
1221
|
* Works out which project folder a page belongs to:
|
|
1217
1222
|
* 1. what the user picked for this address before,
|
|
1218
|
-
* 2. the
|
|
1223
|
+
* 2. the repository root the Vite or Next loader sent, if it's a git checkout,
|
|
1224
|
+
* 3. the dev server's working directory, found from the port it listens on.
|
|
1219
1225
|
* Returns undefined when neither works; the overlay then asks.
|
|
1220
1226
|
*/
|
|
1221
1227
|
var ProjectResolver = class {
|
|
@@ -1227,11 +1233,12 @@ var ProjectResolver = class {
|
|
|
1227
1233
|
this.#exec = options.exec ?? defaultExec;
|
|
1228
1234
|
this.#platform = options.platform ?? process.platform;
|
|
1229
1235
|
}
|
|
1230
|
-
async resolve(pageUrl) {
|
|
1236
|
+
async resolve(pageUrl, claimedRoot) {
|
|
1231
1237
|
const origin = safeOrigin(pageUrl);
|
|
1232
1238
|
if (!origin) return void 0;
|
|
1233
1239
|
const remembered = await this.#memory.get(origin);
|
|
1234
1240
|
if (remembered && existsSync(remembered)) return remembered;
|
|
1241
|
+
if (claimedRoot && isGitRoot(claimedRoot)) return resolve(claimedRoot);
|
|
1235
1242
|
const port = portOf(origin);
|
|
1236
1243
|
if (!port) return void 0;
|
|
1237
1244
|
const folder = await this.folderForPort(port).catch(() => void 0);
|
|
@@ -1242,15 +1249,32 @@ var ProjectResolver = class {
|
|
|
1242
1249
|
const origin = safeOrigin(pageUrl);
|
|
1243
1250
|
return origin ? this.#memory.set(origin, resolve(root)) : Promise.resolve();
|
|
1244
1251
|
}
|
|
1245
|
-
/**
|
|
1252
|
+
/**
|
|
1253
|
+
* Folder of the process listening on `port`: its working directory, or its script's
|
|
1254
|
+
* package. When Docker publishes the port, the compose project of the container.
|
|
1255
|
+
*/
|
|
1246
1256
|
async folderForPort(port) {
|
|
1247
|
-
|
|
1257
|
+
const pids = await this.#listeners(port);
|
|
1258
|
+
if (pids.length === 0 && this.#platform === "linux") return this.#composeFolder(port);
|
|
1259
|
+
for (const pid of pids) {
|
|
1248
1260
|
const cwd = await this.#cwd(pid).catch(() => void 0);
|
|
1249
1261
|
if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return cwd;
|
|
1250
|
-
const
|
|
1262
|
+
const commandLine = await this.#commandLine(pid).catch(() => "");
|
|
1263
|
+
if (isDockerForwarder(commandLine)) return this.#composeFolder(port);
|
|
1264
|
+
const fromCommand = projectFromCommandLine(commandLine);
|
|
1251
1265
|
if (fromCommand) return fromCommand;
|
|
1252
1266
|
}
|
|
1253
1267
|
}
|
|
1268
|
+
/** Working directory of the compose project whose container publishes `port`. */
|
|
1269
|
+
async #composeFolder(port) {
|
|
1270
|
+
return firstLine(await this.#exec("docker", [
|
|
1271
|
+
"ps",
|
|
1272
|
+
"--filter",
|
|
1273
|
+
`publish=${port}`,
|
|
1274
|
+
"--format",
|
|
1275
|
+
"{{.Label \"com.docker.compose.project.working_dir\"}}"
|
|
1276
|
+
]).catch(() => ""));
|
|
1277
|
+
}
|
|
1254
1278
|
async #listeners(port) {
|
|
1255
1279
|
if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
|
|
1256
1280
|
"-ano",
|
|
@@ -1295,6 +1319,14 @@ var ProjectResolver = class {
|
|
|
1295
1319
|
]);
|
|
1296
1320
|
}
|
|
1297
1321
|
};
|
|
1322
|
+
/**
|
|
1323
|
+
* A folder with `.git` in it: a checkout, or a worktree (where `.git` is a
|
|
1324
|
+
* file). Any local page can claim a root, so only accept a real repository;
|
|
1325
|
+
* that's the same trust as picking it in the overlay.
|
|
1326
|
+
*/
|
|
1327
|
+
function isGitRoot(folder) {
|
|
1328
|
+
return isAbsolute(folder) && existsSync(join(folder, ".git"));
|
|
1329
|
+
}
|
|
1298
1330
|
/** Closest folder with a package.json at or above `folder`, or `folder` itself. */
|
|
1299
1331
|
function projectRoot(folder) {
|
|
1300
1332
|
let dir = resolve(folder);
|
|
@@ -1322,6 +1354,15 @@ function parseNetstat(output, port) {
|
|
|
1322
1354
|
return [...new Set(pids.filter(Number.isInteger))];
|
|
1323
1355
|
}
|
|
1324
1356
|
/**
|
|
1357
|
+
* Processes that forward a published container port to the host: Docker Desktop
|
|
1358
|
+
* (`com.docker.backend`, `vpnkit` before 4.x), Docker Engine on Linux (`docker-proxy`),
|
|
1359
|
+
* OrbStack (`OrbStack Helper`), Colima and Rancher Desktop (`limactl`), Podman (`gvproxy`)
|
|
1360
|
+
* and WSL 2's localhost relay (`wslrelay`).
|
|
1361
|
+
*/
|
|
1362
|
+
function isDockerForwarder(commandLine) {
|
|
1363
|
+
return /(?:^|[\\/"])(?:com\.docker\.backend|vpnkit|docker-proxy|OrbStack Helper|limactl|gvproxy|wslrelay)(?:\.exe)?(?:["\s]|$)/i.test(commandLine.trim());
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1325
1366
|
* Dev servers are started from a project's node_modules
|
|
1326
1367
|
* (`…/eyes/apps/frontend/node_modules/next/dist/bin/next dev`): the part
|
|
1327
1368
|
* before `node_modules` is the project.
|
|
@@ -1329,6 +1370,9 @@ function parseNetstat(output, port) {
|
|
|
1329
1370
|
function projectFromCommandLine(commandLine) {
|
|
1330
1371
|
return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
|
|
1331
1372
|
}
|
|
1373
|
+
function firstLine(output) {
|
|
1374
|
+
return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
|
|
1375
|
+
}
|
|
1332
1376
|
function safeOrigin(pageUrl) {
|
|
1333
1377
|
try {
|
|
1334
1378
|
return new URL(pageUrl).origin;
|
|
@@ -3257,7 +3301,7 @@ function errorMessage(error) {
|
|
|
3257
3301
|
}
|
|
3258
3302
|
//#endregion
|
|
3259
3303
|
//#region src/version.ts
|
|
3260
|
-
const VERSION = "0.
|
|
3304
|
+
const VERSION = "0.8.0";
|
|
3261
3305
|
//#endregion
|
|
3262
3306
|
//#region src/daemon/thread-store.ts
|
|
3263
3307
|
const StoreFile = z.object({
|
|
@@ -3514,6 +3558,801 @@ function isLoopbackAddress(address) {
|
|
|
3514
3558
|
return ip === "::1" || /^127(?:\.\d{1,3}){3}$/.test(ip);
|
|
3515
3559
|
}
|
|
3516
3560
|
//#endregion
|
|
3561
|
+
//#region src/service/daemon-command.ts
|
|
3562
|
+
function daemonArgs(command) {
|
|
3563
|
+
return [
|
|
3564
|
+
command.cli,
|
|
3565
|
+
"daemon",
|
|
3566
|
+
"--port",
|
|
3567
|
+
String(command.port),
|
|
3568
|
+
...command.args ?? []
|
|
3569
|
+
];
|
|
3570
|
+
}
|
|
3571
|
+
//#endregion
|
|
3572
|
+
//#region src/service/versions.ts
|
|
3573
|
+
/** Compare dotted versions by number (pre-release tags ignored): below 0, 0 or above 0. */
|
|
3574
|
+
function compareVersions(a, b) {
|
|
3575
|
+
const parts = (version) => version.split("-")[0]?.split(".").map(Number) ?? [];
|
|
3576
|
+
const [left, right] = [parts(a), parts(b)];
|
|
3577
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
3578
|
+
const difference = (left[i] ?? 0) - (right[i] ?? 0);
|
|
3579
|
+
if (difference) return difference;
|
|
3580
|
+
}
|
|
3581
|
+
return 0;
|
|
3582
|
+
}
|
|
3583
|
+
/**
|
|
3584
|
+
* npx reuses what it cached for `npx tencil`, so an older Tencil can run after
|
|
3585
|
+
* a newer one was set up. It must never replace that newer daemon.
|
|
3586
|
+
*/
|
|
3587
|
+
function isNewerThanThis(version) {
|
|
3588
|
+
return version !== void 0 && compareVersions(version, VERSION) > 0;
|
|
3589
|
+
}
|
|
3590
|
+
var NewerDaemonError = class extends Error {
|
|
3591
|
+
constructor(running) {
|
|
3592
|
+
super(`Tencil ${running} is already running and this is ${VERSION}, which is older. Run \`npx tencil@latest\` instead.`);
|
|
3593
|
+
this.name = "NewerDaemonError";
|
|
3594
|
+
}
|
|
3595
|
+
};
|
|
3596
|
+
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
3597
|
+
/** Where to look Tencil up: npm, or `TENCIL_REGISTRY_URL` (a mirror, a test registry). */
|
|
3598
|
+
function registryUrl(env = process.env) {
|
|
3599
|
+
return (env.TENCIL_REGISTRY_URL || DEFAULT_REGISTRY).replace(/\/+$/, "");
|
|
3600
|
+
}
|
|
3601
|
+
/**
|
|
3602
|
+
* Machines that shouldn't phone home: `TENCIL_NO_UPDATE_CHECK` is set, or
|
|
3603
|
+
* it's CI. Neither the CLI nor the daemon asks the registry then.
|
|
3604
|
+
*/
|
|
3605
|
+
function updateChecksDisabled(env = process.env) {
|
|
3606
|
+
const set = (value) => value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
3607
|
+
return set(env.TENCIL_NO_UPDATE_CHECK) || set(env.CI);
|
|
3608
|
+
}
|
|
3609
|
+
/** The newest published Tencil, or undefined when the registry doesn't answer quickly. */
|
|
3610
|
+
async function latestVersion(options = {}) {
|
|
3611
|
+
const response = await fetch(`${options.registry ?? registryUrl()}/tencil/latest`, { signal: AbortSignal.timeout(options.timeoutMs ?? 1500) }).catch(() => void 0);
|
|
3612
|
+
if (!response?.ok) return void 0;
|
|
3613
|
+
const body = await response.json().catch(() => void 0);
|
|
3614
|
+
return typeof body?.version === "string" ? body.version : void 0;
|
|
3615
|
+
}
|
|
3616
|
+
/** A one-line nudge when a newer Tencil is published. */
|
|
3617
|
+
async function updateNotice() {
|
|
3618
|
+
if (updateChecksDisabled()) return void 0;
|
|
3619
|
+
const latest = await latestVersion();
|
|
3620
|
+
return latest && isNewerThanThis(latest) ? `Tencil ${latest} is out (this is ${VERSION}): npx tencil@latest` : void 0;
|
|
3621
|
+
}
|
|
3622
|
+
//#endregion
|
|
3623
|
+
//#region src/service/background.ts
|
|
3624
|
+
/**
|
|
3625
|
+
* Start the daemon in the background unless it already runs. A daemon from an
|
|
3626
|
+
* older Tencil version is replaced so pages always get the current overlay;
|
|
3627
|
+
* so is one running with other flags than the ones given. Without flags of
|
|
3628
|
+
* its own, a replacement keeps the running daemon's (`--listen`, `--t3-url`, …).
|
|
3629
|
+
*/
|
|
3630
|
+
async function startInBackground(command, dataDir) {
|
|
3631
|
+
const running = await probeDaemon(command.port);
|
|
3632
|
+
if (running && isNewerThanThis(running.version)) return {
|
|
3633
|
+
status: "running",
|
|
3634
|
+
pid: running.pid,
|
|
3635
|
+
newer: running.version
|
|
3636
|
+
};
|
|
3637
|
+
const flags = command.args?.length ? command.args : running?.flags ?? [];
|
|
3638
|
+
if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
|
|
3639
|
+
status: "running",
|
|
3640
|
+
pid: running.pid
|
|
3641
|
+
};
|
|
3642
|
+
if (running) await stopDaemon(command.port);
|
|
3643
|
+
spawnDaemon({
|
|
3644
|
+
...command,
|
|
3645
|
+
args: flags
|
|
3646
|
+
}, dataDir);
|
|
3647
|
+
const health = await waitForDaemon(command.port, dataDir);
|
|
3648
|
+
return {
|
|
3649
|
+
status: running ? "restarted" : "started",
|
|
3650
|
+
pid: health.pid
|
|
3651
|
+
};
|
|
3652
|
+
}
|
|
3653
|
+
/** Launch the daemon detached, logging to daemon.log. Doesn't wait for it. */
|
|
3654
|
+
function spawnDaemon(command, dataDir) {
|
|
3655
|
+
mkdirSync(dataDir, { recursive: true });
|
|
3656
|
+
const logFile = openSync(join(dataDir, "daemon.log"), "a");
|
|
3657
|
+
spawn(command.node, daemonArgs(command), {
|
|
3658
|
+
detached: true,
|
|
3659
|
+
stdio: [
|
|
3660
|
+
"ignore",
|
|
3661
|
+
logFile,
|
|
3662
|
+
logFile
|
|
3663
|
+
],
|
|
3664
|
+
windowsHide: true
|
|
3665
|
+
}).unref();
|
|
3666
|
+
}
|
|
3667
|
+
/** Wait for a daemon on `port` (optionally one of `version`) to answer. */
|
|
3668
|
+
async function waitForDaemon(port, dataDir, version, attempts = 100) {
|
|
3669
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
3670
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
3671
|
+
const health = await probeDaemon(port);
|
|
3672
|
+
if (health && (!version || health.version === version)) return health;
|
|
3673
|
+
}
|
|
3674
|
+
throw new Error(`The daemon didn't start. See ${join(dataDir, "daemon.log")}.`);
|
|
3675
|
+
}
|
|
3676
|
+
function sameFlags(a, b) {
|
|
3677
|
+
return a.length === b.length && a.every((flag, i) => flag === b[i]);
|
|
3678
|
+
}
|
|
3679
|
+
/** Stop the daemon answering on `port`. Returns false when none was running. */
|
|
3680
|
+
async function stopDaemon(port = DEFAULT_PORT) {
|
|
3681
|
+
const running = await probeDaemon(port);
|
|
3682
|
+
if (!running) return false;
|
|
3683
|
+
try {
|
|
3684
|
+
process.kill(running.pid, "SIGTERM");
|
|
3685
|
+
} catch {
|
|
3686
|
+
return false;
|
|
3687
|
+
}
|
|
3688
|
+
for (let attempt = 0; attempt < 50; attempt++) {
|
|
3689
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
3690
|
+
if (!await probeDaemon(port)) return true;
|
|
3691
|
+
}
|
|
3692
|
+
return true;
|
|
3693
|
+
}
|
|
3694
|
+
//#endregion
|
|
3695
|
+
//#region src/service/login-service.ts
|
|
3696
|
+
function serviceNames(port = DEFAULT_PORT) {
|
|
3697
|
+
const own = port !== DEFAULT_PORT;
|
|
3698
|
+
return {
|
|
3699
|
+
label: own ? `dev.tencil.daemon.${port}` : "dev.tencil.daemon",
|
|
3700
|
+
unit: own ? `tencil-${port}.service` : "tencil.service",
|
|
3701
|
+
task: own ? `Tencil ${port}` : "Tencil"
|
|
3702
|
+
};
|
|
3703
|
+
}
|
|
3704
|
+
/**
|
|
3705
|
+
* What the daemon needs from the shell that installed it. launchd and systemd
|
|
3706
|
+
* start it with a bare PATH (`/usr/bin:/bin`), where nvm's npm and npx, which
|
|
3707
|
+
* it runs to pair and to install the Claude Agent SDK, can't be found; and a
|
|
3708
|
+
* custom XDG_CONFIG_HOME must reach it, or it reads another data folder than
|
|
3709
|
+
* the CLI. npx's and npm's own folders (anything in node_modules) are left out of PATH.
|
|
3710
|
+
*/
|
|
3711
|
+
function serviceEnvironment(command, env = process.env) {
|
|
3712
|
+
const separator = process.platform === "win32" ? ";" : ":";
|
|
3713
|
+
const entries = [dirname(command.node), ...(env.PATH ?? "").split(separator)].filter((entry) => entry && !/[\\/](?:_npx|node_modules)[\\/]/.test(entry));
|
|
3714
|
+
const environment = { PATH: [...new Set(entries)].join(separator) };
|
|
3715
|
+
if (env.XDG_CONFIG_HOME) environment.XDG_CONFIG_HOME = env.XDG_CONFIG_HOME;
|
|
3716
|
+
return environment;
|
|
3717
|
+
}
|
|
3718
|
+
function launchdPlist(command, logPath, environment = {}) {
|
|
3719
|
+
const args = [command.node, ...daemonArgs(command)].map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n");
|
|
3720
|
+
const variables = Object.entries(environment).map(([key, value]) => ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`).join("\n");
|
|
3721
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
3722
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3723
|
+
<plist version="1.0">
|
|
3724
|
+
<dict>
|
|
3725
|
+
<key>Label</key>
|
|
3726
|
+
<string>${serviceNames(command.port).label}</string>
|
|
3727
|
+
<key>ProgramArguments</key>
|
|
3728
|
+
<array>
|
|
3729
|
+
${args}
|
|
3730
|
+
</array>
|
|
3731
|
+
<key>EnvironmentVariables</key>
|
|
3732
|
+
<dict>
|
|
3733
|
+
${variables}
|
|
3734
|
+
</dict>
|
|
3735
|
+
<key>RunAtLoad</key>
|
|
3736
|
+
<true/>
|
|
3737
|
+
<key>KeepAlive</key>
|
|
3738
|
+
<true/>
|
|
3739
|
+
<key>StandardOutPath</key>
|
|
3740
|
+
<string>${escapeXml(logPath)}</string>
|
|
3741
|
+
<key>StandardErrorPath</key>
|
|
3742
|
+
<string>${escapeXml(logPath)}</string>
|
|
3743
|
+
</dict>
|
|
3744
|
+
</plist>
|
|
3745
|
+
`;
|
|
3746
|
+
}
|
|
3747
|
+
function systemdUnit(command, environment = {}) {
|
|
3748
|
+
return `[Unit]
|
|
3749
|
+
Description=Tencil daemon
|
|
3750
|
+
|
|
3751
|
+
[Service]
|
|
3752
|
+
${Object.entries(environment).map(([key, value]) => `Environment="${key}=${value}"\n`).join("")}ExecStart=${[command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ")}
|
|
3753
|
+
Restart=on-failure
|
|
3754
|
+
|
|
3755
|
+
[Install]
|
|
3756
|
+
WantedBy=default.target
|
|
3757
|
+
`;
|
|
3758
|
+
}
|
|
3759
|
+
function windowsTaskCommand(command) {
|
|
3760
|
+
return [command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ");
|
|
3761
|
+
}
|
|
3762
|
+
const launchAgent = (names) => join(homedir(), "Library", "LaunchAgents", `${names.label}.plist`);
|
|
3763
|
+
const systemdUnitPath = (names) => join(homedir(), ".config", "systemd", "user", names.unit);
|
|
3764
|
+
const launchdDomain = () => `gui/${process.getuid?.() ?? 501}`;
|
|
3765
|
+
/** Whether Tencil is set up to start at login, serving `port`. */
|
|
3766
|
+
function isServiceInstalled(port = DEFAULT_PORT) {
|
|
3767
|
+
return servicePort(readServiceDefinition(serviceNames(port))) === port;
|
|
3768
|
+
}
|
|
3769
|
+
/** The daemon port in a launchd plist, systemd unit or scheduled task definition. */
|
|
3770
|
+
function servicePort(definition) {
|
|
3771
|
+
const match = definition?.match(/--port(?:<\/string>\s*<string>|"?\s+"?|"\s*")(\d+)/);
|
|
3772
|
+
return match?.[1] ? Number(match[1]) : void 0;
|
|
3773
|
+
}
|
|
3774
|
+
/** The launchd plist, systemd unit or scheduled task behind `names`, if installed. */
|
|
3775
|
+
function readServiceDefinition(names) {
|
|
3776
|
+
try {
|
|
3777
|
+
switch (process.platform) {
|
|
3778
|
+
case "darwin": return readFileSync(launchAgent(names), "utf8");
|
|
3779
|
+
case "linux": return readFileSync(systemdUnitPath(names), "utf8");
|
|
3780
|
+
case "win32": return execFileSync("schtasks", [
|
|
3781
|
+
"/Query",
|
|
3782
|
+
"/TN",
|
|
3783
|
+
names.task,
|
|
3784
|
+
"/XML"
|
|
3785
|
+
], {
|
|
3786
|
+
encoding: "utf8",
|
|
3787
|
+
stdio: [
|
|
3788
|
+
"ignore",
|
|
3789
|
+
"pipe",
|
|
3790
|
+
"ignore"
|
|
3791
|
+
]
|
|
3792
|
+
});
|
|
3793
|
+
default: return;
|
|
3794
|
+
}
|
|
3795
|
+
} catch {
|
|
3796
|
+
return;
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
/** Install (or replace) the login service and start the daemon through it. */
|
|
3800
|
+
async function installService(command, dataDir) {
|
|
3801
|
+
const logPath = join(dataDir, "daemon.log");
|
|
3802
|
+
const names = serviceNames(command.port);
|
|
3803
|
+
const { unit: unitName, task } = names;
|
|
3804
|
+
mkdirSync(dataDir, { recursive: true });
|
|
3805
|
+
switch (process.platform) {
|
|
3806
|
+
case "darwin": {
|
|
3807
|
+
const plist = launchAgent(names);
|
|
3808
|
+
quietly("launchctl", [
|
|
3809
|
+
"bootout",
|
|
3810
|
+
launchdDomain(),
|
|
3811
|
+
plist
|
|
3812
|
+
]);
|
|
3813
|
+
await stopDaemon(command.port);
|
|
3814
|
+
mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
|
|
3815
|
+
writeFileSync(plist, launchdPlist(command, logPath, serviceEnvironment(command)));
|
|
3816
|
+
execFileSync("launchctl", [
|
|
3817
|
+
"bootstrap",
|
|
3818
|
+
launchdDomain(),
|
|
3819
|
+
plist
|
|
3820
|
+
]);
|
|
3821
|
+
return plist;
|
|
3822
|
+
}
|
|
3823
|
+
case "linux": {
|
|
3824
|
+
const unit = systemdUnitPath(names);
|
|
3825
|
+
quietly("systemctl", [
|
|
3826
|
+
"--user",
|
|
3827
|
+
"stop",
|
|
3828
|
+
unitName
|
|
3829
|
+
]);
|
|
3830
|
+
await stopDaemon(command.port);
|
|
3831
|
+
mkdirSync(join(homedir(), ".config", "systemd", "user"), { recursive: true });
|
|
3832
|
+
writeFileSync(unit, systemdUnit(command, serviceEnvironment(command)));
|
|
3833
|
+
execFileSync("systemctl", ["--user", "daemon-reload"]);
|
|
3834
|
+
execFileSync("systemctl", [
|
|
3835
|
+
"--user",
|
|
3836
|
+
"enable",
|
|
3837
|
+
"--now",
|
|
3838
|
+
unitName
|
|
3839
|
+
], { stdio: [
|
|
3840
|
+
"ignore",
|
|
3841
|
+
"ignore",
|
|
3842
|
+
"pipe"
|
|
3843
|
+
] });
|
|
3844
|
+
return unit;
|
|
3845
|
+
}
|
|
3846
|
+
case "win32":
|
|
3847
|
+
quietly("schtasks", [
|
|
3848
|
+
"/End",
|
|
3849
|
+
"/TN",
|
|
3850
|
+
task
|
|
3851
|
+
]);
|
|
3852
|
+
await stopDaemon(command.port);
|
|
3853
|
+
execFileSync("schtasks", [
|
|
3854
|
+
"/Create",
|
|
3855
|
+
"/F",
|
|
3856
|
+
"/SC",
|
|
3857
|
+
"ONLOGON",
|
|
3858
|
+
"/TN",
|
|
3859
|
+
task,
|
|
3860
|
+
"/TR",
|
|
3861
|
+
windowsTaskCommand(command)
|
|
3862
|
+
]);
|
|
3863
|
+
execFileSync("schtasks", [
|
|
3864
|
+
"/Run",
|
|
3865
|
+
"/TN",
|
|
3866
|
+
task
|
|
3867
|
+
]);
|
|
3868
|
+
return `Task Scheduler: ${task}`;
|
|
3869
|
+
default: throw new Error(`Login service isn't supported on ${process.platform}; use \`tencil start\`.`);
|
|
3870
|
+
}
|
|
3871
|
+
}
|
|
3872
|
+
/** Stop the service's daemon until the next login, without uninstalling it. */
|
|
3873
|
+
async function stopService(port = DEFAULT_PORT) {
|
|
3874
|
+
const names = serviceNames(port);
|
|
3875
|
+
const { unit, task } = names;
|
|
3876
|
+
switch (process.platform) {
|
|
3877
|
+
case "darwin":
|
|
3878
|
+
quietly("launchctl", [
|
|
3879
|
+
"bootout",
|
|
3880
|
+
launchdDomain(),
|
|
3881
|
+
launchAgent(names)
|
|
3882
|
+
]);
|
|
3883
|
+
break;
|
|
3884
|
+
case "linux":
|
|
3885
|
+
quietly("systemctl", [
|
|
3886
|
+
"--user",
|
|
3887
|
+
"stop",
|
|
3888
|
+
unit
|
|
3889
|
+
]);
|
|
3890
|
+
break;
|
|
3891
|
+
case "win32": quietly("schtasks", [
|
|
3892
|
+
"/End",
|
|
3893
|
+
"/TN",
|
|
3894
|
+
task
|
|
3895
|
+
]);
|
|
3896
|
+
}
|
|
3897
|
+
await stopDaemon(port);
|
|
3898
|
+
}
|
|
3899
|
+
async function uninstallService(port = DEFAULT_PORT) {
|
|
3900
|
+
removeService(serviceNames(port));
|
|
3901
|
+
await stopDaemon(port);
|
|
3902
|
+
}
|
|
3903
|
+
/** Unload and delete the service behind `names`, wherever it is in its life. */
|
|
3904
|
+
function removeService(names) {
|
|
3905
|
+
switch (process.platform) {
|
|
3906
|
+
case "darwin":
|
|
3907
|
+
quietly("launchctl", [
|
|
3908
|
+
"bootout",
|
|
3909
|
+
launchdDomain(),
|
|
3910
|
+
launchAgent(names)
|
|
3911
|
+
]);
|
|
3912
|
+
rmSync(launchAgent(names), { force: true });
|
|
3913
|
+
break;
|
|
3914
|
+
case "linux":
|
|
3915
|
+
quietly("systemctl", [
|
|
3916
|
+
"--user",
|
|
3917
|
+
"disable",
|
|
3918
|
+
"--now",
|
|
3919
|
+
names.unit
|
|
3920
|
+
]);
|
|
3921
|
+
rmSync(systemdUnitPath(names), { force: true });
|
|
3922
|
+
quietly("systemctl", ["--user", "daemon-reload"]);
|
|
3923
|
+
break;
|
|
3924
|
+
case "win32":
|
|
3925
|
+
quietly("schtasks", [
|
|
3926
|
+
"/End",
|
|
3927
|
+
"/TN",
|
|
3928
|
+
names.task
|
|
3929
|
+
]);
|
|
3930
|
+
quietly("schtasks", [
|
|
3931
|
+
"/Delete",
|
|
3932
|
+
"/F",
|
|
3933
|
+
"/TN",
|
|
3934
|
+
names.task
|
|
3935
|
+
]);
|
|
3936
|
+
}
|
|
3937
|
+
}
|
|
3938
|
+
/** Run a command whose failure only means "nothing to do" (not loaded, already gone). */
|
|
3939
|
+
function quietly(command, args) {
|
|
3940
|
+
try {
|
|
3941
|
+
execFileSync(command, args, { stdio: "ignore" });
|
|
3942
|
+
} catch {}
|
|
3943
|
+
}
|
|
3944
|
+
function escapeXml(value) {
|
|
3945
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
3946
|
+
}
|
|
3947
|
+
//#endregion
|
|
3948
|
+
//#region src/service/autostart.ts
|
|
3949
|
+
/**
|
|
3950
|
+
* Running from a package manager's install (npx's cache, a project, a global
|
|
3951
|
+
* prefix) rather than a source checkout. Those can be cleaned up or upgraded
|
|
3952
|
+
* under a login service, so it gets its own copy.
|
|
3953
|
+
*/
|
|
3954
|
+
function isPackageInstall(cliPath) {
|
|
3955
|
+
return /[\\/]node_modules[\\/]/.test(cliPath);
|
|
3956
|
+
}
|
|
3957
|
+
/** The login service's own copy of Tencil; one per port, like the service. */
|
|
3958
|
+
function runtimeDir(dataDir, port = DEFAULT_PORT) {
|
|
3959
|
+
return join(dataDir, port === 4747 ? "runtime" : `runtime-${port}`);
|
|
3960
|
+
}
|
|
3961
|
+
function runtimeCli(dataDir, port = DEFAULT_PORT) {
|
|
3962
|
+
return cliIn(runtimeDir(dataDir, port));
|
|
3963
|
+
}
|
|
3964
|
+
/** The CLI of a Tencil installed with `npm install --prefix dir`. */
|
|
3965
|
+
function cliIn(dir) {
|
|
3966
|
+
return join(dir, "node_modules", "tencil", "dist", "cli.mjs");
|
|
3967
|
+
}
|
|
3968
|
+
function runtimeInstallArgs(dataDir, spec, port = DEFAULT_PORT) {
|
|
3969
|
+
return installArgs(runtimeDir(dataDir, port), spec);
|
|
3970
|
+
}
|
|
3971
|
+
function installArgs(dir, spec) {
|
|
3972
|
+
const registry = process.env.TENCIL_REGISTRY_URL;
|
|
3973
|
+
return [
|
|
3974
|
+
"install",
|
|
3975
|
+
"--prefix",
|
|
3976
|
+
dir,
|
|
3977
|
+
spec,
|
|
3978
|
+
"--no-audit",
|
|
3979
|
+
"--no-fund",
|
|
3980
|
+
"--loglevel=error",
|
|
3981
|
+
...registry ? ["--registry", registry] : []
|
|
3982
|
+
];
|
|
3983
|
+
}
|
|
3984
|
+
/**
|
|
3985
|
+
* Start Tencil at login and now. Keeps the running daemon's flags unless new
|
|
3986
|
+
* ones are given. `from` installs another package spec (a local tarball) as
|
|
3987
|
+
* the service's copy instead of this version from npm.
|
|
3988
|
+
*/
|
|
3989
|
+
async function enableAutostart(command, dataDir, from) {
|
|
3990
|
+
const running = await probeDaemon(command.port);
|
|
3991
|
+
if (running && isNewerThanThis(running.version)) throw new NewerDaemonError(running.version);
|
|
3992
|
+
const args = command.args?.length ? command.args : running?.flags ?? [];
|
|
3993
|
+
let cli = command.cli;
|
|
3994
|
+
if (isPackageInstall(cli)) {
|
|
3995
|
+
const spec = from && existsSync(from) ? resolve(from) : from ?? `tencil@${VERSION}`;
|
|
3996
|
+
const result = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", runtimeInstallArgs(dataDir, spec, command.port), {
|
|
3997
|
+
encoding: "utf8",
|
|
3998
|
+
stdio: [
|
|
3999
|
+
"ignore",
|
|
4000
|
+
"ignore",
|
|
4001
|
+
"pipe"
|
|
4002
|
+
],
|
|
4003
|
+
shell: process.platform === "win32",
|
|
4004
|
+
env: withoutNpmEnv()
|
|
4005
|
+
});
|
|
4006
|
+
if (result.status !== 0) throw new Error(`Couldn't install Tencil for the login service (npm ${result.status ?? "failed"}): ${result.stderr?.trim() ?? ""}`);
|
|
4007
|
+
cli = runtimeCli(dataDir, command.port);
|
|
4008
|
+
}
|
|
4009
|
+
const where = await installService({
|
|
4010
|
+
...command,
|
|
4011
|
+
cli,
|
|
4012
|
+
args
|
|
4013
|
+
}, dataDir);
|
|
4014
|
+
await waitForDaemon(command.port, dataDir);
|
|
4015
|
+
return where;
|
|
4016
|
+
}
|
|
4017
|
+
/**
|
|
4018
|
+
* Make sure this version of the daemon runs. With a login service it is
|
|
4019
|
+
* updated in place, since stopping its daemon would only make it restart.
|
|
4020
|
+
*/
|
|
4021
|
+
async function ensureDaemon(command, dataDir) {
|
|
4022
|
+
if (!isServiceInstalled(command.port)) {
|
|
4023
|
+
const { status, newer } = await startInBackground(command, dataDir);
|
|
4024
|
+
return {
|
|
4025
|
+
status,
|
|
4026
|
+
autostart: false,
|
|
4027
|
+
newer
|
|
4028
|
+
};
|
|
4029
|
+
}
|
|
4030
|
+
const running = await probeDaemon(command.port);
|
|
4031
|
+
if (running && isNewerThanThis(running.version)) return {
|
|
4032
|
+
status: "running",
|
|
4033
|
+
autostart: true,
|
|
4034
|
+
newer: running.version
|
|
4035
|
+
};
|
|
4036
|
+
const flags = command.args?.length ? command.args : running?.flags ?? [];
|
|
4037
|
+
if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
|
|
4038
|
+
status: "running",
|
|
4039
|
+
autostart: true
|
|
4040
|
+
};
|
|
4041
|
+
await enableAutostart(command, dataDir);
|
|
4042
|
+
return {
|
|
4043
|
+
status: running ? "restarted" : "started",
|
|
4044
|
+
autostart: true
|
|
4045
|
+
};
|
|
4046
|
+
}
|
|
4047
|
+
//#endregion
|
|
4048
|
+
//#region src/service/self-update.ts
|
|
4049
|
+
/**
|
|
4050
|
+
* Updating from the overlay. The daemon installs the new version next to the
|
|
4051
|
+
* runtime (`runtime.next`), then hands off to a helper process, since a
|
|
4052
|
+
* login service's daemon can't restart itself: stopping it ends the
|
|
4053
|
+
* service. The helper swaps the copies, restarts the daemon on the new one
|
|
4054
|
+
* and keeps the old copy (`runtime.previous`) until the new daemon answers.
|
|
4055
|
+
* If it doesn't, the old copy goes back and the old daemon is restarted.
|
|
4056
|
+
*/
|
|
4057
|
+
function stagingDir(dataDir, port) {
|
|
4058
|
+
return `${runtimeDir(dataDir, port)}.next`;
|
|
4059
|
+
}
|
|
4060
|
+
function previousDir(dataDir, port) {
|
|
4061
|
+
return `${runtimeDir(dataDir, port)}.previous`;
|
|
4062
|
+
}
|
|
4063
|
+
/** Why the last update was rolled back, for the restarted old daemon to report. */
|
|
4064
|
+
function failureFile(dataDir, port) {
|
|
4065
|
+
return `${runtimeDir(dataDir, port)}.failed.json`;
|
|
4066
|
+
}
|
|
4067
|
+
function planFile(dataDir, port) {
|
|
4068
|
+
return `${runtimeDir(dataDir, port)}.update.json`;
|
|
4069
|
+
}
|
|
4070
|
+
/** The setup way (`runtimeInstallArgs`), without blocking the daemon while npm runs. */
|
|
4071
|
+
const npmInstall = (spec, dir) => new Promise((resolve, reject) => {
|
|
4072
|
+
const child = spawn(process.platform === "win32" ? "npm.cmd" : "npm", installArgs(dir, spec), {
|
|
4073
|
+
stdio: [
|
|
4074
|
+
"ignore",
|
|
4075
|
+
"ignore",
|
|
4076
|
+
"pipe"
|
|
4077
|
+
],
|
|
4078
|
+
shell: process.platform === "win32",
|
|
4079
|
+
env: withoutNpmEnv(),
|
|
4080
|
+
windowsHide: true
|
|
4081
|
+
});
|
|
4082
|
+
let stderr = "";
|
|
4083
|
+
child.stderr?.on("data", (chunk) => {
|
|
4084
|
+
stderr = (stderr + String(chunk)).slice(-2e3);
|
|
4085
|
+
});
|
|
4086
|
+
const timer = setTimeout(() => child.kill(), 3e5);
|
|
4087
|
+
child.once("error", (error) => {
|
|
4088
|
+
clearTimeout(timer);
|
|
4089
|
+
reject(error);
|
|
4090
|
+
});
|
|
4091
|
+
child.once("close", (code) => {
|
|
4092
|
+
clearTimeout(timer);
|
|
4093
|
+
if (code === 0) return resolve();
|
|
4094
|
+
const lines = stderr.trim().split("\n").slice(-3).join(" ");
|
|
4095
|
+
reject(/* @__PURE__ */ new Error(`npm install failed (${code ?? "killed"})${lines ? `: ${lines}` : ""}`));
|
|
4096
|
+
});
|
|
4097
|
+
});
|
|
4098
|
+
/** Install `version` into the staging folder. Returns its CLI. */
|
|
4099
|
+
async function stageUpdate(version, options) {
|
|
4100
|
+
const dir = stagingDir(options.dataDir, options.port);
|
|
4101
|
+
rmSync(dir, {
|
|
4102
|
+
recursive: true,
|
|
4103
|
+
force: true
|
|
4104
|
+
});
|
|
4105
|
+
mkdirSync(dir, { recursive: true });
|
|
4106
|
+
await (options.install ?? npmInstall)(`tencil@${version}`, dir);
|
|
4107
|
+
const installed = installedVersion(dir);
|
|
4108
|
+
if (installed !== version) {
|
|
4109
|
+
rmSync(dir, {
|
|
4110
|
+
recursive: true,
|
|
4111
|
+
force: true
|
|
4112
|
+
});
|
|
4113
|
+
throw new Error(`Installed ${installed ? `Tencil ${installed}` : "nothing"}, not ${version}`);
|
|
4114
|
+
}
|
|
4115
|
+
return cliIn(dir);
|
|
4116
|
+
}
|
|
4117
|
+
function installedVersion(dir) {
|
|
4118
|
+
try {
|
|
4119
|
+
const pkg = JSON.parse(readFileSync(join(dir, "node_modules", "tencil", "package.json"), "utf8"));
|
|
4120
|
+
return existsSync(cliIn(dir)) ? pkg.version : void 0;
|
|
4121
|
+
} catch {
|
|
4122
|
+
return;
|
|
4123
|
+
}
|
|
4124
|
+
}
|
|
4125
|
+
/**
|
|
4126
|
+
* Start the helper (`tencil finish-update`) from `cli`, detached so it
|
|
4127
|
+
* outlives this daemon. On Linux a service's processes all stop with it,
|
|
4128
|
+
* so the helper gets its own scope there.
|
|
4129
|
+
*/
|
|
4130
|
+
function handOffUpdate(plan, cli) {
|
|
4131
|
+
const file = planFile(plan.dataDir, plan.port);
|
|
4132
|
+
writeFileSync(file, JSON.stringify(plan, null, 2));
|
|
4133
|
+
const args = [
|
|
4134
|
+
cli,
|
|
4135
|
+
"finish-update",
|
|
4136
|
+
file
|
|
4137
|
+
];
|
|
4138
|
+
const scoped = process.platform === "linux" && isServiceInstalled(plan.port) && spawnSync("systemd-run", ["--version"], { stdio: "ignore" }).status === 0;
|
|
4139
|
+
const logFile = openSync(join(plan.dataDir, "daemon.log"), "a");
|
|
4140
|
+
spawn(scoped ? "systemd-run" : plan.node, scoped ? [
|
|
4141
|
+
"--user",
|
|
4142
|
+
"--scope",
|
|
4143
|
+
"--collect",
|
|
4144
|
+
"--quiet",
|
|
4145
|
+
plan.node,
|
|
4146
|
+
...args
|
|
4147
|
+
] : args, {
|
|
4148
|
+
detached: true,
|
|
4149
|
+
stdio: [
|
|
4150
|
+
"ignore",
|
|
4151
|
+
logFile,
|
|
4152
|
+
logFile
|
|
4153
|
+
],
|
|
4154
|
+
windowsHide: true
|
|
4155
|
+
}).unref();
|
|
4156
|
+
}
|
|
4157
|
+
function readPlan(file) {
|
|
4158
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
4159
|
+
}
|
|
4160
|
+
/** Restart the daemon on `command.cli`: through the login service if there is one. */
|
|
4161
|
+
async function restartDaemon(command, dataDir) {
|
|
4162
|
+
if (isServiceInstalled(command.port)) {
|
|
4163
|
+
await installService(command, dataDir);
|
|
4164
|
+
return;
|
|
4165
|
+
}
|
|
4166
|
+
await stopDaemon(command.port);
|
|
4167
|
+
spawnDaemon(command, dataDir);
|
|
4168
|
+
}
|
|
4169
|
+
/**
|
|
4170
|
+
* The helper's job. Returns whether the daemon now runs `plan.version`;
|
|
4171
|
+
* when it doesn't, the old version runs again and the reason is in
|
|
4172
|
+
* `failureFile`.
|
|
4173
|
+
*/
|
|
4174
|
+
async function finishUpdate(plan, options = {}) {
|
|
4175
|
+
const { dataDir, port } = plan;
|
|
4176
|
+
const restart = options.restart ?? restartDaemon;
|
|
4177
|
+
const attempts = options.attempts ?? 300;
|
|
4178
|
+
const current = runtimeDir(dataDir, port);
|
|
4179
|
+
const previous = previousDir(dataDir, port);
|
|
4180
|
+
const command = (cli) => ({
|
|
4181
|
+
node: plan.node,
|
|
4182
|
+
cli,
|
|
4183
|
+
port,
|
|
4184
|
+
args: plan.flags
|
|
4185
|
+
});
|
|
4186
|
+
rmSync(planFile(dataDir, port), { force: true });
|
|
4187
|
+
rmSync(failureFile(dataDir, port), { force: true });
|
|
4188
|
+
rmSync(previous, {
|
|
4189
|
+
recursive: true,
|
|
4190
|
+
force: true
|
|
4191
|
+
});
|
|
4192
|
+
const hadRuntime = existsSync(current);
|
|
4193
|
+
try {
|
|
4194
|
+
if (hadRuntime) renameSync(current, previous);
|
|
4195
|
+
renameSync(stagingDir(dataDir, port), current);
|
|
4196
|
+
await restart(command(runtimeCli(dataDir, port)), dataDir);
|
|
4197
|
+
await waitForDaemon(port, dataDir, plan.version, attempts);
|
|
4198
|
+
rmSync(previous, {
|
|
4199
|
+
recursive: true,
|
|
4200
|
+
force: true
|
|
4201
|
+
});
|
|
4202
|
+
return true;
|
|
4203
|
+
} catch (error) {
|
|
4204
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4205
|
+
writeFileSync(failureFile(dataDir, port), JSON.stringify({
|
|
4206
|
+
version: plan.version,
|
|
4207
|
+
error: message
|
|
4208
|
+
}));
|
|
4209
|
+
if (existsSync(previous)) {
|
|
4210
|
+
rmSync(current, {
|
|
4211
|
+
recursive: true,
|
|
4212
|
+
force: true
|
|
4213
|
+
});
|
|
4214
|
+
renameSync(previous, current);
|
|
4215
|
+
} else if (!hadRuntime) rmSync(current, {
|
|
4216
|
+
recursive: true,
|
|
4217
|
+
force: true
|
|
4218
|
+
});
|
|
4219
|
+
await restart(command(plan.previousCli), dataDir).catch(() => {});
|
|
4220
|
+
await waitForDaemon(port, dataDir, void 0, attempts).catch(() => {});
|
|
4221
|
+
return false;
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
/** The rolled-back update's version and error, read once by the daemon that runs again. */
|
|
4225
|
+
function takeUpdateFailure(dataDir, port) {
|
|
4226
|
+
const file = failureFile(dataDir, port);
|
|
4227
|
+
try {
|
|
4228
|
+
const failure = JSON.parse(readFileSync(file, "utf8"));
|
|
4229
|
+
rmSync(file, { force: true });
|
|
4230
|
+
return failure;
|
|
4231
|
+
} catch {
|
|
4232
|
+
return;
|
|
4233
|
+
}
|
|
4234
|
+
}
|
|
4235
|
+
//#endregion
|
|
4236
|
+
//#region src/daemon/updates.ts
|
|
4237
|
+
const DAY_MS = 864e5;
|
|
4238
|
+
const HOUR_MS = 36e5;
|
|
4239
|
+
/**
|
|
4240
|
+
* Looks for new Tencil versions (on start, then about daily) and runs an
|
|
4241
|
+
* update started from the overlay: install it, wait until no thread is
|
|
4242
|
+
* running, then hand over to the helper that restarts the daemon on it.
|
|
4243
|
+
*
|
|
4244
|
+
* It waits rather than carrying threads across: Claude Code runs inside
|
|
4245
|
+
* the daemon, so a restart would end its running turns.
|
|
4246
|
+
*/
|
|
4247
|
+
var Updater = class {
|
|
4248
|
+
#options;
|
|
4249
|
+
#status = { state: "idle" };
|
|
4250
|
+
#timer;
|
|
4251
|
+
#restartTimer;
|
|
4252
|
+
#disposed = false;
|
|
4253
|
+
constructor(options) {
|
|
4254
|
+
this.#options = options;
|
|
4255
|
+
const failure = takeUpdateFailure(options.dataDir, options.port);
|
|
4256
|
+
if (failure) this.#status = {
|
|
4257
|
+
state: "failed",
|
|
4258
|
+
error: `Tencil ${failure.version} didn't start (${failure.error})`
|
|
4259
|
+
};
|
|
4260
|
+
}
|
|
4261
|
+
status() {
|
|
4262
|
+
return this.#status;
|
|
4263
|
+
}
|
|
4264
|
+
/** Check now and then on a timer. Never waits for the registry. */
|
|
4265
|
+
start() {
|
|
4266
|
+
const { check = !updateChecksDisabled() } = this.#options;
|
|
4267
|
+
if (check) this.check();
|
|
4268
|
+
}
|
|
4269
|
+
async check() {
|
|
4270
|
+
clearTimeout(this.#timer);
|
|
4271
|
+
const latest = await latestVersion({
|
|
4272
|
+
registry: this.#options.registry,
|
|
4273
|
+
timeoutMs: 5e3
|
|
4274
|
+
});
|
|
4275
|
+
if (this.#disposed) return;
|
|
4276
|
+
this.#timer = setTimeout(() => void this.check(), latest ? this.#options.intervalMs ?? DAY_MS : HOUR_MS);
|
|
4277
|
+
this.#timer.unref?.();
|
|
4278
|
+
if (!latest) return;
|
|
4279
|
+
const newer = compareVersions(latest, this.#options.version) > 0 ? latest : void 0;
|
|
4280
|
+
if (newer === this.#status.latest) return;
|
|
4281
|
+
this.#set({
|
|
4282
|
+
...this.#status,
|
|
4283
|
+
latest: newer
|
|
4284
|
+
});
|
|
4285
|
+
}
|
|
4286
|
+
/** Move to the latest version. Progress and failures arrive through `onChange`. */
|
|
4287
|
+
async update() {
|
|
4288
|
+
const { latest, state } = this.#status;
|
|
4289
|
+
if (state !== "idle" && state !== "failed") return;
|
|
4290
|
+
const { cli, dataDir, port, log } = this.#options;
|
|
4291
|
+
if (!latest) return this.#fail("Tencil is up to date");
|
|
4292
|
+
if (!cli) return this.#fail("This daemon wasn't started by the Tencil CLI");
|
|
4293
|
+
try {
|
|
4294
|
+
this.#set({
|
|
4295
|
+
latest,
|
|
4296
|
+
state: "installing"
|
|
4297
|
+
});
|
|
4298
|
+
log(`Installing Tencil ${latest}`);
|
|
4299
|
+
await stageUpdate(latest, {
|
|
4300
|
+
dataDir,
|
|
4301
|
+
port,
|
|
4302
|
+
install: this.#options.install
|
|
4303
|
+
});
|
|
4304
|
+
await this.#idle(latest);
|
|
4305
|
+
this.#set({
|
|
4306
|
+
latest,
|
|
4307
|
+
state: "restarting"
|
|
4308
|
+
});
|
|
4309
|
+
log(`Restarting on Tencil ${latest}`);
|
|
4310
|
+
(this.#options.handOff ?? ((plan) => handOffUpdate(plan, cli)))({
|
|
4311
|
+
version: latest,
|
|
4312
|
+
port,
|
|
4313
|
+
dataDir,
|
|
4314
|
+
node: this.#options.node,
|
|
4315
|
+
flags: this.#options.flags,
|
|
4316
|
+
previousCli: cli
|
|
4317
|
+
});
|
|
4318
|
+
this.#restartTimer = setTimeout(() => this.#fail(`Tencil ${latest} didn't take over. See daemon.log.`), this.#options.restartTimeoutMs ?? 12e4);
|
|
4319
|
+
this.#restartTimer.unref?.();
|
|
4320
|
+
} catch (error) {
|
|
4321
|
+
this.#fail(error instanceof Error ? error.message : String(error));
|
|
4322
|
+
}
|
|
4323
|
+
}
|
|
4324
|
+
dispose() {
|
|
4325
|
+
this.#disposed = true;
|
|
4326
|
+
clearTimeout(this.#timer);
|
|
4327
|
+
clearTimeout(this.#restartTimer);
|
|
4328
|
+
}
|
|
4329
|
+
async #idle(latest) {
|
|
4330
|
+
for (;;) {
|
|
4331
|
+
const running = await this.#options.running();
|
|
4332
|
+
if (!running) return;
|
|
4333
|
+
if (this.#status.state !== "waiting" || this.#status.running !== running) this.#set({
|
|
4334
|
+
latest,
|
|
4335
|
+
state: "waiting",
|
|
4336
|
+
running
|
|
4337
|
+
});
|
|
4338
|
+
await new Promise((resolve) => setTimeout(resolve, this.#options.idlePollMs ?? 1e3));
|
|
4339
|
+
if (this.#disposed) throw new Error("The daemon stopped");
|
|
4340
|
+
}
|
|
4341
|
+
}
|
|
4342
|
+
#fail(error) {
|
|
4343
|
+
this.#options.log(`Update failed: ${error}`);
|
|
4344
|
+
this.#set({
|
|
4345
|
+
latest: this.#status.latest,
|
|
4346
|
+
state: "failed",
|
|
4347
|
+
error
|
|
4348
|
+
});
|
|
4349
|
+
}
|
|
4350
|
+
#set(status) {
|
|
4351
|
+
this.#status = status;
|
|
4352
|
+
this.#options.onChange(status);
|
|
4353
|
+
}
|
|
4354
|
+
};
|
|
4355
|
+
//#endregion
|
|
3517
4356
|
//#region src/daemon/server.ts
|
|
3518
4357
|
const DEFAULT_PORT = 4747;
|
|
3519
4358
|
/** Screenshots ride along as data URLs. */
|
|
@@ -3536,9 +4375,10 @@ async function startDaemon(options = {}) {
|
|
|
3536
4375
|
dataDir,
|
|
3537
4376
|
exec: options.exec
|
|
3538
4377
|
});
|
|
3539
|
-
const resolveProject = options.resolveProject ?? ((pageUrl) => resolver.resolve(pageUrl));
|
|
4378
|
+
const resolveProject = options.resolveProject ?? ((pageUrl, root) => resolver.resolve(pageUrl, root));
|
|
3540
4379
|
const sessions = /* @__PURE__ */ new Map();
|
|
3541
4380
|
const overlayPath = resolveOverlayPath();
|
|
4381
|
+
let updater;
|
|
3542
4382
|
const claudeCodeDir = join(dataDir, "claude-code");
|
|
3543
4383
|
const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
|
|
3544
4384
|
const createProvider = options.createProvider ?? ((root, id) => {
|
|
@@ -3583,6 +4423,7 @@ async function startDaemon(options = {}) {
|
|
|
3583
4423
|
root: key
|
|
3584
4424
|
},
|
|
3585
4425
|
version: VERSION,
|
|
4426
|
+
update: () => updater?.status() ?? { state: "idle" },
|
|
3586
4427
|
log: (message) => log(`[${basename(key)}] ${message}`)
|
|
3587
4428
|
});
|
|
3588
4429
|
log(`Serving ${key} with ${providers.default().label}`);
|
|
@@ -3590,6 +4431,7 @@ async function startDaemon(options = {}) {
|
|
|
3590
4431
|
root: key,
|
|
3591
4432
|
bridge,
|
|
3592
4433
|
providers,
|
|
4434
|
+
store,
|
|
3593
4435
|
clients: 0
|
|
3594
4436
|
};
|
|
3595
4437
|
})();
|
|
@@ -3692,7 +4534,8 @@ async function startDaemon(options = {}) {
|
|
|
3692
4534
|
const message = raw;
|
|
3693
4535
|
if (message.type === "hello") {
|
|
3694
4536
|
pageUrl = message.pageUrl ?? "";
|
|
3695
|
-
const
|
|
4537
|
+
const claimed = typeof message.root === "string" ? message.root : void 0;
|
|
4538
|
+
const root = await resolveProject(pageUrl, claimed).catch(() => void 0);
|
|
3696
4539
|
if (root) return attach(root, raw);
|
|
3697
4540
|
return client.send({
|
|
3698
4541
|
type: "project.unknown",
|
|
@@ -3701,6 +4544,11 @@ async function startDaemon(options = {}) {
|
|
|
3701
4544
|
emptyHint: noChoicesHint
|
|
3702
4545
|
});
|
|
3703
4546
|
}
|
|
4547
|
+
if (message.type === "update.start") {
|
|
4548
|
+
if (!updater) throw new Error("Tencil can't update itself yet");
|
|
4549
|
+
updater.update();
|
|
4550
|
+
return;
|
|
4551
|
+
}
|
|
3704
4552
|
if (message.type === "project.select" && message.root) {
|
|
3705
4553
|
await resolver.remember(pageUrl, message.root);
|
|
3706
4554
|
return attach(message.root, {
|
|
@@ -3755,6 +4603,25 @@ async function startDaemon(options = {}) {
|
|
|
3755
4603
|
for (const server of servers) server.close();
|
|
3756
4604
|
throw error;
|
|
3757
4605
|
}
|
|
4606
|
+
updater = new Updater({
|
|
4607
|
+
...options.updates,
|
|
4608
|
+
version: VERSION,
|
|
4609
|
+
dataDir,
|
|
4610
|
+
port: actualPort,
|
|
4611
|
+
node: process.execPath,
|
|
4612
|
+
cli: options.cli,
|
|
4613
|
+
flags: options.flags ?? [],
|
|
4614
|
+
running: async () => (await settled()).flatMap((s) => s.store.list()).filter((thread) => thread.status === "starting" || thread.status === "working").length,
|
|
4615
|
+
onChange: (update) => {
|
|
4616
|
+
const message = JSON.stringify({
|
|
4617
|
+
type: "update",
|
|
4618
|
+
update
|
|
4619
|
+
});
|
|
4620
|
+
for (const ws of wss.clients) if (ws.readyState === WebSocket$1.OPEN) ws.send(message);
|
|
4621
|
+
},
|
|
4622
|
+
log
|
|
4623
|
+
});
|
|
4624
|
+
updater.start();
|
|
3758
4625
|
const url = `http://${host === "127.0.0.1" || host === "0.0.0.0" ? "localhost" : host}:${actualPort}`;
|
|
3759
4626
|
log(`Tencil daemon listening on ${url}`);
|
|
3760
4627
|
for (const extra of addresses.slice(1)) log(`Also listening on http://${extra}:${actualPort}`);
|
|
@@ -3763,7 +4630,9 @@ async function startDaemon(options = {}) {
|
|
|
3763
4630
|
scriptUrl: `${url}/tencil.js`,
|
|
3764
4631
|
port: actualPort,
|
|
3765
4632
|
projects: () => statuses,
|
|
4633
|
+
checkForUpdates: () => updater?.check() ?? Promise.resolve(),
|
|
3766
4634
|
async close() {
|
|
4635
|
+
updater?.dispose();
|
|
3767
4636
|
for (const ws of wss.clients) ws.terminate();
|
|
3768
4637
|
for (const s of await settled()) {
|
|
3769
4638
|
await s.bridge.dispose();
|
|
@@ -3797,4 +4666,4 @@ function resolveOverlayPath() {
|
|
|
3797
4666
|
return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
|
|
3798
4667
|
}
|
|
3799
4668
|
//#endregion
|
|
3800
|
-
export {
|
|
4669
|
+
export { withoutNpmEnv as A, projectStorePath as C, createLocalPairingCode as D, DEFAULT_T3_URL as E, renderPrompt as F, stripContext as I, ProjectResolver as M, projectRoot as N, exchangePairingCredential as O, Bridge as P, defaultDataDir as S, CredentialStore as T, detectAgents as _, readPlan as a, savedProvider as b, runtimeDir as c, uninstallService as d, startInBackground as f, PROVIDERS as g, updateNotice as h, finishUpdate as i, loadAgentSdk as j, parsePairingInput as k, isServiceInstalled as l, isNewerThanThis as m, probeDaemon as n, enableAutostart as o, stopDaemon as p, startDaemon as r, ensureDaemon as s, DEFAULT_PORT as t, stopService as u, providerLabel as v, VERSION as w, FileThreadStore as x, saveProvider as y };
|