@sideboard-ai/core 0.1.349 → 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 (78) 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-DMPBFF3F.js → agents-P5QIV24I.js} +37 -7
  12. package/dist/{agents-AZ2PV6XP.js → agents-RGAV5OHD.js} +42 -11
  13. package/dist/{app-settings-SNOPJ7P5.js → app-settings-IA7ZZKWQ.js} +2 -2
  14. package/dist/{app-settings-PPIMYJKS.js → app-settings-XILTSD6L.js} +1 -1
  15. package/dist/{chunk-Q4I6KDOL.js → chunk-2MESZ5XR.js} +60 -39
  16. package/dist/{chunk-RUIHNWRV.js → chunk-37ZBEBP6.js} +6 -6
  17. package/dist/{chunk-WHMLMCPU.js → chunk-5AHWUJRT.js} +1925 -1722
  18. package/dist/{chunk-7B2OUQON.js → chunk-5TCMXEYL.js} +48 -3
  19. package/dist/{chunk-FDYMVJFU.js → chunk-5WF54R3B.js} +5 -5
  20. package/dist/{chunk-PVCECFJK.js → chunk-7ZD4OK6G.js} +1 -1
  21. package/dist/{chunk-RYPD7XWV.js → chunk-B4EFQTMP.js} +5 -5
  22. package/dist/chunk-BF6INES4.js +144 -0
  23. package/dist/{chunk-IVRWRYTH.js → chunk-BZK62VPT.js} +2 -2
  24. package/dist/{chunk-AJMERXZP.js → chunk-CCWQ65VD.js} +2 -2
  25. package/dist/{chunk-62ALWH3T.js → chunk-DL4OHDBV.js} +3 -3
  26. package/dist/{chunk-CATTIFSP.js → chunk-EZ2MUWNW.js} +3 -3
  27. package/dist/{chunk-4NXGVJA6.js → chunk-F4RFFE2H.js} +48 -3
  28. package/dist/{chunk-E77SRVVO.js → chunk-FCKTBE26.js} +1 -1
  29. package/dist/{chunk-3DBL2C45.js → chunk-FQ3JYUKI.js} +2 -2
  30. package/dist/{chunk-CEQ4Z32M.js → chunk-J4EA5SHF.js} +3 -3
  31. package/dist/{chunk-MHSBF3SO.js → chunk-LFSTOECH.js} +3 -3
  32. package/dist/{chunk-OHUAAX3O.js → chunk-M45WGODR.js} +2 -2
  33. package/dist/{chunk-MVFFLU5V.js → chunk-MANERA6F.js} +12 -5
  34. package/dist/{chunk-ZXI5DR5S.js → chunk-NDEVAA34.js} +1624 -1487
  35. package/dist/{chunk-UJMCTGV7.js → chunk-PXSWVZIL.js} +2 -2
  36. package/dist/{chunk-6RIPZ73M.js → chunk-SMSD6U3N.js} +3 -1
  37. package/dist/{chunk-RPHH4FNK.js → chunk-TCEUNSLX.js} +3 -1
  38. package/dist/chunk-TRMPDDVL.js +232 -0
  39. package/dist/{chunk-6WMNIX2U.js → chunk-UFUAIVNV.js} +9 -5
  40. package/dist/{chunk-QHXZKHUL.js → chunk-VHQ6OG3U.js} +2 -2
  41. package/dist/{chunk-WWU4SYZR.js → chunk-VL6F2KRE.js} +5 -1
  42. package/dist/{chunk-IRFBD6GU.js → chunk-W5GHFT7E.js} +71 -47
  43. package/dist/{chunk-5FUAOU3G.js → chunk-WB3G2LQO.js} +1 -1
  44. package/dist/{chunk-JCYGQKER.js → chunk-WFX4ZVSZ.js} +1 -1
  45. package/dist/{chunk-F7WP2U5I.js → chunk-WJURGCBR.js} +1 -1
  46. package/dist/chunk-YE7Z5WH3.js +142 -0
  47. package/dist/{chunk-ROXM6QZV.js → chunk-ZBSEJIOV.js} +12 -5
  48. package/dist/{conductor-NHC6X74J.js → conductor-HVOGBK63.js} +6 -5
  49. package/dist/{conductor-65VPUPOW.js → conductor-VGCXUUG6.js} +7 -6
  50. package/dist/connected-teams-2YDE2EZ2.js +1 -1
  51. package/dist/{coordinator-prompt-5GZWIVSY.js → coordinator-prompt-DPO7L2JO.js} +5 -5
  52. package/dist/{coordinator-prompt-R2PURZL3.js → coordinator-prompt-E736TJBS.js} +4 -4
  53. package/dist/{global-workspace-64KC7PST.js → global-workspace-4RDPAOTT.js} +5 -5
  54. package/dist/{global-workspace-UEECLWSX.js → global-workspace-TG2TVLUF.js} +4 -4
  55. package/dist/index.cjs +1600 -929
  56. package/dist/index.d.cts +132 -891
  57. package/dist/index.d.ts +132 -891
  58. package/dist/index.js +433 -207
  59. package/dist/{linear-PKYJH4WK.js → linear-E3BX5PX5.js} +2 -2
  60. package/dist/{linear-MIJO6DCV.js → linear-WG23LBCX.js} +3 -3
  61. package/dist/{linear-list-JPQ27RXG.js → linear-list-OINZWVV5.js} +1 -1
  62. package/dist/{linear-list-N57PR6JM.js → linear-list-VU47BNUV.js} +1 -1
  63. package/dist/mcp/run-stdio.cjs +1097 -720
  64. package/dist/mcp/run-stdio.js +32 -24
  65. package/dist/{optional-cli-4GTEDEYJ.js → optional-cli-K6HX2X5O.js} +4 -3
  66. package/dist/{optional-cli-RPJIQBDX.js → optional-cli-SA3EQYML.js} +6 -5
  67. package/dist/{orchestrator-Y5PYSMR6.js → orchestrator-3I2FLEZL.js} +17 -15
  68. package/dist/{orchestrator-I5G5A5BV.js → orchestrator-QDHZ56LA.js} +11 -10
  69. package/dist/thread-CJRchYLj.d.cts +856 -0
  70. package/dist/thread-CJRchYLj.d.ts +856 -0
  71. package/dist/{thread-store-HZ4U4OXB.js → thread-store-4YTOV2HL.js} +3 -3
  72. package/dist/{thread-store-QKNU5CHM.js → thread-store-LME2ICZP.js} +2 -2
  73. package/dist/{workspaces-6TIM2TM2.js → workspaces-4PA24IX6.js} +4 -4
  74. package/dist/{workspaces-I2EHNTFE.js → workspaces-6TMYV4N2.js} +5 -5
  75. package/dist/{worktree-7JFYDNUX.js → worktree-4ATMCYIE.js} +3 -3
  76. package/dist/{worktree-M2GJGK2P.js → worktree-DA6SKIU5.js} +4 -4
  77. package/package.json +3 -3
  78. /package/dist/{chunk-XOEKCE6L.js → chunk-OHXNGBC4.js} +0 -0
@@ -3,31 +3,44 @@ import {
3
3
  brightsyMcpServerName,
4
4
  ensureCliTeamTracked,
5
5
  ensureConnectedBrightsyTeamTokens
6
- } from "./chunk-XOEKCE6L.js";
6
+ } from "./chunk-OHXNGBC4.js";
7
+ import {
8
+ loadBrightsyConfig
9
+ } from "./chunk-RSA47QYR.js";
7
10
  import {
8
11
  listAssignedLinearIssues
9
- } from "./chunk-5FUAOU3G.js";
12
+ } from "./chunk-WB3G2LQO.js";
10
13
  import {
11
14
  looksLikeConversationSummary,
12
15
  looksLikeSkillBody,
13
16
  skillCommandFromBody,
14
17
  withEventParentId
15
18
  } from "./chunk-WWBPK7GB.js";
