tencil 0.6.1 → 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.
@@ -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";
@@ -28,6 +28,39 @@ const Rect = z.object({
28
28
  width: z.number(),
29
29
  height: z.number()
30
30
  });
31
+ /** CSS pixels per side, in CSS order: top, right, bottom, left. */
32
+ const Sides = z.tuple([
33
+ z.number(),
34
+ z.number(),
35
+ z.number(),
36
+ z.number()
37
+ ]);
38
+ /** The element's computed box model. */
39
+ const BoxModel = z.object({
40
+ margin: Sides,
41
+ padding: Sides,
42
+ border: Sides,
43
+ /** Only on flex and grid containers with a gap. */
44
+ gap: z.object({
45
+ row: z.number(),
46
+ column: z.number()
47
+ }).optional()
48
+ });
49
+ /**
50
+ * Distances measured from the element to another one (Alt in the overlay):
51
+ * the space on each side of the element, up to the other element's nearest edge.
52
+ */
53
+ const Spacing = z.object({
54
+ /** Label of the other element (component · tag). */
55
+ to: z.string(),
56
+ selector: z.string().optional(),
57
+ /** The other element is the picked one's parent. */
58
+ parent: z.boolean().optional(),
59
+ top: z.number().optional(),
60
+ right: z.number().optional(),
61
+ bottom: z.number().optional(),
62
+ left: z.number().optional()
63
+ });
31
64
  /**
32
65
  * Everything the overlay knows about the picked element. Captured once when
33
66
  * the pin is placed and forwarded to the agent as context.
@@ -47,7 +80,9 @@ const ElementContext = z.object({
47
80
  dpr: z.number()
48
81
  }),
49
82
  /** Selected text inside the element at pin time, if any. */
50
- selection: z.string().optional()
83
+ selection: z.string().optional(),
84
+ box: BoxModel.optional(),
85
+ spacing: Spacing.optional()
51
86
  });
52
87
  /** Where a pin sits: the element plus the click offset inside it (0..1). */
