This repository was archived by the owner on May 6, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1628 lines (1483 loc) · 67 KB
/
Copy pathindex.ts
File metadata and controls
1628 lines (1483 loc) · 67 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
import { existsSync, readFileSync, writeFileSync, appendFileSync, rmSync, realpathSync, mkdirSync, cpSync } from "fs";
import { createHash } from "crypto";
import { join, resolve, dirname, isAbsolute } from "path";
import { homedir } from "os";
import { execSync, spawn, spawnSync } from "child_process";
import { createRequire } from "module";
import { runSetup, type SetupContext, type CursorModel, detectCursorPath, detectOutputFormat, discoverCursorModels } from "./src/setup.js";
import { runDoctorChecks, formatDoctorResults, countDiscoveredTools } from "./src/doctor.js";
import { PLUGIN_ID, PROVIDER_ID, DEFAULT_PROXY_PORT, parseProxyPort, OPENCLAW_CONFIG_PATH, OPENCLAW_LOGS_DIR, CURSOR_PROXY_PID_PATH, CURSOR_PROXY_LOG_PATH, CURSOR_PROXY_STDERR_LOG_PATH, getCursorMcpConfigPath, type OutputFormat } from "./src/constants.js";
let proxyChild: ReturnType<typeof spawn> | null = null;
let proxyRestartCount = 0;
let lastProxyStartTime = 0;
let healthCheckTimer: ReturnType<typeof setInterval> | null = null;
/** Ensures only one startProxy run at a time (no concurrent kill+spawn from register + health + exit). */
let startProxyInProgress = false;
/** So we only show "gateway restart" outro once per process (avoid duplicate when both runInteractiveSetupInProcess and setup command run). */
let gatewayRestartOutroShown = false;
const MAX_PROXY_RESTARTS = 3;
const PROXY_RESTART_DELAYS = [2000, 10000, 60000];
const PROXY_STABLE_PERIOD = 300000;
const HEALTH_CHECK_INTERVAL = 60000; // 60s
// @clack/prompts lives in openclaw's node_modules; follow the bin symlink to resolve
let _clack: any;
function loadClack() {
if (_clack) return _clack;
let entry = process.argv[1] || __filename;
try { entry = realpathSync(entry); } catch {}
_clack = createRequire(entry)("@clack/prompts");
return _clack;
}
function fetchProxyHealth(port: number, timeoutMs = 5000): Record<string, any> | null {
try {
const cmd = process.platform === "win32"
? `node -e "fetch('http://127.0.0.1:${port}/v1/health').then(r=>r.text()).then(t=>process.stdout.write(t)).catch(()=>process.stdout.write('{}'))"`
: `curl -sf http://127.0.0.1:${port}/v1/health`;
const raw = execSync(cmd, { encoding: "utf-8", timeout: timeoutMs, stdio: ["pipe", "pipe", "pipe"] });
return JSON.parse(raw);
} catch {
return null;
}
}
function isProxyRunning(port: number): boolean {
return fetchProxyHealth(port) !== null;
}
/** True if any process is listening on the port (lsof/netstat). More reliable than isProxyRunning when health check times out. */
function portHasProcess(port: number): boolean {
try {
if (process.platform === "win32") {
const out = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, {
encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
}).trim();
return out.length > 0;
}
const out = execSync(`lsof -ti :${port}`, { encoding: "utf-8", timeout: 3000, stdio: ["pipe", "pipe", "pipe"] }).trim();
return out.length > 0;
} catch {
return false;
}
}
/** Kill one PID via system kill/taskkill in a subprocess. Used when running inside gateway daemon where process.kill may be restricted. */
function killPidBySubprocess(pid: number): void {
if (!Number.isFinite(pid) || pid <= 0) return;
try {
if (process.platform === "win32") {
execSync(`taskkill /F /PID ${pid}`, { encoding: "utf-8", stdio: "pipe", timeout: 5000 });
} else {
spawnSync("kill", ["-9", String(pid)], { stdio: "pipe", timeout: 5000 });
}
} catch {}
}
/** @param signal Default SIGTERM; use "SIGKILL" to force-immediate exit (releases port without graceful shutdown). */
function killPortProcess(port: number, signal: "SIGTERM" | "SIGKILL" = "SIGTERM") {
try {
if (process.platform === "win32") {
const out = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, {
encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
}).trim();
const pids = new Set(out.split("\n").map(l => l.trim().split(/\s+/).pop()).filter(Boolean));
for (const pid of pids) {
const n = parseInt(pid!, 10);
if (Number.isFinite(n)) killPidBySubprocess(n);
}
} else {
const out = execSync(`lsof -ti :${port}`, { encoding: "utf-8", timeout: 3000, stdio: ["pipe", "pipe", "pipe"] }).trim();
if (out) {
for (const pid of out.split("\n")) {
const n = parseInt(pid, 10);
if (Number.isFinite(n)) killPidBySubprocess(n);
}
}
}
} catch {}
}
function computeFileHash(filePath: string): string {
try {
const content = readFileSync(filePath, "utf-8");
return createHash("sha256").update(content).digest("hex").slice(0, 12);
} catch { return "unknown"; }
}
/** Run interactive setup (model selection + plugin config) in the same process during install. Blocks until user completes; re-applies in setImmediate after core may overwrite. */
async function runInteractiveSetupInProcess(opts: {
pluginDir: string;
config: Record<string, any>;
pluginConfig: Record<string, unknown>;
result: { cursorPath: string; cursorModels: CursorModel[]; outputFormat: OutputFormat };
proxyPort: number;
}): Promise<void> {
const clack = loadClack();
clack.intro(`Cursor Brain Setup (v${readPackageVersion(opts.pluginDir)})`);
const currentModel = (opts.config.agents as any)?.defaults?.model;
const curPrimary = currentModel?.primary?.replace(`${PROVIDER_ID}/`, "");
const curFallbacks = (currentModel?.fallbacks as string[] | undefined)?.map((f: string) => f.replace(`${PROVIDER_ID}/`, ""));
const selection = await promptModelSelection(opts.result.cursorModels, curPrimary, curFallbacks);
if (selection) {
try {
saveModelSelection(selection.primary, selection.fallbacks, opts.proxyPort, opts.result.cursorModels);
clack.log.success("Model configuration saved to openclaw.json (agents.defaults.model + providers)");
} catch (e: any) {
clack.log.error(`Could not save model config: ${e?.message ?? String(e)}`);
}
}
const configResult = await promptPluginConfig(opts.pluginConfig as Record<string, unknown>);
if (configResult) {
try {
mergePluginConfig(configResult);
clack.log.success("Plugin configuration saved to openclaw.json");
} catch (e: any) {
clack.log.error(`Could not save config: ${e?.message ?? String(e)}`);
}
}
try {
syncPluginInstallRecord({ installPath: opts.pluginDir, updateTimestamp: false, preservedConfig: configResult ?? undefined });
} catch {}
const savedSelection = selection;
const savedPluginConfig = configResult;
setImmediate(() => {
fixInstallRecordSourceOnDisk(opts.pluginDir);
if (savedSelection) saveModelSelection(savedSelection.primary, savedSelection.fallbacks, opts.proxyPort, opts.result.cursorModels);
if (savedPluginConfig) mergePluginConfig(savedPluginConfig);
});
if (!gatewayRestartOutroShown) {
gatewayRestartOutroShown = true;
clack.outro("Run `openclaw gateway restart` (or restart your gateway) to apply changes.");
}
}
function readPackageVersion(dir: string): string {
try {
return JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")).version || "unknown";
} catch { return "unknown"; }
}
/** Returns 1 if a > b, -1 if a < b, 0 if equal. Non-semver strings compare as equal. */
function compareSemver(a: string, b: string): number {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
if (pa.some(isNaN) || pb.some(isNaN)) return 0;
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const na = pa[i] ?? 0;
const nb = pb[i] ?? 0;
if (na > nb) return 1;
if (na < nb) return -1;
}
return 0;
}
/**
* Keys that must not be stored in plugin config (single source is agents.defaults.model + models.providers).
* Rule: plugins.entries[PLUGIN_ID].config only stores keys that are the single source of truth and directly used; no duplication of data that lives elsewhere.
*/
const PLUGIN_CONFIG_EXCLUDE_KEYS = new Set(["model", "fallbackModel"]);
/** Build minimal env for proxy child to avoid spreading full process.env (reduces security-scan "env + network" warning). */
function buildProxyChildEnv(vars: {
CURSOR_PATH: string;
CURSOR_WORKSPACE_DIR: string;
CURSOR_PROXY_PORT: string;
CURSOR_OUTPUT_FORMAT: string;
CURSOR_PROXY_SCRIPT_HASH: string;
}): NodeJS.ProcessEnv {
const e = process.env;
const env: NodeJS.ProcessEnv = {
PATH: e.PATH ?? "",
HOME: e.HOME ?? e.USERPROFILE ?? "",
USER: e.USER ?? e.USERNAME ?? "",
LANG: e.LANG ?? "en_US.UTF-8",
OPENCLAW_CONFIG_PATH: OPENCLAW_CONFIG_PATH,
...vars,
};
if (process.platform === "win32") {
env.USERPROFILE = e.USERPROFILE ?? env.HOME;
env.SYSTEMROOT = e.SYSTEMROOT ?? "";
env.TEMP = e.TEMP ?? e.TMP ?? "";
}
return env;
}
/**
* Single entry point to start the streaming proxy. Serialized: only one run at a time.
* Flow: kill our child (if any) → kill any process on port → wait until port free → spawn.
*/
function startProxy(opts: {
pluginDir: string;
cursorPath: string;
workspaceDir: string;
port: number;
outputFormat: OutputFormat;
logger: any;
}) {
if (startProxyInProgress) return;
startProxyInProgress = true;
const proxyScript = join(opts.pluginDir, "mcp-server", "streaming-proxy.mjs");
if (!existsSync(proxyScript)) {
startProxyInProgress = false;
return;
}
if (proxyChild) {
try { proxyChild.kill("SIGKILL"); } catch { /* process may already be dead */ }
proxyChild = null;
}
// Kill by PID file using system kill (subprocess). Upgrade runs in CLI so process.kill works; gateway restart runs in daemon where process.kill may be restricted — shell "kill -9" works.
try {
if (existsSync(CURSOR_PROXY_PID_PATH)) {
const pidStr = readFileSync(CURSOR_PROXY_PID_PATH, "utf-8").trim();
const pid = parseInt(pidStr, 10);
if (Number.isFinite(pid) && pid > 0) killPidBySubprocess(pid);
rmSync(CURSOR_PROXY_PID_PATH, { force: true });
}
} catch { /* best-effort kill by PID and remove PID file */ }
killPortProcess(opts.port, "SIGKILL");
const waitMs = 200;
const maxTries = 30;
let portFree = false;
for (let i = 0; i < maxTries; i++) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, waitMs);
if (!portHasProcess(opts.port)) {
portFree = true;
break;
}
}
if (!portFree) {
opts.logger.error(`Port ${opts.port} still in use after ${(maxTries * waitMs) / 1000}s — retrying in 10s`);
startProxyInProgress = false;
setTimeout(() => startProxy(opts), 10_000);
return;
}
// Extra kill + short wait before spawn so port is reliably free (e.g. after gateway restart race).
killPortProcess(opts.port, "SIGKILL");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 500);
if (portHasProcess(opts.port)) {
opts.logger.warn(`Port ${opts.port} still in use before spawn — retrying in 10s`);
startProxyInProgress = false;
setTimeout(() => startProxy(opts), 10_000);
return;
}
try { mkdirSync(OPENCLAW_LOGS_DIR, { recursive: true }); } catch {}
let stderrBuf = "";
const appendProxyStderr = (chunk: string) => {
stderrBuf = (stderrBuf + chunk).slice(-50_000);
try { appendFileSync(CURSOR_PROXY_STDERR_LOG_PATH, chunk); } catch {}
};
try {
const child = spawn("node", [proxyScript], {
env: buildProxyChildEnv({
CURSOR_PATH: opts.cursorPath,
CURSOR_WORKSPACE_DIR: opts.workspaceDir,
CURSOR_PROXY_PORT: String(opts.port),
CURSOR_OUTPUT_FORMAT: opts.outputFormat,
CURSOR_PROXY_SCRIPT_HASH: computeFileHash(proxyScript),
}),
stdio: ["ignore", "ignore", "pipe"],
});
proxyChild = child;
child.stderr?.on("data", (d: Buffer | string) => {
const s = Buffer.isBuffer(d) ? d.toString("utf-8") : String(d);
appendProxyStderr(s);
});
child.on("error", (err: Error) => {
const msg = `[proxy-child-error] ${err?.message || String(err)}\n`;
appendProxyStderr(msg);
opts.logger.error(`Streaming proxy child process error: ${err?.message || String(err)}`);
});
lastProxyStartTime = Date.now();
child.on("exit", (code, signal) => {
opts.logger.info(`Streaming proxy exited (code ${code}, signal ${signal ?? "none"})`);
if (proxyChild === child) proxyChild = null;
// Normal exit or killed by signal (e.g. gateway restart / killPortProcess): do not auto-restart.
if (code === 0 || code === null || proxyRestartScheduled) return;
if (signal != null || (typeof code === "number" && code >= 128 && code <= 255)) return;
const stderrSnippet = stderrBuf.trim().slice(-2000);
if (stderrSnippet) {
opts.logger.warn(`Streaming proxy stderr (tail): ${stderrSnippet.replace(/\s+/g, " ")}`);
}
const uptime = Date.now() - lastProxyStartTime;
if (uptime > PROXY_STABLE_PERIOD) proxyRestartCount = 0;
if (proxyRestartCount >= MAX_PROXY_RESTARTS) {
opts.logger.error(`Proxy crashed ${proxyRestartCount} times within cooldown, not restarting. Run: openclaw cursor-brain proxy restart`);
return;
}
const delay = PROXY_RESTART_DELAYS[Math.min(proxyRestartCount, PROXY_RESTART_DELAYS.length - 1)];
proxyRestartCount++;
opts.logger.warn(`Proxy crashed (code ${code}), restarting in ${delay / 1000}s (attempt ${proxyRestartCount}/${MAX_PROXY_RESTARTS})`);
setTimeout(() => startProxy(opts), delay);
});
opts.logger.info(`Streaming proxy started on port ${opts.port} (pid ${child.pid})`);
startHealthCheck(opts);
} finally {
startProxyInProgress = false;
}
}
let proxyRestartScheduled = false;
function startHealthCheck(opts: { pluginDir: string; cursorPath: string; workspaceDir: string; port: number; outputFormat: OutputFormat; logger: any }) {
if (healthCheckTimer) clearInterval(healthCheckTimer);
proxyRestartScheduled = false;
healthCheckTimer = setInterval(() => {
if (!proxyChild || proxyRestartScheduled) return;
try {
const health = fetchProxyHealth(opts.port);
if (!health) return;
if (health.status === "degraded") {
opts.logger.warn(`Proxy health degraded (failures=${health.consecutiveFailures}, timeouts=${health.consecutiveTimeouts}), restarting...`);
proxyRestartScheduled = true;
if (healthCheckTimer) clearInterval(healthCheckTimer);
try { proxyChild?.kill("SIGKILL"); } catch {}
proxyChild = null;
setTimeout(() => {
proxyRestartScheduled = false;
startProxy(opts);
}, 2000);
}
} catch {
// health check itself failed — proxy may be down, exit handler will restart it
}
}, HEALTH_CHECK_INTERVAL);
healthCheckTimer.unref();
}
const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
const MODEL_DEFAULTS = { input: ["text"], contextWindow: 128000, maxTokens: 8192, cost: ZERO_COST };
function buildProviderConfig(port: number, cursorModels: CursorModel[]) {
const models = cursorModels.length
? cursorModels.map((m) => ({ id: m.id, name: m.name, reasoning: m.reasoning, ...MODEL_DEFAULTS }))
: [{ id: "auto", name: "Cursor Auto", reasoning: true, ...MODEL_DEFAULTS }];
return {
baseUrl: `http://127.0.0.1:${port}/v1`,
apiKey: "local",
api: "openai-completions",
models,
};
}
function autoSelectModels(
models: CursorModel[],
currentPrimary?: string,
currentFallbacks?: string[],
): { primary: string; fallbacks: string[] } {
const defaultModel = models.find((m) => m.isDefault);
const primary = currentPrimary || defaultModel?.id || models[0]?.id || "auto";
const fallbacks = currentFallbacks?.length
? currentFallbacks.filter((id) => id !== primary)
: models.filter((m) => m.id !== primary).map((m) => m.id);
return { primary, fallbacks };
}
/** Read default values from openclaw.plugin.json configSchema.properties[].default. */
function getPluginConfigDefaults(): Record<string, unknown> {
const schema = loadPluginConfigSchema() as { properties?: Record<string, { default?: unknown }> };
const props = schema?.properties;
if (!props || typeof props !== "object") return {};
const out: Record<string, unknown> = {};
for (const [key, def] of Object.entries(props)) {
if (def != null && typeof def === "object" && "default" in def) {
out[key] = (def as { default?: unknown }).default;
}
}
return out;
}
/** Read configSchema.properties from openclaw.plugin.json for schema-driven prompts. */
function getSchemaProperties(): Record<string, { type?: string; default?: unknown; description?: string; enum?: unknown[] }> {
const schema = loadPluginConfigSchema() as { properties?: Record<string, { type?: string; default?: unknown; description?: string; enum?: unknown[] }> };
return schema?.properties ?? {};
}
function parseNum(input: string | undefined, fallback: number): number {
if (input == null || input.trim() === "") return fallback;
const n = Number(input.trim());
return Number.isFinite(n) ? n : fallback;
}
/** Merge patch into plugins.entries[PLUGIN_ID].config. User-submitted patch overwrites existing entry.config (patch wins). PLUGIN_CONFIG_EXCLUDE_KEYS are dropped. */
function mergePluginConfig(patch: Record<string, unknown>): void {
const filtered = { ...patch };
for (const k of PLUGIN_CONFIG_EXCLUDE_KEYS) delete filtered[k];
let cfg: Record<string, any> = {};
try { cfg = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8")); } catch {}
const plugins = cfg.plugins || {};
const entries = plugins.entries || {};
const entry = entries[PLUGIN_ID] || {};
entry.config = { ...entry.config, ...filtered };
for (const k of PLUGIN_CONFIG_EXCLUDE_KEYS) delete entry.config[k];
entries[PLUGIN_ID] = { ...entry, enabled: entry.enabled ?? true };
plugins.entries = entries;
cfg.plugins = plugins;
writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(cfg, null, 2) + "\n");
}
/**
* Interactive prompts for plugin config. Initial values: old/saved (current) overrides schema defaults per key; if no old value, use schema default. Returned value is what the user submitted and must overwrite old when saving (see mergePluginConfig).
* Model/fallbacks are not in plugin config; they live in agents.defaults.model and providers (see saveModelSelection).
*/
async function promptPluginConfig(current: Record<string, unknown>): Promise<Record<string, unknown> | null> {
const defaults = getPluginConfigDefaults();
const props = getSchemaProperties();
const cur = { ...defaults, ...current } as Record<string, unknown>;
const out: Record<string, unknown> = { ...current };
try {
const clack = loadClack();
clack.note("Press Ctrl+C to skip and use defaults for all options.", "Plugin options");
for (const [key, def] of Object.entries(props)) {
const type = def?.type ?? "string";
const message = (def?.description as string) || key;
if (type === "boolean") {
const val = await clack.confirm({
message,
initialValue: cur[key] === true,
});
if (clack.isCancel(val)) return null;
out[key] = val === true;
continue;
}
if (type === "number") {
const defNum = (def?.default as number) ?? 0;
const val = await clack.text({
message,
initialValue: String(cur[key] ?? def?.default ?? ""),
placeholder: String(def?.default ?? ""),
});
if (clack.isCancel(val)) return null;
out[key] = parseNum(val as string, defNum);
continue;
}
if (type === "string" && Array.isArray(def?.enum) && def.enum.length) {
const options = (def.enum as string[]).map((v) => ({ value: v, label: v }));
const initial = (cur[key] as string) ?? (def?.default as string) ?? options[0]?.value;
const val = await clack.select({
message,
options,
initialValue: initial,
maxItems: Math.min(12, options.length),
});
if (clack.isCancel(val)) return null;
out[key] = val;
continue;
}
const val = await clack.text({
message,
initialValue: String(cur[key] ?? def?.default ?? ""),
placeholder: String(def?.default ?? ""),
});
if (clack.isCancel(val)) return null;
out[key] = (val as string).trim();
}
for (const k of PLUGIN_CONFIG_EXCLUDE_KEYS) delete out[k];
return out;
} catch (err: any) {
console.log(` ⚠ Config prompt failed (${err?.code ?? err?.message ?? String(err)}), keeping current.`);
return null;
}
}
async function promptModelSelection(
models: CursorModel[],
currentPrimary?: string,
currentFallbacks?: string[],
): Promise<{ primary: string; fallbacks: string[] } | null> {
if (!models.length) {
console.log(" ⚠ No models discovered from cursor-agent");
return null;
}
try {
const clack = loadClack();
const toOption = (m: CursorModel) => {
const tags: string[] = [];
if (m.reasoning) tags.push("thinking");
if (m.isDefault) tags.push("cursor default");
return { value: m.id, label: m.id, hint: `${m.name}${tags.length ? ` (${tags.join(", ")})` : ""}` };
};
const options = models.map(toOption);
const primary = await clack.select({
message: "Select primary model (↑↓ navigate, enter confirm)",
options,
initialValue: currentPrimary || models[0].id,
maxItems: 12,
});
if (clack.isCancel(primary)) { clack.cancel("Cancelled"); return null; }
const fallbackOptions = models.filter((m) => m.id !== primary).map(toOption);
const defaultFallbacks = currentFallbacks?.length
? currentFallbacks.filter((id) => id !== primary)
: fallbackOptions.map((o) => o.value);
const fallbacks = await clack.multiselect({
message: "Select fallback models (space toggle, enter confirm, order follows list)",
options: fallbackOptions,
initialValues: defaultFallbacks,
maxItems: 12,
required: false,
});
if (clack.isCancel(fallbacks)) { clack.cancel("Cancelled"); return null; }
const selectedFallbacks = fallbacks as string[];
clack.log.success(`Primary: ${PROVIDER_ID}/${primary}`);
clack.log.success(`Fallbacks: ${selectedFallbacks.length ? selectedFallbacks.map((f) => `${PROVIDER_ID}/${f}`).join(" → ") : "none"}`);
return { primary: primary as string, fallbacks: selectedFallbacks };
} catch (err: any) {
console.log(` ⚠ Interactive prompt failed (${err?.code ?? err?.message ?? String(err)}), using defaults.`);
const result = autoSelectModels(models, currentPrimary, currentFallbacks);
console.log(` Primary: ${PROVIDER_ID}/${result.primary}`);
console.log(` Fallbacks: ${result.fallbacks.length ? result.fallbacks.map((f) => `${PROVIDER_ID}/${f}`).join(" → ") : "none"}`);
console.log(" Run `openclaw cursor-brain setup` in an interactive terminal to choose manually.");
return result;
}
}
function saveModelSelection(primary: string, fallbacks: string[], proxyPort: number, models: CursorModel[]) {
let config: Record<string, any> = {};
try { config = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8")); } catch {}
const agents = config.agents || {};
const defaults = agents.defaults || {};
defaults.model = {
primary: `${PROVIDER_ID}/${primary}`,
fallbacks: fallbacks.map((f) => `${PROVIDER_ID}/${f}`),
};
agents.defaults = defaults;
config.agents = agents;
const modelsSection = config.models || {};
modelsSection.mode = "merge";
const providers = modelsSection.providers || {};
providers[PROVIDER_ID] = buildProviderConfig(proxyPort, models);
modelsSection.providers = providers;
config.models = modelsSection;
writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");
}
const VALID_SOURCES = ["npm", "archive", "path"] as const;
/**
* Remove this plugin from openclaw.json (entries, installs, allow; provider + model refs).
* Used after "openclaw plugins uninstall" during upgrade — core deletes the extension dir
* so we cannot run uninstall.mjs; this inline cleanup makes config valid for "plugins install".
*/
function removePluginFromOpenClawConfig(): boolean {
try {
if (!existsSync(OPENCLAW_CONFIG_PATH)) return false;
const cfg = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8")) as Record<string, any>;
const plugins = cfg.plugins || {};
let changed = false;
if (plugins.entries?.[PLUGIN_ID]) {
delete plugins.entries[PLUGIN_ID];
changed = true;
}
if (plugins.installs?.[PLUGIN_ID]) {
delete plugins.installs[PLUGIN_ID];
changed = true;
}
if (Array.isArray(plugins.allow)) {
const idx = plugins.allow.indexOf(PLUGIN_ID);
if (idx !== -1) {
plugins.allow.splice(idx, 1);
changed = true;
}
}
const prefix = `${PROVIDER_ID}/`;
const defaults = cfg.agents?.defaults;
if (defaults?.model) {
if ((defaults.model.primary || "").toString().startsWith(prefix)) {
delete defaults.model.primary;
changed = true;
}
if (defaults.model.fallbacks && Array.isArray(defaults.model.fallbacks)) {
const cleaned = defaults.model.fallbacks.filter((f: string) => !f.startsWith(prefix));
if (cleaned.length !== defaults.model.fallbacks.length) {
defaults.model.fallbacks = cleaned.length ? cleaned : undefined;
changed = true;
}
}
if (!defaults.model.primary && !defaults.model.fallbacks) delete defaults.model;
}
if (cfg.models?.providers?.[PROVIDER_ID]) {
delete cfg.models.providers[PROVIDER_ID];
if (Object.keys(cfg.models.providers || {}).length === 0) delete cfg.models.providers;
changed = true;
}
if (changed) writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(cfg, null, 2) + "\n");
return changed;
} catch {
return false;
}
}
/**
* Re-read openclaw.json and fix plugins.installs[PLUGIN_ID].source to a valid
* value (or re-add the record if missing after core overwrite). Called from
* setImmediate after install so we run after core may have written invalid source.
*/
function fixInstallRecordSourceOnDisk(installPath: string): void {
try {
if (!existsSync(OPENCLAW_CONFIG_PATH)) return;
const raw = readFileSync(OPENCLAW_CONFIG_PATH, "utf-8");
const cfg = JSON.parse(raw);
const plugins = cfg.plugins || {};
const installs = plugins.installs || {};
const entries = plugins.entries || {};
let rec = installs[PLUGIN_ID];
let changed = false;
if (!rec) {
rec = { installPath, source: "path", sourcePath: resolve(installPath) };
if (existsSync(join(installPath, "package.json"))) {
try { rec.version = JSON.parse(readFileSync(join(installPath, "package.json"), "utf-8")).version; } catch { /* ignore */ }
}
installs[PLUGIN_ID] = rec;
plugins.installs = installs;
const defaultConfig = getPluginConfigDefaults();
const mergedConfig: Record<string, unknown> = { ...defaultConfig, ...(entries[PLUGIN_ID]?.config || {}) };
for (const k of PLUGIN_CONFIG_EXCLUDE_KEYS) delete mergedConfig[k];
entries[PLUGIN_ID] = { ...entries[PLUGIN_ID], enabled: true, config: mergedConfig };
plugins.entries = entries;
const allow: string[] = Array.isArray(plugins.allow) ? plugins.allow : [];
if (!allow.includes(PLUGIN_ID)) {
allow.push(PLUGIN_ID);
plugins.allow = allow;
}
cfg.plugins = plugins;
changed = true;
} else if (rec.source === "tarball" || (rec.source && !VALID_SOURCES.includes(rec.source as any))) {
rec.source = existsSync(join(installPath, "package.json")) ? "path" : "archive";
if (rec.source === "path") rec.sourcePath = resolve(installPath);
changed = true;
}
if (changed) writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(cfg, null, 2) + "\n");
} catch { /* ignore */ }
}
/**
* Ensure plugins.installs and plugins.entries in openclaw.json reflect the
* actual on-disk state. Both `openclaw plugins install` and `uninstall` may
* exit non-zero (e.g. plugins.allow warnings) without persisting config
* changes, so the plugin itself must reconcile the record.
*/
function syncPluginInstallRecord(opts: {
installPath: string;
source?: string;
updateTimestamp?: boolean;
/** When set (e.g. after interactive setup), merged on top so user choices are not overwritten by core defaults. */
preservedConfig?: Record<string, unknown>;
}): void {
let config: Record<string, any> = {};
try { config = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8")); } catch {}
const plugins = config.plugins || {};
const entries = plugins.entries || {};
const installs = plugins.installs || {};
const entry = entries[PLUGIN_ID] || {};
const defaultConfig = getPluginConfigDefaults();
const mergedConfig: Record<string, unknown> = { ...defaultConfig, ...entry.config, ...(opts.preservedConfig || {}) };
for (const k of PLUGIN_CONFIG_EXCLUDE_KEYS) delete mergedConfig[k];
entries[PLUGIN_ID] = { ...entry, enabled: true, config: mergedConfig };
const allow: string[] = Array.isArray(plugins.allow) ? plugins.allow : [];
if (!allow.includes(PLUGIN_ID)) {
allow.push(PLUGIN_ID);
plugins.allow = allow;
}
const version = readPackageVersion(opts.installPath);
const prev = installs[PLUGIN_ID] || {};
const record: Record<string, any> = { ...prev, installPath: opts.installPath };
// OpenClaw only allows source: "npm" | "archive" | "path"
if (record.source === "tarball") record.source = "archive";
if (version !== "unknown") record.version = version;
if (opts.updateTimestamp !== false) record.installedAt = new Date().toISOString();
if (opts.source) {
const abs = resolve(opts.source);
if (opts.source.endsWith(".tgz") || opts.source.endsWith(".tar.gz")) {
record.source = "archive";
record.sourcePath = abs;
delete record.spec;
} else if (existsSync(join(abs, "package.json"))) {
record.source = "path";
record.sourcePath = abs;
delete record.spec;
} else {
record.source = "npm";
record.spec = opts.source;
delete record.sourcePath;
}
} else if (!record.source || record.source === "tarball") {
// Always set a valid source so core validation never sees invalid/tarball
if (existsSync(join(opts.installPath, "package.json"))) {
record.source = "path";
record.sourcePath = resolve(opts.installPath);
delete record.spec;
} else {
record.source = "npm";
record.spec = PLUGIN_ID;
delete record.sourcePath;
}
}
installs[PLUGIN_ID] = record;
plugins.entries = entries;
plugins.installs = installs;
config.plugins = plugins;
writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");
}
function resolvePluginDir(api: OpenClawPluginApi): string {
const installRecord = (api.config.plugins as any)?.installs?.[PLUGIN_ID];
if (installRecord?.installPath && existsSync(join(installRecord.installPath, "mcp-server", "server.mjs"))) {
return installRecord.installPath;
}
const conventionPath = join(homedir(), ".openclaw", "extensions", PLUGIN_ID);
if (existsSync(join(conventionPath, "mcp-server", "server.mjs"))) {
return conventionPath;
}
return api.resolvePath(".");
}
/** Load configSchema from openclaw.plugin.json so the host shows all options (e.g. requestTimeout, proxy) in config UI; fallback to empty if manifest missing. */
function loadPluginConfigSchema(): Record<string, unknown> {
try {
const pluginDir = dirname(createRequire(import.meta.url).resolve("./package.json"));
const manifestPath = join(pluginDir, "openclaw.plugin.json");
if (!existsSync(manifestPath)) return emptyPluginConfigSchema();
const raw = readFileSync(manifestPath, "utf-8");
const manifest = JSON.parse(raw) as { configSchema?: Record<string, unknown> };
if (manifest?.configSchema && typeof manifest.configSchema === "object") {
return manifest.configSchema as Record<string, unknown>;
}
} catch {
/* ignore */
}
return emptyPluginConfigSchema();
}
/**
* Provider sync + streaming proxy spawn — runs on gateway_start only so plain `openclaw` CLI
* invocations (status, doctor, config, etc.) do not rewrite models/providers or manage the proxy.
*/
async function handleCursorBrainGatewayStart(
api: OpenClawPluginApi,
pluginDir: string,
ctx: { port?: number },
): Promise<void> {
let diskConfig: Record<string, any> = {};
try {
diskConfig = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8"));
} catch {
diskConfig = { ...(api.config as Record<string, any>) };
}
const pluginConfig = (diskConfig.plugins?.entries?.[PLUGIN_ID]?.config ??
api.pluginConfig ??
{}) as Record<string, unknown>;
const workspaceDir = (diskConfig.agents as any)?.defaults?.workspace ?? "";
const setupCtx: SetupContext = {
pluginDir,
gatewayPort: diskConfig.gateway?.port ?? ctx.port ?? 18789,
gatewayToken: (diskConfig.gateway as any)?.auth?.token ?? "",
workspaceDir,
pluginConfig,
logger: api.logger,
};
const result = runSetup(setupCtx);
for (const w of result.warnings) api.logger.warn(w);
for (const e of result.errors) api.logger.error(e);
const proxyPort = parseProxyPort(pluginConfig.proxyPort);
const existingProviders = diskConfig.models?.providers ?? {};
const discovered = result.cursorModels;
const providerExists = !!existingProviders[PROVIDER_ID];
const doSyncInstallRecord = () => {
try {
syncPluginInstallRecord({ installPath: pluginDir, updateTimestamp: false });
} catch (e: any) {
api.logger.warn(`Could not sync install record: ${e?.message ?? String(e)}`);
}
};
if (!result.cursorPath) {
doSyncInstallRecord();
return;
}
try {
const newProviderConfig = buildProviderConfig(proxyPort, discovered);
const existingProvider = existingProviders[PROVIDER_ID];
const providerUnchanged =
existingProvider &&
JSON.stringify(existingProvider) === JSON.stringify(newProviderConfig);
if (providerUnchanged && providerExists) {
api.logger.info(`Provider "${PROVIDER_ID}" unchanged (${discovered.length} models, port ${proxyPort})`);
doSyncInstallRecord();
try {
let cfg: Record<string, any> = {};
try {
cfg = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8"));
} catch { /* ignore */ }
const currentPrimary = (cfg.agents?.defaults?.model as any)?.primary;
if (!currentPrimary || String(currentPrimary).startsWith(`${PROVIDER_ID}/`)) {
const primary = (currentPrimary as string)?.replace(`${PROVIDER_ID}/`, "") || "auto";
const existingFallbacks = (cfg.agents?.defaults?.model as any)?.fallbacks as string[] | undefined;
const fallbacks = existingFallbacks?.length
? existingFallbacks
: discovered.filter((m) => m.id !== primary).map((m) => `${PROVIDER_ID}/${m.id}`);
const agents = cfg.agents || {};
const defaults = agents.defaults || {};
defaults.model = { primary: `${PROVIDER_ID}/${primary}`, fallbacks };
agents.defaults = defaults;
cfg.agents = agents;
writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(cfg, null, 2) + "\n");
api.logger.info(`Default model set to ${PROVIDER_ID}/${primary}`);
}
} catch (e: any) {
api.logger.warn(`Could not set default model: ${e?.message ?? String(e)}`);
}
} else {
let freshConfig: Record<string, any> = {};
try {
freshConfig = JSON.parse(readFileSync(OPENCLAW_CONFIG_PATH, "utf-8"));
} catch {
freshConfig = { ...diskConfig };
}
const patch: Record<string, unknown> = {
...freshConfig,
models: {
...(freshConfig.models || {}),
mode: "merge",
providers: {
...(freshConfig.models?.providers || {}),
[PROVIDER_ID]: newProviderConfig,
},
},
};
const currentPrimary = (freshConfig.agents?.defaults?.model as any)?.primary;
const shouldSetDefaultModel =
!providerExists ||
!currentPrimary ||
String(currentPrimary).startsWith(`${PROVIDER_ID}/`);
if (shouldSetDefaultModel) {
const primary = (currentPrimary as string)?.replace(`${PROVIDER_ID}/`, "") || "auto";
const existingFallbacks = (freshConfig.agents?.defaults?.model as any)?.fallbacks as string[] | undefined;
const fallbacks = existingFallbacks?.length
? existingFallbacks
: discovered.filter((m) => m.id !== primary).map((m) => `${PROVIDER_ID}/${m.id}`);
(patch as any).agents = {
...(freshConfig.agents || {}),
defaults: {
...(freshConfig.agents?.defaults || {}),
model: {
primary: `${PROVIDER_ID}/${primary}`,
fallbacks,
},
},
};
}
const patchInstallRecord = (patch as any).plugins?.installs?.[PLUGIN_ID];
if (patchInstallRecord?.source === "tarball") patchInstallRecord.source = "archive";
try {
await api.runtime.config.writeConfigFile(patch as any);
api.logger.info(`Provider "${PROVIDER_ID}" synced (${discovered.length} models, port ${proxyPort})`);
doSyncInstallRecord();
} catch (err: any) {
api.logger.warn(`Could not write config: ${err?.message ?? String(err)}`);
doSyncInstallRecord();
}
}
} catch (e: any) {
api.logger.warn(`Could not auto-configure: ${e?.message ?? String(e)}`);
doSyncInstallRecord();
}
const effectiveCursorPath =
result.cursorPath || detectCursorPath(pluginConfig.cursorPath as string | undefined);
const effectiveOutputFormat =
result.outputFormat ??
(effectiveCursorPath
? detectOutputFormat(effectiveCursorPath, pluginConfig.outputFormat as string | undefined)
: undefined);
if (!effectiveCursorPath) return;
const proxyOpts = {
pluginDir,
cursorPath: effectiveCursorPath,
workspaceDir,
port: proxyPort,
outputFormat: effectiveOutputFormat ?? ("stream-json" as OutputFormat),
logger: api.logger,
};
proxyChild = null;
const proxyRunning = isProxyRunning(proxyPort);
let needRestart = !proxyRunning;
if (proxyRunning) {
const health = fetchProxyHealth(proxyPort, 3000);
if (health) {
const proxyScript = join(pluginDir, "mcp-server", "streaming-proxy.mjs");
const installedHash = computeFileHash(proxyScript);
if (health.scriptHash !== installedHash) {
api.logger.info(`Proxy script changed (running=${health.scriptHash}, installed=${installedHash}), restarting...`);
needRestart = true;
}
} else {
needRestart = true;
}
}
if (needRestart) {
startProxy(proxyOpts);
} else {
api.logger.info(`Adopting proxy on port ${proxyPort} — killing and restarting under this gateway`);
startProxy(proxyOpts);
}
}
/** Stop proxy child and timers when the gateway shuts down (avoids orphan restarts). */
function handleCursorBrainGatewayStop(): void {
proxyRestartScheduled = true;
if (healthCheckTimer) {
clearInterval(healthCheckTimer);
healthCheckTimer = null;
}
if (proxyChild) {
try {
proxyChild.kill("SIGKILL");
} catch {
/* ignore */
}
proxyChild = null;