friend-assistant 0.1.90 → 0.1.91
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/BUILD.json +2 -2
- package/dist/friend.mjs +1009 -295
- package/dist/web/assets/{OrgParts-D5rK_L8n.js → OrgParts-cdCcRE9C.js} +1 -1
- package/dist/web/assets/index-L9B7BU-1.js +4460 -0
- package/dist/web/assets/{jarvis-ui-PfbsZUDC.js → jarvis-ui-CvToZv-V.js} +1 -1
- package/dist/web/assets/{jarvisTree-CqxGUlrO.js → jarvisTree-CGo-bC9r.js} +1 -1
- package/dist/web/assets/{ort.bundle.min-pnuPnpk0.js → ort.bundle.min-PYTlFFxi.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/web/assets/index-vbysdsEw.js +0 -4460
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.",
|
|
@@ -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";
|
|
@@ -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
|
|
6109
|
-
return { enabled: r.enabled !== false, cooldownMinutes:
|
|
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
|
|
6114
|
-
return { maxBytes:
|
|
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
|
|
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:
|
|
6126
|
-
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
|
|
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:
|
|
6148
|
-
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
|
|
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:
|
|
6172
|
-
scanDepth:
|
|
6173
|
-
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:
|
|
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
|
|
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:
|
|
6293
|
-
startTimeoutSec:
|
|
6294
|
-
pauseAtWindow:
|
|
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:
|
|
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:
|
|
6300
|
-
budget: { perWorkerTokens:
|
|
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
|
|
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 =
|
|
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:
|
|
6328
|
-
holdMinutes:
|
|
6329
|
-
permissionSeconds:
|
|
6330
|
-
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
|
|
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:
|
|
6370
|
-
bigDropPct:
|
|
6371
|
-
cacheSeconds:
|
|
6372
|
-
maxSchedules:
|
|
6373
|
-
maxTriesPerDay:
|
|
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
|
|
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:
|
|
6465
|
-
minGapMin:
|
|
6466
|
-
silenceHours:
|
|
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,
|
|
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
|
|
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
|
|
14913
|
-
import { chmodSync as
|
|
14914
|
-
import { join as
|
|
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
|
|
15446
|
+
return join19(this.dir, `broker-${broker}.session.json`);
|
|
14929
15447
|
}
|
|
14930
15448
|
save(broker, info) {
|
|
14931
15449
|
const file = this.file(broker);
|
|
14932
|
-
|
|
14933
|
-
|
|
15450
|
+
mkdirSync13(this.dir, { recursive: true });
|
|
15451
|
+
writeFileSync12(file, JSON.stringify({ accessToken: info.accessToken, expiresAt: info.expiresAt }), { mode: 384 });
|
|
14934
15452
|
try {
|
|
14935
|
-
|
|
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 (!
|
|
15461
|
+
if (!existsSync17(file)) return null;
|
|
14944
15462
|
try {
|
|
14945
|
-
const raw = JSON.parse(
|
|
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 =
|
|
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
|
|
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:
|
|
15068
|
-
avgPrice:
|
|
15069
|
-
lastPrice:
|
|
15070
|
-
closePrice:
|
|
15071
|
-
pnl:
|
|
15072
|
-
dayChange:
|
|
15073
|
-
dayChangePct:
|
|
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:
|
|
15083
|
-
avgPrice:
|
|
15084
|
-
lastPrice:
|
|
15085
|
-
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 =
|
|
15091
|
-
const used2 =
|
|
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:
|
|
15101
|
-
price:
|
|
15102
|
-
avgPrice:
|
|
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
|
|
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
|
|
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
|
|
15805
|
+
import { existsSync as existsSync18, realpathSync } from "node:fs";
|
|
15288
15806
|
import { createRequire } from "node:module";
|
|
15289
|
-
import { dirname as dirname5, join as
|
|
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 [
|
|
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 (
|
|
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(
|
|
16010
|
+
const dir = mkdtempSync2(join21(tmpdir2(), "friend-code-"));
|
|
15493
16011
|
try {
|
|
15494
|
-
const file =
|
|
15495
|
-
|
|
15496
|
-
|
|
15497
|
-
|
|
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
|
-
|
|
15500
|
-
|
|
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
|
|
15645
|
-
import { join as
|
|
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 =
|
|
15650
|
-
if (
|
|
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
|
-
|
|
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
|
|
15663
|
-
import { join as
|
|
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
|
|
16249
|
+
return join23(this.d.tree.root, CURSOR_FILE);
|
|
15732
16250
|
}
|
|
15733
16251
|
readCursor() {
|
|
15734
16252
|
try {
|
|
15735
|
-
if (!
|
|
15736
|
-
const n2 = Number(JSON.parse(
|
|
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
|
-
|
|
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
|
|
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 (
|
|
16073
|
-
const s = JSON.parse(
|
|
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
|
-
|
|
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
|
|
16229
|
-
import { join as
|
|
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(
|
|
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(
|
|
16769
|
+
if (!have.has(id2) && plugins.install(join24(catalogDir, id2)).ok) done.push(id2);
|
|
16252
16770
|
}
|
|
16253
|
-
if (changed &&
|
|
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
|
|
16259
|
-
import { mkdirSync as
|
|
16260
|
-
import { join as
|
|
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
|
|
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) =>
|
|
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) =>
|
|
16453
|
-
for (const p of m.plugins) entries.set(
|
|
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 ?? (() =>
|
|
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,
|
|
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
|
|
17112
|
+
return join25(this.d.dir, "marketplaces.json");
|
|
16595
17113
|
}
|
|
16596
17114
|
marketplaces() {
|
|
16597
17115
|
try {
|
|
16598
|
-
const list2 = JSON.parse(
|
|
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
|
-
|
|
16606
|
-
|
|
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
|
|
16643
|
-
import { join as
|
|
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
|
|
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 =
|
|
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
|
|
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 =
|
|
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:
|
|
16831
|
-
durationMs:
|
|
16832
|
-
input:
|
|
16833
|
-
output:
|
|
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 =
|
|
17425
|
-
|
|
17426
|
-
const mcp =
|
|
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
|
-
|
|
17948
|
+
writeFileSync19(mcp, JSON.stringify({ mcpServers: servers }));
|
|
17431
17949
|
let pluginDir;
|
|
17432
17950
|
if (live.skills.length > 0) {
|
|
17433
|
-
pluginDir =
|
|
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 &&
|
|
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
|
|
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 =
|
|
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
|
|
18461
|
+
import { join as join33 } from "node:path";
|
|
17944
18462
|
|
|
17945
18463
|
// ../server/src/attach/store.ts
|
|
17946
|
-
import { randomBytes as
|
|
17947
|
-
import { existsSync as
|
|
17948
|
-
import { join as
|
|
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
|
-
|
|
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 =
|
|
18283
|
-
const d =
|
|
18284
|
-
|
|
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
|
-
|
|
18287
|
-
|
|
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(
|
|
18294
|
-
return { meta, bytes: () =>
|
|
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(
|
|
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(
|
|
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 =
|
|
18848
|
+
const d = join28(this.dir, n2);
|
|
18331
18849
|
try {
|
|
18332
|
-
const meta =
|
|
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
|
|
18376
|
-
import { join as
|
|
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
|
-
|
|
18703
|
-
const db = new Database(
|
|
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
|
|
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 =
|
|
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
|
|
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 &&
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
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(
|
|
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 =
|
|
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
|
-
|
|
21083
|
-
profile = mkdtempSync3(
|
|
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] =
|
|
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
|
|
21440
|
-
import { join as
|
|
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 =
|
|
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
|
-
|
|
22198
|
+
mkdirSync19(this.home, { recursive: true });
|
|
21603
22199
|
this.fresh = { seed: seed?.trim() || null };
|
|
21604
22200
|
try {
|
|
21605
|
-
|
|
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
|
-
|
|
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",
|
|
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(
|
|
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 =
|
|
21828
|
-
|
|
22423
|
+
const file = join31(this.home, `system-${++this.systemCount}.txt`);
|
|
22424
|
+
writeFileSync21(file, text5);
|
|
21829
22425
|
try {
|
|
21830
|
-
|
|
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 =
|
|
21845
|
-
|
|
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
|
-
|
|
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 = () =>
|
|
22450
|
+
sessionFile = () => join31(this.home, "session-id");
|
|
21855
22451
|
readSession() {
|
|
21856
22452
|
try {
|
|
21857
|
-
return
|
|
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
|
-
|
|
22467
|
+
writeFileSync21(this.sessionFile(), id2);
|
|
21872
22468
|
} catch {
|
|
21873
22469
|
}
|
|
21874
22470
|
}
|
|
21875
|
-
freshFile = () =>
|
|
22471
|
+
freshFile = () => join31(this.home, "fresh.json");
|
|
21876
22472
|
readFresh() {
|
|
21877
22473
|
try {
|
|
21878
|
-
if (!
|
|
21879
|
-
const r = JSON.parse(
|
|
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
|
|
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
|
|
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 =
|
|
23109
|
-
const keyFile =
|
|
23110
|
-
const certFile =
|
|
23111
|
-
const metaFile =
|
|
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 (
|
|
23709
|
+
if (existsSync28(keyFile) && existsSync28(certFile) && existsSync28(metaFile)) {
|
|
23114
23710
|
try {
|
|
23115
|
-
const meta = JSON.parse(
|
|
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:
|
|
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
|
-
|
|
23136
|
-
|
|
23137
|
-
|
|
23138
|
-
|
|
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
|
-
|
|
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
|
|
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) =>
|
|
23957
|
+
exists: (p) => existsSync29(p),
|
|
23362
23958
|
read: (p) => {
|
|
23363
23959
|
try {
|
|
23364
|
-
return
|
|
23960
|
+
return readFileSync21(p, "utf8");
|
|
23365
23961
|
} catch {
|
|
23366
23962
|
return null;
|
|
23367
23963
|
}
|
|
23368
23964
|
},
|
|
23369
23965
|
write: (p, text5) => {
|
|
23370
|
-
|
|
23371
|
-
|
|
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.
|
|
23988
|
+
var runningVersion = () => true ? "0.1.91" : "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
|
|
23683
|
-
import { chmodSync as
|
|
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 (
|
|
23690
|
-
const key3 =
|
|
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
|
-
|
|
23695
|
-
const key2 =
|
|
23696
|
-
|
|
24290
|
+
mkdirSync22(dirname7(path3), { recursive: true });
|
|
24291
|
+
const key2 = randomBytes16(KEY_BYTES);
|
|
24292
|
+
writeFileSync24(path3, key2, { mode: 384 });
|
|
23697
24293
|
try {
|
|
23698
|
-
|
|
24294
|
+
chmodSync11(path3, 384);
|
|
23699
24295
|
} catch {
|
|
23700
24296
|
}
|
|
23701
24297
|
return key2;
|
|
23702
24298
|
}
|
|
23703
24299
|
function encrypt(key2, plain6) {
|
|
23704
|
-
const iv =
|
|
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 =
|
|
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(
|
|
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,
|
|
24984
|
+
const soul = new Soul(memoryTree, join33(opts.dataDir, "soul-history"));
|
|
24389
24985
|
soul.ensure();
|
|
24390
|
-
const browserHub = new BrowserHub({ config: () => config.browser, tmpRoot:
|
|
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,
|
|
24988
|
+
const plugins = new Plugins(db, join33(opts.dataDir, "plugins"));
|
|
24393
24989
|
const connectorStore = new ConnectorStore(opts.dataDir);
|
|
24394
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
25178
|
+
return plugins.install(join33(catalogDir, id2));
|
|
24568
25179
|
}
|
|
24569
25180
|
},
|
|
24570
25181
|
integrations: {
|
|
@@ -24722,7 +25333,7 @@ async function createApp(opts) {
|
|
|
24722
25333
|
tries: () => config.office.decideTries,
|
|
24723
25334
|
runTurn: (text5) => runWithRequest({ prefix: "office-approval" }, () => agent.runTurn(text5, { trust: "owner", emit: broadcastLate, ip: "127.0.0.1", source: "office" }))
|
|
24724
25335
|
});
|
|
24725
|
-
const attachments = new AttachmentStore(
|
|
25336
|
+
const attachments = new AttachmentStore(join33(opts.dataDir, "uploads"), () => config.attachments);
|
|
24726
25337
|
const office = new Office({
|
|
24727
25338
|
config: () => config,
|
|
24728
25339
|
store: officeStore,
|
|
@@ -24889,6 +25500,7 @@ First check the work: read the whole report (office.report) and, when it changed
|
|
|
24889
25500
|
eyeGate: new EyeGate({ eye, audit }),
|
|
24890
25501
|
presence,
|
|
24891
25502
|
visitors,
|
|
25503
|
+
oauth: { start: (target) => connectByName(target) },
|
|
24892
25504
|
people,
|
|
24893
25505
|
camera: {
|
|
24894
25506
|
request: (emit, signal, clip10, recognise) => {
|
|
@@ -24995,7 +25607,7 @@ First check the work: read the whole report (office.report) and, when it changed
|
|
|
24995
25607
|
const voice2 = opts.voice;
|
|
24996
25608
|
const speaker = voice2 ? new Speaker(voice2, audit, () => config.voice.ttsVoice, () => ({ hindi: config.voice.hindiVoice || void 0, marathi: config.voice.marathiVoice || void 0 })) : null;
|
|
24997
25609
|
const voiceAvailable = () => !!voice2 && voice2.available();
|
|
24998
|
-
const voiceKey = voice2 ? loadOrCreateKey(
|
|
25610
|
+
const voiceKey = voice2 ? loadOrCreateKey(join33(opts.dataDir, "voice.key")) : null;
|
|
24999
25611
|
const voiceprint = voiceKey ? new Voiceprint(db, voiceKey) : null;
|
|
25000
25612
|
const enrollment = voiceprint ? new Enrollment(voiceprint, SPEAKER_MODEL) : null;
|
|
25001
25613
|
const household = voiceKey ? new Household(db, voiceKey) : null;
|
|
@@ -25081,7 +25693,7 @@ ${task.title}`) !== null,
|
|
|
25081
25693
|
}
|
|
25082
25694
|
},
|
|
25083
25695
|
audit,
|
|
25084
|
-
statePath:
|
|
25696
|
+
statePath: join33(opts.dataDir, "proactive.json")
|
|
25085
25697
|
});
|
|
25086
25698
|
async function requirePin(pin, ip) {
|
|
25087
25699
|
let ok2 = false;
|
|
@@ -25177,7 +25789,7 @@ ${task.title}`) !== null,
|
|
|
25177
25789
|
if (!isPluginId(id2)) throw new HttpError(400, "That is not a plugin name.");
|
|
25178
25790
|
if (!listCatalog(catalogDir).some((c) => c.id === id2)) throw new HttpError(404, "That plugin is not in the catalog.");
|
|
25179
25791
|
await requirePin(pin, ip);
|
|
25180
|
-
const r = plugins.install(
|
|
25792
|
+
const r = plugins.install(join33(catalogDir, id2));
|
|
25181
25793
|
if (!r.ok) throw new HttpError(400, `That plugin cannot be installed: ${r.error}`);
|
|
25182
25794
|
audit.log("owner", "plugin.installed", { id: r.id, upgraded: r.upgraded, ip });
|
|
25183
25795
|
return { id: r.id, upgraded: r.upgraded };
|
|
@@ -25215,6 +25827,106 @@ ${task.title}`) !== null,
|
|
|
25215
25827
|
audit.log("owner", "plugin.removed", { id: id2 });
|
|
25216
25828
|
}
|
|
25217
25829
|
};
|
|
25830
|
+
const oauthHub = new OAuthHub({
|
|
25831
|
+
dataDir: opts.dataDir,
|
|
25832
|
+
config: () => ({ publicUrl: config.publicUrl, port: listenPort, oauth: config.oauth }),
|
|
25833
|
+
audit,
|
|
25834
|
+
send: async (text5) => (await alertOwnerPhone(text5)).length > 0,
|
|
25835
|
+
...opts.oauthFetch ? { fetch: opts.oauthFetch } : {}
|
|
25836
|
+
});
|
|
25837
|
+
oauthHubRef = oauthHub;
|
|
25838
|
+
const changeOauthConfig = (fn) => {
|
|
25839
|
+
const saved = loadConfig(opts.dataDir);
|
|
25840
|
+
fn(saved.oauth);
|
|
25841
|
+
fn(config.oauth);
|
|
25842
|
+
saveConfig(saved);
|
|
25843
|
+
};
|
|
25844
|
+
const oauthApi = {
|
|
25845
|
+
state: () => ({
|
|
25846
|
+
services: oauthHub.services(),
|
|
25847
|
+
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 })),
|
|
25848
|
+
redirectUri: oauthHub.redirectUri()
|
|
25849
|
+
}),
|
|
25850
|
+
connectService: async (id2, toPhone) => {
|
|
25851
|
+
try {
|
|
25852
|
+
return await oauthHub.startService(id2, { toPhone });
|
|
25853
|
+
} catch (e) {
|
|
25854
|
+
throw new HttpError(400, e.message);
|
|
25855
|
+
}
|
|
25856
|
+
},
|
|
25857
|
+
disconnectService: async (id2) => {
|
|
25858
|
+
if (!providerById(id2)) throw new HttpError(404, "Friend does not know that service.");
|
|
25859
|
+
await oauthHub.disconnect(`svc:${id2}`);
|
|
25860
|
+
},
|
|
25861
|
+
connectConnector: async (id2, toPhone) => {
|
|
25862
|
+
let v;
|
|
25863
|
+
try {
|
|
25864
|
+
v = await hub.reload(id2);
|
|
25865
|
+
} catch (e) {
|
|
25866
|
+
throw new HttpError(404, e.message);
|
|
25867
|
+
}
|
|
25868
|
+
if (!v.oauth) throw new HttpError(400, "That connector does not sign in with a link.");
|
|
25869
|
+
if (v.status === "ready") return { connected: true };
|
|
25870
|
+
const consent = hub.takeConsent(id2);
|
|
25871
|
+
if (!consent) throw new HttpError(400, v.error ?? "That connector is not waiting for approval.");
|
|
25872
|
+
return oauthHub.approvalForMcp(id2, consent, v.name, toPhone);
|
|
25873
|
+
},
|
|
25874
|
+
disconnectConnector: async (id2) => {
|
|
25875
|
+
await oauthHub.disconnect(`mcp:${id2}`);
|
|
25876
|
+
await hub.reload(id2).catch(() => {
|
|
25877
|
+
});
|
|
25878
|
+
},
|
|
25879
|
+
setClient: async (id2, clientId, clientSecret, pin, ip) => {
|
|
25880
|
+
const p = providerById(id2);
|
|
25881
|
+
if (!p) throw new HttpError(404, "Friend does not know that service.");
|
|
25882
|
+
await requirePin(pin, ip);
|
|
25883
|
+
const cid = clientId.trim();
|
|
25884
|
+
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.");
|
|
25885
|
+
const changed = cid !== config.oauth.clients[id2]?.clientId;
|
|
25886
|
+
changeOauthConfig((o) => {
|
|
25887
|
+
o.clients[id2] = { clientId: cid };
|
|
25888
|
+
});
|
|
25889
|
+
if (clientSecret) oauthHub.setClientSecret(id2, clientSecret.trim());
|
|
25890
|
+
if (changed) await oauthHub.disconnect(`svc:${id2}`);
|
|
25891
|
+
audit.log("owner", "oauth.client", { id: id2, ip });
|
|
25892
|
+
},
|
|
25893
|
+
open: (ticket) => oauthHub.openTicket(ticket),
|
|
25894
|
+
callback: async (params) => {
|
|
25895
|
+
const r = await oauthHub.callback(params);
|
|
25896
|
+
if (!r.ok || !r.key) return false;
|
|
25897
|
+
if (r.code && r.key.startsWith("mcp:")) {
|
|
25898
|
+
try {
|
|
25899
|
+
await hub.finishOAuth(r.key.slice(4), r.code);
|
|
25900
|
+
audit.log("owner", "oauth.connected", { key: r.key });
|
|
25901
|
+
return true;
|
|
25902
|
+
} catch {
|
|
25903
|
+
audit.log("owner", "oauth.failed", { key: r.key });
|
|
25904
|
+
return false;
|
|
25905
|
+
}
|
|
25906
|
+
}
|
|
25907
|
+
return true;
|
|
25908
|
+
}
|
|
25909
|
+
};
|
|
25910
|
+
const connectByName = async (target) => {
|
|
25911
|
+
const name = target.trim().toLowerCase();
|
|
25912
|
+
try {
|
|
25913
|
+
const service = providerById(name);
|
|
25914
|
+
if (service) {
|
|
25915
|
+
const r = await oauthHub.startService(service.id, { toPhone: true });
|
|
25916
|
+
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}.` };
|
|
25917
|
+
}
|
|
25918
|
+
const c = hub.list().find((x) => x.oauth && (x.id === name || x.name.toLowerCase() === name));
|
|
25919
|
+
if (c) {
|
|
25920
|
+
const r = await oauthApi.connectConnector(c.id, true);
|
|
25921
|
+
if (r.connected) return { ok: true, message: `${c.name} is already connected.` };
|
|
25922
|
+
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}.` };
|
|
25923
|
+
}
|
|
25924
|
+
const names = [...oauthHub.services().map((s) => s.id), ...hub.list().filter((x) => x.oauth).map((x) => x.id)];
|
|
25925
|
+
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." };
|
|
25926
|
+
} catch (e) {
|
|
25927
|
+
return { ok: false, message: e.message.slice(0, 200) };
|
|
25928
|
+
}
|
|
25929
|
+
};
|
|
25218
25930
|
const connectorsApi = {
|
|
25219
25931
|
// 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
25932
|
list: () => ({ connectors: hub.list(), presets: chromeBundled ? PRESETS.filter((p) => p.id !== "chrome") : PRESETS }),
|
|
@@ -25269,6 +25981,7 @@ ${task.title}`) !== null,
|
|
|
25269
25981
|
remove: async (id2) => {
|
|
25270
25982
|
try {
|
|
25271
25983
|
await hub.remove(id2);
|
|
25984
|
+
oauthHub.vault.forget(`mcp:${id2}`);
|
|
25272
25985
|
audit.log("owner", "connector.removed", { id: id2 });
|
|
25273
25986
|
} catch (e) {
|
|
25274
25987
|
throw new HttpError(404, e.message);
|
|
@@ -25389,6 +26102,7 @@ ${task.title}`) !== null,
|
|
|
25389
26102
|
const gateway = createGateway({
|
|
25390
26103
|
...tls ? { tls } : {},
|
|
25391
26104
|
connectors: connectorsApi,
|
|
26105
|
+
oauth: oauthApi,
|
|
25392
26106
|
chrome: chromeRemoteApi,
|
|
25393
26107
|
system: systemApi,
|
|
25394
26108
|
soul: soulApi,
|
|
@@ -26054,7 +26768,7 @@ ${url}`);
|
|
|
26054
26768
|
}
|
|
26055
26769
|
const prune = () => {
|
|
26056
26770
|
try {
|
|
26057
|
-
const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir:
|
|
26771
|
+
const r = pruneAudit(db, { keepDays: config.audit.keepDays, archive: config.audit.archive, dir: join33(opts.dataDir, "audit-archive"), now: Date.now() });
|
|
26058
26772
|
if (r.removed) audit.log("system", "audit.pruned", { removed: r.removed, archive: r.archivePath });
|
|
26059
26773
|
} catch (e) {
|
|
26060
26774
|
audit.log("system", "audit.prune_failed", { message: e.message.slice(0, 200) });
|
|
@@ -26577,8 +27291,8 @@ import { resolve as resolve9 } from "node:path";
|
|
|
26577
27291
|
import { WebSocket as WebSocket4 } from "ws";
|
|
26578
27292
|
|
|
26579
27293
|
// ../agent-cli/src/tools/fs.ts
|
|
26580
|
-
import { closeSync, mkdirSync as
|
|
26581
|
-
import { dirname as dirname10, join as
|
|
27294
|
+
import { closeSync, mkdirSync as mkdirSync23, openSync, readSync, readdirSync as readdirSync10, statSync as statSync9, writeFileSync as writeFileSync25 } from "node:fs";
|
|
27295
|
+
import { dirname as dirname10, join as join34 } from "node:path";
|
|
26582
27296
|
|
|
26583
27297
|
// ../agent-cli/src/tools/roots.ts
|
|
26584
27298
|
import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "node:fs";
|
|
@@ -26640,7 +27354,7 @@ function fsList(args, ctx) {
|
|
|
26640
27354
|
if (e.isDirectory()) return `[dir] ${e.name}`;
|
|
26641
27355
|
let size = 0;
|
|
26642
27356
|
try {
|
|
26643
|
-
size = statSync9(
|
|
27357
|
+
size = statSync9(join34(g.abs, e.name)).size;
|
|
26644
27358
|
} catch {
|
|
26645
27359
|
}
|
|
26646
27360
|
return `[file] ${e.name} (${size} bytes)`;
|
|
@@ -26681,8 +27395,8 @@ function fsWrite(args, ctx) {
|
|
|
26681
27395
|
if ("error" in g) return { ok: false, error: g.error };
|
|
26682
27396
|
if (Buffer.byteLength(args.content) > MAX_WRITE) return { ok: false, error: "Content too large (5 MB limit)" };
|
|
26683
27397
|
try {
|
|
26684
|
-
|
|
26685
|
-
|
|
27398
|
+
mkdirSync23(dirname10(g.abs), { recursive: true });
|
|
27399
|
+
writeFileSync25(g.abs, args.content);
|
|
26686
27400
|
return { ok: true, output: `Wrote ${Buffer.byteLength(args.content)} bytes to ${g.abs}`, truncated: false };
|
|
26687
27401
|
} catch (e) {
|
|
26688
27402
|
return { ok: false, error: e.message };
|
|
@@ -26917,9 +27631,9 @@ function startDeviceNode(opts) {
|
|
|
26917
27631
|
}
|
|
26918
27632
|
|
|
26919
27633
|
// ../agent-cli/src/commands/start.ts
|
|
26920
|
-
import { randomBytes as
|
|
26921
|
-
import { existsSync as
|
|
26922
|
-
import { dirname as dirname12, join as
|
|
27634
|
+
import { randomBytes as randomBytes17 } from "node:crypto";
|
|
27635
|
+
import { existsSync as existsSync32, readFileSync as readFileSync24, writeFileSync as writeFileSync27 } from "node:fs";
|
|
27636
|
+
import { dirname as dirname12, join as join36, resolve as resolve8 } from "node:path";
|
|
26923
27637
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
26924
27638
|
|
|
26925
27639
|
// ../agent-cli/src/commands/lan.ts
|
|
@@ -27025,23 +27739,23 @@ async function lanCommand(args, io2, ifaces = networkInterfaces2) {
|
|
|
27025
27739
|
|
|
27026
27740
|
// ../agent-cli/src/commands/voice.ts
|
|
27027
27741
|
import { spawn as spawn13 } from "node:child_process";
|
|
27028
|
-
import { existsSync as
|
|
27029
|
-
import { dirname as dirname11, join as
|
|
27742
|
+
import { existsSync as existsSync31, mkdirSync as mkdirSync24, readFileSync as readFileSync23, writeFileSync as writeFileSync26 } from "node:fs";
|
|
27743
|
+
import { dirname as dirname11, join as join35, resolve as resolve7 } from "node:path";
|
|
27030
27744
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
27031
27745
|
function voicePaths(dataDir) {
|
|
27032
|
-
const home =
|
|
27033
|
-
const venv =
|
|
27746
|
+
const home = join35(dataDir, "voice");
|
|
27747
|
+
const venv = join35(home, "venv");
|
|
27034
27748
|
return {
|
|
27035
27749
|
home,
|
|
27036
27750
|
venv,
|
|
27037
|
-
python: process.platform === "win32" ?
|
|
27038
|
-
models:
|
|
27039
|
-
marker:
|
|
27751
|
+
python: process.platform === "win32" ? join35(venv, "Scripts", "python.exe") : join35(venv, "bin", "python"),
|
|
27752
|
+
models: join35(home, "models"),
|
|
27753
|
+
marker: join35(home, "installed.json")
|
|
27040
27754
|
};
|
|
27041
27755
|
}
|
|
27042
27756
|
function readMarker(dataDir) {
|
|
27043
27757
|
try {
|
|
27044
|
-
return JSON.parse(
|
|
27758
|
+
return JSON.parse(readFileSync23(voicePaths(dataDir).marker, "utf8"));
|
|
27045
27759
|
} catch {
|
|
27046
27760
|
return null;
|
|
27047
27761
|
}
|
|
@@ -27138,8 +27852,8 @@ async function voiceSetupCommand(io2, deps = {}, args = []) {
|
|
|
27138
27852
|
io2.err("Python 3.10 or newer is required. Install it from https://www.python.org/downloads/ and run this again.");
|
|
27139
27853
|
return 1;
|
|
27140
27854
|
}
|
|
27141
|
-
|
|
27142
|
-
if (!
|
|
27855
|
+
mkdirSync24(p.home, { recursive: true });
|
|
27856
|
+
if (!existsSync31(p.python)) {
|
|
27143
27857
|
io2.out("1/3 Creating a private Python environment\u2026");
|
|
27144
27858
|
const r = await run2(py.cmd, [...py.args, "-m", "venv", p.venv], { onLine });
|
|
27145
27859
|
if (r.code !== 0) {
|
|
@@ -27173,7 +27887,7 @@ ${tail(dl.stdout)}`);
|
|
|
27173
27887
|
return 1;
|
|
27174
27888
|
}
|
|
27175
27889
|
const marker = { python: p.python, sttModel: cfg.voice.sttModel, ttsVoice: cfg.voice.ttsVoice, at: Date.now() };
|
|
27176
|
-
|
|
27890
|
+
writeFileSync26(p.marker, JSON.stringify(marker, null, 2));
|
|
27177
27891
|
io2.out("Voice is ready. Start Friend with `friend start`, then hold Space to talk.");
|
|
27178
27892
|
return 0;
|
|
27179
27893
|
}
|
|
@@ -27189,7 +27903,7 @@ async function voiceStatusCommand(io2) {
|
|
|
27189
27903
|
io2.out("Voice engine: not installed. Run: friend voice setup");
|
|
27190
27904
|
return 0;
|
|
27191
27905
|
}
|
|
27192
|
-
if (!
|
|
27906
|
+
if (!existsSync31(marker.python)) {
|
|
27193
27907
|
io2.out("Voice engine: installed, but its Python is missing. Run: friend voice setup");
|
|
27194
27908
|
return 0;
|
|
27195
27909
|
}
|
|
@@ -27262,12 +27976,12 @@ async function voiceCommand(args, io2) {
|
|
|
27262
27976
|
function findWebDir(explicit) {
|
|
27263
27977
|
const here2 = dirname12(fileURLToPath5(import.meta.url));
|
|
27264
27978
|
const candidates = [explicit, process.env.FRIEND_WEB_DIR, resolve8(here2, "../../../web/dist"), resolve8(here2, "web")];
|
|
27265
|
-
return candidates.find((c) => !!c &&
|
|
27979
|
+
return candidates.find((c) => !!c && existsSync32(join36(c, "index.html")));
|
|
27266
27980
|
}
|
|
27267
27981
|
async function startFriend(opts) {
|
|
27268
27982
|
const stored = loadConfig(opts.dataDir);
|
|
27269
27983
|
const marker = stored.voice.enabled ? readMarker(opts.dataDir) : null;
|
|
27270
|
-
const secret =
|
|
27984
|
+
const secret = randomBytes17(24).toString("hex");
|
|
27271
27985
|
const sidecar = marker ? new SidecarProcess({
|
|
27272
27986
|
command: marker.python,
|
|
27273
27987
|
args: [
|
|
@@ -27298,17 +28012,17 @@ async function startFriend(opts) {
|
|
|
27298
28012
|
}
|
|
27299
28013
|
});
|
|
27300
28014
|
const { port } = await app.start();
|
|
27301
|
-
const tokenFile =
|
|
27302
|
-
let token =
|
|
28015
|
+
const tokenFile = join36(opts.dataDir, "local-device.token");
|
|
28016
|
+
let token = existsSync32(tokenFile) ? readFileSync24(tokenFile, "utf8").trim() : "";
|
|
27303
28017
|
if (!token || !app.auth.resolveDevice(token)) {
|
|
27304
28018
|
token = app.auth.redeemPairCode(app.auth.createPairCode(), "this-pc");
|
|
27305
|
-
|
|
28019
|
+
writeFileSync27(tokenFile, token, { mode: 384 });
|
|
27306
28020
|
}
|
|
27307
28021
|
const node = startDeviceNode({
|
|
27308
28022
|
url: `${app.config.https ? "wss" : "ws"}://127.0.0.1:${port}/device`,
|
|
27309
28023
|
token,
|
|
27310
28024
|
roots: app.config.roots,
|
|
27311
|
-
...app.config.https ? { ca:
|
|
28025
|
+
...app.config.https ? { ca: readFileSync24(join36(opts.dataDir, "tls", "cert.pem"), "utf8") } : {}
|
|
27312
28026
|
// this PC trusts only its own Friend's certificate
|
|
27313
28027
|
});
|
|
27314
28028
|
const urls = urlsFor(app.config.bind, port, void 0, app.config.https);
|
|
@@ -27478,8 +28192,8 @@ async function devicesCommand(args, io2) {
|
|
|
27478
28192
|
}
|
|
27479
28193
|
|
|
27480
28194
|
// ../agent-cli/src/commands/memory.ts
|
|
27481
|
-
import { existsSync as
|
|
27482
|
-
import { join as
|
|
28195
|
+
import { existsSync as existsSync33 } from "node:fs";
|
|
28196
|
+
import { join as join37 } from "node:path";
|
|
27483
28197
|
var USAGE = "Usage: friend memory list | friend memory show <path> | friend memory forget <path or number> | friend memory clear";
|
|
27484
28198
|
async function memoryCommand(args, io2) {
|
|
27485
28199
|
const [sub, arg] = args;
|
|
@@ -27491,7 +28205,7 @@ async function memoryCommand(args, io2) {
|
|
|
27491
28205
|
try {
|
|
27492
28206
|
const memory = new Memory(db);
|
|
27493
28207
|
const audit = new Audit(db);
|
|
27494
|
-
const tree2 =
|
|
28208
|
+
const tree2 = existsSync33(join37(io2.dataDir, "memory", "INDEX.md")) ? new MemoryTree(join37(io2.dataDir, "memory")) : null;
|
|
27495
28209
|
if (sub === "show") {
|
|
27496
28210
|
if (!tree2 || !arg) {
|
|
27497
28211
|
io2.err(tree2 ? USAGE : "There is no memory tree yet.");
|
|
@@ -27570,8 +28284,8 @@ async function memoryCommand(args, io2) {
|
|
|
27570
28284
|
}
|
|
27571
28285
|
|
|
27572
28286
|
// ../agent-cli/src/commands/plugin.ts
|
|
27573
|
-
import { existsSync as
|
|
27574
|
-
import { dirname as dirname13, join as
|
|
28287
|
+
import { existsSync as existsSync34, readdirSync as readdirSync11, statSync as statSync10 } from "node:fs";
|
|
28288
|
+
import { dirname as dirname13, join as join38, resolve as resolve10 } from "node:path";
|
|
27575
28289
|
import { fileURLToPath as fileURLToPath6 } from "node:url";
|
|
27576
28290
|
var USAGE2 = "Usage: friend plugin catalog | list | install <name|folder> [--yes] | enable <id> | disable <id> | remove <id>";
|
|
27577
28291
|
function defaultCatalog() {
|
|
@@ -27585,10 +28299,10 @@ async function pluginCommand(args, io2, deps = {}) {
|
|
|
27585
28299
|
const flags = rest.filter((a) => a.startsWith("--"));
|
|
27586
28300
|
const arg = rest.find((a) => !a.startsWith("--"));
|
|
27587
28301
|
if (sub === "catalog") {
|
|
27588
|
-
const dirs =
|
|
28302
|
+
const dirs = existsSync34(catalogDir) ? readdirSync11(catalogDir).filter((d) => statSync10(join38(catalogDir, d)).isDirectory()) : [];
|
|
27589
28303
|
if (dirs.length === 0) io2.out("The catalog is empty.");
|
|
27590
28304
|
for (const d of dirs.sort()) {
|
|
27591
|
-
const r = inspectPlugin(
|
|
28305
|
+
const r = inspectPlugin(join38(catalogDir, d));
|
|
27592
28306
|
if (!r.ok) {
|
|
27593
28307
|
io2.out(`${d} (invalid: ${r.error})`);
|
|
27594
28308
|
continue;
|
|
@@ -27604,7 +28318,7 @@ async function pluginCommand(args, io2, deps = {}) {
|
|
|
27604
28318
|
}
|
|
27605
28319
|
const db = openDb(io2.dataDir);
|
|
27606
28320
|
try {
|
|
27607
|
-
const plugins = new Plugins(db,
|
|
28321
|
+
const plugins = new Plugins(db, join38(io2.dataDir, "plugins"));
|
|
27608
28322
|
if (sub === "list") {
|
|
27609
28323
|
const all = plugins.list();
|
|
27610
28324
|
if (all.length === 0) io2.out("No plugins installed. See: friend plugin catalog");
|
|
@@ -27618,8 +28332,8 @@ async function pluginCommand(args, io2, deps = {}) {
|
|
|
27618
28332
|
io2.err(USAGE2);
|
|
27619
28333
|
return 1;
|
|
27620
28334
|
}
|
|
27621
|
-
const inCatalog = !/[\\/]/.test(arg) &&
|
|
27622
|
-
const source = inCatalog ?
|
|
28335
|
+
const inCatalog = !/[\\/]/.test(arg) && existsSync34(join38(catalogDir, arg));
|
|
28336
|
+
const source = inCatalog ? join38(catalogDir, arg) : existsSync34(resolve10(arg)) ? resolve10(arg) : null;
|
|
27623
28337
|
if (!source) {
|
|
27624
28338
|
io2.err(`"${arg}" is not in the catalog and there is no such folder. See: friend plugin catalog`);
|
|
27625
28339
|
return 1;
|
|
@@ -27674,7 +28388,7 @@ async function pluginCommand(args, io2, deps = {}) {
|
|
|
27674
28388
|
|
|
27675
28389
|
// ../agent-cli/src/commands/onboard/index.ts
|
|
27676
28390
|
import crossSpawn4 from "cross-spawn";
|
|
27677
|
-
import { mkdirSync as
|
|
28391
|
+
import { mkdirSync as mkdirSync26 } from "node:fs";
|
|
27678
28392
|
import { resolve as resolve11 } from "node:path";
|
|
27679
28393
|
|
|
27680
28394
|
// ../agent-cli/src/commands/ollama.ts
|
|
@@ -27997,16 +28711,16 @@ function installPlan(id2, platform, have) {
|
|
|
27997
28711
|
}
|
|
27998
28712
|
|
|
27999
28713
|
// ../agent-cli/src/commands/onboard/state.ts
|
|
28000
|
-
import { existsSync as
|
|
28001
|
-
import { dirname as dirname14, join as
|
|
28714
|
+
import { existsSync as existsSync35, mkdirSync as mkdirSync25, readFileSync as readFileSync25, renameSync as renameSync6, rmSync as rmSync15, writeFileSync as writeFileSync28 } from "node:fs";
|
|
28715
|
+
import { dirname as dirname14, join as join39 } from "node:path";
|
|
28002
28716
|
var FEATURES = ["claude-code", "claude-api", "ollama", "voice", "sandbox"];
|
|
28003
28717
|
var emptyState = () => ({ version: 1, done: {}, features: [], restart: [] });
|
|
28004
|
-
var statePath = (dataDir) =>
|
|
28718
|
+
var statePath = (dataDir) => join39(dataDir, "onboarding.json");
|
|
28005
28719
|
function loadState(dataDir) {
|
|
28006
28720
|
const f = statePath(dataDir);
|
|
28007
|
-
if (!
|
|
28721
|
+
if (!existsSync35(f)) return emptyState();
|
|
28008
28722
|
try {
|
|
28009
|
-
const raw = JSON.parse(
|
|
28723
|
+
const raw = JSON.parse(readFileSync25(f, "utf8"));
|
|
28010
28724
|
const done = raw.done && typeof raw.done === "object" ? Object.fromEntries(Object.entries(raw.done).filter(([, v]) => typeof v === "string")) : {};
|
|
28011
28725
|
const features2 = Array.isArray(raw.features) ? raw.features.filter((x) => FEATURES.includes(x)) : [];
|
|
28012
28726
|
const restart = Array.isArray(raw.restart) ? raw.restart.filter((x) => typeof x === "string") : [];
|
|
@@ -28017,10 +28731,10 @@ function loadState(dataDir) {
|
|
|
28017
28731
|
}
|
|
28018
28732
|
function saveState(dataDir, state) {
|
|
28019
28733
|
const f = statePath(dataDir);
|
|
28020
|
-
|
|
28734
|
+
mkdirSync25(dirname14(f), { recursive: true });
|
|
28021
28735
|
const tmp = `${f}.tmp`;
|
|
28022
|
-
|
|
28023
|
-
|
|
28736
|
+
writeFileSync28(tmp, JSON.stringify(state, null, 2));
|
|
28737
|
+
renameSync6(tmp, f);
|
|
28024
28738
|
}
|
|
28025
28739
|
function resetState(dataDir) {
|
|
28026
28740
|
rmSync15(statePath(dataDir), { force: true });
|
|
@@ -28375,7 +29089,7 @@ async function workspace(c) {
|
|
|
28375
29089
|
const answer = await text4(c.ui, current ? "Workspace folder" : "Workspace folder (Enter to skip)", current ?? "");
|
|
28376
29090
|
if (answer) {
|
|
28377
29091
|
const abs = resolve11(answer);
|
|
28378
|
-
|
|
29092
|
+
mkdirSync26(abs, { recursive: true });
|
|
28379
29093
|
cfg.roots = [abs];
|
|
28380
29094
|
saveConfig(cfg);
|
|
28381
29095
|
io2.out(`Workspace: ${abs}`);
|
|
@@ -28629,8 +29343,8 @@ async function usageCommand(args, io2, log) {
|
|
|
28629
29343
|
}
|
|
28630
29344
|
|
|
28631
29345
|
// ../agent-cli/src/commands/audit.ts
|
|
28632
|
-
import { writeFileSync as
|
|
28633
|
-
import { join as
|
|
29346
|
+
import { writeFileSync as writeFileSync29 } from "node:fs";
|
|
29347
|
+
import { join as join40 } from "node:path";
|
|
28634
29348
|
var USAGE5 = [
|
|
28635
29349
|
"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
29350
|
" friend audit show <request-id>",
|
|
@@ -28735,7 +29449,7 @@ async function auditCommand(args, io2, deps = {}) {
|
|
|
28735
29449
|
afterwards = async (res2) => {
|
|
28736
29450
|
const raw = /filename="([^"]+)"/.exec(res2.headers.get("content-disposition") ?? "")?.[1] ?? `friend-audit.${f.query.format}`;
|
|
28737
29451
|
const name = (raw.split(/[\\/]/).pop() ?? "friend-audit").replace(/[^A-Za-z0-9._-]/g, "_") || "friend-audit";
|
|
28738
|
-
(deps.write ?? ((n2, b) =>
|
|
29452
|
+
(deps.write ?? ((n2, b) => writeFileSync29(join40(process.cwd(), n2), b)))(name, await res2.text());
|
|
28739
29453
|
io2.out(`Saved ${name} in this folder. It contains private content: keep it safe.`);
|
|
28740
29454
|
return 0;
|
|
28741
29455
|
};
|
|
@@ -28763,9 +29477,9 @@ async function auditCommand(args, io2, deps = {}) {
|
|
|
28763
29477
|
|
|
28764
29478
|
// ../agent-cli/src/commands/daemon.ts
|
|
28765
29479
|
import { spawn as spawn14, spawnSync as spawnSync3 } from "node:child_process";
|
|
28766
|
-
import { closeSync as closeSync2, existsSync as
|
|
29480
|
+
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
29481
|
import { connect } from "node:net";
|
|
28768
|
-
import { join as
|
|
29482
|
+
import { join as join41 } from "node:path";
|
|
28769
29483
|
var USAGE6 = "Usage: friend daemon start | stop | restart | status";
|
|
28770
29484
|
var MAX_LOG_BYTES = 5 * 1024 * 1024;
|
|
28771
29485
|
var sleep2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
|
|
@@ -28821,11 +29535,11 @@ var realDeps = {
|
|
|
28821
29535
|
},
|
|
28822
29536
|
now: Date.now
|
|
28823
29537
|
};
|
|
28824
|
-
var pidFile = (dataDir) =>
|
|
28825
|
-
var logFileOf = (dataDir) =>
|
|
29538
|
+
var pidFile = (dataDir) => join41(dataDir, "friend.pid");
|
|
29539
|
+
var logFileOf = (dataDir) => join41(dataDir, "friend.log");
|
|
28826
29540
|
function readPid(dataDir) {
|
|
28827
29541
|
try {
|
|
28828
|
-
const r = JSON.parse(
|
|
29542
|
+
const r = JSON.parse(readFileSync26(pidFile(dataDir), "utf8"));
|
|
28829
29543
|
return Number.isInteger(r.pid) && r.pid > 0 ? r : null;
|
|
28830
29544
|
} catch {
|
|
28831
29545
|
return null;
|
|
@@ -28856,10 +29570,10 @@ async function start(io2, deps) {
|
|
|
28856
29570
|
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
29571
|
return 1;
|
|
28858
29572
|
}
|
|
28859
|
-
|
|
29573
|
+
mkdirSync27(io2.dataDir, { recursive: true });
|
|
28860
29574
|
const log = logFileOf(io2.dataDir);
|
|
28861
29575
|
try {
|
|
28862
|
-
if (
|
|
29576
|
+
if (existsSync36(log) && statSync11(log).size > MAX_LOG_BYTES) renameSync7(log, `${log}.old`);
|
|
28863
29577
|
} catch {
|
|
28864
29578
|
}
|
|
28865
29579
|
const pid = deps.launch(log);
|
|
@@ -28867,7 +29581,7 @@ async function start(io2, deps) {
|
|
|
28867
29581
|
io2.err("Could not start Friend in the background.");
|
|
28868
29582
|
return 1;
|
|
28869
29583
|
}
|
|
28870
|
-
|
|
29584
|
+
writeFileSync30(pidFile(io2.dataDir), JSON.stringify({ pid, startedAt: deps.now() }));
|
|
28871
29585
|
for (let i = 0; i < 60; i++) {
|
|
28872
29586
|
if (await deps.portOpen(cfg.port, 300)) {
|
|
28873
29587
|
io2.out(`Friend is running in the background (pid ${pid}) at ${urls.local}`);
|
|
@@ -28933,10 +29647,10 @@ async function daemonCommand(args, io2, deps = realDeps) {
|
|
|
28933
29647
|
// ../agent-cli/src/commands/upgrade.ts
|
|
28934
29648
|
import crossSpawn5 from "cross-spawn";
|
|
28935
29649
|
import { appendFileSync } from "node:fs";
|
|
28936
|
-
import { join as
|
|
29650
|
+
import { join as join42 } from "node:path";
|
|
28937
29651
|
var PACKAGE2 = "friend-assistant";
|
|
28938
29652
|
var real2 = {
|
|
28939
|
-
current: () => true ? "0.1.
|
|
29653
|
+
current: () => true ? "0.1.91" : "development",
|
|
28940
29654
|
latest: () => new Promise((resolve13) => {
|
|
28941
29655
|
const child = crossSpawn5("npm", ["view", PACKAGE2, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
|
|
28942
29656
|
let out = "";
|
|
@@ -28974,7 +29688,7 @@ async function upgradeCommand(args, io0, deps = real2) {
|
|
|
28974
29688
|
io0.err("Usage: friend upgrade [--force] [--auto]");
|
|
28975
29689
|
return 1;
|
|
28976
29690
|
}
|
|
28977
|
-
const log = deps.log ?? ((line2) => appendFileSync(
|
|
29691
|
+
const log = deps.log ?? ((line2) => appendFileSync(join42(io0.dataDir, "update.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
|
|
28978
29692
|
`));
|
|
28979
29693
|
const io2 = auto ? {
|
|
28980
29694
|
...io0,
|
|
@@ -29092,7 +29806,7 @@ async function claudeCommand(args, io2, deps = {}) {
|
|
|
29092
29806
|
}
|
|
29093
29807
|
|
|
29094
29808
|
// ../agent-cli/src/commands/setup.ts
|
|
29095
|
-
import { mkdirSync as
|
|
29809
|
+
import { mkdirSync as mkdirSync28 } from "node:fs";
|
|
29096
29810
|
import { resolve as resolve12 } from "node:path";
|
|
29097
29811
|
async function setupCommand3(io2) {
|
|
29098
29812
|
const db = openDb(io2.dataDir);
|
|
@@ -29118,7 +29832,7 @@ async function setupCommand3(io2) {
|
|
|
29118
29832
|
const cfg = loadConfig(io2.dataDir);
|
|
29119
29833
|
if (workspace2) {
|
|
29120
29834
|
const abs = resolve12(workspace2);
|
|
29121
|
-
|
|
29835
|
+
mkdirSync28(abs, { recursive: true });
|
|
29122
29836
|
cfg.roots = [abs];
|
|
29123
29837
|
}
|
|
29124
29838
|
if (apiKey) cfg.apiKey = apiKey;
|
|
@@ -29254,7 +29968,7 @@ async function run(argv, io2) {
|
|
|
29254
29968
|
case "version":
|
|
29255
29969
|
case "--version":
|
|
29256
29970
|
case "-v":
|
|
29257
|
-
io2.out(true ? "0.1.
|
|
29971
|
+
io2.out(true ? "0.1.91" : "development");
|
|
29258
29972
|
return 0;
|
|
29259
29973
|
case "lan":
|
|
29260
29974
|
return await lanCommand(rest, io2);
|