53
88
  const Anchor = z.object({
@@ -81,6 +116,8 @@ const ClientMessage = z.discriminatedUnion("type", [
81
116
  type: z.literal("hello"),
82
117
  protocol: z.literal(1),
83
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(),
84
121
  build: BuildInfo.optional(),
85
122
  /** Tencil Cloud access token; the local daemon has no sign-in. */
86
123
  token: z.string().min(1).max(4096).optional()
@@ -152,12 +189,14 @@ const ClientMessage = z.discriminatedUnion("type", [
152
189
  z.object({
153
190
  type: z.literal("settings.update"),
154
191
  provider: z.string().min(1).optional(),
155
- batch: z.boolean().optional()
192
+ batch: z.boolean().optional(),
193
+ ruler: z.boolean().optional()
156
194
  }),
157
195
  z.object({
158
196
  type: z.literal("model.select"),
159
197
  model: z.string().min(1).nullable()
160
- })
198
+ }),
199
+ z.object({ type: z.literal("update.start") })
161
200
  ]);
162
201
  z.object({
163
202
  id: z.string(),
@@ -186,7 +225,9 @@ z.object({
186
225
  /** Model picked for the provider's new threads; unset means the provider's default. */
187
226
  model: z.string().optional(),
188
227
  /** New comments are queued and sent together. */
189
- batch: z.boolean()
228
+ batch: z.boolean(),
229
+ /** The toolbar offers the ruler: spacing while picking, distances with Alt. */
230
+ ruler: z.boolean()
190
231
  });
191
232
  //#endregion
192
233
  //#region ../protocol/src/thread.ts
@@ -388,8 +429,46 @@ function contextLines(pageUrl, context) {
388
429
  if (context.selection) lines.push(`- Selected text: "${page(truncate(oneLine(context.selection), 300))}"`);
389
430
  const { rect, viewport } = context;
390
431
  lines.push(`- Layout: ${Math.round(rect.width)}×${Math.round(rect.height)} at (${Math.round(rect.x)}, ${Math.round(rect.y)}) in a ${viewport.width}×${viewport.height} viewport @${viewport.dpr}x`);
432
+ const box = context.box && boxLine(context.box);
433
+ if (box) lines.push(`- Box: ${box}`);
434
+ if (context.spacing) lines.push(spacingLine(context.spacing));
391
435
  return lines;
392
436
  }
437
+ /** Computed spacing in CSS shorthand, px: `padding 12 16, margin 0 0 24, gap 8`. */
438
+ function boxLine(box) {
439
+ const parts = [];
440
+ for (const kind of [
441
+ "padding",
442
+ "margin",
443
+ "border"
444
+ ]) if (box[kind].some((value) => value !== 0)) parts.push(`${kind} ${shorthand(box[kind])}`);
445
+ if (box.gap) {
446
+ const { row, column } = box.gap;
447
+ parts.push(`gap ${row === column ? row : `${row} ${column}`}`);
448
+ }
449
+ return parts.length > 0 ? `${parts.join(", ")} (px)` : void 0;
450
+ }
451
+ function shorthand([top, right, bottom, left]) {
452
+ if (left !== right) return `${top} ${right} ${bottom} ${left}`;
453
+ if (top !== bottom) return `${top} ${right} ${bottom}`;
454
+ return top === right ? `${top}` : `${top} ${right}`;
455
+ }
456
+ const SIDE_WORDS = {
457
+ top: "above",
458
+ right: "right",
459
+ bottom: "below",
460
+ left: "left"
461
+ };
462
+ /** What the user measured with Alt: the space on each side of the element. */
463
+ function spacingLine(spacing) {
464
+ const sides = [
465
+ "top",
466
+ "right",
467
+ "bottom",
468
+ "left"
469
+ ].filter((side) => spacing[side] !== void 0).map((side) => `${spacing[side]}px ${SIDE_WORDS[side]}`);
470
+ return `- Measured spacing to ${`${spacing.parent ? "its parent " : ""}\`${page(truncate(spacing.to, 200))}\``}${spacing.selector ? ` (\`${page(truncate(spacing.selector, 500))}\`)` : ""}: ${sides.length > 0 ? sides.join(", ") : "none"}`;
471
+ }
393
472
  function stripContext(text) {
394
473
  const index = text.indexOf(CONTEXT_OPEN);
395
474
  return index === -1 ? text : text.slice(0, index).trimEnd();
@@ -486,7 +565,8 @@ var Bridge = class {
486
565
  provider: this.#provider().info(),
487
566
  settings: this.#settings(),
488
567
  threads: this.#options.store.list(),
489
- ...client.viewer && { viewer: client.viewer }
568
+ ...client.viewer && { viewer: client.viewer },
569
+ ...this.#options.update && { update: this.#options.update() }
490
570
  });
491
571
  return;
492
572
  case "thread.create":
@@ -527,6 +607,7 @@ var Bridge = class {
527
607
  const { providers } = this.#options;
528
608
  if (message.provider) await providers.setDefault(message.provider);
529
609
  if (message.batch !== void 0) await providers.setBatch(message.batch);
610
+ if (message.ruler !== void 0) await providers.setRuler(message.ruler);
530
611
  return;
531
612
  }
532
613
  case "provider.models": {
@@ -573,6 +654,7 @@ var Bridge = class {
573
654
  if (provider?.threadId) this.#release(provider.id, provider.threadId);
574
655
  return;
575
656
  }
657
+ case "update.start": throw new Error("Tencil can't update itself here");
576
658
  }
577
659
  } catch (error) {
578
660
  const threadId = "threadId" in message ? message.threadId : void 0;
@@ -893,7 +975,8 @@ var Bridge = class {
893
975
  provider: providers.defaultId,
894
976
  providers: providers.choices,
895
977
  ...model ? { model } : {},
896
- batch: providers.batch
978
+ batch: providers.batch,
979
+ ruler: providers.ruler
897
980
  };
898
981
  }
899
982
  #require(threadId) {
@@ -995,6 +1078,8 @@ var ProjectProviders = class ProjectProviders {
995
1078
  #models = {};
996
1079
  /** On unless the project turns it off. */
997
1080
  #batch = true;
1081
+ /** On unless the project turns it off. */
1082
+ #ruler = true;
998
1083
  constructor(options) {
999
1084
  this.#options = options;
1000
1085
  this.choices = options.choices;
@@ -1025,6 +1110,7 @@ var ProjectProviders = class ProjectProviders {
1025
1110
  this.#chosen = saved.provider;
1026
1111
  this.#models = saved.models ?? {};
1027
1112
  this.#batch = saved.batch ?? true;
1113
+ this.#ruler = saved.ruler ?? true;
1028
1114
  }
1029
1115
  }
1030
1116
  get defaultId() {
@@ -1078,7 +1164,16 @@ var ProjectProviders = class ProjectProviders {
1078
1164
  await this.#save();
1079
1165
  for (const listener of this.#settingsListeners) listener();
1080
1166
  }
1081
- /** Fires when a picked model or batching changes. */
1167
+ get ruler() {
1168
+ return this.#ruler;
1169
+ }
1170
+ async setRuler(on) {
1171
+ if (on === this.#ruler) return;
1172
+ this.#ruler = on;
1173
+ await this.#save();
1174
+ for (const listener of this.#settingsListeners) listener();
1175
+ }
1176
+ /** Fires when a picked model, batching or the ruler changes. */
1082
1177
  onSettingsChange(listener) {
1083
1178
  this.#settingsListeners.add(listener);
1084
1179
  return () => this.#settingsListeners.delete(listener);
@@ -1095,7 +1190,8 @@ var ProjectProviders = class ProjectProviders {
1095
1190
  await this.#options.settings?.save({
1096
1191
  provider: this.#chosen,
1097
1192
  models: this.#models,
1098
- batch: this.#batch
1193
+ batch: this.#batch,
1194
+ ruler: this.#ruler
1099
1195
  });
1100
1196
  }
1101
1197
  };
@@ -1124,7 +1220,8 @@ const defaultExec = async (command, args) => (await run$1(command, args, {
1124
1220
  /**
1125
1221
  * Works out which project folder a page belongs to:
1126
1222
  * 1. what the user picked for this address before,
1127
- * 2. the dev server's working directory, found from the port it listens on.
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.
1128
1225
  * Returns undefined when neither works; the overlay then asks.
1129
1226
  */
1130
1227
  var ProjectResolver = class {
@@ -1136,11 +1233,12 @@ var ProjectResolver = class {
1136
1233
  this.#exec = options.exec ?? defaultExec;
1137
1234
  this.#platform = options.platform ?? process.platform;
1138
1235
  }
1139
- async resolve(pageUrl) {
1236
+ async resolve(pageUrl, claimedRoot) {
1140
1237
  const origin = safeOrigin(pageUrl);
1141
1238
  if (!origin) return void 0;
1142
1239
  const remembered = await this.#memory.get(origin);
1143
1240
  if (remembered && existsSync(remembered)) return remembered;
1241
+ if (claimedRoot && isGitRoot(claimedRoot)) return resolve(claimedRoot);
1144
1242
  const port = portOf(origin);
1145
1243
  if (!port) return void 0;
1146
1244
  const folder = await this.folderForPort(port).catch(() => void 0);
@@ -1151,15 +1249,32 @@ var ProjectResolver = class {
1151
1249
  const origin = safeOrigin(pageUrl);
1152
1250
  return origin ? this.#memory.set(origin, resolve(root)) : Promise.resolve();
1153
1251
  }
1154
- /** Folder of the process listening on `port`: its working directory, or its script's package. */
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
+ */
1155
1256
  async folderForPort(port) {
1156
- for (const pid of await this.#listeners(port)) {
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) {
1157
1260
  const cwd = await this.#cwd(pid).catch(() => void 0);
1158
1261
  if (cwd && cwd !== sep && existsSync(join(cwd, "package.json"))) return cwd;
1159
- const fromCommand = projectFromCommandLine(await this.#commandLine(pid).catch(() => ""));
1262
+ const commandLine = await this.#commandLine(pid).catch(() => "");
1263
+ if (isDockerForwarder(commandLine)) return this.#composeFolder(port);
1264
+ const fromCommand = projectFromCommandLine(commandLine);
1160
1265
  if (fromCommand) return fromCommand;
1161
1266
  }
1162
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
+ }
1163
1278
  async #listeners(port) {
1164
1279
  if (this.#platform === "win32") return parseNetstat(await this.#exec("netstat", [
1165
1280
  "-ano",
@@ -1204,6 +1319,14 @@ var ProjectResolver = class {
1204
1319
  ]);
1205
1320
  }
1206
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
+ }
1207
1330
  /** Closest folder with a package.json at or above `folder`, or `folder` itself. */
1208
1331
  function projectRoot(folder) {
1209
1332
  let dir = resolve(folder);
@@ -1231,6 +1354,15 @@ function parseNetstat(output, port) {
1231
1354
  return [...new Set(pids.filter(Number.isInteger))];
1232
1355
  }
1233
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
+ /**
1234
1366
  * Dev servers are started from a project's node_modules
1235
1367
  * (`…/eyes/apps/frontend/node_modules/next/dist/bin/next dev`): the part
1236
1368
  * before `node_modules` is the project.
@@ -1238,6 +1370,9 @@ function parseNetstat(output, port) {
1238
1370
  function projectFromCommandLine(commandLine) {
1239
1371
  return commandLine.match(/(?:^|[\s"'])((?:[A-Za-z]:)?[\\/][^\s"']*?)[\\/]node_modules[\\/]/)?.[1];
1240
1372
  }
1373
+ function firstLine(output) {
1374
+ return output.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
1375
+ }
1241
1376
  function safeOrigin(pageUrl) {
1242
1377
  try {
1243
1378
  return new URL(pageUrl).origin;
@@ -3166,7 +3301,7 @@ function errorMessage(error) {
3166
3301
  }
3167
3302
  //#endregion
3168
3303
  //#region src/version.ts
3169
- const VERSION = "0.6.1";
3304
+ const VERSION = "0.8.0";
3170
3305
  //#endregion
3171
3306
  //#region src/daemon/thread-store.ts
3172
3307
  const StoreFile = z.object({
@@ -3338,13 +3473,15 @@ const SettingsFile = z.object({
3338
3473
  /** Model picked per provider for new threads; unset means the provider's default. */
3339
3474
  models: z.record(z.string(), z.string()).optional(),
3340
3475
  /** Queue new comments and send them together. */
3341
- batch: z.boolean().optional()
3476
+ batch: z.boolean().optional(),
3477
+ /** Offer the ruler in the overlay's toolbar. */
3478
+ ruler: z.boolean().optional()
3342
3479
  });
3343
3480
  /** A project's settings live next to its pins: `<slug>-<hash>.settings.json`. */
3344
3481
  function projectSettingsPath(projectRoot, dataDir = defaultDataDir()) {
3345
3482
  return projectStorePath(projectRoot, dataDir).replace(/\.json$/, ".settings.json");
3346
3483
  }
3347
- /** A project's overlay settings (provider, models, batching) in a JSON file. */
3484
+ /** A project's overlay settings (provider, models, batching, ruler) in a JSON file. */
3348
3485
  var FileProjectSettings = class {
3349
3486
  path;
3350
3487
  constructor(path) {
@@ -3362,7 +3499,8 @@ var FileProjectSettings = class {
3362
3499
  version: 1,
3363
3500
  provider: settings.provider,
3364
3501
  models: settings.models,
3365
- batch: settings.batch
3502
+ batch: settings.batch,
3503
+ ruler: settings.ruler
3366
3504
  }, null, 2)}\n`);
3367
3505
  await rename(temp, this.path);
3368
3506
  }
@@ -3420,6 +3558,801 @@ function isLoopbackAddress(address) {
3420
3558
  return ip === "::1" || /^127(?:\.\d{1,3}){3}$/.test(ip);
3421
3559
  }
3422
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+"?|&quot;\s*&quot;)(\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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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
3423
4356
  //#region src/daemon/server.ts
3424
4357
  const DEFAULT_PORT = 4747;
3425
4358
  /** Screenshots ride along as data URLs. */
@@ -3442,9 +4375,10 @@ async function startDaemon(options = {}) {
3442
4375
  dataDir,
3443
4376
  exec: options.exec
3444
4377
  });
3445
- const resolveProject = options.resolveProject ?? ((pageUrl) => resolver.resolve(pageUrl));
4378
+ const resolveProject = options.resolveProject ?? ((pageUrl, root) => resolver.resolve(pageUrl, root));
3446
4379
  const sessions = /* @__PURE__ */ new Map();
3447
4380
  const overlayPath = resolveOverlayPath();
4381
+ let updater;
3448
4382
  const claudeCodeDir = join(dataDir, "claude-code");
3449
4383
  const t3Url = options.t3?.url ?? process.env.TENCIL_T3_URL;
3450
4384
  const createProvider = options.createProvider ?? ((root, id) => {
@@ -3489,6 +4423,7 @@ async function startDaemon(options = {}) {
3489
4423
  root: key
3490
4424
  },
3491
4425
  version: VERSION,
4426
+ update: () => updater?.status() ?? { state: "idle" },
3492
4427
  log: (message) => log(`[${basename(key)}] ${message}`)
3493
4428
  });
3494
4429
  log(`Serving ${key} with ${providers.default().label}`);
@@ -3496,6 +4431,7 @@ async function startDaemon(options = {}) {
3496
4431
  root: key,
3497
4432
  bridge,
3498
4433
  providers,
4434
+ store,
3499
4435
  clients: 0
3500
4436
  };
3501
4437
  })();
