@sideboard-ai/core 0.1.264 → 0.1.267

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/{abletime-6AOJI2YZ.js → abletime-4ZSDI4YP.js} +9 -6
  2. package/dist/{abletime-U75ZGDIX.js → abletime-JNQAHLHH.js} +7 -4
  3. package/dist/{abletime-oauth-TA2YDCYX.js → abletime-oauth-4RXZH2KU.js} +3 -3
  4. package/dist/{abletime-oauth-LOAHGG4X.js → abletime-oauth-DCEIINYT.js} +5 -5
  5. package/dist/{abletime-rest-CTA5WV26.js → abletime-rest-KVBJFVFD.js} +3 -3
  6. package/dist/{abletime-rest-YZPFM6IY.js → abletime-rest-VN6PZ6P2.js} +5 -5
  7. package/dist/agents/cursor-runner.js +7 -5
  8. package/dist/{agents-3TUMFSMH.js → agents-G3JTULM2.js} +7 -5
  9. package/dist/{agents-6FWDRVA2.js → agents-XRXJCAWJ.js} +11 -10
  10. package/dist/{app-settings-RKFFUIFQ.js → app-settings-L5HGYXWJ.js} +1 -3
  11. package/dist/{app-settings-MVZPM6WW.js → app-settings-RAC4PSSP.js} +3 -5
  12. package/dist/{caffeinate-hold-UAGLSGMM.js → caffeinate-hold-7JM5H5P3.js} +2 -2
  13. package/dist/{chunk-F5MFNUAA.js → chunk-27Z4MEQ5.js} +1 -1
  14. package/dist/{chunk-EK3KVT7I.js → chunk-2XIRV7FS.js} +53 -1254
  15. package/dist/{chunk-3H7O27X2.js → chunk-3VBS6MES.js} +39 -1017
  16. package/dist/chunk-4ECDIKAS.js +2273 -0
  17. package/dist/{chunk-H547WSSZ.js → chunk-4RZRHTSZ.js} +1 -1
  18. package/dist/{chunk-QN5DL2QO.js → chunk-5DZUWGKV.js} +1 -1
  19. package/dist/chunk-5N4Q46SG.js +392 -0
  20. package/dist/{chunk-YKYEHDMX.js → chunk-AGXZAMOF.js} +5 -5
  21. package/dist/{chunk-RKPBIB2U.js → chunk-DB7MVDYS.js} +33 -7
  22. package/dist/{chunk-BOMSJUXW.js → chunk-DBFAFI5A.js} +5 -5
  23. package/dist/chunk-FAGK33E2.js +994 -0
  24. package/dist/{chunk-A5SAYFJ4.js → chunk-FIBZEFKA.js} +4 -390
  25. package/dist/{chunk-5PK53SAP.js → chunk-GONPMH36.js} +5 -5
  26. package/dist/{chunk-L5WGAIL2.js → chunk-GZXKUUJO.js} +35 -9
  27. package/dist/{chunk-Z2LGMV6C.js → chunk-H5XL4KUS.js} +21 -0
  28. package/dist/{chunk-T3AYRQJZ.js → chunk-HSRN2CSL.js} +473 -2487
  29. package/dist/{chunk-TJ673EZT.js → chunk-JANCPF7Z.js} +2 -2
  30. package/dist/chunk-KZ2CDZBZ.js +828 -0
  31. package/dist/{chunk-6YY7XPPL.js → chunk-L6CYOON4.js} +5 -5
  32. package/dist/{chunk-6YOXQVJ7.js → chunk-LAIBYKZS.js} +3 -3
  33. package/dist/{chunk-4ALDX5IO.js → chunk-NWE3NOWQ.js} +3 -3
  34. package/dist/{chunk-36FOBJBF.js → chunk-OIENQEGG.js} +63 -38
  35. package/dist/{chunk-2QUQH2SZ.js → chunk-PAH7KDL2.js} +68 -24
  36. package/dist/{chunk-XAISOBBG.js → chunk-TQRSVE7D.js} +1 -1
  37. package/dist/chunk-UKSJO36E.js +1224 -0
  38. package/dist/{chunk-CEMNIGQH.js → chunk-UN5Q7POQ.js} +1 -1
  39. package/dist/{chunk-5ZPT5YAV.js → chunk-USBZ7PH4.js} +1 -1
  40. package/dist/chunk-UXI52MLJ.js +826 -0
  41. package/dist/chunk-X7RP3TQB.js +2385 -0
  42. package/dist/{chunk-QX6QUZVD.js → chunk-ZSGSVFWD.js} +424 -2611
  43. package/dist/conductor-MLM5NGTP.js +104 -0
  44. package/dist/conductor-NRKTEN5X.js +105 -0
  45. package/dist/{connected-teams-7CENZDWU.js → connected-teams-JIUOSZ6C.js} +2 -2
  46. package/dist/{coordinator-prompt-J7DKHOCH.js → coordinator-prompt-4GHKCVRH.js} +7 -7
  47. package/dist/{coordinator-prompt-HZCQZ6C5.js → coordinator-prompt-BKRQDZFT.js} +3 -3
  48. package/dist/{cursor-recover-FALSNEZN.js → cursor-recover-MB3T2K5T.js} +2 -2
  49. package/dist/{global-workspace-TI26K25J.js → global-workspace-EEWJOMED.js} +9 -3
  50. package/dist/{global-workspace-6LDUZ2NF.js → global-workspace-EWFL4HPW.js} +13 -7
  51. package/dist/index.cjs +3918 -2592
  52. package/dist/index.d.cts +363 -68
  53. package/dist/index.d.ts +363 -68
  54. package/dist/index.js +4181 -3462
  55. package/dist/{managed-accounts-4BLTJKAN.js → managed-accounts-46A4KRUE.js} +2 -2
  56. package/dist/mcp/run-stdio.cjs +1894 -2012
  57. package/dist/mcp/run-stdio.js +719 -1445
  58. package/dist/{orchestrator-5YU46YNS.js → orchestrator-6ZQ2CYS4.js} +9 -6
  59. package/dist/{orchestrator-4JSG7BWC.js → orchestrator-MA3MHYIM.js} +15 -13
  60. package/dist/{paths-IUR3ABNG.js → paths-HYT5WOOX.js} +1 -1
  61. package/dist/{thread-store-FJ5CDX2M.js → thread-store-B3ZM4QEZ.js} +3 -3
  62. package/dist/{workspaces-QJ3XIPUJ.js → workspaces-F33Z4CEY.js} +3 -3
  63. package/dist/{workspaces-WOQHJFRQ.js → workspaces-SLP24Z3S.js} +7 -7
  64. package/dist/{worktree-6U2FA5LO.js → worktree-ACW23KJ5.js} +6 -6
  65. package/dist/{worktree-KQA4ON2G.js → worktree-C7RPVHZ7.js} +2 -2
  66. package/package.json +1 -1
  67. package/dist/chunk-CEOTK5GZ.js +0 -479
  68. package/dist/chunk-K7B25HO4.js +0 -477
@@ -1,26 +1,36 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import {
4
- isOrchestratorThread
5
- } from "./chunk-L5WGAIL2.js";
6
- import {
7
- codexUnattendedGitConfigArgs,
8
- mergeAgentGitAuthEnv,
9
- resolveAgentGitAuthEnv,
10
- resolveCodexGitWritableRoots
11
- } from "./chunk-4ALDX5IO.js";
12
3
  import {
13
4
  applyConnectedTeamToCli,
14
5
  brightsyMcpServerName,
15
6
  ensureCliTeamTracked,
16
7
  ensureConnectedBrightsyTeamTokens
17
- } from "./chunk-XAISOBBG.js";
8
+ } from "./chunk-TQRSVE7D.js";
18
9
  import {
19
10
  loadBrightsyConfig
20
11
  } from "./chunk-P2BSMNHB.js";
21
12
  import {
22
13
  httpFetch
23
14
  } from "./chunk-VKQGAWHY.js";
15
+ import {
16
+ extractJsonErrorMessage,
17
+ formatUnknownDetail,
18
+ looksLikeAgentFailureMessage,
19
+ looksLikeBrightsyEmptyCompletion,
20
+ looksLikeConversationSummary,
21
+ looksLikeSkillBody,
22
+ skillCommandFromBody,
23
+ withEventParentId
24
+ } from "./chunk-UKSJO36E.js";
25
+ import {
26
+ isOrchestratorThread
27
+ } from "./chunk-GZXKUUJO.js";
28
+ import {
29
+ codexUnattendedGitConfigArgs,
30
+ mergeAgentGitAuthEnv,
31
+ resolveAgentGitAuthEnv,
32
+ resolveCodexGitWritableRoots
33
+ } from "./chunk-NWE3NOWQ.js";
24
34
  import {
25
35
  enrichPathWithNpmGlobalBin,
26
36
  isConductorBundledCli,
@@ -37,7 +47,7 @@ import {
37
47
  loadAppSettings,
38
48
  resolveAgentExecutable,
39
49
  resolveClaudeExecutable
40
- } from "./chunk-36FOBJBF.js";
50
+ } from "./chunk-OIENQEGG.js";
41
51
  import {
42
52
  isElectronLikeCommand,
43
53
  unwrapStrippedElectronLaunch,
@@ -45,7 +55,7 @@ import {
45
55
  } from "./chunk-WWUABK6B.js";
46
56
  import {
47
57
  appDataDir
48
- } from "./chunk-Z2LGMV6C.js";
58
+ } from "./chunk-H5XL4KUS.js";
49
59
 
50
60
  // src/agents/brightsy.ts
51
61
  import { existsSync } from "fs";
@@ -80,377 +90,6 @@ function decodeBrightsyTarget(model) {
80
90
  return { type: "model", id: raw };
81
91
  }
82
92
 
