@sideboard-ai/core 0.1.345 → 0.1.347

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 (67) hide show
  1. package/dist/{abletime-MSIMJKKQ.js → abletime-3HRWLQZJ.js} +4 -4
  2. package/dist/{abletime-X2TJ6PPK.js → abletime-CGFJZB7L.js} +4 -4
  3. package/dist/{abletime-oauth-DEIENLHC.js → abletime-oauth-JQDSH5OL.js} +3 -3
  4. package/dist/{abletime-oauth-2RUKRZYZ.js → abletime-oauth-QNJQLHR4.js} +3 -3
  5. package/dist/{abletime-rest-UBLSGMSA.js → abletime-rest-TANL5TMY.js} +3 -3
  6. package/dist/{abletime-rest-HWBUPI4R.js → abletime-rest-UQA2CRZN.js} +3 -3
  7. package/dist/{agents-AQM7NLXD.js → agents-5MFGVK7C.js} +7 -7
  8. package/dist/{agents-7CHZO3K3.js → agents-T4XBZZDA.js} +7 -7
  9. package/dist/{app-settings-Q2F57NVK.js → app-settings-PPIMYJKS.js} +3 -1
  10. package/dist/{app-settings-A6JUT2SF.js → app-settings-SNOPJ7P5.js} +3 -1
  11. package/dist/{chunk-5IMXA563.js → chunk-27XWAI7S.js} +22 -22
  12. package/dist/{chunk-RTZO2YJC.js → chunk-2HPVGTHF.js} +2 -2
  13. package/dist/{chunk-GHKJBZW5.js → chunk-4NXGVJA6.js} +2 -2
  14. package/dist/{chunk-O5WRVQFT.js → chunk-5FUAOU3G.js} +1 -1
  15. package/dist/{chunk-3J3XOIHF.js → chunk-62ALWH3T.js} +3 -3
  16. package/dist/{chunk-J3BQHHDZ.js → chunk-6TV6L2DD.js} +4 -4
  17. package/dist/{chunk-4PHOJMZI.js → chunk-6WMNIX2U.js} +35 -2
  18. package/dist/{chunk-4PXHJA5K.js → chunk-7B2OUQON.js} +2 -2
  19. package/dist/{chunk-TD76ORBJ.js → chunk-AJMERXZP.js} +2 -2
  20. package/dist/{chunk-QTDCPMOW.js → chunk-ATS7SYHG.js} +1 -1
  21. package/dist/{chunk-AG2RM3DF.js → chunk-CEQ4Z32M.js} +3 -3
  22. package/dist/{chunk-5TS3KVGI.js → chunk-E77SRVVO.js} +1 -1
  23. package/dist/{chunk-5SJGR3VS.js → chunk-F7WP2U5I.js} +12 -9
  24. package/dist/{chunk-YFPSTG52.js → chunk-FDYMVJFU.js} +5 -5
  25. package/dist/{chunk-IYX53WZY.js → chunk-GAGTEI6B.js} +5 -5
  26. package/dist/{chunk-JZKNRDKF.js → chunk-IJNTTVFH.js} +23 -23
  27. package/dist/{chunk-MB3GOWB3.js → chunk-IVRWRYTH.js} +19 -10
  28. package/dist/{chunk-3DMRQB4Y.js → chunk-JCYGQKER.js} +1 -1
  29. package/dist/{chunk-JHT3CYLT.js → chunk-MOUAM6ZC.js} +1 -1
  30. package/dist/{chunk-Z54FI4VL.js → chunk-NTY5WGRD.js} +2 -2
  31. package/dist/{chunk-LHU6ZBFB.js → chunk-OHUAAX3O.js} +2 -2
  32. package/dist/{chunk-NQHEEGTH.js → chunk-PVCECFJK.js} +1 -1
  33. package/dist/{chunk-MHRU743Z.js → chunk-Q4TZA4MN.js} +2247 -2155
  34. package/dist/{chunk-4SNEW63T.js → chunk-RUIHNWRV.js} +3 -3
  35. package/dist/{chunk-NDBMDHQ5.js → chunk-RYPD7XWV.js} +5 -5
  36. package/dist/{chunk-FNAP6CCS.js → chunk-UJMCTGV7.js} +2 -2
  37. package/dist/{chunk-S3UGLMGE.js → chunk-WWU4SYZR.js} +35 -2
  38. package/dist/{chunk-4YGVJRXY.js → chunk-XNGW4OYD.js} +4 -4
  39. package/dist/{chunk-TW63CYUA.js → chunk-Y6VQX2LY.js} +2679 -2587
  40. package/dist/{chunk-BD7KUYJA.js → chunk-ZJMYCDYQ.js} +5 -5
  41. package/dist/{conductor-DUHRZUQY.js → conductor-EMGMDNHL.js} +5 -5
  42. package/dist/{conductor-3A2TNWUW.js → conductor-LYQKONSA.js} +5 -5
  43. package/dist/{coordinator-prompt-OX6A4MDA.js → coordinator-prompt-DLY3FS2L.js} +4 -4
  44. package/dist/{coordinator-prompt-7QALNDIV.js → coordinator-prompt-WALVMGKI.js} +4 -4
  45. package/dist/{global-workspace-HM2RKBCT.js → global-workspace-7OQ5O6JT.js} +4 -4
  46. package/dist/{global-workspace-6GGS3DWU.js → global-workspace-UG2A3CEM.js} +4 -4
  47. package/dist/index.cjs +1090 -640
  48. package/dist/index.d.cts +62 -8
  49. package/dist/index.d.ts +62 -8
  50. package/dist/index.js +325 -32
  51. package/dist/{linear-WYI64BMX.js → linear-MIJO6DCV.js} +2 -2
  52. package/dist/{linear-JE4WAZ3W.js → linear-PKYJH4WK.js} +2 -2
  53. package/dist/{linear-list-I4NAOWPN.js → linear-list-JPQ27RXG.js} +1 -1
  54. package/dist/{linear-list-CGUCPWTV.js → linear-list-N57PR6JM.js} +1 -1
  55. package/dist/mcp/run-stdio.cjs +500 -224
  56. package/dist/mcp/run-stdio.js +106 -21
  57. package/dist/{optional-cli-7QXXPEN6.js → optional-cli-4GTEDEYJ.js} +3 -3
  58. package/dist/{optional-cli-YHLVTVRK.js → optional-cli-RPJIQBDX.js} +4 -4
  59. package/dist/{orchestrator-OWO6LQ5U.js → orchestrator-AJZNVREM.js} +10 -10
  60. package/dist/{orchestrator-POMFVZLB.js → orchestrator-BUEPWNCF.js} +10 -10
  61. package/dist/{thread-store-HETUMDVA.js → thread-store-MEUWZDVV.js} +2 -2
  62. package/dist/{thread-store-V5IDUJ4L.js → thread-store-R3G5VBII.js} +2 -2
  63. package/dist/{workspaces-DTMPNDPW.js → workspaces-35T6FW57.js} +4 -4
  64. package/dist/{workspaces-V6IIBSKA.js → workspaces-KWGTP7DI.js} +4 -4
  65. package/dist/{worktree-FX5FT6BI.js → worktree-5P7SCST3.js} +3 -3
  66. package/dist/{worktree-BD3EJE24.js → worktree-ROJXGBWS.js} +3 -3
  67. package/package.json +1 -1
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-XOEKCE6L.js";
7
7
  import {
8
8
  listAssignedLinearIssues
9
- } from "./chunk-O5WRVQFT.js";
9
+ } from "./chunk-5FUAOU3G.js";
10
10
  import {
11
11
  looksLikeConversationSummary,
12
12
  looksLikeSkillBody,
@@ -15,13 +15,13 @@ import {
15
15
  } from "./chunk-BIM24I3O.js";
16
16
  import {
17
17
  isOrchestratorThread
18
- } from "./chunk-4YGVJRXY.js";
18
+ } from "./chunk-XNGW4OYD.js";
19
19
  import {
20
20
  codexUnattendedGitConfigArgs,
21
21
  mergeAgentGitAuthEnv,
22
22
  resolveAgentGitAuthEnv,
23
23
  resolveCodexGitWritableRoots
24
- } from "./chunk-Z54FI4VL.js";
24
+ } from "./chunk-NTY5WGRD.js";
25
25
  import {
26
26
  loadBrightsyConfig
27
27
  } from "./chunk-RSA47QYR.js";
