friend-assistant 0.1.90 → 0.1.92

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
@@ -1147,6 +1147,13 @@ var TOOL_DEFS = [
1147
1147
  baseTier: "T0",
1148
1148
  target: "gateway"
1149
1149
  },
1150
+ {
1151
+ name: "connect.start",
1152
+ description: "Start signing in to an outside service or connector the owner asked to connect (for example Gmail). Friend sends the owner a one-time approval link on their phone; the owner approves it themselves. You never see the link or any login, and you cannot approve it. Use the service or connector name the owner used.",
1153
+ input: z5.object({ service: z5.string().min(1).max(40) }),
1154
+ baseTier: "T0",
1155
+ target: "gateway"
1156
+ },
1150
1157
  {
1151
1158
  name: "people.remove",
1152
1159
  description: "Forget one person the owner introduced: their saved face numbers and the notes about them are deleted. The owner types their PIN.",
@@ -1434,8 +1441,8 @@ var TOOL_DEFS = [
1434
1441
  },
1435
1442
  {
1436
1443
  name: "view.set",
1437
- description: "Change what the owner's screen shows besides your pictures: minimal (only the voice presence), companion (plus a status line and a clock) or workspace (plus the chat and the schedule panels). Use it when the owner asks for a cleaner or fuller screen.",
1438
- input: z5.object({ view: ViewPreset }),
1444
+ description: "Change what the owner's screen shows besides your pictures: minimal (only the voice presence), companion (plus a status line and a clock) or workspace (plus the chat and the schedule panels). Use it when the owner asks for a cleaner or fuller screen. layout switches the whole screen between classic (the corner widgets and panels) and orbital (the round HUD with nodes around the presence): use it when the owner asks to change the layout, the look of the home screen, or to go back to the old one. Give view, layout, or both.",
1445
+ input: z5.object({ view: ViewPreset.optional(), layout: z5.enum(["classic", "orbital"]).optional() }).refine((a) => a.view !== void 0 || a.layout !== void 0, { message: "Give a view, a layout, or both." }),
1439
1446
  baseTier: "T1",
1440
1447
  target: "gateway"
1441
1448
  },
@@ -1996,7 +2003,7 @@ ${visible(clip(String(a.text ?? ""), 600))}`;
1996
2003
  case "look.set":
1997
2004
  return `Change the look: ${visible(clip(JSON.stringify(a), 300))}`;
1998
2005
  case "view.set":
1999
- return `Change the view to ${visible(String(a.view ?? ""))}`;
2006
+ return a.layout ? `Change the screen layout to ${visible(String(a.layout))}` : `Change the view to ${visible(String(a.view ?? ""))}`;
2000
2007
  case "connectors.list":
2001
2008
  return "List the connectors";
2002
2009
  case "connectors.add": {
@@ -2054,6 +2061,8 @@ ${visible(String(t.code ?? ""))}`);
2054
2061
  return "List the people I remember";
2055
2062
  case "people.answer":
2056
2063
  return String(a.who) === "known" ? `Remember the person in the photo as ${visible(String(a.name ?? ""))}` : "Mark the person in the photo as a stranger";
2064
+ case "connect.start":
2065
+ return `Send the owner a link to approve connecting ${visible(String(a.service ?? ""))}`;
2057
2066
  case "people.share":
2058
2067
  return `Allow telling ${visible(String(a.name ?? ""))} this about you: ${visible(String(a.text ?? "") || "(nothing)")}`;
2059
2068
  case "people.remove":
@@ -2796,6 +2805,7 @@ function toolLabel(name, args) {
2796
2805
  if (name === "camera.watch") return "Watching through the camera";
2797
2806
  if (name === "people.introduce") return "Remembering a face";
2798
2807
  if (name === "people.answer") return "Noting who a visitor is";
2808
+ if (name === "connect.start") return "Sending a link to connect a service";
2799
2809
  if (name === "people.share") return "Noting what a person may be told";
2800
2810
  if (name.startsWith("shell.")) return "Running a command";
2801
2811
  if (name.startsWith("fs.")) return "Working with files";
@@ -3769,7 +3779,7 @@ var LAYOUT_GUIDE = `Screen layout (follow this when you decide where things go)
3769
3779
  - Check your work. After you draw more than one object, or a Jarvis drawing, call stage.check once. It reports in words what overlaps, is cut off, is empty, or is too crowded or has no focus; fix exactly what it names (move, resize or redraw it) and stop. Do not call it again and again, and do not describe the check to the owner.
3770
3780
  - Temporary and pinned. What you show for a task is temporary: when the task is done and the owner has what they need, take it off the screen (stage.hide for one, stage.clear for all) so the screen goes back to how the owner keeps it. Pinned widgets are the owner's: they stay across refreshes, logins and restarts, in the place the owner dragged them to, and stage.clear leaves them alone. Pin something with stage.pin only when the owner asks for it to stay, or when you offer and they agree (for example a clock, a to-do list, a status gauge). Never hide, move or unpin a pinned widget unless the owner asks. To change what a pinned widget shows, stage.update it by its id.
3771
3781
  - Pick the object by the data: one number gauge or stat, a few numbers side by side stat, a trend chart, items with details table, a to-do or schedule list or timeline, relationships graph, a short note card, anything else a sandbox page. Keep text short; the pictures carry the answer and your voice adds one or two sentences.
3772
- - The owner can open a chat panel (right edge) and a schedule panel (upper left); the request's screen description lists them when open. Keep your pictures out of their way and do not repeat what they already show. The owner arranges the corner widgets and panels themselves; never try to move them. Change what the screen shows with view.set only when the owner asks for a cleaner or fuller screen.
3782
+ - The owner can open a chat panel (right edge) and a schedule panel (upper left); the request's screen description lists them when open. Keep your pictures out of their way and do not repeat what they already show. The owner arranges the corner widgets and panels themselves; never try to move them. Change what the screen shows with view.set only when the owner asks for a cleaner or fuller screen. When the owner asks to change the layout of the whole screen (the round orbital HUD or the classic corner-widget screen, "the old layout", "switch the layout"), call view.set with layout orbital or classic: that is allowed and takes effect at once. Moving or resizing single widgets is still the owner's: say so and offer the layout switch or a new composition instead.
3773
3783
  - The look of the voice presence (style, colour, brightness, size) belongs to the owner. If stage.presence or stage.mood say the look is fixed, accept it. Use look.set only when the owner asks you to change it.
3774
3784
  - The theme is a HUD, like the screens in science-fiction films: a near-black blue background, translucent glass panels with thin glowing edges, one bright accent colour, small upper-case letter-spaced labels, and monospace for numbers and code. Nothing is white, nothing is solid or rounded and cheerful. The colours are: accent (the current one is in each request as accent=#rrggbb; default cyan #3fd8ff), ink #d4ecf7 for text, muted #7fa3b6 for labels, ok #5ef0b0 for good, warn #ffb454 for caution, bad #ff6b7a for errors, background #050b10, glass rgba(6,20,28,0.62). Use warn and bad only for real warnings. Do not invent other colours, and never put dark text on a dark background. In a sandbox page do not write colours at all: use var(--accent), var(--ink), var(--muted), var(--ok), var(--warn), var(--bad), var(--glass), var(--edge), var(--ui) and var(--mono); they follow the owner's theme and accent exactly. Draw with thin lines (1px), a soft glow (box-shadow or drop-shadow of var(--accent)) and transparent backgrounds.
3775
3785
  - What is already on the screen decides how you show something new. A short explanation or quick answer while something is showing: role note (it moves nothing). Something IMPORTANT or urgent (an error, a warning, something the owner must act on): role alert, shown alone. A new topic: mode replace. More of the same topic: mode add, or update the objects you have. Call stage.guide (topics widgets, layout, overlay, theme, files, recipes) for the full manual before building a screen you have not built before.
@@ -5778,7 +5788,7 @@ ${r.stderr}` : ""}`);
5778
5788
  if (call.name === "settings.get" || call.name === "settings.set" || call.name === "view.set" || call.name === "look.set") {
5779
5789
  if (!d.settings) return fail3("Settings are not available.");
5780
5790
  try {
5781
- const text6 = call.name === "settings.get" ? JSON.stringify(d.settings.get()) : call.name === "view.set" ? d.settings.setView(args.view) : call.name === "look.set" ? d.settings.setLook(args) : await d.settings.set(args.settings);
5791
+ const text6 = call.name === "settings.get" ? JSON.stringify(d.settings.get()) : call.name === "view.set" ? [args.layout ? d.settings.setLayout ? d.settings.setLayout(args.layout) : "The layout cannot be changed here." : "", args.view ? d.settings.setView(args.view) : ""].filter(Boolean).join(" ") : call.name === "look.set" ? d.settings.setLook(args) : await d.settings.set(args.settings);
5782
5792
  d.audit.log("agent", "tool.call", { tool: call.name, args: call.name === "settings.set" ? { fields: Object.keys(args.settings ?? {}) } : clipArgs(args), tier, ok: true });
5783
5793
  return { text: text6, isError: false };
5784
5794
  } catch (e) {
@@ -5937,6 +5947,13 @@ ${lines.join("\n")}`, isError: false };
5937
5947
  d.audit.log("agent", "tool.call", { tool: call.name, args: { name }, tier, ok: true });
5938
5948
  return { text: `I will remember ${name}${relation ? ` (${relation})` : ""}. Only numbers about the face are kept, not the picture.`, isError: false };
5939
5949
  }
5950
+ if (call.name === "connect.start") {
5951
+ if (ctx.trust !== "owner" || !["chat", "voice", "channel"].includes(ctx.source ?? "")) return fail3("Only the owner can ask for that.");
5952
+ if (!d.oauth) return fail3("Signing in with a link is not available.");
5953
+ const r = await d.oauth.start(String(args.service ?? ""));
5954
+ d.audit.log("agent", "tool.call", { tool: call.name, args: { service: String(args.service ?? "").slice(0, 40) }, tier, ok: r.ok });
5955
+ return r.ok ? { text: r.message, isError: false } : fail3(r.message);
5956
+ }
5940
5957
  if (call.name === "people.answer") {
5941
5958
  if (ctx.trust !== "owner" || !["chat", "voice", "channel"].includes(ctx.source ?? "")) return fail3("Only the owner can answer that.");
5942
5959
  const waiting = d.visitors?.pending();
@@ -6105,25 +6122,25 @@ import { homedir } from "node:os";
6105
6122
  import { join as join5, posix as posix2, win32 as win322 } from "node:path";
6106
6123
  function sanitizeSecurityAlerts(raw) {
6107
6124
  const r = raw && typeof raw === "object" ? raw : {};
6108
- const num5 = (v, lo, hi, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : def;
6109
- return { enabled: r.enabled !== false, cooldownMinutes: num5(r.cooldownMinutes, 1, 1440, 15), maxPerDay: num5(r.maxPerDay, 1, 200, 20) };
6125
+ const num6 = (v, lo, hi, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : def;
6126
+ return { enabled: r.enabled !== false, cooldownMinutes: num6(r.cooldownMinutes, 1, 1440, 15), maxPerDay: num6(r.maxPerDay, 1, 200, 20) };
6110
6127
  }
6111
6128
  function sanitizeAttachments(raw) {
6112
6129
  const r = raw && typeof raw === "object" ? raw : {};
6113
- const num5 = (v, lo, hi, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : def;
6114
- return { maxBytes: num5(r.maxBytes, 1024, 50 * 1024 * 1024, 10 * 1024 * 1024), maxFiles: num5(r.maxFiles, 1, 10, 5), keepDays: num5(r.keepDays, 1, 3650, 30) };
6130
+ const num6 = (v, lo, hi, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.round(v))) : def;
6131
+ return { maxBytes: num6(r.maxBytes, 1024, 50 * 1024 * 1024, 10 * 1024 * 1024), maxFiles: num6(r.maxFiles, 1, 10, 5), keepDays: num6(r.keepDays, 1, 3650, 30) };
6115
6132
  }
6116
6133
  var BROWSER_LIMITS = { timeoutSec: { min: 5, max: 60, def: 20 }, maxChars: { min: 1e3, max: 3e4, def: 12e3 } };
6117
6134
  var chromePathOk = (v) => v === "" || v.length <= 300 && !/[\u0000-\u001f"<>|*?]/.test(v) && !v.startsWith("-");
6118
6135
  function sanitizeBrowser(raw) {
6119
6136
  const r = raw && typeof raw === "object" ? raw : {};
6120
- const num5 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6137
+ const num6 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6121
6138
  return {
6122
6139
  installed: r.installed === true,
6123
6140
  enabled: r.enabled === true,
6124
6141
  chromePath: typeof r.chromePath === "string" && chromePathOk(r.chromePath.trim()) ? r.chromePath.trim() : "",
6125
- timeoutSec: num5(r.timeoutSec, BROWSER_LIMITS.timeoutSec),
6126
- maxChars: num5(r.maxChars, BROWSER_LIMITS.maxChars)
6142
+ timeoutSec: num6(r.timeoutSec, BROWSER_LIMITS.timeoutSec),
6143
+ maxChars: num6(r.maxChars, BROWSER_LIMITS.maxChars)
6127
6144
  };
6128
6145
  }
6129
6146
  var SKILL_ID = /^amzn1\.ask\.skill\.[A-Za-z0-9-]{8,80}$/;
@@ -6138,14 +6155,14 @@ function sanitizeSpotify(raw) {
6138
6155
  }
6139
6156
  function sanitizeVideo(raw) {
6140
6157
  const r = raw && typeof raw === "object" ? raw : {};
6141
- const num5 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6158
+ const num6 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6142
6159
  const program = (v) => typeof v === "string" && programProblem(v.trim()) === null ? v.trim() : "";
6143
6160
  return {
6144
6161
  installed: r.installed === true || r.installed === void 0 && r.enabled === true,
6145
6162
  enabled: r.enabled === true,
6146
6163
  output: VIDEO_OUTPUTS.includes(r.output) ? r.output : "screen",
6147
- maxHeight: num5(r.maxHeight, VIDEO_LIMITS.maxHeight),
6148
- maxMinutes: num5(r.maxMinutes, VIDEO_LIMITS.maxMinutes),
6164
+ maxHeight: num6(r.maxHeight, VIDEO_LIMITS.maxHeight),
6165
+ maxMinutes: num6(r.maxMinutes, VIDEO_LIMITS.maxMinutes),
6149
6166
  allowedSites: normalizeSites(r.allowedSites),
6150
6167
  ytdlp: program(r.ytdlp),
6151
6168
  ffmpeg: program(r.ffmpeg),
@@ -6163,20 +6180,20 @@ function sanitizeAudius(raw) {
6163
6180
  }
6164
6181
  function sanitizeMusic(raw) {
6165
6182
  const r = raw && typeof raw === "object" ? raw : {};
6166
- const num5 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6183
+ const num6 = (v, o) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, Math.round(v))) : o.def;
6167
6184
  const exts = [...new Set((Array.isArray(r.extensions) ? r.extensions : []).map((e) => typeof e === "string" ? e.toLowerCase().replace(/^\./, "") : "").filter((e) => AUDIO_EXTENSIONS.includes(e)))];
6168
6185
  return {
6169
6186
  folder: typeof r.folder === "string" ? r.folder.trim().slice(0, 500) : "",
6170
6187
  extensions: exts.length ? exts : [...AUDIO_EXTENSIONS],
6171
- maxTracks: num5(r.maxTracks, MUSIC_LIMITS.maxTracks),
6172
- scanDepth: num5(r.scanDepth, MUSIC_LIMITS.scanDepth),
6173
- volume: num5(r.volume, MUSIC_LIMITS.volume),
6188
+ maxTracks: num6(r.maxTracks, MUSIC_LIMITS.maxTracks),
6189
+ scanDepth: num6(r.scanDepth, MUSIC_LIMITS.scanDepth),
6190
+ volume: num6(r.volume, MUSIC_LIMITS.volume),
6174
6191
  shuffle: r.shuffle === true,
6175
6192
  repeat: REPEAT_MODES.includes(r.repeat) ? r.repeat : "all",
6176
6193
  visualizer: r.visualizer !== false,
6177
6194
  startView: r.startView === "full" ? "full" : "mini",
6178
6195
  defaultSource: DEFAULT_SOURCES.includes(r.defaultSource) ? r.defaultSource : "local",
6179
- searchLimit: num5(r.searchLimit, MUSIC_LIMITS.searchLimit),
6196
+ searchLimit: num6(r.searchLimit, MUSIC_LIMITS.searchLimit),
6180
6197
  output: MUSIC_OUTPUTS.includes(r.output) ? r.output : "screen",
6181
6198
  hostPlayer: typeof r.hostPlayer === "string" && programProblem(r.hostPlayer.trim()) === null ? r.hostPlayer.trim() : "",
6182
6199
  spotifyDevice: typeof r.spotifyDevice === "string" ? r.spotifyDevice.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 100) : "",
@@ -6264,7 +6281,7 @@ function tidyFolder(p) {
6264
6281
  function sanitizeOffice(raw) {
6265
6282
  const r = raw && typeof raw === "object" ? raw : {};
6266
6283
  const obj2 = (v) => v && typeof v === "object" ? v : {};
6267
- const num5 = (v, lo, hi, def, whole = true) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, whole ? Math.round(v) : Math.round(v * 100) / 100)) : def;
6284
+ const num6 = (v, lo, hi, def, whole = true) => typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, whole ? Math.round(v) : Math.round(v * 100) / 100)) : def;
6268
6285
  const b = obj2(r.budget);
6269
6286
  const c = obj2(r.context);
6270
6287
  const cap2 = obj2(r.capabilities);
@@ -6289,15 +6306,15 @@ function sanitizeOffice(raw) {
6289
6306
  }).slice(0, 20);
6290
6307
  return {
6291
6308
  enabled: r.enabled === true,
6292
- maxConcurrent: num5(r.maxConcurrent, 1, 8, 2),
6293
- startTimeoutSec: num5(r.startTimeoutSec, 10, 600, 60),
6294
- pauseAtWindow: num5(r.pauseAtWindow, 0, 1, 0.9, false),
6309
+ maxConcurrent: num6(r.maxConcurrent, 1, 8, 2),
6310
+ startTimeoutSec: num6(r.startTimeoutSec, 10, 600, 60),
6311
+ pauseAtWindow: num6(r.pauseAtWindow, 0, 1, 0.9, false),
6295
6312
  notifyFriend: r.notifyFriend !== false,
6296
6313
  autonomy: OFFICE_AUTONOMY.find((l) => l === r.autonomy) ?? "low",
6297
- decideTries: num5(r.decideTries, 1, 10, 3),
6314
+ decideTries: num6(r.decideTries, 1, 10, 3),
6298
6315
  capabilities: { skillRoots: strings2(cap2.skillRoots, [], 10, 260), allowSkills: strings2(cap2.allowSkills, ["*"], 100, 80), allowMcp: strings2(cap2.allowMcp, [], 40, 16) },
6299
- context: { window: num5(c.window, 1e4, 5e6, 2e5), warnAt: num5(c.warnAt, 0, 1, 0.7, false), hardAt: num5(c.hardAt, 0, 1, 0, false) },
6300
- budget: { perWorkerTokens: num5(b.perWorkerTokens, 0, 1e9, 0), totalTokens: num5(b.totalTokens, 0, 1e9, 0) },
6316
+ context: { window: num6(c.window, 1e4, 5e6, 2e5), warnAt: num6(c.warnAt, 0, 1, 0.7, false), hardAt: num6(c.hardAt, 0, 1, 0, false) },
6317
+ budget: { perWorkerTokens: num6(b.perWorkerTokens, 0, 1e9, 0), totalTokens: num6(b.totalTokens, 0, 1e9, 0) },
6301
6318
  roles,
6302
6319
  projects,
6303
6320
  policy: { allowTools: strings2(p.allowTools, DEFAULT_OFFICE_POLICY.allowTools, 40, 60), denyCommands: strings2(p.denyCommands, DEFAULT_OFFICE_POLICY.denyCommands, 40, 200) }
@@ -6313,10 +6330,10 @@ function sanitizeAlexa(raw) {
6313
6330
  const label5 = typeof x.name === "string" ? x.name.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 40) : "";
6314
6331
  return [{ id: x.id, name: label5 || "Echo", addedAt: typeof x.addedAt === "number" && Number.isFinite(x.addedAt) ? x.addedAt : 0 }];
6315
6332
  });
6316
- const num5 = (v, o, whole = true) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, whole ? Math.round(v) : Math.round(v * 10) / 10)) : o.def;
6333
+ const num6 = (v, o, whole = true) => typeof v === "number" && Number.isFinite(v) ? Math.min(o.max, Math.max(o.min, whole ? Math.round(v) : Math.round(v * 10) / 10)) : o.def;
6317
6334
  const locales = [...new Set((Array.isArray(r.locales) ? r.locales : []).filter((l) => ALEXA_LOCALES.includes(l)))];
6318
6335
  const tools = [...new Set((Array.isArray(r.extraVoiceTools) ? r.extraVoiceTools : []).filter((t) => typeof t === "string" && TOOL_NAME.test(t) && !isNeverByVoice(t)))].slice(0, 20);
