friend-assistant 0.1.71 → 0.1.73

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 {
@@ -8629,15 +8724,24 @@ var LockoutError = class extends Error {
8629
8724
  }
8630
8725
  retryAfterMs;
8631
8726
  };
8727
+ var FORGET_AFTER_MS = 24 * 3600 * 1e3;
8632
8728
  var RateLimiter = class {
8633
- constructor(clock2, maxFails = 5, baseLockMs = 6e4) {
8729
+ constructor(clock2, maxFails = 5, baseLockMs = 6e4, store2) {
8634
8730
  this.clock = clock2;
8635
8731
  this.maxFails = maxFails;
8636
8732
  this.baseLockMs = baseLockMs;
8733
+ this.store = store2;
8734
+ if (!store2) return;
8735
+ const now = clock2();
8736
+ for (const r of store2.load()) {
8737
+ if (now - r.updatedAt > FORGET_AFTER_MS) store2.remove(r.key);
8738
+ else this.entries.set(r.key, { fails: r.fails, lockedUntil: r.lockedUntil, updatedAt: r.updatedAt });
8739
+ }
8637
8740
  }
8638
8741
  clock;
8639
8742
  maxFails;
8640
8743
  baseLockMs;
8744
+ store;
8641
8745
  entries = /* @__PURE__ */ new Map();
8642
8746
  check(key2) {
8643
8747
  const e = this.entries.get(key2);
@@ -8651,7 +8755,9 @@ var RateLimiter = class {
8651
8755
  const over = e.fails - this.maxFails;
8652
8756
  e.lockedUntil = this.clock() + Math.min(this.baseLockMs * 2 ** over, 36e5);
8653
8757
  }
8758
+ e.updatedAt = this.clock();
8654
8759
  this.entries.set(key2, e);
8760
+ this.store?.save(key2, { fails: e.fails, lockedUntil: e.lockedUntil, updatedAt: e.updatedAt });
8655
8761
  }
8656
8762
  /** Wrong tries left before the next lock. Once locked before, one wrong try is enough to lock again, for longer. */
8657
8763
  triesLeft(key2) {
@@ -8666,6 +8772,7 @@ var RateLimiter = class {
8666
8772
  }
8667
8773
  reset(key2) {
8668
8774
  this.entries.delete(key2);
8775
+ this.store?.remove(key2);
8669
8776
  }
8670
8777
  };
8671
8778
 
@@ -8673,6 +8780,20 @@ var RateLimiter = class {
8673
8780
  var SESSION_TTL_MS = 7 * 24 * 3600 * 1e3;
8674
8781
  var LOGIN_TRIES = 3;
8675
8782
  var PAIR_TTL_MS = 5 * 60 * 1e3;
8783
+ function lockoutStore(db, scope) {
8784
+ const upsert = db.prepare("insert or replace into lockouts (scope, key, fails, locked_until, updated_at) values (?, ?, ?, ?, ?)");
8785
+ const del = db.prepare("delete from lockouts where scope = ? and key = ?");
8786
+ return {
8787
+ load: () => db.prepare("select key, fails, locked_until, updated_at from lockouts where scope = ?").all(scope).map((r) => ({
8788
+ key: r.key,
8789
+ fails: r.fails,
8790
+ lockedUntil: r.locked_until,
8791
+ updatedAt: r.updated_at
8792
+ })),
8793
+ save: (key2, e) => void upsert.run(scope, key2, e.fails, e.lockedUntil, e.updatedAt),
8794
+ remove: (key2) => void del.run(scope, key2)
8795
+ };
8796
+ }
8676
8797
  var sha256 = (s) => createHash6("sha256").update(s).digest("hex");
8677
8798
  var SCRYPT_N = 131072;
8678
8799
  var LEGACY_N = 16384;
@@ -8683,7 +8804,7 @@ function scryptAsync(secret, salt, N) {
8683
8804
  );
8684
8805
  }
8685
8806
  async function hashSecret(secret) {
8686
- const salt = randomBytes4(16);
8807
+ const salt = randomBytes5(16);
8687
8808
  const key2 = await scryptAsync(secret, salt, cost);
8688
8809
  return `scrypt2$${cost}$${salt.toString("hex")}$${key2.toString("hex")}`;
8689
8810
  }
@@ -8710,8 +8831,9 @@ var Auth = class _Auth {
8710
8831
  this.db = db;
8711
8832
  this.audit = audit;
8712
8833
  this.clock = clock2;
8713
- this.limiter = new RateLimiter(clock2, LOGIN_TRIES);
8714
- this.accountLimiter = new RateLimiter(clock2, 20);
8834
+ db.exec("create table if not exists lockouts (scope text not null, key text not null, fails integer not null, locked_until integer not null, updated_at integer not null, primary key (scope, key))");
8835
+ this.limiter = new RateLimiter(clock2, LOGIN_TRIES, 6e4, lockoutStore(db, "address"));
8836
+ this.accountLimiter = new RateLimiter(clock2, 20, 6e4, lockoutStore(db, "account"));
8715
8837
  }
8716
8838
  db;
8717
8839
  audit;
@@ -8719,6 +8841,10 @@ var Auth = class _Auth {
8719
8841
  limiter;
8720
8842
  /** Account-wide limits, so rotating source addresses does not multiply the guesses. */
8721
8843
  accountLimiter;
8844
+ /** A limiter whose counts are kept in the database (for example the pairing codes), so a restart does not reset it. */
8845
+ persistentLimiter(scope, maxFails = 5) {
8846
+ return new RateLimiter(this.clock, maxFails, 6e4, lockoutStore(this.db, scope));
8847
+ }
8722
8848
  /** Where a sign-in stands for this address: the wrong tries left, and how long it is locked. Safe to show the visitor. */
8723
8849
  loginState(ip) {
8724
8850
  const key2 = `login:${ip}`;
@@ -8760,7 +8886,7 @@ var Auth = class _Auth {
8760
8886
  }
8761
8887
  succeeded();
8762
8888
  if (row2 && outdated(row2.h)) this.db.prepare("update owner set password_hash = ? where id = 1").run(await hashSecret(password));
8763
- const token = randomBytes4(32).toString("hex");
8889
+ const token = randomBytes5(32).toString("hex");
8764
8890
  const expiresAt = this.clock() + SESSION_TTL_MS;
8765
8891
  this.db.prepare("insert into sessions (token_hash, kind, expires_at, ip) values (?, 'web', ?, ?)").run(sha256(token), expiresAt, ip);
8766
8892
  this.audit.log("owner", "login.ok", { ip });
@@ -8836,7 +8962,7 @@ var Auth = class _Auth {
8836
8962
  this.audit.log("system", "secrets.reset", { password: input.newPassword !== void 0, pin: input.newPin !== void 0 });
8837
8963
  }
8838
8964
  createPairCode() {
8839
- const code = randomBytes4(5).toString("hex").toUpperCase();
8965
+ const code = randomBytes5(5).toString("hex").toUpperCase();
8840
8966
  this.db.prepare("insert into pair_codes (code_hash, expires_at) values (?, ?)").run(sha256(code), this.clock() + PAIR_TTL_MS);
8841
8967
  return code;
8842
8968
  }
@@ -8848,7 +8974,7 @@ var Auth = class _Auth {
8848
8974
  this.audit.log("device", "pair.fail", { deviceName });
8849
8975
  throw new Error("Invalid or expired pairing code");
8850
8976
  }
8851
- const token = randomBytes4(32).toString("hex");
8977
+ const token = randomBytes5(32).toString("hex");
8852
8978
  this.db.prepare("insert into devices (name, token_hash, last_seen) values (?, ?, ?)").run(deviceName, sha256(token), this.clock());
8853
8979
  this.audit.log("device", "pair.ok", { deviceName });
8854
8980
  return token;
@@ -9578,8 +9704,8 @@ var AuditQuery = class {
9578
9704
  };
9579
9705
 
9580
9706
  // ../server/src/auditRetention.ts
9581
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
9582
- import { join as join13 } from "node:path";
9707
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
9708
+ import { join as join14 } from "node:path";
9583
9709
  import { gzipSync } from "node:zlib";
9584
9710
  var DAY = 864e5;
9585
9711
  var APPEND_ONLY = "create trigger audit_no_delete before delete on audit_log begin select raise(abort, 'audit_log is append-only'); end;";
@@ -9597,9 +9723,9 @@ function pruneAudit(db, o) {
9597
9723
  let archivePath = null;
9598
9724
  if (o.archive) {
9599
9725
  const rows4 = db.prepare("select * from audit_log where id between ? and ? order by id").all(fromId, toId);
9600
- mkdirSync8(o.dir, { recursive: true });
9601
- archivePath = join13(o.dir, `audit-${fromId}-${toId}.jsonl.gz`);
9602
- writeFileSync7(archivePath, gzipSync(`${rows4.map((r) => JSON.stringify(r)).join("\n")}
9726
+ mkdirSync9(o.dir, { recursive: true });
9727
+ archivePath = join14(o.dir, `audit-${fromId}-${toId}.jsonl.gz`);
9728
+ writeFileSync8(archivePath, gzipSync(`${rows4.map((r) => JSON.stringify(r)).join("\n")}
9603
9729
  `));
9604
9730
  }
9605
9731
  const audit = new Audit(db);
@@ -10085,8 +10211,8 @@ function detectSetups(symbol, s) {
10085
10211
  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 });
10086
10212
  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 });
10087
10213
  }
10088
- const open2 = day2[0].o;
10089
- if (last.c <= open2 * (1 - BOUNCE_DROP) && last.c > last.o && last.v > avgVol) {
10214
+ const open3 = day2[0].o;
10215
+ if (last.c <= open3 * (1 - BOUNCE_DROP) && last.c > last.o && last.v > avgVol) {
10090
10216
  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 });
10091
10217
  }
10092
10218
  for (const o of out) if (o.state === "triggered" && o.at && minutes(o.at) >= TOO_LATE_MINUTES) o.state = "late";
@@ -10324,7 +10450,7 @@ async function runMarketTool(name, args, d, signal) {
10324
10450
  }
10325
10451
 
10326
10452
  // ../server/src/media.ts
10327
- import { randomBytes as randomBytes5 } from "node:crypto";
10453
+ import { randomBytes as randomBytes6 } from "node:crypto";
10328
10454
  import { promises as fs } from "node:fs";
10329
10455
  import { basename, extname, isAbsolute, relative as relative2, resolve as resolve4, sep } from "node:path";
10330
10456
  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" };
@@ -10430,7 +10556,7 @@ var MediaStore = class {
10430
10556
  this.db.prepare("update media set mime = ?, size = ?, created_at = ? where id = ?").run(mime, size, this.clock(), existing.id);
10431
10557
  return existing.id;
10432
10558
  }
10433
- const id2 = randomBytes5(16).toString("hex");
10559
+ const id2 = randomBytes6(16).toString("hex");
10434
10560
  this.db.prepare("insert into media (id, path, mime, size, created_at) values (?, ?, ?, ?, ?)").run(id2, path3, mime, size, this.clock());
10435
10561
  return id2;
10436
10562
  }
@@ -10517,7 +10643,7 @@ var MediaStore = class {
10517
10643
 
10518
10644
  // ../server/src/channels/hub.ts
10519
10645
  import { promises as fsp } from "node:fs";
10520
- import { createHmac, randomBytes as randomBytes6, randomInt, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
10646
+ import { createHmac, randomBytes as randomBytes7, randomInt, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
10521
10647
  var CHANNEL_LABEL = { telegram: "Telegram", sms: "SMS", whatsapp: "WhatsApp" };
10522
10648
  var VoiceMessageError = class extends Error {
10523
10649
  };
@@ -10998,7 +11124,7 @@ ${reply}` : reply);
10998
11124
  const now = this.now();
10999
11125
  for (const [k, v] of this.outbox) if (v.expires <= now) this.outbox.delete(k);
11000
11126
  while (this.outbox.size >= OUTBOX_MAX) this.outbox.delete(this.outbox.keys().next().value);
11001
- const token = randomBytes6(16).toString("hex");
11127
+ const token = randomBytes7(16).toString("hex");
11002
11128
  this.outbox.set(token, { path: file.path, mime: file.mime, name: file.name, expires: now + OUTBOX_TTL_MS });
11003
11129
  return token;
11004
11130
  }
@@ -11852,9 +11978,9 @@ ${lines.join("\n")}${found.total > lines.length ? `
11852
11978
  };
11853
11979
 
11854
11980
  // ../server/src/music/oauth.ts
11855
- import { createHash as createHash9, randomBytes as randomBytes7 } from "node:crypto";
11856
- import { chmodSync as chmodSync4, existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync8, rmSync as rmSync7, writeFileSync as writeFileSync8 } from "node:fs";
11857
- import { join as join14 } from "node:path";
11981
+ import { createHash as createHash9, randomBytes as randomBytes8 } from "node:crypto";
11982
+ import { chmodSync as chmodSync5, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync9, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "node:fs";
11983
+ import { join as join15 } from "node:path";
11858
11984
  var STATE_TTL_MS = 10 * 6e4;
11859
11985
  var MAX_STATES = 20;
11860
11986
  var REFRESH_AHEAD_MS = 6e4;
@@ -11863,7 +11989,7 @@ var RefreshRejected = class extends Error {
11863
11989
  };
11864
11990
  var b64url = (b) => b.toString("base64url");
11865
11991
  var challengeOf = (verifier) => b64url(createHash9("sha256").update(verifier).digest());
11866
- function pkcePair(random = randomBytes7) {
11992
+ function pkcePair(random = randomBytes8) {
11867
11993
  const verifier = b64url(random(48));
11868
11994
  return { verifier, challenge: challengeOf(verifier) };
11869
11995
  }
@@ -11874,7 +12000,7 @@ var OAuthStates = class {
11874
12000
  clock;
11875
12001
  pending = /* @__PURE__ */ new Map();
11876
12002
  issue(source, verifier) {
11877
- const state = b64url(randomBytes7(24));
12003
+ const state = b64url(randomBytes8(24));
11878
12004
  this.pending.set(state, { source, verifier, at: this.clock() });
11879
12005
  while (this.pending.size > MAX_STATES) this.pending.delete(this.pending.keys().next().value);
11880
12006
  return state;
@@ -11898,23 +12024,23 @@ var MusicTokens = class {
11898
12024
  reconnect = /* @__PURE__ */ new Set();
11899
12025
  generations = /* @__PURE__ */ new Map();
11900
12026
  file(source) {
11901
- return join14(this.dir, `music-${source}.tokens.json`);
12027
+ return join15(this.dir, `music-${source}.tokens.json`);
11902
12028
  }
11903
12029
  save(source, login) {
11904
- mkdirSync9(this.dir, { recursive: true });
12030
+ mkdirSync10(this.dir, { recursive: true });
11905
12031
  const file = this.file(source);
11906
- writeFileSync8(file, JSON.stringify(login), { mode: 384 });
12032
+ writeFileSync9(file, JSON.stringify(login), { mode: 384 });
11907
12033
  try {
11908
- chmodSync4(file, 384);
12034
+ chmodSync5(file, 384);
11909
12035
  } catch {
11910
12036
  }
11911
12037
  this.reconnect.delete(source);
11912
12038
  }
11913
12039
  load(source) {
11914
12040
  const file = this.file(source);
11915
- if (!existsSync13(file)) return null;
12041
+ if (!existsSync14(file)) return null;
11916
12042
  try {
11917
- const j = JSON.parse(readFileSync8(file, "utf8"));
12043
+ const j = JSON.parse(readFileSync9(file, "utf8"));
11918
12044
  if (typeof j.accessToken !== "string" || typeof j.refreshToken !== "string" || typeof j.expiresAt !== "number" || typeof j.account !== "string") return null;
11919
12045
  return { accessToken: j.accessToken, refreshToken: j.refreshToken, expiresAt: j.expiresAt, account: j.account, premium: typeof j.premium === "boolean" ? j.premium : null };
11920
12046
  } catch {
@@ -11944,21 +12070,21 @@ var MusicSecrets = class {
11944
12070
  }
11945
12071
  dir;
11946
12072
  file(source) {
11947
- return join14(this.dir, `music-${source}.secret.json`);
12073
+ return join15(this.dir, `music-${source}.secret.json`);
11948
12074
  }
11949
12075
  set(source, secret) {
11950
- mkdirSync9(this.dir, { recursive: true });
12076
+ mkdirSync10(this.dir, { recursive: true });
11951
12077
  const file = this.file(source);
11952
- writeFileSync8(file, JSON.stringify({ secret }), { mode: 384 });
12078
+ writeFileSync9(file, JSON.stringify({ secret }), { mode: 384 });
11953
12079
  try {
11954
- chmodSync4(file, 384);
12080
+ chmodSync5(file, 384);
11955
12081
  } catch {
11956
12082
  }
11957
12083
  }
11958
12084
  /** For the service's own token call only. */
11959
12085
  get(source) {
11960
12086
  try {
11961
- const j = JSON.parse(readFileSync8(this.file(source), "utf8"));
12087
+ const j = JSON.parse(readFileSync9(this.file(source), "utf8"));
11962
12088
  return typeof j.secret === "string" ? j.secret : "";
11963
12089
  } catch {
11964
12090
  return "";
@@ -12546,7 +12672,7 @@ var HostPlayer = class {
12546
12672
  // ../server/src/music/library.ts
12547
12673
  import { createHash as createHash10 } from "node:crypto";
12548
12674
  import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
12549
- import { basename as basename2, extname as extname2, join as join15, sep as sep2 } from "node:path";
12675
+ import { basename as basename2, extname as extname2, join as join16, sep as sep2 } from "node:path";
12550
12676
  import { parseFile } from "music-metadata";
12551
12677
  var MAX_PAGE = 500;
12552
12678
  var MAX_COVER_BYTES = 3 * 1024 * 1024;
@@ -12601,7 +12727,7 @@ var MusicLibrary = class {
12601
12727
  const depthLimit = this.o.scanDepth();
12602
12728
  const found = [];
12603
12729
  let truncated = false;
12604
- const walk2 = async (dir, rel, depth) => {
12730
+ const walk3 = async (dir, rel, depth) => {
12605
12731
  if (truncated) return;
12606
12732
  let entries;
12607
12733
  try {
@@ -12621,7 +12747,7 @@ var MusicLibrary = class {
12621
12747
  if (e.name.startsWith(".") || e.isSymbolicLink()) continue;
12622
12748
  const childRel = rel ? `${rel}${sep2}${e.name}` : e.name;
12623
12749
  if (e.isDirectory()) {
12624
- if (depth < depthLimit) await walk2(join15(dir, e.name), childRel, depth + 1);
12750
+ if (depth < depthLimit) await walk3(join16(dir, e.name), childRel, depth + 1);
12625
12751
  } else if (e.isFile() && allowed.has(extname2(e.name).slice(1).toLowerCase())) {
12626
12752
  if (found.length >= max) {
12627
12753
  truncated = true;
@@ -12631,7 +12757,7 @@ var MusicLibrary = class {
12631
12757
  }
12632
12758
  }
12633
12759
  };
12634
- await walk2(root, "", 0);
12760
+ await walk3(root, "", 0);
12635
12761
  const tracks = new Array(found.length);
12636
12762
  let next = 0;
12637
12763
  const worker = async () => {
@@ -12653,7 +12779,7 @@ var MusicLibrary = class {
12653
12779
  const name = basename2(rel);
12654
12780
  const ext = extname2(name).slice(1).toLowerCase();
12655
12781
  const stem = name.slice(0, name.length - extname2(name).length);
12656
- const parent = rel.includes(sep2) ? basename2(join15(rel, "..")) : "";
12782
+ const parent = rel.includes(sep2) ? basename2(join16(rel, "..")) : "";
12657
12783
  let title2 = "";
12658
12784
  let artist = "";
12659
12785
  let album = "";
@@ -12661,7 +12787,7 @@ var MusicLibrary = class {
12661
12787
  let durationSec = null;
12662
12788
  let embedded = false;
12663
12789
  try {
12664
- const m = await parseFile(join15(root, rel));
12790
+ const m = await parseFile(join16(root, rel));
12665
12791
  title2 = m.common.title?.trim() ?? "";
12666
12792
  artist = (m.common.artist ?? m.common.albumartist ?? "").trim();
12667
12793
  album = m.common.album?.trim() ?? "";
@@ -12704,7 +12830,7 @@ var MusicLibrary = class {
12704
12830
  if (!t || !this.root) return null;
12705
12831
  const allowed = this.o.extensions().map((e) => e.toLowerCase().replace(/^\./, ""));
12706
12832
  if (!allowed.includes(t.ext)) return null;
12707
- return this.inside(join15(this.root, t.rel));
12833
+ return this.inside(join16(this.root, t.rel));
12708
12834
  }
12709
12835
  async inside(path3) {
12710
12836
  try {
@@ -12722,7 +12848,7 @@ var MusicLibrary = class {
12722
12848
  const t = this.tracks.find((x) => x.id === id2);
12723
12849
  if (!t || !this.root) return null;
12724
12850
  if (t.coverFile) {
12725
- const path3 = await this.inside(join15(this.root, t.coverFile));
12851
+ const path3 = await this.inside(join16(this.root, t.coverFile));
12726
12852
  if (path3) {
12727
12853
  try {
12728
12854
  if ((await stat(path3)).size <= MAX_COVER_BYTES) return { mime: COVER_EXT[extname2(path3).slice(1).toLowerCase()], data: await readFile(path3) };
@@ -12731,7 +12857,7 @@ var MusicLibrary = class {
12731
12857
  }
12732
12858
  }
12733
12859
  if (t.embedded) {
12734
- const path3 = await this.inside(join15(this.root, t.rel));
12860
+ const path3 = await this.inside(join16(this.root, t.rel));
12735
12861
  if (path3) {
12736
12862
  try {
12737
12863
  const pic = (await parseFile(path3)).common.picture?.[0];
@@ -13228,11 +13354,11 @@ function buildReport(input) {
13228
13354
  out.push("");
13229
13355
  if (!snap.positions.ok) out.push(missing("Positions", snap.positions));
13230
13356
  else {
13231
- const open2 = snap.positions.data.filter((p) => p.quantity !== 0);
13232
- if (open2.length === 0) out.push("No open positions.");
13357
+ const open3 = snap.positions.data.filter((p) => p.quantity !== 0);
13358
+ if (open3.length === 0) out.push("No open positions.");
13233
13359
  else {
13234
13360
  out.push("Open positions:");
13235
- 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)}`);
13361
+ 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)}`);
13236
13362
  }
13237
13363
  }
13238
13364
  }
@@ -13346,9 +13472,9 @@ var ReportSchedules = class {
13346
13472
  };
13347
13473
 
13348
13474
  // ../server/src/brokers/session.ts
13349
- import { randomBytes as randomBytes8 } from "node:crypto";
13350
- import { chmodSync as chmodSync5, existsSync as existsSync14, mkdirSync as mkdirSync10, readFileSync as readFileSync9, rmSync as rmSync8, writeFileSync as writeFileSync9 } from "node:fs";
13351
- import { join as join16 } from "node:path";
13475
+ import { randomBytes as randomBytes9 } from "node:crypto";
13476
+ import { chmodSync as chmodSync6, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync10, rmSync as rmSync8, writeFileSync as writeFileSync10 } from "node:fs";
13477
+ import { join as join17 } from "node:path";
13352
13478
  var STATE_TTL_MS2 = 10 * 6e4;
13353
13479
  var MAX_STATES2 = 20;
13354
13480
  var BROKER_ID = /^[a-z0-9-]{1,40}$/;
@@ -13362,14 +13488,14 @@ var BrokerSessions = class {
13362
13488
  states = /* @__PURE__ */ new Map();
13363
13489
  file(broker) {
13364
13490
  if (!BROKER_ID.test(broker)) throw new Error("That is not a broker id.");
13365
- return join16(this.dir, `broker-${broker}.session.json`);
13491
+ return join17(this.dir, `broker-${broker}.session.json`);
13366
13492
  }
13367
13493
  save(broker, info) {
13368
13494
  const file = this.file(broker);
13369
- mkdirSync10(this.dir, { recursive: true });
13370
- writeFileSync9(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
13495
+ mkdirSync11(this.dir, { recursive: true });
13496
+ writeFileSync10(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
13371
13497
  try {
13372
- chmodSync5(file, 384);
13498
+ chmodSync6(file, 384);
13373
13499
  } catch {
13374
13500
  }
13375
13501
  }
@@ -13377,9 +13503,9 @@ var BrokerSessions = class {
13377
13503
  load(broker) {
13378
13504
  if (!BROKER_ID.test(broker)) return null;
13379
13505
  const file = this.file(broker);
13380
- if (!existsSync14(file)) return null;
13506
+ if (!existsSync15(file)) return null;
13381
13507
  try {
13382
- const raw = JSON.parse(readFileSync9(file, "utf8"));
13508
+ const raw = JSON.parse(readFileSync10(file, "utf8"));
13383
13509
  if (typeof raw.accessToken !== "string" || typeof raw.expiresAt !== "number") return null;
13384
13510
  if (raw.expiresAt <= this.clock()) {
13385
13511
  this.clear(broker);
@@ -13396,7 +13522,7 @@ var BrokerSessions = class {
13396
13522
  }
13397
13523
  /** A fresh unguessable code for one login at `broker`. At most twenty wait at once; the oldest is dropped. */
13398
13524
  newState(broker) {
13399
- const state = randomBytes8(24).toString("hex");
13525
+ const state = randomBytes9(24).toString("hex");
13400
13526
  this.states.set(state, { broker, at: this.clock() });
13401
13527
  while (this.states.size > MAX_STATES2) this.states.delete(this.states.keys().next().value);
13402
13528
  return state;
@@ -13715,9 +13841,9 @@ ${url}`);
13715
13841
  // ../server/src/codebox.ts
13716
13842
  import { spawn as spawn4 } from "node:child_process";
13717
13843
  import { randomUUID as randomUUID5 } from "node:crypto";
13718
- import { chmodSync as chmodSync6, mkdtempSync as mkdtempSync2, rmSync as rmSync9, writeFileSync as writeFileSync10 } from "node:fs";
13844
+ import { chmodSync as chmodSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
13719
13845
  import { tmpdir as tmpdir2 } from "node:os";
13720
- import { join as join17 } from "node:path";
13846
+ import { join as join18 } from "node:path";
13721
13847
  var MAX_CODE_CHARS = 5e4;
13722
13848
  var MAX_OUTPUT_CHARS = 2e4;
13723
13849
  var MAX_EXTRA_FILES = 10;
@@ -13777,15 +13903,15 @@ var CodeBox = class {
13777
13903
  if (extra.reduce((sum, [, body]) => sum + body.length, 0) > MAX_EXTRA_FILE_CHARS) return { ok: false, error: "The sandbox files are too large." };
13778
13904
  const setup = SETUP[input.language];
13779
13905
  const timeoutMs = input.timeoutSec && input.timeoutSec > 0 ? Math.min(input.timeoutSec * 1e3, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
13780
- const dir = mkdtempSync2(join17(tmpdir2(), "friend-code-"));
13906
+ const dir = mkdtempSync2(join18(tmpdir2(), "friend-code-"));
13781
13907
  try {
13782
- const file = join17(dir, setup.file);
13783
- writeFileSync10(file, input.code);
13784
- chmodSync6(dir, 493);
13785
- chmodSync6(file, 420);
13908
+ const file = join18(dir, setup.file);
13909
+ writeFileSync11(file, input.code);
13910
+ chmodSync7(dir, 493);
13911
+ chmodSync7(file, 420);
13786
13912
  for (const [name, body] of extra) {
13787
- writeFileSync10(join17(dir, name), body);
13788
- chmodSync6(join17(dir, name), 420);
13913
+ writeFileSync11(join18(dir, name), body);
13914
+ chmodSync7(join18(dir, name), 420);
13789
13915
  }
13790
13916
  const args = [
13791
13917
  "run",
@@ -13929,26 +14055,26 @@ var Memory = class {
13929
14055
  };
13930
14056
 
13931
14057
  // ../server/src/memory/import.ts
13932
- import { existsSync as existsSync15, writeFileSync as writeFileSync11 } from "node:fs";
13933
- import { join as join18 } from "node:path";
14058
+ import { existsSync as existsSync16, writeFileSync as writeFileSync12 } from "node:fs";
14059
+ import { join as join19 } from "node:path";
13934
14060
  var MARKER = ".imported-notes";
13935
14061
  function importFlatNotes(memory, tree2) {
13936
14062
  tree2.ensure();
13937
- const marker = join18(tree2.root, MARKER);
13938
- if (existsSync15(marker)) return 0;
14063
+ const marker = join19(tree2.root, MARKER);
14064
+ if (existsSync16(marker)) return 0;
13939
14065
  let n2 = 0;
13940
14066
  for (const m of [...memory.list()].reverse()) {
13941
14067
  const name = inboxName(m.text, (x) => tree2.has(`inbox/${x}.md`));
13942
14068
  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" } : {} });
13943
14069
  if (r.ok) n2++;
13944
14070
  }
13945
- writeFileSync11(marker, (/* @__PURE__ */ new Date()).toISOString());
14071
+ writeFileSync12(marker, (/* @__PURE__ */ new Date()).toISOString());
13946
14072
  return n2;
13947
14073
  }
13948
14074
 
13949
14075
  // ../server/src/memory/keeper.ts
13950
- import { existsSync as existsSync16, readFileSync as readFileSync10, writeFileSync as writeFileSync12 } from "node:fs";
13951
- import { join as join19 } from "node:path";
14076
+ import { existsSync as existsSync17, readFileSync as readFileSync11, writeFileSync as writeFileSync13 } from "node:fs";
14077
+ import { join as join20 } from "node:path";
13952
14078
  import { z as z11 } from "zod";
13953
14079
  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.
13954
14080
 
@@ -14016,12 +14142,12 @@ var MemoryKeeper = class {
14016
14142
  this.d.after?.();
14017
14143
  }
14018
14144
  cursorPath() {
14019
- return join19(this.d.tree.root, CURSOR_FILE);
14145
+ return join20(this.d.tree.root, CURSOR_FILE);
14020
14146
  }
14021
14147
  readCursor() {
14022
14148
  try {
14023
- if (!existsSync16(this.cursorPath())) return -1;
14024
- const n2 = Number(JSON.parse(readFileSync10(this.cursorPath(), "utf8")).lastId);
14149
+ if (!existsSync17(this.cursorPath())) return -1;
14150
+ const n2 = Number(JSON.parse(readFileSync11(this.cursorPath(), "utf8")).lastId);
14025
14151
  return Number.isInteger(n2) && n2 >= 0 ? n2 : -1;
14026
14152
  } catch {
14027
14153
  return -1;
@@ -14029,7 +14155,7 @@ var MemoryKeeper = class {
14029
14155
  }
14030
14156
  writeCursor(id2) {
14031
14157
  this.d.tree.ensure();
14032
- writeFileSync12(this.cursorPath(), JSON.stringify({ lastId: id2 }));
14158
+ writeFileSync13(this.cursorPath(), JSON.stringify({ lastId: id2 }));
14033
14159
  }
14034
14160
  window(after) {
14035
14161
  const max = this.d.db.prepare("select max(id) m from messages").get().m ?? 0;
@@ -14314,7 +14440,7 @@ ${n2.body.trim().slice(0, NOTE_CHARS)}`).join("\n")}`,
14314
14440
  };
14315
14441
 
14316
14442
  // ../server/src/proactive/beat.ts
14317
- import { existsSync as existsSync17, readFileSync as readFileSync11, writeFileSync as writeFileSync13 } from "node:fs";
14443
+ import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync14 } from "node:fs";
14318
14444
  var LEVEL2 = { off: 0, low: 1, medium: 2, high: 3 };
14319
14445
  var MAX_SAY = 400;
14320
14446
  var OVERDUE_AFTER_MS = 2 * 36e5;
@@ -14357,8 +14483,8 @@ var ProactiveBeat = class {
14357
14483
  }
14358
14484
  load(day2) {
14359
14485
  try {
14360
- if (existsSync17(this.d.statePath)) {
14361
- const s = JSON.parse(readFileSync11(this.d.statePath, "utf8"));
14486
+ if (existsSync18(this.d.statePath)) {
14487
+ const s = JSON.parse(readFileSync12(this.d.statePath, "utf8"));
14362
14488
  if (s.day === day2) return { day: day2, sent: s.sent ?? 0, lastAt: s.lastAt ?? 0, fired: s.fired ?? {}, said: s.said ?? [] };
14363
14489
  const week = this.now() - 7 * 864e5;
14364
14490
  return { day: day2, sent: 0, lastAt: s.lastAt ?? 0, fired: Object.fromEntries(Object.entries(s.fired ?? {}).filter(([, t]) => t > week)), said: [] };
@@ -14369,7 +14495,7 @@ var ProactiveBeat = class {
14369
14495
  }
14370
14496
  save(s) {
14371
14497
  try {
14372
- writeFileSync13(this.d.statePath, JSON.stringify(s));
14498
+ writeFileSync14(this.d.statePath, JSON.stringify(s));
14373
14499
  } catch {
14374
14500
  }
14375
14501
  }
@@ -14395,15 +14521,15 @@ var ProactiveBeat = class {
14395
14521
  }
14396
14522
  const here2 = this.d.screens() > 0 || c.phone && !!this.d.phoneReady?.();
14397
14523
  if (lvl >= 2 && here2) {
14398
- const open2 = this.d.tasks.list();
14399
- const todays = open2.filter((t) => t.dueAt !== null && dayKey2(new Date(t.dueAt)) === day2);
14524
+ const open3 = this.d.tasks.list();
14525
+ const todays = open3.filter((t) => t.dueAt !== null && dayKey2(new Date(t.dueAt)) === day2);
14400
14526
  const office = this.d.officeLine?.() ?? null;
14401
14527
  if (minute >= hm(c.morningAt) && minute < hm(c.morningAt) + 240) {
14402
14528
  out.push({
14403
14529
  key: `morning:${day2}`,
14404
14530
  kind: "morning",
14405
14531
  level: 2,
14406
- 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}`] : []]
14532
+ 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}`] : []]
14407
14533
  });
14408
14534
  }
14409
14535
  if (minute >= hm(c.eveningAt) && !within(minute, c.quietFrom, c.quietTo)) {
@@ -14518,14 +14644,14 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
14518
14644
 
14519
14645
  // ../server/src/office/office.ts
14520
14646
  import { randomUUID as randomUUID6 } from "node:crypto";
14521
- import { mkdirSync as mkdirSync11, statSync as statSync3, writeFileSync as writeFileSync14 } from "node:fs";
14522
- import { join as join20 } from "node:path";
14647
+ import { mkdirSync as mkdirSync12, statSync as statSync3, writeFileSync as writeFileSync15 } from "node:fs";
14648
+ import { join as join21 } from "node:path";
14523
14649
 
14524
14650
  // ../server/src/provider/claude-code/bridge.ts
14525
14651
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
14526
14652
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
14527
14653
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
14528
- import { randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
14654
+ import { randomBytes as randomBytes10, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
14529
14655
  import { createServer } from "node:http";
14530
14656
  var encodeToolName = (name) => name.replaceAll(".", "__");
14531
14657
  var MAX_BODY_BYTES = 8 * 1024 * 1024;
@@ -14534,7 +14660,7 @@ var ToolBridge = class {
14534
14660
  this.onCall = onCall;
14535
14661
  }
14536
14662
  onCall;
14537
- token = randomBytes9(24).toString("hex");
14663
+ token = randomBytes10(24).toString("hex");
14538
14664
  tools = [];
14539
14665
  http = null;
14540
14666
  port = 0;
@@ -15177,10 +15303,10 @@ var Office = class {
15177
15303
  const cfg = this.d.config();
15178
15304
  await run2.bridge.start();
15179
15305
  if (run2.concluded) return;
15180
- const dir = join20(this.d.dataDir, "office");
15181
- mkdirSync11(dir, { recursive: true });
15182
- const mcp = join20(dir, `${worker.id}.mcp.json`);
15183
- writeFileSync14(mcp, JSON.stringify({ mcpServers: { office: { type: "http", url: run2.bridge.url, headers: { Authorization: `Bearer ${run2.bridge.token}` } } } }));
15306
+ const dir = join21(this.d.dataDir, "office");
15307
+ mkdirSync12(dir, { recursive: true });
15308
+ const mcp = join21(dir, `${worker.id}.mcp.json`);
15309
+ writeFileSync15(mcp, JSON.stringify({ mcpServers: { office: { type: "http", url: run2.bridge.url, headers: { Authorization: `Bearer ${run2.bridge.token}` } } } }));
15184
15310
  const args = buildWorkerArgs({
15185
15311
  model: worker.model.trim() || cfg.claudeCode.model,
15186
15312
  instructions: this.briefing(worker),
@@ -15439,7 +15565,7 @@ ${ticket.description}` : "", goal: project.goal, action: describeAction(tool, in
15439
15565
  };
15440
15566
 
15441
15567
  // ../server/src/office/store.ts
15442
- import { randomBytes as randomBytes10 } from "node:crypto";
15568
+ import { randomBytes as randomBytes11 } from "node:crypto";
15443
15569
  var MAX_EVENT_CHARS = 200;
15444
15570
  var MAX_EVENTS_PER_WORKER = 500;
15445
15571
  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 });
@@ -15456,7 +15582,7 @@ var OfficeStore = class {
15456
15582
  db;
15457
15583
  now;
15458
15584
  createWorker(w) {
15459
- const id2 = randomBytes10(4).toString("hex");
15585
+ const id2 = randomBytes11(4).toString("hex");
15460
15586
  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);
15461
15587
  return this.getWorker(id2);
15462
15588
  }
@@ -15569,12 +15695,12 @@ var OfficeStore = class {
15569
15695
  };
15570
15696
 
15571
15697
  // ../server/src/app.ts
15572
- import { join as join25 } from "node:path";
15698
+ import { join as join26 } from "node:path";
15573
15699
 
15574
15700
  // ../server/src/db.ts
15575
15701
  import Database from "better-sqlite3";
15576
- import { mkdirSync as mkdirSync12 } from "node:fs";
15577
- import { join as join21 } from "node:path";
15702
+ import { mkdirSync as mkdirSync13 } from "node:fs";
15703
+ import { join as join22 } from "node:path";
15578
15704
 
15579
15705
  // ../server/src/migrations.ts
15580
15706
  var MIGRATIONS = [
@@ -15869,8 +15995,8 @@ create trigger audit_no_delete before delete on audit_log begin select raise(abo
15869
15995
 
15870
15996
  // ../server/src/db.ts
15871
15997
  function openDb(dataDir) {
15872
- mkdirSync12(dataDir, { recursive: true });
15873
- const db = new Database(join21(dataDir, "friend.db"));
15998
+ mkdirSync13(dataDir, { recursive: true });
15999
+ const db = new Database(join22(dataDir, "friend.db"));
15874
16000
  db.pragma("journal_mode = WAL");
15875
16001
  db.pragma("foreign_keys = ON");
15876
16002
  db.exec("create table if not exists schema_version (id integer primary key, applied_at integer not null)");
@@ -16199,17 +16325,17 @@ function scan2(html) {
16199
16325
  }
16200
16326
  return { title: title2, out: out.join("") };
16201
16327
  }
16202
- function firstRegion(s, open2, close) {
16203
- const a = s.indexOf(open2);
16328
+ function firstRegion(s, open3, close) {
16329
+ const a = s.indexOf(open3);
16204
16330
  if (a < 0) return null;
16205
16331
  const b = s.indexOf(close, a + 1);
16206
16332
  return s.slice(a + 1, b < 0 ? s.length : b);
16207
16333
  }
16208
- function allRegions(s, open2, close) {
16334
+ function allRegions(s, open3, close) {
16209
16335
  const parts = [];
16210
16336
  let at = 0;
16211
16337
  for (; ; ) {
16212
- const a = s.indexOf(open2, at);
16338
+ const a = s.indexOf(open3, at);
16213
16339
  if (a < 0) break;
16214
16340
  const b = s.indexOf(close, a + 1);
16215
16341
  parts.push(s.slice(a + 1, b < 0 ? s.length : b));
@@ -16501,7 +16627,7 @@ var DeviceHub = class {
16501
16627
  import fastifyCookie from "@fastify/cookie";
16502
16628
 
16503
16629
  // ../server/src/auditApi.ts
16504
- import { randomBytes as randomBytes11 } from "node:crypto";
16630
+ import { randomBytes as randomBytes12 } from "node:crypto";
16505
16631
  import { z as z13 } from "zod";
16506
16632
 
16507
16633
  // ../server/src/auditExport.ts
@@ -16550,7 +16676,7 @@ var UnlockStore = class {
16550
16676
  issue(minutes3) {
16551
16677
  const t = this.now();
16552
16678
  for (const [k, v] of this.tokens) if (v < t) this.tokens.delete(k);
16553
- const token = randomBytes11(32).toString("hex");
16679
+ const token = randomBytes12(32).toString("hex");
16554
16680
  const expiresAt = t + minutes3 * 6e4;
16555
16681
  this.tokens.set(token, expiresAt);
16556
16682
  return { token, expiresAt };
@@ -16687,15 +16813,15 @@ function registerAuditRoutes(d) {
16687
16813
  app.get("/api/audit/status", { onRequest: guard2 }, async (req) => {
16688
16814
  read("/api/audit/status", req);
16689
16815
  const last = d.audit.last();
16690
- const seal = d.query.lastSeal();
16691
- 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() };
16816
+ const seal2 = d.query.lastSeal();
16817
+ 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() };
16692
16818
  });
16693
16819
  }
16694
16820
 
16695
16821
  // ../server/src/gateway.ts
16696
16822
  import fastifyStatic from "@fastify/static";
16697
16823
  import Fastify from "fastify";
16698
- import { createReadStream as createReadStream2, existsSync as existsSync18, promises as fsp2 } from "node:fs";
16824
+ import { createReadStream as createReadStream2, existsSync as existsSync19, promises as fsp2 } from "node:fs";
16699
16825
  import { isIP as isIP3 } from "node:net";
16700
16826
  import { Readable } from "node:stream";
16701
16827
  import { WebSocket as WebSocket2, WebSocketServer } from "ws";
@@ -16931,7 +17057,7 @@ function createGateway(deps) {
16931
17057
  return reply.code(400).send({ error: e.message });
16932
17058
  }
16933
17059
  });
16934
- const pairLimiter = new RateLimiter(Date.now);
17060
+ const pairLimiter = auth.persistentLimiter("pair");
16935
17061
  app.post("/api/pair", async (req, reply) => {
16936
17062
  const body = z14.object({ code: z14.string().min(1).max(64), name: z14.string().min(1).max(64) }).safeParse(req.body);
16937
17063
  if (!body.success) return reply.code(400).send({ error: "Invalid input" });
@@ -17828,7 +17954,7 @@ function createGateway(deps) {
17828
17954
  deps.onLock?.();
17829
17955
  return { ok: true };
17830
17956
  });
17831
- if (deps.webDir && existsSync18(deps.webDir)) {
17957
+ if (deps.webDir && existsSync19(deps.webDir)) {
17832
17958
  app.register(fastifyStatic, { root: deps.webDir });
17833
17959
  app.setNotFoundHandler((req, reply) => {
17834
17960
  if (req.method === "GET" && !req.url.startsWith("/api")) return reply.sendFile("index.html");
@@ -17983,9 +18109,9 @@ Connection: close\r
17983
18109
 
17984
18110
  // ../server/src/browser/hub.ts
17985
18111
  import { spawn as spawn7, spawnSync } from "node:child_process";
17986
- import { mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync3, readdirSync as readdirSync6, readFileSync as readFileSync12, rmSync as rmSync10, statSync as statSync5 } from "node:fs";
18112
+ import { mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync3, readdirSync as readdirSync6, readFileSync as readFileSync13, rmSync as rmSync10, statSync as statSync5 } from "node:fs";
17987
18113
  import { tmpdir as tmpdir3 } from "node:os";
17988
- import { join as join22 } from "node:path";
18114
+ import { join as join23 } from "node:path";
17989
18115
 
17990
18116
  // ../server/src/browser/cdp.ts
17991
18117
  import { WebSocket as WebSocket3 } from "ws";
@@ -18055,11 +18181,11 @@ var Cdp = class _Cdp {
18055
18181
  };
18056
18182
 
18057
18183
  // ../server/src/browser/chrome.ts
18058
- import { existsSync as existsSync19, statSync as statSync4 } from "node:fs";
18184
+ import { existsSync as existsSync20, statSync as statSync4 } from "node:fs";
18059
18185
  import { posix as posix3, win32 as win323 } from "node:path";
18060
18186
  var fileThere = (p) => {
18061
18187
  try {
18062
- return existsSync19(p) && statSync4(p).isFile();
18188
+ return existsSync20(p) && statSync4(p).isFile();
18063
18189
  } catch {
18064
18190
  return false;
18065
18191
  }
@@ -18070,15 +18196,15 @@ function findChrome(override = "", w = {}) {
18070
18196
  const platform = w.platform ?? process.platform;
18071
18197
  const env = w.env ?? process.env;
18072
18198
  const isFile = w.isFile ?? fileThere;
18073
- const join35 = platform === "win32" ? win323.join : posix3.join;
18199
+ const join36 = platform === "win32" ? win323.join : posix3.join;
18074
18200
  if (override.trim()) return isFile(override.trim()) ? override.trim() : null;
18075
18201
  if (platform === "win32") {
18076
18202
  const roots = [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].filter((r) => !!r);
18077
- 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);
18203
+ 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);
18078
18204
  return null;
18079
18205
  }
18080
18206
  if (platform === "darwin") return MAC_PATHS.find(isFile) ?? null;
18081
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join35(dir, name))) return join35(dir, name);
18207
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join36(dir, name))) return join36(dir, name);
18082
18208
  return null;
18083
18209
  }
18084
18210
 
@@ -18105,7 +18231,7 @@ var BrowserHub = class {
18105
18231
  try {
18106
18232
  for (const name of readdirSync6(root)) {
18107
18233
  if (!/^friend-browser-/.test(name)) continue;
18108
- const dir = join22(root, name);
18234
+ const dir = join23(root, name);
18109
18235
  if (Date.now() - statSync5(dir).mtimeMs > 36e5) rmSync10(dir, { recursive: true, force: true });
18110
18236
  }
18111
18237
  } catch {
@@ -18169,8 +18295,8 @@ A picture of the page "${r.value.title || r.value.href}" (${r.value.href}). Text
18169
18295
  let cdp = null;
18170
18296
  try {
18171
18297
  const root = this.o.tmpRoot ?? tmpdir3();
18172
- mkdirSync13(root, { recursive: true });
18173
- profile = mkdtempSync3(join22(root, "friend-browser-"));
18298
+ mkdirSync14(root, { recursive: true });
18299
+ profile = mkdtempSync3(join23(root, "friend-browser-"));
18174
18300
  child = spawn7(
18175
18301
  chrome,
18176
18302
  [
@@ -18284,7 +18410,7 @@ async function endpoint(profile, signal) {
18284
18410
  for (; ; ) {
18285
18411
  signal.throwIfAborted();
18286
18412
  try {
18287
- const [port, path3] = readFileSync12(join22(profile, "DevToolsActivePort"), "utf8").split("\n");
18413
+ const [port, path3] = readFileSync13(join23(profile, "DevToolsActivePort"), "utf8").split("\n");
18288
18414
  if (port && path3) return `ws://127.0.0.1:${port.trim()}${path3.trim()}`;
18289
18415
  } catch {
18290
18416
  }
@@ -18526,8 +18652,8 @@ function startStatsFeed(opts) {
18526
18652
 
18527
18653
  // ../server/src/provider/claude-code/provider.ts
18528
18654
  import { createHash as createHash12 } from "node:crypto";
18529
- 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";
18530
- import { join as join23 } from "node:path";
18655
+ 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";
18656
+ import { join as join24 } from "node:path";
18531
18657
 
18532
18658
  // ../server/src/provider/claude-code/limits.ts
18533
18659
  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;
@@ -18625,7 +18751,7 @@ var NOT_SIGNED_IN = /not logged in|please run \/login|invalid api key|authentica
18625
18751
  var ClaudeCodeProvider = class {
18626
18752
  constructor(opts) {
18627
18753
  this.opts = opts;
18628
- this.home = join23(opts.dataDir, "claude");
18754
+ this.home = join24(opts.dataDir, "claude");
18629
18755
  this.now = opts.now ?? Date.now;
18630
18756
  this.bridge = new ToolBridge((call) => this.owner.inbox.push({ kind: "call", call }));
18631
18757
  }
@@ -18689,10 +18815,10 @@ var ClaudeCodeProvider = class {
18689
18815
  conv.hasContext = false;
18690
18816
  conv.systemKey = "";
18691
18817
  this.forgetSession(conv);
18692
- mkdirSync14(this.home, { recursive: true });
18818
+ mkdirSync15(this.home, { recursive: true });
18693
18819
  this.fresh = { seed: seed?.trim() || null };
18694
18820
  try {
18695
- writeFileSync15(this.freshFile(), JSON.stringify(this.fresh));
18821
+ writeFileSync16(this.freshFile(), JSON.stringify(this.fresh));
18696
18822
  } catch {
18697
18823
  }
18698
18824
  }
@@ -18851,7 +18977,7 @@ ${item.stderr}`;
18851
18977
  conv.proc = null;
18852
18978
  }
18853
18979
  conv.inbox.clear();
18854
- mkdirSync14(this.home, { recursive: true });
18980
+ mkdirSync15(this.home, { recursive: true });
18855
18981
  if (!conv.guest) {
18856
18982
  conv.sessionId ??= this.readSession();
18857
18983
  this.fresh = conv.sessionId ? null : this.readFresh();
@@ -18881,7 +19007,7 @@ ${item.stderr}`;
18881
19007
  "local",
18882
19008
  "--system-prompt-file",
18883
19009
  systemFile,
18884
- ...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] : []]
19010
+ ...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] : []]
18885
19011
  ];
18886
19012
  const proc = new ClaudeProc(
18887
19013
  {
@@ -18910,14 +19036,14 @@ ${item.stderr}`;
18910
19036
  if (!this.swept) {
18911
19037
  this.swept = true;
18912
19038
  try {
18913
- for (const f of readdirSync7(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync11(join23(this.home, f), { force: true });
19039
+ for (const f of readdirSync7(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync11(join24(this.home, f), { force: true });
18914
19040
  } catch {
18915
19041
  }
18916
19042
  }
18917
- const file = join23(this.home, `system-${++this.systemCount}.txt`);
18918
- writeFileSync15(file, text4);
19043
+ const file = join24(this.home, `system-${++this.systemCount}.txt`);
19044
+ writeFileSync16(file, text4);
18919
19045
  try {
18920
- chmodSync7(file, 384);
19046
+ chmodSync8(file, 384);
18921
19047
  } catch {
18922
19048
  }
18923
19049
  return file;
@@ -18931,20 +19057,20 @@ ${item.stderr}`;
18931
19057
  startBridge() {
18932
19058
  this.bridgeReady ??= (async () => {
18933
19059
  await this.bridge.start();
18934
- const file = join23(this.home, "mcp.json");
18935
- writeFileSync15(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
19060
+ const file = join24(this.home, "mcp.json");
19061
+ writeFileSync16(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
18936
19062
  try {
18937
- chmodSync7(file, 384);
19063
+ chmodSync8(file, 384);
18938
19064
  } catch {
18939
19065
  }
18940
19066
  })();
18941
19067
  return this.bridgeReady;
18942
19068
  }
18943
19069
  // ---- the session id, kept so a restart of Friend can pick the conversation up again ----
18944
- sessionFile = () => join23(this.home, "session-id");
19070
+ sessionFile = () => join24(this.home, "session-id");
18945
19071
  readSession() {
18946
19072
  try {
18947
- return existsSync20(this.sessionFile()) ? readFileSync13(this.sessionFile(), "utf8").trim() || null : null;
19073
+ return existsSync21(this.sessionFile()) ? readFileSync14(this.sessionFile(), "utf8").trim() || null : null;
18948
19074
  } catch {
18949
19075
  return null;
18950
19076
  }
@@ -18958,15 +19084,15 @@ ${item.stderr}`;
18958
19084
  } catch {
18959
19085
  }
18960
19086
  try {
18961
- writeFileSync15(this.sessionFile(), id2);
19087
+ writeFileSync16(this.sessionFile(), id2);
18962
19088
  } catch {
18963
19089
  }
18964
19090
  }
18965
- freshFile = () => join23(this.home, "fresh.json");
19091
+ freshFile = () => join24(this.home, "fresh.json");
18966
19092
  readFresh() {
18967
19093
  try {
18968
- if (!existsSync20(this.freshFile())) return null;
18969
- const r = JSON.parse(readFileSync13(this.freshFile(), "utf8"));
19094
+ if (!existsSync21(this.freshFile())) return null;
19095
+ const r = JSON.parse(readFileSync14(this.freshFile(), "utf8"));
18970
19096
  return { seed: typeof r.seed === "string" && r.seed ? r.seed : null };
18971
19097
  } catch {
18972
19098
  return null;
@@ -19978,10 +20104,10 @@ function dbWidgetStore(db) {
19978
20104
  }
19979
20105
 
19980
20106
  // ../server/src/tls.ts
19981
- import { chmodSync as chmodSync8, existsSync as existsSync21, mkdirSync as mkdirSync15, readFileSync as readFileSync14, writeFileSync as writeFileSync16 } from "node:fs";
20107
+ import { chmodSync as chmodSync9, existsSync as existsSync22, mkdirSync as mkdirSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync17 } from "node:fs";
19982
20108
  import { networkInterfaces } from "node:os";
19983
20109
  import { isIP as isIP4 } from "node:net";
19984
- import { join as join24 } from "node:path";
20110
+ import { join as join25 } from "node:path";
19985
20111
  import { generate } from "selfsigned";
19986
20112
  var DAYS = 825;
19987
20113
  var RENEW_BEFORE_MS = 30 * 24 * 36e5;
@@ -19996,16 +20122,16 @@ function tlsHosts(extra = [], ifaces) {
19996
20122
  return [.../* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", ...lanAddresses(ifaces), ...extra.map((h) => h.toLowerCase()).filter(Boolean)])];
19997
20123
  }
19998
20124
  async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
19999
- const dir = join24(dataDir, "tls");
20000
- const keyFile = join24(dir, "key.pem");
20001
- const certFile = join24(dir, "cert.pem");
20002
- const metaFile = join24(dir, "meta.json");
20125
+ const dir = join25(dataDir, "tls");
20126
+ const keyFile = join25(dir, "key.pem");
20127
+ const certFile = join25(dir, "cert.pem");
20128
+ const metaFile = join25(dir, "meta.json");
20003
20129
  const hosts = tlsHosts(extraHosts, ifaces);
20004
- if (existsSync21(keyFile) && existsSync21(certFile) && existsSync21(metaFile)) {
20130
+ if (existsSync22(keyFile) && existsSync22(certFile) && existsSync22(metaFile)) {
20005
20131
  try {
20006
- const meta = JSON.parse(readFileSync14(metaFile, "utf8"));
20132
+ const meta = JSON.parse(readFileSync15(metaFile, "utf8"));
20007
20133
  const covered = hosts.every((h) => meta.hosts.includes(h));
20008
- if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync14(keyFile, "utf8"), cert: readFileSync14(certFile, "utf8") };
20134
+ if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync15(keyFile, "utf8"), cert: readFileSync15(certFile, "utf8") };
20009
20135
  } catch {
20010
20136
  }
20011
20137
  }
@@ -20023,12 +20149,12 @@ async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
20023
20149
  { name: "subjectAltName", altNames }
20024
20150
  ]
20025
20151
  });
20026
- mkdirSync15(dir, { recursive: true });
20027
- writeFileSync16(keyFile, pems.private);
20028
- writeFileSync16(certFile, pems.cert);
20029
- writeFileSync16(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
20152
+ mkdirSync16(dir, { recursive: true });
20153
+ writeFileSync17(keyFile, pems.private);
20154
+ writeFileSync17(certFile, pems.cert);
20155
+ writeFileSync17(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
20030
20156
  try {
20031
- chmodSync8(keyFile, 384);
20157
+ chmodSync9(keyFile, 384);
20032
20158
  } catch {
20033
20159
  }
20034
20160
  return { key: pems.private, cert: pems.cert };
@@ -20072,7 +20198,7 @@ var DuckController = class {
20072
20198
 
20073
20199
  // ../server/src/system/autostart.ts
20074
20200
  import { spawn as spawn8 } from "node:child_process";
20075
- import { existsSync as existsSync22, mkdirSync as mkdirSync16, readFileSync as readFileSync15, rmSync as rmSync12, writeFileSync as writeFileSync17 } from "node:fs";
20201
+ import { existsSync as existsSync23, mkdirSync as mkdirSync17, readFileSync as readFileSync16, rmSync as rmSync12, writeFileSync as writeFileSync18 } from "node:fs";
20076
20202
  import { homedir as homedir4 } from "node:os";
20077
20203
  import { dirname as dirname5, posix as posix4, win32 as win324 } from "node:path";
20078
20204
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
@@ -20249,17 +20375,17 @@ function realAutostartDeps(dataDir) {
20249
20375
  uid: typeof process.getuid === "function" ? process.getuid() : 0,
20250
20376
  path: process.env.PATH ?? "",
20251
20377
  ...process.env.XDG_CONFIG_HOME ? { configHome: process.env.XDG_CONFIG_HOME } : {},
20252
- exists: (p) => existsSync22(p),
20378
+ exists: (p) => existsSync23(p),
20253
20379
  read: (p) => {
20254
20380
  try {
20255
- return readFileSync15(p, "utf8");
20381
+ return readFileSync16(p, "utf8");
20256
20382
  } catch {
20257
20383
  return null;
20258
20384
  }
20259
20385
  },
20260
20386
  write: (p, text4) => {
20261
- mkdirSync16(dirname5(p), { recursive: true });
20262
- writeFileSync17(p, text4);
20387
+ mkdirSync17(dirname5(p), { recursive: true });
20388
+ writeFileSync18(p, text4);
20263
20389
  },
20264
20390
  remove: (p) => rmSync12(p, { force: true }),
20265
20391
  run: (cmd, args) => new Promise((resolve13) => {
@@ -20280,7 +20406,7 @@ function currentSelf() {
20280
20406
  // ../server/src/system/npm.ts
20281
20407
  import { spawn as spawn9 } from "node:child_process";
20282
20408
  var PACKAGE = "friend-assistant";
20283
- var runningVersion = () => true ? "0.1.71" : "development";
20409
+ var runningVersion = () => true ? "0.1.73" : "development";
20284
20410
  async function npmLatest(fetchFn = fetch, timeoutMs = 1e4) {
20285
20411
  try {
20286
20412
  const res = await fetchFn(`https://registry.npmjs.org/${PACKAGE}/latest`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
@@ -20492,36 +20618,36 @@ var Challenges = class {
20492
20618
  };
20493
20619
 
20494
20620
  // ../server/src/voice/crypto.ts
20495
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes12 } from "node:crypto";
20496
- import { chmodSync as chmodSync9, existsSync as existsSync23, mkdirSync as mkdirSync17, readFileSync as readFileSync16, writeFileSync as writeFileSync18 } from "node:fs";
20621
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes13 } from "node:crypto";
20622
+ import { chmodSync as chmodSync10, existsSync as existsSync24, mkdirSync as mkdirSync18, readFileSync as readFileSync17, writeFileSync as writeFileSync19 } from "node:fs";
20497
20623
  import { dirname as dirname6 } from "node:path";
20498
20624
  var KEY_BYTES = 32;
20499
20625
  var IV_BYTES = 12;
20500
20626
  var TAG_BYTES = 16;
20501
20627
  function loadOrCreateKey(path3) {
20502
- if (existsSync23(path3)) {
20503
- const key3 = readFileSync16(path3);
20628
+ if (existsSync24(path3)) {
20629
+ const key3 = readFileSync17(path3);
20504
20630
  if (key3.length !== KEY_BYTES) throw new Error(`invalid voice key file (expected ${KEY_BYTES} bytes): ${path3}`);
20505
20631
  return key3;
20506
20632
  }
20507
- mkdirSync17(dirname6(path3), { recursive: true });
20508
- const key2 = randomBytes12(KEY_BYTES);
20509
- writeFileSync18(path3, key2, { mode: 384 });
20633
+ mkdirSync18(dirname6(path3), { recursive: true });
20634
+ const key2 = randomBytes13(KEY_BYTES);
20635
+ writeFileSync19(path3, key2, { mode: 384 });
20510
20636
  try {
20511
- chmodSync9(path3, 384);
20637
+ chmodSync10(path3, 384);
20512
20638
  } catch {
20513
20639
  }
20514
20640
  return key2;
20515
20641
  }
20516
20642
  function encrypt(key2, plain6) {
20517
- const iv = randomBytes12(IV_BYTES);
20518
- const cipher = createCipheriv("aes-256-gcm", key2, iv);
20643
+ const iv = randomBytes13(IV_BYTES);
20644
+ const cipher = createCipheriv2("aes-256-gcm", key2, iv);
20519
20645
  const body = Buffer.concat([cipher.update(plain6), cipher.final()]);
20520
20646
  return Buffer.concat([iv, cipher.getAuthTag(), body]);
20521
20647
  }
20522
20648
  function decrypt(key2, blob) {
20523
20649
  if (blob.length < IV_BYTES + TAG_BYTES) throw new Error("encrypted data is too short");
20524
- const decipher = createDecipheriv("aes-256-gcm", key2, blob.subarray(0, IV_BYTES));
20650
+ const decipher = createDecipheriv2("aes-256-gcm", key2, blob.subarray(0, IV_BYTES));
20525
20651
  decipher.setAuthTag(blob.subarray(IV_BYTES, IV_BYTES + TAG_BYTES));
20526
20652
  return Buffer.concat([decipher.update(blob.subarray(IV_BYTES + TAG_BYTES)), decipher.final()]);
20527
20653
  }
@@ -20909,9 +21035,9 @@ var Speaker = class {
20909
21035
  if (alive()) this.active = false;
20910
21036
  });
20911
21037
  const take = (final) => {
20912
- const open2 = fenceCount(pending) % 2 === 1;
20913
- if (open2 && !final) return;
20914
- const text4 = open2 ? pending.slice(0, pending.lastIndexOf("```")) : pending;
21038
+ const open3 = fenceCount(pending) % 2 === 1;
21039
+ if (open3 && !final) return;
21040
+ const text4 = open3 ? pending.slice(0, pending.lastIndexOf("```")) : pending;
20915
21041
  const cut = final ? text4.length : lastBoundary(text4);
20916
21042
  if (cut === 0) return;
20917
21043
  pending = final ? "" : text4.slice(cut);
@@ -21144,17 +21270,17 @@ async function createApp(opts) {
21144
21270
  void musicLibrary.scan().catch(() => {
21145
21271
  });
21146
21272
  const memory = new Memory(db);
21147
- const memoryTree = new MemoryTree(join25(opts.dataDir, "memory"));
21273
+ const memoryTree = new MemoryTree(join26(opts.dataDir, "memory"));
21148
21274
  if (config.memory.enabled) {
21149
21275
  memoryTree.ensure();
21150
21276
  importFlatNotes(memory, memoryTree);
21151
21277
  memoryTree.repair();
21152
21278
  }
21153
- const soul = new Soul(memoryTree, join25(opts.dataDir, "soul-history"));
21279
+ const soul = new Soul(memoryTree, join26(opts.dataDir, "soul-history"));
21154
21280
  soul.ensure();
21155
- const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join25(opts.dataDir, "browser-profiles") });
21281
+ const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join26(opts.dataDir, "browser-profiles") });
21156
21282
  const tasks = new Tasks(db);
21157
- const plugins = new Plugins(db, join25(opts.dataDir, "plugins"));
21283
+ const plugins = new Plugins(db, join26(opts.dataDir, "plugins"));
21158
21284
  const hub = new McpHub(new ConnectorStore(opts.dataDir));
21159
21285
  let listenPort = config.port;
21160
21286
  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) }) });
@@ -21266,13 +21392,13 @@ async function createApp(opts) {
21266
21392
  if (id2 === "audius") return changeAudiusConfig((s) => changeAudius(s, change));
21267
21393
  if (id2 === "browser") {
21268
21394
  const err2 = changeBrowserConfig((b) => changeBrowser(b, change, !!browserHub.status().chrome));
21269
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join25(catalogDir, BROWSER_SKILL));
21395
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join26(catalogDir, BROWSER_SKILL));
21270
21396
  if (!err2 && "remove" in change) plugins.remove(BROWSER_SKILL);
21271
21397
  return err2;
21272
21398
  }
21273
21399
  if (id2 === "tavily") {
21274
21400
  const err2 = changeTavilyConfig((t) => changeTavily(t, change, !!config.web.tavilyKey));
21275
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join25(catalogDir, TAVILY_SKILL));
21401
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join26(catalogDir, TAVILY_SKILL));
21276
21402
  if (!err2 && "remove" in change) plugins.remove(TAVILY_SKILL);
21277
21403
  return err2;
21278
21404
  }
@@ -21303,7 +21429,7 @@ async function createApp(opts) {
21303
21429
  }
21304
21430
  if (id2 !== "zerodha") return changeChannels((c) => changeIntegration(c, id2, change));
21305
21431
  const err = changeBrokers((b) => changeBroker(b, id2, change, (gone) => brokerHub.forget(gone)));
21306
- if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join25(catalogDir, PORTFOLIO_SKILL));
21432
+ if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join26(catalogDir, PORTFOLIO_SKILL));
21307
21433
  if (!err && "remove" in change) plugins.remove(PORTFOLIO_SKILL);
21308
21434
  return err;
21309
21435
  };
@@ -21319,7 +21445,7 @@ async function createApp(opts) {
21319
21445
  },
21320
21446
  install: (id2) => {
21321
21447
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) return { ok: false, error: "That plugin is not in the catalog." };
21322
- return plugins.install(join25(catalogDir, id2));
21448
+ return plugins.install(join26(catalogDir, id2));
21323
21449
  }
21324
21450
  },
21325
21451
  integrations: {
@@ -21718,7 +21844,7 @@ First check the work: read the whole report (office.report) and, when it changed
21718
21844
  const voice2 = opts.voice;
21719
21845
  const speaker = voice2 ? new Speaker(voice2, audit, () => config.voice.ttsVoice, () => ({ hindi: config.voice.hindiVoice || void 0, marathi: config.voice.marathiVoice || void 0 })) : null;
21720
21846
  const voiceAvailable = () => !!voice2 && voice2.available();
21721
- const voiceKey = voice2 ? loadOrCreateKey(join25(opts.dataDir, "voice.key")) : null;
21847
+ const voiceKey = voice2 ? loadOrCreateKey(join26(opts.dataDir, "voice.key")) : null;
21722
21848
  const voiceprint = voiceKey ? new Voiceprint(db, voiceKey) : null;
21723
21849
  const enrollment = voiceprint ? new Enrollment(voiceprint, SPEAKER_MODEL) : null;
21724
21850
  const household = voiceKey ? new Household(db, voiceKey) : null;
@@ -21803,7 +21929,7 @@ ${task.title}`) !== null,
21803
21929
  }
21804
21930
  },
21805
21931
  audit,
21806
- statePath: join25(opts.dataDir, "proactive.json")
21932
+ statePath: join26(opts.dataDir, "proactive.json")
21807
21933
  });
21808
21934
  async function requirePin(pin, ip) {
21809
21935
  let ok2 = false;
@@ -21894,7 +22020,7 @@ ${task.title}`) !== null,
21894
22020
  if (!isPluginId(id2)) throw new HttpError(400, "That is not a plugin name.");
21895
22021
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) throw new HttpError(404, "That plugin is not in the catalog.");
21896
22022
  await requirePin(pin, ip);