@@ -80,7 +80,7 @@ import {
80
80
  requestOccupancy,
81
81
  resolveAgentExecutable,
82
82
  resolveClaudeExecutable
83
- } from "./chunk-4PHOJMZI.js";
83
+ } from "./chunk-6WMNIX2U.js";
84
84
  import {
85
85
  isElectronLikeCommand,
86
86
  unwrapStrippedElectronLaunch
@@ -517,7 +517,7 @@ var brightsyAdapter = {
517
517
  };
518
518
 
519
519
  // src/agents/claude.ts
520
- import { existsSync as existsSync7 } from "fs";
520
+ import { existsSync as existsSync8 } from "fs";
521
521
  import { dirname as dirname4 } from "path";
522
522
 
523
523
  // src/agents/claude-mcp-status.ts
@@ -2165,1261 +2165,976 @@ function dirsKeyFor(projectDirs) {
2165
2165
  return createHash("sha256").update(projectDirs.join("\0")).digest("hex").slice(0, 16);
2166
2166
  }
2167
2167
 
2168
- // src/agents/types.ts
2169
- var PLAN_MODE_INSTRUCTION = "Plan mode is active and must remain active until the user turns Plan mode off in the UI (or Approves / Hands off the plan). Analyze the codebase, search and read files as needed, and produce or refine a clear implementation plan. Do not modify, create, or delete any project files except via Sideboard MCP present_plan (writes .context/attachments/plan.md). When you need a clarifying decision (approach forks, auth choice, scope) \u2014 not greetings, check-ins, or an invented task menu: (1) first write a short chat message that explains the decision and what each option means (tradeoffs, when to pick it) \u2014 do not leave the user staring at bare labels; (2) then call Sideboard MCP ask_user with the same options, including a description on every option. If one option is the obvious default, proceed without asking. Sideboard shows questions in the composer and mirrors them in chat. After ask_user, wait for the user's next message with their answers before finalizing the plan. When the plan is ready for approval: (1) call present_plan with the full markdown plan (title + content) so Sideboard saves .context/attachments/plan.md and shows it in chat for Approve / Hand off / Copy; (2) Claude should also call ExitPlanMode after present_plan. Do not skip present_plan \u2014 the plan must be a markdown file, not only chat prose.";
2170
- var PLAN_MODE_OFF_INSTRUCTION = "Plan mode is off. Do not call present_plan or ExitPlanMode \u2014 those only work when the user turns Plan on in the composer. If you need to propose an approach, write it in chat.";
2171
- function planModeTurnInstruction(planMode) {
2172
- return planMode ? PLAN_MODE_INSTRUCTION : PLAN_MODE_OFF_INSTRUCTION;
2173
- }
2174
- function permissionMode(thread) {
2175
- if (thread.planMode) {
2176
- return {
2177
- claude: "plan",
2178
- opencodePermission: JSON.stringify({
2179
- edit: "deny",
2180
- write: "deny",
2181
- bash: { "*": "deny" }
2182
- }),
2183
- codexSandbox: "read-only"
2184
- };
2168
+ // src/agents/claude-usage-client.ts
2169
+ import { existsSync as existsSync6, readFileSync as readFileSync4 } from "fs";
2170
+ import { homedir as homedir6 } from "os";
2171
+ import { join as join6 } from "path";
2172
+
2173
+ // src/agents/claude-usage.ts
2174
+ var WINDOW_META = {
2175
+ five_hour: {
2176
+ label: "5-hour session",
2177
+ shortLabel: "5h",
2178
+ detail: "Rolling 5-hour limit across all models"
2179
+ },
2180
+ seven_day: {
2181
+ label: "Weekly",
2182
+ shortLabel: "wk",
2183
+ detail: "7-day cap across all models"
2184
+ },
2185
+ seven_day_opus: {
2186
+ label: "Opus",
2187
+ shortLabel: "Opus",
2188
+ detail: "Weekly Opus-only cap"
2189
+ },
2190
+ seven_day_sonnet: {
2191
+ label: "Sonnet",
2192
+ shortLabel: "Sonnet",
2193
+ detail: "Weekly Sonnet-only cap"
2185
2194
  }
2186
- if (thread.sourceType === "orchestration") {
2187
- return {
2188
- claude: "acceptEdits",
2189
- // Unattended coordinators cannot answer permission prompts. Explicit
2190
- // allows override the user's OpenCode denies for this process only.
2191
- opencodePermission: JSON.stringify({
2192
- edit: "allow",
2193
- bash: { "*": "allow" }
2194
- }),
2195
- codexSandbox: "danger-full-access"
2196
- };
2195
+ };
2196
+ var WINDOW_ORDER = [
2197
+ "five_hour",
2198
+ "seven_day",
2199
+ "seven_day_opus",
2200
+ "seven_day_sonnet"
2201
+ ];
2202
+ function parseClaudeResetsAt(value) {
2203
+ if (typeof value === "number" && Number.isFinite(value)) {
2204
+ const ms = value > 1e12 ? value : value * 1e3;
2205
+ const d = new Date(ms);
2206
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
2197
2207
  }
2198
- if (thread.autonomy === "full") {
2199
- return {
2200
- claude: "bypassPermissions",
2201
- opencodePermission: JSON.stringify({ "*": "allow" }),
2202
- codexSandbox: "workspace-write"
2203
- };
2208
+ if (typeof value === "string") {
2209
+ const trimmed = value.trim();
2210
+ if (!trimmed) return null;
2211
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
2212
+ return parseClaudeResetsAt(Number(trimmed));
2213
+ }
2214
+ const d = new Date(trimmed);
2215
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
2204
2216
  }
2217
+ return null;
2218
+ }
2219
+ function parseClaudeUtilization(value) {
2220
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
2221
+ return Math.max(0, Math.min(100, value));
2222
+ }
2223
+ function windowFromRaw(id, raw) {
2224
+ if (!raw || typeof raw !== "object") return null;
2225
+ const row = raw;
2226
+ const used = parseClaudeUtilization(row.utilization ?? row.used_percentage);
2227
+ if (used == null) return null;
2228
+ const meta = WINDOW_META[id];
2205
2229
  return {
2206
- claude: "acceptEdits",
2207
- opencodePermission: JSON.stringify({}),
2208
- codexSandbox: "workspace-write"
2230
+ id,
2231
+ label: meta.label,
2232
+ shortLabel: meta.shortLabel,
2233
+ detail: meta.detail,
2234
+ usedPercent: used,
2235
+ remainingPercent: Math.max(0, Math.min(100, 100 - used)),
2236
+ resetsAt: parseClaudeResetsAt(row.resets_at)
2209
2237
  };
2210
2238
  }
2211
-
2212
- // src/agent-rpc/rpc-env.ts
2213
- function worktreeAgentRpc(isOrchestrator) {
2214
- return isOrchestrator ? null : agentRpcConnectFromMetadata();
2239
+ function extraUsageFromRaw(raw) {
2240
+ if (!raw || typeof raw !== "object") return void 0;
2241
+ const row = raw;
2242
+ const enabled = row.is_enabled === true || row.enabled === true;
2243
+ if (!enabled && row.is_enabled !== false && row.enabled !== false) return void 0;
2244
+ const usedCredits = numberOrUndef(row.used_credits ?? row.used);
2245
+ const monthlyLimit = numberOrUndef(row.monthly_limit);
2246
+ const usedPercent = parseClaudeUtilization(row.utilization) ?? void 0;
2247
+ return {
2248
+ enabled,
2249
+ ...usedCredits != null ? { usedCredits } : {},
2250
+ ...monthlyLimit != null ? { monthlyLimit } : {},
2251
+ ...usedPercent != null ? { usedPercent } : {}
2252
+ };
2215
2253
  }
2216
- function agentRpcChildEnv(rpc, cwd) {
2254
+ function numberOrUndef(value) {
2255
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
2256
+ return value;
2257
+ }
2258
+ function parseClaudeUsagePayload(raw, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
2259
+ if (!raw || typeof raw !== "object") return null;
2260
+ const obj = raw;
2261
+ const source = obj.rate_limits && typeof obj.rate_limits === "object" ? obj.rate_limits : obj;
2262
+ const windows = [];
2263
+ for (const id of WINDOW_ORDER) {
2264
+ const parsed = windowFromRaw(id, source[id]);
2265
+ if (parsed) windows.push(parsed);
2266
+ }
2267
+ if (windows.length === 0) return null;
2268
+ const extra = extraUsageFromRaw(obj.extra_usage ?? source.extra_usage);
2217
2269
  return {
2218
- [AGENT_RPC_NATIVE_ENV]: "1",
2219
- [AGENT_RPC_URL_ENV]: rpc.url,
2220
- [AGENT_RPC_TOKEN_ENV]: rpc.authToken,
2221
- [AGENT_RPC_CWD_ENV]: cwd
2270
+ windows,
2271
+ ...extra ? { extraUsage: extra } : {},
2272
+ fetchedAt
2222
2273
  };
2223
2274
  }
2224
-
2225
- // src/agents/claude-host.ts
2226
- import { existsSync as existsSync6 } from "fs";
2227
- import { createRequire as createRequire2 } from "module";
2228
- import { dirname as dirname3, join as join6 } from "path";
2229
- import { fileURLToPath as fileURLToPath2 } from "url";
2230
- function claudePilotSdkAllowedTools() {
2231
- return PILOT_TOOL_NAMES.map(
2232
- (name) => `mcp__${AGENT_RPC_CLAUDE_SDK_SERVER}__${name}`
2233
- );
2275
+ function hottestClaudeWindow(usage) {
2276
+ if (usage.windows.length === 0) return null;
2277
+ return usage.windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);
2234
2278
  }
2235
- function withClaudePilotRpcTools(allowed) {
2236
- const omit = new Set(PILOT_TOOL_NAMES.map((name) => `mcp__sideboard__${name}`));
2237
- return [...allowed.filter((name) => !omit.has(name)), ...claudePilotSdkAllowedTools()];
2279
+ function formatClaudeUsageReset(resetsAt, now = /* @__PURE__ */ new Date()) {
2280
+ if (!resetsAt) return "";
2281
+ const at = new Date(resetsAt);
2282
+ if (Number.isNaN(at.getTime())) return "";
2283
+ const ms = at.getTime() - now.getTime();
2284
+ if (ms <= 0) return "resets soon";
2285
+ const minutes = Math.round(ms / 6e4);
2286
+ if (minutes < 60) return `resets in ${Math.max(1, minutes)}m`;
2287
+ const hours = Math.round(minutes / 60);
2288
+ if (hours < 36) return `resets in ${hours}h`;
2289
+ try {
2290
+ return `resets ${at.toLocaleString(void 0, {
2291
+ weekday: "short",
2292
+ hour: "numeric",
2293
+ minute: "2-digit"
2294
+ })}`;
2295
+ } catch {
2296
+ return `resets ${at.toISOString()}`;
2297
+ }
2238
2298
  }
2239
- function entryDir() {
2240
- const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
2241
- if (cjsDir) return cjsDir;
2299
+ function formatClaudeUsageResetClock(resetsAt) {
2300
+ if (!resetsAt) return "";
2301
+ const at = new Date(resetsAt);
2302
+ if (Number.isNaN(at.getTime())) return "";
2242
2303
  try {
2243
- return dirname3(fileURLToPath2(import.meta.url));
2304
+ return at.toLocaleString(void 0, {
2305
+ weekday: "short",
2306
+ month: "short",
2307
+ day: "numeric",
2308
+ hour: "numeric",
2309
+ minute: "2-digit"
2310
+ });
2244
2311
  } catch {
2245
- try {
2246
- const req = createRequire2(process.cwd() + "/");
2247
- return dirname3(req.resolve("@sideboard-ai/core"));
2248
- } catch {
2249
- return process.cwd();
2250
- }
2312
+ return at.toISOString();
2251
2313
  }
2252
2314
  }
2253
- function claudeRunnerPath() {
2254
- const packagedDir = packagedCursorRuntimeDir();
2255
- if (packagedDir) {
2256
- const packaged = join6(packagedDir, "core-dist", "agents", "claude-runner.js");
2257
- if (existsSync6(packaged)) return packaged;
2315
+ function formatClaudeUsageFetchedAt(fetchedAt, now = /* @__PURE__ */ new Date()) {
2316
+ const at = new Date(fetchedAt);
2317
+ if (Number.isNaN(at.getTime())) return "";
2318
+ const minutes = Math.max(0, Math.round((now.getTime() - at.getTime()) / 6e4));
2319
+ if (minutes < 1) return "Updated just now";
2320
+ if (minutes < 60) return `Updated ${minutes}m ago`;
2321
+ const hours = Math.round(minutes / 60);
2322
+ if (hours < 36) return `Updated ${hours}h ago`;
2323
+ return `Updated ${formatClaudeUsageResetClock(fetchedAt)}`;
2324
+ }
2325
+ function formatClaudeExtraUsageDetail(extra) {
2326
+ if (!extra.enabled) return "Extra usage off";
2327
+ const bits = ["Extra usage on"];
2328
+ if (extra.usedCredits != null && extra.monthlyLimit != null) {
2329
+ bits.push(`${extra.usedCredits} / ${extra.monthlyLimit} credits this month`);
2330
+ } else if (extra.usedCredits != null) {
2331
+ bits.push(`${extra.usedCredits} credits used`);
2258
2332
  }
2259
- const root = entryDir();
2260
- const candidates = [
2261
- join6(root, "agents", "claude-runner.js"),
2262
- join6(root, "agents", "claude-runner.cjs"),
2263
- join6(root, "dist", "agents", "claude-runner.js"),
2264
- join6(root, "dist", "agents", "claude-runner.cjs"),
2265
- join6(root, "claude-runner.ts"),
2266
- join6(root, "src", "agents", "claude-runner.ts")
2267
- ];
2268
- for (const candidate of candidates) {
2269
- if (existsSync6(candidate)) return candidate;
2333
+ if (extra.usedPercent != null) {
2334
+ bits.push(`${Math.round(extra.usedPercent)}% of extra pool`);
2270
2335
  }
2271
- return candidates[0];
2272
- }
2273
- async function buildClaudeRpcTurnCommand(req) {
2274
- const runner = claudeRunnerPath();
2275
- const isTs = runner.endsWith(".ts");
2276
- const launch = applyNodeLaunch(
2277
- await resolveNodeLaunch(runner),
2278
- isTs ? ["--import", "tsx", runner] : [runner]
2279
- );
2280
- return {
2281
- file: launch.file,
2282
- args: launch.args,
2283
- cwd: req.cwd,
2284
- stdin: JSON.stringify(req),
2285
- env: {
2286
- ...launch.env,
2287
- CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
2288
- CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? "7200000",
2289
- ...req.isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
2290
- }
2291
- };
2336
+ return bits.join(" \xB7 ");
2292
2337
  }
2293
-
2294
- // src/agents/claude.ts
2295
- function isLocalDevAppDataDir(dir = process.env.SIDEBOARD_APP_DATA) {
2296
- return /[/\\]\.sideboard[/\\]dev-app-data(?:[/\\]|$)/.test(dir ?? "");
2338
+ function formatClaudeUsageWindowLine(window, now = /* @__PURE__ */ new Date()) {
2339
+ const reset = formatClaudeUsageReset(window.resetsAt, now);
2340
+ const clock = formatClaudeUsageResetClock(window.resetsAt);
2341
+ const left = `${Math.round(window.remainingPercent)}% left`;
2342
+ const used = `${Math.round(window.usedPercent)}% used`;
2343
+ const resetBit = reset ? clock && !reset.includes(clock) ? `${reset} (${clock})` : reset : "";
2344
+ return resetBit ? `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used} \xB7 ${resetBit}` : `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used}`;
2297
2345
  }
2298
- var CLAUDE_PROMPT_ARG_MAX = 2e5;
2299
- function usageFromClaude(usage) {
2300
- if (!usage) return null;
2301
- const inputTokens = Number(usage.input_tokens ?? 0);
2302
- const outputTokens = Number(usage.output_tokens ?? 0);
2303
- const cacheReadTokens = Number(usage.cache_read_input_tokens ?? 0);
2304
- const cacheWriteTokens = Number(usage.cache_creation_input_tokens ?? 0);
2305
- if (!inputTokens && !outputTokens && !cacheReadTokens && !cacheWriteTokens) return null;
2346
+ function formatClaudeUsageTooltip(usage, now = /* @__PURE__ */ new Date()) {
2347
+ const lines = [
2348
+ "Claude Code plan",
2349
+ ...usage.windows.map((w) => formatClaudeUsageWindowLine(w, now))
2350
+ ];
2351
+ if (usage.extraUsage) {
2352
+ lines.push(formatClaudeExtraUsageDetail(usage.extraUsage));
2353
+ }
2354
+ const fetched = formatClaudeUsageFetchedAt(usage.fetchedAt, now);
2355
+ if (fetched) lines.push(fetched);
2356
+ return lines.join("\n");
2357
+ }
2358
+ function formatClaudeUsageCompact(window) {
2359
+ return `${window.shortLabel} ${Math.round(window.remainingPercent)}%`;
2360
+ }
2361
+ function claudeUsageWindowOverLimit(window) {
2362
+ return window.remainingPercent <= 0 || window.usedPercent >= 100;
2363
+ }
2364
+ function claudeUsageOverLimitWindows(usage) {
2365
+ if (!usage) return [];
2366
+ return usage.windows.filter(claudeUsageWindowOverLimit);
2367
+ }
2368
+ function formatOverLimitWindowList(windows, now) {
2369
+ const parts = windows.map((w) => {
2370
+ const reset = formatClaudeUsageReset(w.resetsAt, now);
2371
+ return reset ? `${w.label} (${reset})` : w.label;
2372
+ });
2306
2373
  return {
2307
- inputTokens,
2308
- outputTokens,
2309
- cacheReadTokens: cacheReadTokens || void 0,
2310
- cacheWriteTokens: cacheWriteTokens || void 0
2374
+ list: parts.join(", "),
2375
+ verb: windows.length === 1 ? "is" : "are"
2311
2376
  };
2312
2377
  }
2313
- function costUsdFromClaudeResult(obj) {
2314
- const modelUsage = obj.modelUsage ?? obj.model_usage;
2315
- if (modelUsage && typeof modelUsage === "object") {
2316
- let sum = 0;
2317
- let any = false;
2318
- for (const entry of Object.values(modelUsage)) {
2319
- if (!entry || typeof entry !== "object") continue;
2320
- const row = entry;
2321
- const cost = row.costUSD ?? row.cost_usd;
2322
- if (cost != null && Number.isFinite(Number(cost))) {
2323
- sum += Number(cost);
2324
- any = true;
2325
- }
2326
- }
2327
- if (any) return sum;
2328
- }
2329
- const totalCost = obj.total_cost_usd ?? obj.totalCostUsd;
2330
- if (totalCost != null && Number.isFinite(Number(totalCost))) {
2331
- return Number(totalCost);
2332
- }
2333
- return void 0;
2378
+ function formatClaudeUsageOverLimitConfirm(windows, now = /* @__PURE__ */ new Date()) {
2379
+ if (windows.length === 0) return "";
2380
+ const { list, verb } = formatOverLimitWindowList(windows, now);
2381
+ return `Claude Code ${list} ${verb} at or over the plan limit. Send this message anyway?`;
2334
2382
  }
2335
- function sessionCostUsdFromClaudeResult(obj) {
2336
- const totalCost = obj.total_cost_usd ?? obj.totalCostUsd;
2337
- if (totalCost != null && Number.isFinite(Number(totalCost))) {
2338
- return Number(totalCost);
2339
- }
2340
- return void 0;
2383
+ function formatClaudeUsageOverLimitWait(windows, now = /* @__PURE__ */ new Date()) {
2384
+ if (windows.length === 0) return "";
2385
+ const { list, verb } = formatOverLimitWindowList(windows, now);
2386
+ return `Claude Code ${list} ${verb} at or over the plan limit. Sending is paused until the window resets.`;
2341
2387
  }
2342
- function claudeResultErrorDetail(obj) {
2343
- const isError = Boolean(obj.is_error) || typeof obj.subtype === "string" && /^error/i.test(obj.subtype);
2344
- const fromResult = typeof obj.result === "string" ? obj.result.trim() : "";
2345
- const shortFailure = fromResult.length > 0 && fromResult.length <= 300 && !fromResult.includes("\n") && looksLikeAgentFailureMessage(fromResult);
2346
- if (fromResult && (isError || shortFailure)) {
2347
- return fromResult;
2388
+
2389
+ // src/agents/claude-usage-client.ts
2390
+ var CLAUDE_OAUTH_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
2391
+ var CLAUDE_USAGE_TTL_MS = 9e4;
2392
+ var CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
2393
+ var CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
2394
+ var KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
2395
+ var cache = null;
2396
+ var errorUntil = 0;
2397
+ var inflight = null;
2398
+ var lastGood = null;
2399
+ var claudeVersion = null;
2400
+ var cacheDirKey = "";
2401
+ function usageCacheDir(opts) {
2402
+ return opts.configDir?.trim() || "";
2403
+ }
2404
+ function adoptCacheDir(dir) {
2405
+ if (dir === cacheDirKey) return;
2406
+ cache = null;
2407
+ lastGood = null;
2408
+ errorUntil = 0;
2409
+ inflight = null;
2410
+ cacheDirKey = dir;
2411
+ }
2412
+ function accessTokenFromCredentialsJson(raw) {
2413
+ const trimmed = raw.trim();
2414
+ if (!trimmed) return null;
2415
+ if (trimmed.startsWith("sk-ant-")) {
2416
+ const token = trimmed.split(/\s+/)[0];
2417
+ return token || null;
2348
2418
  }
2349
- if (!isError) return null;
2350
- const errors = obj.errors;
2351
- if (Array.isArray(errors)) {
2352
- const parts = errors.map((e) => {
2353
- if (typeof e === "string") return e.trim();
2354
- if (e && typeof e === "object" && typeof e.message === "string") {
2355
- return e.message.trim();
2356
- }
2357
- return "";
2358
- }).filter(Boolean);
2359
- if (parts.length) return parts.join("; ");
2419
+ try {
2420
+ const parsed = JSON.parse(trimmed);
2421
+ const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
2422
+ const token = oauth.accessToken ?? oauth.access_token;
2423
+ return typeof token === "string" && token.trim() ? token.trim() : null;
2424
+ } catch {
2425
+ return null;
2360
2426
  }
2361
- if (typeof obj.error === "string" && obj.error.trim()) return obj.error.trim();
2362
- if (typeof obj.subtype === "string" && obj.subtype) {
2363
- return obj.subtype.replace(/^error[_-]?/i, "").replace(/_/g, " ") || "Claude turn failed";
2427
+ }
2428
+ function claudeCredentialsPath(configDir) {
2429
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir6(), ".claude");
2430
+ return join6(root, ".credentials.json");
2431
+ }
2432
+ async function readFileAccessToken(configDir) {
2433
+ const path = claudeCredentialsPath(configDir);
2434
+ if (!existsSync6(path)) return null;
2435
+ try {
2436
+ return accessTokenFromCredentialsJson(readFileSync4(path, "utf8"));
2437
+ } catch {
2438
+ return null;
2364
2439
  }
2365
- return "Claude turn failed";
2366
2440
  }
2367
- function toolResultContent(block) {
2368
- if (typeof block.content === "string") return block.content;
2369
- if (Array.isArray(block.content)) {
2370
- return block.content.map(
2371
- (c) => typeof c === "string" ? c : c && typeof c === "object" && "text" in c ? String(c.text ?? "") : ""
2372
- ).join("");
2441
+ async function readKeychainAccessToken(configDir) {
2442
+ if (process.platform !== "darwin") return null;
2443
+ const root = configDir?.trim();
2444
+ const accounts = root ? [root, void 0] : [void 0];
2445
+ for (const service of KEYCHAIN_SERVICES) {
2446
+ for (const account of accounts) {
2447
+ const args = ["find-generic-password", "-s", service, "-w"];
2448
+ if (account) args.splice(3, 0, "-a", account);
2449
+ const result = await run("security", args, {
2450
+ reject: false,
2451
+ timeoutMs: 4e3
2452
+ });
2453
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
2454
+ const token = accessTokenFromCredentialsJson(result.stdout);
2455
+ if (token) return token;
2456
+ }
2373
2457
  }
2374
- if (block.content != null) return JSON.stringify(block.content);
2375
- return void 0;
2458
+ return null;
2376
2459
  }
2377
- function skillToolEventsFromBody(text, parentId) {
2378
- const command = skillCommandFromBody(text) ?? "skill";
2379
- const id = `skill-${command}`;
2380
- return [
2381
- withEventParentId(
2382
- { type: "tool_use", id, name: "Skill", input: { skill: command } },
2383
- parentId
2384
- ),
2385
- withEventParentId({ type: "tool_result", id, content: text }, parentId)
2386
- ];
2460
+ async function readClaudeAccessToken(configDir) {
2461
+ const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
2462
+ if (envToken) return envToken;
2463
+ const fromFile = await readFileAccessToken(configDir);
2464
+ if (fromFile) return fromFile;
2465
+ return readKeychainAccessToken(configDir);
2387
2466
  }
2388
- function compactToolEventsFromBody(text, parentId) {
2389
- const id = "compact-summary";
2390
- return [
2391
- withEventParentId(
2392
- { type: "tool_use", id, name: "Compact", input: { trigger: "injected" } },
2393
- parentId
2394
- ),
2395
- withEventParentId({ type: "tool_result", id, content: text }, parentId)
2396
- ];
2467
+ async function resolveClaudeUserAgent() {
2468
+ if (claudeVersion) return `claude-code/${claudeVersion}`;
2469
+ try {
2470
+ const claude = resolveClaudeExecutable();
2471
+ const result = await run(claude, ["--version"], { reject: false, timeoutMs: 4e3 });
2472
+ const match = `${result.stdout}
2473
+ ${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
2474
+ claudeVersion = match?.[1] ?? "2.1.80";
2475
+ } catch {
2476
+ claudeVersion = "2.1.80";
2477
+ }
2478
+ return `claude-code/${claudeVersion}`;
2397
2479
  }
2398
- function eventsFromInjectedUserText(text, parentId) {
2399
- if (looksLikeSkillBody(text)) return skillToolEventsFromBody(text, parentId);
2400
- if (looksLikeConversationSummary(text)) return compactToolEventsFromBody(text, parentId);
2401
- return [];
2480
+ function staleOk(now) {
2481
+ if (!lastGood) return null;
2482
+ if (now - lastGood.at > CLAUDE_USAGE_STALE_OK_MS) return null;
2483
+ return lastGood.value;
2402
2484
  }
2403
- function eventsFromAssistantText(text, parentId) {
2404
- if (looksLikeSkillBody(text)) return skillToolEventsFromBody(text, parentId);
2405
- return [withEventParentId({ type: "stdout", data: text }, parentId)];
2485
+ function reuseLast() {
2486
+ return lastGood?.value ?? null;
2406
2487
  }
2407
- function eventsFromUserContent(content, parentId) {
2408
- if (typeof content === "string" && content.trim()) {
2409
- return eventsFromInjectedUserText(content, parentId);
2488
+ async function getClaudePlanUsage(opts = {}) {
2489
+ const now = opts.now ?? Date.now();
2490
+ adoptCacheDir(usageCacheDir(opts));
2491
+ if (now < errorUntil) return reuseLast() ?? staleOk(now);
2492
+ if (!opts.force) {
2493
+ if (cache && now - cache.at < CLAUDE_USAGE_TTL_MS) return cache.value;
2410
2494
  }
2411
- if (!Array.isArray(content) || content.length === 0) return [];
2412
- const out = [];
2413
- const injected = [];
2414
- for (const block of content) {
2415
- if (!block?.type) continue;
2416
- if (block.type === "tool_use" && block.id && block.name) {
2417
- out.push(
2418
- withEventParentId(
2419
- {
2420
- type: "tool_use",
2421
- id: block.id,
2422
- name: block.name,
2423
- input: block.input
2424
- },
2425
- parentId
2426
- )
2427
- );
2428
- continue;
2429
- }
2430
- if (block.type === "tool_result" && block.tool_use_id) {
2431
- out.push(
2432
- withEventParentId(
2433
- {
2434
- type: "tool_result",
2435
- id: block.tool_use_id,
2436
- content: toolResultContent(block),
2437
- isError: Boolean(block.is_error)
2438
- },
2439
- parentId
2440
- )
2441
- );
2442
- continue;
2443
- }
2444
- if (block.type === "text" && block.text) {
2445
- injected.push(...eventsFromInjectedUserText(block.text, parentId));
2446
- }
2447
- }
2448
- if (out.length === 0 && injected.length === 0) return [];
2449
- return [...out, ...injected];
2450
- }
2451
- function eventsFromContentBlocks(blocks, parentId) {
2452
- if (!blocks?.length) return [];
2453
- const out = [];
2454
- for (const block of blocks) {
2455
- if (!block?.type) continue;
2456
- if (block.type === "text" && block.text) {
2457
- out.push(...eventsFromAssistantText(block.text, parentId));
2458
- continue;
2459
- }
2460
- if ((block.type === "thinking" || block.type === "redacted_thinking") && block.thinking) {
2461
- out.push(withEventParentId({ type: "thinking", data: block.thinking }, parentId));
2462
- continue;
2463
- }
2464
- if (block.type === "tool_use" && block.id && block.name) {
2465
- out.push(
2466
- withEventParentId(
2467
- {
2468
- type: "tool_use",
2469
- id: block.id,
2470
- name: block.name,
2471
- input: block.input
2472
- },
2473
- parentId
2474
- )
2475
- );
2476
- continue;
2477
- }
2478
- if (block.type === "tool_result" && block.tool_use_id) {
2479
- out.push(
2480
- withEventParentId(
2481
- {
2482
- type: "tool_result",
2483
- id: block.tool_use_id,
2484
- content: toolResultContent(block),
2485
- isError: Boolean(block.is_error)
2495
+ if (inflight) return inflight;
2496
+ inflight = (async () => {
2497
+ try {
2498
+ const token = await (opts.readAccessToken ?? (() => readClaudeAccessToken(opts.configDir)))();
2499
+ if (!token) {
2500
+ cache = { at: now, dir: cacheDirKey, value: null };
2501
+ return null;
2502
+ }
2503
+ const fetchFn = opts.fetch ?? httpFetch;
2504
+ const userAgent = opts.userAgent ?? await resolveClaudeUserAgent();
2505
+ const ac = new AbortController();
2506
+ const timer = setTimeout(() => ac.abort(), 8e3);
2507
+ let res;
2508
+ try {
2509
+ res = await fetchFn(CLAUDE_OAUTH_USAGE_URL, {
2510
+ headers: {
2511
+ Authorization: `Bearer ${token}`,
2512
+ "anthropic-beta": "oauth-2025-04-20",
2513
+ "User-Agent": userAgent
2486
2514
  },
2487
- parentId
2488
- )
2489
- );
2515
+ signal: ac.signal
2516
+ });
2517
+ } finally {
2518
+ clearTimeout(timer);
2519
+ }
2520
+ if (res.status === 401 || res.status === 403) {
2521
+ cache = { at: now, dir: cacheDirKey, value: null };
2522
+ return null;
2523
+ }
2524
+ if (res.status === 429) {
2525
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
2526
+ const last = reuseLast();
2527
+ if (last) cache = { at: now, dir: cacheDirKey, value: last };
2528
+ return last;
2529
+ }
2530
+ if (!res.ok) {
2531
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
2532
+ return staleOk(now);
2533
+ }
2534
+ const usage = parseClaudeUsagePayload(await res.json(), new Date(now).toISOString());
2535
+ cache = { at: now, dir: cacheDirKey, value: usage };
2536
+ if (usage) lastGood = { at: now, dir: cacheDirKey, value: usage };
2537
+ return usage;
2538
+ } catch {
2539
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
2540
+ return staleOk(now);
2541
+ } finally {
2542
+ inflight = null;
2490
2543
  }
2491
- }
2492
- return out;
2544
+ })();
2545
+ return inflight;
2493
2546
  }
2494
- function claudeParentToolUseId(obj) {
2495
- const nested = obj.event && typeof obj.event === "object" && !Array.isArray(obj.event) ? obj.event : void 0;
2496
- for (const id of [obj.parent_tool_use_id, nested?.parent_tool_use_id]) {
2497
- if (typeof id === "string" && id.trim()) return id.trim();
2547
+
2548
+ // src/agents/claude-posthog-connector.ts
2549
+ var CLAUDE_POSTHOG_CONNECTOR_SERVER = "claude.ai PostHog";
2550
+ var LIST_URL = "https://api.anthropic.com/v1/mcp_servers?limit=1000&include_additional_installs=true";
2551
+ var PROXY_ORIGIN = "https://mcp-proxy.anthropic.com";
2552
+ var ID_RE = /^[A-Za-z0-9_-]+$/;
2553
+ var SUCCESS_TTL_MS = 5 * 6e4;
2554
+ var MISS_TTL_MS = 3e4;
2555
+ var cache2 = null;
2556
+ var turnOverride;
2557
+ function asRecord3(value) {
2558
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2559
+ return value;
2560
+ }
2561
+ function rowsFrom(body) {
2562
+ if (Array.isArray(body)) {
2563
+ return body.filter((row) => asRecord3(row) !== null);
2498
2564
  }
2499
- return void 0;
2565
+ const record = asRecord3(body);
2566
+ const data = record?.data;
2567
+ if (!Array.isArray(data)) return [];
2568
+ return data.filter((row) => asRecord3(row) !== null);
2500
2569
  }
2501
- function claudeString(obj, key) {
2502
- const v = obj[key];
2503
- return typeof v === "string" && v.trim() ? v.trim() : void 0;
2570
+ function isPosthogName(value) {
2571
+ if (typeof value !== "string") return false;
2572
+ const head = value.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
2573
+ return head === "posthog";
2504
2574
  }
2505
- function eventsFromClaudeSystem(obj) {
2506
- const subtype = claudeString(obj, "subtype") ?? "";
2507
- const parentId = claudeParentToolUseId(obj);
2508
- if (subtype === "init") {
2509
- if (parentId) return null;
2510
- const sid = claudeString(obj, "session_id");
2511
- const mcpNote = mcpStatusThinkingFromClaudeInit(obj);
2512
- const events = [];
2513
- if (sid) events.push({ type: "session_id", data: sid });
2514
- if (mcpNote) events.push({ type: "thinking", data: mcpNote, replace: true });
2515
- if (events.length === 0) return null;
2516
- return events.length === 1 ? events[0] : events;
2517
- }
2518
- if (subtype === "task_started") {
2519
- const id = claudeString(obj, "tool_use_id") ?? claudeString(obj, "task_id");
2520
- if (!id) return null;
2521
- const description = claudeString(obj, "description");
2522
- const taskType = claudeString(obj, "task_type");
2523
- const prompt = claudeString(obj, "prompt");
2524
- return withEventParentId(
2525
- {
2526
- type: "tool_use",
2527
- id,
2528
- name: taskType || "Agent",
2529
- input: {
2530
- ...description ? { description } : {},
2531
- ...prompt ? { prompt } : {},
2532
- ...claudeString(obj, "task_id") ? { task_id: claudeString(obj, "task_id") } : {}
2533
- }
2534
- },
2535
- parentId
2536
- );
2575
+ function rowId(row) {
2576
+ const id = row.id;
2577
+ return typeof id === "string" && ID_RE.test(id) ? id : null;
2578
+ }
2579
+ function posthogConnectorFromList(body) {
2580
+ const matches = rowsFrom(body).filter(
2581
+ (row2) => row2.eligible !== false && rowId(row2) !== null && (isPosthogName(row2.display_name) || isPosthogName(row2.displayName) || isPosthogName(row2.name))
2582
+ );
2583
+ const row = matches.find((item) => item.additional_install !== true && item.additionalInstall !== true) ?? matches[0];
2584
+ const id = row ? rowId(row) : null;
2585
+ if (!id) return null;
2586
+ return {
2587
+ type: "claudeai-proxy",
2588
+ id,
2589
+ url: `${PROXY_ORIGIN}/v1/mcp/${id}`,
2590
+ displayName: "PostHog",
2591
+ alwaysLoad: true
2592
+ };
2593
+ }
2594
+ async function loadClaudePosthogConnector(now = Date.now()) {
2595
+ if (cache2 && now - cache2.at < (cache2.value ? SUCCESS_TTL_MS : MISS_TTL_MS)) return cache2.value;
2596
+ const token = await readClaudeAccessToken();
2597
+ if (!token) {
2598
+ cache2 = { at: now, value: null };
2599
+ return null;
2537
2600
  }
2538
- if (subtype === "task_notification") {
2539
- const id = claudeString(obj, "tool_use_id") ?? claudeString(obj, "task_id") ?? parentId;
2540
- if (!id) return null;
2541
- const status = claudeString(obj, "status") ?? "working";
2542
- const tools = typeof obj.tool_uses === "number" ? obj.tool_uses : void 0;
2543
- const durationMs = typeof obj.duration_ms === "number" ? obj.duration_ms : void 0;
2544
- const lastTool = claudeString(obj, "last_tool") ?? claudeString(obj, "current_tool") ?? claudeString(obj, "tool");
2545
- const snapshot = [
2546
- status,
2547
- tools != null ? `${tools} tools` : null,
2548
- durationMs != null ? `${Math.round(durationMs / 1e3)}s` : null,
2549
- lastTool
2550
- ].filter((bit) => Boolean(bit)).join(" \xB7 ");
2551
- return [
2552
- {
2553
- type: "tool_use",
2554
- id,
2555
- name: claudeString(obj, "task_type") || "Agent",
2556
- input: {
2557
- live_status: status,
2558
- ...tools != null ? { live_tool_uses: tools } : {},
2559
- ...durationMs != null ? { live_duration_ms: durationMs } : {},
2560
- ...lastTool ? { live_last_tool: lastTool } : {}
2561
- }
2601
+ try {
2602
+ const res = await httpFetch(LIST_URL, {
2603
+ headers: {
2604
+ Authorization: `Bearer ${token}`,
2605
+ "anthropic-version": "2023-06-01",
2606
+ "anthropic-beta": "mcp-servers-2025-12-04"
2562
2607
  },
2563
- withEventParentId(
2564
- { type: "thinking", data: snapshot, replace: true },
2565
- id
2566
- )
2567
- ];
2608
+ signal: AbortSignal.timeout(4e3)
2609
+ });
2610
+ if (!res.ok) {
2611
+ cache2 = { at: now, value: null };
2612
+ return null;
2613
+ }
2614
+ const value = posthogConnectorFromList(await res.json());
2615
+ cache2 = { at: now, value };
2616
+ return value;
2617
+ } catch {
2618
+ cache2 = { at: now, value: null };
2619
+ return null;
2568
2620
  }
2569
- if (subtype === "api_retry") {
2570
- const attempt = obj.attempt;
2571
- const max = obj.max_retries;
2572
- const delay = obj.retry_delay_ms;
2621
+ }
2622
+ async function claudePosthogConnectorForTurn() {
2623
+ if (turnOverride) return turnOverride();
2624
+ if (process.env.VITEST) return null;
2625
+ return loadClaudePosthogConnector();
2626
+ }
2627
+
2628
+ // src/agents/types.ts
2629
+ var PLAN_MODE_INSTRUCTION = "Plan mode is active and must remain active until the user turns Plan mode off in the UI (or Approves / Hands off the plan). Analyze the codebase, search and read files as needed, and produce or refine a clear implementation plan. Do not modify, create, or delete any project files except via Sideboard MCP present_plan (writes .context/attachments/plan.md). When you need a clarifying decision (approach forks, auth choice, scope) \u2014 not greetings, check-ins, or an invented task menu: (1) first write a short chat message that explains the decision and what each option means (tradeoffs, when to pick it) \u2014 do not leave the user staring at bare labels; (2) then call Sideboard MCP ask_user with the same options, including a description on every option. If one option is the obvious default, proceed without asking. Sideboard shows questions in the composer and mirrors them in chat. After ask_user, wait for the user's next message with their answers before finalizing the plan. When the plan is ready for approval: (1) call present_plan with the full markdown plan (title + content) so Sideboard saves .context/attachments/plan.md and shows it in chat for Approve / Hand off / Copy; (2) Claude should also call ExitPlanMode after present_plan. Do not skip present_plan \u2014 the plan must be a markdown file, not only chat prose.";
2630
+ var PLAN_MODE_OFF_INSTRUCTION = "Plan mode is off. Do not call present_plan or ExitPlanMode \u2014 those only work when the user turns Plan on in the composer. If you need to propose an approach, write it in chat.";
2631
+ function planModeTurnInstruction(planMode) {
2632
+ return planMode ? PLAN_MODE_INSTRUCTION : PLAN_MODE_OFF_INSTRUCTION;
2633
+ }
2634
+ function permissionMode(thread) {
2635
+ if (thread.planMode) {
2573
2636
  return {
2574
- type: "thinking",
2575
- data: `API retry ${attempt ?? "?"}/${max ?? "?"}${typeof delay === "number" ? ` (wait ${delay}ms)` : ""}`
2637
+ claude: "plan",
2638
+ opencodePermission: JSON.stringify({
2639
+ edit: "deny",
2640
+ write: "deny",
2641
+ bash: { "*": "deny" }
2642
+ }),
2643
+ codexSandbox: "read-only"
2576
2644
  };
2577
2645
  }
2578
- if (subtype === "status") {
2579
- const status = claudeString(obj, "status");
2580
- if (status === "compacting") {
2581
- return { type: "thinking", data: "Compressing context\u2026", replace: true };
2582
- }
2583
- return null;
2646
+ if (thread.sourceType === "orchestration") {
2647
+ return {
2648
+ claude: "acceptEdits",
2649
+ // Unattended coordinators cannot answer permission prompts. Explicit
2650
+ // allows override the user's OpenCode denies for this process only.
2651
+ opencodePermission: JSON.stringify({
2652
+ edit: "allow",
2653
+ bash: { "*": "allow" }
2654
+ }),
2655
+ codexSandbox: "danger-full-access"
2656
+ };
2584
2657
  }
2585
- if (subtype === "compact_boundary" || subtype === "compact") {
2586
- const meta = compactMetadataFromClaude(obj);
2587
- const trigger = meta.trigger ? ` (${meta.trigger})` : "";
2588
- const thinking = {
2589
- type: "thinking",
2590
- data: `Context compressed${trigger}`,
2591
- replace: true
2658
+ if (thread.autonomy === "full") {
2659
+ return {
2660
+ claude: "bypassPermissions",
2661
+ opencodePermission: JSON.stringify({ "*": "allow" }),
2662
+ codexSandbox: "workspace-write"
2592
2663
  };
2593
- if (meta.postTokens != null && meta.postTokens > 0 && !parentId) {
2594
- return [
2595
- thinking,
2596
- {
2597
- type: "usage",
2598
- data: {
2599
- inputTokens: 0,
2600
- outputTokens: 0,
2601
- lastRequestTokens: meta.postTokens
2602
- },
2603
- scope: "request"
2604
- }
2605
- ];
2606
- }
2607
- return thinking;
2608
2664
  }
2609
- return null;
2610
- }
2611
- function compactMetadataFromClaude(obj) {
2612
- const raw = obj.compactMetadata ?? obj.compact_metadata;
2613
- if (!raw || typeof raw !== "object") return {};
2614
- const meta = raw;
2615
- const trigger = typeof meta.trigger === "string" && meta.trigger.trim() ? meta.trigger.trim() : void 0;
2616
- const post = meta.postTokens ?? meta.post_tokens;
2617
- const postTokens = typeof post === "number" && Number.isFinite(post) && post > 0 ? Math.round(post) : void 0;
2618
- return { trigger, postTokens };
2665
+ return {
2666
+ claude: "acceptEdits",
2667
+ opencodePermission: JSON.stringify({}),
2668
+ codexSandbox: "workspace-write"
2669
+ };
2619
2670
  }
2620
- var claudeAdapter = {
2621
- kind: "claude",
2622
- async detect() {
2623
- const claude = resolveClaudeExecutable();
2624
- if (claude !== "claude") {
2625
- if (!existsSync7(claude)) {
2626
- return {
2627
- agent: "claude",
2628
- installed: false,
2629
- authenticated: false,
2630
- linearMcp: false,
2631
- warnings: [],
2632
- reason: `Claude Code executable not found: ${claude}`
2633
- };
2634
- }
2635
- } else {
2636
- const which = await run("which", ["claude"], { reject: false });
2637
- if (which.exitCode !== 0) {
2638
- return {
2639
- agent: "claude",
2640
- installed: false,
2641
- authenticated: false,
2642
- linearMcp: false,
2643
- warnings: [],
2644
- reason: "claude CLI not found on PATH"
2645
- };
2646
- }
2647
- }
2648
- const auth = await run(claude, ["auth", "status"], {
2649
- reject: false,
2650
- timeoutMs: 5e3
2651
- });
2652
- const authenticated = auth.exitCode === 0;
2653
- return {
2654
- agent: "claude",
2655
- installed: true,
2656
- authenticated,
2657
- linearMcp: false,
2658
- warnings: [],
2659
- reason: authenticated ? void 0 : "claude auth status failed \u2014 run `claude auth login`"
2660
- };
2661
- },
2662
- async buildTurn(thread, input) {
2663
- const claude = resolveClaudeExecutable();
2664
- const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
2665
- const effective = dropCachedPrefixOnResume(input, sessionId);
2666
- const { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
2667
- const useStdin = promptText.length > CLAUDE_PROMPT_ARG_MAX;
2668
- if (process.env.SIDEBOARD_DEBUG_CLAUDE_TURN === "1") {
2669
- console.error(
2670
- `[sideboard/claude] promptChars=${promptText.length} resumed=${Boolean(sessionId)} stdin=${useStdin}`
2671
- );
2672
- }
2673
- const mode = permissionMode(thread);
2674
- const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-6GGS3DWU.js");
2675
- const isOrchestrator = isOrchestratorThread2(thread);
2676
- const rpc = worktreeAgentRpc(isOrchestrator);
2677
- const injectedServers = await buildInjectedMcpServers({
2678
- includeSideboard: true,
2679
- includeBrightsy: shouldInjectBrightsyMcp(thread, {
2680
- orchestrator: isOrchestrator
2681
- }),
2682
- orchestratorThreadId: isOrchestrator ? thread.id : null,
2683
- threadId: thread.id,
2684
- rpcNativeTools: Boolean(rpc)
2685
- });
2686
- const injectedBrightsyNames = injectedServers.filter((s) => s.name === "brightsy" || s.name.startsWith("brightsy_")).map((s) => s.name);
2687
- const chromeOn = claudeChromeEnabled();
2688
- const userMcpEntries = await proxyClaudeUserMcp(isOrchestrator, [thread.repoPath, thread.worktreePath]);
2689
- let allowedTools;
2690
- if (isOrchestrator) {
2691
- allowedTools = [
2692
- ...BASE_ALLOWED_TOOLS,
2693
- ...SIDEBOARD_MCP_ALLOWED_TOOLS,
2694
- ...brightsyMcpAllowedTools(injectedBrightsyNames),
2695
- ...mcpAllowToolsFromNames(thread.approvedMcpServers ?? [])
2696
- ];
2697
- } else {
2698
- allowedTools = [
2699
- ...BASE_ALLOWED_TOOLS,
2700
- ...mcpAllowToolsFromNames([...Object.keys(userMcpEntries), ...thread.approvedMcpServers ?? []]),
2701
- ...sideboardWorktreeAllowedTools({
2702
- github: true,
2703
- linear: isLinearConnected(),
2704
- abletime: isAbleTimeConnected(),
2705
- planMode: thread.planMode,
2706
- posthog: isPosthogConnected()
2707
- }),
2708
- ...brightsyMcpAllowedTools(injectedBrightsyNames),
2709
- ...isPosthogConnected() ? [] : CLAUDE_POSTHOG_CONNECTOR_ALLOWED_TOOLS
2710
- ];
2711
- }
2712
- if (chromeOn) {
2713
- allowedTools = [...allowedTools, ...CLAUDE_CHROME_ALLOWED_TOOLS];
2714
- }
2715
- if (rpc) {
2716
- return buildClaudeRpcTurnCommand({
2717
- prompt: promptText,
2718
- cwd: thread.worktreePath,
2719
- sessionId,
2720
- model: thread.model,
2721
- effort: thread.effort ?? (thread.fast ? "low" : "high"),
2722
- permissionMode: mode.claude,
2723
- systemPrompt,
2724
- claudePath: claude,
2725
- chrome: chromeOn,
2726
- mcpServers: mcpServersRecord(injectedServers, userMcpEntries),
2727
- allowedTools: withClaudePilotRpcTools(allowedTools),
2728
- agentRpc: rpc,
2729
- isolateClaudeAiMcp: isOrchestrator || isLocalDevAppDataDir()
2730
- });
2731
- }
2732
- const args = [
2733
- "-p",
2734
- ...useStdin ? [] : [promptText],
2735
- "--output-format",
2736
- "stream-json",
2737
- "--verbose",
2738
- "--include-partial-messages",
2739
- "--permission-mode",
2740
- mode.claude,
2741
- ...mode.claude === "bypassPermissions" ? ["--dangerously-skip-permissions"] : []
2742
- ];
2743
- if (systemPrompt) {
2744
- args.push("--append-system-prompt", systemPrompt);
2745
- }
2746
- const mcpConfigPath = writeMcpServersConfig(injectedServers, userMcpEntries);
2747
- if (mcpConfigPath) {
2748
- args.push("--mcp-config", mcpConfigPath);
2749
- args.push("--strict-mcp-config");
2750
- }
2751
- if (chromeOn) {
2752
- args.push("--chrome");
2753
- }
2754
- if (useStdin) {
2755
- args.push("--input-format", "text");
2671
+
2672
+ // src/agent-rpc/rpc-env.ts
2673
+ function worktreeAgentRpc(isOrchestrator) {
2674
+ return isOrchestrator ? null : agentRpcConnectFromMetadata();
2675
+ }
2676
+ function agentRpcChildEnv(rpc, cwd) {
2677
+ return {
2678
+ [AGENT_RPC_NATIVE_ENV]: "1",
2679
+ [AGENT_RPC_URL_ENV]: rpc.url,
2680
+ [AGENT_RPC_TOKEN_ENV]: rpc.authToken,
2681
+ [AGENT_RPC_CWD_ENV]: cwd
2682
+ };
2683
+ }
2684
+
2685
+ // src/agents/claude-host.ts
2686
+ import { existsSync as existsSync7 } from "fs";
2687
+ import { createRequire as createRequire2 } from "module";
2688
+ import { dirname as dirname3, join as join7 } from "path";
2689
+ import { fileURLToPath as fileURLToPath2 } from "url";
2690
+ function claudePilotSdkAllowedTools() {
2691
+ return PILOT_TOOL_NAMES.map(
2692
+ (name) => `mcp__${AGENT_RPC_CLAUDE_SDK_SERVER}__${name}`
2693
+ );
2694
+ }
2695
+ function withClaudePilotRpcTools(allowed) {
2696
+ const omit = new Set(PILOT_TOOL_NAMES.map((name) => `mcp__sideboard__${name}`));
2697
+ return [...allowed.filter((name) => !omit.has(name)), ...claudePilotSdkAllowedTools()];
2698
+ }
2699
+ function entryDir() {
2700
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
2701
+ if (cjsDir) return cjsDir;
2702
+ try {
2703
+ return dirname3(fileURLToPath2(import.meta.url));
2704
+ } catch {
2705
+ try {
2706
+ const req = createRequire2(process.cwd() + "/");
2707
+ return dirname3(req.resolve("@sideboard-ai/core"));
2708
+ } catch {
2709
+ return process.cwd();
2756
2710
  }
2757
- for (const tool of allowedTools) {
2758
- args.push("--allowedTools", tool);
2711
+ }
2712
+ }
2713
+ function claudeRunnerPath() {
2714
+ const packagedDir = packagedCursorRuntimeDir();
2715
+ if (packagedDir) {
2716
+ const packaged = join7(packagedDir, "core-dist", "agents", "claude-runner.js");
2717
+ if (existsSync7(packaged)) return packaged;
2718
+ }
2719
+ const root = entryDir();
2720
+ const candidates = [
2721
+ join7(root, "agents", "claude-runner.js"),
2722
+ join7(root, "agents", "claude-runner.cjs"),
2723
+ join7(root, "dist", "agents", "claude-runner.js"),
2724
+ join7(root, "dist", "agents", "claude-runner.cjs"),
2725
+ join7(root, "claude-runner.ts"),
2726
+ join7(root, "src", "agents", "claude-runner.ts")
2727
+ ];
2728
+ for (const candidate of candidates) {
2729
+ if (existsSync7(candidate)) return candidate;
2730
+ }
2731
+ return candidates[0];
2732
+ }
2733
+ async function buildClaudeRpcTurnCommand(req) {
2734
+ const runner = claudeRunnerPath();
2735
+ const isTs = runner.endsWith(".ts");
2736
+ const launch = applyNodeLaunch(
2737
+ await resolveNodeLaunch(runner),
2738
+ isTs ? ["--import", "tsx", runner] : [runner]
2739
+ );
2740
+ return {
2741
+ file: launch.file,
2742
+ args: launch.args,
2743
+ cwd: req.cwd,
2744
+ stdin: JSON.stringify(req),
2745
+ env: {
2746
+ ...launch.env,
2747
+ CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
2748
+ CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? "7200000",
2749
+ ...req.isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
2759
2750
  }
2760
- if (thread.model) {
2761
- args.push("--model", thread.model);
2751
+ };
2752
+ }
2753
+
2754
+ // src/agents/claude.ts
2755
+ function isLocalDevAppDataDir(dir = process.env.SIDEBOARD_APP_DATA) {
2756
+ return /[/\\]\.sideboard[/\\]dev-app-data(?:[/\\]|$)/.test(dir ?? "");
2757
+ }
2758
+ var CLAUDE_PROMPT_ARG_MAX = 2e5;
2759
+ function usageFromClaude(usage) {
2760
+ if (!usage) return null;
2761
+ const inputTokens = Number(usage.input_tokens ?? 0);
2762
+ const outputTokens = Number(usage.output_tokens ?? 0);
2763
+ const cacheReadTokens = Number(usage.cache_read_input_tokens ?? 0);
2764
+ const cacheWriteTokens = Number(usage.cache_creation_input_tokens ?? 0);
2765
+ if (!inputTokens && !outputTokens && !cacheReadTokens && !cacheWriteTokens) return null;
2766
+ return {
2767
+ inputTokens,
2768
+ outputTokens,
2769
+ cacheReadTokens: cacheReadTokens || void 0,
2770
+ cacheWriteTokens: cacheWriteTokens || void 0
2771
+ };
2772
+ }
2773
+ function costUsdFromClaudeResult(obj) {
2774
+ const modelUsage = obj.modelUsage ?? obj.model_usage;
2775
+ if (modelUsage && typeof modelUsage === "object") {
2776
+ let sum = 0;
2777
+ let any = false;
2778
+ for (const entry of Object.values(modelUsage)) {
2779
+ if (!entry || typeof entry !== "object") continue;
2780
+ const row = entry;
2781
+ const cost = row.costUSD ?? row.cost_usd;
2782
+ if (cost != null && Number.isFinite(Number(cost))) {
2783
+ sum += Number(cost);
2784
+ any = true;
2785
+ }
2762
2786
  }
2763
- const effort = thread.effort ?? (thread.fast ? "low" : "high");
2764
- args.push("--effort", effort);
2765
- if (sessionId) {
2766
- args.push("--resume", sessionId);
2767
- }
2768
- return {
2769
- file: claude,
2770
- args,
2771
- cwd: thread.worktreePath,
2772
- stdin: useStdin ? `${promptText}
2773
- ` : void 0,
2774
- ...mcpConfigPath ? { cleanupDirs: [dirname4(mcpConfigPath)] } : {},
2775
- // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
2776
- // Raise the -p background-agent wait so long TaskOutput polls are not
2777
- // abandoned at Claude Code’s 10-minute default.
2778
- env: {
2779
- CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
2780
- CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? String(CLAUDE_PRINT_BG_WAIT_CEILING_MS),
2781
- // `--strict-mcp-config` still fetches claude.ai connectors on some CLI
2782
- // builds (anthropics/claude-code#60252). Coordinators never need them.
2783
- // Local `pnpm dev` also disables them: those HTTP connectors hang the
2784
- // first worktree turn when Electron's cwd is this Sideboard repo.
2785
- ...isOrchestrator || isLocalDevAppDataDir() ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
2786
- }
2787
- };
2788
- },
2789
- parseEvent(line) {
2790
- const trimmed = line.trim();
2791
- if (!trimmed) return null;
2792
- try {
2793
- const obj = JSON.parse(trimmed);
2794
- if (obj.type === "system") {
2795
- return eventsFromClaudeSystem(obj);
2796
- }
2797
- if (obj.type === "assistant" || obj.type === "user") {
2798
- const parentId = claudeParentToolUseId(obj);
2799
- const message = obj.message;
2800
- const events = obj.type === "user" ? eventsFromUserContent(message?.content, parentId) : eventsFromContentBlocks(
2801
- Array.isArray(message?.content) ? message.content : void 0,
2802
- parentId
2803
- );
2804
- if (obj.type === "assistant" && !parentId) {
2805
- const usage = usageFromClaude(message?.usage);
2806
- const messageId = message && typeof message.id === "string" ? message.id : void 0;
2807
- if (usage) {
2808
- events.push({
2809
- type: "usage",
2810
- data: usage,
2811
- scope: "request",
2812
- ...messageId ? { messageId } : {}
2813
- });
2814
- }
2815
- }
2816
- if (events.length === 0) return null;
2817
- return events.length === 1 ? events[0] : events;
2818
- }
2819
- if (obj.type === "stream_event") {
2820
- const parentId = claudeParentToolUseId(obj);
2821
- const event = obj.event;
2822
- if (!event) return null;
2823
- if (event.type === "content_block_start" && event.content_block) {
2824
- const block = event.content_block;
2825
- if (block.type === "tool_use" && block.id && block.name) {
2826
- return withEventParentId(
2827
- {
2828
- type: "tool_use",
2829
- id: block.id,
2830
- name: block.name,
2831
- input: block.input
2832
- },
2833
- parentId
2834
- );
2835
- }
2836
- if (block.type === "thinking" && block.thinking) {
2837
- return withEventParentId({ type: "thinking", data: block.thinking }, parentId);
2838
- }
2839
- return null;
2840
- }
2841
- if (event.type === "content_block_delta" && event.delta) {
2842
- if (event.delta.text) {
2843
- return withEventParentId({ type: "stdout", data: event.delta.text }, parentId);
2844
- }
2845
- if (event.delta.thinking) {
2846
- return withEventParentId({ type: "thinking", data: event.delta.thinking }, parentId);
2847
- }
2848
- return null;
2849
- }
2850
- return null;
2851
- }
2852
- if (obj.type === "content_block_delta") {
2853
- const parentId = claudeParentToolUseId(obj);
2854
- const delta = obj.delta;
2855
- if (delta?.text) return withEventParentId({ type: "stdout", data: delta.text }, parentId);
2856
- if (delta?.thinking) {
2857
- return withEventParentId({ type: "thinking", data: delta.thinking }, parentId);
2858
- }
2859
- return null;
2860
- }
2861
- if (obj.type === "result") {
2862
- const events = [];
2863
- const errorDetail = claudeResultErrorDetail(obj);
2864
- if (errorDetail) {
2865
- events.push({ type: "stderr", data: errorDetail });
2866
- } else {
2867
- const text = obj.result;
2868
- if (typeof text === "string" && text) {
2869
- events.push(...eventsFromAssistantText(text));
2870
- }
2871
- }
2872
- const usage = usageFromClaude(obj.usage);
2873
- if (usage) {
2874
- const costUsd = costUsdFromClaudeResult(obj);
2875
- if (costUsd != null) usage.costUsd = costUsd;
2876
- const sessionCostUsd = sessionCostUsdFromClaudeResult(obj);
2877
- if (sessionCostUsd != null) usage.sessionCostUsd = sessionCostUsd;
2878
- events.push({ type: "usage", data: usage, scope: "turn" });
2879
- }
2880
- if (events.length === 0) return null;
2881
- return events.length === 1 ? events[0] : events;
2882
- }
2883
- return null;
2884
- } catch {
2885
- return { type: "stdout", data: line };
2886
- }
2887
- },
2888
- async resolveSessionId(_worktreePath, cached) {
2889
- return cached;
2890
- },
2891
- async buildAttach(thread) {
2892
- const claude = resolveClaudeExecutable();
2893
- const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
2894
- const args = sessionId ? ["--resume", sessionId] : [];
2895
- if (claudeChromeEnabled()) {
2896
- args.push("--chrome");
2897
- }
2898
- return { file: claude, args, cwd: thread.worktreePath };
2899
- },
2900
- async listLinearIssues(_repoPath) {
2901
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-CGUCPWTV.js");
2902
- return listAssignedLinearIssues2();
2903
- }
2904
- };
2905
-
2906
- // src/agents/codex.ts
2907
- import { existsSync as existsSync8, statSync } from "fs";
2908
- import { homedir as homedir6 } from "os";
2909
- import { join as join7 } from "path";
2910
-
2911
- // src/agents/codex-items.ts
2912
- function eventsFromCodexItem(eventType, item) {
2913
- const itemType = item.type ?? item.item_type;
2914
- if (itemType === "reasoning" && typeof item.text === "string" && item.text) {
2915
- return { type: "thinking", data: item.text };
2787
+ if (any) return sum;
2916
2788
  }
2917
- if (itemType !== "file_change" || !item.id) return null;
2918
- const changes = Array.isArray(item.changes) ? item.changes : [];
2919
- const paths = changes.map((change) => typeof change?.path === "string" ? change.path : "").filter(Boolean);
2920
- const added = changes.some((change) => change?.kind === "add");
2921
- const events = [
2922
- {
2923
- type: "tool_use",
2924
- id: item.id,
2925
- name: added ? "Write" : "Edit",
2926
- input: paths.length ? { paths } : void 0
2927
- }
2928
- ];
2929
- const finished = eventType === "item.completed" || item.status === "completed" || item.status === "failed";
2930
- if (finished) {
2931
- events.push({
2932
- type: "tool_result",
2933
- id: item.id,
2934
- content: paths.join("\n") || void 0,
2935
- isError: item.status === "failed"
2936
- });
2789
+ const totalCost = obj.total_cost_usd ?? obj.totalCostUsd;
2790
+ if (totalCost != null && Number.isFinite(Number(totalCost))) {
2791
+ return Number(totalCost);
2937
2792
  }
2938
- return events.length === 1 ? events[0] : events;
2793
+ return void 0;
2939
2794
  }
2940
-
2941
- // src/agents/codex.ts
2942
- var CODEX_PROMPT_ARG_MAX = 2e5;
2943
- var FALLBACK_CODEX_MODELS = [
2944
- { id: "gpt-5.6-sol", displayName: "GPT-5.6 Sol" },
2945
- { id: "gpt-5.6-terra", displayName: "GPT-5.6 Terra" },
2946
- { id: "gpt-5.6-luna", displayName: "GPT-5.6 Luna" },
2947
- { id: "gpt-5.5", displayName: "GPT-5.5" },
2948
- { id: "gpt-5.2", displayName: "GPT-5.2" }
2949
- ];
2950
- var cachedCodexModels = null;
2951
- var CODEX_MODEL_CACHE_MS = 5 * 60 * 1e3;
2952
- async function listCodexModels() {
2953
- const now = Date.now();
2954
- if (cachedCodexModels && now - cachedCodexModels.at < CODEX_MODEL_CACHE_MS) {
2955
- return cachedCodexModels.models;
2795
+ function sessionCostUsdFromClaudeResult(obj) {
2796
+ const totalCost = obj.total_cost_usd ?? obj.totalCostUsd;
2797
+ if (totalCost != null && Number.isFinite(Number(totalCost))) {
2798
+ return Number(totalCost);
2956
2799
  }
2957
- const codex = resolveAgentExecutable("codex");
2958
- if (codex === "codex") {
2959
- const which = await run("which", ["codex"], { reject: false });
2960
- if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
2961
- } else if (!existsSync8(codex)) {
2962
- return FALLBACK_CODEX_MODELS;
2800
+ return void 0;
2801
+ }
2802
+ function claudeResultErrorDetail(obj) {
2803
+ const isError = Boolean(obj.is_error) || typeof obj.subtype === "string" && /^error/i.test(obj.subtype);
2804
+ const fromResult = typeof obj.result === "string" ? obj.result.trim() : "";
2805
+ const shortFailure = fromResult.length > 0 && fromResult.length <= 300 && !fromResult.includes("\n") && looksLikeAgentFailureMessage(fromResult);
2806
+ if (fromResult && (isError || shortFailure)) {
2807
+ return fromResult;
2963
2808
  }
2964
- const listed = await run(codex, ["debug", "models"], { reject: false });
2965
- if (listed.exitCode !== 0 || !listed.stdout.trim()) {
2966
- return cachedCodexModels?.models ?? FALLBACK_CODEX_MODELS;
2809
+ if (!isError) return null;
2810
+ const errors = obj.errors;
2811
+ if (Array.isArray(errors)) {
2812
+ const parts = errors.map((e) => {
2813
+ if (typeof e === "string") return e.trim();
2814
+ if (e && typeof e === "object" && typeof e.message === "string") {
2815
+ return e.message.trim();
2816
+ }
2817
+ return "";
2818
+ }).filter(Boolean);
2819
+ if (parts.length) return parts.join("; ");
2967
2820
  }
2968
- try {
2969
- const parsed = JSON.parse(listed.stdout);
2970
- const rows = Array.isArray(parsed.models) ? parsed.models : [];
2971
- const preferred = rows.filter((m) => (m.visibility ?? "list") === "list");
2972
- const source = preferred.length > 0 ? preferred : rows;
2973
- const models = source.map((m) => ({
2974
- id: (m.slug || "").trim(),
2975
- displayName: (m.display_name || m.slug || "").trim(),
2976
- description: m.description,
2977
- priority: typeof m.priority === "number" ? m.priority : 999
2978
- })).filter((m) => m.id).sort((a, b) => a.priority - b.priority).map(({ id, displayName, description }) => ({ id, displayName, description }));
2979
- if (models.length === 0) return FALLBACK_CODEX_MODELS;
2980
- cachedCodexModels = { at: now, models };
2981
- return models;
2982
- } catch {
2983
- return cachedCodexModels?.models ?? FALLBACK_CODEX_MODELS;
2821
+ if (typeof obj.error === "string" && obj.error.trim()) return obj.error.trim();
2822
+ if (typeof obj.subtype === "string" && obj.subtype) {
2823
+ return obj.subtype.replace(/^error[_-]?/i, "").replace(/_/g, " ") || "Claude turn failed";
2984
2824
  }
2825
+ return "Claude turn failed";
2985
2826
  }
2986
- function usageFromCodex(usage, asContext = false) {
2987
- if (!usage) return null;
2988
- const mapped = fromInclusiveInputUsage({
2989
- inputTokens: Number(usage.input_tokens ?? 0),
2990
- outputTokens: Number(usage.output_tokens ?? 0),
2991
- cachedInputTokens: Number(usage.cached_input_tokens ?? 0)
2992
- });
2993
- if (!mapped || !asContext) return mapped;
2994
- const occ = requestOccupancy(mapped);
2995
- return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
2996
- }
2997
- function codexHomeDir() {
2998
- return process.env.CODEX_HOME?.trim() || join7(homedir6(), ".codex");
2827
+ function toolResultContent(block) {
2828
+ if (typeof block.content === "string") return block.content;
2829
+ if (Array.isArray(block.content)) {
2830
+ return block.content.map(
2831
+ (c) => typeof c === "string" ? c : c && typeof c === "object" && "text" in c ? String(c.text ?? "") : ""
2832
+ ).join("");
2833
+ }
2834
+ if (block.content != null) return JSON.stringify(block.content);
2835
+ return void 0;
2999
2836
  }
3000
- function unwrapCodexMcpResult(result) {
3001
- if (result == null) return void 0;
3002
- if (typeof result === "string") return result;
3003
- if (typeof result !== "object") return String(result);
3004
- const rec = result;
3005
- if (Array.isArray(rec.content)) {
3006
- const texts = [];
3007
- for (const item of rec.content) {
3008
- if (!item || typeof item !== "object") continue;
3009
- const text = item.text;
3010
- if (typeof text === "string") texts.push(text);
3011
- }
3012
- if (texts.length) return texts.join("\n");
3013
- }
3014
- try {
3015
- return JSON.stringify(result);
3016
- } catch {
3017
- return String(result);
3018
- }
2837
+ function skillToolEventsFromBody(text, parentId) {
2838
+ const command = skillCommandFromBody(text) ?? "skill";
2839
+ const id = `skill-${command}`;
2840
+ return [
2841
+ withEventParentId(
2842
+ { type: "tool_use", id, name: "Skill", input: { skill: command } },
2843
+ parentId
2844
+ ),
2845
+ withEventParentId({ type: "tool_result", id, content: text }, parentId)
2846
+ ];
3019
2847
  }
3020
- function asRecord3(value) {
3021
- if (value && typeof value === "object" && !Array.isArray(value)) {
3022
- return value;
3023
- }
3024
- return void 0;
2848
+ function compactToolEventsFromBody(text, parentId) {
2849
+ const id = "compact-summary";
2850
+ return [
2851
+ withEventParentId(
2852
+ { type: "tool_use", id, name: "Compact", input: { trigger: "injected" } },
2853
+ parentId
2854
+ ),
2855
+ withEventParentId({ type: "tool_result", id, content: text }, parentId)
2856
+ ];
3025
2857
  }
3026
- function codexLooksAuthenticated() {
3027
- const authPath = join7(codexHomeDir(), "auth.json");
3028
- if (!existsSync8(authPath)) return false;
3029
- try {
3030
- return statSync(authPath).size > 2;
3031
- } catch {
3032
- return false;
3033
- }
2858
+ function eventsFromInjectedUserText(text, parentId) {
2859
+ if (looksLikeSkillBody(text)) return skillToolEventsFromBody(text, parentId);
2860
+ if (looksLikeConversationSummary(text)) return compactToolEventsFromBody(text, parentId);
2861
+ return [];
3034
2862
  }
3035
- var codexAdapter = {
3036
- kind: "codex",
3037
- async detect() {
3038
- const codex = resolveAgentExecutable("codex");
3039
- if (codex !== "codex") {
3040
- if (!existsSync8(codex)) {
3041
- return {
3042
- agent: "codex",
3043
- installed: false,
3044
- authenticated: false,
3045
- linearMcp: false,
3046
- warnings: [],
3047
- reason: `Codex executable not found: ${codex}`
3048
- };
3049
- }
3050
- } else {
3051
- const which = await run("which", ["codex"], { reject: false, timeoutMs: 3e3 });
3052
- if (which.exitCode !== 0) {
3053
- return {
3054
- agent: "codex",
3055
- installed: false,
3056
- authenticated: false,
3057
- linearMcp: false,
3058
- warnings: [],
3059
- reason: "codex CLI not found on PATH"
3060
- };
3061
- }
2863
+ function eventsFromAssistantText(text, parentId) {
2864
+ if (looksLikeSkillBody(text)) return skillToolEventsFromBody(text, parentId);
2865
+ return [withEventParentId({ type: "stdout", data: text }, parentId)];
2866
+ }
2867
+ function eventsFromUserContent(content, parentId) {
2868
+ if (typeof content === "string" && content.trim()) {
2869
+ return eventsFromInjectedUserText(content, parentId);
2870
+ }
2871
+ if (!Array.isArray(content) || content.length === 0) return [];
2872
+ const out = [];
2873
+ const injected = [];
2874
+ for (const block of content) {
2875
+ if (!block?.type) continue;
2876
+ if (block.type === "tool_use" && block.id && block.name) {
2877
+ out.push(
2878
+ withEventParentId(
2879
+ {
2880
+ type: "tool_use",
2881
+ id: block.id,
2882
+ name: block.name,
2883
+ input: block.input
2884
+ },
2885
+ parentId
2886
+ )
2887
+ );
2888
+ continue;
3062
2889
  }
3063
- const authenticated = codexLooksAuthenticated();
3064
- const linearMcp = false;
3065
- const warnings = [];
3066
- return {
3067
- agent: "codex",
3068
- installed: true,
3069
- authenticated,
3070
- linearMcp,
3071
- warnings,
3072
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join7(codexHomeDir(), "auth.json")})`
3073
- };
3074
- },
3075
- async buildTurn(thread, input) {
3076
- const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3077
- const prompt = flattenTurnInput(dropCachedPrefixOnResume(input, sessionId));
3078
- const useStdin = prompt.length > CODEX_PROMPT_ARG_MAX;
3079
- const promptArg = useStdin ? "-" : prompt;
3080
- if (process.env.SIDEBOARD_DEBUG_CODEX_TURN === "1") {
3081
- console.error(
3082
- `[sideboard/codex] promptChars=${prompt.length} resumed=${Boolean(sessionId)} stdin=${useStdin} hasPrefix=${prompt.includes("Current request:")}`
2890
+ if (block.type === "tool_result" && block.tool_use_id) {
2891
+ out.push(
2892
+ withEventParentId(
2893
+ {
2894
+ type: "tool_result",
2895
+ id: block.tool_use_id,
2896
+ content: toolResultContent(block),
2897
+ isError: Boolean(block.is_error)
2898
+ },
2899
+ parentId
2900
+ )
3083
2901
  );
2902
+ continue;
3084
2903
  }
3085
- const mode = permissionMode(thread);
3086
- const model = thread.model?.trim();
3087
- const isOrchestrator = isOrchestratorThread(thread);
3088
- const injected = await buildInjectedMcpServers({
3089
- includeSideboard: true,
3090
- includeBrightsy: shouldInjectBrightsyMcp(thread, {
3091
- orchestrator: isOrchestrator
3092
- }),
3093
- orchestratorThreadId: isOrchestrator ? thread.id : null,
3094
- threadId: thread.id
3095
- });
3096
- const isolatePlugins = isOrchestrator || Boolean(thread.isolateCodexPlugins) || Boolean(normalizeTurnInput(input).isolateCodexPlugins);
3097
- const gitEnv = await resolveAgentGitAuthEnv(process.env, {
3098
- cwd: thread.worktreePath
3099
- });
3100
- const writableRoots = mode.codexSandbox === "workspace-write" ? await resolveCodexGitWritableRoots(thread.worktreePath) : [];
3101
- const secretProfile = writeCodexMcpSecretProfile(injected);
3102
- const effort = thread.effort?.trim() ?? "";
3103
- const mcpOverrides = [
3104
- // Worktree first try keeps plugins (Claude connectors). Coordinators
3105
- // isolate. After a fatal plugin MCP, the orchestrator retries with
3106
- // isolateCodexPlugins so the turn continues. Never invent mcp_servers.posthog.
3107
- ...isolatePlugins ? toCodexUnattendedAppsArgs() : [],
3108
- ...toCodexMcpConfigArgs(injected),
3109
- ...isOrchestrator ? toCodexDisableUserMcpArgs(
3110
- userMcpNamesToDisable({
3111
- injectedNames: injected.map((s) => s.name),
3112
- names: listUserCodexMcpNames()
3113
- })
3114
- ) : []
3115
- ];
3116
- const execOpts = [
3117
- // Global orchestration cwd is not a git repo; without this Codex ≥0.147
3118
- // refuses to start ("Not inside a trusted directory").
3119
- ...secretProfile ? ["-p", secretProfile.profile] : [],
3120
- "--skip-git-repo-check",
3121
- "--cd",
3122
- thread.worktreePath,
3123
- "--json",
3124
- "--sandbox",
3125
- mode.codexSandbox,
3126
- // `codex exec` rejects `--ask-for-approval` (global-only on newer CLIs).
3127
- "-c",
3128
- 'approval_policy="never"',
3129
- // Seatbelt cannot use the login Keychain. inherit=all keeps GH_CONFIG_DIR
3130
- // and GIT_CONFIG_*. Default excludes still strip *TOKEN*/*SECRET*/*KEY*;
3131
- // GIT_CONFIG_KEY_n is re-set because it matches *KEY*. Linked worktrees
3132
- // need the main repo `.git` as writable_roots so git commit can lock.
3133
- ...codexUnattendedGitConfigArgs(mode.codexSandbox, {
3134
- writableRoots,
3135
- preserveEnv: gitEnv
3136
- }),
3137
- ...model ? ["--model", model] : [],
3138
- ...effort ? ["-c", `model_reasoning_effort=${JSON.stringify(effort)}`] : [],
3139
- ...mcpOverrides
3140
- ];
3141
- const args = sessionId ? ["exec", ...execOpts, "resume", sessionId, promptArg] : ["exec", ...execOpts, promptArg];
3142
- return {
3143
- file: resolveAgentExecutable("codex"),
3144
- args,
3145
- cwd: thread.worktreePath,
3146
- stdin: useStdin ? `${prompt}
3147
- ` : void 0,
3148
- ...secretProfile ? { cleanupDirs: [secretProfile.file] } : {}
3149
- };
3150
- },
3151
- parseEvent(line) {
3152
- const trimmed = line.trim();
3153
- if (!trimmed) return null;
3154
- try {
3155
- const obj = JSON.parse(trimmed);
3156
- const type = typeof obj.type === "string" ? obj.type : "";
3157
- if (type === "turn.failed" || type === "turn_failed") {
3158
- const detail = extractJsonErrorMessage(obj) || extractJsonErrorMessage(obj.error ?? {}) || "Codex turn failed";
3159
- return { type: "stderr", data: detail };
3160
- }
3161
- if (type === "error") {
3162
- const detail = extractJsonErrorMessage(obj) || trimmed;
3163
- if (/^reconnecting\.\.\./i.test(detail)) return null;
3164
- return { type: "stderr", data: detail };
3165
- }
3166
- if (typeof obj.item === "object" && obj.item !== null) {
3167
- const item = obj.item;
3168
- const itemType = item.type ?? item.item_type;
3169
- const mapped = eventsFromCodexItem(type, item);
3170
- if (mapped) return mapped;
3171
- if (itemType === "error") {
3172
- const detail = (typeof item.message === "string" ? item.message.trim() : "") || extractJsonErrorMessage(obj) || "Codex item error";
3173
- return { type: "stderr", data: detail };
3174
- }
3175
- if (itemType === "agent_message" && item.text) {
3176
- return { type: "stdout", data: item.text };
3177
- }
3178
- if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
3179
- const name = `mcp__${item.server}__${item.tool}`;
3180
- const input = asRecord3(item.arguments);
3181
- const events = [
3182
- { type: "tool_use", id: item.id, name, input }
3183
- ];
3184
- const finished = type === "item.completed" || item.status === "completed" || item.status === "failed";
3185
- if (finished) {
3186
- const errMsg = item.error && typeof item.error.message === "string" ? item.error.message : void 0;
3187
- events.push({
3188
- type: "tool_result",
3189
- id: item.id,
3190
- content: unwrapCodexMcpResult(item.result) ?? errMsg,
3191
- isError: item.status === "failed" || Boolean(errMsg)
3192
- });
3193
- }
3194
- return events.length === 1 ? events[0] : events;
3195
- }
3196
- if (itemType === "command_execution" && item.id) {
3197
- const input = item.command ? { command: item.command } : void 0;
3198
- const events = [
3199
- { type: "tool_use", id: item.id, name: "Bash", input }
3200
- ];
3201
- const finished = type === "item.completed" || item.status === "completed" || item.status === "failed" || item.status === "declined";
3202
- const output = typeof item.aggregated_output === "string" && item.aggregated_output ? item.aggregated_output : void 0;
3203
- if (finished) {
3204
- events.push({
3205
- type: "tool_result",
3206
- id: item.id,
3207
- content: output,
3208
- isError: item.status === "failed" || item.status === "declined"
3209
- });
3210
- } else if (output) {
3211
- events.push({
3212
- type: "tool_result",
3213
- id: item.id,
3214
- content: output,
3215
- partial: true
3216
- });
3217
- }
3218
- return events.length === 1 ? events[0] : events;
3219
- }
3220
- if (itemType === "collab_tool_call" && item.id) {
3221
- const rawTool = typeof item.tool === "string" ? item.tool : "spawn_agent";
3222
- const name = /spawn/i.test(rawTool) ? "spawn_agent" : rawTool;
3223
- const input = {};
3224
- if (item.prompt) input.prompt = item.prompt;
3225
- if (Array.isArray(item.receiver_thread_ids)) {
3226
- input.receiver_thread_ids = item.receiver_thread_ids;
3227
- }
3228
- const events = [{ type: "tool_use", id: item.id, name, input }];
3229
- const finished = type === "item.completed" || item.status === "completed" || item.status === "failed";
3230
- if (finished) {
3231
- const nested = [];
3232
- if (item.agents_states && typeof item.agents_states === "object") {
3233
- for (const value of Object.values(item.agents_states)) {
3234
- const msg = value && typeof value === "object" && typeof value.message === "string" ? value.message.trim() : "";
3235
- if (msg) nested.push(msg);
3236
- }
3237
- }
3238
- for (const text of nested) {
3239
- events.push({ type: "stdout", data: text, parentId: item.id });
3240
- }
3241
- events.push({
3242
- type: "tool_result",
3243
- id: item.id,
3244
- content: nested.join("\n") || void 0,
3245
- isError: item.status === "failed"
3246
- });
3247
- }
3248
- return events.length === 1 ? events[0] : events;
3249
- }
3250
- if (item.status === "failed") {
3251
- const detail = (typeof item.message === "string" ? item.message.trim() : "") || extractJsonErrorMessage(item) || `Codex ${itemType ?? "item"} failed`;
3252
- return { type: "stderr", data: detail };
3253
- }
3254
- }
3255
- const sid = typeof obj.session_id === "string" && obj.session_id || typeof obj.thread_id === "string" && obj.thread_id || typeof obj.session?.id === "string" && obj.session.id;
3256
- if (sid && (type === "thread.started" || type === "session" || !type)) {
3257
- return { type: "session_id", data: sid };
3258
- }
3259
- if (type === "turn.completed" || type === "turn_completed") {
3260
- const payload = obj;
3261
- const usage = payload.last_token_usage ? usageFromCodex(payload.last_token_usage, true) : usageFromCodex(payload.usage);
3262
- return usage ? { type: "usage", data: usage, scope: "turn" } : null;
3263
- }
3264
- if (typeof obj.content === "string" && obj.content.trim()) {
3265
- return { type: "stdout", data: obj.content };
3266
- }
3267
- return null;
3268
- } catch {
3269
- if (/error|failed|unauthorized|quota|limit/i.test(trimmed)) {
3270
- return { type: "stderr", data: trimmed };
3271
- }
3272
- return { type: "stdout", data: line };
2904
+ if (block.type === "text" && block.text) {
2905
+ injected.push(...eventsFromInjectedUserText(block.text, parentId));
3273
2906
  }
3274
- },
3275
- async resolveSessionId(_worktreePath, cached) {
3276
- return cached;
3277
- },
3278
- async buildAttach(thread) {
3279
- const codex = resolveAgentExecutable("codex");
3280
- const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3281
- if (sessionId) {
3282
- return {
3283
- file: codex,
3284
- args: ["resume", sessionId],
3285
- cwd: thread.worktreePath
3286
- };
2907
+ }
2908
+ if (out.length === 0 && injected.length === 0) return [];
2909
+ return [...out, ...injected];
2910
+ }
2911
+ function eventsFromContentBlocks(blocks, parentId) {
2912
+ if (!blocks?.length) return [];
2913
+ const out = [];
2914
+ for (const block of blocks) {
2915
+ if (!block?.type) continue;
2916
+ if (block.type === "text" && block.text) {
2917
+ out.push(...eventsFromAssistantText(block.text, parentId));
2918
+ continue;
2919
+ }
2920
+ if ((block.type === "thinking" || block.type === "redacted_thinking") && block.thinking) {
2921
+ out.push(withEventParentId({ type: "thinking", data: block.thinking }, parentId));
2922
+ continue;
2923
+ }
2924
+ if (block.type === "tool_use" && block.id && block.name) {
2925
+ out.push(
2926
+ withEventParentId(
2927
+ {
2928
+ type: "tool_use",
2929
+ id: block.id,
2930
+ name: block.name,
2931
+ input: block.input
2932
+ },
2933
+ parentId
2934
+ )
2935
+ );
2936
+ continue;
2937
+ }
2938
+ if (block.type === "tool_result" && block.tool_use_id) {
2939
+ out.push(
2940
+ withEventParentId(
2941
+ {
2942
+ type: "tool_result",
2943
+ id: block.tool_use_id,
2944
+ content: toolResultContent(block),
2945
+ isError: Boolean(block.is_error)
2946
+ },
2947
+ parentId
2948
+ )
2949
+ );
3287
2950
  }
3288
- return {
3289
- file: codex,
3290
- args: ["--cd", thread.worktreePath],
3291
- cwd: thread.worktreePath
3292
- };
3293
- },
3294
- async listLinearIssues(_repoPath) {
3295
- return listAssignedLinearIssues();
3296
2951
  }
3297
- };
3298
-
3299
- // src/agents/cursor.ts
3300
- import { existsSync as existsSync9 } from "fs";
3301
- import { createRequire as createRequire3 } from "module";
3302
- import { dirname as dirname5, join as join8 } from "path";
3303
- import { fileURLToPath as fileURLToPath3 } from "url";
3304
- var FALLBACK_CURSOR_MODELS = [
3305
- { id: "default", displayName: "Auto" },
3306
- { id: "composer-2.5", displayName: "Composer 2.5" },
3307
- { id: "composer-2", displayName: "Composer 2" }
3308
- ];
3309
- var cachedModels = null;
3310
- var MODEL_CACHE_MS = 5 * 60 * 1e3;
3311
- function resolveCursorApiKey() {
3312
- const fromEnv = (process.env.CURSOR_API_KEY || "").trim();
3313
- if (fromEnv) return fromEnv;
3314
- return (loadAppSettings().environment.CURSOR_API_KEY || "").trim();
3315
- }
3316
- function isCursorApiKeyConfigured() {
3317
- return Boolean(resolveCursorApiKey());
2952
+ return out;
3318
2953
  }
3319
- function isCursorAutoModel(model) {
3320
- const id = (model ?? "").trim().toLowerCase();
3321
- return !id || id === "default" || id === "auto";
2954
+ function claudeParentToolUseId(obj) {
2955
+ const nested = obj.event && typeof obj.event === "object" && !Array.isArray(obj.event) ? obj.event : void 0;
2956
+ for (const id of [obj.parent_tool_use_id, nested?.parent_tool_use_id]) {
2957
+ if (typeof id === "string" && id.trim()) return id.trim();
2958
+ }
2959
+ return void 0;
3322
2960
  }
3323
- function resolveCursorModelId(model) {
3324
- if (isCursorAutoModel(model)) return "default";
3325
- return model.trim();
2961
+ function claudeString(obj, key) {
2962
+ const v = obj[key];
2963
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
3326
2964
  }
3327
- async function listCursorModels() {
3328
- const now = Date.now();
3329
- if (cachedModels && now - cachedModels.at < MODEL_CACHE_MS) {
3330
- return cachedModels.models;
2965
+ function eventsFromClaudeSystem(obj) {
2966
+ const subtype = claudeString(obj, "subtype") ?? "";
2967
+ const parentId = claudeParentToolUseId(obj);
2968
+ if (subtype === "init") {
2969
+ if (parentId) return null;
2970
+ const sid = claudeString(obj, "session_id");
2971
+ const mcpNote = mcpStatusThinkingFromClaudeInit(obj);
2972
+ const events = [];
2973
+ if (sid) events.push({ type: "session_id", data: sid });
2974
+ if (mcpNote) events.push({ type: "thinking", data: mcpNote, replace: true });
2975
+ if (events.length === 0) return null;
2976
+ return events.length === 1 ? events[0] : events;
3331
2977
  }
3332
- const apiKey = resolveCursorApiKey();
3333
- if (!apiKey) return FALLBACK_CURSOR_MODELS;
3334
- const sdk = await importCursorSdk();
3335
- if (!sdk) return FALLBACK_CURSOR_MODELS;
3336
- try {
3337
- const listed = await sdk.Cursor.models.list({ apiKey });
3338
- const models = listed.map((m) => ({
3339
- id: m.id,
3340
- displayName: m.displayName || m.id,
3341
- description: m.description
3342
- })).filter((m) => Boolean(m.id));
3343
- if (models.length === 0) return FALLBACK_CURSOR_MODELS;
3344
- cachedModels = { at: now, models };
3345
- return models;
3346
- } catch {
3347
- return cachedModels?.models ?? FALLBACK_CURSOR_MODELS;
2978
+ if (subtype === "task_started") {
2979
+ const id = claudeString(obj, "tool_use_id") ?? claudeString(obj, "task_id");
2980
+ if (!id) return null;
2981
+ const description = claudeString(obj, "description");
2982
+ const taskType = claudeString(obj, "task_type");
2983
+ const prompt = claudeString(obj, "prompt");
2984
+ return withEventParentId(
2985
+ {
2986
+ type: "tool_use",
2987
+ id,
2988
+ name: taskType || "Agent",
2989
+ input: {
2990
+ ...description ? { description } : {},
2991
+ ...prompt ? { prompt } : {},
2992
+ ...claudeString(obj, "task_id") ? { task_id: claudeString(obj, "task_id") } : {}
2993
+ }
2994
+ },
2995
+ parentId
2996
+ );
3348
2997
  }
3349
- }
3350
- function entryDir2() {
3351
- const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
3352
- if (cjsDir) return cjsDir;
3353
- try {
3354
- return dirname5(fileURLToPath3(import.meta.url));
3355
- } catch {
3356
- try {
3357
- const req = createRequire3(process.cwd() + "/");
3358
- return dirname5(req.resolve("@sideboard-ai/core"));
3359
- } catch {
3360
- return process.cwd();
2998
+ if (subtype === "task_notification") {
2999
+ const id = claudeString(obj, "tool_use_id") ?? claudeString(obj, "task_id") ?? parentId;
3000
+ if (!id) return null;
3001
+ const status = claudeString(obj, "status") ?? "working";
3002
+ const tools = typeof obj.tool_uses === "number" ? obj.tool_uses : void 0;
3003
+ const durationMs = typeof obj.duration_ms === "number" ? obj.duration_ms : void 0;
3004
+ const lastTool = claudeString(obj, "last_tool") ?? claudeString(obj, "current_tool") ?? claudeString(obj, "tool");
3005
+ const snapshot = [
3006
+ status,
3007
+ tools != null ? `${tools} tools` : null,
3008
+ durationMs != null ? `${Math.round(durationMs / 1e3)}s` : null,
3009
+ lastTool
3010
+ ].filter((bit) => Boolean(bit)).join(" \xB7 ");
3011
+ return [
3012
+ {
3013
+ type: "tool_use",
3014
+ id,
3015
+ name: claudeString(obj, "task_type") || "Agent",
3016
+ input: {
3017
+ live_status: status,
3018
+ ...tools != null ? { live_tool_uses: tools } : {},
3019
+ ...durationMs != null ? { live_duration_ms: durationMs } : {},
3020
+ ...lastTool ? { live_last_tool: lastTool } : {}
3021
+ }
3022
+ },
3023
+ withEventParentId(
3024
+ { type: "thinking", data: snapshot, replace: true },
3025
+ id
3026
+ )
3027
+ ];
3028
+ }
3029
+ if (subtype === "api_retry") {
3030
+ const attempt = obj.attempt;
3031
+ const max = obj.max_retries;
3032
+ const delay = obj.retry_delay_ms;
3033
+ return {
3034
+ type: "thinking",
3035
+ data: `API retry ${attempt ?? "?"}/${max ?? "?"}${typeof delay === "number" ? ` (wait ${delay}ms)` : ""}`
3036
+ };
3037
+ }
3038
+ if (subtype === "status") {
3039
+ const status = claudeString(obj, "status");
3040
+ if (status === "compacting") {
3041
+ return { type: "thinking", data: "Compressing context\u2026", replace: true };
3361
3042
  }
3043
+ return null;
3362
3044
  }
3363
- }
3364
- function cursorRunnerPath() {
3365
- const packaged = packagedCursorRunnerPath();
3366
- if (packaged) return packaged;
3367
- const root = entryDir2();
3368
- const candidates = [
3369
- join8(root, "agents", "cursor-runner.js"),
3370
- join8(root, "agents", "cursor-runner.cjs"),
3371
- // If somehow resolved from package root instead of dist/
3372
- join8(root, "dist", "agents", "cursor-runner.js"),
3373
- join8(root, "dist", "agents", "cursor-runner.cjs"),
3374
- // Source tree (dev): packages/core/src/agents/cursor-runner.ts
3375
- join8(root, "cursor-runner.ts"),
3376
- join8(root, "src", "agents", "cursor-runner.ts")
3377
- ];
3378
- for (const candidate of candidates) {
3379
- if (existsSync9(candidate)) return candidate;
3045
+ if (subtype === "compact_boundary" || subtype === "compact") {
3046
+ const meta = compactMetadataFromClaude(obj);
3047
+ const trigger = meta.trigger ? ` (${meta.trigger})` : "";
3048
+ const thinking = {
3049
+ type: "thinking",
3050
+ data: `Context compressed${trigger}`,
3051
+ replace: true
3052
+ };
3053
+ if (meta.postTokens != null && meta.postTokens > 0 && !parentId) {
3054
+ return [
3055
+ thinking,
3056
+ {
3057
+ type: "usage",
3058
+ data: {
3059
+ inputTokens: 0,
3060
+ outputTokens: 0,
3061
+ lastRequestTokens: meta.postTokens
3062
+ },
3063
+ scope: "request"
3064
+ }
3065
+ ];
3066
+ }
3067
+ return thinking;
3380
3068
  }
3381
- return candidates[0];
3069
+ return null;
3382
3070
  }
3383
- var cursorAdapter = {
3384
- kind: "cursor",
3071
+ function compactMetadataFromClaude(obj) {
3072
+ const raw = obj.compactMetadata ?? obj.compact_metadata;
3073
+ if (!raw || typeof raw !== "object") return {};
3074
+ const meta = raw;
3075
+ const trigger = typeof meta.trigger === "string" && meta.trigger.trim() ? meta.trigger.trim() : void 0;
3076
+ const post = meta.postTokens ?? meta.post_tokens;
3077
+ const postTokens = typeof post === "number" && Number.isFinite(post) && post > 0 ? Math.round(post) : void 0;
3078
+ return { trigger, postTokens };
3079
+ }
3080
+ var claudeAdapter = {
3081
+ kind: "claude",
3385
3082
  async detect() {
3386
- if (!isCursorSdkInstalled()) {
3387
- return {
3388
- agent: "cursor",
3389
- installed: false,
3390
- authenticated: false,
3391
- linearMcp: false,
3392
- warnings: [],
3393
- reason: CURSOR_SDK_INSTALL_HINT
3394
- };
3395
- }
3396
- const apiKey = resolveCursorApiKey();
3397
- if (!apiKey) {
3398
- return {
3399
- agent: "cursor",
3400
- installed: true,
3401
- authenticated: false,
3402
- linearMcp: false,
3403
- warnings: [],
3404
- reason: "CURSOR_API_KEY not set \u2014 add it in Settings \u2192 Agents \u2192 Cursor, or Settings \u2192 Environment"
3405
- };
3083
+ const claude = resolveClaudeExecutable();
3084
+ if (claude !== "claude") {
3085
+ if (!existsSync8(claude)) {
3086
+ return {
3087
+ agent: "claude",
3088
+ installed: false,
3089
+ authenticated: false,
3090
+ linearMcp: false,
3091
+ warnings: [],
3092
+ reason: `Claude Code executable not found: ${claude}`
3093
+ };
3094
+ }
3095
+ } else {
3096
+ const which = await run("which", ["claude"], { reject: false });
3097
+ if (which.exitCode !== 0) {
3098
+ return {
3099
+ agent: "claude",
3100
+ installed: false,
3101
+ authenticated: false,
3102
+ linearMcp: false,
3103
+ warnings: [],
3104
+ reason: "claude CLI not found on PATH"
3105
+ };
3106
+ }
3406
3107
  }
3108
+ const auth = await run(claude, ["auth", "status"], {
3109
+ reject: false,
3110
+ timeoutMs: 5e3
3111
+ });
3112
+ const authenticated = auth.exitCode === 0;
3407
3113
  return {
3408
- agent: "cursor",
3114
+ agent: "claude",
3409
3115
  installed: true,
3410
- authenticated: true,
3116
+ authenticated,
3411
3117
  linearMcp: false,
3412
- warnings: []
3118
+ warnings: [],
3119
+ reason: authenticated ? void 0 : "claude auth status failed \u2014 run `claude auth login`"
3413
3120
  };
3414
3121
  },
3415
3122
  async buildTurn(thread, input) {
3416
- const agentId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3417
- const fullPrompt = flattenTurnInput(input);
3418
- const prompt = flattenTurnInput(dropCachedPrefixOnResume(input, agentId));
3419
- const apiKey = resolveCursorApiKey() || void 0;
3420
- const isOrchestrator = isOrchestratorThread(thread);
3421
- const rpc = agentRpcConnectFromMetadata();
3422
- const injected = await buildInjectedMcpServers({
3123
+ const claude = resolveClaudeExecutable();
3124
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3125
+ const effective = dropCachedPrefixOnResume(input, sessionId);
3126
+ let { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
3127
+ const useStdin = promptText.length > CLAUDE_PROMPT_ARG_MAX;
3128
+ if (process.env.SIDEBOARD_DEBUG_CLAUDE_TURN === "1") {
3129
+ console.error(
3130
+ `[sideboard/claude] promptChars=${promptText.length} resumed=${Boolean(sessionId)} stdin=${useStdin}`
3131
+ );
3132
+ }
3133
+ const mode = permissionMode(thread);
3134
+ const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-UG2A3CEM.js");
3135
+ const isOrchestrator = isOrchestratorThread2(thread);
3136
+ const rpc = worktreeAgentRpc(isOrchestrator);
3137
+ const injectedServers = await buildInjectedMcpServers({
3423
3138
  includeSideboard: true,
3424
3139
  includeBrightsy: shouldInjectBrightsyMcp(thread, {
3425
3140
  orchestrator: isOrchestrator
@@ -3428,387 +3143,479 @@ var cursorAdapter = {
3428
3143
  threadId: thread.id,
3429
3144
  rpcNativeTools: Boolean(rpc)
3430
3145
  });
3431
- const mcpServers = toCursorMcpServers(injected);
3432
- const req = {
3433
- prompt,
3434
- ...fullPrompt !== prompt ? { freshPrompt: fullPrompt } : {},
3435
- cwd: thread.worktreePath,
3436
- threadId: thread.id,
3437
- agentId,
3438
- model: thread.model,
3439
- effort: thread.effort,
3440
- fast: thread.fast,
3441
- planMode: thread.planMode,
3442
- apiKey,
3443
- ...isOrchestrator ? { isolateAmbientMcp: true } : {},
3444
- ...rpc ? { agentRpc: rpc } : {},
3445
- ...isOrchestrator && rpc ? { rpcWaitForTurn: true } : {},
3446
- ...Object.keys(mcpServers).length > 0 ? { mcpServers } : {}
3447
- };
3448
- const runner = cursorRunnerPath();
3449
- const isTs = runner.endsWith(".ts");
3450
- const launch = applyNodeLaunch(
3451
- await resolveNodeLaunch(runner),
3452
- isTs ? ["--import", "tsx", runner] : [runner]
3453
- );
3146
+ const injectedBrightsyNames = injectedServers.filter((s) => s.name === "brightsy" || s.name.startsWith("brightsy_")).map((s) => s.name);
3147
+ const chromeOn = claudeChromeEnabled();
3148
+ const userMcpEntries = await proxyClaudeUserMcp(isOrchestrator, [thread.repoPath, thread.worktreePath]);
3149
+ const posthogConnector = !isOrchestrator && !isPosthogConnected() ? await claudePosthogConnectorForTurn() : null;
3150
+ if (posthogConnector && !Object.prototype.hasOwnProperty.call(userMcpEntries, CLAUDE_POSTHOG_CONNECTOR_SERVER)) {
3151
+ userMcpEntries[CLAUDE_POSTHOG_CONNECTOR_SERVER] = { ...posthogConnector };
3152
+ const hint = "PostHog: Settings \u2192 Connectors is not signed in. This turn loads the claude.ai PostHog connector (`claude.ai PostHog`, tools `mcp__claude_ai_PostHog__*`). Use those tools. Do not say PostHog is unavailable.";
3153
+ systemPrompt = systemPrompt ? `${systemPrompt}
3154
+
3155
+ ${hint}` : hint;
3156
+ }
3157
+ const isolateClaudeAiMcp = isOrchestrator || isLocalDevAppDataDir() && !posthogConnector;
3158
+ let allowedTools;
3159
+ if (isOrchestrator) {
3160
+ allowedTools = [
3161
+ ...BASE_ALLOWED_TOOLS,
3162
+ ...SIDEBOARD_MCP_ALLOWED_TOOLS,
3163
+ ...brightsyMcpAllowedTools(injectedBrightsyNames),
3164
+ ...mcpAllowToolsFromNames(thread.approvedMcpServers ?? [])
3165
+ ];
3166
+ } else {
3167
+ allowedTools = [
3168
+ ...BASE_ALLOWED_TOOLS,
3169
+ ...mcpAllowToolsFromNames([...Object.keys(userMcpEntries), ...thread.approvedMcpServers ?? []]),
3170
+ ...sideboardWorktreeAllowedTools({
3171
+ github: true,
3172
+ linear: isLinearConnected(),
3173
+ abletime: isAbleTimeConnected(),
3174
+ planMode: thread.planMode,
3175
+ posthog: isPosthogConnected()
3176
+ }),
3177
+ ...brightsyMcpAllowedTools(injectedBrightsyNames),
3178
+ ...isPosthogConnected() ? [] : CLAUDE_POSTHOG_CONNECTOR_ALLOWED_TOOLS
3179
+ ];
3180
+ }
3181
+ if (chromeOn) {
3182
+ allowedTools = [...allowedTools, ...CLAUDE_CHROME_ALLOWED_TOOLS];
3183
+ }
3184
+ if (rpc) {
3185
+ return buildClaudeRpcTurnCommand({
3186
+ prompt: promptText,
3187
+ cwd: thread.worktreePath,
3188
+ sessionId,
3189
+ model: thread.model,
3190
+ effort: thread.effort ?? (thread.fast ? "low" : "high"),
3191
+ permissionMode: mode.claude,
3192
+ systemPrompt,
3193
+ claudePath: claude,
3194
+ chrome: chromeOn,
3195
+ mcpServers: mcpServersRecord(injectedServers, userMcpEntries),
3196
+ allowedTools: withClaudePilotRpcTools(allowedTools),
3197
+ agentRpc: rpc,
3198
+ isolateClaudeAiMcp
3199
+ });
3200
+ }
3201
+ const args = [
3202
+ "-p",
3203
+ ...useStdin ? [] : [promptText],
3204
+ "--output-format",
3205
+ "stream-json",
3206
+ "--verbose",
3207
+ "--include-partial-messages",
3208
+ "--permission-mode",
3209
+ mode.claude,
3210
+ ...mode.claude === "bypassPermissions" ? ["--dangerously-skip-permissions"] : []
3211
+ ];
3212
+ if (systemPrompt) {
3213
+ args.push("--append-system-prompt", systemPrompt);
3214
+ }
3215
+ const mcpConfigPath = writeMcpServersConfig(injectedServers, userMcpEntries);
3216
+ if (mcpConfigPath) {
3217
+ args.push("--mcp-config", mcpConfigPath);
3218
+ args.push("--strict-mcp-config");
3219
+ }
3220
+ if (chromeOn) {
3221
+ args.push("--chrome");
3222
+ }
3223
+ if (useStdin) {
3224
+ args.push("--input-format", "text");
3225
+ }
3226
+ for (const tool of allowedTools) {
3227
+ args.push("--allowedTools", tool);
3228
+ }
3229
+ if (thread.model) {
3230
+ args.push("--model", thread.model);
3231
+ }
3232
+ const effort = thread.effort ?? (thread.fast ? "low" : "high");
3233
+ args.push("--effort", effort);
3234
+ if (sessionId) {
3235
+ args.push("--resume", sessionId);
3236
+ }
3454
3237
  return {
3455
- file: launch.file,
3456
- args: launch.args,
3238
+ file: claude,
3239
+ args,
3457
3240
  cwd: thread.worktreePath,
3458
- stdin: JSON.stringify(req),
3241
+ stdin: useStdin ? `${promptText}
3242
+ ` : void 0,
3243
+ ...mcpConfigPath ? { cleanupDirs: [dirname4(mcpConfigPath)] } : {},
3244
+ // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
3245
+ // Raise the -p background-agent wait so long TaskOutput polls are not
3246
+ // abandoned at Claude Code’s 10-minute default.
3459
3247
  env: {
3460
- ...launch.env,
3461
- ...cursorRipgrepEnv({ startFile: runner })
3462
- // API key stays on the stdin request. Do not copy it into the child env,
3463
- // where `ps` and crash dumps can see it. The runner reads `req.apiKey`.
3248
+ CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
3249
+ CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? String(CLAUDE_PRINT_BG_WAIT_CEILING_MS),
3250
+ // Current Claude Code does not fetch claude.ai connectors under
3251
+ // `--strict-mcp-config`. The env is the off switch for older builds
3252
+ // that still fetched the whole account list, and it also refuses an
3253
+ // explicit claudeai-proxy. Orchestrators always set it. Local dev sets
3254
+ // it only when this turn is not passing the PostHog connector.
3255
+ ...isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
3464
3256
  }
3465
3257
  };
3466
3258
  },
3467
3259
  parseEvent(line) {
3468
- return parseCursorRunnerLine(line);
3260
+ const trimmed = line.trim();
3261
+ if (!trimmed) return null;
3262
+ try {
3263
+ const obj = JSON.parse(trimmed);
3264
+ if (obj.type === "system") {
3265
+ return eventsFromClaudeSystem(obj);
3266
+ }
3267
+ if (obj.type === "assistant" || obj.type === "user") {
3268
+ const parentId = claudeParentToolUseId(obj);
3269
+ const message = obj.message;
3270
+ const events = obj.type === "user" ? eventsFromUserContent(message?.content, parentId) : eventsFromContentBlocks(
3271
+ Array.isArray(message?.content) ? message.content : void 0,
3272
+ parentId
3273
+ );
3274
+ if (obj.type === "assistant" && !parentId) {
3275
+ const usage = usageFromClaude(message?.usage);
3276
+ const messageId = message && typeof message.id === "string" ? message.id : void 0;
3277
+ if (usage) {
3278
+ events.push({
3279
+ type: "usage",
3280
+ data: usage,
3281
+ scope: "request",
3282
+ ...messageId ? { messageId } : {}
3283
+ });
3284
+ }
3285
+ }
3286
+ if (events.length === 0) return null;
3287
+ return events.length === 1 ? events[0] : events;
3288
+ }
3289
+ if (obj.type === "stream_event") {
3290
+ const parentId = claudeParentToolUseId(obj);
3291
+ const event = obj.event;
3292
+ if (!event) return null;
3293
+ if (event.type === "content_block_start" && event.content_block) {
3294
+ const block = event.content_block;
3295
+ if (block.type === "tool_use" && block.id && block.name) {
3296
+ return withEventParentId(
3297
+ {
3298
+ type: "tool_use",
3299
+ id: block.id,
3300
+ name: block.name,
3301
+ input: block.input
3302
+ },
3303
+ parentId
3304
+ );
3305
+ }
3306
+ if (block.type === "thinking" && block.thinking) {
3307
+ return withEventParentId({ type: "thinking", data: block.thinking }, parentId);
3308
+ }
3309
+ return null;
3310
+ }
3311
+ if (event.type === "content_block_delta" && event.delta) {
3312
+ if (event.delta.text) {
3313
+ return withEventParentId({ type: "stdout", data: event.delta.text }, parentId);
3314
+ }
3315
+ if (event.delta.thinking) {
3316
+ return withEventParentId({ type: "thinking", data: event.delta.thinking }, parentId);
3317
+ }
3318
+ return null;
3319
+ }
3320
+ return null;
3321
+ }
3322
+ if (obj.type === "content_block_delta") {
3323
+ const parentId = claudeParentToolUseId(obj);
3324
+ const delta = obj.delta;
3325
+ if (delta?.text) return withEventParentId({ type: "stdout", data: delta.text }, parentId);
3326
+ if (delta?.thinking) {
3327
+ return withEventParentId({ type: "thinking", data: delta.thinking }, parentId);
3328
+ }
3329
+ return null;
3330
+ }
3331
+ if (obj.type === "result") {
3332
+ const events = [];
3333
+ const errorDetail = claudeResultErrorDetail(obj);
3334
+ if (errorDetail) {
3335
+ events.push({ type: "stderr", data: errorDetail });
3336
+ } else {
3337
+ const text = obj.result;
3338
+ if (typeof text === "string" && text) {
3339
+ events.push(...eventsFromAssistantText(text));
3340
+ }
3341
+ }
3342
+ const usage = usageFromClaude(obj.usage);
3343
+ if (usage) {
3344
+ const costUsd = costUsdFromClaudeResult(obj);
3345
+ if (costUsd != null) usage.costUsd = costUsd;
3346
+ const sessionCostUsd = sessionCostUsdFromClaudeResult(obj);
3347
+ if (sessionCostUsd != null) usage.sessionCostUsd = sessionCostUsd;
3348
+ events.push({ type: "usage", data: usage, scope: "turn" });
3349
+ }
3350
+ if (events.length === 0) return null;
3351
+ return events.length === 1 ? events[0] : events;
3352
+ }
3353
+ return null;
3354
+ } catch {
3355
+ return { type: "stdout", data: line };
3356
+ }
3469
3357
  },
3470
3358
  async resolveSessionId(_worktreePath, cached) {
3471
3359
  return cached;
3472
3360
  },
3473
3361
  async buildAttach(thread) {
3474
- const which = await run("which", ["cursor"], { reject: false });
3475
- if (which.exitCode === 0) {
3476
- return { file: "cursor", args: [thread.worktreePath], cwd: thread.worktreePath };
3477
- }
3478
- throw new Error(
3479
- "Cursor agents have no interactive CLI attach. Install the Cursor shell command (`cursor`) to open the worktree, or continue the thread in Sideboard."
3480
- );
3362
+ const claude = resolveClaudeExecutable();
3363
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3364
+ const args = sessionId ? ["--resume", sessionId] : [];
3365
+ if (claudeChromeEnabled()) {
3366
+ args.push("--chrome");
3367
+ }
3368
+ return { file: claude, args, cwd: thread.worktreePath };
3369
+ },
3370
+ async listLinearIssues(_repoPath) {
3371
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-N57PR6JM.js");
3372
+ return listAssignedLinearIssues2();
3481
3373
  }
3482
3374
  };
3483
3375
 
3484
- // src/agents/opencode.ts
3485
- import { existsSync as existsSync11 } from "fs";
3486
-
3487
- // src/agent-rpc/opencode-host.ts
3488
- import { pathToFileURL } from "url";
3489
-
3490
- // src/agent-rpc/opencode-hook.ts
3491
- import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync, writeFileSync as writeFileSync4 } from "fs";
3492
- import { join as join9 } from "path";
3493
- var OPENCODE_PLUGIN_SOURCE = `import { tool } from "@opencode-ai/plugin"
3494
-
3495
- const RPC_URL = process.env[${JSON.stringify(AGENT_RPC_URL_ENV)}] || ""
3496
- const TOKEN = process.env[${JSON.stringify(AGENT_RPC_TOKEN_ENV)}] || ""
3497
- const CWD = process.env[${JSON.stringify(AGENT_RPC_CWD_ENV)}] || ""
3498
-
3499
- function jsonResult(value) {
3500
- return JSON.stringify(value)
3501
- }
3502
-
3503
- function jsonError(err) {
3504
- return jsonResult({ ok: false, error: err instanceof Error ? err.message : String(err) })
3505
- }
3506
-
3507
- function socketUrl() {
3508
- const u = new URL(RPC_URL)
3509
- u.searchParams.set(${JSON.stringify(AGENT_RPC_TOKEN_QUERY)}, TOKEN)
3510
- return u.toString()
3511
- }
3376
+ // src/agents/codex.ts
3377
+ import { existsSync as existsSync9, statSync } from "fs";
3378
+ import { homedir as homedir7 } from "os";
3379
+ import { join as join8 } from "path";
3512
3380
 
3513
- function call(method, params) {
3514
- if (!RPC_URL || !TOKEN) {
3515
- return Promise.resolve(jsonError(new Error("Agent RPC runtime is not running")))
3381
+ // src/agents/codex-items.ts
3382
+ function eventsFromCodexItem(eventType, item) {
3383
+ const itemType = item.type ?? item.item_type;
3384
+ if (itemType === "reasoning" && typeof item.text === "string" && item.text) {
3385
+ return { type: "thinking", data: item.text };
3516
3386
  }
3517
- const timeoutMs = method === "job.wait" ? 130000 : 30000
3518
- return new Promise((resolve) => {
3519
- let settled = false
3520
- let ws
3521
- let timer
3522
- const done = (value) => {
3523
- if (settled) return
3524
- settled = true
3525
- clearTimeout(timer)
3526
- try { ws.close() } catch {}
3527
- resolve(value)
3387
+ if (itemType !== "file_change" || !item.id) return null;
3388
+ const changes = Array.isArray(item.changes) ? item.changes : [];
3389
+ const paths = changes.map((change) => typeof change?.path === "string" ? change.path : "").filter(Boolean);
3390
+ const added = changes.some((change) => change?.kind === "add");
3391
+ const events = [
3392
+ {
3393
+ type: "tool_use",
3394
+ id: item.id,
3395
+ name: added ? "Write" : "Edit",
3396
+ input: paths.length ? { paths } : void 0
3528
3397
  }
3529
- timer = setTimeout(() => done(jsonError(new Error("Agent RPC timed out"))), timeoutMs)
3530
- ws = new WebSocket(socketUrl())
3531
- const id = Date.now()
3532
- ws.addEventListener("open", () => {
3533
- ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params, authToken: TOKEN }))
3534
- })
3535
- ws.addEventListener("message", (ev) => {
3536
- let msg
3537
- try { msg = JSON.parse(String(ev.data)) } catch { return }
3538
- if (msg && msg.id === id) {
3539
- if (msg.error) done(jsonError(new Error(msg.error.message || "Agent RPC error")))
3540
- else done(jsonResult(msg.result))
3541
- }
3542
- })
3543
- ws.addEventListener("error", () => done(jsonError(new Error("Agent RPC socket error"))))
3544
- ws.addEventListener("close", () => {
3545
- if (!settled) done(jsonError(new Error("Agent RPC socket closed")))
3546
- })
3547
- })
3548
- }
3549
-
3550
- function str(description) {
3551
- return tool.schema.string().describe(description)
3552
- }
3553
-
3554
- function opt(description) {
3555
- return tool.schema.string().optional().describe(description)
3398
+ ];
3399
+ const finished = eventType === "item.completed" || item.status === "completed" || item.status === "failed";
3400
+ if (finished) {
3401
+ events.push({
3402
+ type: "tool_result",
3403
+ id: item.id,
3404
+ content: paths.join("\n") || void 0,
3405
+ isError: item.status === "failed"
3406
+ });
3407
+ }
3408
+ return events.length === 1 ? events[0] : events;
3556
3409
  }
3557
3410
 
3558
- export const SideboardRpc = async (ctx) => {
3559
- const cwd = CWD || ctx.worktree || ctx.directory || ""
3560
- const job = (method, args) => call(method, { ...args, cwd })
3561
- return {
3562
- tool: {
3563
- present_artifact: tool({
3564
- description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.present_artifact)},
3565
- args: {
3566
- title: str("Short title shown in the artifact pane header"),
3567
- type: tool.schema.enum(["html", "svg", "markdown", "react", "log"]),
3568
- content: str("html/svg/markdown/react: full document. log: only the new lines."),
3569
- artifact_id: opt("Stable id. Required for type=log."),
3570
- status: tool.schema.enum(["running", "ok", "failed", "idle"]).optional(),
3571
- phase: opt("Progress phase"),
3572
- mode: tool.schema.enum(["append", "replace"]).optional(),
3573
- },
3574
- async execute(args) {
3575
- return call("ui.presentArtifact", args)
3576
- },
3577
- }),
3578
- wait_for_job: tool({
3579
- description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.wait_for_job)},
3580
- args: {
3581
- id: str("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
3582
- },
3583
- async execute(args) {
3584
- return job("job.wait", args)
3585
- },
3586
- }),
3587
- stop_job: tool({
3588
- description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.stop_job)},
3589
- args: {
3590
- id: str("Detached job id"),
3591
- reason: opt("Why the job is being stopped"),
3592
- },
3593
- async execute(args) {
3594
- return job("job.stop", args)
3595
- },
3596
- }),
3597
- },
3411
+ // src/agents/codex.ts
3412
+ var CODEX_PROMPT_ARG_MAX = 2e5;
3413
+ var FALLBACK_CODEX_MODELS = [
3414
+ { id: "gpt-5.6-sol", displayName: "GPT-5.6 Sol" },
3415
+ { id: "gpt-5.6-terra", displayName: "GPT-5.6 Terra" },
3416
+ { id: "gpt-5.6-luna", displayName: "GPT-5.6 Luna" },
3417
+ { id: "gpt-5.5", displayName: "GPT-5.5" },
3418
+ { id: "gpt-5.2", displayName: "GPT-5.2" }
3419
+ ];
3420
+ var cachedCodexModels = null;
3421
+ var CODEX_MODEL_CACHE_MS = 5 * 60 * 1e3;
3422
+ async function listCodexModels() {
3423
+ const now = Date.now();
3424
+ if (cachedCodexModels && now - cachedCodexModels.at < CODEX_MODEL_CACHE_MS) {
3425
+ return cachedCodexModels.models;
3598
3426
  }
3599
- }
3600
- `;
3601
- function writeOpencodeRpcPlugin() {
3602
- const pluginDir = join9(appDataDir(), "agent-rpc", "opencode");
3603
- mkdirSync3(pluginDir, { recursive: true });
3604
- const pluginFile = join9(pluginDir, "sideboard-rpc.js");
3605
- if (existsSync10(pluginFile)) {
3606
- try {
3607
- if (readFileSync4(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
3608
- } catch {
3609
- }
3427
+ const codex = resolveAgentExecutable("codex");
3428
+ if (codex === "codex") {
3429
+ const which = await run("which", ["codex"], { reject: false });
3430
+ if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
3431
+ } else if (!existsSync9(codex)) {
3432
+ return FALLBACK_CODEX_MODELS;
3610
3433
  }
3611
- const tmp = `${pluginFile}.${process.pid}.tmp`;
3612
- writeFileSync4(tmp, OPENCODE_PLUGIN_SOURCE);
3613
- renameSync(tmp, pluginFile);
3614
- return pluginFile;
3615
- }
3616
-
3617
- // src/agent-rpc/opencode-host.ts
3618
- async function buildOpencodeHostEnv(thread) {
3619
- const isOrchestrator = isOrchestratorThread(thread);
3620
- const rpc = worktreeAgentRpc(isOrchestrator);
3621
- const injected = await buildInjectedMcpServers({
3622
- includeSideboard: true,
3623
- includeBrightsy: shouldInjectBrightsyMcp(thread, {
3624
- orchestrator: isOrchestrator
3625
- }),
3626
- orchestratorThreadId: isOrchestrator ? thread.id : null,
3627
- threadId: thread.id,
3628
- rpcNativeTools: Boolean(rpc)
3629
- });
3630
- const disableNames = isOrchestrator ? userMcpNamesToDisable({
3631
- injectedNames: injected.map((s) => s.name),
3632
- names: listUserOpencodeMcpNames()
3633
- }) : [];
3634
- const config = injected.length > 0 || disableNames.length > 0 ? JSON.parse(toOpencodeMcpConfigContent(injected, { disableNames })) : {};
3635
- const env = {};
3636
- if (rpc) {
3637
- const pluginFile = writeOpencodeRpcPlugin();
3638
- Object.assign(env, agentRpcChildEnv(rpc, thread.worktreePath));
3639
- config.plugin = [pathToFileURL(pluginFile).href];
3434
+ const listed = await run(codex, ["debug", "models"], { reject: false });
3435
+ if (listed.exitCode !== 0 || !listed.stdout.trim()) {
3436
+ return cachedCodexModels?.models ?? FALLBACK_CODEX_MODELS;
3640
3437
  }
3641
- if (Object.keys(config).length > 0) {
3642
- env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
3438
+ try {
3439
+ const parsed = JSON.parse(listed.stdout);
3440
+ const rows = Array.isArray(parsed.models) ? parsed.models : [];
3441
+ const preferred = rows.filter((m) => (m.visibility ?? "list") === "list");
3442
+ const source = preferred.length > 0 ? preferred : rows;
3443
+ const models = source.map((m) => ({
3444
+ id: (m.slug || "").trim(),
3445
+ displayName: (m.display_name || m.slug || "").trim(),
3446
+ description: m.description,
3447
+ priority: typeof m.priority === "number" ? m.priority : 999
3448
+ })).filter((m) => m.id).sort((a, b) => a.priority - b.priority).map(({ id, displayName, description }) => ({ id, displayName, description }));
3449
+ if (models.length === 0) return FALLBACK_CODEX_MODELS;
3450
+ cachedCodexModels = { at: now, models };
3451
+ return models;
3452
+ } catch {
3453
+ return cachedCodexModels?.models ?? FALLBACK_CODEX_MODELS;
3643
3454
  }
3644
- return env;
3645
3455
  }
3646
-
3647
- // src/agents/opencode.ts
3648
- var FALLBACK_OPENCODE_MODELS = [
3649
- { id: "opencode/big-pickle", displayName: "opencode \xB7 big-pickle" },
3650
- {
3651
- id: "openrouter/~anthropic/claude-sonnet-latest",
3652
- displayName: "openrouter \xB7 claude-sonnet-latest"
3653
- },
3654
- {
3655
- id: "openrouter/~openai/gpt-latest",
3656
- displayName: "openrouter \xB7 gpt-latest"
3456
+ function usageFromCodex(usage, asContext = false) {
3457
+ if (!usage) return null;
3458
+ const mapped = fromInclusiveInputUsage({
3459
+ inputTokens: Number(usage.input_tokens ?? 0),
3460
+ outputTokens: Number(usage.output_tokens ?? 0),
3461
+ cachedInputTokens: Number(usage.cached_input_tokens ?? 0)
3462
+ });
3463
+ if (!mapped || !asContext) return mapped;
3464
+ const occ = requestOccupancy(mapped);
3465
+ return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
3466
+ }
3467
+ function codexHomeDir() {
3468
+ return process.env.CODEX_HOME?.trim() || join8(homedir7(), ".codex");
3469
+ }
3470
+ function unwrapCodexMcpResult(result) {
3471
+ if (result == null) return void 0;
3472
+ if (typeof result === "string") return result;
3473
+ if (typeof result !== "object") return String(result);
3474
+ const rec = result;
3475
+ if (Array.isArray(rec.content)) {
3476
+ const texts = [];
3477
+ for (const item of rec.content) {
3478
+ if (!item || typeof item !== "object") continue;
3479
+ const text = item.text;
3480
+ if (typeof text === "string") texts.push(text);
3481
+ }
3482
+ if (texts.length) return texts.join("\n");
3483
+ }
3484
+ try {
3485
+ return JSON.stringify(result);
3486
+ } catch {
3487
+ return String(result);
3657
3488
  }
3658
- ];
3659
- var cachedOpencodeModels = null;
3660
- var OPENCODE_MODEL_CACHE_MS = 5 * 60 * 1e3;
3489
+ }
3661
3490
  function asRecord4(value) {
3662
3491
  if (value && typeof value === "object" && !Array.isArray(value)) {
3663
3492
  return value;
3664
3493
  }
3665
3494
  return void 0;
3666
3495
  }
3667
- function str(v) {
3668
- return typeof v === "string" && v.trim() ? v.trim() : void 0;
3669
- }
3670
- function opencodeToolId(name, callId, metadata) {
3671
- const sessionId = str(metadata?.sessionId) ?? str(metadata?.sessionID);
3672
- if (name === "task" && sessionId) return sessionId;
3673
- return callId || `tool-${Date.now()}`;
3674
- }
3675
- function withTaskParent(parentId, nested) {
3676
- const events = Array.isArray(nested) ? nested : [nested];
3677
- return [{ type: "tool_use", id: parentId, name: "task" }, ...events];
3678
- }
3679
- function displayNameFromOpencodeId(id) {
3680
- const slash = id.indexOf("/");
3681
- if (slash <= 0) return id;
3682
- const provider = id.slice(0, slash);
3683
- const name = id.slice(slash + 1);
3684
- return `${provider} \xB7 ${name}`;
3685
- }
3686
- function sortOpencodeModelIds(ids) {
3687
- return [...ids].sort((a, b) => {
3688
- const aLatest = /latest|~/.test(a) ? 0 : 1;
3689
- const bLatest = /latest|~/.test(b) ? 0 : 1;
3690
- if (aLatest !== bLatest) return aLatest - bLatest;
3691
- const aOc = a.startsWith("opencode/") ? 0 : 1;
3692
- const bOc = b.startsWith("opencode/") ? 0 : 1;
3693
- if (aOc !== bOc) return aOc - bOc;
3694
- return a.localeCompare(b);
3695
- });
3696
- }
3697
- async function listOpencodeModels() {
3698
- const now = Date.now();
3699
- if (cachedOpencodeModels && now - cachedOpencodeModels.at < OPENCODE_MODEL_CACHE_MS) {
3700
- return cachedOpencodeModels.models;
3701
- }
3702
- const opencode = resolveAgentExecutable("opencode");
3703
- if (opencode === "opencode") {
3704
- const which = await run("which", ["opencode"], { reject: false });
3705
- if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
3706
- } else if (!existsSync11(opencode)) {
3707
- return FALLBACK_OPENCODE_MODELS;
3708
- }
3709
- const listed = await run(opencode, ["models"], { reject: false });
3710
- if (listed.exitCode !== 0 || !listed.stdout.trim()) {
3711
- return cachedOpencodeModels?.models ?? FALLBACK_OPENCODE_MODELS;
3496
+ function codexLooksAuthenticated() {
3497
+ const authPath = join8(codexHomeDir(), "auth.json");
3498
+ if (!existsSync9(authPath)) return false;
3499
+ try {
3500
+ return statSync(authPath).size > 2;
3501
+ } catch {
3502
+ return false;
3712
3503
  }
3713
- const ids = listed.stdout.split("\n").map((l) => l.trim()).filter((l) => /^[\w.~@+-]+\/[\w.~@+/-]+$/.test(l));
3714
- const unique = [...new Set(ids)];
3715
- if (unique.length === 0) return FALLBACK_OPENCODE_MODELS;
3716
- const OPENCODE_PICKER_LIMIT = 60;
3717
- const models = sortOpencodeModelIds(unique).slice(0, OPENCODE_PICKER_LIMIT).map((id) => ({
3718
- id,
3719
- displayName: displayNameFromOpencodeId(id)
3720
- }));
3721
- cachedOpencodeModels = { at: now, models };
3722
- return models;
3723
- }
3724
- function usageFromOpencode(tokens) {
3725
- if (!tokens) return null;
3726
- const inputTokens = Number(tokens.input ?? 0);
3727
- const outputTokens = Number(tokens.output ?? 0) + Number(tokens.reasoning ?? 0);
3728
- if (!inputTokens && !outputTokens) return null;
3729
- return {
3730
- inputTokens,
3731
- outputTokens,
3732
- cacheReadTokens: tokens.cache?.read ? Number(tokens.cache.read) : void 0,
3733
- cacheWriteTokens: tokens.cache?.write ? Number(tokens.cache.write) : void 0
3734
- };
3735
3504
  }
3736
- var opencodeAdapter = {
3737
- kind: "opencode",
3505
+ var codexAdapter = {
3506
+ kind: "codex",
3738
3507
  async detect() {
3739
- const opencode = resolveAgentExecutable("opencode");
3740
- if (opencode !== "opencode") {
3741
- if (!existsSync11(opencode)) {
3508
+ const codex = resolveAgentExecutable("codex");
3509
+ if (codex !== "codex") {
3510
+ if (!existsSync9(codex)) {
3742
3511
  return {
3743
- agent: "opencode",
3512
+ agent: "codex",
3744
3513
  installed: false,
3745
3514
  authenticated: false,
3746
3515
  linearMcp: false,
3747
3516
  warnings: [],
3748
- reason: `OpenCode executable not found: ${opencode}`
3517
+ reason: `Codex executable not found: ${codex}`
3749
3518
  };
3750
3519
  }
3751
3520
  } else {
3752
- const which = await run("which", ["opencode"], { reject: false });
3521
+ const which = await run("which", ["codex"], { reject: false, timeoutMs: 3e3 });
3753
3522
  if (which.exitCode !== 0) {
3754
3523
  return {
3755
- agent: "opencode",
3524
+ agent: "codex",
3756
3525
  installed: false,
3757
3526
  authenticated: false,
3758
3527
  linearMcp: false,
3759
3528
  warnings: [],
3760
- reason: "opencode CLI not found on PATH"
3529
+ reason: "codex CLI not found on PATH"
3761
3530
  };
3762
3531
  }
3763
3532
  }
3764
- const auth = await run(opencode, ["auth", "list"], { reject: false });
3765
- const authenticated = auth.exitCode === 0 && auth.stdout.trim().length > 0;
3766
- const mcp = await run(opencode, ["mcp", "list"], { reject: false });
3767
- const linearMcp = /linear/i.test(mcp.stdout + mcp.stderr);
3533
+ const authenticated = codexLooksAuthenticated();
3534
+ const linearMcp = false;
3535
+ const warnings = [];
3768
3536
  return {
3769
- agent: "opencode",
3537
+ agent: "codex",
3770
3538
  installed: true,
3771
3539
  authenticated,
3772
3540
  linearMcp,
3773
- warnings: [],
3774
- reason: authenticated ? void 0 : "opencode auth list empty \u2014 run `opencode auth login`"
3541
+ warnings,
3542
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${join8(codexHomeDir(), "auth.json")})`
3775
3543
  };
3776
3544
  },
3777
3545
  async buildTurn(thread, input) {
3778
3546
  const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3779
3547
  const prompt = flattenTurnInput(dropCachedPrefixOnResume(input, sessionId));
3548
+ const useStdin = prompt.length > CODEX_PROMPT_ARG_MAX;
3549
+ const promptArg = useStdin ? "-" : prompt;
3550
+ if (process.env.SIDEBOARD_DEBUG_CODEX_TURN === "1") {
3551
+ console.error(
3552
+ `[sideboard/codex] promptChars=${prompt.length} resumed=${Boolean(sessionId)} stdin=${useStdin} hasPrefix=${prompt.includes("Current request:")}`
3553
+ );
3554
+ }
3780
3555
  const mode = permissionMode(thread);
3781
3556
  const model = thread.model?.trim();
3782
- const args = [
3783
- "run",
3784
- "--dir",
3557
+ const isOrchestrator = isOrchestratorThread(thread);
3558
+ const injected = await buildInjectedMcpServers({
3559
+ includeSideboard: true,
3560
+ includeBrightsy: shouldInjectBrightsyMcp(thread, {
3561
+ orchestrator: isOrchestrator
3562
+ }),
3563
+ orchestratorThreadId: isOrchestrator ? thread.id : null,
3564
+ threadId: thread.id
3565
+ });
3566
+ const isolatePlugins = isOrchestrator || Boolean(thread.isolateCodexPlugins) || Boolean(normalizeTurnInput(input).isolateCodexPlugins);
3567
+ const gitEnv = await resolveAgentGitAuthEnv(process.env, {
3568
+ cwd: thread.worktreePath
3569
+ });
3570
+ const writableRoots = mode.codexSandbox === "workspace-write" ? await resolveCodexGitWritableRoots(thread.worktreePath) : [];
3571
+ const secretProfile = writeCodexMcpSecretProfile(injected);
3572
+ const effort = thread.effort?.trim() ?? "";
3573
+ const mcpOverrides = [
3574
+ // Worktree first try keeps plugins (Claude connectors). Coordinators
3575
+ // isolate. After a fatal plugin MCP, the orchestrator retries with
3576
+ // isolateCodexPlugins so the turn continues. Never invent mcp_servers.posthog.
3577
+ ...isolatePlugins ? toCodexUnattendedAppsArgs() : [],
3578
+ ...toCodexMcpConfigArgs(injected),
3579
+ ...isOrchestrator ? toCodexDisableUserMcpArgs(
3580
+ userMcpNamesToDisable({
3581
+ injectedNames: injected.map((s) => s.name),
3582
+ names: listUserCodexMcpNames()
3583
+ })
3584
+ ) : []
3585
+ ];
3586
+ const execOpts = [
3587
+ // Global orchestration cwd is not a git repo; without this Codex ≥0.147
3588
+ // refuses to start ("Not inside a trusted directory").
3589
+ ...secretProfile ? ["-p", secretProfile.profile] : [],
3590
+ "--skip-git-repo-check",
3591
+ "--cd",
3785
3592
  thread.worktreePath,
3786
- "--format",
3787
- "json"
3593
+ "--json",
3594
+ "--sandbox",
3595
+ mode.codexSandbox,
3596
+ // `codex exec` rejects `--ask-for-approval` (global-only on newer CLIs).
3597
+ "-c",
3598
+ 'approval_policy="never"',
3599
+ // Seatbelt cannot use the login Keychain. inherit=all keeps GH_CONFIG_DIR
3600
+ // and GIT_CONFIG_*. Default excludes still strip *TOKEN*/*SECRET*/*KEY*;
3601
+ // GIT_CONFIG_KEY_n is re-set because it matches *KEY*. Linked worktrees
3602
+ // need the main repo `.git` as writable_roots so git commit can lock.
3603
+ ...codexUnattendedGitConfigArgs(mode.codexSandbox, {
3604
+ writableRoots,
3605
+ preserveEnv: gitEnv
3606
+ }),
3607
+ ...model ? ["--model", model] : [],
3608
+ ...effort ? ["-c", `model_reasoning_effort=${JSON.stringify(effort)}`] : [],
3609
+ ...mcpOverrides
3788
3610
  ];
3789
- if (sessionId) {
3790
- args.push("--session", sessionId);
3791
- }
3792
- if (model) {
3793
- args.push("--model", model);
3794
- }
3795
- args.push("--thinking");
3796
- const variant = thread.effort?.trim() ?? "";
3797
- if (variant && /^(minimal|low|medium|high|max|xhigh)$/i.test(variant)) {
3798
- args.push("--variant", variant);
3799
- }
3800
- const hostEnv = await buildOpencodeHostEnv(thread);
3611
+ const args = sessionId ? ["exec", ...execOpts, "resume", sessionId, promptArg] : ["exec", ...execOpts, promptArg];
3801
3612
  return {
3802
- file: resolveAgentExecutable("opencode"),
3613
+ file: resolveAgentExecutable("codex"),
3803
3614
  args,
3804
3615
  cwd: thread.worktreePath,
3805
- // `opencode run` treats non-TTY stdin as the message body when no positional
3806
- // message is given (see resolveRunInput in opencode's run.ts).
3807
- stdin: prompt,
3808
- env: {
3809
- OPENCODE_PERMISSION: mode.opencodePermission,
3810
- ...hostEnv
3811
- }
3616
+ stdin: useStdin ? `${prompt}
3617
+ ` : void 0,
3618
+ ...secretProfile ? { cleanupDirs: [secretProfile.file] } : {}
3812
3619
  };
3813
3620
  },
3814
3621
  parseEvent(line) {
@@ -3816,124 +3623,116 @@ var opencodeAdapter = {
3816
3623
  if (!trimmed) return null;
3817
3624
  try {
3818
3625
  const obj = JSON.parse(trimmed);
3819
- if (obj.type === "error") {
3820
- const detail = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
3626
+ const type = typeof obj.type === "string" ? obj.type : "";
3627
+ if (type === "turn.failed" || type === "turn_failed") {
3628
+ const detail = extractJsonErrorMessage(obj) || extractJsonErrorMessage(obj.error ?? {}) || "Codex turn failed";
3821
3629
  return { type: "stderr", data: detail };
3822
3630
  }
3823
- const sid = typeof obj.sessionID === "string" && obj.sessionID || typeof obj.sessionId === "string" && obj.sessionId || typeof obj.session_id === "string" && obj.session_id;
3824
- const childSid = str(obj.childSessionID) ?? str(obj.childSessionId) ?? str(obj.parentID) ?? str(obj.parentId);
3825
- if (sid && !childSid && (!obj.type || obj.type === "step_start" || obj.type === "session")) {
3826
- return { type: "session_id", data: sid };
3827
- }
3828
- if (obj.type === "text") {
3829
- const text = obj.part?.text ?? obj.text;
3830
- if (text) return { type: "stdout", data: text };
3831
- }
3832
- if (obj.type === "reasoning" || obj.type === "thinking") {
3833
- const text = obj.part?.text ?? obj.text;
3834
- if (typeof text === "string" && text) return { type: "thinking", data: text };
3835
- }
3836
- if (obj.type === "tool_use") {
3837
- const part = obj.part;
3838
- const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
3839
- const state = part?.state;
3840
- const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
3841
- const metadata = asRecord4(state?.metadata);
3842
- const id = opencodeToolId(
3843
- name,
3844
- part?.callID ?? part?.id ?? obj.id,
3845
- metadata
3846
- );
3847
- const events = [{ type: "tool_use", id, name, input }];
3848
- const output = state?.output;
3849
- const finished = state?.status === "completed" || state?.status === "error" || state?.status === "failed";
3850
- const running = state?.status === "running" || state?.status === "in_progress" || state?.status === "pending";
3851
- if (output != null || finished) {
3852
- const content = typeof output === "string" ? output : output != null ? JSON.stringify(output) : formatUnknownDetail(state?.error) || void 0;
3853
- events.push({
3854
- type: "tool_result",
3855
- id,
3856
- content,
3857
- isError: state?.status === "error" || state?.status === "failed",
3858
- ...running && !finished ? { partial: true } : {}
3859
- });
3860
- }
3861
- return events.length === 1 ? events[0] : events;
3631
+ if (type === "error") {
3632
+ const detail = extractJsonErrorMessage(obj) || trimmed;
3633
+ if (/^reconnecting\.\.\./i.test(detail)) return null;
3634
+ return { type: "stderr", data: detail };
3862
3635
  }
3863
- if (obj.type === "subtask_delta") {
3864
- const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
3865
- const delta = str(obj.delta);
3866
- if (parentId && delta) {
3867
- return withTaskParent(
3868
- parentId,
3869
- withEventParentId({ type: "thinking", data: delta }, parentId)
3870
- );
3636
+ if (typeof obj.item === "object" && obj.item !== null) {
3637
+ const item = obj.item;
3638
+ const itemType = item.type ?? item.item_type;
3639
+ const mapped = eventsFromCodexItem(type, item);
3640
+ if (mapped) return mapped;
3641
+ if (itemType === "error") {
3642
+ const detail = (typeof item.message === "string" ? item.message.trim() : "") || extractJsonErrorMessage(obj) || "Codex item error";
3643
+ return { type: "stderr", data: detail };
3871
3644
  }
3872
- return null;
3873
- }
3874
- if (obj.type === "subtask_event") {
3875
- const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
3876
- const part = asRecord4(obj.part);
3877
- if (!parentId || !part) return null;
3878
- if (part.type === "text" && str(part.text)) {
3879
- return withTaskParent(
3880
- parentId,
3881
- withEventParentId({ type: "stdout", data: str(part.text) }, parentId)
3882
- );
3645
+ if (itemType === "agent_message" && item.text) {
3646
+ return { type: "stdout", data: item.text };
3883
3647
  }
3884
- if (part.type === "tool" || str(part.tool)) {
3885
- const name = str(part.tool) ?? str(part.name) ?? "tool";
3886
- const id = str(part.callID) ?? str(part.id) ?? `${parentId}-${name}`;
3887
- const state = asRecord4(part.state);
3888
- const input = asRecord4(state?.input) ?? asRecord4(part.input);
3889
- const nested = [
3890
- withEventParentId({ type: "tool_use", id, name, input }, parentId)
3648
+ if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
3649
+ const name = `mcp__${item.server}__${item.tool}`;
3650
+ const input = asRecord4(item.arguments);
3651
+ const events = [
3652
+ { type: "tool_use", id: item.id, name, input }
3891
3653
  ];
3892
- const output = state?.output ?? part.output;
3893
- const finished = state?.status === "completed" || state?.status === "error" || state?.status === "failed";
3894
- const running = state?.status === "running" || state?.status === "in_progress" || state?.status === "pending";
3895
- if (output != null || finished) {
3896
- nested.push(
3897
- withEventParentId(
3898
- {
3899
- type: "tool_result",
3900
- id,
3901
- content: typeof output === "string" ? output : output != null ? JSON.stringify(output) : void 0,
3902
- isError: state?.status === "error" || state?.status === "failed",
3903
- ...running && !finished ? { partial: true } : {}
3904
- },
3905
- parentId
3906
- )
3907
- );
3654
+ const finished = type === "item.completed" || item.status === "completed" || item.status === "failed";
3655
+ if (finished) {
3656
+ const errMsg = item.error && typeof item.error.message === "string" ? item.error.message : void 0;
3657
+ events.push({
3658
+ type: "tool_result",
3659
+ id: item.id,
3660
+ content: unwrapCodexMcpResult(item.result) ?? errMsg,
3661
+ isError: item.status === "failed" || Boolean(errMsg)
3662
+ });
3908
3663
  }
3909
- return withTaskParent(parentId, nested);
3664
+ return events.length === 1 ? events[0] : events;
3665
+ }
3666
+ if (itemType === "command_execution" && item.id) {
3667
+ const input = item.command ? { command: item.command } : void 0;
3668
+ const events = [
3669
+ { type: "tool_use", id: item.id, name: "Bash", input }
3670
+ ];
3671
+ const finished = type === "item.completed" || item.status === "completed" || item.status === "failed" || item.status === "declined";
3672
+ const output = typeof item.aggregated_output === "string" && item.aggregated_output ? item.aggregated_output : void 0;
3673
+ if (finished) {
3674
+ events.push({
3675
+ type: "tool_result",
3676
+ id: item.id,
3677
+ content: output,
3678
+ isError: item.status === "failed" || item.status === "declined"
3679
+ });
3680
+ } else if (output) {
3681
+ events.push({
3682
+ type: "tool_result",
3683
+ id: item.id,
3684
+ content: output,
3685
+ partial: true
3686
+ });
3687
+ }
3688
+ return events.length === 1 ? events[0] : events;
3689
+ }
3690
+ if (itemType === "collab_tool_call" && item.id) {
3691
+ const rawTool = typeof item.tool === "string" ? item.tool : "spawn_agent";
3692
+ const name = /spawn/i.test(rawTool) ? "spawn_agent" : rawTool;
3693
+ const input = {};
3694
+ if (item.prompt) input.prompt = item.prompt;
3695
+ if (Array.isArray(item.receiver_thread_ids)) {
3696
+ input.receiver_thread_ids = item.receiver_thread_ids;
3697
+ }
3698
+ const events = [{ type: "tool_use", id: item.id, name, input }];
3699
+ const finished = type === "item.completed" || item.status === "completed" || item.status === "failed";
3700
+ if (finished) {
3701
+ const nested = [];
3702
+ if (item.agents_states && typeof item.agents_states === "object") {
3703
+ for (const value of Object.values(item.agents_states)) {
3704
+ const msg = value && typeof value === "object" && typeof value.message === "string" ? value.message.trim() : "";
3705
+ if (msg) nested.push(msg);
3706
+ }
3707
+ }
3708
+ for (const text of nested) {
3709
+ events.push({ type: "stdout", data: text, parentId: item.id });
3710
+ }
3711
+ events.push({
3712
+ type: "tool_result",
3713
+ id: item.id,
3714
+ content: nested.join("\n") || void 0,
3715
+ isError: item.status === "failed"
3716
+ });
3717
+ }
3718
+ return events.length === 1 ? events[0] : events;
3719
+ }
3720
+ if (item.status === "failed") {
3721
+ const detail = (typeof item.message === "string" ? item.message.trim() : "") || extractJsonErrorMessage(item) || `Codex ${itemType ?? "item"} failed`;
3722
+ return { type: "stderr", data: detail };
3910
3723
  }
3911
- return null;
3912
3724
  }
3913
- if (obj.type === "tool_result") {
3914
- const part = obj.part;
3915
- const id = part?.tool_use_id ?? part?.id ?? obj.tool_use_id ?? obj.id;
3916
- if (!id) return null;
3917
- const flagged = obj.isError === true || obj.is_error === true;
3918
- const errText = formatUnknownDetail(obj.error);
3919
- return {
3920
- type: "tool_result",
3921
- id,
3922
- content: part?.output ?? part?.content ?? obj.output ?? obj.content ?? (errText || void 0),
3923
- isError: flagged || Boolean(errText)
3924
- };
3725
+ const sid = typeof obj.session_id === "string" && obj.session_id || typeof obj.thread_id === "string" && obj.thread_id || typeof obj.session?.id === "string" && obj.session.id;
3726
+ if (sid && (type === "thread.started" || type === "session" || !type)) {
3727
+ return { type: "session_id", data: sid };
3925
3728
  }
3926
- if (obj.type === "step_finish" || obj.type === "step-finish") {
3927
- const part = obj.part;
3928
- const usage = usageFromOpencode(
3929
- part?.tokens ?? obj.tokens
3930
- );
3931
- if (!usage) return null;
3932
- const cost = part?.cost ?? obj.cost;
3933
- if (cost != null && Number.isFinite(Number(cost))) {
3934
- usage.costUsd = Number(cost);
3935
- }
3936
- return { type: "usage", data: usage, scope: "request" };
3729
+ if (type === "turn.completed" || type === "turn_completed") {
3730
+ const payload = obj;
3731
+ const usage = payload.last_token_usage ? usageFromCodex(payload.last_token_usage, true) : usageFromCodex(payload.usage);
3732
+ return usage ? { type: "usage", data: usage, scope: "turn" } : null;
3733
+ }
3734
+ if (typeof obj.content === "string" && obj.content.trim()) {
3735
+ return { type: "stdout", data: obj.content };
3937
3736
  }
3938
3737
  return null;
3939
3738
  } catch {
@@ -3942,612 +3741,905 @@ var opencodeAdapter = {
3942
3741
  }
3943
3742
  return { type: "stdout", data: line };
3944
3743
  }
3945
- },
3946
- async resolveSessionId(worktreePath, cached) {
3947
- const cachedId = cached?.trim() || null;
3948
- const listed = await run(
3949
- resolveAgentExecutable("opencode"),
3950
- ["session", "list", "--format", "json"],
3951
- { cwd: worktreePath, reject: false, timeoutMs: 8e3 }
3952
- );
3953
- if (listed.exitCode === 0) {
3954
- const raw = listed.stdout.trim();
3955
- if (!raw) return null;
3956
- try {
3957
- const sessions = JSON.parse(raw);
3958
- if (Array.isArray(sessions) && sessions.length === 0) return null;
3959
- if (Array.isArray(sessions) && sessions.length > 0) {
3960
- const norm = (p) => p.replace(/\/+$/, "");
3961
- const wt = norm(worktreePath);
3962
- const forWorktree = sessions.filter(
3963
- (s) => s.directory && norm(s.directory) === wt || s.path && norm(s.path) === wt
3964
- );
3965
- if (cachedId && forWorktree.some((s) => s.id === cachedId)) {
3966
- return cachedId;
3967
- }
3968
- if (cachedId && sessions.some((s) => s.id === cachedId)) {
3969
- return cachedId;
3970
- }
3971
- return null;
3972
- }
3973
- } catch {
3974
- }
3744
+ },
3745
+ async resolveSessionId(_worktreePath, cached) {
3746
+ return cached;
3747
+ },
3748
+ async buildAttach(thread) {
3749
+ const codex = resolveAgentExecutable("codex");
3750
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3751
+ if (sessionId) {
3752
+ return {
3753
+ file: codex,
3754
+ args: ["resume", sessionId],
3755
+ cwd: thread.worktreePath
3756
+ };
3757
+ }
3758
+ return {
3759
+ file: codex,
3760
+ args: ["--cd", thread.worktreePath],
3761
+ cwd: thread.worktreePath
3762
+ };
3763
+ },
3764
+ async listLinearIssues(_repoPath) {
3765
+ return listAssignedLinearIssues();
3766
+ }
3767
+ };
3768
+
3769
+ // src/agents/cursor.ts
3770
+ import { existsSync as existsSync10 } from "fs";
3771
+ import { createRequire as createRequire3 } from "module";
3772
+ import { dirname as dirname5, join as join9 } from "path";
3773
+ import { fileURLToPath as fileURLToPath3 } from "url";
3774
+ var FALLBACK_CURSOR_MODELS = [
3775
+ { id: "default", displayName: "Auto" },
3776
+ { id: "composer-2.5", displayName: "Composer 2.5" },
3777
+ { id: "composer-2", displayName: "Composer 2" }
3778
+ ];
3779
+ var cachedModels = null;
3780
+ var MODEL_CACHE_MS = 5 * 60 * 1e3;
3781
+ function resolveCursorApiKey() {
3782
+ const fromEnv = (process.env.CURSOR_API_KEY || "").trim();
3783
+ if (fromEnv) return fromEnv;
3784
+ return (loadAppSettings().environment.CURSOR_API_KEY || "").trim();
3785
+ }
3786
+ function isCursorApiKeyConfigured() {
3787
+ return Boolean(resolveCursorApiKey());
3788
+ }
3789
+ function isCursorAutoModel(model) {
3790
+ const id = (model ?? "").trim().toLowerCase();
3791
+ return !id || id === "default" || id === "auto";
3792
+ }
3793
+ function resolveCursorModelId(model) {
3794
+ if (isCursorAutoModel(model)) return "default";
3795
+ return model.trim();
3796
+ }
3797
+ async function listCursorModels() {
3798
+ const now = Date.now();
3799
+ if (cachedModels && now - cachedModels.at < MODEL_CACHE_MS) {
3800
+ return cachedModels.models;
3801
+ }
3802
+ const apiKey = resolveCursorApiKey();
3803
+ if (!apiKey) return FALLBACK_CURSOR_MODELS;
3804
+ const sdk = await importCursorSdk();
3805
+ if (!sdk) return FALLBACK_CURSOR_MODELS;
3806
+ try {
3807
+ const listed = await sdk.Cursor.models.list({ apiKey });
3808
+ const models = listed.map((m) => ({
3809
+ id: m.id,
3810
+ displayName: m.displayName || m.id,
3811
+ description: m.description
3812
+ })).filter((m) => Boolean(m.id));
3813
+ if (models.length === 0) return FALLBACK_CURSOR_MODELS;
3814
+ cachedModels = { at: now, models };
3815
+ return models;
3816
+ } catch {
3817
+ return cachedModels?.models ?? FALLBACK_CURSOR_MODELS;
3818
+ }
3819
+ }
3820
+ function entryDir2() {
3821
+ const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
3822
+ if (cjsDir) return cjsDir;
3823
+ try {
3824
+ return dirname5(fileURLToPath3(import.meta.url));
3825
+ } catch {
3826
+ try {
3827
+ const req = createRequire3(process.cwd() + "/");
3828
+ return dirname5(req.resolve("@sideboard-ai/core"));
3829
+ } catch {
3830
+ return process.cwd();
3831
+ }
3832
+ }
3833
+ }
3834
+ function cursorRunnerPath() {
3835
+ const packaged = packagedCursorRunnerPath();
3836
+ if (packaged) return packaged;
3837
+ const root = entryDir2();
3838
+ const candidates = [
3839
+ join9(root, "agents", "cursor-runner.js"),
3840
+ join9(root, "agents", "cursor-runner.cjs"),
3841
+ // If somehow resolved from package root instead of dist/
3842
+ join9(root, "dist", "agents", "cursor-runner.js"),
3843
+ join9(root, "dist", "agents", "cursor-runner.cjs"),
3844
+ // Source tree (dev): packages/core/src/agents/cursor-runner.ts
3845
+ join9(root, "cursor-runner.ts"),
3846
+ join9(root, "src", "agents", "cursor-runner.ts")
3847
+ ];
3848
+ for (const candidate of candidates) {
3849
+ if (existsSync10(candidate)) return candidate;
3850
+ }
3851
+ return candidates[0];
3852
+ }
3853
+ var cursorAdapter = {
3854
+ kind: "cursor",
3855
+ async detect() {
3856
+ if (!isCursorSdkInstalled()) {
3857
+ return {
3858
+ agent: "cursor",
3859
+ installed: false,
3860
+ authenticated: false,
3861
+ linearMcp: false,
3862
+ warnings: [],
3863
+ reason: CURSOR_SDK_INSTALL_HINT
3864
+ };
3865
+ }
3866
+ const apiKey = resolveCursorApiKey();
3867
+ if (!apiKey) {
3868
+ return {
3869
+ agent: "cursor",
3870
+ installed: true,
3871
+ authenticated: false,
3872
+ linearMcp: false,
3873
+ warnings: [],
3874
+ reason: "CURSOR_API_KEY not set \u2014 add it in Settings \u2192 Agents \u2192 Cursor, or Settings \u2192 Environment"
3875
+ };
3975
3876
  }
3976
- return cachedId;
3877
+ return {
3878
+ agent: "cursor",
3879
+ installed: true,
3880
+ authenticated: true,
3881
+ linearMcp: false,
3882
+ warnings: []
3883
+ };
3977
3884
  },
3978
- async buildAttach(thread) {
3979
- const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3980
- const args = ["--dir", thread.worktreePath];
3981
- if (sessionId) args.push("--session", sessionId);
3885
+ async buildTurn(thread, input) {
3886
+ const agentId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
3887
+ const fullPrompt = flattenTurnInput(input);
3888
+ const prompt = flattenTurnInput(dropCachedPrefixOnResume(input, agentId));
3889
+ const apiKey = resolveCursorApiKey() || void 0;
3890
+ const isOrchestrator = isOrchestratorThread(thread);
3891
+ const rpc = agentRpcConnectFromMetadata();
3892
+ const injected = await buildInjectedMcpServers({
3893
+ includeSideboard: true,
3894
+ includeBrightsy: shouldInjectBrightsyMcp(thread, {
3895
+ orchestrator: isOrchestrator
3896
+ }),
3897
+ orchestratorThreadId: isOrchestrator ? thread.id : null,
3898
+ threadId: thread.id,
3899
+ rpcNativeTools: Boolean(rpc)
3900
+ });
3901
+ const mcpServers = toCursorMcpServers(injected);
3902
+ const req = {
3903
+ prompt,
3904
+ ...fullPrompt !== prompt ? { freshPrompt: fullPrompt } : {},
3905
+ cwd: thread.worktreePath,
3906
+ threadId: thread.id,
3907
+ agentId,
3908
+ model: thread.model,
3909
+ effort: thread.effort,
3910
+ fast: thread.fast,
3911
+ planMode: thread.planMode,
3912
+ apiKey,
3913
+ ...isOrchestrator ? { isolateAmbientMcp: true } : {},
3914
+ ...rpc ? { agentRpc: rpc } : {},
3915
+ ...isOrchestrator && rpc ? { rpcWaitForTurn: true } : {},
3916
+ ...Object.keys(mcpServers).length > 0 ? { mcpServers } : {}
3917
+ };
3918
+ const runner = cursorRunnerPath();
3919
+ const isTs = runner.endsWith(".ts");
3920
+ const launch = applyNodeLaunch(
3921
+ await resolveNodeLaunch(runner),
3922
+ isTs ? ["--import", "tsx", runner] : [runner]
3923
+ );
3982
3924
  return {
3983
- file: resolveAgentExecutable("opencode"),
3984
- args,
3925
+ file: launch.file,
3926
+ args: launch.args,
3985
3927
  cwd: thread.worktreePath,
3928
+ stdin: JSON.stringify(req),
3986
3929
  env: {
3987
- OPENCODE_PERMISSION: permissionMode(thread).opencodePermission
3930
+ ...launch.env,
3931
+ ...cursorRipgrepEnv({ startFile: runner })
3932
+ // API key stays on the stdin request. Do not copy it into the child env,
3933
+ // where `ps` and crash dumps can see it. The runner reads `req.apiKey`.
3988
3934
  }
3989
3935
  };
3990
3936
  },
3991
- async listLinearIssues(_repoPath) {
3992
- const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-CGUCPWTV.js");
3993
- return listAssignedLinearIssues2();
3937
+ parseEvent(line) {
3938
+ return parseCursorRunnerLine(line);
3939
+ },
3940
+ async resolveSessionId(_worktreePath, cached) {
3941
+ return cached;
3942
+ },
3943
+ async buildAttach(thread) {
3944
+ const which = await run("which", ["cursor"], { reject: false });
3945
+ if (which.exitCode === 0) {
3946
+ return { file: "cursor", args: [thread.worktreePath], cwd: thread.worktreePath };
3947
+ }
3948
+ throw new Error(
3949
+ "Cursor agents have no interactive CLI attach. Install the Cursor shell command (`cursor`) to open the worktree, or continue the thread in Sideboard."
3950
+ );
3994
3951
  }
3995
3952
  };
3996
3953
 
3997
- // src/agents/list-models.ts
3998
- var CLAUDE_MODEL_CATALOG = [
3999
- { id: "fable", displayName: "Fable" },
4000
- { id: "opus", displayName: "Opus" },
4001
- { id: "sonnet", displayName: "Sonnet" },
4002
- { id: "haiku", displayName: "Haiku" }
4003
- ];
4004
- async function listBrightsyModels() {
4005
- try {
4006
- const targets = await listBrightsyChatTargets();
4007
- const accountId = targets.activeAccountId;
4008
- const models = (targets.models ?? []).map((m) => ({
4009
- id: encodeBrightsyTarget("model", m.id, accountId),
4010
- displayName: m.name || m.id,
4011
- description: m.description ?? void 0
4012
- }));
4013
- const agents = (targets.agents ?? []).map((a) => ({
4014
- id: encodeBrightsyTarget("agent", a.id, accountId),
4015
- displayName: a.name || a.id,
4016
- description: a.description ?? "Brightsy agent target"
4017
- }));
4018
- return [...models, ...agents].slice(0, 80);
4019
- } catch {
4020
- return [];
4021
- }
3954
+ // src/agents/opencode.ts
3955
+ import { existsSync as existsSync12 } from "fs";
3956
+
3957
+ // src/agent-rpc/opencode-host.ts
3958
+ import { pathToFileURL } from "url";
3959
+
3960
+ // src/agent-rpc/opencode-hook.ts
3961
+ import { existsSync as existsSync11, mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync4 } from "fs";
3962
+ import { join as join10 } from "path";
3963
+ var OPENCODE_PLUGIN_SOURCE = `import { tool } from "@opencode-ai/plugin"
3964
+
3965
+ const RPC_URL = process.env[${JSON.stringify(AGENT_RPC_URL_ENV)}] || ""
3966
+ const TOKEN = process.env[${JSON.stringify(AGENT_RPC_TOKEN_ENV)}] || ""
3967
+ const CWD = process.env[${JSON.stringify(AGENT_RPC_CWD_ENV)}] || ""
3968
+
3969
+ function jsonResult(value) {
3970
+ return JSON.stringify(value)
4022
3971
  }
4023
- async function listModelsForAgent(agent) {
4024
- const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy"];
4025
- const out = [];
4026
- for (const kind of kinds) {
4027
- if (kind === "claude") {
4028
- out.push({
4029
- agent: kind,
4030
- auto: true,
4031
- models: CLAUDE_MODEL_CATALOG,
4032
- note: "Default Auto \u2014 only pass a model id when you have a reason."
4033
- });
4034
- continue;
4035
- }
4036
- if (kind === "codex") {
4037
- out.push({
4038
- agent: kind,
4039
- auto: true,
4040
- models: await listCodexModels(),
4041
- note: "Default Auto \u2014 only pass a model slug when you have a reason."
4042
- });
4043
- continue;
4044
- }
4045
- if (kind === "opencode") {
4046
- out.push({
4047
- agent: kind,
4048
- auto: true,
4049
- models: await listOpencodeModels(),
4050
- note: "Default Auto \u2014 only pass a provider/model id when you have a reason."
4051
- });
4052
- continue;
4053
- }
4054
- if (kind === "cursor") {
4055
- out.push({
4056
- agent: kind,
4057
- auto: true,
4058
- models: await listCursorModels(),
4059
- note: 'Default Auto \u2014 only pass a model id when you have a reason (or use "default").'
4060
- });
4061
- continue;
4062
- }
4063
- if (kind === "brightsy") {
4064
- const models = await listBrightsyModels();
4065
- out.push({
4066
- agent: kind,
4067
- auto: true,
4068
- models,
4069
- note: models.length ? "Default Auto / Default agent \u2014 only pass a model/agent id when you have a reason." : "Brightsy not logged in or no targets \u2014 leave model unset for Default."
4070
- });
4071
- }
3972
+
3973
+ function jsonError(err) {
3974
+ return jsonResult({ ok: false, error: err instanceof Error ? err.message : String(err) })
3975
+ }
3976
+
3977
+ function socketUrl() {
3978
+ const u = new URL(RPC_URL)
3979
+ u.searchParams.set(${JSON.stringify(AGENT_RPC_TOKEN_QUERY)}, TOKEN)
3980
+ return u.toString()
3981
+ }
3982
+
3983
+ function call(method, params) {
3984
+ if (!RPC_URL || !TOKEN) {
3985
+ return Promise.resolve(jsonError(new Error("Agent RPC runtime is not running")))
4072
3986
  }
4073
- return out;
3987
+ const timeoutMs = method === "job.wait" ? 130000 : 30000
3988
+ return new Promise((resolve) => {
3989
+ let settled = false
3990
+ let ws
3991
+ let timer
3992
+ const done = (value) => {
3993
+ if (settled) return
3994
+ settled = true
3995
+ clearTimeout(timer)
3996
+ try { ws.close() } catch {}
3997
+ resolve(value)
3998
+ }
3999
+ timer = setTimeout(() => done(jsonError(new Error("Agent RPC timed out"))), timeoutMs)
4000
+ ws = new WebSocket(socketUrl())
4001
+ const id = Date.now()
4002
+ ws.addEventListener("open", () => {
4003
+ ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params, authToken: TOKEN }))
4004
+ })
4005
+ ws.addEventListener("message", (ev) => {
4006
+ let msg
4007
+ try { msg = JSON.parse(String(ev.data)) } catch { return }
4008
+ if (msg && msg.id === id) {
4009
+ if (msg.error) done(jsonError(new Error(msg.error.message || "Agent RPC error")))
4010
+ else done(jsonResult(msg.result))
4011
+ }
4012
+ })
4013
+ ws.addEventListener("error", () => done(jsonError(new Error("Agent RPC socket error"))))
4014
+ ws.addEventListener("close", () => {
4015
+ if (!settled) done(jsonError(new Error("Agent RPC socket closed")))
4016
+ })
4017
+ })
4018
+ }
4019
+
4020
+ function str(description) {
4021
+ return tool.schema.string().describe(description)
4074
4022
  }
4075
4023
 
4076
- // src/agents/session-quota.ts
4077
- function isSessionQuotaLimit(text) {
4078
- const lower = text.trim().toLowerCase();
4079
- if (!lower) return false;
4080
- if (/credit balance is too low|out of credits|insufficient.?quota|billing/.test(lower)) {
4081
- return false;
4082
- }
4083
- if (/prompt is too long|context.*(too long|exceed)|conversation too long/.test(lower)) {
4084
- return false;
4024
+ function opt(description) {
4025
+ return tool.schema.string().optional().describe(description)
4026
+ }
4027
+
4028
+ export const SideboardRpc = async (ctx) => {
4029
+ const cwd = CWD || ctx.worktree || ctx.directory || ""
4030
+ const job = (method, args) => call(method, { ...args, cwd })
4031
+ return {
4032
+ tool: {
4033
+ present_artifact: tool({
4034
+ description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.present_artifact)},
4035
+ args: {
4036
+ title: str("Short title shown in the artifact pane header"),
4037
+ type: tool.schema.enum(["html", "svg", "markdown", "react", "log"]),
4038
+ content: str("html/svg/markdown/react: full document. log: only the new lines."),
4039
+ artifact_id: opt("Stable id. Required for type=log."),
4040
+ status: tool.schema.enum(["running", "ok", "failed", "idle"]).optional(),
4041
+ phase: opt("Progress phase"),
4042
+ mode: tool.schema.enum(["append", "replace"]).optional(),
4043
+ },
4044
+ async execute(args) {
4045
+ return call("ui.presentArtifact", args)
4046
+ },
4047
+ }),
4048
+ wait_for_job: tool({
4049
+ description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.wait_for_job)},
4050
+ args: {
4051
+ id: str("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
4052
+ },
4053
+ async execute(args) {
4054
+ return job("job.wait", args)
4055
+ },
4056
+ }),
4057
+ stop_job: tool({
4058
+ description: ${JSON.stringify(PILOT_TOOL_DESCRIPTIONS.stop_job)},
4059
+ args: {
4060
+ id: str("Detached job id"),
4061
+ reason: opt("Why the job is being stopped"),
4062
+ },
4063
+ async execute(args) {
4064
+ return job("job.stop", args)
4065
+ },
4066
+ }),
4067
+ },
4085
4068
  }
4086
- return /you've hit your/.test(lower) || /hit your (session|weekly|opus) limit/.test(lower) || /usage limit/.test(lower) || /rate.?limit|too many requests|\b429\b/.test(lower) && /reset/i.test(text);
4087
4069
  }
4088
- function parseSessionQuotaResetAt(text, now = /* @__PURE__ */ new Date()) {
4089
- const absolute = text.match(
4090
- /resets\s+(?:at\s+)?(\d{1,2}):(\d{2})\s*(am|pm)(?:\s*\(([^)]+)\))?/i
4091
- );
4092
- if (absolute) {
4093
- const hour12 = Number(absolute[1]);
4094
- const minute = Number(absolute[2]);
4095
- const ampm = absolute[3].toLowerCase();
4096
- const timeZone = absolute[4]?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone;
4097
- let hour = hour12 % 12;
4098
- if (ampm === "pm") hour += 12;
4099
- const at = zonedWallTimeToUtc(now, hour, minute, timeZone);
4100
- if (!at) return null;
4101
- if (at.getTime() <= now.getTime() + 3e4) {
4102
- const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1e3);
4103
- return zonedWallTimeToUtc(tomorrow, hour, minute, timeZone);
4070
+ `;
4071
+ function writeOpencodeRpcPlugin() {
4072
+ const pluginDir = join10(appDataDir(), "agent-rpc", "opencode");
4073
+ mkdirSync3(pluginDir, { recursive: true });
4074
+ const pluginFile = join10(pluginDir, "sideboard-rpc.js");
4075
+ if (existsSync11(pluginFile)) {
4076
+ try {
4077
+ if (readFileSync5(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
4078
+ } catch {
4104
4079
  }
4105
- return at;
4106
- }
4107
- const relative2 = text.match(
4108
- /resets\s+in\s+(\d+)\s*(minutes?|hours?|days?)/i
4109
- );
4110
- if (relative2) {
4111
- const n = Number(relative2[1]);
4112
- const unit = relative2[2].toLowerCase();
4113
- const ms = unit.startsWith("day") ? n * 24 * 60 * 60 * 1e3 : unit.startsWith("hour") ? n * 60 * 60 * 1e3 : n * 60 * 1e3;
4114
- return new Date(now.getTime() + ms);
4115
4080
  }
4116
- return null;
4081
+ const tmp = `${pluginFile}.${process.pid}.tmp`;
4082
+ writeFileSync4(tmp, OPENCODE_PLUGIN_SOURCE);
4083
+ renameSync(tmp, pluginFile);
4084
+ return pluginFile;
4117
4085
  }
4118
- function zonedWallTimeToUtc(day, hour, minute, timeZone) {
4119
- try {
4120
- const cal = new Intl.DateTimeFormat("en-US", {
4121
- timeZone,
4122
- year: "numeric",
4123
- month: "2-digit",
4124
- day: "2-digit"
4125
- });
4126
- const parts = Object.fromEntries(
4127
- cal.formatToParts(day).filter((p) => p.type !== "literal").map((p) => [p.type, p.value])
4128
- );
4129
- const year = Number(parts.year);
4130
- const month = Number(parts.month);
4131
- const date = Number(parts.day);
4132
- if (![year, month, date].every((n) => Number.isFinite(n))) return null;
4133
- const utcGuess = Date.UTC(year, month - 1, date, hour, minute, 0);
4134
- const dtf = new Intl.DateTimeFormat("en-US", {
4135
- timeZone,
4136
- year: "numeric",
4137
- month: "2-digit",
4138
- day: "2-digit",
4139
- hour: "2-digit",
4140
- minute: "2-digit",
4141
- second: "2-digit",
4142
- hourCycle: "h23"
4143
- });
4144
- const asParts = Object.fromEntries(
4145
- dtf.formatToParts(new Date(utcGuess)).filter((p) => p.type !== "literal").map((p) => [p.type, p.value])
4146
- );
4147
- const asUtc = Date.UTC(
4148
- Number(asParts.year),
4149
- Number(asParts.month) - 1,
4150
- Number(asParts.day),
4151
- Number(asParts.hour),
4152
- Number(asParts.minute),
4153
- Number(asParts.second || "0")
4154
- );
4155
- const offset = asUtc - utcGuess;
4156
- return new Date(utcGuess - offset);
4157
- } catch {
4158
- return null;
4086
+
4087
+ // src/agent-rpc/opencode-host.ts
4088
+ async function buildOpencodeHostEnv(thread) {
4089
+ const isOrchestrator = isOrchestratorThread(thread);
4090
+ const rpc = worktreeAgentRpc(isOrchestrator);
4091
+ const injected = await buildInjectedMcpServers({
4092
+ includeSideboard: true,
4093
+ includeBrightsy: shouldInjectBrightsyMcp(thread, {
4094
+ orchestrator: isOrchestrator
4095
+ }),
4096
+ orchestratorThreadId: isOrchestrator ? thread.id : null,
4097
+ threadId: thread.id,
4098
+ rpcNativeTools: Boolean(rpc)
4099
+ });
4100
+ const disableNames = isOrchestrator ? userMcpNamesToDisable({
4101
+ injectedNames: injected.map((s) => s.name),
4102
+ names: listUserOpencodeMcpNames()
4103
+ }) : [];
4104
+ const config = injected.length > 0 || disableNames.length > 0 ? JSON.parse(toOpencodeMcpConfigContent(injected, { disableNames })) : {};
4105
+ const env = {};
4106
+ if (rpc) {
4107
+ const pluginFile = writeOpencodeRpcPlugin();
4108
+ Object.assign(env, agentRpcChildEnv(rpc, thread.worktreePath));
4109
+ config.plugin = [pathToFileURL(pluginFile).href];
4159
4110
  }
4160
- }
4161
- var FALLBACK_ORDER = [
4162
- "cursor",
4163
- "codex",
4164
- "opencode",
4165
- "claude"
4166
- ];
4167
- function resolveQuotaFallbackAgent(current, preferred) {
4168
- const ordered = [
4169
- ...preferred && preferred !== "brightsy" ? [preferred] : [],
4170
- ...FALLBACK_ORDER.filter((a) => a !== preferred)
4171
- ];
4172
- return ordered.find((a) => a !== current) ?? (current === "cursor" ? "codex" : "cursor");
4111
+ if (Object.keys(config).length > 0) {
4112
+ env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
4113
+ }
4114
+ return env;
4173
4115
  }
4174
4116
 
4175
- // src/agents/claude-usage.ts
4176
- var WINDOW_META = {
4177
- five_hour: {
4178
- label: "5-hour session",
4179
- shortLabel: "5h",
4180
- detail: "Rolling 5-hour limit across all models"
4181
- },
4182
- seven_day: {
4183
- label: "Weekly",
4184
- shortLabel: "wk",
4185
- detail: "7-day cap across all models"
4186
- },
4187
- seven_day_opus: {
4188
- label: "Opus",
4189
- shortLabel: "Opus",
4190
- detail: "Weekly Opus-only cap"
4117
+ // src/agents/opencode.ts
4118
+ var FALLBACK_OPENCODE_MODELS = [
4119
+ { id: "opencode/big-pickle", displayName: "opencode \xB7 big-pickle" },
4120
+ {
4121
+ id: "openrouter/~anthropic/claude-sonnet-latest",
4122
+ displayName: "openrouter \xB7 claude-sonnet-latest"
4191
4123
  },
4192
- seven_day_sonnet: {
4193
- label: "Sonnet",
4194
- shortLabel: "Sonnet",
4195
- detail: "Weekly Sonnet-only cap"
4124
+ {
4125
+ id: "openrouter/~openai/gpt-latest",
4126
+ displayName: "openrouter \xB7 gpt-latest"
4196
4127
  }
4197
- };
4198
- var WINDOW_ORDER = [
4199
- "five_hour",
4200
- "seven_day",
4201
- "seven_day_opus",
4202
- "seven_day_sonnet"
4203
4128
  ];
4204
- function parseClaudeResetsAt(value) {
4205
- if (typeof value === "number" && Number.isFinite(value)) {
4206
- const ms = value > 1e12 ? value : value * 1e3;
4207
- const d = new Date(ms);
4208
- return Number.isNaN(d.getTime()) ? null : d.toISOString();
4209
- }
4210
- if (typeof value === "string") {
4211
- const trimmed = value.trim();
4212
- if (!trimmed) return null;
4213
- if (/^\d+(\.\d+)?$/.test(trimmed)) {
4214
- return parseClaudeResetsAt(Number(trimmed));
4215
- }
4216
- const d = new Date(trimmed);
4217
- return Number.isNaN(d.getTime()) ? null : d.toISOString();
4129
+ var cachedOpencodeModels = null;
4130
+ var OPENCODE_MODEL_CACHE_MS = 5 * 60 * 1e3;
4131
+ function asRecord5(value) {
4132
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4133
+ return value;
4218
4134
  }
4219
- return null;
4135
+ return void 0;
4220
4136
  }
4221
- function parseClaudeUtilization(value) {
4222
- if (typeof value !== "number" || !Number.isFinite(value)) return null;
4223
- return Math.max(0, Math.min(100, value));
4137
+ function str(v) {
4138
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
4224
4139
  }
4225
- function windowFromRaw(id, raw) {
4226
- if (!raw || typeof raw !== "object") return null;
4227
- const row = raw;
4228
- const used = parseClaudeUtilization(row.utilization ?? row.used_percentage);
4229
- if (used == null) return null;
4230
- const meta = WINDOW_META[id];
4231
- return {
4232
- id,
4233
- label: meta.label,
4234
- shortLabel: meta.shortLabel,
4235
- detail: meta.detail,
4236
- usedPercent: used,
4237
- remainingPercent: Math.max(0, Math.min(100, 100 - used)),
4238
- resetsAt: parseClaudeResetsAt(row.resets_at)
4239
- };
4140
+ function opencodeToolId(name, callId, metadata) {
4141
+ const sessionId = str(metadata?.sessionId) ?? str(metadata?.sessionID);
4142
+ if (name === "task" && sessionId) return sessionId;
4143
+ return callId || `tool-${Date.now()}`;
4144
+ }
4145
+ function withTaskParent(parentId, nested) {
4146
+ const events = Array.isArray(nested) ? nested : [nested];
4147
+ return [{ type: "tool_use", id: parentId, name: "task" }, ...events];
4240
4148
  }
4241
- function extraUsageFromRaw(raw) {
4242
- if (!raw || typeof raw !== "object") return void 0;
4243
- const row = raw;
4244
- const enabled = row.is_enabled === true || row.enabled === true;
4245
- if (!enabled && row.is_enabled !== false && row.enabled !== false) return void 0;
4246
- const usedCredits = numberOrUndef(row.used_credits ?? row.used);
4247
- const monthlyLimit = numberOrUndef(row.monthly_limit);
4248
- const usedPercent = parseClaudeUtilization(row.utilization) ?? void 0;
4249
- return {
4250
- enabled,
4251
- ...usedCredits != null ? { usedCredits } : {},
4252
- ...monthlyLimit != null ? { monthlyLimit } : {},
4253
- ...usedPercent != null ? { usedPercent } : {}
4254
- };
4149
+ function displayNameFromOpencodeId(id) {
4150
+ const slash = id.indexOf("/");
4151
+ if (slash <= 0) return id;
4152
+ const provider = id.slice(0, slash);
4153
+ const name = id.slice(slash + 1);
4154
+ return `${provider} \xB7 ${name}`;
4255
4155
  }
4256
- function numberOrUndef(value) {
4257
- if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
4258
- return value;
4156
+ function sortOpencodeModelIds(ids) {
4157
+ return [...ids].sort((a, b) => {
4158
+ const aLatest = /latest|~/.test(a) ? 0 : 1;
4159
+ const bLatest = /latest|~/.test(b) ? 0 : 1;
4160
+ if (aLatest !== bLatest) return aLatest - bLatest;
4161
+ const aOc = a.startsWith("opencode/") ? 0 : 1;
4162
+ const bOc = b.startsWith("opencode/") ? 0 : 1;
4163
+ if (aOc !== bOc) return aOc - bOc;
4164
+ return a.localeCompare(b);
4165
+ });
4259
4166
  }
4260
- function parseClaudeUsagePayload(raw, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
4261
- if (!raw || typeof raw !== "object") return null;
4262
- const obj = raw;
4263
- const source = obj.rate_limits && typeof obj.rate_limits === "object" ? obj.rate_limits : obj;
4264
- const windows = [];
4265
- for (const id of WINDOW_ORDER) {
4266
- const parsed = windowFromRaw(id, source[id]);
4267
- if (parsed) windows.push(parsed);
4167
+ async function listOpencodeModels() {
4168
+ const now = Date.now();
4169
+ if (cachedOpencodeModels && now - cachedOpencodeModels.at < OPENCODE_MODEL_CACHE_MS) {
4170
+ return cachedOpencodeModels.models;
4268
4171
  }
4269
- if (windows.length === 0) return null;
4270
- const extra = extraUsageFromRaw(obj.extra_usage ?? source.extra_usage);
4172
+ const opencode = resolveAgentExecutable("opencode");
4173
+ if (opencode === "opencode") {
4174
+ const which = await run("which", ["opencode"], { reject: false });
4175
+ if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
4176
+ } else if (!existsSync12(opencode)) {
4177
+ return FALLBACK_OPENCODE_MODELS;
4178
+ }
4179
+ const listed = await run(opencode, ["models"], { reject: false });
4180
+ if (listed.exitCode !== 0 || !listed.stdout.trim()) {
4181
+ return cachedOpencodeModels?.models ?? FALLBACK_OPENCODE_MODELS;
4182
+ }
4183
+ const ids = listed.stdout.split("\n").map((l) => l.trim()).filter((l) => /^[\w.~@+-]+\/[\w.~@+/-]+$/.test(l));
4184
+ const unique = [...new Set(ids)];
4185
+ if (unique.length === 0) return FALLBACK_OPENCODE_MODELS;
4186
+ const OPENCODE_PICKER_LIMIT = 60;
4187
+ const models = sortOpencodeModelIds(unique).slice(0, OPENCODE_PICKER_LIMIT).map((id) => ({
4188
+ id,
4189
+ displayName: displayNameFromOpencodeId(id)
4190
+ }));
4191
+ cachedOpencodeModels = { at: now, models };
4192
+ return models;
4193
+ }
4194
+ function usageFromOpencode(tokens) {
4195
+ if (!tokens) return null;
4196
+ const inputTokens = Number(tokens.input ?? 0);
4197
+ const outputTokens = Number(tokens.output ?? 0) + Number(tokens.reasoning ?? 0);
4198
+ if (!inputTokens && !outputTokens) return null;
4271
4199
  return {
4272
- windows,
4273
- ...extra ? { extraUsage: extra } : {},
4274
- fetchedAt
4200
+ inputTokens,
4201
+ outputTokens,
4202
+ cacheReadTokens: tokens.cache?.read ? Number(tokens.cache.read) : void 0,
4203
+ cacheWriteTokens: tokens.cache?.write ? Number(tokens.cache.write) : void 0
4275
4204
  };
4276
4205
  }
4277
- function hottestClaudeWindow(usage) {
4278
- if (usage.windows.length === 0) return null;
4279
- return usage.windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);
4280
- }
4281
- function formatClaudeUsageReset(resetsAt, now = /* @__PURE__ */ new Date()) {
4282
- if (!resetsAt) return "";
4283
- const at = new Date(resetsAt);
4284
- if (Number.isNaN(at.getTime())) return "";
4285
- const ms = at.getTime() - now.getTime();
4286
- if (ms <= 0) return "resets soon";
4287
- const minutes = Math.round(ms / 6e4);
4288
- if (minutes < 60) return `resets in ${Math.max(1, minutes)}m`;
4289
- const hours = Math.round(minutes / 60);
4290
- if (hours < 36) return `resets in ${hours}h`;
4291
- try {
4292
- return `resets ${at.toLocaleString(void 0, {
4293
- weekday: "short",
4294
- hour: "numeric",
4295
- minute: "2-digit"
4296
- })}`;
4297
- } catch {
4298
- return `resets ${at.toISOString()}`;
4206
+ var opencodeAdapter = {
4207
+ kind: "opencode",
4208
+ async detect() {
4209
+ const opencode = resolveAgentExecutable("opencode");
4210
+ if (opencode !== "opencode") {
4211
+ if (!existsSync12(opencode)) {
4212
+ return {
4213
+ agent: "opencode",
4214
+ installed: false,
4215
+ authenticated: false,
4216
+ linearMcp: false,
4217
+ warnings: [],
4218
+ reason: `OpenCode executable not found: ${opencode}`
4219
+ };
4220
+ }
4221
+ } else {
4222
+ const which = await run("which", ["opencode"], { reject: false });
4223
+ if (which.exitCode !== 0) {
4224
+ return {
4225
+ agent: "opencode",
4226
+ installed: false,
4227
+ authenticated: false,
4228
+ linearMcp: false,
4229
+ warnings: [],
4230
+ reason: "opencode CLI not found on PATH"
4231
+ };
4232
+ }
4233
+ }
4234
+ const auth = await run(opencode, ["auth", "list"], { reject: false });
4235
+ const authenticated = auth.exitCode === 0 && auth.stdout.trim().length > 0;
4236
+ const mcp = await run(opencode, ["mcp", "list"], { reject: false });
4237
+ const linearMcp = /linear/i.test(mcp.stdout + mcp.stderr);
4238
+ return {
4239
+ agent: "opencode",
4240
+ installed: true,
4241
+ authenticated,
4242
+ linearMcp,
4243
+ warnings: [],
4244
+ reason: authenticated ? void 0 : "opencode auth list empty \u2014 run `opencode auth login`"
4245
+ };
4246
+ },
4247
+ async buildTurn(thread, input) {
4248
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
4249
+ const prompt = flattenTurnInput(dropCachedPrefixOnResume(input, sessionId));
4250
+ const mode = permissionMode(thread);
4251
+ const model = thread.model?.trim();
4252
+ const args = [
4253
+ "run",
4254
+ "--dir",
4255
+ thread.worktreePath,
4256
+ "--format",
4257
+ "json"
4258
+ ];
4259
+ if (sessionId) {
4260
+ args.push("--session", sessionId);
4261
+ }
4262
+ if (model) {
4263
+ args.push("--model", model);
4264
+ }
4265
+ args.push("--thinking");
4266
+ const variant = thread.effort?.trim() ?? "";
4267
+ if (variant && /^(minimal|low|medium|high|max|xhigh)$/i.test(variant)) {
4268
+ args.push("--variant", variant);
4269
+ }
4270
+ const hostEnv = await buildOpencodeHostEnv(thread);
4271
+ return {
4272
+ file: resolveAgentExecutable("opencode"),
4273
+ args,
4274
+ cwd: thread.worktreePath,
4275
+ // `opencode run` treats non-TTY stdin as the message body when no positional
4276
+ // message is given (see resolveRunInput in opencode's run.ts).
4277
+ stdin: prompt,
4278
+ env: {
4279
+ OPENCODE_PERMISSION: mode.opencodePermission,
4280
+ ...hostEnv
4281
+ }
4282
+ };
4283
+ },
4284
+ parseEvent(line) {
4285
+ const trimmed = line.trim();
4286
+ if (!trimmed) return null;
4287
+ try {
4288
+ const obj = JSON.parse(trimmed);
4289
+ if (obj.type === "error") {
4290
+ const detail = extractJsonErrorMessage(obj) || formatUnknownDetail(obj.error) || formatUnknownDetail(obj.message) || trimmed;
4291
+ return { type: "stderr", data: detail };
4292
+ }
4293
+ const sid = typeof obj.sessionID === "string" && obj.sessionID || typeof obj.sessionId === "string" && obj.sessionId || typeof obj.session_id === "string" && obj.session_id;
4294
+ const childSid = str(obj.childSessionID) ?? str(obj.childSessionId) ?? str(obj.parentID) ?? str(obj.parentId);
4295
+ if (sid && !childSid && (!obj.type || obj.type === "step_start" || obj.type === "session")) {
4296
+ return { type: "session_id", data: sid };
4297
+ }
4298
+ if (obj.type === "text") {
4299
+ const text = obj.part?.text ?? obj.text;
4300
+ if (text) return { type: "stdout", data: text };
4301
+ }
4302
+ if (obj.type === "reasoning" || obj.type === "thinking") {
4303
+ const text = obj.part?.text ?? obj.text;
4304
+ if (typeof text === "string" && text) return { type: "thinking", data: text };
4305
+ }
4306
+ if (obj.type === "tool_use") {
4307
+ const part = obj.part;
4308
+ const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
4309
+ const state = part?.state;
4310
+ const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
4311
+ const metadata = asRecord5(state?.metadata);
4312
+ const id = opencodeToolId(
4313
+ name,
4314
+ part?.callID ?? part?.id ?? obj.id,
4315
+ metadata
4316
+ );
4317
+ const events = [{ type: "tool_use", id, name, input }];
4318
+ const output = state?.output;
4319
+ const finished = state?.status === "completed" || state?.status === "error" || state?.status === "failed";
4320
+ const running = state?.status === "running" || state?.status === "in_progress" || state?.status === "pending";
4321
+ if (output != null || finished) {
4322
+ const content = typeof output === "string" ? output : output != null ? JSON.stringify(output) : formatUnknownDetail(state?.error) || void 0;
4323
+ events.push({
4324
+ type: "tool_result",
4325
+ id,
4326
+ content,
4327
+ isError: state?.status === "error" || state?.status === "failed",
4328
+ ...running && !finished ? { partial: true } : {}
4329
+ });
4330
+ }
4331
+ return events.length === 1 ? events[0] : events;
4332
+ }
4333
+ if (obj.type === "subtask_delta") {
4334
+ const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
4335
+ const delta = str(obj.delta);
4336
+ if (parentId && delta) {
4337
+ return withTaskParent(
4338
+ parentId,
4339
+ withEventParentId({ type: "thinking", data: delta }, parentId)
4340
+ );
4341
+ }
4342
+ return null;
4343
+ }
4344
+ if (obj.type === "subtask_event") {
4345
+ const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
4346
+ const part = asRecord5(obj.part);
4347
+ if (!parentId || !part) return null;
4348
+ if (part.type === "text" && str(part.text)) {
4349
+ return withTaskParent(
4350
+ parentId,
4351
+ withEventParentId({ type: "stdout", data: str(part.text) }, parentId)
4352
+ );
4353
+ }
4354
+ if (part.type === "tool" || str(part.tool)) {
4355
+ const name = str(part.tool) ?? str(part.name) ?? "tool";
4356
+ const id = str(part.callID) ?? str(part.id) ?? `${parentId}-${name}`;
4357
+ const state = asRecord5(part.state);
4358
+ const input = asRecord5(state?.input) ?? asRecord5(part.input);
4359
+ const nested = [
4360
+ withEventParentId({ type: "tool_use", id, name, input }, parentId)
4361
+ ];
4362
+ const output = state?.output ?? part.output;
4363
+ const finished = state?.status === "completed" || state?.status === "error" || state?.status === "failed";
4364
+ const running = state?.status === "running" || state?.status === "in_progress" || state?.status === "pending";
4365
+ if (output != null || finished) {
4366
+ nested.push(
4367
+ withEventParentId(
4368
+ {
4369
+ type: "tool_result",
4370
+ id,
4371
+ content: typeof output === "string" ? output : output != null ? JSON.stringify(output) : void 0,
4372
+ isError: state?.status === "error" || state?.status === "failed",
4373
+ ...running && !finished ? { partial: true } : {}
4374
+ },
4375
+ parentId
4376
+ )
4377
+ );
4378
+ }
4379
+ return withTaskParent(parentId, nested);
4380
+ }
4381
+ return null;
4382
+ }
4383
+ if (obj.type === "tool_result") {
4384
+ const part = obj.part;
4385
+ const id = part?.tool_use_id ?? part?.id ?? obj.tool_use_id ?? obj.id;
4386
+ if (!id) return null;
4387
+ const flagged = obj.isError === true || obj.is_error === true;
4388
+ const errText = formatUnknownDetail(obj.error);
4389
+ return {
4390
+ type: "tool_result",
4391
+ id,
4392
+ content: part?.output ?? part?.content ?? obj.output ?? obj.content ?? (errText || void 0),
4393
+ isError: flagged || Boolean(errText)
4394
+ };
4395
+ }
4396
+ if (obj.type === "step_finish" || obj.type === "step-finish") {
4397
+ const part = obj.part;
4398
+ const usage = usageFromOpencode(
4399
+ part?.tokens ?? obj.tokens
4400
+ );
4401
+ if (!usage) return null;
4402
+ const cost = part?.cost ?? obj.cost;
4403
+ if (cost != null && Number.isFinite(Number(cost))) {
4404
+ usage.costUsd = Number(cost);
4405
+ }
4406
+ return { type: "usage", data: usage, scope: "request" };
4407
+ }
4408
+ return null;
4409
+ } catch {
4410
+ if (/error|failed|unauthorized|quota|limit/i.test(trimmed)) {
4411
+ return { type: "stderr", data: trimmed };
4412
+ }
4413
+ return { type: "stdout", data: line };
4414
+ }
4415
+ },
4416
+ async resolveSessionId(worktreePath, cached) {
4417
+ const cachedId = cached?.trim() || null;
4418
+ const listed = await run(
4419
+ resolveAgentExecutable("opencode"),
4420
+ ["session", "list", "--format", "json"],
4421
+ { cwd: worktreePath, reject: false, timeoutMs: 8e3 }
4422
+ );
4423
+ if (listed.exitCode === 0) {
4424
+ const raw = listed.stdout.trim();
4425
+ if (!raw) return null;
4426
+ try {
4427
+ const sessions = JSON.parse(raw);
4428
+ if (Array.isArray(sessions) && sessions.length === 0) return null;
4429
+ if (Array.isArray(sessions) && sessions.length > 0) {
4430
+ const norm = (p) => p.replace(/\/+$/, "");
4431
+ const wt = norm(worktreePath);
4432
+ const forWorktree = sessions.filter(
4433
+ (s) => s.directory && norm(s.directory) === wt || s.path && norm(s.path) === wt
4434
+ );
4435
+ if (cachedId && forWorktree.some((s) => s.id === cachedId)) {
4436
+ return cachedId;
4437
+ }
4438
+ if (cachedId && sessions.some((s) => s.id === cachedId)) {
4439
+ return cachedId;
4440
+ }
4441
+ return null;
4442
+ }
4443
+ } catch {
4444
+ }
4445
+ }
4446
+ return cachedId;
4447
+ },
4448
+ async buildAttach(thread) {
4449
+ const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
4450
+ const args = ["--dir", thread.worktreePath];
4451
+ if (sessionId) args.push("--session", sessionId);
4452
+ return {
4453
+ file: resolveAgentExecutable("opencode"),
4454
+ args,
4455
+ cwd: thread.worktreePath,
4456
+ env: {
4457
+ OPENCODE_PERMISSION: permissionMode(thread).opencodePermission
4458
+ }
4459
+ };
4460
+ },
4461
+ async listLinearIssues(_repoPath) {
4462
+ const { listAssignedLinearIssues: listAssignedLinearIssues2 } = await import("./linear-list-N57PR6JM.js");
4463
+ return listAssignedLinearIssues2();
4299
4464
  }
4300
- }
4301
- function formatClaudeUsageResetClock(resetsAt) {
4302
- if (!resetsAt) return "";
4303
- const at = new Date(resetsAt);
4304
- if (Number.isNaN(at.getTime())) return "";
4465
+ };
4466
+
4467
+ // src/agents/list-models.ts
4468
+ var CLAUDE_MODEL_CATALOG = [
4469
+ { id: "fable", displayName: "Fable" },
4470
+ { id: "opus", displayName: "Opus" },
4471
+ { id: "sonnet", displayName: "Sonnet" },
4472
+ { id: "haiku", displayName: "Haiku" }
4473
+ ];
4474
+ async function listBrightsyModels() {
4305
4475
  try {
4306
- return at.toLocaleString(void 0, {
4307
- weekday: "short",
4308
- month: "short",
4309
- day: "numeric",
4310
- hour: "numeric",
4311
- minute: "2-digit"
4312
- });
4476
+ const targets = await listBrightsyChatTargets();
4477
+ const accountId = targets.activeAccountId;
4478
+ const models = (targets.models ?? []).map((m) => ({
4479
+ id: encodeBrightsyTarget("model", m.id, accountId),
4480
+ displayName: m.name || m.id,
4481
+ description: m.description ?? void 0
4482
+ }));
4483
+ const agents = (targets.agents ?? []).map((a) => ({
4484
+ id: encodeBrightsyTarget("agent", a.id, accountId),
4485
+ displayName: a.name || a.id,
4486
+ description: a.description ?? "Brightsy agent target"
4487
+ }));
4488
+ return [...models, ...agents].slice(0, 80);
4313
4489
  } catch {
4314
- return at.toISOString();
4315
- }
4316
- }
4317
- function formatClaudeUsageFetchedAt(fetchedAt, now = /* @__PURE__ */ new Date()) {
4318
- const at = new Date(fetchedAt);
4319
- if (Number.isNaN(at.getTime())) return "";
4320
- const minutes = Math.max(0, Math.round((now.getTime() - at.getTime()) / 6e4));
4321
- if (minutes < 1) return "Updated just now";
4322
- if (minutes < 60) return `Updated ${minutes}m ago`;
4323
- const hours = Math.round(minutes / 60);
4324
- if (hours < 36) return `Updated ${hours}h ago`;
4325
- return `Updated ${formatClaudeUsageResetClock(fetchedAt)}`;
4326
- }
4327
- function formatClaudeExtraUsageDetail(extra) {
4328
- if (!extra.enabled) return "Extra usage off";
4329
- const bits = ["Extra usage on"];
4330
- if (extra.usedCredits != null && extra.monthlyLimit != null) {
4331
- bits.push(`${extra.usedCredits} / ${extra.monthlyLimit} credits this month`);
4332
- } else if (extra.usedCredits != null) {
4333
- bits.push(`${extra.usedCredits} credits used`);
4334
- }
4335
- if (extra.usedPercent != null) {
4336
- bits.push(`${Math.round(extra.usedPercent)}% of extra pool`);
4337
- }
4338
- return bits.join(" \xB7 ");
4339
- }
4340
- function formatClaudeUsageWindowLine(window, now = /* @__PURE__ */ new Date()) {
4341
- const reset = formatClaudeUsageReset(window.resetsAt, now);
4342
- const clock = formatClaudeUsageResetClock(window.resetsAt);
4343
- const left = `${Math.round(window.remainingPercent)}% left`;
4344
- const used = `${Math.round(window.usedPercent)}% used`;
4345
- const resetBit = reset ? clock && !reset.includes(clock) ? `${reset} (${clock})` : reset : "";
4346
- return resetBit ? `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used} \xB7 ${resetBit}` : `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used}`;
4347
- }
4348
- function formatClaudeUsageTooltip(usage, now = /* @__PURE__ */ new Date()) {
4349
- const lines = [
4350
- "Claude Code plan",
4351
- ...usage.windows.map((w) => formatClaudeUsageWindowLine(w, now))
4352
- ];
4353
- if (usage.extraUsage) {
4354
- lines.push(formatClaudeExtraUsageDetail(usage.extraUsage));
4490
+ return [];
4355
4491
  }
4356
- const fetched = formatClaudeUsageFetchedAt(usage.fetchedAt, now);
4357
- if (fetched) lines.push(fetched);
4358
- return lines.join("\n");
4359
- }
4360
- function formatClaudeUsageCompact(window) {
4361
- return `${window.shortLabel} ${Math.round(window.remainingPercent)}%`;
4362
- }
4363
- function claudeUsageWindowOverLimit(window) {
4364
- return window.remainingPercent <= 0 || window.usedPercent >= 100;
4365
- }
4366
- function claudeUsageOverLimitWindows(usage) {
4367
- if (!usage) return [];
4368
- return usage.windows.filter(claudeUsageWindowOverLimit);
4369
- }
4370
- function formatOverLimitWindowList(windows, now) {
4371
- const parts = windows.map((w) => {
4372
- const reset = formatClaudeUsageReset(w.resetsAt, now);
4373
- return reset ? `${w.label} (${reset})` : w.label;
4374
- });
4375
- return {
4376
- list: parts.join(", "),
4377
- verb: windows.length === 1 ? "is" : "are"
4378
- };
4379
- }
4380
- function formatClaudeUsageOverLimitConfirm(windows, now = /* @__PURE__ */ new Date()) {
4381
- if (windows.length === 0) return "";
4382
- const { list, verb } = formatOverLimitWindowList(windows, now);
4383
- return `Claude Code ${list} ${verb} at or over the plan limit. Send this message anyway?`;
4384
4492
  }
4385
- function formatClaudeUsageOverLimitWait(windows, now = /* @__PURE__ */ new Date()) {
4386
- if (windows.length === 0) return "";
4387
- const { list, verb } = formatOverLimitWindowList(windows, now);
4388
- return `Claude Code ${list} ${verb} at or over the plan limit. Sending is paused until the window resets.`;
4493
+ async function listModelsForAgent(agent) {
4494
+ const kinds = agent ? [agent] : ["claude", "codex", "opencode", "cursor", "brightsy"];
4495
+ const out = [];
4496
+ for (const kind of kinds) {
4497
+ if (kind === "claude") {
4498
+ out.push({
4499
+ agent: kind,
4500
+ auto: true,
4501
+ models: CLAUDE_MODEL_CATALOG,
4502
+ note: "Default Auto \u2014 only pass a model id when you have a reason."
4503
+ });
4504
+ continue;
4505
+ }
4506
+ if (kind === "codex") {
4507
+ out.push({
4508
+ agent: kind,
4509
+ auto: true,
4510
+ models: await listCodexModels(),
4511
+ note: "Default Auto \u2014 only pass a model slug when you have a reason."
4512
+ });
4513
+ continue;
4514
+ }
4515
+ if (kind === "opencode") {
4516
+ out.push({
4517
+ agent: kind,
4518
+ auto: true,
4519
+ models: await listOpencodeModels(),
4520
+ note: "Default Auto \u2014 only pass a provider/model id when you have a reason."
4521
+ });
4522
+ continue;
4523
+ }
4524
+ if (kind === "cursor") {
4525
+ out.push({
4526
+ agent: kind,
4527
+ auto: true,
4528
+ models: await listCursorModels(),
4529
+ note: 'Default Auto \u2014 only pass a model id when you have a reason (or use "default").'
4530
+ });
4531
+ continue;
4532
+ }
4533
+ if (kind === "brightsy") {
4534
+ const models = await listBrightsyModels();
4535
+ out.push({
4536
+ agent: kind,
4537
+ auto: true,
4538
+ models,
4539
+ note: models.length ? "Default Auto / Default agent \u2014 only pass a model/agent id when you have a reason." : "Brightsy not logged in or no targets \u2014 leave model unset for Default."
4540
+ });
4541
+ }
4542
+ }
4543
+ return out;
4389
4544
  }
4390
4545
 
4391
- // src/agents/claude-usage-client.ts
4392
- import { existsSync as existsSync12, readFileSync as readFileSync5 } from "fs";
4393
- import { homedir as homedir7 } from "os";
4394
- import { join as join10 } from "path";
4395
- var CLAUDE_OAUTH_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
4396
- var CLAUDE_USAGE_TTL_MS = 9e4;
4397
- var CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
4398
- var CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
4399
- var KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
4400
- var cache = null;
4401
- var errorUntil = 0;
4402
- var inflight = null;
4403
- var lastGood = null;
4404
- var claudeVersion = null;
4405
- var cacheDirKey = "";
4406
- function usageCacheDir(opts) {
4407
- return opts.configDir?.trim() || "";
4408
- }
4409
- function adoptCacheDir(dir) {
4410
- if (dir === cacheDirKey) return;
4411
- cache = null;
4412
- lastGood = null;
4413
- errorUntil = 0;
4414
- inflight = null;
4415
- cacheDirKey = dir;
4416
- }
4417
- function accessTokenFromCredentialsJson(raw) {
4418
- const trimmed = raw.trim();
4419
- if (!trimmed) return null;
4420
- if (trimmed.startsWith("sk-ant-")) {
4421
- const token = trimmed.split(/\s+/)[0];
4422
- return token || null;
4423
- }
4424
- try {
4425
- const parsed = JSON.parse(trimmed);
4426
- const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
4427
- const token = oauth.accessToken ?? oauth.access_token;
4428
- return typeof token === "string" && token.trim() ? token.trim() : null;
4429
- } catch {
4430
- return null;
4546
+ // src/agents/session-quota.ts
4547
+ function isSessionQuotaLimit(text) {
4548
+ const lower = text.trim().toLowerCase();
4549
+ if (!lower) return false;
4550
+ if (/credit balance is too low|out of credits|insufficient.?quota|billing/.test(lower)) {
4551
+ return false;
4431
4552
  }
4432
- }
4433
- function claudeCredentialsPath(configDir) {
4434
- const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || join10(homedir7(), ".claude");
4435
- return join10(root, ".credentials.json");
4436
- }
4437
- async function readFileAccessToken(configDir) {
4438
- const path = claudeCredentialsPath(configDir);
4439
- if (!existsSync12(path)) return null;
4440
- try {
4441
- return accessTokenFromCredentialsJson(readFileSync5(path, "utf8"));
4442
- } catch {
4443
- return null;
4553
+ if (/prompt is too long|context.*(too long|exceed)|conversation too long/.test(lower)) {
4554
+ return false;
4444
4555
  }
4556
+ return /you've hit your/.test(lower) || /hit your (session|weekly|opus) limit/.test(lower) || /usage limit/.test(lower) || /rate.?limit|too many requests|\b429\b/.test(lower) && /reset/i.test(text);
4445
4557
  }
4446
- async function readKeychainAccessToken(configDir) {
4447
- if (process.platform !== "darwin") return null;
4448
- const root = configDir?.trim();
4449
- const accounts = root ? [root, void 0] : [void 0];
4450
- for (const service of KEYCHAIN_SERVICES) {
4451
- for (const account of accounts) {
4452
- const args = ["find-generic-password", "-s", service, "-w"];
4453
- if (account) args.splice(3, 0, "-a", account);
4454
- const result = await run("security", args, {
4455
- reject: false,
4456
- timeoutMs: 4e3
4457
- });
4458
- if (result.exitCode !== 0 || !result.stdout.trim()) continue;
4459
- const token = accessTokenFromCredentialsJson(result.stdout);
4460
- if (token) return token;
4558
+ function parseSessionQuotaResetAt(text, now = /* @__PURE__ */ new Date()) {
4559
+ const absolute = text.match(
4560
+ /resets\s+(?:at\s+)?(\d{1,2}):(\d{2})\s*(am|pm)(?:\s*\(([^)]+)\))?/i
4561
+ );
4562
+ if (absolute) {
4563
+ const hour12 = Number(absolute[1]);
4564
+ const minute = Number(absolute[2]);
4565
+ const ampm = absolute[3].toLowerCase();
4566
+ const timeZone = absolute[4]?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone;
4567
+ let hour = hour12 % 12;
4568
+ if (ampm === "pm") hour += 12;
4569
+ const at = zonedWallTimeToUtc(now, hour, minute, timeZone);
4570
+ if (!at) return null;
4571
+ if (at.getTime() <= now.getTime() + 3e4) {
4572
+ const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1e3);
4573
+ return zonedWallTimeToUtc(tomorrow, hour, minute, timeZone);
4461
4574
  }
4575
+ return at;
4576
+ }
4577
+ const relative2 = text.match(
4578
+ /resets\s+in\s+(\d+)\s*(minutes?|hours?|days?)/i
4579
+ );
4580
+ if (relative2) {
4581
+ const n = Number(relative2[1]);
4582
+ const unit = relative2[2].toLowerCase();
4583
+ const ms = unit.startsWith("day") ? n * 24 * 60 * 60 * 1e3 : unit.startsWith("hour") ? n * 60 * 60 * 1e3 : n * 60 * 1e3;
4584
+ return new Date(now.getTime() + ms);
4462
4585
  }
4463
4586
  return null;
4464
4587
  }
4465
- async function readClaudeAccessToken(configDir) {
4466
- const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
4467
- if (envToken) return envToken;
4468
- const fromFile = await readFileAccessToken(configDir);
4469
- if (fromFile) return fromFile;
4470
- return readKeychainAccessToken(configDir);
4471
- }
4472
- async function resolveClaudeUserAgent() {
4473
- if (claudeVersion) return `claude-code/${claudeVersion}`;
4588
+ function zonedWallTimeToUtc(day, hour, minute, timeZone) {
4474
4589
  try {
4475
- const claude = resolveClaudeExecutable();
4476
- const result = await run(claude, ["--version"], { reject: false, timeoutMs: 4e3 });
4477
- const match = `${result.stdout}
4478
- ${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
4479
- claudeVersion = match?.[1] ?? "2.1.80";
4590
+ const cal = new Intl.DateTimeFormat("en-US", {
4591
+ timeZone,
4592
+ year: "numeric",
4593
+ month: "2-digit",
4594
+ day: "2-digit"
4595
+ });
4596
+ const parts = Object.fromEntries(
4597
+ cal.formatToParts(day).filter((p) => p.type !== "literal").map((p) => [p.type, p.value])
4598
+ );
4599
+ const year = Number(parts.year);
4600
+ const month = Number(parts.month);
4601
+ const date = Number(parts.day);
4602
+ if (![year, month, date].every((n) => Number.isFinite(n))) return null;
4603
+ const utcGuess = Date.UTC(year, month - 1, date, hour, minute, 0);
4604
+ const dtf = new Intl.DateTimeFormat("en-US", {
4605
+ timeZone,
4606
+ year: "numeric",
4607
+ month: "2-digit",
4608
+ day: "2-digit",
4609
+ hour: "2-digit",
4610
+ minute: "2-digit",
4611
+ second: "2-digit",
4612
+ hourCycle: "h23"
4613
+ });
4614
+ const asParts = Object.fromEntries(
4615
+ dtf.formatToParts(new Date(utcGuess)).filter((p) => p.type !== "literal").map((p) => [p.type, p.value])
4616
+ );
4617
+ const asUtc = Date.UTC(
4618
+ Number(asParts.year),
4619
+ Number(asParts.month) - 1,
4620
+ Number(asParts.day),
4621
+ Number(asParts.hour),
4622
+ Number(asParts.minute),
4623
+ Number(asParts.second || "0")
4624
+ );
4625
+ const offset = asUtc - utcGuess;
4626
+ return new Date(utcGuess - offset);
4480
4627
  } catch {
4481
- claudeVersion = "2.1.80";
4628
+ return null;
4482
4629
  }
4483
- return `claude-code/${claudeVersion}`;
4484
- }
4485
- function staleOk(now) {
4486
- if (!lastGood) return null;
4487
- if (now - lastGood.at > CLAUDE_USAGE_STALE_OK_MS) return null;
4488
- return lastGood.value;
4489
- }
4490
- function reuseLast() {
4491
- return lastGood?.value ?? null;
4492
4630
  }
4493
- async function getClaudePlanUsage(opts = {}) {
4494
- const now = opts.now ?? Date.now();
4495
- adoptCacheDir(usageCacheDir(opts));
4496
- if (now < errorUntil) return reuseLast() ?? staleOk(now);
4497
- if (!opts.force) {
4498
- if (cache && now - cache.at < CLAUDE_USAGE_TTL_MS) return cache.value;
4499
- }
4500
- if (inflight) return inflight;
4501
- inflight = (async () => {
4502
- try {
4503
- const token = await (opts.readAccessToken ?? (() => readClaudeAccessToken(opts.configDir)))();
4504
- if (!token) {
4505
- cache = { at: now, dir: cacheDirKey, value: null };
4506
- return null;
4507
- }
4508
- const fetchFn = opts.fetch ?? httpFetch;
4509
- const userAgent = opts.userAgent ?? await resolveClaudeUserAgent();
4510
- const ac = new AbortController();
4511
- const timer = setTimeout(() => ac.abort(), 8e3);
4512
- let res;
4513
- try {
4514
- res = await fetchFn(CLAUDE_OAUTH_USAGE_URL, {
4515
- headers: {
4516
- Authorization: `Bearer ${token}`,
4517
- "anthropic-beta": "oauth-2025-04-20",
4518
- "User-Agent": userAgent
4519
- },
4520
- signal: ac.signal
4521
- });
4522
- } finally {
4523
- clearTimeout(timer);
4524
- }
4525
- if (res.status === 401 || res.status === 403) {
4526
- cache = { at: now, dir: cacheDirKey, value: null };
4527
- return null;
4528
- }
4529
- if (res.status === 429) {
4530
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
4531
- const last = reuseLast();
4532
- if (last) cache = { at: now, dir: cacheDirKey, value: last };
4533
- return last;
4534
- }
4535
- if (!res.ok) {
4536
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
4537
- return staleOk(now);
4538
- }
4539
- const usage = parseClaudeUsagePayload(await res.json(), new Date(now).toISOString());
4540
- cache = { at: now, dir: cacheDirKey, value: usage };
4541
- if (usage) lastGood = { at: now, dir: cacheDirKey, value: usage };
4542
- return usage;
4543
- } catch {
4544
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
4545
- return staleOk(now);
4546
- } finally {
4547
- inflight = null;
4548
- }
4549
- })();
4550
- return inflight;
4631
+ var FALLBACK_ORDER = [
4632
+ "cursor",
4633
+ "codex",
4634
+ "opencode",
4635
+ "claude"
4636
+ ];
4637
+ function resolveQuotaFallbackAgent(current, preferred) {
4638
+ const ordered = [
4639
+ ...preferred && preferred !== "brightsy" ? [preferred] : [],
4640
+ ...FALLBACK_ORDER.filter((a) => a !== preferred)
4641
+ ];
4642
+ return ordered.find((a) => a !== current) ?? (current === "cursor" ? "codex" : "cursor");
4551
4643
  }
4552
4644
 
4553
4645
  // src/agents/index.ts
@@ -4608,6 +4700,18 @@ export {
4608
4700
  userMcpNamesToDisable,
4609
4701
  getMcpUiHost,
4610
4702
  closeMcpUiHost,
4703
+ parseClaudeUsagePayload,
4704
+ hottestClaudeWindow,
4705
+ formatClaudeUsageReset,
4706
+ formatClaudeUsageResetClock,
4707
+ formatClaudeUsageFetchedAt,
4708
+ formatClaudeExtraUsageDetail,
4709
+ formatClaudeUsageTooltip,
4710
+ formatClaudeUsageCompact,
4711
+ claudeUsageOverLimitWindows,
4712
+ formatClaudeUsageOverLimitConfirm,
4713
+ formatClaudeUsageOverLimitWait,
4714
+ getClaudePlanUsage,
4611
4715
  PLAN_MODE_INSTRUCTION,
4612
4716
  PLAN_MODE_OFF_INSTRUCTION,
4613
4717
  planModeTurnInstruction,
@@ -4627,18 +4731,6 @@ export {
4627
4731
  isSessionQuotaLimit,
4628
4732
  parseSessionQuotaResetAt,
4629
4733
  resolveQuotaFallbackAgent,
4630
- parseClaudeUsagePayload,
4631
- hottestClaudeWindow,
4632
- formatClaudeUsageReset,
4633
- formatClaudeUsageResetClock,
4634
- formatClaudeUsageFetchedAt,
4635
- formatClaudeExtraUsageDetail,
4636
- formatClaudeUsageTooltip,
4637
- formatClaudeUsageCompact,
4638
- claudeUsageOverLimitWindows,
4639
- formatClaudeUsageOverLimitConfirm,
4640
- formatClaudeUsageOverLimitWait,
4641
- getClaudePlanUsage,
4642
4734
  getAdapter,
4643
4735
  allAdapters
4644
4736
  };