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
@@ -1,12 +1,12 @@
1
1
  import { A as runWithSpan, C as isObject$1, D as parseEmptyableJSON, E as overlayProxy, M as toArray, N as value, S as isAsyncIteratorObject, T as onError, _ as toORPCError, a as toHttpPath, b as asyncIteratorWithSpan, c as toStandardLazyRequest, d as HibernationEventIterator, f as flattenHeader, g as isORPCErrorStatus, h as fallbackORPCErrorStatus, i as StandardRPCSerializer, j as setSpanError, k as resolveMaybeOptionalOptions, n as StandardRPCJsonSerializer, p as ORPCError, s as toFetchResponse, u as mapEventIterator, v as NullProtoObj, w as isTypescriptObject, x as intercept, y as ORPC_NAME } from "./client.BPI7fHX3-CSey2FaL.mjs";
2
- import { t as version$1 } from "./package-COJ2H5Hh.mjs";
3
- import { a as localAddress, c as safeEqual, i as loadComputerKey, l as saveServerInfo, n as PairLimiter, r as kitelineHome, t as DEVICE_COOKIE } from "./auth-CYNu-f_h.mjs";
4
- import { _ as RelayPath, a as pairingLinks, b as relaySocketUrl, c as printPairingCode, d as SettingsError, f as command, g as RelayClose, i as dim, l as printSettingsError, m as readSettings, n as addressesFor, o as printAlreadyRunning, r as bold, s as printBanner, t as accent, u as spaced, v as fromBase64Url, x as toBase64Url, y as hostIdFor } from "./banner-C1Jj4n4W.mjs";
2
+ import { t as version$1 } from "./package-DHOE_RH7.mjs";
3
+ import { a as localAddress, c as safeEqual, i as loadComputerKey, l as saveServerInfo, n as PairLimiter, r as kitelineHome, t as DEVICE_COOKIE } from "./auth-DfYnQl7W.mjs";
4
+ import { _ as RelayPath, a as pairingLinks, b as relaySocketUrl, c as printPairingCode, d as SettingsError, f as command, g as RelayClose, i as dim, l as printSettingsError, m as readSettings, n as addressesFor, o as printAlreadyRunning, r as bold, s as printBanner, t as accent, u as spaced, v as fromBase64Url, x as toBase64Url, y as hostIdFor } from "./banner-BuOcmDsa.mjs";
5
5
  import { homedir, hostname, platform } from "node:os";
6
6
  import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
- import { dirname, join, resolve } from "node:path";
7
+ import { basename, dirname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
9
+ import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, randomInt, randomUUID, sign, timingSafeEqual } from "node:crypto";
10
10
  import { STATUS_CODES, ServerResponse, createServer } from "node:http";
11
11
  import { Http2ServerRequest, constants } from "node:http2";
12
12
  import { Readable } from "node:stream";
@@ -1939,8 +1939,10 @@ function transcriptToItems(messages) {
1939
1939
  }
1940
1940
  // ../../packages/api/src/agent/run.ts
1941
1941
  const PHONE_NOTE = "The user is driving this session from Kiteline, a web client usually open on a phone. Keep replies easy to scan on a narrow screen: short paragraphs, and code blocks only when they help.";