21897
- const r = plugins.install(join25(catalogDir, id2));
22023
+ const r = plugins.install(join26(catalogDir, id2));
21898
22024
  if (!r.ok) throw new HttpError(400, `That plugin cannot be installed: ${r.error}`);
21899
22025
  audit.log("owner", "plugin.installed", { id: r.id, upgraded: r.upgraded, ip });
21900
22026
  return { id: r.id, upgraded: r.upgraded };
@@ -22704,7 +22830,7 @@ ${url}`);
22704
22830
  }
22705
22831
  const prune = () => {
22706
22832
  try {
22707
- const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join25(opts.dataDir, "audit-archive"), now: Date.now() });
22833
+ const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join26(opts.dataDir, "audit-archive"), now: Date.now() });
22708
22834
  if (r.removed) audit.log("system", "audit.pruned", { removed: r.removed, archive: r.archivePath });
22709
22835
  } catch (e) {
22710
22836
  audit.log("system", "audit.prune_failed", { message: e.message.slice(0, 200) });
@@ -22714,7 +22840,7 @@ ${url}`);
22714
22840
  pruneTimer = setInterval(prune, 24 * 36e5);
22715
22841
  pruneTimer.unref?.();
22716
22842
  let lastSealAttempt = null;
22717
- const seal = async () => {
22843
+ const seal2 = async () => {
22718
22844
  try {
22719
22845
  const lastSeal = new AuditQuery(db).lastSeal({ sent: true });
22720
22846
  if (!sealDue(/* @__PURE__ */ new Date(), config.audit.sealAt, typeof lastSeal?.detail.date === "string" ? lastSeal.detail.date : null, lastSealAttempt)) return;
@@ -22723,7 +22849,7 @@ ${url}`);
22723
22849
  } catch {
22724
22850
  }
22725
22851
  };
22726
- sealTimer = setInterval(() => void seal(), 6e4);
22852
+ sealTimer = setInterval(() => void seal2(), 6e4);
22727
22853
  sealTimer.unref?.();
22728
22854
  heartbeat.start();
22729
22855
  proactive.start();
@@ -23210,8 +23336,8 @@ import { resolve as resolve9 } from "node:path";
23210
23336
  import { WebSocket as WebSocket4 } from "ws";
23211
23337
 
23212
23338
  // ../agent-cli/src/tools/fs.ts
23213
- import { closeSync, mkdirSync as mkdirSync18, openSync, readSync, readdirSync as readdirSync8, statSync as statSync7, writeFileSync as writeFileSync19 } from "node:fs";
23214
- import { dirname as dirname9, join as join26 } from "node:path";
23339
+ import { closeSync, mkdirSync as mkdirSync19, openSync, readSync, readdirSync as readdirSync8, statSync as statSync7, writeFileSync as writeFileSync20 } from "node:fs";
23340
+ import { dirname as dirname9, join as join27 } from "node:path";
23215
23341
 
23216
23342
  // ../agent-cli/src/tools/roots.ts
23217
23343
  import { lstatSync as lstatSync3, realpathSync } from "node:fs";
@@ -23273,7 +23399,7 @@ function fsList(args, ctx) {
23273
23399
  if (e.isDirectory()) return `[dir] ${e.name}`;
23274
23400
  let size = 0;
23275
23401
  try {
23276
- size = statSync7(join26(g.abs, e.name)).size;
23402
+ size = statSync7(join27(g.abs, e.name)).size;
23277
23403
  } catch {
23278
23404
  }
23279
23405
  return `[file] ${e.name} (${size} bytes)`;
@@ -23314,8 +23440,8 @@ function fsWrite(args, ctx) {
23314
23440
  if ("error" in g) return { ok: false, error: g.error };
23315
23441
  if (Buffer.byteLength(args.content) > MAX_WRITE) return { ok: false, error: "Content too large (5 MB limit)" };
23316
23442
  try {
23317
- mkdirSync18(dirname9(g.abs), { recursive: true });
23318
- writeFileSync19(g.abs, args.content);
23443
+ mkdirSync19(dirname9(g.abs), { recursive: true });
23444
+ writeFileSync20(g.abs, args.content);
23319
23445
  return { ok: true, output: `Wrote ${Buffer.byteLength(args.content)} bytes to ${g.abs}`, truncated: false };
23320
23446
  } catch (e) {
23321
23447
  return { ok: false, error: e.message };
@@ -23550,9 +23676,9 @@ function startDeviceNode(opts) {
23550
23676
  }
23551
23677
 
23552
23678
  // ../agent-cli/src/commands/start.ts
23553
- import { randomBytes as randomBytes13 } from "node:crypto";
23554
- import { existsSync as existsSync25, readFileSync as readFileSync18, writeFileSync as writeFileSync21 } from "node:fs";
23555
- import { dirname as dirname11, join as join28, resolve as resolve8 } from "node:path";
23679
+ import { randomBytes as randomBytes14 } from "node:crypto";
23680
+ import { existsSync as existsSync26, readFileSync as readFileSync19, writeFileSync as writeFileSync22 } from "node:fs";
23681
+ import { dirname as dirname11, join as join29, resolve as resolve8 } from "node:path";
23556
23682
  import { fileURLToPath as fileURLToPath4 } from "node:url";
23557
23683
 
23558
23684
  // ../agent-cli/src/commands/lan.ts
@@ -23658,23 +23784,23 @@ async function lanCommand(args, io2, ifaces = networkInterfaces2) {
23658
23784
 
23659
23785
  // ../agent-cli/src/commands/voice.ts
23660
23786
  import { spawn as spawn12 } from "node:child_process";
23661
- import { existsSync as existsSync24, mkdirSync as mkdirSync19, readFileSync as readFileSync17, writeFileSync as writeFileSync20 } from "node:fs";
23662
- import { dirname as dirname10, join as join27, resolve as resolve7 } from "node:path";
23787
+ import { existsSync as existsSync25, mkdirSync as mkdirSync20, readFileSync as readFileSync18, writeFileSync as writeFileSync21 } from "node:fs";
23788
+ import { dirname as dirname10, join as join28, resolve as resolve7 } from "node:path";
23663
23789
  import { fileURLToPath as fileURLToPath3 } from "node:url";
23664
23790
  function voicePaths(dataDir) {
23665
- const home = join27(dataDir, "voice");
23666
- const venv = join27(home, "venv");
23791
+ const home = join28(dataDir, "voice");
23792
+ const venv = join28(home, "venv");
23667
23793
  return {
23668
23794
  home,
23669
23795
  venv,
23670
- python: process.platform === "win32" ? join27(venv, "Scripts", "python.exe") : join27(venv, "bin", "python"),
23671
- models: join27(home, "models"),
23672
- marker: join27(home, "installed.json")
23796
+ python: process.platform === "win32" ? join28(venv, "Scripts", "python.exe") : join28(venv, "bin", "python"),
23797
+ models: join28(home, "models"),
23798
+ marker: join28(home, "installed.json")
23673
23799
  };
23674
23800
  }
23675
23801
  function readMarker(dataDir) {
23676
23802
  try {
23677
- return JSON.parse(readFileSync17(voicePaths(dataDir).marker, "utf8"));
23803
+ return JSON.parse(readFileSync18(voicePaths(dataDir).marker, "utf8"));
23678
23804
  } catch {
23679
23805
  return null;
23680
23806
  }
@@ -23771,8 +23897,8 @@ async function voiceSetupCommand(io2, deps = {}, args = []) {
23771
23897
  io2.err("Python 3.10 or newer is required. Install it from https://www.python.org/downloads/ and run this again.");
23772
23898
  return 1;
23773
23899
  }
23774
- mkdirSync19(p.home, { recursive: true });
23775
- if (!existsSync24(p.python)) {
23900
+ mkdirSync20(p.home, { recursive: true });
23901
+ if (!existsSync25(p.python)) {
23776
23902
  io2.out("1/3 Creating a private Python environment\u2026");
23777
23903
  const r = await run2(py.cmd, [...py.args, "-m", "venv", p.venv], { onLine });
23778
23904
  if (r.code !== 0) {
@@ -23806,7 +23932,7 @@ ${tail(dl.stdout)}`);
23806
23932
  return 1;
23807
23933
  }
23808
23934
  const marker = { python: p.python, sttModel: cfg.voice.sttModel, ttsVoice: cfg.voice.ttsVoice, at: Date.now() };
23809
- writeFileSync20(p.marker, JSON.stringify(marker, null, 2));
23935
+ writeFileSync21(p.marker, JSON.stringify(marker, null, 2));
23810
23936
  io2.out("Voice is ready. Start Friend with `friend start`, then hold Space to talk.");
23811
23937
  return 0;
23812
23938
  }