83
- // src/agents/error-detail.ts
84
- function formatUnknownDetail(err) {
85
- if (err == null) return "";
86
- if (typeof err === "string") return err.trim();
87
- if (err instanceof Error) {
88
- const base = err.message.trim() || err.name;
89
- const code = "code" in err && typeof err.code === "string" ? err.code.trim() : "";
90
- return code && !base.includes(code) ? `${base} (${code})` : base;
91
- }
92
- if (typeof err === "object") {
93
- const o = err;
94
- const nested = o.error != null && typeof o.error === "object" ? formatUnknownDetail(o.error) : "";
95
- const message = typeof o.message === "string" ? o.message.trim() : typeof o.error === "string" ? o.error.trim() : typeof o.result === "string" ? o.result.trim() : nested;
96
- const code = typeof o.code === "string" ? o.code.trim() : "";
97
- if (message) return code && !message.includes(code) ? `${message} (${code})` : message;
98
- try {
99
- const json = JSON.stringify(err);
100
- if (json && json !== "{}" && json !== "null") return json;
101
- } catch {
102
- }
103
- }
104
- const fallback = String(err);
105
- return fallback === "[object Object]" ? "" : fallback;
106
- }
107
- function extractJsonErrorMessage(obj) {
108
- const nested = obj.error != null && typeof obj.error === "object" ? obj.error : null;
109
- const candidates = [
110
- typeof obj.message === "string" ? obj.message : null,
111
- typeof obj.error === "string" ? obj.error : null,
112
- nested && typeof nested.message === "string" ? nested.message : null,
113
- typeof obj.result === "string" ? obj.result : null,
114
- typeof obj.detail === "string" ? obj.detail : null
115
- ];
116
- for (const c of candidates) {
117
- const t = c?.trim();
118
- if (t) return t;
119
- }
120
- if (Array.isArray(obj.errors)) {
121
- const parts = obj.errors.map((e) => formatUnknownDetail(e)).map((s) => s.trim()).filter(Boolean);
122
- if (parts.length) return parts.join("; ");
123
- }
124
- return null;
125
- }
126
- var NODE_VERSION_FOOTER = /^Node\.js v\d+/i;
127
- function isPinnedStderrLine(line) {
128
- if (/^\s*at\s/.test(line)) return false;
129
- return /cannot find (?:package|module)|ERR_MODULE_NOT_FOUND|cursor startup failed:|FATAL ERROR|heap out of memory|javascript heap|OOMErrorHandler|FatalProcessOutOfMemory/i.test(
130
- line
131
- );
132
- }
133
- function pushTurnStderr(tail, line, maxLines = 12) {
134
- const trimmed = line.trim();
135
- if (!trimmed) return;
136
- if (NODE_VERSION_FOOTER.test(trimmed)) return;
137
- if (/^reconnecting\.\.\./i.test(trimmed)) return;
138
- tail.push(trimmed);
139
- while (tail.length > maxLines) {
140
- const dropIdx = tail.findIndex((l) => !isPinnedStderrLine(l));
141
- if (dropIdx === -1) tail.shift();
142
- else tail.splice(dropIdx, 1);
143
- }
144
- }
145
- function looksLikeMinifiedJsDump(line) {
146
- if (line.length < 200) return false;
147
- return /yield Promise\.all/.test(line) || /\(0,[A-Za-z$]\.\w+\)/.test(line) || /CURSOR_RIPGREP_PATH/.test(line) || /findFilesWithRipgrep/.test(line) || /@cursor\/sdk\/dist\//.test(line) || looksLikeCursorSdkSourceDump(line);
148
- }
149
- function looksLikeCursorSdkSourceDump(text) {
150
- const t = text.trim();
151
- if (t.length < 120) return false;
152
- return /cursor-runtime\/node_modules\/@cursor\/sdk/.test(t) || /importas [a-z] from"@bufbuild\/protobuf"/.test(t) || /file:\/\/[^\s]*@cursor\/sdk\/dist\/esm\/index\.js/.test(t);
153
- }
154
- function looksLikeHugeToolResultDump(text) {
155
- if (looksLikeCursorSdkSourceDump(text)) return true;
156
- const t = text.trim();
157
- if (t.length < 4e3) return false;
158
- return looksLikeMinifiedJsDump(t);
159
- }
160
- function looksLikeJobWaitResult(rec) {
161
- if (typeof rec.delta === "string") {
162
- return typeof rec.status === "string" || typeof rec.id === "string" || typeof rec.stillRunning === "boolean";
163
- }
164
- if (typeof rec.stopped === "boolean") {
165
- return typeof rec.id === "string" || typeof rec.status === "string";
166
- }
167
- return rec.started === true || rec.reason === "already-running";
168
- }
169
- function clipJobWaitResultJson(content) {
170
- const trimmed = content.trim();
171
- if (!trimmed.startsWith("{")) return void 0;
172
- try {
173
- const rec = JSON.parse(trimmed);
174
- if (!looksLikeJobWaitResult(rec)) return void 0;
175
- if (typeof rec.delta === "string" && rec.delta.length > 3500) {
176
- rec.delta = `\u2026(truncated ${rec.delta.length} chars)
177
- ${rec.delta.slice(-3500)}`;
178
- }
179
- if (typeof rec.progress === "string" && rec.progress.length > 800) {
180
- rec.progress = rec.progress.slice(-800);
181
- }
182
- if (typeof rec.hint === "string" && rec.hint.length > 240) {
183
- rec.hint = rec.hint.slice(0, 240);
184
- }
185
- let out = JSON.stringify(rec);
186
- if (out.length <= TOOL_RESULT_STORE_MAX_CHARS) return out;
187
- return JSON.stringify({
188
- stillRunning: rec.stillRunning,
189
- ok: rec.ok,
190
- failed: rec.failed,
191
- status: rec.status,
192
- id: rec.id,
193
- phase: rec.phase,
194
- delta: typeof rec.delta === "string" ? rec.delta.slice(-2500) : ""
195
- });
196
- } catch {
197
- return void 0;
198
- }
199
- }
200
- function clipToolResultForStore(content) {
201
- if (content == null) return void 0;
202
- if (looksLikeCursorSdkSourceDump(content) || looksLikeMinifiedJsDump(content)) {
203
- return `${HUGE_TOOL_RESULT_SUMMARY} (${content.length} chars omitted)`;
204
- }
205
- const jobClipped = clipJobWaitResultJson(content);
206
- if (jobClipped) return jobClipped;
207
- if (content.length <= TOOL_RESULT_STORE_MAX_CHARS) return content;
208
- const head = 5e3;
209
- const tail = 2e3;
210
- return `${content.slice(0, head)}
211
-
212
- \u2026(truncated ${content.length} chars \u2014 write output to .context/cli/ and read a slice)
213
-
214
- ${content.slice(-tail)}`;
215
- }
216
- function looksLikeNestedElectronCrash(line) {
217
- return /HasCustomHostObject|ElectronInitializeICUandStartNode/i.test(line);
218
- }
219
- function looksLikeNativeEventLoopCrash(text) {
220
- return /uv_run|uv__io_poll|SpinEventLoopInternal/i.test(text);
221
- }
222
- function looksLikeV8Oom(text) {
223
- return /javascript heap|reached heap limit|OOMErrorHandler|FatalProcessOutOfMemory|Allocation failed - JavaScript heap/i.test(
224
- text
225
- );
226
- }
227
- function looksLikeHomebrewLibuvCrash(text) {
228
- if (!looksLikeNativeEventLoopCrash(text)) return false;
229
- return /Cellar\/(?:libuv|node)|libuv\.\d+\.dylib/i.test(text);
230
- }
231
- var NESTED_ELECTRON_SUMMARY = "Cursor local agent crashed at Electron startup (nested Chromium / HasCustomHostObject)";
232
- var HOMEBREW_LIBUV_SUMMARY = "Cursor runner crashed in Node (Homebrew Node + shared libuv). Install Node 24 LTS (`brew install node@24`) and retry.";
233
- var BUNDLED_NODE_CRASH_SUMMARY = "Cursor runner crashed in Node. Retry the turn.";
234
- var V8_OOM_SUMMARY = "Agent ran out of memory (JavaScript heap). If it keeps happening, exclude large files from the project folder.";
235
- var MINIFIED_DUMP_SUMMARY = "Cursor local agent crashed during startup (truncated crash dump)";
236
- var HUGE_TOOL_RESULT_SUMMARY = "Agent crashed mid-turn after a huge tool result. Write CLI/HTTP output to .context/cli/ and read a slice \u2014 never dump raw --json/--expand into the tool result.";
237
- var TOOL_RESULT_STORE_MAX_CHARS = 8e3;
238
- function clipStderr(text, maxChars) {
239
- const trimmed = text.trim();
240
- if (trimmed.length <= maxChars) return trimmed;
241
- return trimmed.slice(0, maxChars);
242
- }
243
- function summarizeTurnStderr(tail, maxChars = 500) {
244
- if (tail.length === 0) return "";
245
- const cursorStartup = [...tail].reverse().find((line) => /cursor startup failed:/i.test(line));
246
- if (cursorStartup) return clipStderr(cursorStartup, maxChars);
247
- const cursorRunFailed = [...tail].reverse().find((line) => /^cursor run failed\b/i.test(line.trim()));
248
- if (cursorRunFailed) return clipStderr(cursorRunFailed, maxChars);
249
- if (tail.some(looksLikeNestedElectronCrash)) return NESTED_ELECTRON_SUMMARY;
250
- const blob = tail.join("\n");
251
- if (looksLikeV8Oom(blob)) return V8_OOM_SUMMARY;
252
- if (looksLikeHomebrewLibuvCrash(blob)) return HOMEBREW_LIBUV_SUMMARY;
253
- if (looksLikeNativeEventLoopCrash(blob)) {
254
- return BUNDLED_NODE_CRASH_SUMMARY;
255
- }
256
- if (tail.some(
257
- (line) => /\[resource_exhausted\]|resource_exhausted/i.test(line) || /findFilesWithRipgrep/.test(line)
258
- )) {
259
- return clipStderr(
260
- "Cursor local file search failed (ripgrep / resource_exhausted). Wait a minute and retry; if it keeps happening, check Cursor usage.",
261
- maxChars
262
- );
263
- }
264
- const moduleMissing = [...tail].reverse().find((line) => /cannot find (?:package|module)/i.test(line));
265
- if (moduleMissing) return clipStderr(moduleMissing, maxChars);
266
- if (tail.some(looksLikeHugeToolResultDump)) {
267
- return HUGE_TOOL_RESULT_SUMMARY;
268
- }
269
- const useful = tail.filter((line) => !looksLikeMinifiedJsDump(line));
270
- if (useful.length === 0 && tail.some(looksLikeMinifiedJsDump)) {
271
- return MINIFIED_DUMP_SUMMARY;
272
- }
273
- const joined = (useful.length ? useful : tail).slice(-6).join("\n").trim();
274
- return clipStderr(joined, maxChars);
275
- }
276
- function looksLikeInvalidAgentSession(text) {
277
- const lower = text.trim().toLowerCase();
278
- if (!lower) return false;
279
- return /session not found/.test(lower) || /no conversation found/.test(lower) || /conversation .+ not found/.test(lower) || /thread .+ not found/.test(lower) || /unknown session/.test(lower) || /invalid session/.test(lower) || /session .+ (missing|expired|deleted|gone)/.test(lower) || /cannot resume/.test(lower) || /failed to (load|resume|open) session/.test(lower) || /corrupt local agent checkpoint/.test(lower) || /missing root blob/.test(lower) || /\bagent\b.{0,120}\bnot found\b/.test(lower) || /\brun\b.{0,80}\bnot found for agent\b/.test(lower);
280
- }
281
- function looksLikeCursorHttp2StreamClose(text) {
282
- return /nghttp2/i.test(text.trim());
283
- }
284
- function looksLikeBrightsyEmptyCompletion(text) {
285
- const core = text.trim().replace(/^exit\s*\d+:\s*/i, "").replace(/^error:\s*/i, "").trim();
286
- return /^i did not receive a valid model response\. please try again\.$/i.test(core);
287
- }
288
- function looksLikeRetryableRunnerCrash(text) {
289
- if (looksLikeAgentFailureMessage(text)) return false;
290
- if (looksLikeInvalidAgentSession(text)) return false;
291
- if (looksLikeV8Oom(text)) return false;
292
- if (looksLikeHugeToolResultDump(text)) return true;
293
- if (looksLikeCursorHttp2StreamClose(text)) return true;
294
- if (looksLikeBrightsyEmptyCompletion(text)) return true;
295
- const lower = text.trim().toLowerCase();
296
- if (/cannot find (?:package|module)|err_module_not_found/.test(lower)) return false;
297
- if (!lower) return true;
298
- return /uv_run|spineventloopinternal|libuv|homebrew node \+ shared libuv|cursor runner crashed in node|hascustomhostobject|electroninitializeicuandstartnode|nested chromium|truncated crash dump|huge tool result|cursor sdk crashed mid-turn|connection stalled|network request failed|cursor startup failed:.+\(retryable\)|sig(?:segv|abrt|ill)|segmentation fault|illegal instruction|fatal error/.test(
299
- lower
300
- );
301
- }
302
- function shouldRetryFailedAgentTurn(detail, opts) {
303
- if (looksLikeInvalidAgentSession(detail) && opts.hasSession) return true;
304
- if (looksLikeV8Oom(detail) && opts.hasSession) return true;
305
- return looksLikeRetryableRunnerCrash(detail);
306
- }
307
- function looksLikeAgentFailureMessage(text) {
308
- const lower = text.trim().toLowerCase();
309
- if (!lower) return false;
310
- return /you've hit your|hit your (session|weekly|opus) limit|usage limit/.test(lower) || /credit balance is too low|out of credits|insufficient.?quota|quota.?exceeded/.test(lower) || /invalid user api key|invalid api key|not logged in|not authenticated|unauthorized/.test(
311
- lower
312
- ) || /\b429\b|too many requests|rate.?limit/.test(lower) || /prompt is too long|context.*(too long|exceed)|conversation too long/.test(lower) || /\[resource_exhausted\]|resource_exhausted/.test(lower) || /findFilesWithRipgrep/.test(text);
313
- }
314
- function fallbackTurnFailDetail(assistantText) {
315
- const t = assistantText.trim();
316
- if (!t) return "";
317
- if (looksLikeHugeToolResultDump(t)) return HUGE_TOOL_RESULT_SUMMARY;
318
- if (looksLikeAgentFailureMessage(t)) return t;
319
- if (t.length <= 400 && !/\n\n/.test(t)) return t;
320
- return "";
321
- }
322
- function humanizeAgentFailDetail(detail) {
323
- const raw = detail.trim();
324
- if (!raw) return raw;
325
- const lower = raw.toLowerCase();
326
- if (/credit balance is too low|out of credits|insufficient.?quota|quota.?exceeded|billing/.test(lower)) {
327
- return `${raw} \u2014 add credits or switch auth, then retry.`;
328
- }
329
- if (/hit your (session|weekly|opus) limit|usage limit|you've hit your/.test(lower)) {
330
- return raw.includes("reset") ? raw : `${raw} \u2014 wait for the limit window to reset, then retry.`;
331
- }
332
- if (/\b429\b|rate.?limit|too many requests/.test(lower)) {
333
- return `${raw} \u2014 wait a moment and retry.`;
334
- }
335
- if (/\[resource_exhausted\]|resource_exhausted|findfileswithripgrep/.test(lower)) {
336
- return "Cursor local file search failed (ripgrep / resource_exhausted). Wait a minute and retry; if it keeps happening, check Cursor usage.";
337
- }
338
- if (looksLikeCodexMcpError(raw)) {
339
- return `${raw} \u2014 skip that vendor MCP and continue (PostHog: Settings \u2192 Connectors + HTTP API).`;
340
- }
341
- if (/invalid user api key|invalid api key|not logged in|not authenticated|unauthorized|authentication|please run.*login|codex login|claude auth|cursor api/.test(
342
- lower
343
- )) {
344
- return `${raw} \u2014 check agent login / API key in Settings.`;
345
- }
346
- if (/model .{0,80}(not found|unavailable|unknown|invalid)/.test(lower)) {
347
- return `${raw} \u2014 pick another model in the agent options.`;
348
- }
349
- if (/context.*(too long|exceed)|prompt is too long|conversation too long/.test(lower)) {
350
- return `${raw} \u2014 start a new chat or compact context, then retry.`;
351
- }
352
- if (/hascustomhostobject|electroninitializeicuandstartnode|nested chromium/i.test(lower)) {
353
- return `${raw} \u2014 retry the turn; if it keeps failing, pick another agent.`;
354
- }
355
- if (looksLikeV8Oom(raw) || /javascript heap out of memory/i.test(lower)) {
356
- return /ran out of memory/i.test(raw) ? raw : V8_OOM_SUMMARY;
357
- }
358
- if (/homebrew node \+ shared libuv|Cellar\/(?:libuv|node)|libuv\.\d+\.dylib/i.test(raw)) {
359
- return /brew install node@(?:22|24)/i.test(raw) ? raw : `${raw} \u2014 install Node 24 LTS (\`brew install node@24\`) and retry.`;
360
- }
361
- if (/uv_run|spineventloopinternal|uv__io_poll|cursor runner crashed in node/i.test(lower)) {
362
- return /retry the turn/i.test(raw) ? raw : BUNDLED_NODE_CRASH_SUMMARY;
363
- }
364
- if (looksLikeHugeToolResultDump(raw) || /huge tool result|cursor sdk crashed mid-turn/.test(lower)) {
365
- return HUGE_TOOL_RESULT_SUMMARY;
366
- }
367
- if (/corrupt local agent checkpoint|missing root blob|truncated crash dump/.test(lower)) {
368
- return `${raw} \u2014 retry the turn (Sideboard will start a fresh Cursor session).`;
369
- }
370
- if (/connection stalled/.test(lower) || looksLikeCursorHttp2StreamClose(raw)) {
371
- return /retry the turn/i.test(raw) ? raw : `${raw} \u2014 retry the turn (Sideboard will start a fresh Cursor session).`;
372
- }
373
- if (looksLikeBrightsyEmptyCompletion(raw)) {
374
- return /retry the turn/i.test(raw) ? raw : `${raw} \u2014 retry the turn (Brightsy returned an empty model completion).`;
375
- }
376
- if (/network request failed|cursor startup failed:.+\(retryable\)/.test(lower)) {
377
- return /retry the turn/i.test(raw) ? raw : `${raw} \u2014 retry the turn (a transient Cursor SDK network error).`;
378
- }
379
- return raw;
380
- }
381
- function turnFailChatText(opts) {
382
- const chat = opts.assistantText.trim();
383
- if (opts.exitCode === 0) return chat;
384
- if (looksLikeHugeToolResultDump(chat)) {
385
- return HUGE_TOOL_RESULT_SUMMARY;
386
- }
387
- const detail = opts.detail.trim();
388
- const fail = detail ? humanizeAgentFailDetail(detail) : formatTurnExitError(opts.exitCode ?? 1, "");
389
- if (!chat) return fail;
390
- const failCore = fail.replace(/^exit\s*\d+:\s*/i, "").trim();
391
- if (looksLikeAgentFailureMessage(chat) || failCore && chat.includes(failCore) || chat.includes(fail)) {
392
- return chat;
393
- }
394
- return `${chat}
395
-
396
- ${fail}`;
397
- }
398
- function shouldRetryCodexPluginIsolate(detail, opts) {
399
- if (opts?.alreadyIsolated) return false;
400
- return looksLikeCodexMcpError(detail);
401
- }
402
- function looksLikeCodexMcpError(text) {
403
- const t = text.trim().toLowerCase();
404
- if (!t) return false;
405
- if (/authrequired|authorization required/.test(t) && /mcp|posthog|rmcp|connector|plugin/.test(t)) {
406
- return true;
407
- }
408
- if (/\bposthog\b/.test(t) && /mcp|oauth|auth|unauthorized|401|plugin|app/.test(t)) {
409
- return true;
410
- }
411
- if (/\brmcp\b/.test(t) && /fatal|quit|transport|error|died|kill|auth/.test(t)) {
412
- return true;
413
- }
414
- return /invalid transport in mcp_servers/.test(t);
415
- }
416
- function shouldFeedErrorBackToAgent(opts) {
417
- const detail = opts.detail.trim();
418
- const chat = (opts.assistantText ?? "").trim();
419
- if (looksLikeCodexMcpError(detail)) return true;
420
- if (looksLikeAgentFailureMessage(detail) || looksLikeAgentFailureMessage(chat)) {
421
- return false;
422
- }
423
- if (looksLikeInvalidAgentSession(detail) || looksLikeV8Oom(detail) || looksLikeRetryableRunnerCrash(detail)) {
424
- return true;
425
- }
426
- if (/without details|segfault|sig(?:segv|abrt|ill)|fatal error/i.test(detail)) {
427
- return true;
428
- }
429
- return !chat && (opts.partsCount ?? 0) === 0;
430
- }
431
- function formatAgentErrorContinuePrompt(detail) {
432
- const fail = humanizeAgentFailDetail(detail.trim()) || "the agent process exited without details";
433
- return [
434
- "The previous agent process ended before it finished. Error:",
435
- fail,
436
- "",
437
- "Continue from where you left off. Use the error to recover \u2014 do not restart the whole task unless the error requires it. If you cannot continue, say why."
438
- ].join("\n");
439
- }
440
- function formatTurnExitError(exitCode, stderrSummary) {
441
- const code = exitCode ?? 1;
442
- const raw = stderrSummary.trim();
443
- if (/^exit\s*\d+$/i.test(raw)) {
444
- return `exit ${code}: agent exited without details (credits, auth, rate limits, or a CLI error)`;
445
- }
446
- const detail = humanizeAgentFailDetail(raw);
447
- if (!detail) {
448
- return `exit ${code}: agent exited without details (credits, auth, rate limits, or a CLI error)`;
449
- }
450
- if (looksLikeAgentFailureMessage(raw)) return detail;
451
- return `exit ${code}: ${detail}`;
452
- }
453
-
454
93
  // src/agents/turn-input.ts
