tencil 0.0.0-stage → 0.3.0

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