-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopencode-bridge.mjs
More file actions
1553 lines (1394 loc) · 43.9 KB
/
opencode-bridge.mjs
File metadata and controls
1553 lines (1394 loc) · 43.9 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
/**
* ESM bridge module loaded by main.cjs via dynamic import().
* Hosts OpenCodeConnection instances (one per project) and wires IPC handlers.
*
* This file MUST be .mjs so Electron's Node runtime treats it as ESM,
* allowing us to import the ESM-only @opencode-ai/sdk.
*
* Uses v2 SDK which supports variant selection and named parameters.
*/
import { execSync, spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { Agent } from "node:http";
import { Agent as HttpsAgent } from "node:https";
import { homedir } from "node:os";
import { join } from "node:path";
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
// ---------------------------------------------------------------------------
// Local server management
// ---------------------------------------------------------------------------
const LOCAL_SERVER_PORT = 4096;
const LOCAL_SERVER_URL = `http://127.0.0.1:${LOCAL_SERVER_PORT}`;
const STARTUP_POLL_INTERVAL = 500; // ms
const STARTUP_TIMEOUT = 15_000; // ms
/** Resolve the opencode binary path (cross-platform). */
function resolveOpencodeBinary() {
const isWindows = process.platform === "win32";
const whichCmd = isWindows ? "where opencode" : "which opencode";
try {
const fromPath = execSync(whichCmd, { encoding: "utf-8" })
.split(/\r?\n/)[0]
.trim();
if (fromPath) return fromPath;
} catch {
// not on PATH
}
const binaryName = isWindows ? "opencode.exe" : "opencode";
const fallback = join(homedir(), ".opencode", "bin", binaryName);
if (existsSync(fallback)) return fallback;
return null;
}
/** Quick health check against the local server. */
async function isLocalServerHealthy() {
try {
const res = await fetch(`${LOCAL_SERVER_URL}/global/health`, {
signal: AbortSignal.timeout(3000),
});
if (!res.ok) return false;
const data = await res.json();
return data.healthy === true;
} catch {
return false;
}
}
/** Poll until healthy or timeout. */
function waitForHealthy(timeoutMs = STARTUP_TIMEOUT) {
return new Promise((resolve, reject) => {
const start = Date.now();
const check = async () => {
if (await isLocalServerHealthy()) return resolve(true);
if (Date.now() - start > timeoutMs) {
return reject(
new Error(
`Server did not become healthy within ${timeoutMs / 1000}s`,
),
);
}
setTimeout(check, STARTUP_POLL_INTERVAL);
};
check();
});
}
// ---------------------------------------------------------------------------
// URL safety helpers
// ---------------------------------------------------------------------------
/** Only allow http:// for local addresses; require https:// for everything else. */
function isBaseUrlSafe(rawUrl) {
try {
const parsed = new URL(rawUrl);
if (parsed.protocol === "https:") return true;
if (parsed.protocol === "http:") {
const host = parsed.hostname;
return (
host === "127.0.0.1" ||
host === "localhost" ||
host === "[::1]" ||
host === "0.0.0.0"
);
}
return false;
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// Inline connection manager (avoids needing to transpile TS in main process)
// ---------------------------------------------------------------------------
const BACKOFF_STEPS = [500, 1000, 2000, 5000]; // ms – fast first attempt
const HEALTH_INTERVAL = 30_000; // ms
const SSE_STALE_THRESHOLD = 45_000; // ms – restart SSE if no event for this long
// Keep-alive agents to prevent idle TCP connections from being dropped.
// Setting keepAlive + very long timeouts prevents OS/proxy idle-timeout kills.
const httpAgent = new Agent({ keepAlive: true, keepAliveMsecs: 15_000 });
const httpsAgent = new HttpsAgent({ keepAlive: true, keepAliveMsecs: 15_000 });
class OpenCodeConnection {
constructor(emit) {
this._emit = emit;
this._lifecycle = 0;
this._streamGeneration = 0;
this._client = null;
this._config = null;
this._abortController = null;
this._reconnectTimer = null;
this._healthTimer = null;
this._reconnectAttempt = 0;
this._status = {
state: "idle",
serverUrl: null,
serverVersion: null,
error: null,
lastEventAt: null,
};
}
// - public ---------------------------------------------------------------
async connect(config) {
if (!isBaseUrlSafe(config.baseUrl)) {
throw new Error(
"Unsafe server URL: use HTTPS for remote servers, or HTTP only for localhost/127.0.0.1",
);
}
this.teardown();
const lifecycle = ++this._lifecycle;
this._config = config;
this._client = this._makeClient(config);
this._setStatus({
state: "connecting",
serverUrl: config.baseUrl,
error: null,
});
try {
await this._healthCheck();
if (!this._isCurrent(lifecycle)) return;
this._setStatus({ state: "connected" });
this._startSSE(lifecycle);
this._startHealthTimer(lifecycle);
} catch (err) {
if (!this._isCurrent(lifecycle)) return;
const msg = err instanceof Error ? err.message : String(err);
this._setStatus({ state: "error", error: msg });
throw err;
}
}
disconnect() {
this.teardown();
this._setStatus({
state: "idle",
serverUrl: null,
serverVersion: null,
error: null,
lastEventAt: null,
});
}
getStatus() {
return { ...this._status };
}
getDirectory() {
return this._config?.directory ?? null;
}
// - sessions -------------------------------------------------------------
async listSessions() {
this._requireClient();
// The server defaults to LIMIT 100. Request a high limit so all
// sessions are returned regardless of how many the user has.
const res = await this._client.session.list({
roots: true,
limit: 10000,
});
return res.data ?? [];
}
async createSession(title) {
this._requireClient();
const normalizedTitle = typeof title === "string" ? title.trim() : "";
const params = normalizedTitle ? { title: normalizedTitle } : undefined;
const res = await this._client.session.create(params);
return res.data;
}
async deleteSession(id) {
this._requireClient();
const res = await this._client.session.delete({ sessionID: id });
return res.data;
}
async updateSession(id, title) {
this._requireClient();
const res = await this._client.session.update({ sessionID: id, title });
return res.data;
}
async getSessionStatuses() {
this._requireClient();
const res = await this._client.session.status();
return res.data ?? {};
}
// - revert / fork ---------------------------------------------------------
async revertSession(sessionID, messageID, partID) {
this._requireClient();
const params = { sessionID, messageID };
if (partID) params.partID = partID;
const res = await this._client.session.revert(params);
return res.data;
}
async unrevertSession(sessionID) {
this._requireClient();
const res = await this._client.session.unrevert({ sessionID });
return res.data;
}
async forkSession(sessionID, messageID) {
this._requireClient();
const params = { sessionID };
if (messageID) params.messageID = messageID;
const res = await this._client.session.fork(params);
return res.data;
}
// - providers / models ----------------------------------------------------
async getProviders() {
this._requireClient();
const res = await this._client.config.providers();
return res.data ?? { providers: [], default: {} };
}
async listAllProviders() {
this._requireClient();
const res = await this._client.provider.list();
return res.data ?? { all: [], default: {}, connected: [] };
}
async getProviderAuthMethods() {
this._requireClient();
const res = await this._client.provider.auth();
return res.data ?? {};
}
async setProviderAuth(providerID, auth) {
this._requireClient();
const res = await this._client.auth.set({ providerID, auth });
return res.data;
}
async removeProviderAuth(providerID) {
this._requireClient();
const res = await this._client.auth.remove({ providerID });
return res.data;
}
async oauthAuthorize(providerID, method) {
this._requireClient();
const params = { providerID };
if (method !== undefined) params.method = method;
const res = await this._client.provider.oauth.authorize(params);
return res.data;
}
async oauthCallback(providerID, method, code) {
this._requireClient();
const params = { providerID };
if (method !== undefined) params.method = method;
if (code !== undefined) params.code = code;
const res = await this._client.provider.oauth.callback(params);
return res.data;
}
async disposeInstance() {
this._requireClient();
const res = await this._client.instance.dispose();
return res.data;
}
// - agents ---------------------------------------------------------------
async getAgents() {
this._requireClient();
const res = await this._client.app.agents();
return res.data ?? [];
}
// - messages -------------------------------------------------------------
async getMessages(sessionId) {
this._requireClient();
const res = await this._client.session.messages({ sessionID: sessionId });
return res.data ?? [];
}
async promptAsync(sessionId, text, images, model, agent, variant) {
this._requireClient();
const parts = [{ type: "text", text }];
if (images) {
for (const url of images) {
// Attempt to detect MIME from data-URI header or file extension
let mime = "image/png";
const dataMatch = url.match(/^data:(image\/[^;,]+)/);
if (dataMatch) {
mime = dataMatch[1];
} else {
const ext = url.split(".").pop()?.toLowerCase();
if (ext === "jpg" || ext === "jpeg") mime = "image/jpeg";
else if (ext === "gif") mime = "image/gif";
else if (ext === "webp") mime = "image/webp";
else if (ext === "svg") mime = "image/svg+xml";
}
parts.push({ type: "file", mime, url });
}
}
const params = { sessionID: sessionId, parts };
if (model) {
params.model = model;
}
if (agent) {
params.agent = agent;
}
if (variant) {
params.variant = variant;
}
await this._client.session.promptAsync(params);
}
async abortSession(sessionId) {
this._requireClient();
await this._client.session.abort({ sessionID: sessionId });
}
// - permissions ----------------------------------------------------------
async respondPermission(sessionId, permissionId, response) {
this._requireClient();
await this._client.permission.respond({
sessionID: sessionId,
permissionID: permissionId,
response,
});
}
// - commands -------------------------------------------------------------
async listCommands() {
this._requireClient();
const res = await this._client.command.list();
return res.data ?? [];
}
async sendCommand(sessionId, command, args, model, agent, variant) {
this._requireClient();
const params = { sessionID: sessionId, command, arguments: args };
if (model) params.model = `${model.providerID}/${model.modelID}`;
if (agent) params.agent = agent;
if (variant) params.variant = variant;
await this._client.session.command(params);
}
// - questions ------------------------------------------------------------
async replyQuestion(requestID, answers) {
this._requireClient();
await this._client.question.reply({ requestID, answers });
}
async rejectQuestion(requestID) {
this._requireClient();
await this._client.question.reject({ requestID });
}
// - MCP ------------------------------------------------------------------
async getMcpStatus() {
this._requireClient();
const res = await this._client.mcp.status();
return res.data ?? {};
}
async addMcp(name, config) {
this._requireClient();
const res = await this._client.mcp.add({ name, config });
return res.data ?? {};
}
async connectMcp(name) {
this._requireClient();
await this._client.mcp.connect({ name });
}
async disconnectMcp(name) {
this._requireClient();
await this._client.mcp.disconnect({ name });
}
// - Config ---------------------------------------------------------------
async getConfig() {
this._requireClient();
const res = await this._client.config.get();
return res.data ?? {};
}
async updateConfig(config) {
this._requireClient();
const res = await this._client.config.update({ config });
return res.data ?? {};
}
// - Skills ---------------------------------------------------------------
async getSkills() {
this._requireClient();
const res = await this._client.app.skills();
return res.data ?? [];
}
// - internal -------------------------------------------------------------
_requireClient() {
if (!this._client) throw new Error("Not connected to any opencode server");
}
_makeClient(config) {
const headers = {};
if (config.password) {
const user = config.username ?? "opencode";
headers.Authorization = `Basic ${Buffer.from(`${user}:${config.password}`).toString("base64")}`;
}
const directory =
typeof config.directory === "string" ? config.directory.trim() : "";
// Custom fetch that uses keep-alive agents to prevent idle connection drops.
const customFetch = (input, init) => {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
const agent = url?.startsWith("https") ? httpsAgent : httpAgent;
return globalThis.fetch(input, { ...init, agent });
};
return createOpencodeClient({
baseUrl: config.baseUrl.replace(/\/+$/, ""),
headers,
fetch: customFetch,
...(directory ? { directory } : {}),
});
}
async _healthCheck() {
this._requireClient();
try {
const res = await this._client.global.health();
const data = res.data;
if (data?.version) this._setStatus({ serverVersion: data.version });
if (!data?.healthy) throw new Error("Server reports unhealthy");
} catch (err) {
// If the v2 global.health() fails with a method-not-found-style error,
// fall back to raw fetch (older servers may not support this endpoint via SDK)
if (err?.message?.includes("unhealthy")) throw err;
const url = `${this._config.baseUrl.replace(/\/+$/, "")}/global/health`;
const headers = {};
if (this._config.password) {
const user = this._config.username ?? "opencode";
headers.Authorization = `Basic ${Buffer.from(`${user}:${this._config.password}`).toString("base64")}`;
}
const rawRes = await fetch(url, { headers });
if (!rawRes.ok)
throw new Error(
`Health check failed: ${rawRes.status} ${rawRes.statusText}`,
);
const data = await rawRes.json();
if (data.version) this._setStatus({ serverVersion: data.version });
if (!data.healthy) throw new Error("Server reports unhealthy");
}
}
_isCurrent(lifecycle) {
return lifecycle === this._lifecycle;
}
async _startSSE(lifecycle) {
if (!this._isCurrent(lifecycle)) return;
this._requireClient();
const streamGeneration = ++this._streamGeneration;
const abortController = new AbortController();
this._abortController = abortController;
try {
const events = await this._client.event.subscribe({
signal: abortController.signal,
// Disable SDK-level retry - we handle reconnection at the app level
// with our own backoff. Without this, the SDK silently retries with
// exponential backoff (3s/6s/12s/24s/30s) and the app has no
// visibility into the disconnect.
sseMaxRetryAttempts: 1,
onSseError: (err) =>
console.warn("[OpenCodeConnection] SDK SSE error:", err),
});
const stream = events.stream ?? events;
for await (const event of stream) {
if (
abortController.signal.aborted ||
this._streamGeneration !== streamGeneration ||
!this._isCurrent(lifecycle)
) {
break;
}
const payload = event.properties ? event : event.payload;
if (payload) {
this._emit({ type: "opencode:event", payload });
this._setStatus({ lastEventAt: Date.now() });
}
this._reconnectAttempt = 0;
}
// Stream ended cleanly (server closed the connection).
// Reconnect unless we intentionally aborted.
if (
!abortController.signal.aborted &&
this._streamGeneration === streamGeneration
) {
console.warn(
"[OpenCodeConnection] SSE stream ended cleanly, reconnecting...",
);
this._scheduleReconnect(lifecycle);
}
} catch (err) {
if (
abortController.signal.aborted ||
this._streamGeneration !== streamGeneration ||
!this._isCurrent(lifecycle)
) {
return;
}
console.error("[OpenCodeConnection] SSE error:", err);
this._scheduleReconnect(lifecycle);
}
}
_scheduleReconnect(lifecycle) {
if (!this._config || !this._isCurrent(lifecycle)) return;
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
const delay =
BACKOFF_STEPS[Math.min(this._reconnectAttempt, BACKOFF_STEPS.length - 1)];
this._reconnectAttempt++;
this._setStatus({
state: "reconnecting",
error: `Reconnecting in ${delay / 1000}s...`,
});
this._reconnectTimer = setTimeout(async () => {
if (!this._isCurrent(lifecycle)) return;
try {
await this._healthCheck();
if (!this._isCurrent(lifecycle)) return;
this._setStatus({ state: "connected", error: null });
this._startSSE(lifecycle);
} catch {
this._scheduleReconnect(lifecycle);
}
}, delay);
}
_startHealthTimer(lifecycle) {
if (!this._isCurrent(lifecycle)) return;
this._stopHealthTimer();
this._healthTimer = setInterval(async () => {
if (!this._isCurrent(lifecycle)) {
this._stopHealthTimer();
return;
}
try {
await this._healthCheck();
if (!this._isCurrent(lifecycle)) return;
// If the server is healthy but SSE has gone stale (no events
// for longer than the stale threshold), proactively restart.
const lastEvent = this._status.lastEventAt;
if (
lastEvent &&
Date.now() - lastEvent > SSE_STALE_THRESHOLD &&
this._status.state === "connected"
) {
console.warn(
"[OpenCodeConnection] SSE stream appears stale, restarting...",
);
// Abort the old stream and wait briefly for it to unwind
// before starting a fresh one to avoid overlapping streams.
this._abortController?.abort();
await new Promise((r) => setTimeout(r, 100));
this._startSSE(lifecycle);
}
} catch {
// Server unreachable - actively trigger reconnect instead of
// waiting for the SSE stream to eventually break on its own.
if (this._status.state === "connected") {
console.warn(
"[OpenCodeConnection] Health check failed while connected, reconnecting...",
);
this._abortController?.abort();
this._stopHealthTimer();
this._scheduleReconnect(lifecycle);
}
}
}, HEALTH_INTERVAL);
}
_stopHealthTimer() {
if (this._healthTimer) {
clearInterval(this._healthTimer);
this._healthTimer = null;
}
}
_setStatus(patch) {
this._status = { ...this._status, ...patch };
this._emit({ type: "connection:status", payload: { ...this._status } });
}
teardown() {
this._lifecycle++;
this._abortController?.abort();
this._abortController = null;
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
this._stopHealthTimer();
this._reconnectAttempt = 0;
this._client = null;
this._config = null;
}
}
// ---------------------------------------------------------------------------
// Setup: called from main.cjs with (ipcMain, mainWindow)
// ---------------------------------------------------------------------------
export function setupOpenCodeBridge(ipcMain, getMainWindow) {
/** @type {Map<string, OpenCodeConnection>} directory -> connection */
const connections = new Map();
/** Map sessionId -> directory for routing session-specific operations */
const sessionDirectoryMap = new Map();
function sendEvent(event) {
const win = getMainWindow();
if (win && !win.isDestroyed()) {
win.webContents.send("opencode:bridge-event", event);
}
}
function createConnection(directory) {
const conn = new OpenCodeConnection((event) => {
if (connections.get(directory) !== conn) return;
// Tag every event with the directory it came from
sendEvent({ ...event, directory });
});
connections.set(directory, conn);
return conn;
}
/** Find which connection owns a session by looking up the cache. */
function getConnectionForSession(sessionId) {
const dir = sessionDirectoryMap.get(sessionId);
if (dir) {
const conn = connections.get(dir);
if (conn) return conn;
}
// No fallback -- routing to an arbitrary connection is dangerous in
// multi-project mode and can send operations to the wrong backend.
return null;
}
/** Get any connected connection (for global operations like providers/agents). */
function getAnyConnection() {
for (const conn of connections.values()) {
if (conn.getStatus().state === "connected") return conn;
}
return null;
}
// --- Project management ---
ipcMain.handle("opencode:project:add", async (_event, config) => {
if (!config || typeof config !== "object") {
return { success: false, error: "Invalid config" };
}
if (typeof config.baseUrl !== "string" || !config.baseUrl.trim()) {
return { success: false, error: "Server URL is required" };
}
const directory = (config.directory ?? "").trim();
if (!directory) {
return { success: false, error: "Directory is required" };
}
try {
// Tear down existing connection for this directory if any
const existing = connections.get(directory);
if (existing) {
existing.teardown();
connections.delete(directory);
}
const conn = createConnection(directory);
await conn.connect(config);
return { success: true, status: conn.getStatus() };
} catch (err) {
if (connections.get(directory)) {
connections.delete(directory);
}
return { success: false, error: err.message ?? String(err) };
}
});
ipcMain.handle("opencode:project:remove", (_event, directory) => {
if (typeof directory !== "string" || !directory.trim()) {
return { success: false, error: "Directory is required" };
}
const conn = connections.get(directory);
if (conn) {
conn.teardown();
connections.delete(directory);
// Clean up session mappings for this directory
for (const [sid, dir] of sessionDirectoryMap) {
if (dir === directory) sessionDirectoryMap.delete(sid);
}
}
return { success: true };
});
ipcMain.handle("opencode:disconnect", () => {
for (const conn of connections.values()) {
conn.teardown();
}
connections.clear();
sessionDirectoryMap.clear();
return { success: true };
});
// --- Session operations ---
ipcMain.handle("opencode:session:list", async (_event, directory) => {
try {
if (directory) {
// List sessions for a specific project
const conn = connections.get(directory);
if (!conn) return { success: false, error: "Project not connected" };
// The server already scopes sessions to this project via the
// x-opencode-directory header, so we don't need to filter by
// directory string (which can differ due to symlinks, trailing
// slashes, etc.). Instead we tag each session with _projectDir
// so the UI can group them by connection directory.
const sessions = (await conn.listSessions()).map((s) => ({
...s,
_projectDir: directory,
}));
// Cache session->directory mappings
for (const s of sessions) {
sessionDirectoryMap.set(s.id, directory);
}
return { success: true, data: sessions };
}
// List sessions from ALL projects
const allSessions = [];
for (const [dir, conn] of connections) {
try {
const sessions = (await conn.listSessions()).map((s) => ({
...s,
_projectDir: dir,
}));
for (const s of sessions) {
sessionDirectoryMap.set(s.id, dir);
}
allSessions.push(...sessions);
} catch {
// Skip failed connections
}
}
return { success: true, data: allSessions };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle(
"opencode:session:create",
async (_event, title, directory) => {
try {
const conn = directory
? connections.get(directory)
: getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
const session = await conn.createSession(title);
if (session) {
const dir = directory || conn.getDirectory();
if (dir) sessionDirectoryMap.set(session.id, dir);
}
return { success: true, data: session };
} catch (err) {
return { success: false, error: err.message };
}
},
);
ipcMain.handle("opencode:session:delete", async (_event, id) => {
try {
const conn = getConnectionForSession(id);
if (!conn)
return { success: false, error: "Session connection not found" };
const result = await conn.deleteSession(id);
sessionDirectoryMap.delete(id);
return { success: true, data: result };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("opencode:session:update", async (_event, id, title) => {
try {
const conn = getConnectionForSession(id);
if (!conn)
return { success: false, error: "Session connection not found" };
const result = await conn.updateSession(id, title);
return { success: true, data: result };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("opencode:session:statuses", async (_event, directory) => {
try {
const conn = directory ? connections.get(directory) : getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
const statuses = await conn.getSessionStatuses();
return { success: true, data: statuses };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle(
"opencode:session:revert",
async (_event, id, messageID, partID) => {
try {
const conn = getConnectionForSession(id);
if (!conn)
return { success: false, error: "Session connection not found" };
const result = await conn.revertSession(id, messageID, partID);
return { success: true, data: result };
} catch (err) {
return { success: false, error: err.message };
}
},
);
ipcMain.handle("opencode:session:unrevert", async (_event, id) => {
try {
const conn = getConnectionForSession(id);
if (!conn)
return { success: false, error: "Session connection not found" };
const result = await conn.unrevertSession(id);
return { success: true, data: result };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("opencode:session:fork", async (_event, id, messageID) => {
try {
const conn = getConnectionForSession(id);
if (!conn)
return { success: false, error: "Session connection not found" };
const result = await conn.forkSession(id, messageID);
// Register the new forked session in the directory map so future
// operations can find the correct connection.
if (result?.id) {
const dir = [...connections.entries()].find(([, c]) => c === conn)?.[0];
if (dir) sessionDirectoryMap.set(result.id, dir);
}
return { success: true, data: result };
} catch (err) {
return { success: false, error: err.message };
}
});
// --- Providers / models (global - use any connection) ---
ipcMain.handle("opencode:providers", async () => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
return { success: true, data: await conn.getProviders() };
} catch (err) {
return { success: false, error: err.message };
}
});
// --- Provider management (global) ---
ipcMain.handle("opencode:provider:list", async () => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
return { success: true, data: await conn.listAllProviders() };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle("opencode:provider:auth-methods", async () => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
return { success: true, data: await conn.getProviderAuthMethods() };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle(
"opencode:provider:connect",
async (_event, providerID, auth) => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
await conn.setProviderAuth(providerID, auth);
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
},
);
ipcMain.handle("opencode:provider:disconnect", async (_event, providerID) => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
await conn.removeProviderAuth(providerID);
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle(
"opencode:provider:oauth:authorize",
async (_event, providerID, method) => {
try {
const conn = getAnyConnection();
if (!conn) return { success: false, error: "No connection available" };
return {
success: true,
data: await conn.oauthAuthorize(providerID, method),
};
} catch (err) {
return { success: false, error: err.message };
}
},
);
ipcMain.handle(
"opencode:provider:oauth:callback",
async (_event, providerID, method, code) => {
try {
const conn = getAnyConnection();