@@ -3598,7 +4534,8 @@ async function startDaemon(options = {}) {
3598
4534
  const message = raw;
3599
4535
  if (message.type === "hello") {
3600
4536
  pageUrl = message.pageUrl ?? "";
3601
- const root = await resolveProject(pageUrl).catch(() => void 0);
4537
+ const claimed = typeof message.root === "string" ? message.root : void 0;
4538
+ const root = await resolveProject(pageUrl, claimed).catch(() => void 0);
3602
4539
  if (root) return attach(root, raw);
3603
4540
  return client.send({
3604
4541
  type: "project.unknown",
@@ -3607,6 +4544,11 @@ async function startDaemon(options = {}) {
3607
4544
  emptyHint: noChoicesHint
3608
4545
  });
3609
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
+ }
3610
4552
  if (message.type === "project.select" && message.root) {
3611
4553
  await resolver.remember(pageUrl, message.root);
3612
4554
  return attach(message.root, {
@@ -3661,6 +4603,25 @@ async function startDaemon(options = {}) {
3661
4603
  for (const server of servers) server.close();
3662
4604
  throw error;
3663
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();
3664
4625
  const url = `http://${host === "127.0.0.1" || host === "0.0.0.0" ? "localhost" : host}:${actualPort}`;
3665
4626
  log(`Tencil daemon listening on ${url}`);
3666
4627
  for (const extra of addresses.slice(1)) log(`Also listening on http://${extra}:${actualPort}`);
@@ -3669,7 +4630,9 @@ async function startDaemon(options = {}) {
3669
4630
  scriptUrl: `${url}/tencil.js`,
3670
4631
  port: actualPort,
3671
4632
  projects: () => statuses,
4633
+ checkForUpdates: () => updater?.check() ?? Promise.resolve(),
3672
4634
  async close() {
4635
+ updater?.dispose();
3673
4636
  for (const ws of wss.clients) ws.terminate();
3674
4637
  for (const s of await settled()) {
3675
4638
  await s.bridge.dispose();
@@ -3703,4 +4666,4 @@ function resolveOverlayPath() {
3703
4666
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
3704
4667
  }
3705
4668
  //#endregion
3706
- export { renderPrompt as C, Bridge as S, parsePairingInput as _, detectAgents as a, ProjectResolver as b, savedProvider as c, projectStorePath as d, VERSION as f, exchangePairingCredential as g, createLocalPairingCode as h, PROVIDERS as i, FileThreadStore as l, DEFAULT_T3_URL as m, probeDaemon as n, providerLabel as o, CredentialStore as p, startDaemon as r, saveProvider as s, DEFAULT_PORT as t, defaultDataDir as u, withoutNpmEnv as v, stripContext as w, projectRoot as x, loadAgentSdk as y };
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 };