kiteline 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +4 -2
  2. package/dist/{auth-CYNu-f_h.mjs → auth-DfYnQl7W.mjs} +6 -2
  3. package/dist/{banner-C1Jj4n4W.mjs → banner-BuOcmDsa.mjs} +2 -1
  4. package/dist/cli.mjs +8 -8
  5. package/dist/{control-BEq2N-wP.mjs → control-BgN8_tax.mjs} +7 -3
  6. package/dist/{control-BpOGsRCZ.mjs → control-C7c3jEfx.mjs} +1 -1
  7. package/dist/{devices-command-Bubh46v1.mjs → devices-command-B3MMYPtN.mjs} +2 -2
  8. package/dist/{package-COJ2H5Hh.mjs → package-DHOE_RH7.mjs} +1 -1
  9. package/dist/{pair-command-DHeG-ZsP.mjs → pair-command-XALkCQUv.mjs} +2 -2
  10. package/dist/service-C5qMgcr3.mjs +1 -0
  11. package/dist/service-DslziQUi.mjs +350 -0
  12. package/dist/{src-MfqVh1pV.mjs → src-CTDwjLMW.mjs} +539 -36
  13. package/dist/web/assets/Check.es-BA1UHLtA.js +1 -0
  14. package/dist/web/assets/X.es-DJ1WqcAP.js +1 -0
  15. package/dist/web/assets/composer-BX_w26mL.js +1 -0
  16. package/dist/web/assets/copy-button-B4svySbV.js +1 -0
  17. package/dist/web/assets/format-CvRKEalM.js +9 -0
  18. package/dist/web/assets/index-BuRrTWI4.css +1 -0
  19. package/dist/web/assets/index-DGeAdCJK.js +11 -0
  20. package/dist/web/assets/lazy/{core-B6TDb-vl.js → core-d0pVacdC.js} +1 -1
  21. package/dist/web/assets/new-BoDUmHwx.js +1 -0
  22. package/dist/web/assets/prefs-CbK1R9ph.js +1 -0
  23. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  24. package/dist/web/assets/routes-BccFpSN5.js +1 -0
  25. package/dist/web/assets/{s._sessionId-zegjksnG.js → s._sessionId-DGue-MjF.js} +12 -12
  26. package/dist/web/assets/settings-DqB0BC9E.js +1 -0
  27. package/dist/web/assets/status-ComAJ-QA.js +1 -0
  28. package/dist/web/assets/version-eBdZEdv0.js +1 -0
  29. package/dist/web/index.html +4 -3
  30. package/dist/web/push-sw.js +45 -0
  31. package/dist/web/sw.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/service-Fzh98Meh.mjs +0 -223
  34. package/dist/web/assets/MagnifyingGlass.es-DUOewsuL.js +0 -1
  35. package/dist/web/assets/Plus.es-wuLJIFEO.js +0 -1
  36. package/dist/web/assets/composer-3-vKn_3C.js +0 -1
  37. package/dist/web/assets/copy-button-CSWEBRJT.js +0 -1
  38. package/dist/web/assets/format-DYOlz7Mf.js +0 -9
  39. package/dist/web/assets/index-BRaZDA7B.css +0 -1
  40. package/dist/web/assets/index-DA4jO1yh.js +0 -11
  41. package/dist/web/assets/new-BGVIKCzl.js +0 -1
  42. package/dist/web/assets/prefs-DzSTtEbH.js +0 -1
  43. package/dist/web/assets/routes-DpVY3ZGq.js +0 -1
  44. package/dist/web/assets/settings-Dvc2znbn.js +0 -1
  45. package/dist/web/assets/status-D-preq93.js +0 -1
package/README.md CHANGED
@@ -19,6 +19,7 @@ It's self-hosted: your phone talks straight to your computer, and Claude Code ke
19
19
  - **Pick up where you left off,** or start a new session in any project.
20
20
  - **Watch it work.** Replies stream in, with every command and edit laid out step by step.
21
21
  - **Approve from anywhere.** Allow, deny with a note, or always allow, right from your phone.
