@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.
- package/dist/{abletime-MSIMJKKQ.js → abletime-3HRWLQZJ.js} +4 -4
- package/dist/{abletime-X2TJ6PPK.js → abletime-CGFJZB7L.js} +4 -4
- package/dist/{abletime-oauth-DEIENLHC.js → abletime-oauth-JQDSH5OL.js} +3 -3
- package/dist/{abletime-oauth-2RUKRZYZ.js → abletime-oauth-QNJQLHR4.js} +3 -3
- package/dist/{abletime-rest-UBLSGMSA.js → abletime-rest-TANL5TMY.js} +3 -3
- package/dist/{abletime-rest-HWBUPI4R.js → abletime-rest-UQA2CRZN.js} +3 -3
- package/dist/{agents-AQM7NLXD.js → agents-5MFGVK7C.js} +7 -7
- package/dist/{agents-7CHZO3K3.js → agents-T4XBZZDA.js} +7 -7
- package/dist/{app-settings-Q2F57NVK.js → app-settings-PPIMYJKS.js} +3 -1
- package/dist/{app-settings-A6JUT2SF.js → app-settings-SNOPJ7P5.js} +3 -1
- package/dist/{chunk-5IMXA563.js → chunk-27XWAI7S.js} +22 -22
- package/dist/{chunk-RTZO2YJC.js → chunk-2HPVGTHF.js} +2 -2
- package/dist/{chunk-GHKJBZW5.js → chunk-4NXGVJA6.js} +2 -2
- package/dist/{chunk-O5WRVQFT.js → chunk-5FUAOU3G.js} +1 -1
- package/dist/{chunk-3J3XOIHF.js → chunk-62ALWH3T.js} +3 -3
- package/dist/{chunk-J3BQHHDZ.js → chunk-6TV6L2DD.js} +4 -4
- package/dist/{chunk-4PHOJMZI.js → chunk-6WMNIX2U.js} +35 -2
- package/dist/{chunk-4PXHJA5K.js → chunk-7B2OUQON.js} +2 -2
- package/dist/{chunk-TD76ORBJ.js → chunk-AJMERXZP.js} +2 -2
- package/dist/{chunk-QTDCPMOW.js → chunk-ATS7SYHG.js} +1 -1
- package/dist/{chunk-AG2RM3DF.js → chunk-CEQ4Z32M.js} +3 -3
- package/dist/{chunk-5TS3KVGI.js → chunk-E77SRVVO.js} +1 -1
- package/dist/{chunk-5SJGR3VS.js → chunk-F7WP2U5I.js} +12 -9
- package/dist/{chunk-YFPSTG52.js → chunk-FDYMVJFU.js} +5 -5
- package/dist/{chunk-IYX53WZY.js → chunk-GAGTEI6B.js} +5 -5
- package/dist/{chunk-JZKNRDKF.js → chunk-IJNTTVFH.js} +23 -23
- package/dist/{chunk-MB3GOWB3.js → chunk-IVRWRYTH.js} +19 -10
- package/dist/{chunk-3DMRQB4Y.js → chunk-JCYGQKER.js} +1 -1
- package/dist/{chunk-JHT3CYLT.js → chunk-MOUAM6ZC.js} +1 -1
- package/dist/{chunk-Z54FI4VL.js → chunk-NTY5WGRD.js} +2 -2
- package/dist/{chunk-LHU6ZBFB.js → chunk-OHUAAX3O.js} +2 -2
- package/dist/{chunk-NQHEEGTH.js → chunk-PVCECFJK.js} +1 -1
- package/dist/{chunk-MHRU743Z.js → chunk-Q4TZA4MN.js} +2247 -2155
- package/dist/{chunk-4SNEW63T.js → chunk-RUIHNWRV.js} +3 -3
- package/dist/{chunk-NDBMDHQ5.js → chunk-RYPD7XWV.js} +5 -5
- package/dist/{chunk-FNAP6CCS.js → chunk-UJMCTGV7.js} +2 -2
- package/dist/{chunk-S3UGLMGE.js → chunk-WWU4SYZR.js} +35 -2
- package/dist/{chunk-4YGVJRXY.js → chunk-XNGW4OYD.js} +4 -4
- package/dist/{chunk-TW63CYUA.js → chunk-Y6VQX2LY.js} +2679 -2587
- package/dist/{chunk-BD7KUYJA.js → chunk-ZJMYCDYQ.js} +5 -5
- package/dist/{conductor-DUHRZUQY.js → conductor-EMGMDNHL.js} +5 -5
- package/dist/{conductor-3A2TNWUW.js → conductor-LYQKONSA.js} +5 -5
- package/dist/{coordinator-prompt-OX6A4MDA.js → coordinator-prompt-DLY3FS2L.js} +4 -4
- package/dist/{coordinator-prompt-7QALNDIV.js → coordinator-prompt-WALVMGKI.js} +4 -4
- package/dist/{global-workspace-HM2RKBCT.js → global-workspace-7OQ5O6JT.js} +4 -4
- package/dist/{global-workspace-6GGS3DWU.js → global-workspace-UG2A3CEM.js} +4 -4
- package/dist/index.cjs +1090 -640
- package/dist/index.d.cts +62 -8
- package/dist/index.d.ts +62 -8
- package/dist/index.js +325 -32
- package/dist/{linear-WYI64BMX.js → linear-MIJO6DCV.js} +2 -2
- package/dist/{linear-JE4WAZ3W.js → linear-PKYJH4WK.js} +2 -2
- package/dist/{linear-list-I4NAOWPN.js → linear-list-JPQ27RXG.js} +1 -1
- package/dist/{linear-list-CGUCPWTV.js → linear-list-N57PR6JM.js} +1 -1
- package/dist/mcp/run-stdio.cjs +500 -224
- package/dist/mcp/run-stdio.js +106 -21
- package/dist/{optional-cli-7QXXPEN6.js → optional-cli-4GTEDEYJ.js} +3 -3
- package/dist/{optional-cli-YHLVTVRK.js → optional-cli-RPJIQBDX.js} +4 -4
- package/dist/{orchestrator-OWO6LQ5U.js → orchestrator-AJZNVREM.js} +10 -10
- package/dist/{orchestrator-POMFVZLB.js → orchestrator-BUEPWNCF.js} +10 -10
- package/dist/{thread-store-HETUMDVA.js → thread-store-MEUWZDVV.js} +2 -2
- package/dist/{thread-store-V5IDUJ4L.js → thread-store-R3G5VBII.js} +2 -2
- package/dist/{workspaces-DTMPNDPW.js → workspaces-35T6FW57.js} +4 -4
- package/dist/{workspaces-V6IIBSKA.js → workspaces-KWGTP7DI.js} +4 -4
- package/dist/{worktree-FX5FT6BI.js → worktree-5P7SCST3.js} +3 -3
- package/dist/{worktree-BD3EJE24.js → worktree-ROJXGBWS.js} +3 -3
- 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-
|
|
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-
|
|
18
|
+
} from "./chunk-XNGW4OYD.js";
|
|
19
19
|
import {
|
|
20
20
|
codexUnattendedGitConfigArgs,
|
|
21
21
|
mergeAgentGitAuthEnv,
|
|
22
22
|
resolveAgentGitAuthEnv,
|
|
23
23
|
resolveCodexGitWritableRoots
|
|
24
|
-
} from "./chunk-
|
|
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-
|
|
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
|
|
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/
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
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
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
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 (
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
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
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
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
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
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
|
|
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
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
[AGENT_RPC_CWD_ENV]: cwd
|
|
2270
|
+
windows,
|
|
2271
|
+
...extra ? { extraUsage: extra } : {},
|
|
2272
|
+
fetchedAt
|
|
2222
2273
|
};
|
|
2223
2274
|
}
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
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
|
|
2236
|
-
|
|
2237
|
-
|
|
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
|
|
2240
|
-
|
|
2241
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
2254
|
-
const
|
|
2255
|
-
if (
|
|
2256
|
-
|
|
2257
|
-
|
|
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
|
-
|
|
2260
|
-
|
|
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
|
|
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
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
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
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
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
|
-
|
|
2308
|
-
|
|
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
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
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
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
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
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
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
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
const
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
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
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
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
|
|
2368
|
-
if (
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
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
|
-
|
|
2375
|
-
return void 0;
|
|
2458
|
+
return null;
|
|
2376
2459
|
}
|
|
2377
|
-
function
|
|
2378
|
-
const
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
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
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
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
|
|
2399
|
-
if (
|
|
2400
|
-
if (
|
|
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
|
|
2404
|
-
|
|
2405
|
-
return [withEventParentId({ type: "stdout", data: text }, parentId)];
|
|
2485
|
+
function reuseLast() {
|
|
2486
|
+
return lastGood?.value ?? null;
|
|
2406
2487
|
}
|
|
2407
|
-
function
|
|
2408
|
-
|
|
2409
|
-
|
|
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 (
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
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
|
-
|
|
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
|
|
2544
|
+
})();
|
|
2545
|
+
return inflight;
|
|
2493
2546
|
}
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
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
|
-
|
|
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
|
|
2502
|
-
|
|
2503
|
-
|
|
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
|
|
2506
|
-
const
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
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
|
-
|
|
2539
|
-
const
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
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
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
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
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
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
|
-
|
|
2575
|
-
|
|
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 (
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
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 (
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
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
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
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
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
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
|
-
|
|
2758
|
-
|
|
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
|
-
|
|
2761
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
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
|
|
2793
|
+
return void 0;
|
|
2939
2794
|
}
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
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
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
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
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
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
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
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
|
|
2987
|
-
if (
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
}
|
|
2993
|
-
if (
|
|
2994
|
-
|
|
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
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
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
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
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
|
|
3027
|
-
|
|
3028
|
-
if (
|
|
3029
|
-
|
|
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
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
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
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
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
|
-
|
|
3086
|
-
|
|
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
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
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
|
|
3320
|
-
const
|
|
3321
|
-
|
|
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
|
|
3324
|
-
|
|
3325
|
-
return
|
|
2961
|
+
function claudeString(obj, key) {
|
|
2962
|
+
const v = obj[key];
|
|
2963
|
+
return typeof v === "string" && v.trim() ? v.trim() : void 0;
|
|
3326
2964
|
}
|
|
3327
|
-
|
|
3328
|
-
const
|
|
3329
|
-
|
|
3330
|
-
|
|
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
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
const
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
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
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
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
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
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
|
|
3069
|
+
return null;
|
|
3382
3070
|
}
|
|
3383
|
-
|
|
3384
|
-
|
|
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
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
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: "
|
|
3114
|
+
agent: "claude",
|
|
3409
3115
|
installed: true,
|
|
3410
|
-
authenticated
|
|
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
|
|
3417
|
-
const
|
|
3418
|
-
const
|
|
3419
|
-
|
|
3420
|
-
const
|
|
3421
|
-
|
|
3422
|
-
|
|
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
|
|
3432
|
-
const
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
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:
|
|
3456
|
-
args
|
|
3238
|
+
file: claude,
|
|
3239
|
+
args,
|
|
3457
3240
|
cwd: thread.worktreePath,
|
|
3458
|
-
stdin:
|
|
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
|
-
|
|
3461
|
-
|
|
3462
|
-
//
|
|
3463
|
-
//
|
|
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
|
-
|
|
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
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
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/
|
|
3485
|
-
import { existsSync as
|
|
3486
|
-
|
|
3487
|
-
|
|
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
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
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
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
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
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
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
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
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
|
-
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
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
|
|
3612
|
-
|
|
3613
|
-
|
|
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
|
-
|
|
3642
|
-
|
|
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
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
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
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
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
|
|
3737
|
-
kind: "
|
|
3505
|
+
var codexAdapter = {
|
|
3506
|
+
kind: "codex",
|
|
3738
3507
|
async detect() {
|
|
3739
|
-
const
|
|
3740
|
-
if (
|
|
3741
|
-
if (!
|
|
3508
|
+
const codex = resolveAgentExecutable("codex");
|
|
3509
|
+
if (codex !== "codex") {
|
|
3510
|
+
if (!existsSync9(codex)) {
|
|
3742
3511
|
return {
|
|
3743
|
-
agent: "
|
|
3512
|
+
agent: "codex",
|
|
3744
3513
|
installed: false,
|
|
3745
3514
|
authenticated: false,
|
|
3746
3515
|
linearMcp: false,
|
|
3747
3516
|
warnings: [],
|
|
3748
|
-
reason: `
|
|
3517
|
+
reason: `Codex executable not found: ${codex}`
|
|
3749
3518
|
};
|
|
3750
3519
|
}
|
|
3751
3520
|
} else {
|
|
3752
|
-
const which = await run("which", ["
|
|
3521
|
+
const which = await run("which", ["codex"], { reject: false, timeoutMs: 3e3 });
|
|
3753
3522
|
if (which.exitCode !== 0) {
|
|
3754
3523
|
return {
|
|
3755
|
-
agent: "
|
|
3524
|
+
agent: "codex",
|
|
3756
3525
|
installed: false,
|
|
3757
3526
|
authenticated: false,
|
|
3758
3527
|
linearMcp: false,
|
|
3759
3528
|
warnings: [],
|
|
3760
|
-
reason: "
|
|
3529
|
+
reason: "codex CLI not found on PATH"
|
|
3761
3530
|
};
|
|
3762
3531
|
}
|
|
3763
3532
|
}
|
|
3764
|
-
const
|
|
3765
|
-
const
|
|
3766
|
-
const
|
|
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: "
|
|
3537
|
+
agent: "codex",
|
|
3770
3538
|
installed: true,
|
|
3771
3539
|
authenticated,
|
|
3772
3540
|
linearMcp,
|
|
3773
|
-
warnings
|
|
3774
|
-
reason: authenticated ? void 0 :
|
|
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
|
|
3783
|
-
|
|
3784
|
-
|
|
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
|
-
"--
|
|
3787
|
-
"
|
|
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
|
-
|
|
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("
|
|
3613
|
+
file: resolveAgentExecutable("codex"),
|
|
3803
3614
|
args,
|
|
3804
3615
|
cwd: thread.worktreePath,
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
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
|
-
|
|
3820
|
-
|
|
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
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
return { type: "
|
|
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.
|
|
3864
|
-
const
|
|
3865
|
-
const
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
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
|
-
|
|
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 (
|
|
3885
|
-
const name =
|
|
3886
|
-
const
|
|
3887
|
-
const
|
|
3888
|
-
|
|
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
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
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
|
|
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
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
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 (
|
|
3927
|
-
const
|
|
3928
|
-
const usage =
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
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(
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
)
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
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
|
|
3877
|
+
return {
|
|
3878
|
+
agent: "cursor",
|
|
3879
|
+
installed: true,
|
|
3880
|
+
authenticated: true,
|
|
3881
|
+
linearMcp: false,
|
|
3882
|
+
warnings: []
|
|
3883
|
+
};
|
|
3977
3884
|
},
|
|
3978
|
-
async
|
|
3979
|
-
const
|
|
3980
|
-
const
|
|
3981
|
-
|
|
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:
|
|
3984
|
-
args,
|
|
3925
|
+
file: launch.file,
|
|
3926
|
+
args: launch.args,
|
|
3985
3927
|
cwd: thread.worktreePath,
|
|
3928
|
+
stdin: JSON.stringify(req),
|
|
3986
3929
|
env: {
|
|
3987
|
-
|
|
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
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
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/
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
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
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
}
|
|
4083
|
-
|
|
4084
|
-
|
|
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
|
-
|
|
4089
|
-
|
|
4090
|
-
|
|
4091
|
-
);
|
|
4092
|
-
|
|
4093
|
-
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
|
|
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
|
-
|
|
4081
|
+
const tmp = `${pluginFile}.${process.pid}.tmp`;
|
|
4082
|
+
writeFileSync4(tmp, OPENCODE_PLUGIN_SOURCE);
|
|
4083
|
+
renameSync(tmp, pluginFile);
|
|
4084
|
+
return pluginFile;
|
|
4117
4085
|
}
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4127
|
-
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
|
|
4140
|
-
|
|
4141
|
-
|
|
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
|
-
|
|
4162
|
-
|
|
4163
|
-
|
|
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/
|
|
4176
|
-
var
|
|
4177
|
-
|
|
4178
|
-
|
|
4179
|
-
|
|
4180
|
-
|
|
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
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
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
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
return
|
|
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
|
|
4135
|
+
return void 0;
|
|
4220
4136
|
}
|
|
4221
|
-
function
|
|
4222
|
-
|
|
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
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
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
|
|
4242
|
-
|
|
4243
|
-
|
|
4244
|
-
const
|
|
4245
|
-
|
|
4246
|
-
|
|
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
|
|
4257
|
-
|
|
4258
|
-
|
|
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
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
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
|
-
|
|
4270
|
-
|
|
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
|
-
|
|
4273
|
-
|
|
4274
|
-
|
|
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
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
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
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
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
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
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
|
|
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
|
|
4386
|
-
|
|
4387
|
-
const
|
|
4388
|
-
|
|
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/
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4396
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
4453
|
-
|
|
4454
|
-
|
|
4455
|
-
|
|
4456
|
-
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
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
|
-
|
|
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
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
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
|
};
|