6319
- const maxDevices = num5(r.maxDevices, ALEXA_LIMITS.maxDevices);
6336
+ const maxDevices = num6(r.maxDevices, ALEXA_LIMITS.maxDevices);
6320
6337
  return {
6321
6338
  installed: r.installed === true || r.installed === void 0 && (r.enabled === true || skillId !== ""),
6322
6339
  enabled: r.enabled === true,
@@ -6324,10 +6341,10 @@ function sanitizeAlexa(raw) {
6324
6341
  invocationName: name,
6325
6342
  skillName: (typeof r.skillName === "string" ? r.skillName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 50) : "") || "Friend Assistant",
6326
6343
  locales: locales.length ? locales : [...ALEXA_LOCALES],
6327
- answerSeconds: num5(r.answerSeconds, ALEXA_LIMITS.answerSeconds, false),
6328
- holdMinutes: num5(r.holdMinutes, ALEXA_LIMITS.holdMinutes),
6329
- permissionSeconds: num5(r.permissionSeconds, ALEXA_LIMITS.permissionSeconds),
6330
- requestsPerMinute: num5(r.requestsPerMinute, ALEXA_LIMITS.requestsPerMinute),
6344
+ answerSeconds: num6(r.answerSeconds, ALEXA_LIMITS.answerSeconds, false),
6345
+ holdMinutes: num6(r.holdMinutes, ALEXA_LIMITS.holdMinutes),
6346
+ permissionSeconds: num6(r.permissionSeconds, ALEXA_LIMITS.permissionSeconds),
6347
+ requestsPerMinute: num6(r.requestsPerMinute, ALEXA_LIMITS.requestsPerMinute),
6331
6348
  maxDevices,
6332
6349
  extraVoiceTools: tools,
6333
6350
  allowedUsers: users.slice(0, maxDevices)
@@ -6361,16 +6378,16 @@ function sanitizeBrokers(raw) {
6361
6378
  const z16 = r.zerodha && typeof r.zerodha === "object" ? r.zerodha : {};
6362
6379
  const str3 = (v, max) => typeof v === "string" ? v.trim().slice(0, max) : "";
6363
6380
  const reminder = typeof r.loginReminderMinutes === "number" && Number.isFinite(r.loginReminderMinutes) ? Math.min(120, Math.max(0, Math.round(r.loginReminderMinutes))) : 15;
6364
- const num5 = (v, min, max, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : def;
6381
+ const num6 = (v, min, max, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : def;
6365
6382
  return {
6366
6383
  currencySymbol: str3(r.currencySymbol, 4) || "\u20B9",
6367
6384
  currencyName: str3(r.currencyName, 20) || "rupees",
6368
6385
  numberLocale: validNumberLocale(r.numberLocale) ? r.numberLocale : "en-IN",
6369
- concentrationPct: num5(r.concentrationPct, 5, 90, 30),
6370
- bigDropPct: num5(r.bigDropPct, 1, 50, 5),
6371
- cacheSeconds: num5(r.cacheSeconds, 5, 300, 30),
6372
- maxSchedules: num5(r.maxSchedules, 1, 50, 20),
6373
- maxTriesPerDay: num5(r.maxTriesPerDay, 1, 10, 3),
6386
+ concentrationPct: num6(r.concentrationPct, 5, 90, 30),
6387
+ bigDropPct: num6(r.bigDropPct, 1, 50, 5),
6388
+ cacheSeconds: num6(r.cacheSeconds, 5, 300, 30),
6389
+ maxSchedules: num6(r.maxSchedules, 1, 50, 20),
6390
+ maxTriesPerDay: num6(r.maxTriesPerDay, 1, 10, 3),
6374
6391
  zerodha: {
6375
6392
  installed: z16.installed === true || z16.installed === void 0 && (z16.enabled === true || !!str3(z16.apiKey, 64)),
6376
6393
  enabled: z16.enabled === true,
@@ -6416,6 +6433,17 @@ var sanitizeEye = (e) => ({
6416
6433
  askAboutStrangers: e?.askAboutStrangers === true,
6417
6434
  autoOffMinutes: typeof e?.autoOffMinutes === "number" && Number.isFinite(e.autoOffMinutes) ? Math.min(1440, Math.max(0, Math.round(e.autoOffMinutes))) : 0
6418
6435
  });
6436
+ var sanitizeOauth = (o) => {
6437
+ const clients = {};
6438
+ const src = o && typeof o === "object" ? o.clients : void 0;
6439
+ if (src && typeof src === "object") {
6440
+ for (const [id2, v] of Object.entries(src).slice(0, 20)) {
6441
+ const clientId = v && typeof v === "object" ? v.clientId : void 0;
6442
+ if (/^[a-z0-9-]{1,32}$/.test(id2) && typeof clientId === "string" && clientId.trim() && clientId.length <= 300 && !/[\s\x00-\x1f\x7f]/.test(clientId.trim())) clients[id2] = { clientId: clientId.trim() };
6443
+ }
6444
+ }
6445
+ return { clients };
6446
+ };
6419
6447
  var sanitizeCodeRunner = (v) => v === "sandbox" || v === "docker" ? v : "auto";
6420
6448
  var DEFAULT_OPENAI = { url: "http://localhost:20128/v1", model: "auto", apiKey: null, vision: false };
6421
6449
  var DEFAULT_CLAUDE_CODE = { model: "sonnet", command: "claude", fallback: "ollama", webSearch: true };
@@ -6453,7 +6481,7 @@ function sanitizeLook(raw) {
6453
6481
  var DEFAULT_OLLAMA = { url: "http://127.0.0.1:11434", model: "qwen2.5:7b", contextTokens: 8192, vision: false };
6454
6482
  var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
6455
6483
  var sanitizeProactive = (p) => {
6456
- const num5 = (v, min, max, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : def;
6484
+ const num6 = (v, min, max, def) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : def;
6457
6485
  const time = (v, def) => typeof v === "string" && HHMM.test(v) ? v : def;
6458
6486
  return {
6459
6487
  level: p?.level === "low" || p?.level === "medium" || p?.level === "high" ? p.level : "off",
@@ -6461,9 +6489,9 @@ var sanitizeProactive = (p) => {
6461
6489
  quietTo: time(p?.quietTo, "07:00"),
6462
6490
  morningAt: time(p?.morningAt, "08:00"),
6463
6491
  eveningAt: time(p?.eveningAt, "20:30"),
6464
- dailyCap: num5(p?.dailyCap, 1, 20, 6),
6465
- minGapMin: num5(p?.minGapMin, 5, 720, 30),
6466
- silenceHours: num5(p?.silenceHours, 2, 72, 8),
6492
+ dailyCap: num6(p?.dailyCap, 1, 20, 6),
6493
+ minGapMin: num6(p?.minGapMin, 5, 720, 30),
6494
+ silenceHours: num6(p?.silenceHours, 2, 72, 8),
6467
6495
  speak: p?.speak === true,
6468
6496
  phone: p?.phone !== false
6469
6497
  };
@@ -6608,6 +6636,7 @@ var defaults = (dataDir) => ({
6608
6636
  approvals: "manual",
6609
6637
  codeRunner: "auto",
6610
6638
  eye: sanitizeEye(void 0),
6639
+ oauth: sanitizeOauth(void 0),
6611
6640
  phoneApprovals: sanitizePhoneApprovals(void 0),
6612
6641
  securityAlerts: sanitizeSecurityAlerts(void 0),
6613
6642
  audit: sanitizeAudit(void 0),
@@ -6690,6 +6719,7 @@ function loadConfig(dataDir = defaultDataDir()) {
6690
6719
  approvals: stored.approvals === "edits" || stored.approvals === "auto" ? stored.approvals : "manual",
6691
6720
  codeRunner: sanitizeCodeRunner(stored.codeRunner),
6692
6721
  eye: sanitizeEye(stored.eye),
6722
+ oauth: sanitizeOauth(stored.oauth),
6693
6723
  phoneApprovals: sanitizePhoneApprovals(stored.phoneApprovals),
6694
6724
  securityAlerts: sanitizeSecurityAlerts(stored.securityAlerts),
6695
6725
  audit: sanitizeAudit(stored.audit),
@@ -7562,6 +7592,7 @@ ${text5}`;
7562
7592
  // ../server/src/connectors/hub.ts
7563
7593
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7564
7594
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
7595
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
7565
7596
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7566
7597
  import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7567
7598
  import crossSpawn from "cross-spawn";
@@ -7600,7 +7631,9 @@ var Http = z10.object({
7600
7631
  return false;
7601
7632
  }
7602
7633
  }, "Use https://, or http:// only for a server on this PC (localhost or 127.0.0.1)"),
7603
- headers: z10.record(z10.string().regex(HeaderName), z10.string().max(2e3).refine(noControl)).refine((r) => Object.keys(r).length <= 10, "At most 10 headers").default({})
7634
+ headers: z10.record(z10.string().regex(HeaderName), z10.string().max(2e3).refine(noControl)).refine((r) => Object.keys(r).length <= 10, "At most 10 headers").default({}),
7635
+ /** Sign in with a link (OAuth) instead of a pasted key. */
7636
+ auth: z10.literal("oauth").optional()
7604
7637
  }).strict();
7605
7638
  var ConnectorInput = z10.discriminatedUnion("kind", [Stdio, Http]);
7606
7639
  var ConnectorStore = class {
@@ -7717,6 +7750,7 @@ var McpHub = class {
7717
7750
  opts;
7718
7751
  live = /* @__PURE__ */ new Map();
7719
7752
  names = /* @__PURE__ */ new Map();
7753
+ consents = /* @__PURE__ */ new Map();
7720
7754
  // ---- what is known ----
7721
7755
  list() {
7722
7756
  return this.store.list().map((c) => this.view(c));
@@ -7732,7 +7766,8 @@ var McpHub = class {
7732
7766
  error: c.enabled ? l?.error ?? null : null,
7733
7767
  tools: c.enabled && l?.status === "ready" ? l.tools.length : 0,
7734
7768
  target: describeTarget(c),
7735
- secret: hasSecrets(c)
7769
+ secret: hasSecrets(c),
7770
+ oauth: c.kind === "http" && c.auth === "oauth"
7736
7771
  };
7737
7772
  }
7738
7773
  /** The tools of every connected connector, for the model. */
@@ -7787,6 +7822,21 @@ var McpHub = class {
7787
7822
  if (c.enabled) await this.tryConnect(id2);
7788
7823
  return this.view(this.store.get(id2));
7789
7824
  }
7825
+ /** The address the owner has to be sent to, once, after a connector asked to sign in. Null when no sign-in is waiting. */
7826
+ takeConsent(id2) {
7827
+ const u = this.consents.get(id2) ?? null;
7828
+ this.consents.delete(id2);
7829
+ return u;
7830
+ }
7831
+ /** Finishes a sign-in with the code the service returned, then connects again. */
7832
+ async finishOAuth(id2, code) {
7833
+ const cfg = this.store.get(id2);
7834
+ if (!cfg || cfg.kind !== "http" || cfg.auth !== "oauth" || !this.opts.oauth) throw new Error(`There is no connector "${id2}" that signs in with a link.`);
7835
+ const transport = new StreamableHTTPClientTransport(new URL(cfg.url), { authProvider: this.opts.oauth.provider(id2, cfg.name, cfg.url, () => {
7836
+ }) });
7837
+ await transport.finishAuth(code);
7838
+ return this.reload(id2);
7839
+ }
7790
7840
  async remove(id2) {
7791
7841
  if (!this.store.remove(id2)) throw new Error(`There is no connector "${id2}".`);
7792
7842
  await this.disconnect(id2);
@@ -7865,6 +7915,12 @@ ${l.stderr}` : ""}`, isError: true };
7865
7915
  entry.status = "ready";
7866
7916
  entry.error = null;
7867
7917
  } catch (e) {
7918
+ if (e instanceof UnauthorizedError) {
7919
+ entry.status = "needs-approval";
7920
+ entry.error = "Waiting for your approval.";
7921
+ await stopLive(entry);
7922
+ return;
7923
+ }
7868
7924
  entry.status = "error";
7869
7925
  entry.error = `${messageOf(e)}${entry.stderr ? ` (${entry.stderr.trim().split("\n").slice(-2).join(" ").slice(0, 200)})` : ""}`;
7870
7926
  await stopLive(entry);
@@ -7888,6 +7944,10 @@ ${l.stderr}` : ""}`, isError: true };
7888
7944
  });
7889
7945
  return t;
7890
7946
  }
7947
+ if (cfg.auth === "oauth" && this.opts.oauth) {
7948
+ const provider = this.opts.oauth.provider(cfg.id, cfg.name, cfg.url, (u) => this.consents.set(cfg.id, u));
7949
+ return new StreamableHTTPClientTransport(new URL(cfg.url), { authProvider: provider, requestInit: { headers: cfg.headers } });
7950
+ }
7891
7951
  return new StreamableHTTPClientTransport(new URL(cfg.url), { requestInit: { headers: cfg.headers } });
7892
7952
  }
7893
7953
  async readTools(id2, entry) {
@@ -13536,7 +13596,7 @@ var MusicSecrets = class {
13536
13596
  };
13537
13597
  var refreshing = /* @__PURE__ */ new WeakMap();
13538
13598
  var waitUntil = /* @__PURE__ */ new WeakMap();
13539
- async function freshToken(source, tokens, refresh, clock3 = Date.now) {
13599
+ async function freshToken(source, tokens, refresh2, clock3 = Date.now) {
13540
13600
  const login = tokens.load(source);
13541
13601
  if (!login || tokens.needsReconnect(source)) return null;
13542
13602
  if (login.expiresAt - clock3() > REFRESH_AHEAD_MS) return login.accessToken;
@@ -13550,7 +13610,7 @@ async function freshToken(source, tokens, refresh, clock3 = Date.now) {
13550
13610
  if (running2) return running2;
13551
13611
  const job = (async () => {
13552
13612
  try {
13553
- const next = await refresh(login.refreshToken);
13613
+ const next = await refresh2(login.refreshToken);
13554
13614
  if (tokens.generation(source) !== generation) return null;
13555
13615
  tokens.save(source, { ...login, accessToken: next.accessToken, refreshToken: next.refreshToken ?? login.refreshToken, expiresAt: next.expiresAt });
13556
13616
  return next.accessToken;
@@ -14307,6 +14367,464 @@ var MusicLibrary = class {
14307
14367
  }
14308
14368
  };
14309
14369
 
14370
+ // ../server/src/oauth/providers.ts
14371
+ var PROVIDERS = [
14372
+ {
14373
+ id: "google",
14374
+ name: "Google (Gmail)",
14375
+ authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
14376
+ tokenUrl: "https://oauth2.googleapis.com/token",
14377
+ revokeUrl: "https://oauth2.googleapis.com/revoke",
14378
+ scopes: ["openid", "email", "https://www.googleapis.com/auth/gmail.readonly"],
14379
+ extraAuthParams: { access_type: "offline", prompt: "consent", include_granted_scopes: "true" }
14380
+ }
14381
+ ];
14382
+ var providerById = (id2) => PROVIDERS.find((p) => p.id === id2);
14383
+
14384
+ // ../server/src/oauth/redirect.ts
14385
+ function redirectUri(publicUrl, port) {
14386
+ const base = publicUrl ? publicUrl.replace(/\/+$/, "") : `http://127.0.0.1:${port}`;
14387
+ return `${base}/api/oauth/callback`;
14388
+ }
14389
+
14390
+ // ../server/src/oauth/guard.ts
14391
+ import { isIPv4, isIPv6 } from "node:net";
14392
+ var LOCAL_NAMES = (h) => h === "localhost" || h.endsWith(".localhost");
14393
+ function privateV4(h) {
14394
+ const [a, b] = h.split(".").map(Number);
14395
+ return a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127 || a >= 224;
14396
+ }
14397
+ function groups(h) {
14398
+ let s = h;
14399
+ const v4 = s.match(/(\d+\.\d+\.\d+\.\d+)$/);
14400
+ if (v4) {
14401
+ const p = v4[1].split(".").map(Number);
14402
+ s = s.slice(0, -v4[1].length) + (p[0] << 8 | p[1]).toString(16) + ":" + (p[2] << 8 | p[3]).toString(16);
14403
+ }
14404
+ const [head = "", tail2 = ""] = s.split("::");
14405
+ const h1 = head ? head.split(":") : [];
14406
+ const t1 = s.includes("::") ? tail2 ? tail2.split(":") : [] : [];
14407
+ const fill = s.includes("::") ? Array(8 - h1.length - t1.length).fill("0") : [];
14408
+ return [...h1, ...fill, ...t1].map((x) => parseInt(x || "0", 16));
14409
+ }
14410
+ function privateV6(h) {
14411
+ const g = groups(h);
14412
+ if (g.length !== 8 || g.some(Number.isNaN)) return true;
14413
+ if (g.every((x) => x === 0) || g.slice(0, 7).every((x) => x === 0) && g[7] === 1) return true;
14414
+ const first3 = g[0];
14415
+ if ((first3 & 65024) === 64512 || (first3 & 65472) === 65152 || (first3 & 65280) === 65280) return true;
14416
+ if (g.slice(0, 5).every((x) => x === 0) && g[5] === 65535) return privateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
14417
+ return false;
14418
+ }
14419
+ function isLoopbackHost(h) {
14420
+ return LOCAL_NAMES(h) || isIPv4(h) && h.startsWith("127.") || h === "::1";
14421
+ }
14422
+ function assertSafeUrl(raw, opts = {}) {
14423
+ let u;
14424
+ try {
14425
+ u = new URL(raw);
14426
+ } catch {
14427
+ throw new Error("That is not a valid web address.");
14428
+ }
14429
+ const host2 = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
14430
+ if (opts.allowLoopback && (u.protocol === "http:" || u.protocol === "https:") && isLoopbackHost(host2)) return u;
14431
+ if (u.protocol !== "https:") throw new Error("Only https:// addresses are allowed.");
14432
+ if (LOCAL_NAMES(host2) || isIPv4(host2) && privateV4(host2) || isIPv6(host2) && privateV6(host2)) throw new Error("That address points inside a private network.");
14433
+ return u;
14434
+ }
14435
+
14436
+ // ../server/src/oauth/service.ts
14437
+ function buildAuthUrl(p, a) {
14438
+ const u = assertSafeUrl(p.authUrl);
14439
+ u.searchParams.set("response_type", "code");
14440
+ u.searchParams.set("client_id", a.clientId);
14441
+ u.searchParams.set("redirect_uri", a.redirectUri);
14442
+ u.searchParams.set("scope", p.scopes.join(" "));
14443
+ u.searchParams.set("state", a.state);
14444
+ u.searchParams.set("code_challenge", a.challenge);
14445
+ u.searchParams.set("code_challenge_method", "S256");
14446
+ for (const [k, v] of Object.entries(p.extraAuthParams ?? {})) u.searchParams.set(k, v);
14447
+ return u.toString();
14448
+ }
14449
+ async function postForm(url, body, f) {
14450
+ const res = await f(assertSafeUrl(url).toString(), {
14451
+ method: "POST",
14452
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
14453
+ body,
14454
+ redirect: "error",
14455
+ signal: AbortSignal.timeout(2e4)
14456
+ });
14457
+ let json = {};
14458
+ try {
14459
+ json = await res.json();
14460
+ } catch {
14461
+ }
14462
+ return { status: res.status, json };
14463
+ }
14464
+ function labelOf(idToken) {
14465
+ if (typeof idToken !== "string") return void 0;
14466
+ try {
14467
+ const payload = JSON.parse(Buffer.from(idToken.split(".")[1] ?? "", "base64url").toString("utf8"));
14468
+ return typeof payload.email === "string" ? payload.email.slice(0, 120) : void 0;
14469
+ } catch {
14470
+ return void 0;
14471
+ }
14472
+ }
14473
+ var num3 = (v, d) => typeof v === "number" && Number.isFinite(v) ? v : d;
14474
+ async function exchangeCode(p, a, f = fetch, clock3 = Date.now) {
14475
+ const body = new URLSearchParams({ grant_type: "authorization_code", code: a.code, code_verifier: a.verifier, redirect_uri: a.redirectUri, client_id: a.clientId });
14476
+ if (a.clientSecret) body.set("client_secret", a.clientSecret);
14477
+ const { status: status2, json } = await postForm(p.tokenUrl, body, f);
14478
+ if (status2 < 200 || status2 >= 300 || typeof json.access_token !== "string") throw new Error(`${p.name} did not accept the sign-in (${typeof json.error === "string" ? json.error.slice(0, 60) : status2}).`);
14479
+ return {
14480
+ accessToken: json.access_token,
14481
+ refreshToken: typeof json.refresh_token === "string" ? json.refresh_token : void 0,
14482
+ expiresAt: clock3() + num3(json.expires_in, 3600) * 1e3,
14483
+ scopes: typeof json.scope === "string" ? json.scope.split(" ").filter(Boolean) : p.scopes,
14484
+ account: labelOf(json.id_token)
14485
+ };
14486
+ }
14487
+ async function refresh(p, a, f = fetch, clock3 = Date.now) {
14488
+ const body = new URLSearchParams({ grant_type: "refresh_token", refresh_token: a.refreshToken, client_id: a.clientId });
14489
+ if (a.clientSecret) body.set("client_secret", a.clientSecret);
14490
+ const { status: status2, json } = await postForm(p.tokenUrl, body, f);
14491
+ if (json.error === "invalid_grant" || json.error === "invalid_client" || json.error === "unauthorized_client") throw new RefreshRejected(String(json.error));
14492
+ if (status2 < 200 || status2 >= 300 || typeof json.access_token !== "string") throw new Error(`${p.name} could not renew the sign-in (${status2}).`);
14493
+ return { accessToken: json.access_token, refreshToken: typeof json.refresh_token === "string" ? json.refresh_token : void 0, expiresAt: clock3() + num3(json.expires_in, 3600) * 1e3 };
14494
+ }
14495
+ async function revoke(p, token, f = fetch) {
14496
+ if (!p.revokeUrl) return;
14497
+ try {
14498
+ await postForm(p.revokeUrl, new URLSearchParams({ token }), f);
14499
+ } catch {
14500
+ }
14501
+ }
14502
+
14503
+ // ../server/src/oauth/tickets.ts
14504
+ import { randomBytes as randomBytes9 } from "node:crypto";
14505
+ var TTL_MS2 = 10 * 6e4;
14506
+ var MAX_WAITING2 = 20;
14507
+ var make = () => randomBytes9(24).toString("base64url");
14508
+ var OAuthTickets = class {
14509
+ constructor(clock3 = Date.now) {
14510
+ this.clock = clock3;
14511
+ }
14512
+ clock;
14513
+ tickets = /* @__PURE__ */ new Map();
14514
+ states = /* @__PURE__ */ new Map();
14515
+ put(map, key2, extra) {
14516
+ const id2 = make();
14517
+ map.set(id2, { key: key2, extra, at: this.clock() });
14518
+ while (map.size > MAX_WAITING2) map.delete(map.keys().next().value);
14519
+ return id2;
14520
+ }
14521
+ take(map, id2) {
14522
+ const item = typeof id2 === "string" ? map.get(id2) : void 0;
14523
+ if (!item) return null;
14524
+ map.delete(id2);
14525
+ return this.clock() - item.at > TTL_MS2 ? null : item;
14526
+ }
14527
+ issueTicket(key2) {
14528
+ return this.put(this.tickets, key2, {});
14529
+ }
14530
+ takeTicket(ticket) {
14531
+ return this.take(this.tickets, ticket)?.key ?? null;
14532
+ }
14533
+ issueState(key2, extra = {}) {
14534
+ return this.put(this.states, key2, extra);
14535
+ }
14536
+ takeState(state) {
14537
+ const i = this.take(this.states, state);
14538
+ return i ? { key: i.key, extra: i.extra } : null;
14539
+ }
14540
+ };
14541
+
14542
+ // ../server/src/oauth/vault.ts
14543
+ import { chmodSync as chmodSync6, existsSync as existsSync16, mkdirSync as mkdirSync12, readFileSync as readFileSync11, renameSync as renameSync5, writeFileSync as writeFileSync11 } from "node:fs";
14544
+ import { join as join18 } from "node:path";
14545
+ var OAuthVault = class {
14546
+ constructor(dataDir) {
14547
+ this.dataDir = dataDir;
14548
+ this.path = join18(dataDir, "oauth-vault.json");
14549
+ this.all = this.load();
14550
+ }
14551
+ dataDir;
14552
+ path;
14553
+ all;
14554
+ load() {
14555
+ if (!existsSync16(this.path)) return {};
14556
+ try {
14557
+ const text5 = unsealText(readFileSync11(this.path, "utf8"), this.dataDir);
14558
+ const j = text5 ? JSON.parse(text5) : null;
14559
+ return j && typeof j === "object" && !Array.isArray(j) ? j : {};
14560
+ } catch {
14561
+ return {};
14562
+ }
14563
+ }
14564
+ save() {
14565
+ mkdirSync12(this.dataDir, { recursive: true });
14566
+ const tmp = `${this.path}.tmp`;
14567
+ writeFileSync11(tmp, sealText(JSON.stringify(this.all), this.dataDir), { mode: 384 });
14568
+ try {
14569
+ chmodSync6(tmp, 384);
14570
+ } catch {
14571
+ }
14572
+ renameSync5(tmp, this.path);
14573
+ }
14574
+ get(key2) {
14575
+ return structuredClone(this.all[key2] ?? {});
14576
+ }
14577
+ has(key2) {
14578
+ return key2 in this.all;
14579
+ }
14580
+ keys() {
14581
+ return Object.keys(this.all);
14582
+ }
14583
+ /** Merges fields. A different authorization server drops the old login and client: they are only good where they were issued. */
14584
+ patch(key2, p) {
14585
+ const cur = this.all[key2] ?? {};
14586
+ const moved = p.issuer !== void 0 && cur.issuer !== void 0 && p.issuer !== cur.issuer;
14587
+ const base = moved ? { clientSecret: cur.clientSecret } : cur;
14588
+ this.all[key2] = structuredClone({ ...base, ...p });
14589
+ this.save();
14590
+ }
14591
+ forget(key2) {
14592
+ if (!(key2 in this.all)) return;
14593
+ delete this.all[key2];
14594
+ this.save();
14595
+ }
14596
+ };
14597
+
14598
+ // ../server/src/oauth/hub.ts
14599
+ var REFRESH_AHEAD_MS2 = 6e4;
14600
+ var TRANSIENT_WAIT_MS2 = 3e4;
14601
+ var OAuthHub = class {
14602
+ constructor(d) {
14603
+ this.d = d;
14604
+ this.clock = d.clock ?? Date.now;
14605
+ this.f = d.fetch ?? fetch;
14606
+ this.vault = new OAuthVault(d.dataDir);
14607
+ this.tickets = new OAuthTickets(this.clock);
14608
+ }
14609
+ d;
14610
+ vault;
14611
+ tickets;
14612
+ clock;
14613
+ f;
14614
+ refreshing = /* @__PURE__ */ new Map();
14615
+ waitUntil = /* @__PURE__ */ new Map();
14616
+ /** The consent address an MCP connector's login library asked us to send the owner to, until the owner opens its link. */
14617
+ mcpPending = /* @__PURE__ */ new Map();
14618
+ base() {
14619
+ const c = this.d.config();
14620
+ return (c.publicUrl ?? `http://127.0.0.1:${c.port}`).replace(/\/+$/, "");
14621
+ }
14622
+ redirectUri() {
14623
+ const c = this.d.config();
14624
+ return redirectUri(c.publicUrl, c.port);
14625
+ }
14626
+ services() {
14627
+ const clients = this.d.config().oauth.clients;
14628
+ return PROVIDERS.map((p) => {
14629
+ const e = this.vault.get(`svc:${p.id}`);
14630
+ return { id: p.id, name: p.name, configured: !!clients[p.id], connected: !!e.tokens, needsReconnect: !!e.needsReconnect, account: e.account ?? null, redirectUri: this.redirectUri() };
14631
+ });
14632
+ }
14633
+ clientOf(p) {
14634
+ const c = this.d.config().oauth.clients[p.id];
14635
+ if (!c) throw new Error(`Add the ${p.name} client ID first (Settings, Connectors).`);
14636
+ return { clientId: c.clientId, clientSecret: this.vault.get(`svc:${p.id}`).clientSecret };
14637
+ }
14638
+ async deliver(key2, toPhone, label5) {
14639
+ const link = `${this.base()}/api/oauth/start/${this.tickets.issueTicket(key2)}`;
14640
+ this.d.audit.log("owner", "oauth.start", { key: key2 });
14641
+ const sent = toPhone ? await this.d.send(`Approve the ${label5} connection (the link works once, for ten minutes):
14642
+ ${link}`).catch(() => false) : false;
14643
+ return { link, sent };
14644
+ }
14645
+ /** An approval link for a known service. Nothing happens until the owner opens it. */
14646
+ async startService(id2, opts = {}) {
14647
+ const p = providerById(id2);
14648
+ if (!p) throw new Error("Friend does not know that service.");
14649
+ this.clientOf(p);
14650
+ return this.deliver(`svc:${id2}`, opts.toPhone, p.name);
14651
+ }
14652
+ /** An approval link for an MCP connector whose login the library has begun: the library gave the consent address. */
14653
+ async approvalForMcp(connectorId, consent, label5, toPhone) {
14654
+ const key2 = `mcp:${connectorId}`;
14655
+ this.mcpPending.set(key2, consent.toString());
14656
+ return this.deliver(key2, toPhone, label5);
14657
+ }
14658
+ /** The consent address behind a link, once. Null for a link that is unknown, used or older than ten minutes. */
14659
+ openTicket(ticket) {
14660
+ const key2 = this.tickets.takeTicket(ticket);
14661
+ if (!key2) return null;
14662
+ if (key2.startsWith("mcp:")) {
14663
+ const url = this.mcpPending.get(key2) ?? null;
14664
+ this.mcpPending.delete(key2);
14665
+ return url;
14666
+ }
14667
+ const p = providerById(key2.slice(4));
14668
+ if (!p) return null;
14669
+ try {
14670
+ const { clientId } = this.clientOf(p);
14671
+ const { verifier, challenge } = pkcePair();
14672
+ const state = this.tickets.issueState(key2, { verifier });
14673
+ return buildAuthUrl(p, { clientId, redirectUri: this.redirectUri(), state, challenge });
14674
+ } catch {
14675
+ return null;
14676
+ }
14677
+ }
14678
+ /** The service sent the owner back. For a known service the login is finished here; for an MCP connector the code is handed back to finish it. */
14679
+ async callback(params) {
14680
+ const st = this.tickets.takeState(params.state ?? "");
14681
+ if (!st) return { ok: false };
14682
+ if (params.error || !params.code) {
14683
+ this.d.audit.log("owner", "oauth.refused", { key: st.key });
14684
+ return { ok: false, key: st.key };
14685
+ }
14686
+ if (st.key.startsWith("mcp:")) return { ok: true, key: st.key, code: params.code };
14687
+ const p = providerById(st.key.slice(4));
14688
+ if (!p) return { ok: false };
14689
+ try {
14690
+ if (params.iss && params.iss !== new URL(p.authUrl).origin) throw new Error("wrong issuer");
14691
+ const c = this.clientOf(p);
14692
+ const g = await exchangeCode(p, { ...c, code: params.code, verifier: st.extra.verifier ?? "", redirectUri: this.redirectUri() }, this.f, this.clock);
14693
+ const tokens = { accessToken: g.accessToken, refreshToken: g.refreshToken, expiresAt: g.expiresAt };
14694
+ this.vault.patch(st.key, { issuer: new URL(p.authUrl).origin, tokens, account: g.account, scopes: g.scopes, needsReconnect: false });
14695
+ this.waitUntil.delete(st.key);
14696
+ this.d.audit.log("owner", "oauth.connected", { key: st.key, account: g.account ?? null });
14697
+ return { ok: true, key: st.key };
14698
+ } catch {
14699
+ this.d.audit.log("owner", "oauth.failed", { key: st.key });
14700
+ return { ok: false, key: st.key };
14701
+ }
14702
+ }
14703
+ /** A good access token for a known service, renewed when it is about to end. Null when not connected or the login has to be redone. */
14704
+ async accessToken(id2) {
14705
+ const key2 = `svc:${id2}`;
14706
+ const p = providerById(id2);
14707
+ const e = this.vault.get(key2);
14708
+ const t = e.tokens;
14709
+ if (!p || !t || e.needsReconnect) return null;
14710
+ if (t.expiresAt - this.clock() > REFRESH_AHEAD_MS2) return t.accessToken;
14711
+ if (!t.refreshToken) return null;
14712
+ if ((this.waitUntil.get(key2) ?? 0) > this.clock()) return null;
14713
+ const running2 = this.refreshing.get(key2);
14714
+ if (running2) return running2;
14715
+ const job = (async () => {
14716
+ try {
14717
+ const next = await refresh(p, { ...this.clientOf(p), refreshToken: t.refreshToken }, this.f, this.clock);
14718
+ this.vault.patch(key2, { tokens: { accessToken: next.accessToken, refreshToken: next.refreshToken ?? t.refreshToken, expiresAt: next.expiresAt } });
14719
+ return next.accessToken;
14720
+ } catch (err) {
14721
+ if (err instanceof RefreshRejected) {
14722
+ this.vault.patch(key2, { needsReconnect: true });
14723
+ this.d.audit.log("system", "oauth.refresh.failed", { key: key2 });
14724
+ void this.d.send(`Your ${p.name} sign-in ended. Open Friend and press Connect to sign in again.`).catch(() => false);
14725
+ } else this.waitUntil.set(key2, this.clock() + TRANSIENT_WAIT_MS2);
14726
+ return null;
14727
+ } finally {
14728
+ this.refreshing.delete(key2);
14729
+ }
14730
+ })();
14731
+ this.refreshing.set(key2, job);
14732
+ return job;
14733
+ }
14734
+ /** Tells the service to forget the login, then forgets it here. A client secret the owner typed stays. */
14735
+ async disconnect(key2) {
14736
+ const e = this.vault.get(key2);
14737
+ if (key2.startsWith("svc:")) {
14738
+ const p = providerById(key2.slice(4));
14739
+ const t = e.tokens;
14740
+ if (p && t) await revoke(p, t.refreshToken ?? t.accessToken, this.f);
14741
+ }
14742
+ this.vault.forget(key2);
14743
+ if (e.clientSecret) this.vault.patch(key2, { clientSecret: e.clientSecret });
14744
+ this.mcpPending.delete(key2);
14745
+ this.d.audit.log("owner", "oauth.revoked", { key: key2 });
14746
+ }
14747
+ /** Write-only: nothing gives the secret back. */
14748
+ setClientSecret(id2, secret) {
14749
+ this.vault.patch(`svc:${id2}`, { clientSecret: secret });
14750
+ }
14751
+ };
14752
+
14753
+ // ../server/src/oauth/mcpProvider.ts
14754
+ var VaultOAuthProvider = class {
14755
+ constructor(key2, vault, tickets, redirect, clientName, onConsent, allowLoopback = false) {
14756
+ this.key = key2;
14757
+ this.vault = vault;
14758
+ this.tickets = tickets;
14759
+ this.redirect = redirect;
14760
+ this.clientName = clientName;
14761
+ this.onConsent = onConsent;
14762
+ this.allowLoopback = allowLoopback;
14763
+ }
14764
+ key;
14765
+ vault;
14766
+ tickets;
14767
+ redirect;
14768
+ clientName;
14769
+ onConsent;
14770
+ allowLoopback;
14771
+ get redirectUrl() {
14772
+ return this.redirect;
14773
+ }
14774
+ get clientMetadata() {
14775
+ return {
14776
+ client_name: this.clientName,
14777
+ redirect_uris: [this.redirect],
14778
+ grant_types: ["authorization_code", "refresh_token"],
14779
+ response_types: ["code"],
14780
+ token_endpoint_auth_method: "none"
14781
+ };
14782
+ }
14783
+ state() {
14784
+ return this.tickets.issueState(this.key);
14785
+ }
14786
+ clientInformation() {
14787
+ return this.vault.get(this.key).clientInfo;
14788
+ }
14789
+ saveClientInformation(info) {
14790
+ const issuer = info.issuer;
14791
+ this.vault.patch(this.key, { clientInfo: info, ...issuer ? { issuer } : {} });
14792
+ }
14793
+ tokens() {
14794
+ return this.vault.get(this.key).tokens;
14795
+ }
14796
+ saveTokens(tokens) {
14797
+ const issuer = tokens.issuer;
14798
+ this.vault.patch(this.key, { tokens, needsReconnect: false, ...issuer ? { issuer } : {} });
14799
+ }
14800
+ redirectToAuthorization(url) {
14801
+ assertSafeUrl(url.toString(), { allowLoopback: this.allowLoopback });
14802
+ this.onConsent(url);
14803
+ }
14804
+ saveCodeVerifier(v) {
14805
+ this.vault.patch(this.key, { verifier: v });
14806
+ }
14807
+ codeVerifier() {
14808
+ const v = this.vault.get(this.key).verifier;
14809
+ if (!v) throw new Error("There is no sign-in in progress.");
14810
+ return v;
14811
+ }
14812
+ saveDiscoveryState(s) {
14813
+ this.vault.patch(this.key, { discovery: s });
14814
+ }
14815
+ discoveryState() {
14816
+ return this.vault.get(this.key).discovery;
14817
+ }
14818
+ invalidateCredentials(scope) {
14819
+ const clear = {};
14820
+ if (scope === "all" || scope === "client") clear.clientInfo = void 0;
14821
+ if (scope === "all" || scope === "tokens") clear.tokens = void 0;
14822
+ if (scope === "all" || scope === "verifier") clear.verifier = void 0;
14823
+ if (scope === "all" || scope === "discovery") clear.discovery = void 0;
14824
+ this.vault.patch(this.key, clear);
14825
+ }
14826
+ };
14827
+
14310
14828
  // ../server/src/music/source.ts
14311
14829
  var NAMES = { local: "The music folder", spotify: "Spotify", soundcloud: "SoundCloud", audius: "Audius" };
14312
14830
  var LocalSource = class {
@@ -14909,9 +15427,9 @@ var ReportSchedules = class {
14909
15427
  };
14910
15428
 
14911
15429
  // ../server/src/brokers/session.ts
14912
- import { randomBytes as randomBytes9 } from "node:crypto";
14913
- import { chmodSync as chmodSync6, existsSync as existsSync16, mkdirSync as mkdirSync12, readFileSync as readFileSync11, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
14914
- import { join as join18 } from "node:path";
15430
+ import { randomBytes as randomBytes10 } from "node:crypto";
15431
+ import { chmodSync as chmodSync7, existsSync as existsSync17, mkdirSync as mkdirSync13, readFileSync as readFileSync12, rmSync as rmSync9, writeFileSync as writeFileSync12 } from "node:fs";
15432
+ import { join as join19 } from "node:path";
14915
15433
  var STATE_TTL_MS2 = 10 * 6e4;
14916
15434
  var MAX_STATES2 = 20;
14917
15435
  var BROKER_ID = /^[a-z0-9-]{1,40}$/;
@@ -14925,14 +15443,14 @@ var BrokerSessions = class {
14925
15443
  states = /* @__PURE__ */ new Map();
14926
15444
  file(broker) {
14927
15445
  if (!BROKER_ID.test(broker)) throw new Error("That is not a broker id.");
14928
- return join18(this.dir, `broker-${broker}.session.json`);
15446
+ return join19(this.dir, `broker-${broker}.session.json`);
14929
15447
  }
14930
15448
  save(broker, info) {
14931
15449
  const file = this.file(broker);
14932
- mkdirSync12(this.dir, { recursive: true });
14933
- writeFileSync11(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
15450
+ mkdirSync13(this.dir, { recursive: true });
15451
+ writeFileSync12(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
14934
15452
  try {
14935
- chmodSync6(file, 384);
15453
+ chmodSync7(file, 384);
14936
15454
  } catch {
14937
15455
  }
14938
15456
  }
@@ -14940,9 +15458,9 @@ var BrokerSessions = class {
14940
15458
  load(broker) {
14941
15459
  if (!BROKER_ID.test(broker)) return null;
14942
15460
  const file = this.file(broker);
14943
- if (!existsSync16(file)) return null;
15461
+ if (!existsSync17(file)) return null;
14944
15462
  try {
14945
- const raw = JSON.parse(readFileSync11(file, "utf8"));
15463
+ const raw = JSON.parse(readFileSync12(file, "utf8"));
14946
15464
  if (typeof raw.accessToken !== "string" || typeof raw.expiresAt !== "number") return null;
14947
15465
  if (raw.expiresAt <= this.clock()) {
14948
15466
  this.clear(broker);
@@ -14959,7 +15477,7 @@ var BrokerSessions = class {
14959
15477
  }
14960
15478
  /** A fresh unguessable code for one login at `broker`. At most twenty wait at once; the oldest is dropped. */
14961
15479
  newState(broker) {
14962
- const state = randomBytes9(24).toString("hex");
15480
+ const state = randomBytes10(24).toString("hex");
14963
15481
  this.states.set(state, { broker, at: this.clock() });
14964
15482
  while (this.states.size > MAX_STATES2) this.states.delete(this.states.keys().next().value);
14965
15483
  return state;
@@ -14985,7 +15503,7 @@ function nextSixIst(now) {
14985
15503
  const today2 = midnightUtc + SIX_IST_UTC_MS;
14986
15504
  return today2 > now ? today2 : today2 + DAY_MS;
14987
15505
  }
14988
- var num3 = (v) => {
15506
+ var num4 = (v) => {
14989
15507
  const n2 = Number(v ?? 0);
14990
15508
  return Number.isFinite(n2) ? n2 : 0;
14991
15509
  };
@@ -15064,13 +15582,13 @@ function createZerodha(opts) {
15064
15582
  symbol: str2(h.tradingsymbol),
15065
15583
  exchange: str2(h.exchange),
15066
15584
  // shares bought in the last day are held but not yet settled: they count as held
15067
- quantity: num3(h.quantity) + num3(h.t1_quantity),
15068
- avgPrice: num3(h.average_price),
15069
- lastPrice: num3(h.last_price),
15070
- closePrice: num3(h.close_price),
15071
- pnl: num3(h.pnl),
15072
- dayChange: num3(h.day_change),
15073
- dayChangePct: num3(h.day_change_percentage),
15585
+ quantity: num4(h.quantity) + num4(h.t1_quantity),
15586
+ avgPrice: num4(h.average_price),
15587
+ lastPrice: num4(h.last_price),
15588
+ closePrice: num4(h.close_price),
15589
+ pnl: num4(h.pnl),
15590
+ dayChange: num4(h.day_change),
15591
+ dayChangePct: num4(h.day_change_percentage),
15074
15592
  product: str2(h.product)
15075
15593
  }));
15076
15594
  },
@@ -15079,16 +15597,16 @@ function createZerodha(opts) {
15079
15597
  symbol: str2(p.tradingsymbol),
15080
15598
  exchange: str2(p.exchange),
15081
15599
  product: str2(p.product),
15082
- quantity: num3(p.quantity),
15083
- avgPrice: num3(p.average_price),
15084
- lastPrice: num3(p.last_price),
15085
- pnl: num3(p.pnl)
15600
+ quantity: num4(p.quantity),
15601
+ avgPrice: num4(p.average_price),
15602
+ lastPrice: num4(p.last_price),
15603
+ pnl: num4(p.pnl)
15086
15604
  }));
15087
15605
  },
15088
15606
  async funds() {
15089
15607
  const equity = rec(rec(await get2("/user/margins")).equity);
15090
- const available = num3(equity.net);
15091
- const used2 = num3(rec(equity.utilised).debits);
15608
+ const available = num4(equity.net);
15609
+ const used2 = num4(rec(equity.utilised).debits);
15092
15610
  return { available, used: used2, total: available + used2 };
15093
15611
  },
15094
15612
  async orders() {
@@ -15097,9 +15615,9 @@ function createZerodha(opts) {
15097
15615
  symbol: str2(o.tradingsymbol),
15098
15616
  exchange: str2(o.exchange),
15099
15617
  side: o.transaction_type === "SELL" ? "SELL" : "BUY",
15100
- quantity: num3(o.quantity),
15101
- price: num3(o.price),
15102
- avgPrice: num3(o.average_price),
15618
+ quantity: num4(o.quantity),
15619
+ price: num4(o.price),
15620
+ avgPrice: num4(o.average_price),
15103
15621
  type: str2(o.order_type),
15104
15622
  product: str2(o.product),
15105
15623
  status: str2(o.status),
@@ -15278,15 +15796,15 @@ ${url}`);
15278
15796
  // ../server/src/codebox.ts
15279
15797
  import { spawn as spawn5 } from "node:child_process";
15280
15798
  import { randomUUID as randomUUID5 } from "node:crypto";
15281
- import { chmodSync as chmodSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync10, writeFileSync as writeFileSync12 } from "node:fs";
15799
+ import { chmodSync as chmodSync8, mkdtempSync as mkdtempSync2, rmSync as rmSync10, writeFileSync as writeFileSync13 } from "node:fs";
15282
15800
  import { tmpdir as tmpdir2 } from "node:os";
15283
- import { join as join20 } from "node:path";
15801
+ import { join as join21 } from "node:path";
15284
15802
 
15285
15803
  // ../server/src/sandbox/index.ts
15286
15804
  import { spawn as spawn4 } from "node:child_process";
15287
- import { existsSync as existsSync17, realpathSync } from "node:fs";
15805
+ import { existsSync as existsSync18, realpathSync } from "node:fs";
15288
15806
  import { createRequire } from "node:module";
15289
- import { dirname as dirname5, join as join19, sep as sep3 } from "node:path";
15807
+ import { dirname as dirname5, join as join20, sep as sep3 } from "node:path";
15290
15808
  import { fileURLToPath as fileURLToPath2 } from "node:url";
15291
15809
 
15292
15810
  // ../server/src/sandbox/types.ts
@@ -15299,13 +15817,13 @@ var SANDBOX_MEMORY_MB = 512;
15299
15817
  var RESULT_MARK = "\n@@friend-sandbox-result@@";
15300
15818
  function childFile() {
15301
15819
  const here2 = dirname5(fileURLToPath2(import.meta.url));
15302
- for (const f of [join19(here2, "sandbox-child.mjs"), join19(here2, "..", "..", ".sandbox-dev", "child.mjs")]) if (existsSync17(f)) return f;
15820
+ for (const f of [join20(here2, "sandbox-child.mjs"), join20(here2, "..", "..", ".sandbox-dev", "child.mjs")]) if (existsSync18(f)) return f;
15303
15821
  throw new SandboxUnavailable("The built-in sandbox program is missing. Run `pnpm build` (from the source) or reinstall Friend.");
15304
15822
  }
15305
15823
  function engineFolders(child) {
15306
15824
  const found = /* @__PURE__ */ new Set();
15307
15825
  for (let dir = dirname5(child); ; dir = dirname5(dir)) {
15308
- if (existsSync17(join19(dir, "node_modules", "quickjs-emscripten"))) found.add(join19(dir, "node_modules"));
15826
+ if (existsSync18(join20(dir, "node_modules", "quickjs-emscripten"))) found.add(join20(dir, "node_modules"));
15309
15827
  if (dirname5(dir) === dir) break;
15310
15828
  }
15311
15829
  try {
@@ -15489,15 +16007,15 @@ var CodeBox = class {
15489
16007
  async inDocker(input, timeoutMs) {
15490
16008
  const extra = Object.entries(input.files ?? {});
15491
16009
  const setup = SETUP[input.language];
15492
- const dir = mkdtempSync2(join20(tmpdir2(), "friend-code-"));
16010
+ const dir = mkdtempSync2(join21(tmpdir2(), "friend-code-"));
15493
16011
  try {
15494
- const file = join20(dir, setup.file);
15495
- writeFileSync12(file, input.code);
15496
- chmodSync7(dir, 493);
15497
- chmodSync7(file, 420);
16012
+ const file = join21(dir, setup.file);
16013
+ writeFileSync13(file, input.code);
16014
+ chmodSync8(dir, 493);
16015
+ chmodSync8(file, 420);
15498
16016
  for (const [name, body] of extra) {
15499
- writeFileSync12(join20(dir, name), body);
15500
- chmodSync7(join20(dir, name), 420);
16017
+ writeFileSync13(join21(dir, name), body);
16018
+ chmodSync8(join21(dir, name), 420);
15501
16019
  }
15502
16020
  const args = [
15503
16021
  "run",
@@ -15641,26 +16159,26 @@ var Memory = class {
15641
16159
  };
15642
16160
 
15643
16161
  // ../server/src/memory/import.ts
15644
- import { existsSync as existsSync18, writeFileSync as writeFileSync13 } from "node:fs";
15645
- import { join as join21 } from "node:path";
16162
+ import { existsSync as existsSync19, writeFileSync as writeFileSync14 } from "node:fs";
16163
+ import { join as join22 } from "node:path";
15646
16164
  var MARKER = ".imported-notes";
15647
16165
  function importFlatNotes(memory, tree2) {
15648
16166
  tree2.ensure();
15649
- const marker = join21(tree2.root, MARKER);
15650
- if (existsSync18(marker)) return 0;
16167
+ const marker = join22(tree2.root, MARKER);
16168
+ if (existsSync19(marker)) return 0;
15651
16169
  let n2 = 0;
15652
16170
  for (const m of [...memory.list()].reverse()) {
15653
16171
  const name = inboxName(m.text, (x) => tree2.has(`inbox/${x}.md`));
15654
16172
  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" } : {} });
15655
16173
  if (r.ok) n2++;
15656
16174
  }
15657
- writeFileSync13(marker, (/* @__PURE__ */ new Date()).toISOString());
16175
+ writeFileSync14(marker, (/* @__PURE__ */ new Date()).toISOString());
15658
16176
  return n2;
15659
16177
  }
15660
16178
 
15661
16179
  // ../server/src/memory/keeper.ts
15662
- import { existsSync as existsSync19, readFileSync as readFileSync12, writeFileSync as writeFileSync14 } from "node:fs";
15663
- import { join as join22 } from "node:path";
16180
+ import { existsSync as existsSync20, readFileSync as readFileSync13, writeFileSync as writeFileSync15 } from "node:fs";
16181
+ import { join as join23 } from "node:path";
15664
16182
  import { z as z11 } from "zod";
15665
16183
  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.
15666
16184
 
@@ -15728,12 +16246,12 @@ var MemoryKeeper = class {
15728
16246
  this.d.after?.();
15729
16247
  }
15730
16248
  cursorPath() {
15731
- return join22(this.d.tree.root, CURSOR_FILE);
16249
+ return join23(this.d.tree.root, CURSOR_FILE);
15732
16250
  }
15733
16251
  readCursor() {
15734
16252
  try {
15735
- if (!existsSync19(this.cursorPath())) return -1;
15736
- const n2 = Number(JSON.parse(readFileSync12(this.cursorPath(), "utf8")).lastId);
16253
+ if (!existsSync20(this.cursorPath())) return -1;
16254
+ const n2 = Number(JSON.parse(readFileSync13(this.cursorPath(), "utf8")).lastId);
15737
16255
  return Number.isInteger(n2) && n2 >= 0 ? n2 : -1;
15738
16256
  } catch {
15739
16257
  return -1;
@@ -15741,7 +16259,7 @@ var MemoryKeeper = class {
15741
16259
  }
15742
16260
  writeCursor(id2) {
15743
16261
  this.d.tree.ensure();
15744
- writeFileSync14(this.cursorPath(), JSON.stringify({ lastId: id2 }));
16262
+ writeFileSync15(this.cursorPath(), JSON.stringify({ lastId: id2 }));
15745
16263
  }
15746
16264
  window(after) {
15747
16265
  const max = this.d.db.prepare("select max(id) m from messages").get().m ?? 0;
@@ -16026,7 +16544,7 @@ ${n2.body.trim().slice(0, NOTE_CHARS)}`).join("\n")}`,
16026
16544
  };
16027
16545
 
16028
16546
  // ../server/src/proactive/beat.ts
16029
- import { existsSync as existsSync20, readFileSync as readFileSync13, writeFileSync as writeFileSync15 } from "node:fs";
16547
+ import { existsSync as existsSync21, readFileSync as readFileSync14, writeFileSync as writeFileSync16 } from "node:fs";
16030
16548
  var LEVEL2 = { off: 0, low: 1, medium: 2, high: 3 };
16031
16549
  var MAX_SAY = 400;
16032
16550
  var OVERDUE_AFTER_MS = 2 * 36e5;
@@ -16069,8 +16587,8 @@ var ProactiveBeat = class {
16069
16587
  }
16070
16588
  load(day2) {
16071
16589
  try {
16072
- if (existsSync20(this.d.statePath)) {
16073
- const s = JSON.parse(readFileSync13(this.d.statePath, "utf8"));
16590
+ if (existsSync21(this.d.statePath)) {
16591
+ const s = JSON.parse(readFileSync14(this.d.statePath, "utf8"));
16074
16592
  if (s.day === day2) return { day: day2, sent: s.sent ?? 0, lastAt: s.lastAt ?? 0, fired: s.fired ?? {}, said: s.said ?? [] };
16075
16593
  const week = this.now() - 7 * 864e5;
16076
16594
  return { day: day2, sent: 0, lastAt: s.lastAt ?? 0, fired: Object.fromEntries(Object.entries(s.fired ?? {}).filter(([, t]) => t > week)), said: [] };
@@ -16081,7 +16599,7 @@ var ProactiveBeat = class {
16081
16599
  }
16082
16600
  save(s) {
16083
16601
  try {
16084
- writeFileSync15(this.d.statePath, JSON.stringify(s));
16602
+ writeFileSync16(this.d.statePath, JSON.stringify(s));
16085
16603
  } catch {
16086
16604
  }
16087
16605
  }
@@ -16225,12 +16743,12 @@ ${recent}` : "",
16225
16743
  };
16226
16744
 
16227
16745
  // ../server/src/defaultPlugins.ts
16228
- import { existsSync as existsSync21, readFileSync as readFileSync14, writeFileSync as writeFileSync16 } from "node:fs";
16229
- import { join as join23 } from "node:path";
16746
+ import { existsSync as existsSync22, readFileSync as readFileSync15, writeFileSync as writeFileSync17 } from "node:fs";
16747
+ import { join as join24 } from "node:path";
16230
16748
  var MARKER2 = "default-plugins.json";
16231
16749
  function offeredBefore(dir) {
16232
16750
  try {
16233
- const raw = JSON.parse(readFileSync14(join23(dir, MARKER2), "utf8"));
16751
+ const raw = JSON.parse(readFileSync15(join24(dir, MARKER2), "utf8"));
16234
16752
  return Array.isArray(raw.offered) ? raw.offered.filter((x) => typeof x === "string") : [];
16235
16753
  } catch {
16236
16754
  return [];
@@ -16248,16 +16766,16 @@ function installDefaults(plugins, catalogDir, dataDir, ids) {
16248
16766
  if (!entry || entry.error) continue;
16249
16767
  offered.add(id2);
16250
16768
  changed = true;
16251
- if (!have.has(id2) && plugins.install(join23(catalogDir, id2)).ok) done.push(id2);
16769
+ if (!have.has(id2) && plugins.install(join24(catalogDir, id2)).ok) done.push(id2);
16252
16770
  }
16253
- if (changed && existsSync21(dataDir)) writeFileSync16(join23(dataDir, MARKER2), JSON.stringify({ offered: [...offered].sort() }));
16771
+ if (changed && existsSync22(dataDir)) writeFileSync17(join24(dataDir, MARKER2), JSON.stringify({ offered: [...offered].sort() }));
16254
16772
  return done;
16255
16773
  }
16256
16774
 
16257
16775
  // ../server/src/marketplace.ts
16258
- import { randomBytes as randomBytes10 } from "node:crypto";
16259
- import { mkdirSync as mkdirSync13, readFileSync as readFileSync15, writeFileSync as writeFileSync17 } from "node:fs";
16260
- import { join as join24 } from "node:path";
16776
+ import { randomBytes as randomBytes11 } from "node:crypto";
16777
+ import { mkdirSync as mkdirSync14, readFileSync as readFileSync16, writeFileSync as writeFileSync18 } from "node:fs";
16778
+ import { join as join25 } from "node:path";
16261
16779
 
16262
16780
  // ../server/src/claudePlugin.ts
16263
16781
  var MAX_SKILLS = 10;
@@ -16404,7 +16922,7 @@ var MAX_LISTED_FILES = 300;
16404
16922
  var MAX_DOCS = 6;
16405
16923
  var MAX_PLUGINS_READ = 3;
16406
16924
  var clean4 = (p) => p.replace(/^\.\//, "").replace(/^\.$/, "").replace(/^\/+|\/+$/g, "");
16407
- var join25 = (base, rest) => base ? `${base}/${rest}` : rest;
16925
+ var join26 = (base, rest) => base ? `${base}/${rest}` : rest;
16408
16926
  var cut2 = (text5) => text5.length > MAX_DOC_CHARS ? `${text5.slice(0, MAX_DOC_CHARS)}
16409
16927
  \u2026(cut here; ask for the rest with plugins.read if you need it)` : text5;
16410
16928
  var Market = class {
@@ -16432,7 +16950,7 @@ var Market = class {
16432
16950
  const { commit, files } = await reader.tree(repo);
16433
16951
  const paths = new Set(files.map((f) => f.path));
16434
16952
  const base = clean4(repo.folder ?? "");
16435
- const at = (rest) => join25(base, rest);
16953
+ const at = (rest) => join26(base, rest);
16436
16954
  const texts = /* @__PURE__ */ new Map();
16437
16955
  const read = async (path3) => {
16438
16956
  try {
@@ -16449,8 +16967,8 @@ var Market = class {
16449
16967
  if (paths.has(at(".claude-plugin/marketplace.json"))) {
16450
16968
  const m = readMarketplace(await reader.file(repo, at(".claude-plugin/marketplace.json")) ?? "");
16451
16969
  marketplace = m.name;
16452
- folders = m.plugins.map((p) => join25(base, clean4(p.source)));
16453
- for (const p of m.plugins) entries.set(join25(base, clean4(p.source)), p);
16970
+ folders = m.plugins.map((p) => join26(base, clean4(p.source)));
16971
+ for (const p of m.plugins) entries.set(join26(base, clean4(p.source)), p);
16454
16972
  } else if (base) folders = [base];
16455
16973
  else {
16456
16974
  const nested = [...paths].filter((p) => /(^|\/)\.claude-plugin\/plugin\.json$/.test(p)).map((p) => p.replace(/\/?\.claude-plugin\/plugin\.json$/, ""));
@@ -16497,7 +17015,7 @@ var Market = class {
16497
17015
  const t = await read(p);
16498
17016
  if (t) docs.push({ path: p, text: cut2(t) });
16499
17017
  }
16500
- const id2 = (this.d.newId ?? (() => randomBytes10(6).toString("hex")))();
17018
+ const id2 = (this.d.newId ?? (() => randomBytes11(6).toString("hex")))();
16501
17019
  this.sweep();
16502
17020
  this.staged.set(id2, { repo, reader, commit, paths, cache: texts, results, expires: this.now() + KEEP_MS });
16503
17021
  this.d.audit.log("agent", "plugins.fetch", { repo: `${repo.owner}/${repo.repo}`, commit, files: paths.size, plugins: results.length });
@@ -16571,7 +17089,7 @@ var Market = class {
16571
17089
  const ids = [];
16572
17090
  const skills = [];
16573
17091
  for (const r of chosen) {
16574
- const done = authorPlugin(this.d.plugins, join24(this.d.dir, "drafts"), { ...r.spec, source });
17092
+ const done = authorPlugin(this.d.plugins, join25(this.d.dir, "drafts"), { ...r.spec, source });
16575
17093
  if (!done.ok) throw new Error(`"${r.spec.id}" was not installed: ${done.error}`);
16576
17094
  ids.push(r.spec.id);
16577
17095
  skills.push(...(r.spec.skills ?? []).map((k) => k.name));
@@ -16591,19 +17109,19 @@ var Market = class {
16591
17109
  }
16592
17110
  // ---- marketplaces ----
16593
17111
  file() {
16594
- return join24(this.d.dir, "marketplaces.json");
17112
+ return join25(this.d.dir, "marketplaces.json");
16595
17113
  }
16596
17114
  marketplaces() {
16597
17115
  try {
16598
- const list2 = JSON.parse(readFileSync15(this.file(), "utf8"));
17116
+ const list2 = JSON.parse(readFileSync16(this.file(), "utf8"));
16599
17117
  return Array.isArray(list2) ? list2 : [];
16600
17118
  } catch {
16601
17119
  return [];
16602
17120
  }
16603
17121
  }
16604
17122
  save(list2) {
16605
- mkdirSync13(this.d.dir, { recursive: true });
16606
- writeFileSync17(this.file(), JSON.stringify(list2, null, 2));
17123
+ mkdirSync14(this.d.dir, { recursive: true });
17124
+ writeFileSync18(this.file(), JSON.stringify(list2, null, 2));
16607
17125
  }
16608
17126
  async addMarketplace(link) {
16609
17127
  const repo = parseRepoLink(link);
@@ -16639,14 +17157,14 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
16639
17157
 
16640
17158
  // ../server/src/office/office.ts
16641
17159
  import { randomUUID as randomUUID6 } from "node:crypto";
16642
- import { existsSync as existsSync22, mkdirSync as mkdirSync14, statSync as statSync4, writeFileSync as writeFileSync18 } from "node:fs";
16643
- import { join as join26 } from "node:path";
17160
+ import { existsSync as existsSync23, mkdirSync as mkdirSync15, statSync as statSync4, writeFileSync as writeFileSync19 } from "node:fs";
17161
+ import { join as join27 } from "node:path";
16644
17162
 
16645
17163
  // ../server/src/provider/claude-code/bridge.ts
16646
17164
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
16647
17165
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
16648
17166
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
16649
- import { randomBytes as randomBytes11, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
17167
+ import { randomBytes as randomBytes12, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
16650
17168
  import { createServer } from "node:http";
16651
17169
  var encodeToolName = (name) => name.replaceAll(".", "__");
16652
17170
  var MAX_BODY_BYTES = 8 * 1024 * 1024;
@@ -16655,7 +17173,7 @@ var ToolBridge = class {
16655
17173
  this.onCall = onCall;
16656
17174
  }
16657
17175
  onCall;
16658
- token = randomBytes11(24).toString("hex");
17176
+ token = randomBytes12(24).toString("hex");
16659
17177
  tools = [];
16660
17178
  http = null;
16661
17179
  port = 0;
@@ -16775,7 +17293,7 @@ var SUMMARY_CHARS = 80;
16775
17293
  var FILE_TOOLS = /* @__PURE__ */ new Set(["Write", "Edit", "MultiEdit", "Read", "NotebookEdit"]);
16776
17294
  var obj = (v) => v && typeof v === "object" ? v : {};
16777
17295
  var clip8 = (s, n2 = MAX_TEXT3) => s.length > n2 ? s.slice(0, n2) : s;
16778
- var num4 = (v) => typeof v === "number" && Number.isFinite(v) ? v : 0;
17296
+ var num5 = (v) => typeof v === "number" && Number.isFinite(v) ? v : 0;
16779
17297
  function summarizeToolCall(name, input) {
16780
17298
  const i = obj(input);
16781
17299
  let s = name;
@@ -16805,7 +17323,7 @@ function parseWorkerEvent(ev) {
16805
17323
  return [];
16806
17324
  });
16807
17325
  const u = obj(e.message?.usage);
16808
- const held = num4(u.input_tokens) + num4(u.cache_read_input_tokens) + num4(u.cache_creation_input_tokens);
17326
+ const held = num5(u.input_tokens) + num5(u.cache_read_input_tokens) + num5(u.cache_creation_input_tokens);
16809
17327
  return held > 0 ? [...blocks, { kind: "context", tokens: held }] : blocks;
16810
17328
  }
16811
17329
  case "user":
@@ -16827,10 +17345,10 @@ function parseWorkerEvent(ev) {
16827
17345
  kind: "result",
16828
17346
  ok: e.is_error !== true && e.subtype === "success",
16829
17347
  text: clip8(typeof e.result === "string" ? e.result : ""),
16830
- turns: num4(e.num_turns),
16831
- durationMs: num4(e.duration_ms),
16832
- input: num4(u.input_tokens) + num4(u.cache_creation_input_tokens),
16833
- output: num4(u.output_tokens),
17348
+ turns: num5(e.num_turns),
17349
+ durationMs: num5(e.duration_ms),
17350
+ input: num5(u.input_tokens) + num5(u.cache_creation_input_tokens),
17351
+ output: num5(u.output_tokens),
16834
17352
  denials: (Array.isArray(e.permission_denials) ? e.permission_denials : []).map((d) => String(obj(d).tool_name ?? "")).filter(Boolean),
16835
17353
  sessionId: typeof e.session_id === "string" ? e.session_id : ""
16836
17354
  }
@@ -17421,16 +17939,16 @@ var Office = class {
17421
17939
  const cfg = this.d.config();
17422
17940
  await run2.bridge.start();
17423
17941
  if (run2.concluded) return;
17424
- const dir = join26(this.d.dataDir, "office");
17425
- mkdirSync14(dir, { recursive: true });
17426
- const mcp = join26(dir, `${worker.id}.mcp.json`);
17942
+ const dir = join27(this.d.dataDir, "office");
17943
+ mkdirSync15(dir, { recursive: true });
17944
+ const mcp = join27(dir, `${worker.id}.mcp.json`);
17427
17945
  const live = this.checkGrantsQuiet(worker);
17428
17946
  const servers = { office: { type: "http", url: run2.bridge.url, headers: { Authorization: `Bearer ${run2.bridge.token}` } } };
17429
17947
  for (const c of this.d.capabilities?.connectors() ?? []) if (live.mcp.includes(c.id)) servers[c.id] = mcpEntry(c);
17430
- writeFileSync18(mcp, JSON.stringify({ mcpServers: servers }));
17948
+ writeFileSync19(mcp, JSON.stringify({ mcpServers: servers }));
17431
17949
  let pluginDir;
17432
17950
  if (live.skills.length > 0) {
17433
- pluginDir = join26(dir, `${worker.id}.skills`);
17951
+ pluginDir = join27(dir, `${worker.id}.skills`);
17434
17952
  buildSkillPlugin(pluginDir, live.skills);
17435
17953
  }
17436
17954
  const args = buildWorkerArgs({
@@ -17523,7 +18041,7 @@ var Office = class {
17523
18041
  `Ticket #${ticket.id}: ${ticket.title}`,
17524
18042
  ticket.description,
17525
18043
  note ? `The owner sent this back with a note: ${note}` : "",
17526
- fresh && existsSync22(join26(project.folder, NOTES_FILE)) ? `This is a clean session. Before you start, read ${NOTES_FILE} in the project folder: it says where the work stands.` : "",
18044
+ fresh && existsSync23(join27(project.folder, NOTES_FILE)) ? `This is a clean session. Before you start, read ${NOTES_FILE} in the project folder: it says where the work stands.` : "",
17527
18045
  `Project: ${project.name}${project.goal ? `
17528
18046
  Goal: ${project.goal}` : ""}`,
17529
18047
  `Work only inside ${project.folder}. When you are done, reply with a short report of what you did.`
@@ -17797,7 +18315,7 @@ ${ticket.description}` : "", goal: project.goal, action: describeAction(tool, in
17797
18315
  };
17798
18316
 
17799
18317
  // ../server/src/office/store.ts
17800
- import { randomBytes as randomBytes12 } from "node:crypto";
18318
+ import { randomBytes as randomBytes13 } from "node:crypto";
17801
18319
  var MAX_EVENT_CHARS = 200;
17802
18320
  var MAX_EVENTS_PER_WORKER = 500;
17803
18321
  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 });
@@ -17822,7 +18340,7 @@ var OfficeStore = class {
17822
18340
  db;
17823
18341
  now;
17824
18342
  createWorker(w) {
17825
- const id2 = randomBytes12(4).toString("hex");
18343
+ const id2 = randomBytes13(4).toString("hex");
17826
18344
  this.db.prepare("insert into office_workers (id, name, role_id, project_id, created_at, title, capabilities, instructions, model, permission, manager_id, skills, mcp) 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, JSON.stringify(w.skills ?? []), JSON.stringify(w.mcp ?? []));
17827
18345
  return this.getWorker(id2);
17828
18346
  }
@@ -17940,12 +18458,12 @@ var OfficeStore = class {
17940
18458
  };
17941
18459
 
17942
18460
  // ../server/src/app.ts
17943
- import { join as join32 } from "node:path";
18461
+ import { join as join33 } from "node:path";
17944
18462
 
17945
18463
  // ../server/src/attach/store.ts
17946
- import { randomBytes as randomBytes13 } from "node:crypto";
17947
- import { existsSync as existsSync23, mkdirSync as mkdirSync15, readFileSync as readFileSync16, readdirSync as readdirSync7, rmSync as rmSync11, statSync as statSync5, writeFileSync as writeFileSync19 } from "node:fs";
17948
- import { join as join27 } from "node:path";
18464
+ import { randomBytes as randomBytes14 } from "node:crypto";
18465
+ import { existsSync as existsSync24, mkdirSync as mkdirSync16, readFileSync as readFileSync17, readdirSync as readdirSync7, rmSync as rmSync11, statSync as statSync5, writeFileSync as writeFileSync20 } from "node:fs";
18466
+ import { join as join28 } from "node:path";
17949
18467
 
17950
18468
  // ../server/src/attach/zip.ts
17951
18469
  import { inflateRawSync } from "node:zlib";
@@ -18265,7 +18783,7 @@ var AttachmentStore = class {
18265
18783
  this.limits = limits;
18266
18784
  this.now = now;
18267
18785
  this.totalBytes = totalBytes;
18268
- mkdirSync15(dir, { recursive: true });
18786
+ mkdirSync16(dir, { recursive: true });
18269
18787
  this.prune();
18270
18788
  }
18271
18789
  dir;
@@ -18279,19 +18797,19 @@ var AttachmentStore = class {
18279
18797
  if (bytes2.length > Math.min(lim.maxBytes, ATTACHMENT_CEILING_BYTES)) return { ok: false, status: 413, error: `That file is ${megabytes(bytes2.length)}; the limit is ${megabytes(Math.min(lim.maxBytes, ATTACHMENT_CEILING_BYTES))} (Settings, Memory).` };
18280
18798
  this.prune();
18281
18799
  this.makeRoom(bytes2.length);
18282
- const id2 = randomBytes13(8).toString("hex");
18283
- const d = join27(this.dir, id2);
18284
- mkdirSync15(d, { recursive: true });
18800
+ const id2 = randomBytes14(8).toString("hex");
18801
+ const d = join28(this.dir, id2);
18802
+ mkdirSync16(d, { recursive: true });
18285
18803
  const meta = { id: id2, name: cleanName(name), size: bytes2.length, at: this.now() };
18286
- writeFileSync19(join27(d, "data.bin"), bytes2);
18287
- writeFileSync19(join27(d, "meta.json"), JSON.stringify(meta));
18804
+ writeFileSync20(join28(d, "data.bin"), bytes2);
18805
+ writeFileSync20(join28(d, "meta.json"), JSON.stringify(meta));
18288
18806
  return { ok: true, meta };
18289
18807
  }
18290
18808
  get(id2) {
18291
18809
  if (!ID4.test(id2)) return void 0;
18292
18810
  try {
18293
- const meta = JSON.parse(readFileSync16(join27(this.dir, id2, "meta.json"), "utf8"));
18294
- return { meta, bytes: () => readFileSync16(join27(this.dir, id2, "data.bin")) };
18811
+ const meta = JSON.parse(readFileSync17(join28(this.dir, id2, "meta.json"), "utf8"));
18812
+ return { meta, bytes: () => readFileSync17(join28(this.dir, id2, "data.bin")) };
18295
18813
  } catch {
18296
18814
  return void 0;
18297
18815
  }
@@ -18302,7 +18820,7 @@ var AttachmentStore = class {
18302
18820
  try {
18303
18821
  for (const n2 of readdirSync7(this.dir).filter((x) => ID4.test(x))) {
18304
18822
  try {
18305
- all.push(JSON.parse(readFileSync16(join27(this.dir, n2, "meta.json"), "utf8")));
18823
+ all.push(JSON.parse(readFileSync17(join28(this.dir, n2, "meta.json"), "utf8")));
18306
18824
  } catch {
18307
18825
  }
18308
18826
  }
@@ -18312,7 +18830,7 @@ var AttachmentStore = class {
18312
18830
  let used2 = all.reduce((n2, m) => n2 + m.size, 0);
18313
18831
  for (const m of all.sort((a, b) => a.at - b.at)) {
18314
18832
  if (used2 + extra <= this.totalBytes) break;
18315
- rmSync11(join27(this.dir, m.id), { recursive: true, force: true });
18833
+ rmSync11(join28(this.dir, m.id), { recursive: true, force: true });
18316
18834
  this.cache.delete(m.id);
18317
18835
  used2 -= m.size;
18318
18836
  }
@@ -18327,9 +18845,9 @@ var AttachmentStore = class {
18327
18845
  return;
18328
18846
  }
18329
18847
  for (const n2 of names) {
18330
- const d = join27(this.dir, n2);
18848
+ const d = join28(this.dir, n2);
18331
18849
  try {
18332
- const meta = existsSync23(join27(d, "meta.json")) ? JSON.parse(readFileSync16(join27(d, "meta.json"), "utf8")) : null;
18850
+ const meta = existsSync24(join28(d, "meta.json")) ? JSON.parse(readFileSync17(join28(d, "meta.json"), "utf8")) : null;
18333
18851
  const at = meta?.at ?? statSync5(d).mtimeMs;
18334
18852
  if (at < (meta ? cutoff : this.now() - 36e5)) {
18335
18853
  rmSync11(d, { recursive: true, force: true });
@@ -18372,8 +18890,8 @@ ${chunk}
18372
18890
 
18373
18891
  // ../server/src/db.ts
18374
18892
  import Database from "better-sqlite3";
18375
- import { mkdirSync as mkdirSync16 } from "node:fs";
18376
- import { join as join28 } from "node:path";
18893
+ import { mkdirSync as mkdirSync17 } from "node:fs";
18894
+ import { join as join29 } from "node:path";
18377
18895
 
18378
18896
  // ../server/src/migrations.ts
18379
18897
  var MIGRATIONS = [
@@ -18699,8 +19217,8 @@ alter table office_workers add column mcp text not null default '[]';`
18699
19217
 
18700
19218
  // ../server/src/db.ts
18701
19219
  function openDb(dataDir) {
18702
- mkdirSync16(dataDir, { recursive: true });
18703
- const db = new Database(join28(dataDir, "friend.db"));
19220
+ mkdirSync17(dataDir, { recursive: true });
19221
+ const db = new Database(join29(dataDir, "friend.db"));
18704
19222
  db.pragma("journal_mode = WAL");
18705
19223
  db.pragma("foreign_keys = ON");
18706
19224
  db.exec("create table if not exists schema_version (id integer primary key, applied_at integer not null)");
@@ -19331,7 +19849,7 @@ var DeviceHub = class {
19331
19849
  import fastifyCookie from "@fastify/cookie";
19332
19850
 
19333
19851
  // ../server/src/auditApi.ts
19334
- import { randomBytes as randomBytes14 } from "node:crypto";
19852
+ import { randomBytes as randomBytes15 } from "node:crypto";
19335
19853
  import { z as z13 } from "zod";
19336
19854
 
19337
19855
  // ../server/src/auditExport.ts
@@ -19380,7 +19898,7 @@ var UnlockStore = class {
19380
19898
  issue(minutes3) {
19381
19899
  const t = this.now();
19382
19900
  for (const [k, v] of this.tokens) if (v < t) this.tokens.delete(k);
19383
- const token = randomBytes14(32).toString("hex");
19901
+ const token = randomBytes15(32).toString("hex");
19384
19902
  const expiresAt = t + minutes3 * 6e4;
19385
19903
  this.tokens.set(token, expiresAt);
19386
19904
  return { token, expiresAt };
@@ -19525,7 +20043,7 @@ function registerAuditRoutes(d) {
19525
20043
  // ../server/src/gateway.ts
19526
20044
  import fastifyStatic from "@fastify/static";
19527
20045
  import Fastify from "fastify";
19528
- import { createReadStream as createReadStream2, existsSync as existsSync24, promises as fsp2 } from "node:fs";
20046
+ import { createReadStream as createReadStream2, existsSync as existsSync25, promises as fsp2 } from "node:fs";
19529
20047
  import { isIP as isIP3 } from "node:net";
19530
20048
  import { Readable } from "node:stream";
19531
20049
  import { WebSocket as WebSocket2, WebSocketServer } from "ws";
@@ -20499,6 +21017,84 @@ function createGateway(deps) {
20499
21017
  audit.log("owner", "connector.failed", { what, message: e.message });
20500
21018
  return reply.code(500).send({ error: "That did not work. Try again." });
20501
21019
  };
21020
+ const oauthWindow = new SlidingWindow(20, 6e4);
21021
+ const oauthPage = (reply, ok2) => reply.code(ok2 ? 200 : 400).header("cache-control", "no-store").header("referrer-policy", "no-referrer").type("text/html; charset=utf-8").send(`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Friend</title><body style="font-family:system-ui;margin:3rem auto;max-width:28rem;padding:0 1rem"><h1>${ok2 ? "Connected" : "That did not work"}</h1><p>${ok2 ? "You can close this page and go back to Friend." : "Open Friend and press Connect to try again. The link may have been used or may be too old."}</p>`);
21022
+ app.get("/api/oauth/start/:ticket", async (req, reply) => {
21023
+ if (!deps.oauth) return reply.code(404).send();
21024
+ if (!oauthWindow.allow(`os:${req.ip}`)) return reply.code(429).header("retry-after", 30).send();
21025
+ const url = typeof req.params.ticket === "string" && req.params.ticket.length <= 100 ? deps.oauth.open(req.params.ticket) : null;
21026
+ if (!url) return oauthPage(reply, false);
21027
+ return reply.header("cache-control", "no-store").header("referrer-policy", "no-referrer").redirect(url);
21028
+ });
21029
+ app.get("/api/oauth/callback", async (req, reply) => {
21030
+ if (!deps.oauth) return reply.code(404).send();
21031
+ if (!oauthWindow.allow(`oc:${req.ip}`)) return reply.code(429).header("retry-after", 30).send();
21032
+ const params = {};
21033
+ for (const [k, v] of Object.entries(req.query ?? {})) if (typeof v === "string" && k.length <= 40 && v.length <= 2e3) params[k] = v;
21034
+ const ok2 = await deps.oauth.callback(params).catch(() => false);
21035
+ return oauthPage(reply, ok2);
21036
+ });
21037
+ const oauthGuard = async (req, reply) => {
21038
+ const token = req.cookies[COOKIE_NAME];
21039
+ const session = token ? auth.resolveSession(token) : null;
21040
+ if (!session) return reply.code(401).send({ error: "Unauthorized" });
21041
+ if (!connectorWindow.allow(String(session.id))) return reply.code(429).header("retry-after", 10).send({ error: "Too many requests" });
21042
+ if (!deps.oauth) return reply.code(503).send({ error: "Signing in with a link is not available" });
21043
+ };
21044
+ const oauthError = (reply, e) => {
21045
+ if (e instanceof HttpError) return reply.code(e.status).send({ error: e.message });
21046
+ audit.log("owner", "oauth.error", { message: e.message.slice(0, 200) });
21047
+ return reply.code(500).send({ error: "That did not work. Try again." });
21048
+ };
21049
+ const toPhoneBody = z14.object({ toPhone: z14.boolean().optional() });
21050
+ const idParam = /^[a-z0-9-]{1,32}$/;
21051
+ app.get("/api/oauth", { onRequest: oauthGuard }, async () => deps.oauth.state());
21052
+ app.post("/api/oauth/services/:id/connect", { onRequest: oauthGuard }, async (req, reply) => {
21053
+ const body = toPhoneBody.safeParse(req.body ?? {});
21054
+ if (!body.success || !idParam.test(req.params.id)) return reply.code(400).send({ error: "That is not a valid request" });
21055
+ try {
21056
+ return await deps.oauth.connectService(req.params.id, body.data.toPhone === true);
21057
+ } catch (e) {
21058
+ return oauthError(reply, e);
21059
+ }
21060
+ });
21061
+ app.post("/api/oauth/services/:id/disconnect", { onRequest: oauthGuard }, async (req, reply) => {
21062
+ if (!idParam.test(req.params.id)) return reply.code(400).send({ error: "That is not a valid request" });
21063
+ try {
21064
+ await deps.oauth.disconnectService(req.params.id);
21065
+ return { ok: true };
21066
+ } catch (e) {
21067
+ return oauthError(reply, e);
21068
+ }
21069
+ });
21070
+ app.post("/api/oauth/connectors/:id/connect", { onRequest: oauthGuard }, async (req, reply) => {
21071
+ const body = toPhoneBody.safeParse(req.body ?? {});
21072
+ if (!body.success || !idParam.test(req.params.id)) return reply.code(400).send({ error: "That is not a valid request" });
21073
+ try {
21074
+ return await deps.oauth.connectConnector(req.params.id, body.data.toPhone === true);
21075
+ } catch (e) {
21076
+ return oauthError(reply, e);
21077
+ }
21078
+ });
21079
+ app.post("/api/oauth/connectors/:id/disconnect", { onRequest: oauthGuard }, async (req, reply) => {
21080
+ if (!idParam.test(req.params.id)) return reply.code(400).send({ error: "That is not a valid request" });
21081
+ try {
21082
+ await deps.oauth.disconnectConnector(req.params.id);
21083
+ return { ok: true };
21084
+ } catch (e) {
21085
+ return oauthError(reply, e);
21086
+ }
21087
+ });
21088
+ app.put("/api/oauth/services/:id/client", { onRequest: oauthGuard }, async (req, reply) => {
21089
+ const body = z14.object({ clientId: z14.string().min(1).max(300), clientSecret: z14.string().max(300).optional(), pin: z14.string().min(1).max(32) }).safeParse(req.body);
21090
+ if (!body.success || !idParam.test(req.params.id)) return reply.code(400).send({ error: "Enter the client ID and your PIN" });
21091
+ try {
21092
+ await deps.oauth.setClient(req.params.id, body.data.clientId, body.data.clientSecret, body.data.pin, req.ip);
21093
+ return { ok: true };
21094
+ } catch (e) {
21095
+ return oauthError(reply, e);
21096
+ }
21097
+ });
20502
21098
  app.get("/api/connectors", { onRequest: connectorGuard }, async () => deps.connectors.list());
20503
21099
  app.post("/api/connectors", { onRequest: connectorGuard }, async (req, reply) => {
20504
21100
  const body = z14.object({ pin: z14.string().min(1).max(32), connector: z14.record(z14.string(), z14.unknown()) }).safeParse(req.body);
@@ -20738,7 +21334,7 @@ function createGateway(deps) {
20738
21334
  deps.onLock?.();
20739
21335
  return { ok: true };
20740
21336
  });
20741
- if (deps.webDir && existsSync24(deps.webDir)) {
21337
+ if (deps.webDir && existsSync25(deps.webDir)) {
20742
21338
  app.register(fastifyStatic, { root: deps.webDir });
20743
21339
  app.setNotFoundHandler((req, reply) => {
20744
21340
  if (req.method === "GET" && !req.url.startsWith("/api")) return reply.sendFile("index.html");
@@ -20893,9 +21489,9 @@ Connection: close\r
20893
21489
 
20894
21490
  // ../server/src/browser/hub.ts
20895
21491
  import { spawn as spawn8, spawnSync } from "node:child_process";
20896
- import { mkdirSync as mkdirSync17, mkdtempSync as mkdtempSync3, readdirSync as readdirSync8, readFileSync as readFileSync17, rmSync as rmSync12, statSync as statSync7 } from "node:fs";
21492
+ import { mkdirSync as mkdirSync18, mkdtempSync as mkdtempSync3, readdirSync as readdirSync8, readFileSync as readFileSync18, rmSync as rmSync12, statSync as statSync7 } from "node:fs";
20897
21493
  import { tmpdir as tmpdir3 } from "node:os";
20898
- import { join as join29 } from "node:path";
21494
+ import { join as join30 } from "node:path";
20899
21495
 
20900
21496
  // ../server/src/browser/cdp.ts
20901
21497
  import { WebSocket as WebSocket3 } from "ws";
@@ -20965,11 +21561,11 @@ var Cdp = class _Cdp {
20965
21561
  };
20966
21562
 
20967
21563
  // ../server/src/browser/chrome.ts
20968
- import { existsSync as existsSync25, statSync as statSync6 } from "node:fs";
21564
+ import { existsSync as existsSync26, statSync as statSync6 } from "node:fs";
20969
21565
  import { posix as posix3, win32 as win323 } from "node:path";
20970
21566
  var fileThere = (p) => {
20971
21567
  try {
20972
- return existsSync25(p) && statSync6(p).isFile();
21568
+ return existsSync26(p) && statSync6(p).isFile();
20973
21569
  } catch {
20974
21570
  return false;
20975
21571
  }
@@ -20980,15 +21576,15 @@ function findChrome(override = "", w = {}) {
20980
21576
  const platform = w.platform ?? process.platform;
20981
21577
  const env = w.env ?? process.env;
20982
21578
  const isFile = w.isFile ?? fileThere;
20983
- const join42 = platform === "win32" ? win323.join : posix3.join;
21579
+ const join43 = platform === "win32" ? win323.join : posix3.join;
20984
21580
  if (override.trim()) return isFile(override.trim()) ? override.trim() : null;
20985
21581
  if (platform === "win32") {
20986
21582
  const roots = [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].filter((r) => !!r);
20987
- 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(join42(r, rel))) return join42(r, rel);
21583
+ 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(join43(r, rel))) return join43(r, rel);
20988
21584
  return null;
20989
21585
  }
20990
21586
  if (platform === "darwin") return MAC_PATHS.find(isFile) ?? null;
20991
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join42(dir, name))) return join42(dir, name);
21587
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) for (const name of LINUX_NAMES) if (isFile(join43(dir, name))) return join43(dir, name);
20992
21588
  return null;
20993
21589
  }
20994
21590
 
@@ -21015,7 +21611,7 @@ var BrowserHub = class {
21015
21611
  try {
21016
21612
  for (const name of readdirSync8(root)) {
21017
21613
  if (!/^friend-browser-/.test(name)) continue;
21018
- const dir = join29(root, name);
21614
+ const dir = join30(root, name);
21019
21615
  if (Date.now() - statSync7(dir).mtimeMs > 36e5) rmSync12(dir, { recursive: true, force: true });
21020
21616
  }
21021
21617
  } catch {
@@ -21079,8 +21675,8 @@ A picture of the page "${r.value.title || r.value.href}" (${r.value.href}). Text
21079
21675
  let cdp = null;
21080
21676
  try {
21081
21677
  const root = this.o.tmpRoot ?? tmpdir3();
21082
- mkdirSync17(root, { recursive: true });
21083
- profile = mkdtempSync3(join29(root, "friend-browser-"));
21678
+ mkdirSync18(root, { recursive: true });
21679
+ profile = mkdtempSync3(join30(root, "friend-browser-"));
21084
21680
  child = spawn8(
21085
21681
  chrome,
21086
21682
  [
@@ -21194,7 +21790,7 @@ async function endpoint(profile, signal) {
21194
21790
  for (; ; ) {
21195
21791
  signal.throwIfAborted();
21196
21792
  try {
21197
- const [port, path3] = readFileSync17(join29(profile, "DevToolsActivePort"), "utf8").split("\n");
21793
+ const [port, path3] = readFileSync18(join30(profile, "DevToolsActivePort"), "utf8").split("\n");
21198
21794
  if (port && path3) return `ws://127.0.0.1:${port.trim()}${path3.trim()}`;
21199
21795
  } catch {
21200
21796
  }
@@ -21436,8 +22032,8 @@ function startStatsFeed(opts) {
21436
22032
 
21437
22033
  // ../server/src/provider/claude-code/provider.ts
21438
22034
  import { createHash as createHash13 } from "node:crypto";
21439
- import { chmodSync as chmodSync8, existsSync as existsSync26, mkdirSync as mkdirSync18, readdirSync as readdirSync9, readFileSync as readFileSync18, rmSync as rmSync13, writeFileSync as writeFileSync20 } from "node:fs";
21440
- import { join as join30 } from "node:path";
22035
+ import { chmodSync as chmodSync9, existsSync as existsSync27, mkdirSync as mkdirSync19, readdirSync as readdirSync9, readFileSync as readFileSync19, rmSync as rmSync13, writeFileSync as writeFileSync21 } from "node:fs";
22036
+ import { join as join31 } from "node:path";
21441
22037
 
21442
22038
  // ../server/src/provider/claude-code/limits.ts
21443
22039
  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;
@@ -21535,7 +22131,7 @@ var NOT_SIGNED_IN = /not logged in|please run \/login|invalid api key|authentica
21535
22131
  var ClaudeCodeProvider = class {
21536
22132
  constructor(opts) {
21537
22133
  this.opts = opts;
21538
- this.home = join30(opts.dataDir, "claude");
22134
+ this.home = join31(opts.dataDir, "claude");
21539
22135
  this.now = opts.now ?? Date.now;
21540
22136
  this.bridge = new ToolBridge((call) => this.owner.inbox.push({ kind: "call", call }));
21541
22137
  }
@@ -21599,10 +22195,10 @@ var ClaudeCodeProvider = class {
21599
22195
  conv.hasContext = false;
21600
22196
  conv.systemKey = "";
21601
22197
  this.forgetSession(conv);
21602
- mkdirSync18(this.home, { recursive: true });
22198
+ mkdirSync19(this.home, { recursive: true });
21603
22199
  this.fresh = { seed: seed?.trim() || null };
21604
22200
  try {
21605
- writeFileSync20(this.freshFile(), JSON.stringify(this.fresh));
22201
+ writeFileSync21(this.freshFile(), JSON.stringify(this.fresh));
21606
22202
  } catch {
21607
22203
  }
21608
22204
  }
@@ -21761,7 +22357,7 @@ ${item.stderr}`;
21761
22357
  conv.proc = null;
21762
22358
  }
21763
22359
  conv.inbox.clear();
21764
- mkdirSync18(this.home, { recursive: true });
22360
+ mkdirSync19(this.home, { recursive: true });
21765
22361
  if (!conv.guest) {
21766
22362
  conv.sessionId ??= this.readSession();
21767
22363
  this.fresh = conv.sessionId ? null : this.readFresh();
@@ -21791,7 +22387,7 @@ ${item.stderr}`;
21791
22387
  "local",
21792
22388
  "--system-prompt-file",
21793
22389
  systemFile,
21794
- ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join30(this.home, "mcp.json"), "--allowedTools", [...web ? ["WebSearch"] : [], ...req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`)].join(","), ...resume ? ["--resume", resume] : []]
22390
+ ...conv.guest ? ["--no-session-persistence"] : ["--mcp-config", join31(this.home, "mcp.json"), "--allowedTools", [...web ? ["WebSearch"] : [], ...req.tools.map((t) => `mcp__friend__${encodeToolName(t.name)}`)].join(","), ...resume ? ["--resume", resume] : []]
21795
22391
  ];
21796
22392
  const proc = new ClaudeProc(
21797
22393
  {
@@ -21820,14 +22416,14 @@ ${item.stderr}`;
21820
22416
  if (!this.swept) {
21821
22417
  this.swept = true;
21822
22418
  try {
21823
- for (const f of readdirSync9(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync13(join30(this.home, f), { force: true });
22419
+ for (const f of readdirSync9(this.home)) if (/^system-\d+\.txt$/.test(f)) rmSync13(join31(this.home, f), { force: true });
21824
22420
  } catch {
21825
22421
  }
21826
22422
  }
21827
- const file = join30(this.home, `system-${++this.systemCount}.txt`);
21828
- writeFileSync20(file, text5);
22423
+ const file = join31(this.home, `system-${++this.systemCount}.txt`);
22424
+ writeFileSync21(file, text5);
21829
22425
  try {
21830
- chmodSync8(file, 384);
22426
+ chmodSync9(file, 384);
21831
22427
  } catch {
21832
22428
  }
21833
22429
  return file;
@@ -21841,20 +22437,20 @@ ${item.stderr}`;
21841
22437
  startBridge() {
21842
22438
  this.bridgeReady ??= (async () => {
21843
22439
  await this.bridge.start();
21844
- const file = join30(this.home, "mcp.json");
21845
- writeFileSync20(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
22440
+ const file = join31(this.home, "mcp.json");
22441
+ writeFileSync21(file, JSON.stringify({ mcpServers: { friend: { type: "http", url: this.bridge.url, headers: { Authorization: `Bearer ${this.bridge.token}` } } } }));
21846
22442
  try {
21847
- chmodSync8(file, 384);
22443
+ chmodSync9(file, 384);
21848
22444
  } catch {
21849
22445
  }
21850
22446
  })();
21851
22447
  return this.bridgeReady;
21852
22448
  }
21853
22449
  // ---- the session id, kept so a restart of Friend can pick the conversation up again ----
21854
- sessionFile = () => join30(this.home, "session-id");
22450
+ sessionFile = () => join31(this.home, "session-id");
21855
22451
  readSession() {
21856
22452
  try {
21857
- return existsSync26(this.sessionFile()) ? readFileSync18(this.sessionFile(), "utf8").trim() || null : null;
22453
+ return existsSync27(this.sessionFile()) ? readFileSync19(this.sessionFile(), "utf8").trim() || null : null;
21858
22454
  } catch {
21859
22455
  return null;
21860
22456
  }
@@ -21868,15 +22464,15 @@ ${item.stderr}`;
21868
22464
  } catch {
21869
22465
  }
21870
22466
  try {
21871
- writeFileSync20(this.sessionFile(), id2);
22467
+ writeFileSync21(this.sessionFile(), id2);
21872
22468
  } catch {
21873
22469
  }
21874
22470
  }
21875
- freshFile = () => join30(this.home, "fresh.json");
22471
+ freshFile = () => join31(this.home, "fresh.json");
21876
22472
  readFresh() {
21877
22473
  try {
21878
- if (!existsSync26(this.freshFile())) return null;
21879
- const r = JSON.parse(readFileSync18(this.freshFile(), "utf8"));
22474
+ if (!existsSync27(this.freshFile())) return null;
22475
+ const r = JSON.parse(readFileSync19(this.freshFile(), "utf8"));
21880
22476
  return { seed: typeof r.seed === "string" && r.seed ? r.seed : null };
21881
22477
  } catch {
21882
22478
  return null;
@@ -23087,10 +23683,10 @@ function dbWidgetStore(db) {
23087
23683
  }
23088
23684
 
23089
23685
  // ../server/src/tls.ts
23090
- import { chmodSync as chmodSync9, existsSync as existsSync27, mkdirSync as mkdirSync19, readFileSync as readFileSync19, writeFileSync as writeFileSync21 } from "node:fs";
23686
+ import { chmodSync as chmodSync10, existsSync as existsSync28, mkdirSync as mkdirSync20, readFileSync as readFileSync20, writeFileSync as writeFileSync22 } from "node:fs";
23091
23687
  import { networkInterfaces } from "node:os";
23092
23688
  import { isIP as isIP4 } from "node:net";
23093
- import { join as join31 } from "node:path";
23689
+ import { join as join32 } from "node:path";
23094
23690
  import { generate } from "selfsigned";
23095
23691
  var DAYS = 825;
23096
23692
  var RENEW_BEFORE_MS = 30 * 24 * 36e5;
@@ -23105,16 +23701,16 @@ function tlsHosts(extra = [], ifaces) {
23105
23701
  return [.../* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", ...lanAddresses(ifaces), ...extra.map((h) => h.toLowerCase()).filter(Boolean)])];
23106
23702
  }
23107
23703
  async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
23108
- const dir = join31(dataDir, "tls");
23109
- const keyFile = join31(dir, "key.pem");
23110
- const certFile = join31(dir, "cert.pem");
23111
- const metaFile = join31(dir, "meta.json");
23704
+ const dir = join32(dataDir, "tls");
23705
+ const keyFile = join32(dir, "key.pem");
23706
+ const certFile = join32(dir, "cert.pem");
23707
+ const metaFile = join32(dir, "meta.json");
23112
23708
  const hosts = tlsHosts(extraHosts, ifaces);
23113
- if (existsSync27(keyFile) && existsSync27(certFile) && existsSync27(metaFile)) {
23709
+ if (existsSync28(keyFile) && existsSync28(certFile) && existsSync28(metaFile)) {
23114
23710
  try {
23115
- const meta = JSON.parse(readFileSync19(metaFile, "utf8"));
23711
+ const meta = JSON.parse(readFileSync20(metaFile, "utf8"));
23116
23712
  const covered = hosts.every((h) => meta.hosts.includes(h));
23117
- if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync19(keyFile, "utf8"), cert: readFileSync19(certFile, "utf8") };
23713
+ if (covered && meta.expires - now() > RENEW_BEFORE_MS) return { key: readFileSync20(keyFile, "utf8"), cert: readFileSync20(certFile, "utf8") };
23118
23714
  } catch {
23119
23715
  }
23120
23716
  }
@@ -23132,12 +23728,12 @@ async function ensureTlsCert(dataDir, extraHosts = [], ifaces, now = Date.now) {
23132
23728
  { name: "subjectAltName", altNames }
23133
23729
  ]
23134
23730
  });
23135
- mkdirSync19(dir, { recursive: true });
23136
- writeFileSync21(keyFile, pems.private);
23137
- writeFileSync21(certFile, pems.cert);
23138
- writeFileSync21(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
23731
+ mkdirSync20(dir, { recursive: true });
23732
+ writeFileSync22(keyFile, pems.private);
23733
+ writeFileSync22(certFile, pems.cert);
23734
+ writeFileSync22(metaFile, JSON.stringify({ hosts, expires: now() + DAYS * 24 * 36e5 }));
23139
23735
  try {
23140
- chmodSync9(keyFile, 384);
23736
+ chmodSync10(keyFile, 384);
23141
23737
  } catch {
23142
23738
  }
23143
23739
  return { key: pems.private, cert: pems.cert };
@@ -23181,7 +23777,7 @@ var DuckController = class {
23181
23777
 
23182
23778
  // ../server/src/system/autostart.ts
23183
23779
  import { spawn as spawn9 } from "node:child_process";
23184
- import { existsSync as existsSync28, mkdirSync as mkdirSync20, readFileSync as readFileSync20, rmSync as rmSync14, writeFileSync as writeFileSync22 } from "node:fs";
23780
+ import { existsSync as existsSync29, mkdirSync as mkdirSync21, readFileSync as readFileSync21, rmSync as rmSync14, writeFileSync as writeFileSync23 } from "node:fs";
23185
23781
  import { homedir as homedir5 } from "node:os";
23186
23782
  import { dirname as dirname6, posix as posix4, win32 as win324 } from "node:path";
23187
23783
  var RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
@@ -23358,17 +23954,17 @@ function realAutostartDeps(dataDir) {
23358
23954
  uid: typeof process.getuid === "function" ? process.getuid() : 0,
23359
23955
  path: process.env.PATH ?? "",
23360
23956
  ...process.env.XDG_CONFIG_HOME ? { configHome: process.env.XDG_CONFIG_HOME } : {},
23361
- exists: (p) => existsSync28(p),
23957
+ exists: (p) => existsSync29(p),
23362
23958
  read: (p) => {
23363
23959
  try {
23364
- return readFileSync20(p, "utf8");
23960
+ return readFileSync21(p, "utf8");
23365
23961
  } catch {
23366
23962
  return null;
23367
23963
  }
23368
23964
  },
23369
23965
  write: (p, text5) => {
23370
- mkdirSync20(dirname6(p), { recursive: true });
23371
- writeFileSync22(p, text5);
23966
+ mkdirSync21(dirname6(p), { recursive: true });
23967
+ writeFileSync23(p, text5);
23372
23968
  },
23373
23969
  remove: (p) => rmSync14(p, { force: true }),
23374
23970
  run: (cmd, args) => new Promise((resolve13) => {
@@ -23389,7 +23985,7 @@ function currentSelf() {
23389
23985
  // ../server/src/system/npm.ts
23390
23986
  import { spawn as spawn10 } from "node:child_process";
23391
23987
  var PACKAGE = "friend-assistant";
23392
- var runningVersion = () => true ? "0.1.90" : "development";
23988
+ var runningVersion = () => true ? "0.1.92" : "development";
23393
23989
  async function npmLatest(fetchFn = fetch, timeoutMs = 1e4) {
23394
23990
  try {
23395
23991
  const res = await fetchFn(`https://registry.npmjs.org/${PACKAGE}/latest`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
@@ -23679,29 +24275,29 @@ var Challenges = class {
23679
24275
  };
23680
24276
 
23681
24277
  // ../server/src/voice/crypto.ts
23682
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes15 } from "node:crypto";
23683
- import { chmodSync as chmodSync10, existsSync as existsSync29, mkdirSync as mkdirSync21, readFileSync as readFileSync21, writeFileSync as writeFileSync23 } from "node:fs";
24278
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes16 } from "node:crypto";
24279
+ import { chmodSync as chmodSync11, existsSync as existsSync30, mkdirSync as mkdirSync22, readFileSync as readFileSync22, writeFileSync as writeFileSync24 } from "node:fs";
23684
24280
  import { dirname as dirname7 } from "node:path";
23685
24281
  var KEY_BYTES = 32;
23686
24282
  var IV_BYTES = 12;
23687
24283
  var TAG_BYTES = 16;
23688
24284
  function loadOrCreateKey(path3) {
23689
- if (existsSync29(path3)) {
23690
- const key3 = readFileSync21(path3);
24285
+ if (existsSync30(path3)) {
24286
+ const key3 = readFileSync22(path3);
23691
24287
  if (key3.length !== KEY_BYTES) throw new Error(`invalid voice key file (expected ${KEY_BYTES} bytes): ${path3}`);
23692
24288
  return key3;
23693
24289
  }
23694
- mkdirSync21(dirname7(path3), { recursive: true });
23695
- const key2 = randomBytes15(KEY_BYTES);
23696
- writeFileSync23(path3, key2, { mode: 384 });
24290
+ mkdirSync22(dirname7(path3), { recursive: true });
24291
+ const key2 = randomBytes16(KEY_BYTES);
24292
+ writeFileSync24(path3, key2, { mode: 384 });
23697
24293
  try {
23698
- chmodSync10(path3, 384);
24294
+ chmodSync11(path3, 384);
23699
24295
  } catch {
23700
24296
  }
23701
24297
  return key2;
23702
24298
  }
23703
24299
  function encrypt(key2, plain6) {
23704
- const iv = randomBytes15(IV_BYTES);
24300
+ const iv = randomBytes16(IV_BYTES);
23705
24301
  const cipher = createCipheriv2("aes-256-gcm", key2, iv);
23706
24302
  const body = Buffer.concat([cipher.update(plain6), cipher.final()]);
23707
24303
  return Buffer.concat([iv, cipher.getAuthTag(), body]);
@@ -24335,7 +24931,7 @@ async function createApp(opts) {
24335
24931
  return false;
24336
24932
  }
24337
24933
  const bytes2 = Buffer.from(shot.data, "base64");
24338
- const path3 = join32(opts.dataDir, `visitor-${visitorId()}.jpg`);
24934
+ const path3 = join33(opts.dataDir, `visitor-${visitorId()}.jpg`);
24339
24935
  await saveVisitorFile(path3, bytes2);
24340
24936
  const caption = "Someone I do not know has been in front of your screen. Do you know this person? Reply with who it is (for example: yes, Ravi, my cousin; you may tell him I am out) or say no.";
24341
24937
  const sent = [];
@@ -24379,19 +24975,34 @@ async function createApp(opts) {
24379
24975
  void musicLibrary.scan().catch(() => {
24380
24976
  });
24381
24977
  const memory = new Memory(db);
24382
- const memoryTree = new MemoryTree(join32(opts.dataDir, "memory"));
24978
+ const memoryTree = new MemoryTree(join33(opts.dataDir, "memory"));
24383
24979
  if (config.memory.enabled) {
24384
24980
  memoryTree.ensure();
24385
24981
  importFlatNotes(memory, memoryTree);
24386
24982
  memoryTree.repair();
24387
24983
  }
24388
- const soul = new Soul(memoryTree, join32(opts.dataDir, "soul-history"));
24984
+ const soul = new Soul(memoryTree, join33(opts.dataDir, "soul-history"));
24389
24985
  soul.ensure();
24390
- const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join32(opts.dataDir, "browser-profiles") });
24986
+ const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot: join33(opts.dataDir, "browser-profiles") });
24391
24987
  const tasks = new Tasks(db);
24392
- const plugins = new Plugins(db, join32(opts.dataDir, "plugins"));
24988
+ const plugins = new Plugins(db, join33(opts.dataDir, "plugins"));
24393
24989
  const connectorStore = new ConnectorStore(opts.dataDir);
24394
- const hub = new McpHub(connectorStore);
24990
+ let oauthHubRef = null;
24991
+ const onThisPc = (url) => {
24992
+ try {
24993
+ return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
24994
+ } catch {
24995
+ return false;
24996
+ }
24997
+ };
24998
+ const hub = new McpHub(connectorStore, {
24999
+ oauth: {
25000
+ provider: (id2, name, url, onConsent) => {
25001
+ if (!oauthHubRef) throw new Error("Signing in with a link is not ready yet.");
25002
+ return new VaultOAuthProvider(`mcp:${id2}`, oauthHubRef.vault, oauthHubRef.tickets, oauthHubRef.redirectUri(), `Friend (${name})`, onConsent, onThisPc(url));
25003
+ }
25004
+ }
25005
+ });
24395
25006
  let listenPort = config.port;
24396
25007
  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) }) });
24397
25008
  const videoHub = new VideoHub({
@@ -24502,13 +25113,13 @@ async function createApp(opts) {
24502
25113
  if (id2 === "audius") return changeAudiusConfig((s) => changeAudius(s, change));
24503
25114
  if (id2 === "browser") {
24504
25115
  const err2 = changeBrowserConfig((b) => changeBrowser(b, change, !!browserHub.status().chrome));
24505
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join32(catalogDir, BROWSER_SKILL));
25116
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === BROWSER_SKILL)) plugins.install(join33(catalogDir, BROWSER_SKILL));
24506
25117
  if (!err2 && "remove" in change) plugins.remove(BROWSER_SKILL);
24507
25118
  return err2;
24508
25119
  }
24509
25120
  if (id2 === "tavily") {
24510
25121
  const err2 = changeTavilyConfig((t) => changeTavily(t, change, !!config.web.tavilyKey));
24511
- if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join32(catalogDir, TAVILY_SKILL));
25122
+ if (!err2 && "install" in change && listCatalog(catalogDir).some((c) => c.id === TAVILY_SKILL)) plugins.install(join33(catalogDir, TAVILY_SKILL));
24512
25123
  if (!err2 && "remove" in change) plugins.remove(TAVILY_SKILL);
24513
25124
  return err2;
24514
25125
  }
@@ -24539,7 +25150,7 @@ async function createApp(opts) {
24539
25150
  }
24540
25151
  if (id2 !== "zerodha") return changeChannels((c) => changeIntegration(c, id2, change));
24541
25152
  const err = changeBrokers((b) => changeBroker(b, id2, change, (gone) => brokerHub.forget(gone)));
24542
- if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join32(catalogDir, PORTFOLIO_SKILL));
25153
+ if (!err && "install" in change && listCatalog(catalogDir).some((c) => c.id === PORTFOLIO_SKILL)) plugins.install(join33(catalogDir, PORTFOLIO_SKILL));
24543
25154
  if (!err && "remove" in change) plugins.remove(PORTFOLIO_SKILL);
24544
25155
  return err;
24545
25156
  };
@@ -24564,7 +25175,7 @@ async function createApp(opts) {
24564
25175
  },
24565
25176
  install: (id2) => {
24566
25177
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) return { ok: false, error: "That plugin is not in the catalog." };
24567
- return plugins.install(join32(catalogDir, id2));
25178
+ return plugins.install(join33(catalogDir, id2));
24568
25179
  }
24569
25180
  },
24570
25181
  integrations: {
@@ -24703,6 +25314,10 @@ async function createApp(opts) {
24703
25314
  commitSettings({ view }, { actor: "agent" });
24704
25315
  return `The view is now ${view}.`;
24705
25316
  },
25317
+ setLayout: (layout) => {
25318
+ commitSettings({ hud: { layout } }, { actor: "agent" });
25319
+ return `The screen layout is now ${layout}.`;
25320
+ },
24706
25321
  setLook: (look2) => {
24707
25322
  commitSettings({ look: look2 }, { actor: "agent" });
24708
25323
  return "The look is updated and saved.";
@@ -24722,7 +25337,7 @@ async function createApp(opts) {
24722
25337
  tries: () => config.office.decideTries,
24723
25338
  runTurn: (text5) => runWithRequest({ prefix: "office-approval" }, () => agent.runTurn(text5, { trust: "owner", emit: broadcastLate, ip: "127.0.0.1", source: "office" }))
24724
25339
  });
24725
- const attachments = new AttachmentStore(join32(opts.dataDir, "uploads"), () => config.attachments);
25340
+ const attachments = new AttachmentStore(join33(opts.dataDir, "uploads"), () => config.attachments);
24726
25341
  const office = new Office({
24727
25342
  config: () => config,
24728
25343
  store: officeStore,
@@ -24889,6 +25504,7 @@ First check the work: read the whole report (office.report) and, when it changed
24889
25504
  eyeGate: new EyeGate({ eye, audit }),
24890
25505
  presence,
24891
25506
  visitors,
25507
+ oauth: { start: (target) => connectByName(target) },
24892
25508
  people,
24893
25509
  camera: {
24894
25510
  request: (emit, signal, clip10, recognise) => {
@@ -24932,6 +25548,17 @@ First check the work: read the whole report (office.report) and, when it changed
24932
25548
  const broadcast = (m) => {
24933
25549
  for (const c of clients) c.send(m);
24934
25550
  };
25551
+ const cameraDenials = /* @__PURE__ */ new Map();
25552
+ const screenDenials = /* @__PURE__ */ new Map();
25553
+ const allDenied = (seen, id2, conn) => {
25554
+ const who = seen.get(id2) ?? /* @__PURE__ */ new Set();
25555
+ who.add(conn);
25556
+ seen.set(id2, who);
25557
+ while (seen.size > 20) seen.delete(seen.keys().next().value);
25558
+ for (const c of clients) if (!who.has(c)) return false;
25559
+ seen.delete(id2);
25560
+ return true;
25561
+ };
24935
25562
  broadcastLate = broadcast;
24936
25563
  hostEmit = (state) => broadcast({ type: "music.host", state });
24937
25564
  const alexaHub = new AlexaHub({
@@ -24995,7 +25622,7 @@ First check the work: read the whole report (office.report) and, when it changed
24995
25622
  const voice2 = opts.voice;
24996
25623
  const speaker = voice2 ? new Speaker(voice2, audit, () => config.voice.ttsVoice, () => ({ hindi: config.voice.hindiVoice || void 0, marathi: config.voice.marathiVoice || void 0 })) : null;
24997
25624
  const voiceAvailable = () => !!voice2 && voice2.available();
24998
- const voiceKey = voice2 ? loadOrCreateKey(join32(opts.dataDir, "voice.key")) : null;
25625
+ const voiceKey = voice2 ? loadOrCreateKey(join33(opts.dataDir, "voice.key")) : null;
24999
25626
  const voiceprint = voiceKey ? new Voiceprint(db, voiceKey) : null;
25000
25627
  const enrollment = voiceprint ? new Enrollment(voiceprint, SPEAKER_MODEL) : null;
25001
25628
  const household = voiceKey ? new Household(db, voiceKey) : null;
@@ -25081,7 +25708,7 @@ ${task.title}`) !== null,
25081
25708
  }
25082
25709
  },
25083
25710
  audit,
25084
- statePath: join32(opts.dataDir, "proactive.json")
25711
+ statePath: join33(opts.dataDir, "proactive.json")
25085
25712
  });
25086
25713
  async function requirePin(pin, ip) {
25087
25714
  let ok2 = false;
@@ -25177,7 +25804,7 @@ ${task.title}`) !== null,
25177
25804
  if (!isPluginId(id2)) throw new HttpError(400, "That is not a plugin name.");
25178
25805
  if (!listCatalog(catalogDir).some((c) => c.id === id2)) throw new HttpError(404, "That plugin is not in the catalog.");
25179
25806
  await requirePin(pin, ip);
25180
- const r = plugins.install(join32(catalogDir, id2));
25807
+ const r = plugins.install(join33(catalogDir, id2));
25181
25808
  if (!r.ok) throw new HttpError(400, `That plugin cannot be installed: ${r.error}`);
25182
25809
  audit.log("owner", "plugin.installed", { id: r.id, upgraded: r.upgraded, ip });
25183
25810
  return { id: r.id, upgraded: r.upgraded };
@@ -25215,6 +25842,106 @@ ${task.title}`) !== null,
25215
25842
  audit.log("owner", "plugin.removed", { id: id2 });
25216
25843
  }
25217
25844
  };
25845
+ const oauthHub = new OAuthHub({
25846
+ dataDir: opts.dataDir,
25847
+ config: () => ({ publicUrl: config.publicUrl, port: listenPort, oauth: config.oauth }),
25848
+ audit,
25849
+ send: async (text5) => (await alertOwnerPhone(text5)).length > 0,
25850
+ ...opts.oauthFetch ? { fetch: opts.oauthFetch } : {}
25851
+ });
25852
+ oauthHubRef = oauthHub;
25853
+ const changeOauthConfig = (fn) => {
25854
+ const saved = loadConfig(opts.dataDir);
25855
+ fn(saved.oauth);
25856
+ fn(config.oauth);
25857
+ saveConfig(saved);
25858
+ };
25859
+ const oauthApi = {
25860
+ state: () => ({
25861
+ services: oauthHub.services(),
25862
+ connectors: hub.list().filter((c) => c.oauth).map((c) => ({ id: c.id, name: c.name, status: c.status, connected: c.status === "ready", account: oauthHub.vault.get(`mcp:${c.id}`).account ?? null })),
25863
+ redirectUri: oauthHub.redirectUri()
25864
+ }),
25865
+ connectService: async (id2, toPhone) => {
25866
+ try {
25867
+ return await oauthHub.startService(id2, { toPhone });
25868
+ } catch (e) {
25869
+ throw new HttpError(400, e.message);
25870
+ }
25871
+ },
25872
+ disconnectService: async (id2) => {
25873
+ if (!providerById(id2)) throw new HttpError(404, "Friend does not know that service.");
25874
+ await oauthHub.disconnect(`svc:${id2}`);
25875
+ },
25876
+ connectConnector: async (id2, toPhone) => {
25877
+ let v;
25878
+ try {
25879
+ v = await hub.reload(id2);
25880
+ } catch (e) {
25881
+ throw new HttpError(404, e.message);
25882
+ }
25883
+ if (!v.oauth) throw new HttpError(400, "That connector does not sign in with a link.");
25884
+ if (v.status === "ready") return { connected: true };
25885
+ const consent = hub.takeConsent(id2);
25886
+ if (!consent) throw new HttpError(400, v.error ?? "That connector is not waiting for approval.");
25887
+ return oauthHub.approvalForMcp(id2, consent, v.name, toPhone);
25888
+ },
25889
+ disconnectConnector: async (id2) => {
25890
+ await oauthHub.disconnect(`mcp:${id2}`);
25891
+ await hub.reload(id2).catch(() => {
25892
+ });
25893
+ },
25894
+ setClient: async (id2, clientId, clientSecret, pin, ip) => {
25895
+ const p = providerById(id2);
25896
+ if (!p) throw new HttpError(404, "Friend does not know that service.");
25897
+ await requirePin(pin, ip);
25898
+ const cid = clientId.trim();
25899
+ if (!/^[A-Za-z0-9._~-]{8,200}$/.test(cid)) throw new HttpError(400, "A client ID is letters, digits and . _ ~ - only. Copy it from the service's developer console.");
25900
+ const changed = cid !== config.oauth.clients[id2]?.clientId;
25901
+ changeOauthConfig((o) => {
25902
+ o.clients[id2] = { clientId: cid };
25903
+ });
25904
+ if (clientSecret) oauthHub.setClientSecret(id2, clientSecret.trim());
25905
+ if (changed) await oauthHub.disconnect(`svc:${id2}`);
25906
+ audit.log("owner", "oauth.client", { id: id2, ip });
25907
+ },
25908
+ open: (ticket) => oauthHub.openTicket(ticket),
25909
+ callback: async (params) => {
25910
+ const r = await oauthHub.callback(params);
25911
+ if (!r.ok || !r.key) return false;
25912
+ if (r.code && r.key.startsWith("mcp:")) {
25913
+ try {
25914
+ await hub.finishOAuth(r.key.slice(4), r.code);
25915
+ audit.log("owner", "oauth.connected", { key: r.key });
25916
+ return true;
25917
+ } catch {
25918
+ audit.log("owner", "oauth.failed", { key: r.key });
25919
+ return false;
25920
+ }
25921
+ }
25922
+ return true;
25923
+ }
25924
+ };
25925
+ const connectByName = async (target) => {
25926
+ const name = target.trim().toLowerCase();
25927
+ try {
25928
+ const service = providerById(name);
25929
+ if (service) {
25930
+ const r = await oauthHub.startService(service.id, { toPhone: true });
25931
+ return r.sent ? { ok: true, message: `I sent a link to your phone. Open it to connect ${service.name}; it works once, for ten minutes.` } : { ok: true, message: `There is no phone app linked, so I could not send the link. Open Settings, Connectors and press Connect next to ${service.name}.` };
25932
+ }
25933
+ const c = hub.list().find((x) => x.oauth && (x.id === name || x.name.toLowerCase() === name));
25934
+ if (c) {
25935
+ const r = await oauthApi.connectConnector(c.id, true);
25936
+ if (r.connected) return { ok: true, message: `${c.name} is already connected.` };
25937
+ return r.sent ? { ok: true, message: `I sent a link to your phone. Open it to connect ${c.name}.` } : { ok: true, message: `There is no phone app linked. Open Settings, Connectors and press Connect next to ${c.name}.` };
25938
+ }
25939
+ const names = [...oauthHub.services().map((s) => s.id), ...hub.list().filter((x) => x.oauth).map((x) => x.id)];
25940
+ return { ok: false, message: names.length ? `I do not know that one. These can sign in with a link: ${names.join(", ")}.` : "Nothing is set up to sign in with a link yet." };
25941
+ } catch (e) {
25942
+ return { ok: false, message: e.message.slice(0, 200) };
25943
+ }
25944
+ };
25218
25945
  const connectorsApi = {
25219
25946
  // Chrome control is a plugin when this Friend has its own copy: the plugins screen offers it, so it is not offered here a second time
25220
25947
  list: () => ({ connectors: hub.list(), presets: chromeBundled ? PRESETS.filter((p) => p.id !== "chrome") : PRESETS }),
@@ -25269,6 +25996,7 @@ ${task.title}`) !== null,
25269
25996
  remove: async (id2) => {
25270
25997
  try {
25271
25998
  await hub.remove(id2);
25999
+ oauthHub.vault.forget(`mcp:${id2}`);
25272
26000
  audit.log("owner", "connector.removed", { id: id2 });
25273
26001
  } catch (e) {
25274
26002
  throw new HttpError(404, e.message);
@@ -25389,6 +26117,7 @@ ${task.title}`) !== null,
25389
26117
  const gateway = createGateway({
25390
26118
  ...tls ? { tls } : {},
25391
26119
  connectors: connectorsApi,
26120
+ oauth: oauthApi,
25392
26121
  chrome: chromeRemoteApi,
25393
26122
  system: systemApi,
25394
26123
  soul: soulApi,
@@ -25894,6 +26623,7 @@ ${url}`);
25894
26623
  break;
25895
26624
  }
25896
26625
  case "camera.denied":
26626
+ if (!allDenied(cameraDenials, msg.id, conn)) break;
25897
26627
  if (camera.deny(msg.id, msg.reason)) {
25898
26628
  audit.log("owner", "camera.denied", { reason: msg.reason });
25899
26629
  broadcast({ type: "camera.cancel", id: msg.id });
@@ -25903,6 +26633,7 @@ ${url}`);
25903
26633
  screenCheck.reply(msg.id, msg.lines);
25904
26634
  break;
25905
26635
  case "screen.denied":
26636
+ if (!allDenied(screenDenials, msg.id, conn)) break;
25906
26637
  if (screenShot.deny(msg.id, msg.reason)) {
25907
26638
  audit.log("owner", "screen.denied", { reason: msg.reason });
25908
26639
  broadcast({ type: "screen.cancel", id: msg.id });
@@ -26054,7 +26785,7 @@ ${url}`);
26054
26785
  }
26055
26786
  const prune = () => {
26056
26787
  try {
26057
- const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join32(opts.dataDir, "audit-archive"), now: Date.now() });
26788
+ const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join33(opts.dataDir, "audit-archive"), now: Date.now() });
26058
26789
  if (r.removed) audit.log("system", "audit.pruned", { removed: r.removed, archive: r.archivePath });
26059
26790
  } catch (e) {
26060
26791
  audit.log("system", "audit.prune_failed", { message: e.message.slice(0, 200) });
@@ -26577,8 +27308,8 @@ import { resolve as resolve9 } from "node:path";
26577
27308
  import { WebSocket as WebSocket4 } from "ws";
26578
27309
 
26579
27310
  // ../agent-cli/src/tools/fs.ts
26580
- import { closeSync, mkdirSync as mkdirSync22, openSync, readSync, readdirSync as readdirSync10, statSync as statSync9, writeFileSync as writeFileSync24 } from "node:fs";
26581
- import { dirname as dirname10, join as join33 } from "node:path";
27311
+ import { closeSync, mkdirSync as mkdirSync23, openSync, readSync, readdirSync as readdirSync10, statSync as statSync9, writeFileSync as writeFileSync25 } from "node:fs";
27312
+ import { dirname as dirname10, join as join34 } from "node:path";
26582
27313
 
26583
27314
  // ../agent-cli/src/tools/roots.ts
26584
27315
  import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "node:fs";
@@ -26640,7 +27371,7 @@ function fsList(args, ctx) {
26640
27371
  if (e.isDirectory()) return `[dir] ${e.name}`;
26641
27372
  let size = 0;
26642
27373
  try {
26643
- size = statSync9(join33(g.abs, e.name)).size;
27374
+ size = statSync9(join34(g.abs, e.name)).size;
26644
27375
  } catch {
26645
27376
  }
26646
27377
  return `[file] ${e.name} (${size} bytes)`;
@@ -26681,8 +27412,8 @@ function fsWrite(args, ctx) {
26681
27412
  if ("error" in g) return { ok: false, error: g.error };
26682
27413
  if (Buffer.byteLength(args.content) > MAX_WRITE) return { ok: false, error: "Content too large (5 MB limit)" };
26683
27414
  try {
26684
- mkdirSync22(dirname10(g.abs), { recursive: true });
26685
- writeFileSync24(g.abs, args.content);
27415
+ mkdirSync23(dirname10(g.abs), { recursive: true });
27416
+ writeFileSync25(g.abs, args.content);
26686
27417
  return { ok: true, output: `Wrote ${Buffer.byteLength(args.content)} bytes to ${g.abs}`, truncated: false };
26687
27418
  } catch (e) {
26688
27419
  return { ok: false, error: e.message };
@@ -26917,9 +27648,9 @@ function startDeviceNode(opts) {
26917
27648
  }
26918
27649
 
26919
27650
  // ../agent-cli/src/commands/start.ts
26920
- import { randomBytes as randomBytes16 } from "node:crypto";
26921
- import { existsSync as existsSync31, readFileSync as readFileSync23, writeFileSync as writeFileSync26 } from "node:fs";
26922
- import { dirname as dirname12, join as join35, resolve as resolve8 } from "node:path";
27651
+ import { randomBytes as randomBytes17 } from "node:crypto";
27652
+ import { existsSync as existsSync32, readFileSync as readFileSync24, writeFileSync as writeFileSync27 } from "node:fs";
27653
+ import { dirname as dirname12, join as join36, resolve as resolve8 } from "node:path";
26923
27654
  import { fileURLToPath as fileURLToPath5 } from "node:url";
26924
27655
 
26925
27656
  // ../agent-cli/src/commands/lan.ts
@@ -27025,23 +27756,23 @@ async function lanCommand(args, io2, ifaces = networkInterfaces2) {
27025
27756
 
27026
27757
  // ../agent-cli/src/commands/voice.ts
27027
27758
  import { spawn as spawn13 } from "node:child_process";
27028
- import { existsSync as existsSync30, mkdirSync as mkdirSync23, readFileSync as readFileSync22, writeFileSync as writeFileSync25 } from "node:fs";
27029
- import { dirname as dirname11, join as join34, resolve as resolve7 } from "node:path";
27759
+ import { existsSync as existsSync31, mkdirSync as mkdirSync24, readFileSync as readFileSync23, writeFileSync as writeFileSync26 } from "node:fs";
27760
+ import { dirname as dirname11, join as join35, resolve as resolve7 } from "node:path";
27030
27761
  import { fileURLToPath as fileURLToPath4 } from "node:url";
27031
27762
  function voicePaths(dataDir) {
27032
- const home = join34(dataDir, "voice");
27033
- const venv = join34(home, "venv");
27763
+ const home = join35(dataDir, "voice");
27764
+ const venv = join35(home, "venv");
27034
27765
  return {
27035
27766
  home,
27036
27767
  venv,
27037
- python: process.platform === "win32" ? join34(venv, "Scripts", "python.exe") : join34(venv, "bin", "python"),
27038
- models: join34(home, "models"),
27039
- marker: join34(home, "installed.json")
27768
+ python: process.platform === "win32" ? join35(venv, "Scripts", "python.exe") : join35(venv, "bin", "python"),
27769
+ models: join35(home, "models"),
27770
+ marker: join35(home, "installed.json")
27040
27771
  };
27041
27772
  }
27042
27773
  function readMarker(dataDir) {
27043
27774
  try {
27044
- return JSON.parse(readFileSync22(voicePaths(dataDir).marker, "utf8"));
27775
+ return JSON.parse(readFileSync23(voicePaths(dataDir).marker, "utf8"));
27045
27776
  } catch {
27046
27777
  return null;
27047
27778
  }
@@ -27138,8 +27869,8 @@ async function voiceSetupCommand(io2, deps = {}, args = []) {
27138
27869
  io2.err("Python 3.10 or newer is required. Install it from https://www.python.org/downloads/ and run this again.");
27139
27870
  return 1;
27140
27871
  }
27141
- mkdirSync23(p.home, { recursive: true });
27142
- if (!existsSync30(p.python)) {
27872
+ mkdirSync24(p.home, { recursive: true });
27873
+ if (!existsSync31(p.python)) {
27143
27874
  io2.out("1/3 Creating a private Python environment\u2026");
27144
27875
  const r = await run2(py.cmd, [...py.args, "-m", "venv", p.venv], { onLine });
27145
27876
  if (r.code !== 0) {
@@ -27173,7 +27904,7 @@ ${tail(dl.stdout)}`);
27173
27904
  return 1;
27174
27905
  }
27175
27906
  const marker = { python: p.python, sttModel: cfg.voice.sttModel, ttsVoice: cfg.voice.ttsVoice, at: Date.now() };
27176
- writeFileSync25(p.marker, JSON.stringify(marker, null, 2));
27907
+ writeFileSync26(p.marker, JSON.stringify(marker, null, 2));
27177
27908
  io2.out("Voice is ready. Start Friend with `friend start`, then hold Space to talk.");
27178
27909
  return 0;
27179
27910
  }
@@ -27189,7 +27920,7 @@ async function voiceStatusCommand(io2) {
27189
27920
  io2.out("Voice engine: not installed. Run: friend voice setup");
27190
27921
  return 0;
27191
27922
  }
27192
- if (!existsSync30(marker.python)) {
27923
+ if (!existsSync31(marker.python)) {
27193
27924
  io2.out("Voice engine: installed, but its Python is missing. Run: friend voice setup");
27194
27925
  return 0;
27195
27926
  }
@@ -27262,12 +27993,12 @@ async function voiceCommand(args, io2) {
27262
27993
  function findWebDir(explicit) {
27263
27994
  const here2 = dirname12(fileURLToPath5(import.meta.url));
27264
27995
  const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve8(here2, "../../../web/dist"), resolve8(here2, "web")];
27265
- return candidates.find((c) => !!c && existsSync31(join35(c, "index.html")));
27996
+ return candidates.find((c) => !!c && existsSync32(join36(c, "index.html")));
27266
27997
  }
27267
27998
  async function startFriend(opts) {
27268
27999
  const stored = loadConfig(opts.dataDir);
27269
28000
  const marker = stored.voice.enabled ? readMarker(opts.dataDir) : null;
27270
- const secret = randomBytes16(24).toString("hex");
28001
+ const secret = randomBytes17(24).toString("hex");
27271
28002
  const sidecar = marker ? new SidecarProcess({
27272
28003
  command: marker.python,
27273
28004
  args: [
@@ -27298,17 +28029,17 @@ async function startFriend(opts) {
27298
28029
  }
27299
28030
  });
27300
28031
  const { port } = await app.start();
27301
- const tokenFile = join35(opts.dataDir, "local-device.token");
27302
- let token = existsSync31(tokenFile) ? readFileSync23(tokenFile, "utf8").trim() : "";
28032
+ const tokenFile = join36(opts.dataDir, "local-device.token");
28033
+ let token = existsSync32(tokenFile) ? readFileSync24(tokenFile, "utf8").trim() : "";
27303
28034
  if (!token || !app.auth.resolveDevice(token)) {
27304
28035
  token = app.auth.redeemPairCode(app.auth.createPairCode(), "this-pc");
27305
- writeFileSync26(tokenFile, token, { mode: 384 });
28036
+ writeFileSync27(tokenFile, token, { mode: 384 });
27306
28037
  }
27307
28038
  const node = startDeviceNode({
27308
28039
  url: `${app.config.https ? "wss" : "ws"}://127.0.0.1:${port}/device`,
27309
28040
  token,
27310
28041
  roots: app.config.roots,
27311
- ...app.config.https ? { ca: readFileSync23(join35(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
28042
+ ...app.config.https ? { ca: readFileSync24(join36(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
27312
28043
  // this PC trusts only its own Friend's certificate
27313
28044
  });
27314
28045
  const urls = urlsFor(app.config.bind, port, void 0, app.config.https);
@@ -27478,8 +28209,8 @@ async function devicesCommand(args, io2) {
27478
28209
  }
27479
28210
 
27480
28211
  // ../agent-cli/src/commands/memory.ts
27481
- import { existsSync as existsSync32 } from "node:fs";
27482
- import { join as join36 } from "node:path";
28212
+ import { existsSync as existsSync33 } from "node:fs";
28213
+ import { join as join37 } from "node:path";
27483
28214
  var USAGE = "Usage: friend memory list | friend memory show <path> | friend memory forget <path or number> | friend memory clear";
27484
28215
  async function memoryCommand(args, io2) {
27485
28216
  const [sub, arg] = args;
@@ -27491,7 +28222,7 @@ async function memoryCommand(args, io2) {
27491
28222
  try {
27492
28223
  const memory = new Memory(db);
27493
28224
  const audit = new Audit(db);
27494
- const tree2 = existsSync32(join36(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join36(io2.dataDir, "memory")) : null;
28225
+ const tree2 = existsSync33(join37(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join37(io2.dataDir, "memory")) : null;
27495
28226
  if (sub === "show") {
27496
28227
  if (!tree2 || !arg) {
27497
28228
  io2.err(tree2 ? USAGE : "There is no memory tree yet.");
@@ -27570,8 +28301,8 @@ async function memoryCommand(args, io2) {
27570
28301
  }
27571
28302
 
27572
28303
  // ../agent-cli/src/commands/plugin.ts
27573
- import { existsSync as existsSync33, readdirSync as readdirSync11, statSync as statSync10 } from "node:fs";
27574
- import { dirname as dirname13, join as join37, resolve as resolve10 } from "node:path";
28304
+ import { existsSync as existsSync34, readdirSync as readdirSync11, statSync as statSync10 } from "node:fs";
28305
+ import { dirname as dirname13, join as join38, resolve as resolve10 } from "node:path";
27575
28306
  import { fileURLToPath as fileURLToPath6 } from "node:url";
27576
28307
  var USAGE2 = "Usage: friend plugin catalog | list | install <name|folder> [--yes] | enable <id> | disable <id> | remove <id>";
27577
28308
  function defaultCatalog() {
@@ -27585,10 +28316,10 @@ async function pluginCommand(args, io2, deps = {}) {
27585
28316
  const flags = rest.filter((a) => a.startsWith("--"));
27586
28317
  const arg = rest.find((a) => !a.startsWith("--"));
27587
28318
  if (sub === "catalog") {
27588
- const dirs = existsSync33(catalogDir) ? readdirSync11(catalogDir).filter((d) => statSync10(join37(catalogDir, d)).isDirectory()) : [];
28319
+ const dirs = existsSync34(catalogDir) ? readdirSync11(catalogDir).filter((d) => statSync10(join38(catalogDir, d)).isDirectory()) : [];
27589
28320
  if (dirs.length === 0) io2.out("The catalog is empty.");
27590
28321
  for (const d of dirs.sort()) {
27591
- const r = inspectPlugin(join37(catalogDir, d));
28322
+ const r = inspectPlugin(join38(catalogDir, d));
27592
28323
  if (!r.ok) {
27593
28324
  io2.out(`${d} (invalid: ${r.error})`);
27594
28325
  continue;
@@ -27604,7 +28335,7 @@ async function pluginCommand(args, io2, deps = {}) {
27604
28335
  }
27605
28336
  const db = openDb(io2.dataDir);
27606
28337
  try {
27607
- const plugins = new Plugins(db, join37(io2.dataDir, "plugins"));
28338
+ const plugins = new Plugins(db, join38(io2.dataDir, "plugins"));
27608
28339
  if (sub === "list") {
27609
28340
  const all = plugins.list();
27610
28341
  if (all.length === 0) io2.out("No plugins installed. See: friend plugin catalog");
@@ -27618,8 +28349,8 @@ async function pluginCommand(args, io2, deps = {}) {
27618
28349
  io2.err(USAGE2);
27619
28350
  return 1;
27620
28351
  }
27621
- const inCatalog = !/[\\/]/.test(arg) && existsSync33(join37(catalogDir, arg));
27622
- const source = inCatalog ? join37(catalogDir, arg) : existsSync33(resolve10(arg)) ? resolve10(arg) : null;
28352
+ const inCatalog = !/[\\/]/.test(arg) && existsSync34(join38(catalogDir, arg));
28353
+ const source = inCatalog ? join38(catalogDir, arg) : existsSync34(resolve10(arg)) ? resolve10(arg) : null;
27623
28354
  if (!source) {
27624
28355
  io2.err(`"${arg}" is not in the catalog and there is no such folder. See: friend plugin catalog`);
27625
28356
  return 1;
@@ -27674,7 +28405,7 @@ async function pluginCommand(args, io2, deps = {}) {
27674
28405
 
27675
28406
  // ../agent-cli/src/commands/onboard/index.ts
27676
28407
  import crossSpawn4 from "cross-spawn";
27677
- import { mkdirSync as mkdirSync25 } from "node:fs";
28408
+ import { mkdirSync as mkdirSync26 } from "node:fs";
27678
28409
  import { resolve as resolve11 } from "node:path";
27679
28410
 
27680
28411
  // ../agent-cli/src/commands/ollama.ts
@@ -27997,16 +28728,16 @@ function installPlan(id2, platform, have) {
27997
28728
  }
27998
28729
 
27999
28730
  // ../agent-cli/src/commands/onboard/state.ts
28000
- import { existsSync as existsSync34, mkdirSync as mkdirSync24, readFileSync as readFileSync24, renameSync as renameSync5, rmSync as rmSync15, writeFileSync as writeFileSync27 } from "node:fs";
28001
- import { dirname as dirname14, join as join38 } from "node:path";
28731
+ import { existsSync as existsSync35, mkdirSync as mkdirSync25, readFileSync as readFileSync25, renameSync as renameSync6, rmSync as rmSync15, writeFileSync as writeFileSync28 } from "node:fs";
28732
+ import { dirname as dirname14, join as join39 } from "node:path";
28002
28733
  var FEATURES = ["claude-code", "claude-api", "ollama", "voice", "sandbox"];
28003
28734
  var emptyState = () => ({ version: 1, done: {}, features: [], restart: [] });
28004
- var statePath = (dataDir) => join38(dataDir, "onboarding.json");
28735
+ var statePath = (dataDir) => join39(dataDir, "onboarding.json");
28005
28736
  function loadState(dataDir) {
28006
28737
  const f = statePath(dataDir);
28007
- if (!existsSync34(f)) return emptyState();
28738
+ if (!existsSync35(f)) return emptyState();
28008
28739
  try {
28009
- const raw = JSON.parse(readFileSync24(f, "utf8"));
28740
+ const raw = JSON.parse(readFileSync25(f, "utf8"));
28010
28741
  const done = raw.done && typeof raw.done === "object" ? Object.fromEntries(Object.entries(raw.done).filter(([, v]) => typeof v === "string")) : {};
28011
28742
  const features2 = Array.isArray(raw.features) ? raw.features.filter((x) => FEATURES.includes(x)) : [];
28012
28743
  const restart = Array.isArray(raw.restart) ? raw.restart.filter((x) => typeof x === "string") : [];
@@ -28017,10 +28748,10 @@ function loadState(dataDir) {
28017
28748
  }
28018
28749
  function saveState(dataDir, state) {
28019
28750
  const f = statePath(dataDir);
28020
- mkdirSync24(dirname14(f), { recursive: true });
28751
+ mkdirSync25(dirname14(f), { recursive: true });
28021
28752
  const tmp = `${f}.tmp`;
28022
- writeFileSync27(tmp, JSON.stringify(state, null, 2));
28023
- renameSync5(tmp, f);
28753
+ writeFileSync28(tmp, JSON.stringify(state, null, 2));
28754
+ renameSync6(tmp, f);
28024
28755
  }
28025
28756
  function resetState(dataDir) {
28026
28757
  rmSync15(statePath(dataDir), { force: true });
@@ -28375,7 +29106,7 @@ async function workspace(c) {
28375
29106
  const answer = await text4(c.ui, current ? "Workspace folder" : "Workspace folder (Enter to skip)", current ?? "");
28376
29107
  if (answer) {
28377
29108
  const abs = resolve11(answer);
28378
- mkdirSync25(abs, { recursive: true });
29109
+ mkdirSync26(abs, { recursive: true });
28379
29110
  cfg.roots = [abs];
28380
29111
  saveConfig(cfg);
28381
29112
  io2.out(`Workspace: ${abs}`);
@@ -28629,8 +29360,8 @@ async function usageCommand(args, io2, log) {
28629
29360
  }
28630
29361
 
28631
29362
  // ../agent-cli/src/commands/audit.ts
28632
- import { writeFileSync as writeFileSync28 } from "node:fs";
28633
- import { join as join39 } from "node:path";
29363
+ import { writeFileSync as writeFileSync29 } from "node:fs";
29364
+ import { join as join40 } from "node:path";
28634
29365
  var USAGE5 = [
28635
29366
  "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]",
28636
29367
  " friend audit show <request-id>",
@@ -28735,7 +29466,7 @@ async function auditCommand(args, io2, deps = {}) {
28735
29466
  afterwards = async (res2) => {
28736
29467
  const raw = /filename="([^"]+)"/.exec(res2.headers.get("content-disposition") ?? "")?.[1] ?? `friend-audit.${f.query.format}`;
28737
29468
  const name = (raw.split(/[\\/]/).pop() ?? "friend-audit").replace(/[^A-Za-z0-9._-]/g, "_") || "friend-audit";
28738
- (deps.write ?? ((n2, b) => writeFileSync28(join39(process.cwd(), n2), b)))(name, await res2.text());
29469
+ (deps.write ?? ((n2, b) => writeFileSync29(join40(process.cwd(), n2), b)))(name, await res2.text());
28739
29470
  io2.out(`Saved ${name} in this folder. It contains private content: keep it safe.`);
28740
29471
  return 0;
28741
29472
  };
@@ -28763,9 +29494,9 @@ async function auditCommand(args, io2, deps = {}) {
28763
29494
 
28764
29495
  // ../agent-cli/src/commands/daemon.ts
28765
29496
  import { spawn as spawn14, spawnSync as spawnSync3 } from "node:child_process";
28766
- import { closeSync as closeSync2, existsSync as existsSync35, mkdirSync as mkdirSync26, openSync as openSync2, readFileSync as readFileSync25, renameSync as renameSync6, rmSync as rmSync16, statSync as statSync11, writeFileSync as writeFileSync29 } from "node:fs";
29497
+ import { closeSync as closeSync2, existsSync as existsSync36, mkdirSync as mkdirSync27, openSync as openSync2, readFileSync as readFileSync26, renameSync as renameSync7, rmSync as rmSync16, statSync as statSync11, writeFileSync as writeFileSync30 } from "node:fs";
28767
29498
  import { connect } from "node:net";
28768
- import { join as join40 } from "node:path";
29499
+ import { join as join41 } from "node:path";
28769
29500
  var USAGE6 = "Usage: friend daemon start | stop | restart | status";
28770
29501
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
28771
29502
  var sleep2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
@@ -28821,11 +29552,11 @@ var realDeps = {
28821
29552
  },
28822
29553
  now: Date.now
28823
29554
  };
28824
- var pidFile = (dataDir) => join40(dataDir, "friend.pid");
28825
- var logFileOf = (dataDir) => join40(dataDir, "friend.log");
29555
+ var pidFile = (dataDir) => join41(dataDir, "friend.pid");
29556
+ var logFileOf = (dataDir) => join41(dataDir, "friend.log");
28826
29557
  function readPid(dataDir) {
28827
29558
  try {
28828
- const r = JSON.parse(readFileSync25(pidFile(dataDir), "utf8"));
29559
+ const r = JSON.parse(readFileSync26(pidFile(dataDir), "utf8"));
28829
29560
  return Number.isInteger(r.pid) && r.pid > 0 ? r : null;
28830
29561
  } catch {
28831
29562
  return null;
@@ -28856,10 +29587,10 @@ async function start(io2, deps) {
28856
29587
  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).`);
28857
29588
  return 1;
28858
29589
  }
28859
- mkdirSync26(io2.dataDir, { recursive: true });
29590
+ mkdirSync27(io2.dataDir, { recursive: true });
28860
29591
  const log = logFileOf(io2.dataDir);
28861
29592
  try {
28862
- if (existsSync35(log) && statSync11(log).size > MAX_LOG_BYTES) renameSync6(log, `${log}.old`);
29593
+ if (existsSync36(log) && statSync11(log).size > MAX_LOG_BYTES) renameSync7(log, `${log}.old`);
28863
29594
  } catch {
28864
29595
  }
28865
29596
  const pid = deps.launch(log);
@@ -28867,7 +29598,7 @@ async function start(io2, deps) {
28867
29598
  io2.err("Could not start Friend in the background.");
28868
29599
  return 1;
28869
29600
  }
28870
- writeFileSync29(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
29601
+ writeFileSync30(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
28871
29602
  for (let i = 0; i < 60; i++) {
28872
29603
  if (await deps.portOpen(cfg.port, 300)) {
28873
29604
  io2.out(`Friend is running in the background (pid ${pid}) at ${urls.local}`);
@@ -28933,10 +29664,10 @@ async function daemonCommand(args, io2, deps = realDeps) {
28933
29664
  // ../agent-cli/src/commands/upgrade.ts
28934
29665
  import crossSpawn5 from "cross-spawn";
28935
29666
  import { appendFileSync } from "node:fs";
28936
- import { join as join41 } from "node:path";
29667
+ import { join as join42 } from "node:path";
28937
29668
  var PACKAGE2 = "friend-assistant";
28938
29669
  var real2 = {
28939
- current: () => true ? "0.1.90" : "development",
29670
+ current: () => true ? "0.1.92" : "development",
28940
29671
  latest: () => new Promise((resolve13) => {
28941
29672
  const child = crossSpawn5("npm", ["view", PACKAGE2, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
28942
29673
  let out = "";
@@ -28974,7 +29705,7 @@ async function upgradeCommand(args, io0, deps = real2) {
28974
29705
  io0.err("Usage: friend upgrade [--force] [--auto]");
28975
29706
  return 1;
28976
29707
  }
28977
- const log = deps.log ?? ((line2) => appendFileSync(join41(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
29708
+ const log = deps.log ?? ((line2) => appendFileSync(join42(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
28978
29709
  `));
28979
29710
  const io2 = auto ? {
28980
29711
  ...io0,
@@ -29092,7 +29823,7 @@ async function claudeCommand(args, io2, deps = {}) {
29092
29823
  }
29093
29824
 
29094
29825
  // ../agent-cli/src/commands/setup.ts
29095
- import { mkdirSync as mkdirSync27 } from "node:fs";
29826
+ import { mkdirSync as mkdirSync28 } from "node:fs";
29096
29827
  import { resolve as resolve12 } from "node:path";
29097
29828
  async function setupCommand3(io2) {
29098
29829
  const db = openDb(io2.dataDir);
@@ -29118,7 +29849,7 @@ async function setupCommand3(io2) {
29118
29849
  const cfg = loadConfig(io2.dataDir);
29119
29850
  if (workspace2) {
29120
29851
  const abs = resolve12(workspace2);
29121
- mkdirSync27(abs, { recursive: true });
29852
+ mkdirSync28(abs, { recursive: true });
29122
29853
  cfg.roots = [abs];
29123
29854
  }
29124
29855
  if (apiKey) cfg.apiKey = apiKey;
@@ -29254,7 +29985,7 @@ async function run(argv, io2) {
29254
29985
  case "version":
29255
29986
  case "--version":
29256
29987
  case "-v":
29257
- io2.out(true ? "0.1.90" : "development");
29988
+ io2.out(true ? "0.1.92" : "development");
29258
29989
  return 0;
29259
29990
  case "lan":
29260
29991
  return await lanCommand(rest, io2);