22
+ - **Hear when it needs you.** Notifications on your lock screen when Claude Code asks for your OK or finishes, sent straight from your computer and sealed to your phone.
22
23
  - **Your modes, your models, your effort.** Change how much it asks, which model it uses and how hard it thinks, mid-session. `/effort` works just like in the terminal.
23
24
  - **Feels like an app.** Add it to your home screen, in light or dark.
24
25
 
@@ -32,7 +33,7 @@ npx kiteline --relay # or: pnpm dlx kiteline --relay, or: bunx kiteline -
32
33
 
33
34
  Scan the QR code it prints with your phone's camera, check that the phone and the terminal show the same six digits, and allow it: you're in, on any network. `--relay` connects through Kiteline's relay, sealed end to end: it passes your sessions on without being able to read them. Leave it out to keep Kiteline to your own Wi-Fi, or [use Tailscale](https://kiteline.seefun.dev/docs/#tailscale).
34
35
 
35
- To keep it running in the background, starting with your computer (Linux):
36
+ To keep it running in the background, starting with your computer (Linux and macOS):
36
37
 
37
38
  ```bash
38
39
  npm install -g kiteline # or: pnpm add -g kiteline, or: bun add -g kiteline
@@ -50,7 +51,7 @@ Everything else is in the **[docs](https://kiteline.seefun.dev/docs/)**:
50
51
 
51
52
  - **You approve every device.** A pairing code works once, for ten minutes, and only lets a device ask; it gets in once you allow it, like Bluetooth. Each device has its own key, and you can remove any one in Settings or with `kiteline devices`. Don't open Kiteline's port to the internet; use `--relay` or Tailscale to reach it from elsewhere.
52
53
  - **It uses Claude Code's own login,** your Claude plan or API key. Check that the way you use it fits your plan's terms.
53
- - **Tested on Linux so far.** Reports from real phones, macOS and Windows are very welcome.
54
+ - **Tested on Linux so far.** The macOS background service is new and has had less use. Reports from real phones, macOS and Windows are very welcome.
54
55
 
55
56
  ## Contributing
56
57
 
@@ -59,6 +60,7 @@ git clone https://github.com/sifenfisaha/kiteline.git && cd kiteline
59
60
  pnpm install
60
61
  pnpm dev # the server, the app and the website, reloading as you edit
61
62
  pnpm check # lint and format
63
+ pnpm test # the tests
62
64
  pnpm release # build the npm package into release/
63
65
  ```
64
66
 
@@ -91,10 +91,14 @@ var PairLimiter = class {
91
91
  }
92
92
  fail(key) {
93
93
  const entry = this.failures.get(key);
94
- const fresh = !entry || entry.until < Date.now();
94
+ const now = Date.now();
95
+ const fresh = !entry || entry.until < now;
96
+ if (this.failures.size > 200) {
97
+ for (const [other, old] of this.failures) if (old.until < now) this.failures.delete(other);
98
+ }
95
99
  this.failures.set(key, {
96
100
  count: fresh ? 1 : entry.count + 1,
97
- until: Date.now() + 6e5
101
+ until: now + 6e5
98
102
  });
99
103
  }
100
104
  clear(key) {
@@ -1024,7 +1024,8 @@ function readSettings() {
1024
1024
  allowBypass: yesNo("KITELINE_ALLOW_BYPASS", "Allowing Bypass mode", true),
1025
1025
  maxSessions: whole("KITELINE_MAX_SESSIONS", "The session limit", 6, 1, 100),
1026
1026
  idleMinutes: whole("KITELINE_IDLE_MINUTES", "The idle time", 20, 1, 10080),
1027
- relay: relay() ?? null
1027
+ relay: relay() ?? null,
1028
+ updateCheck: yesNo("KITELINE_UPDATE_CHECK", "Checking for updates", true)
1028
1029
  };
1029
1030
  }
1030
1031
  /** How the person started Kiteline, so the hints it prints name a command they can run. */
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-COJ2H5Hh.mjs";
3
- import { h as startedFromCli, i as dim, r as bold, t as accent } from "./banner-C1Jj4n4W.mjs";
2
+ import { t as version } from "./package-DHOE_RH7.mjs";
3
+ import { h as startedFromCli, i as dim, r as bold, t as accent } from "./banner-BuOcmDsa.mjs";
4
4
  import { parseArgs } from "node:util";
