-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathruntime.ts
More file actions
512 lines (462 loc) · 17.8 KB
/
Copy pathruntime.ts
File metadata and controls
512 lines (462 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import { spawn } from "node:child_process";
import { closeSync, existsSync, mkdirSync, openSync, statSync, renameSync } from "node:fs";
import { join } from "node:path";
import { getSettingsSnapshot } from "../settings.js";
import { isLockStale, killStaleDaemonPid, removeStaleLock } from "./stale-version.js";
import {
disableDaemonTunnel,
enableDaemonTunnel,
ensureDaemon,
exportHistoryViaDaemon,
getDaemonStatus,
getAuditLogPath,
getLockfilePath,
getTunnelBinaryPath,
hydrateCloudHistoryEntryViaDaemon,
installCloudflared,
listOAuthClients,
listOAuthConsents,
readAuditTail,
read as readDaemonLock,
restartDaemon,
revokeAllOAuthClients,
revokeAllOAuthConsents,
revokeOAuthClient,
revokeOAuthConsent,
rotateDaemonToken,
stopDaemon,
syncCloudHistoryViaDaemon,
type AuthorizedClientSummary,
type ConsentEntrySummary,
type DaemonCloudSyncProgress,
type DaemonCloudSyncResult,
type DaemonExportResult,
type DaemonHydrateResult,
type InstallTunnelResult,
} from "perplexity-user-mcp/daemon";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore — subpath export from mcp-server daemon bundle
import {
listTunnelProviderStatuses,
readTunnelSettings,
writeTunnelSettings,
readNgrokSettings,
writeNgrokSettings,
clearNgrokSettings,
runCloudflaredLogin,
listNamedTunnels,
createNamedTunnel,
deleteNamedTunnel,
clearNamedTunnelConfig,
writeTunnelConfig,
readNamedTunnelConfig,
type TunnelProviderId,
type TunnelProviderStatus,
type NgrokSettings,
type CloudflaredLoginResult,
type NamedTunnelSummary,
type CreatedTunnel,
type NamedTunnelConfig,
type DeletedNamedTunnel,
} from "perplexity-user-mcp/daemon/tunnel-providers";
import { existsSync as fsExistsSync } from "node:fs";
import { homedir } from "node:os";
import { join as pathJoin } from "node:path";
const DAEMON_LOG_MAX_BYTES = 2 * 1024 * 1024;
interface RuntimeConfig {
configDir: string;
serverPath: string;
/** Bundled mcp-server version (extension and mcp-server are versioned together). */
bundledVersion: string;
/** Optional logger; falls back to a no-op for tests / pre-init paths. */
log?: (line: string) => void;
/**
* Async provider returning env vars to merge into the daemon's spawn env.
* Called once per spawn (no caching). Implementations live in extension.ts
* and may read VS Code SecretStorage; this seam keeps daemon/runtime.ts
* free of any vscode import.
*
* Returned keys will be merged AFTER process.env and BEFORE the hard-coded
* overrides (ELECTRON_RUN_AS_NODE / PERPLEXITY_CONFIG_DIR / ...), so the
* provider cannot accidentally override critical spawn env. (Merge logic
* itself is added in a follow-up task; this task only declares the type.)
*/
buildDaemonEnv?: () => Promise<Record<string, string>>;
}
let runtimeConfig: RuntimeConfig | null = null;
export function configureDaemonRuntime(config: RuntimeConfig): void {
runtimeConfig = config;
}
/**
* If a daemon.lock exists with a `version` that doesn't match the bundled
* version, the running daemon was launched by a previous extension version
* and is pinned to chunk filenames that no longer exist on disk. SIGTERM the
* pid and remove the lock so the existing ensure-loop falls through to the
* spawn path. See [stale-version.ts] for the rule.
*/
function reapStaleVersionedDaemon(config: RuntimeConfig): void {
const lockPath = getLockfilePath(config.configDir);
let lock: { pid: number; version: string } | null = null;
try {
lock = readDaemonLock({ lockPath }) as { pid: number; version: string } | null;
} catch {
return; // corrupt JSON — existing flow handles it
}
if (!lock) return;
if (!isLockStale(lock, config.bundledVersion)) return;
const log = config.log ?? (() => undefined);
log(`[daemon] stale daemon detected (lock=v${lock.version ?? "unknown"}, bundled=v${config.bundledVersion}) — restarting`);
killStaleDaemonPid(lock.pid, log);
removeStaleLock(lockPath);
}
export async function ensureBundledDaemon(options: { startTimeoutMs?: number } = {}) {
const config = requireRuntimeConfig();
reapStaleVersionedDaemon(config);
return ensureDaemon({
configDir: config.configDir,
spawnDaemon: spawnBundledDaemon,
treatSelfAsZombie: true,
...(options.startTimeoutMs !== undefined ? { startTimeoutMs: options.startTimeoutMs } : {}),
});
}
export async function exportHistoryFromDaemon(historyId: string, format: "pdf" | "markdown" | "docx"): Promise<DaemonExportResult> {
const config = requireRuntimeConfig();
return exportHistoryViaDaemon(historyId, format, {
configDir: config.configDir,
spawnDaemon: spawnBundledDaemon,
});
}
export async function syncCloudHistoryFromDaemon(
onProgress: (progress: DaemonCloudSyncProgress) => void,
options: { pageSize?: number } = {},
): Promise<DaemonCloudSyncResult> {
const config = requireRuntimeConfig();
return syncCloudHistoryViaDaemon({
configDir: config.configDir,
spawnDaemon: spawnBundledDaemon,
pageSize: options.pageSize,
onProgress,
});
}
export async function hydrateCloudEntryFromDaemon(historyId: string): Promise<DaemonHydrateResult> {
const config = requireRuntimeConfig();
return hydrateCloudHistoryEntryViaDaemon(historyId, {
configDir: config.configDir,
spawnDaemon: spawnBundledDaemon,
});
}
export async function getBundledDaemonStatus() {
const config = requireRuntimeConfig();
return getDaemonStatus({
configDir: config.configDir,
reclaimStale: true,
});
}
export async function rotateBundledDaemonToken() {
const config = requireRuntimeConfig();
return rotateDaemonToken({ configDir: config.configDir });
}
export async function restartBundledDaemon() {
const config = requireRuntimeConfig();
return restartDaemon({
configDir: config.configDir,
spawnDaemon: spawnBundledDaemon,
treatSelfAsZombie: true,
});
}
export async function killBundledDaemon() {
const config = requireRuntimeConfig();
// force=true escalates to SIGTERM/SIGKILL + lockfile release if the
// daemon doesn't respond to the graceful /daemon/shutdown.
return stopDaemon({ configDir: config.configDir, force: true, waitTimeoutMs: 3_000 });
}
export async function enableBundledDaemonTunnel() {
const config = requireRuntimeConfig();
return enableDaemonTunnel({ configDir: config.configDir });
}
export async function disableBundledDaemonTunnel() {
const config = requireRuntimeConfig();
return disableDaemonTunnel({ configDir: config.configDir });
}
export function isCloudflaredInstalled(): boolean {
const config = requireRuntimeConfig();
return existsSync(getTunnelBinaryPath(config.configDir));
}
export async function installBundledCloudflared(): Promise<InstallTunnelResult> {
const config = requireRuntimeConfig();
return installCloudflared({ configDir: config.configDir });
}
export async function listBundledTunnelProviders(): Promise<TunnelProviderStatus[]> {
const config = requireRuntimeConfig();
return listTunnelProviderStatuses(config.configDir);
}
export function getBundledActiveTunnelProvider(): TunnelProviderId {
const config = requireRuntimeConfig();
return readTunnelSettings(config.configDir).activeProvider;
}
export function setBundledActiveTunnelProvider(id: TunnelProviderId): TunnelProviderId {
const config = requireRuntimeConfig();
const next = writeTunnelSettings(config.configDir, { activeProvider: id });
return next.activeProvider;
}
export function getBundledNgrokSettings(): { configured: boolean; domain?: string; updatedAt?: string } {
const config = requireRuntimeConfig();
const settings = readNgrokSettings(config.configDir);
if (!settings) return { configured: false };
return {
configured: true,
...(settings.domain ? { domain: settings.domain } : {}),
updatedAt: settings.updatedAt,
};
}
export function setBundledNgrokAuthtoken(authtoken: string): NgrokSettings {
const config = requireRuntimeConfig();
return writeNgrokSettings(config.configDir, { authtoken });
}
export function setBundledNgrokDomain(domain: string | null): NgrokSettings {
const config = requireRuntimeConfig();
return writeNgrokSettings(config.configDir, { domain });
}
export function clearBundledNgrokSettings(): void {
const config = requireRuntimeConfig();
clearNgrokSettings(config.configDir);
}
// ─────────────────────────────────────────────────────────────────────
// cf-named (cloudflared named-tunnel) setup wrappers — 8.4.3
// ─────────────────────────────────────────────────────────────────────
/**
* Spawn `cloudflared tunnel login` on the host. Opens the user's default
* browser so they can authorize the cert that lands at
* `~/.cloudflared/cert.pem`. Resolves once the cert is observed.
*/
export async function runCfNamedLogin(
options: { signal?: AbortSignal } = {},
): Promise<CloudflaredLoginResult> {
const config = requireRuntimeConfig();
return runCloudflaredLogin({
configDir: config.configDir,
...(options.signal ? { signal: options.signal } : {}),
});
}
/**
* List all cloudflared tunnels visible to the user's origin cert. Read-only;
* no side effects. Used by the UI's "bind existing tunnel" alternative.
*/
export async function listCfNamedTunnels(): Promise<NamedTunnelSummary[]> {
const config = requireRuntimeConfig();
return listNamedTunnels({ configDir: config.configDir });
}
export async function deleteCfNamedTunnel(uuid: string): Promise<DeletedNamedTunnel> {
const config = requireRuntimeConfig();
return deleteNamedTunnel({ configDir: config.configDir, uuid });
}
/**
* Either create a fresh tunnel (runs `cloudflared tunnel create` + DNS route)
* OR bind the managed YAML to an existing tunnel UUID the user already set up
* by hand. The "bind-existing" branch skips both network calls and just
* rewrites `<configDir>/cloudflared-named.yml`.
*
* For bind-existing we require the `~/.cloudflared/<uuid>.json` credentials
* file to exist up front; cloudflared would fail later with a cryptic error if
* it's missing and the YAML would persist a broken config.
*
* Port is pinned to 1 as a placeholder — the provider's start() rewrites the
* port on every spawn (port-drift rewrite). The YAML is worthless until
* start() runs anyway, so the placeholder never leaks.
*/
export async function createCfNamedTunnel(params: {
mode: "create" | "bind-existing";
name?: string;
hostname: string;
uuid?: string;
}): Promise<CreatedTunnel | NamedTunnelConfig> {
const config = requireRuntimeConfig();
if (!params.hostname) throw new Error("hostname is required.");
if (params.mode === "bind-existing") {
const uuid = (params.uuid ?? "").trim();
if (!uuid) throw new Error("uuid is required for bind-existing mode.");
const credentialsPath = pathJoin(homedir(), ".cloudflared", `${uuid}.json`);
if (!fsExistsSync(credentialsPath)) {
throw new Error(
`Credentials file not found at ${credentialsPath}. Run "cloudflared tunnel create" for this UUID first, or switch to "create" mode.`,
);
}
return writeTunnelConfig({
configDir: config.configDir,
uuid,
hostname: params.hostname,
// Placeholder port. The provider's start() rewrites this to the live
// daemon port on every spawn, so the value we persist here is never read.
port: 1,
credentialsPath,
});
}
// mode === "create"
const name = (params.name ?? "").trim();
if (!name) throw new Error("name is required for create mode.");
const created = await createNamedTunnel({
configDir: config.configDir,
name,
hostname: params.hostname,
});
// Wire the newly-created tunnel into the managed YAML so the next daemon
// start picks it up without a second UI round-trip.
writeTunnelConfig({
configDir: config.configDir,
uuid: created.uuid,
hostname: params.hostname,
port: 1,
credentialsPath: created.credentialsPath,
});
return created;
}
/** Read the managed cf-named YAML, or null if not configured. */
export async function readCfNamedConfig(): Promise<NamedTunnelConfig | null> {
const config = requireRuntimeConfig();
return readNamedTunnelConfig(config.configDir);
}
export function clearCfNamedConfig(): boolean {
const config = requireRuntimeConfig();
return clearNamedTunnelConfig(config.configDir);
}
export function getBundledCfNamedState(): {
config: { uuid: string; hostname: string; configPath: string; credentialsPresent: boolean } | null;
} {
const config = requireRuntimeConfig();
const managed = readNamedTunnelConfig(config.configDir);
if (!managed) return { config: null };
return {
config: {
uuid: managed.uuid,
hostname: managed.hostname,
configPath: managed.configPath,
credentialsPresent: fsExistsSync(managed.credentialsPath),
},
};
}
export function readBundledDaemonAuditTail(limit = 50) {
const config = requireRuntimeConfig();
return readAuditTail(limit, { auditPath: getAuditLogPath(config.configDir) });
}
export async function listBundledOAuthConsents(): Promise<ConsentEntrySummary[]> {
const config = requireRuntimeConfig();
return listOAuthConsents({ configDir: config.configDir });
}
export async function revokeBundledOAuthConsent(clientId: string, redirectUri?: string): Promise<number> {
const config = requireRuntimeConfig();
return revokeOAuthConsent(clientId, redirectUri, { configDir: config.configDir });
}
export async function revokeAllBundledOAuthConsents(): Promise<number> {
const config = requireRuntimeConfig();
return revokeAllOAuthConsents({ configDir: config.configDir });
}
export async function listBundledOAuthClients(): Promise<AuthorizedClientSummary[]> {
const config = requireRuntimeConfig();
return listOAuthClients({ configDir: config.configDir });
}
export async function revokeBundledOAuthClient(clientId: string): Promise<boolean> {
const config = requireRuntimeConfig();
return revokeOAuthClient(clientId, { configDir: config.configDir });
}
export async function revokeAllBundledOAuthClients(): Promise<number> {
const config = requireRuntimeConfig();
return revokeAllOAuthClients({ configDir: config.configDir });
}
export function getBundledDaemonConfigDir(): string {
return requireRuntimeConfig().configDir;
}
function requireRuntimeConfig(): RuntimeConfig {
if (!runtimeConfig) {
throw new Error("Daemon runtime has not been configured yet.");
}
return runtimeConfig;
}
async function spawnBundledDaemon(options: { configDir: string; host?: string; port?: number; tunnel?: boolean }): Promise<void> {
const config = requireRuntimeConfig();
const args = [config.serverPath, "daemon", "start"];
if (typeof options.port === "number") {
args.push("--port", String(options.port));
}
if (options.tunnel) {
args.push("--tunnel");
}
const logFd = openDaemonLogFd(options.configDir);
let consentTtlHours = 24;
try {
consentTtlHours = getSettingsSnapshot().oauthConsentCacheTtlHours;
} catch {
// settings unavailable outside the extension host — fall back to default
}
let extraEnv: Record<string, string> = {};
if (config.buildDaemonEnv) {
try {
const provided = await config.buildDaemonEnv();
if (provided && typeof provided === "object") {
for (const [k, v] of Object.entries(provided)) {
if (typeof k === "string" && typeof v === "string") {
extraEnv[k] = v;
} else {
(config.log ?? (() => undefined))(
`[daemon] buildDaemonEnv produced non-string entry for ${String(k)}; ignored`,
);
}
}
}
} catch (err) {
(config.log ?? (() => undefined))(
`[daemon] buildDaemonEnv threw: ${err instanceof Error ? err.message : String(err)}; spawning without overlay`,
);
}
}
// Telemetry: log only the SET/UNSET status of vault passphrase, never the value.
(config.log ?? (() => undefined))(
`[daemon] PERPLEXITY_VAULT_PASSPHRASE: ${extraEnv.PERPLEXITY_VAULT_PASSPHRASE ? "set" : "unset"}`,
);
// Strip launcher-scoped flags that must never reach the daemon's own
// PerplexityClient.init() — they would force headless mode or stdio bypass.
const baseEnv = { ...process.env };
delete baseEnv.PERPLEXITY_HEADLESS_ONLY;
delete baseEnv.PERPLEXITY_NO_DAEMON;
const child = spawn(process.execPath, args, {
detached: true,
stdio: ["ignore", logFd, logFd],
env: {
...baseEnv,
...extraEnv,
// Hard-coded overrides — must come AFTER extraEnv so a buggy provider
// cannot clobber them.
// Critical: process.execPath inside a VS Code extension host points at
// Electron, not Node. Without this flag Electron ignores the JS script
// and starts a GUI session. ELECTRON_RUN_AS_NODE=1 tells the same
// binary to behave as a pure Node runtime for this child.
ELECTRON_RUN_AS_NODE: "1",
PERPLEXITY_CONFIG_DIR: options.configDir,
PERPLEXITY_OAUTH_CONSENT_TTL_HOURS: String(consentTtlHours),
},
});
closeSync(logFd);
child.on("error", (err) => {
try {
const extraFd = openDaemonLogFd(options.configDir);
const message = `\n[trace] spawnBundledDaemon error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`;
require("node:fs").writeSync(extraFd, message);
closeSync(extraFd);
} catch {
// logging best-effort
}
});
child.unref();
}
function openDaemonLogFd(configDir: string): number {
mkdirSync(configDir, { recursive: true });
const logPath = join(configDir, "daemon.log");
try {
const stat = statSync(logPath);
if (stat.size > DAEMON_LOG_MAX_BYTES) {
renameSync(logPath, logPath + ".1");
}
} catch {
// fresh log
}
return openSync(logPath, "a");
}