@sideboard-ai/core 0.1.348 → 0.1.350

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.
Files changed (84) hide show
  1. package/dist/{abletime-CGFJZB7L.js → abletime-TX7BTTR2.js} +5 -5
  2. package/dist/{abletime-3HRWLQZJ.js → abletime-URSRZW7P.js} +4 -4
  3. package/dist/{abletime-oauth-QNJQLHR4.js → abletime-oauth-QS3WPSCC.js} +3 -3
  4. package/dist/{abletime-oauth-JQDSH5OL.js → abletime-oauth-SL3NMNEC.js} +4 -4
  5. package/dist/{abletime-rest-TANL5TMY.js → abletime-rest-GGQLUO55.js} +3 -3
  6. package/dist/{abletime-rest-UQA2CRZN.js → abletime-rest-JZU6JJCV.js} +4 -4
  7. package/dist/agents/acp-runner.cjs +491 -0
  8. package/dist/agents/acp-runner.d.cts +46 -0
  9. package/dist/agents/acp-runner.d.ts +46 -0
  10. package/dist/agents/acp-runner.js +323 -0
  11. package/dist/agents/cursor-runner.js +3 -3
  12. package/dist/{agents-T4XBZZDA.js → agents-P5QIV24I.js} +38 -8
  13. package/dist/{agents-5MFGVK7C.js → agents-RGAV5OHD.js} +44 -13
  14. package/dist/{app-settings-SNOPJ7P5.js → app-settings-IA7ZZKWQ.js} +2 -2
  15. package/dist/{app-settings-PPIMYJKS.js → app-settings-XILTSD6L.js} +1 -1
  16. package/dist/{chunk-UGUWFONI.js → chunk-2E2HMJDU.js} +1 -1
  17. package/dist/{chunk-OH3BAUMC.js → chunk-2MESZ5XR.js} +273 -84
  18. package/dist/{chunk-RUIHNWRV.js → chunk-37ZBEBP6.js} +6 -6
  19. package/dist/{chunk-Y6VQX2LY.js → chunk-5AHWUJRT.js} +1927 -1718
  20. package/dist/{chunk-7B2OUQON.js → chunk-5TCMXEYL.js} +48 -3
  21. package/dist/{chunk-FDYMVJFU.js → chunk-5WF54R3B.js} +5 -5
  22. package/dist/{chunk-PVCECFJK.js → chunk-7ZD4OK6G.js} +1 -1
  23. package/dist/{chunk-RYPD7XWV.js → chunk-B4EFQTMP.js} +5 -5
  24. package/dist/chunk-BF6INES4.js +144 -0
  25. package/dist/{chunk-IVRWRYTH.js → chunk-BZK62VPT.js} +2 -2
  26. package/dist/{chunk-AJMERXZP.js → chunk-CCWQ65VD.js} +2 -2
  27. package/dist/{chunk-62ALWH3T.js → chunk-DL4OHDBV.js} +3 -3
  28. package/dist/{chunk-6TV6L2DD.js → chunk-EZ2MUWNW.js} +7 -6
  29. package/dist/{chunk-4NXGVJA6.js → chunk-F4RFFE2H.js} +48 -3
  30. package/dist/{chunk-E77SRVVO.js → chunk-FCKTBE26.js} +1 -1
  31. package/dist/{chunk-NTY5WGRD.js → chunk-FQ3JYUKI.js} +2 -2
  32. package/dist/{chunk-CEQ4Z32M.js → chunk-J4EA5SHF.js} +3 -3
  33. package/dist/{chunk-ORO4ENZR.js → chunk-LESWJ7L4.js} +1 -0
  34. package/dist/{chunk-XNGW4OYD.js → chunk-LFSTOECH.js} +7 -6
  35. package/dist/{chunk-OHUAAX3O.js → chunk-M45WGODR.js} +2 -2
  36. package/dist/{chunk-ZJMYCDYQ.js → chunk-MANERA6F.js} +55 -10
  37. package/dist/{chunk-Q4TZA4MN.js → chunk-NDEVAA34.js} +1629 -1486
  38. package/dist/{chunk-OPXEJJBM.js → chunk-PWOFUPYM.js} +1 -0
  39. package/dist/{chunk-UJMCTGV7.js → chunk-PXSWVZIL.js} +2 -2
  40. package/dist/{chunk-MOUAM6ZC.js → chunk-SMSD6U3N.js} +135 -3
  41. package/dist/{chunk-ATS7SYHG.js → chunk-TCEUNSLX.js} +135 -3
  42. package/dist/chunk-TRMPDDVL.js +232 -0
  43. package/dist/{chunk-6WMNIX2U.js → chunk-UFUAIVNV.js} +9 -5
  44. package/dist/{chunk-2HPVGTHF.js → chunk-VHQ6OG3U.js} +2 -2
  45. package/dist/{chunk-WWU4SYZR.js → chunk-VL6F2KRE.js} +5 -1
  46. package/dist/{chunk-WMD77UCY.js → chunk-W5GHFT7E.js} +279 -87
  47. package/dist/{chunk-5FUAOU3G.js → chunk-WB3G2LQO.js} +1 -1
  48. package/dist/{chunk-JCYGQKER.js → chunk-WFX4ZVSZ.js} +1 -1
  49. package/dist/{chunk-F7WP2U5I.js → chunk-WJURGCBR.js} +1 -1
  50. package/dist/{chunk-BIM24I3O.js → chunk-WWBPK7GB.js} +1 -1
  51. package/dist/chunk-YE7Z5WH3.js +142 -0
  52. package/dist/{chunk-5YCKATG6.js → chunk-YVN7L4KG.js} +1 -1
  53. package/dist/{chunk-GAGTEI6B.js → chunk-ZBSEJIOV.js} +56 -11
  54. package/dist/{conductor-LYQKONSA.js → conductor-HVOGBK63.js} +7 -6
  55. package/dist/{conductor-EMGMDNHL.js → conductor-VGCXUUG6.js} +9 -8
  56. package/dist/connected-teams-2YDE2EZ2.js +1 -1
  57. package/dist/{coordinator-prompt-DLY3FS2L.js → coordinator-prompt-DPO7L2JO.js} +5 -5
  58. package/dist/{coordinator-prompt-WALVMGKI.js → coordinator-prompt-E736TJBS.js} +4 -4
  59. package/dist/{global-workspace-UG2A3CEM.js → global-workspace-4RDPAOTT.js} +5 -5
  60. package/dist/{global-workspace-7OQ5O6JT.js → global-workspace-TG2TVLUF.js} +4 -4
  61. package/dist/index.cjs +2881 -1761
  62. package/dist/index.d.cts +140 -877
  63. package/dist/index.d.ts +140 -877
  64. package/dist/index.js +865 -559
  65. package/dist/{linear-PKYJH4WK.js → linear-E3BX5PX5.js} +2 -2
  66. package/dist/{linear-MIJO6DCV.js → linear-WG23LBCX.js} +3 -3
  67. package/dist/{linear-list-JPQ27RXG.js → linear-list-OINZWVV5.js} +1 -1
  68. package/dist/{linear-list-N57PR6JM.js → linear-list-VU47BNUV.js} +1 -1
  69. package/dist/mcp/run-stdio.cjs +2112 -1287
  70. package/dist/mcp/run-stdio.js +318 -230
  71. package/dist/{optional-cli-4GTEDEYJ.js → optional-cli-K6HX2X5O.js} +4 -3
  72. package/dist/{optional-cli-RPJIQBDX.js → optional-cli-SA3EQYML.js} +6 -5
  73. package/dist/{orchestrator-KNOMW5CZ.js → orchestrator-3I2FLEZL.js} +20 -18
  74. package/dist/{orchestrator-4SXTORD2.js → orchestrator-QDHZ56LA.js} +12 -11
  75. package/dist/thread-CJRchYLj.d.cts +856 -0
  76. package/dist/thread-CJRchYLj.d.ts +856 -0
  77. package/dist/{thread-store-R3G5VBII.js → thread-store-4YTOV2HL.js} +3 -3
  78. package/dist/{thread-store-MEUWZDVV.js → thread-store-LME2ICZP.js} +2 -2
  79. package/dist/{workspaces-KWGTP7DI.js → workspaces-4PA24IX6.js} +4 -4
  80. package/dist/{workspaces-35T6FW57.js → workspaces-6TMYV4N2.js} +5 -5
  81. package/dist/{worktree-ROJXGBWS.js → worktree-4ATMCYIE.js} +3 -3
  82. package/dist/{worktree-5P7SCST3.js → worktree-DA6SKIU5.js} +4 -4
  83. package/package.json +3 -3
  84. /package/dist/{chunk-XOEKCE6L.js → chunk-OHXNGBC4.js} +0 -0
