friend-assistant 0.1.70 → 0.1.72

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
@@ -89,7 +89,7 @@ function jarvisProblem(props) {
89
89
  const ui = props && typeof props === "object" ? props.ui : void 0;
90
90
  if (!ui || typeof ui !== "object") return 'A jarvis object needs ui: a tree like {c: "JStatCard", p: {...}, kids: [...]}, where c is the component name.';
91
91
  let count3 = 0;
92
- const walk2 = (n2, depth) => {
92
+ const walk3 = (n2, depth) => {
93
93
  if (typeof n2 === "string") return n2.length > JARVIS_LIMITS.text ? "A text is too long." : null;
94
94
  if (!n2 || typeof n2 !== "object" || typeof n2.c !== "string") return "Every node needs c, the component name.";
95
95
  if (depth > JARVIS_LIMITS.depth) return `The tree is too deep (at most ${JARVIS_LIMITS.depth} levels).`;
@@ -108,19 +108,19 @@ function jarvisProblem(props) {
108
108
  const parts = node.slots[slot];
109
109
  if (!Array.isArray(parts)) return `${node.c}: the slot ${slot} must be a list.`;
110
110
  for (const part of parts) {
111
- const r = walk2(part, depth + 1);
111
+ const r = walk3(part, depth + 1);
112
112
  if (r) return r;
113
113
  }
114
114
  }
115
115
  if (node.kids !== void 0 && !Array.isArray(node.kids)) return `${node.c}: kids must be a list.`;
116
116
  if (node.kids && !def.kids && node.kids.some((k) => typeof k !== "string")) return `${node.c} cannot contain other components.`;
117
117
  for (const k of node.kids ?? []) {
118
- const r = walk2(k, depth + 1);
118
+ const r = walk3(k, depth + 1);
119
119
  if (r) return r;
120
120
  }
121
121
  return null;
122
122
  };
123
- return walk2(ui, 1);
123
+ return walk3(ui, 1);
124
124
  }
125
125
  function jarvisObjectProblem(type, props) {
126
126
  return jarvisProblem({ ui: jarvisTreeOf(type, props) });
@@ -2400,14 +2400,14 @@ var MemoryTree = class {
2400
2400
  /** Counts every note (not index files). */
2401
2401
  count() {
2402
2402
  let n2 = 0;
2403
- const walk2 = (dir) => {
2403
+ const walk3 = (dir) => {
2404
2404
  for (const e of readdirSync(dir, { withFileTypes: true })) {
2405
2405
  if (e.isSymbolicLink()) continue;
2406
- if (e.isDirectory()) walk2(join(dir, e.name));
2406
+ if (e.isDirectory()) walk3(join(dir, e.name));
2407
2407
  else if (e.isFile() && e.name.endsWith(".md") && e.name !== INDEX_FILE) n2++;
2408
2408
  }
2409
2409
  };
2410
- if (existsSync(this.root)) walk2(this.root);
2410
+ if (existsSync(this.root)) walk3(this.root);
2411
2411
  return n2;
2412
2412
  }
2413
2413
  /** A note's text, or a folder's index. An empty path is the root. */
@@ -2499,18 +2499,18 @@ var MemoryTree = class {
2499
2499
  /** Every note (path, title, summary, related), reading the files. For tidying, and for the notes' links. */
2500
2500
  notes() {
2501
2501
  const out = [];
2502
- const walk2 = (dir, parts) => {
2502
+ const walk3 = (dir, parts) => {
2503
2503
  if (!existsSync(dir)) return;
2504
2504
  for (const e of readdirSync(dir, { withFileTypes: true })) {
2505
2505
  if (e.isSymbolicLink()) continue;
2506
- if (e.isDirectory()) walk2(join(dir, e.name), [...parts, e.name]);
2506
+ if (e.isDirectory()) walk3(join(dir, e.name), [...parts, e.name]);
2507
2507
  else if (e.isFile() && e.name.endsWith(".md") && e.name !== INDEX_FILE) {
2508
2508
  const n2 = parseNote(readFileSync(join(dir, e.name), "utf8"), humanize(e.name));
2509
2509
  out.push({ path: [...parts, e.name].join("/"), title: n2.title, summary: n2.summary, related: n2.related, body: n2.body });
2510
2510
  }
2511
2511
  }
2512
2512
  };
2513
- walk2(this.root, []);
2513
+ walk3(this.root, []);
2514
2514
  return out;
2515
2515
  }
2516
2516
  /** After a note or folder moved or was deleted, notes that pointed at it follow it (or drop the pointer). */
@@ -2542,14 +2542,14 @@ var MemoryTree = class {
2542
2542
  }
2543
2543
  countUnder(parts) {
2544
2544
  let n2 = 0;
2545
- const walk2 = (dir) => {
2545
+ const walk3 = (dir) => {
2546
2546
  for (const e of readdirSync(dir, { withFileTypes: true })) {
2547
2547
  if (e.isSymbolicLink()) continue;
2548
- if (e.isDirectory()) walk2(join(dir, e.name));
2548
+ if (e.isDirectory()) walk3(join(dir, e.name));
2549
2549
  else if (e.name.endsWith(".md") && e.name !== INDEX_FILE) n2++;
2550
2550
  }
2551
2551
  };
2552
- walk2(this.abs(parts));
2552
+ walk3(this.abs(parts));
2553
2553
  return n2;
2554
2554
  }
2555
2555
  /** Moves a note to another folder or name; both indexes follow. A folder moves with everything in it. */
@@ -2590,11 +2590,11 @@ var MemoryTree = class {
2590
2590
  const words = query.toLowerCase().split(/\s+/).filter(Boolean);
2591
2591
  if (words.length === 0) return [];
2592
2592
  const hits = [];
2593
- const walk2 = (dir, parts) => {
2593
+ const walk3 = (dir, parts) => {
2594
2594
  if (!existsSync(dir)) return;
2595
2595
  for (const e of readdirSync(dir, { withFileTypes: true })) {
2596
2596
  if (e.isSymbolicLink()) continue;
2597
- if (e.isDirectory()) walk2(join(dir, e.name), [...parts, e.name]);
2597
+ if (e.isDirectory()) walk3(join(dir, e.name), [...parts, e.name]);
2598
2598
  else if (e.isFile() && e.name.endsWith(".md") && e.name !== INDEX_FILE) {
2599
2599
  const note = parseNote(readFileSync(join(dir, e.name), "utf8"), humanize(e.name));
2600
2600
  const head = `${note.title} ${note.summary}`.toLowerCase();
@@ -2604,21 +2604,21 @@ var MemoryTree = class {
2604
2604
  }
2605
2605
  }
2606
2606
  };
2607
- walk2(this.root, []);
2607
+ walk3(this.root, []);
2608
2608
  return hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, limit).map(({ score: _s, ...f }) => f);
2609
2609
  }
2610
2610
  /** Every folder and note, walking down from the root by the indexes, with how deep each is. */
2611
2611
  outline() {
2612
2612
  const out = [];
2613
- const walk2 = (folder) => {
2613
+ const walk3 = (folder) => {
2614
2614
  if (!existsSync(this.abs([...folder, INDEX_FILE]))) return;
2615
2615
  for (const e of this.readIndexOf(folder).entries) {
2616
2616
  const path3 = [...folder, e.target.replace(/\/$/, "")].join("/");
2617
2617
  out.push({ path: e.kind === "folder" ? `${path3}/` : path3, kind: e.kind, title: e.title, summary: e.summary, depth: folder.length });
2618
- if (e.kind === "folder" && folder.length < MAX_DEPTH) walk2([...folder, e.target.replace(/\/$/, "")]);
2618
+ if (e.kind === "folder" && folder.length < MAX_DEPTH) walk3([...folder, e.target.replace(/\/$/, "")]);
2619
2619
  }
2620
2620
  };
2621
- walk2([]);
2621
+ walk3([]);
2622
2622
  return out;
2623
2623
  }
2624
2624
  /** Deletes every note and folder and starts the root index again. Returns how many notes there were. */
@@ -2632,7 +2632,7 @@ var MemoryTree = class {
2632
2632
  check() {
2633
2633
  this.ensure();
2634
2634
  const problems = [];
2635
- const walk2 = (folder) => {
2635
+ const walk3 = (folder) => {
2636
2636
  const dir = this.abs(folder);
2637
2637
  const hasIndex = existsSync(join(dir, INDEX_FILE));
2638
2638
  if (!hasIndex) problems.push({ kind: "no-index", path: folder.join("/") });
@@ -2643,7 +2643,7 @@ var MemoryTree = class {
2643
2643
  if (e.isDirectory()) {
2644
2644
  seen.add(`${e.name}/`);
2645
2645
  if (!listed.some((l) => l.target === `${e.name}/`)) problems.push({ kind: "unlisted-folder", path: [...folder, e.name].join("/") });
2646
- walk2([...folder, e.name]);
2646
+ walk3([...folder, e.name]);
2647
2647
  } else if (e.isFile() && e.name.endsWith(".md") && e.name !== INDEX_FILE) {
2648
2648
  const key2 = e.name;
2649
2649
  seen.add(key2);
@@ -2652,7 +2652,7 @@ var MemoryTree = class {
2652
2652
  }
2653
2653
  for (const l of listed) if (!seen.has(l.target)) problems.push({ kind: "dead-link", path: [...folder, l.target].join("/") });
2654
2654
  };
2655
- walk2([]);
2655
+ walk3([]);
2656
2656
  for (const n2 of this.notes()) for (const r of n2.related) if (!this.noteExists(r)) problems.push({ kind: "dead-related", path: `${n2.path} -> ${r}` });
2657
2657
  return problems;
2658
2658
  }
@@ -3074,14 +3074,14 @@ function regionUse(objects) {
3074
3074
  return { used: used2, free: REGION_NAMES.filter((n2) => !used2.has(n2)) };
3075
3075
  }
3076
3076
  function describeScreen(scene, presence, entries, now, panels = [], screen = null, view, accent) {
3077
- const open2 = panels.length ? `; the owner has open: ${panels.map((p) => PANEL_TEXT[p]).join(", ")}, so keep clear of them` : "";
3077
+ const open3 = panels.length ? `; the owner has open: ${panels.map((p) => PANEL_TEXT[p]).join(", ")}, so keep clear of them` : "";
3078
3078
  const known = [screen ? describeDevice(screen) : "", view ? `view=${view}` : "", accent ? `accent=${accent}` : ""].filter(Boolean);
3079
3079
  const device = known.length ? `${known.join("; ")}; ` : "";
3080
3080
  const phone = screen?.kind === "phone";
3081
3081
  const taken = panelObjects(panels);
3082
3082
  if (entries.length === 0) {
3083
3083
  const { free: free2 } = regionUse(taken);
3084
- return `${device}scene=${scene}; presence=${presence}; the stage is empty${open2}${phone ? "" : `; free regions: ${free2.join(", ") || "none"}`}`;
3084
+ return `${device}scene=${scene}; presence=${presence}; the stage is empty${open3}${phone ? "" : `; free regions: ${free2.join(", ") || "none"}`}`;
3085
3085
  }
3086
3086
  const items = entries.map(({ object: o, expiresAt }) => {
3087
3087
  const where = typeof o.placement === "string" ? o.placement : "custom box";
@@ -3089,7 +3089,7 @@ function describeScreen(scene, presence, entries, now, panels = [], screen = nul
3089
3089
  return `${o.id} (${o.type}, ${o.layer === "overlay" ? "overlay on top" : phone ? "stacked" : where}, ${life})`;
3090
3090
  });
3091
3091
  const { free } = regionUse([...entries.map((e) => e.object).filter((o) => o.layer !== "overlay"), ...taken]);
3092
- return `${device}scene=${scene}; presence=${presence}; on screen: ${items.join("; ")}${open2}${phone ? "" : `; free regions: ${free.join(", ") || "none, replace something first"}`}`;
3092
+ return `${device}scene=${scene}; presence=${presence}; on screen: ${items.join("; ")}${open3}${phone ? "" : `; free regions: ${free.join(", ") || "none, replace something first"}`}`;
3093
3093
  }
3094
3094
  var LAYOUT_GUIDE = `Screen layout (follow this when you decide where things go)
3095
3095
  - Always on screen, never yours to cover or move: the voice presence (middle of the screen; a small round shape in the bottom-left corner during "focus" and "multi" scenes), the live captions at the bottom, a status line in the bottom-left, a small clock in the bottom-right, and the owner's notices along the top edge. Use the middle of the screen for what the owner asked to see.
@@ -3348,8 +3348,8 @@ var StageState = class {
3348
3348
  return this.locked;
3349
3349
  }
3350
3350
  /** The side panels the owner has open right now; objects are kept out of their way. */
3351
- setPanels(open2) {
3352
- this.panels = ["chat", "tasks"].filter((p) => open2.includes(p));
3351
+ setPanels(open3) {
3352
+ this.panels = ["chat", "tasks"].filter((p) => open3.includes(p));
3353
3353
  }
3354
3354
  openPanels() {
3355
3355
  return [...this.panels];
@@ -4201,8 +4201,8 @@ var Agent = class {
4201
4201
  return { ok: true, text: `Added task #${r.id}${describe({ dueAt: due, repeat: repeat ?? null })}.` };
4202
4202
  }
4203
4203
  if (name === "task.list") {
4204
- const open2 = tasks.list();
4205
- return { ok: true, text: open2.length ? open2.map((t) => `#${t.id} ${t.title}${describe(t)}`).join("\n") : "No open tasks." };
4204
+ const open3 = tasks.list();
4205
+ return { ok: true, text: open3.length ? open3.map((t) => `#${t.id} ${t.title}${describe(t)}`).join("\n") : "No open tasks." };
4206
4206
  }
4207
4207
  if (name === "task.done") {
4208
4208
  const id2 = Number(args.id);
@@ -4734,7 +4734,7 @@ ${lines.join("\n")}`, isError: false };
4734
4734
  };
4735
4735
 
4736
4736
  // ../server/src/admin.ts
4737
- import { join as join6 } from "node:path";
4737
+ import { join as join7 } from "node:path";
4738
4738
 
4739
4739
  // ../server/src/author.ts
4740
4740
  import { mkdirSync as mkdirSync3, mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
@@ -4786,9 +4786,100 @@ function authorPlugin(plugins, scratchRoot, spec) {
4786
4786
 
4787
4787
  // ../server/src/config.ts
4788
4788
  import { createHash as createHash2 } from "node:crypto";
4789
- import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
4789
+ import { chmodSync as chmodSync2, existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync5 } from "node:fs";
4790
4790
  import { homedir } from "node:os";
4791
- import { join as join4, posix as posix2, win32 as win322 } from "node:path";
4791
+ import { join as join5, posix as posix2, win32 as win322 } from "node:path";
4792
+
4793
+ // ../server/src/secretBox.ts
4794
+ import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
4795
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
4796
+ import { join as join4 } from "node:path";
4797
+ var PREFIX = "enc:v1:";
4798
+ var SECRET_NAME = /(token|secret|password|passphrase|key|sid)$/i;
4799
+ var keyCache = /* @__PURE__ */ new Map();
4800
+ function masterKey(dataDir) {
4801
+ const pass = process.env.FRIEND_SECRET_KEY;
4802
+ const id2 = pass ? `p:${pass}` : `f:${dataDir}`;
4803
+ const hit = keyCache.get(id2);
4804
+ if (hit) return hit;
4805
+ let key2;
4806
+ if (pass) key2 = scryptSync(pass, "friend-secret-box-v1", 32);
4807
+ else {
4808
+ const file = join4(dataDir, "secret.key");
4809
+ if (existsSync3(file)) key2 = Buffer.from(readFileSync3(file, "utf8").trim(), "hex");
4810
+ else {
4811
+ key2 = randomBytes(32);
4812
+ mkdirSync4(dataDir, { recursive: true });
4813
+ writeFileSync4(file, key2.toString("hex"), { mode: 384 });
4814
+ try {
4815
+ chmodSync(file, 384);
4816
+ } catch {
4817
+ }
4818
+ }
4819
+ if (key2.length !== 32) throw new Error(`${file} is damaged (it must hold a 32-byte key). Restore it from a backup.`);
4820
+ }
4821
+ keyCache.set(id2, key2);
4822
+ return key2;
4823
+ }
4824
+ function seal(text4, key2) {
4825
+ const iv = randomBytes(12);
4826
+ const c = createCipheriv("aes-256-gcm", key2, iv);
4827
+ const data2 = Buffer.concat([c.update(text4, "utf8"), c.final()]);
4828
+ return PREFIX + [iv, c.getAuthTag(), data2].map((b) => b.toString("base64url")).join(".");
4829
+ }
4830
+ function open(text4, key2) {
4831
+ try {
4832
+ const [iv, tag, data2] = text4.slice(PREFIX.length).split(".").map((s) => Buffer.from(s, "base64url"));
4833
+ if (!iv || !tag || !data2 || iv.length !== 12 || tag.length !== 16) return null;
4834
+ const d = createDecipheriv("aes-256-gcm", key2, iv);
4835
+ d.setAuthTag(tag);
4836
+ return Buffer.concat([d.update(data2), d.final()]).toString("utf8");
4837
+ } catch {
4838
+ return null;
4839
+ }
4840
+ }
4841
+ function walk(v, path3, visit) {
4842
+ if (Array.isArray(v)) v.forEach((x, i) => walk(x, `${path3}[${i}]`, visit));
4843
+ else if (v && typeof v === "object") {
4844
+ const o = v;
4845
+ for (const k of Object.keys(o)) {
4846
+ const p = path3 ? `${path3}.${k}` : k;
4847
+ visit(o, k, p);
4848
+ walk(o[k], p, visit);
4849
+ }
4850
+ }
4851
+ }
4852
+ function sealSecrets(value, dataDir) {
4853
+ const copy = JSON.parse(JSON.stringify(value));
4854
+ let changed = false;
4855
+ walk(copy, "", (o, k) => {
4856
+ const s = o[k];
4857
+ if (typeof s === "string" && s !== "" && !s.startsWith(PREFIX) && SECRET_NAME.test(k)) {
4858
+ o[k] = seal(s, masterKey(dataDir));
4859
+ changed = true;
4860
+ }
4861
+ });
4862
+ return { value: copy, changed };
4863
+ }
4864
+ function unsealSecrets(value, dataDir) {
4865
+ const copy = JSON.parse(JSON.stringify(value));
4866
+ const lost = [];
4867
+ walk(copy, "", (o, k, p) => {
4868
+ const s = o[k];
4869
+ if (typeof s !== "string" || !s.startsWith(PREFIX)) return;
4870
+ let plain6 = null;
4871
+ try {
4872
+ plain6 = open(s, masterKey(dataDir));
4873
+ } catch {
4874
+ plain6 = null;
4875
+ }
4876
+ if (plain6 === null) lost.push(p);
4877
+ o[k] = plain6 ?? "";
4878
+ });
4879
+ return { value: copy, lost };
4880
+ }
4881
+
4882
+ // ../server/src/config.ts
4792
4883
  var BROWSER_LIMITS = { timeoutSec: { min: 5, max: 60, def: 20 }, maxChars: { min: 1e3, max: 3e4, def: 12e3 } };
4793
4884
  var chromePathOk = (v) => v === "" || v.length <= 300 && !/[\u0000-\u001f"<>|*?]/.test(v) && !v.startsWith("-");
4794
4885
  function sanitizeBrowser(raw) {
@@ -5231,7 +5322,7 @@ var DEFAULT_DESTRUCTIVE_PATTERNS = [
5231
5322
  String.raw`\b(iex|invoke-expression)\b`
5232
5323
  ];
5233
5324
  function defaultDataDir() {
5234
- return process.env.FRIEND_HOME ?? join4(homedir(), ".friend");
5325
+ return process.env.FRIEND_HOME ?? join5(homedir(), ".friend");
5235
5326
  }
5236
5327
  var defaults = (dataDir) => ({
5237
5328
  bind: "127.0.0.1",
@@ -5274,46 +5365,50 @@ var defaults = (dataDir) => ({
5274
5365
  dataDir
5275
5366
  });
5276
5367
  function configPath(dataDir) {
5277
- return join4(dataDir, "config.json");
5368
+ return join5(dataDir, "config.json");
5278
5369
  }
5279
5370
  var trackHash = false;
5280
5371
  function trackConfigHash(on = true) {
5281
5372
  trackHash = on;
5282
5373
  }
5283
- var hashFile = (dataDir) => join4(dataDir, "config.hash");
5284
- var fingerprint = (dataDir) => createHash2("sha256").update(readFileSync3(configPath(dataDir))).digest("hex");
5374
+ var hashFile = (dataDir) => join5(dataDir, "config.hash");
5375
+ var fingerprint = (dataDir) => createHash2("sha256").update(readFileSync4(configPath(dataDir))).digest("hex");
5285
5376
  function checkConfigFile(dataDir) {
5286
5377
  const to = fingerprint(dataDir);
5287
5378
  let from = null;
5288
5379
  try {
5289
- from = readFileSync3(hashFile(dataDir), "utf8").trim();
5380
+ from = readFileSync4(hashFile(dataDir), "utf8").trim();
5290
5381
  } catch {
5291
5382
  from = null;
5292
5383
  }
5293
- writeFileSync4(hashFile(dataDir), to);
5384
+ writeFileSync5(hashFile(dataDir), to);
5294
5385
  if (from === null) return { state: "baseline", to };
5295
5386
  return from === to ? { state: "same", to } : { state: "changed", from, to };
5296
5387
  }
5297
5388
  function saveConfig(cfg) {
5298
5389
  const { dataDir, ...rest } = cfg;
5299
- mkdirSync4(dataDir, { recursive: true });
5300
- writeFileSync4(configPath(dataDir), JSON.stringify(rest, null, 2));
5301
- if (trackHash) writeFileSync4(hashFile(dataDir), fingerprint(dataDir));
5390
+ mkdirSync5(dataDir, { recursive: true });
5391
+ writeFileSync5(configPath(dataDir), JSON.stringify(sealSecrets(rest, dataDir).value, null, 2));
5392
+ if (trackHash) writeFileSync5(hashFile(dataDir), fingerprint(dataDir));
5302
5393
  try {
5303
- chmodSync(configPath(dataDir), 384);
5394
+ chmodSync2(configPath(dataDir), 384);
5304
5395
  } catch {
5305
5396
  }
5306
5397
  }
5307
5398
  function loadConfig(dataDir = defaultDataDir()) {
5308
- mkdirSync4(dataDir, { recursive: true });
5399
+ mkdirSync5(dataDir, { recursive: true });
5309
5400
  const file = configPath(dataDir);
5310
5401
  const base = defaults(dataDir);
5311
- if (!existsSync3(file)) {
5402
+ if (!existsSync4(file)) {
5312
5403
  const { dataDir: _d, ...rest } = base;
5313
5404
  saveConfig({ ...rest, dataDir });
5314
5405
  return base;
5315
5406
  }
5316
- const stored = JSON.parse(readFileSync3(file, "utf8"));
5407
+ const raw = JSON.parse(readFileSync4(file, "utf8"));
5408
+ const opened = unsealSecrets(raw, dataDir);
5409
+ const stored = opened.value;
5410
+ if (opened.lost.length) console.warn(`[friend] These saved keys could not be decrypted (wrong or missing secret.key / FRIEND_SECRET_KEY) and were left empty: ${opened.lost.join(", ")}. Enter them again in Settings.`);
5411
+ else if (sealSecrets(raw, dataDir).changed) saveConfig({ ...stored, dataDir });
5317
5412
  const destructivePatterns = [.../* @__PURE__ */ new Set([...base.destructivePatterns, ...stored.destructivePatterns ?? []])];
5318
5413
  return {
5319
5414
  ...base,
@@ -5735,8 +5830,8 @@ function integrationSummary(views) {
5735
5830
 
5736
5831
  // ../server/src/plugins.ts
5737
5832
  import { randomUUID } from "node:crypto";
5738
- import { cpSync, existsSync as existsSync4, lstatSync as lstatSync2, mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, rmSync as rmSync4 } from "node:fs";
5739
- import { join as join5, relative, resolve } from "node:path";
5833
+ import { cpSync, existsSync as existsSync5, lstatSync as lstatSync2, mkdirSync as mkdirSync6, readdirSync as readdirSync3, readFileSync as readFileSync5, renameSync as renameSync2, rmSync as rmSync4 } from "node:fs";
5834
+ import { join as join6, relative, resolve } from "node:path";
5740
5835
  import { z as z9 } from "zod";
5741
5836
  var MAX_SKILL_BYTES = 20 * 1024;
5742
5837
  var MAX_TOOL_BYTES = 50 * 1024;
@@ -5779,13 +5874,13 @@ function safeRelative(file) {
5779
5874
  function scan(dir) {
5780
5875
  let files = 0;
5781
5876
  let bytes2 = 0;
5782
- const walk2 = (d) => {
5877
+ const walk3 = (d) => {
5783
5878
  for (const entry of readdirSync3(d)) {
5784
- const full = join5(d, entry);
5879
+ const full = join6(d, entry);
5785
5880
  const st = lstatSync2(full);
5786
5881
  if (st.isSymbolicLink()) return `The plugin contains a link (${entry}), which is not allowed.`;
5787
5882
  if (st.isDirectory()) {
5788
- const err2 = walk2(full);
5883
+ const err2 = walk3(full);
5789
5884
  if (err2) return err2;
5790
5885
  } else if (st.isFile()) {
5791
5886
  files++;
@@ -5798,7 +5893,7 @@ function scan(dir) {
5798
5893
  }
5799
5894
  return null;
5800
5895
  };
5801
- const err = walk2(dir);
5896
+ const err = walk3(dir);
5802
5897
  return err ?? { files, bytes: bytes2 };
5803
5898
  }
5804
5899
  function readInside(dir, file, limit) {
@@ -5806,20 +5901,20 @@ function readInside(dir, file, limit) {
5806
5901
  if (!parts) return { ok: false, error: `"${file}" must be a file inside the plugin folder.` };
5807
5902
  const full = resolve(dir, ...parts);
5808
5903
  if (relative(resolve(dir), full).startsWith("..")) return { ok: false, error: `"${file}" must be a file inside the plugin folder.` };
5809
- if (!existsSync4(full) || !lstatSync2(full).isFile()) return { ok: false, error: `The file "${file}" does not exist.` };
5904
+ if (!existsSync5(full) || !lstatSync2(full).isFile()) return { ok: false, error: `The file "${file}" does not exist.` };
5810
5905
  if (lstatSync2(full).size > limit) return { ok: false, error: `"${file}" is too large (limit ${limit / 1024} KB).` };
5811
- return { ok: true, text: readFileSync4(full, "utf8") };
5906
+ return { ok: true, text: readFileSync5(full, "utf8") };
5812
5907
  }
5813
5908
  function inspectPlugin(dir) {
5814
- if (!existsSync4(dir) || !lstatSync2(dir).isDirectory()) return { ok: false, error: "That plugin folder does not exist." };
5909
+ if (!existsSync5(dir) || !lstatSync2(dir).isDirectory()) return { ok: false, error: "That plugin folder does not exist." };
5815
5910
  const counted = scan(dir);
5816
5911
  if (typeof counted === "string") return { ok: false, error: counted };
5817
- const manifestPath = join5(dir, "plugin.json");
5818
- if (!existsSync4(manifestPath)) return { ok: false, error: "plugin.json is missing." };
5912
+ const manifestPath = join6(dir, "plugin.json");
5913
+ if (!existsSync5(manifestPath)) return { ok: false, error: "plugin.json is missing." };
5819
5914
  if (lstatSync2(manifestPath).size > MAX_MANIFEST_BYTES) return { ok: false, error: "plugin.json is too large." };
5820
5915
  let raw;
5821
5916
  try {
5822
- raw = JSON.parse(readFileSync4(manifestPath, "utf8"));
5917
+ raw = JSON.parse(readFileSync5(manifestPath, "utf8"));
5823
5918
  } catch {
5824
5919
  return { ok: false, error: "plugin.json is not valid JSON." };
5825
5920
  }
@@ -5876,9 +5971,9 @@ function toolDef(m, t, code) {
5876
5971
  }
5877
5972
  var isPluginId = (id2) => id2.length >= 1 && id2.length <= 40 && NAME.test(id2);
5878
5973
  function listCatalog(dir) {
5879
- if (!existsSync4(dir)) return [];
5880
- return readdirSync3(dir).filter((d) => isPluginId(d) && lstatSync2(join5(dir, d)).isDirectory()).sort().map((id2) => {
5881
- const r = inspectPlugin(join5(dir, id2));
5974
+ if (!existsSync5(dir)) return [];
5975
+ return readdirSync3(dir).filter((d) => isPluginId(d) && lstatSync2(join6(dir, d)).isDirectory()).sort().map((id2) => {
5976
+ const r = inspectPlugin(join6(dir, id2));
5882
5977
  if (!r.ok) return { id: id2, name: id2, version: "", description: "", tools: 0, skills: 0, error: r.error };
5883
5978
  const m = r.manifest;
5884
5979
  return { id: id2, name: m.name, version: m.version, description: m.description, tools: m.tools.length, skills: m.skills.length, error: null };
@@ -5901,12 +5996,12 @@ var Plugins = class {
5901
5996
  const r = inspectPlugin(srcDir);
5902
5997
  if (!r.ok) return r;
5903
5998
  const id2 = r.manifest.id;
5904
- mkdirSync5(this.root, { recursive: true });
5905
- const staging = join5(this.root, `.tmp-${randomUUID()}`);
5999
+ mkdirSync6(this.root, { recursive: true });
6000
+ const staging = join6(this.root, `.tmp-${randomUUID()}`);
5906
6001
  try {
5907
6002
  cpSync(srcDir, staging, { recursive: true, dereference: false });
5908
- const dest = join5(this.root, id2);
5909
- const upgraded = existsSync4(dest);
6003
+ const dest = join6(this.root, id2);
6004
+ const upgraded = existsSync5(dest);
5910
6005
  rmSync4(dest, { recursive: true, force: true });
5911
6006
  renameSync2(staging, dest);
5912
6007
  this.db.prepare("insert into plugins (id, enabled, installed_at) values (?, 1, ?) on conflict(id) do update set installed_at = excluded.installed_at").run(id2, this.clock());
@@ -5926,8 +6021,8 @@ var Plugins = class {
5926
6021
  this.cache ??= /* @__PURE__ */ new Map();
5927
6022
  let hit = this.cache.get(id2);
5928
6023
  if (!hit) {
5929
- const dir = join5(this.root, id2);
5930
- hit = existsSync4(dir) ? inspectPlugin(dir) : { ok: false, error: "The plugin files are missing." };
6024
+ const dir = join6(this.root, id2);
6025
+ hit = existsSync5(dir) ? inspectPlugin(dir) : { ok: false, error: "The plugin files are missing." };
5931
6026
  this.cache.set(id2, hit);
5932
6027
  }
5933
6028
  return hit;
@@ -5954,7 +6049,7 @@ var Plugins = class {
5954
6049
  }
5955
6050
  remove(id2) {
5956
6051
  const had = this.db.prepare("delete from plugins where id = ?").run(id2).changes > 0;
5957
- if (NAME.test(id2)) rmSync4(join5(this.root, id2), { recursive: true, force: true });
6052
+ if (NAME.test(id2)) rmSync4(join6(this.root, id2), { recursive: true, force: true });
5958
6053
  this.cache = null;
5959
6054
  return had;
5960
6055
  }
@@ -6087,7 +6182,7 @@ ${steps}
6087
6182
  return list2.length ? list2.map((p) => `${p.id}: ${p.name} ${p.version}, ${p.enabled ? "on" : "off"}${p.error ? ` (cannot be used: ${p.error})` : ""}, ${p.skills.length} skills [${p.skills.map((s) => s.name).join(", ")}], ${p.tools.length} tools [${p.tools.map((t) => t.name).join(", ")}]`).join("\n") : "No plugins installed.";
6088
6183
  }
6089
6184
  case "plugins.create": {
6090
- const r = authorPlugin(d.plugins, join6(d.dataDir, "drafts"), args);
6185
+ const r = authorPlugin(d.plugins, join7(d.dataDir, "drafts"), args);
6091
6186
  if (!r.ok) throw new Error(`The plugin was not created: ${r.error}`);
6092
6187
  d.audit("plugins.create", { id: r.id, upgraded: r.upgraded, skills: r.skills, tools: r.tools });
6093
6188
  return `${r.upgraded ? "Updated" : "Created"} the plugin ${r.id} and switched it on: ${r.skills} skills, ${r.tools} tools. ${r.skills ? "Load a skill with skill.use. " : ""}${r.tools ? `Its tools are plugin.${r.id}.<tool> (each call asks the owner).` : ""}`.trim();
@@ -6120,10 +6215,10 @@ ${steps}
6120
6215
  }
6121
6216
 
6122
6217
  // ../server/src/assets.ts
6123
- import { existsSync as existsSync5 } from "node:fs";
6124
- import { join as join7 } from "node:path";
6218
+ import { existsSync as existsSync6 } from "node:fs";
6219
+ import { join as join8 } from "node:path";
6125
6220
  function firstExistingDir(candidates, mustContain) {
6126
- return candidates.find((c) => !!c && existsSync5(mustContain ? join7(c, mustContain) : c));
6221
+ return candidates.find((c) => !!c && existsSync6(mustContain ? join8(c, mustContain) : c));
6127
6222
  }
6128
6223
 
6129
6224
  // ../server/src/chatlog.ts
@@ -6158,8 +6253,8 @@ import crossSpawn from "cross-spawn";
6158
6253
  import { createHash as createHash3 } from "node:crypto";
6159
6254
 
6160
6255
  // ../server/src/connectors/store.ts
6161
- import { chmodSync as chmodSync2, existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync5, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "node:fs";
6162
- import { dirname as dirname2, join as join8 } from "node:path";
6256
+ import { chmodSync as chmodSync3, existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync6, renameSync as renameSync3, writeFileSync as writeFileSync6 } from "node:fs";
6257
+ import { dirname as dirname2, join as join9 } from "node:path";
6163
6258
  import { z as z10 } from "zod";
6164
6259
  var CONNECTOR_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
6165
6260
  var MAX_CONNECTORS = 20;
@@ -6197,14 +6292,14 @@ var ConnectorStore = class {
6197
6292
  path;
6198
6293
  items;
6199
6294
  constructor(dataDir) {
6200
- this.path = join8(dataDir, "connectors.json");
6295
+ this.path = join9(dataDir, "connectors.json");
6201
6296
  this.items = this.load();
6202
6297
  }
6203
6298
  load() {
6204
- if (!existsSync6(this.path)) return [];
6299
+ if (!existsSync7(this.path)) return [];
6205
6300
  let raw;
6206
6301
  try {
6207
- raw = JSON.parse(readFileSync5(this.path, "utf8"));
6302
+ raw = JSON.parse(readFileSync6(this.path, "utf8"));
6208
6303
  } catch {
6209
6304
  return [];
6210
6305
  }
@@ -6219,11 +6314,11 @@ var ConnectorStore = class {
6219
6314
  return out.slice(0, MAX_CONNECTORS);
6220
6315
  }
6221
6316
  save() {
6222
- mkdirSync6(dirname2(this.path), { recursive: true });
6317
+ mkdirSync7(dirname2(this.path), { recursive: true });
6223
6318
  const tmp = `${this.path}.tmp`;
6224
- writeFileSync5(tmp, JSON.stringify(this.items, null, 2));
6319
+ writeFileSync6(tmp, JSON.stringify(this.items, null, 2));
6225
6320
  try {
6226
- chmodSync2(tmp, 384);
6321
+ chmodSync3(tmp, 384);
6227
6322
  } catch {
6228
6323
  }
6229
6324
  renameSync3(tmp, this.path);
@@ -6556,9 +6651,9 @@ var PRESETS = [
6556
6651
  ];
6557
6652
 
6558
6653
  // ../server/src/connectors/quick.ts
6559
- import { existsSync as existsSync7 } from "node:fs";
6654
+ import { existsSync as existsSync8 } from "node:fs";
6560
6655
  import { homedir as homedir2 } from "node:os";
6561
- import { join as join9 } from "node:path";
6656
+ import { join as join10 } from "node:path";
6562
6657
  var find = (id2) => PRESETS.find((p) => p.id === id2 && p.quick);
6563
6658
  var isQuickPreset = (id2) => !!find(id2);
6564
6659
  function programFor(preset, bundled) {
@@ -6566,12 +6661,12 @@ function programFor(preset, bundled) {
6566
6661
  }
6567
6662
  var MANUAL_EXTENSION = "One step only you can do, because Chrome does not allow programs to install extensions silently: open chrome://extensions, turn on Developer mode (top right), click Load unpacked and choose the folder shown above. Then click the extension's icon and switch it on.";
6568
6663
  function chromeFolder(home) {
6569
- return join9(home, ".chrome-control-mcp");
6664
+ return join10(home, ".chrome-control-mcp");
6570
6665
  }
6571
6666
  function chromeInstalled(home = homedir2()) {
6572
6667
  const base = chromeFolder(home);
6573
- const ext = join9(base, "extension");
6574
- const installed = existsSync7(join9(base, "token")) && existsSync7(join9(ext, "manifest.json")) && existsSync7(join9(base, "native-host"));
6668
+ const ext = join10(base, "extension");
6669
+ const installed = existsSync8(join10(base, "token")) && existsSync8(join10(ext, "manifest.json")) && existsSync8(join10(base, "native-host"));
6575
6670
  return { installed, extensionFolder: installed ? ext : null };
6576
6671
  }
6577
6672
  function quickCheck(id2, deps = {}) {
@@ -6650,14 +6745,14 @@ async function quickConnect(id2, deps) {
6650
6745
  }
6651
6746
 
6652
6747
  // ../server/src/connectors/chromePlugin.ts
6653
- import { existsSync as existsSync8 } from "node:fs";
6748
+ import { existsSync as existsSync9 } from "node:fs";
6654
6749
  import { dirname as dirname3, resolve as resolve2 } from "node:path";
6655
6750
  import { fileURLToPath } from "node:url";
6656
6751
  var here = dirname3(fileURLToPath(import.meta.url));
6657
6752
  var ID = "chrome";
6658
6753
  function bundledChromeControl() {
6659
6754
  const candidates = [process.env.FRIEND_CHROME_CONTROL, resolve2(here, "chrome-control/dist/index.js"), resolve2(here, "../../../chrome-control/dist/index.js")];
6660
- for (const c of candidates) if (c && existsSync8(c)) return c;
6755
+ for (const c of candidates) if (c && existsSync9(c)) return c;
6661
6756
  return null;
6662
6757
  }
6663
6758
  var ChromePlugin = class {
@@ -6806,15 +6901,15 @@ var ChromePlugin = class {
6806
6901
  };
6807
6902
 
6808
6903
  // ../server/src/connectors/chromeRemote.ts
6809
- import { existsSync as existsSync9, readFileSync as readFileSync6 } from "node:fs";
6904
+ import { existsSync as existsSync10, readFileSync as readFileSync7 } from "node:fs";
6810
6905
  import { createHash as createHash4, timingSafeEqual } from "node:crypto";
6811
6906
  import { request } from "node:http";
6812
6907
  import { homedir as homedir3 } from "node:os";
6813
- import { dirname as dirname4, join as join10, resolve as resolve3 } from "node:path";
6908
+ import { dirname as dirname4, join as join11, resolve as resolve3 } from "node:path";
6814
6909
  import { WebSocket } from "ws";
6815
6910
  function chromeToken(home = homedir3()) {
6816
6911
  try {
6817
- const t = readFileSync6(join10(home, ".chrome-control-mcp", "token"), "utf8").trim();
6912
+ const t = readFileSync7(join11(home, ".chrome-control-mcp", "token"), "utf8").trim();
6818
6913
  return t || null;
6819
6914
  } catch {
6820
6915
  return null;
@@ -6831,7 +6926,7 @@ function keyFromRequest(headers, search) {
6831
6926
  function bundledExtensionDir(bundledIndex) {
6832
6927
  if (!bundledIndex) return null;
6833
6928
  const dir = resolve3(dirname4(bundledIndex), "..", "extension");
6834
- return existsSync9(join10(dir, "manifest.json")) ? dir : null;
6929
+ return existsSync10(join11(dir, "manifest.json")) ? dir : null;
6835
6930
  }
6836
6931
  function chromeAddresses(origin) {
6837
6932
  const url = new URL(origin);
@@ -6906,8 +7001,8 @@ function relayExtension(client, up) {
6906
7001
  }
6907
7002
 
6908
7003
  // ../server/src/zip.ts
6909
- import { readdirSync as readdirSync4, readFileSync as readFileSync7, statSync } from "node:fs";
6910
- import { join as join11 } from "node:path";
7004
+ import { readdirSync as readdirSync4, readFileSync as readFileSync8, statSync } from "node:fs";
7005
+ import { join as join12 } from "node:path";
6911
7006
  import { deflateRawSync } from "node:zlib";
6912
7007
  var TABLE = (() => {
6913
7008
  const t = new Uint32Array(256);
@@ -6926,17 +7021,17 @@ function crc32(data2) {
6926
7021
  var SKIP = /* @__PURE__ */ new Set(["node_modules", ".git"]);
6927
7022
  var MAX_FILES2 = 500;
6928
7023
  var MAX_BYTES = 2e7;
6929
- function walk(dir, prefix, out) {
7024
+ function walk2(dir, prefix, out) {
6930
7025
  for (const e of readdirSync4(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
6931
7026
  if (SKIP.has(e.name)) continue;
6932
- const path3 = join11(dir, e.name);
6933
- if (e.isDirectory()) walk(path3, `${prefix}${e.name}/`, out);
7027
+ const path3 = join12(dir, e.name);
7028
+ if (e.isDirectory()) walk2(path3, `${prefix}${e.name}/`, out);
6934
7029
  else if (e.isFile()) out.push({ name: `${prefix}${e.name}`, path: path3 });
6935
7030
  }
6936
7031
  }
6937
7032
  function zipDirectory(dir, folder) {
6938
7033
  const files = [];
6939
- walk(dir, `${folder}/`, files);
7034
+ walk2(dir, `${folder}/`, files);
6940
7035
  if (files.length > MAX_FILES2) throw new Error("That folder has too many files to zip.");
6941
7036
  const parts = [];
6942
7037
  const central = [];
@@ -6945,7 +7040,7 @@ function zipDirectory(dir, folder) {
6945
7040
  const time = 0;
6946
7041
  const date = 2020 - 1980 << 9 | 1 << 5 | 1;
6947
7042
  for (const f of files) {
6948
- const data2 = readFileSync7(f.path);
7043
+ const data2 = readFileSync8(f.path);
6949
7044
  total += data2.length;
6950
7045
  if (total > MAX_BYTES || statSync(f.path).size > MAX_BYTES) throw new Error("That folder is too big to zip.");
6951
7046
  const packed = deflateRawSync(data2);
@@ -6995,7 +7090,7 @@ function zipDirectory(dir, folder) {
6995
7090
 
6996
7091
  // ../server/src/music/mpv.ts
6997
7092
  import { spawn as nodeSpawn } from "node:child_process";
6998
- import { existsSync as existsSync10, rmSync as rmSync5 } from "node:fs";
7093
+ import { existsSync as existsSync11, rmSync as rmSync5 } from "node:fs";
6999
7094
  import net from "node:net";
7000
7095
  import { tmpdir } from "node:os";
7001
7096
  import path from "node:path";
@@ -7048,7 +7143,7 @@ function places(platform, env) {
7048
7143
  async function findMpv(d) {
7049
7144
  const platform = d.platform ?? process.platform;
7050
7145
  const env = d.env ?? process.env;
7051
- const exists2 = d.exists ?? existsSync10;
7146
+ const exists2 = d.exists ?? existsSync11;
7052
7147
  const run2 = d.run ?? defaultRun;
7053
7148
  const versionOf = async (p) => {
7054
7149
  const r = await run2(p, ["--version"]);
@@ -7359,12 +7454,12 @@ async function openInBrowser(url, d = {}) {
7359
7454
 
7360
7455
  // ../server/src/video/provision.ts
7361
7456
  import { spawn as spawn2 } from "node:child_process";
7362
- import { createHash as createHash5, randomBytes } from "node:crypto";
7363
- import { chmodSync as chmodSync3, createReadStream, createWriteStream, existsSync as existsSync11, mkdirSync as mkdirSync7, readdirSync as readdirSync5, renameSync as renameSync4, rmSync as rmSync6, copyFileSync, statSync as statSync2, utimesSync, writeFileSync as writeFileSync6 } from "node:fs";
7364
- import { open } from "node:fs/promises";
7457
+ import { createHash as createHash5, randomBytes as randomBytes2 } from "node:crypto";
7458
+ import { chmodSync as chmodSync4, createReadStream, createWriteStream, existsSync as existsSync12, mkdirSync as mkdirSync8, readdirSync as readdirSync5, renameSync as renameSync4, rmSync as rmSync6, copyFileSync, statSync as statSync2, utimesSync, writeFileSync as writeFileSync7 } from "node:fs";
7459
+ import { open as open2 } from "node:fs/promises";
7365
7460
  import { createInflateRaw } from "node:zlib";
7366
7461
  import { pipeline } from "node:stream/promises";
7367
- import { join as join12 } from "node:path";
7462
+ import { join as join13 } from "node:path";
7368
7463
 
7369
7464
  // ../server/src/video/resolve.ts
7370
7465
  import { spawn } from "node:child_process";
@@ -7781,7 +7876,7 @@ var MAX_HOPS2 = 5;
7781
7876
  var hostOk = (host2) => ALLOWED_HOSTS.some((h) => host2 === h || host2.endsWith(`.${h}`));
7782
7877
  var zipExtract = async (archive, plan, dest) => {
7783
7878
  const want = `/${(plan.inside ?? plan.file).replace(/\\/g, "/")}`;
7784
- const fh = await open(archive, "r");
7879
+ const fh = await open2(archive, "r");
7785
7880
  try {
7786
7881
  const size = (await fh.stat()).size;
7787
7882
  const tailLen = Math.min(size, 65557);
@@ -7823,8 +7918,8 @@ var zipExtract = async (archive, plan, dest) => {
7823
7918
  }
7824
7919
  };
7825
7920
  var tarExtract = (archive, plan, dest) => new Promise((resolve13, reject) => {
7826
- const tmp = `${dest}.extract-${randomBytes(4).toString("hex")}`;
7827
- mkdirSync7(tmp, { recursive: true });
7921
+ const tmp = `${dest}.extract-${randomBytes2(4).toString("hex")}`;
7922
+ mkdirSync8(tmp, { recursive: true });
7828
7923
  const done = (err) => {
7829
7924
  if (!err) {
7830
7925
  try {
@@ -7849,17 +7944,17 @@ var tarExtract = (archive, plan, dest) => new Promise((resolve13, reject) => {
7849
7944
  });
7850
7945
  function findInside(root, inside) {
7851
7946
  const want = `/${inside.replace(/\\/g, "/")}`;
7852
- const walk2 = (dir) => {
7947
+ const walk3 = (dir) => {
7853
7948
  for (const e of readdirSync5(dir, { withFileTypes: true })) {
7854
- const p = join12(dir, e.name);
7949
+ const p = join13(dir, e.name);
7855
7950
  if (e.isDirectory()) {
7856
- const r = walk2(p);
7951
+ const r = walk3(p);
7857
7952
  if (r) return r;
7858
7953
  } else if (`/${p.slice(root.length).replace(/\\/g, "/").replace(/^\//, "")}`.endsWith(want) || !inside.includes("/") && e.name === inside) return p;
7859
7954
  }
7860
7955
  return null;
7861
7956
  };
7862
- return walk2(root);
7957
+ return walk3(root);
7863
7958
  }
7864
7959
  function checksumFor(list2, name) {
7865
7960
  const lines = list2.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
@@ -7894,20 +7989,20 @@ var Provisioner = class {
7894
7989
  */
7895
7990
  async update() {
7896
7991
  const file = managedPath(this.d.dataDir, "yt-dlp", this.platform);
7897
- if (!existsSync11(file)) return;
7898
- const stamp = join12(this.d.dataDir, "tools", ".yt-dlp-updated");
7992
+ if (!existsSync12(file)) return;
7993
+ const stamp = join13(this.d.dataDir, "tools", ".yt-dlp-updated");
7899
7994
  const now = (this.d.now ?? Date.now)();
7900
7995
  const WEEK = 7 * 24 * 3600 * 1e3;
7901
- if (existsSync11(stamp) && now - statSync2(stamp).mtimeMs < WEEK) return;
7996
+ if (existsSync12(stamp) && now - statSync2(stamp).mtimeMs < WEEK) return;
7902
7997
  try {
7903
- writeFileSync6(stamp, "");
7998
+ writeFileSync7(stamp, "");
7904
7999
  utimesSync(stamp, now / 1e3, now / 1e3);
7905
8000
  await (this.d.run ?? ytRun)(file, ["-U"], { timeoutMs: 12e4, maxBytes: 1e5 });
7906
8001
  } catch {
7907
8002
  }
7908
8003
  }
7909
8004
  has(name) {
7910
- return existsSync11(managedPath(this.d.dataDir, name, this.platform));
8005
+ return existsSync12(managedPath(this.d.dataDir, name, this.platform));
7911
8006
  }
7912
8007
  async ensure(names) {
7913
8008
  while (this.running) await this.running.catch(() => {
@@ -7938,9 +8033,9 @@ var Provisioner = class {
7938
8033
  return { ok: false, error };
7939
8034
  };
7940
8035
  if (!plan) return fail3(`Friend cannot set up ${name} on this system by itself. Install it with your package manager, then press Check again.`);
7941
- const tools = join12(this.d.dataDir, "tools");
7942
- mkdirSync7(tools, { recursive: true });
7943
- const part = join12(tools, `.download-${name}-${randomBytes(4).toString("hex")}`);
8036
+ const tools = join13(this.d.dataDir, "tools");
8037
+ mkdirSync8(tools, { recursive: true });
8038
+ const part = join13(tools, `.download-${name}-${randomBytes2(4).toString("hex")}`);
7944
8039
  const final = managedPath(this.d.dataDir, name, this.platform);
7945
8040
  try {
7946
8041
  this.set(name, { phase: "downloading", percent: null });
@@ -7969,7 +8064,7 @@ var Provisioner = class {
7969
8064
  return fail3(`Friend could not unpack ${name}. Install it with your package manager, then press Check again.`);
7970
8065
  }
7971
8066
  }
7972
- if (this.platform !== "win32") chmodSync3(final, 493);
8067
+ if (this.platform !== "win32") chmodSync4(final, 493);
7973
8068
  this.set(name, { phase: "ready" });
7974
8069
  return { ok: true };
7975
8070
  } catch (e) {
@@ -8055,13 +8150,13 @@ var Provisioner = class {
8055
8150
  out.destroy();
8056
8151
  return { error: "failed", why: e.message };
8057
8152
  }
8058
- if (!existsSync11(dest) || statSync2(dest).size === 0) return { error: "failed", why: "empty download" };
8153
+ if (!existsSync12(dest) || statSync2(dest).size === 0) return { error: "failed", why: "empty download" };
8059
8154
  return { sha: hash.digest("hex") };
8060
8155
  }
8061
8156
  };
8062
8157
 
8063
8158
  // ../server/src/video/hub.ts
8064
- import { randomBytes as randomBytes2 } from "node:crypto";
8159
+ import { randomBytes as randomBytes3 } from "node:crypto";
8065
8160
 
8066
8161
  // ../server/src/video/stream.ts
8067
8162
  import { spawn as nodeSpawn3 } from "node:child_process";
@@ -8130,7 +8225,7 @@ function startStream(ffmpeg, info, o, d = {}) {
8130
8225
 
8131
8226
  // ../server/src/video/tools.ts
8132
8227
  import { spawn as spawn3 } from "node:child_process";
8133
- import { existsSync as existsSync12 } from "node:fs";
8228
+ import { existsSync as existsSync13 } from "node:fs";
8134
8229
  import path2 from "node:path";
8135
8230
  var INSTALL2 = {
8136
8231
  "yt-dlp": {
@@ -8197,7 +8292,7 @@ var versionOfOutput = (name, out) => {
8197
8292
  async function findHelper(name, d) {
8198
8293
  const platform = d.platform ?? process.platform;
8199
8294
  const env = d.env ?? process.env;
8200
- const exists2 = d.exists ?? existsSync12;
8295
+ const exists2 = d.exists ?? existsSync13;
8201
8296
  const run2 = d.run ?? defaultRun2;
8202
8297
  const isPath = (p) => /[\\/]/.test(p);
8203
8298
  const tryOne = async (p) => {
@@ -8376,7 +8471,7 @@ var VideoHub = class {
8376
8471
  const now = this.clock();
8377
8472
  for (const [id3, t] of this.tokens) if (t.expires <= now) this.tokens.delete(id3);
8378
8473
  while (this.tokens.size >= MAX_TOKENS) this.tokens.delete(this.tokens.keys().next().value);
8379
- const id2 = randomBytes2(16).toString("hex");
8474
+ const id2 = randomBytes3(16).toString("hex");
8380
8475
  this.tokens.set(id2, { info, startSec, expires: now + TTL_MS });
8381
8476
  return { id: CARD, props: { title: info.title, src: `/api/video/${id2}` } };
8382
8477
  }
@@ -8459,7 +8554,7 @@ var VideoHub = class {
8459
8554
  if (browserWindow) {
8460
8555
  const show3 = this.issue(info, start2);
8461
8556
  const id2 = /\/api\/video\/([0-9a-f]{32})$/.exec(show3.props.src)[1];
8462
- const ticket = randomBytes2(16).toString("hex");
8557
+ const ticket = randomBytes3(16).toString("hex");
8463
8558
  this.tickets.set(ticket, { id: id2, expires: this.clock() + TICKET_MS });
8464
8559
  const ok2 = await this.d.openBrowser(this.d.windowUrl(id2, ticket)).catch(() => false);
8465
8560
  if (!ok2) return { ok: false, text: "Friend could not open a browser window on this PC." };
@@ -8598,9 +8693,9 @@ import { randomUUID as randomUUID2 } from "node:crypto";
8598
8693
 
8599
8694
  // ../server/src/auditContext.ts
8600
8695
  import { AsyncLocalStorage } from "node:async_hooks";
8601
- import { randomBytes as randomBytes3 } from "node:crypto";
8696
+ import { randomBytes as randomBytes4 } from "node:crypto";
8602
8697
  var store = new AsyncLocalStorage();
8603
- var newRequestId = (prefix) => `${prefix}-${randomBytes3(4).toString("hex")}`;
8698
+ var newRequestId = (prefix) => `${prefix}-${randomBytes4(4).toString("hex")}`;
8604
8699
  function runWithRequest(ctx, fn) {
8605
8700
  const outer = store.getStore();
8606
8701
  const next = {
@@ -8619,7 +8714,7 @@ function ensureRequest(prefix, fn) {
8619
8714
  }
8620
8715
 
8621
8716
  // ../server/src/auth.ts
8622
- import { createHash as createHash6, randomBytes as randomBytes4, scrypt, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
8717
+ import { createHash as createHash6, randomBytes as randomBytes5, scrypt, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
8623
8718
 
8624
8719
  // ../server/src/ratelimit.ts
8625
8720
  var LockoutError = class extends Error {
@@ -8674,23 +8769,37 @@ var SESSION_TTL_MS = 7 * 24 * 3600 * 1e3;
8674
8769
  var LOGIN_TRIES = 3;
8675
8770
  var PAIR_TTL_MS = 5 * 60 * 1e3;
8676
8771
  var sha256 = (s) => createHash6("sha256").update(s).digest("hex");
8677
- function scryptAsync(secret, salt) {
8772
+ var SCRYPT_N = 131072;
8773
+ var LEGACY_N = 16384;
8774
+ var cost = SCRYPT_N;
8775
+ function scryptAsync(secret, salt, N) {
8678
8776
  return new Promise(
8679
- (res, rej) => scrypt(secret, salt, 64, { N: 16384, r: 8, p: 1 }, (err, key2) => err ? rej(err) : res(key2))
8777
+ (res, rej) => scrypt(secret, salt, 64, { N, r: 8, p: 1, maxmem: 256 * 1024 * 1024 }, (err, key2) => err ? rej(err) : res(key2))
8680
8778
  );
8681
8779
  }
8682
8780
  async function hashSecret(secret) {
8683
- const salt = randomBytes4(16);
8684
- const key2 = await scryptAsync(secret, salt);
8685
- return `scrypt$${salt.toString("hex")}$${key2.toString("hex")}`;
8781
+ const salt = randomBytes5(16);
8782
+ const key2 = await scryptAsync(secret, salt, cost);
8783
+ return `scrypt2$${cost}$${salt.toString("hex")}$${key2.toString("hex")}`;
8686
8784
  }
8687
8785
  async function verifySecret(secret, stored) {
8688
- const [alg, saltHex, keyHex] = stored.split("$");
8689
- if (alg !== "scrypt" || !saltHex || !keyHex) return false;
8786
+ const parts = stored.split("$");
8787
+ let N;
8788
+ let saltHex;
8789
+ let keyHex;
8790
+ if (parts[0] === "scrypt" && parts.length === 3) {
8791
+ N = LEGACY_N;
8792
+ [, saltHex, keyHex] = parts;
8793
+ } else if (parts[0] === "scrypt2" && parts.length === 4 && (Number(parts[1]) === SCRYPT_N || Number(parts[1]) === cost)) {
8794
+ N = Number(parts[1]);
8795
+ [, , saltHex, keyHex] = parts;
8796
+ } else return false;
8797
+ if (!saltHex || !keyHex) return false;
8690
8798
  const expected = Buffer.from(keyHex, "hex");
8691
- const actual = await scryptAsync(secret, Buffer.from(saltHex, "hex"));
8799
+ const actual = await scryptAsync(secret, Buffer.from(saltHex, "hex"), N);
8692
8800
  return expected.length === actual.length && timingSafeEqual2(expected, actual);
8693
8801
  }
8802
+ var outdated = (stored) => !stored.startsWith(`scrypt2$${cost}$`);
8694
8803
  var Auth = class _Auth {
8695
8804
  constructor(db, audit, clock2 = Date.now) {
8696
8805
  this.db = db;
@@ -8745,7 +8854,8 @@ var Auth = class _Auth {
8745
8854
  throw new Error("Invalid credentials");
8746
8855
  }
8747
8856
  succeeded();
8748
- const token = randomBytes4(32).toString("hex");
8857
+ if (row2 && outdated(row2.h)) this.db.prepare("update owner set password_hash = ? where id = 1").run(await hashSecret(password));
8858
+ const token = randomBytes5(32).toString("hex");
8749
8859
  const expiresAt = this.clock() + SESSION_TTL_MS;
8750
8860
  this.db.prepare("insert into sessions (token_hash, kind, expires_at, ip) values (?, 'web', ?, ?)").run(sha256(token), expiresAt, ip);
8751
8861
  this.audit.log("owner", "login.ok", { ip });
@@ -8772,8 +8882,10 @@ var Auth = class _Auth {
8772
8882
  const succeeded = this.begin("pin", ip);
8773
8883
  const row2 = this.db.prepare("select pin_hash h from owner where id = 1").get();
8774
8884
  const ok2 = row2 ? await verifySecret(pin, row2.h) : false;
8775
- if (ok2) succeeded();
8776
- else this.audit.log("owner", "pin.fail", { ip });
8885
+ if (ok2) {
8886
+ succeeded();
8887
+ if (row2 && outdated(row2.h)) this.db.prepare("update owner set pin_hash = ? where id = 1").run(await hashSecret(pin));
8888
+ } else this.audit.log("owner", "pin.fail", { ip });
8777
8889
  return ok2;
8778
8890
  }
8779
8891
  /** Checks a new password and/or PIN the same way setup does. Returns the problem, or null when both are fine. */
@@ -8819,7 +8931,7 @@ var Auth = class _Auth {
8819
8931
  this.audit.log("system", "secrets.reset", { password: input.newPassword !== void 0, pin: input.newPin !== void 0 });
8820
8932
  }
8821
8933
  createPairCode() {
8822
- const code = randomBytes4(5).toString("hex").toUpperCase();
8934
+ const code = randomBytes5(5).toString("hex").toUpperCase();
8823
8935
  this.db.prepare("insert into pair_codes (code_hash, expires_at) values (?, ?)").run(sha256(code), this.clock() + PAIR_TTL_MS);
8824
8936
  return code;
8825
8937
  }
@@ -8831,7 +8943,7 @@ var Auth = class _Auth {
8831
8943
  this.audit.log("device", "pair.fail", { deviceName });
8832
8944
  throw new Error("Invalid or expired pairing code");
8833
8945
  }
8834
- const token = randomBytes4(32).toString("hex");
8946
+ const token = randomBytes5(32).toString("hex");
8835
8947
  this.db.prepare("insert into devices (name, token_hash, last_seen) values (?, ?, ?)").run(deviceName, sha256(token), this.clock());
8836
8948
  this.audit.log("device", "pair.ok", { deviceName });
8837
8949
  return token;
@@ -9561,8 +9673,8 @@ var AuditQuery = class {
9561
9673
  };
9562
9674
 
9563
9675
  // ../server/src/auditRetention.ts
9564
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
9565
- import { join as join13 } from "node:path";
9676
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
9677
+ import { join as join14 } from "node:path";
9566
9678
  import { gzipSync } from "node:zlib";
9567
9679
  var DAY = 864e5;
9568
9680
  var APPEND_ONLY = "create trigger audit_no_delete before delete on audit_log begin select raise(abort, 'audit_log is append-only'); end;";
@@ -9580,9 +9692,9 @@ function pruneAudit(db, o) {
9580
9692
  let archivePath = null;
9581
9693
  if (o.archive) {
9582
9694
  const rows4 = db.prepare("select * from audit_log where id between ? and ? order by id").all(fromId, toId);
9583
- mkdirSync8(o.dir, { recursive: true });
9584
- archivePath = join13(o.dir, `audit-${fromId}-${toId}.jsonl.gz`);
9585
- writeFileSync7(archivePath, gzipSync(`${rows4.map((r) => JSON.stringify(r)).join("\n")}
9695
+ mkdirSync9(o.dir, { recursive: true });
9696
+ archivePath = join14(o.dir, `audit-${fromId}-${toId}.jsonl.gz`);
9697
+ writeFileSync8(archivePath, gzipSync(`${rows4.map((r) => JSON.stringify(r)).join("\n")}
9586
9698
  `));
9587
9699
  }
9588
9700
  const audit = new Audit(db);
@@ -10068,8 +10180,8 @@ function detectSetups(symbol, s) {
10068
10180
  if ((hi - last.c) / width <= NEAR && last.c <= hi) out.push({ symbol, kind: "orb-long", state: "near", at: null, ...plan(1, hi, mid), last: r2(last.c), rangeLow: r2(lo), rangeHigh: r2(hi), volumeRatio, score: 0 });
10069
10181
  else if ((last.c - lo) / width <= NEAR && last.c >= lo) out.push({ symbol, kind: "orb-short", state: "near", at: null, ...plan(-1, lo, mid), last: r2(last.c), rangeLow: r2(lo), rangeHigh: r2(hi), volumeRatio, score: 0 });
10070
10182
  }
10071
- const open2 = day2[0].o;
10072
- if (last.c <= open2 * (1 - BOUNCE_DROP) && last.c > last.o && last.v > avgVol) {
10183
+ const open3 = day2[0].o;
10184
+ if (last.c <= open3 * (1 - BOUNCE_DROP) && last.c > last.o && last.v > avgVol) {
10073
10185
  out.push({ symbol, kind: "bounce", state: "triggered", at: hhmm(last.t, s.offset), ...plan(1, last.c, last.l), last: r2(last.c), rangeLow: r2(lo), rangeHigh: r2(hi), volumeRatio, score: 0 });
10074
10186
  }
10075
10187
  for (const o of out) if (o.state === "triggered" && o.at && minutes(o.at) >= TOO_LATE_MINUTES) o.state = "late";
@@ -10307,7 +10419,7 @@ async function runMarketTool(name, args, d, signal) {
10307
10419
  }
10308
10420
 
10309
10421
  // ../server/src/media.ts
10310
- import { randomBytes as randomBytes5 } from "node:crypto";
10422
+ import { randomBytes as randomBytes6 } from "node:crypto";
10311
10423
  import { promises as fs } from "node:fs";
10312
10424
  import { basename, extname, isAbsolute, relative as relative2, resolve as resolve4, sep } from "node:path";
10313
10425
  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" };
@@ -10413,7 +10525,7 @@ var MediaStore = class {
10413
10525
  this.db.prepare("update media set mime = ?, size = ?, created_at = ? where id = ?").run(mime, size, this.clock(), existing.id);
10414
10526
  return existing.id;
10415
10527
  }
10416
- const id2 = randomBytes5(16).toString("hex");
10528
+ const id2 = randomBytes6(16).toString("hex");
10417
10529
  this.db.prepare("insert into media (id, path, mime, size, created_at) values (?, ?, ?, ?, ?)").run(id2, path3, mime, size, this.clock());
10418
10530
  return id2;
10419
10531
  }
@@ -10500,7 +10612,7 @@ var MediaStore = class {
10500
10612
 
10501
10613
  // ../server/src/channels/hub.ts
10502
10614
  import { promises as fsp } from "node:fs";
10503
- import { createHmac, randomBytes as randomBytes6, randomInt, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
10615
+ import { createHmac, randomBytes as randomBytes7, randomInt, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
10504
10616
  var CHANNEL_LABEL = { telegram: "Telegram", sms: "SMS", whatsapp: "WhatsApp" };
10505
10617
  var VoiceMessageError = class extends Error {
10506
10618
  };
@@ -10981,7 +11093,7 @@ ${reply}` : reply);
10981
11093
  const now = this.now();
10982
11094
  for (const [k, v] of this.outbox) if (v.expires <= now) this.outbox.delete(k);
10983
11095
  while (this.outbox.size >= OUTBOX_MAX) this.outbox.delete(this.outbox.keys().next().value);
10984
- const token = randomBytes6(16).toString("hex");
11096
+ const token = randomBytes7(16).toString("hex");
10985
11097
  this.outbox.set(token, { path: file.path, mime: file.mime, name: file.name, expires: now + OUTBOX_TTL_MS });
10986
11098
  return token;
10987
11099
  }
@@ -11835,9 +11947,9 @@ ${lines.join("\n")}${found.total > lines.length ? `
11835
11947
  };
11836
11948
 
11837
11949
  // ../server/src/music/oauth.ts
11838
- import { createHash as createHash9, randomBytes as randomBytes7 } from "node:crypto";
11839
- import { chmodSync as chmodSync4, existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync8, rmSync as rmSync7, writeFileSync as writeFileSync8 } from "node:fs";
11840
- import { join as join14 } from "node:path";
11950
+ import { createHash as createHash9, randomBytes as randomBytes8 } from "node:crypto";
11951
+ import { chmodSync as chmodSync5, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync9, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "node:fs";
11952
+ import { join as join15 } from "node:path";
11841
11953
  var STATE_TTL_MS = 10 * 6e4;
11842
11954
  var MAX_STATES = 20;
11843
11955
  var REFRESH_AHEAD_MS = 6e4;
@@ -11846,7 +11958,7 @@ var RefreshRejected = class extends Error {
11846
11958
  };
11847
11959
  var b64url = (b) => b.toString("base64url");
11848
11960
  var challengeOf = (verifier) => b64url(createHash9("sha256").update(verifier).digest());
11849
- function pkcePair(random = randomBytes7) {
11961
+ function pkcePair(random = randomBytes8) {
11850
11962
  const verifier = b64url(random(48));
11851
11963
  return { verifier, challenge: challengeOf(verifier) };
11852
11964
  }
@@ -11857,7 +11969,7 @@ var OAuthStates = class {
11857
11969
  clock;
11858
11970
  pending = /* @__PURE__ */ new Map();
11859
11971
  issue(source, verifier) {
11860
- const state = b64url(randomBytes7(24));
11972
+ const state = b64url(randomBytes8(24));
11861
11973
  this.pending.set(state, { source, verifier, at: this.clock() });
11862
11974
  while (this.pending.size > MAX_STATES) this.pending.delete(this.pending.keys().next().value);
11863
11975
  return state;
@@ -11881,23 +11993,23 @@ var MusicTokens = class {
11881
11993
  reconnect = /* @__PURE__ */ new Set();
11882
11994
  generations = /* @__PURE__ */ new Map();
11883
11995
  file(source) {
11884
- return join14(this.dir, `music-${source}.tokens.json`);
11996
+ return join15(this.dir, `music-${source}.tokens.json`);
11885
11997
  }
11886
11998
  save(source, login) {
11887
- mkdirSync9(this.dir, { recursive: true });
11999
+ mkdirSync10(this.dir, { recursive: true });
11888
12000
  const file = this.file(source);
11889
- writeFileSync8(file, JSON.stringify(login), { mode: 384 });
12001
+ writeFileSync9(file, JSON.stringify(login), { mode: 384 });
11890
12002
  try {
11891
- chmodSync4(file, 384);
12003
+ chmodSync5(file, 384);
11892
12004
  } catch {
11893
12005
  }
11894
12006
  this.reconnect.delete(source);
11895
12007
  }
11896
12008
  load(source) {
11897
12009
  const file = this.file(source);
11898
- if (!existsSync13(file)) return null;
12010
+ if (!existsSync14(file)) return null;
11899
12011
  try {
11900
- const j = JSON.parse(readFileSync8(file, "utf8"));
12012
+ const j = JSON.parse(readFileSync9(file, "utf8"));
11901
12013
  if (typeof j.accessToken !== "string" || typeof j.refreshToken !== "string" || typeof j.expiresAt !== "number" || typeof j.account !== "string") return null;
11902
12014
  return { accessToken: j.accessToken, refreshToken: j.refreshToken, expiresAt: j.expiresAt, account: j.account, premium: typeof j.premium === "boolean" ? j.premium : null };
11903
12015
  } catch {
@@ -11927,21 +12039,21 @@ var MusicSecrets = class {
11927
12039
  }
11928
12040
  dir;
11929
12041
  file(source) {
11930
- return join14(this.dir, `music-${source}.secret.json`);
12042
+ return join15(this.dir, `music-${source}.secret.json`);
11931
12043
  }
11932
12044
  set(source, secret) {
11933
- mkdirSync9(this.dir, { recursive: true });
12045
+ mkdirSync10(this.dir, { recursive: true });
11934
12046
  const file = this.file(source);
11935
- writeFileSync8(file, JSON.stringify({ secret }), { mode: 384 });
12047
+ writeFileSync9(file, JSON.stringify({ secret }), { mode: 384 });
11936
12048
  try {
11937
- chmodSync4(file, 384);
12049
+ chmodSync5(file, 384);
11938
12050
  } catch {
11939
12051
  }
11940
12052
  }
11941
12053
  /** For the service's own token call only. */
11942
12054
  get(source) {
11943
12055
  try {
11944
- const j = JSON.parse(readFileSync8(this.file(source), "utf8"));
12056
+ const j = JSON.parse(readFileSync9(this.file(source), "utf8"));
11945
12057
  return typeof j.secret === "string" ? j.secret : "";
11946
12058
  } catch {
11947
12059
  return "";
@@ -12529,7 +12641,7 @@ var HostPlayer = class {
12529
12641
  // ../server/src/music/library.ts
12530
12642
  import { createHash as createHash10 } from "node:crypto";
12531
12643
  import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
12532
- import { basename as basename2, extname as extname2, join as join15, sep as sep2 } from "node:path";
12644
+ import { basename as basename2, extname as extname2, join as join16, sep as sep2 } from "node:path";
12533
12645
  import { parseFile } from "music-metadata";
12534
12646
  var MAX_PAGE = 500;
12535
12647
  var MAX_COVER_BYTES = 3 * 1024 * 1024;
@@ -12584,7 +12696,7 @@ var MusicLibrary = class {
12584
12696
  const depthLimit = this.o.scanDepth();
12585
12697
  const found = [];
12586
12698
  let truncated = false;
12587
- const walk2 = async (dir, rel, depth) => {
12699
+ const walk3 = async (dir, rel, depth) => {
12588
12700
  if (truncated) return;
12589
12701
  let entries;
12590
12702
  try {
@@ -12604,7 +12716,7 @@ var MusicLibrary = class {
12604
12716
  if (e.name.startsWith(".") || e.isSymbolicLink()) continue;
12605
12717
  const childRel = rel ? `${rel}${sep2}${e.name}` : e.name;
12606
12718
  if (e.isDirectory()) {
12607
- if (depth < depthLimit) await walk2(join15(dir, e.name), childRel, depth + 1);
12719
+ if (depth < depthLimit) await walk3(join16(dir, e.name), childRel, depth + 1);
12608
12720
  } else if (e.isFile() && allowed.has(extname2(e.name).slice(1).toLowerCase())) {
12609
12721
  if (found.length >= max) {
12610
12722
  truncated = true;
@@ -12614,7 +12726,7 @@ var MusicLibrary = class {
12614
12726
  }
12615
12727
  }
12616
12728
  };
12617
- await walk2(root, "", 0);
12729
+ await walk3(root, "", 0);
12618
12730
  const tracks = new Array(found.length);
12619
12731
  let next = 0;
12620
12732
  const worker = async () => {
@@ -12636,7 +12748,7 @@ var MusicLibrary = class {
12636
12748
  const name = basename2(rel);
12637
12749
  const ext = extname2(name).slice(1).toLowerCase();
12638
12750
  const stem = name.slice(0, name.length - extname2(name).length);
12639
- const parent = rel.includes(sep2) ? basename2(join15(rel, "..")) : "";
12751
+ const parent = rel.includes(sep2) ? basename2(join16(rel, "..")) : "";
12640
12752
  let title2 = "";
12641
12753
  let artist = "";
12642
12754
  let album = "";
@@ -12644,7 +12756,7 @@ var MusicLibrary = class {
12644
12756
  let durationSec = null;
12645
12757
  let embedded = false;
12646
12758
  try {
12647
- const m = await parseFile(join15(root, rel));
12759
+ const m = await parseFile(join16(root, rel));
12648
12760
  title2 = m.common.title?.trim() ?? "";
12649
12761
  artist = (m.common.artist ?? m.common.albumartist ?? "").trim();
12650
12762
  album = m.common.album?.trim() ?? "";
@@ -12687,7 +12799,7 @@ var MusicLibrary = class {
12687
12799
  if (!t || !this.root) return null;
12688
12800
  const allowed = this.o.extensions().map((e) => e.toLowerCase().replace(/^\./, ""));
12689
12801
  if (!allowed.includes(t.ext)) return null;
12690
- return this.inside(join15(this.root, t.rel));
12802
+ return this.inside(join16(this.root, t.rel));
12691
12803
  }
12692
12804
  async inside(path3) {
12693
12805
  try {
@@ -12705,7 +12817,7 @@ var MusicLibrary = class {
12705
12817
  const t = this.tracks.find((x) => x.id === id2);
12706
12818
  if (!t || !this.root) return null;
12707
12819
  if (t.coverFile) {
12708
- const path3 = await this.inside(join15(this.root, t.coverFile));
12820
+ const path3 = await this.inside(join16(this.root, t.coverFile));
12709
12821
  if (path3) {
12710
12822
  try {
12711
12823
  if ((await stat(path3)).size <= MAX_COVER_BYTES) return { mime: COVER_EXT[extname2(path3).slice(1).toLowerCase()], data: await readFile(path3) };
@@ -12714,7 +12826,7 @@ var MusicLibrary = class {
12714
12826
  }
12715
12827
  }
12716
12828
  if (t.embedded) {
12717
- const path3 = await this.inside(join15(this.root, t.rel));
12829
+ const path3 = await this.inside(join16(this.root, t.rel));
12718
12830
  if (path3) {
12719
12831
  try {
12720
12832
  const pic = (await parseFile(path3)).common.picture?.[0];
@@ -13211,11 +13323,11 @@ function buildReport(input) {
13211
13323
  out.push("");
13212
13324
  if (!snap.positions.ok) out.push(missing("Positions", snap.positions));
13213
13325
  else {
13214
- const open2 = snap.positions.data.filter((p) => p.quantity !== 0);
13215
- if (open2.length === 0) out.push("No open positions.");
13326
+ const open3 = snap.positions.data.filter((p) => p.quantity !== 0);
13327
+ if (open3.length === 0) out.push("No open positions.");
13216
13328
  else {
13217
13329
  out.push("Open positions:");
13218
- for (const p of open2) out.push(`- ${p.symbol} ${p.product} ${p.quantity}${p.quantity < 0 ? " (short)" : ""} @ ${fmt(p.avgPrice)}, P&L ${signed(p.pnl)}`);
13330
+ for (const p of open3) out.push(`- ${p.symbol} ${p.product} ${p.quantity}${p.quantity < 0 ? " (short)" : ""} @ ${fmt(p.avgPrice)}, P&L ${signed(p.pnl)}`);
13219
13331
  }
13220
13332
  }
13221
13333
  }
@@ -13329,9 +13441,9 @@ var ReportSchedules = class {
13329
13441
  };
13330
13442
 
13331
13443
  // ../server/src/brokers/session.ts
13332
- import { randomBytes as randomBytes8 } from "node:crypto";
13333
- import { chmodSync as chmodSync5, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync9, rmSync as rmSync8, writeFileSync as writeFileSync9 } from "node:fs";
13334
- import { join as join16 } from "node:path";
13444
+ import { randomBytes as randomBytes9 } from "node:crypto";
13445
+ import { chmodSync as chmodSync6, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync10, rmSync as rmSync8, writeFileSync as writeFileSync10 } from "node:fs";
13446
+ import { join as join17 } from "node:path";
13335
13447
  var STATE_TTL_MS2 = 10 * 6e4;
13336
13448
  var MAX_STATES2 = 20;
13337
13449
  var BROKER_ID = /^[a-z0-9-]{1,40}$/;
@@ -13345,14 +13457,14 @@ var BrokerSessions = class {
13345
13457
  states = /* @__PURE__ */ new Map();
13346
13458
  file(broker) {
13347
13459
  if (!BROKER_ID.test(broker)) throw new Error("That is not a broker id.");
13348
- return join16(this.dir, `broker-${broker}.session.json`);
13460
+ return join17(this.dir, `broker-${broker}.session.json`);
13349
13461
  }
13350
13462
  save(broker, info) {
13351
13463
  const file = this.file(broker);
13352
- mkdirSync10(this.dir, { recursive: true });
13353
- writeFileSync9(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
13464
+ mkdirSync11(this.dir, { recursive: true });
13465
+ writeFileSync10(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
13354
13466
  try {
13355
- chmodSync5(file, 384);
13467
+ chmodSync6(file, 384);
13356
13468
  } catch {
13357
13469
  }
13358
13470
  }
@@ -13360,9 +13472,9 @@ var BrokerSessions = class {
13360
13472
  load(broker) {
13361
13473
  if (!BROKER_ID.test(broker)) return null;
13362
13474
  const file = this.file(broker);
13363
- if (!existsSync14(file)) return null;
13475
+ if (!existsSync15(file)) return null;
13364
13476
  try {
13365
- const raw = JSON.parse(readFileSync9(file, "utf8"));
13477
+ const raw = JSON.parse(readFileSync10(file, "utf8"));
13366
13478
  if (typeof raw.accessToken !== "string" || typeof raw.expiresAt !== "number") return null;
13367
13479
  if (raw.expiresAt <= this.clock()) {
13368
13480
  this.clear(broker);
@@ -13379,7 +13491,7 @@ var BrokerSessions = class {
13379
13491
  }
13380
13492
  /** A fresh unguessable code for one login at `broker`. At most twenty wait at once; the oldest is dropped. */
13381
13493
  newState(broker) {
13382
- const state = randomBytes8(24).toString("hex");
13494
+ const state = randomBytes9(24).toString("hex");
13383
13495
  this.states.set(state, { broker, at: this.clock() });
13384
13496
  while (this.states.size > MAX_STATES2) this.states.delete(this.states.keys().next().value);
13385
13497
  return state;
@@ -13698,9 +13810,9 @@ ${url}`);
13698
13810
  // ../server/src/codebox.ts
13699
13811
  import { spawn as spawn4 } from "node:child_process";
13700
13812
  import { randomUUID as randomUUID5 } from "node:crypto";
13701
- import { chmodSync as chmodSync6, mkdtempSync as mkdtempSync2, rmSync as rmSync9, writeFileSync as writeFileSync10 } from "node:fs";
13813
+ import { chmodSync as chmodSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
13702
13814
  import { tmpdir as tmpdir2 } from "node:os";
13703
- import { join as join17 } from "node:path";
13815
+ import { join as join18 } from "node:path";
13704
13816
  var MAX_CODE_CHARS = 5e4;
13705
13817
  var MAX_OUTPUT_CHARS = 2e4;
13706
13818
  var MAX_EXTRA_FILES = 10;
@@ -13760,15 +13872,15 @@ var CodeBox = class {
13760
13872
  if (extra.reduce((sum, [, body]) => sum + body.length, 0) > MAX_EXTRA_FILE_CHARS) return { ok: false, error: "The sandbox files are too large." };
13761
13873
  const setup = SETUP[input.language];
13762
13874
  const timeoutMs = input.timeoutSec && input.timeoutSec > 0 ? Math.min(input.timeoutSec * 1e3, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
13763
- const dir = mkdtempSync2(join17(tmpdir2(), "friend-code-"));
13875
+ const dir = mkdtempSync2(join18(tmpdir2(), "friend-code-"));
13764
13876
  try {
13765
- const file = join17(dir, setup.file);
13766
- writeFileSync10(file, input.code);
13767
- chmodSync6(dir, 493);
13768
- chmodSync6(file, 420);
13877
+ const file = join18(dir, setup.file);
13878
+ writeFileSync11(file, input.code);
13879
+ chmodSync7(dir, 493);
13880
+ chmodSync7(file, 420);
13769
13881
  for (const [name, body] of extra) {
13770
- writeFileSync10(join17(dir, name), body);
13771
- chmodSync6(join17(dir, name), 420);
13882
+ writeFileSync11(join18(dir, name), body);
13883
+ chmodSync7(join18(dir, name), 420);
13772
13884
  }
13773
13885
  const args = [
13774
13886
  "run",
@@ -13912,26 +14024,26 @@ var Memory = class {
13912
14024
  };
13913
14025
 
13914
14026
  // ../server/src/memory/import.ts
13915
- import { existsSync as existsSync15, writeFileSync as writeFileSync11 } from "node:fs";
13916
- import { join as join18 } from "node:path";
14027
+ import { existsSync as existsSync16, writeFileSync as writeFileSync12 } from "node:fs";
14028
+ import { join as join19 } from "node:path";
13917
14029
  var MARKER = ".imported-notes";
13918
14030
  function importFlatNotes(memory, tree2) {
13919
14031
  tree2.ensure();
13920
- const marker = join18(tree2.root, MARKER);
13921
- if (existsSync15(marker)) return 0;
14032
+ const marker = join19(tree2.root, MARKER);
14033
+ if (existsSync16(marker)) return 0;
13922
14034
  let n2 = 0;
13923
14035
  for (const m of [...memory.list()].reverse()) {
13924
14036
  const name = inboxName(m.text, (x) => tree2.has(`inbox/${x}.md`));
13925
14037
  const r = tree2.write(`inbox/${name}.md`, m.text, { title: m.text.slice(0, 60), summary: m.text.slice(0, 120), source: "import", ...n2 === 0 ? { folderSummary: "quick notes not filed yet, and notes brought over from the older list" } : {} });
13926
14038
  if (r.ok) n2++;
13927
14039
  }
13928
- writeFileSync11(marker, (/* @__PURE__ */ new Date()).toISOString());
14040
+ writeFileSync12(marker, (/* @__PURE__ */ new Date()).toISOString());
13929
14041
  return n2;
13930
14042
  }
13931
14043
 
13932
14044
  // ../server/src/memory/keeper.ts
13933
- import { existsSync as existsSync16, readFileSync as readFileSync10, writeFileSync as writeFileSync12 } from "node:fs";
13934
- import { join as join19 } from "node:path";
14045
+ import { existsSync as existsSync17, readFileSync as readFileSync11, writeFileSync as writeFileSync13 } from "node:fs";
14046
+ import { join as join20 } from "node:path";
13935
14047
  import { z as z11 } from "zod";
13936
14048
  var SYSTEM3 = `You keep the long-term memory of a personal assistant for its owner. You are given the memory index, a few existing notes that may be related, and the latest conversation between the owner and the assistant. Decide what, if anything, is worth keeping for months, and return it as JSON.
13937
14049
 
@@ -13999,12 +14111,12 @@ var MemoryKeeper = class {
13999
14111
  this.d.after?.();
14000
14112
  }
14001
14113
  cursorPath() {
14002
- return join19(this.d.tree.root, CURSOR_FILE);
14114
+ return join20(this.d.tree.root, CURSOR_FILE);
14003
14115
  }
14004
14116
  readCursor() {
14005
14117
  try {
14006
- if (!existsSync16(this.cursorPath())) return -1;
14007
- const n2 = Number(JSON.parse(readFileSync10(this.cursorPath(), "utf8")).lastId);
14118
+ if (!existsSync17(this.cursorPath())) return -1;
14119
+ const n2 = Number(JSON.parse(readFileSync11(this.cursorPath(), "utf8")).lastId);
14008
14120
  return Number.isInteger(n2) && n2 >= 0 ? n2 : -1;
14009
14121
  } catch {
14010
14122
  return -1;
@@ -14012,7 +14124,7 @@ var MemoryKeeper = class {
14012
14124
  }
14013
14125
  writeCursor(id2) {
14014
14126
  this.d.tree.ensure();
14015
- writeFileSync12(this.cursorPath(), JSON.stringify({ lastId: id2 }));
14127
+ writeFileSync13(this.cursorPath(), JSON.stringify({ lastId: id2 }));
14016
14128
  }
14017
14129
  window(after) {
14018
14130
  const max = this.d.db.prepare("select max(id) m from messages").get().m ?? 0;
@@ -14297,7 +14409,7 @@ ${n2.body.trim().slice(0, NOTE_CHARS)}`).join("\n")}`,
14297
14409
  };
14298
14410
 
14299
14411
  // ../server/src/proactive/beat.ts
14300
- import { existsSync as existsSync17, readFileSync as readFileSync11, writeFileSync as writeFileSync13 } from "node:fs";
14412
+ import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync14 } from "node:fs";
14301
14413
  var LEVEL2 = { off: 0, low: 1, medium: 2, high: 3 };
14302
14414
  var MAX_SAY = 400;
14303
14415
  var OVERDUE_AFTER_MS = 2 * 36e5;
@@ -14340,8 +14452,8 @@ var ProactiveBeat = class {
14340
14452
  }
14341
14453
  load(day2) {
14342
14454
  try {
14343
- if (existsSync17(this.d.statePath)) {
14344
- const s = JSON.parse(readFileSync11(this.d.statePath, "utf8"));
14455
+ if (existsSync18(this.d.statePath)) {
14456
+ const s = JSON.parse(readFileSync12(this.d.statePath, "utf8"));
14345
14457
  if (s.day === day2) return { day: day2, sent: s.sent ?? 0, lastAt: s.lastAt ?? 0, fired: s.fired ?? {}, said: s.said ?? [] };
14346
14458
  const week = this.now() - 7 * 864e5;
14347
14459
  return { day: day2, sent: 0, lastAt: s.lastAt ?? 0, fired: Object.fromEntries(Object.entries(s.fired ?? {}).filter(([, t]) => t > week)), said: [] };
@@ -14352,7 +14464,7 @@ var ProactiveBeat = class {
14352
14464
  }
14353
14465
  save(s) {
14354
14466
  try {
14355
- writeFileSync13(this.d.statePath, JSON.stringify(s));
14467
+ writeFileSync14(this.d.statePath, JSON.stringify(s));
14356
14468
  } catch {
14357
14469
  }
14358
14470
  }
@@ -14378,15 +14490,15 @@ var ProactiveBeat = class {
14378
14490
  }
14379
14491
  const here2 = this.d.screens() > 0 || c.phone && !!this.d.phoneReady?.();
14380
14492
  if (lvl >= 2 && here2) {
14381
- const open2 = this.d.tasks.list();
14382
- const todays = open2.filter((t) => t.dueAt !== null && dayKey2(new Date(t.dueAt)) === day2);
14493
+ const open3 = this.d.tasks.list();
14494
+ const todays = open3.filter((t) => t.dueAt !== null && dayKey2(new Date(t.dueAt)) === day2);
14383
14495
  const office = this.d.officeLine?.() ?? null;
14384
14496
  if (minute >= hm(c.morningAt) && minute < hm(c.morningAt) + 240) {
14385
14497
  out.push({
14386
14498
  key: `morning:${day2}`,
14387
14499
  kind: "morning",
14388
14500
  level: 2,
14389
- facts: [`It is the morning of ${at.toDateString()}.`, todays.length ? `Due today: ${todays.map((t) => t.title).join("; ")}.` : "Nothing is due today.", `${open2.length} items are open on the task list.`, ...office ? [`Office: ${office}`] : []]
14501
+ facts: [`It is the morning of ${at.toDateString()}.`, todays.length ? `Due today: ${todays.map((t) => t.title).join("; ")}.` : "Nothing is due today.", `${open3.length} items are open on the task list.`, ...office ? [`Office: ${office}`] : []]
14390
14502
  });
14391
14503
  }
14392
14504
  if (minute >= hm(c.eveningAt) && !within(minute, c.quietFrom, c.quietTo)) {
@@ -14501,14 +14613,14 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
14501
14613
 
14502
14614
  // ../server/src/office/office.ts
14503
14615
  import { randomUUID as randomUUID6 } from "node:crypto";
14504
- import { mkdirSync as mkdirSync11, statSync as statSync3, writeFileSync as writeFileSync14 } from "node:fs";
14505
- import { join as join20 } from "node:path";
14616
+ import { mkdirSync as mkdirSync12, statSync as statSync3, writeFileSync as writeFileSync15 } from "node:fs";
14617
+ import { join as join21 } from "node:path";
14506
14618
 
14507
14619
  // ../server/src/provider/claude-code/bridge.ts
14508
14620
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
14509
14621
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
14510
14622
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
14511
- import { randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
14623
+ import { randomBytes as randomBytes10, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
14512
14624
  import { createServer } from "node:http";
14513
14625
  var encodeToolName = (name) => name.replaceAll(".", "__");
14514
14626
  var MAX_BODY_BYTES = 8 * 1024 * 1024;
@@ -14517,7 +14629,7 @@ var ToolBridge = class {
14517
14629
  this.onCall = onCall;
14518
14630
  }
14519
14631
  onCall;
14520
- token = randomBytes9(24).toString("hex");
14632
+ token = randomBytes10(24).toString("hex");
14521
14633
  tools = [];
14522
14634
  http = null;
14523
14635
  port = 0;
@@ -15160,10 +15272,10 @@ var Office = class {
15160
15272
  const cfg = this.d.config();
15161
15273
  await run2.bridge.start();
15162
15274
  if (run2.concluded) return;
15163
- const dir = join20(this.d.dataDir, "office");
15164
- mkdirSync11(dir, { recursive: true });
15165
- const mcp = join20(dir, `${worker.id}.mcp.json`);
15166
- writeFileSync14(mcp, JSON.stringify({ mcpServers: { office: { type: "http", url: run2.bridge.url, headers: { Authorization: `Bearer ${run2.bridge.token}` } } } }));
15275
+ const dir = join21(this.d.dataDir, "office");
15276
+ mkdirSync12(dir, { recursive: true });
15277
+ const mcp = join21(dir, `${worker.id}.mcp.json`);
15278
+ writeFileSync15(mcp, JSON.stringify({ mcpServers: { office: { type: "http", url: run2.bridge.url, headers: { Authorization: `Bearer ${run2.bridge.token}` } } } }));
15167
15279
  const args = buildWorkerArgs({
15168
15280
  model: worker.model.trim() || cfg.claudeCode.model,
15169
15281
  instructions: this.briefing(worker),
@@ -15422,7 +15534,7 @@ ${ticket.description}` : "", goal: project.goal, action: describeAction(tool, in
15422
15534
  };
15423
15535
 
15424
15536
  // ../server/src/office/store.ts
15425
- import { randomBytes as randomBytes10 } from "node:crypto";
15537
+ import { randomBytes as randomBytes11 } from "node:crypto";
15426
15538
  var MAX_EVENT_CHARS = 200;
15427
15539
  var MAX_EVENTS_PER_WORKER = 500;
15428
15540
  var toRequest = (r) => ({ id: r.id, workerId: r.worker_id, ticketId: r.ticket_id, tool: r.tool, summary: r.summary, danger: r.danger === 1, status: r.status, decision: r.decision, reason: r.reason, tries: r.tries, createdAt: r.created_at, decidedAt: r.decided_at });
@@ -15439,7 +15551,7 @@ var OfficeStore = class {
15439
15551
  db;
15440
15552
  now;
15441
15553
  createWorker(w) {
15442
- const id2 = randomBytes10(4).toString("hex");
15554
+ const id2 = randomBytes11(4).toString("hex");
15443
15555
  this.db.prepare("insert into office_workers (id, name, role_id, project_id, created_at, title, capabilities, instructions, model, permission, manager_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(id2, w.name, w.roleId, w.projectId, this.now(), w.title ?? "", w.capabilities ?? "", w.instructions ?? "", w.model ?? "", w.permission ?? "default", w.managerId ?? null);
15444
15556
  return this.getWorker(id2);
15445
15557
  }
@@ -15552,12 +15664,12 @@ var OfficeStore = class {
15552
15664
  };
15553
15665
 
15554
15666
  // ../server/src/app.ts
15555
- import { join as join25 } from "node:path";
15667
+ import { join as join26 } from "node:path";
15556
15668
 
15557
15669
  // ../server/src/db.ts
15558
15670
  import Database from "better-sqlite3";
15559
- import { mkdirSync as mkdirSync12 } from "node:fs";
15560
- import { join as join21 } from "node:path";
15671
+ import { mkdirSync as mkdirSync13 } from "node:fs";
15672
+ import { join as join22 } from "node:path";
15561
15673
 
15562
15674
  // ../server/src/migrations.ts
15563
15675
  var MIGRATIONS = [
@@ -15852,8 +15964,8 @@ create trigger audit_no_delete before delete on audit_log begin select raise(abo
15852
15964
 
15853
15965
  // ../server/src/db.ts
15854
15966
  function openDb(dataDir) {
15855
- mkdirSync12(dataDir, { recursive: true });
15856
- const db = new Database(join21(dataDir, "friend.db"));
15967
+ mkdirSync13(dataDir, { recursive: true });
15968
+ const db = new Database(join22(dataDir, "friend.db"));
15857
15969
  db.pragma("journal_mode = WAL");
15858
15970
  db.pragma("foreign_keys = ON");
15859
15971
  db.exec("create table if not exists schema_version (id integer primary key, applied_at integer not null)");
@@ -16182,17 +16294,17 @@ function scan2(html) {
16182
16294
  }
16183
16295
  return { title: title2, out: out.join("") };
16184
16296
  }
16185
- function firstRegion(s, open2, close) {
16186
- const a = s.indexOf(open2);
16297
+ function firstRegion(s, open3, close) {
16298
+ const a = s.indexOf(open3);
16187
16299
  if (a < 0) return null;
16188
16300
  const b = s.indexOf(close, a + 1);
16189
16301
  return s.slice(a + 1, b < 0 ? s.length : b);
16190
16302
  }
16191
- function allRegions(s, open2, close) {
16303
+ function allRegions(s, open3, close) {
16192
16304
  const parts = [];
16193
16305
  let at = 0;
16194
16306
  for (; ; ) {
16195
- const a = s.indexOf(open2, at);
16307
+ const a = s.indexOf(open3, at);
16196
16308
  if (a < 0) break;
16197
16309
  const b = s.indexOf(close, a + 1);
16198
16310
  parts.push(s.slice(a + 1, b < 0 ? s.length : b));
@@ -16484,7 +16596,7 @@ var DeviceHub = class {
16484
16596
  import fastifyCookie from "@fastify/cookie";
16485
16597
 
16486
16598
  // ../server/src/auditApi.ts
16487
- import { randomBytes as randomBytes11 } from "node:crypto";
16599
+ import { randomBytes as randomBytes12 } from "node:crypto";
16488
16600
  import { z as z13 } from "zod";
16489
16601
 
16490
16602
  // ../server/src/auditExport.ts
@@ -16533,7 +16645,7 @@ var UnlockStore = class {
16533
16645
  issue(minutes3) {
16534
16646
  const t = this.now();
16535
16647
  for (const [k, v] of this.tokens) if (v < t) this.tokens.delete(k);
16536
- const token = randomBytes11(32).toString("hex");
16648
+ const token = randomBytes12(32).toString("hex");
16537
16649
  const expiresAt = t + minutes3 * 6e4;
16538
16650
  this.tokens.set(token, expiresAt);
16539
16651
  return { token, expiresAt };
@@ -16670,15 +16782,15 @@ function registerAuditRoutes(d) {
16670
16782
  app.get("/api/audit/status", { onRequest: guard2 }, async (req) => {
16671
16783
  read("/api/audit/status", req);
16672
16784
  const last = d.audit.last();
16673
- const seal = d.query.lastSeal();
16674
- return { rows: d.query.counts({}).total, lastId: last?.id ?? null, lastSeal: seal ? { at: seal.ts, text: seal.detail.seal ?? null } : null, keepDays: d.config().keepDays, workers: d.query.workers() };
16785
+ const seal2 = d.query.lastSeal();
16786
+ return { rows: d.query.counts({}).total, lastId: last?.id ?? null, lastSeal: seal2 ? { at: seal2.ts, text: seal2.detail.seal ?? null } : null, keepDays: d.config().keepDays, workers: d.query.workers() };
16675
16787
  });
16676
16788
  }
16677
16789
 
16678
16790
  // ../server/src/gateway.ts
16679
16791
  import fastifyStatic from "@fastify/static";
16680
16792
  import Fastify from "fastify";
16681
- import { createReadStream as createReadStream2, existsSync as existsSync18, promises as fsp2 } from "node:fs";
16793
+ import { createReadStream as createReadStream2, existsSync as existsSync19, promises as fsp2 } from "node:fs";
16682
16794
  import { isIP as isIP3 } from "node:net";
16683
16795
  import { Readable } from "node:stream";
16684
16796
  import { WebSocket as WebSocket2, WebSocketServer } from "ws";
@@ -16787,6 +16899,17 @@ function createGateway(deps) {
16787
16899
  return reply.code(421).send({ error: "Unknown host" });
16788
16900
  }
16789
16901
  });
16902
+ app.addHook("onSend", async (req, reply, payload) => {
16903
+ const set = (name, value) => {
16904
+ if (!reply.hasHeader(name)) reply.header(name, value);
16905
+ };
16906
+ set("x-content-type-options", "nosniff");
16907
+ set("x-frame-options", "SAMEORIGIN");
16908
+ set("referrer-policy", "no-referrer");
16909
+ set("content-security-policy", "frame-ancestors 'self'; object-src 'none'; base-uri 'self'; form-action 'self'");
16910
+ if (isSecure(req)) set("strict-transport-security", "max-age=15552000");
16911
+ return payload;
16912
+ });
16790
16913
  const MISSES_PER_MINUTE = 30;
16791
16914
  const misses = /* @__PURE__ */ new Map();
16792
16915
  const allowMiss = (ip) => {
@@ -17800,7 +17923,7 @@ function createGateway(deps) {
17800
17923
  deps.onLock?.();
17801
17924
  return { ok: true };
17802
17925
  });
17803
- if (deps.webDir && existsSync18(deps.webDir)) {
17926
+ if (deps.webDir && existsSync19(deps.webDir)) {
17804
17927
  app.register(fastifyStatic, { root: deps.webDir });
17805
17928
  app.setNotFoundHandler((req, reply) => {
17806
17929
  if (req.method === "GET" && !req.url.startsWith("/api")) return reply.sendFile("index.html");
@@ -17955,9 +18078,9 @@ Connection: close\r
17955
18078
 
17956
18079
  // ../server/src/browser/hub.ts
17957
18080
  import { spawn as spawn7, spawnSync } from "node:child_process";
17958
- import { mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync3, readdirSync as readdirSync6, readFileSync as readFileSync12, rmSync as rmSync10, statSync as statSync5 } from "node:fs";
18081
+ import { mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync3, readdirSync as readdirSync6, readFileSync as readFileSync13, rmSync as rmSync10, statSync as statSync5 } from "node:fs";
17959
18082
  import { tmpdir as tmpdir3 } from "node:os";
17960
- import { join as join22 } from "node:path";
18083
+ import { join as join23 } from "node:path";
17961
18084
 
17962
18085
  // ../server/src/browser/cdp.ts
17963
18086
  import { WebSocket as WebSocket3 } from "ws";
@@ -18027,11 +18150,11 @@ var Cdp = class _Cdp {
18027
18150
  };
18028
18151
 
18029
18152
  // ../server/src/browser/chrome.ts
18030
- import { existsSync as existsSync19, statSync as statSync4 } from "node:fs";
18153
+ import { existsSync as existsSync20, statSync as statSync4 } from "node:fs";
18031
18154
  import { posix as posix3, win32 as win323 } from "node:path";
18032
18155
  var fileThere = (p) => {
18033
18156
  try {
18034
- return existsSync19(p) && statSync4(p).isFile();
18157
+ return existsSync20(p) && statSync4(p).isFile();
18035
18158
  } catch {
18036
18159
  return false;
18037
18160
  }
@@ -18042,15 +18165,15 @@ function findChrome(override = "", w = {}) {
18042
18165
  const platform = w.platform ?? process.platform;
18043
18166
  const env = w.env ?? process.env;
18044
18167
  const isFile = w.isFile ?? fileThere;
18045
- const join35 = platform === "win32" ? win323.join : posix3.join;
18168
+ const join36 = platform === "win32" ? win323.join : posix3.join;
18046
18169
  if (override.trim()) return isFile(override.trim()) ? override.trim() : null;
18047
18170
  if (platform === "win32") {
18048
18171
  const roots = [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].filter((r) => !!r);
18049
- for (const r of roots) for (const rel of ["Google/Chrome/Application/chrome.exe", "Chromium/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe"]) if (isFile(join35(r, rel))) return join35(r, rel);
18172
+ for (const r of roots) for (const rel of ["Google/Chrome/Application/chrome.exe", "Chromium/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe"]) if (isFile(join36(r, rel))) return join36(r, rel);
18050
18173
  return null;
18051
18174
  }
18052
18175
  if (platform === "darwin") return MAC_PATHS.find(isFile) ?? null;
18053
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join35(dir, name))) return join35(dir, name);
18176
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join36(dir, name))) return join36(dir, name);
18054
18177
  return null;
18055
18178
  }
18056
18179
 
@@ -18077,7 +18200,7 @@ var BrowserHub = class {
18077
18200
  try {
18078
18201
  for (const name of readdirSync6(root)) {
18079
18202
  if (!/^friend-browser-/.test(name)) continue;
18080
- const dir = join22(root, name);
18203
+ const dir = join23(root, name);
18081
18204
  if (Date.now() - statSync5(dir).mtimeMs > 36e5) rmSync10(dir, { recursive: true, force: true });
18082
18205
  }
18083
18206
  } catch {
@@ -18141,8 +18264,8 @@ A picture of the page "${r.value.title || r.value.href}" (${r.value.href}). Text
18141
18264
  let cdp = null;
18142
18265
  try {
18143
18266
  const root = this.o.tmpRoot ?? tmpdir3();
18144
- mkdirSync13(root, { recursive: true });
18145
- profile = mkdtempSync3(join22(root, "friend-browser-"));
18267
+ mkdirSync14(root, { recursive: true });
18268
+ profile = mkdtempSync3(join23(root, "friend-browser-"));
18146
18269
  child = spawn7(
18147
18270
  chrome,
18148
18271
  [
@@ -18256,7 +18379,7 @@ async function endpoint(profile, signal) {
18256
18379
  for (; ; ) {
18257
18380
  signal.throwIfAborted();
18258
18381
  try {
18259
- const [port, path3] = readFileSync12(join22(profile, "DevToolsActivePort"), "utf8").split("\n");
18382
+ const [port, path3] = readFileSync13(join23(profile, "DevToolsActivePort"), "utf8").split("\n");
18260
18383
  if (port && path3) return `ws://127.0.0.1:${port.trim()}${path3.trim()}`;
18261
18384
  } catch {
18262
18385
  }
@@ -18498,8 +18621,8 @@ function startStatsFeed(opts) {
18498
18621
 
18499
18622
  // ../server/src/provider/claude-code/provider.ts
18500
18623
  import { createHash as createHash12 } from "node:crypto";
18501
- import { chmodSync as chmodSync7, existsSync as existsSync20, mkdirSync as mkdirSync14, readdirSync as readdirSync7, readFileSync as readFileSync13, rmSync as rmSync11, writeFileSync as writeFileSync15 } from "node:fs";
18502
- import { join as join23 } from "node:path";
18624
+ import { chmodSync as chmodSync8, existsSync as existsSync21, mkdirSync as mkdirSync15, readdirSync as readdirSync7, readFileSync as readFileSync14, rmSync as rmSync11, writeFileSync as writeFileSync16 } from "node:fs";
18625
+ import { join as join24 } from "node:path";
18503
18626
 
18504
18627
  // ../server/src/provider/claude-code/limits.ts
18505
18628
  var LIMIT2 = /\b(?:hit|reached)\s+(?:your\s+|the\s+)?(?:[\w-]+\s+)?(?:usage\s+)?limit\b|\busage\s+limit\b|\b(?:\d+-hour|weekly|daily|monthly)\s+limit\s+reached\b|\bhit your (?:weekly|daily|monthly|usage|\d+-hour) limit\b/i;
@@ -18597,7 +18720,7 @@ var NOT_SIGNED_IN = /not logged in|please run \/login|invalid api key|authentica
18597
18720
  var ClaudeCodeProvider = class {
18598
18721
  constructor(opts) {
18599
18722
  this.opts = opts;
18600
- this.home = join23(opts.dataDir, "claude");
18723
+ this.home = join24(opts.dataDir, "claude");
18601
18724
  this.now = opts.now ?? Date.now;
18602
18725
  this.bridge = new ToolBridge((call) => this.owner.inbox.push({ kind: "call", call }));
18603
18726
  }
@@ -18661,10 +18784,10 @@ var ClaudeCodeProvider = class {
18661
18784
  conv.hasContext = false;
18662
18785
  conv.systemKey = "";
18663
18786
  this.forgetSession(conv);
18664
- mkdirSync14(this.home, { recursive: true });
18787
+ mkdirSync15(this.home, { recursive: true });
18665
18788
  this.fresh = { seed: seed?.trim() || null };
18666
18789
  try {
18667
- writeFileSync15(this.freshFile(), JSON.stringify(this.fresh));
18790
+ writeFileSync16(this.freshFile(), JSON.stringify(this.fresh));
18668
18791
  } catch {
18669
18792
  }
18670
18793
  }
@@ -18823,7 +18946,7 @@ ${item.stderr}`;
18823
18946
  conv.proc = null;
18824
18947
  }
18825
18948
  conv.inbox.clear();
18826
- mkdirSync14(this.home, { recursive: true });
18949
+ mkdirSync15(this.home, { recursive: true });
18827
18950
  if (!conv.guest) {
18828
18951
  conv.sessionId ??= this.readSession();
18829
18952
  this.fresh = conv.sessionId ? null : this.readFresh();
@@ -18853,7 +18976,7 @@ ${item.stderr}`;
18853
18976
  "local",
18854
18977
  "--system-prompt-file",
18855
18978
  systemFile,
18856
- ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join23(this.home, "mcp.json"), "--allowedTools", [...web ? ["WebSearch"] : [], ...req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`)].join(","), ...resume ? ["--resume", resume] : []]
18979
+ ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join24(this.home, "mcp.json"), "--allowedTools", [...web ? ["WebSearch"] : [], ...req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`)].join(","), ...resume ? ["--resume", resume] : []]
18857
18980
  ];
18858
18981
  const proc = new ClaudeProc(
18859
18982
  {
@@ -18882,14 +19005,14 @@ ${item.stderr}`;
18882
19005
  if (!this.swept) {
18883
19006
  this.swept = true;
18884
19007
  try {
18885
- for (const f of readdirSync7(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync11(join23(this.home, f), { force: true });
19008
+ for (const f of readdirSync7(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync11(join24(this.home, f), { force: true });
18886
19009
  } catch {
18887
19010
  }
18888
19011
  }
18889
- const file = join23(this.home, `system-${++this.systemCount}.txt`);
18890
- writeFileSync15(file, text4);
19012
+ const file = join24(this.home, `system-${++this.systemCount}.txt`);
19013
+ writeFileSync16(file, text4);
18891
19014
  try {
18892
- chmodSync7(file, 384);
19015
+ chmodSync8(file, 384);
18893
19016
  } catch {
18894
19017
  }
18895
19018
  return file;
@@ -18903,20 +19026,20 @@ ${item.stderr}`;
18903
19026
  startBridge() {
18904
19027
  this.bridgeReady ??= (async () => {
18905
19028
  await this.bridge.start();
18906
- const file = join23(this.home, "mcp.json");
18907
- writeFileSync15(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
19029
+ const file = join24(this.home, "mcp.json");
19030
+ writeFileSync16(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
18908
19031
  try {
18909
- chmodSync7(file, 384);
19032
+ chmodSync8(file, 384);
18910
19033
  } catch {
18911
19034
  }
18912
19035
  })();
18913
19036
  return this.bridgeReady;
18914
19037
  }
18915
19038
  // ---- the session id, kept so a restart of Friend can pick the conversation up again ----
18916
- sessionFile = () => join23(this.home, "session-id");
19039
+ sessionFile = () => join24(this.home, "session-id");
18917
19040
  readSession() {
18918
19041
  try {
18919
- return existsSync20(this.sessionFile()) ? readFileSync13(this.sessionFile(), "utf8").trim() || null : null;
19042
+ return existsSync21(this.sessionFile()) ? readFileSync14(this.sessionFile(), "utf8").trim() || null : null;
18920
19043
  } catch {
18921
19044
  return null;
18922
19045
  }
@@ -18930,15 +19053,15 @@ ${item.stderr}`;
18930
19053
  } catch {
18931
19054
  }
18932
19055
  try {
18933
- writeFileSync15(this.sessionFile(), id2);
19056
+ writeFileSync16(this.sessionFile(), id2);
18934
19057
  } catch {
18935
19058
  }
18936
19059
  }
18937
- freshFile = () => join23(this.home, "fresh.json");
19060
+ freshFile = () => join24(this.home, "fresh.json");
18938
19061
  readFresh() {
18939
19062
  try {
18940
- if (!existsSync20(this.freshFile())) return null;
18941
- const r = JSON.parse(readFileSync13(this.freshFile(), "utf8"));
19063
+ if (!existsSync21(this.freshFile())) return null;
19064
+ const r = JSON.parse(readFileSync14(this.freshFile(), "utf8"));
18942
19065
  return { seed: typeof r.seed === "string" && r.seed ? r.seed : null };
18943
19066
  } catch {
18944
19067
  return null;
@@ -19950,10 +20073,10 @@ function dbWidgetStore(db) {
19950
20073
  }
19951
20074
 
19952
20075
  // ../server/src/tls.ts
19953
- import { chmodSync as chmodSync8, existsSync as existsSync21, mkdirSync as mkdirSync15, readFileSync as readFileSync14, writeFileSync as writeFileSync16 } from "node:fs";
20076
+ import { chmodSync as chmodSync9, existsSync as existsSync22, mkdirSync as mkdirSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync17 } from "node:fs";
19954
20077
  import { networkInterfaces } from "node:os";
19955
20078
  import { isIP as isIP4 } from "node:net";
19956
- import { join as join24 } from "node:path";
20079
+ import { join as join25 } from "node:path";
19957
20080
  import { generate } from "selfsigned";
19958
20081
  var DAYS = 825;
19959
20082
  var RENEW_BEFORE_MS = 30 * 24 * 36e5;
@@ -19968,16 +20091,16 @@ function tlsHosts(extra = [], ifaces) {
19968
20091
  return [.../* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", ...lanAddresses(ifaces), ...extra.map((h) => h.toLowerCase()).filter(Boolean)])];
19969
20092
  }
19970
20093
  async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
19971
- const dir = join24(dataDir, "tls");
19972
- const keyFile = join24(dir, "key.pem");
19973
- const certFile = join24(dir, "cert.pem");
19974
- const metaFile = join24(dir, "meta.json");
20094
+ const dir = join25(dataDir, "tls");
20095
+ const keyFile = join25(dir, "key.pem");
20096
+ const certFile = join25(dir, "cert.pem");
20097
+ const metaFile = join25(dir, "meta.json");
19975
20098
  const hosts = tlsHosts(extraHosts, ifaces);
19976
- if (existsSync21(keyFile) && existsSync21(certFile) && existsSync21(metaFile)) {
20099
+ if (existsSync22(keyFile) && existsSync22(certFile) && existsSync22(metaFile)) {
19977
20100
  try {
19978
- const meta = JSON.parse(readFileSync14(metaFile, "utf8"));
20101
+ const meta = JSON.parse(readFileSync15(metaFile, "utf8"));
19979
20102
  const covered = hosts.every((h) => meta.hosts.includes(h));
19980
- if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync14(keyFile, "utf8"), cert: readFileSync14(certFile, "utf8") };
20103
+ if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync15(keyFile, "utf8"), cert: readFileSync15(certFile, "utf8") };
19981
20104
  } catch {
19982
20105
  }
19983
20106
  }
@@ -19995,12 +20118,12 @@ async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
19995
20118
  { name: "subjectAltName", altNames }
19996
20119
  ]
19997
20120
  });
19998
- mkdirSync15(dir, { recursive: true });
19999
- writeFileSync16(keyFile, pems.private);
20000
- writeFileSync16(certFile, pems.cert);
20001
- writeFileSync16(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
20121
+ mkdirSync16(dir, { recursive: true });
20122
+ writeFileSync17(keyFile, pems.private);
20123
+ writeFileSync17(certFile, pems.cert);
20124
+ writeFileSync17(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
20002
20125
  try {
20003
- chmodSync8(keyFile, 384);
20126
+ chmodSync9(keyFile, 384);
20004
20127
  } catch {
20005
20128
  }
20006
20129
  return { key: pems.private, cert: pems.cert };
@@ -20044,7 +20167,7 @@ var DuckController = class {
20044
20167
 
20045
20168
  // ../server/src/system/autostart.ts
20046
20169
  import { spawn as spawn8 } from "node:child_process";
20047
- import { existsSync as existsSync22, mkdirSync as mkdirSync16, readFileSync as readFileSync15, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "node:fs";
20170
+ import { existsSync as existsSync23, mkdirSync as mkdirSync17, readFileSync as readFileSync16, rmSync as rmSync12, writeFileSync as writeFileSync18 } from "node:fs";
20048
20171
  import { homedir as homedir4 } from "node:os";
20049
20172
  import { dirname as dirname5, posix as posix4, win32 as win324 } from "node:path";
20050
20173
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
@@ -20221,17 +20344,17 @@ function realAutostartDeps(dataDir) {
20221
20344
  uid: typeof process.getuid === "function" ? process.getuid() : 0,
20222
20345
  path: process.env.PATH ?? "",
20223
20346
  ...process.env.XDG_CONFIG_HOME ? { configHome: process.env.XDG_CONFIG_HOME } : {},
20224
- exists: (p) => existsSync22(p),
20347
+ exists: (p) => existsSync23(p),
20225
20348
  read: (p) => {
20226
20349
  try {
20227
- return readFileSync15(p, "utf8");
20350
+ return readFileSync16(p, "utf8");
20228
20351
  } catch {
20229
20352
  return null;
20230
20353
  }
20231
20354
  },
20232
20355
  write: (p, text4) => {
20233
- mkdirSync16(dirname5(p), { recursive: true });
20234
- writeFileSync17(p, text4);
20356
+ mkdirSync17(dirname5(p), { recursive: true });
20357
+ writeFileSync18(p, text4);
20235
20358
  },
20236
20359
  remove: (p) => rmSync12(p, { force: true }),
20237
20360
  run: (cmd, args) => new Promise((resolve13) => {
@@ -20252,7 +20375,7 @@ function currentSelf() {
20252
20375
  // ../server/src/system/npm.ts
20253
20376
  import { spawn as spawn9 } from "node:child_process";
20254
20377
  var PACKAGE = "friend-assistant";
20255
- var runningVersion = () => true ? "0.1.70" : "development";
20378
+ var runningVersion = () => true ? "0.1.72" : "development";
20256
20379
  async function npmLatest(fetchFn = fetch, timeoutMs = 1e4) {
20257
20380
  try {
20258
20381
  const res = await fetchFn(`https://registry.npmjs.org/${PACKAGE}/latest`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
@@ -20464,36 +20587,36 @@ var Challenges = class {
20464
20587
  };
20465
20588
 
20466
20589
  // ../server/src/voice/crypto.ts
20467
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes12 } from "node:crypto";
20468
- import { chmodSync as chmodSync9, existsSync as existsSync23, mkdirSync as mkdirSync17, readFileSync as readFileSync16, writeFileSync as writeFileSync18 } from "node:fs";
20590
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes13 } from "node:crypto";
20591
+ import { chmodSync as chmodSync10, existsSync as existsSync24, mkdirSync as mkdirSync18, readFileSync as readFileSync17, writeFileSync as writeFileSync19 } from "node:fs";
20469
20592
  import { dirname as dirname6 } from "node:path";
20470
20593
  var KEY_BYTES = 32;
20471
20594
  var IV_BYTES = 12;
20472
20595
  var TAG_BYTES = 16;
20473
20596
  function loadOrCreateKey(path3) {
20474
- if (existsSync23(path3)) {
20475
- const key3 = readFileSync16(path3);
20597
+ if (existsSync24(path3)) {
20598
+ const key3 = readFileSync17(path3);
20476
20599
  if (key3.length !== KEY_BYTES) throw new Error(`invalid voice key file (expected ${KEY_BYTES} bytes): ${path3}`);
20477
20600
  return key3;
20478
20601
  }
20479
- mkdirSync17(dirname6(path3), { recursive: true });
20480
- const key2 = randomBytes12(KEY_BYTES);
20481
- writeFileSync18(path3, key2, { mode: 384 });
20602
+ mkdirSync18(dirname6(path3), { recursive: true });
20603
+ const key2 = randomBytes13(KEY_BYTES);
20604
+ writeFileSync19(path3, key2, { mode: 384 });
20482
20605
  try {
20483
- chmodSync9(path3, 384);
20606
+ chmodSync10(path3, 384);
20484
20607
  } catch {
20485
20608
  }
20486
20609
  return key2;
20487
20610
  }
20488
20611
  function encrypt(key2, plain6) {
20489
- const iv = randomBytes12(IV_BYTES);
20490
- const cipher = createCipheriv("aes-256-gcm", key2, iv);
20612
+ const iv = randomBytes13(IV_BYTES);
20613
+ const cipher = createCipheriv2("aes-256-gcm", key2, iv);
20491
20614
  const body = Buffer.concat([cipher.update(plain6), cipher.final()]);
20492
20615
  return Buffer.concat([iv, cipher.getAuthTag(), body]);
20493
20616
  }
20494
20617
  function decrypt(key2, blob) {
20495
20618
  if (blob.length < IV_BYTES + TAG_BYTES) throw new Error("encrypted data is too short");
20496
- const decipher = createDecipheriv("aes-256-gcm", key2, blob.subarray(0, IV_BYTES));
20619
+ const decipher = createDecipheriv2("aes-256-gcm", key2, blob.subarray(0, IV_BYTES));
20497
20620
  decipher.setAuthTag(blob.subarray(IV_BYTES, IV_BYTES + TAG_BYTES));
20498
20621
  return Buffer.concat([decipher.update(blob.subarray(IV_BYTES + TAG_BYTES)), decipher.final()]);
20499
20622
  }
@@ -20881,9 +21004,9 @@ var Speaker = class {
20881
21004
  if (alive()) this.active = false;
20882
21005
  });
20883
21006
  const take = (final) => {
20884
- const open2 = fenceCount(pending) % 2 === 1;
20885
- if (open2 && !final) return;
20886
- const text4 = open2 ? pending.slice(0, pending.lastIndexOf("```")) : pending;
21007
+ const open3 = fenceCount(pending) % 2 === 1;
21008
+ if (open3 && !final) return;
21009
+ const text4 = open3 ? pending.slice(0, pending.lastIndexOf("```")) : pending;
20887
21010
  const cut = final ? text4.length : lastBoundary(text4);
20888
21011
  if (cut === 0) return;
20889
21012
  pending = final ? "" : text4.slice(cut);
@@ -21116,17 +21239,17 @@ async function createApp(opts) {
21116
21239
  void musicLibrary.scan().catch(() => {
21117
21240
  });
21118
21241
  const memory = new Memory(db);
21119
- const memoryTree = new MemoryTree(join25(opts.dataDir, "memory"));
21242
+ const memoryTree = new MemoryTree(join26(opts.dataDir, "memory"));
21120
21243
  if (config.memory.enabled) {
21121
21244
  memoryTree.ensure();
21122
21245
  importFlatNotes(memory, memoryTree);
21123
21246
  memoryTree.repair();
21124
21247
  }
21125
- const soul = new Soul(memoryTree, join25(opts.dataDir, "soul-history"));
21248
+ const soul = new Soul(memoryTree, join26(opts.dataDir, "soul-history"));
21126
21249
  soul.ensure();
21127
- const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join25(opts.dataDir, "browser-profiles") });
21250
+ const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join26(opts.dataDir, "browser-profiles") });
21128
21251
  const tasks = new Tasks(db);
21129
- const plugins = new Plugins(db, join25(opts.dataDir, "plugins"));
21252
+ const plugins = new Plugins(db, join26(opts.dataDir, "plugins"));
21130
21253
  const hub = new McpHub(new ConnectorStore(opts.dataDir));
21131
21254
  let listenPort = config.port;
21132
21255
  const provisioner = opts.video?.provisioner ?? new Provisioner({ dataDir: opts.dataDir, onError: (name, why) => audit.log("system", "video.provision_failed", { name, why: why.slice(0, 200) }) });
@@ -21238,13 +21361,13 @@ async function createApp(opts) {
21238
21361
  if (id2 === "audius") return changeAudiusConfig((s) => changeAudius(s, change));
21239
21362
  if (id2 === "browser") {
21240
21363
  const err2 = changeBrowserConfig((b) => changeBrowser(b, change, !!browserHub.status().chrome));
21241
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join25(catalogDir, BROWSER_SKILL));
21364
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join26(catalogDir, BROWSER_SKILL));
21242
21365
  if (!err2 && "remove" in change) plugins.remove(BROWSER_SKILL);
21243
21366
  return err2;
21244
21367
  }
21245
21368
  if (id2 === "tavily") {
21246
21369
  const err2 = changeTavilyConfig((t) => changeTavily(t, change, !!config.web.tavilyKey));
21247
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join25(catalogDir, TAVILY_SKILL));
21370
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join26(catalogDir, TAVILY_SKILL));
21248
21371
  if (!err2 && "remove" in change) plugins.remove(TAVILY_SKILL);
21249
21372
  return err2;
21250
21373
  }
@@ -21275,7 +21398,7 @@ async function createApp(opts) {
21275
21398
  }
21276
21399
  if (id2 !== "zerodha") return changeChannels((c) => changeIntegration(c, id2, change));
21277
21400
  const err = changeBrokers((b) => changeBroker(b, id2, change, (gone) => brokerHub.forget(gone)));
21278
- if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join25(catalogDir, PORTFOLIO_SKILL));
21401
+ if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join26(catalogDir, PORTFOLIO_SKILL));
21279
21402
  if (!err && "remove" in change) plugins.remove(PORTFOLIO_SKILL);
21280
21403
  return err;
21281
21404
  };
@@ -21291,7 +21414,7 @@ async function createApp(opts) {
21291
21414
  },
21292
21415
  install: (id2) => {
21293
21416
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) return { ok: false, error: "That plugin is not in the catalog." };
21294
- return plugins.install(join25(catalogDir, id2));
21417
+ return plugins.install(join26(catalogDir, id2));
21295
21418
  }
21296
21419
  },
21297
21420
  integrations: {
@@ -21690,7 +21813,7 @@ First check the work: read the whole report (office.report) and, when it changed
21690
21813
  const voice2 = opts.voice;
21691
21814
  const speaker = voice2 ? new Speaker(voice2, audit, () => config.voice.ttsVoice, () => ({ hindi: config.voice.hindiVoice || void 0, marathi: config.voice.marathiVoice || void 0 })) : null;
21692
21815
  const voiceAvailable = () => !!voice2 && voice2.available();
21693
- const voiceKey = voice2 ? loadOrCreateKey(join25(opts.dataDir, "voice.key")) : null;
21816
+ const voiceKey = voice2 ? loadOrCreateKey(join26(opts.dataDir, "voice.key")) : null;
21694
21817
  const voiceprint = voiceKey ? new Voiceprint(db, voiceKey) : null;
21695
21818
  const enrollment = voiceprint ? new Enrollment(voiceprint, SPEAKER_MODEL) : null;
21696
21819
  const household = voiceKey ? new Household(db, voiceKey) : null;
@@ -21775,7 +21898,7 @@ ${task.title}`) !== null,
21775
21898
  }
21776
21899
  },
21777
21900
  audit,
21778
- statePath: join25(opts.dataDir, "proactive.json")
21901
+ statePath: join26(opts.dataDir, "proactive.json")
21779
21902
  });
21780
21903
  async function requirePin(pin, ip) {
21781
21904
  let ok2 = false;
@@ -21866,7 +21989,7 @@ ${task.title}`) !== null,
21866
21989
  if (!isPluginId(id2)) throw new HttpError(400, "That is not a plugin name.");
21867
21990
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) throw new HttpError(404, "That plugin is not in the catalog.");
21868
21991
  await requirePin(pin, ip);
21869
- const r = plugins.install(join25(catalogDir, id2));
21992
+ const r = plugins.install(join26(catalogDir, id2));
21870
21993
  if (!r.ok) throw new HttpError(400, `That plugin cannot be installed: ${r.error}`);
21871
21994
  audit.log("owner", "plugin.installed", { id: r.id, upgraded: r.upgraded, ip });
21872
21995
  return { id: r.id, upgraded: r.upgraded };
@@ -22676,7 +22799,7 @@ ${url}`);
22676
22799
  }
22677
22800
  const prune = () => {
22678
22801
  try {
22679
- const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join25(opts.dataDir, "audit-archive"), now: Date.now() });
22802
+ const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join26(opts.dataDir, "audit-archive"), now: Date.now() });
22680
22803
  if (r.removed) audit.log("system", "audit.pruned", { removed: r.removed, archive: r.archivePath });
22681
22804
  } catch (e) {
22682
22805
  audit.log("system", "audit.prune_failed", { message: e.message.slice(0, 200) });
@@ -22686,7 +22809,7 @@ ${url}`);
22686
22809
  pruneTimer = setInterval(prune, 24 * 36e5);
22687
22810
  pruneTimer.unref?.();
22688
22811
  let lastSealAttempt = null;
22689
- const seal = async () => {
22812
+ const seal2 = async () => {
22690
22813
  try {
22691
22814
  const lastSeal = new AuditQuery(db).lastSeal({ sent: true });
22692
22815
  if (!sealDue(/* @__PURE__ */ new Date(), config.audit.sealAt, typeof lastSeal?.detail.date === "string" ? lastSeal.detail.date : null, lastSealAttempt)) return;
@@ -22695,7 +22818,7 @@ ${url}`);
22695
22818
  } catch {
22696
22819
  }
22697
22820
  };
22698
- sealTimer = setInterval(() => void seal(), 6e4);
22821
+ sealTimer = setInterval(() => void seal2(), 6e4);
22699
22822
  sealTimer.unref?.();
22700
22823
  heartbeat.start();
22701
22824
  proactive.start();
@@ -23182,8 +23305,8 @@ import { resolve as resolve9 } from "node:path";
23182
23305
  import { WebSocket as WebSocket4 } from "ws";
23183
23306
 
23184
23307
  // ../agent-cli/src/tools/fs.ts
23185
- import { closeSync, mkdirSync as mkdirSync18, openSync, readSync, readdirSync as readdirSync8, statSync as statSync7, writeFileSync as writeFileSync19 } from "node:fs";
23186
- import { dirname as dirname9, join as join26 } from "node:path";
23308
+ import { closeSync, mkdirSync as mkdirSync19, openSync, readSync, readdirSync as readdirSync8, statSync as statSync7, writeFileSync as writeFileSync20 } from "node:fs";
23309
+ import { dirname as dirname9, join as join27 } from "node:path";
23187
23310
 
23188
23311
  // ../agent-cli/src/tools/roots.ts
23189
23312
  import { lstatSync as lstatSync3, realpathSync } from "node:fs";
@@ -23245,7 +23368,7 @@ function fsList(args, ctx) {
23245
23368
  if (e.isDirectory()) return `[dir] ${e.name}`;
23246
23369
  let size = 0;
23247
23370
  try {
23248
- size = statSync7(join26(g.abs, e.name)).size;
23371
+ size = statSync7(join27(g.abs, e.name)).size;
23249
23372
  } catch {
23250
23373
  }
23251
23374
  return `[file] ${e.name} (${size} bytes)`;
@@ -23286,8 +23409,8 @@ function fsWrite(args, ctx) {
23286
23409
  if ("error" in g) return { ok: false, error: g.error };
23287
23410
  if (Buffer.byteLength(args.content) > MAX_WRITE) return { ok: false, error: "Content too large (5 MB limit)" };
23288
23411
  try {
23289
- mkdirSync18(dirname9(g.abs), { recursive: true });
23290
- writeFileSync19(g.abs, args.content);
23412
+ mkdirSync19(dirname9(g.abs), { recursive: true });
23413
+ writeFileSync20(g.abs, args.content);
23291
23414
  return { ok: true, output: `Wrote ${Buffer.byteLength(args.content)} bytes to ${g.abs}`, truncated: false };
23292
23415
  } catch (e) {
23293
23416
  return { ok: false, error: e.message };
@@ -23522,9 +23645,9 @@ function startDeviceNode(opts) {
23522
23645
  }
23523
23646
 
23524
23647
  // ../agent-cli/src/commands/start.ts
23525
- import { randomBytes as randomBytes13 } from "node:crypto";
23526
- import { existsSync as existsSync25, readFileSync as readFileSync18, writeFileSync as writeFileSync21 } from "node:fs";
23527
- import { dirname as dirname11, join as join28, resolve as resolve8 } from "node:path";
23648
+ import { randomBytes as randomBytes14 } from "node:crypto";
23649
+ import { existsSync as existsSync26, readFileSync as readFileSync19, writeFileSync as writeFileSync22 } from "node:fs";
23650
+ import { dirname as dirname11, join as join29, resolve as resolve8 } from "node:path";
23528
23651
  import { fileURLToPath as fileURLToPath4 } from "node:url";
23529
23652
 
23530
23653
  // ../agent-cli/src/commands/lan.ts
@@ -23630,23 +23753,23 @@ async function lanCommand(args, io2, ifaces = networkInterfaces2) {
23630
23753
 
23631
23754
  // ../agent-cli/src/commands/voice.ts
23632
23755
  import { spawn as spawn12 } from "node:child_process";
23633
- import { existsSync as existsSync24, mkdirSync as mkdirSync19, readFileSync as readFileSync17, writeFileSync as writeFileSync20 } from "node:fs";
23634
- import { dirname as dirname10, join as join27, resolve as resolve7 } from "node:path";
23756
+ import { existsSync as existsSync25, mkdirSync as mkdirSync20, readFileSync as readFileSync18, writeFileSync as writeFileSync21 } from "node:fs";
23757
+ import { dirname as dirname10, join as join28, resolve as resolve7 } from "node:path";
23635
23758
  import { fileURLToPath as fileURLToPath3 } from "node:url";
23636
23759
  function voicePaths(dataDir) {
23637
- const home = join27(dataDir, "voice");
23638
- const venv = join27(home, "venv");
23760
+ const home = join28(dataDir, "voice");
23761
+ const venv = join28(home, "venv");
23639
23762
  return {
23640
23763
  home,
23641
23764
  venv,
23642
- python: process.platform === "win32" ? join27(venv, "Scripts", "python.exe") : join27(venv, "bin", "python"),
23643
- models: join27(home, "models"),
23644
- marker: join27(home, "installed.json")
23765
+ python: process.platform === "win32" ? join28(venv, "Scripts", "python.exe") : join28(venv, "bin", "python"),
23766
+ models: join28(home, "models"),
23767
+ marker: join28(home, "installed.json")
23645
23768
  };
23646
23769
  }
23647
23770
  function readMarker(dataDir) {
23648
23771
  try {
23649
- return JSON.parse(readFileSync17(voicePaths(dataDir).marker, "utf8"));
23772
+ return JSON.parse(readFileSync18(voicePaths(dataDir).marker, "utf8"));
23650
23773
  } catch {
23651
23774
  return null;
23652
23775
  }
@@ -23743,8 +23866,8 @@ async function voiceSetupCommand(io2, deps = {}, args = []) {
23743
23866
  io2.err("Python 3.10 or newer is required. Install it from https://www.python.org/downloads/ and run this again.");
23744
23867
  return 1;
23745
23868
  }
23746
- mkdirSync19(p.home, { recursive: true });
23747
- if (!existsSync24(p.python)) {
23869
+ mkdirSync20(p.home, { recursive: true });
23870
+ if (!existsSync25(p.python)) {
23748
23871
  io2.out("1/3 Creating a private Python environment\u2026");
23749
23872
  const r = await run2(py.cmd, [...py.args, "-m", "venv", p.venv], { onLine });
23750
23873
  if (r.code !== 0) {
@@ -23778,7 +23901,7 @@ ${tail(dl.stdout)}`);
23778
23901
  return 1;
23779
23902
  }
23780
23903
  const marker = { python: p.python, sttModel: cfg.voice.sttModel, ttsVoice: cfg.voice.ttsVoice, at: Date.now() };
23781
- writeFileSync20(p.marker, JSON.stringify(marker, null, 2));
23904
+ writeFileSync21(p.marker, JSON.stringify(marker, null, 2));
23782
23905
  io2.out("Voice is ready. Start Friend with `friend start`, then hold Space to talk.");
23783
23906
  return 0;
23784
23907
  }
@@ -23794,7 +23917,7 @@ async function voiceStatusCommand(io2) {
23794
23917
  io2.out("Voice engine: not installed. Run: friend voice setup");
23795
23918
  return 0;
23796
23919
  }
23797
- if (!existsSync24(marker.python)) {
23920
+ if (!existsSync25(marker.python)) {
23798
23921
  io2.out("Voice engine: installed, but its Python is missing. Run: friend voice setup");
23799
23922
  return 0;
23800
23923
  }
@@ -23867,12 +23990,12 @@ async function voiceCommand(args, io2) {
23867
23990
  function findWebDir(explicit) {
23868
23991
  const here2 = dirname11(fileURLToPath4(import.meta.url));
23869
23992
  const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve8(here2, "../../../web/dist"), resolve8(here2, "web")];
23870
- return candidates.find((c) => !!c && existsSync25(join28(c, "index.html")));
23993
+ return candidates.find((c) => !!c && existsSync26(join29(c, "index.html")));
23871
23994
  }
23872
23995
  async function startFriend(opts) {
23873
23996
  const stored = loadConfig(opts.dataDir);
23874
23997
  const marker = stored.voice.enabled ? readMarker(opts.dataDir) : null;
23875
- const secret = randomBytes13(24).toString("hex");
23998
+ const secret = randomBytes14(24).toString("hex");
23876
23999
  const sidecar = marker ? new SidecarProcess({
23877
24000
  command: marker.python,
23878
24001
  args: [
@@ -23903,17 +24026,17 @@ async function startFriend(opts) {
23903
24026
  }
23904
24027
  });
23905
24028
  const { port } = await app.start();
23906
- const tokenFile = join28(opts.dataDir, "local-device.token");
23907
- let token = existsSync25(tokenFile) ? readFileSync18(tokenFile, "utf8").trim() : "";
24029
+ const tokenFile = join29(opts.dataDir, "local-device.token");
24030
+ let token = existsSync26(tokenFile) ? readFileSync19(tokenFile, "utf8").trim() : "";
23908
24031
  if (!token || !app.auth.resolveDevice(token)) {
23909
24032
  token = app.auth.redeemPairCode(app.auth.createPairCode(), "this-pc");
23910
- writeFileSync21(tokenFile, token, { mode: 384 });
24033
+ writeFileSync22(tokenFile, token, { mode: 384 });
23911
24034
  }
23912
24035
  const node = startDeviceNode({
23913
24036
  url: `${app.config.https ? "wss" : "ws"}://127.0.0.1:${port}/device`,
23914
24037
  token,
23915
24038
  roots: app.config.roots,
23916
- ...app.config.https ? { ca: readFileSync18(join28(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
24039
+ ...app.config.https ? { ca: readFileSync19(join29(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
23917
24040
  // this PC trusts only its own Friend's certificate
23918
24041
  });
23919
24042
  const urls = urlsFor(app.config.bind, port, void 0, app.config.https);
@@ -24083,8 +24206,8 @@ async function devicesCommand(args, io2) {
24083
24206
  }
24084
24207
 
24085
24208
  // ../agent-cli/src/commands/memory.ts
24086
- import { existsSync as existsSync26 } from "node:fs";
24087
- import { join as join29 } from "node:path";
24209
+ import { existsSync as existsSync27 } from "node:fs";
24210
+ import { join as join30 } from "node:path";
24088
24211
  var USAGE = "Usage: friend memory list | friend memory show <path> | friend memory forget <path or number> | friend memory clear";
24089
24212
  async function memoryCommand(args, io2) {
24090
24213
  const [sub, arg] = args;
@@ -24096,7 +24219,7 @@ async function memoryCommand(args, io2) {
24096
24219
  try {
24097
24220
  const memory = new Memory(db);
24098
24221
  const audit = new Audit(db);
24099
- const tree2 = existsSync26(join29(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join29(io2.dataDir, "memory")) : null;
24222
+ const tree2 = existsSync27(join30(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join30(io2.dataDir, "memory")) : null;
24100
24223
  if (sub === "show") {
24101
24224
  if (!tree2 || !arg) {
24102
24225
  io2.err(tree2 ? USAGE : "There is no memory tree yet.");
@@ -24175,8 +24298,8 @@ async function memoryCommand(args, io2) {
24175
24298
  }
24176
24299
 
24177
24300
  // ../agent-cli/src/commands/plugin.ts
24178
- import { existsSync as existsSync27, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
24179
- import { dirname as dirname12, join as join30, resolve as resolve10 } from "node:path";
24301
+ import { existsSync as existsSync28, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
24302
+ import { dirname as dirname12, join as join31, resolve as resolve10 } from "node:path";
24180
24303
  import { fileURLToPath as fileURLToPath5 } from "node:url";
24181
24304
  var USAGE2 = "Usage: friend plugin catalog | list | install <name|folder> [--yes] | enable <id> | disable <id> | remove <id>";
24182
24305
  function defaultCatalog() {
@@ -24190,10 +24313,10 @@ async function pluginCommand(args, io2, deps = {}) {
24190
24313
  const flags = rest.filter((a) => a.startsWith("--"));
24191
24314
  const arg = rest.find((a) => !a.startsWith("--"));
24192
24315
  if (sub === "catalog") {
24193
- const dirs = existsSync27(catalogDir) ? readdirSync9(catalogDir).filter((d) => statSync8(join30(catalogDir, d)).isDirectory()) : [];
24316
+ const dirs = existsSync28(catalogDir) ? readdirSync9(catalogDir).filter((d) => statSync8(join31(catalogDir, d)).isDirectory()) : [];
24194
24317
  if (dirs.length === 0) io2.out("The catalog is empty.");
24195
24318
  for (const d of dirs.sort()) {
24196
- const r = inspectPlugin(join30(catalogDir, d));
24319
+ const r = inspectPlugin(join31(catalogDir, d));
24197
24320
  if (!r.ok) {
24198
24321
  io2.out(`${d} (invalid: ${r.error})`);
24199
24322
  continue;
@@ -24209,7 +24332,7 @@ async function pluginCommand(args, io2, deps = {}) {
24209
24332
  }
24210
24333
  const db = openDb(io2.dataDir);
24211
24334
  try {
24212
- const plugins = new Plugins(db, join30(io2.dataDir, "plugins"));
24335
+ const plugins = new Plugins(db, join31(io2.dataDir, "plugins"));
24213
24336
  if (sub === "list") {
24214
24337
  const all = plugins.list();
24215
24338
  if (all.length === 0) io2.out("No plugins installed. See: friend plugin catalog");
@@ -24223,8 +24346,8 @@ async function pluginCommand(args, io2, deps = {}) {
24223
24346
  io2.err(USAGE2);
24224
24347
  return 1;
24225
24348
  }
24226
- const inCatalog = !/[\\/]/.test(arg) && existsSync27(join30(catalogDir, arg));
24227
- const source = inCatalog ? join30(catalogDir, arg) : existsSync27(resolve10(arg)) ? resolve10(arg) : null;
24349
+ const inCatalog = !/[\\/]/.test(arg) && existsSync28(join31(catalogDir, arg));
24350
+ const source = inCatalog ? join31(catalogDir, arg) : existsSync28(resolve10(arg)) ? resolve10(arg) : null;
24228
24351
  if (!source) {
24229
24352
  io2.err(`"${arg}" is not in the catalog and there is no such folder. See: friend plugin catalog`);
24230
24353
  return 1;
@@ -24279,7 +24402,7 @@ async function pluginCommand(args, io2, deps = {}) {
24279
24402
 
24280
24403
  // ../agent-cli/src/commands/onboard/index.ts
24281
24404
  import crossSpawn4 from "cross-spawn";
24282
- import { mkdirSync as mkdirSync21 } from "node:fs";
24405
+ import { mkdirSync as mkdirSync22 } from "node:fs";
24283
24406
  import { resolve as resolve11 } from "node:path";
24284
24407
 
24285
24408
  // ../agent-cli/src/commands/ollama.ts
@@ -24602,16 +24725,16 @@ function installPlan(id2, platform, have) {
24602
24725
  }
24603
24726
 
24604
24727
  // ../agent-cli/src/commands/onboard/state.ts
24605
- import { existsSync as existsSync28, mkdirSync as mkdirSync20, readFileSync as readFileSync19, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync22 } from "node:fs";
24606
- import { dirname as dirname13, join as join31 } from "node:path";
24728
+ import { existsSync as existsSync29, mkdirSync as mkdirSync21, readFileSync as readFileSync20, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync23 } from "node:fs";
24729
+ import { dirname as dirname13, join as join32 } from "node:path";
24607
24730
  var FEATURES = ["claude-code", "claude-api", "ollama", "voice", "sandbox"];
24608
24731
  var emptyState = () => ({ version: 1, done: {}, features: [], restart: [] });
24609
- var statePath = (dataDir) => join31(dataDir, "onboarding.json");
24732
+ var statePath = (dataDir) => join32(dataDir, "onboarding.json");
24610
24733
  function loadState(dataDir) {
24611
24734
  const f = statePath(dataDir);
24612
- if (!existsSync28(f)) return emptyState();
24735
+ if (!existsSync29(f)) return emptyState();
24613
24736
  try {
24614
- const raw = JSON.parse(readFileSync19(f, "utf8"));
24737
+ const raw = JSON.parse(readFileSync20(f, "utf8"));
24615
24738
  const done = raw.done && typeof raw.done === "object" ? Object.fromEntries(Object.entries(raw.done).filter(([, v]) => typeof v === "string")) : {};
24616
24739
  const features2 = Array.isArray(raw.features) ? raw.features.filter((x) => FEATURES.includes(x)) : [];
24617
24740
  const restart = Array.isArray(raw.restart) ? raw.restart.filter((x) => typeof x === "string") : [];
@@ -24622,9 +24745,9 @@ function loadState(dataDir) {
24622
24745
  }
24623
24746
  function saveState(dataDir, state) {
24624
24747
  const f = statePath(dataDir);
24625
- mkdirSync20(dirname13(f), { recursive: true });
24748
+ mkdirSync21(dirname13(f), { recursive: true });
24626
24749
  const tmp = `${f}.tmp`;
24627
- writeFileSync22(tmp, JSON.stringify(state, null, 2));
24750
+ writeFileSync23(tmp, JSON.stringify(state, null, 2));
24628
24751
  renameSync5(tmp, f);
24629
24752
  }
24630
24753
  function resetState(dataDir) {
@@ -24980,7 +25103,7 @@ async function workspace(c) {
24980
25103
  const answer = await text3(c.ui, current ? "Workspace folder" : "Workspace folder (Enter to skip)", current ?? "");
24981
25104
  if (answer) {
24982
25105
  const abs = resolve11(answer);
24983
- mkdirSync21(abs, { recursive: true });
25106
+ mkdirSync22(abs, { recursive: true });
24984
25107
  cfg.roots = [abs];
24985
25108
  saveConfig(cfg);
24986
25109
  io2.out(`Workspace: ${abs}`);
@@ -25234,8 +25357,8 @@ async function usageCommand(args, io2, log) {
25234
25357
  }
25235
25358
 
25236
25359
  // ../agent-cli/src/commands/audit.ts
25237
- import { writeFileSync as writeFileSync23 } from "node:fs";
25238
- import { join as join32 } from "node:path";
25360
+ import { writeFileSync as writeFileSync24 } from "node:fs";
25361
+ import { join as join33 } from "node:path";
25239
25362
  var USAGE5 = [
25240
25363
  "Usage: friend audit list [--since 2h|1d|7d] [--who owner|assistant|worker|system|outsider|<worker name>] [--group approvals|tools|workers|logins|messages|settings|system] [--result refused|failed|done] [--q text] [--limit N]",
25241
25364
  " friend audit show <request-id>",
@@ -25340,7 +25463,7 @@ async function auditCommand(args, io2, deps = {}) {
25340
25463
  afterwards = async (res2) => {
25341
25464
  const raw = /filename="([^"]+)"/.exec(res2.headers.get("content-disposition") ?? "")?.[1] ?? `friend-audit.${f.query.format}`;
25342
25465
  const name = (raw.split(/[\\/]/).pop() ?? "friend-audit").replace(/[^A-Za-z0-9._-]/g, "_") || "friend-audit";
25343
- (deps.write ?? ((n2, b) => writeFileSync23(join32(process.cwd(), n2), b)))(name, await res2.text());
25466
+ (deps.write ?? ((n2, b) => writeFileSync24(join33(process.cwd(), n2), b)))(name, await res2.text());
25344
25467
  io2.out(`Saved ${name} in this folder. It contains private content: keep it safe.`);
25345
25468
  return 0;
25346
25469
  };
@@ -25368,9 +25491,9 @@ async function auditCommand(args, io2, deps = {}) {
25368
25491
 
25369
25492
  // ../agent-cli/src/commands/daemon.ts
25370
25493
  import { spawn as spawn13, spawnSync as spawnSync3 } from "node:child_process";
25371
- import { closeSync as closeSync2, existsSync as existsSync29, mkdirSync as mkdirSync22, openSync as openSync2, readFileSync as readFileSync20, renameSync as renameSync6, rmSync as rmSync14, statSync as statSync9, writeFileSync as writeFileSync24 } from "node:fs";
25494
+ import { closeSync as closeSync2, existsSync as existsSync30, mkdirSync as mkdirSync23, openSync as openSync2, readFileSync as readFileSync21, renameSync as renameSync6, rmSync as rmSync14, statSync as statSync9, writeFileSync as writeFileSync25 } from "node:fs";
25372
25495
  import { connect } from "node:net";
25373
- import { join as join33 } from "node:path";
25496
+ import { join as join34 } from "node:path";
25374
25497
  var USAGE6 = "Usage: friend daemon start | stop | restart | status";
25375
25498
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
25376
25499
  var sleep2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
@@ -25426,11 +25549,11 @@ var realDeps = {
25426
25549
  },
25427
25550
  now: Date.now
25428
25551
  };
25429
- var pidFile = (dataDir) => join33(dataDir, "friend.pid");
25430
- var logFileOf = (dataDir) => join33(dataDir, "friend.log");
25552
+ var pidFile = (dataDir) => join34(dataDir, "friend.pid");
25553
+ var logFileOf = (dataDir) => join34(dataDir, "friend.log");
25431
25554
  function readPid(dataDir) {
25432
25555
  try {
25433
- const r = JSON.parse(readFileSync20(pidFile(dataDir), "utf8"));
25556
+ const r = JSON.parse(readFileSync21(pidFile(dataDir), "utf8"));
25434
25557
  return Number.isInteger(r.pid) && r.pid > 0 ? r : null;
25435
25558
  } catch {
25436
25559
  return null;
@@ -25461,10 +25584,10 @@ async function start(io2, deps) {
25461
25584
  io2.err(`Port ${cfg.port} is already in use. Friend may be running in a terminal (stop it with Ctrl+C), or another program uses that port (friend lan port N).`);
25462
25585
  return 1;
25463
25586
  }
25464
- mkdirSync22(io2.dataDir, { recursive: true });
25587
+ mkdirSync23(io2.dataDir, { recursive: true });
25465
25588
  const log = logFileOf(io2.dataDir);
25466
25589
  try {
25467
- if (existsSync29(log) && statSync9(log).size > MAX_LOG_BYTES) renameSync6(log, `${log}.old`);
25590
+ if (existsSync30(log) && statSync9(log).size > MAX_LOG_BYTES) renameSync6(log, `${log}.old`);
25468
25591
  } catch {
25469
25592
  }
25470
25593
  const pid = deps.launch(log);
@@ -25472,7 +25595,7 @@ async function start(io2, deps) {
25472
25595
  io2.err("Could not start Friend in the background.");
25473
25596
  return 1;
25474
25597
  }
25475
- writeFileSync24(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
25598
+ writeFileSync25(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
25476
25599
  for (let i = 0; i < 60; i++) {
25477
25600
  if (await deps.portOpen(cfg.port, 300)) {
25478
25601
  io2.out(`Friend is running in the background (pid ${pid}) at ${urls.local}`);
@@ -25538,10 +25661,10 @@ async function daemonCommand(args, io2, deps = realDeps) {
25538
25661
  // ../agent-cli/src/commands/upgrade.ts
25539
25662
  import crossSpawn5 from "cross-spawn";
25540
25663
  import { appendFileSync } from "node:fs";
25541
- import { join as join34 } from "node:path";
25664
+ import { join as join35 } from "node:path";
25542
25665
  var PACKAGE2 = "friend-assistant";
25543
25666
  var real2 = {
25544
- current: () => true ? "0.1.70" : "development",
25667
+ current: () => true ? "0.1.72" : "development",
25545
25668
  latest: () => new Promise((resolve13) => {
25546
25669
  const child = crossSpawn5("npm", ["view", PACKAGE2, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
25547
25670
  let out = "";
@@ -25579,7 +25702,7 @@ async function upgradeCommand(args, io0, deps = real2) {
25579
25702
  io0.err("Usage: friend upgrade [--force] [--auto]");
25580
25703
  return 1;
25581
25704
  }
25582
- const log = deps.log ?? ((line2) => appendFileSync(join34(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
25705
+ const log = deps.log ?? ((line2) => appendFileSync(join35(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
25583
25706
  `));
25584
25707
  const io2 = auto ? {
25585
25708
  ...io0,
@@ -25697,7 +25820,7 @@ async function claudeCommand(args, io2, deps = {}) {
25697
25820
  }
25698
25821
 
25699
25822
  // ../agent-cli/src/commands/setup.ts
25700
- import { mkdirSync as mkdirSync23 } from "node:fs";
25823
+ import { mkdirSync as mkdirSync24 } from "node:fs";
25701
25824
  import { resolve as resolve12 } from "node:path";
25702
25825
  async function setupCommand3(io2) {
25703
25826
  const db = openDb(io2.dataDir);
@@ -25723,7 +25846,7 @@ async function setupCommand3(io2) {
25723
25846
  const cfg = loadConfig(io2.dataDir);
25724
25847
  if (workspace2) {
25725
25848
  const abs = resolve12(workspace2);
25726
- mkdirSync23(abs, { recursive: true });
25849
+ mkdirSync24(abs, { recursive: true });
25727
25850
  cfg.roots = [abs];
25728
25851
  }
25729
25852
  if (apiKey) cfg.apiKey = apiKey;
@@ -25859,7 +25982,7 @@ async function run(argv, io2) {
25859
25982
  case "version":
25860
25983
  case "--version":
25861
25984
  case "-v":
25862
- io2.out(true ? "0.1.70" : "development");
25985
+ io2.out(true ? "0.1.72" : "development");
25863
25986
  return 0;
25864
25987
  case "lan":
25865
25988
  return await lanCommand(rest, io2);