tencil 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,1368 @@
1
+ #!/usr/bin/env node
2
+ import { _ as parsePairingInput, a as detectAgents, c as savedProvider, f as VERSION, g as exchangePairingCredential, h as createLocalPairingCode, i as PROVIDERS, m as DEFAULT_T3_URL, n as probeDaemon, o as providerLabel, p as CredentialStore, r as startDaemon, s as saveProvider, t as DEFAULT_PORT, u as defaultDataDir, v as withoutNpmEnv, y as loadAgentSdk } from "./server-PYBcw-eR.mjs";
3
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
4
+ import { cpSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { readFile, readdir, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, join, relative, resolve } from "node:path";
7
+ import { parseArgs } from "node:util";
8
+ import { fileURLToPath } from "node:url";
9
+ import { homedir } from "node:os";
10
+ import pc from "picocolors";
11
+ import { createInterface } from "node:readline/promises";
12
+ //#region src/service/daemon-command.ts
13
+ function daemonArgs(command) {
14
+ return [
15
+ command.cli,
16
+ "daemon",
17
+ "--port",
18
+ String(command.port),
19
+ ...command.args ?? []
20
+ ];
21
+ }
22
+ //#endregion
23
+ //#region src/service/background.ts
24
+ /**
25
+ * Start the daemon in the background unless it already runs. A daemon from an
26
+ * older Tencil version is replaced so pages always get the current overlay;
27
+ * so is one running with other flags than the ones given. Without flags of
28
+ * its own, a replacement keeps the running daemon's (`--listen`, `--t3-url`, …).
29
+ */
30
+ async function startInBackground(command, dataDir) {
31
+ const running = await probeDaemon(command.port);
32
+ const flags = command.args?.length ? command.args : running?.flags ?? [];
33
+ if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
34
+ status: "running",
35
+ pid: running.pid
36
+ };
37
+ if (running) await stopDaemon(command.port);
38
+ mkdirSync(dataDir, { recursive: true });
39
+ const logFile = openSync(join(dataDir, "daemon.log"), "a");
40
+ spawn(command.node, daemonArgs({
41
+ ...command,
42
+ args: flags
43
+ }), {
44
+ detached: true,
45
+ stdio: [
46
+ "ignore",
47
+ logFile,
48
+ logFile
49
+ ],
50
+ windowsHide: true
51
+ }).unref();
52
+ const health = await waitForDaemon(command.port, dataDir);
53
+ return {
54
+ status: running ? "restarted" : "started",
55
+ pid: health.pid
56
+ };
57
+ }
58
+ /** Wait for a daemon on `port` (optionally one of `version`) to answer. */
59
+ async function waitForDaemon(port, dataDir, version) {
60
+ for (let attempt = 0; attempt < 100; attempt++) {
61
+ await new Promise((resolve) => setTimeout(resolve, 100));
62
+ const health = await probeDaemon(port);
63
+ if (health && (!version || health.version === version)) return health;
64
+ }
65
+ throw new Error(`The daemon didn't start. See ${join(dataDir, "daemon.log")}.`);
66
+ }
67
+ function sameFlags(a, b) {
68
+ return a.length === b.length && a.every((flag, i) => flag === b[i]);
69
+ }
70
+ /** Stop the daemon answering on `port`. Returns false when none was running. */
71
+ async function stopDaemon(port = DEFAULT_PORT) {
72
+ const running = await probeDaemon(port);
73
+ if (!running) return false;
74
+ try {
75
+ process.kill(running.pid, "SIGTERM");
76
+ } catch {
77
+ return false;
78
+ }
79
+ for (let attempt = 0; attempt < 50; attempt++) {
80
+ await new Promise((resolve) => setTimeout(resolve, 100));
81
+ if (!await probeDaemon(port)) return true;
82
+ }
83
+ return true;
84
+ }
85
+ //#endregion
86
+ //#region src/service/login-service.ts
87
+ function serviceNames(port = DEFAULT_PORT) {
88
+ const own = port !== DEFAULT_PORT;
89
+ return {
90
+ label: own ? `dev.tencil.daemon.${port}` : "dev.tencil.daemon",
91
+ unit: own ? `tencil-${port}.service` : "tencil.service",
92
+ task: own ? `Tencil ${port}` : "Tencil"
93
+ };
94
+ }
95
+ /**
96
+ * What the daemon needs from the shell that installed it. launchd and systemd
97
+ * start it with a bare PATH (`/usr/bin:/bin`), where nvm's npm and npx, which
98
+ * it runs to pair and to install the Claude Agent SDK, can't be found; and a
99
+ * custom XDG_CONFIG_HOME must reach it, or it reads another data folder than
100
+ * the CLI. npx's and npm's own folders (anything in node_modules) are left out of PATH.
101
+ */
102
+ function serviceEnvironment(command, env = process.env) {
103
+ const separator = process.platform === "win32" ? ";" : ":";
104
+ const entries = [dirname(command.node), ...(env.PATH ?? "").split(separator)].filter((entry) => entry && !/[\\/](?:_npx|node_modules)[\\/]/.test(entry));
105
+ const environment = { PATH: [...new Set(entries)].join(separator) };
106
+ if (env.XDG_CONFIG_HOME) environment.XDG_CONFIG_HOME = env.XDG_CONFIG_HOME;
107
+ return environment;
108
+ }
109
+ function launchdPlist(command, logPath, environment = {}) {
110
+ const args = [command.node, ...daemonArgs(command)].map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n");
111
+ const variables = Object.entries(environment).map(([key, value]) => ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`).join("\n");
112
+ return `<?xml version="1.0" encoding="UTF-8"?>
113
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
114
+ <plist version="1.0">
115
+ <dict>
116
+ <key>Label</key>
117
+ <string>${serviceNames(command.port).label}</string>
118
+ <key>ProgramArguments</key>
119
+ <array>
120
+ ${args}
121
+ </array>
122
+ <key>EnvironmentVariables</key>
123
+ <dict>
124
+ ${variables}
125
+ </dict>
126
+ <key>RunAtLoad</key>
127
+ <true/>
128
+ <key>KeepAlive</key>
129
+ <true/>
130
+ <key>StandardOutPath</key>
131
+ <string>${escapeXml(logPath)}</string>
132
+ <key>StandardErrorPath</key>
133
+ <string>${escapeXml(logPath)}</string>
134
+ </dict>
135
+ </plist>
136
+ `;
137
+ }
138
+ function systemdUnit(command, environment = {}) {
139
+ return `[Unit]
140
+ Description=Tencil daemon
141
+
142
+ [Service]
143
+ ${Object.entries(environment).map(([key, value]) => `Environment="${key}=${value}"\n`).join("")}ExecStart=${[command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ")}
144
+ Restart=on-failure
145
+
146
+ [Install]
147
+ WantedBy=default.target
148
+ `;
149
+ }
150
+ function windowsTaskCommand(command) {
151
+ return [command.node, ...daemonArgs(command)].map((arg) => `"${arg}"`).join(" ");
152
+ }
153
+ const launchAgent = (names) => join(homedir(), "Library", "LaunchAgents", `${names.label}.plist`);
154
+ const systemdUnitPath = (names) => join(homedir(), ".config", "systemd", "user", names.unit);
155
+ const launchdDomain = () => `gui/${process.getuid?.() ?? 501}`;
156
+ /** Whether Tencil is set up to start at login, serving `port`. */
157
+ function isServiceInstalled(port = DEFAULT_PORT) {
158
+ return servicePort(readServiceDefinition(serviceNames(port))) === port;
159
+ }
160
+ /** The daemon port in a launchd plist, systemd unit or scheduled task definition. */
161
+ function servicePort(definition) {
162
+ const match = definition?.match(/--port(?:<\/string>\s*<string>|"?\s+"?|&quot;\s*&quot;)(\d+)/);
163
+ return match?.[1] ? Number(match[1]) : void 0;
164
+ }
165
+ /** The launchd plist, systemd unit or scheduled task behind `names`, if installed. */
166
+ function readServiceDefinition(names) {
167
+ try {
168
+ switch (process.platform) {
169
+ case "darwin": return readFileSync(launchAgent(names), "utf8");
170
+ case "linux": return readFileSync(systemdUnitPath(names), "utf8");
171
+ case "win32": return execFileSync("schtasks", [
172
+ "/Query",
173
+ "/TN",
174
+ names.task,
175
+ "/XML"
176
+ ], {
177
+ encoding: "utf8",
178
+ stdio: [
179
+ "ignore",
180
+ "pipe",
181
+ "ignore"
182
+ ]
183
+ });
184
+ default: return;
185
+ }
186
+ } catch {
187
+ return;
188
+ }
189
+ }
190
+ /** Install (or replace) the login service and start the daemon through it. */
191
+ async function installService(command, dataDir) {
192
+ const logPath = join(dataDir, "daemon.log");
193
+ const names = serviceNames(command.port);
194
+ const { unit: unitName, task } = names;
195
+ mkdirSync(dataDir, { recursive: true });
196
+ switch (process.platform) {
197
+ case "darwin": {
198
+ const plist = launchAgent(names);
199
+ quietly("launchctl", [
200
+ "bootout",
201
+ launchdDomain(),
202
+ plist
203
+ ]);
204
+ await stopDaemon(command.port);
205
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
206
+ writeFileSync(plist, launchdPlist(command, logPath, serviceEnvironment(command)));
207
+ execFileSync("launchctl", [
208
+ "bootstrap",
209
+ launchdDomain(),
210
+ plist
211
+ ]);
212
+ return plist;
213
+ }
214
+ case "linux": {
215
+ const unit = systemdUnitPath(names);
216
+ quietly("systemctl", [
217
+ "--user",
218
+ "stop",
219
+ unitName
220
+ ]);
221
+ await stopDaemon(command.port);
222
+ mkdirSync(join(homedir(), ".config", "systemd", "user"), { recursive: true });
223
+ writeFileSync(unit, systemdUnit(command, serviceEnvironment(command)));
224
+ execFileSync("systemctl", ["--user", "daemon-reload"]);
225
+ execFileSync("systemctl", [
226
+ "--user",
227
+ "enable",
228
+ "--now",
229
+ unitName
230
+ ], { stdio: [
231
+ "ignore",
232
+ "ignore",
233
+ "pipe"
234
+ ] });
235
+ return unit;
236
+ }
237
+ case "win32":
238
+ quietly("schtasks", [
239
+ "/End",
240
+ "/TN",
241
+ task
242
+ ]);
243
+ await stopDaemon(command.port);
244
+ execFileSync("schtasks", [
245
+ "/Create",
246
+ "/F",
247
+ "/SC",
248
+ "ONLOGON",
249
+ "/TN",
250
+ task,
251
+ "/TR",
252
+ windowsTaskCommand(command)
253
+ ]);
254
+ execFileSync("schtasks", [
255
+ "/Run",
256
+ "/TN",
257
+ task
258
+ ]);
259
+ return `Task Scheduler: ${task}`;
260
+ default: throw new Error(`Login service isn't supported on ${process.platform}; use \`tencil start\`.`);
261
+ }
262
+ }
263
+ /** Stop the service's daemon until the next login, without uninstalling it. */
264
+ async function stopService(port = DEFAULT_PORT) {
265
+ const names = serviceNames(port);
266
+ const { unit, task } = names;
267
+ switch (process.platform) {
268
+ case "darwin":
269
+ quietly("launchctl", [
270
+ "bootout",
271
+ launchdDomain(),
272
+ launchAgent(names)
273
+ ]);
274
+ break;
275
+ case "linux":
276
+ quietly("systemctl", [
277
+ "--user",
278
+ "stop",
279
+ unit
280
+ ]);
281
+ break;
282
+ case "win32": quietly("schtasks", [
283
+ "/End",
284
+ "/TN",
285
+ task
286
+ ]);
287
+ }
288
+ await stopDaemon(port);
289
+ }
290
+ async function uninstallService(port = DEFAULT_PORT) {
291
+ removeService(serviceNames(port));
292
+ await stopDaemon(port);
293
+ }
294
+ /** Unload and delete the service behind `names`, wherever it is in its life. */
295
+ function removeService(names) {
296
+ switch (process.platform) {
297
+ case "darwin":
298
+ quietly("launchctl", [
299
+ "bootout",
300
+ launchdDomain(),
301
+ launchAgent(names)
302
+ ]);
303
+ rmSync(launchAgent(names), { force: true });
304
+ break;
305
+ case "linux":
306
+ quietly("systemctl", [
307
+ "--user",
308
+ "disable",
309
+ "--now",
310
+ names.unit
311
+ ]);
312
+ rmSync(systemdUnitPath(names), { force: true });
313
+ quietly("systemctl", ["--user", "daemon-reload"]);
314
+ break;
315
+ case "win32":
316
+ quietly("schtasks", [
317
+ "/End",
318
+ "/TN",
319
+ names.task
320
+ ]);
321
+ quietly("schtasks", [
322
+ "/Delete",
323
+ "/F",
324
+ "/TN",
325
+ names.task
326
+ ]);
327
+ }
328
+ }
329
+ /** Run a command whose failure only means "nothing to do" (not loaded, already gone). */
330
+ function quietly(command, args) {
331
+ try {
332
+ execFileSync(command, args, { stdio: "ignore" });
333
+ } catch {}
334
+ }
335
+ function escapeXml(value) {
336
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
337
+ }
338
+ //#endregion
339
+ //#region src/service/autostart.ts
340
+ /**
341
+ * Running from a package manager's install (npx's cache, a project, a global
342
+ * prefix) rather than a source checkout. Those can be cleaned up or upgraded
343
+ * under a login service, so it gets its own copy.
344
+ */
345
+ function isPackageInstall(cliPath) {
346
+ return /[\\/]node_modules[\\/]/.test(cliPath);
347
+ }
348
+ /** The login service's own copy of Tencil; one per port, like the service. */
349
+ function runtimeDir(dataDir, port = DEFAULT_PORT) {
350
+ return join(dataDir, port === 4747 ? "runtime" : `runtime-${port}`);
351
+ }
352
+ function runtimeCli(dataDir, port = DEFAULT_PORT) {
353
+ return join(runtimeDir(dataDir, port), "node_modules", "tencil", "dist", "cli.mjs");
354
+ }
355
+ function runtimeInstallArgs(dataDir, spec, port = DEFAULT_PORT) {
356
+ return [
357
+ "install",
358
+ "--prefix",
359
+ runtimeDir(dataDir, port),
360
+ spec,
361
+ "--no-audit",
362
+ "--no-fund",
363
+ "--loglevel=error"
364
+ ];
365
+ }
366
+ /**
367
+ * Start Tencil at login and now. Keeps the running daemon's flags unless new
368
+ * ones are given. `from` installs another package spec (a local tarball) as
369
+ * the service's copy instead of this version from npm.
370
+ */
371
+ async function enableAutostart(command, dataDir, from) {
372
+ const running = await probeDaemon(command.port);
373
+ const args = command.args?.length ? command.args : running?.flags ?? [];
374
+ let cli = command.cli;
375
+ if (isPackageInstall(cli)) {
376
+ const spec = from && existsSync(from) ? resolve(from) : from ?? `tencil@${VERSION}`;
377
+ const result = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", runtimeInstallArgs(dataDir, spec, command.port), {
378
+ encoding: "utf8",
379
+ stdio: [
380
+ "ignore",
381
+ "ignore",
382
+ "pipe"
383
+ ],
384
+ shell: process.platform === "win32",
385
+ env: withoutNpmEnv()
386
+ });
387
+ if (result.status !== 0) throw new Error(`Couldn't install Tencil for the login service (npm ${result.status ?? "failed"}): ${result.stderr?.trim() ?? ""}`);
388
+ cli = runtimeCli(dataDir, command.port);
389
+ }
390
+ const where = await installService({
391
+ ...command,
392
+ cli,
393
+ args
394
+ }, dataDir);
395
+ await waitForDaemon(command.port, dataDir);
396
+ return where;
397
+ }
398
+ /**
399
+ * Make sure this version of the daemon runs. With a login service it is
400
+ * updated in place, since stopping its daemon would only make it restart.
401
+ */
402
+ async function ensureDaemon(command, dataDir) {
403
+ if (!isServiceInstalled(command.port)) {
404
+ const { status } = await startInBackground(command, dataDir);
405
+ return {
406
+ status,
407
+ autostart: false
408
+ };
409
+ }
410
+ const running = await probeDaemon(command.port);
411
+ const flags = command.args?.length ? command.args : running?.flags ?? [];
412
+ if (running && running.version === VERSION && sameFlags(running.flags, flags)) return {
413
+ status: "running",
414
+ autostart: true
415
+ };
416
+ await enableAutostart(command, dataDir);
417
+ return {
418
+ status: running ? "restarted" : "started",
419
+ autostart: true
420
+ };
421
+ }
422
+ //#endregion
423
+ //#region src/service/choose-provider.ts
424
+ /**
425
+ * The agent pins go to on this machine. Asked once: kept from an earlier run
426
+ * or `--provider`, taken without asking when only one agent is installed, and
427
+ * otherwise picked by the user. With nobody to ask it's T3 Code for now, not
428
+ * saved, so the daemon keeps looking for what gets installed later.
429
+ */
430
+ async function chooseProvider(options) {
431
+ const saved = await savedProvider();
432
+ if (saved) return saved;
433
+ const found = await detectAgents({ t3Url: options.t3Url });
434
+ const installed = PROVIDERS.filter((id) => found[id]);
435
+ const hint = () => options.log(pc.dim(" Each project can switch agents in the overlay's settings (the gear)."));
436
+ if (installed.length === 1) {
437
+ const provider = installed[0];
438
+ await saveProvider(provider);
439
+ options.log(` ${pc.green("✓")} Pins go to ${providerLabel(provider)}, found on this machine.`);
440
+ hint();
441
+ return provider;
442
+ }
443
+ if (options.yes || !process.stdin.isTTY) return "t3code";
444
+ const provider = await ask(installed.length === 0, options.log);
445
+ await saveProvider(provider);
446
+ options.log(` ${pc.green("✓")} Pins go to ${providerLabel(provider)}.`);
447
+ hint();
448
+ return provider;
449
+ }
450
+ async function ask(noneFound, log) {
451
+ log(noneFound ? " Neither T3 Code nor Claude Code was found. Which one will you use?" : " T3 Code and Claude Code are both here. Which agent should pins go to?");
452
+ PROVIDERS.forEach((id, index) => {
453
+ log(` ${pc.cyan(String(index + 1))} ${providerLabel(id)}`);
454
+ });
455
+ const rl = createInterface({
456
+ input: process.stdin,
457
+ output: process.stdout
458
+ });
459
+ const answer = await rl.question(` Choose ${pc.dim("(1)")} `);
460
+ rl.close();
461
+ const index = Number.parseInt(answer.trim(), 10) - 1;
462
+ return PROVIDERS[index] ?? PROVIDERS[0];
463
+ }
464
+ //#endregion
465
+ //#region src/service/pairing.ts
466
+ /** Get the agent ready now, so the first page load is ready to go. */
467
+ async function prepareProvider(provider, t3Url, log) {
468
+ if (provider === "claude-code") return prepareClaudeCode(log);
469
+ return pairWithLocalT3(t3Url, log);
470
+ }
471
+ /** Pair with the local T3 Code. */
472
+ async function pairWithLocalT3(t3Url, log) {
473
+ const store = new CredentialStore();
474
+ const baseUrl = t3Url ?? await store.lastBaseUrl() ?? "http://127.0.0.1:3773";
475
+ if (await store.get(baseUrl)) return log(` ${pc.green("✓")} Paired with T3 Code.`);
476
+ const code = await createLocalPairingCode(baseUrl).catch(() => void 0);
477
+ if (!code) {
478
+ log(await fetch(new URL("/.well-known/t3/environment", baseUrl), { signal: AbortSignal.timeout(3e3) }).then((response) => response.ok, () => false) ? ` ${pc.yellow("!")} Couldn't pair with T3 Code automatically. Press Pair in the overlay, or run ${pc.cyan("npx tencil connect")} with a pairing link from T3 Code.` : ` ${pc.yellow("!")} T3 Code isn't running, so pairing is skipped. Tencil pairs on its own once it is.`);
479
+ return;
480
+ }
481
+ try {
482
+ await store.set(baseUrl, await exchangePairingCredential({
483
+ baseUrl,
484
+ credential: code
485
+ }));
486
+ log(` ${pc.green("✓")} Paired with T3 Code at ${baseUrl}`);
487
+ } catch (error) {
488
+ log(` ${pc.yellow("!")} ${error instanceof Error ? error.message : String(error)}`);
489
+ }
490
+ }
491
+ /** Install the Claude Agent SDK the daemon runs Claude Code with, if Tencil has none yet. */
492
+ async function prepareClaudeCode(log) {
493
+ try {
494
+ await loadAgentSdk({
495
+ installDir: join(defaultDataDir(), "claude-code"),
496
+ onInstall: () => log(pc.dim(" Installing Claude Code support (one time)…"))
497
+ });
498
+ log(` ${pc.green("✓")} Claude Code is ready. Pins run in your Claude Code login.`);
499
+ } catch (error) {
500
+ log(` ${pc.yellow("!")} ${error instanceof Error ? error.message : String(error)}`);
501
+ }
502
+ }
503
+ //#endregion
504
+ //#region src/init/codemods.ts
505
+ function detectStyle(source) {
506
+ const singles = (source.match(/^import .*'[^']+';?$/gm) ?? []).length;
507
+ const doubles = (source.match(/^import .*"[^"]+";?$/gm) ?? []).length;
508
+ const usesSemicolons = /;[ \t]*$/m.test(source);
509
+ const indent = source.match(/^( +|\t)\S/m)?.[1] ?? " ";
510
+ return {
511
+ quote: singles > doubles ? "'" : "\"",
512
+ semi: usesSemicolons || source.trim() === "" ? ";" : "",
513
+ indent: indent === " " ? " " : indent.length >= 4 ? " " : " "
514
+ };
515
+ }
516
+ /** Insert an import after the last top-level import (or after directives). */
517
+ function addImport(source, statement) {
518
+ const imports = [...source.matchAll(/^import\s[\s\S]*?\sfrom\s+['"][^'"]+['"];?[ \t]*$/gm), ...source.matchAll(/^import\s+['"][^'"]+['"];?[ \t]*$/gm)];
519
+ const end = Math.max(-1, ...imports.map((m) => (m.index ?? 0) + m[0].length));
520
+ if (end >= 0) return `${source.slice(0, end)}\n${statement}${source.slice(end)}`;
521
+ const directive = source.match(/^(?:\s*(['"])use [a-z]+\1;?\s*\n)+/);
522
+ const at = directive ? directive[0].length : 0;
523
+ return `${source.slice(0, at)}${statement}\n${at === 0 ? "\n" : ""}${source.slice(at)}`;
524
+ }
525
+ /** `plugins: [react()]` → `plugins: [react(), tencil()]`, plus the import. */
526
+ function addVitePlugin(source) {
527
+ if (/["']tencil\/vite["']/.test(source)) return source;
528
+ const style = detectStyle(source);
529
+ let edited = null;
530
+ const plugins = /plugins\s*:\s*\[/.exec(source);
531
+ if (plugins) {
532
+ const open = plugins.index + plugins[0].length - 1;
533
+ const close = matchBracket(source, open);
534
+ if (close === -1) return null;
535
+ const inner = source.slice(open + 1, close);
536
+ if (inner.includes("\n")) {
537
+ const lastContent = inner.trimEnd();
538
+ const indent = inner.match(/\n([ \t]*)\S/)?.[1] ?? style.indent.repeat(2);
539
+ const comma = lastContent.trim() === "" || lastContent.endsWith(",") ? "" : ",";
540
+ const insertAt = open + 1 + lastContent.length;
541
+ edited = `${source.slice(0, insertAt)}${comma}\n${indent}tencil(),${source.slice(insertAt)}`;
542
+ } else {
543
+ const trimmed = inner.trim().replace(/,$/, "");
544
+ edited = `${source.slice(0, open + 1)}${trimmed ? `${trimmed}, ` : ""}tencil()${source.slice(close)}`;
545
+ }
546
+ } else {
547
+ const config = /defineConfig\(\s*\{/.exec(source);
548
+ if (!config) return null;
549
+ const at = config.index + config[0].length;
550
+ edited = `${source.slice(0, at)}\n${style.indent}plugins: [tencil()],${source.slice(at)}`;
551
+ }
552
+ return addImport(edited, `import tencil from ${style.quote}tencil/vite${style.quote}${style.semi}`);
553
+ }
554
+ /** Render `<Tencil />` as the last child of `<body>` in a layout or _document. */
555
+ function addTencilToBody(source) {
556
+ if (/["']tencil\/react["']/.test(source)) return source;
557
+ const style = detectStyle(source);
558
+ const close = source.lastIndexOf("</body>");
559
+ if (close === -1) return null;
560
+ const lineStart = source.lastIndexOf("\n", close) + 1;
561
+ const before = source.slice(lineStart, close);
562
+ let edited;
563
+ if (before.trim() === "") edited = `${source.slice(0, lineStart)}${before}${style.indent}<Tencil />\n${source.slice(lineStart)}`;
564
+ else edited = `${source.slice(0, close)}<Tencil />${source.slice(close)}`;
565
+ return addImport(edited, `import { Tencil } from ${style.quote}tencil/react${style.quote}${style.semi}`);
566
+ }
567
+ /** Index of the bracket closing the one at `open`, skipping strings and comments. */
568
+ function matchBracket(source, open) {
569
+ const pairs = {
570
+ "[": "]",
571
+ "(": ")",
572
+ "{": "}"
573
+ };
574
+ const stack = [];
575
+ for (let i = open; i < source.length; i++) {
576
+ const char = source[i];
577
+ if (char === "\"" || char === "'" || char === "`") {
578
+ i = skipString(source, i);
579
+ continue;
580
+ }
581
+ if (char === "/" && source[i + 1] === "/") {
582
+ i = source.indexOf("\n", i);
583
+ if (i === -1) return -1;
584
+ continue;
585
+ }
586
+ if (char === "/" && source[i + 1] === "*") {
587
+ i = source.indexOf("*/", i + 2) + 1;
588
+ if (i === 0) return -1;
589
+ continue;
590
+ }
591
+ if (pairs[char]) stack.push(pairs[char]);
592
+ else if (char === stack.at(-1)) {
593
+ stack.pop();
594
+ if (stack.length === 0) return i;
595
+ }
596
+ }
597
+ return -1;
598
+ }
599
+ function skipString(source, start) {
600
+ const quote = source[start];
601
+ for (let i = start + 1; i < source.length; i++) if (source[i] === "\\") i++;
602
+ else if (source[i] === quote) return i;
603
+ return source.length;
604
+ }
605
+ /** Projects set up while Tencil was called Fixhere (up to 0.2.0) import it under the old name. */
606
+ function usesFixhere(source) {
607
+ return /(['"])fixhere\/(?:react|vite)\1/.test(source);
608
+ }
609
+ /** Point a Fixhere integration at Tencil: `fixhere/react` → `tencil/react`, `<Fixhere />` → `<Tencil />`. */
610
+ function renameFromFixhere(source) {
611
+ return source.replace(/(['"])fixhere\/(react|vite)\1/g, "$1tencil/$2$1").replace(/\bFixhere\b/g, "Tencil").replace(/\bimport\s+fixhere\b/g, "import tencil").replace(/\bfixhere\(/g, "tencil(");
612
+ }
613
+ //#endregion
614
+ //#region src/init/detect-framework.ts
615
+ /** Inspect a project folder to decide how Tencil should be wired in. */
616
+ async function detectFramework(root) {
617
+ const pkg = await readPackageJson(root);
618
+ if (!pkg) return {
619
+ kind: "unknown",
620
+ reason: "No package.json in this folder."
621
+ };
622
+ const deps = {
623
+ ...pkg.dependencies,
624
+ ...pkg.devDependencies
625
+ };
626
+ const first = (candidates) => candidates.map((c) => join(root, c)).find(existsSync);
627
+ if (deps.next) {
628
+ const layout = first(variants(["app/layout", "src/app/layout"], [
629
+ "tsx",
630
+ "jsx",
631
+ "ts",
632
+ "js"
633
+ ]));
634
+ if (layout) return {
635
+ kind: "next-app",
636
+ layout
637
+ };
638
+ return {
639
+ kind: "next-pages",
640
+ document: first(variants(["pages/_document", "src/pages/_document"], [
641
+ "tsx",
642
+ "jsx",
643
+ "ts",
644
+ "js"
645
+ ]))
646
+ };
647
+ }
648
+ const viteConfig = first(variants(["vite.config"], [
649
+ "ts",
650
+ "mts",
651
+ "js",
652
+ "mjs",
653
+ "cts",
654
+ "cjs"
655
+ ]));
656
+ if (viteConfig) return {
657
+ kind: "vite",
658
+ config: viteConfig
659
+ };
660
+ if (deps.vite) return {
661
+ kind: "unknown",
662
+ reason: "Vite is installed but no vite.config was found."
663
+ };
664
+ return {
665
+ kind: "unknown",
666
+ reason: "Couldn't detect Next.js or Vite. Add the script tag to your dev HTML instead."
667
+ };
668
+ }
669
+ /** Next.js and Vite apps up to two folders down (apps/web, packages/site), for monorepo roots. */
670
+ async function findApps(root) {
671
+ const apps = [];
672
+ const visit = async (dir, depth) => {
673
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
674
+ for (const entry of entries) {
675
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
676
+ const child = join(dir, entry.name);
677
+ const framework = await detectFramework(child);
678
+ if (framework.kind !== "unknown") apps.push({
679
+ dir: child,
680
+ label: framework.kind === "vite" ? "Vite" : "Next.js"
681
+ });
682
+ else if (depth < 2) await visit(child, depth + 1);
683
+ }
684
+ };
685
+ await visit(root, 1);
686
+ return apps.sort((a, b) => a.dir.localeCompare(b.dir));
687
+ }
688
+ /** Walk up from `root` to the nearest lockfile; monorepo apps share the root's manager. */
689
+ function detectPackageManager(root) {
690
+ let dir = root;
691
+ while (true) {
692
+ if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
693
+ if (existsSync(join(dir, "yarn.lock"))) return "yarn";
694
+ if (existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb"))) return "bun";
695
+ if (existsSync(join(dir, "package-lock.json"))) return "npm";
696
+ const parent = dirname(dir);
697
+ if (parent === dir) return "npm";
698
+ dir = parent;
699
+ }
700
+ }
701
+ function installCommand(manager, spec) {
702
+ switch (manager) {
703
+ case "pnpm": return ["pnpm", [
704
+ "add",
705
+ "-D",
706
+ spec
707
+ ]];
708
+ case "yarn": return ["yarn", [
709
+ "add",
710
+ "-D",
711
+ spec
712
+ ]];
713
+ case "bun": return ["bun", [
714
+ "add",
715
+ "-d",
716
+ spec
717
+ ]];
718
+ default: return ["npm", [
719
+ "install",
720
+ "-D",
721
+ spec
722
+ ]];
723
+ }
724
+ }
725
+ function uninstallCommand(manager, name) {
726
+ return manager === "npm" ? ["npm", ["uninstall", name]] : [manager, ["remove", name]];
727
+ }
728
+ function variants(bases, extensions) {
729
+ return bases.flatMap((base) => extensions.map((ext) => `${base}.${ext}`));
730
+ }
731
+ async function readPackageJson(root) {
732
+ try {
733
+ return JSON.parse(await readFile(join(root, "package.json"), "utf8"));
734
+ } catch {
735
+ return null;
736
+ }
737
+ }
738
+ //#endregion
739
+ //#region src/init/diff.ts
740
+ function diffLines(before, after) {
741
+ const a = before.split("\n");
742
+ const b = after.split("\n");
743
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
744
+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
745
+ const out = [];
746
+ let i = 0;
747
+ let j = 0;
748
+ while (i < a.length || j < b.length) if (i < a.length && j < b.length && a[i] === b[j]) {
749
+ out.push({
750
+ kind: "same",
751
+ text: a[i++]
752
+ });
753
+ j++;
754
+ } else if (i < a.length && (j === b.length || lcs[i + 1][j] >= lcs[i][j + 1])) out.push({
755
+ kind: "remove",
756
+ text: a[i++]
757
+ });
758
+ else out.push({
759
+ kind: "add",
760
+ text: b[j++]
761
+ });
762
+ return out;
763
+ }
764
+ /** Keep `context` unchanged lines around each change; collapse the rest. */
765
+ function hunks(lines, context = 2) {
766
+ const keep = /* @__PURE__ */ new Set();
767
+ lines.forEach((line, index) => {
768
+ if (line.kind === "same") return;
769
+ for (let k = index - context; k <= index + context; k++) keep.add(k);
770
+ });
771
+ const out = [];
772
+ let skipped = false;
773
+ lines.forEach((line, index) => {
774
+ if (keep.has(index)) {
775
+ out.push(line);
776
+ skipped = false;
777
+ } else if (!skipped) {
778
+ out.push("…");
779
+ skipped = true;
780
+ }
781
+ });
782
+ return out;
783
+ }
784
+ //#endregion
785
+ //#region src/init/run-init.ts
786
+ const SCRIPT_TAG = "<script src=\"http://localhost:4747/tencil.js\" async><\/script>";
787
+ /** Work out the edits without touching the disk. */
788
+ async function planInit(root) {
789
+ const framework = await detectFramework(root);
790
+ const edits = [];
791
+ const manual = [];
792
+ const edit = async (path, codemod, instruction) => {
793
+ if (!path) return void manual.push(instruction);
794
+ const before = await readFile(path, "utf8");
795
+ if (usesFixhere(before)) {
796
+ edits.push({
797
+ path,
798
+ before,
799
+ after: renameFromFixhere(before)
800
+ });
801
+ return;
802
+ }
803
+ if (/(?:tencil|fixhere)\.js/.test(before)) {
804
+ manual.push(`${relative(root, path)} loads tencil.js by hand. Replace that tag with \`<Tencil />\` from \`tencil/react\` so the bridge's port is picked up automatically.`);
805
+ return;
806
+ }
807
+ const after = codemod(before);
808
+ if (after === null) manual.push(`${instruction} (in ${relative(root, path)})`);
809
+ else if (after !== before) edits.push({
810
+ path,
811
+ before,
812
+ after
813
+ });
814
+ };
815
+ switch (framework.kind) {
816
+ case "vite":
817
+ await edit(framework.config, addVitePlugin, "Add `tencil()` from `tencil/vite` to `plugins`");
818
+ break;
819
+ case "next-app":
820
+ await edit(framework.layout, addTencilToBody, "Render `<Tencil />` from `tencil/react` at the end of `<body>`");
821
+ break;
822
+ case "next-pages":
823
+ await edit(framework.document, addTencilToBody, "Create pages/_document and render `<Tencil />` from `tencil/react` at the end of `<body>`");
824
+ break;
825
+ case "unknown": manual.push(`${framework.reason} Load this in development only: ${SCRIPT_TAG}`);
826
+ }
827
+ return {
828
+ framework,
829
+ edits,
830
+ manual
831
+ };
832
+ }
833
+ async function runInit(options) {
834
+ const log = options.log ?? console.log;
835
+ const plan = await planInit(options.root);
836
+ log(`\n ${pc.bold("Tencil")} ${pc.dim("·")} ${describe(plan.framework)}\n`);
837
+ for (const edit of plan.edits) {
838
+ log(` ${pc.bold(relative(options.root, edit.path))}`);
839
+ for (const line of hunks(diffLines(edit.before, edit.after))) if (line === "…") log(pc.dim(" …"));
840
+ else if (line.kind === "add") log(pc.green(` + ${line.text}`));
841
+ else if (line.kind === "remove") log(pc.red(` - ${line.text}`));
842
+ else log(pc.dim(` ${line.text}`));
843
+ log("");
844
+ }
845
+ if (plan.edits.length === 0 && plan.manual.length === 0) log(` ${pc.green("✓")} Already set up.\n`);
846
+ for (const step of plan.manual) log(` ${pc.yellow("!")} ${step}`);
847
+ if (plan.manual.length) log("");
848
+ if (options.dryRun) return;
849
+ if (plan.edits.length && !options.yes) {
850
+ if (!process.stdin.isTTY) {
851
+ log(` Re-run with ${pc.cyan("--yes")} to apply these changes.\n`);
852
+ return;
853
+ }
854
+ const rl = createInterface({
855
+ input: process.stdin,
856
+ output: process.stdout
857
+ });
858
+ const answer = await rl.question(` Apply these changes? ${pc.dim("(Y/n)")} `);
859
+ rl.close();
860
+ if (/^n/i.test(answer.trim())) return log(" Nothing changed.\n");
861
+ }
862
+ for (const edit of plan.edits) await writeFile(edit.path, edit.after);
863
+ if (!options.skipInstall && plan.framework.kind !== "unknown") {
864
+ if (!await hasDependency(options.root, "tencil") || options.from) install(options, log);
865
+ if (await hasDependency(options.root, "fixhere")) uninstall(options, "fixhere", log);
866
+ }
867
+ let autostart = false;
868
+ if (options.daemon) {
869
+ const result = await ensureDaemon(options.daemon, defaultDataDir());
870
+ autostart = result.autostart;
871
+ log(` ${pc.green("✓")} Tencil ${result.status === "running" ? "is running" : result.status} on port ${options.daemon.port}.`);
872
+ }
873
+ if (!options.skipPair) await prepareProvider(await chooseProvider({
874
+ yes: options.yes,
875
+ t3Url: options.t3Url,
876
+ log
877
+ }), options.t3Url, log);
878
+ log(` ${pc.green("✓")} Done. Start your dev server and press ${pc.bold("C")} on the page.`);
879
+ if (options.daemon && !autostart) log(pc.dim(" Start Tencil at login: npx tencil setup"));
880
+ log("");
881
+ }
882
+ /** Already a dependency (and no other package asked for with `--from`)? */
883
+ async function hasDependency(root, name) {
884
+ try {
885
+ const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
886
+ return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
887
+ } catch {
888
+ return false;
889
+ }
890
+ }
891
+ function uninstall(options, name, log) {
892
+ const [command, args] = uninstallCommand(detectPackageManager(options.root), name);
893
+ log(` ${pc.dim(`$ ${command} ${args.join(" ")}`)}`);
894
+ spawnSync(command, args, {
895
+ cwd: options.root,
896
+ stdio: "inherit",
897
+ shell: process.platform === "win32",
898
+ env: withoutNpmEnv()
899
+ });
900
+ }
901
+ function install(options, log) {
902
+ const [command, args] = installCommand(detectPackageManager(options.root), options.from ?? "tencil");
903
+ log(` ${pc.dim(`$ ${command} ${args.join(" ")}`)}`);
904
+ if (spawnSync(command, args, {
905
+ cwd: options.root,
906
+ stdio: "inherit",
907
+ shell: process.platform === "win32",
908
+ env: withoutNpmEnv()
909
+ }).status !== 0) log(` ${pc.yellow("!")} Install failed; run it yourself: ${command} ${args.join(" ")}\n`);
910
+ }
911
+ function describe(framework) {
912
+ switch (framework.kind) {
913
+ case "next-app": return "Next.js (app router)";
914
+ case "next-pages": return "Next.js (pages router)";
915
+ case "vite": return "Vite";
916
+ default: return "framework not detected";
917
+ }
918
+ }
919
+ //#endregion
920
+ //#region src/service/migrate-from-fixhere.ts
921
+ /** What Fixhere (Tencil's name up to 0.2.0) called its login service. */
922
+ function fixhereServiceNames(port = DEFAULT_PORT) {
923
+ const names = [{
924
+ label: "dev.fixhere.daemon",
925
+ unit: "fixhere.service",
926
+ task: "Fixhere"
927
+ }];
928
+ if (port !== 4747) names.push({
929
+ label: `dev.fixhere.daemon.${port}`,
930
+ unit: `fixhere-${port}.service`,
931
+ task: `Fixhere ${port}`
932
+ });
933
+ return names;
934
+ }
935
+ /** Files that move to Tencil's data folder: pins, pairing, settings. Not the runtime copy or logs. */
936
+ function carriesOver(path) {
937
+ const name = basename(path);
938
+ return !/^runtime(-\d+)?$/.test(name) && name !== "daemon.log";
939
+ }
940
+ /**
941
+ * Move a Fixhere install over to Tencil, once: copy its data folder, remove its
942
+ * login service and stop its daemon, which would otherwise hold the port.
943
+ */
944
+ async function migrateFromFixhere(port, dataDir, log) {
945
+ const steps = [];
946
+ const oldDir = join(dirname(dataDir), "fixhere");
947
+ if (existsSync(oldDir) && !existsSync(dataDir)) {
948
+ cpSync(oldDir, dataDir, {
949
+ recursive: true,
950
+ filter: carriesOver
951
+ });
952
+ steps.push("pins and pairing");
953
+ }
954
+ for (const names of fixhereServiceNames(port)) {
955
+ if (servicePort(readServiceDefinition(names)) !== port) continue;
956
+ removeService(names);
957
+ steps.push("login service");
958
+ }
959
+ if (await stopFixhereDaemon(port)) steps.push("daemon");
960
+ if (steps.length) log(`\n ${pc.green("✓")} Moved Fixhere over to Tencil ${pc.dim(`(${[...new Set(steps)].join(", ")})`)}`);
961
+ }
962
+ /** A Fixhere daemon on `port` answers /health as "fixhere"; stop it so Tencil can listen. */
963
+ async function stopFixhereDaemon(port) {
964
+ const health = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1500) }).then((response) => response.json()).catch(() => void 0);
965
+ if (health?.name !== "fixhere" || !health.pid) return false;
966
+ try {
967
+ process.kill(health.pid, "SIGTERM");
968
+ } catch {
969
+ return false;
970
+ }
971
+ for (let attempt = 0; attempt < 50; attempt++) {
972
+ await new Promise((resolve) => setTimeout(resolve, 100));
973
+ if (!await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(500) }).catch(() => void 0)) return true;
974
+ }
975
+ return true;
976
+ }
977
+ //#endregion
978
+ //#region src/cli/commands/connect.ts
979
+ async function connect(input, t3Url) {
980
+ const store = new CredentialStore();
981
+ const baseUrl = t3Url ?? await store.lastBaseUrl() ?? "http://127.0.0.1:3773";
982
+ let pairing = input;
983
+ if (!pairing) {
984
+ console.log(`\n ${pc.dim("Creating a pairing code on the local T3 Code…")}`);
985
+ pairing = await createLocalPairingCode(baseUrl).catch(() => void 0);
986
+ }
987
+ if (!pairing) {
988
+ console.log(`
989
+ Create a pairing link in ${pc.bold("T3 Code → Settings → Connections")}
990
+ (or run ${pc.cyan("npx t3 pair")}) and paste it below.
991
+ `);
992
+ const rl = createInterface({
993
+ input: process.stdin,
994
+ output: process.stdout
995
+ });
996
+ pairing = await rl.question(" Pairing link or code: ");
997
+ rl.close();
998
+ }
999
+ const target = parsePairingInput(pairing, baseUrl);
1000
+ const credential = await exchangePairingCredential(target);
1001
+ await store.set(target.baseUrl, credential);
1002
+ console.log(`\n ${pc.green("✓")} Paired with T3 Code at ${target.baseUrl} ${pc.dim(`(valid until ${new Date(credential.expiresAt).toLocaleDateString()})`)}\n`);
1003
+ }
1004
+ //#endregion
1005
+ //#region src/cli/format.ts
1006
+ function time() {
1007
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString([], {
1008
+ hour: "2-digit",
1009
+ minute: "2-digit",
1010
+ second: "2-digit"
1011
+ });
1012
+ }
1013
+ //#endregion
1014
+ //#region src/cli/options.ts
1015
+ const RUNTIME_MODES = [
1016
+ "approval-required",
1017
+ "auto-accept-edits",
1018
+ "auto",
1019
+ "full-access"
1020
+ ];
1021
+ /** Flags the background daemon and the login service inherit from `start`. */
1022
+ const DAEMON_FLAGS = [
1023
+ "t3-url",
1024
+ "model",
1025
+ "runtime-mode",
1026
+ "listen",
1027
+ "allow-origin",
1028
+ "no-create-project"
1029
+ ];
1030
+ function forwardedFlags(values) {
1031
+ const args = [];
1032
+ for (const flag of DAEMON_FLAGS) {
1033
+ const value = values[flag];
1034
+ if (value === true) args.push(`--${flag}`);
1035
+ else if (typeof value === "string") args.push(`--${flag}`, value);
1036
+ else if (Array.isArray(value)) for (const v of value) args.push(`--${flag}`, String(v));
1037
+ }
1038
+ return args;
1039
+ }
1040
+ /** Tencil's runtime modes in Claude Code's terms. */
1041
+ const PERMISSION_MODES = {
1042
+ "approval-required": "default",
1043
+ "auto-accept-edits": "acceptEdits",
1044
+ auto: "auto",
1045
+ "full-access": "bypassPermissions"
1046
+ };
1047
+ function permissionModeFor(runtimeMode) {
1048
+ return runtimeMode ? PERMISSION_MODES[runtimeMode] : void 0;
1049
+ }
1050
+ function parseModel(value) {
1051
+ if (!value) return void 0;
1052
+ const [instanceId, ...model] = value.split(":");
1053
+ if (!instanceId || model.length === 0) throw new Error("--model must look like instance:model");
1054
+ return {
1055
+ instanceId,
1056
+ model: model.join(":")
1057
+ };
1058
+ }
1059
+ //#endregion
1060
+ //#region src/cli/commands/daemon.ts
1061
+ async function runDaemon(values, port, provider, t3Url, runtimeMode) {
1062
+ const model = values.model;
1063
+ const t3Model = model?.includes(":") ? model : void 0;
1064
+ const daemon = await startDaemon({
1065
+ port,
1066
+ listen: values.listen,
1067
+ allowedOrigins: values["allow-origin"],
1068
+ provider,
1069
+ claudeCode: {
1070
+ model: t3Model ? void 0 : model,
1071
+ permissionMode: permissionModeFor(runtimeMode)
1072
+ },
1073
+ t3: {
1074
+ url: t3Url,
1075
+ modelSelection: parseModel(t3Model),
1076
+ runtimeMode,
1077
+ createProjectIfMissing: !values["no-create-project"]
1078
+ },
1079
+ log: (message) => console.log(`${pc.dim(time())} ${message}`),
1080
+ flags: forwardedFlags(values)
1081
+ }).catch((error) => {
1082
+ if (error.code === "EADDRINUSE") throw new Error(`Port ${port} is in use. Is Tencil already running? Try \`tencil status\`.`);
1083
+ throw error;
1084
+ });
1085
+ const shutdown = async () => {
1086
+ await daemon.close();
1087
+ process.exit(0);
1088
+ };
1089
+ process.once("SIGINT", shutdown);
1090
+ process.once("SIGTERM", shutdown);
1091
+ }
1092
+ //#endregion
1093
+ //#region src/cli/commands/setup.ts
1094
+ /** `tencil setup`: once per machine. Starts the daemon (at login, by default) and pairs. */
1095
+ async function setup(command, options = {}) {
1096
+ const log = (message) => console.log(message);
1097
+ log(`\n ${pc.bold("Tencil")} setup ${pc.dim(`v${VERSION}`)}\n`);
1098
+ await prepareProvider(await chooseProvider({
1099
+ ...options,
1100
+ log
1101
+ }), options.t3Url, log);
1102
+ await setUpMachine(command, options, log);
1103
+ log(`
1104
+ Next, in each project: ${pc.cyan("npx tencil")}
1105
+ Then start its dev server and press ${pc.bold("C")} on the page.
1106
+ `);
1107
+ }
1108
+ /** Ask about starting at login (yes by default), then start the daemon that way. */
1109
+ async function setUpMachine(command, options, log) {
1110
+ const dataDir = defaultDataDir();
1111
+ if (options.yes || !process.stdin.isTTY ? true : await confirm("Start Tencil automatically when you log in?")) {
1112
+ log(pc.dim(" Setting up the login service…"));
1113
+ try {
1114
+ const where = await enableAutostart(command, dataDir, options.from);
1115
+ log(` ${pc.green("✓")} Tencil is running on port ${command.port} and starts when you log in ${pc.dim(`(${where})`)}`);
1116
+ return;
1117
+ } catch (error) {
1118
+ log(` ${pc.yellow("!")} ${error instanceof Error ? error.message : String(error)}`);
1119
+ }
1120
+ } else if (isServiceInstalled(command.port)) await uninstallService(command.port);
1121
+ await startInBackground(command, dataDir);
1122
+ log(` ${pc.green("✓")} Tencil is running on port ${command.port}. After a restart, run ${pc.cyan("npx tencil start")}.`);
1123
+ }
1124
+ async function confirm(question) {
1125
+ const rl = createInterface({
1126
+ input: process.stdin,
1127
+ output: process.stdout
1128
+ });
1129
+ const answer = await rl.question(` ${question} ${pc.dim("(Y/n)")} `);
1130
+ rl.close();
1131
+ return !/^n/i.test(answer.trim());
1132
+ }
1133
+ //#endregion
1134
+ //#region src/cli/commands/quickstart.ts
1135
+ /**
1136
+ * `npx tencil`: set up this machine if it isn't yet, then add Tencil to the
1137
+ * project in the current folder when there is one.
1138
+ */
1139
+ async function quickstart(command, options) {
1140
+ const log = (message) => console.log(message);
1141
+ log(`\n ${pc.bold("Tencil")} ${pc.dim(`v${VERSION}`)}\n`);
1142
+ await prepareProvider(await chooseProvider({
1143
+ ...options,
1144
+ log
1145
+ }), options.t3Url, log);
1146
+ if (!await probeDaemon(command.port) && !isServiceInstalled(command.port)) await setUpMachine(command, options, log);
1147
+ else {
1148
+ const result = await ensureDaemon(command, defaultDataDir());
1149
+ const verb = result.status === "running" ? "is running" : result.status;
1150
+ log(` ${pc.green("✓")} Tencil ${verb} on port ${command.port}${result.autostart ? pc.dim(" (starts at login)") : ""}`);
1151
+ }
1152
+ const framework = await detectFramework(options.root);
1153
+ if (framework.kind !== "unknown" || existsSync(join(options.root, "package.json"))) {
1154
+ const apps = framework.kind === "unknown" ? await findApps(options.root) : [];
1155
+ if (apps.length === 0) return runInit({
1156
+ root: options.root,
1157
+ yes: options.yes,
1158
+ from: options.from,
1159
+ port: command.port,
1160
+ skipPair: true
1161
+ });
1162
+ log(`\n This looks like a monorepo. Run ${pc.cyan("npx tencil")} in the app to add it to:`);
1163
+ for (const app of apps) log(` ${pc.bold(relative(options.root, app.dir))} ${pc.dim(app.label)}`);
1164
+ log("");
1165
+ return;
1166
+ }
1167
+ log(`
1168
+ To add Tencil to a project, run ${pc.cyan("npx tencil")} in its folder (Next.js or Vite).
1169
+ Then start its dev server and press ${pc.bold("C")} on the page.
1170
+ `);
1171
+ }
1172
+ //#endregion
1173
+ //#region src/cli/commands/service.ts
1174
+ async function service(action, command, from) {
1175
+ if (action === "install") {
1176
+ const where = await enableAutostart(command, defaultDataDir(), from);
1177
+ console.log(`\n ${pc.green("✓")} Tencil now starts when you log in ${pc.dim(`(${where})`)}\n`);
1178
+ return;
1179
+ }
1180
+ if (action === "uninstall") {
1181
+ await uninstallService(command.port);
1182
+ rmSync(runtimeDir(defaultDataDir(), command.port), {
1183
+ recursive: true,
1184
+ force: true
1185
+ });
1186
+ console.log(`\n ${pc.green("✓")} Removed the login service.\n`);
1187
+ return;
1188
+ }
1189
+ throw new Error("Use `tencil service install` or `tencil service uninstall`.");
1190
+ }
1191
+ //#endregion
1192
+ //#region src/cli/commands/start.ts
1193
+ async function start(command) {
1194
+ const result = await ensureDaemon(command, defaultDataDir());
1195
+ const verb = result.status === "running" ? "is running" : result.status;
1196
+ console.log(`
1197
+ ${pc.green("●")} ${pc.bold("Tencil")} ${verb} ${pc.dim(`(v${VERSION}, port ${command.port})`)}
1198
+
1199
+ Open a project's dev server and press ${pc.bold("C")} on the page. Projects need the
1200
+ overlay loaded once: run ${pc.cyan("npx tencil")} in the project.${result.autostart ? "" : `\n ${pc.dim(`Start it automatically at login: ${pc.cyan("npx tencil setup")}`)}`}
1201
+ `);
1202
+ }
1203
+ //#endregion
1204
+ //#region src/cli/commands/status.ts
1205
+ async function status(port) {
1206
+ const health = await probeDaemon(port);
1207
+ if (!health) {
1208
+ console.log(`\n The Tencil daemon isn't running. Start it with ${pc.cyan("npx tencil start")}.\n`);
1209
+ process.exitCode = 1;
1210
+ return;
1211
+ }
1212
+ console.log(`\n ${pc.green("●")} Tencil v${health.version} on port ${port} ${pc.dim(`(pid ${health.pid})`)}`);
1213
+ if (health.projects.length === 0) console.log(pc.dim(" No projects yet; open a dev page with the overlay."));
1214
+ for (const project of health.projects) {
1215
+ const state = project.provider.state === "ready" ? pc.green("ready") : pc.yellow(project.provider.state);
1216
+ console.log(` ${pc.bold(project.name)} ${pc.dim(project.root)} ${project.provider.label}: ${state} ${pc.dim(`${project.clients} page(s)`)}`);
1217
+ }
1218
+ console.log("");
1219
+ }
1220
+ //#endregion
1221
+ //#region src/cli/index.ts
1222
+ const HELP = `
1223
+ ${pc.bold("tencil")}: point at your UI, prompt your agent.
1224
+
1225
+ ${pc.dim("Usage")}
1226
+ tencil Set up this machine if needed, then add Tencil to this project
1227
+ tencil setup Set up this machine: start Tencil (at login) and pair
1228
+ tencil init [options] Load the overlay in this project (Next.js, Vite)
1229
+ tencil start Start the daemon in the background
1230
+ tencil start --foreground Run the daemon in this terminal
1231
+ tencil stop Stop the daemon
1232
+ tencil status Show the daemon and the projects it serves
1233
+ tencil service install Start the daemon automatically when you log in
1234
+ tencil service uninstall Remove the login service
1235
+ tencil connect [pairing-link] Pair with T3 Code (automatic for a local T3 Code)
1236
+
1237
+ ${pc.dim("Daemon options")}
1238
+ --port <n> Port (default ${DEFAULT_PORT}, env TENCIL_PORT)
1239
+ --provider <name> t3code | claude-code: this machine's agent (setup asks when unset)
1240
+ --t3-url <url> T3 Code server (default ${DEFAULT_T3_URL}, env TENCIL_T3_URL)
1241
+ --model <model> T3 Code: instance:model, e.g. claudeAgent:claude-fable-5-1
1242
+ Claude Code: a model, e.g. claude-opus-5-5 (default: its default)
1243
+ --runtime-mode <mode> approval-required | auto-accept-edits | auto | full-access
1244
+ --listen <address> Also listen here, e.g. a Tailscale IP for a remote browser (repeatable)
1245
+ --allow-origin <url> Allow a non-localhost page to connect (repeatable)
1246
+ --no-create-project Don't register unknown folders as T3 Code projects
1247
+
1248
+ ${pc.dim("Setup and init options")}
1249
+ -y, --yes Accept the defaults / apply changes without asking
1250
+ --dry-run Show the changes without writing them
1251
+ --skip-install Don't install the tencil package
1252
+ --skip-pair Don't pair with T3 Code
1253
+ --from <spec> Package to install instead of "tencil" (e.g. a local path)
1254
+
1255
+ -h, --help Show help
1256
+ -v, --version Show version
1257
+ `;
1258
+ /** Commands that start or install the daemon. */
1259
+ const SETS_UP = [
1260
+ "setup",
1261
+ "start",
1262
+ "init",
1263
+ "service"
1264
+ ];
1265
+ async function main() {
1266
+ const { values, positionals } = parseArgs({
1267
+ allowPositionals: true,
1268
+ options: {
1269
+ port: { type: "string" },
1270
+ root: { type: "string" },
1271
+ provider: { type: "string" },
1272
+ "t3-url": { type: "string" },
1273
+ model: { type: "string" },
1274
+ "runtime-mode": { type: "string" },
1275
+ listen: {
1276
+ type: "string",
1277
+ multiple: true
1278
+ },
1279
+ "allow-origin": {
1280
+ type: "string",
1281
+ multiple: true
1282
+ },
1283
+ "no-create-project": { type: "boolean" },
1284
+ foreground: { type: "boolean" },
1285
+ yes: {
1286
+ type: "boolean",
1287
+ short: "y"
1288
+ },
1289
+ "dry-run": { type: "boolean" },
1290
+ "skip-install": { type: "boolean" },
1291
+ "skip-pair": { type: "boolean" },
1292
+ from: { type: "string" },
1293
+ help: {
1294
+ type: "boolean",
1295
+ short: "h"
1296
+ },
1297
+ version: {
1298
+ type: "boolean",
1299
+ short: "v"
1300
+ }
1301
+ }
1302
+ });
1303
+ if (values.help) return void console.log(HELP);
1304
+ if (values.version) return void console.log(VERSION);
1305
+ const [command, ...rest] = positionals;
1306
+ const t3Url = values["t3-url"] ?? process.env.TENCIL_T3_URL;
1307
+ const port = values.port ? Number.parseInt(values.port, 10) : Number(process.env.TENCIL_PORT ?? 4747);
1308
+ const provider = values.provider;
1309
+ if (provider && !PROVIDERS.includes(provider)) throw new Error(`--provider must be one of ${PROVIDERS.join(", ")}`);
1310
+ if (provider && command !== "daemon") await saveProvider(provider);
1311
+ const runtimeMode = values["runtime-mode"];
1312
+ if (runtimeMode && !RUNTIME_MODES.includes(runtimeMode)) throw new Error(`--runtime-mode must be one of ${RUNTIME_MODES.join(", ")}`);
1313
+ const daemonCommand = {
1314
+ node: process.execPath,
1315
+ cli: fileURLToPath(import.meta.url),
1316
+ port,
1317
+ args: forwardedFlags(values)
1318
+ };
1319
+ if (command === void 0 || SETS_UP.includes(command)) await migrateFromFixhere(port, defaultDataDir(), console.log);
1320
+ switch (command) {
1321
+ case void 0: return quickstart(daemonCommand, {
1322
+ root: resolve(values.root ?? process.cwd()),
1323
+ yes: values.yes,
1324
+ from: values.from,
1325
+ t3Url
1326
+ });
1327
+ case "daemon": return runDaemon(values, port, provider, t3Url, runtimeMode);
1328
+ case "start":
1329
+ if (values.foreground) return runDaemon(values, port, provider, t3Url, runtimeMode);
1330
+ return start(daemonCommand);
1331
+ case "setup": return setup(daemonCommand, {
1332
+ yes: values.yes,
1333
+ from: values.from,
1334
+ t3Url
1335
+ });
1336
+ case "stop":
1337
+ if (isServiceInstalled(port)) {
1338
+ await stopService(port);
1339
+ console.log(`\n ${pc.green("✓")} Stopped the Tencil daemon until you next log in. ${pc.dim("Remove the login service: npx tencil service uninstall")}\n`);
1340
+ return;
1341
+ }
1342
+ console.log(await stopDaemon(port) ? `\n ${pc.green("✓")} Stopped the Tencil daemon.\n` : "\n The Tencil daemon isn't running.\n");
1343
+ return;
1344
+ case "status": return status(port);
1345
+ case "service": return service(rest[0], daemonCommand, values.from);
1346
+ case "connect": return connect(rest[0], t3Url);
1347
+ case "init": return runInit({
1348
+ root: resolve(values.root ?? process.cwd()),
1349
+ yes: values.yes,
1350
+ dryRun: values["dry-run"],
1351
+ skipInstall: values["skip-install"],
1352
+ skipPair: values["skip-pair"],
1353
+ from: values.from,
1354
+ port,
1355
+ daemon: daemonCommand,
1356
+ t3Url
1357
+ });
1358
+ default:
1359
+ console.error(`Unknown command "${command}"\n${HELP}`);
1360
+ process.exitCode = 1;
1361
+ }
1362
+ }
1363
+ main().catch((error) => {
1364
+ console.error(`\n ${pc.red("✗")} ${error instanceof Error ? error.message : String(error)}\n`);
1365
+ process.exit(1);
1366
+ });
1367
+ //#endregion
1368
+ export {};