455
94
  function normalizeTurnInput(input) {
456
95
  if (typeof input === "string") return { prompt: input };
@@ -1741,819 +1380,6 @@ function toCodexUnattendedAppsArgs() {
1741
1380
  ];
1742
1381
  }
1743
1382
 
1744
- // src/agents/message-parts.ts
1745
- function asRecord(input) {
1746
- if (input && typeof input === "object" && !Array.isArray(input)) {
1747
- return input;
1748
- }
1749
- return void 0;
1750
- }
1751
- function str(v) {
1752
- return typeof v === "string" && v.trim() ? v : void 0;
1753
- }
1754
- var CHAT_DETAIL_MAX = 72;
1755
- function clipChatLine(value, max = CHAT_DETAIL_MAX) {
1756
- const line = value.trim().split(/\r?\n/, 1)[0] ?? "";
1757
- if (line.length <= max) return line;
1758
- return `${line.slice(0, Math.max(1, max - 1))}\u2026`;
1759
- }
1760
- function isSkillToolName(name) {
1761
- const n = (name ?? "").trim();
1762
- if (/^(Skill|SlashCommand)$/i.test(n)) return true;
1763
- return /(?:^|__)Skill$/i.test(n);
1764
- }
1765
- function skillCommandFromInput(input) {
1766
- const raw = str(input?.skill) ?? str(input?.command) ?? str(input?.name) ?? str(input?.skill_name) ?? str(input?.skillName);
1767
- if (raw) return raw.replace(/^\//, "").trim() || void 0;
1768
- const path = str(input?.file_path) ?? str(input?.path);
1769
- if (path && /SKILL\.md$/i.test(path)) {
1770
- const parts = path.replace(/\\/g, "/").split("/");
1771
- const dir = parts[parts.length - 2];
1772
- if (dir && dir !== "skills") return dir;
1773
- }
1774
- return void 0;
1775
- }
1776
- function looksLikeComposerSkillExpansion(text) {
1777
- const t = text.trim();
1778
- return /^## Skill: \//m.test(t) && /Follow this skill for the request above:/i.test(t);
1779
- }
1780
- var SKILL_FRONTMATTER_NAME = /^\s*name\s*:\s*['"]?([A-Za-z0-9][A-Za-z0-9._-]*)['"]?\s*$/m;
1781
- function skillNameFromFrontmatter(text) {
1782
- const t = text.trim();
1783
- if (!t) return void 0;
1784
- let yaml = t;
1785
- if (!yaml.startsWith("---")) {
1786
- const at = t.search(/(?:^|\n)---(?:\r?\n)/);
1787
- if (at < 0 || at > 800) return void 0;
1788
- yaml = t.slice(at).replace(/^\n/, "");
1789
- }
1790
- if (!yaml.startsWith("---")) return void 0;
1791
- const close = yaml.indexOf("\n---", 3);
1792
- if (close < 0) return void 0;
1793
- return yaml.slice(3, close).match(SKILL_FRONTMATTER_NAME)?.[1];
1794
- }
1795
- function skillCommandFromBody(text) {
1796
- return skillNameFromFrontmatter(text) ?? text.match(/^## Skill: \/([A-Za-z0-9][A-Za-z0-9._-]*)/m)?.[1] ?? text.match(/^Launching skill:\s*\/?([A-Za-z0-9][A-Za-z0-9._-]*)/im)?.[1];
1797
- }
1798
- function looksLikeSkillBody(text) {
1799
- const t = text.trim();
1800
- if (!t) return false;
1801
- if (looksLikeComposerSkillExpansion(t)) return true;
1802
- if (skillNameFromFrontmatter(t) != null) return true;
1803
- return /^Launching skill:/im.test(t) && /Base directory for this skill:/i.test(t);
1804
- }
1805
- function looksLikeIncompleteSkillDump(text) {
1806
- const t = text.trim();
1807
- if (!t || looksLikeSkillBody(t)) return false;
1808
- if (/^## Skill: \//m.test(t)) return true;
1809
- if (/^Launching skill:/im.test(t)) return true;
1810
- if (/Base directory for this skill:/i.test(t)) return true;
1811
- return t.startsWith("---") && SKILL_FRONTMATTER_NAME.test(t);
1812
- }
1813
- function isCompactToolName(name) {
1814
- const short = (name ?? "").replace(/^mcp__[^_]+__/, "").trim();
1815
- return /^(Compact|ConversationCompact|summarize_context|SummarizeContext|SummarizeConversation)$/i.test(
1816
- short
1817
- );
1818
- }
1819
- function isContextCompactDone(text) {
1820
- return /\bContext compressed\b/i.test(text.trim());
1821
- }
1822
- function isContextCompactInProgress(text) {
1823
- const t = text.trim();
1824
- if (isContextCompactDone(t)) return false;
1825
- return /^Compressing context/i.test(t);
1826
- }
1827
- function isSystemStatusThinking(event) {
1828
- if (event.replace) return true;
1829
- const t = (event.data ?? "").trim();
1830
- if (!t) return true;
1831
- if (/^API retry\b/i.test(t)) return true;
1832
- if (/^MCP:/i.test(t)) return true;
1833
- if (isContextCompactInProgress(t) || isContextCompactDone(t)) return true;
1834
- return false;
1835
- }
1836
- function looksLikeConversationSummary(text) {
1837
- const t = text.trim();
1838
- if (t.length < 80) return false;
1839
- if (/<summarized_conversation\b/i.test(t) || /<conversation_summary\b/i.test(t)) {
1840
- return true;
1841
- }
1842
- if (/this session is being continued from a previous conversation/i.test(t)) {
1843
- return true;
1844
- }
1845
- if (/conversation compacted|replaced with a summary/i.test(t)) return true;
1846
- if (/^## Prior summary\b/m.test(t)) return true;
1847
- if (/_Automatic extractive summary/i.test(t)) return true;
1848
- if (/"context_summary"\s*:/.test(t)) return true;
1849
- if (/^(?:#+\s*)?(?:conversation summary|summary of (?:the )?conversation|compacted (?:conversation|context))\b/im.test(
1850
- t
1851
- )) {
1852
- return true;
1853
- }
1854
- return false;
1855
- }
1856
- function toolDetail(name, input) {
1857
- if (isSkillToolName(name) || isCompactToolName(name)) return void 0;
1858
- if (!input) return void 0;
1859
- const command = str(input.command) ?? str(input.cmd);
1860
- if (command) return clipChatLine(command);
1861
- const pattern = str(input.pattern) ?? str(input.glob) ?? str(input.glob_pattern);
1862
- const isSearch = /grep|glob|search|ripgrep|findfiles|semsearch/i.test(name);
1863
- if (isSearch && pattern) {
1864
- return pattern.length > 80 ? `${pattern.slice(0, 77)}\u2026` : pattern;
1865
- }
1866
- const path = str(input.file_path) ?? str(input.path) ?? str(input.filePath) ?? str(input.filename);
1867
- if (path) return path;
1868
- if (pattern) return pattern.length > 80 ? `${pattern.slice(0, 77)}\u2026` : pattern;
1869
- const query = str(input.query) ?? str(input.prompt);
1870
- if (query) return query.length > 80 ? `${query.slice(0, 77)}\u2026` : query;
1871
- try {
1872
- const raw = JSON.stringify(input);
1873
- return raw.length > 80 ? `${raw.slice(0, 77)}\u2026` : raw;
1874
- } catch {
1875
- return name;
1876
- }
1877
- }
1878
- function toolDescription(name, input) {
1879
- const n = name.replace(/^mcp__/, "").replace(/__/g, " \xB7 ");
1880
- if (/^get_record_types$|recordTypes/i.test(name)) return "List record types";
1881
- if (/connectedAgentRequest/i.test(name)) {
1882
- return str(input?.agent_id) ? `Ask connected agent` : "Ask connected agent";
1883
- }
1884
- if (/present_artifact$/i.test(name)) {
1885
- return str(input?.title) ? `Present ${str(input?.title)}` : "Present artifact";
1886
- }
1887
- if (/present_plan$/i.test(name)) {
1888
- return str(input?.title) ? `Plan ${str(input?.title)}` : "Present plan";
1889
- }
1890
- if (/present_schema$/i.test(name)) {
1891
- return str(input?.title) ? `Schema ${str(input?.title)}` : "Present schema";
1892
- }
1893
- if (/present_files$/i.test(name)) {
1894
- return str(input?.title) ? `Files ${str(input?.title)}` : "Present files";
1895
- }
1896
- if (/wait_for_job$/i.test(name)) {
1897
- return str(input?.id) ? `Wait for ${str(input?.id)}` : "Wait for job";
1898
- }
1899
- if (/stop_job$/i.test(name)) {
1900
- return str(input?.id) ? `Stop ${str(input?.id)}` : "Stop job";
1901
- }
1902
- if (/list_run_scripts$/i.test(name)) return "List run scripts";
1903
- if (/run_dev_script$/i.test(name)) {
1904
- return str(input?.name) ? `Start ${str(input?.name)}` : "Start Dev script";
1905
- }
1906
- if (/stop_dev_script$/i.test(name)) {
1907
- return str(input?.name) ? `Stop ${str(input?.name)}` : "Stop Dev script";
1908
- }
1909
- if (/get_run_log$/i.test(name)) {
1910
- return str(input?.name) ? `Read ${str(input?.name)} log` : "Read Dev log";
1911
- }
1912
- if (/notify_orchestrator$/i.test(name)) return "Notify orchestrator";
1913
- if (/list_schedules$/i.test(name)) return "List schedules";
1914
- if (/create_schedule$/i.test(name)) {
1915
- return str(input?.name) ? `Schedule ${str(input?.name)}` : "Create schedule";
1916
- }
1917
- if (/update_schedule$/i.test(name)) return "Update schedule";
1918
- if (/delete_schedule$/i.test(name)) return "Delete schedule";
1919
- if (/run_schedule$/i.test(name)) return "Run schedule";
1920
- if (isSkillToolName(name)) {
1921
- const cmd = skillCommandFromInput(input);
1922
- return cmd ? `Using /${cmd}` : "Using skill";
1923
- }
1924
- if (isCompactToolName(name)) {
1925
- const trigger = str(input?.trigger);
1926
- if (trigger && !/^auto$/i.test(trigger) && trigger !== "injected") {
1927
- return `Summarized conversation (${trigger})`;
1928
- }
1929
- return "Summarized conversation";
1930
- }
1931
- if (isSubagentToolName(name)) {
1932
- const desc = str(input?.description);
1933
- const sub = asRecord(input?.subagentType);
1934
- const kind = str(sub?.name) ?? str(sub?.kind) ?? str(input?.subagent_type) ?? str(input?.subagentType);
1935
- if (/^spawn_agent$/i.test(name)) {
1936
- return str(input?.prompt) ?? desc ?? "Subagent";
1937
- }
1938
- if (/connectedAgentRequest/i.test(name)) {
1939
- return str(input?.agent_id) ? `Ask connected agent` : "Ask connected agent";
1940
- }
1941
- if (desc && kind) return `${kind}: ${desc}${subagentLiveSuffix(input)}`;
1942
- if (desc) return `${desc}${subagentLiveSuffix(input)}`;
1943
- return `Subagent${subagentLiveSuffix(input)}`;
1944
- }
1945
- if (/^(create|update)_artifact$/i.test(name.replace(/^mcp__[^_]+__/, ""))) {
1946
- return str(input?.title) ? `Artifact ${str(input?.title)}` : "Artifact";
1947
- }
1948
- if (!input) return n;
1949
- if (/bash|shell|terminal/i.test(name) && str(input.command)) {
1950
- const cmd = str(input.command);
1951
- if (/git\s+fetch/i.test(cmd)) return "Fetch latest from origin and check status";
1952
- if (/git\s+status/i.test(cmd)) return "Check git status";
1953
- if (/git\s+log/i.test(cmd)) return "Inspect recent commits";
1954
- if (/git\s+branch/i.test(cmd)) return "List branches";
1955
- if (/grep|rg\b/i.test(cmd)) return "Search repository";
1956
- return "Run shell command";
1957
- }
1958
- if (/edit|write|apply/i.test(name)) {
1959
- const path = str(input.file_path) ?? str(input.path);
1960
- return path ? `Edit ${path.split("/").pop()}` : "Edit file";
1961
- }
1962
- if (/read/i.test(name)) {
1963
- const path = str(input.file_path) ?? str(input.path);
1964
- return path ? `Read ${path.split("/").pop()}` : "Read file";
1965
- }
1966
- if (/grep/i.test(name)) return "Search files";
1967
- if (/glob/i.test(name)) return "Find files";
1968
- const compact = n.replace(/[_-]/g, "");
1969
- if (/^taskoutput$/i.test(compact)) {
1970
- return str(input.task_id) ? `Wait for ${str(input.task_id)}` : "Wait for background task";
1971
- }
1972
- if (/^taskstop$/i.test(compact)) {
1973
- return str(input.task_id) ? `Stop ${str(input.task_id)}` : "Stop background task";
1974
- }
1975
- if (/^monitor$/i.test(compact)) {
1976
- const command = str(input.command);
1977
- return command ? `Watch ${command.length > 48 ? `${command.slice(0, 45)}\u2026` : command}` : "Watch command";
1978
- }
1979
- return n;
1980
- }
1981
- function subagentLiveSuffix(input) {
1982
- if (!input) return "";
1983
- const bits = [];
1984
- const status = str(input.live_status);
1985
- if (status && !/^runn(ing)?$|^working$/i.test(status)) bits.push(status);
1986
- if (typeof input.live_tool_uses === "number") bits.push(`${input.live_tool_uses} tools`);
1987
- if (typeof input.live_duration_ms === "number") {
1988
- bits.push(`${Math.max(0, Math.round(Number(input.live_duration_ms) / 1e3))}s`);
1989
- }
1990
- const last = str(input.live_last_tool);
1991
- if (last) bits.push(last);
1992
- return bits.length ? ` \xB7 ${bits.join(" \xB7 ")}` : "";
1993
- }
1994
- function isSubagentToolName(name) {
1995
- const n = (name ?? "").trim();
1996
- if (/^(task|agent|spawn_agent)$/i.test(n)) return true;
1997
- return /connectedAgentRequest/i.test(n);
1998
- }
1999
- function isInternalAgentStatusText(text) {
2000
- const t = text.trim();
2001
- if (!t) return false;
2002
- if (/waiting for gate to pass/i.test(t)) return true;
2003
- if (/^agent is running\b/i.test(t) && t.length < 160) return true;
2004
- return false;
2005
- }
2006
- function isPollWrapperToolName(name) {
2007
- const n = (name ?? "").replace(/[_-]/g, "");
2008
- return /^(taskoutput|taskstop|sleep)$/i.test(n);
2009
- }
2010
- function lastTextPart(parts, type) {
2011
- for (let i = parts.length - 1; i >= 0; i--) {
2012
- const p = parts[i];
2013
- if (p.type !== type) continue;
2014
- const text = p.text.trim();
2015
- if (!text || isInternalAgentStatusText(text)) continue;
2016
- return text;
2017
- }
2018
- return "";
2019
- }
2020
- function toolLabel(tool) {
2021
- return tool.description || toolDescription(tool.name, tool.input) || tool.name;
2022
- }
2023
- function liveActivitySummary(parts, opts) {
2024
- if (opts?.queued && parts.length === 0) {
2025
- return "Queued \u2014 waiting for a slot";
2026
- }
2027
- const tools = parts.filter((p) => p.type === "tool");
2028
- const runningSubs = tools.filter(
2029
- (t) => t.status === "running" && !t.parentId && isSubagentToolName(t.name)
2030
- );
2031
- const runningNested = [...tools].reverse().find((t) => t.status === "running" && t.parentId && !isPollWrapperToolName(t.name));
2032
- const runningTop = [...tools].reverse().find(
2033
- (t) => t.status === "running" && !t.parentId && !isPollWrapperToolName(t.name) && !isSubagentToolName(t.name)
2034
- );
2035
- const runningPoll = [...tools].reverse().find((t) => t.status === "running" && isPollWrapperToolName(t.name));
2036
- const thinking = lastTextPart(parts, "thinking");
2037
- const text = lastTextPart(parts, "text");
2038
- if (runningSubs.length > 0) {
2039
- const heads = runningSubs.map(toolLabel);
2040
- const head = runningSubs.length === 1 ? heads[0] : `${runningSubs.length} subagents \xB7 ${heads.slice(0, 2).join(" \xB7 ")}`;
2041
- if (runningNested) return `${head} \xB7 ${toolLabel(runningNested)}`;
2042
- return head;
2043
- }
2044
- if (runningTop) return toolLabel(runningTop);
2045
- if (runningPoll) return toolLabel(runningPoll);
2046
- if (thinking) return thinking.length > 96 ? `\u2026${thinking.slice(-96)}` : thinking;
2047
- if (text) return "Writing reply\u2026";
2048
- const last = [...tools].reverse().find((t) => !isPollWrapperToolName(t.name)) ?? tools.at(-1);
2049
- if (last) {
2050
- const label = toolLabel(last);
2051
- return last.status === "running" ? label : `Finished ${label}`;
2052
- }
2053
- return "Working\u2026";
2054
- }
2055
- function messagePartParentId(part) {
2056
- if ("parentId" in part && typeof part.parentId === "string" && part.parentId.trim()) {
2057
- return part.parentId;
2058
- }
2059
- return void 0;
2060
- }
2061
- function sameParentId(a, b) {
2062
- return (a ?? "") === (b ?? "");
2063
- }
2064
- function withEventParentId(event, parentId) {
2065
- if (!parentId) return event;
2066
- if (event.type === "stdout" || event.type === "thinking" || event.type === "tool_use" || event.type === "tool_result") {
2067
- return { ...event, parentId: event.parentId ?? parentId };
2068
- }
2069
- return event;
2070
- }
2071
- function toolFilePath(input) {
2072
- if (!input) return void 0;
2073
- return str(input.file_path) ?? str(input.path) ?? str(input.filePath) ?? str(input.filename);
2074
- }
2075
- function countLines(text) {
2076
- if (!text) return 0;
2077
- return text.split("\n").length;
2078
- }
2079
- function diffFromInput(input) {
2080
- if (!input) return {};
2081
- const oldS = str(input.old_string) ?? str(input.oldString);
2082
- const newS = str(input.new_string) ?? str(input.newString) ?? str(input.content);
2083
- if (oldS != null || newS != null) {
2084
- return {
2085
- additions: countLines(newS),
2086
- deletions: countLines(oldS)
2087
- };
2088
- }
2089
- return {};
2090
- }
2091
- function parseDiffStat(result) {
2092
- if (!result) return {};
2093
- const paired = result.match(/\+(\d+)\s+-(\d+)/);
2094
- if (paired) {
2095
- return {
2096
- additions: Number(paired[1]),
2097
- deletions: Number(paired[2])
2098
- };
2099
- }
2100
- const verbose = result.match(
2101
- /(\d+)\s+insertions?(?:,\s*(\d+)\s+deletions?)?/i
2102
- );
2103
- if (verbose) {
2104
- return {
2105
- additions: Number(verbose[1]),
2106
- deletions: verbose[2] != null ? Number(verbose[2]) : void 0
2107
- };
2108
- }
2109
- return {};
2110
- }
2111
- var THINKING_PART_MAX_CHARS = 64e3;
2112
- function clipThinkingForStore(text, max = THINKING_PART_MAX_CHARS) {
2113
- if (text.length <= max) return text;
2114
- const marker = "\u2026(earlier thinking trimmed)\n";
2115
- return marker + text.slice(text.length - Math.max(1, max - marker.length));
2116
- }
2117
- var STDOUT_EVENT_MAX_CHARS = 16e3;
2118
- var STDERR_EVENT_MAX_CHARS = 4e3;
2119
- function clipEventTail(text, max) {
2120
- if (text.length <= max) return text;
2121
- const marker = "\u2026(truncated)\n";
2122
- return marker + text.slice(text.length - Math.max(1, max - marker.length));
2123
- }
2124
- function clipAgentEventForPaint(event) {
2125
- if (event.type === "tool_result" && event.content) {
2126
- const content = clipToolResultForStore(event.content);
2127
- if (content === event.content) return event;
2128
- return { ...event, content };
2129
- }
2130
- if (event.type === "thinking" && event.data.length > THINKING_PART_MAX_CHARS) {
2131
- return { ...event, data: clipThinkingForStore(event.data) };
2132
- }
2133
- if (event.type === "stdout" && event.data.length > STDOUT_EVENT_MAX_CHARS) {
2134
- return { ...event, data: clipEventTail(event.data, STDOUT_EVENT_MAX_CHARS) };
2135
- }
2136
- if (event.type === "stderr" && event.data.length > STDERR_EVENT_MAX_CHARS) {
2137
- return { ...event, data: clipEventTail(event.data, STDERR_EVENT_MAX_CHARS) };
2138
- }
2139
- return event;
2140
- }
2141
- function withPartTimes(next, prev) {
2142
- const now = Date.now();
2143
- const startedAt = prev && typeof prev.startedAt === "number" ? prev.startedAt : now;
2144
- return { ...next, startedAt, updatedAt: now };
2145
- }
2146
- function skillToolFromTextPart(part, id, status = "done") {
2147
- const command = skillCommandFromBody(part.text);
2148
- const input = command ? { skill: command } : void 0;
2149
- return {
2150
- type: "tool",
2151
- id: command ? `skill-${command}` : id,
2152
- name: "Skill",
2153
- input,
2154
- description: toolDescription("Skill", input),
2155
- status,
2156
- result: clipToolResultForStore(part.text),
2157
- ...part.parentId ? { parentId: part.parentId } : {},
2158
- startedAt: part.startedAt,
2159
- updatedAt: Date.now()
2160
- };
2161
- }
2162
- function lastSkillToolIndex(parts, parentId) {
2163
- for (let i = parts.length - 1; i >= 0; i--) {
2164
- const p = parts[i];
2165
- if (p.type === "tool" && isSkillToolName(p.name) && sameParentId(p.parentId, parentId)) {
2166
- return i;
2167
- }
2168
- }
2169
- return -1;
2170
- }
2171
- function lastRunningSkillIndex(parts, parentId) {
2172
- for (let i = parts.length - 1; i >= 0; i--) {
2173
- const p = parts[i];
2174
- if (p.type === "tool" && isSkillToolName(p.name) && p.status === "running" && sameParentId(p.parentId, parentId)) {
2175
- return i;
2176
- }
2177
- }
2178
- return -1;
2179
- }
2180
- function markRunningSkillsDone(parts, parentId) {
2181
- return parts.map((p) => {
2182
- if (p.type === "tool" && isSkillToolName(p.name) && p.status === "running" && sameParentId(p.parentId, parentId)) {
2183
- return withPartTimes({ ...p, status: "done" }, p);
2184
- }
2185
- return p;
2186
- });
2187
- }
2188
- function promoteOrFoldSkillText(parts, textIdx) {
2189
- const acc = parts[textIdx];
2190
- if (acc?.type !== "text") return parts;
2191
- const complete = looksLikeSkillBody(acc.text);
2192
- const incomplete = looksLikeIncompleteSkillDump(acc.text);
2193
- if (!complete && !incomplete) return parts;
2194
- const existing = lastSkillToolIndex(parts, acc.parentId);
2195
- if (existing >= 0 && existing !== textIdx) {
2196
- const prev = parts[existing];
2197
- const next2 = parts.filter((_, i) => i !== textIdx);
2198
- const existingIdx = lastSkillToolIndex(next2, acc.parentId);
2199
- if (existingIdx < 0) return parts;
2200
- next2[existingIdx] = withPartTimes(
2201
- {
2202
- ...prev,
2203
- status: complete ? "done" : prev.status,
2204
- result: clipToolResultForStore(acc.text) ?? prev.result
2205
- },
2206
- prev
2207
- );
2208
- return next2;
2209
- }
2210
- const next = [...parts];
2211
- next[textIdx] = skillToolFromTextPart(
2212
- acc,
2213
- `skill-${next.length}`,
2214
- complete ? "done" : "running"
2215
- );
2216
- return next;
2217
- }
2218
- function compactSummaryPart(text, id = "compact-summary") {
2219
- return compactToolPart(text, id, { status: "done" });
2220
- }
2221
- function compactToolPart(text, id, opts) {
2222
- const input = { trigger: opts?.trigger ?? "auto" };
2223
- return withPartTimes(
2224
- {
2225
- type: "tool",
2226
- id,
2227
- name: "Compact",
2228
- input,
2229
- description: toolDescription("Compact", input),
2230
- status: opts?.status ?? "done",
2231
- result: clipToolResultForStore(text) ?? "",
2232
- ...opts?.parentId ? { parentId: opts.parentId } : {}
2233
- },
2234
- opts?.prev
2235
- );
2236
- }
2237
- function contextCompactInProgress(parts, parentId) {
2238
- let compressing = false;
2239
- for (const p of parts) {
2240
- if (!sameParentId(p.parentId, parentId)) continue;
2241
- if (p.type === "thinking" && isContextCompactInProgress(p.text)) compressing = true;
2242
- if (p.type === "thinking" && isContextCompactDone(p.text)) compressing = false;
2243
- }
2244
- return compressing;
2245
- }
2246
- function lastRunningCompactIndex(parts, parentId) {
2247
- for (let i = parts.length - 1; i >= 0; i--) {
2248
- const p = parts[i];
2249
- if (p.type === "tool" && isCompactToolName(p.name) && p.status === "running" && sameParentId(p.parentId, parentId)) {
2250
- return i;
2251
- }
2252
- }
2253
- return -1;
2254
- }
2255
- function markRunningCompactDone(parts, parentId) {
2256
- return parts.map((p) => {
2257
- if (p.type === "tool" && isCompactToolName(p.name) && p.status === "running" && sameParentId(p.parentId, parentId)) {
2258
- return withPartTimes({ ...p, status: "done" }, p);
2259
- }
2260
- return p;
2261
- });
2262
- }
2263
- function ensureCompactTool(parts, parentId) {
2264
- const hasCompact = parts.some(
2265
- (p) => p.type === "tool" && isCompactToolName(p.name) && sameParentId(p.parentId, parentId)
2266
- );
2267
- if (hasCompact) return parts;
2268
- return [
2269
- ...parts,
2270
- compactToolPart("Context compressed", `compact-${parts.length}`, {
2271
- parentId,
2272
- status: "done"
2273
- })
2274
- ];
2275
- }
2276
- function withCompactFinish(parts, thinking, parentId) {
2277
- if (!isContextCompactDone(thinking)) return parts;
2278
- return ensureCompactTool(markRunningCompactDone(parts, parentId), parentId);
2279
- }
2280
- function applyAgentEvent(parts, event) {
2281
- if (event.type === "stdout") {
2282
- const data = event.data;
2283
- if (!data) return parts;
2284
- const runningIdx = lastRunningCompactIndex(parts, event.parentId);
2285
- if (runningIdx >= 0) {
2286
- const prev = parts[runningIdx];
2287
- const next2 = [...parts];
2288
- next2[runningIdx] = withPartTimes(
2289
- {
2290
- ...prev,
2291
- result: clipToolResultForStore(`${prev.result ?? ""}${data}`)
2292
- },
2293
- prev
2294
- );
2295
- return next2;
2296
- }
2297
- const runningSkillIdx = lastRunningSkillIndex(parts, event.parentId);
2298
- if (runningSkillIdx >= 0) {
2299
- const prev = parts[runningSkillIdx];
2300
- const result = `${prev.result ?? ""}${data}`;
2301
- const next2 = [...parts];
2302
- next2[runningSkillIdx] = withPartTimes(
2303
- {
2304
- ...prev,
2305
- result: clipToolResultForStore(result),
2306
- // Stay running after the YAML `name:` fence so later content_block_delta
2307
- // tokens of SKILL.md stay on this row. thinking / tool_use / finalizeParts
2308
- // mark the row done so the real reply can be chat.
2309
- status: "running"
2310
- },
2311
- prev
2312
- );
2313
- return next2;
2314
- }
2315
- if (contextCompactInProgress(parts, event.parentId)) {
2316
- return [
2317
- ...parts,
2318
- compactToolPart(data, `compact-${parts.length}`, {
2319
- parentId: event.parentId,
2320
- status: "running"
2321
- })
2322
- ];
2323
- }
2324
- const next = [...parts];
2325
- const last = next[next.length - 1];
2326
- if (last?.type === "text" && sameParentId(last.parentId, event.parentId)) {
2327
- next[next.length - 1] = withPartTimes(
2328
- {
2329
- type: "text",
2330
- text: last.text + data,
2331
- ...event.parentId ? { parentId: event.parentId } : {}
2332
- },
2333
- last
2334
- );
2335
- } else {
2336
- next.push(
2337
- withPartTimes({
2338
- type: "text",
2339
- text: data,
2340
- ...event.parentId ? { parentId: event.parentId } : {}
2341
- })
2342
- );
2343
- }
2344
- const acc = next[next.length - 1];
2345
- if (acc?.type === "text" && (looksLikeSkillBody(acc.text) || looksLikeIncompleteSkillDump(acc.text))) {
2346
- return promoteOrFoldSkillText(next, next.length - 1);
2347
- }
2348
- if (acc?.type === "text" && looksLikeConversationSummary(acc.text)) {
2349
- next[next.length - 1] = compactToolPart(acc.text, `compact-${next.length}`, {
2350
- parentId: acc.parentId,
2351
- status: "done",
2352
- prev: acc
2353
- });
2354
- }
2355
- return next;
2356
- }
2357
- if (event.type === "thinking") {
2358
- const data = event.data;
2359
- if (!data) return parts;
2360
- if (!isSystemStatusThinking(event)) {
2361
- parts = markRunningSkillsDone(parts, event.parentId);
2362
- }
2363
- const next = [...parts];
2364
- if (event.replace) {
2365
- for (let i = next.length - 1; i >= 0; i--) {
2366
- const prev = next[i];
2367
- if (prev?.type === "thinking" && sameParentId(prev.parentId, event.parentId)) {
2368
- next[i] = withPartTimes(
2369
- {
2370
- type: "thinking",
2371
- text: clipThinkingForStore(data),
2372
- ...event.parentId ? { parentId: event.parentId } : {}
2373
- },
2374
- prev
2375
- );
2376
- return withCompactFinish(next, data, event.parentId);
2377
- }
2378
- }
2379
- next.push(
2380
- withPartTimes({
2381
- type: "thinking",
2382
- text: clipThinkingForStore(data),
2383
- ...event.parentId ? { parentId: event.parentId } : {}
2384
- })
2385
- );
2386
- return withCompactFinish(next, data, event.parentId);
2387
- }
2388
- const last = next[next.length - 1];
2389
- if (last?.type === "thinking" && sameParentId(last.parentId, event.parentId)) {
2390
- next[next.length - 1] = withPartTimes(
2391
- {
2392
- type: "thinking",
2393
- text: clipThinkingForStore(last.text + data),
2394
- ...event.parentId ? { parentId: event.parentId } : {}
2395
- },
2396
- last
2397
- );
2398
- } else {
2399
- next.push(
2400
- withPartTimes({
2401
- type: "thinking",
2402
- text: clipThinkingForStore(data),
2403
- ...event.parentId ? { parentId: event.parentId } : {}
2404
- })
2405
- );
2406
- }
2407
- return withCompactFinish(next, data, event.parentId);
2408
- }
2409
- if (event.type === "tool_use") {
2410
- parts = markRunningSkillsDone(parts, event.parentId);
2411
- const input = asRecord(event.input);
2412
- const diff = diffFromInput(input);
2413
- const existing = parts.findIndex((p) => p.type === "tool" && p.id === event.id);
2414
- if (existing >= 0) {
2415
- const prev = parts[existing];
2416
- const next = [...parts];
2417
- const mergedInput = {
2418
- ...prev.input ?? {},
2419
- ...input ?? {}
2420
- };
2421
- const mergedRecord = Object.keys(mergedInput).length > 0 ? mergedInput : void 0;
2422
- next[existing] = withPartTimes(
2423
- {
2424
- ...prev,
2425
- name: event.name || prev.name,
2426
- input: mergedRecord,
2427
- description: toolDescription(event.name || prev.name, mergedRecord),
2428
- detail: toolDetail(event.name || prev.name, mergedRecord) ?? prev.detail,
2429
- filePath: toolFilePath(mergedRecord) ?? prev.filePath,
2430
- additions: diff.additions ?? prev.additions,
2431
- deletions: diff.deletions ?? prev.deletions,
2432
- parentId: event.parentId ?? prev.parentId
2433
- },
2434
- prev
2435
- );
2436
- return next;
2437
- }
2438
- return [
2439
- ...parts,
2440
- withPartTimes({
2441
- type: "tool",
2442
- id: event.id,
2443
- name: event.name,
2444
- input,
2445
- description: toolDescription(event.name, input),
2446
- detail: toolDetail(event.name, input),
2447
- status: "running",
2448
- filePath: toolFilePath(input),
2449
- ...event.parentId ? { parentId: event.parentId } : {},
2450
- ...diff
2451
- })
2452
- ];
2453
- }
2454
- if (event.type === "tool_result") {
2455
- const existing = parts.findIndex((p) => p.type === "tool" && p.id === event.id);
2456
- const fromResult = parseDiffStat(event.content);
2457
- if (event.partial) {
2458
- if (existing < 0) {
2459
- return [
2460
- ...parts,
2461
- withPartTimes({
2462
- type: "tool",
2463
- id: event.id,
2464
- name: "tool",
2465
- description: "tool",
2466
- status: event.isError ? "error" : "running",
2467
- result: clipToolResultForStore(event.content),
2468
- ...event.parentId ? { parentId: event.parentId } : {}
2469
- })
2470
- ];
2471
- }
2472
- return parts.map((p, i) => {
2473
- if (i !== existing || p.type !== "tool") return p;
2474
- if (p.status === "done" || p.status === "error") return p;
2475
- return withPartTimes(
2476
- {
2477
- ...p,
2478
- result: clipToolResultForStore(event.content) ?? p.result
2479
- },
2480
- p
2481
- );
2482
- });
2483
- }
2484
- if (existing < 0) {
2485
- return [
2486
- ...parts,
2487
- withPartTimes({
2488
- type: "tool",
2489
- id: event.id,
2490
- name: "tool",
2491
- description: "tool",
2492
- status: event.isError ? "error" : "done",
2493
- result: clipToolResultForStore(event.content),
2494
- ...event.parentId ? { parentId: event.parentId } : {},
2495
- ...fromResult.additions != null ? { additions: fromResult.additions } : {},
2496
- ...fromResult.deletions != null ? { deletions: fromResult.deletions } : {}
2497
- })
2498
- ];
2499
- }
2500
- return parts.map((p, i) => {
2501
- if (i !== existing || p.type !== "tool") return p;
2502
- return withPartTimes(
2503
- {
2504
- ...p,
2505
- status: event.isError ? "error" : "done",
2506
- result: clipToolResultForStore(event.content),
2507
- ...fromResult.additions != null ? { additions: fromResult.additions } : {},
2508
- ...fromResult.deletions != null ? { deletions: fromResult.deletions } : {}
2509
- },
2510
- p
2511
- );
2512
- });
2513
- }
2514
- return parts;
2515
- }
2516
- function partsToAssistantText(parts) {
2517
- return parts.filter(
2518
- (p) => p.type === "text" && !messagePartParentId(p)
2519
- ).map((p) => p.text).join("").trim();
2520
- }
2521
- function lastAssistantMessageText(parts) {
2522
- if (!parts?.length) return "";
2523
- for (let i = parts.length - 1; i >= 0; i--) {
2524
- const p = parts[i];
2525
- if (!p || p.type !== "text" || messagePartParentId(p)) continue;
2526
- const text = p.text.trim();
2527
- if (!text || isInternalAgentStatusText(text)) continue;
2528
- return text;
2529
- }
2530
- return "";
2531
- }
2532
- function stripBrightsyNdjsonNoise(text) {
2533
- if (!text || !text.includes('"type"')) return text;
2534
- let out = text;
2535
- out = out.replace(
2536
- /\{"type":"(?:tool_use|tool_result|tool|thinking|usage|done|error)"[\s\S]*?\}\s*(?=\{"type":"|$|(?=[A-Za-z*#]))/g,
2537
- ""
2538
- );
2539
- out = out.replace(/\{"type":"(?:tool_use|tool_result|tool)"[\s\S]*$/g, "");
2540
- return out.trim();
2541
- }
2542
- function isBrightsyNdjsonLine(line) {
2543
- const t = line.trim();
2544
- if (!t.startsWith("{")) return false;
2545
- return /"type"\s*:\s*"(tool_use|tool_result|tool|thinking|usage|done|error|text)"/.test(t);
2546
- }
2547
- function finalizeParts(parts) {
2548
- return parts.map(
2549
- (p) => p.type === "tool" && p.status === "running" ? { ...p, status: "done" } : p
2550
- );
2551
- }
2552
- function normalizeParseResult(parsed) {
2553
- if (!parsed) return [];
2554
- return Array.isArray(parsed) ? parsed : [parsed];
2555
- }
2556
-
2557
1383
  // src/agents/types.ts
2558
1384
  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.";
2559
1385
  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.";
@@ -3184,7 +2010,7 @@ var claudeAdapter = {
3184
2010
  );
3185
2011
  }
3186
2012
  const mode = permissionMode(thread);
3187
- const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-6LDUZ2NF.js");
2013
+ const { isOrchestratorThread: isOrchestratorThread2 } = await import("./global-workspace-EWFL4HPW.js");
3188
2014
  const isOrchestrator = isOrchestratorThread2(thread);
3189
2015
  const rpc = worktreeAgentRpc(isOrchestrator);
3190
2016
  const injectedServers = await buildInjectedMcpServers({
@@ -3532,7 +2358,7 @@ function unwrapCodexMcpResult(result) {
3532
2358
  return String(result);
3533
2359
  }
3534
2360
  }
3535
- function asRecord2(value) {
2361
+ function asRecord(value) {
3536
2362
  if (value && typeof value === "object" && !Array.isArray(value)) {
3537
2363
  return value;
3538
2364
  }
@@ -3685,7 +2511,7 @@ var codexAdapter = {
3685
2511
  }
3686
2512
  if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
3687
2513
  const name = `mcp__${item.server}__${item.tool}`;
3688
- const input = asRecord2(item.arguments);
2514
+ const input = asRecord(item.arguments);
3689
2515
  const events = [
3690
2516
  { type: "tool_use", id: item.id, name, input }
3691
2517
  ];
@@ -3986,20 +2812,20 @@ function turnCostUsdFromCursorUsage(before, after) {
3986
2812
  if (!(delta >= 0) || !Number.isFinite(delta)) return void 0;
3987
2813
  return delta / 100;
3988
2814
  }
3989
- function asRecord3(value) {
2815
+ function asRecord2(value) {
3990
2816
  if (value && typeof value === "object" && !Array.isArray(value)) {
3991
2817
  return value;
3992
2818
  }
3993
2819
  return void 0;
3994
2820
  }
3995
2821
  function normalizeCursorToolCall(name, args) {
3996
- const raw = asRecord3(args);
2822
+ const raw = asRecord2(args);
3997
2823
  const toolName = typeof raw?.toolName === "string" && raw.toolName.trim() ? raw.toolName.trim() : null;
3998
- const looksLikeMcp = name === "mcp" || toolName != null && (typeof raw?.providerIdentifier === "string" || asRecord3(raw?.args) != null);
2824
+ const looksLikeMcp = name === "mcp" || toolName != null && (typeof raw?.providerIdentifier === "string" || asRecord2(raw?.args) != null);
3999
2825
  if (looksLikeMcp && toolName) {
4000
2826
  const providerRaw = typeof raw.providerIdentifier === "string" && raw.providerIdentifier.trim() ? raw.providerIdentifier.trim() : "sideboard";
4001
2827
  const provider = providerRaw.replace(/[^a-zA-Z0-9_-]/g, "_");
4002
- const nested = asRecord3(raw.args);
2828
+ const nested = asRecord2(raw.args);
4003
2829
  return {
4004
2830
  name: `mcp__${provider}__${toolName}`,
4005
2831
  input: nested ?? { toolName }
@@ -4010,7 +2836,7 @@ function normalizeCursorToolCall(name, args) {
4010
2836
  function unwrapCursorToolResult(result) {
4011
2837
  if (result == null) return void 0;
4012
2838
  if (typeof result === "string") return result;
4013
- const rec = asRecord3(result);
2839
+ const rec = asRecord2(result);
4014
2840
  if (!rec) {
4015
2841
  try {
4016
2842
  return JSON.stringify(result);
@@ -4021,18 +2847,18 @@ function unwrapCursorToolResult(result) {
4021
2847
  const collectTexts = (items) => {
4022
2848
  const texts = [];
4023
2849
  for (const item of items) {
4024
- const row = asRecord3(item);
2850
+ const row = asRecord2(item);
4025
2851
  if (!row) continue;
4026
2852
  if (typeof row.text === "string") {
4027
2853
  texts.push(row.text);
4028
2854
  continue;
4029
2855
  }
4030
- const nested = asRecord3(row.text);
2856
+ const nested = asRecord2(row.text);
4031
2857
  if (typeof nested?.text === "string") texts.push(nested.text);
4032
2858
  }
4033
2859
  return texts;
4034
2860
  };
4035
- const value = asRecord3(rec.value);
2861
+ const value = asRecord2(rec.value);
4036
2862
  if (value && Array.isArray(value.content)) {
4037
2863
  const texts = collectTexts(value.content);
4038
2864
  if (texts.length) return texts.join("\n");
@@ -4049,10 +2875,10 @@ function unwrapCursorToolResult(result) {
4049
2875
  }
4050
2876
  function cursorToolResultIsError(status, result) {
4051
2877
  if (status === "error") return true;
4052
- const rec = asRecord3(result);
2878
+ const rec = asRecord2(result);
4053
2879
  if (!rec) return false;
4054
2880
  if (rec.status === "error") return true;
4055
- const value = asRecord3(rec.value);
2881
+ const value = asRecord2(rec.value);
4056
2882
  return value?.isError === true;
4057
2883
  }
4058
2884
  function cursorSdkMessageToEvents(msg) {
@@ -4553,17 +3379,17 @@ var FALLBACK_OPENCODE_MODELS = [
4553
3379
  ];
4554
3380
  var cachedOpencodeModels = null;
4555
3381
  var OPENCODE_MODEL_CACHE_MS = 5 * 60 * 1e3;
4556
- function asRecord4(value) {
3382
+ function asRecord3(value) {
4557
3383
  if (value && typeof value === "object" && !Array.isArray(value)) {
4558
3384
  return value;
4559
3385
  }
4560
3386
  return void 0;
4561
3387
  }
4562
- function str2(v) {
3388
+ function str(v) {
4563
3389
  return typeof v === "string" && v.trim() ? v.trim() : void 0;
4564
3390
  }
4565
3391
  function opencodeToolId(name, callId, metadata) {
4566
- const sessionId = str2(metadata?.sessionId) ?? str2(metadata?.sessionID);
3392
+ const sessionId = str(metadata?.sessionId) ?? str(metadata?.sessionID);
4567
3393
  if (name === "task" && sessionId) return sessionId;
4568
3394
  return callId || `tool-${Date.now()}`;
4569
3395
  }
@@ -4711,7 +3537,7 @@ var opencodeAdapter = {
4711
3537
  return { type: "stderr", data: detail };
4712
3538
  }
4713
3539
  const sid = typeof obj.sessionID === "string" && obj.sessionID || typeof obj.sessionId === "string" && obj.sessionId || typeof obj.session_id === "string" && obj.session_id;
4714
- const childSid = str2(obj.childSessionID) ?? str2(obj.childSessionId) ?? str2(obj.parentID) ?? str2(obj.parentId);
3540
+ const childSid = str(obj.childSessionID) ?? str(obj.childSessionId) ?? str(obj.parentID) ?? str(obj.parentId);
4715
3541
  if (sid && !childSid && (!obj.type || obj.type === "step_start" || obj.type === "session")) {
4716
3542
  return { type: "session_id", data: sid };
4717
3543
  }
@@ -4724,7 +3550,7 @@ var opencodeAdapter = {
4724
3550
  const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
4725
3551
  const state = part?.state;
4726
3552
  const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
4727
- const metadata = asRecord4(state?.metadata);
3553
+ const metadata = asRecord3(state?.metadata);
4728
3554
  const id = opencodeToolId(
4729
3555
  name,
4730
3556
  part?.callID ?? part?.id ?? obj.id,
@@ -4747,8 +3573,8 @@ var opencodeAdapter = {
4747
3573
  return events.length === 1 ? events[0] : events;
4748
3574
  }
4749
3575
  if (obj.type === "subtask_delta") {
4750
- const parentId = str2(obj.childSessionID) ?? str2(obj.childSessionId);
4751
- const delta = str2(obj.delta);
3576
+ const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
3577
+ const delta = str(obj.delta);
4752
3578
  if (parentId && delta) {
4753
3579
  return withTaskParent(
4754
3580
  parentId,
@@ -4758,20 +3584,20 @@ var opencodeAdapter = {
4758
3584
  return null;
4759
3585
  }
4760
3586
  if (obj.type === "subtask_event") {
4761
- const parentId = str2(obj.childSessionID) ?? str2(obj.childSessionId);
4762
- const part = asRecord4(obj.part);
3587
+ const parentId = str(obj.childSessionID) ?? str(obj.childSessionId);
3588
+ const part = asRecord3(obj.part);
4763
3589
  if (!parentId || !part) return null;
4764
- if (part.type === "text" && str2(part.text)) {
3590
+ if (part.type === "text" && str(part.text)) {
4765
3591
  return withTaskParent(
4766
3592
  parentId,
4767
- withEventParentId({ type: "stdout", data: str2(part.text) }, parentId)
3593
+ withEventParentId({ type: "stdout", data: str(part.text) }, parentId)
4768
3594
  );
4769
3595
  }
4770
- if (part.type === "tool" || str2(part.tool)) {
4771
- const name = str2(part.tool) ?? str2(part.name) ?? "tool";
4772
- const id = str2(part.callID) ?? str2(part.id) ?? `${parentId}-${name}`;
4773
- const state = asRecord4(part.state);
4774
- const input = asRecord4(state?.input) ?? asRecord4(part.input);
3596
+ if (part.type === "tool" || str(part.tool)) {
3597
+ const name = str(part.tool) ?? str(part.name) ?? "tool";
3598
+ const id = str(part.callID) ?? str(part.id) ?? `${parentId}-${name}`;
3599
+ const state = asRecord3(part.state);
3600
+ const input = asRecord3(state?.input) ?? asRecord3(part.input);
4775
3601
  const nested = [
4776
3602
  withEventParentId({ type: "tool_use", id, name, input }, parentId)
4777
3603
  ];
@@ -5715,8 +4541,8 @@ async function loginAgent(agent) {
5715
4541
  };
5716
4542
  }
5717
4543
  async function loginManagedAccount(accountId) {
5718
- const { loadAppSettings: loadAppSettings2 } = await import("./app-settings-MVZPM6WW.js");
5719
- const { loginEnvPrefix } = await import("./managed-accounts-4BLTJKAN.js");
4544
+ const { loadAppSettings: loadAppSettings2 } = await import("./app-settings-RAC4PSSP.js");
4545
+ const { loginEnvPrefix } = await import("./managed-accounts-46A4KRUE.js");
5720
4546
  const account = loadAppSettings2().accounts.accounts.find((a) => a.id === accountId);
5721
4547
  if (!account) {
5722
4548
  return { ok: false, message: `Account not found: ${accountId}` };
@@ -5755,33 +4581,6 @@ export {
5755
4581
  materializeSystemCaBundle,
5756
4582
  applySystemCaEnv,
5757
4583
  trustSystemCertificates,
5758
- pushTurnStderr,
5759
- looksLikeHugeToolResultDump,
5760
- clipToolResultForStore,
5761
- looksLikeV8Oom,
5762
- summarizeTurnStderr,
5763
- looksLikeInvalidAgentSession,
5764
- shouldRetryFailedAgentTurn,
5765
- looksLikeAgentFailureMessage,
5766
- fallbackTurnFailDetail,
5767
- turnFailChatText,
5768
- shouldRetryCodexPluginIsolate,
5769
- shouldFeedErrorBackToAgent,
5770
- formatAgentErrorContinuePrompt,
5771
- formatTurnExitError,
5772
- toolDescription,
5773
- isInternalAgentStatusText,
5774
- isPollWrapperToolName,
5775
- liveActivitySummary,
5776
- clipAgentEventForPaint,
5777
- compactSummaryPart,
5778
- applyAgentEvent,
5779
- partsToAssistantText,
5780
- lastAssistantMessageText,
5781
- stripBrightsyNdjsonNoise,
5782
- isBrightsyNdjsonLine,
5783
- finalizeParts,
5784
- normalizeParseResult,
5785
4584
  encodeBrightsyTarget,
5786
4585
  decodeBrightsyTarget,
5787
4586
  parseBrightsyCliLine,