@@ -23822,7 +23948,7 @@ async function voiceStatusCommand(io2) {
23822
23948
  io2.out("Voice engine: not installed. Run: friend voice setup");
23823
23949
  return 0;
23824
23950
  }
23825
- if (!existsSync24(marker.python)) {
23951
+ if (!existsSync25(marker.python)) {
23826
23952
  io2.out("Voice engine: installed, but its Python is missing. Run: friend voice setup");
23827
23953
  return 0;
23828
23954
  }
@@ -23895,12 +24021,12 @@ async function voiceCommand(args, io2) {
23895
24021
  function findWebDir(explicit) {
23896
24022
  const here2 = dirname11(fileURLToPath4(import.meta.url));
23897
24023
  const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve8(here2, "../../../web/dist"), resolve8(here2, "web")];
23898
- return candidates.find((c) => !!c && existsSync25(join28(c, "index.html")));
24024
+ return candidates.find((c) => !!c && existsSync26(join29(c, "index.html")));
23899
24025
  }
23900
24026
  async function startFriend(opts) {
23901
24027
  const stored = loadConfig(opts.dataDir);
23902
24028
  const marker = stored.voice.enabled ? readMarker(opts.dataDir) : null;
23903
- const secret = randomBytes13(24).toString("hex");
24029
+ const secret = randomBytes14(24).toString("hex");
23904
24030
  const sidecar = marker ? new SidecarProcess({
23905
24031
  command: marker.python,
23906
24032
  args: [
@@ -23931,17 +24057,17 @@ async function startFriend(opts) {
23931
24057
  }
23932
24058
  });
23933
24059
  const { port } = await app.start();
23934
- const tokenFile = join28(opts.dataDir, "local-device.token");
23935
- let token = existsSync25(tokenFile) ? readFileSync18(tokenFile, "utf8").trim() : "";
24060
+ const tokenFile = join29(opts.dataDir, "local-device.token");
24061
+ let token = existsSync26(tokenFile) ? readFileSync19(tokenFile, "utf8").trim() : "";
23936
24062
  if (!token || !app.auth.resolveDevice(token)) {
23937
24063
  token = app.auth.redeemPairCode(app.auth.createPairCode(), "this-pc");
23938
- writeFileSync21(tokenFile, token, { mode: 384 });
24064
+ writeFileSync22(tokenFile, token, { mode: 384 });
23939
24065
  }
23940
24066
  const node = startDeviceNode({
23941
24067
  url: `${app.config.https ? "wss" : "ws"}://127.0.0.1:${port}/device`,
23942
24068
  token,
23943
24069
  roots: app.config.roots,
23944
- ...app.config.https ? { ca: readFileSync18(join28(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
24070
+ ...app.config.https ? { ca: readFileSync19(join29(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
23945
24071
  // this PC trusts only its own Friend's certificate
23946
24072
  });
23947
24073
  const urls = urlsFor(app.config.bind, port, void 0, app.config.https);
@@ -24111,8 +24237,8 @@ async function devicesCommand(args, io2) {
24111
24237
  }
24112
24238
 
24113
24239
  // ../agent-cli/src/commands/memory.ts
24114
- import { existsSync as existsSync26 } from "node:fs";
24115
- import { join as join29 } from "node:path";
24240
+ import { existsSync as existsSync27 } from "node:fs";
24241
+ import { join as join30 } from "node:path";
24116
24242
  var USAGE = "Usage: friend memory list | friend memory show <path> | friend memory forget <path or number> | friend memory clear";
24117
24243
  async function memoryCommand(args, io2) {
24118
24244
  const [sub, arg] = args;
@@ -24124,7 +24250,7 @@ async function memoryCommand(args, io2) {
24124
24250
  try {
24125
24251
  const memory = new Memory(db);
24126
24252
  const audit = new Audit(db);
24127
- const tree2 = existsSync26(join29(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join29(io2.dataDir, "memory")) : null;
24253
+ const tree2 = existsSync27(join30(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join30(io2.dataDir, "memory")) : null;
24128
24254
  if (sub === "show") {
24129
24255
  if (!tree2 || !arg) {
24130
24256
  io2.err(tree2 ? USAGE : "There is no memory tree yet.");
@@ -24203,8 +24329,8 @@ async function memoryCommand(args, io2) {
24203
24329
  }
24204
24330
 
24205
24331
  // ../agent-cli/src/commands/plugin.ts
24206
- import { existsSync as existsSync27, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
24207
- import { dirname as dirname12, join as join30, resolve as resolve10 } from "node:path";
24332
+ import { existsSync as existsSync28, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
24333
+ import { dirname as dirname12, join as join31, resolve as resolve10 } from "node:path";
24208
24334
  import { fileURLToPath as fileURLToPath5 } from "node:url";
24209
24335
  var USAGE2 = "Usage: friend plugin catalog | list | install <name|folder> [--yes] | enable <id> | disable <id> | remove <id>";
24210
24336
  function defaultCatalog() {
@@ -24218,10 +24344,10 @@ async function pluginCommand(args, io2, deps = {}) {
24218
24344
  const flags = rest.filter((a) => a.startsWith("--"));
24219
24345
  const arg = rest.find((a) => !a.startsWith("--"));
24220
24346
  if (sub === "catalog") {
24221
- const dirs = existsSync27(catalogDir) ? readdirSync9(catalogDir).filter((d) => statSync8(join30(catalogDir, d)).isDirectory()) : [];
24347
+ const dirs = existsSync28(catalogDir) ? readdirSync9(catalogDir).filter((d) => statSync8(join31(catalogDir, d)).isDirectory()) : [];
24222
24348
  if (dirs.length === 0) io2.out("The catalog is empty.");
24223
24349
  for (const d of dirs.sort()) {
24224
- const r = inspectPlugin(join30(catalogDir, d));
24350
+ const r = inspectPlugin(join31(catalogDir, d));
24225
24351
  if (!r.ok) {
24226
24352
  io2.out(`${d} (invalid: ${r.error})`);
24227
24353
  continue;
@@ -24237,7 +24363,7 @@ async function pluginCommand(args, io2, deps = {}) {
24237
24363
  }
24238
24364
  const db = openDb(io2.dataDir);
24239
24365
  try {
24240
- const plugins = new Plugins(db, join30(io2.dataDir, "plugins"));
24366
+ const plugins = new Plugins(db, join31(io2.dataDir, "plugins"));
24241
24367
  if (sub === "list") {
24242
24368
  const all = plugins.list();
24243
24369
  if (all.length === 0) io2.out("No plugins installed. See: friend plugin catalog");
@@ -24251,8 +24377,8 @@ async function pluginCommand(args, io2, deps = {}) {
24251
24377
  io2.err(USAGE2);
24252
24378
  return 1;
24253
24379
  }
24254
- const inCatalog = !/[\\/]/.test(arg) && existsSync27(join30(catalogDir, arg));
24255
- const source = inCatalog ? join30(catalogDir, arg) : existsSync27(resolve10(arg)) ? resolve10(arg) : null;
24380
+ const inCatalog = !/[\\/]/.test(arg) && existsSync28(join31(catalogDir, arg));
24381
+ const source = inCatalog ? join31(catalogDir, arg) : existsSync28(resolve10(arg)) ? resolve10(arg) : null;
24256
24382
  if (!source) {
24257
24383
  io2.err(`"${arg}" is not in the catalog and there is no such folder. See: friend plugin catalog`);
24258
24384
  return 1;
@@ -24307,7 +24433,7 @@ async function pluginCommand(args, io2, deps = {}) {
24307
24433
 
24308
24434
  // ../agent-cli/src/commands/onboard/index.ts
24309
24435
  import crossSpawn4 from "cross-spawn";
24310
- import { mkdirSync as mkdirSync21 } from "node:fs";
24436
+ import { mkdirSync as mkdirSync22 } from "node:fs";
24311
24437
  import { resolve as resolve11 } from "node:path";
24312
24438
 
24313
24439
  // ../agent-cli/src/commands/ollama.ts
@@ -24630,16 +24756,16 @@ function installPlan(id2, platform, have) {
24630
24756
  }
24631
24757
 
24632
24758
  // ../agent-cli/src/commands/onboard/state.ts
24633
- import { existsSync as existsSync28, mkdirSync as mkdirSync20, readFileSync as readFileSync19, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync22 } from "node:fs";
24634
- import { dirname as dirname13, join as join31 } from "node:path";
24759
+ import { existsSync as existsSync29, mkdirSync as mkdirSync21, readFileSync as readFileSync20, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync23 } from "node:fs";
24760
+ import { dirname as dirname13, join as join32 } from "node:path";
24635
24761
  var FEATURES = ["claude-code", "claude-api", "ollama", "voice", "sandbox"];
24636
24762
  var emptyState = () => ({ version: 1, done: {}, features: [], restart: [] });
24637
- var statePath = (dataDir) => join31(dataDir, "onboarding.json");
24763
+ var statePath = (dataDir) => join32(dataDir, "onboarding.json");
24638
24764
  function loadState(dataDir) {
24639
24765
  const f = statePath(dataDir);
24640
- if (!existsSync28(f)) return emptyState();
24766
+ if (!existsSync29(f)) return emptyState();
24641
24767
  try {
24642
- const raw = JSON.parse(readFileSync19(f, "utf8"));
24768
+ const raw = JSON.parse(readFileSync20(f, "utf8"));
24643
24769
  const done = raw.done && typeof raw.done === "object" ? Object.fromEntries(Object.entries(raw.done).filter(([, v]) => typeof v === "string")) : {};
24644
24770
  const features2 = Array.isArray(raw.features) ? raw.features.filter((x) => FEATURES.includes(x)) : [];
24645
24771
  const restart = Array.isArray(raw.restart) ? raw.restart.filter((x) => typeof x === "string") : [];
@@ -24650,9 +24776,9 @@ function loadState(dataDir) {
24650
24776
  }
24651
24777
  function saveState(dataDir, state) {
24652
24778
  const f = statePath(dataDir);
24653
- mkdirSync20(dirname13(f), { recursive: true });
24779
+ mkdirSync21(dirname13(f), { recursive: true });
24654
24780
  const tmp = `${f}.tmp`;
24655
- writeFileSync22(tmp, JSON.stringify(state, null, 2));
24781
+ writeFileSync23(tmp, JSON.stringify(state, null, 2));
24656
24782
  renameSync5(tmp, f);
24657
24783
  }
24658
24784
  function resetState(dataDir) {
@@ -25008,7 +25134,7 @@ async function workspace(c) {
25008
25134
  const answer = await text3(c.ui, current ? "Workspace folder" : "Workspace folder (Enter to skip)", current ?? "");
25009
25135
  if (answer) {
25010
25136
  const abs = resolve11(answer);
25011
- mkdirSync21(abs, { recursive: true });
25137
+ mkdirSync22(abs, { recursive: true });
25012
25138
  cfg.roots = [abs];
25013
25139
  saveConfig(cfg);
25014
25140
  io2.out(`Workspace: ${abs}`);
@@ -25262,8 +25388,8 @@ async function usageCommand(args, io2, log) {
25262
25388
  }
25263
25389
 
25264
25390
  // ../agent-cli/src/commands/audit.ts
25265
- import { writeFileSync as writeFileSync23 } from "node:fs";
25266
- import { join as join32 } from "node:path";
25391
+ import { writeFileSync as writeFileSync24 } from "node:fs";
25392
+ import { join as join33 } from "node:path";
25267
25393
  var USAGE5 = [
25268
25394
  "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]",
25269
25395
  " friend audit show <request-id>",
@@ -25368,7 +25494,7 @@ async function auditCommand(args, io2, deps = {}) {
25368
25494
  afterwards = async (res2) => {
25369
25495
  const raw = /filename="([^"]+)"/.exec(res2.headers.get("content-disposition") ?? "")?.[1] ?? `friend-audit.${f.query.format}`;
25370
25496
  const name = (raw.split(/[\\/]/).pop() ?? "friend-audit").replace(/[^A-Za-z0-9._-]/g, "_") || "friend-audit";
25371
- (deps.write ?? ((n2, b) => writeFileSync23(join32(process.cwd(), n2), b)))(name, await res2.text());
25497
+ (deps.write ?? ((n2, b) => writeFileSync24(join33(process.cwd(), n2), b)))(name, await res2.text());
25372
25498
  io2.out(`Saved ${name} in this folder. It contains private content: keep it safe.`);
25373
25499
  return 0;
25374
25500
  };
@@ -25396,9 +25522,9 @@ async function auditCommand(args, io2, deps = {}) {
25396
25522
 
25397
25523
  // ../agent-cli/src/commands/daemon.ts
25398
25524
  import { spawn as spawn13, spawnSync as spawnSync3 } from "node:child_process";
25399
- 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";
25525
+ 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";
25400
25526
  import { connect } from "node:net";
25401
- import { join as join33 } from "node:path";
25527
+ import { join as join34 } from "node:path";
25402
25528
  var USAGE6 = "Usage: friend daemon start | stop | restart | status";
25403
25529
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
25404
25530
  var sleep2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
@@ -25454,11 +25580,11 @@ var realDeps = {
25454
25580
  },
25455
25581
  now: Date.now
25456
25582
  };
25457
- var pidFile = (dataDir) => join33(dataDir, "friend.pid");
25458
- var logFileOf = (dataDir) => join33(dataDir, "friend.log");
25583
+ var pidFile = (dataDir) => join34(dataDir, "friend.pid");
25584
+ var logFileOf = (dataDir) => join34(dataDir, "friend.log");
25459
25585
  function readPid(dataDir) {
25460
25586
  try {
25461
- const r = JSON.parse(readFileSync20(pidFile(dataDir), "utf8"));
25587
+ const r = JSON.parse(readFileSync21(pidFile(dataDir), "utf8"));
25462
25588
  return Number.isInteger(r.pid) && r.pid > 0 ? r : null;
25463
25589
  } catch {
25464
25590
  return null;
@@ -25489,10 +25615,10 @@ async function start(io2, deps) {
25489
25615
  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).`);
25490
25616
  return 1;
25491
25617
  }
25492
- mkdirSync22(io2.dataDir, { recursive: true });
25618
+ mkdirSync23(io2.dataDir, { recursive: true });
25493
25619
  const log = logFileOf(io2.dataDir);
25494
25620
  try {
25495
- if (existsSync29(log) && statSync9(log).size > MAX_LOG_BYTES) renameSync6(log, `${log}.old`);
25621
+ if (existsSync30(log) && statSync9(log).size > MAX_LOG_BYTES) renameSync6(log, `${log}.old`);
25496
25622
  } catch {
25497
25623
  }
25498
25624
  const pid = deps.launch(log);
@@ -25500,7 +25626,7 @@ async function start(io2, deps) {
25500
25626
  io2.err("Could not start Friend in the background.");
25501
25627
  return 1;
25502
25628
  }
25503
- writeFileSync24(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
25629
+ writeFileSync25(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
25504
25630
  for (let i = 0; i < 60; i++) {
25505
25631
  if (await deps.portOpen(cfg.port, 300)) {
25506
25632
  io2.out(`Friend is running in the background (pid ${pid}) at ${urls.local}`);
@@ -25566,10 +25692,10 @@ async function daemonCommand(args, io2, deps = realDeps) {
25566
25692
  // ../agent-cli/src/commands/upgrade.ts
25567
25693
  import crossSpawn5 from "cross-spawn";
25568
25694
  import { appendFileSync } from "node:fs";
25569
- import { join as join34 } from "node:path";
25695
+ import { join as join35 } from "node:path";
25570
25696
  var PACKAGE2 = "friend-assistant";
25571
25697
  var real2 = {
25572
- current: () => true ? "0.1.71" : "development",
25698
+ current: () => true ? "0.1.73" : "development",
25573
25699
  latest: () => new Promise((resolve13) => {
25574
25700
  const child = crossSpawn5("npm", ["view", PACKAGE2, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
25575
25701
  let out = "";
@@ -25607,7 +25733,7 @@ async function upgradeCommand(args, io0, deps = real2) {
25607
25733
  io0.err("Usage: friend upgrade [--force] [--auto]");
25608
25734
  return 1;
25609
25735
  }
25610
- const log = deps.log ?? ((line2) => appendFileSync(join34(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
25736
+ const log = deps.log ?? ((line2) => appendFileSync(join35(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
25611
25737
  `));
25612
25738
  const io2 = auto ? {
25613
25739
  ...io0,
@@ -25725,7 +25851,7 @@ async function claudeCommand(args, io2, deps = {}) {
25725
25851
  }
25726
25852
 
25727
25853
  // ../agent-cli/src/commands/setup.ts
25728
- import { mkdirSync as mkdirSync23 } from "node:fs";
25854
+ import { mkdirSync as mkdirSync24 } from "node:fs";
25729
25855
  import { resolve as resolve12 } from "node:path";
25730
25856
  async function setupCommand3(io2) {
25731
25857
  const db = openDb(io2.dataDir);
@@ -25751,7 +25877,7 @@ async function setupCommand3(io2) {
25751
25877
  const cfg = loadConfig(io2.dataDir);
25752
25878
  if (workspace2) {
25753
25879
  const abs = resolve12(workspace2);
25754
- mkdirSync23(abs, { recursive: true });
25880
+ mkdirSync24(abs, { recursive: true });
25755
25881
  cfg.roots = [abs];
25756
25882
  }
25757
25883
  if (apiKey) cfg.apiKey = apiKey;
@@ -25887,7 +26013,7 @@ async function run(argv, io2) {
25887
26013
  case "version":
25888
26014
  case "--version":
25889
26015
  case "-v":
25890
- io2.out(true ? "0.1.71" : "development");
26016
+ io2.out(true ? "0.1.73" : "development");
25891
26017
  return 0;
25892
26018
  case "lan":
25893
26019
  return await lanCommand(rest, io2);