19
+ import {
20
+ acpHarnessLabel,
21
+ defaultAcpHarness,
22
+ detectAcpHarness,
23
+ isAcpHarnessId,
24
+ resolveAcpHarnessCommand
25
+ } from "./chunk-YE7Z5WH3.js";
26
+ import {
27
+ httpFetch
28
+ } from "./chunk-JAT3JFOS.js";
16
29
  import {
17
30
  isOrchestratorThread
18
- } from "./chunk-MHSBF3SO.js";
31
+ } from "./chunk-LFSTOECH.js";
19
32
  import {
20
33
  codexUnattendedGitConfigArgs,
21
34
  mergeAgentGitAuthEnv,
22
35
  resolveAgentGitAuthEnv,
23
36
  resolveCodexGitWritableRoots
24
- } from "./chunk-3DBL2C45.js";
25
- import {
26
- loadBrightsyConfig
27
- } from "./chunk-RSA47QYR.js";
37
+ } from "./chunk-FQ3JYUKI.js";
28
38
  import {
29
- httpFetch
30
- } from "./chunk-JAT3JFOS.js";
39
+ acpPriorTranscript,
40
+ acpUserStdioServers,
41
+ parseAcpRunnerLine,
42
+ toAcpMcpServers
43
+ } from "./chunk-TRMPDDVL.js";
31
44
  import {
32
45
  BASE_ALLOWED_TOOLS,
33
46
  CLAUDE_CHROME_ALLOWED_TOOLS,
@@ -80,7 +93,7 @@ import {
80
93
  requestOccupancy,
81
94
  resolveAgentExecutable,
82
95
  resolveClaudeExecutable
83
- } from "./chunk-6WMNIX2U.js";
96
+ } from "./chunk-UFUAIVNV.js";
84
97
  import {
85
98
  isElectronLikeCommand,
86
99
  unwrapStrippedElectronLaunch
@@ -89,1597 +102,1708 @@ import {
89
102
  appDataDir
90
103
  } from "./chunk-H4UEFJRI.js";
91
104
 
92
- // src/agents/brightsy.ts
93
- import { existsSync } from "fs";
105
+ // src/agents/acp.ts
106
+ import { existsSync as existsSync5 } from "fs";
107
+ import { createRequire as createRequire2 } from "module";
108
+ import { homedir as homedir5 } from "os";
109
+ import { dirname as dirname3, join as join6 } from "path";
110
+ import { fileURLToPath as fileURLToPath2 } from "url";
94
111
 
95
- // src/agents/brightsy-targets.ts
96
- function encodeBrightsyTarget(type, id, accountId) {
97
- if (accountId) return `team:${accountId}:${type}:${id}`;
98
- return `${type}:${id}`;
99
- }
100
- function decodeBrightsyTarget(model) {
101
- const raw = model?.trim();
102
- if (!raw || raw === "default" || raw === "agent:default") {
103
- return { type: "agent", id: "default" };
112
+ // src/agents/orch-mcp-isolation.ts
113
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
114
+
115
+ // src/agents/claude-plugins.ts
116
+ import { existsSync, readFileSync } from "fs";
117
+ import { homedir } from "os";
118
+ import { isAbsolute, join, relative, resolve } from "path";
119
+
120
+ // src/mcp-ui/meta.ts
121
+ var HTML_MAX = 15e5;
122
+ function matchClaudeMcpTool(toolName, serverNames) {
123
+ const name = toolName.trim();
124
+ if (!name.startsWith("mcp__")) return null;
125
+ const ranked = [...serverNames].filter((s) => s.trim()).sort((a, b) => b.length - a.length);
126
+ for (const server of ranked) {
127
+ const prefix = `mcp__${server}__`;
128
+ if (!name.startsWith(prefix)) continue;
129
+ const tool = name.slice(prefix.length).trim();
130
+ if (!tool) continue;
131
+ return { server, tool };
104
132
  }
105
- const teamMatch = raw.match(/^team:([^:]+):(agent|model):(.+)$/);
106
- if (teamMatch) {
133
+ return null;
134
+ }
135
+ function parseMcpServerLaunch(entry) {
136
+ const command = typeof entry.command === "string" ? entry.command.trim() : "";
137
+ if (command) {
138
+ const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
139
+ const env = stringRecord(entry.env);
140
+ const cwd = typeof entry.cwd === "string" && entry.cwd.trim() ? entry.cwd.trim() : void 0;
107
141
  return {
108
- type: teamMatch[2],
109
- id: teamMatch[3] || "default",
110
- accountId: teamMatch[1]
142
+ kind: "stdio",
143
+ command,
144
+ args,
145
+ ...env ? { env } : {},
146
+ ...cwd ? { cwd } : {}
111
147
  };
112
148
  }
113
- if (raw.startsWith("agent:")) {
114
- return { type: "agent", id: raw.slice("agent:".length) || "default" };
115
- }
116
- if (raw.startsWith("model:")) {
117
- return { type: "model", id: raw.slice("model:".length) };
118
- }
119
- if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw) || raw === "default") {
120
- return { type: "agent", id: raw };
149
+ const url = typeof entry.url === "string" ? entry.url.trim() : "";
150
+ if (!url) return null;
151
+ let parsed;
152
+ try {
153
+ parsed = new URL(url);
154
+ } catch {
155
+ return null;
121
156
  }
122
- return { type: "model", id: raw };
123
- }
124
-
125
- // src/agents/turn-input.ts
126
- function normalizeTurnInput(input) {
127
- if (typeof input === "string") return { prompt: input };
157
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
158
+ const type = typeof entry.type === "string" ? entry.type.trim().toLowerCase() : "";
159
+ const headers = stringRecord(entry.headers);
128
160
  return {
129
- prompt: input.prompt,
130
- cachedPrefix: input.cachedPrefix?.trim() || void 0,
131
- systemPrompt: input.systemPrompt?.trim() || void 0,
132
- ...input.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
161
+ kind: type === "sse" ? "sse" : "http",
162
+ url: parsed.toString(),
163
+ ...headers ? { headers } : {}
133
164
  };
134
165
  }
135
- function dropCachedPrefixOnResume(input, sessionId) {
136
- const turn = normalizeTurnInput(input);
137
- if (sessionId) {
138
- return {
139
- prompt: turn.prompt,
140
- ...turn.systemPrompt ? { systemPrompt: turn.systemPrompt } : {},
141
- ...turn.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
142
- };
143
- }
144
- return turn;
145
- }
146
- function flattenTurnInput(input) {
147
- const { cachedPrefix, prompt, systemPrompt } = normalizeTurnInput(input);
148
- if (cachedPrefix) return `${cachedPrefix}
149
-
150
- ---
151
-
152
- Current request:
153
- ${prompt}`;
154
- if (systemPrompt) return `${systemPrompt}
155
-
156
- ${prompt}`;
157
- return prompt;
166
+ function uiResourceUriFromMeta(meta) {
167
+ const rec = asRecord(meta);
168
+ const nested = asRecord(rec.ui);
169
+ const fromNested = typeof nested.resourceUri === "string" ? nested.resourceUri.trim() : "";
170
+ const legacy = typeof rec["ui/resourceUri"] === "string" ? rec["ui/resourceUri"].trim() : "";
171
+ const uri = fromNested || legacy;
172
+ return uri.startsWith("ui://") ? uri : null;
158
173
  }
159
- function splitTurnInputForSystemPrompt(input) {
160
- const turn = normalizeTurnInput(input);
174
+ function cspFromMeta(meta) {
175
+ const ui = asRecord(asRecord(meta).ui);
176
+ const csp = asRecord(ui.csp);
177
+ const connectDomains = originList(csp.connectDomains);
178
+ const resourceDomains = originList(csp.resourceDomains);
179
+ const frameDomains = originList(csp.frameDomains);
180
+ const baseUriDomains = originList(csp.baseUriDomains);
181
+ if (!connectDomains?.length && !resourceDomains?.length && !frameDomains?.length && !baseUriDomains?.length) {
182
+ return void 0;
183
+ }
161
184
  return {
162
- promptText: flattenTurnInput({ cachedPrefix: turn.cachedPrefix, prompt: turn.prompt }),
163
- systemPrompt: turn.systemPrompt
185
+ ...connectDomains?.length ? { connectDomains } : {},
186
+ ...resourceDomains?.length ? { resourceDomains } : {},
187
+ ...frameDomains?.length ? { frameDomains } : {},
188
+ ...baseUriDomains?.length ? { baseUriDomains } : {}
164
189
  };
165
190
  }
166
- function buildCachedUserContent(input) {
167
- return [{ type: "text", text: flattenTurnInput(input) }];
191
+ function htmlFromResourceContent(content) {
192
+ const uri = content.uri?.trim() ?? "";
193
+ if (!uri.startsWith("ui://")) return null;
194
+ const mimeType = content.mimeType?.trim() || "text/html";
195
+ if (!isHtmlMime(mimeType)) return null;
196
+ const html = htmlText(content.text, content.blob);
197
+ if (!html) return null;
198
+ return { uri, mimeType, html };
168
199
  }
169
- function buildClaudeStreamJsonUserMessage(input) {
170
- return `${JSON.stringify({
171
- type: "user",
172
- message: {
173
- role: "user",
174
- content: buildCachedUserContent(input)
175
- }
176
- })}
177
- `;
200
+ function mcpUiContentSecurityPolicy(csp) {
201
+ const resource = (csp?.resourceDomains ?? []).join(" ");
202
+ const connect = (csp?.connectDomains ?? []).join(" ");
203
+ const frames = csp?.frameDomains?.length ? csp.frameDomains.join(" ") : "'none'";
204
+ const base = csp?.baseUriDomains?.length ? csp.baseUriDomains.join(" ") : "'none'";
205
+ const connectSrc = connect ? `'self' ${connect}`.trim() : "'none'";
206
+ return [
207
+ "default-src 'none'",
208
+ `script-src 'self' 'unsafe-inline' ${resource}`.trim(),
209
+ `style-src 'self' 'unsafe-inline' ${resource}`.trim(),
210
+ `img-src 'self' data: ${resource}`.trim(),
211
+ `font-src 'self' ${resource}`.trim(),
212
+ `connect-src ${connectSrc}`,
213
+ `media-src 'self' data: ${resource}`.trim(),
214
+ `frame-src ${frames}`,
215
+ `base-uri ${base}`,
216
+ "object-src 'none'"
217
+ ].join("; ");
178
218
  }
179
- function walkCacheControls(blocks, saw5m) {
180
- if (!blocks?.length) return { saw5m, invalid: null };
181
- for (let i = 0; i < blocks.length; i++) {
182
- const block = blocks[i];
183
- const ttl = block.cache_control?.ttl ?? (block.cache_control ? "5m" : null);
184
- if (ttl === "5m") saw5m = true;
185
- if (ttl === "1h" && saw5m) return { saw5m, invalid: { index: i, ttl: "1h" } };
186
- if (Array.isArray(block.content)) {
187
- const nested = walkCacheControls(block.content, saw5m);
188
- if (nested.invalid) return { saw5m: nested.saw5m, invalid: { index: i, ttl: "1h" } };
189
- saw5m = nested.saw5m;
190
- }
219
+ function htmlText(text, blob) {
220
+ if (typeof text === "string" && text.trim()) {
221
+ return text.length <= HTML_MAX ? text : null;
222
+ }
223
+ if (typeof blob !== "string" || !blob.trim()) return null;
224
+ try {
225
+ const decoded = decodeBase64(blob.trim());
226
+ if (!decoded.trim() || decoded.length > HTML_MAX) return null;
227
+ return decoded;
228
+ } catch {
229
+ return null;
191
230
  }
192
- return { saw5m, invalid: null };
193
231
  }
194
- function findInvalidCacheControlTtlOrder(blocks) {
195
- return walkCacheControls(blocks, false).invalid;
232
+ function decodeBase64(blob) {
233
+ if (typeof Buffer !== "undefined") return Buffer.from(blob, "base64").toString("utf8");
234
+ const bin = atob(blob);
235
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
236
+ return new TextDecoder().decode(bytes);
196
237
  }
197
- function countCacheControlBlocks(blocks) {
198
- if (!blocks?.length) return 0;
199
- let count = 0;
200
- for (const block of blocks) {
201
- if (block.cache_control) count++;
202
- if (Array.isArray(block.content)) {
203
- count += countCacheControlBlocks(block.content);
204
- }
205
- }
206
- return count;
238
+ function isHtmlMime(mime) {
239
+ const base = mime.split(";")[0]?.trim().toLowerCase() ?? "";
240
+ return base === "text/html";
207
241
  }
208
- var MAX_ANTHROPIC_CACHE_CONTROL_BLOCKS = 4;
209
-
210
- // src/agents/brightsy.ts
211
- function usageFromBrightsy(usage) {
212
- if (!usage) return null;
213
- const mapped = fromInclusiveInputUsage({
214
- inputTokens: Number(usage.prompt_tokens ?? 0),
215
- outputTokens: Number(usage.completion_tokens ?? 0),
216
- cachedInputTokens: Number(usage.prompt_tokens_details?.cached_tokens ?? 0)
217
- });
218
- if (!mapped) return null;
219
- if (usage.cost != null && Number.isFinite(Number(usage.cost))) {
220
- mapped.costUsd = Number(usage.cost);
242
+ function originList(value) {
243
+ if (!Array.isArray(value)) return void 0;
244
+ const out = [];
245
+ for (const item of value) {
246
+ if (typeof item !== "string") continue;
247
+ const origin = originToken(item);
248
+ if (origin && !out.includes(origin)) out.push(origin);
221
249
  }
222
- return mapped;
250
+ return out;
223
251
  }
224
- function parseBrightsyCliLine(line) {
225
- const trimmed = line.trim();
226
- if (!trimmed) return null;
252
+ function originToken(value) {
253
+ const trimmed = value.trim();
254
+ if (/^(https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?$/i.test(trimmed)) return trimmed;
227
255
  try {
228
- const obj = JSON.parse(trimmed);
229
- if (obj.type === "text" && typeof obj.text === "string") {
230
- if (looksLikeBrightsyEmptyCompletion(obj.text)) {
231
- return [
232
- { type: "stderr", data: obj.text },
233
- { type: "stdout", data: `Error: ${obj.text}` }
234
- ];
235
- }
236
- return { type: "stdout", data: obj.text };
237
- }
238
- if (obj.type === "thinking" && typeof obj.text === "string") {
239
- return { type: "thinking", data: obj.text };
240
- }
241
- if (obj.type === "error") {
242
- const msg = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
243
- return [
244
- { type: "stderr", data: msg },
245
- { type: "stdout", data: `Error: ${msg}` }
246
- ];
247
- }
248
- if (obj.type === "usage") {
249
- const usage = usageFromBrightsy(obj.usage);
250
- return usage ? { type: "usage", data: usage } : null;
251
- }
252
- if (obj.type === "tool_use") {
253
- const id = typeof obj.id === "string" && obj.id || `brightsy-tool-${Date.now()}`;
254
- const name = typeof obj.name === "string" && obj.name || "brightsy_tool";
255
- const input = obj.input && typeof obj.input === "object" && !Array.isArray(obj.input) ? obj.input : void 0;
256
- return { type: "tool_use", id, name, input };
257
- }
258
- if (obj.type === "tool_result" || obj.type === "tool") {
259
- const id = typeof obj.id === "string" && obj.id || typeof obj.tool_call_id === "string" && obj.tool_call_id || `brightsy-tool-${Date.now()}`;
260
- const content = typeof obj.content === "string" ? obj.content : obj.content != null ? JSON.stringify(obj.content) : void 0;
261
- return {
262
- type: "tool_result",
263
- id,
264
- content,
265
- isError: obj.isError === true
266
- };
267
- }
268
- if (obj.type === "done") return null;
269
- if (typeof obj.type === "string" && ["tool_use", "tool_result", "tool", "thinking", "usage", "error", "done", "text"].includes(
270
- obj.type
271
- )) {
256
+ const url = new URL(trimmed);
257
+ if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "wss:" && url.protocol !== "ws:") {
272
258
  return null;
273
259
  }
274
- return { type: "stdout", data: trimmed };
260
+ return url.origin;
275
261
  } catch {
276
- if (trimmed.startsWith("{") && /"type"\s*:\s*"(tool_use|tool_result|tool|text|thinking|usage|done|error)"/.test(trimmed)) {
277
- return null;
278
- }
279
- if (looksLikeBrightsyEmptyCompletion(trimmed) || /error|failed|unauthorized|quota|limit|not logged in/i.test(trimmed)) {
280
- return [
281
- { type: "stderr", data: trimmed },
282
- { type: "stdout", data: `Error: ${trimmed}` }
283
- ];
284
- }
285
- return { type: "stdout", data: line };
262
+ return null;
286
263
  }
287
264
  }
288
- function adjustBrightsyTurnExit(exitCode, assistantText) {
289
- if (looksLikeBrightsyEmptyCompletion(assistantText) && (exitCode === 0 || exitCode == null)) {
290
- return 2;
265
+ function stringRecord(value) {
266
+ const rec = asRecord(value);
267
+ const out = {};
268
+ for (const [key, item] of Object.entries(rec)) {
269
+ if (typeof item === "string") out[key] = item;
291
270
  }
292
- return exitCode;
271
+ return Object.keys(out).length > 0 ? out : void 0;
293
272
  }
294
- async function fetchTeamChatTargets(team) {
295
- const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
296
- let agents = [
297
- {
298
- type: "agent",
299
- id: "default",
300
- name: "Default Agent",
301
- description: "Account default agent (tools + memory)",
302
- accountId: team.id,
303
- accountSlug: team.slug,
304
- accountName: team.name
305
- }
306
- ];
307
- let models = [];
308
- try {
309
- const res = await fetch(`${endpoint}/api/v1beta/${team.id}/agents`, {
310
- headers: { Authorization: `Bearer ${team.access_token}` }
311
- });
312
- if (res.ok) {
313
- const json = await res.json();
314
- const listed = (json.data || []).filter(
315
- (a) => Boolean(a?.id && a?.name)
316
- ).filter((a) => a.id !== "default").map((a) => ({
317
- type: "agent",
318
- id: a.id,
319
- name: a.name,
320
- description: a.description,
321
- accountId: team.id,
322
- accountSlug: team.slug,
323
- accountName: team.name
324
- }));
325
- agents = [...agents, ...listed];
326
- if (Array.isArray(json.models)) {
327
- models = json.models.filter(
328
- (m) => Boolean(m?.id && m?.name)
329
- ).slice(0, 12).map((m) => ({
330
- type: "model",
331
- id: m.id,
332
- name: m.name,
333
- description: m.description,
334
- accountId: team.id,
335
- accountSlug: team.slug,
336
- accountName: team.name
337
- }));
338
- }
339
- }
340
- } catch {
341
- }
342
- return {
343
- accountId: team.id,
344
- accountSlug: team.slug,
345
- accountName: team.name,
346
- agents,
347
- models
348
- };
273
+ function asRecord(value) {
274
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
275
+ return value;
349
276
  }
350
- async function listBrightsyChatTargetsViaCli() {
351
- const listed = await run(
352
- resolveAgentExecutable("brightsy"),
353
- ["chat", "--list-targets", "--json"],
354
- {
355
- reject: false
356
- }
357
- );
358
- if (listed.exitCode !== 0 || !listed.stdout.trim()) {
359
- throw new Error(
360
- listed.stderr.trim() || "Failed to list Brightsy chat targets \u2014 is `brightsy` installed and logged in?"
361
- );
362
- }
363
- try {
364
- const parsed = JSON.parse(listed.stdout);
365
- let accountId = null;
366
- let accountSlug = "team";
367
- let accountName = "Brightsy";
368
- try {
369
- const cfg = loadBrightsyConfig();
370
- accountId = cfg.account_id;
371
- accountSlug = cfg.account_slug || accountSlug;
372
- accountName = cfg.account_slug || accountName;
373
- } catch {
277
+
278
+ // src/agents/claude-plugins.ts
279
+ function claudePluginServerId(pluginName, serverName) {
280
+ return `plugin_${pluginName}_${serverName}`.replace(/[^A-Za-z0-9_-]/g, "_");
281
+ }
282
+ function listEnabledClaudePluginMcpServers(opts) {
283
+ const home = opts?.home ?? homedir();
284
+ const pluginsRoot = claudePluginsRoot(home);
285
+ const enabled = enabledPluginIds(home, opts?.projectDirs ?? []);
286
+ const installed = readInstalledPlugins(join(pluginsRoot, "installed_plugins.json"));
287
+ const out = {};
288
+ for (const [id, on] of enabled) {
289
+ if (!on) continue;
290
+ const root = installPathFor(id, installed);
291
+ if (!root || !existsSync(root)) continue;
292
+ const pluginName = manifestName(root) || id.split("@")[0]?.trim() || "";
293
+ if (!pluginName) continue;
294
+ const dataDir = join(pluginsRoot, "data", pluginDataId(id));
295
+ for (const [serverName, entry] of Object.entries(loadPluginMcpServers(root))) {
296
+ const expanded = expandPluginEntry(entry, root, dataDir);
297
+ if (!parseMcpServerLaunch(expanded)) continue;
298
+ const key = claudePluginServerId(pluginName, serverName);
299
+ if (!key || key === "plugin__") continue;
300
+ out[key] = expanded;
374
301
  }
375
- const agents = (Array.isArray(parsed.agents) ? parsed.agents : []).map((a) => ({
376
- ...a,
377
- accountId: accountId ?? void 0,
378
- accountSlug,
379
- accountName
380
- }));
381
- const models = (Array.isArray(parsed.models) ? parsed.models : []).map((m) => ({
382
- ...m,
383
- accountId: accountId ?? void 0,
384
- accountSlug,
385
- accountName
386
- }));
387
- const teams = accountId ? [
388
- {
389
- accountId,
390
- accountSlug,
391
- accountName,
392
- agents,
393
- models
394
- }
395
- ] : [];
396
- return { teams, agents, models, activeAccountId: accountId };
397
- } catch {
398
- throw new Error("Brightsy --list-targets returned invalid JSON");
399
302
  }
303
+ return out;
400
304
  }
401
- async function listBrightsyChatTargets() {
402
- ensureCliTeamTracked();
403
- const teamsRaw = await ensureConnectedBrightsyTeamTokens();
404
- if (teamsRaw.length === 0) {
405
- return listBrightsyChatTargetsViaCli();
305
+ function claudePluginsRoot(home) {
306
+ const override = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim();
307
+ if (override && isAbsolute(override)) return override;
308
+ return join(home, ".claude", "plugins");
309
+ }
310
+ function pluginDataId(pluginId) {
311
+ return pluginId.replace(/[^A-Za-z0-9_-]/g, "-");
312
+ }
313
+ function enabledPluginIds(home, projectDirs) {
314
+ const enabled = /* @__PURE__ */ new Map();
315
+ applyEnabled(enabled, readEnabledPlugins(join(home, ".claude", "settings.json")));
316
+ const dirs = [...new Set(projectDirs.map((dir) => dir.trim()).filter(Boolean))];
317
+ for (const dir of dirs) {
318
+ applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.json")));
406
319
  }
407
- let activeAccountId = null;
408
- try {
409
- activeAccountId = loadBrightsyConfig().account_id;
410
- } catch {
411
- activeAccountId = teamsRaw[0]?.id ?? null;
320
+ for (const dir of dirs) {
321
+ applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.local.json")));
412
322
  }
413
- const teams = await Promise.all(teamsRaw.map((t) => fetchTeamChatTargets(t)));
414
- teams.sort((a, b) => {
415
- if (a.accountId === activeAccountId) return -1;
416
- if (b.accountId === activeAccountId) return 1;
417
- return a.accountSlug.localeCompare(b.accountSlug);
418
- });
419
- const active = teams.find((t) => t.accountId === activeAccountId) ?? teams[0] ?? null;
420
- return {
421
- teams,
422
- agents: active?.agents ?? [],
423
- models: active?.models ?? [],
424
- activeAccountId
425
- };
323
+ return enabled;
426
324
  }
427
- async function syncCliForTarget(accountId) {
428
- if (!accountId) return;
429
- const teams = await ensureConnectedBrightsyTeamTokens();
430
- const team = teams.find((t) => t.id === accountId);
431
- if (!team) return;
432
- try {
433
- const cfg = loadBrightsyConfig();
434
- if (cfg.account_id === team.id && cfg.access_token === team.access_token) {
435
- return;
436
- }
437
- } catch {
325
+ function applyEnabled(into, next) {
326
+ for (const [id, on] of Object.entries(next)) {
327
+ const key = id.trim();
328
+ if (!key) continue;
329
+ into.set(key, on);
438
330
  }
439
- applyConnectedTeamToCli(team);
440
331
  }
441
- var brightsyAdapter = {
442
- kind: "brightsy",
443
- async detect() {
444
- const brightsy = resolveAgentExecutable("brightsy");
445
- if (brightsy !== "brightsy") {
446
- if (!existsSync(brightsy)) {
447
- return {
448
- agent: "brightsy",
449
- installed: false,
450
- authenticated: false,
451
- linearMcp: false,
452
- warnings: [],
453
- reason: `Brightsy executable not found: ${brightsy}`
454
- };
455
- }
456
- } else {
457
- const which = await run("which", ["brightsy"], { reject: false });
458
- if (which.exitCode !== 0) {
459
- return {
460
- agent: "brightsy",
461
- installed: false,
462
- authenticated: false,
463
- linearMcp: false,
464
- warnings: [],
465
- reason: "brightsy CLI not found on PATH \u2014 npm i -g @brightsy/cli"
466
- };
467
- }
332
+ function readEnabledPlugins(path) {
333
+ const root = readJson(path);
334
+ const raw = root.enabledPlugins;
335
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
336
+ const out = {};
337
+ for (const [id, value] of Object.entries(raw)) {
338
+ if (value === true || value === false) out[id] = value;
339
+ }
340
+ return out;
341
+ }
342
+ function readInstalledPlugins(path) {
343
+ const root = readJson(path);
344
+ const plugins = root.plugins;
345
+ if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) return {};
346
+ const out = {};
347
+ for (const [id, value] of Object.entries(plugins)) {
348
+ const rows = Array.isArray(value) ? value : [value];
349
+ const installs = [];
350
+ for (const row of rows) {
351
+ if (!row || typeof row !== "object" || Array.isArray(row)) continue;
352
+ const installPath = row.installPath;
353
+ installs.push({
354
+ ...typeof installPath === "string" && installPath.trim() ? { installPath: installPath.trim() } : {}
355
+ });
468
356
  }
469
- const who = await run(brightsy, ["whoami"], { reject: false });
470
- const authenticated = who.exitCode === 0 && /logged in as/i.test(who.stdout);
471
- return {
472
- agent: "brightsy",
473
- installed: true,
474
- authenticated,
475
- linearMcp: false,
476
- warnings: [],
477
- reason: authenticated ? void 0 : "not logged in \u2014 run `brightsy login`"
478
- };
479
- },
480
- async buildTurn(thread, input) {
481
- const prompt = flattenTurnInput(input);
482
- const target = decodeBrightsyTarget(thread.model);
483
- await syncCliForTarget(target.accountId);
484
- const mode = thread.planMode ? "plan" : target.type === "model" ? "ask" : "agent";
485
- const args = [
486
- "chat",
487
- "--json",
488
- "--mode",
489
- mode,
490
- target.type === "model" ? "--model" : "--agent",
491
- target.id
492
- ];
493
- return {
494
- file: resolveAgentExecutable("brightsy"),
495
- args,
496
- cwd: thread.worktreePath,
497
- // Piped stdin becomes the message body (avoids ARG_MAX for long seeds).
498
- stdin: prompt
499
- };
500
- },
501
- parseEvent(line) {
502
- return parseBrightsyCliLine(line);
503
- },
504
- async resolveSessionId() {
505
- return null;
506
- },
507
- async buildAttach(thread) {
508
- const target = decodeBrightsyTarget(thread.model);
509
- await syncCliForTarget(target.accountId);
510
- const args = target.type === "model" ? ["chat", "--model", target.id] : ["chat", "--agent", target.id];
511
- return {
512
- file: resolveAgentExecutable("brightsy"),
513
- args,
514
- cwd: thread.worktreePath
515
- };
357
+ if (installs.length) out[id] = installs;
516
358
  }
517
- };
518
-
519
- // src/agents/claude.ts
520
- import { existsSync as existsSync8 } from "fs";
521
- import { dirname as dirname4 } from "path";
522
-
523
- // src/agents/claude-mcp-status.ts
524
- var SIDEBOARD_CONNECTOR_SERVICES = [
525
- "github",
526
- "linear",
527
- "posthog",
528
- "vercel",
529
- "supabase",
530
- "sentry"
531
- ];
532
- function mcpStatusThinkingFromClaudeInit(obj) {
533
- const raw = obj.mcp_servers ?? obj.mcpServers;
534
- const servers = [];
535
- if (Array.isArray(raw)) {
536
- for (const item of raw) {
537
- if (!item || typeof item !== "object" || Array.isArray(item)) continue;
538
- const rec = item;
539
- const name = typeof rec.name === "string" && rec.name.trim() || typeof rec.server === "string" && rec.server.trim() || "";
540
- const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "";
541
- if (name) servers.push({ name, status: status || "unknown" });
359
+ return out;
360
+ }
361
+ function installPathFor(id, installed) {
362
+ const rows = installed[id] ?? [];
363
+ for (let i = rows.length - 1; i >= 0; i--) {
364
+ const path = rows[i]?.installPath;
365
+ if (path && existsSync(path)) return path;
366
+ }
367
+ return null;
368
+ }
369
+ function manifestName(root) {
370
+ const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
371
+ return typeof manifest.name === "string" ? manifest.name.trim() : "";
372
+ }
373
+ function loadPluginMcpServers(root) {
374
+ const servers = {};
375
+ mergeServerMap(servers, serversFromFile(join(root, ".mcp.json"), root));
376
+ const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
377
+ mergeServerMap(servers, serversFromManifest(manifest.mcpServers, root));
378
+ return servers;
379
+ }
380
+ function serversFromManifest(value, root) {
381
+ if (!value) return {};
382
+ if (typeof value === "string") return serversFromFile(resolveInside(root, value), root);
383
+ if (Array.isArray(value)) {
384
+ const out = {};
385
+ for (const item of value) {
386
+ if (typeof item === "string") mergeServerMap(out, serversFromFile(resolveInside(root, item), root));
387
+ else mergeServerMap(out, serverMap(item, root));
542
388
  }
543
- } else if (raw && typeof raw === "object") {
544
- for (const [name, value] of Object.entries(raw)) {
545
- if (!name.trim()) continue;
546
- if (typeof value === "string" && value.trim()) {
547
- servers.push({ name, status: value.trim() });
548
- continue;
549
- }
550
- if (value && typeof value === "object" && !Array.isArray(value)) {
551
- const rec = value;
552
- const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "unknown";
553
- servers.push({ name, status });
554
- }
389
+ return out;
390
+ }
391
+ return serverMap(value, root);
392
+ }
393
+ function serversFromFile(path, root) {
394
+ if (!path || !existsSync(path)) return {};
395
+ return serverMap(readJson(path), root);
396
+ }
397
+ function serverMap(value, root) {
398
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
399
+ const record = value;
400
+ const wrapped = record.mcpServers;
401
+ const source = wrapped && typeof wrapped === "object" && !Array.isArray(wrapped) ? wrapped : record;
402
+ if (typeof wrapped === "string") return serversFromFile(resolveInside(root, wrapped), root);
403
+ const out = {};
404
+ for (const [name, entry] of Object.entries(source)) {
405
+ if (!name.trim() || !entry || typeof entry !== "object" || Array.isArray(entry)) continue;
406
+ const row = entry;
407
+ if (row.disabled === true) continue;
408
+ if (typeof row.command !== "string" && typeof row.url !== "string") continue;
409
+ out[name.trim()] = row;
410
+ }
411
+ return out;
412
+ }
413
+ function mergeServerMap(into, extra) {
414
+ for (const [name, entry] of Object.entries(extra)) into[name] = entry;
415
+ }
416
+ function expandPluginEntry(entry, root, dataDir) {
417
+ const next = { ...entry };
418
+ if (typeof next.command === "string") next.command = expandVars(next.command, root, dataDir);
419
+ if (Array.isArray(next.args)) {
420
+ next.args = next.args.map((arg) => typeof arg === "string" ? expandVars(arg, root, dataDir) : arg);
421
+ }
422
+ if (typeof next.url === "string") next.url = expandVars(next.url, root, dataDir);
423
+ if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) {
424
+ const env = {};
425
+ for (const [key, value] of Object.entries(next.env)) {
426
+ if (typeof value === "string") env[key] = expandVars(value, root, dataDir);
555
427
  }
428
+ env.CLAUDE_PLUGIN_ROOT = env.CLAUDE_PLUGIN_ROOT || root;
429
+ env.CLAUDE_PLUGIN_DATA = env.CLAUDE_PLUGIN_DATA || dataDir;
430
+ next.env = env;
431
+ } else if (typeof next.command === "string") {
432
+ next.env = { CLAUDE_PLUGIN_ROOT: root, CLAUDE_PLUGIN_DATA: dataDir };
556
433
  }
557
- const coverage = claudeConnectorCoverage();
558
- const sideboardOk = sideboardMcpOk(servers);
559
- const notable = servers.filter(
560
- (server) => isNotableMcpInitStatus(server, sideboardOk, coverage)
561
- );
562
- if (notable.length === 0) return null;
563
- return `MCP: ${notable.map((s) => `${s.name} ${s.status}`).join(", ")}`;
434
+ if (next.headers && typeof next.headers === "object" && !Array.isArray(next.headers)) {
435
+ const headers = {};
436
+ for (const [key, value] of Object.entries(next.headers)) {
437
+ if (typeof value === "string") headers[key] = expandVars(value, root, dataDir);
438
+ }
439
+ next.headers = headers;
440
+ }
441
+ return next;
442
+ }
443
+ function expandVars(value, root, dataDir) {
444
+ return value.replaceAll("${CLAUDE_PLUGIN_ROOT}", root).replaceAll("${CLAUDE_PLUGIN_DATA}", dataDir);
445
+ }
446
+ function resolveInside(root, spec) {
447
+ const trimmed = spec.trim();
448
+ if (!trimmed || trimmed.endsWith(".mcpb") || trimmed.endsWith(".dxt")) return null;
449
+ if (/^https?:\/\//i.test(trimmed)) return null;
450
+ const abs = resolve(root, trimmed);
451
+ const rel = relative(root, abs);
452
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
453
+ return abs;
454
+ }
455
+ function readJson(path) {
456
+ if (!existsSync(path)) return {};
457
+ try {
458
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
459
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
460
+ return parsed;
461
+ } catch {
462
+ return {};
463
+ }
464
+ }
465
+
466
+ // src/agents/orch-mcp-isolation.ts
467
+ import { homedir as homedir4 } from "os";
468
+ import { join as join5 } from "path";
469
+ import { parse as parseToml } from "smol-toml";
470
+
471
+ // src/agents/user-mcp-config.ts
472
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
473
+ import { homedir as homedir3 } from "os";
474
+ import { dirname as dirname2, join as join4 } from "path";
475
+
476
+ // src/agents/injected-mcp.ts
477
+ import { existsSync as existsSync2, mkdtempSync, writeFileSync as writeFileSync2 } from "fs";
478
+ import { createRequire } from "module";
479
+ import { tmpdir } from "os";
480
+ import { dirname, join as join3 } from "path";
481
+ import { fileURLToPath } from "url";
482
+
483
+ // src/mcp/profile.ts
484
+ var SIDEBOARD_MCP_PROFILE_ENV = "SIDEBOARD_MCP_PROFILE";
485
+ var SIDEBOARD_THREAD_ID_ENV = "SIDEBOARD_THREAD_ID";
486
+ function agentRpcOwnsPilotTools(env = process.env) {
487
+ return env[AGENT_RPC_NATIVE_ENV]?.trim() === "1";
488
+ }
489
+ function injectedSideboardMcpEnv(opts) {
490
+ const orchId = opts.orchestratorThreadId?.trim();
491
+ const threadId = opts.threadId?.trim() || orchId;
492
+ const env = {
493
+ SIDEBOARD_APP_DATA: appDataDir(),
494
+ [SIDEBOARD_MCP_PROFILE_ENV]: orchId ? "orchestration" : "worktree"
495
+ };
496
+ if (orchId) env.SIDEBOARD_ORCHESTRATOR_THREAD_ID = orchId;
497
+ if (threadId) env[SIDEBOARD_THREAD_ID_ENV] = threadId;
498
+ if (opts.rpcNativeTools) env[AGENT_RPC_NATIVE_ENV] = "1";
499
+ return env;
500
+ }
501
+ var AGENT_RPC_PILOT_MCP_TOOLS = [
502
+ "present_artifact",
503
+ "wait_for_job",
504
+ "stop_job"
505
+ ];
506
+ function shouldRegisterMcpWaitForTurn(env = process.env) {
507
+ return !agentRpcOwnsPilotTools(env);
508
+ }
509
+ function worktreeMcpToolNames(env = process.env) {
510
+ if (!agentRpcOwnsPilotTools(env)) return WORKTREE_MCP_TOOLS;
511
+ const omit = new Set(AGENT_RPC_PILOT_MCP_TOOLS);
512
+ return WORKTREE_MCP_TOOLS.filter((name) => !omit.has(name));
513
+ }
514
+ var WORKTREE_MCP_TOOLS = [
515
+ "present_artifact",
516
+ "ask_user",
517
+ "present_plan",
518
+ "present_schema",
519
+ "present_files",
520
+ "wait_for_job",
521
+ "stop_job",
522
+ "list_run_scripts",
523
+ "run_dev_script",
524
+ "stop_dev_script",
525
+ "get_run_log",
526
+ "get_orchestrator",
527
+ "notify_orchestrator",
528
+ "set_workspace_tags",
529
+ "set_wake_on_github_edges",
530
+ "get_viewer_context",
531
+ "update_viewer_context",
532
+ "list_env",
533
+ "set_env",
534
+ "delete_env",
535
+ "list_schedules",
536
+ "create_schedule",
537
+ "update_schedule",
538
+ "delete_schedule",
539
+ "run_schedule",
540
+ "list_follow_ups",
541
+ "create_follow_up",
542
+ "delete_follow_up",
543
+ "list_order",
544
+ "show_plan",
545
+ "set_dependency",
546
+ "clear_dependency",
547
+ "satisfy_dependency"
548
+ ];
549
+ var WORKTREE_GITHUB_MCP_TOOLS = [
550
+ "github_search_issues",
551
+ "github_list_projects",
552
+ "github_get_issue",
553
+ "github_download_attachment",
554
+ "github_comment",
555
+ "github_update_issue",
556
+ "github_create_issue"
557
+ ];
558
+ var WORKTREE_LINEAR_MCP_TOOLS = [
559
+ "linear_list_teams",
560
+ "linear_list_projects",
561
+ "linear_search_issues",
562
+ "linear_get_issue",
563
+ "linear_download_attachment",
564
+ "linear_create_issue",
565
+ "linear_update_issue",
566
+ "linear_comment"
567
+ ];
568
+ var WORKTREE_ABLETIME_MCP_TOOLS = [
569
+ "abletime_orientation",
570
+ "abletime_list_projects",
571
+ "abletime_list_tasks",
572
+ "abletime_search_tasks",
573
+ "abletime_get_task",
574
+ "abletime_download_attachment",
575
+ "abletime_comment",
576
+ "abletime_update_task",
577
+ "abletime_create_task",
578
+ "abletime_ensure_task"
579
+ ];
580
+ function sideboardMcpProfile(env = process.env) {
581
+ return env[SIDEBOARD_MCP_PROFILE_ENV]?.trim().toLowerCase() === "worktree" ? "worktree" : "orchestration";
564
582
  }
565
- function isCleanMcpConnect(status) {
566
- return /^(connected|ok|ready|success)$/i.test(status.trim());
583
+
584
+ // src/agents/codex-mcp-profile.ts
585
+ import { randomBytes } from "crypto";
586
+ import { mkdirSync, writeFileSync } from "fs";
587
+ import { homedir as homedir2 } from "os";
588
+ import { join as join2 } from "path";
589
+ function isCodexSecretEnvKey(key) {
590
+ return /token|secret|password|credential|oauth|api_key|_key$/i.test(key);
567
591
  }
568
- function isMcpAuthStatus(status) {
569
- return /needs[_-]?auth|needs authentication|unauthorized|not authenticated|authrequired/i.test(
570
- status
571
- );
592
+ function tomlBasicString(value) {
593
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`;
572
594
  }
573
- function isSideboardMcpName(name) {
574
- return /^sideboard$/i.test(name.trim()) || /^mcp__sideboard$/i.test(name.trim());
595
+ function secretEnv(env) {
596
+ if (!env) return void 0;
597
+ const out = { ...env };
598
+ delete out.ELECTRON_RUN_AS_NODE;
599
+ return Object.keys(out).length > 0 ? out : void 0;
575
600
  }
576
- function isVendorClaudeAiMcpName(name) {
577
- return /^claude\.ai\b/i.test(name.trim()) || /^mcp__claude_ai_/i.test(name.trim());
601
+ function writeCodexMcpSecretProfile(servers) {
602
+ const blocks = [];
603
+ for (const s of servers) {
604
+ const env = secretEnv(s.env);
605
+ if (!env) continue;
606
+ const secrets = Object.entries(env).filter(([key]) => isCodexSecretEnvKey(key));
607
+ if (secrets.length === 0) continue;
608
+ const lines = [`[mcp_servers.${s.name}.env]`];
609
+ for (const [key, value] of secrets) lines.push(`${key} = ${tomlBasicString(value)}`);
610
+ blocks.push(lines.join("\n"));
611
+ }
612
+ if (blocks.length === 0) return null;
613
+ const home = process.env.CODEX_HOME?.trim() || join2(homedir2(), ".codex");
614
+ mkdirSync(home, { recursive: true, mode: 448 });
615
+ const profile = `sideboard-${randomBytes(8).toString("hex")}`;
616
+ const file = join2(home, `${profile}.config.toml`);
617
+ writeFileSync(file, `${blocks.join("\n\n")}
618
+ `, { mode: 384 });
619
+ return { profile, file };
578
620
  }
579
- function sideboardMcpOk(servers) {
580
- const row = servers.find((server) => isSideboardMcpName(server.name));
581
- return Boolean(row && isCleanMcpConnect(row.status));
621
+
622
+ // src/agents/injected-mcp.ts
623
+ var SIDEBOARD_MCP_ALLOWED_TOOLS = [
624
+ "mcp__sideboard",
625
+ "mcp__sideboard__*"
626
+ ];
627
+ var SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS = [
628
+ "mcp__sideboard__present_artifact",
629
+ "mcp__sideboard__present_schema",
630
+ "mcp__sideboard__present_files",
631
+ "mcp__sideboard__ask_user",
632
+ "mcp__sideboard__present_plan",
633
+ "mcp__sideboard__wait_for_job",
634
+ "mcp__sideboard__stop_job",
635
+ "mcp__sideboard__list_run_scripts",
636
+ "mcp__sideboard__run_dev_script",
637
+ "mcp__sideboard__stop_dev_script",
638
+ "mcp__sideboard__get_run_log",
639
+ "mcp__sideboard__get_orchestrator",
640
+ "mcp__sideboard__notify_orchestrator",
641
+ "mcp__sideboard__set_workspace_tags",
642
+ "mcp__sideboard__set_wake_on_github_edges",
643
+ "mcp__sideboard__get_viewer_context",
644
+ "mcp__sideboard__update_viewer_context",
645
+ "mcp__sideboard__list_env",
646
+ "mcp__sideboard__set_env",
647
+ "mcp__sideboard__delete_env",
648
+ "mcp__sideboard__list_schedules",
649
+ "mcp__sideboard__create_schedule",
650
+ "mcp__sideboard__update_schedule",
651
+ "mcp__sideboard__delete_schedule",
652
+ "mcp__sideboard__run_schedule",
653
+ "mcp__sideboard__list_follow_ups",
654
+ "mcp__sideboard__create_follow_up",
655
+ "mcp__sideboard__delete_follow_up",
656
+ "mcp__sideboard__list_order",
657
+ "mcp__sideboard__show_plan",
658
+ "mcp__sideboard__set_dependency",
659
+ "mcp__sideboard__clear_dependency",
660
+ "mcp__sideboard__satisfy_dependency",
661
+ "mcp__sideboard__posthog_api"
662
+ ];
663
+ var SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS = ["mcp__sideboard__github_*"];
664
+ var SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS = ["mcp__sideboard__linear_*"];
665
+ var SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS = ["mcp__sideboard__abletime_*"];
666
+ function sideboardWorktreeAllowedTools(opts) {
667
+ const out = SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS.filter(
668
+ (tool) => (opts?.planMode || tool !== "mcp__sideboard__present_plan") && (opts?.posthog || tool !== "mcp__sideboard__posthog_api")
669
+ );
670
+ if (opts?.github !== false) out.push(...SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS);
671
+ if (opts?.linear) out.push(...SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS);
672
+ if (opts?.abletime) out.push(...SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS);
673
+ return out;
582
674
  }
583
- function sideboardServiceForClaudeConnector(name) {
584
- const raw = name.trim();
585
- if (!raw || isSideboardMcpName(raw)) return null;
586
- const pluginLike = /^(?:plugin[:_]|mcp__plugin_|claude\.ai\s|(?:mcp__)?claude_ai_)/i.test(raw);
587
- const doubled = raw.match(/^mcp_([a-z0-9]+)_([a-z0-9]+)$/i);
588
- if (!pluginLike && !(doubled && doubled[1].toLowerCase() === doubled[2].toLowerCase())) {
589
- return null;
675
+ var BRIGHTSY_MCP_ALLOWED_TOOLS = [
676
+ "mcp__brightsy",
677
+ "mcp__brightsy__*"
678
+ ];
679
+ var brightsyMcpCommandCache = null;
680
+ async function resolveBrightsyMcpCommand() {
681
+ const now = Date.now();
682
+ if (brightsyMcpCommandCache && now - brightsyMcpCommandCache.at < 6e4 && brightsyMcpCommandCache.command) {
683
+ return brightsyMcpCommandCache.command;
590
684
  }
591
- let body = raw;
592
- if (/^claude\.ai\s+/i.test(body)) body = body.replace(/^claude\.ai\s+/i, "");
593
- else if (/^(?:mcp__)?claude_ai_/i.test(body)) body = body.replace(/^(?:mcp__)?claude_ai_/i, "");
594
- else if (/^mcp__plugin_/i.test(body)) body = body.slice("mcp__plugin_".length);
595
- else if (/^plugin_/i.test(body)) body = body.slice("plugin_".length);
596
- else if (/^plugin:/i.test(body)) body = body.slice("plugin:".length);
597
- else if (/^mcp_/i.test(body)) body = body.slice("mcp_".length);
598
- const head = body.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
599
- if (!head || !SIDEBOARD_CONNECTOR_SERVICES.includes(head)) return null;
600
- return head;
685
+ const which = await run("which", ["brightsy-mcp"], { reject: false });
686
+ const command = which.exitCode === 0 && which.stdout.trim() ? "brightsy-mcp" : "npx";
687
+ brightsyMcpCommandCache = { at: now, command };
688
+ return command;
601
689
  }
602
- function claudeConnectorCoverage() {
603
- let github = false;
690
+ function isBrightsyConnected() {
604
691
  try {
605
- github = githubAgentAuthReady();
692
+ loadBrightsyConfig();
693
+ return true;
606
694
  } catch {
607
- github = false;
695
+ return false;
608
696
  }
609
- let linear = false;
610
- let posthog = false;
611
- let vercel = false;
612
- let supabase = false;
613
- let sentry = false;
614
- try {
615
- linear = isLinearConnected();
616
- posthog = isPosthogConnected();
617
- const integrations = loadAppSettings().integrations ?? {};
618
- if (integrations.githubPat?.trim()) github = true;
619
- vercel = Boolean(integrations.vercelToken?.trim());
620
- supabase = Boolean(integrations.supabaseAccessToken?.trim());
621
- sentry = Boolean(integrations.sentryAuthToken?.trim());
622
- } catch {
697
+ }
698
+ var BRIGHTSY_WORD = /(?<![a-z0-9_-])brightsy(?![a-z0-9_-])/i;
699
+ function promptMentionsBrightsy(text) {
700
+ return BRIGHTSY_WORD.test(text ?? "");
701
+ }
702
+ function isBrightsyMcpToolName(name) {
703
+ const n = name.toLowerCase();
704
+ return n === "brightsy" || n.startsWith("mcp__brightsy") || n.startsWith("brightsy_");
705
+ }
706
+ function toolInputUsesBrightsyDatasource(input) {
707
+ const ds = input?.datasource;
708
+ return typeof ds === "string" && ds.toLowerCase() === "brightsy";
709
+ }
710
+ function messageUsedBrightsyMcp(msg) {
711
+ if (msg.role === "user" && promptMentionsBrightsy(msg.text)) return true;
712
+ for (const part of msg.parts ?? []) {
713
+ if (part.type !== "tool") continue;
714
+ if (isBrightsyMcpToolName(part.name)) return true;
715
+ if (/present_(schema|files)$/i.test(part.name) && toolInputUsesBrightsyDatasource(part.input)) {
716
+ return true;
717
+ }
623
718
  }
624
- return { github, linear, posthog, vercel, supabase, sentry };
719
+ return false;
625
720
  }
626
- function isNotableMcpInitStatus(server, sideboardOk, coverage) {
627
- if (isCleanMcpConnect(server.status)) return false;
628
- if (isSideboardMcpName(server.name)) return true;
629
- if (isMcpAuthStatus(server.status)) return false;
630
- const service = sideboardServiceForClaudeConnector(server.name);
631
- if (service) return !(sideboardOk && coverage[service]);
632
- if (isVendorClaudeAiMcpName(server.name)) return false;
633
- return true;
721
+ function threadRequestsBrightsyMcp(thread) {
722
+ return (thread?.messages ?? []).some(messageUsedBrightsyMcp);
634
723
  }
635
-
636
- // src/mcp-ui/host.ts
637
- import { createHash } from "crypto";
638
- import { homedir as homedir5 } from "os";
639
-
640
- // src/agents/orch-mcp-isolation.ts
641
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
642
-
643
- // src/agents/claude-plugins.ts
644
- import { existsSync as existsSync2, readFileSync } from "fs";
645
- import { homedir } from "os";
646
- import { isAbsolute, join, relative, resolve } from "path";
647
-
648
- // src/mcp-ui/meta.ts
649
- var HTML_MAX = 15e5;
650
- function matchClaudeMcpTool(toolName, serverNames) {
651
- const name = toolName.trim();
652
- if (!name.startsWith("mcp__")) return null;
653
- const ranked = [...serverNames].filter((s) => s.trim()).sort((a, b) => b.length - a.length);
654
- for (const server of ranked) {
655
- const prefix = `mcp__${server}__`;
656
- if (!name.startsWith(prefix)) continue;
657
- const tool = name.slice(prefix.length).trim();
658
- if (!tool) continue;
659
- return { server, tool };
724
+ function shouldInjectBrightsyMcp(thread, opts) {
725
+ if (!(opts?.connected ?? isBrightsyConnected())) return false;
726
+ if (opts?.orchestrator) return true;
727
+ const alwaysOn = opts?.alwaysOnWorktree ?? Boolean(loadAppSettings().brightsy?.injectWorktreeMcp);
728
+ if (alwaysOn) return true;
729
+ return threadRequestsBrightsyMcp(thread);
730
+ }
731
+ function mcpLaunch(cmd, name, env) {
732
+ if (cmd === "brightsy-mcp") {
733
+ return { name, command: "brightsy-mcp", ...env ? { env } : {} };
734
+ }
735
+ return {
736
+ name,
737
+ command: "npx",
738
+ args: ["-y", "@brightsy/mcp-server"],
739
+ ...env ? { env } : {}
740
+ };
741
+ }
742
+ function teamEnv(team) {
743
+ const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
744
+ return {
745
+ BRIGHTSY_API_TOKEN: team.access_token,
746
+ ...team.refresh_token ? { BRIGHTSY_REFRESH_TOKEN: team.refresh_token } : {},
747
+ ...team.oauth_client_id ? { BRIGHTSY_OAUTH_CLIENT_ID: team.oauth_client_id } : {},
748
+ BRIGHTSY_ACCOUNT_ID: team.id,
749
+ BRIGHTSY_API_URL: endpoint
750
+ };
751
+ }
752
+ function brightsyMcpAllowedTools(serverNames) {
753
+ const out = [];
754
+ for (const name of serverNames) {
755
+ out.push(`mcp__${name}`, `mcp__${name}__*`);
660
756
  }
661
- return null;
757
+ return out;
662
758
  }
663
- function parseMcpServerLaunch(entry) {
664
- const command = typeof entry.command === "string" ? entry.command.trim() : "";
665
- if (command) {
666
- const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === "string") : [];
667
- const env = stringRecord(entry.env);
668
- const cwd = typeof entry.cwd === "string" && entry.cwd.trim() ? entry.cwd.trim() : void 0;
669
- return {
670
- kind: "stdio",
671
- command,
672
- args,
673
- ...env ? { env } : {},
674
- ...cwd ? { cwd } : {}
675
- };
759
+ function corePackageDir() {
760
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
761
+ if (cjsDir) return cjsDir;
762
+ try {
763
+ const url = import.meta.url;
764
+ if (typeof url === "string" && url.length > 0) {
765
+ return dirname(fileURLToPath(url));
766
+ }
767
+ } catch {
676
768
  }
677
- const url = typeof entry.url === "string" ? entry.url.trim() : "";
678
- if (!url) return null;
679
- let parsed;
680
769
  try {
681
- parsed = new URL(url);
770
+ const req = createRequire(join3(process.cwd(), "package.json"));
771
+ return dirname(req.resolve("@sideboard-ai/core"));
682
772
  } catch {
683
- return null;
773
+ return process.cwd();
684
774
  }
685
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
686
- const type = typeof entry.type === "string" ? entry.type.trim().toLowerCase() : "";
687
- const headers = stringRecord(entry.headers);
688
- return {
689
- kind: type === "sse" ? "sse" : "http",
690
- url: parsed.toString(),
691
- ...headers ? { headers } : {}
692
- };
693
775
  }
694
- function uiResourceUriFromMeta(meta) {
695
- const rec = asRecord(meta);
696
- const nested = asRecord(rec.ui);
697
- const fromNested = typeof nested.resourceUri === "string" ? nested.resourceUri.trim() : "";
698
- const legacy = typeof rec["ui/resourceUri"] === "string" ? rec["ui/resourceUri"].trim() : "";
699
- const uri = fromNested || legacy;
700
- return uri.startsWith("ui://") ? uri : null;
776
+ function findSideboardMcpJsEntry() {
777
+ const override = process.env.SIDEBOARD_MCP_ENTRY?.trim() || process.env.SIDEBOARD_CLI?.trim();
778
+ if (override && existsSync2(override)) return override;
779
+ const packaged = packagedMcpStdioPath();
780
+ if (packaged) return packaged;
781
+ let dir = corePackageDir();
782
+ for (let i = 0; i < 10; i++) {
783
+ const candidates = [
784
+ join3(dir, "mcp/run-stdio.js"),
785
+ join3(dir, "mcp/run-stdio.cjs"),
786
+ join3(dir, "dist/mcp/run-stdio.js"),
787
+ join3(dir, "dist/mcp/run-stdio.cjs"),
788
+ join3(dir, "packages/core/dist/mcp/run-stdio.js"),
789
+ join3(dir, "packages/cli/dist/index.js"),
790
+ join3(dir, "cli/dist/index.js")
791
+ ];
792
+ for (const p of candidates) {
793
+ if (existsSync2(p) && !isAsarPath(p)) return p;
794
+ }
795
+ const parent = dirname(dir);
796
+ if (parent === dir) break;
797
+ dir = parent;
798
+ }
799
+ return null;
701
800
  }
702
- function cspFromMeta(meta) {
703
- const ui = asRecord(asRecord(meta).ui);
704
- const csp = asRecord(ui.csp);
705
- const connectDomains = originList(csp.connectDomains);
706
- const resourceDomains = originList(csp.resourceDomains);
707
- const frameDomains = originList(csp.frameDomains);
708
- const baseUriDomains = originList(csp.baseUriDomains);
709
- if (!connectDomains?.length && !resourceDomains?.length && !frameDomains?.length && !baseUriDomains?.length) {
710
- return void 0;
801
+ async function resolveSideboardMcpServer() {
802
+ const entry = findSideboardMcpJsEntry();
803
+ if (entry) {
804
+ const isCli = /[/\\]cli[/\\]dist[/\\]index\.js$/.test(entry);
805
+ const scriptArgs = isCli ? [entry, "mcp"] : [entry];
806
+ const launch = applyNodeLaunch(await resolveNodeLaunch(entry), scriptArgs);
807
+ if (launch.file !== "/bin/sh" && !isElectronLikeCommand(launch.file)) {
808
+ return {
809
+ name: "sideboard",
810
+ command: launch.file,
811
+ args: launch.args,
812
+ ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {}
813
+ };
814
+ }
711
815
  }
712
- return {
713
- ...connectDomains?.length ? { connectDomains } : {},
714
- ...resourceDomains?.length ? { resourceDomains } : {},
715
- ...frameDomains?.length ? { frameDomains } : {},
716
- ...baseUriDomains?.length ? { baseUriDomains } : {}
717
- };
816
+ const which = await run("which", ["sideboard"], { reject: false });
817
+ if (which.exitCode === 0 && which.stdout.trim()) {
818
+ return { name: "sideboard", command: which.stdout.trim(), args: ["mcp"] };
819
+ }
820
+ return { name: "sideboard", command: "sideboard", args: ["mcp"] };
718
821
  }
719
- function htmlFromResourceContent(content) {
720
- const uri = content.uri?.trim() ?? "";
721
- if (!uri.startsWith("ui://")) return null;
722
- const mimeType = content.mimeType?.trim() || "text/html";
723
- if (!isHtmlMime(mimeType)) return null;
724
- const html = htmlText(content.text, content.blob);
725
- if (!html) return null;
726
- return { uri, mimeType, html };
822
+ async function buildInjectedMcpServers(opts) {
823
+ const servers = [];
824
+ if (opts.includeSideboard) {
825
+ const sideboard = await resolveSideboardMcpServer();
826
+ sideboard.env = {
827
+ ...sideboard.env ?? {},
828
+ ...injectedSideboardMcpEnv(opts)
829
+ };
830
+ try {
831
+ mergeAgentGitAuthEnv(
832
+ sideboard.env,
833
+ await resolveAgentGitAuthEnv(sideboard.env)
834
+ );
835
+ } catch {
836
+ }
837
+ applyAgentRunnerHeapEnv(sideboard.env);
838
+ servers.push(sideboard);
839
+ }
840
+ if (opts.includeBrightsy && isBrightsyConnected()) {
841
+ const cmd = await resolveBrightsyMcpCommand();
842
+ const teams = await ensureConnectedBrightsyTeamTokens();
843
+ if (teams.length > 0) {
844
+ const used = /* @__PURE__ */ new Set();
845
+ for (const team of teams) {
846
+ let name = brightsyMcpServerName(team.slug);
847
+ if (used.has(name)) name = `${name}_${team.id.slice(0, 8)}`;
848
+ used.add(name);
849
+ servers.push(mcpLaunch(cmd, name, teamEnv(team)));
850
+ }
851
+ } else {
852
+ servers.push(mcpLaunch(cmd, "brightsy"));
853
+ }
854
+ }
855
+ return servers;
727
856
  }
728
- function mcpUiContentSecurityPolicy(csp) {
729
- const resource = (csp?.resourceDomains ?? []).join(" ");
730
- const connect = (csp?.connectDomains ?? []).join(" ");
731
- const frames = csp?.frameDomains?.length ? csp.frameDomains.join(" ") : "'none'";
732
- const base = csp?.baseUriDomains?.length ? csp.baseUriDomains.join(" ") : "'none'";
733
- const connectSrc = connect ? `'self' ${connect}`.trim() : "'none'";
734
- return [
735
- "default-src 'none'",
736
- `script-src 'self' 'unsafe-inline' ${resource}`.trim(),
737
- `style-src 'self' 'unsafe-inline' ${resource}`.trim(),
738
- `img-src 'self' data: ${resource}`.trim(),
739
- `font-src 'self' ${resource}`.trim(),
740
- `connect-src ${connectSrc}`,
741
- `media-src 'self' data: ${resource}`.trim(),
742
- `frame-src ${frames}`,
743
- `base-uri ${base}`,
744
- "object-src 'none'"
745
- ].join("; ");
857
+ function cursorSafeMcpLaunch(command, args) {
858
+ if (process.platform === "win32") {
859
+ return args && args.length > 0 ? { command, args } : { command };
860
+ }
861
+ const unwrapped = unwrapStrippedElectronLaunch(command, args);
862
+ const file = unwrapped?.file ?? command;
863
+ const fileArgs = unwrapped?.args ?? args ?? [];
864
+ return fileArgs.length > 0 ? { command: file, args: fileArgs } : { command: file };
746
865
  }
747
- function htmlText(text, blob) {
748
- if (typeof text === "string" && text.trim()) {
749
- return text.length <= HTML_MAX ? text : null;
866
+ function mcpSpawnEnv(env) {
867
+ if (!env) return void 0;
868
+ const out = { ...env };
869
+ delete out.ELECTRON_RUN_AS_NODE;
870
+ delete out.ELECTRON_RUN_AS_NODE;
871
+ return Object.keys(out).length > 0 ? out : void 0;
872
+ }
873
+ function toCursorMcpServers(servers) {
874
+ const out = {};
875
+ for (const s of servers) {
876
+ const env = mcpSpawnEnv(s.env);
877
+ const launch = cursorSafeMcpLaunch(s.command, s.args);
878
+ out[s.name] = {
879
+ type: "stdio",
880
+ command: launch.command,
881
+ ...launch.args && launch.args.length > 0 ? { args: launch.args } : {},
882
+ ...env ? { env } : {}
883
+ };
750
884
  }
751
- if (typeof blob !== "string" || !blob.trim()) return null;
752
- try {
753
- const decoded = decodeBase64(blob.trim());
754
- if (!decoded.trim() || decoded.length > HTML_MAX) return null;
755
- return decoded;
756
- } catch {
757
- return null;
885
+ return out;
886
+ }
887
+ function toCodexMcpConfigArgs(servers) {
888
+ const args = [];
889
+ for (const s of servers) {
890
+ const prefix = `mcp_servers.${s.name}`;
891
+ args.push("-c", `${prefix}.command=${JSON.stringify(s.command)}`);
892
+ if (s.args?.length) {
893
+ args.push("-c", `${prefix}.args=${JSON.stringify(s.args)}`);
894
+ }
895
+ const env = mcpSpawnEnv(s.env);
896
+ if (env) {
897
+ for (const [key, value] of Object.entries(env)) {
898
+ if (isCodexSecretEnvKey(key)) continue;
899
+ args.push("-c", `${prefix}.env.${key}=${JSON.stringify(value)}`);
900
+ }
901
+ }
902
+ args.push("-c", `${prefix}.default_tools_approval_mode=${JSON.stringify("approve")}`);
903
+ args.push("-c", `${prefix}.tool_timeout_sec=300`);
904
+ args.push("-c", `${prefix}.startup_timeout_sec=30`);
758
905
  }
906
+ return args;
759
907
  }
760
- function decodeBase64(blob) {
761
- if (typeof Buffer !== "undefined") return Buffer.from(blob, "base64").toString("utf8");
762
- const bin = atob(blob);
763
- const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
764
- return new TextDecoder().decode(bytes);
908
+ function toOpencodeMcpConfigContent(servers, opts) {
909
+ const mcp = {};
910
+ for (const s of servers) {
911
+ const env = mcpSpawnEnv(s.env);
912
+ mcp[s.name] = {
913
+ type: "local",
914
+ command: [s.command, ...s.args ?? []],
915
+ enabled: true,
916
+ ...env ? { environment: env } : {}
917
+ };
918
+ }
919
+ for (const name of opts?.disableNames ?? []) {
920
+ const key = name.trim();
921
+ if (!key || mcp[key]?.enabled === true) continue;
922
+ mcp[key] = { ...mcp[key], enabled: false };
923
+ }
924
+ return JSON.stringify({ mcp });
765
925
  }
766
- function isHtmlMime(mime) {
767
- const base = mime.split(";")[0]?.trim().toLowerCase() ?? "";
768
- return base === "text/html";
926
+ function stripElectronFromUserMcpEntry(entry) {
927
+ const next = { ...entry };
928
+ const env = next.env;
929
+ if (!env || typeof env !== "object" || Array.isArray(env)) return next;
930
+ const cleaned = { ...env };
931
+ delete cleaned.ELECTRON_RUN_AS_NODE;
932
+ next.env = cleaned;
933
+ return next;
769
934
  }
770
- function originList(value) {
771
- if (!Array.isArray(value)) return void 0;
772
- const out = [];
773
- for (const item of value) {
774
- if (typeof item !== "string") continue;
775
- const origin = originToken(item);
776
- if (origin && !out.includes(origin)) out.push(origin);
935
+ function mcpServersRecord(servers, extraServers) {
936
+ const mcpServers = {};
937
+ for (const s of servers) {
938
+ const env = mcpSpawnEnv(s.env);
939
+ mcpServers[s.name] = {
940
+ command: s.command,
941
+ ...s.args ? { args: s.args } : {},
942
+ ...env ? { env } : {}
943
+ };
777
944
  }
778
- return out;
779
- }
780
- function originToken(value) {
781
- const trimmed = value.trim();
782
- if (/^(https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?$/i.test(trimmed)) return trimmed;
783
- try {
784
- const url = new URL(trimmed);
785
- if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "wss:" && url.protocol !== "ws:") {
786
- return null;
945
+ if (extraServers) {
946
+ for (const [rawName, entry] of Object.entries(extraServers)) {
947
+ const name = rawName.trim();
948
+ if (!name || mcpServers[name] || !entry) continue;
949
+ mcpServers[name] = stripElectronFromUserMcpEntry(entry);
787
950
  }
788
- return url.origin;
789
- } catch {
790
- return null;
791
951
  }
952
+ return mcpServers;
792
953
  }
793
- function stringRecord(value) {
794
- const rec = asRecord(value);
795
- const out = {};
796
- for (const [key, item] of Object.entries(rec)) {
797
- if (typeof item === "string") out[key] = item;
798
- }
799
- return Object.keys(out).length > 0 ? out : void 0;
954
+ function writeMcpServersConfig(servers, extraServers) {
955
+ const mcpServers = mcpServersRecord(servers, extraServers);
956
+ if (Object.keys(mcpServers).length === 0) return null;
957
+ const dir = mkdtempSync(join3(tmpdir(), "sideboard-mcp-"));
958
+ const cfgPath = join3(dir, "mcp.json");
959
+ writeFileSync2(cfgPath, JSON.stringify({ mcpServers }, null, 2), { mode: 384 });
960
+ return cfgPath;
800
961
  }
801
- function asRecord(value) {
802
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
803
- return value;
962
+ async function writeInjectedMcpConfig(opts) {
963
+ return writeMcpServersConfig(await buildInjectedMcpServers(opts));
804
964
  }
805
965
 
806
- // src/agents/claude-plugins.ts
807
- function claudePluginServerId(pluginName, serverName) {
808
- return `plugin_${pluginName}_${serverName}`.replace(/[^A-Za-z0-9_-]/g, "_");
966
+ // src/agents/user-mcp-config.ts
967
+ function userCursorMcpConfigPath() {
968
+ return join4(homedir3(), ".cursor", "mcp.json");
809
969
  }
810
- function listEnabledClaudePluginMcpServers(opts) {
811
- const home = opts?.home ?? homedir();
812
- const pluginsRoot = claudePluginsRoot(home);
813
- const enabled = enabledPluginIds(home, opts?.projectDirs ?? []);
814
- const installed = readInstalledPlugins(join(pluginsRoot, "installed_plugins.json"));
815
- const out = {};
816
- for (const [id, on] of enabled) {
817
- if (!on) continue;
818
- const root = installPathFor(id, installed);
819
- if (!root || !existsSync2(root)) continue;
820
- const pluginName = manifestName(root) || id.split("@")[0]?.trim() || "";
821
- if (!pluginName) continue;
822
- const dataDir = join(pluginsRoot, "data", pluginDataId(id));
823
- for (const [serverName, entry] of Object.entries(loadPluginMcpServers(root))) {
824
- const expanded = expandPluginEntry(entry, root, dataDir);
825
- if (!parseMcpServerLaunch(expanded)) continue;
826
- const key = claudePluginServerId(pluginName, serverName);
827
- if (!key || key === "plugin__") continue;
828
- out[key] = expanded;
829
- }
830
- }
831
- return out;
970
+ function userClaudeMcpConfigPath() {
971
+ return join4(homedir3(), ".claude.json");
832
972
  }
833
- function claudePluginsRoot(home) {
834
- const override = process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim();
835
- if (override && isAbsolute(override)) return override;
836
- return join(home, ".claude", "plugins");
973
+ function asObject(value) {
974
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
975
+ return { ...value };
837
976
  }
838
- function pluginDataId(pluginId) {
839
- return pluginId.replace(/[^A-Za-z0-9_-]/g, "-");
977
+ function stripElectronSpawnEnv(env) {
978
+ if (!env) return void 0;
979
+ const next = { ...env };
980
+ delete next.ELECTRON_RUN_AS_NODE;
981
+ delete next.ELECTRON_RUN_AS_NODE;
982
+ return Object.keys(next).length > 0 ? next : void 0;
840
983
  }
841
- function enabledPluginIds(home, projectDirs) {
842
- const enabled = /* @__PURE__ */ new Map();
843
- applyEnabled(enabled, readEnabledPlugins(join(home, ".claude", "settings.json")));
844
- const dirs = [...new Set(projectDirs.map((dir) => dir.trim()).filter(Boolean))];
845
- for (const dir of dirs) {
846
- applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.json")));
847
- }
848
- for (const dir of dirs) {
849
- applyEnabled(enabled, readEnabledPlugins(join(dir, ".claude", "settings.local.json")));
984
+ function mergeSideboardIntoMcpServersJson(existing, sideboard) {
985
+ const root = asObject(existing);
986
+ const servers = asObject(root.mcpServers);
987
+ const env = stripElectronSpawnEnv(sideboard.env);
988
+ servers.sideboard = {
989
+ type: "stdio",
990
+ command: sideboard.command,
991
+ ...sideboard.args && sideboard.args.length > 0 ? { args: sideboard.args } : {},
992
+ ...env ? { env } : {}
993
+ };
994
+ return { ...root, mcpServers: servers };
995
+ }
996
+ function writeMergedMcpServersJson(configPath, sideboard) {
997
+ let existing = {};
998
+ if (existsSync3(configPath)) {
999
+ try {
1000
+ existing = JSON.parse(readFileSync2(configPath, "utf8"));
1001
+ } catch {
1002
+ existing = {};
1003
+ }
850
1004
  }
851
- return enabled;
1005
+ const next = mergeSideboardIntoMcpServersJson(existing, sideboard);
1006
+ mkdirSync2(dirname2(configPath), { recursive: true });
1007
+ writeFileSync3(configPath, `${JSON.stringify(next, null, 2)}
1008
+ `);
852
1009
  }
853
- function applyEnabled(into, next) {
854
- for (const [id, on] of Object.entries(next)) {
855
- const key = id.trim();
856
- if (!key) continue;
857
- into.set(key, on);
1010
+ function launchFromResolved(server) {
1011
+ return {
1012
+ command: server.command,
1013
+ args: server.args,
1014
+ env: {
1015
+ ...server.env ?? {},
1016
+ SIDEBOARD_APP_DATA: appDataDir()
1017
+ }
1018
+ };
1019
+ }
1020
+ async function registerPackagedUserMcpClients() {
1021
+ const launch = launchFromResolved(await resolveSideboardMcpServer());
1022
+ const cursor = userCursorMcpConfigPath();
1023
+ writeMergedMcpServersJson(cursor, launch);
1024
+ const claude = userClaudeMcpConfigPath();
1025
+ if (existsSync3(claude)) {
1026
+ writeMergedMcpServersJson(claude, launch);
1027
+ return { cursor, claude };
858
1028
  }
1029
+ return { cursor };
859
1030
  }
860
- function readEnabledPlugins(path) {
861
- const root = readJson(path);
862
- const raw = root.enabledPlugins;
863
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
864
- const out = {};
865
- for (const [id, value] of Object.entries(raw)) {
866
- if (value === true || value === false) out[id] = value;
1031
+
1032
+ // src/agents/orch-mcp-isolation.ts
1033
+ function isInjectedOrchMcpName(name) {
1034
+ const n = name.trim().toLowerCase();
1035
+ return n === "sideboard" || n === "brightsy" || n.startsWith("brightsy_");
1036
+ }
1037
+ function asObject2(value) {
1038
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1039
+ return value;
1040
+ }
1041
+ function listMcpNamesFromJsonMap(raw, key) {
1042
+ return Object.keys(asObject2(asObject2(raw)[key])).filter((n) => n.trim());
1043
+ }
1044
+ function listMcpNamesFromCodexToml(text) {
1045
+ try {
1046
+ const parsed = parseToml(text);
1047
+ return Object.keys(asObject2(parsed.mcp_servers)).filter((n) => n.trim());
1048
+ } catch {
1049
+ return [];
867
1050
  }
868
- return out;
869
1051
  }
870
- function readInstalledPlugins(path) {
871
- const root = readJson(path);
872
- const plugins = root.plugins;
873
- if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) return {};
874
- const out = {};
875
- for (const [id, value] of Object.entries(plugins)) {
876
- const rows = Array.isArray(value) ? value : [value];
877
- const installs = [];
878
- for (const row of rows) {
879
- if (!row || typeof row !== "object" || Array.isArray(row)) continue;
880
- const installPath = row.installPath;
881
- installs.push({
882
- ...typeof installPath === "string" && installPath.trim() ? { installPath: installPath.trim() } : {}
883
- });
884
- }
885
- if (installs.length) out[id] = installs;
1052
+ function readJsonObject(path) {
1053
+ try {
1054
+ return JSON.parse(readFileSync3(path, "utf8"));
1055
+ } catch {
1056
+ return {};
886
1057
  }
887
- return out;
888
1058
  }
889
- function installPathFor(id, installed) {
890
- const rows = installed[id] ?? [];
891
- for (let i = rows.length - 1; i >= 0; i--) {
892
- const path = rows[i]?.installPath;
893
- if (path && existsSync2(path)) return path;
1059
+ function readText(path) {
1060
+ try {
1061
+ return readFileSync3(path, "utf8");
1062
+ } catch {
1063
+ return "";
894
1064
  }
895
- return null;
896
1065
  }
897
- function manifestName(root) {
898
- const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
899
- return typeof manifest.name === "string" ? manifest.name.trim() : "";
1066
+ function userCodexConfigPaths(home = homedir4()) {
1067
+ const paths = [
1068
+ join5(home, ".codex", "config.toml"),
1069
+ join5(home, ".config", "codex", "config.toml")
1070
+ ];
1071
+ const codexHome = process.env.CODEX_HOME?.trim();
1072
+ if (codexHome) paths.unshift(join5(codexHome, "config.toml"));
1073
+ return paths;
900
1074
  }
901
- function loadPluginMcpServers(root) {
902
- const servers = {};
903
- mergeServerMap(servers, serversFromFile(join(root, ".mcp.json"), root));
904
- const manifest = readJson(join(root, ".claude-plugin", "plugin.json"));
905
- mergeServerMap(servers, serversFromManifest(manifest.mcpServers, root));
906
- return servers;
1075
+ function userOpencodeConfigPaths(home = homedir4()) {
1076
+ return [
1077
+ join5(home, ".config", "opencode", "opencode.json"),
1078
+ join5(home, ".config", "opencode", "opencode.jsonc")
1079
+ ];
907
1080
  }
908
- function serversFromManifest(value, root) {
909
- if (!value) return {};
910
- if (typeof value === "string") return serversFromFile(resolveInside(root, value), root);
911
- if (Array.isArray(value)) {
912
- const out = {};
913
- for (const item of value) {
914
- if (typeof item === "string") mergeServerMap(out, serversFromFile(resolveInside(root, item), root));
915
- else mergeServerMap(out, serverMap(item, root));
916
- }
917
- return out;
1081
+ function userMcpNamesToDisable(opts) {
1082
+ const keep = new Set(
1083
+ [...opts.injectedNames ?? []].map((n) => n.trim().toLowerCase()).filter(Boolean)
1084
+ );
1085
+ const out = [];
1086
+ const seen = /* @__PURE__ */ new Set();
1087
+ for (const raw of opts.names) {
1088
+ const name = raw.trim();
1089
+ if (!name) continue;
1090
+ const key = name.toLowerCase();
1091
+ if (seen.has(key) || keep.has(key) || isInjectedOrchMcpName(name)) continue;
1092
+ seen.add(key);
1093
+ out.push(name);
918
1094
  }
919
- return serverMap(value, root);
1095
+ return out;
920
1096
  }
921
- function serversFromFile(path, root) {
922
- if (!path || !existsSync2(path)) return {};
923
- return serverMap(readJson(path), root);
1097
+ function listUserCodexMcpNames(home = homedir4()) {
1098
+ const names = [];
1099
+ for (const path of userCodexConfigPaths(home)) {
1100
+ if (!existsSync4(path)) continue;
1101
+ names.push(...listMcpNamesFromCodexToml(readText(path)));
1102
+ }
1103
+ return names;
924
1104
  }
925
- function serverMap(value, root) {
926
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
927
- const record = value;
928
- const wrapped = record.mcpServers;
929
- const source = wrapped && typeof wrapped === "object" && !Array.isArray(wrapped) ? wrapped : record;
930
- if (typeof wrapped === "string") return serversFromFile(resolveInside(root, wrapped), root);
931
- const out = {};
932
- for (const [name, entry] of Object.entries(source)) {
933
- if (!name.trim() || !entry || typeof entry !== "object" || Array.isArray(entry)) continue;
934
- const row = entry;
935
- if (row.disabled === true) continue;
936
- if (typeof row.command !== "string" && typeof row.url !== "string") continue;
937
- out[name.trim()] = row;
1105
+ function listUserOpencodeMcpNames(home = homedir4()) {
1106
+ const names = [];
1107
+ for (const path of userOpencodeConfigPaths(home)) {
1108
+ if (!existsSync4(path)) continue;
1109
+ names.push(...listMcpNamesFromJsonMap(readJsonObject(path), "mcp"));
938
1110
  }
939
- return out;
1111
+ return names;
940
1112
  }
941
- function mergeServerMap(into, extra) {
942
- for (const [name, entry] of Object.entries(extra)) into[name] = entry;
1113
+ function userClaudeMcpConfigObject(home = homedir4()) {
1114
+ const claudePath = home === homedir4() ? userClaudeMcpConfigPath() : join5(home, ".claude.json");
1115
+ if (!existsSync4(claudePath)) return {};
1116
+ return asObject2(asObject2(readJsonObject(claudePath)).mcpServers);
943
1117
  }
944
- function expandPluginEntry(entry, root, dataDir) {
945
- const next = { ...entry };
946
- if (typeof next.command === "string") next.command = expandVars(next.command, root, dataDir);
947
- if (Array.isArray(next.args)) {
948
- next.args = next.args.map((arg) => typeof arg === "string" ? expandVars(arg, root, dataDir) : arg);
1118
+ function listUserClaudeMcpServerEntries(home = homedir4(), projectDirs) {
1119
+ const out = {};
1120
+ for (const [name, entry] of Object.entries(
1121
+ listEnabledClaudePluginMcpServers({ home, projectDirs })
1122
+ )) {
1123
+ if (!name || isInjectedOrchMcpName(name)) continue;
1124
+ out[name] = entry;
949
1125
  }
950
- if (typeof next.url === "string") next.url = expandVars(next.url, root, dataDir);
951
- if (next.env && typeof next.env === "object" && !Array.isArray(next.env)) {
952
- const env = {};
953
- for (const [key, value] of Object.entries(next.env)) {
954
- if (typeof value === "string") env[key] = expandVars(value, root, dataDir);
955
- }
956
- env.CLAUDE_PLUGIN_ROOT = env.CLAUDE_PLUGIN_ROOT || root;
957
- env.CLAUDE_PLUGIN_DATA = env.CLAUDE_PLUGIN_DATA || dataDir;
958
- next.env = env;
959
- } else if (typeof next.command === "string") {
960
- next.env = { CLAUDE_PLUGIN_ROOT: root, CLAUDE_PLUGIN_DATA: dataDir };
1126
+ for (const [rawName, value] of Object.entries(userClaudeMcpConfigObject(home))) {
1127
+ const name = rawName.trim();
1128
+ if (!name || isInjectedOrchMcpName(name)) continue;
1129
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1130
+ out[name] = value;
961
1131
  }
962
- if (next.headers && typeof next.headers === "object" && !Array.isArray(next.headers)) {
963
- const headers = {};
964
- for (const [key, value] of Object.entries(next.headers)) {
965
- if (typeof value === "string") headers[key] = expandVars(value, root, dataDir);
966
- }
967
- next.headers = headers;
1132
+ return out;
1133
+ }
1134
+ function toCodexDisableUserMcpArgs(names) {
1135
+ const args = [];
1136
+ for (const name of names) {
1137
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
1138
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
968
1139
  }
969
- return next;
1140
+ return args;
970
1141
  }
971
- function expandVars(value, root, dataDir) {
972
- return value.replaceAll("${CLAUDE_PLUGIN_ROOT}", root).replaceAll("${CLAUDE_PLUGIN_DATA}", dataDir);
1142
+ function toCodexUnattendedAppsArgs() {
1143
+ return [
1144
+ "-c",
1145
+ "features.apps=false",
1146
+ "-c",
1147
+ "apps._default.enabled=false",
1148
+ "-c",
1149
+ "apps.posthog.enabled=false",
1150
+ "-c",
1151
+ "features.plugins=false"
1152
+ ];
973
1153
  }
974
- function resolveInside(root, spec) {
975
- const trimmed = spec.trim();
976
- if (!trimmed || trimmed.endsWith(".mcpb") || trimmed.endsWith(".dxt")) return null;
977
- if (/^https?:\/\//i.test(trimmed)) return null;
978
- const abs = resolve(root, trimmed);
979
- const rel = relative(root, abs);
980
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
981
- return abs;
1154
+
1155
+ // src/agents/turn-input.ts
1156
+ function normalizeTurnInput(input) {
1157
+ if (typeof input === "string") return { prompt: input };
1158
+ return {
1159
+ prompt: input.prompt,
1160
+ cachedPrefix: input.cachedPrefix?.trim() || void 0,
1161
+ systemPrompt: input.systemPrompt?.trim() || void 0,
1162
+ ...input.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
1163
+ };
982
1164
  }
983
- function readJson(path) {
984
- if (!existsSync2(path)) return {};
985
- try {
986
- const parsed = JSON.parse(readFileSync(path, "utf8"));
987
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
988
- return parsed;
989
- } catch {
990
- return {};
1165
+ function dropCachedPrefixOnResume(input, sessionId) {
1166
+ const turn = normalizeTurnInput(input);
1167
+ if (sessionId) {
1168
+ return {
1169
+ prompt: turn.prompt,
1170
+ ...turn.systemPrompt ? { systemPrompt: turn.systemPrompt } : {},
1171
+ ...turn.isolateCodexPlugins ? { isolateCodexPlugins: true } : {}
1172
+ };
991
1173
  }
1174
+ return turn;
992
1175
  }
1176
+ function flattenTurnInput(input) {
1177
+ const { cachedPrefix, prompt, systemPrompt } = normalizeTurnInput(input);
1178
+ if (cachedPrefix) return `${cachedPrefix}
993
1179
 
994
- // src/agents/orch-mcp-isolation.ts
995
- import { homedir as homedir4 } from "os";
996
- import { join as join5 } from "path";
997
- import { parse as parseToml } from "smol-toml";
998
-
999
- // src/agents/user-mcp-config.ts
1000
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
1001
- import { homedir as homedir3 } from "os";
1002
- import { dirname as dirname2, join as join4 } from "path";
1003
-
1004
- // src/agents/injected-mcp.ts
1005
- import { existsSync as existsSync3, mkdtempSync, writeFileSync as writeFileSync2 } from "fs";
1006
- import { createRequire } from "module";
1007
- import { tmpdir } from "os";
1008
- import { dirname, join as join3 } from "path";
1009
- import { fileURLToPath } from "url";
1180
+ ---
1010
1181
 
1011
- // src/mcp/profile.ts
1012
- var SIDEBOARD_MCP_PROFILE_ENV = "SIDEBOARD_MCP_PROFILE";
1013
- var SIDEBOARD_THREAD_ID_ENV = "SIDEBOARD_THREAD_ID";
1014
- function agentRpcOwnsPilotTools(env = process.env) {
1015
- return env[AGENT_RPC_NATIVE_ENV]?.trim() === "1";
1016
- }
1017
- function injectedSideboardMcpEnv(opts) {
1018
- const orchId = opts.orchestratorThreadId?.trim();
1019
- const threadId = opts.threadId?.trim() || orchId;
1020
- const env = {
1021
- SIDEBOARD_APP_DATA: appDataDir(),
1022
- [SIDEBOARD_MCP_PROFILE_ENV]: orchId ? "orchestration" : "worktree"
1023
- };
1024
- if (orchId) env.SIDEBOARD_ORCHESTRATOR_THREAD_ID = orchId;
1025
- if (threadId) env[SIDEBOARD_THREAD_ID_ENV] = threadId;
1026
- if (opts.rpcNativeTools) env[AGENT_RPC_NATIVE_ENV] = "1";
1027
- return env;
1028
- }
1029
- var AGENT_RPC_PILOT_MCP_TOOLS = [
1030
- "present_artifact",
1031
- "wait_for_job",
1032
- "stop_job"
1033
- ];
1034
- function shouldRegisterMcpWaitForTurn(env = process.env) {
1035
- return !agentRpcOwnsPilotTools(env);
1036
- }
1037
- function worktreeMcpToolNames(env = process.env) {
1038
- if (!agentRpcOwnsPilotTools(env)) return WORKTREE_MCP_TOOLS;
1039
- const omit = new Set(AGENT_RPC_PILOT_MCP_TOOLS);
1040
- return WORKTREE_MCP_TOOLS.filter((name) => !omit.has(name));
1041
- }
1042
- var WORKTREE_MCP_TOOLS = [
1043
- "present_artifact",
1044
- "ask_user",
1045
- "present_plan",
1046
- "present_schema",
1047
- "present_files",
1048
- "wait_for_job",
1049
- "stop_job",
1050
- "list_run_scripts",
1051
- "run_dev_script",
1052
- "stop_dev_script",
1053
- "get_run_log",
1054
- "get_orchestrator",
1055
- "notify_orchestrator",
1056
- "set_workspace_tags",
1057
- "set_wake_on_github_edges",
1058
- "get_viewer_context",
1059
- "update_viewer_context",
1060
- "list_env",
1061
- "set_env",
1062
- "delete_env",
1063
- "list_schedules",
1064
- "create_schedule",
1065
- "update_schedule",
1066
- "delete_schedule",
1067
- "run_schedule",
1068
- "list_follow_ups",
1069
- "create_follow_up",
1070
- "delete_follow_up",
1071
- "list_order",
1072
- "show_plan",
1073
- "set_dependency",
1074
- "clear_dependency",
1075
- "satisfy_dependency"
1076
- ];
1077
- var WORKTREE_GITHUB_MCP_TOOLS = [
1078
- "github_search_issues",
1079
- "github_list_projects",
1080
- "github_get_issue",
1081
- "github_download_attachment",
1082
- "github_comment",
1083
- "github_update_issue",
1084
- "github_create_issue"
1085
- ];
1086
- var WORKTREE_LINEAR_MCP_TOOLS = [
1087
- "linear_list_teams",
1088
- "linear_list_projects",
1089
- "linear_search_issues",
1090
- "linear_get_issue",
1091
- "linear_download_attachment",
1092
- "linear_create_issue",
1093
- "linear_update_issue",
1094
- "linear_comment"
1095
- ];
1096
- var WORKTREE_ABLETIME_MCP_TOOLS = [
1097
- "abletime_orientation",
1098
- "abletime_list_projects",
1099
- "abletime_list_tasks",
1100
- "abletime_search_tasks",
1101
- "abletime_get_task",
1102
- "abletime_download_attachment",
1103
- "abletime_comment",
1104
- "abletime_update_task",
1105
- "abletime_create_task",
1106
- "abletime_ensure_task"
1107
- ];
1108
- function sideboardMcpProfile(env = process.env) {
1109
- return env[SIDEBOARD_MCP_PROFILE_ENV]?.trim().toLowerCase() === "worktree" ? "worktree" : "orchestration";
1110
- }
1182
+ Current request:
1183
+ ${prompt}`;
1184
+ if (systemPrompt) return `${systemPrompt}
1111
1185
 
1112
- // src/agents/codex-mcp-profile.ts
1113
- import { randomBytes } from "crypto";
1114
- import { mkdirSync, writeFileSync } from "fs";
1115
- import { homedir as homedir2 } from "os";
1116
- import { join as join2 } from "path";
1117
- function isCodexSecretEnvKey(key) {
1118
- return /token|secret|password|credential|oauth|api_key|_key$/i.test(key);
1186
+ ${prompt}`;
1187
+ return prompt;
1119
1188
  }
1120
- function tomlBasicString(value) {
1121
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`;
1189
+ function splitTurnInputForSystemPrompt(input) {
1190
+ const turn = normalizeTurnInput(input);
1191
+ return {
1192
+ promptText: flattenTurnInput({ cachedPrefix: turn.cachedPrefix, prompt: turn.prompt }),
1193
+ systemPrompt: turn.systemPrompt
1194
+ };
1122
1195
  }
1123
- function secretEnv(env) {
1124
- if (!env) return void 0;
1125
- const out = { ...env };
1126
- delete out.ELECTRON_RUN_AS_NODE;
1127
- return Object.keys(out).length > 0 ? out : void 0;
1196
+ function buildCachedUserContent(input) {
1197
+ return [{ type: "text", text: flattenTurnInput(input) }];
1128
1198
  }
1129
- function writeCodexMcpSecretProfile(servers) {
1130
- const blocks = [];
1131
- for (const s of servers) {
1132
- const env = secretEnv(s.env);
1133
- if (!env) continue;
1134
- const secrets = Object.entries(env).filter(([key]) => isCodexSecretEnvKey(key));
1135
- if (secrets.length === 0) continue;
1136
- const lines = [`[mcp_servers.${s.name}.env]`];
1137
- for (const [key, value] of secrets) lines.push(`${key} = ${tomlBasicString(value)}`);
1138
- blocks.push(lines.join("\n"));
1199
+ function buildClaudeStreamJsonUserMessage(input) {
1200
+ return `${JSON.stringify({
1201
+ type: "user",
1202
+ message: {
1203
+ role: "user",
1204
+ content: buildCachedUserContent(input)
1205
+ }
1206
+ })}
1207
+ `;
1208
+ }
1209
+ function walkCacheControls(blocks, saw5m) {
1210
+ if (!blocks?.length) return { saw5m, invalid: null };
1211
+ for (let i = 0; i < blocks.length; i++) {
1212
+ const block = blocks[i];
1213
+ const ttl = block.cache_control?.ttl ?? (block.cache_control ? "5m" : null);
1214
+ if (ttl === "5m") saw5m = true;
1215
+ if (ttl === "1h" && saw5m) return { saw5m, invalid: { index: i, ttl: "1h" } };
1216
+ if (Array.isArray(block.content)) {
1217
+ const nested = walkCacheControls(block.content, saw5m);
1218
+ if (nested.invalid) return { saw5m: nested.saw5m, invalid: { index: i, ttl: "1h" } };
1219
+ saw5m = nested.saw5m;
1220
+ }
1139
1221
  }
1140
- if (blocks.length === 0) return null;
1141
- const home = process.env.CODEX_HOME?.trim() || join2(homedir2(), ".codex");
1142
- mkdirSync(home, { recursive: true, mode: 448 });
1143
- const profile = `sideboard-${randomBytes(8).toString("hex")}`;
1144
- const file = join2(home, `${profile}.config.toml`);
1145
- writeFileSync(file, `${blocks.join("\n\n")}
1146
- `, { mode: 384 });
1147
- return { profile, file };
1222
+ return { saw5m, invalid: null };
1148
1223
  }
1149
-
1150
- // src/agents/injected-mcp.ts
1151
- var SIDEBOARD_MCP_ALLOWED_TOOLS = [
1152
- "mcp__sideboard",
1153
- "mcp__sideboard__*"
1154
- ];
1155
- var SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS = [
1156
- "mcp__sideboard__present_artifact",
1157
- "mcp__sideboard__present_schema",
1158
- "mcp__sideboard__present_files",
1159
- "mcp__sideboard__ask_user",
1160
- "mcp__sideboard__present_plan",
1161
- "mcp__sideboard__wait_for_job",
1162
- "mcp__sideboard__stop_job",
1163
- "mcp__sideboard__list_run_scripts",
1164
- "mcp__sideboard__run_dev_script",
1165
- "mcp__sideboard__stop_dev_script",
1166
- "mcp__sideboard__get_run_log",
1167
- "mcp__sideboard__get_orchestrator",
1168
- "mcp__sideboard__notify_orchestrator",
1169
- "mcp__sideboard__set_workspace_tags",
1170
- "mcp__sideboard__set_wake_on_github_edges",
1171
- "mcp__sideboard__get_viewer_context",
1172
- "mcp__sideboard__update_viewer_context",
1173
- "mcp__sideboard__list_env",
1174
- "mcp__sideboard__set_env",
1175
- "mcp__sideboard__delete_env",
1176
- "mcp__sideboard__list_schedules",
1177
- "mcp__sideboard__create_schedule",
1178
- "mcp__sideboard__update_schedule",
1179
- "mcp__sideboard__delete_schedule",
1180
- "mcp__sideboard__run_schedule",
1181
- "mcp__sideboard__list_follow_ups",
1182
- "mcp__sideboard__create_follow_up",
1183
- "mcp__sideboard__delete_follow_up",
1184
- "mcp__sideboard__list_order",
1185
- "mcp__sideboard__show_plan",
1186
- "mcp__sideboard__set_dependency",
1187
- "mcp__sideboard__clear_dependency",
1188
- "mcp__sideboard__satisfy_dependency",
1189
- "mcp__sideboard__posthog_api"
1190
- ];
1191
- var SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS = ["mcp__sideboard__github_*"];
1192
- var SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS = ["mcp__sideboard__linear_*"];
1193
- var SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS = ["mcp__sideboard__abletime_*"];
1194
- function sideboardWorktreeAllowedTools(opts) {
1195
- const out = SIDEBOARD_ARTIFACT_MCP_ALLOWED_TOOLS.filter(
1196
- (tool) => (opts?.planMode || tool !== "mcp__sideboard__present_plan") && (opts?.posthog || tool !== "mcp__sideboard__posthog_api")
1197
- );
1198
- if (opts?.github !== false) out.push(...SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS);
1199
- if (opts?.linear) out.push(...SIDEBOARD_LINEAR_MCP_ALLOWED_TOOLS);
1200
- if (opts?.abletime) out.push(...SIDEBOARD_ABLETIME_MCP_ALLOWED_TOOLS);
1201
- return out;
1224
+ function findInvalidCacheControlTtlOrder(blocks) {
1225
+ return walkCacheControls(blocks, false).invalid;
1202
1226
  }
1203
- var BRIGHTSY_MCP_ALLOWED_TOOLS = [
1204
- "mcp__brightsy",
1205
- "mcp__brightsy__*"
1206
- ];
1207
- var brightsyMcpCommandCache = null;
1208
- async function resolveBrightsyMcpCommand() {
1209
- const now = Date.now();
1210
- if (brightsyMcpCommandCache && now - brightsyMcpCommandCache.at < 6e4 && brightsyMcpCommandCache.command) {
1211
- return brightsyMcpCommandCache.command;
1227
+ function countCacheControlBlocks(blocks) {
1228
+ if (!blocks?.length) return 0;
1229
+ let count = 0;
1230
+ for (const block of blocks) {
1231
+ if (block.cache_control) count++;
1232
+ if (Array.isArray(block.content)) {
1233
+ count += countCacheControlBlocks(block.content);
1234
+ }
1212
1235
  }
1213
- const which = await run("which", ["brightsy-mcp"], { reject: false });
1214
- const command = which.exitCode === 0 && which.stdout.trim() ? "brightsy-mcp" : "npx";
1215
- brightsyMcpCommandCache = { at: now, command };
1216
- return command;
1236
+ return count;
1217
1237
  }
1218
- function isBrightsyConnected() {
1238
+ var MAX_ANTHROPIC_CACHE_CONTROL_BLOCKS = 4;
1239
+
1240
+ // src/agents/acp.ts
1241
+ var ACP_ATTACH_ERROR = "ACP harnesses have no interactive attach. Continue the chat in Sideboard.";
1242
+ function entryDir() {
1243
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
1244
+ if (cjsDir) return cjsDir;
1219
1245
  try {
1220
- loadBrightsyConfig();
1221
- return true;
1246
+ return dirname3(fileURLToPath2(import.meta.url));
1222
1247
  } catch {
1223
- return false;
1248
+ try {
1249
+ const req = createRequire2(process.cwd() + "/");
1250
+ return dirname3(req.resolve("@sideboard-ai/core"));
1251
+ } catch {
1252
+ return process.cwd();
1253
+ }
1224
1254
  }
1225
1255
  }
1226
- var BRIGHTSY_WORD = /(?<![a-z0-9_-])brightsy(?![a-z0-9_-])/i;
1227
- function promptMentionsBrightsy(text) {
1228
- return BRIGHTSY_WORD.test(text ?? "");
1229
- }
1230
- function isBrightsyMcpToolName(name) {
1231
- const n = name.toLowerCase();
1232
- return n === "brightsy" || n.startsWith("mcp__brightsy") || n.startsWith("brightsy_");
1256
+ function acpRunnerPath() {
1257
+ const packagedRoot = packagedCursorRuntimeDir();
1258
+ if (packagedRoot) {
1259
+ const packaged = join6(packagedRoot, "core-dist", "agents", "acp-runner.js");
1260
+ if (existsSync5(packaged)) return packaged;
1261
+ }
1262
+ const root = entryDir();
1263
+ const candidates = [
1264
+ join6(root, "agents", "acp-runner.js"),
1265
+ join6(root, "agents", "acp-runner.cjs"),
1266
+ join6(root, "dist", "agents", "acp-runner.js"),
1267
+ join6(root, "dist", "agents", "acp-runner.cjs"),
1268
+ join6(root, "acp-runner.ts"),
1269
+ join6(root, "src", "agents", "acp-runner.ts")
1270
+ ];
1271
+ for (const candidate of candidates) {
1272
+ if (existsSync5(candidate)) return candidate;
1273
+ }
1274
+ return candidates[0];
1233
1275
  }
1234
- function toolInputUsesBrightsyDatasource(input) {
1235
- const ds = input?.datasource;
1236
- return typeof ds === "string" && ds.toLowerCase() === "brightsy";
1276
+ function harnessFor(thread) {
1277
+ return isAcpHarnessId(thread.acpHarness) ? thread.acpHarness : defaultAcpHarness();
1237
1278
  }
1238
- function messageUsedBrightsyMcp(msg) {
1239
- if (msg.role === "user" && promptMentionsBrightsy(msg.text)) return true;
1240
- for (const part of msg.parts ?? []) {
1241
- if (part.type !== "tool") continue;
1242
- if (isBrightsyMcpToolName(part.name)) return true;
1243
- if (/present_(schema|files)$/i.test(part.name) && toolInputUsesBrightsyDatasource(part.input)) {
1244
- return true;
1245
- }
1279
+ var acpAdapter = {
1280
+ kind: "acp",
1281
+ async detect() {
1282
+ return detectAcpHarness(defaultAcpHarness());
1283
+ },
1284
+ async buildTurn(thread, input) {
1285
+ const harness = harnessFor(thread);
1286
+ const command = await resolveAcpHarnessCommand(harness);
1287
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
1288
+ const prompt = flattenTurnInput(input);
1289
+ const resumePrompt = flattenTurnInput(dropCachedPrefixOnResume(input, sessionId));
1290
+ const isOrchestrator = isOrchestratorThread(thread);
1291
+ const injected = await buildInjectedMcpServers({
1292
+ includeSideboard: true,
1293
+ includeBrightsy: shouldInjectBrightsyMcp(thread, { orchestrator: isOrchestrator }),
1294
+ orchestratorThreadId: isOrchestrator ? thread.id : null,
1295
+ threadId: thread.id
1296
+ });
1297
+ const injectedAcp = toAcpMcpServers(injected);
1298
+ const userMcp = isOrchestrator ? [] : acpUserStdioServers(
1299
+ listUserClaudeMcpServerEntries(homedir5(), [thread.repoPath, thread.worktreePath]),
1300
+ new Set(injectedAcp.map((server) => server.name))
1301
+ );
1302
+ const req = {
1303
+ prompt,
1304
+ resumePrompt,
1305
+ transcript: acpPriorTranscript(thread.messages ?? []),
1306
+ cwd: thread.worktreePath,
1307
+ sessionId,
1308
+ harness,
1309
+ command: command.file,
1310
+ args: command.args,
1311
+ mcpServers: [...injectedAcp, ...userMcp],
1312
+ planMode: thread.planMode,
1313
+ autonomy: thread.autonomy
1314
+ };
1315
+ const runner = acpRunnerPath();
1316
+ const isTs = runner.endsWith(".ts");
1317
+ const launch = applyNodeLaunch(
1318
+ await resolveNodeLaunch(runner),
1319
+ isTs ? ["--import", "tsx", runner] : [runner]
1320
+ );
1321
+ return {
1322
+ file: launch.file,
1323
+ args: launch.args,
1324
+ cwd: thread.worktreePath,
1325
+ stdin: JSON.stringify(req),
1326
+ env: launch.env
1327
+ };
1328
+ },
1329
+ parseEvent(line) {
1330
+ return parseAcpRunnerLine(line);
1331
+ },
1332
+ async resolveSessionId(_worktreePath, cached) {
1333
+ return cached?.trim() || null;
1334
+ },
1335
+ async buildAttach(_thread) {
1336
+ throw new Error(ACP_ATTACH_ERROR);
1246
1337
  }
1247
- return false;
1248
- }
1249
- function threadRequestsBrightsyMcp(thread) {
1250
- return (thread?.messages ?? []).some(messageUsedBrightsyMcp);
1338
+ };
1339
+ function acpHarnessDisplayName(thread) {
1340
+ if (thread.agent !== "acp") return thread.agent;
1341
+ return acpHarnessLabel(thread.acpHarness);
1251
1342
  }
1252
- function shouldInjectBrightsyMcp(thread, opts) {
1253
- if (!(opts?.connected ?? isBrightsyConnected())) return false;
1254
- if (opts?.orchestrator) return true;
1255
- const alwaysOn = opts?.alwaysOnWorktree ?? Boolean(loadAppSettings().brightsy?.injectWorktreeMcp);
1256
- if (alwaysOn) return true;
1257
- return threadRequestsBrightsyMcp(thread);
1343
+
1344
+ // src/agents/brightsy.ts
1345
+ import { existsSync as existsSync6 } from "fs";
1346
+
1347
+ // src/agents/brightsy-targets.ts
1348
+ function encodeBrightsyTarget(type, id, accountId) {
1349
+ if (accountId) return `team:${accountId}:${type}:${id}`;
1350
+ return `${type}:${id}`;
1258
1351
  }
1259
- function mcpLaunch(cmd, name, env) {
1260
- if (cmd === "brightsy-mcp") {
1261
- return { name, command: "brightsy-mcp", ...env ? { env } : {} };
1352
+ function decodeBrightsyTarget(model) {
1353
+ const raw = model?.trim();
1354
+ if (!raw || raw === "default" || raw === "agent:default") {
1355
+ return { type: "agent", id: "default" };
1262
1356
  }
1263
- return {
1264
- name,
1265
- command: "npx",
1266
- args: ["-y", "@brightsy/mcp-server"],
1267
- ...env ? { env } : {}
1268
- };
1269
- }
1270
- function teamEnv(team) {
1271
- const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
1272
- return {
1273
- BRIGHTSY_API_TOKEN: team.access_token,
1274
- ...team.refresh_token ? { BRIGHTSY_REFRESH_TOKEN: team.refresh_token } : {},
1275
- ...team.oauth_client_id ? { BRIGHTSY_OAUTH_CLIENT_ID: team.oauth_client_id } : {},
1276
- BRIGHTSY_ACCOUNT_ID: team.id,
1277
- BRIGHTSY_API_URL: endpoint
1278
- };
1357
+ const teamMatch = raw.match(/^team:([^:]+):(agent|model):(.+)$/);
1358
+ if (teamMatch) {
1359
+ return {
1360
+ type: teamMatch[2],
1361
+ id: teamMatch[3] || "default",
1362
+ accountId: teamMatch[1]
1363
+ };
1364
+ }
1365
+ if (raw.startsWith("agent:")) {
1366
+ return { type: "agent", id: raw.slice("agent:".length) || "default" };
1367
+ }
1368
+ if (raw.startsWith("model:")) {
1369
+ return { type: "model", id: raw.slice("model:".length) };
1370
+ }
1371
+ if (/^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(raw) || raw === "default") {
1372
+ return { type: "agent", id: raw };
1373
+ }
1374
+ return { type: "model", id: raw };
1279
1375
  }
1280
- function brightsyMcpAllowedTools(serverNames) {
1281
- const out = [];
1282
- for (const name of serverNames) {
1283
- out.push(`mcp__${name}`, `mcp__${name}__*`);
1376
+
1377
+ // src/agents/brightsy.ts
1378
+ function usageFromBrightsy(usage) {
1379
+ if (!usage) return null;
1380
+ const mapped = fromInclusiveInputUsage({
1381
+ inputTokens: Number(usage.prompt_tokens ?? 0),
1382
+ outputTokens: Number(usage.completion_tokens ?? 0),
1383
+ cachedInputTokens: Number(usage.prompt_tokens_details?.cached_tokens ?? 0)
1384
+ });
1385
+ if (!mapped) return null;
1386
+ if (usage.cost != null && Number.isFinite(Number(usage.cost))) {
1387
+ mapped.costUsd = Number(usage.cost);
1284
1388
  }
1285
- return out;
1389
+ return mapped;
1286
1390
  }
1287
- function corePackageDir() {
1288
- const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
1289
- if (cjsDir) return cjsDir;
1391
+ function parseBrightsyCliLine(line) {
1392
+ const trimmed = line.trim();
1393
+ if (!trimmed) return null;
1290
1394
  try {
1291
- const url = import.meta.url;
1292
- if (typeof url === "string" && url.length > 0) {
1293
- return dirname(fileURLToPath(url));
1395
+ const obj = JSON.parse(trimmed);
1396
+ if (obj.type === "text" && typeof obj.text === "string") {
1397
+ if (looksLikeBrightsyEmptyCompletion(obj.text)) {
1398
+ return [
1399
+ { type: "stderr", data: obj.text },
1400
+ { type: "stdout", data: `Error: ${obj.text}` }
1401
+ ];
1402
+ }
1403
+ return { type: "stdout", data: obj.text };
1404
+ }
1405
+ if (obj.type === "thinking" && typeof obj.text === "string") {
1406
+ return { type: "thinking", data: obj.text };
1407
+ }
1408
+ if (obj.type === "error") {
1409
+ const msg = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
1410
+ return [
1411
+ { type: "stderr", data: msg },
1412
+ { type: "stdout", data: `Error: ${msg}` }
1413
+ ];
1414
+ }
1415
+ if (obj.type === "usage") {
1416
+ const usage = usageFromBrightsy(obj.usage);
1417
+ return usage ? { type: "usage", data: usage } : null;
1418
+ }
1419
+ if (obj.type === "tool_use") {
1420
+ const id = typeof obj.id === "string" && obj.id || `brightsy-tool-${Date.now()}`;
1421
+ const name = typeof obj.name === "string" && obj.name || "brightsy_tool";
1422
+ const input = obj.input && typeof obj.input === "object" && !Array.isArray(obj.input) ? obj.input : void 0;
1423
+ return { type: "tool_use", id, name, input };
1424
+ }
1425
+ if (obj.type === "tool_result" || obj.type === "tool") {
1426
+ const id = typeof obj.id === "string" && obj.id || typeof obj.tool_call_id === "string" && obj.tool_call_id || `brightsy-tool-${Date.now()}`;
1427
+ const content = typeof obj.content === "string" ? obj.content : obj.content != null ? JSON.stringify(obj.content) : void 0;
1428
+ return {
1429
+ type: "tool_result",
1430
+ id,
1431
+ content,
1432
+ isError: obj.isError === true
1433
+ };
1434
+ }
1435
+ if (obj.type === "done") return null;
1436
+ if (typeof obj.type === "string" && ["tool_use", "tool_result", "tool", "thinking", "usage", "error", "done", "text"].includes(
1437
+ obj.type
1438
+ )) {
1439
+ return null;
1294
1440
  }
1441
+ return { type: "stdout", data: trimmed };
1295
1442
  } catch {
1443
+ if (trimmed.startsWith("{") && /"type"\s*:\s*"(tool_use|tool_result|tool|text|thinking|usage|done|error)"/.test(trimmed)) {
1444
+ return null;
1445
+ }
1446
+ if (looksLikeBrightsyEmptyCompletion(trimmed) || /error|failed|unauthorized|quota|limit|not logged in/i.test(trimmed)) {
1447
+ return [
1448
+ { type: "stderr", data: trimmed },
1449
+ { type: "stdout", data: `Error: ${trimmed}` }
1450
+ ];
1451
+ }
1452
+ return { type: "stdout", data: line };
1296
1453
  }
1297
- try {
1298
- const req = createRequire(join3(process.cwd(), "package.json"));
1299
- return dirname(req.resolve("@sideboard-ai/core"));
1300
- } catch {
1301
- return process.cwd();
1454
+ }
1455
+ function adjustBrightsyTurnExit(exitCode, assistantText) {
1456
+ if (looksLikeBrightsyEmptyCompletion(assistantText) && (exitCode === 0 || exitCode == null)) {
1457
+ return 2;
1302
1458
  }
1459
+ return exitCode;
1303
1460
  }
1304
- function findSideboardMcpJsEntry() {
1305
- const override = process.env.SIDEBOARD_MCP_ENTRY?.trim() || process.env.SIDEBOARD_CLI?.trim();
1306
- if (override && existsSync3(override)) return override;
1307
- const packaged = packagedMcpStdioPath();
1308
- if (packaged) return packaged;
1309
- let dir = corePackageDir();
1310
- for (let i = 0; i < 10; i++) {
1311
- const candidates = [
1312
- join3(dir, "mcp/run-stdio.js"),
1313
- join3(dir, "mcp/run-stdio.cjs"),
1314
- join3(dir, "dist/mcp/run-stdio.js"),
1315
- join3(dir, "dist/mcp/run-stdio.cjs"),
1316
- join3(dir, "packages/core/dist/mcp/run-stdio.js"),
1317
- join3(dir, "packages/cli/dist/index.js"),
1318
- join3(dir, "cli/dist/index.js")
1319
- ];
1320
- for (const p of candidates) {
1321
- if (existsSync3(p) && !isAsarPath(p)) return p;
1461
+ async function fetchTeamChatTargets(team) {
1462
+ const endpoint = (team.endpoint || "https://brightsy.ai").replace(/\/$/, "");
1463
+ let agents = [
1464
+ {
1465
+ type: "agent",
1466
+ id: "default",
1467
+ name: "Default Agent",
1468
+ description: "Account default agent (tools + memory)",
1469
+ accountId: team.id,
1470
+ accountSlug: team.slug,
1471
+ accountName: team.name
1322
1472
  }
1323
- const parent = dirname(dir);
1324
- if (parent === dir) break;
1325
- dir = parent;
1473
+ ];
1474
+ let models = [];
1475
+ try {
1476
+ const res = await fetch(`${endpoint}/api/v1beta/${team.id}/agents`, {
1477
+ headers: { Authorization: `Bearer ${team.access_token}` }
1478
+ });
1479
+ if (res.ok) {
1480
+ const json = await res.json();
1481
+ const listed = (json.data || []).filter(
1482
+ (a) => Boolean(a?.id && a?.name)
1483
+ ).filter((a) => a.id !== "default").map((a) => ({
1484
+ type: "agent",
1485
+ id: a.id,
1486
+ name: a.name,
1487
+ description: a.description,
1488
+ accountId: team.id,
1489
+ accountSlug: team.slug,
1490
+ accountName: team.name
1491
+ }));
1492
+ agents = [...agents, ...listed];
1493
+ if (Array.isArray(json.models)) {
1494
+ models = json.models.filter(
1495
+ (m) => Boolean(m?.id && m?.name)
1496
+ ).slice(0, 12).map((m) => ({
1497
+ type: "model",
1498
+ id: m.id,
1499
+ name: m.name,
1500
+ description: m.description,
1501
+ accountId: team.id,
1502
+ accountSlug: team.slug,
1503
+ accountName: team.name
1504
+ }));
1505
+ }
1506
+ }
1507
+ } catch {
1326
1508
  }
1327
- return null;
1509
+ return {
1510
+ accountId: team.id,
1511
+ accountSlug: team.slug,
1512
+ accountName: team.name,
1513
+ agents,
1514
+ models
1515
+ };
1328
1516
  }
1329
- async function resolveSideboardMcpServer() {
1330
- const entry = findSideboardMcpJsEntry();
1331
- if (entry) {
1332
- const isCli = /[/\\]cli[/\\]dist[/\\]index\.js$/.test(entry);
1333
- const scriptArgs = isCli ? [entry, "mcp"] : [entry];
1334
- const launch = applyNodeLaunch(await resolveNodeLaunch(entry), scriptArgs);
1335
- if (launch.file !== "/bin/sh" && !isElectronLikeCommand(launch.file)) {
1336
- return {
1337
- name: "sideboard",
1338
- command: launch.file,
1339
- args: launch.args,
1340
- ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {}
1341
- };
1517
+ async function listBrightsyChatTargetsViaCli() {
1518
+ const listed = await run(
1519
+ resolveAgentExecutable("brightsy"),
1520
+ ["chat", "--list-targets", "--json"],
1521
+ {
1522
+ reject: false
1342
1523
  }
1524
+ );
1525
+ if (listed.exitCode !== 0 || !listed.stdout.trim()) {
1526
+ throw new Error(
1527
+ listed.stderr.trim() || "Failed to list Brightsy chat targets \u2014 is `brightsy` installed and logged in?"
1528
+ );
1343
1529
  }
1344
- const which = await run("which", ["sideboard"], { reject: false });
1345
- if (which.exitCode === 0 && which.stdout.trim()) {
1346
- return { name: "sideboard", command: which.stdout.trim(), args: ["mcp"] };
1347
- }
1348
- return { name: "sideboard", command: "sideboard", args: ["mcp"] };
1349
- }
1350
- async function buildInjectedMcpServers(opts) {
1351
- const servers = [];
1352
- if (opts.includeSideboard) {
1353
- const sideboard = await resolveSideboardMcpServer();
1354
- sideboard.env = {
1355
- ...sideboard.env ?? {},
1356
- ...injectedSideboardMcpEnv(opts)
1357
- };
1530
+ try {
1531
+ const parsed = JSON.parse(listed.stdout);
1532
+ let accountId = null;
1533
+ let accountSlug = "team";
1534
+ let accountName = "Brightsy";
1358
1535
  try {
1359
- mergeAgentGitAuthEnv(
1360
- sideboard.env,
1361
- await resolveAgentGitAuthEnv(sideboard.env)
1362
- );
1536
+ const cfg = loadBrightsyConfig();
1537
+ accountId = cfg.account_id;
1538
+ accountSlug = cfg.account_slug || accountSlug;
1539
+ accountName = cfg.account_slug || accountName;
1363
1540
  } catch {
1364
1541
  }
1365
- applyAgentRunnerHeapEnv(sideboard.env);
1366
- servers.push(sideboard);
1367
- }
1368
- if (opts.includeBrightsy && isBrightsyConnected()) {
1369
- const cmd = await resolveBrightsyMcpCommand();
1370
- const teams = await ensureConnectedBrightsyTeamTokens();
1371
- if (teams.length > 0) {
1372
- const used = /* @__PURE__ */ new Set();
1373
- for (const team of teams) {
1374
- let name = brightsyMcpServerName(team.slug);
1375
- if (used.has(name)) name = `${name}_${team.id.slice(0, 8)}`;
1376
- used.add(name);
1377
- servers.push(mcpLaunch(cmd, name, teamEnv(team)));
1542
+ const agents = (Array.isArray(parsed.agents) ? parsed.agents : []).map((a) => ({
1543
+ ...a,
1544
+ accountId: accountId ?? void 0,
1545
+ accountSlug,
1546
+ accountName
1547
+ }));
1548
+ const models = (Array.isArray(parsed.models) ? parsed.models : []).map((m) => ({
1549
+ ...m,
1550
+ accountId: accountId ?? void 0,
1551
+ accountSlug,
1552
+ accountName
1553
+ }));
1554
+ const teams = accountId ? [
1555
+ {
1556
+ accountId,
1557
+ accountSlug,
1558
+ accountName,
1559
+ agents,
1560
+ models
1378
1561
  }
1379
- } else {
1380
- servers.push(mcpLaunch(cmd, "brightsy"));
1381
- }
1562
+ ] : [];
1563
+ return { teams, agents, models, activeAccountId: accountId };
1564
+ } catch {
1565
+ throw new Error("Brightsy --list-targets returned invalid JSON");
1382
1566
  }
1383
- return servers;
1384
1567
  }
1385
- function cursorSafeMcpLaunch(command, args) {
1386
- if (process.platform === "win32") {
1387
- return args && args.length > 0 ? { command, args } : { command };
1568
+ async function listBrightsyChatTargets() {
1569
+ ensureCliTeamTracked();
1570
+ const teamsRaw = await ensureConnectedBrightsyTeamTokens();
1571
+ if (teamsRaw.length === 0) {
1572
+ return listBrightsyChatTargetsViaCli();
1388
1573
  }
1389
- const unwrapped = unwrapStrippedElectronLaunch(command, args);
1390
- const file = unwrapped?.file ?? command;
1391
- const fileArgs = unwrapped?.args ?? args ?? [];
1392
- return fileArgs.length > 0 ? { command: file, args: fileArgs } : { command: file };
1393
- }
1394
- function mcpSpawnEnv(env) {
1395
- if (!env) return void 0;
1396
- const out = { ...env };
1397
- delete out.ELECTRON_RUN_AS_NODE;
1398
- delete out.ELECTRON_RUN_AS_NODE;
1399
- return Object.keys(out).length > 0 ? out : void 0;
1400
- }
1401
- function toCursorMcpServers(servers) {
1402
- const out = {};
1403
- for (const s of servers) {
1404
- const env = mcpSpawnEnv(s.env);
1405
- const launch = cursorSafeMcpLaunch(s.command, s.args);
1406
- out[s.name] = {
1407
- type: "stdio",
1408
- command: launch.command,
1409
- ...launch.args && launch.args.length > 0 ? { args: launch.args } : {},
1410
- ...env ? { env } : {}
1411
- };
1574
+ let activeAccountId = null;
1575
+ try {
1576
+ activeAccountId = loadBrightsyConfig().account_id;
1577
+ } catch {
1578
+ activeAccountId = teamsRaw[0]?.id ?? null;
1412
1579
  }
1413
- return out;
1580
+ const teams = await Promise.all(teamsRaw.map((t) => fetchTeamChatTargets(t)));
1581
+ teams.sort((a, b) => {
1582
+ if (a.accountId === activeAccountId) return -1;
1583
+ if (b.accountId === activeAccountId) return 1;
1584
+ return a.accountSlug.localeCompare(b.accountSlug);
1585
+ });
1586
+ const active = teams.find((t) => t.accountId === activeAccountId) ?? teams[0] ?? null;
1587
+ return {
1588
+ teams,
1589
+ agents: active?.agents ?? [],
1590
+ models: active?.models ?? [],
1591
+ activeAccountId
1592
+ };
1414
1593
  }
1415
- function toCodexMcpConfigArgs(servers) {
1416
- const args = [];
1417
- for (const s of servers) {
1418
- const prefix = `mcp_servers.${s.name}`;
1419
- args.push("-c", `${prefix}.command=${JSON.stringify(s.command)}`);
1420
- if (s.args?.length) {
1421
- args.push("-c", `${prefix}.args=${JSON.stringify(s.args)}`);
1422
- }
1423
- const env = mcpSpawnEnv(s.env);
1424
- if (env) {
1425
- for (const [key, value] of Object.entries(env)) {
1426
- if (isCodexSecretEnvKey(key)) continue;
1427
- args.push("-c", `${prefix}.env.${key}=${JSON.stringify(value)}`);
1428
- }
1594
+ async function syncCliForTarget(accountId) {
1595
+ if (!accountId) return;
1596
+ const teams = await ensureConnectedBrightsyTeamTokens();
1597
+ const team = teams.find((t) => t.id === accountId);
1598
+ if (!team) return;
1599
+ try {
1600
+ const cfg = loadBrightsyConfig();
1601
+ if (cfg.account_id === team.id && cfg.access_token === team.access_token) {
1602
+ return;
1429
1603
  }
1430
- args.push("-c", `${prefix}.default_tools_approval_mode=${JSON.stringify("approve")}`);
1431
- args.push("-c", `${prefix}.tool_timeout_sec=300`);
1432
- args.push("-c", `${prefix}.startup_timeout_sec=30`);
1604
+ } catch {
1433
1605
  }
1434
- return args;
1606
+ applyConnectedTeamToCli(team);
1435
1607
  }
1436
- function toOpencodeMcpConfigContent(servers, opts) {
1437
- const mcp = {};
1438
- for (const s of servers) {
1439
- const env = mcpSpawnEnv(s.env);
1440
- mcp[s.name] = {
1441
- type: "local",
1442
- command: [s.command, ...s.args ?? []],
1443
- enabled: true,
1444
- ...env ? { environment: env } : {}
1608
+ var brightsyAdapter = {
1609
+ kind: "brightsy",
1610
+ async detect() {
1611
+ const brightsy = resolveAgentExecutable("brightsy");
1612
+ if (brightsy !== "brightsy") {
1613
+ if (!existsSync6(brightsy)) {
1614
+ return {
1615
+ agent: "brightsy",
1616
+ installed: false,
1617
+ authenticated: false,
1618
+ linearMcp: false,
1619
+ warnings: [],
1620
+ reason: `Brightsy executable not found: ${brightsy}`
1621
+ };
1622
+ }
1623
+ } else {
1624
+ const which = await run("which", ["brightsy"], { reject: false });
1625
+ if (which.exitCode !== 0) {
1626
+ return {
1627
+ agent: "brightsy",
1628
+ installed: false,
1629
+ authenticated: false,
1630
+ linearMcp: false,
1631
+ warnings: [],
1632
+ reason: "brightsy CLI not found on PATH \u2014 npm i -g @brightsy/cli"
1633
+ };
1634
+ }
1635
+ }
1636
+ const who = await run(brightsy, ["whoami"], { reject: false });
1637
+ const authenticated = who.exitCode === 0 && /logged in as/i.test(who.stdout);
1638
+ return {
1639
+ agent: "brightsy",
1640
+ installed: true,
1641
+ authenticated,
1642
+ linearMcp: false,
1643
+ warnings: [],
1644
+ reason: authenticated ? void 0 : "not logged in \u2014 run `brightsy login`"
1445
1645
  };
1446
- }
1447
- for (const name of opts?.disableNames ?? []) {
1448
- const key = name.trim();
1449
- if (!key || mcp[key]?.enabled === true) continue;
1450
- mcp[key] = { ...mcp[key], enabled: false };
1451
- }
1452
- return JSON.stringify({ mcp });
1453
- }
1454
- function stripElectronFromUserMcpEntry(entry) {
1455
- const next = { ...entry };
1456
- const env = next.env;
1457
- if (!env || typeof env !== "object" || Array.isArray(env)) return next;
1458
- const cleaned = { ...env };
1459
- delete cleaned.ELECTRON_RUN_AS_NODE;
1460
- next.env = cleaned;
1461
- return next;
1462
- }
1463
- function mcpServersRecord(servers, extraServers) {
1464
- const mcpServers = {};
1465
- for (const s of servers) {
1466
- const env = mcpSpawnEnv(s.env);
1467
- mcpServers[s.name] = {
1468
- command: s.command,
1469
- ...s.args ? { args: s.args } : {},
1470
- ...env ? { env } : {}
1646
+ },
1647
+ async buildTurn(thread, input) {
1648
+ const prompt = flattenTurnInput(input);
1649
+ const target = decodeBrightsyTarget(thread.model);
1650
+ await syncCliForTarget(target.accountId);
1651
+ const mode = thread.planMode ? "plan" : target.type === "model" ? "ask" : "agent";
1652
+ const args = [
1653
+ "chat",
1654
+ "--json",
1655
+ "--mode",
1656
+ mode,
1657
+ target.type === "model" ? "--model" : "--agent",
1658
+ target.id
1659
+ ];
1660
+ return {
1661
+ file: resolveAgentExecutable("brightsy"),
1662
+ args,
1663
+ cwd: thread.worktreePath,
1664
+ // Piped stdin becomes the message body (avoids ARG_MAX for long seeds).
1665
+ stdin: prompt
1666
+ };
1667
+ },
1668
+ parseEvent(line) {
1669
+ return parseBrightsyCliLine(line);
1670
+ },
1671
+ async resolveSessionId() {
1672
+ return null;
1673
+ },
1674
+ async buildAttach(thread) {
1675
+ const target = decodeBrightsyTarget(thread.model);
1676
+ await syncCliForTarget(target.accountId);
1677
+ const args = target.type === "model" ? ["chat", "--model", target.id] : ["chat", "--agent", target.id];
1678
+ return {
1679
+ file: resolveAgentExecutable("brightsy"),
1680
+ args,
1681
+ cwd: thread.worktreePath
1471
1682
  };
1472
1683
  }
1473
- if (extraServers) {
1474
- for (const [rawName, entry] of Object.entries(extraServers)) {
1475
- const name = rawName.trim();
1476
- if (!name || mcpServers[name] || !entry) continue;
1477
- mcpServers[name] = stripElectronFromUserMcpEntry(entry);
1478
- }
1479
- }
1480
- return mcpServers;
1481
- }
1482
- function writeMcpServersConfig(servers, extraServers) {
1483
- const mcpServers = mcpServersRecord(servers, extraServers);
1484
- if (Object.keys(mcpServers).length === 0) return null;
1485
- const dir = mkdtempSync(join3(tmpdir(), "sideboard-mcp-"));
1486
- const cfgPath = join3(dir, "mcp.json");
1487
- writeFileSync2(cfgPath, JSON.stringify({ mcpServers }, null, 2), { mode: 384 });
1488
- return cfgPath;
1489
- }
1490
- async function writeInjectedMcpConfig(opts) {
1491
- return writeMcpServersConfig(await buildInjectedMcpServers(opts));
1492
- }
1684
+ };
1493
1685
 
1494
- // src/agents/user-mcp-config.ts
1495
- function userCursorMcpConfigPath() {
1496
- return join4(homedir3(), ".cursor", "mcp.json");
1497
- }
1498
- function userClaudeMcpConfigPath() {
1499
- return join4(homedir3(), ".claude.json");
1500
- }
1501
- function asObject(value) {
1502
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1503
- return { ...value };
1504
- }
1505
- function stripElectronSpawnEnv(env) {
1506
- if (!env) return void 0;
1507
- const next = { ...env };
1508
- delete next.ELECTRON_RUN_AS_NODE;
1509
- delete next.ELECTRON_RUN_AS_NODE;
1510
- return Object.keys(next).length > 0 ? next : void 0;
1511
- }
1512
- function mergeSideboardIntoMcpServersJson(existing, sideboard) {
1513
- const root = asObject(existing);
1514
- const servers = asObject(root.mcpServers);
1515
- const env = stripElectronSpawnEnv(sideboard.env);
1516
- servers.sideboard = {
1517
- type: "stdio",
1518
- command: sideboard.command,
1519
- ...sideboard.args && sideboard.args.length > 0 ? { args: sideboard.args } : {},
1520
- ...env ? { env } : {}
1521
- };
1522
- return { ...root, mcpServers: servers };
1523
- }
1524
- function writeMergedMcpServersJson(configPath, sideboard) {
1525
- let existing = {};
1526
- if (existsSync4(configPath)) {
1527
- try {
1528
- existing = JSON.parse(readFileSync2(configPath, "utf8"));
1529
- } catch {
1530
- existing = {};
1686
+ // src/agents/claude.ts
1687
+ import { existsSync as existsSync9 } from "fs";
1688
+ import { dirname as dirname5 } from "path";
1689
+
1690
+ // src/agents/claude-mcp-status.ts
1691
+ var SIDEBOARD_CONNECTOR_SERVICES = [
1692
+ "github",
1693
+ "linear",
1694
+ "posthog",
1695
+ "vercel",
1696
+ "supabase",
1697
+ "sentry"
1698
+ ];
1699
+ function mcpStatusThinkingFromClaudeInit(obj) {
1700
+ const raw = obj.mcp_servers ?? obj.mcpServers;
1701
+ const servers = [];
1702
+ if (Array.isArray(raw)) {
1703
+ for (const item of raw) {
1704
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
1705
+ const rec = item;
1706
+ const name = typeof rec.name === "string" && rec.name.trim() || typeof rec.server === "string" && rec.server.trim() || "";
1707
+ const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "";
1708
+ if (name) servers.push({ name, status: status || "unknown" });
1709
+ }
1710
+ } else if (raw && typeof raw === "object") {
1711
+ for (const [name, value] of Object.entries(raw)) {
1712
+ if (!name.trim()) continue;
1713
+ if (typeof value === "string" && value.trim()) {
1714
+ servers.push({ name, status: value.trim() });
1715
+ continue;
1716
+ }
1717
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1718
+ const rec = value;
1719
+ const status = typeof rec.status === "string" && rec.status.trim() || typeof rec.state === "string" && rec.state.trim() || "unknown";
1720
+ servers.push({ name, status });
1721
+ }
1531
1722
  }
1532
1723
  }
1533
- const next = mergeSideboardIntoMcpServersJson(existing, sideboard);
1534
- mkdirSync2(dirname2(configPath), { recursive: true });
1535
- writeFileSync3(configPath, `${JSON.stringify(next, null, 2)}
1536
- `);
1724
+ const coverage = claudeConnectorCoverage();
1725
+ const sideboardOk = sideboardMcpOk(servers);
1726
+ const notable = servers.filter(
1727
+ (server) => isNotableMcpInitStatus(server, sideboardOk, coverage)
1728
+ );
1729
+ if (notable.length === 0) return null;
1730
+ return `MCP: ${notable.map((s) => `${s.name} ${s.status}`).join(", ")}`;
1537
1731
  }
1538
- function launchFromResolved(server) {
1539
- return {
1540
- command: server.command,
1541
- args: server.args,
1542
- env: {
1543
- ...server.env ?? {},
1544
- SIDEBOARD_APP_DATA: appDataDir()
1545
- }
1546
- };
1732
+ function isCleanMcpConnect(status) {
1733
+ return /^(connected|ok|ready|success)$/i.test(status.trim());
1547
1734
  }
1548
- async function registerPackagedUserMcpClients() {
1549
- const launch = launchFromResolved(await resolveSideboardMcpServer());
1550
- const cursor = userCursorMcpConfigPath();
1551
- writeMergedMcpServersJson(cursor, launch);
1552
- const claude = userClaudeMcpConfigPath();
1553
- if (existsSync4(claude)) {
1554
- writeMergedMcpServersJson(claude, launch);
1555
- return { cursor, claude };
1556
- }
1557
- return { cursor };
1735
+ function isMcpAuthStatus(status) {
1736
+ return /needs[_-]?auth|needs authentication|unauthorized|not authenticated|authrequired/i.test(
1737
+ status
1738
+ );
1558
1739
  }
1559
-
1560
- // src/agents/orch-mcp-isolation.ts
1561
- function isInjectedOrchMcpName(name) {
1562
- const n = name.trim().toLowerCase();
1563
- return n === "sideboard" || n === "brightsy" || n.startsWith("brightsy_");
1740
+ function isSideboardMcpName(name) {
1741
+ return /^sideboard$/i.test(name.trim()) || /^mcp__sideboard$/i.test(name.trim());
1564
1742
  }
1565
- function asObject2(value) {
1566
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1567
- return value;
1743
+ function isVendorClaudeAiMcpName(name) {
1744
+ return /^claude\.ai\b/i.test(name.trim()) || /^mcp__claude_ai_/i.test(name.trim());
1568
1745
  }
1569
- function listMcpNamesFromJsonMap(raw, key) {
1570
- return Object.keys(asObject2(asObject2(raw)[key])).filter((n) => n.trim());
1746
+ function sideboardMcpOk(servers) {
1747
+ const row = servers.find((server) => isSideboardMcpName(server.name));
1748
+ return Boolean(row && isCleanMcpConnect(row.status));
1571
1749
  }
1572
- function listMcpNamesFromCodexToml(text) {
1573
- try {
1574
- const parsed = parseToml(text);
1575
- return Object.keys(asObject2(parsed.mcp_servers)).filter((n) => n.trim());
1576
- } catch {
1577
- return [];
1750
+ function sideboardServiceForClaudeConnector(name) {
1751
+ const raw = name.trim();
1752
+ if (!raw || isSideboardMcpName(raw)) return null;
1753
+ const pluginLike = /^(?:plugin[:_]|mcp__plugin_|claude\.ai\s|(?:mcp__)?claude_ai_)/i.test(raw);
1754
+ const doubled = raw.match(/^mcp_([a-z0-9]+)_([a-z0-9]+)$/i);
1755
+ if (!pluginLike && !(doubled && doubled[1].toLowerCase() === doubled[2].toLowerCase())) {
1756
+ return null;
1578
1757
  }
1758
+ let body = raw;
1759
+ if (/^claude\.ai\s+/i.test(body)) body = body.replace(/^claude\.ai\s+/i, "");
1760
+ else if (/^(?:mcp__)?claude_ai_/i.test(body)) body = body.replace(/^(?:mcp__)?claude_ai_/i, "");
1761
+ else if (/^mcp__plugin_/i.test(body)) body = body.slice("mcp__plugin_".length);
1762
+ else if (/^plugin_/i.test(body)) body = body.slice("plugin_".length);
1763
+ else if (/^plugin:/i.test(body)) body = body.slice("plugin:".length);
1764
+ else if (/^mcp_/i.test(body)) body = body.slice("mcp_".length);
1765
+ const head = body.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
1766
+ if (!head || !SIDEBOARD_CONNECTOR_SERVICES.includes(head)) return null;
1767
+ return head;
1579
1768
  }
1580
- function readJsonObject(path) {
1769
+ function claudeConnectorCoverage() {
1770
+ let github = false;
1581
1771
  try {
1582
- return JSON.parse(readFileSync3(path, "utf8"));
1772
+ github = githubAgentAuthReady();
1583
1773
  } catch {
1584
- return {};
1774
+ github = false;
1585
1775
  }
1586
- }
1587
- function readText(path) {
1776
+ let linear = false;
1777
+ let posthog = false;
1778
+ let vercel = false;
1779
+ let supabase = false;
1780
+ let sentry = false;
1588
1781
  try {
1589
- return readFileSync3(path, "utf8");
1782
+ linear = isLinearConnected();
1783
+ posthog = isPosthogConnected();
1784
+ const integrations = loadAppSettings().integrations ?? {};
1785
+ if (integrations.githubPat?.trim()) github = true;
1786
+ vercel = Boolean(integrations.vercelToken?.trim());
1787
+ supabase = Boolean(integrations.supabaseAccessToken?.trim());
1788
+ sentry = Boolean(integrations.sentryAuthToken?.trim());
1590
1789
  } catch {
1591
- return "";
1592
- }
1593
- }
1594
- function userCodexConfigPaths(home = homedir4()) {
1595
- const paths = [
1596
- join5(home, ".codex", "config.toml"),
1597
- join5(home, ".config", "codex", "config.toml")
1598
- ];
1599
- const codexHome = process.env.CODEX_HOME?.trim();
1600
- if (codexHome) paths.unshift(join5(codexHome, "config.toml"));
1601
- return paths;
1602
- }
1603
- function userOpencodeConfigPaths(home = homedir4()) {
1604
- return [
1605
- join5(home, ".config", "opencode", "opencode.json"),
1606
- join5(home, ".config", "opencode", "opencode.jsonc")
1607
- ];
1608
- }
1609
- function userMcpNamesToDisable(opts) {
1610
- const keep = new Set(
1611
- [...opts.injectedNames ?? []].map((n) => n.trim().toLowerCase()).filter(Boolean)
1612
- );
1613
- const out = [];
1614
- const seen = /* @__PURE__ */ new Set();
1615
- for (const raw of opts.names) {
1616
- const name = raw.trim();
1617
- if (!name) continue;
1618
- const key = name.toLowerCase();
1619
- if (seen.has(key) || keep.has(key) || isInjectedOrchMcpName(name)) continue;
1620
- seen.add(key);
1621
- out.push(name);
1622
- }
1623
- return out;
1624
- }
1625
- function listUserCodexMcpNames(home = homedir4()) {
1626
- const names = [];
1627
- for (const path of userCodexConfigPaths(home)) {
1628
- if (!existsSync5(path)) continue;
1629
- names.push(...listMcpNamesFromCodexToml(readText(path)));
1630
- }
1631
- return names;
1632
- }
1633
- function listUserOpencodeMcpNames(home = homedir4()) {
1634
- const names = [];
1635
- for (const path of userOpencodeConfigPaths(home)) {
1636
- if (!existsSync5(path)) continue;
1637
- names.push(...listMcpNamesFromJsonMap(readJsonObject(path), "mcp"));
1638
- }
1639
- return names;
1640
- }
1641
- function userClaudeMcpConfigObject(home = homedir4()) {
1642
- const claudePath = home === homedir4() ? userClaudeMcpConfigPath() : join5(home, ".claude.json");
1643
- if (!existsSync5(claudePath)) return {};
1644
- return asObject2(asObject2(readJsonObject(claudePath)).mcpServers);
1645
- }
1646
- function listUserClaudeMcpServerEntries(home = homedir4(), projectDirs) {
1647
- const out = {};
1648
- for (const [name, entry] of Object.entries(
1649
- listEnabledClaudePluginMcpServers({ home, projectDirs })
1650
- )) {
1651
- if (!name || isInjectedOrchMcpName(name)) continue;
1652
- out[name] = entry;
1653
- }
1654
- for (const [rawName, value] of Object.entries(userClaudeMcpConfigObject(home))) {
1655
- const name = rawName.trim();
1656
- if (!name || isInjectedOrchMcpName(name)) continue;
1657
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1658
- out[name] = value;
1659
- }
1660
- return out;
1661
- }
1662
- function toCodexDisableUserMcpArgs(names) {
1663
- const args = [];
1664
- for (const name of names) {
1665
- if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
1666
- args.push("-c", `mcp_servers.${name}.enabled=false`);
1667
1790
  }
1668
- return args;
1791
+ return { github, linear, posthog, vercel, supabase, sentry };
1669
1792
  }
1670
- function toCodexUnattendedAppsArgs() {
1671
- return [
1672
- "-c",
1673
- "features.apps=false",
1674
- "-c",
1675
- "apps._default.enabled=false",
1676
- "-c",
1677
- "apps.posthog.enabled=false",
1678
- "-c",
1679
- "features.plugins=false"
1680
- ];
1793
+ function isNotableMcpInitStatus(server, sideboardOk, coverage) {
1794
+ if (isCleanMcpConnect(server.status)) return false;
1795
+ if (isSideboardMcpName(server.name)) return true;
1796
+ if (isMcpAuthStatus(server.status)) return false;
1797
+ const service = sideboardServiceForClaudeConnector(server.name);
1798
+ if (service) return !(sideboardOk && coverage[service]);
1799
+ if (isVendorClaudeAiMcpName(server.name)) return false;
1800
+ return true;
1681
1801
  }
1682
1802
 
1803
+ // src/mcp-ui/host.ts
1804
+ import { createHash } from "crypto";
1805
+ import { homedir as homedir6 } from "os";
1806
+
1683
1807
  // src/mcp-ui/proxy-http.ts
1684
1808
  import { randomBytes as randomBytes2, randomUUID } from "crypto";
1685
1809
  import { createServer } from "http";
@@ -2151,7 +2275,7 @@ var singleton;
2151
2275
  function getMcpUiHost() {
2152
2276
  if (!singleton) {
2153
2277
  singleton = new McpUiHost({
2154
- entries: (projectDirs) => listUserClaudeMcpServerEntries(homedir5(), projectDirs)
2278
+ entries: (projectDirs) => listUserClaudeMcpServerEntries(homedir6(), projectDirs)
2155
2279
  });
2156
2280
  }
2157
2281
  return singleton;
@@ -2159,7 +2283,7 @@ function getMcpUiHost() {
2159
2283
  async function proxyClaudeUserMcp(orchestrator, projectDirs) {
2160
2284
  if (orchestrator) return {};
2161
2285
  const dirs = projectDirs.filter((d) => typeof d === "string" && d.length > 0);
2162
- return getMcpUiHost().proxyEntries(listUserClaudeMcpServerEntries(homedir5(), dirs), dirs);
2286
+ return getMcpUiHost().proxyEntries(listUserClaudeMcpServerEntries(homedir6(), dirs), dirs);
2163
2287
  }
2164
2288
  function closeMcpUiHost() {
2165
2289
  const host = singleton;
@@ -2172,9 +2296,9 @@ function dirsKeyFor(projectDirs) {
2172
2296
  }
2173
2297
 
2174
2298
  // src/agents/claude-usage-client.ts
2175
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "fs";
2176
- import { homedir as homedir6 } from "os";
2177
- import { join as join6 } from "path";
2299
+ import { existsSync as existsSync7, readFileSync as readFileSync4 } from "fs";
2300
+ import { homedir as homedir7 } from "os";
2301
+ import { join as join7 } from "path";
2178
2302
 
2179
2303
  // src/agents/claude-usage.ts
2180
2304
  var WINDOW_META = {
@@ -2432,12 +2556,12 @@ function accessTokenFromCredentialsJson(raw) {
2432
2556
  }
2433
2557
  }
2434
2558
  function claudeCredentialsPath(configDir) {
2435
- const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir6(), ".claude");
2436
- return join6(root, ".credentials.json");
2559
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir7(), ".claude");
2560
+ return join7(root, ".credentials.json");
2437
2561
  }
2438
2562
  async function readFileAccessToken(configDir) {
2439
2563
  const path = claudeCredentialsPath(configDir);
2440
- if (!existsSync6(path)) return null;
2564
+ if (!existsSync7(path)) return null;
2441
2565
  try {
2442
2566
  return accessTokenFromCredentialsJson(readFileSync4(path, "utf8"));
2443
2567
  } catch {
@@ -2689,10 +2813,10 @@ function agentRpcChildEnv(rpc, cwd) {
2689
2813
  }
2690
2814
 
2691
2815
  // src/agents/claude-host.ts
2692
- import { existsSync as existsSync7 } from "fs";
2693
- import { createRequire as createRequire2 } from "module";
2694
- import { dirname as dirname3, join as join7 } from "path";
2695
- import { fileURLToPath as fileURLToPath2 } from "url";
2816
+ import { existsSync as existsSync8 } from "fs";
2817
+ import { createRequire as createRequire3 } from "module";
2818
+ import { dirname as dirname4, join as join8 } from "path";
2819
+ import { fileURLToPath as fileURLToPath3 } from "url";
2696
2820
  function claudePilotSdkAllowedTools() {
2697
2821
  return PILOT_TOOL_NAMES.map(
2698
2822
  (name) => `mcp__${AGENT_RPC_CLAUDE_SDK_SERVER}__${name}`
@@ -2702,15 +2826,15 @@ function withClaudePilotRpcTools(allowed) {
2702
2826
  const omit = new Set(PILOT_TOOL_NAMES.map((name) => `mcp__sideboard__${name}`));
2703
2827
  return [...allowed.filter((name) => !omit.has(name)), ...claudePilotSdkAllowedTools()];
2704
2828
  }
2705
- function entryDir() {
2829
+ function entryDir2() {
2706
2830
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
2707
2831
  if (cjsDir) return cjsDir;
2708
2832
  try {
2709
- return dirname3(fileURLToPath2(import.meta.url));
2833
+ return dirname4(fileURLToPath3(import.meta.url));
2710
2834
  } catch {
2711
2835
  try {
2712
- const req = createRequire2(process.cwd() + "/");
2713
- return dirname3(req.resolve("@sideboard-ai/core"));
2836
+ const req = createRequire3(process.cwd() + "/");
2837
+ return dirname4(req.resolve("@sideboard-ai/core"));
2714
2838
  } catch {
2715
2839
  return process.cwd();
2716
2840
  }
@@ -2719,20 +2843,20 @@ function entryDir() {
2719
2843
  function claudeRunnerPath() {
2720
2844
  const packagedDir = packagedCursorRuntimeDir();
2721
2845
  if (packagedDir) {
2722
- const packaged = join7(packagedDir, "core-dist", "agents", "claude-runner.js");
2723
- if (existsSync7(packaged)) return packaged;
2846
+ const packaged = join8(packagedDir, "core-dist", "agents", "claude-runner.js");
2847
+ if (existsSync8(packaged)) return packaged;
2724
2848
  }
2725
- const root = entryDir();
2849
+ const root = entryDir2();
2726
2850
  const candidates = [
2727
- join7(root, "agents", "claude-runner.js"),
2728
- join7(root, "agents", "claude-runner.cjs"),
2729
- join7(root, "dist", "agents", "claude-runner.js"),
2730
- join7(root, "dist", "agents", "claude-runner.cjs"),
2731
- join7(root, "claude-runner.ts"),
2732
- join7(root, "src", "agents", "claude-runner.ts")
2851
+ join8(root, "agents", "claude-runner.js"),
2852
+ join8(root, "agents", "claude-runner.cjs"),
2853
+ join8(root, "dist", "agents", "claude-runner.js"),
2854
+ join8(root, "dist", "agents", "claude-runner.cjs"),
2855
+ join8(root, "claude-runner.ts"),
2856
+ join8(root, "src", "agents", "claude-runner.ts")
2733
2857
  ];
2734
2858
  for (const candidate of candidates) {
2735
- if (existsSync7(candidate)) return candidate;
2859
+ if (existsSync8(candidate)) return candidate;
2736
2860
  }
2737
2861
  return candidates[0];
2738
2862
  }
@@ -3088,7 +3212,7 @@ var claudeAdapter = {
3088
3212
  async detect() {
3089
3213
  const claude = resolveClaudeExecutable();
3090
3214
  if (claude !== "claude") {
3091
- if (!existsSync8(claude)) {
3215
+ if (!existsSync9(claude)) {
3092
3216
  return {
3093
3217
  agent: "claude",
3094
3218
  installed: false,
@@ -3137,7 +3261,7 @@ var claudeAdapter = {
3137
3261
  );
3138
3262
  }
3139
3263
  const mode = permissionMode(thread);
3140
- const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-64KC7PST.js");
3264
+ const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-4RDPAOTT.js");
3141
3265
  const isOrchestrator = isOrchestratorThread2(thread);
3142
3266
  const rpc = worktreeAgentRpc(isOrchestrator);
3143
3267
  const injectedServers = await buildInjectedMcpServers({
@@ -3246,7 +3370,7 @@ ${hint}` : hint;
3246
3370
  cwd: thread.worktreePath,
3247
3371
  stdin: useStdin ? `${promptText}
3248
3372
  ` : void 0,
3249
- ...mcpConfigPath ? { cleanupDirs: [dirname4(mcpConfigPath)] } : {},
3373
+ ...mcpConfigPath ? { cleanupDirs: [dirname5(mcpConfigPath)] } : {},
3250
3374
  // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
3251
3375
  // Raise the -p background-agent wait so long TaskOutput polls are not
3252
3376
  // abandoned at Claude Code’s 10-minute default.
@@ -3374,15 +3498,15 @@ ${hint}` : hint;
3374
3498
  return { file: claude, args, cwd: thread.worktreePath };
3375
3499
  },
3376
3500
  async listLinearIssues(_repoPath) {
3377
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-N57PR6JM.js");
3501
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-VU47BNUV.js");
3378
3502
  return listAssignedLinearIssues2();
3379
3503
  }
3380
3504
  };
3381
3505
 
3382
3506
  // src/agents/codex.ts
3383
- import { existsSync as existsSync9, statSync } from "fs";
3384
- import { homedir as homedir7 } from "os";
3385
- import { join as join8 } from "path";
3507
+ import { existsSync as existsSync10, statSync } from "fs";
3508
+ import { homedir as homedir8 } from "os";
3509
+ import { join as join9 } from "path";
3386
3510
 
3387
3511
  // src/agents/codex-items.ts
3388
3512
  function eventsFromCodexItem(eventType, item) {
@@ -3434,7 +3558,7 @@ async function listCodexModels() {
3434
3558
  if (codex === "codex") {
3435
3559
  const which = await run("which", ["codex"], { reject: false });
3436
3560
  if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
3437
- } else if (!existsSync9(codex)) {
3561
+ } else if (!existsSync10(codex)) {
3438
3562
  return FALLBACK_CODEX_MODELS;
3439
3563
  }
3440
3564
  const listed = await run(codex, ["debug", "models"], { reject: false });
@@ -3471,7 +3595,7 @@ function usageFromCodex(usage, asContext = false) {
3471
3595
  return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
3472
3596
  }
3473
3597
  function codexHomeDir() {
3474
- return process.env.CODEX_HOME?.trim() || join8(homedir7(), ".codex");
3598
+ return process.env.CODEX_HOME?.trim() || join9(homedir8(), ".codex");
3475
3599
  }
3476
3600
  function unwrapCodexMcpResult(result) {
3477
3601
  if (result == null) return void 0;
@@ -3500,8 +3624,8 @@ function asRecord4(value) {
3500
3624
  return void 0;
3501
3625
  }
3502
3626
  function codexLooksAuthenticated() {
3503
- const authPath = join8(codexHomeDir(), "auth.json");
3504
- if (!existsSync9(authPath)) return false;
3627
+ const authPath = join9(codexHomeDir(), "auth.json");
3628
+ if (!existsSync10(authPath)) return false;
3505
3629
  try {
3506
3630
  return statSync(authPath).size > 2;
3507
3631
  } catch {
@@ -3513,7 +3637,7 @@ var codexAdapter = {
3513
3637
  async detect() {
3514
3638
  const codex = resolveAgentExecutable("codex");
3515
3639
  if (codex !== "codex") {
3516
- if (!existsSync9(codex)) {
3640
+ if (!existsSync10(codex)) {
3517
3641
  return {
3518
3642
  agent: "codex",
3519
3643
  installed: false,
@@ -3545,7 +3669,7 @@ var codexAdapter = {
3545
3669
  authenticated,
3546
3670
  linearMcp,
3547
3671
  warnings,
3548
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join8(codexHomeDir(), "auth.json")})`
3672
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join9(codexHomeDir(), "auth.json")})`
3549
3673
  };
3550
3674
  },
3551
3675
  async buildTurn(thread, input) {
@@ -3773,10 +3897,10 @@ var codexAdapter = {
3773
3897
  };
3774
3898
 
3775
3899
  // src/agents/cursor.ts
3776
- import { existsSync as existsSync10 } from "fs";
3777
- import { createRequire as createRequire3 } from "module";
3778
- import { dirname as dirname5, join as join9 } from "path";
3779
- import { fileURLToPath as fileURLToPath3 } from "url";
3900
+ import { existsSync as existsSync11 } from "fs";
3901
+ import { createRequire as createRequire4 } from "module";
3902
+ import { dirname as dirname6, join as join10 } from "path";
3903
+ import { fileURLToPath as fileURLToPath4 } from "url";
3780
3904
  var FALLBACK_CURSOR_MODELS = [
3781
3905
  { id: "default", displayName: "Auto" },
3782
3906
  { id: "composer-2.5", displayName: "Composer 2.5" },
@@ -3823,15 +3947,15 @@ async function listCursorModels() {
3823
3947
  return cachedModels?.models ?? FALLBACK_CURSOR_MODELS;
3824
3948
  }
3825
3949
  }
3826
- function entryDir2() {
3950
+ function entryDir3() {
3827
3951
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
3828
3952
  if (cjsDir) return cjsDir;
3829
3953
  try {
3830
- return dirname5(fileURLToPath3(import.meta.url));
3954
+ return dirname6(fileURLToPath4(import.meta.url));
3831
3955
  } catch {
3832
3956
  try {
3833
- const req = createRequire3(process.cwd() + "/");
3834
- return dirname5(req.resolve("@sideboard-ai/core"));
3957
+ const req = createRequire4(process.cwd() + "/");
3958
+ return dirname6(req.resolve("@sideboard-ai/core"));
3835
3959
  } catch {
3836
3960
  return process.cwd();
3837
3961
  }
@@ -3840,19 +3964,19 @@ function entryDir2() {
3840
3964
  function cursorRunnerPath() {
3841
3965
  const packaged = packagedCursorRunnerPath();
3842
3966
  if (packaged) return packaged;
3843
- const root = entryDir2();
3967
+ const root = entryDir3();
3844
3968
  const candidates = [
3845
- join9(root, "agents", "cursor-runner.js"),
3846
- join9(root, "agents", "cursor-runner.cjs"),
3969
+ join10(root, "agents", "cursor-runner.js"),
3970
+ join10(root, "agents", "cursor-runner.cjs"),
3847
3971
  // If somehow resolved from package root instead of dist/
3848
- join9(root, "dist", "agents", "cursor-runner.js"),
3849
- join9(root, "dist", "agents", "cursor-runner.cjs"),
3972
+ join10(root, "dist", "agents", "cursor-runner.js"),
3973
+ join10(root, "dist", "agents", "cursor-runner.cjs"),
3850
3974
  // Source tree (dev): packages/core/src/agents/cursor-runner.ts
3851
- join9(root, "cursor-runner.ts"),
3852
- join9(root, "src", "agents", "cursor-runner.ts")
3975
+ join10(root, "cursor-runner.ts"),
3976
+ join10(root, "src", "agents", "cursor-runner.ts")
3853
3977
  ];
3854
3978
  for (const candidate of candidates) {
3855
- if (existsSync10(candidate)) return candidate;
3979
+ if (existsSync11(candidate)) return candidate;
3856
3980
  }
3857
3981
  return candidates[0];
3858
3982
  }
@@ -3958,14 +4082,14 @@ var cursorAdapter = {
3958
4082
  };
3959
4083
 
3960
4084
  // src/agents/opencode.ts
3961
- import { existsSync as existsSync12 } from "fs";
4085
+ import { existsSync as existsSync13 } from "fs";
3962
4086
 
3963
4087
  // src/agent-rpc/opencode-host.ts
3964
4088
  import { pathToFileURL } from "url";
3965
4089
 
3966
4090
  // src/agent-rpc/opencode-hook.ts
3967
- import { existsSync as existsSync11, mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync4 } from "fs";
3968
- import { join as join10 } from "path";
4091
+ import { existsSync as existsSync12, mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync4 } from "fs";
4092
+ import { join as join11 } from "path";
3969
4093
  var OPENCODE_PLUGIN_SOURCE = `import { tool } from "@opencode-ai/plugin"
3970
4094
 
3971
4095
  const RPC_URL = process.env[${JSON.stringify(AGENT_RPC_URL_ENV)}] || ""
@@ -4075,10 +4199,10 @@ export const SideboardRpc = async (ctx) => {
4075
4199
  }
4076
4200
  `;
4077
4201
  function writeOpencodeRpcPlugin() {
4078
- const pluginDir = join10(appDataDir(), "agent-rpc", "opencode");
4202
+ const pluginDir = join11(appDataDir(), "agent-rpc", "opencode");
4079
4203
  mkdirSync3(pluginDir, { recursive: true });
4080
- const pluginFile = join10(pluginDir, "sideboard-rpc.js");
4081
- if (existsSync11(pluginFile)) {
4204
+ const pluginFile = join11(pluginDir, "sideboard-rpc.js");
4205
+ if (existsSync12(pluginFile)) {
4082
4206
  try {
4083
4207
  if (readFileSync5(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
4084
4208
  } catch {
@@ -4179,7 +4303,7 @@ async function listOpencodeModels() {
4179
4303
  if (opencode === "opencode") {
4180
4304
  const which = await run("which", ["opencode"], { reject: false });
4181
4305
  if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
4182
- } else if (!existsSync12(opencode)) {
4306
+ } else if (!existsSync13(opencode)) {
4183
4307
  return FALLBACK_OPENCODE_MODELS;
4184
4308
  }
4185
4309
  const listed = await run(opencode, ["models"], { reject: false });
@@ -4214,7 +4338,7 @@ var opencodeAdapter = {
4214
4338
  async detect() {
4215
4339
  const opencode = resolveAgentExecutable("opencode");
4216
4340
  if (opencode !== "opencode") {
4217
- if (!existsSync12(opencode)) {
4341
+ if (!existsSync13(opencode)) {
4218
4342
  return {
4219
4343
  agent: "opencode",
4220
4344
  installed: false,
@@ -4465,7 +4589,7 @@ var opencodeAdapter = {
4465
4589
  };
4466
4590
  },
4467
4591
  async listLinearIssues(_repoPath) {
4468
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-N57PR6JM.js");
4592
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-VU47BNUV.js");
4469
4593
  return listAssignedLinearIssues2();
4470
4594
  }
4471
4595
  };
@@ -4497,7 +4621,7 @@ async function listBrightsyModels() {
4497
4621
  }
4498
4622
  }
4499
4623
  async function listModelsForAgent(agent) {
4500
- const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy"];
4624
+ const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy", "acp"];
4501
4625
  const out = [];
4502
4626
  for (const kind of kinds) {
4503
4627
  if (kind === "claude") {
@@ -4536,6 +4660,15 @@ async function listModelsForAgent(agent) {
4536
4660
  });
4537
4661
  continue;
4538
4662
  }
4663
+ if (kind === "acp") {
4664
+ out.push({
4665
+ agent: kind,
4666
+ auto: true,
4667
+ models: [],
4668
+ note: "Gemini CLI and Copilot CLI choose the model. Leave model unset."
4669
+ });
4670
+ continue;
4671
+ }
4539
4672
  if (kind === "brightsy") {
4540
4673
  const models = await listBrightsyModels();
4541
4674
  out.push({
@@ -4654,7 +4787,8 @@ var adapters = {
4654
4787
  codex: codexAdapter,
4655
4788
  opencode: opencodeAdapter,
4656
4789
  brightsy: brightsyAdapter,
4657
- cursor: cursorAdapter
4790
+ cursor: cursorAdapter,
4791
+ acp: acpAdapter
4658
4792
  };
4659
4793
  function getAdapter(kind) {
4660
4794
  return adapters[kind];
@@ -4679,7 +4813,6 @@ export {
4679
4813
  adjustBrightsyTurnExit,
4680
4814
  listBrightsyChatTargets,
4681
4815
  brightsyAdapter,
4682
- mcpStatusThinkingFromClaudeInit,
4683
4816
  mcpUiContentSecurityPolicy,
4684
4817
  SIDEBOARD_MCP_PROFILE_ENV,
4685
4818
  SIDEBOARD_THREAD_ID_ENV,
@@ -4704,6 +4837,10 @@ export {
4704
4837
  registerPackagedUserMcpClients,
4705
4838
  isInjectedOrchMcpName,
4706
4839
  userMcpNamesToDisable,
4840
+ acpRunnerPath,
4841
+ acpAdapter,
4842
+ acpHarnessDisplayName,
4843
+ mcpStatusThinkingFromClaudeInit,
4707
4844
  getMcpUiHost,
4708
4845
  closeMcpUiHost,
4709
4846
  parseClaudeUsagePayload,