@@ -9,16 +9,23 @@ import {
9
9
  looksLikeSkillBody,
10
10
  skillCommandFromBody,
11
11
  withEventParentId
12
- } from "./chunk-ORO4ENZR.js";
12
+ } from "./chunk-LESWJ7L4.js";
13
+ import {
14
+ acpHarnessLabel,
15
+ defaultAcpHarness,
16
+ detectAcpHarness,
17
+ isAcpHarnessId,
18
+ resolveAcpHarnessCommand
19
+ } from "./chunk-BF6INES4.js";
13
20
  import {
14
21
  isOrchestratorThread
15
- } from "./chunk-6TV6L2DD.js";
22
+ } from "./chunk-EZ2MUWNW.js";
16
23
  import {
17
24
  codexUnattendedGitConfigArgs,
18
25
  mergeAgentGitAuthEnv,
19
26
  resolveAgentGitAuthEnv,
20
27
  resolveCodexGitWritableRoots
21
- } from "./chunk-2HPVGTHF.js";
28
+ } from "./chunk-VHQ6OG3U.js";
22
29
  import {
23
30
  applyConnectedTeamToCli,
24
31
  brightsyMcpServerName,
@@ -33,7 +40,7 @@ import {
33
40
  } from "./chunk-2GPQZZLY.js";
34
41
  import {
35
42
  listAssignedLinearIssues
36
- } from "./chunk-JCYGQKER.js";
43
+ } from "./chunk-WFX4ZVSZ.js";
37
44
  import {
38
45
  githubAgentAuthReady,
39
46
  npmGlobalNodeModules,
@@ -45,7 +52,7 @@ import {
45
52
  CLAUDE_POSTHOG_CONNECTOR_ALLOWED_TOOLS,
46
53
  CLAUDE_PRINT_BG_WAIT_CEILING_MS,
47
54
  mcpAllowToolsFromNames
48
- } from "./chunk-MOUAM6ZC.js";
55
+ } from "./chunk-SMSD6U3N.js";
49
56
  import {
50
57
  claudeChromeEnabled,
51
58
  fromInclusiveInputUsage,
@@ -56,7 +63,7 @@ import {
56
63
  requestOccupancy,
57
64
  resolveAgentExecutable,
58
65
  resolveClaudeExecutable
59
- } from "./chunk-WWU4SYZR.js";
66
+ } from "./chunk-VL6F2KRE.js";
60
67
  import {
61
68
  isElectronLikeCommand,
62
69
  unwrapStrippedElectronLaunch,
@@ -66,1852 +73,2041 @@ import {
66
73
  appDataDir
67
74
  } from "./chunk-WOU343SI.js";
68
75
 
69
- // src/agents/brightsy.ts
70
- import { existsSync } from "fs";
76
+ // src/agents/acp.ts
77
+ import { existsSync as existsSync8 } from "fs";
78
+ import { createRequire as createRequire2 } from "module";
79
+ import { homedir as homedir6 } from "os";
80
+ import { dirname as dirname4, join as join9 } from "path";
81
+ import { fileURLToPath as fileURLToPath2 } from "url";
71
82
 
72
- // src/agents/brightsy-targets.ts
73
- function encodeBrightsyTarget(type, id, accountId) {
74
- if (accountId) return `team:${accountId}:${type}:${id}`;
75
- return `${type}:${id}`;
76
- }
77
- function decodeBrightsyTarget(model) {
78
- const raw = model?.trim();
79
- if (!raw || raw === "default" || raw === "agent:default") {
80
- return { type: "agent", id: "default" };
81
- }
82
- const teamMatch = raw.match(/^team:([^:]+):(agent|model):(.+)$/);
83
- if (teamMatch) {
84
- return {
85
- type: teamMatch[2],
86
- id: teamMatch[3] || "default",
87
- accountId: teamMatch[1]
88
- };
89
- }
90
- if (raw.startsWith("agent:")) {
91
- return { type: "agent", id: raw.slice("agent:".length) || "default" };
92
- }
93
- if (raw.startsWith("model:")) {
94
- return { type: "model", id: raw.slice("model:".length) };
95
- }
96
- if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw) || raw === "default") {
97
- return { type: "agent", id: raw };
83
+ // src/agents/acp-protocol.ts
84
+ function acpStdioServerFromEntry(name, entry) {
85
+ const trimmed = name.trim();
86
+ if (!trimmed) return null;
87
+ const type = typeof entry.type === "string" ? entry.type : "";
88
+ if (type === "http" || type === "sse" || typeof entry.url === "string") return null;
89
+ const command = typeof entry.command === "string" ? entry.command.trim() : "";
90
+ if (!command) return null;
91
+ const args = Array.isArray(entry.args) ? entry.args.filter((item) => typeof item === "string") : [];
92
+ const env = [];
93
+ const rawEnv = entry.env;
94
+ if (rawEnv && typeof rawEnv === "object" && !Array.isArray(rawEnv)) {
95
+ for (const [key, value] of Object.entries(rawEnv)) {
96
+ if (key === "ELECTRON_RUN_AS_NODE" || typeof value !== "string") continue;
97
+ env.push({ name: key, value });
98
+ }
98
99
  }
99
- return { type: "model", id: raw };
100
- }
101
-
102
- // src/agents/turn-input.ts
103
- function normalizeTurnInput(input) {
104
- if (typeof input === "string") return { prompt: input };
105
- return {
106
- prompt: input.prompt,
107
- cachedPrefix: input.cachedPrefix?.trim() || void 0,
108
- systemPrompt: input.systemPrompt?.trim() || void 0,
109
- ...input.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
110
- };
100
+ return { name: trimmed, command, args, env };
111
101
  }
112
- function dropCachedPrefixOnResume(input, sessionId) {
113
- const turn = normalizeTurnInput(input);
114
- if (sessionId) {
115
- return {
116
- prompt: turn.prompt,
117
- ...turn.systemPrompt ? { systemPrompt: turn.systemPrompt } : {},
118
- ...turn.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
119
- };
102
+ function acpUserStdioServers(entries, taken) {
103
+ const out = [];
104
+ for (const [name, entry] of Object.entries(entries)) {
105
+ if (taken.has(name.trim())) continue;
106
+ const server = acpStdioServerFromEntry(name, entry);
107
+ if (server) out.push(server);
120
108
  }
121
- return turn;
122
- }
123
- function flattenTurnInput(input) {
124
- const { cachedPrefix, prompt, systemPrompt } = normalizeTurnInput(input);
125
- if (cachedPrefix) return `${cachedPrefix}
126
-
127
- ---
128
-
129
- Current request:
130
- ${prompt}`;
131
- if (systemPrompt) return `${systemPrompt}
132
-
133
- ${prompt}`;
134
- return prompt;
135
- }
136
- function splitTurnInputForSystemPrompt(input) {
137
- const turn = normalizeTurnInput(input);
138
- return {
139
- promptText: flattenTurnInput({ cachedPrefix: turn.cachedPrefix, prompt: turn.prompt }),
140
- systemPrompt: turn.systemPrompt
141
- };
109
+ return out;
142
110
  }
143
-
144
- // src/agents/brightsy.ts
145
- function usageFromBrightsy(usage) {
146
- if (!usage) return null;
147
- const mapped = fromInclusiveInputUsage({
148
- inputTokens: Number(usage.prompt_tokens ?? 0),
149
- outputTokens: Number(usage.completion_tokens ?? 0),
150
- cachedInputTokens: Number(usage.prompt_tokens_details?.cached_tokens ?? 0)
151
- });
152
- if (!mapped) return null;
153
- if (usage.cost != null && Number.isFinite(Number(usage.cost))) {
154
- mapped.costUsd = Number(usage.cost);
155
- }
156
- return mapped;
111
+ function toAcpMcpServers(servers) {
112
+ return servers.map((server) => ({
113
+ name: server.name,
114
+ command: server.command,
115
+ args: server.args ?? [],
116
+ env: Object.entries(server.env ?? {}).map(([name, value]) => ({ name, value }))
117
+ }));
157
118
  }
158
- function parseBrightsyCliLine(line) {
119
+ function acpPriorTranscript(messages) {
120
+ const rows = [];
121
+ for (const message of messages) {
122
+ if (message.role !== "user" && message.role !== "agent" && message.role !== "summary") {
123
+ continue;
124
+ }
125
+ const text = message.text?.trim() ?? "";
126
+ if (!text) continue;
127
+ rows.push({ role: message.role, text });
128
+ }
129
+ const last = rows[rows.length - 1];
130
+ if (last?.role === "user") rows.pop();
131
+ return rows;
132
+ }
133
+ var AGENT_EVENT_TYPES = /* @__PURE__ */ new Set([
134
+ "stdout",
135
+ "stderr",
136
+ "session_id",
137
+ "thinking",
138
+ "tool_use",
139
+ "tool_result",
140
+ "usage",
141
+ "exit"
142
+ ]);
143
+ function parseAcpRunnerLine(line) {
159
144
  const trimmed = line.trim();
160
- if (!trimmed) return null;
145
+ if (!trimmed.startsWith("{")) return null;
161
146
  try {
162
- const obj = JSON.parse(trimmed);
163
- if (obj.type === "text" && typeof obj.text === "string") {
164
- if (looksLikeBrightsyEmptyCompletion(obj.text)) {
165
- return [
166
- { type: "stderr", data: obj.text },
167
- { type: "stdout", data: `Error: ${obj.text}` }
168
- ];
169
- }
170
- return { type: "stdout", data: obj.text };
171
- }
172
- if (obj.type === "thinking" && typeof obj.text === "string") {
173
- return { type: "thinking", data: obj.text };
174
- }
175
- if (obj.type === "error") {
176
- const msg = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
177
- return [
178
- { type: "stderr", data: msg },
179
- { type: "stdout", data: `Error: ${msg}` }
180
- ];
181
- }
182
- if (obj.type === "usage") {
183
- const usage = usageFromBrightsy(obj.usage);
184
- return usage ? { type: "usage", data: usage } : null;
185
- }
186
- if (obj.type === "tool_use") {
187
- const id = typeof obj.id === "string" && obj.id || `brightsy-tool-${Date.now()}`;
188
- const name = typeof obj.name === "string" && obj.name || "brightsy_tool";
189
- const input = obj.input && typeof obj.input === "object" && !Array.isArray(obj.input) ? obj.input : void 0;
190
- return { type: "tool_use", id, name, input };
191
- }
192
- if (obj.type === "tool_result" || obj.type === "tool") {
193
- const id = typeof obj.id === "string" && obj.id || typeof obj.tool_call_id === "string" && obj.tool_call_id || `brightsy-tool-${Date.now()}`;
194
- const content = typeof obj.content === "string" ? obj.content : obj.content != null ? JSON.stringify(obj.content) : void 0;
195
- return {
196
- type: "tool_result",
197
- id,
198
- content,
199
- isError: obj.isError === true
200
- };
201
- }
202
- if (obj.type === "done") return null;
203
- if (typeof obj.type === "string" && ["tool_use", "tool_result", "tool", "thinking", "usage", "error", "done", "text"].includes(
204
- obj.type
205
- )) {
206
- return null;
207
- }
208
- return { type: "stdout", data: trimmed };
147
+ const parsed = JSON.parse(trimmed);
148
+ if (typeof parsed.type !== "string" || !AGENT_EVENT_TYPES.has(parsed.type)) return null;
149
+ return parsed;
209
150
  } catch {
210
- if (trimmed.startsWith("{") && /"type"\s*:\s*"(tool_use|tool_result|tool|text|thinking|usage|done|error)"/.test(trimmed)) {
211
- return null;
212
- }
213
- if (looksLikeBrightsyEmptyCompletion(trimmed) || /error|failed|unauthorized|quota|limit|not logged in/i.test(trimmed)) {
214
- return [
215
- { type: "stderr", data: trimmed },
216
- { type: "stdout", data: `Error: ${trimmed}` }
217
- ];
218
- }
219
- return { type: "stdout", data: line };
151
+ return null;
220
152
  }
221
153
  }
222
- function adjustBrightsyTurnExit(exitCode, assistantText) {
223
- if (looksLikeBrightsyEmptyCompletion(assistantText) && (exitCode === 0 || exitCode == null)) {
224
- return 2;
154
+
155
+ // src/agents/orch-mcp-isolation.ts
156
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "fs";
157
+
158
+ // src/agents/claude-plugins.ts
159
+ import { existsSync, readFileSync } from "fs";
160
+ import { homedir } from "os";
161
+ import { isAbsolute, join, relative, resolve } from "path";
162
+
163
+ // src/mcp-ui/meta.ts
164
+ var HTML_MAX = 15e5;
165
+ function matchClaudeMcpTool(toolName, serverNames) {
166
+ const name = toolName.trim();
167
+ if (!name.startsWith("mcp__")) return null;
168
+ const ranked = [...serverNames].filter((s) => s.trim()).sort((a, b) => b.length - a.length);
169
+ for (const server of ranked) {
170
+ const prefix = `mcp__${server}__`;
171
+ if (!name.startsWith(prefix)) continue;
172
+ const tool = name.slice(prefix.length).trim();
173
+ if (!tool) continue;
174
+ return { server, tool };
225
175
  }
226
- return exitCode;
176
+ return null;
227
177
  }
228
- async function fetchTeamChatTargets(team) {
229
- const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
230
- let agents = [
231
- {
232
- type: "agent",
233
- id: "default",
234
- name: "Default Agent",
235
- description: "Account default agent (tools + memory)",
236
- accountId: team.id,
237
- accountSlug: team.slug,
238
- accountName: team.name
239
- }
240
- ];
241
- let models = [];
178
+ function parseMcpServerLaunch(entry) {
179
+ const command = typeof entry.command === "string" ? entry.command.trim() : "";
180
+ if (command) {
181
+ const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
182
+ const env = stringRecord(entry.env);
183
+ const cwd = typeof entry.cwd === "string" && entry.cwd.trim() ? entry.cwd.trim() : void 0;
184
+ return {
185
+ kind: "stdio",
186
+ command,
187
+ args,
188
+ ...env ? { env } : {},
189
+ ...cwd ? { cwd } : {}
190
+ };
191
+ }
192
+ const url = typeof entry.url === "string" ? entry.url.trim() : "";
193
+ if (!url) return null;
194
+ let parsed;
242
195
  try {
243
- const res = await fetch(`${endpoint}/api/v1beta/${team.id}/agents`, {
244
- headers: { Authorization: `Bearer ${team.access_token}` }
245
- });
246
- if (res.ok) {
247
- const json = await res.json();
248
- const listed = (json.data || []).filter(
249
- (a) => Boolean(a?.id && a?.name)
250
- ).filter((a) => a.id !== "default").map((a) => ({
251
- type: "agent",
252
- id: a.id,
253
- name: a.name,
254
- description: a.description,
255
- accountId: team.id,
256
- accountSlug: team.slug,
257
- accountName: team.name
258
- }));
259
- agents = [...agents, ...listed];
260
- if (Array.isArray(json.models)) {
261
- models = json.models.filter(
262
- (m) => Boolean(m?.id && m?.name)
263
- ).slice(0, 12).map((m) => ({
264
- type: "model",
265
- id: m.id,
266
- name: m.name,
267
- description: m.description,
268
- accountId: team.id,
269
- accountSlug: team.slug,
270
- accountName: team.name
271
- }));
272
- }
273
- }
196
+ parsed = new URL(url);
274
197
  } catch {
198
+ return null;
275
199
  }
200
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
201
+ const type = typeof entry.type === "string" ? entry.type.trim().toLowerCase() : "";
202
+ const headers = stringRecord(entry.headers);
276
203
  return {
277
- accountId: team.id,
278
- accountSlug: team.slug,
279
- accountName: team.name,
280
- agents,
281
- models
204
+ kind: type === "sse" ? "sse" : "http",
205
+ url: parsed.toString(),
206
+ ...headers ? { headers } : {}
282
207
  };
283
208
  }
284
- async function listBrightsyChatTargetsViaCli() {
285
- const listed = await run(
286
- resolveAgentExecutable("brightsy"),
287
- ["chat", "--list-targets", "--json"],
288
- {
289
- reject: false
290
- }
291
- );
292
- if (listed.exitCode !== 0 || !listed.stdout.trim()) {
293
- throw new Error(
294
- listed.stderr.trim() || "Failed to list Brightsy chat targets \u2014 is `brightsy` installed and logged in?"
295
- );
296
- }
297
- try {
298
- const parsed = JSON.parse(listed.stdout);
299
- let accountId = null;
300
- let accountSlug = "team";
301
- let accountName = "Brightsy";
302
- try {
303
- const cfg = loadBrightsyConfig();
304
- accountId = cfg.account_id;
305
- accountSlug = cfg.account_slug || accountSlug;
306
- accountName = cfg.account_slug || accountName;
307
- } catch {
308
- }
309
- const agents = (Array.isArray(parsed.agents) ? parsed.agents : []).map((a) => ({
310
- ...a,
311
- accountId: accountId ?? void 0,
312
- accountSlug,
313
- accountName
314
- }));
315
- const models = (Array.isArray(parsed.models) ? parsed.models : []).map((m) => ({
316
- ...m,
317
- accountId: accountId ?? void 0,
318
- accountSlug,
319
- accountName
320
- }));
321
- const teams = accountId ? [
322
- {
323
- accountId,
324
- accountSlug,
325
- accountName,
326
- agents,
327
- models
328
- }
329
- ] : [];
330
- return { teams, agents, models, activeAccountId: accountId };
331
- } catch {
332
- throw new Error("Brightsy --list-targets returned invalid JSON");
209
+ function uiResourceUriFromMeta(meta) {
210
+ const rec = asRecord(meta);
211
+ const nested = asRecord(rec.ui);
212
+ const fromNested = typeof nested.resourceUri === "string" ? nested.resourceUri.trim() : "";
213
+ const legacy = typeof rec["ui/resourceUri"] === "string" ? rec["ui/resourceUri"].trim() : "";
214
+ const uri = fromNested || legacy;
215
+ return uri.startsWith("ui://") ? uri : null;
216
+ }
217
+ function cspFromMeta(meta) {
218
+ const ui = asRecord(asRecord(meta).ui);
219
+ const csp = asRecord(ui.csp);
220
+ const connectDomains = originList(csp.connectDomains);
221
+ const resourceDomains = originList(csp.resourceDomains);
222
+ const frameDomains = originList(csp.frameDomains);
223
+ const baseUriDomains = originList(csp.baseUriDomains);
224
+ if (!connectDomains?.length && !resourceDomains?.length && !frameDomains?.length && !baseUriDomains?.length) {
225
+ return void 0;
333
226
  }
227
+ return {
228
+ ...connectDomains?.length ? { connectDomains } : {},
229
+ ...resourceDomains?.length ? { resourceDomains } : {},
230
+ ...frameDomains?.length ? { frameDomains } : {},
231
+ ...baseUriDomains?.length ? { baseUriDomains } : {}
232
+ };
334
233
  }
335
- async function listBrightsyChatTargets() {
336
- ensureCliTeamTracked();
337
- const teamsRaw = await ensureConnectedBrightsyTeamTokens();
338
- if (teamsRaw.length === 0) {
339
- return listBrightsyChatTargetsViaCli();
234
+ function htmlFromResourceContent(content) {
235
+ const uri = content.uri?.trim() ?? "";
236
+ if (!uri.startsWith("ui://")) return null;
237
+ const mimeType = content.mimeType?.trim() || "text/html";
238
+ if (!isHtmlMime(mimeType)) return null;
239
+ const html = htmlText(content.text, content.blob);
240
+ if (!html) return null;
241
+ return { uri, mimeType, html };
242
+ }
243
+ function mcpUiContentSecurityPolicy(csp) {
244
+ const resource = (csp?.resourceDomains ?? []).join(" ");
245
+ const connect = (csp?.connectDomains ?? []).join(" ");
246
+ const frames = csp?.frameDomains?.length ? csp.frameDomains.join(" ") : "'none'";
247
+ const base = csp?.baseUriDomains?.length ? csp.baseUriDomains.join(" ") : "'none'";
248
+ const connectSrc = connect ? `'self' ${connect}`.trim() : "'none'";
249
+ return [
250
+ "default-src 'none'",
251
+ `script-src 'self' 'unsafe-inline' ${resource}`.trim(),
252
+ `style-src 'self' 'unsafe-inline' ${resource}`.trim(),
253
+ `img-src 'self' data: ${resource}`.trim(),
254
+ `font-src 'self' ${resource}`.trim(),
255
+ `connect-src ${connectSrc}`,
256
+ `media-src 'self' data: ${resource}`.trim(),
257
+ `frame-src ${frames}`,
258
+ `base-uri ${base}`,
259
+ "object-src 'none'"
260
+ ].join("; ");
261
+ }
262
+ function htmlText(text, blob) {
263
+ if (typeof text === "string" && text.trim()) {
264
+ return text.length <= HTML_MAX ? text : null;
340
265
  }
341
- let activeAccountId = null;
266
+ if (typeof blob !== "string" || !blob.trim()) return null;
342
267
  try {
343
- activeAccountId = loadBrightsyConfig().account_id;
268
+ const decoded = decodeBase64(blob.trim());
269
+ if (!decoded.trim() || decoded.length > HTML_MAX) return null;
270
+ return decoded;
344
271
  } catch {
345
- activeAccountId = teamsRaw[0]?.id ?? null;
272
+ return null;
346
273
  }
347
- const teams = await Promise.all(teamsRaw.map((t) => fetchTeamChatTargets(t)));
348
- teams.sort((a, b) => {
349
- if (a.accountId === activeAccountId) return -1;
350
- if (b.accountId === activeAccountId) return 1;
351
- return a.accountSlug.localeCompare(b.accountSlug);
352
- });
353
- const active = teams.find((t) => t.accountId === activeAccountId) ?? teams[0] ?? null;
354
- return {
355
- teams,
356
- agents: active?.agents ?? [],
357
- models: active?.models ?? [],
358
- activeAccountId
359
- };
360
274
  }
361
- async function syncCliForTarget(accountId) {
362
- if (!accountId) return;
363
- const teams = await ensureConnectedBrightsyTeamTokens();
364
- const team = teams.find((t) => t.id === accountId);
365
- if (!team) return;
275
+ function decodeBase64(blob) {
276
+ if (typeof Buffer !== "undefined") return Buffer.from(blob, "base64").toString("utf8");
277
+ const bin = atob(blob);
278
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
279
+ return new TextDecoder().decode(bytes);
280
+ }
281
+ function isHtmlMime(mime) {
282
+ const base = mime.split(";")[0]?.trim().toLowerCase() ?? "";
283
+ return base === "text/html";
284
+ }
285
+ function originList(value) {
286
+ if (!Array.isArray(value)) return void 0;
287
+ const out = [];
288
+ for (const item of value) {
289
+ if (typeof item !== "string") continue;
290
+ const origin = originToken(item);
291
+ if (origin && !out.includes(origin)) out.push(origin);
292
+ }
293
+ return out;
294
+ }
295
+ function originToken(value) {
296
+ const trimmed = value.trim();
297
+ if (/^(https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?$/i.test(trimmed)) return trimmed;
366
298
  try {
367
- const cfg = loadBrightsyConfig();
368
- if (cfg.account_id === team.id && cfg.access_token === team.access_token) {
369
- return;
299
+ const url = new URL(trimmed);
300
+ if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "wss:" && url.protocol !== "ws:") {
301
+ return null;
370
302
  }
303
+ return url.origin;
371
304
  } catch {
305
+ return null;
372
306
  }
373
- applyConnectedTeamToCli(team);
374
307
  }
375
- var brightsyAdapter = {
376
- kind: "brightsy",
377
- async detect() {
378
- const brightsy = resolveAgentExecutable("brightsy");
379
- if (brightsy !== "brightsy") {
380
- if (!existsSync(brightsy)) {
381
- return {
382
- agent: "brightsy",
383
- installed: false,
384
- authenticated: false,
385
- linearMcp: false,
386
- warnings: [],
387
- reason: `Brightsy executable not found: ${brightsy}`
388
- };
389
- }
390
- } else {
391
- const which = await run("which", ["brightsy"], { reject: false });
392
- if (which.exitCode !== 0) {
393
- return {
394
- agent: "brightsy",
395
- installed: false,
396
- authenticated: false,
397
- linearMcp: false,
398
- warnings: [],
399
- reason: "brightsy CLI not found on PATH \u2014 npm i -g @brightsy/cli"
400
- };
401
- }
402
- }
403
- const who = await run(brightsy, ["whoami"], { reject: false });
404
- const authenticated = who.exitCode === 0 && /logged in as/i.test(who.stdout);
405
- return {
406
- agent: "brightsy",
407
- installed: true,
408
- authenticated,
409
- linearMcp: false,
410
- warnings: [],
411
- reason: authenticated ? void 0 : "not logged in \u2014 run `brightsy login`"
412
- };
413
- },
414
- async buildTurn(thread, input) {
415
- const prompt = flattenTurnInput(input);
416
- const target = decodeBrightsyTarget(thread.model);
417
- await syncCliForTarget(target.accountId);
418
- const mode = thread.planMode ? "plan" : target.type === "model" ? "ask" : "agent";
419
- const args = [
420
- "chat",
421
- "--json",
422
- "--mode",
423
- mode,
424
- target.type === "model" ? "--model" : "--agent",
425
- target.id
426
- ];
427
- return {
428
- file: resolveAgentExecutable("brightsy"),
429
- args,
430
- cwd: thread.worktreePath,
431
- // Piped stdin becomes the message body (avoids ARG_MAX for long seeds).
432
- stdin: prompt
433
- };
434
- },
435
- parseEvent(line) {
436
- return parseBrightsyCliLine(line);
437
- },
438
- async resolveSessionId() {
439
- return null;
440
- },
441
- async buildAttach(thread) {
442
- const target = decodeBrightsyTarget(thread.model);
443
- await syncCliForTarget(target.accountId);
444
- const args = target.type === "model" ? ["chat", "--model", target.id] : ["chat", "--agent", target.id];
445
- return {
446
- file: resolveAgentExecutable("brightsy"),
447
- args,
448
- cwd: thread.worktreePath
449
- };
308
+ function stringRecord(value) {
309
+ const rec = asRecord(value);
310
+ const out = {};
311
+ for (const [key, item] of Object.entries(rec)) {
312
+ if (typeof item === "string") out[key] = item;
450
313
  }
451
- };
452
-
453
- // src/agents/claude.ts
454
- import { existsSync as existsSync12 } from "fs";
455
- import { dirname as dirname5 } from "path";
314
+ return Object.keys(out).length > 0 ? out : void 0;
315
+ }
316
+ function asRecord(value) {
317
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
318
+ return value;
319
+ }
456
320
 
457
- // src/agents/claude-mcp-status.ts
458
- var SIDEBOARD_CONNECTOR_SERVICES = [
459
- "github",
460
- "linear",
461
- "posthog",
462
- "vercel",
463
- "supabase",
464
- "sentry"
465
- ];
466
- function mcpStatusThinkingFromClaudeInit(obj) {
467
- const raw = obj.mcp_servers ?? obj.mcpServers;
468
- const servers = [];
469
- if (Array.isArray(raw)) {
470
- for (const item of raw) {
471
- if (!item || typeof item !== "object" || Array.isArray(item)) continue;
472
- const rec = item;
473
- const name = typeof rec.name === "string" && rec.name.trim() || typeof rec.server === "string" && rec.server.trim() || "";
474
- const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "";
475
- if (name) servers.push({ name, status: status || "unknown" });
321
+ // src/agents/claude-plugins.ts
322
+ function claudePluginServerId(pluginName, serverName) {
323
+ return `plugin_${pluginName}_${serverName}`.replace(/[^A-Za-z0-9_-]/g, "_");
324
+ }
325
+ function listEnabledClaudePluginMcpServers(opts) {
326
+ const home = opts?.home ?? homedir();
327
+ const pluginsRoot = claudePluginsRoot(home);
328
+ const enabled = enabledPluginIds(home, opts?.projectDirs ?? []);
329
+ const installed = readInstalledPlugins(join(pluginsRoot, "installed_plugins.json"));
330
+ const out = {};
331
+ for (const [id, on] of enabled) {
332
+ if (!on) continue;
333
+ const root = installPathFor(id, installed);
334
+ if (!root || !existsSync(root)) continue;
335
+ const pluginName = manifestName(root) || id.split("@")[0]?.trim() || "";
336
+ if (!pluginName) continue;
337
+ const dataDir = join(pluginsRoot, "data", pluginDataId(id));
338
+ for (const [serverName, entry] of Object.entries(loadPluginMcpServers(root))) {
339
+ const expanded = expandPluginEntry(entry, root, dataDir);
340
+ if (!parseMcpServerLaunch(expanded)) continue;
341
+ const key = claudePluginServerId(pluginName, serverName);
342
+ if (!key || key === "plugin__") continue;
343
+ out[key] = expanded;
476
344
  }
477
- } else if (raw && typeof raw === "object") {
478
- for (const [name, value] of Object.entries(raw)) {
479
- if (!name.trim()) continue;
480
- if (typeof value === "string" && value.trim()) {
481
- servers.push({ name, status: value.trim() });
482
- continue;
483
- }
484
- if (value && typeof value === "object" && !Array.isArray(value)) {
485
- const rec = value;
486
- const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "unknown";
487
- servers.push({ name, status });
488
- }
345
+ }
346
+ return out;
347
+ }
348
+ function claudePluginsRoot(home) {
349
+ const override = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim();
350
+ if (override && isAbsolute(override)) return override;
351
+ return join(home, ".claude", "plugins");
352
+ }
353
+ function pluginDataId(pluginId) {
354
+ return pluginId.replace(/[^A-Za-z0-9_-]/g, "-");
355
+ }
356
+ function enabledPluginIds(home, projectDirs) {
357
+ const enabled = /* @__PURE__ */ new Map();
358
+ applyEnabled(enabled, readEnabledPlugins(join(home, ".claude", "settings.json")));
359
+ const dirs = [...new Set(projectDirs.map((dir) => dir.trim()).filter(Boolean))];
360
+ for (const dir of dirs) {
361
+ applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.json")));
362
+ }
363
+ for (const dir of dirs) {
364
+ applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.local.json")));
365
+ }
366
+ return enabled;
367
+ }
368
+ function applyEnabled(into, next) {
369
+ for (const [id, on] of Object.entries(next)) {
370
+ const key = id.trim();
371
+ if (!key) continue;
372
+ into.set(key, on);
373
+ }
374
+ }
375
+ function readEnabledPlugins(path) {
376
+ const root = readJson(path);
377
+ const raw = root.enabledPlugins;
378
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
379
+ const out = {};
380
+ for (const [id, value] of Object.entries(raw)) {
381
+ if (value === true || value === false) out[id] = value;
382
+ }
383
+ return out;
384
+ }
385
+ function readInstalledPlugins(path) {
386
+ const root = readJson(path);
387
+ const plugins = root.plugins;
388
+ if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) return {};
389
+ const out = {};
390
+ for (const [id, value] of Object.entries(plugins)) {
391
+ const rows = Array.isArray(value) ? value : [value];
392
+ const installs = [];
393
+ for (const row of rows) {
394
+ if (!row || typeof row !== "object" || Array.isArray(row)) continue;
395
+ const installPath = row.installPath;
396
+ installs.push({
397
+ ...typeof installPath === "string" && installPath.trim() ? { installPath: installPath.trim() } : {}
398
+ });
489
399
  }
400
+ if (installs.length) out[id] = installs;
490
401
  }
491
- const coverage = claudeConnectorCoverage();
492
- const sideboardOk = sideboardMcpOk(servers);
493
- const notable = servers.filter(
494
- (server) => isNotableMcpInitStatus(server, sideboardOk, coverage)
495
- );
496
- if (notable.length === 0) return null;
497
- return `MCP: ${notable.map((s) => `${s.name} ${s.status}`).join(", ")}`;
402
+ return out;
498
403
  }
499
- function isCleanMcpConnect(status) {
500
- return /^(connected|ok|ready|success)$/i.test(status.trim());
404
+ function installPathFor(id, installed) {
405
+ const rows = installed[id] ?? [];
406
+ for (let i = rows.length - 1; i >= 0; i--) {
407
+ const path = rows[i]?.installPath;
408
+ if (path && existsSync(path)) return path;
409
+ }
410
+ return null;
501
411
  }
502
- function isMcpAuthStatus(status) {
503
- return /needs[_-]?auth|needs authentication|unauthorized|not authenticated|authrequired/i.test(
504
- status
505
- );
412
+ function manifestName(root) {
413
+ const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
414
+ return typeof manifest.name === "string" ? manifest.name.trim() : "";
506
415
  }
507
- function isSideboardMcpName(name) {
508
- return /^sideboard$/i.test(name.trim()) || /^mcp__sideboard$/i.test(name.trim());
416
+ function loadPluginMcpServers(root) {
417
+ const servers = {};
418
+ mergeServerMap(servers, serversFromFile(join(root, ".mcp.json"), root));
419
+ const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
420
+ mergeServerMap(servers, serversFromManifest(manifest.mcpServers, root));
421
+ return servers;
509
422
  }
510
- function isVendorClaudeAiMcpName(name) {
511
- return /^claude\.ai\b/i.test(name.trim()) || /^mcp__claude_ai_/i.test(name.trim());
423
+ function serversFromManifest(value, root) {
424
+ if (!value) return {};
425
+ if (typeof value === "string") return serversFromFile(resolveInside(root, value), root);
426
+ if (Array.isArray(value)) {
427
+ const out = {};
428
+ for (const item of value) {
429
+ if (typeof item === "string") mergeServerMap(out, serversFromFile(resolveInside(root, item), root));
430
+ else mergeServerMap(out, serverMap(item, root));
431
+ }
432
+ return out;
433
+ }
434
+ return serverMap(value, root);
512
435
  }
513
- function sideboardMcpOk(servers) {
514
- const row = servers.find((server) => isSideboardMcpName(server.name));
515
- return Boolean(row && isCleanMcpConnect(row.status));
436
+ function serversFromFile(path, root) {
437
+ if (!path || !existsSync(path)) return {};
438
+ return serverMap(readJson(path), root);
516
439
  }
517
- function sideboardServiceForClaudeConnector(name) {
518
- const raw = name.trim();
519
- if (!raw || isSideboardMcpName(raw)) return null;
520
- const pluginLike = /^(?:plugin[:_]|mcp__plugin_|claude\.ai\s|(?:mcp__)?claude_ai_)/i.test(raw);
521
- const doubled = raw.match(/^mcp_([a-z0-9]+)_([a-z0-9]+)$/i);
522
- if (!pluginLike && !(doubled && doubled[1].toLowerCase() === doubled[2].toLowerCase())) {
523
- return null;
440
+ function serverMap(value, root) {
441
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
442
+ const record = value;
443
+ const wrapped = record.mcpServers;
444
+ const source = wrapped && typeof wrapped === "object" && !Array.isArray(wrapped) ? wrapped : record;
445
+ if (typeof wrapped === "string") return serversFromFile(resolveInside(root, wrapped), root);
446
+ const out = {};
447
+ for (const [name, entry] of Object.entries(source)) {
448
+ if (!name.trim() || !entry || typeof entry !== "object" || Array.isArray(entry)) continue;
449
+ const row = entry;
450
+ if (row.disabled === true) continue;
451
+ if (typeof row.command !== "string" && typeof row.url !== "string") continue;
452
+ out[name.trim()] = row;
524
453
  }
525
- let body = raw;
526
- if (/^claude\.ai\s+/i.test(body)) body = body.replace(/^claude\.ai\s+/i, "");
527
- else if (/^(?:mcp__)?claude_ai_/i.test(body)) body = body.replace(/^(?:mcp__)?claude_ai_/i, "");
528
- else if (/^mcp__plugin_/i.test(body)) body = body.slice("mcp__plugin_".length);
529
- else if (/^plugin_/i.test(body)) body = body.slice("plugin_".length);
530
- else if (/^plugin:/i.test(body)) body = body.slice("plugin:".length);
531
- else if (/^mcp_/i.test(body)) body = body.slice("mcp_".length);
532
- const head = body.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
533
- if (!head || !SIDEBOARD_CONNECTOR_SERVICES.includes(head)) return null;
534
- return head;
454
+ return out;
535
455
  }
536
- function claudeConnectorCoverage() {
537
- let github = false;
538
- try {
539
- github = githubAgentAuthReady();
540
- } catch {
541
- github = false;
456
+ function mergeServerMap(into, extra) {
457
+ for (const [name, entry] of Object.entries(extra)) into[name] = entry;
458
+ }
459
+ function expandPluginEntry(entry, root, dataDir) {
460
+ const next = { ...entry };
461
+ if (typeof next.command === "string") next.command = expandVars(next.command, root, dataDir);
462
+ if (Array.isArray(next.args)) {
463
+ next.args = next.args.map((arg) => typeof arg === "string" ? expandVars(arg, root, dataDir) : arg);
464
+ }
465
+ if (typeof next.url === "string") next.url = expandVars(next.url, root, dataDir);
466
+ if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) {
467
+ const env = {};
468
+ for (const [key, value] of Object.entries(next.env)) {
469
+ if (typeof value === "string") env[key] = expandVars(value, root, dataDir);
470
+ }
471
+ env.CLAUDE_PLUGIN_ROOT = env.CLAUDE_PLUGIN_ROOT || root;
472
+ env.CLAUDE_PLUGIN_DATA = env.CLAUDE_PLUGIN_DATA || dataDir;
473
+ next.env = env;
474
+ } else if (typeof next.command === "string") {
475
+ next.env = { CLAUDE_PLUGIN_ROOT: root, CLAUDE_PLUGIN_DATA: dataDir };
542
476
  }
543
- let linear = false;
544
- let posthog = false;
545
- let vercel = false;
546
- let supabase = false;
547
- let sentry = false;
477
+ if (next.headers && typeof next.headers === "object" && !Array.isArray(next.headers)) {
478
+ const headers = {};
479
+ for (const [key, value] of Object.entries(next.headers)) {
480
+ if (typeof value === "string") headers[key] = expandVars(value, root, dataDir);
481
+ }
482
+ next.headers = headers;
483
+ }
484
+ return next;
485
+ }
486
+ function expandVars(value, root, dataDir) {
487
+ return value.replaceAll("${CLAUDE_PLUGIN_ROOT}", root).replaceAll("${CLAUDE_PLUGIN_DATA}", dataDir);
488
+ }
489
+ function resolveInside(root, spec) {
490
+ const trimmed = spec.trim();
491
+ if (!trimmed || trimmed.endsWith(".mcpb") || trimmed.endsWith(".dxt")) return null;
492
+ if (/^https?:\/\//i.test(trimmed)) return null;
493
+ const abs = resolve(root, trimmed);
494
+ const rel = relative(root, abs);
495
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
496
+ return abs;
497
+ }
498
+ function readJson(path) {
499
+ if (!existsSync(path)) return {};
548
500
  try {
549
- linear = isLinearConnected();
550
- posthog = isPosthogConnected();
551
- const integrations = loadAppSettings().integrations ?? {};
552
- if (integrations.githubPat?.trim()) github = true;
553
- vercel = Boolean(integrations.vercelToken?.trim());
554
- supabase = Boolean(integrations.supabaseAccessToken?.trim());
555
- sentry = Boolean(integrations.sentryAuthToken?.trim());
501
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
502
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
503
+ return parsed;
556
504
  } catch {
505
+ return {};
557
506
  }
558
- return { github, linear, posthog, vercel, supabase, sentry };
559
- }
560
- function isNotableMcpInitStatus(server, sideboardOk, coverage) {
561
- if (isCleanMcpConnect(server.status)) return false;
562
- if (isSideboardMcpName(server.name)) return true;
563
- if (isMcpAuthStatus(server.status)) return false;
564
- const service = sideboardServiceForClaudeConnector(server.name);
565
- if (service) return !(sideboardOk && coverage[service]);
566
- if (isVendorClaudeAiMcpName(server.name)) return false;
567
- return true;
568
507
  }
569
508
 
570
- // src/mcp-ui/host.ts
571
- import { createHash } from "crypto";
572
- import { homedir as homedir6 } from "os";
573
-
574
509
  // src/agents/orch-mcp-isolation.ts
575
- import { existsSync as existsSync8, readFileSync as readFileSync4 } from "fs";
510
+ import { homedir as homedir5 } from "os";
511
+ import { join as join8 } from "path";
512
+ import { parse as parseToml } from "smol-toml";
576
513
 
577
- // src/agents/claude-plugins.ts
578
- import { existsSync as existsSync2, readFileSync } from "fs";
579
- import { homedir } from "os";
580
- import { isAbsolute, join, relative, resolve } from "path";
514
+ // src/agents/user-mcp-config.ts
515
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
516
+ import { homedir as homedir4 } from "os";
517
+ import { dirname as dirname3, join as join7 } from "path";
581
518
 
582
- // src/mcp-ui/meta.ts
583
- var HTML_MAX = 15e5;
584
- function matchClaudeMcpTool(toolName, serverNames) {
585
- const name = toolName.trim();
586
- if (!name.startsWith("mcp__")) return null;
587
- const ranked = [...serverNames].filter((s) => s.trim()).sort((a, b) => b.length - a.length);
588
- for (const server of ranked) {
589
- const prefix = `mcp__${server}__`;
590
- if (!name.startsWith(prefix)) continue;
591
- const tool = name.slice(prefix.length).trim();
592
- if (!tool) continue;
593
- return { server, tool };
594
- }
595
- return null;
519
+ // src/agents/injected-mcp.ts
520
+ import { existsSync as existsSync5, mkdtempSync, writeFileSync as writeFileSync3 } from "fs";
521
+ import { createRequire } from "module";
522
+ import { tmpdir } from "os";
523
+ import { dirname as dirname2, join as join6 } from "path";
524
+ import { fileURLToPath } from "url";
525
+
526
+ // src/agent-rpc/protocol.ts
527
+ var AGENT_RPC_PROTOCOL_VERSION = 1;
528
+ var AGENT_RPC_TOKEN_QUERY = "authToken";
529
+ var AGENT_RPC_NATIVE_ENV = "SIDEBOARD_AGENT_RPC_NATIVE";
530
+ var AGENT_RPC_URL_ENV = "SIDEBOARD_AGENT_RPC_URL";
531
+ var AGENT_RPC_TOKEN_ENV = "SIDEBOARD_AGENT_RPC_TOKEN";
532
+ var AGENT_RPC_CWD_ENV = "SIDEBOARD_AGENT_RPC_CWD";
533
+ var AGENT_RPC_CLAUDE_SDK_SERVER = "sideboard_rpc";
534
+
535
+ // src/mcp/profile.ts
536
+ var SIDEBOARD_MCP_PROFILE_ENV = "SIDEBOARD_MCP_PROFILE";
537
+ var SIDEBOARD_THREAD_ID_ENV = "SIDEBOARD_THREAD_ID";
538
+ function agentRpcOwnsPilotTools(env = process.env) {
539
+ return env[AGENT_RPC_NATIVE_ENV]?.trim() === "1";
596
540
  }
597
- function parseMcpServerLaunch(entry) {
598
- const command = typeof entry.command === "string" ? entry.command.trim() : "";
599
- if (command) {
600
- const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
601
- const env = stringRecord(entry.env);
602
- const cwd = typeof entry.cwd === "string" && entry.cwd.trim() ? entry.cwd.trim() : void 0;
603
- return {
604
- kind: "stdio",
605
- command,
606
- args,
607
- ...env ? { env } : {},
608
- ...cwd ? { cwd } : {}
609
- };
610
- }
611
- const url = typeof entry.url === "string" ? entry.url.trim() : "";
612
- if (!url) return null;
613
- let parsed;
614
- try {
615
- parsed = new URL(url);
616
- } catch {
617
- return null;
618
- }
619
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
620
- const type = typeof entry.type === "string" ? entry.type.trim().toLowerCase() : "";
621
- const headers = stringRecord(entry.headers);
622
- return {
623
- kind: type === "sse" ? "sse" : "http",
624
- url: parsed.toString(),
625
- ...headers ? { headers } : {}
541
+ function injectedSideboardMcpEnv(opts) {
542
+ const orchId = opts.orchestratorThreadId?.trim();
543
+ const threadId = opts.threadId?.trim() || orchId;
544
+ const env = {
545
+ SIDEBOARD_APP_DATA: appDataDir(),
546
+ [SIDEBOARD_MCP_PROFILE_ENV]: orchId ? "orchestration" : "worktree"
626
547
  };
548
+ if (orchId) env.SIDEBOARD_ORCHESTRATOR_THREAD_ID = orchId;
549
+ if (threadId) env[SIDEBOARD_THREAD_ID_ENV] = threadId;
550
+ if (opts.rpcNativeTools) env[AGENT_RPC_NATIVE_ENV] = "1";
551
+ return env;
627
552
  }
628
- function uiResourceUriFromMeta(meta) {
629
- const rec = asRecord(meta);
630
- const nested = asRecord(rec.ui);
631
- const fromNested = typeof nested.resourceUri === "string" ? nested.resourceUri.trim() : "";
632
- const legacy = typeof rec["ui/resourceUri"] === "string" ? rec["ui/resourceUri"].trim() : "";
633
- const uri = fromNested || legacy;
634
- return uri.startsWith("ui://") ? uri : null;
635
- }
636
- function cspFromMeta(meta) {
637
- const ui = asRecord(asRecord(meta).ui);
638
- const csp = asRecord(ui.csp);
639
- const connectDomains = originList(csp.connectDomains);
640
- const resourceDomains = originList(csp.resourceDomains);
641
- const frameDomains = originList(csp.frameDomains);
642
- const baseUriDomains = originList(csp.baseUriDomains);
643
- if (!connectDomains?.length && !resourceDomains?.length && !frameDomains?.length && !baseUriDomains?.length) {
644
- return void 0;
645
- }
646
- return {
647
- ...connectDomains?.length ? { connectDomains } : {},
648
- ...resourceDomains?.length ? { resourceDomains } : {},
649
- ...frameDomains?.length ? { frameDomains } : {},
650
- ...baseUriDomains?.length ? { baseUriDomains } : {}
651
- };
553
+ var AGENT_RPC_PILOT_MCP_TOOLS = [
554
+ "present_artifact",
555
+ "wait_for_job",
556
+ "stop_job"
557
+ ];
558
+ function shouldRegisterMcpWaitForTurn(env = process.env) {
559
+ return !agentRpcOwnsPilotTools(env);
652
560
  }
653
- function htmlFromResourceContent(content) {
654
- const uri = content.uri?.trim() ?? "";
655
- if (!uri.startsWith("ui://")) return null;
656
- const mimeType = content.mimeType?.trim() || "text/html";
657
- if (!isHtmlMime(mimeType)) return null;
658
- const html = htmlText(content.text, content.blob);
659
- if (!html) return null;
660
- return { uri, mimeType, html };
561
+ function worktreeMcpToolNames(env = process.env) {
562
+ if (!agentRpcOwnsPilotTools(env)) return WORKTREE_MCP_TOOLS;
563
+ const omit = new Set(AGENT_RPC_PILOT_MCP_TOOLS);
564
+ return WORKTREE_MCP_TOOLS.filter((name) => !omit.has(name));
661
565
  }
662
- function mcpUiContentSecurityPolicy(csp) {
663
- const resource = (csp?.resourceDomains ?? []).join(" ");
664
- const connect = (csp?.connectDomains ?? []).join(" ");
665
- const frames = csp?.frameDomains?.length ? csp.frameDomains.join(" ") : "'none'";
666
- const base = csp?.baseUriDomains?.length ? csp.baseUriDomains.join(" ") : "'none'";
667
- const connectSrc = connect ? `'self' ${connect}`.trim() : "'none'";
668
- return [
669
- "default-src 'none'",
670
- `script-src 'self' 'unsafe-inline' ${resource}`.trim(),
671
- `style-src 'self' 'unsafe-inline' ${resource}`.trim(),
672
- `img-src 'self' data: ${resource}`.trim(),
673
- `font-src 'self' ${resource}`.trim(),
674
- `connect-src ${connectSrc}`,
675
- `media-src 'self' data: ${resource}`.trim(),
676
- `frame-src ${frames}`,
677
- `base-uri ${base}`,
678
- "object-src 'none'"
679
- ].join("; ");
566
+ var WORKTREE_MCP_TOOLS = [
567
+ "present_artifact",
568
+ "ask_user",
569
+ "present_plan",
570
+ "present_schema",
571
+ "present_files",
572
+ "wait_for_job",
573
+ "stop_job",
574
+ "list_run_scripts",
575
+ "run_dev_script",
576
+ "stop_dev_script",
577
+ "get_run_log",
578
+ "get_orchestrator",
579
+ "notify_orchestrator",
580
+ "set_workspace_tags",
581
+ "set_wake_on_github_edges",
582
+ "get_viewer_context",
583
+ "update_viewer_context",
584
+ "list_env",
585
+ "set_env",
586
+ "delete_env",
587
+ "list_schedules",
588
+ "create_schedule",
589
+ "update_schedule",
590
+ "delete_schedule",
591
+ "run_schedule",
592
+ "list_follow_ups",
593
+ "create_follow_up",
594
+ "delete_follow_up",
595
+ "list_order",
596
+ "show_plan",
597
+ "set_dependency",
598
+ "clear_dependency",
599
+ "satisfy_dependency"
600
+ ];
601
+ function sideboardMcpProfile(env = process.env) {
602
+ return env[SIDEBOARD_MCP_PROFILE_ENV]?.trim().toLowerCase() === "worktree" ? "worktree" : "orchestration";
680
603
  }
681
- function htmlText(text, blob) {
682
- if (typeof text === "string" && text.trim()) {
683
- return text.length <= HTML_MAX ? text : null;
684
- }
685
- if (typeof blob !== "string" || !blob.trim()) return null;
604
+
605
+ // src/agents/node-launch.ts
606
+ import { existsSync as existsSync4, readdirSync, realpathSync } from "fs";
607
+ import { homedir as homedir2 } from "os";
608
+ import { join as join4 } from "path";
609
+
610
+ // src/http/system-ca.ts
611
+ import { spawnSync } from "child_process";
612
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, statSync, writeFileSync } from "fs";
613
+ import { dirname, join as join2 } from "path";
614
+ import tls from "tls";
615
+ var NODE_USE_SYSTEM_CA = "NODE_USE_SYSTEM_CA";
616
+ var NODE_EXTRA_CA_CERTS = "NODE_EXTRA_CA_CERTS";
617
+ var BUNDLE_NAME = "system-ca.pem";
618
+ var BUNDLE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
619
+ var LINUX_CA_FILES = [
620
+ "/etc/ssl/certs/ca-certificates.crt",
621
+ "/etc/pki/tls/certs/ca-bundle.crt",
622
+ "/etc/ssl/ca-bundle.pem",
623
+ "/etc/ssl/cert.pem"
624
+ ];
625
+ var PEM_CERT_RE = /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;
626
+ function splitPemCertificates(pem) {
627
+ return pem.match(PEM_CERT_RE) ?? [];
628
+ }
629
+ function readExistingFile(path) {
686
630
  try {
687
- const decoded = decodeBase64(blob.trim());
688
- if (!decoded.trim() || decoded.length > HTML_MAX) return null;
689
- return decoded;
631
+ return existsSync2(path) ? readFileSync2(path, "utf8") : "";
690
632
  } catch {
691
- return null;
633
+ return "";
692
634
  }
693
635
  }
694
- function decodeBase64(blob) {
695
- if (typeof Buffer !== "undefined") return Buffer.from(blob, "base64").toString("utf8");
696
- const bin = atob(blob);
697
- const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
698
- return new TextDecoder().decode(bytes);
636
+ function darwinKeychainPem(spawn) {
637
+ const result = spawn("/usr/bin/security", ["find-certificate", "-a", "-p"], {
638
+ encoding: "utf8",
639
+ maxBuffer: 32 * 1024 * 1024,
640
+ timeout: 15e3
641
+ });
642
+ if (result.status !== 0) return "";
643
+ return typeof result.stdout === "string" ? result.stdout : "";
699
644
  }
700
- function isHtmlMime(mime) {
701
- const base = mime.split(";")[0]?.trim().toLowerCase() ?? "";
702
- return base === "text/html";
645
+ function linuxSystemCaPem() {
646
+ for (const path of LINUX_CA_FILES) {
647
+ const pem = readExistingFile(path);
648
+ if (splitPemCertificates(pem).length > 0) return pem;
649
+ }
650
+ return "";
703
651
  }
704
- function originList(value) {
705
- if (!Array.isArray(value)) return void 0;
706
- const out = [];
707
- for (const item of value) {
708
- if (typeof item !== "string") continue;
709
- const origin = originToken(item);
710
- if (origin && !out.includes(origin)) out.push(origin);
652
+ function collectSystemCaPem(io = {}) {
653
+ const platform = io.platform ?? process.platform;
654
+ if (platform === "darwin") {
655
+ return darwinKeychainPem(io.spawn ?? spawnSync);
711
656
  }
712
- return out;
657
+ if (platform === "linux") {
658
+ return linuxSystemCaPem();
659
+ }
660
+ return "";
713
661
  }
714
- function originToken(value) {
715
- const trimmed = value.trim();
716
- if (/^(https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?$/i.test(trimmed)) return trimmed;
662
+ function systemCaBundlePath(io = {}) {
663
+ return join2((io.appData ?? appDataDir)(), BUNDLE_NAME);
664
+ }
665
+ function bundleIsFresh(path, now) {
717
666
  try {
718
- const url = new URL(trimmed);
719
- if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "wss:" && url.protocol !== "ws:") {
720
- return null;
667
+ if (!existsSync2(path)) return false;
668
+ if (splitPemCertificates(readFileSync2(path, "utf8")).length === 0) return false;
669
+ return now - statSync(path).mtimeMs < BUNDLE_MAX_AGE_MS;
670
+ } catch {
671
+ return false;
672
+ }
673
+ }
674
+ function materializeSystemCaBundle(io = {}) {
675
+ const inherited = process.env.NODE_EXTRA_CA_CERTS?.trim();
676
+ if (inherited && splitPemCertificates(readExistingFile(inherited)).length > 0) {
677
+ return inherited;
678
+ }
679
+ const platform = io.platform ?? process.platform;
680
+ if (platform === "linux") {
681
+ for (const path of LINUX_CA_FILES) {
682
+ if (splitPemCertificates(readExistingFile(path)).length > 0) return path;
721
683
  }
722
- return url.origin;
684
+ }
685
+ const dest = systemCaBundlePath(io);
686
+ const now = (io.now ?? Date.now)();
687
+ if (bundleIsFresh(dest, now)) return dest;
688
+ const pem = collectSystemCaPem(io);
689
+ if (splitPemCertificates(pem).length === 0) {
690
+ return existsSync2(dest) && splitPemCertificates(readExistingFile(dest)).length > 0 ? dest : void 0;
691
+ }
692
+ try {
693
+ mkdirSync(dirname(dest), { recursive: true });
694
+ writeFileSync(dest, pem.endsWith("\n") ? pem : `${pem}
695
+ `, { mode: 384 });
696
+ return dest;
723
697
  } catch {
724
- return null;
698
+ return void 0;
725
699
  }
726
700
  }
727
- function stringRecord(value) {
728
- const rec = asRecord(value);
729
- const out = {};
730
- for (const [key, item] of Object.entries(rec)) {
731
- if (typeof item === "string") out[key] = item;
701
+ function applySystemCaEnv(env) {
702
+ if (!String(env[NODE_USE_SYSTEM_CA] ?? "").trim()) {
703
+ env[NODE_USE_SYSTEM_CA] = "1";
732
704
  }
733
- return Object.keys(out).length > 0 ? out : void 0;
705
+ if (String(env[NODE_EXTRA_CA_CERTS] ?? "").trim()) return;
706
+ const inherited = process.env.NODE_EXTRA_CA_CERTS?.trim();
707
+ if (inherited) env[NODE_EXTRA_CA_CERTS] = inherited;
734
708
  }
735
- function asRecord(value) {
736
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
737
- return value;
709
+ function extraCertsFromBundle(io = {}) {
710
+ const path = process.env.NODE_EXTRA_CA_CERTS?.trim();
711
+ if (path) return splitPemCertificates(readExistingFile(path));
712
+ return splitPemCertificates(readExistingFile(systemCaBundlePath(io)));
738
713
  }
739
-
740
- // src/agents/claude-plugins.ts
741
- function claudePluginServerId(pluginName, serverName) {
742
- return `plugin_${pluginName}_${serverName}`.replace(/[^A-Za-z0-9_-]/g, "_");
714
+ function extraSystemCaPems(io = {}) {
715
+ const fromBundle = extraCertsFromBundle(io);
716
+ if (fromBundle.length > 0) return fromBundle;
717
+ return splitPemCertificates(collectSystemCaPem(io));
743
718
  }
744
- function listEnabledClaudePluginMcpServers(opts) {
745
- const home = opts?.home ?? homedir();
746
- const pluginsRoot = claudePluginsRoot(home);
747
- const enabled = enabledPluginIds(home, opts?.projectDirs ?? []);
748
- const installed = readInstalledPlugins(join(pluginsRoot, "installed_plugins.json"));
749
- const out = {};
750
- for (const [id, on] of enabled) {
751
- if (!on) continue;
752
- const root = installPathFor(id, installed);
753
- if (!root || !existsSync2(root)) continue;
754
- const pluginName = manifestName(root) || id.split("@")[0]?.trim() || "";
755
- if (!pluginName) continue;
756
- const dataDir = join(pluginsRoot, "data", pluginDataId(id));
757
- for (const [serverName, entry] of Object.entries(loadPluginMcpServers(root))) {
758
- const expanded = expandPluginEntry(entry, root, dataDir);
759
- if (!parseMcpServerLaunch(expanded)) continue;
760
- const key = claudePluginServerId(pluginName, serverName);
761
- if (!key || key === "plugin__") continue;
762
- out[key] = expanded;
719
+ function mergeSystemCaIntoTlsOptions(options, extra, roots = tls.rootCertificates) {
720
+ const existing = options?.ca;
721
+ const base = existing == null ? [...roots] : Array.isArray(existing) ? [...existing] : [existing];
722
+ return { ...options, ca: [...base, ...extra] };
723
+ }
724
+ function installCreateSecureContextCaPatch(api, extra) {
725
+ if (api.__sideboardSystemCaPatched) return true;
726
+ if (typeof api.createSecureContext !== "function") return false;
727
+ const orig = api.createSecureContext;
728
+ const roots = api.rootCertificates ?? tls.rootCertificates;
729
+ api.createSecureContext = ((options) => orig(mergeSystemCaIntoTlsOptions(options, extra, roots)));
730
+ api.__sideboardSystemCaPatched = true;
731
+ return true;
732
+ }
733
+ function trustSystemCertificates(io = {}) {
734
+ try {
735
+ const extra = extraSystemCaPems(io);
736
+ const api = io.tls ?? tls;
737
+ if (typeof api.getCACertificates === "function" && typeof api.setDefaultCACertificates === "function") {
738
+ const current = api.getCACertificates("default");
739
+ const system = api.getCACertificates("system");
740
+ if (system.length === 0 && extra.length === 0) return false;
741
+ api.setDefaultCACertificates([...current, ...system, ...extra]);
742
+ return true;
763
743
  }
744
+ if (extra.length === 0) return false;
745
+ return installCreateSecureContextCaPatch(api, extra);
746
+ } catch {
747
+ return false;
764
748
  }
765
- return out;
766
749
  }
767
- function claudePluginsRoot(home) {
768
- const override = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim();
769
- if (override && isAbsolute(override)) return override;
770
- return join(home, ".claude", "plugins");
750
+ function bootstrapSystemCa(io = {}) {
751
+ const systemCaBundle = materializeSystemCaBundle(io);
752
+ if (systemCaBundle && !process.env.NODE_EXTRA_CA_CERTS?.trim()) {
753
+ process.env.NODE_EXTRA_CA_CERTS = systemCaBundle;
754
+ }
755
+ applySystemCaEnv(process.env);
756
+ trustSystemCertificates(io);
771
757
  }
772
- function pluginDataId(pluginId) {
773
- return pluginId.replace(/[^A-Za-z0-9_-]/g, "-");
758
+
759
+ // src/agents/packaged-runtime.ts
760
+ import { existsSync as existsSync3 } from "fs";
761
+ import { join as join3 } from "path";
762
+ function electronResourcesPath() {
763
+ const resources = process.resourcesPath;
764
+ if (typeof resources !== "string" || !resources) return null;
765
+ return resources;
774
766
  }
775
- function enabledPluginIds(home, projectDirs) {
776
- const enabled = /* @__PURE__ */ new Map();
777
- applyEnabled(enabled, readEnabledPlugins(join(home, ".claude", "settings.json")));
778
- const dirs = [...new Set(projectDirs.map((dir) => dir.trim()).filter(Boolean))];
779
- for (const dir of dirs) {
780
- applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.json")));
781
- }
782
- for (const dir of dirs) {
783
- applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.local.json")));
784
- }
785
- return enabled;
767
+ function packagedCursorRuntimeDir() {
768
+ const resources = electronResourcesPath();
769
+ if (!resources) return null;
770
+ const dir = join3(resources, "cursor-runtime");
771
+ if (!existsSync3(join3(dir, "core-dist", "agents", "cursor-runner.js"))) return null;
772
+ return dir;
786
773
  }
787
- function applyEnabled(into, next) {
788
- for (const [id, on] of Object.entries(next)) {
789
- const key = id.trim();
790
- if (!key) continue;
791
- into.set(key, on);
792
- }
774
+ function packagedCursorRunnerPath() {
775
+ const dir = packagedCursorRuntimeDir();
776
+ return dir ? join3(dir, "core-dist", "agents", "cursor-runner.js") : null;
793
777
  }
794
- function readEnabledPlugins(path) {
795
- const root = readJson(path);
796
- const raw = root.enabledPlugins;
797
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
798
- const out = {};
799
- for (const [id, value] of Object.entries(raw)) {
800
- if (value === true || value === false) out[id] = value;
801
- }
802
- return out;
778
+ function packagedMcpDir() {
779
+ const resources = electronResourcesPath();
780
+ if (!resources) return null;
781
+ const dir = join3(resources, "sideboard-mcp");
782
+ if (!existsSync3(join3(dir, "core-dist", "mcp", "run-stdio.js"))) return null;
783
+ return dir;
803
784
  }
804
- function readInstalledPlugins(path) {
805
- const root = readJson(path);
806
- const plugins = root.plugins;
807
- if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) return {};
808
- const out = {};
809
- for (const [id, value] of Object.entries(plugins)) {
810
- const rows = Array.isArray(value) ? value : [value];
811
- const installs = [];
812
- for (const row of rows) {
813
- if (!row || typeof row !== "object" || Array.isArray(row)) continue;
814
- const installPath = row.installPath;
815
- installs.push({
816
- ...typeof installPath === "string" && installPath.trim() ? { installPath: installPath.trim() } : {}
817
- });
818
- }
819
- if (installs.length) out[id] = installs;
820
- }
821
- return out;
785
+ function packagedMcpStdioPath() {
786
+ const dir = packagedMcpDir();
787
+ return dir ? join3(dir, "core-dist", "mcp", "run-stdio.js") : null;
822
788
  }
823
- function installPathFor(id, installed) {
824
- const rows = installed[id] ?? [];
825
- for (let i = rows.length - 1; i >= 0; i--) {
826
- const path = rows[i]?.installPath;
827
- if (path && existsSync2(path)) return path;
789
+ function packagedBundledNodePath() {
790
+ const resources = electronResourcesPath();
791
+ if (!resources) return null;
792
+ const bin = join3(resources, "node", "bin", "node");
793
+ if (!existsSync3(bin)) return null;
794
+ return bin;
795
+ }
796
+ function packagedCursorRipgrepCandidate(platformPkg, binName) {
797
+ const dir = packagedCursorRuntimeDir();
798
+ if (!dir) return null;
799
+ return join3(dir, "node_modules", platformPkg, "bin", binName);
800
+ }
801
+
802
+ // src/agents/node-launch.ts
803
+ var AGENT_RUNNER_MAX_OLD_SPACE_MB = 8192;
804
+ var MAX_OLD_SPACE_FLAG = /(?:^|\s)(--max[-_]old[-_]space[-_]size)(?:[= ](\d+))?(?=\s|$)/;
805
+ function withMaxOldSpaceSize(nodeOptions, heapMb) {
806
+ const existing = (nodeOptions ?? "").trim();
807
+ const match = MAX_OLD_SPACE_FLAG.exec(existing);
808
+ if (match) {
809
+ const current = match[2] ? Number(match[2]) : 0;
810
+ if (Number.isFinite(current) && current >= heapMb) return existing;
811
+ return existing.replace(MAX_OLD_SPACE_FLAG, ` --max-old-space-size=${heapMb}`).trim();
828
812
  }
829
- return null;
813
+ return existing ? `${existing} --max-old-space-size=${heapMb}` : `--max-old-space-size=${heapMb}`;
830
814
  }
831
- function manifestName(root) {
832
- const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
833
- return typeof manifest.name === "string" ? manifest.name.trim() : "";
815
+ function applyAgentRunnerHeapEnv(env) {
816
+ env.NODE_OPTIONS = withMaxOldSpaceSize(
817
+ env.NODE_OPTIONS,
818
+ AGENT_RUNNER_MAX_OLD_SPACE_MB
819
+ );
820
+ applySystemCaEnv(env);
834
821
  }
835
- function loadPluginMcpServers(root) {
836
- const servers = {};
837
- mergeServerMap(servers, serversFromFile(join(root, ".mcp.json"), root));
838
- const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
839
- mergeServerMap(servers, serversFromManifest(manifest.mcpServers, root));
840
- return servers;
822
+ function envWithAgentHeap(env) {
823
+ const next = { ...env };
824
+ applyAgentRunnerHeapEnv(next);
825
+ return next;
841
826
  }
842
- function serversFromManifest(value, root) {
843
- if (!value) return {};
844
- if (typeof value === "string") return serversFromFile(resolveInside(root, value), root);
845
- if (Array.isArray(value)) {
846
- const out = {};
847
- for (const item of value) {
848
- if (typeof item === "string") mergeServerMap(out, serversFromFile(resolveInside(root, item), root));
849
- else mergeServerMap(out, serverMap(item, root));
850
- }
851
- return out;
852
- }
853
- return serverMap(value, root);
827
+ function isAsarPath(filePath) {
828
+ if (/\.asar\.unpacked([/\\]|$)/.test(filePath)) return false;
829
+ return /\.asar([/\\]|$)/.test(filePath);
854
830
  }
855
- function serversFromFile(path, root) {
856
- if (!path || !existsSync2(path)) return {};
857
- return serverMap(readJson(path), root);
831
+ function unpackedAsarPath(filePath) {
832
+ if (!isAsarPath(filePath)) return null;
833
+ const unpacked = filePath.replace(/\.asar(?=[/\\])/, ".asar.unpacked");
834
+ if (unpacked === filePath) return null;
835
+ return existsSync4(unpacked) ? unpacked : null;
858
836
  }
859
- function serverMap(value, root) {
860
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
861
- const record = value;
862
- const wrapped = record.mcpServers;
863
- const source = wrapped && typeof wrapped === "object" && !Array.isArray(wrapped) ? wrapped : record;
864
- if (typeof wrapped === "string") return serversFromFile(resolveInside(root, wrapped), root);
865
- const out = {};
866
- for (const [name, entry] of Object.entries(source)) {
867
- if (!name.trim() || !entry || typeof entry !== "object" || Array.isArray(entry)) continue;
868
- const row = entry;
869
- if (row.disabled === true) continue;
870
- if (typeof row.command !== "string" && typeof row.url !== "string") continue;
871
- out[name.trim()] = row;
872
- }
873
- return out;
837
+ function nodeReadableScriptPath(scriptPath) {
838
+ return unpackedAsarPath(scriptPath) ?? scriptPath;
874
839
  }
875
- function mergeServerMap(into, extra) {
876
- for (const [name, entry] of Object.entries(extra)) into[name] = entry;
840
+ var PREFERRED_LTS_MAJORS = [24, 22];
841
+ function parseNodeMajor(version) {
842
+ const match = /^v?(\d+)/.exec(version.trim());
843
+ if (!match) return null;
844
+ const major = Number(match[1]);
845
+ return Number.isInteger(major) ? major : null;
877
846
  }
878
- function expandPluginEntry(entry, root, dataDir) {
879
- const next = { ...entry };
880
- if (typeof next.command === "string") next.command = expandVars(next.command, root, dataDir);
881
- if (Array.isArray(next.args)) {
882
- next.args = next.args.map((arg) => typeof arg === "string" ? expandVars(arg, root, dataDir) : arg);
847
+ function scoreNodeForAgentRuntime(candidate) {
848
+ const major = parseNodeMajor(candidate.version);
849
+ if (major == null) return Number.NEGATIVE_INFINITY;
850
+ if (major < 22) return major - 100;
851
+ const posix = candidate.path.replace(/\\/g, "/");
852
+ let score = 0;
853
+ if (major % 2 === 0) {
854
+ score += 1e3 + major * 10;
855
+ } else {
856
+ score += major;
883
857
  }
884
- if (typeof next.url === "string") next.url = expandVars(next.url, root, dataDir);
885
- if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) {
886
- const env = {};
887
- for (const [key, value] of Object.entries(next.env)) {
888
- if (typeof value === "string") env[key] = expandVars(value, root, dataDir);
889
- }
890
- env.CLAUDE_PLUGIN_ROOT = env.CLAUDE_PLUGIN_ROOT || root;
891
- env.CLAUDE_PLUGIN_DATA = env.CLAUDE_PLUGIN_DATA || dataDir;
892
- next.env = env;
893
- } else if (typeof next.command === "string") {
894
- next.env = { CLAUDE_PLUGIN_ROOT: root, CLAUDE_PLUGIN_DATA: dataDir };
858
+ if (/\/Cellar\/node\/\d/.test(posix) && !/\/Cellar\/node@\d+/.test(posix)) {
859
+ score -= 50;
895
860
  }
896
- if (next.headers && typeof next.headers === "object" && !Array.isArray(next.headers)) {
897
- const headers = {};
898
- for (const [key, value] of Object.entries(next.headers)) {
899
- if (typeof value === "string") headers[key] = expandVars(value, root, dataDir);
861
+ return score;
862
+ }
863
+ function pickPreferredNode(candidates) {
864
+ let best = null;
865
+ let bestScore = Number.NEGATIVE_INFINITY;
866
+ for (const candidate of candidates) {
867
+ const score = scoreNodeForAgentRuntime(candidate);
868
+ if (score > bestScore) {
869
+ bestScore = score;
870
+ best = candidate;
900
871
  }
901
- next.headers = headers;
902
872
  }
903
- return next;
904
- }
905
- function expandVars(value, root, dataDir) {
906
- return value.replaceAll("${CLAUDE_PLUGIN_ROOT}", root).replaceAll("${CLAUDE_PLUGIN_DATA}", dataDir);
907
- }
908
- function resolveInside(root, spec) {
909
- const trimmed = spec.trim();
910
- if (!trimmed || trimmed.endsWith(".mcpb") || trimmed.endsWith(".dxt")) return null;
911
- if (/^https?:\/\//i.test(trimmed)) return null;
912
- const abs = resolve(root, trimmed);
913
- const rel = relative(root, abs);
914
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
915
- return abs;
873
+ return best;
916
874
  }
917
- function readJson(path) {
918
- if (!existsSync2(path)) return {};
875
+ function versionDirNodeBins(root, toBin) {
876
+ if (!existsSync4(root)) return [];
919
877
  try {
920
- const parsed = JSON.parse(readFileSync(path, "utf8"));
921
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
922
- return parsed;
878
+ return readdirSync(root).map(toBin);
923
879
  } catch {
924
- return {};
880
+ return [];
925
881
  }
926
882
  }
927
-
928
- // src/agents/orch-mcp-isolation.ts
929
- import { homedir as homedir5 } from "os";
930
- import { join as join8 } from "path";
931
- import { parse as parseToml } from "smol-toml";
932
-
933
- // src/agents/user-mcp-config.ts
934
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
935
- import { homedir as homedir4 } from "os";
936
- import { dirname as dirname3, join as join7 } from "path";
937
-
938
- // src/agents/injected-mcp.ts
939
- import { existsSync as existsSync6, mkdtempSync, writeFileSync as writeFileSync3 } from "fs";
940
- import { createRequire } from "module";
941
- import { tmpdir } from "os";
942
- import { dirname as dirname2, join as join6 } from "path";
943
- import { fileURLToPath } from "url";
944
-
945
- // src/agent-rpc/protocol.ts
946
- var AGENT_RPC_PROTOCOL_VERSION = 1;
947
- var AGENT_RPC_TOKEN_QUERY = "authToken";
948
- var AGENT_RPC_NATIVE_ENV = "SIDEBOARD_AGENT_RPC_NATIVE";
949
- var AGENT_RPC_URL_ENV = "SIDEBOARD_AGENT_RPC_URL";
950
- var AGENT_RPC_TOKEN_ENV = "SIDEBOARD_AGENT_RPC_TOKEN";
951
- var AGENT_RPC_CWD_ENV = "SIDEBOARD_AGENT_RPC_CWD";
952
- var AGENT_RPC_CLAUDE_SDK_SERVER = "sideboard_rpc";
953
-
954
- // src/mcp/profile.ts
955
- var SIDEBOARD_MCP_PROFILE_ENV = "SIDEBOARD_MCP_PROFILE";
956
- var SIDEBOARD_THREAD_ID_ENV = "SIDEBOARD_THREAD_ID";
957
- function agentRpcOwnsPilotTools(env = process.env) {
958
- return env[AGENT_RPC_NATIVE_ENV]?.trim() === "1";
883
+ function defaultNodeBinCandidates(home = homedir2()) {
884
+ const kegs = ["/opt/homebrew", "/usr/local"].flatMap(
885
+ (prefix) => PREFERRED_LTS_MAJORS.map((major) => join4(prefix, "opt", `node@${major}`, "bin", "node"))
886
+ );
887
+ return [
888
+ ...kegs,
889
+ "/opt/homebrew/bin/node",
890
+ "/usr/local/bin/node",
891
+ join4(home, ".local/share/fnm/aliases/default/bin/node"),
892
+ join4(home, ".nvm/current/bin/node"),
893
+ join4(home, ".volta/bin/node"),
894
+ join4(home, ".asdf/shims/node"),
895
+ join4(home, ".local/share/mise/shims/node"),
896
+ ...versionDirNodeBins(
897
+ join4(home, ".nvm", "versions", "node"),
898
+ (name) => join4(home, ".nvm", "versions", "node", name, "bin", "node")
899
+ ),
900
+ ...versionDirNodeBins(
901
+ join4(home, ".local/share/fnm", "node-versions"),
902
+ (name) => join4(home, ".local/share/fnm", "node-versions", name, "installation", "bin", "node")
903
+ ),
904
+ ...versionDirNodeBins(
905
+ join4(home, ".volta", "tools", "image", "node"),
906
+ (name) => join4(home, ".volta", "tools", "image", "node", name, "bin", "node")
907
+ )
908
+ ];
959
909
  }
960
- function injectedSideboardMcpEnv(opts) {
961
- const orchId = opts.orchestratorThreadId?.trim();
962
- const threadId = opts.threadId?.trim() || orchId;
963
- const env = {
964
- SIDEBOARD_APP_DATA: appDataDir(),
965
- [SIDEBOARD_MCP_PROFILE_ENV]: orchId ? "orchestration" : "worktree"
966
- };
967
- if (orchId) env.SIDEBOARD_ORCHESTRATOR_THREAD_ID = orchId;
968
- if (threadId) env[SIDEBOARD_THREAD_ID_ENV] = threadId;
969
- if (opts.rpcNativeTools) env[AGENT_RPC_NATIVE_ENV] = "1";
970
- return env;
910
+ function uniqueExistingNodeBins(paths) {
911
+ const seen = /* @__PURE__ */ new Set();
912
+ const out = [];
913
+ for (const raw of paths) {
914
+ const p = raw.trim();
915
+ if (!p || !existsSync4(p) || isElectronLikeCommand(p)) continue;
916
+ let key = p;
917
+ try {
918
+ key = realpathSync(p);
919
+ } catch {
920
+ continue;
921
+ }
922
+ if (seen.has(key)) continue;
923
+ seen.add(key);
924
+ out.push(p);
925
+ }
926
+ return out;
971
927
  }
972
- var AGENT_RPC_PILOT_MCP_TOOLS = [
973
- "present_artifact",
974
- "wait_for_job",
975
- "stop_job"
976
- ];
977
- function shouldRegisterMcpWaitForTurn(env = process.env) {
978
- return !agentRpcOwnsPilotTools(env);
928
+ async function whichAllNode() {
929
+ if (process.platform === "win32") {
930
+ const located = await run("where", ["node"], { reject: false, timeoutMs: 5e3 });
931
+ if (located.exitCode !== 0) return [];
932
+ return located.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
933
+ }
934
+ const all = await run("which", ["-a", "node"], { reject: false, timeoutMs: 5e3 });
935
+ if (all.exitCode === 0 && all.stdout.trim()) {
936
+ return all.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
937
+ }
938
+ const single = await run("which", ["node"], { reject: false, timeoutMs: 5e3 });
939
+ if (single.exitCode !== 0 || !single.stdout.trim()) return [];
940
+ return [single.stdout.trim()];
941
+ }
942
+ async function probeNodeVersion(bin) {
943
+ const probed = await run(bin, ["-v"], { reject: false, timeoutMs: 4e3 });
944
+ if (probed.exitCode !== 0) return null;
945
+ const version = probed.stdout.trim().split(/\r?\n/).find(Boolean);
946
+ return version || null;
947
+ }
948
+ async function findSystemNode() {
949
+ const fromPath = await whichAllNode();
950
+ const bins = uniqueExistingNodeBins([...fromPath, ...defaultNodeBinCandidates()]);
951
+ if (bins.length === 0) return null;
952
+ const probed = await Promise.all(
953
+ bins.map(async (path) => {
954
+ const version = await probeNodeVersion(path);
955
+ return version ? { path, version } : null;
956
+ })
957
+ );
958
+ return pickPreferredNode(probed.filter((c) => c != null));
979
959
  }
980
- function worktreeMcpToolNames(env = process.env) {
981
- if (!agentRpcOwnsPilotTools(env)) return WORKTREE_MCP_TOOLS;
982
- const omit = new Set(AGENT_RPC_PILOT_MCP_TOOLS);
983
- return WORKTREE_MCP_TOOLS.filter((name) => !omit.has(name));
960
+ function applyNodeLaunch(launch, args) {
961
+ const readableArgs = args.map(nodeReadableScriptPath);
962
+ if (!launch.env.ELECTRON_RUN_AS_NODE) {
963
+ return {
964
+ file: launch.file,
965
+ args: readableArgs,
966
+ env: envWithAgentHeap(launch.env)
967
+ };
968
+ }
969
+ const wrapped = wrapElectronAsNodeLaunch(launch.file, readableArgs);
970
+ if (process.platform === "win32") {
971
+ return {
972
+ file: wrapped.file,
973
+ args: wrapped.args,
974
+ env: envWithAgentHeap(launch.env)
975
+ };
976
+ }
977
+ const env = envWithAgentHeap(launch.env);
978
+ delete env.ELECTRON_RUN_AS_NODE;
979
+ return { file: wrapped.file, args: wrapped.args, env };
984
980
  }
985
- var WORKTREE_MCP_TOOLS = [
986
- "present_artifact",
987
- "ask_user",
988
- "present_plan",
989
- "present_schema",
990
- "present_files",
991
- "wait_for_job",
992
- "stop_job",
993
- "list_run_scripts",
994
- "run_dev_script",
995
- "stop_dev_script",
996
- "get_run_log",
997
- "get_orchestrator",
998
- "notify_orchestrator",
999
- "set_workspace_tags",
1000
- "set_wake_on_github_edges",
1001
- "get_viewer_context",
1002
- "update_viewer_context",
1003
- "list_env",
1004
- "set_env",
1005
- "delete_env",
1006
- "list_schedules",
1007
- "create_schedule",
1008
- "update_schedule",
1009
- "delete_schedule",
1010
- "run_schedule",
1011
- "list_order",
1012
- "show_plan",
1013
- "set_dependency",
1014
- "clear_dependency",
1015
- "satisfy_dependency"
1016
- ];
1017
- function sideboardMcpProfile(env = process.env) {
1018
- return env[SIDEBOARD_MCP_PROFILE_ENV]?.trim().toLowerCase() === "worktree" ? "worktree" : "orchestration";
981
+ async function resolveNodeLaunch(scriptPath) {
982
+ const script = nodeReadableScriptPath(scriptPath);
983
+ if (!isAsarPath(script)) {
984
+ const bundled = packagedBundledNodePath();
985
+ if (bundled && !isElectronLikeCommand(bundled)) {
986
+ return { file: bundled, env: {} };
987
+ }
988
+ const node = await findSystemNode();
989
+ if (node) {
990
+ return { file: node.path, env: {}, nodeVersion: node.version };
991
+ }
992
+ }
993
+ return {
994
+ file: process.execPath,
995
+ env: { ELECTRON_RUN_AS_NODE: "1" }
996
+ };
1019
997
  }
1020
998
 
1021
- // src/agents/node-launch.ts
1022
- import { existsSync as existsSync5, readdirSync, realpathSync } from "fs";
1023
- import { homedir as homedir2 } from "os";
1024
- import { join as join4 } from "path";
1025
-
1026
- // src/http/system-ca.ts
1027
- import { spawnSync } from "child_process";
1028
- import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, statSync, writeFileSync } from "fs";
1029
- import { dirname, join as join2 } from "path";
1030
- import tls from "tls";
1031
- var NODE_USE_SYSTEM_CA = "NODE_USE_SYSTEM_CA";
1032
- var NODE_EXTRA_CA_CERTS = "NODE_EXTRA_CA_CERTS";
1033
- var BUNDLE_NAME = "system-ca.pem";
1034
- var BUNDLE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
1035
- var LINUX_CA_FILES = [
1036
- "/etc/ssl/certs/ca-certificates.crt",
1037
- "/etc/pki/tls/certs/ca-bundle.crt",
1038
- "/etc/ssl/ca-bundle.pem",
1039
- "/etc/ssl/cert.pem"
1040
- ];
1041
- var PEM_CERT_RE = /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;
1042
- function splitPemCertificates(pem) {
1043
- return pem.match(PEM_CERT_RE) ?? [];
999
+ // src/agents/codex-mcp-profile.ts
1000
+ import { randomBytes } from "crypto";
1001
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
1002
+ import { homedir as homedir3 } from "os";
1003
+ import { join as join5 } from "path";
1004
+ function isCodexSecretEnvKey(key) {
1005
+ return /token|secret|password|credential|oauth|api_key|_key$/i.test(key);
1044
1006
  }
1045
- function readExistingFile(path) {
1046
- try {
1047
- return existsSync3(path) ? readFileSync2(path, "utf8") : "";
1048
- } catch {
1049
- return "";
1050
- }
1007
+ function tomlBasicString(value) {
1008
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`;
1051
1009
  }
1052
- function darwinKeychainPem(spawn) {
1053
- const result = spawn("/usr/bin/security", ["find-certificate", "-a", "-p"], {
1054
- encoding: "utf8",
1055
- maxBuffer: 32 * 1024 * 1024,
1056
- timeout: 15e3
1057
- });
1058
- if (result.status !== 0) return "";
1059
- return typeof result.stdout === "string" ? result.stdout : "";
1010
+ function secretEnv(env) {
1011
+ if (!env) return void 0;
1012
+ const out = { ...env };
1013
+ delete out.ELECTRON_RUN_AS_NODE;
1014
+ return Object.keys(out).length > 0 ? out : void 0;
1060
1015
  }
1061
- function linuxSystemCaPem() {
1062
- for (const path of LINUX_CA_FILES) {
1063
- const pem = readExistingFile(path);
1064
- if (splitPemCertificates(pem).length > 0) return pem;
1016
+ function writeCodexMcpSecretProfile(servers) {
1017
+ const blocks = [];
1018
+ for (const s of servers) {
1019
+ const env = secretEnv(s.env);
1020
+ if (!env) continue;
1021
+ const secrets = Object.entries(env).filter(([key]) => isCodexSecretEnvKey(key));
1022
+ if (secrets.length === 0) continue;
1023
+ const lines = [`[mcp_servers.${s.name}.env]`];
1024
+ for (const [key, value] of secrets) lines.push(`${key} = ${tomlBasicString(value)}`);
1025
+ blocks.push(lines.join("\n"));
1065
1026
  }
1066
- return "";
1027
+ if (blocks.length === 0) return null;
1028
+ const home = process.env.CODEX_HOME?.trim() || join5(homedir3(), ".codex");
1029
+ mkdirSync2(home, { recursive: true, mode: 448 });
1030
+ const profile = `sideboard-${randomBytes(8).toString("hex")}`;
1031
+ const file = join5(home, `${profile}.config.toml`);
1032
+ writeFileSync2(file, `${blocks.join("\n\n")}
1033
+ `, { mode: 384 });
1034
+ return { profile, file };
1067
1035
  }
1068
- function collectSystemCaPem(io = {}) {
1069
- const platform = io.platform ?? process.platform;
1070
- if (platform === "darwin") {
1071
- return darwinKeychainPem(io.spawn ?? spawnSync);
1072
- }
1073
- if (platform === "linux") {
1074
- return linuxSystemCaPem();
1075
- }
1076
- return "";
1036
+
1037
+ // src/agents/injected-mcp.ts
1038
+ var SIDEBOARD_MCP_ALLOWED_TOOLS = [
1039
+ "mcp__sideboard",
1040
+ "mcp__sideboard__*"
1041
+ ];
1042
+ var SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS = [
1043
+ "mcp__sideboard__present_artifact",
1044
+ "mcp__sideboard__present_schema",
1045
+ "mcp__sideboard__present_files",
1046
+ "mcp__sideboard__ask_user",
1047
+ "mcp__sideboard__present_plan",
1048
+ "mcp__sideboard__wait_for_job",
1049
+ "mcp__sideboard__stop_job",
1050
+ "mcp__sideboard__list_run_scripts",
1051
+ "mcp__sideboard__run_dev_script",
1052
+ "mcp__sideboard__stop_dev_script",
1053
+ "mcp__sideboard__get_run_log",
1054
+ "mcp__sideboard__get_orchestrator",
1055
+ "mcp__sideboard__notify_orchestrator",
1056
+ "mcp__sideboard__set_workspace_tags",
1057
+ "mcp__sideboard__set_wake_on_github_edges",
1058
+ "mcp__sideboard__get_viewer_context",
1059
+ "mcp__sideboard__update_viewer_context",
1060
+ "mcp__sideboard__list_env",
1061
+ "mcp__sideboard__set_env",
1062
+ "mcp__sideboard__delete_env",
1063
+ "mcp__sideboard__list_schedules",
1064
+ "mcp__sideboard__create_schedule",
1065
+ "mcp__sideboard__update_schedule",
1066
+ "mcp__sideboard__delete_schedule",
1067
+ "mcp__sideboard__run_schedule",
1068
+ "mcp__sideboard__list_follow_ups",
1069
+ "mcp__sideboard__create_follow_up",
1070
+ "mcp__sideboard__delete_follow_up",
1071
+ "mcp__sideboard__list_order",
1072
+ "mcp__sideboard__show_plan",
1073
+ "mcp__sideboard__set_dependency",
1074
+ "mcp__sideboard__clear_dependency",
1075
+ "mcp__sideboard__satisfy_dependency",
1076
+ "mcp__sideboard__posthog_api"
1077
+ ];
1078
+ var SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS = ["mcp__sideboard__github_*"];
1079
+ var SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS = ["mcp__sideboard__linear_*"];
1080
+ var SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS = ["mcp__sideboard__abletime_*"];
1081
+ function sideboardWorktreeAllowedTools(opts) {
1082
+ const out = SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS.filter(
1083
+ (tool) => (opts?.planMode || tool !== "mcp__sideboard__present_plan") && (opts?.posthog || tool !== "mcp__sideboard__posthog_api")
1084
+ );
1085
+ if (opts?.github !== false) out.push(...SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS);
1086
+ if (opts?.linear) out.push(...SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS);
1087
+ if (opts?.abletime) out.push(...SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS);
1088
+ return out;
1077
1089
  }
1078
- function systemCaBundlePath(io = {}) {
1079
- return join2((io.appData ?? appDataDir)(), BUNDLE_NAME);
1090
+ var brightsyMcpCommandCache = null;
1091
+ async function resolveBrightsyMcpCommand() {
1092
+ const now = Date.now();
1093
+ if (brightsyMcpCommandCache && now - brightsyMcpCommandCache.at < 6e4 && brightsyMcpCommandCache.command) {
1094
+ return brightsyMcpCommandCache.command;
1095
+ }
1096
+ const which = await run("which", ["brightsy-mcp"], { reject: false });
1097
+ const command = which.exitCode === 0 && which.stdout.trim() ? "brightsy-mcp" : "npx";
1098
+ brightsyMcpCommandCache = { at: now, command };
1099
+ return command;
1080
1100
  }
1081
- function bundleIsFresh(path, now) {
1101
+ function isBrightsyConnected() {
1082
1102
  try {
1083
- if (!existsSync3(path)) return false;
1084
- if (splitPemCertificates(readFileSync2(path, "utf8")).length === 0) return false;
1085
- return now - statSync(path).mtimeMs < BUNDLE_MAX_AGE_MS;
1103
+ loadBrightsyConfig();
1104
+ return true;
1086
1105
  } catch {
1087
1106
  return false;
1088
1107
  }
1089
1108
  }
1090
- function materializeSystemCaBundle(io = {}) {
1091
- const inherited = process.env.NODE_EXTRA_CA_CERTS?.trim();
1092
- if (inherited && splitPemCertificates(readExistingFile(inherited)).length > 0) {
1093
- return inherited;
1094
- }
1095
- const platform = io.platform ?? process.platform;
1096
- if (platform === "linux") {
1097
- for (const path of LINUX_CA_FILES) {
1098
- if (splitPemCertificates(readExistingFile(path)).length > 0) return path;
1109
+ var BRIGHTSY_WORD = /(?<![a-z0-9_-])brightsy(?![a-z0-9_-])/i;
1110
+ function promptMentionsBrightsy(text) {
1111
+ return BRIGHTSY_WORD.test(text ?? "");
1112
+ }
1113
+ function isBrightsyMcpToolName(name) {
1114
+ const n = name.toLowerCase();
1115
+ return n === "brightsy" || n.startsWith("mcp__brightsy") || n.startsWith("brightsy_");
1116
+ }
1117
+ function toolInputUsesBrightsyDatasource(input) {
1118
+ const ds = input?.datasource;
1119
+ return typeof ds === "string" && ds.toLowerCase() === "brightsy";
1120
+ }
1121
+ function messageUsedBrightsyMcp(msg) {
1122
+ if (msg.role === "user" && promptMentionsBrightsy(msg.text)) return true;
1123
+ for (const part of msg.parts ?? []) {
1124
+ if (part.type !== "tool") continue;
1125
+ if (isBrightsyMcpToolName(part.name)) return true;
1126
+ if (/present_(schema|files)$/i.test(part.name) && toolInputUsesBrightsyDatasource(part.input)) {
1127
+ return true;
1099
1128
  }
1100
1129
  }
1101
- const dest = systemCaBundlePath(io);
1102
- const now = (io.now ?? Date.now)();
1103
- if (bundleIsFresh(dest, now)) return dest;
1104
- const pem = collectSystemCaPem(io);
1105
- if (splitPemCertificates(pem).length === 0) {
1106
- return existsSync3(dest) && splitPemCertificates(readExistingFile(dest)).length > 0 ? dest : void 0;
1107
- }
1108
- try {
1109
- mkdirSync(dirname(dest), { recursive: true });
1110
- writeFileSync(dest, pem.endsWith("\n") ? pem : `${pem}
1111
- `, { mode: 384 });
1112
- return dest;
1113
- } catch {
1114
- return void 0;
1115
- }
1130
+ return false;
1116
1131
  }
1117
- function applySystemCaEnv(env) {
1118
- if (!String(env[NODE_USE_SYSTEM_CA] ?? "").trim()) {
1119
- env[NODE_USE_SYSTEM_CA] = "1";
1120
- }
1121
- if (String(env[NODE_EXTRA_CA_CERTS] ?? "").trim()) return;
1122
- const inherited = process.env.NODE_EXTRA_CA_CERTS?.trim();
1123
- if (inherited) env[NODE_EXTRA_CA_CERTS] = inherited;
1132
+ function threadRequestsBrightsyMcp(thread) {
1133
+ return (thread?.messages ?? []).some(messageUsedBrightsyMcp);
1124
1134
  }
1125
- function extraCertsFromBundle(io = {}) {
1126
- const path = process.env.NODE_EXTRA_CA_CERTS?.trim();
1127
- if (path) return splitPemCertificates(readExistingFile(path));
1128
- return splitPemCertificates(readExistingFile(systemCaBundlePath(io)));
1135
+ function shouldInjectBrightsyMcp(thread, opts) {
1136
+ if (!(opts?.connected ?? isBrightsyConnected())) return false;
1137
+ if (opts?.orchestrator) return true;
1138
+ const alwaysOn = opts?.alwaysOnWorktree ?? Boolean(loadAppSettings().brightsy?.injectWorktreeMcp);
1139
+ if (alwaysOn) return true;
1140
+ return threadRequestsBrightsyMcp(thread);
1129
1141
  }
1130
- function extraSystemCaPems(io = {}) {
1131
- const fromBundle = extraCertsFromBundle(io);
1132
- if (fromBundle.length > 0) return fromBundle;
1133
- return splitPemCertificates(collectSystemCaPem(io));
1142
+ function mcpLaunch(cmd, name, env) {
1143
+ if (cmd === "brightsy-mcp") {
1144
+ return { name, command: "brightsy-mcp", ...env ? { env } : {} };
1145
+ }
1146
+ return {
1147
+ name,
1148
+ command: "npx",
1149
+ args: ["-y", "@brightsy/mcp-server"],
1150
+ ...env ? { env } : {}
1151
+ };
1134
1152
  }
1135
- function mergeSystemCaIntoTlsOptions(options, extra, roots = tls.rootCertificates) {
1136
- const existing = options?.ca;
1137
- const base = existing == null ? [...roots] : Array.isArray(existing) ? [...existing] : [existing];
1138
- return { ...options, ca: [...base, ...extra] };
1153
+ function teamEnv(team) {
1154
+ const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
1155
+ return {
1156
+ BRIGHTSY_API_TOKEN: team.access_token,
1157
+ ...team.refresh_token ? { BRIGHTSY_REFRESH_TOKEN: team.refresh_token } : {},
1158
+ ...team.oauth_client_id ? { BRIGHTSY_OAUTH_CLIENT_ID: team.oauth_client_id } : {},
1159
+ BRIGHTSY_ACCOUNT_ID: team.id,
1160
+ BRIGHTSY_API_URL: endpoint
1161
+ };
1139
1162
  }
1140
- function installCreateSecureContextCaPatch(api, extra) {
1141
- if (api.__sideboardSystemCaPatched) return true;
1142
- if (typeof api.createSecureContext !== "function") return false;
1143
- const orig = api.createSecureContext;
1144
- const roots = api.rootCertificates ?? tls.rootCertificates;
1145
- api.createSecureContext = ((options) => orig(mergeSystemCaIntoTlsOptions(options, extra, roots)));
1146
- api.__sideboardSystemCaPatched = true;
1147
- return true;
1163
+ function brightsyMcpAllowedTools(serverNames) {
1164
+ const out = [];
1165
+ for (const name of serverNames) {
1166
+ out.push(`mcp__${name}`, `mcp__${name}__*`);
1167
+ }
1168
+ return out;
1148
1169
  }
1149
- function trustSystemCertificates(io = {}) {
1170
+ function corePackageDir() {
1171
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
1172
+ if (cjsDir) return cjsDir;
1150
1173
  try {
1151
- const extra = extraSystemCaPems(io);
1152
- const api = io.tls ?? tls;
1153
- if (typeof api.getCACertificates === "function" && typeof api.setDefaultCACertificates === "function") {
1154
- const current = api.getCACertificates("default");
1155
- const system = api.getCACertificates("system");
1156
- if (system.length === 0 && extra.length === 0) return false;
1157
- api.setDefaultCACertificates([...current, ...system, ...extra]);
1158
- return true;
1174
+ const url = import.meta.url;
1175
+ if (typeof url === "string" && url.length > 0) {
1176
+ return dirname2(fileURLToPath(url));
1159
1177
  }
1160
- if (extra.length === 0) return false;
1161
- return installCreateSecureContextCaPatch(api, extra);
1162
1178
  } catch {
1163
- return false;
1164
1179
  }
1165
- }
1166
- function bootstrapSystemCa(io = {}) {
1167
- const systemCaBundle = materializeSystemCaBundle(io);
1168
- if (systemCaBundle && !process.env.NODE_EXTRA_CA_CERTS?.trim()) {
1169
- process.env.NODE_EXTRA_CA_CERTS = systemCaBundle;
1180
+ try {
1181
+ const req = createRequire(join6(process.cwd(), "package.json"));
1182
+ return dirname2(req.resolve("@sideboard-ai/core"));
1183
+ } catch {
1184
+ return process.cwd();
1170
1185
  }
1171
- applySystemCaEnv(process.env);
1172
- trustSystemCertificates(io);
1173
- }
1174
-
1175
- // src/agents/packaged-runtime.ts
1176
- import { existsSync as existsSync4 } from "fs";
1177
- import { join as join3 } from "path";
1178
- function electronResourcesPath() {
1179
- const resources = process.resourcesPath;
1180
- if (typeof resources !== "string" || !resources) return null;
1181
- return resources;
1182
1186
  }
1183
- function packagedCursorRuntimeDir() {
1184
- const resources = electronResourcesPath();
1185
- if (!resources) return null;
1186
- const dir = join3(resources, "cursor-runtime");
1187
- if (!existsSync4(join3(dir, "core-dist", "agents", "cursor-runner.js"))) return null;
1188
- return dir;
1187
+ function findSideboardMcpJsEntry() {
1188
+ const override = process.env.SIDEBOARD_MCP_ENTRY?.trim() || process.env.SIDEBOARD_CLI?.trim();
1189
+ if (override && existsSync5(override)) return override;
1190
+ const packaged = packagedMcpStdioPath();
1191
+ if (packaged) return packaged;
1192
+ let dir = corePackageDir();
1193
+ for (let i = 0; i < 10; i++) {
1194
+ const candidates = [
1195
+ join6(dir, "mcp/run-stdio.js"),
1196
+ join6(dir, "mcp/run-stdio.cjs"),
1197
+ join6(dir, "dist/mcp/run-stdio.js"),
1198
+ join6(dir, "dist/mcp/run-stdio.cjs"),
1199
+ join6(dir, "packages/core/dist/mcp/run-stdio.js"),
1200
+ join6(dir, "packages/cli/dist/index.js"),
1201
+ join6(dir, "cli/dist/index.js")
1202
+ ];
1203
+ for (const p of candidates) {
1204
+ if (existsSync5(p) && !isAsarPath(p)) return p;
1205
+ }
1206
+ const parent = dirname2(dir);
1207
+ if (parent === dir) break;
1208
+ dir = parent;
1209
+ }
1210
+ return null;
1189
1211
  }
1190
- function packagedCursorRunnerPath() {
1191
- const dir = packagedCursorRuntimeDir();
1192
- return dir ? join3(dir, "core-dist", "agents", "cursor-runner.js") : null;
1212
+ async function resolveSideboardMcpServer() {
1213
+ const entry = findSideboardMcpJsEntry();
1214
+ if (entry) {
1215
+ const isCli = /[/\\]cli[/\\]dist[/\\]index\.js$/.test(entry);
1216
+ const scriptArgs = isCli ? [entry, "mcp"] : [entry];
1217
+ const launch = applyNodeLaunch(await resolveNodeLaunch(entry), scriptArgs);
1218
+ if (launch.file !== "/bin/sh" && !isElectronLikeCommand(launch.file)) {
1219
+ return {
1220
+ name: "sideboard",
1221
+ command: launch.file,
1222
+ args: launch.args,
1223
+ ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {}
1224
+ };
1225
+ }
1226
+ }
1227
+ const which = await run("which", ["sideboard"], { reject: false });
1228
+ if (which.exitCode === 0 && which.stdout.trim()) {
1229
+ return { name: "sideboard", command: which.stdout.trim(), args: ["mcp"] };
1230
+ }
1231
+ return { name: "sideboard", command: "sideboard", args: ["mcp"] };
1193
1232
  }
1194
- function packagedMcpDir() {
1195
- const resources = electronResourcesPath();
1196
- if (!resources) return null;
1197
- const dir = join3(resources, "sideboard-mcp");
1198
- if (!existsSync4(join3(dir, "core-dist", "mcp", "run-stdio.js"))) return null;
1199
- return dir;
1233
+ async function buildInjectedMcpServers(opts) {
1234
+ const servers = [];
1235
+ if (opts.includeSideboard) {
1236
+ const sideboard = await resolveSideboardMcpServer();
1237
+ sideboard.env = {
1238
+ ...sideboard.env ?? {},
1239
+ ...injectedSideboardMcpEnv(opts)
1240
+ };
1241
+ try {
1242
+ mergeAgentGitAuthEnv(
1243
+ sideboard.env,
1244
+ await resolveAgentGitAuthEnv(sideboard.env)
1245
+ );
1246
+ } catch {
1247
+ }
1248
+ applyAgentRunnerHeapEnv(sideboard.env);
1249
+ servers.push(sideboard);
1250
+ }
1251
+ if (opts.includeBrightsy && isBrightsyConnected()) {
1252
+ const cmd = await resolveBrightsyMcpCommand();
1253
+ const teams = await ensureConnectedBrightsyTeamTokens();
1254
+ if (teams.length > 0) {
1255
+ const used = /* @__PURE__ */ new Set();
1256
+ for (const team of teams) {
1257
+ let name = brightsyMcpServerName(team.slug);
1258
+ if (used.has(name)) name = `${name}_${team.id.slice(0, 8)}`;
1259
+ used.add(name);
1260
+ servers.push(mcpLaunch(cmd, name, teamEnv(team)));
1261
+ }
1262
+ } else {
1263
+ servers.push(mcpLaunch(cmd, "brightsy"));
1264
+ }
1265
+ }
1266
+ return servers;
1200
1267
  }
1201
- function packagedMcpStdioPath() {
1202
- const dir = packagedMcpDir();
1203
- return dir ? join3(dir, "core-dist", "mcp", "run-stdio.js") : null;
1268
+ function cursorSafeMcpLaunch(command, args) {
1269
+ if (process.platform === "win32") {
1270
+ return args && args.length > 0 ? { command, args } : { command };
1271
+ }
1272
+ const unwrapped = unwrapStrippedElectronLaunch(command, args);
1273
+ const file = unwrapped?.file ?? command;
1274
+ const fileArgs = unwrapped?.args ?? args ?? [];
1275
+ return fileArgs.length > 0 ? { command: file, args: fileArgs } : { command: file };
1204
1276
  }
1205
- function packagedBundledNodePath() {
1206
- const resources = electronResourcesPath();
1207
- if (!resources) return null;
1208
- const bin = join3(resources, "node", "bin", "node");
1209
- if (!existsSync4(bin)) return null;
1210
- return bin;
1277
+ function mcpSpawnEnv(env) {
1278
+ if (!env) return void 0;
1279
+ const out = { ...env };
1280
+ delete out.ELECTRON_RUN_AS_NODE;
1281
+ delete out.ELECTRON_RUN_AS_NODE;
1282
+ return Object.keys(out).length > 0 ? out : void 0;
1211
1283
  }
1212
- function packagedCursorRipgrepCandidate(platformPkg, binName) {
1213
- const dir = packagedCursorRuntimeDir();
1214
- if (!dir) return null;
1215
- return join3(dir, "node_modules", platformPkg, "bin", binName);
1284
+ function toCursorMcpServers(servers) {
1285
+ const out = {};
1286
+ for (const s of servers) {
1287
+ const env = mcpSpawnEnv(s.env);
1288
+ const launch = cursorSafeMcpLaunch(s.command, s.args);
1289
+ out[s.name] = {
1290
+ type: "stdio",
1291
+ command: launch.command,
1292
+ ...launch.args && launch.args.length > 0 ? { args: launch.args } : {},
1293
+ ...env ? { env } : {}
1294
+ };
1295
+ }
1296
+ return out;
1216
1297
  }
1217
-
1218
- // src/agents/node-launch.ts
1219
- var AGENT_RUNNER_MAX_OLD_SPACE_MB = 8192;
1220
- var MAX_OLD_SPACE_FLAG = /(?:^|\s)(--max[-_]old[-_]space[-_]size)(?:[= ](\d+))?(?=\s|$)/;
1221
- function withMaxOldSpaceSize(nodeOptions, heapMb) {
1222
- const existing = (nodeOptions ?? "").trim();
1223
- const match = MAX_OLD_SPACE_FLAG.exec(existing);
1224
- if (match) {
1225
- const current = match[2] ? Number(match[2]) : 0;
1226
- if (Number.isFinite(current) && current >= heapMb) return existing;
1227
- return existing.replace(MAX_OLD_SPACE_FLAG, ` --max-old-space-size=${heapMb}`).trim();
1298
+ function toCodexMcpConfigArgs(servers) {
1299
+ const args = [];
1300
+ for (const s of servers) {
1301
+ const prefix = `mcp_servers.${s.name}`;
1302
+ args.push("-c", `${prefix}.command=${JSON.stringify(s.command)}`);
1303
+ if (s.args?.length) {
1304
+ args.push("-c", `${prefix}.args=${JSON.stringify(s.args)}`);
1305
+ }
1306
+ const env = mcpSpawnEnv(s.env);
1307
+ if (env) {
1308
+ for (const [key, value] of Object.entries(env)) {
1309
+ if (isCodexSecretEnvKey(key)) continue;
1310
+ args.push("-c", `${prefix}.env.${key}=${JSON.stringify(value)}`);
1311
+ }
1312
+ }
1313
+ args.push("-c", `${prefix}.default_tools_approval_mode=${JSON.stringify("approve")}`);
1314
+ args.push("-c", `${prefix}.tool_timeout_sec=300`);
1315
+ args.push("-c", `${prefix}.startup_timeout_sec=30`);
1228
1316
  }
1229
- return existing ? `${existing} --max-old-space-size=${heapMb}` : `--max-old-space-size=${heapMb}`;
1317
+ return args;
1230
1318
  }
1231
- function applyAgentRunnerHeapEnv(env) {
1232
- env.NODE_OPTIONS = withMaxOldSpaceSize(
1233
- env.NODE_OPTIONS,
1234
- AGENT_RUNNER_MAX_OLD_SPACE_MB
1235
- );
1236
- applySystemCaEnv(env);
1319
+ function toOpencodeMcpConfigContent(servers, opts) {
1320
+ const mcp = {};
1321
+ for (const s of servers) {
1322
+ const env = mcpSpawnEnv(s.env);
1323
+ mcp[s.name] = {
1324
+ type: "local",
1325
+ command: [s.command, ...s.args ?? []],
1326
+ enabled: true,
1327
+ ...env ? { environment: env } : {}
1328
+ };
1329
+ }
1330
+ for (const name of opts?.disableNames ?? []) {
1331
+ const key = name.trim();
1332
+ if (!key || mcp[key]?.enabled === true) continue;
1333
+ mcp[key] = { ...mcp[key], enabled: false };
1334
+ }
1335
+ return JSON.stringify({ mcp });
1237
1336
  }
1238
- function envWithAgentHeap(env) {
1239
- const next = { ...env };
1240
- applyAgentRunnerHeapEnv(next);
1337
+ function stripElectronFromUserMcpEntry(entry) {
1338
+ const next = { ...entry };
1339
+ const env = next.env;
1340
+ if (!env || typeof env !== "object" || Array.isArray(env)) return next;
1341
+ const cleaned = { ...env };
1342
+ delete cleaned.ELECTRON_RUN_AS_NODE;
1343
+ next.env = cleaned;
1241
1344
  return next;
1242
1345
  }
1243
- function isAsarPath(filePath) {
1244
- if (/\.asar\.unpacked([/\\]|$)/.test(filePath)) return false;
1245
- return /\.asar([/\\]|$)/.test(filePath);
1346
+ function mcpServersRecord(servers, extraServers) {
1347
+ const mcpServers = {};
1348
+ for (const s of servers) {
1349
+ const env = mcpSpawnEnv(s.env);
1350
+ mcpServers[s.name] = {
1351
+ command: s.command,
1352
+ ...s.args ? { args: s.args } : {},
1353
+ ...env ? { env } : {}
1354
+ };
1355
+ }
1356
+ if (extraServers) {
1357
+ for (const [rawName, entry] of Object.entries(extraServers)) {
1358
+ const name = rawName.trim();
1359
+ if (!name || mcpServers[name] || !entry) continue;
1360
+ mcpServers[name] = stripElectronFromUserMcpEntry(entry);
1361
+ }
1362
+ }
1363
+ return mcpServers;
1246
1364
  }
1247
- function unpackedAsarPath(filePath) {
1248
- if (!isAsarPath(filePath)) return null;
1249
- const unpacked = filePath.replace(/\.asar(?=[/\\])/, ".asar.unpacked");
1250
- if (unpacked === filePath) return null;
1251
- return existsSync5(unpacked) ? unpacked : null;
1365
+ function writeMcpServersConfig(servers, extraServers) {
1366
+ const mcpServers = mcpServersRecord(servers, extraServers);
1367
+ if (Object.keys(mcpServers).length === 0) return null;
1368
+ const dir = mkdtempSync(join6(tmpdir(), "sideboard-mcp-"));
1369
+ const cfgPath = join6(dir, "mcp.json");
1370
+ writeFileSync3(cfgPath, JSON.stringify({ mcpServers }, null, 2), { mode: 384 });
1371
+ return cfgPath;
1252
1372
  }
1253
- function nodeReadableScriptPath(scriptPath) {
1254
- return unpackedAsarPath(scriptPath) ?? scriptPath;
1373
+
1374
+ // src/agents/user-mcp-config.ts
1375
+ function userClaudeMcpConfigPath() {
1376
+ return join7(homedir4(), ".claude.json");
1255
1377
  }
1256
- var PREFERRED_LTS_MAJORS = [24, 22];
1257
- function parseNodeMajor(version) {
1258
- const match = /^v?(\d+)/.exec(version.trim());
1259
- if (!match) return null;
1260
- const major = Number(match[1]);
1261
- return Number.isInteger(major) ? major : null;
1378
+
1379
+ // src/agents/orch-mcp-isolation.ts
1380
+ function isInjectedOrchMcpName(name) {
1381
+ const n = name.trim().toLowerCase();
1382
+ return n === "sideboard" || n === "brightsy" || n.startsWith("brightsy_");
1262
1383
  }
1263
- function scoreNodeForAgentRuntime(candidate) {
1264
- const major = parseNodeMajor(candidate.version);
1265
- if (major == null) return Number.NEGATIVE_INFINITY;
1266
- if (major < 22) return major - 100;
1267
- const posix = candidate.path.replace(/\\/g, "/");
1268
- let score = 0;
1269
- if (major % 2 === 0) {
1270
- score += 1e3 + major * 10;
1271
- } else {
1272
- score += major;
1273
- }
1274
- if (/\/Cellar\/node\/\d/.test(posix) && !/\/Cellar\/node@\d+/.test(posix)) {
1275
- score -= 50;
1384
+ function asObject(value) {
1385
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1386
+ return value;
1387
+ }
1388
+ function listMcpNamesFromJsonMap(raw, key) {
1389
+ return Object.keys(asObject(asObject(raw)[key])).filter((n) => n.trim());
1390
+ }
1391
+ function listMcpNamesFromCodexToml(text) {
1392
+ try {
1393
+ const parsed = parseToml(text);
1394
+ return Object.keys(asObject(parsed.mcp_servers)).filter((n) => n.trim());
1395
+ } catch {
1396
+ return [];
1276
1397
  }
1277
- return score;
1278
1398
  }
1279
- function pickPreferredNode(candidates) {
1280
- let best = null;
1281
- let bestScore = Number.NEGATIVE_INFINITY;
1282
- for (const candidate of candidates) {
1283
- const score = scoreNodeForAgentRuntime(candidate);
1284
- if (score > bestScore) {
1285
- bestScore = score;
1286
- best = candidate;
1287
- }
1399
+ function readJsonObject(path) {
1400
+ try {
1401
+ return JSON.parse(readFileSync4(path, "utf8"));
1402
+ } catch {
1403
+ return {};
1288
1404
  }
1289
- return best;
1290
1405
  }
1291
- function versionDirNodeBins(root, toBin) {
1292
- if (!existsSync5(root)) return [];
1406
+ function readText(path) {
1293
1407
  try {
1294
- return readdirSync(root).map(toBin);
1408
+ return readFileSync4(path, "utf8");
1295
1409
  } catch {
1296
- return [];
1410
+ return "";
1297
1411
  }
1298
1412
  }
1299
- function defaultNodeBinCandidates(home = homedir2()) {
1300
- const kegs = ["/opt/homebrew", "/usr/local"].flatMap(
1301
- (prefix) => PREFERRED_LTS_MAJORS.map((major) => join4(prefix, "opt", `node@${major}`, "bin", "node"))
1302
- );
1413
+ function userCodexConfigPaths(home = homedir5()) {
1414
+ const paths = [
1415
+ join8(home, ".codex", "config.toml"),
1416
+ join8(home, ".config", "codex", "config.toml")
1417
+ ];
1418
+ const codexHome = process.env.CODEX_HOME?.trim();
1419
+ if (codexHome) paths.unshift(join8(codexHome, "config.toml"));
1420
+ return paths;
1421
+ }
1422
+ function userOpencodeConfigPaths(home = homedir5()) {
1303
1423
  return [
1304
- ...kegs,
1305
- "/opt/homebrew/bin/node",
1306
- "/usr/local/bin/node",
1307
- join4(home, ".local/share/fnm/aliases/default/bin/node"),
1308
- join4(home, ".nvm/current/bin/node"),
1309
- join4(home, ".volta/bin/node"),
1310
- join4(home, ".asdf/shims/node"),
1311
- join4(home, ".local/share/mise/shims/node"),
1312
- ...versionDirNodeBins(
1313
- join4(home, ".nvm", "versions", "node"),
1314
- (name) => join4(home, ".nvm", "versions", "node", name, "bin", "node")
1315
- ),
1316
- ...versionDirNodeBins(
1317
- join4(home, ".local/share/fnm", "node-versions"),
1318
- (name) => join4(home, ".local/share/fnm", "node-versions", name, "installation", "bin", "node")
1319
- ),
1320
- ...versionDirNodeBins(
1321
- join4(home, ".volta", "tools", "image", "node"),
1322
- (name) => join4(home, ".volta", "tools", "image", "node", name, "bin", "node")
1323
- )
1424
+ join8(home, ".config", "opencode", "opencode.json"),
1425
+ join8(home, ".config", "opencode", "opencode.jsonc")
1324
1426
  ];
1325
1427
  }
1326
- function uniqueExistingNodeBins(paths) {
1327
- const seen = /* @__PURE__ */ new Set();
1428
+ function userMcpNamesToDisable(opts) {
1429
+ const keep = new Set(
1430
+ [...opts.injectedNames ?? []].map((n) => n.trim().toLowerCase()).filter(Boolean)
1431
+ );
1328
1432
  const out = [];
1329
- for (const raw of paths) {
1330
- const p = raw.trim();
1331
- if (!p || !existsSync5(p) || isElectronLikeCommand(p)) continue;
1332
- let key = p;
1333
- try {
1334
- key = realpathSync(p);
1335
- } catch {
1336
- continue;
1337
- }
1338
- if (seen.has(key)) continue;
1433
+ const seen = /* @__PURE__ */ new Set();
1434
+ for (const raw of opts.names) {
1435
+ const name = raw.trim();
1436
+ if (!name) continue;
1437
+ const key = name.toLowerCase();
1438
+ if (seen.has(key) || keep.has(key) || isInjectedOrchMcpName(name)) continue;
1339
1439
  seen.add(key);
1340
- out.push(p);
1440
+ out.push(name);
1341
1441
  }
1342
1442
  return out;
1343
1443
  }
1344
- async function whichAllNode() {
1345
- if (process.platform === "win32") {
1346
- const located = await run("where", ["node"], { reject: false, timeoutMs: 5e3 });
1347
- if (located.exitCode !== 0) return [];
1348
- return located.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1349
- }
1350
- const all = await run("which", ["-a", "node"], { reject: false, timeoutMs: 5e3 });
1351
- if (all.exitCode === 0 && all.stdout.trim()) {
1352
- return all.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1353
- }
1354
- const single = await run("which", ["node"], { reject: false, timeoutMs: 5e3 });
1355
- if (single.exitCode !== 0 || !single.stdout.trim()) return [];
1356
- return [single.stdout.trim()];
1357
- }
1358
- async function probeNodeVersion(bin) {
1359
- const probed = await run(bin, ["-v"], { reject: false, timeoutMs: 4e3 });
1360
- if (probed.exitCode !== 0) return null;
1361
- const version = probed.stdout.trim().split(/\r?\n/).find(Boolean);
1362
- return version || null;
1363
- }
1364
- async function findSystemNode() {
1365
- const fromPath = await whichAllNode();
1366
- const bins = uniqueExistingNodeBins([...fromPath, ...defaultNodeBinCandidates()]);
1367
- if (bins.length === 0) return null;
1368
- const probed = await Promise.all(
1369
- bins.map(async (path) => {
1370
- const version = await probeNodeVersion(path);
1371
- return version ? { path, version } : null;
1372
- })
1373
- );
1374
- return pickPreferredNode(probed.filter((c) => c != null));
1375
- }
1376
- function applyNodeLaunch(launch, args) {
1377
- const readableArgs = args.map(nodeReadableScriptPath);
1378
- if (!launch.env.ELECTRON_RUN_AS_NODE) {
1379
- return {
1380
- file: launch.file,
1381
- args: readableArgs,
1382
- env: envWithAgentHeap(launch.env)
1383
- };
1444
+ function listUserCodexMcpNames(home = homedir5()) {
1445
+ const names = [];
1446
+ for (const path of userCodexConfigPaths(home)) {
1447
+ if (!existsSync7(path)) continue;
1448
+ names.push(...listMcpNamesFromCodexToml(readText(path)));
1384
1449
  }
1385
- const wrapped = wrapElectronAsNodeLaunch(launch.file, readableArgs);
1386
- if (process.platform === "win32") {
1387
- return {
1388
- file: wrapped.file,
1389
- args: wrapped.args,
1390
- env: envWithAgentHeap(launch.env)
1391
- };
1450
+ return names;
1451
+ }
1452
+ function listUserOpencodeMcpNames(home = homedir5()) {
1453
+ const names = [];
1454
+ for (const path of userOpencodeConfigPaths(home)) {
1455
+ if (!existsSync7(path)) continue;
1456
+ names.push(...listMcpNamesFromJsonMap(readJsonObject(path), "mcp"));
1392
1457
  }
1393
- const env = envWithAgentHeap(launch.env);
1394
- delete env.ELECTRON_RUN_AS_NODE;
1395
- return { file: wrapped.file, args: wrapped.args, env };
1458
+ return names;
1396
1459
  }
1397
- async function resolveNodeLaunch(scriptPath) {
1398
- const script = nodeReadableScriptPath(scriptPath);
1399
- if (!isAsarPath(script)) {
1400
- const bundled = packagedBundledNodePath();
1401
- if (bundled && !isElectronLikeCommand(bundled)) {
1402
- return { file: bundled, env: {} };
1403
- }
1404
- const node = await findSystemNode();
1405
- if (node) {
1406
- return { file: node.path, env: {}, nodeVersion: node.version };
1407
- }
1460
+ function userClaudeMcpConfigObject(home = homedir5()) {
1461
+ const claudePath = home === homedir5() ? userClaudeMcpConfigPath() : join8(home, ".claude.json");
1462
+ if (!existsSync7(claudePath)) return {};
1463
+ return asObject(asObject(readJsonObject(claudePath)).mcpServers);
1464
+ }
1465
+ function listUserClaudeMcpServerEntries(home = homedir5(), projectDirs) {
1466
+ const out = {};
1467
+ for (const [name, entry] of Object.entries(
1468
+ listEnabledClaudePluginMcpServers({ home, projectDirs })
1469
+ )) {
1470
+ if (!name || isInjectedOrchMcpName(name)) continue;
1471
+ out[name] = entry;
1408
1472
  }
1409
- return {
1410
- file: process.execPath,
1411
- env: { ELECTRON_RUN_AS_NODE: "1" }
1412
- };
1473
+ for (const [rawName, value] of Object.entries(userClaudeMcpConfigObject(home))) {
1474
+ const name = rawName.trim();
1475
+ if (!name || isInjectedOrchMcpName(name)) continue;
1476
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1477
+ out[name] = value;
1478
+ }
1479
+ return out;
1413
1480
  }
1414
-
1415
- // src/agents/codex-mcp-profile.ts
1416
- import { randomBytes } from "crypto";
1417
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
1418
- import { homedir as homedir3 } from "os";
1419
- import { join as join5 } from "path";
1420
- function isCodexSecretEnvKey(key) {
1421
- return /token|secret|password|credential|oauth|api_key|_key$/i.test(key);
1481
+ function toCodexDisableUserMcpArgs(names) {
1482
+ const args = [];
1483
+ for (const name of names) {
1484
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
1485
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
1486
+ }
1487
+ return args;
1422
1488
  }
1423
- function tomlBasicString(value) {
1424
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`;
1489
+ function toCodexUnattendedAppsArgs() {
1490
+ return [
1491
+ "-c",
1492
+ "features.apps=false",
1493
+ "-c",
1494
+ "apps._default.enabled=false",
1495
+ "-c",
1496
+ "apps.posthog.enabled=false",
1497
+ "-c",
1498
+ "features.plugins=false"
1499
+ ];
1425
1500
  }
1426
- function secretEnv(env) {
1427
- if (!env) return void 0;
1428
- const out = { ...env };
1429
- delete out.ELECTRON_RUN_AS_NODE;
1430
- return Object.keys(out).length > 0 ? out : void 0;
1501
+
1502
+ // src/agents/turn-input.ts
1503
+ function normalizeTurnInput(input) {
1504
+ if (typeof input === "string") return { prompt: input };
1505
+ return {
1506
+ prompt: input.prompt,
1507
+ cachedPrefix: input.cachedPrefix?.trim() || void 0,
1508
+ systemPrompt: input.systemPrompt?.trim() || void 0,
1509
+ ...input.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
1510
+ };
1431
1511
  }
1432
- function writeCodexMcpSecretProfile(servers) {
1433
- const blocks = [];
1434
- for (const s of servers) {
1435
- const env = secretEnv(s.env);
1436
- if (!env) continue;
1437
- const secrets = Object.entries(env).filter(([key]) => isCodexSecretEnvKey(key));
1438
- if (secrets.length === 0) continue;
1439
- const lines = [`[mcp_servers.${s.name}.env]`];
1440
- for (const [key, value] of secrets) lines.push(`${key} = ${tomlBasicString(value)}`);
1441
- blocks.push(lines.join("\n"));
1512
+ function dropCachedPrefixOnResume(input, sessionId) {
1513
+ const turn = normalizeTurnInput(input);
1514
+ if (sessionId) {
1515
+ return {
1516
+ prompt: turn.prompt,
1517
+ ...turn.systemPrompt ? { systemPrompt: turn.systemPrompt } : {},
1518
+ ...turn.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
1519
+ };
1442
1520
  }
1443
- if (blocks.length === 0) return null;
1444
- const home = process.env.CODEX_HOME?.trim() || join5(homedir3(), ".codex");
1445
- mkdirSync2(home, { recursive: true, mode: 448 });
1446
- const profile = `sideboard-${randomBytes(8).toString("hex")}`;
1447
- const file = join5(home, `${profile}.config.toml`);
1448
- writeFileSync2(file, `${blocks.join("\n\n")}
1449
- `, { mode: 384 });
1450
- return { profile, file };
1521
+ return turn;
1451
1522
  }
1523
+ function flattenTurnInput(input) {
1524
+ const { cachedPrefix, prompt, systemPrompt } = normalizeTurnInput(input);
1525
+ if (cachedPrefix) return `${cachedPrefix}
1452
1526
 
1453
- // src/agents/injected-mcp.ts
1454
- var SIDEBOARD_MCP_ALLOWED_TOOLS = [
1455
- "mcp__sideboard",
1456
- "mcp__sideboard__*"
1457
- ];
1458
- var SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS = [
1459
- "mcp__sideboard__present_artifact",
1460
- "mcp__sideboard__present_schema",
1461
- "mcp__sideboard__present_files",
1462
- "mcp__sideboard__ask_user",
1463
- "mcp__sideboard__present_plan",
1464
- "mcp__sideboard__wait_for_job",
1465
- "mcp__sideboard__stop_job",
1466
- "mcp__sideboard__list_run_scripts",
1467
- "mcp__sideboard__run_dev_script",
1468
- "mcp__sideboard__stop_dev_script",
1469
- "mcp__sideboard__get_run_log",
1470
- "mcp__sideboard__get_orchestrator",
1471
- "mcp__sideboard__notify_orchestrator",
1472
- "mcp__sideboard__set_workspace_tags",
1473
- "mcp__sideboard__set_wake_on_github_edges",
1474
- "mcp__sideboard__get_viewer_context",
1475
- "mcp__sideboard__update_viewer_context",
1476
- "mcp__sideboard__list_env",
1477
- "mcp__sideboard__set_env",
1478
- "mcp__sideboard__delete_env",
1479
- "mcp__sideboard__list_schedules",
1480
- "mcp__sideboard__create_schedule",
1481
- "mcp__sideboard__update_schedule",
1482
- "mcp__sideboard__delete_schedule",
1483
- "mcp__sideboard__run_schedule",
1484
- "mcp__sideboard__list_order",
1485
- "mcp__sideboard__show_plan",
1486
- "mcp__sideboard__set_dependency",
1487
- "mcp__sideboard__clear_dependency",
1488
- "mcp__sideboard__satisfy_dependency",
1489
- "mcp__sideboard__posthog_api"
1490
- ];
1491
- var SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS = ["mcp__sideboard__github_*"];
1492
- var SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS = ["mcp__sideboard__linear_*"];
1493
- var SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS = ["mcp__sideboard__abletime_*"];
1494
- function sideboardWorktreeAllowedTools(opts) {
1495
- const out = SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS.filter(
1496
- (tool) => (opts?.planMode || tool !== "mcp__sideboard__present_plan") && (opts?.posthog || tool !== "mcp__sideboard__posthog_api")
1497
- );
1498
- if (opts?.github !== false) out.push(...SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS);
1499
- if (opts?.linear) out.push(...SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS);
1500
- if (opts?.abletime) out.push(...SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS);
1501
- return out;
1527
+ ---
1528
+
1529
+ Current request:
1530
+ ${prompt}`;
1531
+ if (systemPrompt) return `${systemPrompt}
1532
+
1533
+ ${prompt}`;
1534
+ return prompt;
1502
1535
  }
1503
- var brightsyMcpCommandCache = null;
1504
- async function resolveBrightsyMcpCommand() {
1505
- const now = Date.now();
1506
- if (brightsyMcpCommandCache && now - brightsyMcpCommandCache.at < 6e4 && brightsyMcpCommandCache.command) {
1507
- return brightsyMcpCommandCache.command;
1508
- }
1509
- const which = await run("which", ["brightsy-mcp"], { reject: false });
1510
- const command = which.exitCode === 0 && which.stdout.trim() ? "brightsy-mcp" : "npx";
1511
- brightsyMcpCommandCache = { at: now, command };
1512
- return command;
1536
+ function splitTurnInputForSystemPrompt(input) {
1537
+ const turn = normalizeTurnInput(input);
1538
+ return {
1539
+ promptText: flattenTurnInput({ cachedPrefix: turn.cachedPrefix, prompt: turn.prompt }),
1540
+ systemPrompt: turn.systemPrompt
1541
+ };
1513
1542
  }
1514
- function isBrightsyConnected() {
1543
+
1544
+ // src/agents/acp.ts
1545
+ var ACP_ATTACH_ERROR = "ACP harnesses have no interactive attach. Continue the chat in Sideboard.";
1546
+ function entryDir() {
1547
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
1548
+ if (cjsDir) return cjsDir;
1515
1549
  try {
1516
- loadBrightsyConfig();
1517
- return true;
1550
+ return dirname4(fileURLToPath2(import.meta.url));
1518
1551
  } catch {
1519
- return false;
1552
+ try {
1553
+ const req = createRequire2(process.cwd() + "/");
1554
+ return dirname4(req.resolve("@sideboard-ai/core"));
1555
+ } catch {
1556
+ return process.cwd();
1557
+ }
1520
1558
  }
1521
1559
  }
1522
- var BRIGHTSY_WORD = /(?<![a-z0-9_-])brightsy(?![a-z0-9_-])/i;
1523
- function promptMentionsBrightsy(text) {
1524
- return BRIGHTSY_WORD.test(text ?? "");
1525
- }
1526
- function isBrightsyMcpToolName(name) {
1527
- const n = name.toLowerCase();
1528
- return n === "brightsy" || n.startsWith("mcp__brightsy") || n.startsWith("brightsy_");
1560
+ function acpRunnerPath() {
1561
+ const packagedRoot = packagedCursorRuntimeDir();
1562
+ if (packagedRoot) {
1563
+ const packaged = join9(packagedRoot, "core-dist", "agents", "acp-runner.js");
1564
+ if (existsSync8(packaged)) return packaged;
1565
+ }
1566
+ const root = entryDir();
1567
+ const candidates = [
1568
+ join9(root, "agents", "acp-runner.js"),
1569
+ join9(root, "agents", "acp-runner.cjs"),
1570
+ join9(root, "dist", "agents", "acp-runner.js"),
1571
+ join9(root, "dist", "agents", "acp-runner.cjs"),
1572
+ join9(root, "acp-runner.ts"),
1573
+ join9(root, "src", "agents", "acp-runner.ts")
1574
+ ];
1575
+ for (const candidate of candidates) {
1576
+ if (existsSync8(candidate)) return candidate;
1577
+ }
1578
+ return candidates[0];
1529
1579
  }
1530
- function toolInputUsesBrightsyDatasource(input) {
1531
- const ds = input?.datasource;
1532
- return typeof ds === "string" && ds.toLowerCase() === "brightsy";
1580
+ function harnessFor(thread) {
1581
+ return isAcpHarnessId(thread.acpHarness) ? thread.acpHarness : defaultAcpHarness();
1533
1582
  }
1534
- function messageUsedBrightsyMcp(msg) {
1535
- if (msg.role === "user" && promptMentionsBrightsy(msg.text)) return true;
1536
- for (const part of msg.parts ?? []) {
1537
- if (part.type !== "tool") continue;
1538
- if (isBrightsyMcpToolName(part.name)) return true;
1539
- if (/present_(schema|files)$/i.test(part.name) && toolInputUsesBrightsyDatasource(part.input)) {
1540
- return true;
1541
- }
1583
+ var acpAdapter = {
1584
+ kind: "acp",
1585
+ async detect() {
1586
+ return detectAcpHarness(defaultAcpHarness());
1587
+ },
1588
+ async buildTurn(thread, input) {
1589
+ const harness = harnessFor(thread);
1590
+ const command = await resolveAcpHarnessCommand(harness);
1591
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
1592
+ const prompt = flattenTurnInput(input);
1593
+ const resumePrompt = flattenTurnInput(dropCachedPrefixOnResume(input, sessionId));
1594
+ const isOrchestrator = isOrchestratorThread(thread);
1595
+ const injected = await buildInjectedMcpServers({
1596
+ includeSideboard: true,
1597
+ includeBrightsy: shouldInjectBrightsyMcp(thread, { orchestrator: isOrchestrator }),
1598
+ orchestratorThreadId: isOrchestrator ? thread.id : null,
1599
+ threadId: thread.id
1600
+ });
1601
+ const injectedAcp = toAcpMcpServers(injected);
1602
+ const userMcp = isOrchestrator ? [] : acpUserStdioServers(
1603
+ listUserClaudeMcpServerEntries(homedir6(), [thread.repoPath, thread.worktreePath]),
1604
+ new Set(injectedAcp.map((server) => server.name))
1605
+ );
1606
+ const req = {
1607
+ prompt,
1608
+ resumePrompt,
1609
+ transcript: acpPriorTranscript(thread.messages ?? []),
1610
+ cwd: thread.worktreePath,
1611
+ sessionId,
1612
+ harness,
1613
+ command: command.file,
1614
+ args: command.args,
1615
+ mcpServers: [...injectedAcp, ...userMcp],
1616
+ planMode: thread.planMode,
1617
+ autonomy: thread.autonomy
1618
+ };
1619
+ const runner = acpRunnerPath();
1620
+ const isTs = runner.endsWith(".ts");
1621
+ const launch = applyNodeLaunch(
1622
+ await resolveNodeLaunch(runner),
1623
+ isTs ? ["--import", "tsx", runner] : [runner]
1624
+ );
1625
+ return {
1626
+ file: launch.file,
1627
+ args: launch.args,
1628
+ cwd: thread.worktreePath,
1629
+ stdin: JSON.stringify(req),
1630
+ env: launch.env
1631
+ };
1632
+ },
1633
+ parseEvent(line) {
1634
+ return parseAcpRunnerLine(line);
1635
+ },
1636
+ async resolveSessionId(_worktreePath, cached) {
1637
+ return cached?.trim() || null;
1638
+ },
1639
+ async buildAttach(_thread) {
1640
+ throw new Error(ACP_ATTACH_ERROR);
1542
1641
  }
1543
- return false;
1544
- }
1545
- function threadRequestsBrightsyMcp(thread) {
1546
- return (thread?.messages ?? []).some(messageUsedBrightsyMcp);
1642
+ };
1643
+ function acpHarnessDisplayName(thread) {
1644
+ if (thread.agent !== "acp") return thread.agent;
1645
+ return acpHarnessLabel(thread.acpHarness);
1547
1646
  }
1548
- function shouldInjectBrightsyMcp(thread, opts) {
1549
- if (!(opts?.connected ?? isBrightsyConnected())) return false;
1550
- if (opts?.orchestrator) return true;
1551
- const alwaysOn = opts?.alwaysOnWorktree ?? Boolean(loadAppSettings().brightsy?.injectWorktreeMcp);
1552
- if (alwaysOn) return true;
1553
- return threadRequestsBrightsyMcp(thread);
1647
+
1648
+ // src/agents/brightsy.ts
1649
+ import { existsSync as existsSync9 } from "fs";
1650
+
1651
+ // src/agents/brightsy-targets.ts
1652
+ function encodeBrightsyTarget(type, id, accountId) {
1653
+ if (accountId) return `team:${accountId}:${type}:${id}`;
1654
+ return `${type}:${id}`;
1554
1655
  }
1555
- function mcpLaunch(cmd, name, env) {
1556
- if (cmd === "brightsy-mcp") {
1557
- return { name, command: "brightsy-mcp", ...env ? { env } : {} };
1656
+ function decodeBrightsyTarget(model) {
1657
+ const raw = model?.trim();
1658
+ if (!raw || raw === "default" || raw === "agent:default") {
1659
+ return { type: "agent", id: "default" };
1558
1660
  }
1559
- return {
1560
- name,
1561
- command: "npx",
1562
- args: ["-y", "@brightsy/mcp-server"],
1563
- ...env ? { env } : {}
1564
- };
1565
- }
1566
- function teamEnv(team) {
1567
- const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
1568
- return {
1569
- BRIGHTSY_API_TOKEN: team.access_token,
1570
- ...team.refresh_token ? { BRIGHTSY_REFRESH_TOKEN: team.refresh_token } : {},
1571
- ...team.oauth_client_id ? { BRIGHTSY_OAUTH_CLIENT_ID: team.oauth_client_id } : {},
1572
- BRIGHTSY_ACCOUNT_ID: team.id,
1573
- BRIGHTSY_API_URL: endpoint
1574
- };
1661
+ const teamMatch = raw.match(/^team:([^:]+):(agent|model):(.+)$/);
1662
+ if (teamMatch) {
1663
+ return {
1664
+ type: teamMatch[2],
1665
+ id: teamMatch[3] || "default",
1666
+ accountId: teamMatch[1]
1667
+ };
1668
+ }
1669
+ if (raw.startsWith("agent:")) {
1670
+ return { type: "agent", id: raw.slice("agent:".length) || "default" };
1671
+ }
1672
+ if (raw.startsWith("model:")) {
1673
+ return { type: "model", id: raw.slice("model:".length) };
1674
+ }
1675
+ if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw) || raw === "default") {
1676
+ return { type: "agent", id: raw };
1677
+ }
1678
+ return { type: "model", id: raw };
1575
1679
  }
1576
- function brightsyMcpAllowedTools(serverNames) {
1577
- const out = [];
1578
- for (const name of serverNames) {
1579
- out.push(`mcp__${name}`, `mcp__${name}__*`);
1680
+
1681
+ // src/agents/brightsy.ts
1682
+ function usageFromBrightsy(usage) {
1683
+ if (!usage) return null;
1684
+ const mapped = fromInclusiveInputUsage({
1685
+ inputTokens: Number(usage.prompt_tokens ?? 0),
1686
+ outputTokens: Number(usage.completion_tokens ?? 0),
1687
+ cachedInputTokens: Number(usage.prompt_tokens_details?.cached_tokens ?? 0)
1688
+ });
1689
+ if (!mapped) return null;
1690
+ if (usage.cost != null && Number.isFinite(Number(usage.cost))) {
1691
+ mapped.costUsd = Number(usage.cost);
1580
1692
  }
1581
- return out;
1693
+ return mapped;
1582
1694
  }
1583
- function corePackageDir() {
1584
- const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
1585
- if (cjsDir) return cjsDir;
1695
+ function parseBrightsyCliLine(line) {
1696
+ const trimmed = line.trim();
1697
+ if (!trimmed) return null;
1586
1698
  try {
1587
- const url = import.meta.url;
1588
- if (typeof url === "string" && url.length > 0) {
1589
- return dirname2(fileURLToPath(url));
1699
+ const obj = JSON.parse(trimmed);
1700
+ if (obj.type === "text" && typeof obj.text === "string") {
1701
+ if (looksLikeBrightsyEmptyCompletion(obj.text)) {
1702
+ return [
1703
+ { type: "stderr", data: obj.text },
1704
+ { type: "stdout", data: `Error: ${obj.text}` }
1705
+ ];
1706
+ }
1707
+ return { type: "stdout", data: obj.text };
1708
+ }
1709
+ if (obj.type === "thinking" && typeof obj.text === "string") {
1710
+ return { type: "thinking", data: obj.text };
1711
+ }
1712
+ if (obj.type === "error") {
1713
+ const msg = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
1714
+ return [
1715
+ { type: "stderr", data: msg },
1716
+ { type: "stdout", data: `Error: ${msg}` }
1717
+ ];
1718
+ }
1719
+ if (obj.type === "usage") {
1720
+ const usage = usageFromBrightsy(obj.usage);
1721
+ return usage ? { type: "usage", data: usage } : null;
1722
+ }
1723
+ if (obj.type === "tool_use") {
1724
+ const id = typeof obj.id === "string" && obj.id || `brightsy-tool-${Date.now()}`;
1725
+ const name = typeof obj.name === "string" && obj.name || "brightsy_tool";
1726
+ const input = obj.input && typeof obj.input === "object" && !Array.isArray(obj.input) ? obj.input : void 0;
1727
+ return { type: "tool_use", id, name, input };
1728
+ }
1729
+ if (obj.type === "tool_result" || obj.type === "tool") {
1730
+ const id = typeof obj.id === "string" && obj.id || typeof obj.tool_call_id === "string" && obj.tool_call_id || `brightsy-tool-${Date.now()}`;
1731
+ const content = typeof obj.content === "string" ? obj.content : obj.content != null ? JSON.stringify(obj.content) : void 0;
1732
+ return {
1733
+ type: "tool_result",
1734
+ id,
1735
+ content,
1736
+ isError: obj.isError === true
1737
+ };
1738
+ }
1739
+ if (obj.type === "done") return null;
1740
+ if (typeof obj.type === "string" && ["tool_use", "tool_result", "tool", "thinking", "usage", "error", "done", "text"].includes(
1741
+ obj.type
1742
+ )) {
1743
+ return null;
1590
1744
  }
1745
+ return { type: "stdout", data: trimmed };
1591
1746
  } catch {
1747
+ if (trimmed.startsWith("{") && /"type"\s*:\s*"(tool_use|tool_result|tool|text|thinking|usage|done|error)"/.test(trimmed)) {
1748
+ return null;
1749
+ }
1750
+ if (looksLikeBrightsyEmptyCompletion(trimmed) || /error|failed|unauthorized|quota|limit|not logged in/i.test(trimmed)) {
1751
+ return [
1752
+ { type: "stderr", data: trimmed },
1753
+ { type: "stdout", data: `Error: ${trimmed}` }
1754
+ ];
1755
+ }
1756
+ return { type: "stdout", data: line };
1592
1757
  }
1593
- try {
1594
- const req = createRequire(join6(process.cwd(), "package.json"));
1595
- return dirname2(req.resolve("@sideboard-ai/core"));
1596
- } catch {
1597
- return process.cwd();
1758
+ }
1759
+ function adjustBrightsyTurnExit(exitCode, assistantText) {
1760
+ if (looksLikeBrightsyEmptyCompletion(assistantText) && (exitCode === 0 || exitCode == null)) {
1761
+ return 2;
1598
1762
  }
1763
+ return exitCode;
1599
1764
  }
1600
- function findSideboardMcpJsEntry() {
1601
- const override = process.env.SIDEBOARD_MCP_ENTRY?.trim() || process.env.SIDEBOARD_CLI?.trim();
1602
- if (override && existsSync6(override)) return override;
1603
- const packaged = packagedMcpStdioPath();
1604
- if (packaged) return packaged;
1605
- let dir = corePackageDir();
1606
- for (let i = 0; i < 10; i++) {
1607
- const candidates = [
1608
- join6(dir, "mcp/run-stdio.js"),
1609
- join6(dir, "mcp/run-stdio.cjs"),
1610
- join6(dir, "dist/mcp/run-stdio.js"),
1611
- join6(dir, "dist/mcp/run-stdio.cjs"),
1612
- join6(dir, "packages/core/dist/mcp/run-stdio.js"),
1613
- join6(dir, "packages/cli/dist/index.js"),
1614
- join6(dir, "cli/dist/index.js")
1615
- ];
1616
- for (const p of candidates) {
1617
- if (existsSync6(p) && !isAsarPath(p)) return p;
1765
+ async function fetchTeamChatTargets(team) {
1766
+ const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
1767
+ let agents = [
1768
+ {
1769
+ type: "agent",
1770
+ id: "default",
1771
+ name: "Default Agent",
1772
+ description: "Account default agent (tools + memory)",
1773
+ accountId: team.id,
1774
+ accountSlug: team.slug,
1775
+ accountName: team.name
1618
1776
  }
1619
- const parent = dirname2(dir);
1620
- if (parent === dir) break;
1621
- dir = parent;
1777
+ ];
1778
+ let models = [];
1779
+ try {
1780
+ const res = await fetch(`${endpoint}/api/v1beta/${team.id}/agents`, {
1781
+ headers: { Authorization: `Bearer ${team.access_token}` }
1782
+ });
1783
+ if (res.ok) {
1784
+ const json = await res.json();
1785
+ const listed = (json.data || []).filter(
1786
+ (a) => Boolean(a?.id && a?.name)
1787
+ ).filter((a) => a.id !== "default").map((a) => ({
1788
+ type: "agent",
1789
+ id: a.id,
1790
+ name: a.name,
1791
+ description: a.description,
1792
+ accountId: team.id,
1793
+ accountSlug: team.slug,
1794
+ accountName: team.name
1795
+ }));
1796
+ agents = [...agents, ...listed];
1797
+ if (Array.isArray(json.models)) {
1798
+ models = json.models.filter(
1799
+ (m) => Boolean(m?.id && m?.name)
1800
+ ).slice(0, 12).map((m) => ({
1801
+ type: "model",
1802
+ id: m.id,
1803
+ name: m.name,
1804
+ description: m.description,
1805
+ accountId: team.id,
1806
+ accountSlug: team.slug,
1807
+ accountName: team.name
1808
+ }));
1809
+ }
1810
+ }
1811
+ } catch {
1622
1812
  }
1623
- return null;
1813
+ return {
1814
+ accountId: team.id,
1815
+ accountSlug: team.slug,
1816
+ accountName: team.name,
1817
+ agents,
1818
+ models
1819
+ };
1624
1820
  }
1625
- async function resolveSideboardMcpServer() {
1626
- const entry = findSideboardMcpJsEntry();
1627
- if (entry) {
1628
- const isCli = /[/\\]cli[/\\]dist[/\\]index\.js$/.test(entry);
1629
- const scriptArgs = isCli ? [entry, "mcp"] : [entry];
1630
- const launch = applyNodeLaunch(await resolveNodeLaunch(entry), scriptArgs);
1631
- if (launch.file !== "/bin/sh" && !isElectronLikeCommand(launch.file)) {
1632
- return {
1633
- name: "sideboard",
1634
- command: launch.file,
1635
- args: launch.args,
1636
- ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {}
1637
- };
1821
+ async function listBrightsyChatTargetsViaCli() {
1822
+ const listed = await run(
1823
+ resolveAgentExecutable("brightsy"),
1824
+ ["chat", "--list-targets", "--json"],
1825
+ {
1826
+ reject: false
1638
1827
  }
1828
+ );
1829
+ if (listed.exitCode !== 0 || !listed.stdout.trim()) {
1830
+ throw new Error(
1831
+ listed.stderr.trim() || "Failed to list Brightsy chat targets \u2014 is `brightsy` installed and logged in?"
1832
+ );
1639
1833
  }
1640
- const which = await run("which", ["sideboard"], { reject: false });
1641
- if (which.exitCode === 0 && which.stdout.trim()) {
1642
- return { name: "sideboard", command: which.stdout.trim(), args: ["mcp"] };
1643
- }
1644
- return { name: "sideboard", command: "sideboard", args: ["mcp"] };
1645
- }
1646
- async function buildInjectedMcpServers(opts) {
1647
- const servers = [];
1648
- if (opts.includeSideboard) {
1649
- const sideboard = await resolveSideboardMcpServer();
1650
- sideboard.env = {
1651
- ...sideboard.env ?? {},
1652
- ...injectedSideboardMcpEnv(opts)
1653
- };
1834
+ try {
1835
+ const parsed = JSON.parse(listed.stdout);
1836
+ let accountId = null;
1837
+ let accountSlug = "team";
1838
+ let accountName = "Brightsy";
1654
1839
  try {
1655
- mergeAgentGitAuthEnv(
1656
- sideboard.env,
1657
- await resolveAgentGitAuthEnv(sideboard.env)
1658
- );
1840
+ const cfg = loadBrightsyConfig();
1841
+ accountId = cfg.account_id;
1842
+ accountSlug = cfg.account_slug || accountSlug;
1843
+ accountName = cfg.account_slug || accountName;
1659
1844
  } catch {
1660
1845
  }
1661
- applyAgentRunnerHeapEnv(sideboard.env);
1662
- servers.push(sideboard);
1663
- }
1664
- if (opts.includeBrightsy && isBrightsyConnected()) {
1665
- const cmd = await resolveBrightsyMcpCommand();
1666
- const teams = await ensureConnectedBrightsyTeamTokens();
1667
- if (teams.length > 0) {
1668
- const used = /* @__PURE__ */ new Set();
1669
- for (const team of teams) {
1670
- let name = brightsyMcpServerName(team.slug);
1671
- if (used.has(name)) name = `${name}_${team.id.slice(0, 8)}`;
1672
- used.add(name);
1673
- servers.push(mcpLaunch(cmd, name, teamEnv(team)));
1846
+ const agents = (Array.isArray(parsed.agents) ? parsed.agents : []).map((a) => ({
1847
+ ...a,
1848
+ accountId: accountId ?? void 0,
1849
+ accountSlug,
1850
+ accountName
1851
+ }));
1852
+ const models = (Array.isArray(parsed.models) ? parsed.models : []).map((m) => ({
1853
+ ...m,
1854
+ accountId: accountId ?? void 0,
1855
+ accountSlug,
1856
+ accountName
1857
+ }));
1858
+ const teams = accountId ? [
1859
+ {
1860
+ accountId,
1861
+ accountSlug,
1862
+ accountName,
1863
+ agents,
1864
+ models
1674
1865
  }
1675
- } else {
1676
- servers.push(mcpLaunch(cmd, "brightsy"));
1677
- }
1866
+ ] : [];
1867
+ return { teams, agents, models, activeAccountId: accountId };
1868
+ } catch {
1869
+ throw new Error("Brightsy --list-targets returned invalid JSON");
1678
1870
  }
1679
- return servers;
1680
1871
  }
1681
- function cursorSafeMcpLaunch(command, args) {
1682
- if (process.platform === "win32") {
1683
- return args && args.length > 0 ? { command, args } : { command };
1872
+ async function listBrightsyChatTargets() {
1873
+ ensureCliTeamTracked();
1874
+ const teamsRaw = await ensureConnectedBrightsyTeamTokens();
1875
+ if (teamsRaw.length === 0) {
1876
+ return listBrightsyChatTargetsViaCli();
1684
1877
  }
1685
- const unwrapped = unwrapStrippedElectronLaunch(command, args);
1686
- const file = unwrapped?.file ?? command;
1687
- const fileArgs = unwrapped?.args ?? args ?? [];
1688
- return fileArgs.length > 0 ? { command: file, args: fileArgs } : { command: file };
1689
- }
1690
- function mcpSpawnEnv(env) {
1691
- if (!env) return void 0;
1692
- const out = { ...env };
1693
- delete out.ELECTRON_RUN_AS_NODE;
1694
- delete out.ELECTRON_RUN_AS_NODE;
1695
- return Object.keys(out).length > 0 ? out : void 0;
1696
- }
1697
- function toCursorMcpServers(servers) {
1698
- const out = {};
1699
- for (const s of servers) {
1700
- const env = mcpSpawnEnv(s.env);
1701
- const launch = cursorSafeMcpLaunch(s.command, s.args);
1702
- out[s.name] = {
1703
- type: "stdio",
1704
- command: launch.command,
1705
- ...launch.args && launch.args.length > 0 ? { args: launch.args } : {},
1706
- ...env ? { env } : {}
1707
- };
1878
+ let activeAccountId = null;
1879
+ try {
1880
+ activeAccountId = loadBrightsyConfig().account_id;
1881
+ } catch {
1882
+ activeAccountId = teamsRaw[0]?.id ?? null;
1708
1883
  }
1709
- return out;
1884
+ const teams = await Promise.all(teamsRaw.map((t) => fetchTeamChatTargets(t)));
1885
+ teams.sort((a, b) => {
1886
+ if (a.accountId === activeAccountId) return -1;
1887
+ if (b.accountId === activeAccountId) return 1;
1888
+ return a.accountSlug.localeCompare(b.accountSlug);
1889
+ });
1890
+ const active = teams.find((t) => t.accountId === activeAccountId) ?? teams[0] ?? null;
1891
+ return {
1892
+ teams,
1893
+ agents: active?.agents ?? [],
1894
+ models: active?.models ?? [],
1895
+ activeAccountId
1896
+ };
1710
1897
  }
1711
- function toCodexMcpConfigArgs(servers) {
1712
- const args = [];
1713
- for (const s of servers) {
1714
- const prefix = `mcp_servers.${s.name}`;
1715
- args.push("-c", `${prefix}.command=${JSON.stringify(s.command)}`);
1716
- if (s.args?.length) {
1717
- args.push("-c", `${prefix}.args=${JSON.stringify(s.args)}`);
1718
- }
1719
- const env = mcpSpawnEnv(s.env);
1720
- if (env) {
1721
- for (const [key, value] of Object.entries(env)) {
1722
- if (isCodexSecretEnvKey(key)) continue;
1723
- args.push("-c", `${prefix}.env.${key}=${JSON.stringify(value)}`);
1724
- }
1898
+ async function syncCliForTarget(accountId) {
1899
+ if (!accountId) return;
1900
+ const teams = await ensureConnectedBrightsyTeamTokens();
1901
+ const team = teams.find((t) => t.id === accountId);
1902
+ if (!team) return;
1903
+ try {
1904
+ const cfg = loadBrightsyConfig();
1905
+ if (cfg.account_id === team.id && cfg.access_token === team.access_token) {
1906
+ return;
1725
1907
  }
1726
- args.push("-c", `${prefix}.default_tools_approval_mode=${JSON.stringify("approve")}`);
1727
- args.push("-c", `${prefix}.tool_timeout_sec=300`);
1728
- args.push("-c", `${prefix}.startup_timeout_sec=30`);
1908
+ } catch {
1729
1909
  }
1730
- return args;
1910
+ applyConnectedTeamToCli(team);
1731
1911
  }
1732
- function toOpencodeMcpConfigContent(servers, opts) {
1733
- const mcp = {};
1734
- for (const s of servers) {
1735
- const env = mcpSpawnEnv(s.env);
1736
- mcp[s.name] = {
1737
- type: "local",
1738
- command: [s.command, ...s.args ?? []],
1739
- enabled: true,
1740
- ...env ? { environment: env } : {}
1912
+ var brightsyAdapter = {
1913
+ kind: "brightsy",
1914
+ async detect() {
1915
+ const brightsy = resolveAgentExecutable("brightsy");
1916
+ if (brightsy !== "brightsy") {
1917
+ if (!existsSync9(brightsy)) {
1918
+ return {
1919
+ agent: "brightsy",
1920
+ installed: false,
1921
+ authenticated: false,
1922
+ linearMcp: false,
1923
+ warnings: [],
1924
+ reason: `Brightsy executable not found: ${brightsy}`
1925
+ };
1926
+ }
1927
+ } else {
1928
+ const which = await run("which", ["brightsy"], { reject: false });
1929
+ if (which.exitCode !== 0) {
1930
+ return {
1931
+ agent: "brightsy",
1932
+ installed: false,
1933
+ authenticated: false,
1934
+ linearMcp: false,
1935
+ warnings: [],
1936
+ reason: "brightsy CLI not found on PATH \u2014 npm i -g @brightsy/cli"
1937
+ };
1938
+ }
1939
+ }
1940
+ const who = await run(brightsy, ["whoami"], { reject: false });
1941
+ const authenticated = who.exitCode === 0 && /logged in as/i.test(who.stdout);
1942
+ return {
1943
+ agent: "brightsy",
1944
+ installed: true,
1945
+ authenticated,
1946
+ linearMcp: false,
1947
+ warnings: [],
1948
+ reason: authenticated ? void 0 : "not logged in \u2014 run `brightsy login`"
1741
1949
  };
1742
- }
1743
- for (const name of opts?.disableNames ?? []) {
1744
- const key = name.trim();
1745
- if (!key || mcp[key]?.enabled === true) continue;
1746
- mcp[key] = { ...mcp[key], enabled: false };
1747
- }
1748
- return JSON.stringify({ mcp });
1749
- }
1750
- function stripElectronFromUserMcpEntry(entry) {
1751
- const next = { ...entry };
1752
- const env = next.env;
1753
- if (!env || typeof env !== "object" || Array.isArray(env)) return next;
1754
- const cleaned = { ...env };
1755
- delete cleaned.ELECTRON_RUN_AS_NODE;
1756
- next.env = cleaned;
1757
- return next;
1758
- }
1759
- function mcpServersRecord(servers, extraServers) {
1760
- const mcpServers = {};
1761
- for (const s of servers) {
1762
- const env = mcpSpawnEnv(s.env);
1763
- mcpServers[s.name] = {
1764
- command: s.command,
1765
- ...s.args ? { args: s.args } : {},
1766
- ...env ? { env } : {}
1950
+ },
1951
+ async buildTurn(thread, input) {
1952
+ const prompt = flattenTurnInput(input);
1953
+ const target = decodeBrightsyTarget(thread.model);
1954
+ await syncCliForTarget(target.accountId);
1955
+ const mode = thread.planMode ? "plan" : target.type === "model" ? "ask" : "agent";
1956
+ const args = [
1957
+ "chat",
1958
+ "--json",
1959
+ "--mode",
1960
+ mode,
1961
+ target.type === "model" ? "--model" : "--agent",
1962
+ target.id
1963
+ ];
1964
+ return {
1965
+ file: resolveAgentExecutable("brightsy"),
1966
+ args,
1967
+ cwd: thread.worktreePath,
1968
+ // Piped stdin becomes the message body (avoids ARG_MAX for long seeds).
1969
+ stdin: prompt
1970
+ };
1971
+ },
1972
+ parseEvent(line) {
1973
+ return parseBrightsyCliLine(line);
1974
+ },
1975
+ async resolveSessionId() {
1976
+ return null;
1977
+ },
1978
+ async buildAttach(thread) {
1979
+ const target = decodeBrightsyTarget(thread.model);
1980
+ await syncCliForTarget(target.accountId);
1981
+ const args = target.type === "model" ? ["chat", "--model", target.id] : ["chat", "--agent", target.id];
1982
+ return {
1983
+ file: resolveAgentExecutable("brightsy"),
1984
+ args,
1985
+ cwd: thread.worktreePath
1767
1986
  };
1768
1987
  }
1769
- if (extraServers) {
1770
- for (const [rawName, entry] of Object.entries(extraServers)) {
1771
- const name = rawName.trim();
1772
- if (!name || mcpServers[name] || !entry) continue;
1773
- mcpServers[name] = stripElectronFromUserMcpEntry(entry);
1988
+ };
1989
+
1990
+ // src/agents/claude.ts
1991
+ import { existsSync as existsSync13 } from "fs";
1992
+ import { dirname as dirname6 } from "path";
1993
+
1994
+ // src/agents/claude-mcp-status.ts
1995
+ var SIDEBOARD_CONNECTOR_SERVICES = [
1996
+ "github",
1997
+ "linear",
1998
+ "posthog",
1999
+ "vercel",
2000
+ "supabase",
2001
+ "sentry"
2002
+ ];
2003
+ function mcpStatusThinkingFromClaudeInit(obj) {
2004
+ const raw = obj.mcp_servers ?? obj.mcpServers;
2005
+ const servers = [];
2006
+ if (Array.isArray(raw)) {
2007
+ for (const item of raw) {
2008
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
2009
+ const rec = item;
2010
+ const name = typeof rec.name === "string" && rec.name.trim() || typeof rec.server === "string" && rec.server.trim() || "";
2011
+ const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "";
2012
+ if (name) servers.push({ name, status: status || "unknown" });
2013
+ }
2014
+ } else if (raw && typeof raw === "object") {
2015
+ for (const [name, value] of Object.entries(raw)) {
2016
+ if (!name.trim()) continue;
2017
+ if (typeof value === "string" && value.trim()) {
2018
+ servers.push({ name, status: value.trim() });
2019
+ continue;
2020
+ }
2021
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2022
+ const rec = value;
2023
+ const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "unknown";
2024
+ servers.push({ name, status });
2025
+ }
1774
2026
  }
1775
2027
  }
1776
- return mcpServers;
2028
+ const coverage = claudeConnectorCoverage();
2029
+ const sideboardOk = sideboardMcpOk(servers);
2030
+ const notable = servers.filter(
2031
+ (server) => isNotableMcpInitStatus(server, sideboardOk, coverage)
2032
+ );
2033
+ if (notable.length === 0) return null;
2034
+ return `MCP: ${notable.map((s) => `${s.name} ${s.status}`).join(", ")}`;
1777
2035
  }
1778
- function writeMcpServersConfig(servers, extraServers) {
1779
- const mcpServers = mcpServersRecord(servers, extraServers);
1780
- if (Object.keys(mcpServers).length === 0) return null;
1781
- const dir = mkdtempSync(join6(tmpdir(), "sideboard-mcp-"));
1782
- const cfgPath = join6(dir, "mcp.json");
1783
- writeFileSync3(cfgPath, JSON.stringify({ mcpServers }, null, 2), { mode: 384 });
1784
- return cfgPath;
2036
+ function isCleanMcpConnect(status) {
2037
+ return /^(connected|ok|ready|success)$/i.test(status.trim());
1785
2038
  }
1786
-
1787
- // src/agents/user-mcp-config.ts
1788
- function userClaudeMcpConfigPath() {
1789
- return join7(homedir4(), ".claude.json");
2039
+ function isMcpAuthStatus(status) {
2040
+ return /needs[_-]?auth|needs authentication|unauthorized|not authenticated|authrequired/i.test(
2041
+ status
2042
+ );
1790
2043
  }
1791
-
1792
- // src/agents/orch-mcp-isolation.ts
1793
- function isInjectedOrchMcpName(name) {
1794
- const n = name.trim().toLowerCase();
1795
- return n === "sideboard" || n === "brightsy" || n.startsWith("brightsy_");
2044
+ function isSideboardMcpName(name) {
2045
+ return /^sideboard$/i.test(name.trim()) || /^mcp__sideboard$/i.test(name.trim());
1796
2046
  }
1797
- function asObject(value) {
1798
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1799
- return value;
2047
+ function isVendorClaudeAiMcpName(name) {
2048
+ return /^claude\.ai\b/i.test(name.trim()) || /^mcp__claude_ai_/i.test(name.trim());
1800
2049
  }
1801
- function listMcpNamesFromJsonMap(raw, key) {
1802
- return Object.keys(asObject(asObject(raw)[key])).filter((n) => n.trim());
2050
+ function sideboardMcpOk(servers) {
2051
+ const row = servers.find((server) => isSideboardMcpName(server.name));
2052
+ return Boolean(row && isCleanMcpConnect(row.status));
1803
2053
  }
1804
- function listMcpNamesFromCodexToml(text) {
1805
- try {
1806
- const parsed = parseToml(text);
1807
- return Object.keys(asObject(parsed.mcp_servers)).filter((n) => n.trim());
1808
- } catch {
1809
- return [];
2054
+ function sideboardServiceForClaudeConnector(name) {
2055
+ const raw = name.trim();
2056
+ if (!raw || isSideboardMcpName(raw)) return null;
2057
+ const pluginLike = /^(?:plugin[:_]|mcp__plugin_|claude\.ai\s|(?:mcp__)?claude_ai_)/i.test(raw);
2058
+ const doubled = raw.match(/^mcp_([a-z0-9]+)_([a-z0-9]+)$/i);
2059
+ if (!pluginLike && !(doubled && doubled[1].toLowerCase() === doubled[2].toLowerCase())) {
2060
+ return null;
1810
2061
  }
2062
+ let body = raw;
2063
+ if (/^claude\.ai\s+/i.test(body)) body = body.replace(/^claude\.ai\s+/i, "");
2064
+ else if (/^(?:mcp__)?claude_ai_/i.test(body)) body = body.replace(/^(?:mcp__)?claude_ai_/i, "");
2065
+ else if (/^mcp__plugin_/i.test(body)) body = body.slice("mcp__plugin_".length);
2066
+ else if (/^plugin_/i.test(body)) body = body.slice("plugin_".length);
2067
+ else if (/^plugin:/i.test(body)) body = body.slice("plugin:".length);
2068
+ else if (/^mcp_/i.test(body)) body = body.slice("mcp_".length);
2069
+ const head = body.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
2070
+ if (!head || !SIDEBOARD_CONNECTOR_SERVICES.includes(head)) return null;
2071
+ return head;
1811
2072
  }
1812
- function readJsonObject(path) {
2073
+ function claudeConnectorCoverage() {
2074
+ let github = false;
1813
2075
  try {
1814
- return JSON.parse(readFileSync4(path, "utf8"));
2076
+ github = githubAgentAuthReady();
1815
2077
  } catch {
1816
- return {};
2078
+ github = false;
1817
2079
  }
1818
- }
1819
- function readText(path) {
2080
+ let linear = false;
2081
+ let posthog = false;
2082
+ let vercel = false;
2083
+ let supabase = false;
2084
+ let sentry = false;
1820
2085
  try {
1821
- return readFileSync4(path, "utf8");
2086
+ linear = isLinearConnected();
2087
+ posthog = isPosthogConnected();
2088
+ const integrations = loadAppSettings().integrations ?? {};
2089
+ if (integrations.githubPat?.trim()) github = true;
2090
+ vercel = Boolean(integrations.vercelToken?.trim());
2091
+ supabase = Boolean(integrations.supabaseAccessToken?.trim());
2092
+ sentry = Boolean(integrations.sentryAuthToken?.trim());
1822
2093
  } catch {
1823
- return "";
1824
- }
1825
- }
1826
- function userCodexConfigPaths(home = homedir5()) {
1827
- const paths = [
1828
- join8(home, ".codex", "config.toml"),
1829
- join8(home, ".config", "codex", "config.toml")
1830
- ];
1831
- const codexHome = process.env.CODEX_HOME?.trim();
1832
- if (codexHome) paths.unshift(join8(codexHome, "config.toml"));
1833
- return paths;
1834
- }
1835
- function userOpencodeConfigPaths(home = homedir5()) {
1836
- return [
1837
- join8(home, ".config", "opencode", "opencode.json"),
1838
- join8(home, ".config", "opencode", "opencode.jsonc")
1839
- ];
1840
- }
1841
- function userMcpNamesToDisable(opts) {
1842
- const keep = new Set(
1843
- [...opts.injectedNames ?? []].map((n) => n.trim().toLowerCase()).filter(Boolean)
1844
- );
1845
- const out = [];
1846
- const seen = /* @__PURE__ */ new Set();
1847
- for (const raw of opts.names) {
1848
- const name = raw.trim();
1849
- if (!name) continue;
1850
- const key = name.toLowerCase();
1851
- if (seen.has(key) || keep.has(key) || isInjectedOrchMcpName(name)) continue;
1852
- seen.add(key);
1853
- out.push(name);
1854
- }
1855
- return out;
1856
- }
1857
- function listUserCodexMcpNames(home = homedir5()) {
1858
- const names = [];
1859
- for (const path of userCodexConfigPaths(home)) {
1860
- if (!existsSync8(path)) continue;
1861
- names.push(...listMcpNamesFromCodexToml(readText(path)));
1862
- }
1863
- return names;
1864
- }
1865
- function listUserOpencodeMcpNames(home = homedir5()) {
1866
- const names = [];
1867
- for (const path of userOpencodeConfigPaths(home)) {
1868
- if (!existsSync8(path)) continue;
1869
- names.push(...listMcpNamesFromJsonMap(readJsonObject(path), "mcp"));
1870
- }
1871
- return names;
1872
- }
1873
- function userClaudeMcpConfigObject(home = homedir5()) {
1874
- const claudePath = home === homedir5() ? userClaudeMcpConfigPath() : join8(home, ".claude.json");
1875
- if (!existsSync8(claudePath)) return {};
1876
- return asObject(asObject(readJsonObject(claudePath)).mcpServers);
1877
- }
1878
- function listUserClaudeMcpServerEntries(home = homedir5(), projectDirs) {
1879
- const out = {};
1880
- for (const [name, entry] of Object.entries(
1881
- listEnabledClaudePluginMcpServers({ home, projectDirs })
1882
- )) {
1883
- if (!name || isInjectedOrchMcpName(name)) continue;
1884
- out[name] = entry;
1885
- }
1886
- for (const [rawName, value] of Object.entries(userClaudeMcpConfigObject(home))) {
1887
- const name = rawName.trim();
1888
- if (!name || isInjectedOrchMcpName(name)) continue;
1889
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1890
- out[name] = value;
1891
- }
1892
- return out;
1893
- }
1894
- function toCodexDisableUserMcpArgs(names) {
1895
- const args = [];
1896
- for (const name of names) {
1897
- if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
1898
- args.push("-c", `mcp_servers.${name}.enabled=false`);
1899
2094
  }
1900
- return args;
2095
+ return { github, linear, posthog, vercel, supabase, sentry };
1901
2096
  }
1902
- function toCodexUnattendedAppsArgs() {
1903
- return [
1904
- "-c",
1905
- "features.apps=false",
1906
- "-c",
1907
- "apps._default.enabled=false",
1908
- "-c",
1909
- "apps.posthog.enabled=false",
1910
- "-c",
1911
- "features.plugins=false"
1912
- ];
2097
+ function isNotableMcpInitStatus(server, sideboardOk, coverage) {
2098
+ if (isCleanMcpConnect(server.status)) return false;
2099
+ if (isSideboardMcpName(server.name)) return true;
2100
+ if (isMcpAuthStatus(server.status)) return false;
2101
+ const service = sideboardServiceForClaudeConnector(server.name);
2102
+ if (service) return !(sideboardOk && coverage[service]);
2103
+ if (isVendorClaudeAiMcpName(server.name)) return false;
2104
+ return true;
1913
2105
  }
1914
2106
 
2107
+ // src/mcp-ui/host.ts
2108
+ import { createHash } from "crypto";
2109
+ import { homedir as homedir7 } from "os";
2110
+
1915
2111
  // src/mcp-ui/proxy-http.ts
1916
2112
  import { randomBytes as randomBytes2, randomUUID } from "crypto";
1917
2113
  import { createServer } from "http";
@@ -2383,7 +2579,7 @@ var singleton;
2383
2579
  function getMcpUiHost() {
2384
2580
  if (!singleton) {
2385
2581
  singleton = new McpUiHost({
2386
- entries: (projectDirs) => listUserClaudeMcpServerEntries(homedir6(), projectDirs)
2582
+ entries: (projectDirs) => listUserClaudeMcpServerEntries(homedir7(), projectDirs)
2387
2583
  });
2388
2584
  }
2389
2585
  return singleton;
@@ -2391,7 +2587,7 @@ function getMcpUiHost() {
2391
2587
  async function proxyClaudeUserMcp(orchestrator, projectDirs) {
2392
2588
  if (orchestrator) return {};
2393
2589
  const dirs = projectDirs.filter((d) => typeof d === "string" && d.length > 0);
2394
- return getMcpUiHost().proxyEntries(listUserClaudeMcpServerEntries(homedir6(), dirs), dirs);
2590
+ return getMcpUiHost().proxyEntries(listUserClaudeMcpServerEntries(homedir7(), dirs), dirs);
2395
2591
  }
2396
2592
  function dirsKeyFor(projectDirs) {
2397
2593
  if (!projectDirs?.length) return "";
@@ -2399,9 +2595,9 @@ function dirsKeyFor(projectDirs) {
2399
2595
  }
2400
2596
 
2401
2597
  // src/agents/claude-usage-client.ts
2402
- import { existsSync as existsSync9, readFileSync as readFileSync5 } from "fs";
2403
- import { homedir as homedir7 } from "os";
2404
- import { join as join9 } from "path";
2598
+ import { existsSync as existsSync10, readFileSync as readFileSync5 } from "fs";
2599
+ import { homedir as homedir8 } from "os";
2600
+ import { join as join10 } from "path";
2405
2601
 
2406
2602
  // src/agents/claude-usage.ts
2407
2603
  var WINDOW_META = {
@@ -2659,12 +2855,12 @@ function accessTokenFromCredentialsJson(raw) {
2659
2855
  }
2660
2856
  }
2661
2857
  function claudeCredentialsPath(configDir) {
2662
- const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir7(), ".claude");
2663
- return join9(root, ".credentials.json");
2858
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir8(), ".claude");
2859
+ return join10(root, ".credentials.json");
2664
2860
  }
2665
2861
  async function readFileAccessToken(configDir) {
2666
2862
  const path = claudeCredentialsPath(configDir);
2667
- if (!existsSync9(path)) return null;
2863
+ if (!existsSync10(path)) return null;
2668
2864
  try {
2669
2865
  return accessTokenFromCredentialsJson(readFileSync5(path, "utf8"));
2670
2866
  } catch {
@@ -2903,10 +3099,10 @@ function permissionMode(thread) {
2903
3099
  }
2904
3100
 
2905
3101
  // src/agent-rpc/metadata.ts
2906
- import { existsSync as existsSync10, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync5 } from "fs";
2907
- import { join as join10 } from "path";
3102
+ import { existsSync as existsSync11, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync5 } from "fs";
3103
+ import { join as join11 } from "path";
2908
3104
  function agentRuntimeMetadataPath() {
2909
- return join10(appDataDir(), "agent-runtime.json");
3105
+ return join11(appDataDir(), "agent-runtime.json");
2910
3106
  }
2911
3107
  function readAgentRuntimeMetadata() {
2912
3108
  try {
@@ -2973,10 +3169,10 @@ function agentRpcChildEnv(rpc, cwd) {
2973
3169
  }
2974
3170
 
2975
3171
  // src/agents/claude-host.ts
2976
- import { existsSync as existsSync11 } from "fs";
2977
- import { createRequire as createRequire2 } from "module";
2978
- import { dirname as dirname4, join as join11 } from "path";
2979
- import { fileURLToPath as fileURLToPath2 } from "url";
3172
+ import { existsSync as existsSync12 } from "fs";
3173
+ import { createRequire as createRequire3 } from "module";
3174
+ import { dirname as dirname5, join as join12 } from "path";
3175
+ import { fileURLToPath as fileURLToPath3 } from "url";
2980
3176
 
2981
3177
  // src/agent-rpc/client.ts
2982
3178
  import { WebSocket } from "ws";
@@ -3003,15 +3199,15 @@ function withClaudePilotRpcTools(allowed) {
3003
3199
  const omit = new Set(PILOT_TOOL_NAMES.map((name) => `mcp__sideboard__${name}`));
3004
3200
  return [...allowed.filter((name) => !omit.has(name)), ...claudePilotSdkAllowedTools()];
3005
3201
  }
3006
- function entryDir() {
3202
+ function entryDir2() {
3007
3203
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
3008
3204
  if (cjsDir) return cjsDir;
3009
3205
  try {
3010
- return dirname4(fileURLToPath2(import.meta.url));
3206
+ return dirname5(fileURLToPath3(import.meta.url));
3011
3207
  } catch {
3012
3208
  try {
3013
- const req = createRequire2(process.cwd() + "/");
3014
- return dirname4(req.resolve("@sideboard-ai/core"));
3209
+ const req = createRequire3(process.cwd() + "/");
3210
+ return dirname5(req.resolve("@sideboard-ai/core"));
3015
3211
  } catch {
3016
3212
  return process.cwd();
3017
3213
  }
@@ -3020,20 +3216,20 @@ function entryDir() {
3020
3216
  function claudeRunnerPath() {
3021
3217
  const packagedDir = packagedCursorRuntimeDir();
3022
3218
  if (packagedDir) {
3023
- const packaged = join11(packagedDir, "core-dist", "agents", "claude-runner.js");
3024
- if (existsSync11(packaged)) return packaged;
3219
+ const packaged = join12(packagedDir, "core-dist", "agents", "claude-runner.js");
3220
+ if (existsSync12(packaged)) return packaged;
3025
3221
  }
3026
- const root = entryDir();
3222
+ const root = entryDir2();
3027
3223
  const candidates = [
3028
- join11(root, "agents", "claude-runner.js"),
3029
- join11(root, "agents", "claude-runner.cjs"),
3030
- join11(root, "dist", "agents", "claude-runner.js"),
3031
- join11(root, "dist", "agents", "claude-runner.cjs"),
3032
- join11(root, "claude-runner.ts"),
3033
- join11(root, "src", "agents", "claude-runner.ts")
3224
+ join12(root, "agents", "claude-runner.js"),
3225
+ join12(root, "agents", "claude-runner.cjs"),
3226
+ join12(root, "dist", "agents", "claude-runner.js"),
3227
+ join12(root, "dist", "agents", "claude-runner.cjs"),
3228
+ join12(root, "claude-runner.ts"),
3229
+ join12(root, "src", "agents", "claude-runner.ts")
3034
3230
  ];
3035
3231
  for (const candidate of candidates) {
3036
- if (existsSync11(candidate)) return candidate;
3232
+ if (existsSync12(candidate)) return candidate;
3037
3233
  }
3038
3234
  return candidates[0];
3039
3235
  }
@@ -3389,7 +3585,7 @@ var claudeAdapter = {
3389
3585
  async detect() {
3390
3586
  const claude = resolveClaudeExecutable();
3391
3587
  if (claude !== "claude") {
3392
- if (!existsSync12(claude)) {
3588
+ if (!existsSync13(claude)) {
3393
3589
  return {
3394
3590
  agent: "claude",
3395
3591
  installed: false,
@@ -3438,7 +3634,7 @@ var claudeAdapter = {
3438
3634
  );
3439
3635
  }
3440
3636
  const mode = permissionMode(thread);
3441
- const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-7OQ5O6JT.js");
3637
+ const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-TG2TVLUF.js");
3442
3638
  const isOrchestrator = isOrchestratorThread2(thread);
3443
3639
  const rpc = worktreeAgentRpc(isOrchestrator);
3444
3640
  const injectedServers = await buildInjectedMcpServers({
@@ -3547,7 +3743,7 @@ ${hint}` : hint;
3547
3743
  cwd: thread.worktreePath,
3548
3744
  stdin: useStdin ? `${promptText}
3549
3745
  ` : void 0,
3550
- ...mcpConfigPath ? { cleanupDirs: [dirname5(mcpConfigPath)] } : {},
3746
+ ...mcpConfigPath ? { cleanupDirs: [dirname6(mcpConfigPath)] } : {},
3551
3747
  // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
3552
3748
  // Raise the -p background-agent wait so long TaskOutput polls are not
3553
3749
  // abandoned at Claude Code’s 10-minute default.
@@ -3675,15 +3871,15 @@ ${hint}` : hint;
3675
3871
  return { file: claude, args, cwd: thread.worktreePath };
3676
3872
  },
3677
3873
  async listLinearIssues(_repoPath) {
3678
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-JPQ27RXG.js");
3874
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-OINZWVV5.js");
3679
3875
  return listAssignedLinearIssues2();
3680
3876
  }
3681
3877
  };
3682
3878
 
3683
3879
  // src/agents/codex.ts
3684
- import { existsSync as existsSync13, statSync as statSync2 } from "fs";
3685
- import { homedir as homedir8 } from "os";
3686
- import { join as join12 } from "path";
3880
+ import { existsSync as existsSync14, statSync as statSync2 } from "fs";
3881
+ import { homedir as homedir9 } from "os";
3882
+ import { join as join13 } from "path";
3687
3883
 
3688
3884
  // src/agents/codex-items.ts
3689
3885
  function eventsFromCodexItem(eventType, item) {
@@ -3735,7 +3931,7 @@ async function listCodexModels() {
3735
3931
  if (codex === "codex") {
3736
3932
  const which = await run("which", ["codex"], { reject: false });
3737
3933
  if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
3738
- } else if (!existsSync13(codex)) {
3934
+ } else if (!existsSync14(codex)) {
3739
3935
  return FALLBACK_CODEX_MODELS;
3740
3936
  }
3741
3937
  const listed = await run(codex, ["debug", "models"], { reject: false });
@@ -3772,7 +3968,7 @@ function usageFromCodex(usage, asContext = false) {
3772
3968
  return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
3773
3969
  }
3774
3970
  function codexHomeDir() {
3775
- return process.env.CODEX_HOME?.trim() || join12(homedir8(), ".codex");
3971
+ return process.env.CODEX_HOME?.trim() || join13(homedir9(), ".codex");
3776
3972
  }
3777
3973
  function unwrapCodexMcpResult(result) {
3778
3974
  if (result == null) return void 0;
@@ -3801,8 +3997,8 @@ function asRecord4(value) {
3801
3997
  return void 0;
3802
3998
  }
3803
3999
  function codexLooksAuthenticated() {
3804
- const authPath = join12(codexHomeDir(), "auth.json");
3805
- if (!existsSync13(authPath)) return false;
4000
+ const authPath = join13(codexHomeDir(), "auth.json");
4001
+ if (!existsSync14(authPath)) return false;
3806
4002
  try {
3807
4003
  return statSync2(authPath).size > 2;
3808
4004
  } catch {
@@ -3814,7 +4010,7 @@ var codexAdapter = {
3814
4010
  async detect() {
3815
4011
  const codex = resolveAgentExecutable("codex");
3816
4012
  if (codex !== "codex") {
3817
- if (!existsSync13(codex)) {
4013
+ if (!existsSync14(codex)) {
3818
4014
  return {
3819
4015
  agent: "codex",
3820
4016
  installed: false,
@@ -3846,7 +4042,7 @@ var codexAdapter = {
3846
4042
  authenticated,
3847
4043
  linearMcp,
3848
4044
  warnings,
3849
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join12(codexHomeDir(), "auth.json")})`
4045
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join13(codexHomeDir(), "auth.json")})`
3850
4046
  };
3851
4047
  },
3852
4048
  async buildTurn(thread, input) {
@@ -4074,40 +4270,40 @@ var codexAdapter = {
4074
4270
  };
4075
4271
 
4076
4272
  // src/agents/cursor.ts
4077
- import { existsSync as existsSync16 } from "fs";
4078
- import { createRequire as createRequire5 } from "module";
4079
- import { dirname as dirname8, join as join15 } from "path";
4080
- import { fileURLToPath as fileURLToPath4 } from "url";
4273
+ import { existsSync as existsSync17 } from "fs";
4274
+ import { createRequire as createRequire6 } from "module";
4275
+ import { dirname as dirname9, join as join16 } from "path";
4276
+ import { fileURLToPath as fileURLToPath5 } from "url";
4081
4277
 
4082
4278
  // src/agents/cursor-sdk-resolve.ts
4083
- import { existsSync as existsSync14, readFileSync as readFileSync7 } from "fs";
4084
- import { createRequire as createRequire3 } from "module";
4085
- import { basename, dirname as dirname6, join as join13 } from "path";
4086
- import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
4279
+ import { existsSync as existsSync15, readFileSync as readFileSync7 } from "fs";
4280
+ import { createRequire as createRequire4 } from "module";
4281
+ import { basename, dirname as dirname7, join as join14 } from "path";
4282
+ import { fileURLToPath as fileURLToPath4, pathToFileURL } from "url";
4087
4283
  var CURSOR_SDK_INSTALL_HINT = "Cursor SDK is not installed. Settings \u2192 Agents \u2192 Cursor \u2192 Install (`npm i -g @cursor/sdk`). Sideboard does not ship the SDK \u2014 update it anytime without a new Sideboard build.";
4088
4284
  function thisModuleFile() {
4089
4285
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
4090
- if (cjsDir) return join13(cjsDir, "cursor-sdk-resolve.js");
4286
+ if (cjsDir) return join14(cjsDir, "cursor-sdk-resolve.js");
4091
4287
  try {
4092
- return fileURLToPath3(import.meta.url);
4288
+ return fileURLToPath4(import.meta.url);
4093
4289
  } catch {
4094
- return join13(process.cwd(), "package.json");
4290
+ return join14(process.cwd(), "package.json");
4095
4291
  }
4096
4292
  }
4097
4293
  function packageRootLooksLikeSdk(dir) {
4098
4294
  try {
4099
- const raw = readFileSync7(join13(dir, "package.json"), "utf8");
4295
+ const raw = readFileSync7(join14(dir, "package.json"), "utf8");
4100
4296
  const pkg = JSON.parse(raw);
4101
- return pkg.name === "@cursor/sdk" && existsSync14(dir);
4297
+ return pkg.name === "@cursor/sdk" && existsSync15(dir);
4102
4298
  } catch {
4103
4299
  return false;
4104
4300
  }
4105
4301
  }
4106
4302
  function resolvedPackageRoot(fromFile) {
4107
4303
  try {
4108
- const req = createRequire3(fromFile);
4304
+ const req = createRequire4(fromFile);
4109
4305
  const pkgJson = req.resolve("@cursor/sdk/package.json");
4110
- const root = dirname6(pkgJson);
4306
+ const root = dirname7(pkgJson);
4111
4307
  return packageRootLooksLikeSdk(root) ? root : null;
4112
4308
  } catch {
4113
4309
  return null;
@@ -4121,10 +4317,10 @@ function resolveCursorSdkRoot(opts) {
4121
4317
  }
4122
4318
  const globalNm = npmGlobalNodeModules(env);
4123
4319
  if (globalNm) {
4124
- const globalRoot = join13(globalNm, "@cursor/sdk");
4320
+ const globalRoot = join14(globalNm, "@cursor/sdk");
4125
4321
  if (packageRootLooksLikeSdk(globalRoot)) return globalRoot;
4126
4322
  }
4127
- const cwdPkg = join13(process.cwd(), "package.json");
4323
+ const cwdPkg = join14(process.cwd(), "package.json");
4128
4324
  return resolvedPackageRoot(thisModuleFile()) ?? resolvedPackageRoot(cwdPkg);
4129
4325
  }
4130
4326
  function isCursorSdkInstalled(opts) {
@@ -4140,13 +4336,13 @@ function exportTarget(value) {
4140
4336
  }
4141
4337
  function cursorSdkEsmEntry(root) {
4142
4338
  try {
4143
- const pkg = JSON.parse(readFileSync7(join13(root, "package.json"), "utf8"));
4339
+ const pkg = JSON.parse(readFileSync7(join14(root, "package.json"), "utf8"));
4144
4340
  const exp = pkg.exports;
4145
4341
  const dot = exp && typeof exp === "object" && !Array.isArray(exp) && "." in exp ? exp["."] : exp;
4146
4342
  const rel = exportTarget(dot) ?? (typeof pkg.module === "string" ? pkg.module : null);
4147
4343
  if (!rel) return null;
4148
- const entry = join13(root, rel);
4149
- return existsSync14(entry) ? entry : null;
4344
+ const entry = join14(root, rel);
4345
+ return existsSync15(entry) ? entry : null;
4150
4346
  } catch {
4151
4347
  return null;
4152
4348
  }
@@ -4162,7 +4358,7 @@ async function importCursorSdk(opts) {
4162
4358
  try {
4163
4359
  let entry = cursorSdkEsmEntry(root);
4164
4360
  if (!entry) {
4165
- const req = createRequire3(join13(root, "package.json"));
4361
+ const req = createRequire4(join14(root, "package.json"));
4166
4362
  entry = req.resolve("@cursor/sdk");
4167
4363
  }
4168
4364
  return unwrapCursorSdkModule(await import(pathToFileURL(entry).href));
@@ -4174,8 +4370,8 @@ function cursorSdkPlatformRipgrepPackage() {
4174
4370
  return `@cursor/sdk-${process.platform}-${process.arch}`;
4175
4371
  }
4176
4372
  function nodeModulesDirForPackageRoot(packageRoot) {
4177
- const parent = dirname6(packageRoot);
4178
- return basename(parent).startsWith("@") ? dirname6(parent) : parent;
4373
+ const parent = dirname7(packageRoot);
4374
+ return basename(parent).startsWith("@") ? dirname7(parent) : parent;
4179
4375
  }
4180
4376
  function cursorSdkRipgrepCandidate(opts) {
4181
4377
  const root = resolveCursorSdkRoot(opts);
@@ -4183,10 +4379,10 @@ function cursorSdkRipgrepCandidate(opts) {
4183
4379
  const nm = nodeModulesDirForPackageRoot(root);
4184
4380
  const pkg = cursorSdkPlatformRipgrepPackage();
4185
4381
  const bin = process.platform === "win32" ? "rg.exe" : "rg";
4186
- const sibling = join13(nm, pkg, "bin", bin);
4187
- if (existsSync14(sibling)) return sibling;
4188
- const nested = join13(root, "node_modules", pkg, "bin", bin);
4189
- return existsSync14(nested) ? nested : null;
4382
+ const sibling = join14(nm, pkg, "bin", bin);
4383
+ if (existsSync15(sibling)) return sibling;
4384
+ const nested = join14(root, "node_modules", pkg, "bin", bin);
4385
+ return existsSync15(nested) ? nested : null;
4190
4386
  }
4191
4387
 
4192
4388
  // src/agents/cursor-events.ts
@@ -4401,9 +4597,9 @@ function parseCursorRunnerLine(line) {
4401
4597
  }
4402
4598
 
4403
4599
  // src/agents/cursor-ripgrep.ts
4404
- import { existsSync as existsSync15 } from "fs";
4405
- import { createRequire as createRequire4 } from "module";
4406
- import { dirname as dirname7, isAbsolute as isAbsolute2, join as join14, parse, resolve as resolvePath } from "path";
4600
+ import { existsSync as existsSync16 } from "fs";
4601
+ import { createRequire as createRequire5 } from "module";
4602
+ import { dirname as dirname8, isAbsolute as isAbsolute2, join as join15, parse, resolve as resolvePath } from "path";
4407
4603
  var RIPGREP_ENV = "CURSOR_RIPGREP_PATH";
4408
4604
  function rgBinaryName() {
4409
4605
  return process.platform === "win32" ? "rg.exe" : "rg";
@@ -4415,19 +4611,19 @@ function usableRipgrepPath(candidate) {
4415
4611
  const raw = candidate?.trim();
4416
4612
  if (!raw || !isAbsolute2(raw)) return null;
4417
4613
  const readable = nodeReadableScriptPath(raw);
4418
- if (!existsSync15(readable) || isAsarPath(readable)) return null;
4614
+ if (!existsSync16(readable) || isAsarPath(readable)) return null;
4419
4615
  return readable;
4420
4616
  }
4421
4617
  function walkForBundledRipgrep(startFile) {
4422
4618
  if (!startFile) return null;
4423
4619
  const pkg = platformRipgrepPackage();
4424
4620
  const name = rgBinaryName();
4425
- let dir = dirname7(resolvePath(startFile));
4621
+ let dir = dirname8(resolvePath(startFile));
4426
4622
  const root = parse(dir).root;
4427
4623
  while (dir !== root) {
4428
- const hit = usableRipgrepPath(join14(dir, "node_modules", pkg, "bin", name));
4624
+ const hit = usableRipgrepPath(join15(dir, "node_modules", pkg, "bin", name));
4429
4625
  if (hit) return hit;
4430
- const next = dirname7(dir);
4626
+ const next = dirname8(dir);
4431
4627
  if (next === dir) break;
4432
4628
  dir = next;
4433
4629
  }
@@ -4435,9 +4631,9 @@ function walkForBundledRipgrep(startFile) {
4435
4631
  }
4436
4632
  function requireResolveBundledRipgrep(fromFile) {
4437
4633
  try {
4438
- const req = createRequire4(fromFile);
4634
+ const req = createRequire5(fromFile);
4439
4635
  const pkgJson = req.resolve(`${platformRipgrepPackage()}/package.json`);
4440
- return usableRipgrepPath(join14(dirname7(pkgJson), "bin", rgBinaryName()));
4636
+ return usableRipgrepPath(join15(dirname8(pkgJson), "bin", rgBinaryName()));
4441
4637
  } catch {
4442
4638
  return null;
4443
4639
  }
@@ -4507,15 +4703,15 @@ async function listCursorModels() {
4507
4703
  return cachedModels?.models ?? FALLBACK_CURSOR_MODELS;
4508
4704
  }
4509
4705
  }
4510
- function entryDir2() {
4706
+ function entryDir3() {
4511
4707
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
4512
4708
  if (cjsDir) return cjsDir;
4513
4709
  try {
4514
- return dirname8(fileURLToPath4(import.meta.url));
4710
+ return dirname9(fileURLToPath5(import.meta.url));
4515
4711
  } catch {
4516
4712
  try {
4517
- const req = createRequire5(process.cwd() + "/");
4518
- return dirname8(req.resolve("@sideboard-ai/core"));
4713
+ const req = createRequire6(process.cwd() + "/");
4714
+ return dirname9(req.resolve("@sideboard-ai/core"));
4519
4715
  } catch {
4520
4716
  return process.cwd();
4521
4717
  }
@@ -4524,19 +4720,19 @@ function entryDir2() {
4524
4720
  function cursorRunnerPath() {
4525
4721
  const packaged = packagedCursorRunnerPath();
4526
4722
  if (packaged) return packaged;
4527
- const root = entryDir2();
4723
+ const root = entryDir3();
4528
4724
  const candidates = [
4529
- join15(root, "agents", "cursor-runner.js"),
4530
- join15(root, "agents", "cursor-runner.cjs"),
4725
+ join16(root, "agents", "cursor-runner.js"),
4726
+ join16(root, "agents", "cursor-runner.cjs"),
4531
4727
  // If somehow resolved from package root instead of dist/
4532
- join15(root, "dist", "agents", "cursor-runner.js"),
4533
- join15(root, "dist", "agents", "cursor-runner.cjs"),
4728
+ join16(root, "dist", "agents", "cursor-runner.js"),
4729
+ join16(root, "dist", "agents", "cursor-runner.cjs"),
4534
4730
  // Source tree (dev): packages/core/src/agents/cursor-runner.ts
4535
- join15(root, "cursor-runner.ts"),
4536
- join15(root, "src", "agents", "cursor-runner.ts")
4731
+ join16(root, "cursor-runner.ts"),
4732
+ join16(root, "src", "agents", "cursor-runner.ts")
4537
4733
  ];
4538
4734
  for (const candidate of candidates) {
4539
- if (existsSync16(candidate)) return candidate;
4735
+ if (existsSync17(candidate)) return candidate;
4540
4736
  }
4541
4737
  return candidates[0];
4542
4738
  }
@@ -4642,14 +4838,14 @@ var cursorAdapter = {
4642
4838
  };
4643
4839
 
4644
4840
  // src/agents/opencode.ts
4645
- import { existsSync as existsSync18 } from "fs";
4841
+ import { existsSync as existsSync19 } from "fs";
4646
4842
 
4647
4843
  // src/agent-rpc/opencode-host.ts
4648
4844
  import { pathToFileURL as pathToFileURL2 } from "url";
4649
4845
 
4650
4846
  // src/agent-rpc/opencode-hook.ts
4651
- import { existsSync as existsSync17, mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync, writeFileSync as writeFileSync6 } from "fs";
4652
- import { join as join16 } from "path";
4847
+ import { existsSync as existsSync18, mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync, writeFileSync as writeFileSync6 } from "fs";
4848
+ import { join as join17 } from "path";
4653
4849
  var OPENCODE_PLUGIN_SOURCE = `import { tool } from "@opencode-ai/plugin"
4654
4850
 
4655
4851
  const RPC_URL = process.env[${JSON.stringify(AGENT_RPC_URL_ENV)}] || ""
@@ -4759,10 +4955,10 @@ export const SideboardRpc = async (ctx) => {
4759
4955
  }
4760
4956
  `;
4761
4957
  function writeOpencodeRpcPlugin() {
4762
- const pluginDir = join16(appDataDir(), "agent-rpc", "opencode");
4958
+ const pluginDir = join17(appDataDir(), "agent-rpc", "opencode");
4763
4959
  mkdirSync4(pluginDir, { recursive: true });
4764
- const pluginFile = join16(pluginDir, "sideboard-rpc.js");
4765
- if (existsSync17(pluginFile)) {
4960
+ const pluginFile = join17(pluginDir, "sideboard-rpc.js");
4961
+ if (existsSync18(pluginFile)) {
4766
4962
  try {
4767
4963
  if (readFileSync8(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
4768
4964
  } catch {
@@ -4863,7 +5059,7 @@ async function listOpencodeModels() {
4863
5059
  if (opencode === "opencode") {
4864
5060
  const which = await run("which", ["opencode"], { reject: false });
4865
5061
  if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
4866
- } else if (!existsSync18(opencode)) {
5062
+ } else if (!existsSync19(opencode)) {
4867
5063
  return FALLBACK_OPENCODE_MODELS;
4868
5064
  }
4869
5065
  const listed = await run(opencode, ["models"], { reject: false });
@@ -4898,7 +5094,7 @@ var opencodeAdapter = {
4898
5094
  async detect() {
4899
5095
  const opencode = resolveAgentExecutable("opencode");
4900
5096
  if (opencode !== "opencode") {
4901
- if (!existsSync18(opencode)) {
5097
+ if (!existsSync19(opencode)) {
4902
5098
  return {
4903
5099
  agent: "opencode",
4904
5100
  installed: false,
@@ -5149,7 +5345,7 @@ var opencodeAdapter = {
5149
5345
  };
5150
5346
  },
5151
5347
  async listLinearIssues(_repoPath) {
5152
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-JPQ27RXG.js");
5348
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-OINZWVV5.js");
5153
5349
  return listAssignedLinearIssues2();
5154
5350
  }
5155
5351
  };
@@ -5181,7 +5377,7 @@ async function listBrightsyModels() {
5181
5377
  }
5182
5378
  }
5183
5379
  async function listModelsForAgent(agent) {
5184
- const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy"];
5380
+ const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy", "acp"];
5185
5381
  const out = [];
5186
5382
  for (const kind of kinds) {
5187
5383
  if (kind === "claude") {
@@ -5220,6 +5416,15 @@ async function listModelsForAgent(agent) {
5220
5416
  });
5221
5417
  continue;
5222
5418
  }
5419
+ if (kind === "acp") {
5420
+ out.push({
5421
+ agent: kind,
5422
+ auto: true,
5423
+ models: [],
5424
+ note: "Gemini CLI and Copilot CLI choose the model. Leave model unset."
5425
+ });
5426
+ continue;
5427
+ }
5223
5428
  if (kind === "brightsy") {
5224
5429
  const models = await listBrightsyModels();
5225
5430
  out.push({
@@ -5338,7 +5543,8 @@ var adapters = {
5338
5543
  codex: codexAdapter,
5339
5544
  opencode: opencodeAdapter,
5340
5545
  brightsy: brightsyAdapter,
5341
- cursor: cursorAdapter
5546
+ cursor: cursorAdapter,
5547
+ acp: acpAdapter
5342
5548
  };
5343
5549
  function getAdapter(kind) {
5344
5550
  return adapters[kind];
@@ -5355,13 +5561,16 @@ export {
5355
5561
  adjustBrightsyTurnExit,
5356
5562
  listBrightsyChatTargets,
5357
5563
  brightsyAdapter,
5358
- mcpStatusThinkingFromClaudeInit,
5359
5564
  SIDEBOARD_THREAD_ID_ENV,
5360
5565
  shouldRegisterMcpWaitForTurn,
5361
5566
  worktreeMcpToolNames,
5362
5567
  sideboardMcpProfile,
5363
5568
  packagedMcpDir,
5364
5569
  applyAgentRunnerHeapEnv,
5570
+ acpRunnerPath,
5571
+ acpAdapter,
5572
+ acpHarnessDisplayName,
5573
+ mcpStatusThinkingFromClaudeInit,
5365
5574
  parseClaudeUsagePayload,
5366
5575
  hottestClaudeWindow,
5367
5576
  formatClaudeUsageReset,