1942
+ /** How many recent events a run keeps, for watchers picking up where a dropped connection left them. */
1943
+ const MAX_RECENT = 3e3;
1942
1944
  var Run = class {
1943
- emit;
1945
+ deliver;
1944
1946
  onEnd;
1945
1947
  sessionId;
1946
1948
  cwd;
@@ -1974,8 +1976,13 @@ var Run = class {
1974
1976
  /** Holds messages back until the session's effort is set, when the start options can't carry it. */
1975
1977
  hold = null;
1976
1978
  modelList = null;
1977
- constructor(options, emit, onEnd) {
1978
- this.emit = emit;
1979
+ /** The number of the last event sent. */
1980
+ seq = 0;
1981
+ /** The latest events, in order: every one numbered above `floor`. */
1982
+ recent = [];
1983
+ floor = 0;
1984
+ constructor(options, deliver, onEnd) {
1985
+ this.deliver = deliver;
1979
1986
  this.onEnd = onEnd;
1980
1987
  this.sessionId = options.sessionId;
1981
1988
  this.cwd = options.cwd;
@@ -2052,6 +2059,34 @@ var Run = class {
2052
2059
  await this.refreshEffort();
2053
2060
  });
2054
2061
  }
2062
+ /**
2063
+ * Numbers each event and keeps the latest, so a watcher that dropped can be sent only what it
2064
+ * missed. A snapshot replaces everything before it, so nothing earlier can be picked up from.
2065
+ */
2066
+ emit(event) {
2067
+ if (event.type === "snapshot") {
2068
+ this.recent = [];
2069
+ this.floor = this.seq;
2070
+ this.deliver(event);
2071
+ return;
2072
+ }
2073
+ const numbered = {
2074
+ ...event,
2075
+ seq: ++this.seq
2076
+ };
2077
+ this.recent.push(numbered);
2078
+ if (this.recent.length > MAX_RECENT) {
2079
+ const dropped = this.recent.splice(0, this.recent.length - MAX_RECENT);
2080
+ this.floor = dropped.at(-1)?.seq ?? this.floor;
2081
+ }
2082
+ this.deliver(numbered);
2083
+ }
2084
+ /** The events after `cursor`, or null when it's from another run or too far back: send a snapshot. */
2085
+ since(cursor) {
2086
+ if (cursor.startedAt !== this.startedAt) return null;
2087
+ if (cursor.seq < this.floor || cursor.seq > this.seq) return null;
2088
+ return this.recent.filter((event) => (event.seq ?? 0) > cursor.seq);
2089
+ }
2055
2090
  snapshot() {
2056
2091
  return {
2057
2092
  sessionId: this.sessionId,
@@ -2064,7 +2099,8 @@ var Run = class {
2064
2099
  error: this.error,
2065
2100
  permissions: [...this.pending.values()].map((p) => p.request),
2066
2101
  toolProgress: Object.fromEntries(this.toolProgress),
2067
- startedAt: this.startedAt
2102
+ startedAt: this.startedAt,
2103
+ seq: this.seq
2068
2104
  };
2069
2105
  }
2070
2106
  get pendingCount() {
@@ -2228,6 +2264,11 @@ var Run = class {
2228
2264
  this.input.close();
2229
2265
  this.q.close();
2230
2266
  }
2267
+ /** Put to sleep to make room: closed, and counted as closed at once rather than when the process has gone. */
2268
+ retire() {
2269
+ this.close();
2270
+ this.finish("closed", null);
2271
+ }
2231
2272
  canUseTool = (toolName, input, options) => new Promise((resolve) => {
2232
2273
  const id = options.toolUseID || randomUUID();
2233
2274
  const request = {
@@ -2283,6 +2324,7 @@ var Run = class {
2283
2324
  }
2284
2325
  }
2285
2326
  finish(status, error) {
2327
+ if (!this.isLive) return;
2286
2328
  this.flushDraft();
2287
2329
  for (const pending of this.pending.values()) pending.settle({
2288
2330
  behavior: "deny",
@@ -2498,6 +2540,15 @@ var Run = class {
2498
2540
  }
2499
2541
  };
2500
2542
  // ../../packages/api/src/agent/manager.ts
2543
+ /** How long a run that died with an error is remembered. */
2544
+ const FAILED_MS = 3e5;
2545
+ /** A turn counts as finished once the session has rested this long: the next queued one starts sooner. */
2546
+ const DONE_SETTLE_MS = 1500;
2547
+ /** A few words of a longer text, on one line. */
2548
+ function snippet(text, max = 180) {
2549
+ const line = text.replace(/\s+/g, " ").trim();
2550
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
2551
+ }
2501
2552
  var RunManager = class {
2502
2553
  config;
2503
2554
  runs = /* @__PURE__ */ new Map();
@@ -2509,6 +2560,8 @@ var RunManager = class {
2509
2560
  listWatchers = /* @__PURE__ */ new Set();
2510
2561
  listTimer = null;
2511
2562
  effort;
2563
+ /** Each session's status as last told, and the wait before calling a turn finished. */
2564
+ told = /* @__PURE__ */ new Map();
2512
2565
  constructor(config) {
2513
2566
  this.config = config;
2514
2567
  this.effort = new EffortCatalog(config.claudePath);
@@ -2600,9 +2653,22 @@ var RunManager = class {
2600
2653
  run.send(text, input.images);
2601
2654
  return { sessionId: id };
2602
2655
  }
2656
+ /**
2657
+ * Makes room for one more session. A session that's only resting holds a place it isn't using, so
2658
+ * at the limit the one idle longest goes to sleep early; the limit only refuses when every session
2659
+ * is working or waiting for an answer.
2660
+ */
2603
2661
  checkLimit() {
2604
- const liveCount = [...this.runs.values()].filter((run) => run.isLive).length;
2605
- if (liveCount >= this.config.maxLiveRuns) throw new Error(`${liveCount} sessions are already running. Stop one before starting another.`);
2662
+ const live = [...this.runs.values()].filter((run) => run.isLive);
2663
+ if (live.length < this.config.maxLiveRuns) return;
2664
+ const resting = live.filter((run) => run.status === "idle" && run.pendingCount === 0).sort((a, b) => a.lastActivity - b.lastActivity);
2665
+ let count = live.length;
2666
+ for (const run of resting) {
2667
+ if (count < this.config.maxLiveRuns) break;
2668
+ run.retire();
2669
+ count--;
2670
+ }
2671
+ if (count >= this.config.maxLiveRuns) throw new Error(`${count} sessions are busy right now. Stop one before starting another.`);
2606
2672
  }
2607
2673
  respond(sessionId, permissionId, decision) {
2608
2674
  this.require(sessionId).respond(permissionId, decision);
@@ -2630,8 +2696,12 @@ var RunManager = class {
2630
2696
  stopAll() {
2631
2697
  for (const run of this.runs.values()) run.close();
2632
2698
  }
2633
- /** Snapshot first, then every event for this session, across process restarts. */
2634
- async *watchSession(sessionId, signal) {
2699
+ /**
2700
+ * Snapshot first, then every event for this session, across process restarts. A watcher coming
2701
+ * back after a dropped connection says where it got to, and is sent only what it missed when the
2702
+ * run still has it.
2703
+ */
2704
+ async *watchSession(sessionId, signal, since) {
2635
2705
  const queue = new AsyncQueue();
2636
2706
  let watchers = this.sessionWatchers.get(sessionId);
2637
2707
  if (!watchers) {
@@ -2644,12 +2714,16 @@ var RunManager = class {
2644
2714
  if (signal?.aborted) queue.close();
2645
2715
  try {
2646
2716
  const run = this.runs.get(sessionId);
2647
- const failed = this.failed.get(sessionId);
2648
- const recent = failed && Date.now() - failed.at < 3e5 ? failed.snapshot : null;
2649
- yield {
2650
- type: "snapshot",
2651
- run: run ? run.snapshot() : recent
2652
- };
2717
+ const missed = run && since ? run.since(since) : null;
2718
+ if (missed) yield* missed;
2719
+ else {
2720
+ const failed = this.failed.get(sessionId);
2721
+ const recent = failed && Date.now() - failed.at < FAILED_MS ? failed.snapshot : null;
2722
+ yield {
2723
+ type: "snapshot",
2724
+ run: run ? run.snapshot() : recent
2725
+ };
2726
+ }
2653
2727
  for await (const event of queue) yield event;
2654
2728
  } finally {
2655
2729
  signal?.removeEventListener("abort", stop);
@@ -2677,9 +2751,57 @@ var RunManager = class {
2677
2751
  }
2678
2752
  broadcast(sessionId, event) {
2679
2753
  for (const queue of this.sessionWatchers.get(sessionId) ?? []) queue.push(event);
2754
+ if (this.config.notify) this.note(sessionId, event, this.config.notify);
2680
2755
  if (event.type === "status" || event.type === "permission" || event.type === "permission-resolved") this.scheduleListUpdate();
2681
2756
  if (event.type === "item" && event.item.kind === "user") this.scheduleListUpdate();
2682
2757
  }
2758
+ /** Picks out the moments worth a notification: asked for an answer, finished a turn, stopped on an error. */
2759
+ note(sessionId, event, notify) {
2760
+ const run = this.runs.get(sessionId);
2761
+ if (!run) return;
2762
+ const name = run.title || basename(run.cwd) || "Claude Code";
2763
+ if (event.type === "permission") {
2764
+ const { request } = event;
2765
+ const what = request.title || request.description || request.displayName || request.toolName;
2766
+ notify({
2767
+ kind: "permission",
2768
+ sessionId,
2769
+ title: `${name} needs your OK`,
2770
+ body: snippet(what)
2771
+ });
2772
+ return;
2773
+ }
2774
+ if (event.type !== "status") return;
2775
+ const before = this.told.get(sessionId);
2776
+ if (before?.timer) clearTimeout(before.timer);
2777
+ if (event.status === "closed" || event.status === "error") this.told.delete(sessionId);
2778
+ else this.told.set(sessionId, {
2779
+ status: event.status,
2780
+ timer: null
2781
+ });
2782
+ if (event.status === "error") notify({
2783
+ kind: "error",
2784
+ sessionId,
2785
+ title: `${name} stopped`,
2786
+ body: snippet(event.error || "Claude Code stopped with an error.")
2787
+ });
2788
+ else if (event.status === "idle" && (before?.status === "running" || before?.status === "waiting")) {
2789
+ const entry = this.told.get(sessionId);
2790
+ if (!entry) return;
2791
+ entry.timer = setTimeout(() => {
2792
+ entry.timer = null;
2793
+ if (run.status !== "idle") return;
2794
+ const reply = run.items.findLast((item) => item.kind === "text" && item.parent === null);
2795
+ notify({
2796
+ kind: "done",
2797
+ sessionId,
2798
+ title: `${name} is done`,
2799
+ body: snippet(reply?.kind === "text" ? reply.text : "") || "Claude Code finished its turn."
2800
+ });
2801
+ }, DONE_SETTLE_MS);
2802
+ entry.timer.unref?.();
2803
+ }
2804
+ }
2683
2805
  scheduleListUpdate() {
2684
2806
  this.listTimer ??= setTimeout(() => {
2685
2807
  this.listTimer = null;
@@ -2697,6 +2819,7 @@ var RunManager = class {
2697
2819
  }
2698
2820
  reap() {
2699
2821
  const now = Date.now();
2822
+ for (const [id, failed] of this.failed) if (now - failed.at > FAILED_MS) this.failed.delete(id);
2700
2823
  for (const run of this.runs.values()) if (run.status === "idle" && run.pendingCount === 0 && now - run.lastActivity > this.config.idleTimeoutMs) run.close();
2701
2824
  }
2702
2825
  };
@@ -2728,7 +2851,9 @@ var SessionTracker = class {
2728
2851
  recursive: true,
2729
2852
  mode: 448
2730
2853
  });
2731
- writeFileSync(this.file, `${JSON.stringify({ sessions: this.entries }, null, 2)}\n`, { mode: 384 });
2854
+ const temp = `${this.file}.${process.pid}.tmp`;
2855
+ writeFileSync(temp, `${JSON.stringify({ sessions: this.entries }, null, 2)}\n`, { mode: 384 });
2856
+ renameSync(temp, this.file);
2732
2857
  } catch {}
2733
2858
  }
2734
2859
  list() {
@@ -2959,26 +3084,53 @@ var Devices = class Devices extends EventEmitter {
2959
3084
  live = /* @__PURE__ */ new Map();
2960
3085
  watchers = /* @__PURE__ */ new Set();
2961
3086
  saveTimer = null;
3087
+ /** Where a devices file that couldn't be read was put aside, if one was: every device pairs again. */
3088
+ damaged;
2962
3089
  constructor(file) {
2963
3090
  super();
2964
3091
  this.file = file;
2965
- this.devices = Devices.load(file);
3092
+ const loaded = Devices.load(file);
3093
+ this.devices = loaded.devices;
3094
+ this.damaged = loaded.damaged;
2966
3095
  setInterval(() => this.sweep(), 15e3).unref();
2967
3096
  }
2968
3097
  static load(file) {
2969
3098
  try {
2970
- const data = JSON.parse(readFileSync(file, "utf8"));
2971
- return Array.isArray(data.devices) ? data.devices.filter(isStored).map((d) => ({
2972
- ...d,
2973
- name: cleanName(d.name),
2974
- lastSeen: typeof d.lastSeen === "string" ? d.lastSeen : null,
2975
- approvedBy: typeof d.approvedBy === "string" ? d.approvedBy : "terminal",
2976
- via: d.via === "relay" ? "relay" : "direct"
2977
- })) : [];
3099
+ return {
3100
+ devices: Devices.parse(readFileSync(file, "utf8")),
3101
+ damaged: null
3102
+ };
2978
3103
  } catch {
2979
- return [];
3104
+ if (!existsSync(file)) return {
3105
+ devices: [],
3106
+ damaged: null
3107
+ };
3108
+ const aside = `${file}.damaged-${Date.now()}`;
3109
+ try {
3110
+ renameSync(file, aside);
3111
+ return {
3112
+ devices: [],
3113
+ damaged: aside
3114
+ };
3115
+ } catch {
3116
+ return {
3117
+ devices: [],
3118
+ damaged: file
3119
+ };
3120
+ }
2980
3121
  }
2981
3122
  }
3123
+ static parse(text) {
3124
+ const data = JSON.parse(text);
3125
+ if (!data || typeof data !== "object") throw new Error("not a devices file");
3126
+ return Array.isArray(data.devices) ? data.devices.filter(isStored).map((d) => ({
3127
+ ...d,
3128
+ name: cleanName(d.name),
3129
+ lastSeen: typeof d.lastSeen === "string" ? d.lastSeen : null,
3130
+ approvedBy: typeof d.approvedBy === "string" ? d.approvedBy : "terminal",
3131
+ via: d.via === "relay" ? "relay" : "direct"
3132
+ })) : [];
3133
+ }
2982
3134
  get count() {
2983
3135
  return this.devices.length;
2984
3136
  }
@@ -3354,6 +3506,236 @@ var Devices = class Devices extends EventEmitter {
3354
3506
  } catch {}
3355
3507
  }
3356
3508
  };
3509
+ // ../../packages/api/src/push.ts
3510
+ /** Who to say the sender is: push services want an address, and this is the project's. */
3511
+ const SUBJECT = "https://kiteline.seefun.dev";
3512
+ /** A notification nobody collected by then isn't worth showing. */
3513
+ const TTL_SECONDS = 3600;
3514
+ /** A push service that keeps failing has lost the subscription, whatever it says. */
3515
+ const MAX_FAILURES = 5;
3516
+ /**
3517
+ * How long a device's word that Kiteline is on its screen holds. It says so again every so often while
3518
+ * that's true, and a phone that locks or loses its connection just stops saying it.
3519
+ */
3520
+ const PRESENCE_MS = 45e3;
3521
+ const b64 = (bytes) => Buffer.from(bytes).toString("base64url");
3522
+ const unb64 = (text) => Buffer.from(text, "base64url");
3523
+ function isSubscription(value) {
3524
+ const s = value;
3525
+ return !!s && typeof s.device === "string" && typeof s.endpoint === "string" && typeof s.p256dh === "string" && typeof s.auth === "string" && !!s.vapid && typeof s.vapid.d === "string" && typeof s.vapid.x === "string" && typeof s.vapid.y === "string";
3526
+ }
3527
+ /** Only a push service over HTTPS: the address comes from a phone, and the computer calls it. */
3528
+ function validEndpoint(endpoint) {
3529
+ try {
3530
+ const url = new URL(endpoint);
3531
+ return url.protocol === "https:" && !!url.hostname && !url.username && !url.password;
3532
+ } catch {
3533
+ return false;
3534
+ }
3535
+ }
3536
+ /**
3537
+ * Seals a message to one browser, as RFC 8291 lays out (aes128gcm): a fresh key pair for each send,
3538
+ * agreed with the browser's own, so only it can open what comes out.
3539
+ */
3540
+ function sealPush(payload, to, fixed) {
3541
+ const browser = unb64(to.p256dh);
3542
+ const secret = unb64(to.auth);
3543
+ if (browser.length !== 65 || browser[0] !== 4) throw new Error("That isn't a browser's push key.");
3544
+ const sender = createECDH("prime256v1");
3545
+ if (fixed) sender.setPrivateKey(fixed.privateKey);
3546
+ else sender.generateKeys();
3547
+ const ours = sender.getPublicKey();
3548
+ const shared = sender.computeSecret(browser);
3549
+ const salt = fixed?.salt ?? randomBytes(16);
3550
+ const info = Buffer.concat([
3551
+ Buffer.from("WebPush: info\0"),
3552
+ browser,
3553
+ ours
3554
+ ]);
3555
+ const material = Buffer.from(hkdfSync("sha256", shared, secret, info, 32));
3556
+ const key = Buffer.from(hkdfSync("sha256", material, salt, "Content-Encoding: aes128gcm\0", 16));
3557
+ const nonce = Buffer.from(hkdfSync("sha256", material, salt, "Content-Encoding: nonce\0", 12));
3558
+ const cipher = createCipheriv("aes-128-gcm", key, nonce);
3559
+ const sealed = Buffer.concat([
3560
+ cipher.update(payload),
3561
+ cipher.update(Buffer.from([2])),
3562
+ cipher.final()
3563
+ ]);
3564
+ const header = Buffer.alloc(21);
3565
+ salt.copy(header, 0);
3566
+ header.writeUInt32BE(4096, 16);
3567
+ header.writeUInt8(ours.length, 20);
3568
+ return Buffer.concat([
3569
+ header,
3570
+ ours,
3571
+ sealed,
3572
+ cipher.getAuthTag()
3573
+ ]);
3574
+ }
3575
+ function signingKey(vapid) {
3576
+ return createPrivateKey({
3577
+ key: {
3578
+ kty: "EC",
3579
+ crv: "P-256",
3580
+ ...vapid
3581
+ },
3582
+ format: "jwk"
3583
+ });
3584
+ }
3585
+ /** The phone's signing key's public half, as the browser was given it when it subscribed. */
3586
+ function vapidPublicKey(vapid) {
3587
+ return b64(Buffer.concat([
3588
+ Buffer.from([4]),
3589
+ unb64(vapid.x),
3590
+ unb64(vapid.y)
3591
+ ]));
3592
+ }
3593
+ /** The header that tells a push service this send is from whoever the phone subscribed to (RFC 8292). */
3594
+ function vapidHeader(endpoint, vapid, now = Date.now()) {
3595
+ const part = (value) => b64(Buffer.from(JSON.stringify(value)));
3596
+ const claims = {
3597
+ aud: new URL(endpoint).origin,
3598
+ exp: Math.floor(now / 1e3) + 43200,
3599
+ sub: SUBJECT
3600
+ };
3601
+ const unsigned = `${part({
3602
+ typ: "JWT",
3603
+ alg: "ES256"
3604
+ })}.${part(claims)}`;
3605
+ const signature = sign("sha256", Buffer.from(unsigned), {
3606
+ key: signingKey(vapid),
3607
+ dsaEncoding: "ieee-p1363"
3608
+ });
3609
+ return `vapid t=${unsigned}.${b64(signature)}, k=${vapidPublicKey(vapid)}`;
3610
+ }
3611
+ var Push = class Push {
3612
+ file;
3613
+ options;
3614
+ subscriptions;
3615
+ failures = /* @__PURE__ */ new Map();
3616
+ /** Devices that said their screen is showing Kiteline, and until when that's believed. */
3617
+ visible = /* @__PURE__ */ new Map();
3618
+ constructor(file, options) {
3619
+ this.file = file;
3620
+ this.options = options;
3621
+ this.subscriptions = Push.load(file);
3622
+ }
3623
+ static load(file) {
3624
+ try {
3625
+ const data = JSON.parse(readFileSync(file, "utf8"));
3626
+ return Array.isArray(data?.subscriptions) ? data.subscriptions.filter(isSubscription) : [];
3627
+ } catch {
3628
+ return [];
3629
+ }
3630
+ }
3631
+ save() {
3632
+ mkdirSync(dirname(this.file), {
3633
+ recursive: true,
3634
+ mode: 448
3635
+ });
3636
+ const temp = `${this.file}.${process.pid}.tmp`;
3637
+ writeFileSync(temp, `${JSON.stringify({
3638
+ version: 1,
3639
+ subscriptions: this.subscriptions
3640
+ }, null, 2)}\n`, { mode: 384 });
3641
+ renameSync(temp, this.file);
3642
+ }
3643
+ /** Where this device's notifications go, if it has them on. */
3644
+ status(device) {
3645
+ const found = this.subscriptions.find((s) => s.device === device);
3646
+ return {
3647
+ enabled: !!found,
3648
+ endpoint: found?.endpoint ?? null
3649
+ };
3650
+ }
3651
+ /**
3652
+ * Turns notifications on for a device, and sends one to show it worked: a subscription that can't be
3653
+ * sent to isn't kept. `quiet` skips that, for a device giving a changed subscription again.
3654
+ */
3655
+ async subscribe(device, subscription, { quiet = false } = {}) {
3656
+ if (!validEndpoint(subscription.endpoint)) throw new Error("That isn't a push service's address.");
3657
+ try {
3658
+ vapidHeader(subscription.endpoint, subscription.vapid);
3659
+ sealPush(/* @__PURE__ */ new Uint8Array(), subscription);
3660
+ } catch {
3661
+ throw new Error("This phone's keys for notifications can't be used. Turn them off and on again.");
3662
+ }
3663
+ const stored = {
3664
+ ...subscription,
3665
+ device,
3666
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
3667
+ };
3668
+ const outcome = quiet ? "sent" : await this.deliver(stored, {
3669
+ kind: "hello",
3670
+ title: "Notifications are on",
3671
+ body: "Kiteline will tell you here when Claude Code needs you or finishes."
3672
+ });
3673
+ if (outcome !== "sent") throw new Error(outcome === "gone" ? "This phone's push service turned the notification away. Turn notifications off and on again." : "Your computer couldn't reach this phone's push service. Check its internet connection.");
3674
+ this.subscriptions = [...this.subscriptions.filter((s) => s.device !== device), stored];
3675
+ this.failures.delete(device);
3676
+ this.save();
3677
+ }
3678
+ unsubscribe(device) {
3679
+ this.visible.delete(device);
3680
+ this.failures.delete(device);
3681
+ if (!this.subscriptions.some((s) => s.device === device)) return;
3682
+ this.subscriptions = this.subscriptions.filter((s) => s.device !== device);
3683
+ try {
3684
+ this.save();
3685
+ } catch {}
3686
+ }
3687
+ /** A device says whether Kiteline is on its screen: while it is, there's nothing to notify it of. */
3688
+ presence(device, visible) {
3689
+ if (visible) this.visible.set(device, Date.now() + PRESENCE_MS);
3690
+ else this.visible.delete(device);
3691
+ }
3692
+ watching(device) {
3693
+ return (this.visible.get(device) ?? 0) > Date.now();
3694
+ }
3695
+ /** Tells every device that has notifications on and isn't looking at Kiteline right now. */
3696
+ async notify(note) {
3697
+ const away = this.subscriptions.filter((s) => !this.watching(s.device));
3698
+ await Promise.all(away.map(async (subscription) => {
3699
+ const outcome = await this.deliver(subscription, note);
3700
+ if (outcome === "sent") {
3701
+ this.failures.delete(subscription.device);
3702
+ return;
3703
+ }
3704
+ const failures = (this.failures.get(subscription.device) ?? 0) + 1;
3705
+ this.failures.set(subscription.device, failures);
3706
+ if (outcome === "gone" || failures >= MAX_FAILURES) {
3707
+ this.options.log?.("A phone's notifications stopped working, so they're turned off for it.");
3708
+ this.unsubscribe(subscription.device);
3709
+ }
3710
+ }));
3711
+ }
3712
+ async deliver(to, note) {
3713
+ try {
3714
+ const computer = this.options.computer;
3715
+ const body = sealPush(Buffer.from(JSON.stringify({
3716
+ ...note,
3717
+ ...computer ? { computer } : {}
3718
+ })), to);
3719
+ const response = await (this.options.send ?? ((url, init) => fetch(url, init)))(to.endpoint, {
3720
+ method: "POST",
3721
+ headers: {
3722
+ authorization: vapidHeader(to.endpoint, to.vapid),
3723
+ "content-encoding": "aes128gcm",
3724
+ "content-type": "application/octet-stream",
3725
+ ttl: String(TTL_SECONDS),
3726
+ urgency: "high",
3727
+ ...note.sessionId ? { topic: note.sessionId.replaceAll("-", "").slice(0, 32) } : {}
3728
+ },
3729
+ body: new Uint8Array(body),
3730
+ signal: AbortSignal.timeout(15e3)
3731
+ });
3732
+ if (response.status >= 200 && response.status < 300) return "sent";
3733
+ return response.status === 404 || response.status === 410 ? "gone" : "failed";
3734
+ } catch {
3735
+ return "failed";
3736
+ }
3737
+ }
3738
+ };
3357
3739
  // ../../node_modules/.pnpm/@orpc+contract@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/contract/dist/shared/contract.D_dZrO__.mjs
3358
3740
  var ValidationError = class extends Error {
3359
3741
  issues;
@@ -9288,6 +9670,9 @@ const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
9288
9670
  $ZodURL.init(inst, def);
9289
9671
  ZodStringFormat.init(inst, def);
9290
9672
  });
9673
+ function url(params) {
9674
+ return /* @__PURE__ */ _url(ZodURL, params);
9675
+ }
9291
9676
  const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
9292
9677
  $ZodEmoji.init(inst, def);
9293
9678
  ZodStringFormat.init(inst, def);
@@ -9897,6 +10282,41 @@ dirs: protectedProcedure.input(object({
9897
10282
  dirs
9898
10283
  };
9899
10284
  }) };
10285
+ // ../../packages/api/src/routers/push.ts
10286
+ const key = string().regex(/^[\w-]+$/);
10287
+ /** Notifications are a device's own: the terminal has none to turn on. */
10288
+ function device(context) {
10289
+ if (context.caller?.kind !== "device") throw new ORPCError("BAD_REQUEST", { message: "Notifications are turned on from a paired device." });
10290
+ return context.caller.id;
10291
+ }
10292
+ /** Lock-screen notifications for the device that's asking; see ../push. */
10293
+ const pushRouter = {
10294
+ status: protectedProcedure.handler(({ context }) => context.push.status(device(context))),
10295
+ subscribe: protectedProcedure.input(object({
10296
+ endpoint: url().max(2e3),
10297
+ p256dh: key.min(80).max(100),
10298
+ auth: key.min(16).max(64),
10299
+ vapid: object({
10300
+ d: key.max(64),
10301
+ x: key.max(64),
10302
+ y: key.max(64)
10303
+ }),
10304
+ /** Giving a changed subscription again, with nothing to show for it. */
10305
+ quiet: boolean().optional()
10306
+ })).handler(async ({ input: { quiet, ...subscription }, context }) => {
10307
+ await context.push.subscribe(device(context), subscription, { quiet });
10308
+ return { ok: true };
10309
+ }),
10310
+ unsubscribe: protectedProcedure.handler(({ context }) => {
10311
+ context.push.unsubscribe(device(context));
10312
+ return { ok: true };
10313
+ }),
10314
+ /** Whether Kiteline is on this device's screen: while it is, it isn't sent notifications. */
10315
+ presence: protectedProcedure.input(object({ visible: boolean() })).handler(({ input, context }) => {
10316
+ context.push.presence(device(context), input.visible);
10317
+ return { ok: true };
10318
+ })
10319
+ };
9900
10320
  // ../../packages/api/src/routers/runs.ts
9901
10321
  const permissionMode = _enum(PERMISSION_MODES);
9902
10322
  const effort = object({
@@ -9931,8 +10351,12 @@ const runsRouter = {
9931
10351
  list: protectedProcedure.handler(async function* ({ context, signal }) {
9932
10352
  yield* context.manager.watchList(signal);
9933
10353
  }),
9934
- watch: protectedProcedure.input(session).handler(async function* ({ input, context, signal }) {
9935
- yield* context.manager.watchSession(input.sessionId, signal);
10354
+ /** `since` is where this watcher got to before its connection dropped, to be sent only the rest. */
10355
+ watch: protectedProcedure.input(session.extend({ since: object({
10356
+ startedAt: number(),
10357
+ seq: number().int().min(0)
10358
+ }).optional() })).handler(async function* ({ input, context, signal }) {
10359
+ yield* context.manager.watchSession(input.sessionId, signal, input.since);
9936
10360
  }),
9937
10361
  send: protectedProcedure.input(object({
9938
10362
  sessionId: uuid().optional(),
@@ -10074,9 +10498,11 @@ const appRouter = {
10074
10498
  home: homedir(),
10075
10499
  platform: platform(),
10076
10500
  version: context.version,
10501
+ latest: context.latestVersion(),
10077
10502
  allowBypass: context.allowBypass
10078
10503
  })) },
10079
10504
  devices: devicesRouter,
10505
+ push: pushRouter,
10080
10506
  sessions: sessionsRouter,
10081
10507
  runs: runsRouter,
10082
10508
  fs: fsRouter
@@ -13147,6 +13573,13 @@ async function startRelay(options) {
13147
13573
  ws.close();
13148
13574
  } catch {}
13149
13575
  if (stopped) return;
13576
+ if (code === RelayClose.Replaced) {
13577
+ stopped = true;
13578
+ connected = false;
13579
+ options.log("Another Kiteline on this computer took over the relay connection, so this one is off the relay now.");
13580
+ options.log("Phones still reach this one on your own network. Stop the other, then restart this, to bring it back.");
13581
+ return;
13582
+ }
13150
13583
  if (connected) options.log("Lost the relay; reconnecting.");
13151
13584
  else if (attempt === 0) {
13152
13585
  const why = code === RelayClose.TooMany ? "it's full right now" : "couldn't reach it";
@@ -13215,6 +13648,50 @@ async function startRelay(options) {
13215
13648
  }
13216
13649
  };
13217
13650
  }
13651
+ // src/update.ts
13652
+ /**
13653
+ * Looks up the newest Kiteline on npm, so the terminal and the app can say when there's an update.
13654
+ * It asks for the package's public page and sends nothing about this computer; KITELINE_UPDATE_CHECK=off
13655
+ * turns it off.
13656
+ */
13657
+ const LATEST = "https://registry.npmjs.org/kiteline/latest";
13658
+ const FIRST_MS = 2e4;
13659
+ const EVERY_MS = 432e5;
13660
+ function parts(version) {
13661
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
13662
+ return match ? [
13663
+ Number(match[1]),
13664
+ Number(match[2]),
13665
+ Number(match[3])
13666
+ ] : null;
13667
+ }
13668
+ /** Whether `candidate` is a newer release than `current`. Anything that isn't a plain x.y.z is not. */
13669
+ function isNewer(candidate, current) {
13670
+ const theirs = parts(candidate);
13671
+ const ours = parts(current);
13672
+ if (!theirs || !ours) return false;
13673
+ for (let i = 0; i < 3; i++) if (theirs[i] !== ours[i]) return (theirs[i] ?? 0) > (ours[i] ?? 0);
13674
+ return false;
13675
+ }
13676
+ function watchForUpdates(current, onNewer) {
13677
+ let latest = null;
13678
+ const check = async () => {
13679
+ try {
13680
+ const response = await fetch(LATEST, {
13681
+ headers: { accept: "application/json" },
13682
+ signal: AbortSignal.timeout(1e4)
13683
+ });
13684
+ if (!response.ok) return;
13685
+ const { version } = await response.json();
13686
+ if (typeof version !== "string" || !isNewer(version, current) || version === latest) return;
13687
+ latest = version;
13688
+ onNewer(version);
13689
+ } catch {}
13690
+ };
13691
+ setTimeout(() => void check(), FIRST_MS).unref();
13692
+ setInterval(() => void check(), EVERY_MS).unref();
13693
+ return () => latest;
13694
+ }
13218
13695
  // src/index.ts
13219
13696
  const dev = process.argv.includes("--dev");
13220
13697
  let settings;
@@ -13245,16 +13722,23 @@ const pairingLink = pairingLinks(webPort, where);
13245
13722
  const limiter = new PairLimiter();
13246
13723
  const interactive = !dev && !!process.stdin.isTTY && !!process.stdout.isTTY;
13247
13724
  const log = (message) => console.log(` ${message}`);
13725
+ const push = new Push(join(home, "push.json"), {
13726
+ computer: where.relay?.hostId,
13727
+ log
13728
+ });
13248
13729
  const manager = new RunManager({
13249
13730
  claudePath: settings.claudePath ?? null,
13250
13731
  allowBypass,
13251
13732
  maxLiveRuns: settings.maxSessions,
13252
13733
  idleTimeoutMs: settings.idleMinutes * 6e4,
13253
- tracker: new SessionTracker(join(home, "sessions.json"))
13734
+ tracker: new SessionTracker(join(home, "sessions.json")),
13735
+ notify: (note) => void push.notify(note)
13254
13736
  });
13255
13737
  const shared = {
13256
13738
  manager,
13257
13739
  devices,
13740
+ push,
13741
+ latestVersion: dev || !settings.updateCheck ? () => null : watchForUpdates(version$1, (version) => log(`Kiteline ${version} is out, and this is ${version$1}. Update with: npm install -g kiteline@latest`)),
13258
13742
  pairingLink,
13259
13743
  allowBypass,
13260
13744
  version: version$1
@@ -13282,6 +13766,15 @@ function callerOf(c) {
13282
13766
  if (header?.startsWith("Bearer ") && safeEqual(header.slice(7), computer.key)) return { kind: "terminal" };
13283
13767
  return null;
13284
13768
  }
13769
+ /**
13770
+ * The address a request came from, to count wrong pairing codes against. Behind Tailscale Serve or
13771
+ * another proxy on this computer every connection is from this computer, so there it's the address
13772
+ * the proxy passes on; that header is believed from nowhere else.
13773
+ */
13774
+ function remoteAddress(c) {
13775
+ const remote = getConnInfo(c).remote.address ?? "unknown";
13776
+ return (remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1" ? c.req.header("x-forwarded-for")?.split(",")[0]?.trim() : "") || remote;
13777
+ }
13285
13778
  const CLAIM_ERRORS = {
13286
13779
  unknown: `That pairing code isn't one this computer made. Make a new one with ${command("pair")}.`,
13287
13780
  expired: `That pairing code has expired. Make a new one with ${command("pair")}.`,
@@ -13375,7 +13868,7 @@ app.post("/auth/pair", async (c) => {
13375
13868
  via: "relay"
13376
13869
  });
13377
13870
  } else {
13378
- const ip = getConnInfo(c).remote.address ?? "unknown";
13871
+ const ip = remoteAddress(c);
13379
13872
  if (limiter.blocked(ip)) return c.json({
13380
13873
  ok: false,
13381
13874
  error: "Too many wrong codes. Wait ten minutes and try again."
@@ -13488,6 +13981,7 @@ if (!dev && webDir) {
13488
13981
  } else if (!dev) app.get("/", (c) => c.text("Kiteline's API is running. Build the web app with `pnpm build` to serve it from here."));
13489
13982
  let relay = null;
13490
13983
  devices.on("removed", (device, by) => {
13984
+ push.unsubscribe(device.id);
13491
13985
  const self = by.kind === "device" && by.id === device.id;
13492
13986
  setTimeout(() => {
13493
13987
  for (const cut of [...streams.get(device.id) ?? []]) cut();
@@ -13525,6 +14019,7 @@ const server = serve({
13525
14019
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
13526
14020
  });
13527
14021
  if (process.env.KITELINE_TOKEN?.trim()) log(`KITELINE_TOKEN isn't used any more: each device pairs with a one-time code from ${command("pair")}.`);
14022
+ if (devices.damaged) log(`The list of paired devices couldn't be read, so each phone needs pairing again. The old file is kept at ${devices.damaged}.`);
13528
14023
  if (startOver) log("Every device was unpaired.");
13529
14024
  else if (computer.replaced) log(`Pairing works differently from this version on: pair each phone again, once, with ${command("pair")}.`);
13530
14025
  if (interactive) startConsole({
@@ -13546,10 +14041,18 @@ const server = serve({
13546
14041
  });
13547
14042
  });
13548
14043
  server.on("error", (error) => {
13549
- if (error.code !== "EADDRINUSE") throw error;
13550
- printAlreadyRunning(port);
14044
+ if (error.code === "EADDRINUSE") printAlreadyRunning(port);
14045
+ else console.error(`\n Kiteline couldn't start listening on port ${port}: ${error.message}\n`);
13551
14046
  process.exit(1);
13552
14047
  });
14048
+ process.on("unhandledRejection", (reason) => {
14049
+ console.error(" Something went wrong inside Kiteline; it's still running.");
14050
+ console.error(reason instanceof Error ? reason.stack ?? reason.message : reason);
14051
+ });
14052
+ process.on("uncaughtException", (error) => {
14053
+ console.error(" Something went wrong inside Kiteline; it's still running.");
14054
+ console.error(error.stack ?? error.message);
14055
+ });
13553
14056
  function shutdown() {
13554
14057
  relay?.stop();
13555
14058
  manager.stopAll();