friend-assistant 0.1.36 → 0.1.37

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/friend.mjs CHANGED
@@ -3031,7 +3031,7 @@ function sanitizeSpotify(raw) {
3031
3031
  }
3032
3032
  function sanitizeChrome(raw) {
3033
3033
  const r = raw && typeof raw === "object" ? raw : {};
3034
- return { installed: r.installed === true || r.installed === void 0 && r.enabled === true, enabled: r.enabled === true };
3034
+ return { installed: r.installed === true || r.installed === void 0 && r.enabled === true, enabled: r.enabled === true, remote: r.remote === true };
3035
3035
  }
3036
3036
  function sanitizeAudius(raw) {
3037
3037
  const r = raw && typeof raw === "object" ? raw : {};
@@ -3626,7 +3626,7 @@ function changeChrome(chrome, change, helper) {
3626
3626
  return null;
3627
3627
  }
3628
3628
  if ("remove" in change) {
3629
- Object.assign(chrome, { installed: false, enabled: false });
3629
+ Object.assign(chrome, { installed: false, enabled: false, remote: false });
3630
3630
  return null;
3631
3631
  }
3632
3632
  if (!chrome.installed) return `${META.chrome.name} is not installed yet.`;
@@ -3684,13 +3684,13 @@ function safeRelative(file) {
3684
3684
  function scan(dir) {
3685
3685
  let files = 0;
3686
3686
  let bytes = 0;
3687
- const walk = (d) => {
3687
+ const walk2 = (d) => {
3688
3688
  for (const entry of readdirSync(d)) {
3689
3689
  const full = join3(d, entry);
3690
3690
  const st = lstatSync(full);
3691
3691
  if (st.isSymbolicLink()) return `The plugin contains a link (${entry}), which is not allowed.`;
3692
3692
  if (st.isDirectory()) {
3693
- const err2 = walk(full);
3693
+ const err2 = walk2(full);
3694
3694
  if (err2) return err2;
3695
3695
  } else if (st.isFile()) {
3696
3696
  files++;
@@ -3703,7 +3703,7 @@ function scan(dir) {
3703
3703
  }
3704
3704
  return null;
3705
3705
  };
3706
- const err = walk(dir);
3706
+ const err = walk2(dir);
3707
3707
  return err ?? { files, bytes };
3708
3708
  }
3709
3709
  function readInside(dir, file, limit) {
@@ -4574,6 +4574,7 @@ var ChromePlugin = class {
4574
4574
  error = null;
4575
4575
  extension = "unknown";
4576
4576
  asking = null;
4577
+ serving = null;
4577
4578
  status() {
4578
4579
  const found = chromeInstalled(this.deps.home);
4579
4580
  const connector = this.deps.hub.list().find((c) => c.id === ID) ?? null;
@@ -4634,6 +4635,20 @@ var ChromePlugin = class {
4634
4635
  })();
4635
4636
  return this.asking;
4636
4637
  }
4638
+ /**
4639
+ * Starts Chrome control's own MCP server in the background (the one other PCs reach through Friend's /chrome/mcp). It is the
4640
+ * program's own "start": it does nothing when the server is already running, and it keeps running after Friend stops.
4641
+ */
4642
+ startServer() {
4643
+ const entry = this.deps.bundled;
4644
+ if (!entry) return Promise.resolve();
4645
+ if (this.serving) return this.serving;
4646
+ this.serving = this.deps.run(process.execPath, [entry, "start"]).then(() => {
4647
+ }).finally(() => {
4648
+ this.serving = null;
4649
+ });
4650
+ return this.serving;
4651
+ }
4637
4652
  /** Switches the connector off but keeps it listed. */
4638
4653
  async disconnect() {
4639
4654
  if (!this.deps.hub.list().some((c) => c.id === ID)) return;
@@ -4648,16 +4663,204 @@ var ChromePlugin = class {
4648
4663
  }
4649
4664
  };
4650
4665
 
4666
+ // ../server/src/connectors/chromeRemote.ts
4667
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
4668
+ import { createHash as createHash3, timingSafeEqual } from "node:crypto";
4669
+ import { request } from "node:http";
4670
+ import { homedir as homedir3 } from "node:os";
4671
+ import { dirname as dirname3, join as join8, resolve as resolve3 } from "node:path";
4672
+ import { WebSocket } from "ws";
4673
+ function chromeToken(home = homedir3()) {
4674
+ try {
4675
+ const t = readFileSync4(join8(home, ".chrome-control-mcp", "token"), "utf8").trim();
4676
+ return t || null;
4677
+ } catch {
4678
+ return null;
4679
+ }
4680
+ }
4681
+ function sameKey(given, real2) {
4682
+ if (!given || !real2) return false;
4683
+ return timingSafeEqual(createHash3("sha256").update(given).digest(), createHash3("sha256").update(real2).digest());
4684
+ }
4685
+ function keyFromRequest(headers, search) {
4686
+ const bearer = /^Bearer (.+)$/i.exec(headers.authorization ?? "")?.[1];
4687
+ return bearer ?? new URLSearchParams(search).get("token");
4688
+ }
4689
+ function bundledExtensionDir(bundledIndex) {
4690
+ if (!bundledIndex) return null;
4691
+ const dir = resolve3(dirname3(bundledIndex), "..", "extension");
4692
+ return existsSync7(join8(dir, "manifest.json")) ? dir : null;
4693
+ }
4694
+ function chromeAddresses(origin) {
4695
+ const url = new URL(origin);
4696
+ const wsScheme = url.protocol === "https:" ? "wss:" : "ws:";
4697
+ return { mcpUrl: `${url.origin}/chrome/mcp`, extensionAddress: `${wsScheme}//${url.host}/chrome/ws` };
4698
+ }
4699
+ var FORWARD_REQUEST = ["content-type", "accept", "mcp-session-id", "last-event-id", "mcp-protocol-version"];
4700
+ var FORWARD_RESPONSE = ["content-type", "mcp-session-id", "cache-control", "mcp-protocol-version"];
4701
+ function proxyMcp(req, res, body, up) {
4702
+ return new Promise((done) => {
4703
+ const headers = { authorization: `Bearer ${up.key}` };
4704
+ for (const h of FORWARD_REQUEST) {
4705
+ const v = req.headers[h];
4706
+ if (typeof v === "string") headers[h] = v;
4707
+ }
4708
+ if (body && body.length) headers["content-length"] = String(body.length);
4709
+ const out = request({ host: "127.0.0.1", port: up.port, path: "/mcp", method: req.method, headers }, (back) => {
4710
+ const h = {};
4711
+ for (const name of FORWARD_RESPONSE) {
4712
+ const v = back.headers[name];
4713
+ if (typeof v === "string") h[name] = v;
4714
+ }
4715
+ res.writeHead(back.statusCode ?? 502, h);
4716
+ back.pipe(res);
4717
+ back.on("end", () => done(true));
4718
+ back.on("error", () => {
4719
+ res.destroy();
4720
+ done(true);
4721
+ });
4722
+ });
4723
+ out.on("error", () => {
4724
+ if (res.headersSent) {
4725
+ res.destroy();
4726
+ return done(true);
4727
+ }
4728
+ done(false);
4729
+ });
4730
+ res.on("close", () => out.destroy());
4731
+ if (body && body.length) out.write(body);
4732
+ out.end();
4733
+ });
4734
+ }
4735
+ var sendable = (code) => code >= 1e3 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1e3;
4736
+ function relayExtension(client, up) {
4737
+ const upstream = new WebSocket(`ws://127.0.0.1:${up.port}/${up.search}`, { ...up.origin ? { origin: up.origin } : {}, maxPayload: up.maxPayload });
4738
+ const waiting = [];
4739
+ client.on("message", (data, binary) => {
4740
+ const buf = Buffer.isBuffer(data) ? data : Buffer.concat(Array.isArray(data) ? data : [Buffer.from(data)]);
4741
+ if (upstream.readyState === WebSocket.OPEN) upstream.send(buf, { binary });
4742
+ else if (waiting.length < 100) waiting.push({ data: buf, binary });
4743
+ });
4744
+ upstream.on("open", () => {
4745
+ for (const m of waiting.splice(0)) upstream.send(m.data, { binary: m.binary });
4746
+ });
4747
+ upstream.on("message", (data, binary) => {
4748
+ if (client.readyState === WebSocket.OPEN) client.send(data, { binary });
4749
+ });
4750
+ upstream.on("close", (code, reason) => {
4751
+ if (client.readyState === WebSocket.OPEN || client.readyState === WebSocket.CONNECTING) client.close(sendable(code), reason.toString().slice(0, 100));
4752
+ });
4753
+ upstream.on("error", () => {
4754
+ if (client.readyState === WebSocket.OPEN) client.close(1013, "Chrome control is not reachable on this PC");
4755
+ });
4756
+ upstream.on("unexpected-response", () => {
4757
+ if (client.readyState === WebSocket.OPEN) client.close(1013, "Chrome control refused the connection");
4758
+ });
4759
+ client.on("close", (code) => {
4760
+ if (upstream.readyState === WebSocket.OPEN) upstream.close(sendable(code));
4761
+ else if (upstream.readyState === WebSocket.CONNECTING) upstream.terminate();
4762
+ });
4763
+ client.on("error", () => upstream.terminate());
4764
+ }
4765
+
4766
+ // ../server/src/zip.ts
4767
+ import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync } from "node:fs";
4768
+ import { join as join9 } from "node:path";
4769
+ import { deflateRawSync } from "node:zlib";
4770
+ var TABLE = (() => {
4771
+ const t = new Uint32Array(256);
4772
+ for (let n = 0; n < 256; n++) {
4773
+ let c = n;
4774
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
4775
+ t[n] = c >>> 0;
4776
+ }
4777
+ return t;
4778
+ })();
4779
+ function crc32(data) {
4780
+ let c = 4294967295;
4781
+ for (const b of data) c = TABLE[(c ^ b) & 255] ^ c >>> 8;
4782
+ return (c ^ 4294967295) >>> 0;
4783
+ }
4784
+ var SKIP = /* @__PURE__ */ new Set(["node_modules", ".git"]);
4785
+ var MAX_FILES2 = 500;
4786
+ var MAX_BYTES = 2e7;
4787
+ function walk(dir, prefix, out) {
4788
+ for (const e of readdirSync2(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
4789
+ if (SKIP.has(e.name)) continue;
4790
+ const path2 = join9(dir, e.name);
4791
+ if (e.isDirectory()) walk(path2, `${prefix}${e.name}/`, out);
4792
+ else if (e.isFile()) out.push({ name: `${prefix}${e.name}`, path: path2 });
4793
+ }
4794
+ }
4795
+ function zipDirectory(dir, folder) {
4796
+ const files = [];
4797
+ walk(dir, `${folder}/`, files);
4798
+ if (files.length > MAX_FILES2) throw new Error("That folder has too many files to zip.");
4799
+ const parts = [];
4800
+ const central = [];
4801
+ let offset = 0;
4802
+ let total = 0;
4803
+ const time = 0;
4804
+ const date = 2020 - 1980 << 9 | 1 << 5 | 1;
4805
+ for (const f of files) {
4806
+ const data = readFileSync5(f.path);
4807
+ total += data.length;
4808
+ if (total > MAX_BYTES || statSync(f.path).size > MAX_BYTES) throw new Error("That folder is too big to zip.");
4809
+ const packed = deflateRawSync(data);
4810
+ const useDeflate = packed.length < data.length;
4811
+ const body = useDeflate ? packed : data;
4812
+ const method = useDeflate ? 8 : 0;
4813
+ const name = Buffer.from(f.name, "utf8");
4814
+ const crc = crc32(data);
4815
+ const local = Buffer.alloc(30);
4816
+ local.writeUInt32LE(67324752, 0);
4817
+ local.writeUInt16LE(20, 4);
4818
+ local.writeUInt16LE(2048, 6);
4819
+ local.writeUInt16LE(method, 8);
4820
+ local.writeUInt16LE(time, 10);
4821
+ local.writeUInt16LE(date, 12);
4822
+ local.writeUInt32LE(crc, 14);
4823
+ local.writeUInt32LE(body.length, 18);
4824
+ local.writeUInt32LE(data.length, 22);
4825
+ local.writeUInt16LE(name.length, 26);
4826
+ local.writeUInt16LE(0, 28);
4827
+ parts.push(local, name, body);
4828
+ const entry = Buffer.alloc(46);
4829
+ entry.writeUInt32LE(33639248, 0);
4830
+ entry.writeUInt16LE(20, 4);
4831
+ entry.writeUInt16LE(20, 6);
4832
+ entry.writeUInt16LE(2048, 8);
4833
+ entry.writeUInt16LE(method, 10);
4834
+ entry.writeUInt16LE(time, 12);
4835
+ entry.writeUInt16LE(date, 14);
4836
+ entry.writeUInt32LE(crc, 16);
4837
+ entry.writeUInt32LE(body.length, 20);
4838
+ entry.writeUInt32LE(data.length, 24);
4839
+ entry.writeUInt16LE(name.length, 28);
4840
+ entry.writeUInt32LE(offset, 42);
4841
+ central.push(entry, name);
4842
+ offset += local.length + name.length + body.length;
4843
+ }
4844
+ const centralBuf = Buffer.concat(central);
4845
+ const end = Buffer.alloc(22);
4846
+ end.writeUInt32LE(101010256, 0);
4847
+ end.writeUInt16LE(files.length, 8);
4848
+ end.writeUInt16LE(files.length, 10);
4849
+ end.writeUInt32LE(centralBuf.length, 12);
4850
+ end.writeUInt32LE(offset, 16);
4851
+ return Buffer.concat([...parts, centralBuf, end]);
4852
+ }
4853
+
4651
4854
  // ../server/src/connectors/run.ts
4652
4855
  import crossSpawn2 from "cross-spawn";
4653
4856
  var LIMIT_MS = 5 * 6e4;
4654
- var runCommand = (cmd, args, opts) => new Promise((resolve12) => {
4857
+ var runCommand = (cmd, args, opts) => new Promise((resolve13) => {
4655
4858
  let stdout = "";
4656
4859
  let child;
4657
4860
  try {
4658
4861
  child = crossSpawn2(cmd, args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
4659
4862
  } catch (e) {
4660
- resolve12({ code: 127, stdout: e.message });
4863
+ resolve13({ code: 127, stdout: e.message });
4661
4864
  return;
4662
4865
  }
4663
4866
  const timer = setTimeout(() => child.kill(), LIMIT_MS);
@@ -4672,11 +4875,11 @@ var runCommand = (cmd, args, opts) => new Promise((resolve12) => {
4672
4875
  child.stderr?.on("data", feed);
4673
4876
  child.on("error", (e) => {
4674
4877
  clearTimeout(timer);
4675
- resolve12({ code: 127, stdout: stdout + e.message });
4878
+ resolve13({ code: 127, stdout: stdout + e.message });
4676
4879
  });
4677
4880
  child.on("close", (code) => {
4678
4881
  clearTimeout(timer);
4679
- resolve12({ code: code ?? 1, stdout });
4882
+ resolve13({ code: code ?? 1, stdout });
4680
4883
  });
4681
4884
  });
4682
4885
 
@@ -4684,7 +4887,7 @@ var runCommand = (cmd, args, opts) => new Promise((resolve12) => {
4684
4887
  import { randomUUID as randomUUID2 } from "node:crypto";
4685
4888
 
4686
4889
  // ../server/src/auth.ts
4687
- import { createHash as createHash3, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
4890
+ import { createHash as createHash4, randomBytes, scrypt, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
4688
4891
 
4689
4892
  // ../server/src/ratelimit.ts
4690
4893
  var LockoutError = class extends Error {
@@ -4738,7 +4941,7 @@ var RateLimiter = class {
4738
4941
  var SESSION_TTL_MS = 7 * 24 * 3600 * 1e3;
4739
4942
  var LOGIN_TRIES = 3;
4740
4943
  var PAIR_TTL_MS = 5 * 60 * 1e3;
4741
- var sha256 = (s) => createHash3("sha256").update(s).digest("hex");
4944
+ var sha256 = (s) => createHash4("sha256").update(s).digest("hex");
4742
4945
  function scryptAsync(secret, salt) {
4743
4946
  return new Promise(
4744
4947
  (res, rej) => scrypt(secret, salt, 64, { N: 16384, r: 8, p: 1 }, (err, key) => err ? rej(err) : res(key))
@@ -4754,7 +4957,7 @@ async function verifySecret(secret, stored) {
4754
4957
  if (alg !== "scrypt" || !saltHex || !keyHex) return false;
4755
4958
  const expected = Buffer.from(keyHex, "hex");
4756
4959
  const actual = await scryptAsync(secret, Buffer.from(saltHex, "hex"));
4757
- return expected.length === actual.length && timingSafeEqual(expected, actual);
4960
+ return expected.length === actual.length && timingSafeEqual2(expected, actual);
4758
4961
  }
4759
4962
  var Auth = class _Auth {
4760
4963
  constructor(db, audit, clock2 = Date.now) {
@@ -4936,9 +5139,9 @@ var Approvals = class {
4936
5139
  needsPin: req.needsPin
4937
5140
  };
4938
5141
  this.deps.db.prepare("insert into approvals (id, tool, summary, tier) values (?, ?, ?, ?)").run(id2, info.tool, info.summary, info.tier);
4939
- return new Promise((resolve12) => {
5142
+ return new Promise((resolve13) => {
4940
5143
  const timer = setTimeout(() => this.finish(id2, { approved: false, reason: "Approval timed out" }, "timeout"), this.timeoutMs);
4941
- this.entries.set(id2, { info, req, emit, resolve: resolve12, timer });
5144
+ this.entries.set(id2, { info, req, emit, resolve: resolve13, timer });
4942
5145
  emit({ type: "approval.request", ...info });
4943
5146
  });
4944
5147
  }
@@ -5062,7 +5265,7 @@ var CameraBroker = class {
5062
5265
  if (this.pending) return Promise.resolve({ ok: false, error: `The ${this.what} is already in use.` });
5063
5266
  if (signal.aborted) return Promise.resolve({ ok: false, error: `The ${this.what} request was cancelled.` });
5064
5267
  const id2 = randomUUID3();
5065
- return new Promise((resolve12) => {
5268
+ return new Promise((resolve13) => {
5066
5269
  let done = false;
5067
5270
  const timer = setTimeout(() => finish2({ ok: false, error: `The ${this.what} did not answer in time.` }), this.timeoutMs);
5068
5271
  const onAbort = () => {
@@ -5075,7 +5278,7 @@ var CameraBroker = class {
5075
5278
  clearTimeout(timer);
5076
5279
  signal.removeEventListener("abort", onAbort);
5077
5280
  if (this.pending?.id === id2) this.pending = null;
5078
- resolve12(r);
5281
+ resolve13(r);
5079
5282
  };
5080
5283
  signal.addEventListener("abort", onAbort, { once: true });
5081
5284
  this.pending = { id: id2, emit, finish: finish2 };
@@ -5110,7 +5313,7 @@ var CameraBroker = class {
5110
5313
  // ../server/src/media.ts
5111
5314
  import { randomBytes as randomBytes2 } from "node:crypto";
5112
5315
  import { promises as fs } from "node:fs";
5113
- import { basename, extname, isAbsolute, relative as relative2, resolve as resolve3, sep } from "node:path";
5316
+ import { basename, extname, isAbsolute, relative as relative2, resolve as resolve4, sep } from "node:path";
5114
5317
  var IMAGE = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", bmp: "image/bmp", avif: "image/avif", svg: "image/svg+xml" };
5115
5318
  var VIDEO = { mp4: "video/mp4", m4v: "video/mp4", webm: "video/webm", mov: "video/quicktime", ogv: "video/ogg", mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", m4a: "audio/mp4", flac: "audio/flac" };
5116
5319
  var MARKDOWN = /* @__PURE__ */ new Set(["md", "markdown", "mdx"]);
@@ -5223,7 +5426,7 @@ var MediaStore = class {
5223
5426
  if (!isAbsolute(rawPath)) return { ok: false, error: "Give the full path of the file, for example D:\\Pictures\\photo.png." };
5224
5427
  let real2;
5225
5428
  try {
5226
- real2 = await fs.realpath(resolve3(rawPath));
5429
+ real2 = await fs.realpath(resolve4(rawPath));
5227
5430
  } catch {
5228
5431
  return { ok: false, error: "That file does not exist." };
5229
5432
  }
@@ -5243,7 +5446,7 @@ var MediaStore = class {
5243
5446
  if (!isAbsolute(rawPath)) return { ok: false, error: "Give the full path of the file, for example D:\\Pictures\\photo.png." };
5244
5447
  let real2;
5245
5448
  try {
5246
- real2 = await fs.realpath(resolve3(rawPath));
5449
+ real2 = await fs.realpath(resolve4(rawPath));
5247
5450
  } catch {
5248
5451
  return { ok: false, error: "That file does not exist." };
5249
5452
  }
@@ -5301,7 +5504,7 @@ var MediaStore = class {
5301
5504
 
5302
5505
  // ../server/src/channels/hub.ts
5303
5506
  import { promises as fsp } from "node:fs";
5304
- import { createHmac, randomBytes as randomBytes3, randomInt, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
5507
+ import { createHmac, randomBytes as randomBytes3, randomInt, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
5305
5508
  var CHANNEL_LABEL = { telegram: "Telegram", sms: "SMS", whatsapp: "WhatsApp" };
5306
5509
  var VoiceMessageError = class extends Error {
5307
5510
  };
@@ -5616,7 +5819,7 @@ var ChannelHub = class _ChannelHub {
5616
5819
  }
5617
5820
  const a = Buffer.from(code.toUpperCase());
5618
5821
  const b = Buffer.from(l.code);
5619
- if (a.length === b.length && timingSafeEqual2(a, b)) {
5822
+ if (a.length === b.length && timingSafeEqual3(a, b)) {
5620
5823
  this.setOwnerChat(chat);
5621
5824
  this.link = null;
5622
5825
  this.deps.audit.log("owner", "channel.telegram_linked", {});
@@ -5772,7 +5975,7 @@ ${reply}` : reply);
5772
5975
  if (!w.installed || !w.enabled || !w.authToken) return "off";
5773
5976
  const expected = Buffer.from(_ChannelHub.twilioSignature(w.authToken, url, params));
5774
5977
  const given = Buffer.from(signature ?? "");
5775
- if (expected.length !== given.length || !timingSafeEqual2(expected, given)) {
5978
+ if (expected.length !== given.length || !timingSafeEqual3(expected, given)) {
5776
5979
  this.deps.audit.log("system", "channel.twilio_refused", {});
5777
5980
  return "forbidden";
5778
5981
  }
@@ -6020,8 +6223,8 @@ var AlexaEngine = class {
6020
6223
  let timer;
6021
6224
  const waited = await Promise.race([
6022
6225
  work,
6023
- new Promise((resolve12) => {
6024
- timer = setTimeout(() => resolve12("late"), ms(this.d.budgetMs, 6500));
6226
+ new Promise((resolve13) => {
6227
+ timer = setTimeout(() => resolve13("late"), ms(this.d.budgetMs, 6500));
6025
6228
  })
6026
6229
  ]);
6027
6230
  clearTimeout(timer);
@@ -6757,9 +6960,9 @@ var AudiusHub = class {
6757
6960
  };
6758
6961
 
6759
6962
  // ../server/src/music/oauth.ts
6760
- import { createHash as createHash4, randomBytes as randomBytes4 } from "node:crypto";
6761
- import { chmodSync as chmodSync3, existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync4, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
6762
- import { join as join8 } from "node:path";
6963
+ import { createHash as createHash5, randomBytes as randomBytes4 } from "node:crypto";
6964
+ import { chmodSync as chmodSync3, existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync6, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
6965
+ import { join as join10 } from "node:path";
6763
6966
  var STATE_TTL_MS = 10 * 6e4;
6764
6967
  var MAX_STATES = 20;
6765
6968
  var REFRESH_AHEAD_MS = 6e4;
@@ -6767,7 +6970,7 @@ var TRANSIENT_WAIT_MS = 3e4;
6767
6970
  var RefreshRejected = class extends Error {
6768
6971
  };
6769
6972
  var b64url = (b) => b.toString("base64url");
6770
- var challengeOf = (verifier) => b64url(createHash4("sha256").update(verifier).digest());
6973
+ var challengeOf = (verifier) => b64url(createHash5("sha256").update(verifier).digest());
6771
6974
  function pkcePair(random = randomBytes4) {
6772
6975
  const verifier = b64url(random(48));
6773
6976
  return { verifier, challenge: challengeOf(verifier) };
@@ -6803,7 +7006,7 @@ var MusicTokens = class {
6803
7006
  reconnect = /* @__PURE__ */ new Set();
6804
7007
  generations = /* @__PURE__ */ new Map();
6805
7008
  file(source) {
6806
- return join8(this.dir, `music-${source}.tokens.json`);
7009
+ return join10(this.dir, `music-${source}.tokens.json`);
6807
7010
  }
6808
7011
  save(source, login) {
6809
7012
  mkdirSync5(this.dir, { recursive: true });
@@ -6817,9 +7020,9 @@ var MusicTokens = class {
6817
7020
  }
6818
7021
  load(source) {
6819
7022
  const file = this.file(source);
6820
- if (!existsSync7(file)) return null;
7023
+ if (!existsSync8(file)) return null;
6821
7024
  try {
6822
- const j = JSON.parse(readFileSync4(file, "utf8"));
7025
+ const j = JSON.parse(readFileSync6(file, "utf8"));
6823
7026
  if (typeof j.accessToken !== "string" || typeof j.refreshToken !== "string" || typeof j.expiresAt !== "number" || typeof j.account !== "string") return null;
6824
7027
  return { accessToken: j.accessToken, refreshToken: j.refreshToken, expiresAt: j.expiresAt, account: j.account, premium: typeof j.premium === "boolean" ? j.premium : null };
6825
7028
  } catch {
@@ -6849,7 +7052,7 @@ var MusicSecrets = class {
6849
7052
  }
6850
7053
  dir;
6851
7054
  file(source) {
6852
- return join8(this.dir, `music-${source}.secret.json`);
7055
+ return join10(this.dir, `music-${source}.secret.json`);
6853
7056
  }
6854
7057
  set(source, secret) {
6855
7058
  mkdirSync5(this.dir, { recursive: true });
@@ -6863,7 +7066,7 @@ var MusicSecrets = class {
6863
7066
  /** For the service's own token call only. */
6864
7067
  get(source) {
6865
7068
  try {
6866
- const j = JSON.parse(readFileSync4(this.file(source), "utf8"));
7069
+ const j = JSON.parse(readFileSync6(this.file(source), "utf8"));
6867
7070
  return typeof j.secret === "string" ? j.secret : "";
6868
7071
  } catch {
6869
7072
  return "";
@@ -7437,16 +7640,16 @@ var HostPlayer = class {
7437
7640
  };
7438
7641
 
7439
7642
  // ../server/src/music/library.ts
7440
- import { createHash as createHash5 } from "node:crypto";
7643
+ import { createHash as createHash6 } from "node:crypto";
7441
7644
  import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
7442
- import { basename as basename2, extname as extname2, join as join9, sep as sep2 } from "node:path";
7645
+ import { basename as basename2, extname as extname2, join as join11, sep as sep2 } from "node:path";
7443
7646
  import { parseFile } from "music-metadata";
7444
7647
  var MAX_PAGE = 500;
7445
7648
  var MAX_COVER_BYTES = 3 * 1024 * 1024;
7446
7649
  var TAG_WORKERS = 6;
7447
7650
  var COVER_NAMES = ["folder", "cover", "front", "album"];
7448
7651
  var COVER_EXT = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png" };
7449
- var idOf = (rel) => createHash5("sha1").update(rel.split(sep2).join("/")).digest("hex").slice(0, 16);
7652
+ var idOf = (rel) => createHash6("sha1").update(rel.split(sep2).join("/")).digest("hex").slice(0, 16);
7450
7653
  var publicOf = ({ rel: _rel, coverFile: _c, embedded: _e, ...rest }) => rest;
7451
7654
  var MusicLibrary = class {
7452
7655
  constructor(o) {
@@ -7494,7 +7697,7 @@ var MusicLibrary = class {
7494
7697
  const depthLimit = this.o.scanDepth();
7495
7698
  const found = [];
7496
7699
  let truncated = false;
7497
- const walk = async (dir, rel, depth) => {
7700
+ const walk2 = async (dir, rel, depth) => {
7498
7701
  if (truncated) return;
7499
7702
  let entries;
7500
7703
  try {
@@ -7514,7 +7717,7 @@ var MusicLibrary = class {
7514
7717
  if (e.name.startsWith(".") || e.isSymbolicLink()) continue;
7515
7718
  const childRel = rel ? `${rel}${sep2}${e.name}` : e.name;
7516
7719
  if (e.isDirectory()) {
7517
- if (depth < depthLimit) await walk(join9(dir, e.name), childRel, depth + 1);
7720
+ if (depth < depthLimit) await walk2(join11(dir, e.name), childRel, depth + 1);
7518
7721
  } else if (e.isFile() && allowed.has(extname2(e.name).slice(1).toLowerCase())) {
7519
7722
  if (found.length >= max) {
7520
7723
  truncated = true;
@@ -7524,7 +7727,7 @@ var MusicLibrary = class {
7524
7727
  }
7525
7728
  }
7526
7729
  };
7527
- await walk(root, "", 0);
7730
+ await walk2(root, "", 0);
7528
7731
  const tracks = new Array(found.length);
7529
7732
  let next = 0;
7530
7733
  const worker = async () => {
@@ -7546,7 +7749,7 @@ var MusicLibrary = class {
7546
7749
  const name = basename2(rel);
7547
7750
  const ext = extname2(name).slice(1).toLowerCase();
7548
7751
  const stem = name.slice(0, name.length - extname2(name).length);
7549
- const parent = rel.includes(sep2) ? basename2(join9(rel, "..")) : "";
7752
+ const parent = rel.includes(sep2) ? basename2(join11(rel, "..")) : "";
7550
7753
  let title2 = "";
7551
7754
  let artist = "";
7552
7755
  let album = "";
@@ -7554,7 +7757,7 @@ var MusicLibrary = class {
7554
7757
  let durationSec = null;
7555
7758
  let embedded = false;
7556
7759
  try {
7557
- const m = await parseFile(join9(root, rel));
7760
+ const m = await parseFile(join11(root, rel));
7558
7761
  title2 = m.common.title?.trim() ?? "";
7559
7762
  artist = (m.common.artist ?? m.common.albumartist ?? "").trim();
7560
7763
  album = m.common.album?.trim() ?? "";
@@ -7597,7 +7800,7 @@ var MusicLibrary = class {
7597
7800
  if (!t || !this.root) return null;
7598
7801
  const allowed = this.o.extensions().map((e) => e.toLowerCase().replace(/^\./, ""));
7599
7802
  if (!allowed.includes(t.ext)) return null;
7600
- return this.inside(join9(this.root, t.rel));
7803
+ return this.inside(join11(this.root, t.rel));
7601
7804
  }
7602
7805
  async inside(path2) {
7603
7806
  try {
@@ -7615,7 +7818,7 @@ var MusicLibrary = class {
7615
7818
  const t = this.tracks.find((x) => x.id === id2);
7616
7819
  if (!t || !this.root) return null;
7617
7820
  if (t.coverFile) {
7618
- const path2 = await this.inside(join9(this.root, t.coverFile));
7821
+ const path2 = await this.inside(join11(this.root, t.coverFile));
7619
7822
  if (path2) {
7620
7823
  try {
7621
7824
  if ((await stat(path2)).size <= MAX_COVER_BYTES) return { mime: COVER_EXT[extname2(path2).slice(1).toLowerCase()], data: await readFile(path2) };
@@ -7624,7 +7827,7 @@ var MusicLibrary = class {
7624
7827
  }
7625
7828
  }
7626
7829
  if (t.embedded) {
7627
- const path2 = await this.inside(join9(this.root, t.rel));
7830
+ const path2 = await this.inside(join11(this.root, t.rel));
7628
7831
  if (path2) {
7629
7832
  try {
7630
7833
  const pic = (await parseFile(path2)).common.picture?.[0];
@@ -7639,7 +7842,7 @@ var MusicLibrary = class {
7639
7842
 
7640
7843
  // ../server/src/music/mpv.ts
7641
7844
  import { spawn as nodeSpawn } from "node:child_process";
7642
- import { existsSync as existsSync8, rmSync as rmSync4 } from "node:fs";
7845
+ import { existsSync as existsSync9, rmSync as rmSync4 } from "node:fs";
7643
7846
  import net from "node:net";
7644
7847
  import { tmpdir } from "node:os";
7645
7848
  import path from "node:path";
@@ -7650,20 +7853,20 @@ var INSTALL = {
7650
7853
  };
7651
7854
  var installFor = (p) => p === "win32" ? INSTALL.win32 : p === "darwin" ? INSTALL.darwin : INSTALL.other;
7652
7855
  function defaultRun(cmd, args) {
7653
- return new Promise((resolve12) => {
7856
+ return new Promise((resolve13) => {
7654
7857
  let out = "";
7655
7858
  let done = false;
7656
7859
  const finish2 = (code) => {
7657
7860
  if (done) return;
7658
7861
  done = true;
7659
7862
  clearTimeout(timer);
7660
- resolve12({ code, out });
7863
+ resolve13({ code, out });
7661
7864
  };
7662
7865
  let child;
7663
7866
  try {
7664
7867
  child = nodeSpawn(cmd, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
7665
7868
  } catch {
7666
- return resolve12({ code: -1, out: "" });
7869
+ return resolve13({ code: -1, out: "" });
7667
7870
  }
7668
7871
  const timer = setTimeout(() => {
7669
7872
  child.kill();
@@ -7692,7 +7895,7 @@ function places(platform, env) {
7692
7895
  async function findMpv(d) {
7693
7896
  const platform = d.platform ?? process.platform;
7694
7897
  const env = d.env ?? process.env;
7695
- const exists2 = d.exists ?? existsSync8;
7898
+ const exists2 = d.exists ?? existsSync9;
7696
7899
  const run2 = d.run ?? defaultRun;
7697
7900
  const versionOf = async (p) => {
7698
7901
  const r = await run2(p, ["--version"]);
@@ -7774,12 +7977,12 @@ var Mpv = class {
7774
7977
  const deadline = Date.now() + (this.d.connectTimeoutMs ?? 5e3);
7775
7978
  let sock = null;
7776
7979
  while (!sock && !died && Date.now() < deadline) {
7777
- sock = await new Promise((resolve12) => {
7980
+ sock = await new Promise((resolve13) => {
7778
7981
  const s = net.connect(pipe);
7779
- s.once("connect", () => resolve12(s));
7982
+ s.once("connect", () => resolve13(s));
7780
7983
  s.once("error", () => {
7781
7984
  s.destroy();
7782
- setTimeout(() => resolve12(null), 50);
7985
+ setTimeout(() => resolve13(null), 50);
7783
7986
  });
7784
7987
  });
7785
7988
  }
@@ -7844,12 +8047,12 @@ var Mpv = class {
7844
8047
  const sock = this.sock;
7845
8048
  if (!sock) return Promise.reject(new Error("mpv is not running."));
7846
8049
  const id2 = this.nextId++;
7847
- return new Promise((resolve12, reject) => {
8050
+ return new Promise((resolve13, reject) => {
7848
8051
  const timer = setTimeout(() => {
7849
8052
  this.pending.delete(id2);
7850
8053
  reject(new Error("mpv did not answer."));
7851
8054
  }, this.d.requestTimeoutMs ?? 5e3);
7852
- this.pending.set(id2, { resolve: resolve12, reject, timer });
8055
+ this.pending.set(id2, { resolve: resolve13, reject, timer });
7853
8056
  sock.write(`${JSON.stringify({ command, request_id: id2 })}
7854
8057
  `, (err) => {
7855
8058
  if (err) {
@@ -8523,8 +8726,8 @@ var ReportSchedules = class {
8523
8726
 
8524
8727
  // ../server/src/brokers/session.ts
8525
8728
  import { randomBytes as randomBytes5 } from "node:crypto";
8526
- import { chmodSync as chmodSync4, existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "node:fs";
8527
- import { join as join10 } from "node:path";
8729
+ import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync7, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "node:fs";
8730
+ import { join as join12 } from "node:path";
8528
8731
  var STATE_TTL_MS2 = 10 * 6e4;
8529
8732
  var MAX_STATES2 = 20;
8530
8733
  var BROKER_ID = /^[a-z0-9-]{1,40}$/;
@@ -8538,7 +8741,7 @@ var BrokerSessions = class {
8538
8741
  states = /* @__PURE__ */ new Map();
8539
8742
  file(broker) {
8540
8743
  if (!BROKER_ID.test(broker)) throw new Error("That is not a broker id.");
8541
- return join10(this.dir, `broker-${broker}.session.json`);
8744
+ return join12(this.dir, `broker-${broker}.session.json`);
8542
8745
  }
8543
8746
  save(broker, info) {
8544
8747
  const file = this.file(broker);
@@ -8553,9 +8756,9 @@ var BrokerSessions = class {
8553
8756
  load(broker) {
8554
8757
  if (!BROKER_ID.test(broker)) return null;
8555
8758
  const file = this.file(broker);
8556
- if (!existsSync9(file)) return null;
8759
+ if (!existsSync10(file)) return null;
8557
8760
  try {
8558
- const raw = JSON.parse(readFileSync5(file, "utf8"));
8761
+ const raw = JSON.parse(readFileSync7(file, "utf8"));
8559
8762
  if (typeof raw.accessToken !== "string" || typeof raw.expiresAt !== "number") return null;
8560
8763
  if (raw.expiresAt <= this.clock()) {
8561
8764
  this.clear(broker);
@@ -8588,7 +8791,7 @@ var BrokerSessions = class {
8588
8791
  };
8589
8792
 
8590
8793
  // ../server/src/brokers/zerodha.ts
8591
- import { createHash as createHash6 } from "node:crypto";
8794
+ import { createHash as createHash7 } from "node:crypto";
8592
8795
  var API4 = "https://api.kite.trade";
8593
8796
  var LOGIN = "https://kite.zerodha.com/connect/login";
8594
8797
  var SIX_IST_UTC_MS = 30 * 6e4;
@@ -8650,7 +8853,7 @@ function createZerodha(opts) {
8650
8853
  complete: async (params) => {
8651
8854
  const requestToken = params.request_token;
8652
8855
  if (!requestToken) throw new BrokerError("Zerodha did not send a login code.", "auth");
8653
- const checksum = createHash6("sha256").update(`${opts.apiKey}${requestToken}${opts.apiSecret}`).digest("hex");
8856
+ const checksum = createHash7("sha256").update(`${opts.apiKey}${requestToken}${opts.apiSecret}`).digest("hex");
8654
8857
  let res;
8655
8858
  try {
8656
8859
  res = await f(`${API4}/session/token`, {
@@ -8893,7 +9096,7 @@ import { spawn } from "node:child_process";
8893
9096
  import { randomUUID as randomUUID4 } from "node:crypto";
8894
9097
  import { chmodSync as chmodSync5, mkdtempSync as mkdtempSync2, rmSync as rmSync6, writeFileSync as writeFileSync6 } from "node:fs";
8895
9098
  import { tmpdir as tmpdir2 } from "node:os";
8896
- import { join as join11 } from "node:path";
9099
+ import { join as join13 } from "node:path";
8897
9100
  var MAX_CODE_CHARS = 5e4;
8898
9101
  var MAX_OUTPUT_CHARS = 2e4;
8899
9102
  var MAX_EXTRA_FILES = 10;
@@ -8905,7 +9108,7 @@ var SETUP = {
8905
9108
  node: { image: "node:22-alpine", file: "main.js", command: ["node"] },
8906
9109
  shell: { image: "alpine:3.20", file: "main.sh", command: ["sh"] }
8907
9110
  };
8908
- var spawnDocker = (args, { timeoutMs }) => new Promise((resolve12, reject) => {
9111
+ var spawnDocker = (args, { timeoutMs }) => new Promise((resolve13, reject) => {
8909
9112
  const name = args[args.indexOf("--name") + 1];
8910
9113
  const child = spawn("docker", args, { windowsHide: true });
8911
9114
  const cap = MAX_OUTPUT_CHARS * 2;
@@ -8931,8 +9134,8 @@ var spawnDocker = (args, { timeoutMs }) => new Promise((resolve12, reject) => {
8931
9134
  });
8932
9135
  child.on("close", (code) => {
8933
9136
  clearTimeout(timer);
8934
- if (timedOut) void remove().then(() => resolve12({ code, stdout, stderr, timedOut }));
8935
- else resolve12({ code, stdout, stderr, timedOut });
9137
+ if (timedOut) void remove().then(() => resolve13({ code, stdout, stderr, timedOut }));
9138
+ else resolve13({ code, stdout, stderr, timedOut });
8936
9139
  });
8937
9140
  });
8938
9141
  var clip3 = (s) => s.length > MAX_OUTPUT_CHARS ? `${s.slice(0, MAX_OUTPUT_CHARS)}
@@ -8953,15 +9156,15 @@ var CodeBox = class {
8953
9156
  if (extra.reduce((sum, [, body]) => sum + body.length, 0) > MAX_EXTRA_FILE_CHARS) return { ok: false, error: "The sandbox files are too large." };
8954
9157
  const setup = SETUP[input.language];
8955
9158
  const timeoutMs = input.timeoutSec && input.timeoutSec > 0 ? Math.min(input.timeoutSec * 1e3, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
8956
- const dir = mkdtempSync2(join11(tmpdir2(), "friend-code-"));
9159
+ const dir = mkdtempSync2(join13(tmpdir2(), "friend-code-"));
8957
9160
  try {
8958
- const file = join11(dir, setup.file);
9161
+ const file = join13(dir, setup.file);
8959
9162
  writeFileSync6(file, input.code);
8960
9163
  chmodSync5(dir, 493);
8961
9164
  chmodSync5(file, 420);
8962
9165
  for (const [name, body] of extra) {
8963
- writeFileSync6(join11(dir, name), body);
8964
- chmodSync5(join11(dir, name), 420);
9166
+ writeFileSync6(join13(dir, name), body);
9167
+ chmodSync5(join13(dir, name), 420);
8965
9168
  }
8966
9169
  const args = [
8967
9170
  "run",
@@ -9094,14 +9297,14 @@ var Memory = class {
9094
9297
  };
9095
9298
 
9096
9299
  // ../server/src/app.ts
9097
- import { dirname as dirname4, extname as extname3, resolve as resolve4 } from "node:path";
9300
+ import { dirname as dirname5, extname as extname3, resolve as resolve5 } from "node:path";
9098
9301
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9099
- import { join as join15 } from "node:path";
9302
+ import { join as join17 } from "node:path";
9100
9303
 
9101
9304
  // ../server/src/db.ts
9102
9305
  import Database from "better-sqlite3";
9103
9306
  import { mkdirSync as mkdirSync7 } from "node:fs";
9104
- import { join as join12 } from "node:path";
9307
+ import { join as join14 } from "node:path";
9105
9308
 
9106
9309
  // ../server/src/migrations.ts
9107
9310
  var MIGRATIONS = [
@@ -9289,7 +9492,7 @@ create table report_schedules (
9289
9492
  // ../server/src/db.ts
9290
9493
  function openDb(dataDir) {
9291
9494
  mkdirSync7(dataDir, { recursive: true });
9292
- const db = new Database(join12(dataDir, "friend.db"));
9495
+ const db = new Database(join14(dataDir, "friend.db"));
9293
9496
  db.pragma("journal_mode = WAL");
9294
9497
  db.pragma("foreign_keys = ON");
9295
9498
  db.exec("create table if not exists schema_version (id integer primary key, applied_at integer not null)");
@@ -9372,12 +9575,12 @@ var DeviceHub = class {
9372
9575
  }
9373
9576
  const [deviceId, { ws }] = entry;
9374
9577
  const id2 = randomUUID5();
9375
- return new Promise((resolve12) => {
9578
+ return new Promise((resolve13) => {
9376
9579
  const timer = setTimeout(() => {
9377
9580
  this.pending.delete(id2);
9378
- resolve12({ ok: false, error: `device call timed out after ${timeoutMs} ms` });
9581
+ resolve13({ ok: false, error: `device call timed out after ${timeoutMs} ms` });
9379
9582
  }, timeoutMs);
9380
- this.pending.set(id2, { resolve: resolve12, timer, deviceId });
9583
+ this.pending.set(id2, { resolve: resolve13, timer, deviceId });
9381
9584
  ws.send(JSON.stringify({ type: "tool.exec", id: id2, tool, args, approvedOutside: opts.approvedOutside }));
9382
9585
  });
9383
9586
  }
@@ -9387,10 +9590,10 @@ var DeviceHub = class {
9387
9590
  import fastifyCookie from "@fastify/cookie";
9388
9591
  import fastifyStatic from "@fastify/static";
9389
9592
  import Fastify from "fastify";
9390
- import { createReadStream, existsSync as existsSync10, promises as fsp2 } from "node:fs";
9593
+ import { createReadStream, existsSync as existsSync11, promises as fsp2 } from "node:fs";
9391
9594
  import { isIP as isIP2 } from "node:net";
9392
9595
  import { Readable } from "node:stream";
9393
- import { WebSocket, WebSocketServer } from "ws";
9596
+ import { WebSocket as WebSocket2, WebSocketServer } from "ws";
9394
9597
  import { z as z10 } from "zod";
9395
9598
 
9396
9599
  // ../server/src/http-error.ts
@@ -9440,6 +9643,11 @@ var SlidingWindow = class {
9440
9643
  size() {
9441
9644
  return this.hits.size;
9442
9645
  }
9646
+ /** Whether the key is out of hits right now, without using one. */
9647
+ full(key) {
9648
+ const now = this.clock();
9649
+ return (this.hits.get(key) ?? []).filter((t) => now - t < this.windowMs).length >= this.max;
9650
+ }
9443
9651
  prune(now) {
9444
9652
  for (const [key, times] of this.hits) {
9445
9653
  if (times.every((t) => now - t >= this.windowMs)) this.hits.delete(key);
@@ -10034,6 +10242,71 @@ function createGateway(deps) {
10034
10242
  return pluginError(reply, e, "remove");
10035
10243
  }
10036
10244
  });
10245
+ const chromeFailures = new SlidingWindow(20, 6e4);
10246
+ const chromeWss = new WebSocketServer({ noServer: true, maxPayload: MAX_DEVICE_FRAME_BYTES });
10247
+ if (deps.chrome) {
10248
+ const chrome = deps.chrome;
10249
+ const refuse2 = (ip, what) => {
10250
+ chromeFailures.allow(ip);
10251
+ audit.log("anonymous", "chrome.remote_refused", { ip, what });
10252
+ };
10253
+ const originOf = (req) => config.publicUrl ? new URL(config.publicUrl).origin : `${req.protocol}://${req.headers.host ?? "127.0.0.1"}`;
10254
+ app.register(async (scope) => {
10255
+ for (const type of ["application/json", "*"]) scope.addContentTypeParser(type, { parseAs: "buffer" }, (_req, body, done) => done(null, body));
10256
+ scope.route({
10257
+ method: ["GET", "POST", "DELETE"],
10258
+ url: "/chrome/mcp",
10259
+ handler: async (req, reply) => {
10260
+ if (!chrome.enabled()) return reply.code(404).send({ error: "Not found" });
10261
+ if (req.headers.origin) return reply.code(403).send({ error: "Forbidden origin" });
10262
+ if (chromeFailures.full(req.ip)) return reply.code(429).header("retry-after", 30).send({ error: "Too many wrong keys. Wait a minute." });
10263
+ const key = chrome.token();
10264
+ if (!sameKey(keyFromRequest(req.headers, new URL(req.raw.url ?? "/", "http://x").search), key)) {
10265
+ refuse2(req.ip, "mcp");
10266
+ return reply.code(401).send({ error: "Unauthorized" });
10267
+ }
10268
+ const body = Buffer.isBuffer(req.body) ? req.body : void 0;
10269
+ reply.hijack();
10270
+ const send = () => proxyMcp(req.raw, reply.raw, body, { port: chrome.ports().http, key });
10271
+ let answered = await send();
10272
+ if (!answered) {
10273
+ await chrome.ensureServer().catch(() => {
10274
+ });
10275
+ answered = await send();
10276
+ }
10277
+ if (!answered && !reply.raw.headersSent) {
10278
+ reply.raw.writeHead(502, { "content-type": "application/json" });
10279
+ reply.raw.end(JSON.stringify({ error: "Chrome control is not running on this PC (its MCP server is not answering). Switch the plugin off and on again." }));
10280
+ }
10281
+ }
10282
+ });
10283
+ });
10284
+ app.get("/api/plugins/chrome/access", { onRequest: pluginGuard }, async (req) => ({ ...chrome.access(originOf(req)) }));
10285
+ app.post("/api/plugins/chrome/remote", { onRequest: pluginGuard }, async (req, reply) => {
10286
+ const body = z10.object({ enabled: z10.boolean(), pin: z10.string().min(1).max(32).optional() }).safeParse(req.body);
10287
+ if (!body.success) return reply.code(400).send({ error: "Invalid input" });
10288
+ try {
10289
+ await chrome.setRemote(body.data.enabled, body.data.pin, req.ip);
10290
+ return { ok: true };
10291
+ } catch (e) {
10292
+ return pluginError(reply, e, "chrome.remote");
10293
+ }
10294
+ });
10295
+ app.post("/api/plugins/chrome/token", { onRequest: pluginGuard }, async (req, reply) => {
10296
+ const body = z10.object({ pin: z10.string().min(1).max(32) }).safeParse(req.body);
10297
+ if (!body.success) return reply.code(400).send({ error: "Enter your PIN" });
10298
+ try {
10299
+ return reply.header("cache-control", "no-store").send({ token: await chrome.revealToken(body.data.pin, req.ip) });
10300
+ } catch (e) {
10301
+ return pluginError(reply, e, "chrome.token");
10302
+ }
10303
+ });
10304
+ app.get("/api/plugins/chrome/extension.zip", { onRequest: pluginGuard }, async (_req, reply) => {
10305
+ const zip = chrome.extensionZip();
10306
+ if (!zip) return reply.code(404).send({ error: "This Friend does not carry the Chrome extension." });
10307
+ return reply.header("content-disposition", 'attachment; filename="friend-chrome-extension.zip"').type("application/zip").send(zip);
10308
+ });
10309
+ }
10037
10310
  const connectorWindow = new SlidingWindow(30, 6e4);
10038
10311
  const connectorGuard = async (req, reply) => {
10039
10312
  const token = req.cookies[COOKIE_NAME];
@@ -10261,7 +10534,7 @@ function createGateway(deps) {
10261
10534
  deps.onLock?.();
10262
10535
  return { ok: true };
10263
10536
  });
10264
- if (deps.webDir && existsSync10(deps.webDir)) {
10537
+ if (deps.webDir && existsSync11(deps.webDir)) {
10265
10538
  app.register(fastifyStatic, { root: deps.webDir });
10266
10539
  app.setNotFoundHandler((req, reply) => {
10267
10540
  if (req.method === "GET" && !req.url.startsWith("/api")) return reply.sendFile("index.html");
@@ -10298,7 +10571,7 @@ function createGateway(deps) {
10298
10571
  const params = new URL(req.url ?? "/", "http://localhost").searchParams;
10299
10572
  const tab = (params.get("tab") ?? "").slice(0, 64);
10300
10573
  if (tab) {
10301
- if (activeOwner && activeOwner.ws.readyState === WebSocket.OPEN) {
10574
+ if (activeOwner && activeOwner.ws.readyState === WebSocket2.OPEN) {
10302
10575
  if (params.get("takeover") !== "1" && activeOwner.tab !== tab) return ws.close(4409, "in use elsewhere");
10303
10576
  activeOwner.ws.close(4410, "replaced");
10304
10577
  }
@@ -10311,7 +10584,7 @@ function createGateway(deps) {
10311
10584
  const conn = {
10312
10585
  ip: clientIp(req),
10313
10586
  send: (m) => {
10314
- if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m));
10587
+ if (ws.readyState === WebSocket2.OPEN) ws.send(JSON.stringify(m));
10315
10588
  },
10316
10589
  close: (code, reason) => ws.close(code, reason)
10317
10590
  };
@@ -10346,8 +10619,44 @@ function createGateway(deps) {
10346
10619
  }
10347
10620
  deps.onDeviceConnect(device, ws);
10348
10621
  }
10622
+ const handleChromeUpgrade = (req, socket, head) => {
10623
+ const chrome = deps.chrome;
10624
+ const answer = (status2) => {
10625
+ socket.write(`HTTP/1.1 ${status2}\r
10626
+ Connection: close\r
10627
+ \r
10628
+ `);
10629
+ socket.destroy();
10630
+ };
10631
+ if (!chrome || !chrome.enabled()) return answer("404 Not Found");
10632
+ const ip = clientIp(req);
10633
+ if (chromeFailures.full(ip)) return answer("429 Too Many Requests");
10634
+ const search = new URL(req.url ?? "/", "http://x").search;
10635
+ const params = new URLSearchParams(search);
10636
+ if (!sameKey(params.get("token"), chrome.token())) {
10637
+ chromeFailures.allow(ip);
10638
+ audit.log("anonymous", "chrome.remote_refused", { ip, what: "ws" });
10639
+ return answer("401 Unauthorized");
10640
+ }
10641
+ const origin = req.headers.origin;
10642
+ const peer = params.get("role") === "peer";
10643
+ if (peer ? !!origin : !origin || !origin.startsWith("chrome-extension://")) return answer("403 Forbidden");
10644
+ chromeWss.handleUpgrade(req, socket, head, (ws) => {
10645
+ ws.on("error", () => {
10646
+ });
10647
+ relayExtension(ws, { port: chrome.ports().ws, search, origin, maxPayload: MAX_DEVICE_FRAME_BYTES });
10648
+ });
10649
+ };
10349
10650
  app.server.on("upgrade", (req, socket, head) => {
10350
10651
  const path2 = (req.url ?? "").split("?")[0];
10652
+ if (path2 === "/chrome/ws") {
10653
+ if (!hostAllowed(req.headers.host)) {
10654
+ audit.log("anonymous", "host.refused", { host: String(req.headers.host).slice(0, 100) });
10655
+ socket.write("HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\n\r\n");
10656
+ return socket.destroy();
10657
+ }
10658
+ return handleChromeUpgrade(req, socket, head);
10659
+ }
10351
10660
  if (path2 !== "/ws" && path2 !== "/device") return socket.destroy();
10352
10661
  if (!hostAllowed(req.headers.host)) {
10353
10662
  audit.log("anonymous", "host.refused", { host: String(req.headers.host).slice(0, 100) });
@@ -10369,9 +10678,10 @@ function createGateway(deps) {
10369
10678
  return { port: typeof addr === "object" && addr ? addr.port : config.port };
10370
10679
  },
10371
10680
  async close() {
10372
- for (const c of [...wss.clients, ...deviceWss.clients]) c.terminate();
10681
+ for (const c of [...wss.clients, ...deviceWss.clients, ...chromeWss.clients]) c.terminate();
10373
10682
  wss.close();
10374
10683
  deviceWss.close();
10684
+ chromeWss.close();
10375
10685
  await app.close();
10376
10686
  }
10377
10687
  };
@@ -10497,15 +10807,15 @@ var ClaudeProvider = class {
10497
10807
  };
10498
10808
 
10499
10809
  // ../server/src/provider/claude-code/provider.ts
10500
- import { createHash as createHash7 } from "node:crypto";
10501
- import { chmodSync as chmodSync6, existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync6, rmSync as rmSync7, writeFileSync as writeFileSync7 } from "node:fs";
10502
- import { join as join13 } from "node:path";
10810
+ import { createHash as createHash8 } from "node:crypto";
10811
+ import { chmodSync as chmodSync6, existsSync as existsSync12, mkdirSync as mkdirSync8, readFileSync as readFileSync8, rmSync as rmSync7, writeFileSync as writeFileSync7 } from "node:fs";
10812
+ import { join as join15 } from "node:path";
10503
10813
 
10504
10814
  // ../server/src/provider/claude-code/bridge.ts
10505
10815
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10506
10816
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10507
10817
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
10508
- import { randomBytes as randomBytes6, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
10818
+ import { randomBytes as randomBytes6, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
10509
10819
  import { createServer } from "node:http";
10510
10820
  var encodeToolName = (name) => name.replaceAll(".", "__");
10511
10821
  var MAX_BODY_BYTES = 8 * 1024 * 1024;
@@ -10528,7 +10838,7 @@ var ToolBridge = class {
10528
10838
  }
10529
10839
  async start() {
10530
10840
  this.http = createServer((req, res) => void this.handle(req, res));
10531
- await new Promise((resolve12) => this.http.listen(0, "127.0.0.1", resolve12));
10841
+ await new Promise((resolve13) => this.http.listen(0, "127.0.0.1", resolve13));
10532
10842
  this.port = this.http.address().port;
10533
10843
  }
10534
10844
  async stop() {
@@ -10537,7 +10847,7 @@ var ToolBridge = class {
10537
10847
  this.http = null;
10538
10848
  if (!h) return;
10539
10849
  h.closeAllConnections();
10540
- await new Promise((resolve12) => h.close(() => resolve12()));
10850
+ await new Promise((resolve13) => h.close(() => resolve13()));
10541
10851
  }
10542
10852
  /** Answers every call that is still waiting with an error, so Claude is never left hanging. */
10543
10853
  failPending(reason) {
@@ -10548,7 +10858,7 @@ var ToolBridge = class {
10548
10858
  if (!header2.startsWith("Bearer ")) return false;
10549
10859
  const given = Buffer.from(header2.slice(7));
10550
10860
  const wanted = Buffer.from(this.token);
10551
- return given.length === wanted.length && timingSafeEqual3(given, wanted);
10861
+ return given.length === wanted.length && timingSafeEqual4(given, wanted);
10552
10862
  }
10553
10863
  async handle(req, res) {
10554
10864
  if (!this.authorized(req)) {
@@ -10584,20 +10894,20 @@ var ToolBridge = class {
10584
10894
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
10585
10895
  tools: this.tools.map((t) => ({ name: encodeToolName(t.name), description: t.description, inputSchema: t.inputSchema }))
10586
10896
  }));
10587
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
10588
- const known = this.tools.find((t) => encodeToolName(t.name) === request.params.name);
10589
- if (!known) return { isError: true, content: [{ type: "text", text: `Unknown tool: ${request.params.name}` }] };
10590
- const answer = await new Promise((resolve12) => {
10897
+ server.setRequestHandler(CallToolRequestSchema, async (request2) => {
10898
+ const known = this.tools.find((t) => encodeToolName(t.name) === request2.params.name);
10899
+ if (!known) return { isError: true, content: [{ type: "text", text: `Unknown tool: ${request2.params.name}` }] };
10900
+ const answer = await new Promise((resolve13) => {
10591
10901
  const id2 = `cc-${++this.seq}`;
10592
10902
  let done = false;
10593
10903
  const respond2 = (a) => {
10594
10904
  if (done) return;
10595
10905
  done = true;
10596
10906
  this.pending.delete(id2);
10597
- resolve12(a);
10907
+ resolve13(a);
10598
10908
  };
10599
10909
  this.pending.set(id2, respond2);
10600
- this.onCall({ id: id2, name: known.name, args: request.params.arguments ?? {}, respond: respond2 });
10910
+ this.onCall({ id: id2, name: known.name, args: request2.params.arguments ?? {}, respond: respond2 });
10601
10911
  });
10602
10912
  return {
10603
10913
  ...answer.isError ? { isError: true } : {},
@@ -10611,7 +10921,7 @@ var ToolBridge = class {
10611
10921
  }
10612
10922
  };
10613
10923
  function readBody(req) {
10614
- return new Promise((resolve12, reject) => {
10924
+ return new Promise((resolve13, reject) => {
10615
10925
  const parts = [];
10616
10926
  let size = 0;
10617
10927
  req.on("data", (d) => {
@@ -10623,7 +10933,7 @@ function readBody(req) {
10623
10933
  }
10624
10934
  parts.push(d);
10625
10935
  });
10626
- req.on("end", () => resolve12(Buffer.concat(parts).toString("utf8")));
10936
+ req.on("end", () => resolve13(Buffer.concat(parts).toString("utf8")));
10627
10937
  req.on("error", reject);
10628
10938
  });
10629
10939
  }
@@ -10676,14 +10986,14 @@ var ClaudeProc = class {
10676
10986
  constructor(opts, emit) {
10677
10987
  this.emit = emit;
10678
10988
  this.child = spawn2(opts.command, opts.args, { cwd: opts.cwd, env: opts.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
10679
- this.exited = new Promise((resolve12) => {
10989
+ this.exited = new Promise((resolve13) => {
10680
10990
  let finished = false;
10681
10991
  const finish2 = (code, notInstalled) => {
10682
10992
  if (finished) return;
10683
10993
  finished = true;
10684
10994
  this.alive = false;
10685
10995
  this.emit({ kind: "exit", code, stderr: this.stderr, notInstalled });
10686
- resolve12();
10996
+ resolve13();
10687
10997
  };
10688
10998
  this.child.on("error", (e) => finish2(null, e.code === "ENOENT"));
10689
10999
  this.child.on("close", (code) => finish2(code, false));
@@ -10747,13 +11057,13 @@ var Inbox = class {
10747
11057
  if (signal?.aborted) return Promise.resolve("abort");
10748
11058
  const first2 = this.items.shift();
10749
11059
  if (first2) return Promise.resolve(first2);
10750
- return new Promise((resolve12) => {
11060
+ return new Promise((resolve13) => {
10751
11061
  let timer;
10752
11062
  const finish2 = (v) => {
10753
11063
  if (timer) clearTimeout(timer);
10754
11064
  signal?.removeEventListener("abort", onAbort);
10755
11065
  this.waiter = null;
10756
- resolve12(v);
11066
+ resolve13(v);
10757
11067
  };
10758
11068
  const onAbort = () => finish2("abort");
10759
11069
  this.waiter = (i) => finish2(i);
@@ -10778,13 +11088,13 @@ var newConv = (guest) => ({
10778
11088
  gotEvent: false,
10779
11089
  draining: null
10780
11090
  });
10781
- var toolsKeyOf = (tools) => createHash7("sha1").update(JSON.stringify(tools)).digest("hex");
11091
+ var toolsKeyOf = (tools) => createHash8("sha1").update(JSON.stringify(tools)).digest("hex");
10782
11092
  var writtenByClaude = (m) => m.role === "assistant" && m.content.every((b) => b.type !== "tool_use" || b.id.startsWith("cc-"));
10783
11093
  var NOT_SIGNED_IN = /not logged in|please run \/login|invalid api key|authentication[_ ]error|oauth token|sign in/i;
10784
11094
  var ClaudeCodeProvider = class {
10785
11095
  constructor(opts) {
10786
11096
  this.opts = opts;
10787
- this.home = join13(opts.dataDir, "claude");
11097
+ this.home = join15(opts.dataDir, "claude");
10788
11098
  this.now = opts.now ?? Date.now;
10789
11099
  this.bridge = new ToolBridge((call) => this.owner.inbox.push({ kind: "call", call }));
10790
11100
  }
@@ -11014,7 +11324,7 @@ ${item.stderr}`;
11014
11324
  "local",
11015
11325
  "--system-prompt",
11016
11326
  req.system,
11017
- ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join13(this.home, "mcp.json"), "--allowedTools", req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`).join(","), ...resume ? ["--resume", resume] : []]
11327
+ ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join15(this.home, "mcp.json"), "--allowedTools", req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`).join(","), ...resume ? ["--resume", resume] : []]
11018
11328
  ];
11019
11329
  const proc = new ClaudeProc(
11020
11330
  {
@@ -11045,7 +11355,7 @@ ${item.stderr}`;
11045
11355
  startBridge() {
11046
11356
  this.bridgeReady ??= (async () => {
11047
11357
  await this.bridge.start();
11048
- const file = join13(this.home, "mcp.json");
11358
+ const file = join15(this.home, "mcp.json");
11049
11359
  writeFileSync7(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
11050
11360
  try {
11051
11361
  chmodSync6(file, 384);
@@ -11055,10 +11365,10 @@ ${item.stderr}`;
11055
11365
  return this.bridgeReady;
11056
11366
  }
11057
11367
  // ---- the session id, kept so a restart of Friend can pick the conversation up again ----
11058
- sessionFile = () => join13(this.home, "session-id");
11368
+ sessionFile = () => join15(this.home, "session-id");
11059
11369
  readSession() {
11060
11370
  try {
11061
- return existsSync11(this.sessionFile()) ? readFileSync6(this.sessionFile(), "utf8").trim() || null : null;
11371
+ return existsSync12(this.sessionFile()) ? readFileSync8(this.sessionFile(), "utf8").trim() || null : null;
11062
11372
  } catch {
11063
11373
  return null;
11064
11374
  }
@@ -11199,7 +11509,7 @@ var SwitchableProvider = class {
11199
11509
 
11200
11510
  // ../server/src/settings.ts
11201
11511
  import { z as z11 } from "zod";
11202
- import { statSync } from "node:fs";
11512
+ import { statSync as statSync2 } from "node:fs";
11203
11513
  var word = /^[\w.:/\\-]+$/;
11204
11514
  var modelName = z11.string().trim().min(1).max(100).regex(/^[A-Za-z0-9][\w.:/-]*$/, "A model name has no spaces");
11205
11515
  var SettingsPatch = z11.object({
@@ -11415,7 +11725,7 @@ function applySettings(config, raw) {
11415
11725
  if (p.music?.folder) {
11416
11726
  let isDir = false;
11417
11727
  try {
11418
- isDir = statSync(p.music.folder).isDirectory();
11728
+ isDir = statSync2(p.music.folder).isDirectory();
11419
11729
  } catch {
11420
11730
  isDir = false;
11421
11731
  }
@@ -11913,10 +12223,10 @@ function dbWidgetStore(db) {
11913
12223
  }
11914
12224
 
11915
12225
  // ../server/src/tls.ts
11916
- import { chmodSync as chmodSync7, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync8 } from "node:fs";
12226
+ import { chmodSync as chmodSync7, existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "node:fs";
11917
12227
  import { networkInterfaces } from "node:os";
11918
12228
  import { isIP as isIP3 } from "node:net";
11919
- import { join as join14 } from "node:path";
12229
+ import { join as join16 } from "node:path";
11920
12230
  import { generate } from "selfsigned";
11921
12231
  var DAYS = 825;
11922
12232
  var RENEW_BEFORE_MS = 30 * 24 * 36e5;
@@ -11931,16 +12241,16 @@ function tlsHosts(extra = [], ifaces) {
11931
12241
  return [.../* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", ...lanAddresses(ifaces), ...extra.map((h) => h.toLowerCase()).filter(Boolean)])];
11932
12242
  }
11933
12243
  async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
11934
- const dir = join14(dataDir, "tls");
11935
- const keyFile = join14(dir, "key.pem");
11936
- const certFile = join14(dir, "cert.pem");
11937
- const metaFile = join14(dir, "meta.json");
12244
+ const dir = join16(dataDir, "tls");
12245
+ const keyFile = join16(dir, "key.pem");
12246
+ const certFile = join16(dir, "cert.pem");
12247
+ const metaFile = join16(dir, "meta.json");
11938
12248
  const hosts = tlsHosts(extraHosts, ifaces);
11939
- if (existsSync12(keyFile) && existsSync12(certFile) && existsSync12(metaFile)) {
12249
+ if (existsSync13(keyFile) && existsSync13(certFile) && existsSync13(metaFile)) {
11940
12250
  try {
11941
- const meta = JSON.parse(readFileSync7(metaFile, "utf8"));
12251
+ const meta = JSON.parse(readFileSync9(metaFile, "utf8"));
11942
12252
  const covered = hosts.every((h) => meta.hosts.includes(h));
11943
- if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync7(keyFile, "utf8"), cert: readFileSync7(certFile, "utf8") };
12253
+ if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync9(keyFile, "utf8"), cert: readFileSync9(certFile, "utf8") };
11944
12254
  } catch {
11945
12255
  }
11946
12256
  }
@@ -12030,18 +12340,18 @@ var Challenges = class {
12030
12340
 
12031
12341
  // ../server/src/voice/crypto.ts
12032
12342
  import { createCipheriv, createDecipheriv, randomBytes as randomBytes7 } from "node:crypto";
12033
- import { chmodSync as chmodSync8, existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, writeFileSync as writeFileSync9 } from "node:fs";
12034
- import { dirname as dirname3 } from "node:path";
12343
+ import { chmodSync as chmodSync8, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync10, writeFileSync as writeFileSync9 } from "node:fs";
12344
+ import { dirname as dirname4 } from "node:path";
12035
12345
  var KEY_BYTES = 32;
12036
12346
  var IV_BYTES = 12;
12037
12347
  var TAG_BYTES = 16;
12038
12348
  function loadOrCreateKey(path2) {
12039
- if (existsSync13(path2)) {
12040
- const key2 = readFileSync8(path2);
12349
+ if (existsSync14(path2)) {
12350
+ const key2 = readFileSync10(path2);
12041
12351
  if (key2.length !== KEY_BYTES) throw new Error(`invalid voice key file (expected ${KEY_BYTES} bytes): ${path2}`);
12042
12352
  return key2;
12043
12353
  }
12044
- mkdirSync10(dirname3(path2), { recursive: true });
12354
+ mkdirSync10(dirname4(path2), { recursive: true });
12045
12355
  const key = randomBytes7(KEY_BYTES);
12046
12356
  writeFileSync9(path2, key, { mode: 384 });
12047
12357
  try {
@@ -12613,7 +12923,7 @@ async function createApp(opts) {
12613
12923
  });
12614
12924
  const memory = new Memory(db);
12615
12925
  const tasks = new Tasks(db);
12616
- const plugins = new Plugins(db, join15(opts.dataDir, "plugins"));
12926
+ const plugins = new Plugins(db, join17(opts.dataDir, "plugins"));
12617
12927
  const hub = new McpHub(new ConnectorStore(opts.dataDir));
12618
12928
  const chromeBundled = opts.quick?.bundled !== void 0 ? opts.quick.bundled : bundledChromeControl();
12619
12929
  const chromePlugin = new ChromePlugin({ hub, run: opts.quick?.run ?? runCommand, home: opts.quick?.home, bundled: chromeBundled });
@@ -12705,7 +13015,7 @@ async function createApp(opts) {
12705
13015
  }
12706
13016
  if (id2 !== "zerodha") return changeChannels((c) => changeIntegration(c, id2, change));
12707
13017
  const err = changeBrokers((b) => changeBroker(b, id2, change, (gone) => brokerHub.forget(gone)));
12708
- if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join15(catalogDir, PORTFOLIO_SKILL));
13018
+ if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join17(catalogDir, PORTFOLIO_SKILL));
12709
13019
  if (!err && "remove" in change) plugins.remove(PORTFOLIO_SKILL);
12710
13020
  return err;
12711
13021
  };
@@ -12721,7 +13031,7 @@ async function createApp(opts) {
12721
13031
  },
12722
13032
  install: (id2) => {
12723
13033
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) return { ok: false, error: "That plugin is not in the catalog." };
12724
- return plugins.install(join15(catalogDir, id2));
13034
+ return plugins.install(join17(catalogDir, id2));
12725
13035
  }
12726
13036
  },
12727
13037
  integrations: {
@@ -12921,7 +13231,7 @@ async function createApp(opts) {
12921
13231
  const voice2 = opts.voice;
12922
13232
  const speaker = voice2 ? new Speaker(voice2, audit, () => config.voice.ttsVoice, () => ({ hindi: config.voice.hindiVoice || void 0, marathi: config.voice.marathiVoice || void 0 })) : null;
12923
13233
  const voiceAvailable = () => !!voice2 && voice2.available();
12924
- const voiceKey = voice2 ? loadOrCreateKey(join15(opts.dataDir, "voice.key")) : null;
13234
+ const voiceKey = voice2 ? loadOrCreateKey(join17(opts.dataDir, "voice.key")) : null;
12925
13235
  const voiceprint = voiceKey ? new Voiceprint(db, voiceKey) : null;
12926
13236
  const enrollment = voiceprint ? new Enrollment(voiceprint, SPEAKER_MODEL) : null;
12927
13237
  const household = voiceKey ? new Household(db, voiceKey) : null;
@@ -13038,8 +13348,8 @@ async function createApp(opts) {
13038
13348
  broadcast({ type: "voice.heard", text: held.text, trust: "owner" });
13039
13349
  await runVoiceTurn(held.text, conn.ip, epoch);
13040
13350
  }
13041
- const here2 = dirname4(fileURLToPath2(import.meta.url));
13042
- const catalogDir = opts.pluginCatalogDir ?? firstExistingDir([process.env.FRIEND_PLUGIN_CATALOG, resolve4(here2, "plugins"), resolve4(here2, "../../..", "plugins")]) ?? resolve4(here2, "plugins");
13351
+ const here2 = dirname5(fileURLToPath2(import.meta.url));
13352
+ const catalogDir = opts.pluginCatalogDir ?? firstExistingDir([process.env.FRIEND_PLUGIN_CATALOG, resolve5(here2, "plugins"), resolve5(here2, "../../..", "plugins")]) ?? resolve5(here2, "plugins");
13043
13353
  const pluginsApi = {
13044
13354
  list: () => {
13045
13355
  void chromePlugin.refresh();
@@ -13058,7 +13368,7 @@ async function createApp(opts) {
13058
13368
  if (!isPluginId(id2)) throw new HttpError(400, "That is not a plugin name.");
13059
13369
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) throw new HttpError(404, "That plugin is not in the catalog.");
13060
13370
  await requirePin(pin, ip);
13061
- const r = plugins.install(join15(catalogDir, id2));
13371
+ const r = plugins.install(join17(catalogDir, id2));
13062
13372
  if (!r.ok) throw new HttpError(400, `That plugin cannot be installed: ${r.error}`);
13063
13373
  audit.log("owner", "plugin.installed", { id: r.id, upgraded: r.upgraded, ip });
13064
13374
  return { id: r.id, upgraded: r.upgraded };
@@ -13156,10 +13466,44 @@ async function createApp(opts) {
13156
13466
  }
13157
13467
  }
13158
13468
  };
13469
+ const chromeRemoteApi = {
13470
+ enabled: () => config.chrome.installed && config.chrome.remote,
13471
+ token: () => chromeToken(opts.quick?.home),
13472
+ ports: () => ({ http: opts.chromeRemote?.httpPort ?? Number(process.env.CHROME_BRIDGE_HTTP_PORT ?? 8766), ws: opts.chromeRemote?.wsPort ?? Number(process.env.CHROME_BRIDGE_PORT ?? 8765) }),
13473
+ ensureServer: () => opts.chromeRemote?.startServer ? opts.chromeRemote.startServer() : chromePlugin.startServer(),
13474
+ extensionZip: () => {
13475
+ const dir = bundledExtensionDir(chromeBundled);
13476
+ return dir ? zipDirectory(dir, "friend-chrome-extension") : null;
13477
+ },
13478
+ access: (origin) => ({ remote: config.chrome.installed && config.chrome.remote, ...chromeAddresses(origin), extensionZip: bundledExtensionDir(chromeBundled) ? "/api/plugins/chrome/extension.zip" : null }),
13479
+ setRemote: async (enabled, pin, ip) => {
13480
+ if (enabled) {
13481
+ if (!pin) throw new HttpError(400, "Enter your PIN to allow Chrome control from other PCs.");
13482
+ await requirePin(pin, ip);
13483
+ if (!config.chrome.installed) throw new HttpError(400, "Chrome control is not installed yet. Install it first.");
13484
+ }
13485
+ const err = changeChromeConfig((c) => {
13486
+ c.remote = enabled;
13487
+ return null;
13488
+ });
13489
+ if (err) throw new HttpError(400, err);
13490
+ audit.log("owner", enabled ? "chrome.remote_on" : "chrome.remote_off", { ip });
13491
+ if (enabled) void chromeRemoteApi.ensureServer().catch(() => {
13492
+ });
13493
+ },
13494
+ revealToken: async (pin, ip) => {
13495
+ await requirePin(pin, ip);
13496
+ const key = chromeToken(opts.quick?.home);
13497
+ if (!key) throw new HttpError(400, "Chrome control is not set up yet, so it has no key.");
13498
+ audit.log("owner", "chrome.token_shown", { ip });
13499
+ return key;
13500
+ }
13501
+ };
13159
13502
  const tls = config.https ? await ensureTlsCert(opts.dataDir, [...config.allowedHosts, ...config.publicUrl ? [new URL(config.publicUrl).hostname] : []]) : void 0;
13160
13503
  const gateway = createGateway({
13161
13504
  ...tls ? { tls } : {},
13162
13505
  connectors: connectorsApi,
13506
+ chrome: chromeRemoteApi,
13163
13507
  voicePreview: async (id2) => {
13164
13508
  if (!voice2 || !voiceAvailable()) throw new HttpError(503, "Voice is not available. Run: friend voice setup");
13165
13509
  const indian = [...HINDI_VOICES, ...MARATHI_VOICES].some((v) => v.id === id2) || id2 === config.voice.hindiVoice || id2 === config.voice.marathiVoice;
@@ -13695,6 +14039,8 @@ ${url}`);
13695
14039
  }
13696
14040
  hub.startAll({ except: config.chrome.enabled ? ["chrome"] : [] });
13697
14041
  if (config.chrome.enabled) void chromePlugin.connect();
14042
+ if (config.chrome.installed && config.chrome.remote) void chromeRemoteApi.ensureServer().catch(() => {
14043
+ });
13698
14044
  channelHub.apply();
13699
14045
  brokerTimer = setInterval(() => void brokerHub.tick(/* @__PURE__ */ new Date()).catch(() => {
13700
14046
  }), opts.brokerTickMs ?? 6e4);
@@ -13760,7 +14106,7 @@ var SidecarProcess = class {
13760
14106
  return this.launch();
13761
14107
  }
13762
14108
  launch() {
13763
- return new Promise((resolve12, reject) => {
14109
+ return new Promise((resolve13, reject) => {
13764
14110
  let settled = false;
13765
14111
  const fail = (message) => {
13766
14112
  if (settled) return;
@@ -13794,7 +14140,7 @@ var SidecarProcess = class {
13794
14140
  this.ready = true;
13795
14141
  clearTimeout(timer);
13796
14142
  settled = true;
13797
- resolve12();
14143
+ resolve13();
13798
14144
  }
13799
14145
  } catch {
13800
14146
  }
@@ -13836,11 +14182,11 @@ var SidecarProcess = class {
13836
14182
  this.restartTimer = null;
13837
14183
  const child = this.child;
13838
14184
  if (!child || child.exitCode !== null) return;
13839
- await new Promise((resolve12) => {
14185
+ await new Promise((resolve13) => {
13840
14186
  const kill = setTimeout(() => child.kill(), 3e3);
13841
14187
  child.once("exit", () => {
13842
14188
  clearTimeout(kill);
13843
- resolve12();
14189
+ resolve13();
13844
14190
  });
13845
14191
  child.stdin?.end();
13846
14192
  });
@@ -14040,18 +14386,18 @@ async function configCommand(args, io2) {
14040
14386
 
14041
14387
  // ../agent-cli/src/commands/node.ts
14042
14388
  import { hostname as hostname2 } from "node:os";
14043
- import { resolve as resolve8 } from "node:path";
14389
+ import { resolve as resolve9 } from "node:path";
14044
14390
 
14045
14391
  // ../agent-cli/src/node.ts
14046
- import { WebSocket as WebSocket2 } from "ws";
14392
+ import { WebSocket as WebSocket3 } from "ws";
14047
14393
 
14048
14394
  // ../agent-cli/src/tools/fs.ts
14049
- import { closeSync, mkdirSync as mkdirSync11, openSync, readSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync10 } from "node:fs";
14050
- import { dirname as dirname6, join as join16 } from "node:path";
14395
+ import { closeSync, mkdirSync as mkdirSync11, openSync, readSync, readdirSync as readdirSync3, statSync as statSync3, writeFileSync as writeFileSync10 } from "node:fs";
14396
+ import { dirname as dirname7, join as join18 } from "node:path";
14051
14397
 
14052
14398
  // ../agent-cli/src/tools/roots.ts
14053
14399
  import { lstatSync as lstatSync2, realpathSync } from "node:fs";
14054
- import { dirname as dirname5, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve5, sep as sep3 } from "node:path";
14400
+ import { dirname as dirname6, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve6, sep as sep3 } from "node:path";
14055
14401
  var isWin = process.platform === "win32";
14056
14402
  var norm = (p) => isWin ? p.toLowerCase() : p;
14057
14403
  var exists = (p) => {
@@ -14067,7 +14413,7 @@ function realish(abs) {
14067
14413
  let cur = abs;
14068
14414
  const tail2 = [];
14069
14415
  while (!exists(cur)) {
14070
- const parent = dirname5(cur);
14416
+ const parent = dirname6(cur);
14071
14417
  if (parent === cur) return abs;
14072
14418
  tail2.unshift(cur.slice(parent.length).replace(/^[\\/]+/, ""));
14073
14419
  cur = parent;
@@ -14078,7 +14424,7 @@ function realish(abs) {
14078
14424
  } catch {
14079
14425
  return UNRESOLVABLE + abs;
14080
14426
  }
14081
- return tail2.length ? resolve5(real2, ...tail2) : real2;
14427
+ return tail2.length ? resolve6(real2, ...tail2) : real2;
14082
14428
  }
14083
14429
  function within(root, target) {
14084
14430
  if (target.startsWith(UNRESOLVABLE)) return false;
@@ -14087,8 +14433,8 @@ function within(root, target) {
14087
14433
  }
14088
14434
  function resolveInRoots(p, roots) {
14089
14435
  const base = roots[0] ?? process.cwd();
14090
- const abs = realish(resolve5(base, p));
14091
- const inside = roots.some((r) => within(realish(resolve5(r)), abs));
14436
+ const abs = realish(resolve6(base, p));
14437
+ const inside = roots.some((r) => within(realish(resolve6(r)), abs));
14092
14438
  return { abs, inside };
14093
14439
  }
14094
14440
 
@@ -14104,12 +14450,12 @@ function fsList(args, ctx) {
14104
14450
  const g = guard(args.path, ctx);
14105
14451
  if ("error" in g) return { ok: false, error: g.error };
14106
14452
  try {
14107
- const entries = readdirSync2(g.abs, { withFileTypes: true });
14453
+ const entries = readdirSync3(g.abs, { withFileTypes: true });
14108
14454
  const lines = entries.slice(0, MAX_ENTRIES).map((e) => {
14109
14455
  if (e.isDirectory()) return `[dir] ${e.name}`;
14110
14456
  let size = 0;
14111
14457
  try {
14112
- size = statSync2(join16(g.abs, e.name)).size;
14458
+ size = statSync3(join18(g.abs, e.name)).size;
14113
14459
  } catch {
14114
14460
  }
14115
14461
  return `[file] ${e.name} (${size} bytes)`;
@@ -14129,7 +14475,7 @@ function fsRead(args, ctx) {
14129
14475
  const g = guard(args.path, ctx);
14130
14476
  if ("error" in g) return { ok: false, error: g.error };
14131
14477
  try {
14132
- const st = statSync2(g.abs);
14478
+ const st = statSync3(g.abs);
14133
14479
  if (!st.isFile()) return { ok: false, error: "Not a file" };
14134
14480
  const want = Math.min(st.size, ctx.maxOutput);
14135
14481
  const buf = Buffer.alloc(want);
@@ -14150,7 +14496,7 @@ function fsWrite(args, ctx) {
14150
14496
  if ("error" in g) return { ok: false, error: g.error };
14151
14497
  if (Buffer.byteLength(args.content) > MAX_WRITE) return { ok: false, error: "Content too large (5 MB limit)" };
14152
14498
  try {
14153
- mkdirSync11(dirname6(g.abs), { recursive: true });
14499
+ mkdirSync11(dirname7(g.abs), { recursive: true });
14154
14500
  writeFileSync10(g.abs, args.content);
14155
14501
  return { ok: true, output: `Wrote ${Buffer.byteLength(args.content)} bytes to ${g.abs}`, truncated: false };
14156
14502
  } catch (e) {
@@ -14184,7 +14530,7 @@ function runCommand2(command, cwdArg, ctx, argv) {
14184
14530
  const win = process.platform === "win32";
14185
14531
  const file = argv?.file ?? (win ? "powershell.exe" : "sh");
14186
14532
  const args = argv?.args ?? (win ? ["-NoProfile", "-NonInteractive", "-Command", command] : ["-c", command]);
14187
- return new Promise((resolve12) => {
14533
+ return new Promise((resolve13) => {
14188
14534
  const child = spawn4(file, args, { cwd, windowsHide: true, detached: !win, stdio: ["ignore", "pipe", "pipe"] });
14189
14535
  let out = "";
14190
14536
  let truncated = false;
@@ -14209,14 +14555,14 @@ function runCommand2(command, cwdArg, ctx, argv) {
14209
14555
  }, ctx.timeoutMs);
14210
14556
  child.on("error", (e) => {
14211
14557
  clearTimeout(timer);
14212
- resolve12({ ok: false, error: e.message });
14558
+ resolve13({ ok: false, error: e.message });
14213
14559
  });
14214
14560
  child.on("close", (code) => {
14215
14561
  clearTimeout(timer);
14216
- if (timedOut) return resolve12({ ok: false, error: `Command timed out after ${ctx.timeoutMs} ms` });
14562
+ if (timedOut) return resolve13({ ok: false, error: `Command timed out after ${ctx.timeoutMs} ms` });
14217
14563
  const tail2 = code === 0 || code === null ? "" : `
14218
14564
  [exit code ${code}]`;
14219
- resolve12({ ok: true, output: out + tail2, truncated });
14565
+ resolve13({ ok: true, output: out + tail2, truncated });
14220
14566
  });
14221
14567
  });
14222
14568
  }
@@ -14320,7 +14666,7 @@ function startDeviceNode(opts) {
14320
14666
  function connect2() {
14321
14667
  if (stopped) return;
14322
14668
  setState("connecting");
14323
- const sock = new WebSocket2(opts.url, { headers: { authorization: `Bearer ${opts.token}` }, ...opts.ca ? { ca: opts.ca } : {} });
14669
+ const sock = new WebSocket3(opts.url, { headers: { authorization: `Bearer ${opts.token}` }, ...opts.ca ? { ca: opts.ca } : {} });
14324
14670
  ws = sock;
14325
14671
  sock.on("error", () => {
14326
14672
  });
@@ -14344,7 +14690,7 @@ function startDeviceNode(opts) {
14344
14690
  if (!msg.success) return;
14345
14691
  const { id: id2, tool, args, approvedOutside } = msg.data;
14346
14692
  const result = await runTool(tool, args, { ...DEFAULT_CTX, roots: opts.roots, allowOutside: !!approvedOutside });
14347
- if (sock.readyState !== WebSocket2.OPEN) return;
14693
+ if (sock.readyState !== WebSocket3.OPEN) return;
14348
14694
  if (result.ok) {
14349
14695
  sock.send(JSON.stringify({ type: "tool.result", id: id2, result: { output: result.output, truncated: result.truncated } }));
14350
14696
  } else {
@@ -14387,8 +14733,8 @@ function startDeviceNode(opts) {
14387
14733
 
14388
14734
  // ../agent-cli/src/commands/start.ts
14389
14735
  import { randomBytes as randomBytes8 } from "node:crypto";
14390
- import { existsSync as existsSync15, readFileSync as readFileSync10, writeFileSync as writeFileSync12 } from "node:fs";
14391
- import { dirname as dirname8, join as join18, resolve as resolve7 } from "node:path";
14736
+ import { existsSync as existsSync16, readFileSync as readFileSync12, writeFileSync as writeFileSync12 } from "node:fs";
14737
+ import { dirname as dirname9, join as join20, resolve as resolve8 } from "node:path";
14392
14738
  import { fileURLToPath as fileURLToPath4 } from "node:url";
14393
14739
 
14394
14740
  // ../agent-cli/src/commands/lan.ts
@@ -14494,30 +14840,30 @@ async function lanCommand(args, io2, ifaces = networkInterfaces2) {
14494
14840
 
14495
14841
  // ../agent-cli/src/commands/voice.ts
14496
14842
  import { spawn as spawn5 } from "node:child_process";
14497
- import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync9, writeFileSync as writeFileSync11 } from "node:fs";
14498
- import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
14843
+ import { existsSync as existsSync15, mkdirSync as mkdirSync12, readFileSync as readFileSync11, writeFileSync as writeFileSync11 } from "node:fs";
14844
+ import { dirname as dirname8, join as join19, resolve as resolve7 } from "node:path";
14499
14845
  import { fileURLToPath as fileURLToPath3 } from "node:url";
14500
14846
  function voicePaths(dataDir) {
14501
- const home = join17(dataDir, "voice");
14502
- const venv = join17(home, "venv");
14847
+ const home = join19(dataDir, "voice");
14848
+ const venv = join19(home, "venv");
14503
14849
  return {
14504
14850
  home,
14505
14851
  venv,
14506
- python: process.platform === "win32" ? join17(venv, "Scripts", "python.exe") : join17(venv, "bin", "python"),
14507
- models: join17(home, "models"),
14508
- marker: join17(home, "installed.json")
14852
+ python: process.platform === "win32" ? join19(venv, "Scripts", "python.exe") : join19(venv, "bin", "python"),
14853
+ models: join19(home, "models"),
14854
+ marker: join19(home, "installed.json")
14509
14855
  };
14510
14856
  }
14511
14857
  function readMarker(dataDir) {
14512
14858
  try {
14513
- return JSON.parse(readFileSync9(voicePaths(dataDir).marker, "utf8"));
14859
+ return JSON.parse(readFileSync11(voicePaths(dataDir).marker, "utf8"));
14514
14860
  } catch {
14515
14861
  return null;
14516
14862
  }
14517
14863
  }
14518
14864
  function findVoiceDir() {
14519
- const here2 = dirname7(fileURLToPath3(import.meta.url));
14520
- return firstExistingDir([process.env.FRIEND_VOICE_DIR, resolve6(here2, "voice"), resolve6(here2, "../../../voice")], "friend_voice") ?? resolve6(here2, "voice");
14865
+ const here2 = dirname8(fileURLToPath3(import.meta.url));
14866
+ return firstExistingDir([process.env.FRIEND_VOICE_DIR, resolve7(here2, "voice"), resolve7(here2, "../../../voice")], "friend_voice") ?? resolve7(here2, "voice");
14521
14867
  }
14522
14868
  var QUIET_ENV = { ...process.env, HF_HUB_DISABLE_SYMLINKS_WARNING: "1", PYTHONUTF8: "1" };
14523
14869
  var defaultRunner = (cmd, args, opts) => new Promise((res) => {
@@ -14608,7 +14954,7 @@ async function voiceSetupCommand(io2, deps = {}, args = []) {
14608
14954
  return 1;
14609
14955
  }
14610
14956
  mkdirSync12(p.home, { recursive: true });
14611
- if (!existsSync14(p.python)) {
14957
+ if (!existsSync15(p.python)) {
14612
14958
  io2.out("1/3 Creating a private Python environment\u2026");
14613
14959
  const r = await run2(py.cmd, [...py.args, "-m", "venv", p.venv], { onLine });
14614
14960
  if (r.code !== 0) {
@@ -14658,7 +15004,7 @@ async function voiceStatusCommand(io2) {
14658
15004
  io2.out("Voice engine: not installed. Run: friend voice setup");
14659
15005
  return 0;
14660
15006
  }
14661
- if (!existsSync14(marker.python)) {
15007
+ if (!existsSync15(marker.python)) {
14662
15008
  io2.out("Voice engine: installed, but its Python is missing. Run: friend voice setup");
14663
15009
  return 0;
14664
15010
  }
@@ -14729,9 +15075,9 @@ async function voiceCommand(args, io2) {
14729
15075
 
14730
15076
  // ../agent-cli/src/commands/start.ts
14731
15077
  function findWebDir(explicit) {
14732
- const here2 = dirname8(fileURLToPath4(import.meta.url));
14733
- const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve7(here2, "../../../web/dist"), resolve7(here2, "web")];
14734
- return candidates.find((c) => !!c && existsSync15(join18(c, "index.html")));
15078
+ const here2 = dirname9(fileURLToPath4(import.meta.url));
15079
+ const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve8(here2, "../../../web/dist"), resolve8(here2, "web")];
15080
+ return candidates.find((c) => !!c && existsSync16(join20(c, "index.html")));
14735
15081
  }
14736
15082
  async function startFriend(opts) {
14737
15083
  const stored = loadConfig(opts.dataDir);
@@ -14765,8 +15111,8 @@ async function startFriend(opts) {
14765
15111
  }
14766
15112
  });
14767
15113
  const { port } = await app.start();
14768
- const tokenFile = join18(opts.dataDir, "local-device.token");
14769
- let token = existsSync15(tokenFile) ? readFileSync10(tokenFile, "utf8").trim() : "";
15114
+ const tokenFile = join20(opts.dataDir, "local-device.token");
15115
+ let token = existsSync16(tokenFile) ? readFileSync12(tokenFile, "utf8").trim() : "";
14770
15116
  if (!token || !app.auth.resolveDevice(token)) {
14771
15117
  token = app.auth.redeemPairCode(app.auth.createPairCode(), "this-pc");
14772
15118
  writeFileSync12(tokenFile, token, { mode: 384 });
@@ -14775,7 +15121,7 @@ async function startFriend(opts) {
14775
15121
  url: `${app.config.https ? "wss" : "ws"}://127.0.0.1:${port}/device`,
14776
15122
  token,
14777
15123
  roots: app.config.roots,
14778
- ...app.config.https ? { ca: readFileSync10(join18(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
15124
+ ...app.config.https ? { ca: readFileSync12(join20(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
14779
15125
  // this PC trusts only its own Friend's certificate
14780
15126
  });
14781
15127
  const urls = urlsFor(app.config.bind, port, void 0, app.config.https);
@@ -14855,7 +15201,7 @@ async function nodeCommand(args, io2) {
14855
15201
  io2.out("Paired. To reconnect later without a code, use:");
14856
15202
  io2.out(` friend node --url ${url} --token ${token}`);
14857
15203
  }
14858
- const roots = (flag(args, "roots") ?? "").split(",").map((s) => s.trim()).filter(Boolean).map((r) => resolve8(r));
15204
+ const roots = (flag(args, "roots") ?? "").split(",").map((s) => s.trim()).filter(Boolean).map((r) => resolve9(r));
14859
15205
  const node = startDeviceNode({ url, token, roots, onState: (s) => io2.out(`device: ${s}`) });
14860
15206
  await node.connected.catch((e) => io2.err(e.message));
14861
15207
  await (io2.waitForExit ?? waitForSignal)();
@@ -15003,13 +15349,13 @@ async function memoryCommand(args, io2) {
15003
15349
  }
15004
15350
 
15005
15351
  // ../agent-cli/src/commands/plugin.ts
15006
- import { existsSync as existsSync16, readdirSync as readdirSync3, statSync as statSync3 } from "node:fs";
15007
- import { dirname as dirname9, join as join19, resolve as resolve9 } from "node:path";
15352
+ import { existsSync as existsSync17, readdirSync as readdirSync4, statSync as statSync4 } from "node:fs";
15353
+ import { dirname as dirname10, join as join21, resolve as resolve10 } from "node:path";
15008
15354
  import { fileURLToPath as fileURLToPath5 } from "node:url";
15009
15355
  var USAGE2 = "Usage: friend plugin catalog | list | install <name|folder> [--yes] | enable <id> | disable <id> | remove <id>";
15010
15356
  function defaultCatalog() {
15011
- const here2 = dirname9(fileURLToPath5(import.meta.url));
15012
- return firstExistingDir([process.env.FRIEND_PLUGIN_CATALOG, resolve9(here2, "plugins"), resolve9(here2, "../../../../plugins")]) ?? resolve9(here2, "plugins");
15357
+ const here2 = dirname10(fileURLToPath5(import.meta.url));
15358
+ return firstExistingDir([process.env.FRIEND_PLUGIN_CATALOG, resolve10(here2, "plugins"), resolve10(here2, "../../../../plugins")]) ?? resolve10(here2, "plugins");
15013
15359
  }
15014
15360
  var count = (n, word2) => `${n} ${word2}${n === 1 ? "" : "s"}`;
15015
15361
  async function pluginCommand(args, io2, deps = {}) {
@@ -15018,10 +15364,10 @@ async function pluginCommand(args, io2, deps = {}) {
15018
15364
  const flags = rest.filter((a) => a.startsWith("--"));
15019
15365
  const arg = rest.find((a) => !a.startsWith("--"));
15020
15366
  if (sub === "catalog") {
15021
- const dirs = existsSync16(catalogDir) ? readdirSync3(catalogDir).filter((d) => statSync3(join19(catalogDir, d)).isDirectory()) : [];
15367
+ const dirs = existsSync17(catalogDir) ? readdirSync4(catalogDir).filter((d) => statSync4(join21(catalogDir, d)).isDirectory()) : [];
15022
15368
  if (dirs.length === 0) io2.out("The catalog is empty.");
15023
15369
  for (const d of dirs.sort()) {
15024
- const r = inspectPlugin(join19(catalogDir, d));
15370
+ const r = inspectPlugin(join21(catalogDir, d));
15025
15371
  if (!r.ok) {
15026
15372
  io2.out(`${d} (invalid: ${r.error})`);
15027
15373
  continue;
@@ -15037,7 +15383,7 @@ async function pluginCommand(args, io2, deps = {}) {
15037
15383
  }
15038
15384
  const db = openDb(io2.dataDir);
15039
15385
  try {
15040
- const plugins = new Plugins(db, join19(io2.dataDir, "plugins"));
15386
+ const plugins = new Plugins(db, join21(io2.dataDir, "plugins"));
15041
15387
  if (sub === "list") {
15042
15388
  const all = plugins.list();
15043
15389
  if (all.length === 0) io2.out("No plugins installed. See: friend plugin catalog");
@@ -15051,8 +15397,8 @@ async function pluginCommand(args, io2, deps = {}) {
15051
15397
  io2.err(USAGE2);
15052
15398
  return 1;
15053
15399
  }
15054
- const inCatalog = !/[\\/]/.test(arg) && existsSync16(join19(catalogDir, arg));
15055
- const source = inCatalog ? join19(catalogDir, arg) : existsSync16(resolve9(arg)) ? resolve9(arg) : null;
15400
+ const inCatalog = !/[\\/]/.test(arg) && existsSync17(join21(catalogDir, arg));
15401
+ const source = inCatalog ? join21(catalogDir, arg) : existsSync17(resolve10(arg)) ? resolve10(arg) : null;
15056
15402
  if (!source) {
15057
15403
  io2.err(`"${arg}" is not in the catalog and there is no such folder. See: friend plugin catalog`);
15058
15404
  return 1;
@@ -15108,7 +15454,7 @@ async function pluginCommand(args, io2, deps = {}) {
15108
15454
  // ../agent-cli/src/commands/onboard/index.ts
15109
15455
  import crossSpawn4 from "cross-spawn";
15110
15456
  import { mkdirSync as mkdirSync14 } from "node:fs";
15111
- import { resolve as resolve10 } from "node:path";
15457
+ import { resolve as resolve11 } from "node:path";
15112
15458
 
15113
15459
  // ../agent-cli/src/commands/ollama.ts
15114
15460
  var CONTAINER = "friend-ollama";
@@ -15277,13 +15623,13 @@ async function ollamaCommand(args, io2, deps = {}) {
15277
15623
  // ../agent-cli/src/commands/onboard/exec.ts
15278
15624
  import crossSpawn3 from "cross-spawn";
15279
15625
  var CHECK_TIMEOUT_MS = 2e4;
15280
- var capture = (cmd, args, opts) => new Promise((resolve12) => {
15626
+ var capture = (cmd, args, opts) => new Promise((resolve13) => {
15281
15627
  let stdout = "";
15282
15628
  let child;
15283
15629
  try {
15284
15630
  child = crossSpawn3(cmd, args, { cwd: opts?.cwd, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
15285
15631
  } catch (e) {
15286
- resolve12({ code: 127, stdout: e.message });
15632
+ resolve13({ code: 127, stdout: e.message });
15287
15633
  return;
15288
15634
  }
15289
15635
  const timer = opts?.onLine ? null : setTimeout(() => child.kill(), CHECK_TIMEOUT_MS);
@@ -15298,32 +15644,32 @@ var capture = (cmd, args, opts) => new Promise((resolve12) => {
15298
15644
  child.stderr?.on("data", feed);
15299
15645
  child.on("error", (e) => {
15300
15646
  if (timer) clearTimeout(timer);
15301
- resolve12({ code: 127, stdout: stdout + e.message });
15647
+ resolve13({ code: 127, stdout: stdout + e.message });
15302
15648
  });
15303
15649
  child.on("close", (code) => {
15304
15650
  if (timer) clearTimeout(timer);
15305
- resolve12({ code: code ?? 1, stdout });
15651
+ resolve13({ code: code ?? 1, stdout });
15306
15652
  });
15307
15653
  });
15308
- var interactive = (cmd, args) => new Promise((resolve12) => {
15654
+ var interactive = (cmd, args) => new Promise((resolve13) => {
15309
15655
  let child;
15310
15656
  try {
15311
15657
  child = crossSpawn3(cmd, args, { stdio: "inherit" });
15312
15658
  } catch {
15313
- resolve12(127);
15659
+ resolve13(127);
15314
15660
  return;
15315
15661
  }
15316
- child.on("error", () => resolve12(127));
15317
- child.on("close", (code) => resolve12(code ?? 1));
15662
+ child.on("error", () => resolve13(127));
15663
+ child.on("close", (code) => resolve13(code ?? 1));
15318
15664
  });
15319
15665
 
15320
15666
  // ../agent-cli/src/commands/onboard/prereq.ts
15321
15667
  import { createServer as createServer2 } from "node:net";
15322
15668
  function defaultPortFree(port) {
15323
- return new Promise((resolve12) => {
15669
+ return new Promise((resolve13) => {
15324
15670
  const s = createServer2();
15325
- s.once("error", () => resolve12(false));
15326
- s.once("listening", () => s.close(() => resolve12(true)));
15671
+ s.once("error", () => resolve13(false));
15672
+ s.once("listening", () => s.close(() => resolve13(true)));
15327
15673
  s.listen(port, "127.0.0.1");
15328
15674
  });
15329
15675
  }
@@ -15430,16 +15776,16 @@ function installPlan(id2, platform, have) {
15430
15776
  }
15431
15777
 
15432
15778
  // ../agent-cli/src/commands/onboard/state.ts
15433
- import { existsSync as existsSync17, mkdirSync as mkdirSync13, readFileSync as readFileSync11, renameSync as renameSync3, rmSync as rmSync8, writeFileSync as writeFileSync13 } from "node:fs";
15434
- import { dirname as dirname10, join as join20 } from "node:path";
15779
+ import { existsSync as existsSync18, mkdirSync as mkdirSync13, readFileSync as readFileSync13, renameSync as renameSync3, rmSync as rmSync8, writeFileSync as writeFileSync13 } from "node:fs";
15780
+ import { dirname as dirname11, join as join22 } from "node:path";
15435
15781
  var FEATURES = ["claude-code", "claude-api", "ollama", "voice", "sandbox"];
15436
15782
  var emptyState = () => ({ version: 1, done: {}, features: [], restart: [] });
15437
- var statePath = (dataDir) => join20(dataDir, "onboarding.json");
15783
+ var statePath = (dataDir) => join22(dataDir, "onboarding.json");
15438
15784
  function loadState(dataDir) {
15439
15785
  const f = statePath(dataDir);
15440
- if (!existsSync17(f)) return emptyState();
15786
+ if (!existsSync18(f)) return emptyState();
15441
15787
  try {
15442
- const raw = JSON.parse(readFileSync11(f, "utf8"));
15788
+ const raw = JSON.parse(readFileSync13(f, "utf8"));
15443
15789
  const done = raw.done && typeof raw.done === "object" ? Object.fromEntries(Object.entries(raw.done).filter(([, v]) => typeof v === "string")) : {};
15444
15790
  const features2 = Array.isArray(raw.features) ? raw.features.filter((x) => FEATURES.includes(x)) : [];
15445
15791
  const restart = Array.isArray(raw.restart) ? raw.restart.filter((x) => typeof x === "string") : [];
@@ -15450,7 +15796,7 @@ function loadState(dataDir) {
15450
15796
  }
15451
15797
  function saveState(dataDir, state) {
15452
15798
  const f = statePath(dataDir);
15453
- mkdirSync13(dirname10(f), { recursive: true });
15799
+ mkdirSync13(dirname11(f), { recursive: true });
15454
15800
  const tmp = `${f}.tmp`;
15455
15801
  writeFileSync13(tmp, JSON.stringify(state, null, 2));
15456
15802
  renameSync3(tmp, f);
@@ -15807,7 +16153,7 @@ async function workspace(c) {
15807
16153
  const current = cfg.roots[0];
15808
16154
  const answer = await text(c.ui, current ? "Workspace folder" : "Workspace folder (Enter to skip)", current ?? "");
15809
16155
  if (answer) {
15810
- const abs = resolve10(answer);
16156
+ const abs = resolve11(answer);
15811
16157
  mkdirSync14(abs, { recursive: true });
15812
16158
  cfg.roots = [abs];
15813
16159
  saveConfig(cfg);
@@ -15980,9 +16326,9 @@ async function doctorCommand(io2, partial = {}) {
15980
16326
 
15981
16327
  // ../agent-cli/src/commands/daemon.ts
15982
16328
  import { spawn as spawn6, spawnSync as spawnSync2 } from "node:child_process";
15983
- import { closeSync as closeSync2, existsSync as existsSync18, mkdirSync as mkdirSync15, openSync as openSync2, readFileSync as readFileSync12, renameSync as renameSync4, rmSync as rmSync9, statSync as statSync4, writeFileSync as writeFileSync14 } from "node:fs";
16329
+ import { closeSync as closeSync2, existsSync as existsSync19, mkdirSync as mkdirSync15, openSync as openSync2, readFileSync as readFileSync14, renameSync as renameSync4, rmSync as rmSync9, statSync as statSync5, writeFileSync as writeFileSync14 } from "node:fs";
15984
16330
  import { connect } from "node:net";
15985
- import { join as join21 } from "node:path";
16331
+ import { join as join23 } from "node:path";
15986
16332
  var USAGE3 = "Usage: friend daemon start | stop | restart | status";
15987
16333
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
15988
16334
  var sleep = (ms2) => new Promise((r) => setTimeout(r, ms2));
@@ -16025,11 +16371,11 @@ var realDeps = {
16025
16371
  for (let i = 0; i < 25 && realDeps.alive(pid); i++) await sleep(200);
16026
16372
  },
16027
16373
  portOpen(port, withinMs) {
16028
- return new Promise((resolve12) => {
16374
+ return new Promise((resolve13) => {
16029
16375
  const s = connect({ port, host: "127.0.0.1" });
16030
16376
  const done = (ok) => {
16031
16377
  s.destroy();
16032
- resolve12(ok);
16378
+ resolve13(ok);
16033
16379
  };
16034
16380
  s.setTimeout(withinMs, () => done(false));
16035
16381
  s.once("connect", () => done(true));
@@ -16038,11 +16384,11 @@ var realDeps = {
16038
16384
  },
16039
16385
  now: Date.now
16040
16386
  };
16041
- var pidFile = (dataDir) => join21(dataDir, "friend.pid");
16042
- var logFileOf = (dataDir) => join21(dataDir, "friend.log");
16387
+ var pidFile = (dataDir) => join23(dataDir, "friend.pid");
16388
+ var logFileOf = (dataDir) => join23(dataDir, "friend.log");
16043
16389
  function readPid(dataDir) {
16044
16390
  try {
16045
- const r = JSON.parse(readFileSync12(pidFile(dataDir), "utf8"));
16391
+ const r = JSON.parse(readFileSync14(pidFile(dataDir), "utf8"));
16046
16392
  return Number.isInteger(r.pid) && r.pid > 0 ? r : null;
16047
16393
  } catch {
16048
16394
  return null;
@@ -16076,7 +16422,7 @@ async function start(io2, deps) {
16076
16422
  mkdirSync15(io2.dataDir, { recursive: true });
16077
16423
  const log = logFileOf(io2.dataDir);
16078
16424
  try {
16079
- if (existsSync18(log) && statSync4(log).size > MAX_LOG_BYTES) renameSync4(log, `${log}.old`);
16425
+ if (existsSync19(log) && statSync5(log).size > MAX_LOG_BYTES) renameSync4(log, `${log}.old`);
16080
16426
  } catch {
16081
16427
  }
16082
16428
  const pid = deps.launch(log);
@@ -16151,23 +16497,23 @@ async function daemonCommand(args, io2, deps = realDeps) {
16151
16497
  import crossSpawn5 from "cross-spawn";
16152
16498
  var PACKAGE = "friend-assistant";
16153
16499
  var real = {
16154
- current: () => true ? "0.1.36" : "development",
16155
- latest: () => new Promise((resolve12) => {
16500
+ current: () => true ? "0.1.37" : "development",
16501
+ latest: () => new Promise((resolve13) => {
16156
16502
  const child = crossSpawn5("npm", ["view", PACKAGE, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
16157
16503
  let out = "";
16158
16504
  child.stdout?.on("data", (d) => out += d.toString());
16159
- child.on("error", () => resolve12(null));
16160
- child.on("close", (code) => resolve12(code === 0 && /^\d+\.\d+\.\d+/.test(out.trim()) ? out.trim().split(/\s+/)[0] : null));
16505
+ child.on("error", () => resolve13(null));
16506
+ child.on("close", (code) => resolve13(code === 0 && /^\d+\.\d+\.\d+/.test(out.trim()) ? out.trim().split(/\s+/)[0] : null));
16161
16507
  }),
16162
- install: (version) => new Promise((resolve12) => {
16508
+ install: (version) => new Promise((resolve13) => {
16163
16509
  const child = crossSpawn5("npm", ["install", "-g", `${PACKAGE}@${version}`, "--prefer-online"], { stdio: "inherit" });
16164
- child.on("error", () => resolve12(1));
16165
- child.on("close", (code) => resolve12(code ?? 1));
16510
+ child.on("error", () => resolve13(1));
16511
+ child.on("close", (code) => resolve13(code ?? 1));
16166
16512
  }),
16167
- startAgain: () => new Promise((resolve12) => {
16513
+ startAgain: () => new Promise((resolve13) => {
16168
16514
  const child = crossSpawn5("friend", ["daemon", "start"], { stdio: "inherit" });
16169
- child.on("error", () => resolve12(1));
16170
- child.on("close", (code) => resolve12(code ?? 1));
16515
+ child.on("error", () => resolve13(1));
16516
+ child.on("close", (code) => resolve13(code ?? 1));
16171
16517
  }),
16172
16518
  daemon: realDeps
16173
16519
  };
@@ -16287,7 +16633,7 @@ async function claudeCommand(args, io2, deps = {}) {
16287
16633
 
16288
16634
  // ../agent-cli/src/commands/setup.ts
16289
16635
  import { mkdirSync as mkdirSync16 } from "node:fs";
16290
- import { resolve as resolve11 } from "node:path";
16636
+ import { resolve as resolve12 } from "node:path";
16291
16637
  async function setupCommand3(io2) {
16292
16638
  const db = openDb(io2.dataDir);
16293
16639
  try {
@@ -16311,7 +16657,7 @@ async function setupCommand3(io2) {
16311
16657
  }
16312
16658
  const cfg = loadConfig(io2.dataDir);
16313
16659
  if (workspace2) {
16314
- const abs = resolve11(workspace2);
16660
+ const abs = resolve12(workspace2);
16315
16661
  mkdirSync16(abs, { recursive: true });
16316
16662
  cfg.roots = [abs];
16317
16663
  }
@@ -16439,7 +16785,7 @@ async function run(argv, io2) {
16439
16785
  case "version":
16440
16786
  case "--version":
16441
16787
  case "-v":
16442
- io2.out(true ? "0.1.36" : "development");
16788
+ io2.out(true ? "0.1.37" : "development");
16443
16789
  return 0;
16444
16790
  case "lan":
16445
16791
  return await lanCommand(rest, io2);
@@ -16469,14 +16815,14 @@ async function run(argv, io2) {
16469
16815
 
16470
16816
  // ../agent-cli/src/bin.ts
16471
16817
  function askHidden(question) {
16472
- return new Promise((resolve12) => {
16818
+ return new Promise((resolve13) => {
16473
16819
  process.stdout.write(question);
16474
16820
  const stdin = process.stdin;
16475
16821
  if (!stdin.isTTY) {
16476
16822
  const rl = createInterface2({ input: stdin });
16477
16823
  rl.once("line", (l) => {
16478
16824
  rl.close();
16479
- resolve12(l);
16825
+ resolve13(l);
16480
16826
  });
16481
16827
  return;
16482
16828
  }
@@ -16491,7 +16837,7 @@ function askHidden(question) {
16491
16837
  stdin.pause();
16492
16838
  stdin.off("data", onData);
16493
16839
  process.stdout.write("\n");
16494
- return resolve12(buf);
16840
+ return resolve13(buf);
16495
16841
  }
16496
16842
  if (c === "") process.exit(130);
16497
16843
  if (c === "\x7F" || c === "\b") buf = buf.slice(0, -1);
@@ -16502,11 +16848,11 @@ function askHidden(question) {
16502
16848
  });
16503
16849
  }
16504
16850
  function askVisible(question) {
16505
- return new Promise((resolve12) => {
16851
+ return new Promise((resolve13) => {
16506
16852
  const rl = createInterface2({ input: process.stdin, output: process.stdout });
16507
16853
  rl.question(question, (a) => {
16508
16854
  rl.close();
16509
- resolve12(a);
16855
+ resolve13(a);
16510
16856
  });
16511
16857
  });
16512
16858
  }