5
5
  // src/cli.ts
6
6
  const HELP = `
@@ -13,7 +13,7 @@ const HELP = `
13
13
  kiteline devices See the paired devices, and when each was last used
14
14
  kiteline devices remove <name or id>
15
15
  Unpair one device; with --all, every one
16
- kiteline service install Keep it running in the background, from startup (Linux)
16
+ kiteline service install Keep it running in the background, from startup (Linux, macOS)
17
17
  kiteline service uninstall Take the background service away
18
18
  kiteline service Say whether it's running in the background
19
19
 
@@ -95,7 +95,7 @@ const [command, action, ...rest] = positionals;
95
95
  if (rest.length && !(command === "devices" && action !== void 0)) fail(`"${rest.join(" ")}" isn't something Kiteline takes. Run ${bold("kiteline --help")}.`);
96
96
  /** The commands that talk to the Kiteline already running, with what to do when it isn't. */
97
97
  async function talk(run) {
98
- const { Unreachable } = await import("./control-BpOGsRCZ.mjs");
98
+ const { Unreachable } = await import("./control-C7c3jEfx.mjs");
99
99
  try {
100
100
  return await run();
101
101
  } catch (error) {
@@ -107,22 +107,22 @@ switch (command) {
107
107
  case void 0:
108
108
  case "start":
109
109
  if (action) fail(`"${action}" isn't something Kiteline takes. Run ${bold("kiteline --help")}.`);
110
- await import("./src-MfqVh1pV.mjs");
110
+ await import("./src-CTDwjLMW.mjs");
111
111
  break;
112
112
  case "pair": {
113
113
  if (action) fail(`"${action}" isn't something kiteline pair takes. Run ${bold("kiteline --help")}.`);
114
- const { pairCommand } = await import("./pair-command-DHeG-ZsP.mjs");
114
+ const { pairCommand } = await import("./pair-command-XALkCQUv.mjs");
115
115
  process.exit(await talk(pairCommand) ? 0 : 1);
116
116
  break;
117
117
  }
118
118
  case "devices": {
119
- const { devicesCommand } = await import("./devices-command-Bubh46v1.mjs");
119
+ const { devicesCommand } = await import("./devices-command-B3MMYPtN.mjs");
120
120
  await talk(() => devicesCommand(action, rest.join(" "), { all: values.all === true }));
121
121
  process.exit(0);
122
122
  break;
123
123
  }
124
124
  case "service": {
125
- const { service } = await import("./service-Fzh98Meh.mjs");
125
+ const { service } = await import("./service-C5qMgcr3.mjs");
126
126
  await service(action, { force: values.force === true });
127
127
  break;
128
128
  }
@@ -1,6 +1,7 @@
1
1
  import { M as toArray, O as preventNativeAwait, l as toStandardLazyResponse, m as RECURSIVE_CLIENT_UNWRAP_KEYS, o as toFetchRequest, r as StandardRPCLink, t as CompositeStandardLinkPlugin, x as intercept } from "./client.BPI7fHX3-CSey2FaL.mjs";
2
- import { a as localAddress, o as readComputerKey, r as kitelineHome, s as readServerInfo } from "./auth-CYNu-f_h.mjs";
3
- import { f as command, m as readSettings, p as loadOwnEnvFile, r as bold } from "./banner-C1Jj4n4W.mjs";
2
+ import { a as localAddress, o as readComputerKey, r as kitelineHome, s as readServerInfo } from "./auth-DfYnQl7W.mjs";
3
+ import { f as command, m as readSettings, p as loadOwnEnvFile, r as bold } from "./banner-BuOcmDsa.mjs";
4
+ import { r as restartCommand } from "./service-DslziQUi.mjs";
4
5
  // ../../node_modules/.pnpm/@orpc+client@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/client/dist/index.mjs
5
6
  function resolveFriendlyClientOptions(options) {
6
7
  return {
@@ -95,7 +96,10 @@ async function connectToKiteline() {
95
96
  const settings = readSettings();
96
97
  guess = localAddress(settings.port, settings.host);
97
98
  } catch {}
98
- if (await status(guess)) throw new Unreachable(`The Kiteline that's running is older than this command. Restart it, then try again${process.platform === "linux" ? `; in the background, that's ${bold("systemctl --user restart kiteline")}` : ""}.`);
99
+ if (await status(guess)) {
100
+ const restart = restartCommand();
101
+ throw new Unreachable(`The Kiteline that's running is older than this command. Restart it, then try again${restart ? `; in the background, that's ${bold(restart)}` : ""}.`);
102
+ }
99
103
  throw new Unreachable(`Kiteline isn't running. Start it with ${bold(command("start"))}, or keep it running with ${bold("kiteline service install")}.`);
100
104
  }
101
105
  export { connectToKiteline as n, Unreachable as t };
@@ -1 +1 @@
1
- export { t as Unreachable, n as connectToKiteline } from "./control-BEq2N-wP.mjs";
1
+ export { t as Unreachable, n as connectToKiteline } from "./control-BgN8_tax.mjs";
@@ -1,5 +1,5 @@
1
- import { f as command, i as dim, r as bold, t as accent, u as spaced } from "./banner-C1Jj4n4W.mjs";
2
- import { n as connectToKiteline, t as Unreachable } from "./control-BEq2N-wP.mjs";
1
+ import { f as command, i as dim, r as bold, t as accent, u as spaced } from "./banner-BuOcmDsa.mjs";
2
+ import { n as connectToKiteline, t as Unreachable } from "./control-BgN8_tax.mjs";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  // src/devices-command.ts
5
5
  const say = (...lines) => console.log(["", ...lines.map((line) => line ? ` ${line}` : "")].join("\n"));
@@ -1,3 +1,3 @@
1
1
  // package.json
2
- var version = "0.3.3";
2
+ var version = "0.4.0";
3
3
  export { version as t };
@@ -1,5 +1,5 @@
1
- import { c as printPairingCode, f as command, i as dim, r as bold, t as accent, u as spaced } from "./banner-C1Jj4n4W.mjs";
2
- import { n as connectToKiteline } from "./control-BEq2N-wP.mjs";
1
+ import { c as printPairingCode, f as command, i as dim, r as bold, t as accent, u as spaced } from "./banner-BuOcmDsa.mjs";
2
+ import { n as connectToKiteline } from "./control-BgN8_tax.mjs";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  // src/pair-command.ts
5
5
  const say = (...lines) => console.log(lines.map((line) => line ? ` ${line}` : "").join("\n"));
@@ -0,0 +1 @@
1
+ export { i as service } from "./service-DslziQUi.mjs";
@@ -0,0 +1,350 @@
1
+ import { a as localAddress, r as kitelineHome } from "./auth-DfYnQl7W.mjs";
2
+ import { d as SettingsError, i as dim, m as readSettings, r as bold, t as accent } from "./banner-BuOcmDsa.mjs";
3
+ import { homedir, userInfo } from "node:os";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { delimiter, dirname, join, resolve } from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ // src/service.ts
8
+ /**
9
+ * `kiteline service`: Kiteline as a background service written for this computer, so it starts with it
10
+ * and restarts if it stops. On Linux that's a systemd user service, which also keeps going after you
11
+ * log out; on a Mac, a launchd agent, which runs while you're logged in. What the docs once listed as
12
+ * steps.
13
+ */
14
+ const NAME = process.env.KITELINE_SERVICE_NAME?.trim() || "kiteline";
15
+ const WRITTEN = "Written by `kiteline service install`. Run it again to change these settings.";
16
+ const MARK = `# ${WRITTEN}`;
17
+ /** launchd names its agents like addresses, back to front. */
18
+ const LABEL = `dev.seefun.${NAME}`;
19
+ /** The settings worth keeping in the service, when they're set now. Never a key. */
20
+ const KEPT = [
21
+ "PORT",
22
+ "HOST",
23
+ "KITELINE_PUBLIC_URL",
24
+ "KITELINE_RELAY",
25
+ "KITELINE_HOME",
26
+ "CLAUDE_PATH",
27
+ "KITELINE_ALLOW_BYPASS",
28
+ "KITELINE_MAX_SESSIONS",
29
+ "KITELINE_IDLE_MINUTES",
30
+ "KITELINE_UPDATE_CHECK"
31
+ ];
32
+ /** A label and a command, lined up with the others. */
33
+ const row = (label, value) => `${dim(label.padEnd(22))}${value}`;
34
+ function say(...lines) {
35
+ console.log([
36
+ "",
37
+ ...lines.map((line) => line ? ` ${line}` : ""),
38
+ ""
39
+ ].join("\n"));
40
+ }
41
+ function fail(...lines) {
42
+ console.error([
43
+ "",
44
+ ...lines.map((line, i) => i === 0 ? ` ${accent("◆")} ${line}` : ` ${line}`),
45
+ ""
46
+ ].join("\n"));
47
+ process.exit(1);
48
+ }
49
+ function systemctl(...args) {
50
+ return spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" });
51
+ }
52
+ function launchctl(...args) {
53
+ return spawnSync("launchctl", args, { encoding: "utf8" });
54
+ }
55
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
56
+ function systemd() {
57
+ const config = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
58
+ const file = join(config, "systemd", "user", `${NAME}.service`);
59
+ return {
60
+ file,
61
+ text: unitText,
62
+ state: () => systemctl("is-active", NAME).stdout.trim(),
63
+ start: async () => {
64
+ for (const step of [
65
+ ["daemon-reload"],
66
+ ["enable", NAME],
67
+ ["restart", NAME]
68
+ ]) {
69
+ const result = systemctl(...step);
70
+ if (result.status !== 0) return `systemctl --user ${step.join(" ")} failed:\n${result.stderr.trim()}`;
71
+ }
72
+ return null;
73
+ },
74
+ remove: () => {
75
+ systemctl("disable", "--now", NAME);
76
+ rmSync(file);
77
+ systemctl("daemon-reload");
78
+ },
79
+ logs: `journalctl --user -u ${NAME} -f`,
80
+ recentLogs: `journalctl --user -u ${NAME} -n 40`,
81
+ promise: "It starts with your computer and restarts if it stops.",
82
+ finish: () => {
83
+ const user = userInfo().username;
84
+ if (spawnSync("loginctl", [
85
+ "show-user",
86
+ user,
87
+ "--property=Linger",
88
+ "--value"
89
+ ], { encoding: "utf8" }).stdout.trim() === "yes") return "";
90
+ return spawnSync("loginctl", ["enable-linger", user], { stdio: [
91
+ "inherit",
92
+ "ignore",
93
+ "pipe"
94
+ ] }).status === 0 ? "" : `To start it at boot, before anyone logs in, run once: ${accent(`sudo loginctl enable-linger ${user}`)}`;
95
+ }
96
+ };
97
+ }
98
+ function launchd() {
99
+ const file = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
100
+ const domain = `gui/${userInfo().uid}`;
101
+ const target = `${domain}/${LABEL}`;
102
+ const log = logFile();
103
+ return {
104
+ file,
105
+ text: (command) => plistText(command, log),
106
+ state: () => {
107
+ const print = launchctl("print", target);
108
+ if (print.status !== 0) return "not loaded";
109
+ return /state = running/.test(print.stdout) ? "active" : "loaded, but not running";
110
+ },
111
+ start: async () => {
112
+ mkdirSync(dirname(log), {
113
+ recursive: true,
114
+ mode: 448
115
+ });
116
+ launchctl("bootout", target);
117
+ let result = launchctl("bootstrap", domain, file);
118
+ for (let i = 0; i < 12 && result.status !== 0; i++) {
119
+ await sleep(250);
120
+ result = launchctl("bootstrap", domain, file);
121
+ }
122
+ if (result.status !== 0) return `launchctl bootstrap ${domain} failed:\n${result.stderr.trim()}`;
123
+ launchctl("enable", target);
124
+ return null;
125
+ },
126
+ remove: () => {
127
+ launchctl("bootout", target);
128
+ rmSync(file);
129
+ },
130
+ logs: `tail -f ${log}`,
131
+ recentLogs: `tail -n 40 ${log}`,
132
+ promise: "It starts when you log in and restarts if it stops.",
133
+ finish: () => ""
134
+ };
135
+ }
136
+ function backend() {
137
+ if (process.platform === "darwin") return launchd();
138
+ if (process.platform !== "linux") fail("Setting Kiteline up to run in the background works on Linux and macOS so far.", `Here, keep ${bold("kiteline")} running in a terminal window.`);
139
+ if (systemctl("show-environment").status !== 0) fail("This computer doesn't run systemd's user services, which the background service needs.", `Keep ${bold("kiteline")} running in a terminal window instead.`);
140
+ return systemd();
141
+ }
142
+ /** Where the Mac service's output goes, beside Kiteline's other files: launchd keeps no log of its own. */
143
+ function logFile() {
144
+ return join(kitelineHome(process.env.KITELINE_HOME?.trim() || void 0), `${NAME}.log`);
145
+ }
146
+ /** systemd reads % and, in commands, $ as its own; a quoted value keeps spaces. */
147
+ function quote(value, { command = false } = {}) {
148
+ let out = value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("%", "%%");
149
+ if (command) out = out.replaceAll("$", () => "$$");
150
+ return `"${out}"`;
151
+ }
152
+ /** The settings worth keeping in the service, as they're set now, then the shell and folders to run with. */
153
+ function environment() {
154
+ return {
155
+ kept: KEPT.flatMap((key) => {
156
+ const value = process.env[key]?.trim();
157
+ return value ? [[key, value]] : [];
158
+ }),
159
+ shell: process.env.SHELL || "/bin/sh",
160
+ path: shellPath()
161
+ };
162
+ }
163
+ /** The folders Claude Code's Bash tool should find tools in: the ones this terminal has, less throwaways. */
164
+ function shellPath() {
165
+ const kept = (process.env.PATH ?? "").split(delimiter).filter(Boolean).filter((folder) => !/[\\/]_npx[\\/]|node_modules[\\/]\.bin/.test(folder));
166
+ return [...new Set(kept)].join(delimiter) || "/usr/local/bin:/usr/bin:/bin";
167
+ }
168
+ /** One-off runners keep their copy only for a while; each one's own way to install it for good. */
169
+ const RUNNERS = [
170
+ {
171
+ pattern: /[\\/]_npx[\\/]/,
172
+ name: "npx",
173
+ install: "npm install -g kiteline"
174
+ },
175
+ {
176
+ pattern: /[\\/]dlx[\\/]/,
177
+ name: "pnpm dlx",
178
+ install: "pnpm add -g kiteline"
179
+ },
180
+ {
181
+ pattern: /[\\/]bunx-/,
182
+ name: "bunx",
183
+ install: "bun add -g kiteline"
184
+ }
185
+ ];
186
+ /**
187
+ * What the service runs. npm and bun install Kiteline at a path that stays put across updates, so the
188
+ * service runs that file with this Node. pnpm keeps each global install in a folder of its own and
189
+ * points its `kiteline` command at the current one, so there the service runs that command, which
190
+ * still finds Kiteline after an update.
191
+ */
192
+ function launcher(script, node) {
193
+ const given = resolve(script);
194
+ const real = realpathSync(given);
195
+ const pnpmHome = /^(.*?)[\\/]global[\\/]v?\d+[\\/]/.exec(given)?.[1];
196
+ if (pnpmHome && /[\\/]\.pnpm[\\/]/.test(real)) {
197
+ const command = [join(pnpmHome, "bin", "kiteline"), join(pnpmHome, "kiteline")].find((shim) => existsSync(shim));
198
+ if (command) return [command];
199
+ }
200
+ return [node, real];
201
+ }
202
+ function unitText(command) {
203
+ const { kept, shell, path } = environment();
204
+ const settings = kept.map(([key, value]) => `Environment=${quote(`${key}=${value}`)}`);
205
+ return `${MARK}
206
+ [Unit]
207
+ Description=Kiteline: drive Claude Code from your phone
208
+ Documentation=https://kiteline.seefun.dev/docs/#always-on
209
+ After=network-online.target
210
+ Wants=network-online.target
211
+
212
+ [Service]
213
+ Type=simple
214
+ ExecStart=${command.map((part) => quote(part, { command: true })).join(" ")}
215
+ ${settings.length ? `${settings.join("\n")}\n` : ""}# Claude Code's Bash tool runs with this shell and finds tools in these folders, as in your terminal.
216
+ Environment=${quote(`SHELL=${shell}`)}
217
+ Environment=${quote(`PATH=${path}`)}
218
+ Restart=always
219
+ RestartSec=3
220
+ TimeoutStopSec=15
221
+
222
+ [Install]
223
+ WantedBy=default.target
224
+ `;
225
+ }
226
+ const xml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
227
+ /** The same service as a launchd agent, for a Mac: started at login, and again whenever it stops. */
228
+ function plistText(command, log) {
229
+ const { kept, shell, path } = environment();
230
+ const variables = [
231
+ ...kept,
232
+ ["SHELL", shell],
233
+ ["PATH", path]
234
+ ];
235
+ const text = (value) => `<string>${xml(value)}</string>`;
236
+ return `<?xml version="1.0" encoding="UTF-8"?>
237
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
238
+ <!-- ${WRITTEN} -->
239
+ <plist version="1.0">
240
+ <dict>
241
+ <key>Label</key>
242
+ ${text(LABEL)}
243
+ <key>ProgramArguments</key>
244
+ <array>
245
+ ${command.map((part) => `\t\t${text(part)}`).join("\n")}
246
+ </array>
247
+ <key>EnvironmentVariables</key>
248
+ <dict>
249
+ ${variables.map(([key, value]) => `\t\t<key>${xml(key)}</key>\n\t\t${text(value)}`).join("\n")}
250
+ </dict>
251
+ <key>WorkingDirectory</key>
252
+ ${text(homedir())}
253
+ <key>RunAtLoad</key>
254
+ <true/>
255
+ <key>KeepAlive</key>
256
+ <true/>
257
+ <key>ThrottleInterval</key>
258
+ <integer>3</integer>
259
+ <key>ProcessType</key>
260
+ <string>Interactive</string>
261
+ <key>StandardOutPath</key>
262
+ ${text(log)}
263
+ <key>StandardErrorPath</key>
264
+ ${text(log)}
265
+ </dict>
266
+ </plist>
267
+ `;
268
+ }
269
+ async function answers(url) {
270
+ return fetch(`${url}/auth/status`, { signal: AbortSignal.timeout(1500) }).then((r) => r.ok).catch(() => false);
271
+ }
272
+ async function install({ force }) {
273
+ const service = backend();
274
+ const script = process.argv[1] ?? "";
275
+ const real = realpathSync(script);
276
+ const runner = RUNNERS.find(({ pattern }) => pattern.test(real) || pattern.test(script));
277
+ if (runner) fail(`This copy of Kiteline came from ${runner.name}, which may clear it out later, and a service needs one that stays.`, "Install it, then set up the service with that copy:", "", ` ${accent(runner.install)}`, ` ${accent("kiteline service install")}`);
278
+ let settings;
279
+ try {
280
+ settings = readSettings();
281
+ } catch (error) {
282
+ if (!(error instanceof SettingsError)) throw error;
283
+ fail(error.message);
284
+ }
285
+ const { file } = service;
286
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : null;
287
+ if (existing !== null && !existing.includes(WRITTEN) && !force) fail(`There's already a ${NAME} service, set up by hand:`, dim(file), `Run ${bold("kiteline service install --force")} to replace it; the old file is kept beside it as .bak.`);
288
+ const url = localAddress(settings.port, settings.host);
289
+ if (!(service.state() === "active") && await answers(url)) fail(`Something already answers on port ${settings.port}, perhaps Kiteline in another terminal.`, `Stop it first (Ctrl C in its window), then run ${bold("kiteline service install")} again.`);
290
+ mkdirSync(dirname(file), { recursive: true });
291
+ if (existing !== null && !existing.includes(WRITTEN)) copyFileSync(file, `${file}.bak`);
292
+ writeFileSync(file, service.text(launcher(script, process.execPath)));
293
+ const serverFile = join(kitelineHome(settings.home), "server.json");
294
+ const before = existsSync(serverFile) ? statSync(serverFile).mtimeMs : 0;
295
+ const problem = await service.start();
296
+ if (problem) fail(...problem.split("\n"));
297
+ const note = service.finish();
298
+ let up = false;
299
+ for (let i = 0; i < 40 && !up; i++) {
300
+ await sleep(250);
301
+ up = existsSync(serverFile) && statSync(serverFile).mtimeMs > before && await answers(url);
302
+ }
303
+ if (!up) fail("The service is set up, but Kiteline didn't come up. See what it said with:", "", ` ${accent(service.recentLogs)}`);
304
+ say(`${bold("Kiteline runs in the background now.")} ${service.promise}`, "", row("See what it's doing", service.logs), row("Pair a phone", "kiteline pair"), row("See paired devices", "kiteline devices"), row("Change its settings", "kiteline service install, with the new options"), row("Stop running it", "kiteline service uninstall"), ...note ? ["", note] : []);
305
+ const { connectToKiteline } = await import("./control-C7c3jEfx.mjs");
306
+ const { client } = await connectToKiteline();
307
+ const { devices } = await client.devices.list();
308
+ if (!devices.length && process.stdin.isTTY && process.stdout.isTTY) {
309
+ const { pairCommand } = await import("./pair-command-XALkCQUv.mjs");
310
+ await pairCommand();
311
+ }
312
+ }
313
+ function uninstall({ force }) {
314
+ const service = backend();
315
+ const { file } = service;
316
+ if (!existsSync(file)) {
317
+ say(`Kiteline isn't set up to run in the background, so there's nothing to take away.`);
318
+ return;
319
+ }
320
+ if (!readFileSync(file, "utf8").includes(WRITTEN) && !force) fail(`The ${NAME} service was set up by hand:`, dim(file), `Run ${bold("kiteline service uninstall --force")} to remove it anyway.`);
321
+ service.remove();
322
+ say(`${bold("Kiteline no longer runs in the background.")} Paired phones stay paired.`, `Start it in a terminal with ${accent("kiteline")} whenever you like.`);
323
+ }
324
+ function status() {
325
+ const service = backend();
326
+ const { file } = service;
327
+ if (!existsSync(file)) {
328
+ say("Kiteline isn't set up to run in the background.", `Set it up with ${accent("kiteline service install")}: it starts with your computer and keeps going.`);
329
+ return;
330
+ }
331
+ const state = service.state();
332
+ say(state === "active" ? `${bold("Kiteline is running in the background.")}` : `${bold(`The ${NAME} service is set up, but it's ${state || "not running"}.`)}`, dim(file), "", row("See what it's doing", service.logs), row("Pair a phone", "kiteline pair"), row("See paired devices", "kiteline devices"), row("Stop running it", "kiteline service uninstall"));
333
+ }
334
+ /** How to start the background service again, for a hint to someone whose Kiteline is out of date. */
335
+ function restartCommand() {
336
+ if (process.platform === "linux") return `systemctl --user restart ${NAME}`;
337
+ if (process.platform === "darwin") return `launchctl kickstart -k gui/${userInfo().uid}/${LABEL}`;
338
+ return null;
339
+ }
340
+ async function service(action, options) {
341
+ switch (action) {
342
+ case "install": return install(options);
343
+ case "uninstall":
344
+ case "remove": return uninstall(options);
345
+ case void 0:
346
+ case "status": return status();
347
+ default: fail(`"kiteline service ${action}" isn't a thing. Try install, uninstall or status.`);
348
+ }
349
+ }
350
+ export { unitText as a, service as i, plistText as n, restartCommand as r, launcher as t };