@sideboard-ai/core 0.1.348 → 0.1.349

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 (41) hide show
  1. package/dist/agents/cursor-runner.js +3 -3
  2. package/dist/{agents-5MFGVK7C.js → agents-AZ2PV6XP.js} +7 -7
  3. package/dist/{agents-T4XBZZDA.js → agents-DMPBFF3F.js} +5 -5
  4. package/dist/{chunk-UGUWFONI.js → chunk-2E2HMJDU.js} +1 -1
  5. package/dist/{chunk-NTY5WGRD.js → chunk-3DBL2C45.js} +1 -1
  6. package/dist/{chunk-MOUAM6ZC.js → chunk-6RIPZ73M.js} +132 -2
  7. package/dist/{chunk-6TV6L2DD.js → chunk-CATTIFSP.js} +6 -5
  8. package/dist/{chunk-WMD77UCY.js → chunk-IRFBD6GU.js} +223 -55
  9. package/dist/{chunk-ORO4ENZR.js → chunk-LESWJ7L4.js} +1 -0
  10. package/dist/{chunk-XNGW4OYD.js → chunk-MHSBF3SO.js} +6 -5
  11. package/dist/{chunk-ZJMYCDYQ.js → chunk-MVFFLU5V.js} +47 -9
  12. package/dist/{chunk-OPXEJJBM.js → chunk-PWOFUPYM.js} +1 -0
  13. package/dist/{chunk-OH3BAUMC.js → chunk-Q4I6KDOL.js} +227 -59
  14. package/dist/{chunk-2HPVGTHF.js → chunk-QHXZKHUL.js} +1 -1
  15. package/dist/{chunk-GAGTEI6B.js → chunk-ROXM6QZV.js} +48 -10
  16. package/dist/{chunk-ATS7SYHG.js → chunk-RPHH4FNK.js} +132 -2
  17. package/dist/{chunk-Y6VQX2LY.js → chunk-WHMLMCPU.js} +11 -5
  18. package/dist/{chunk-BIM24I3O.js → chunk-WWBPK7GB.js} +1 -1
  19. package/dist/{chunk-5YCKATG6.js → chunk-YVN7L4KG.js} +1 -1
  20. package/dist/{chunk-Q4TZA4MN.js → chunk-ZXI5DR5S.js} +12 -6
  21. package/dist/{conductor-EMGMDNHL.js → conductor-65VPUPOW.js} +6 -6
  22. package/dist/{conductor-LYQKONSA.js → conductor-NHC6X74J.js} +5 -5
  23. package/dist/{coordinator-prompt-DLY3FS2L.js → coordinator-prompt-5GZWIVSY.js} +3 -3
  24. package/dist/{coordinator-prompt-WALVMGKI.js → coordinator-prompt-R2PURZL3.js} +3 -3
  25. package/dist/{global-workspace-UG2A3CEM.js → global-workspace-64KC7PST.js} +3 -3
  26. package/dist/{global-workspace-7OQ5O6JT.js → global-workspace-UEECLWSX.js} +3 -3
  27. package/dist/index.cjs +1298 -849
  28. package/dist/index.d.cts +30 -8
  29. package/dist/index.d.ts +30 -8
  30. package/dist/index.js +445 -365
  31. package/dist/mcp/run-stdio.cjs +1033 -585
  32. package/dist/mcp/run-stdio.js +296 -216
  33. package/dist/{orchestrator-4SXTORD2.js → orchestrator-I5G5A5BV.js} +7 -7
  34. package/dist/{orchestrator-KNOMW5CZ.js → orchestrator-Y5PYSMR6.js} +9 -9
  35. package/dist/{thread-store-R3G5VBII.js → thread-store-HZ4U4OXB.js} +1 -1
  36. package/dist/{thread-store-MEUWZDVV.js → thread-store-QKNU5CHM.js} +1 -1
  37. package/dist/{workspaces-KWGTP7DI.js → workspaces-6TIM2TM2.js} +3 -3
  38. package/dist/{workspaces-35T6FW57.js → workspaces-I2EHNTFE.js} +3 -3
  39. package/dist/{worktree-ROJXGBWS.js → worktree-7JFYDNUX.js} +2 -2
  40. package/dist/{worktree-5P7SCST3.js → worktree-M2GJGK2P.js} +2 -2
  41. package/package.json +1 -1
@@ -805,14 +805,14 @@ var init_system_ca = __esm({
805
805
  });
806
806
 
807
807
  // src/agents/cursor-stream-cutoff.ts
808
- function looksLikeCursorStreamCutOff(text7) {
809
- return CURSOR_STREAM_CUTOFF.test(text7.trim());
808
+ function looksLikeCursorStreamCutOff(text8) {
809
+ return CURSOR_STREAM_CUTOFF.test(text8.trim());
810
810
  }
811
- function looksLikeCursorStreamIdleAfterTools(text7) {
812
- return CURSOR_STREAM_IDLE_AFTER_TOOLS.test(text7.trim());
811
+ function looksLikeCursorStreamIdleAfterTools(text8) {
812
+ return CURSOR_STREAM_IDLE_AFTER_TOOLS.test(text8.trim());
813
813
  }
814
- function looksLikeCursorStreamFailure(text7) {
815
- return looksLikeCursorStreamCutOff(text7) || looksLikeCursorStreamIdleAfterTools(text7);
814
+ function looksLikeCursorStreamFailure(text8) {
815
+ return looksLikeCursorStreamCutOff(text8) || looksLikeCursorStreamIdleAfterTools(text8);
816
816
  }
817
817
  function cursorStreamCutOffContinueLimit(detail) {
818
818
  if (looksLikeCursorStreamCutOff(detail) || /connection stalled/i.test(detail)) {
@@ -900,14 +900,14 @@ function looksLikeMinifiedJsDump(line) {
900
900
  if (line.length < 200) return false;
901
901
  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);
902
902
  }
903
- function looksLikeCursorSdkSourceDump(text7) {
904
- const t = text7.trim();
903
+ function looksLikeCursorSdkSourceDump(text8) {
904
+ const t = text8.trim();
905
905
  if (t.length < 120) return false;
906
906
  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);
907
907
  }
908
- function looksLikeHugeToolResultDump(text7) {
909
- if (looksLikeCursorSdkSourceDump(text7)) return true;
910
- const t = text7.trim();
908
+ function looksLikeHugeToolResultDump(text8) {
909
+ if (looksLikeCursorSdkSourceDump(text8)) return true;
910
+ const t = text8.trim();
911
911
  if (t.length < 4e3) return false;
912
912
  return looksLikeMinifiedJsDump(t);
913
913
  }
@@ -970,20 +970,20 @@ ${content.slice(-tail)}`;
970
970
  function looksLikeNestedElectronCrash(line) {
971
971
  return /HasCustomHostObject|ElectronInitializeICUandStartNode/i.test(line);
972
972
  }
973
- function looksLikeNativeEventLoopCrash(text7) {
974
- return /uv_run|uv__io_poll|SpinEventLoopInternal/i.test(text7);
973
+ function looksLikeNativeEventLoopCrash(text8) {
974
+ return /uv_run|uv__io_poll|SpinEventLoopInternal/i.test(text8);
975
975
  }
976
- function looksLikeV8Oom(text7) {
976
+ function looksLikeV8Oom(text8) {
977
977
  return /javascript heap|reached heap limit|OOMErrorHandler|FatalProcessOutOfMemory|Allocation failed - JavaScript heap/i.test(
978
- text7
978
+ text8
979
979
  );
980
980
  }
981
- function looksLikeHomebrewLibuvCrash(text7) {
982
- if (!looksLikeNativeEventLoopCrash(text7)) return false;
983
- return /Cellar\/(?:libuv|node)|libuv\.\d+\.dylib/i.test(text7);
981
+ function looksLikeHomebrewLibuvCrash(text8) {
982
+ if (!looksLikeNativeEventLoopCrash(text8)) return false;
983
+ return /Cellar\/(?:libuv|node)|libuv\.\d+\.dylib/i.test(text8);
984
984
  }
985
- function clipStderr(text7, maxChars) {
986
- const trimmed = text7.trim();
985
+ function clipStderr(text8, maxChars) {
986
+ const trimmed = text8.trim();
987
987
  if (trimmed.length <= maxChars) return trimmed;
988
988
  return trimmed.slice(0, maxChars);
989
989
  }
@@ -1020,23 +1020,23 @@ function summarizeTurnStderr(tail, maxChars = 500) {
1020
1020
  const joined = (useful.length ? useful : tail).slice(-6).join("\n").trim();
1021
1021
  return clipStderr(joined, maxChars);
1022
1022
  }
1023
- function looksLikeInvalidAgentSession(text7) {
1024
- const lower = text7.trim().toLowerCase();
1023
+ function looksLikeInvalidAgentSession(text8) {
1024
+ const lower = text8.trim().toLowerCase();
1025
1025
  if (!lower) return false;
1026
1026
  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);
1027
1027
  }
1028
- function looksLikeBrightsyEmptyCompletion(text7) {
1029
- const core = text7.trim().replace(/^exit\s*\d+:\s*/i, "").replace(/^error:\s*/i, "").trim();
1028
+ function looksLikeBrightsyEmptyCompletion(text8) {
1029
+ const core = text8.trim().replace(/^exit\s*\d+:\s*/i, "").replace(/^error:\s*/i, "").trim();
1030
1030
  return /^i did not receive a valid model response\. please try again\.$/i.test(core);
1031
1031
  }
1032
- function looksLikeRetryableRunnerCrash(text7) {
1033
- if (looksLikeAgentFailureMessage(text7)) return false;
1034
- if (looksLikeInvalidAgentSession(text7)) return false;
1035
- if (looksLikeV8Oom(text7)) return false;
1036
- if (looksLikeHugeToolResultDump(text7)) return true;
1037
- if (looksLikeCursorStreamFailure(text7)) return true;
1038
- if (looksLikeBrightsyEmptyCompletion(text7)) return true;
1039
- const lower = text7.trim().toLowerCase();
1032
+ function looksLikeRetryableRunnerCrash(text8) {
1033
+ if (looksLikeAgentFailureMessage(text8)) return false;
1034
+ if (looksLikeInvalidAgentSession(text8)) return false;
1035
+ if (looksLikeV8Oom(text8)) return false;
1036
+ if (looksLikeHugeToolResultDump(text8)) return true;
1037
+ if (looksLikeCursorStreamFailure(text8)) return true;
1038
+ if (looksLikeBrightsyEmptyCompletion(text8)) return true;
1039
+ const lower = text8.trim().toLowerCase();
1040
1040
  if (/cannot find (?:package|module)|err_module_not_found/.test(lower)) return false;
1041
1041
  if (!lower) return true;
1042
1042
  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(
@@ -1048,12 +1048,12 @@ function shouldRetryFailedAgentTurn(detail, opts) {
1048
1048
  if (looksLikeV8Oom(detail) && opts.hasSession) return true;
1049
1049
  return looksLikeRetryableRunnerCrash(detail);
1050
1050
  }
1051
- function looksLikeAgentFailureMessage(text7) {
1052
- const lower = text7.trim().toLowerCase();
1051
+ function looksLikeAgentFailureMessage(text8) {
1052
+ const lower = text8.trim().toLowerCase();
1053
1053
  if (!lower) return false;
1054
1054
  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(
1055
1055
  lower
1056
- ) || /\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(text7);
1056
+ ) || /\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(text8);
1057
1057
  }
1058
1058
  function fallbackTurnFailDetail(assistantText) {
1059
1059
  const t = assistantText.trim();
@@ -1143,8 +1143,8 @@ function shouldRetryCodexPluginIsolate(detail, opts) {
1143
1143
  if (opts?.alreadyIsolated) return false;
1144
1144
  return looksLikeCodexMcpError(detail);
1145
1145
  }
1146
- function looksLikeCodexMcpError(text7) {
1147
- const t = text7.trim().toLowerCase();
1146
+ function looksLikeCodexMcpError(text8) {
1147
+ const t = text8.trim().toLowerCase();
1148
1148
  if (!t) return false;
1149
1149
  if (/authrequired|authorization required/.test(t) && /mcp|posthog|rmcp|connector|plugin/.test(t)) {
1150
1150
  return true;
@@ -1266,12 +1266,12 @@ function skillCommandFromInput(input) {
1266
1266
  }
1267
1267
  return void 0;
1268
1268
  }
1269
- function looksLikeComposerSkillExpansion(text7) {
1270
- const t = text7.trim();
1269
+ function looksLikeComposerSkillExpansion(text8) {
1270
+ const t = text8.trim();
1271
1271
  return /^## Skill: \//m.test(t) && /Follow this skill for the request above:/i.test(t);
1272
1272
  }
1273
- function skillNameFromFrontmatter(text7) {
1274
- const t = text7.trim();
1273
+ function skillNameFromFrontmatter(text8) {
1274
+ const t = text8.trim();
1275
1275
  if (!t) return void 0;
1276
1276
  let yaml = t;
1277
1277
  if (!yaml.startsWith("---")) {
@@ -1284,18 +1284,18 @@ function skillNameFromFrontmatter(text7) {
1284
1284
  if (close < 0) return void 0;
1285
1285
  return yaml.slice(3, close).match(SKILL_FRONTMATTER_NAME)?.[1];
1286
1286
  }
1287
- function skillCommandFromBody(text7) {
1288
- return skillNameFromFrontmatter(text7) ?? text7.match(/^## Skill: \/([A-Za-z0-9][A-Za-z0-9._-]*)/m)?.[1] ?? text7.match(/^Launching skill:\s*\/?([A-Za-z0-9][A-Za-z0-9._-]*)/im)?.[1];
1287
+ function skillCommandFromBody(text8) {
1288
+ return skillNameFromFrontmatter(text8) ?? text8.match(/^## Skill: \/([A-Za-z0-9][A-Za-z0-9._-]*)/m)?.[1] ?? text8.match(/^Launching skill:\s*\/?([A-Za-z0-9][A-Za-z0-9._-]*)/im)?.[1];
1289
1289
  }
1290
- function looksLikeSkillBody(text7) {
1291
- const t = text7.trim();
1290
+ function looksLikeSkillBody(text8) {
1291
+ const t = text8.trim();
1292
1292
  if (!t) return false;
1293
1293
  if (looksLikeComposerSkillExpansion(t)) return true;
1294
1294
  if (skillNameFromFrontmatter(t) != null) return true;
1295
1295
  return /^Launching skill:/im.test(t) && /Base directory for this skill:/i.test(t);
1296
1296
  }
1297
- function looksLikeIncompleteSkillDump(text7) {
1298
- const t = text7.trim();
1297
+ function looksLikeIncompleteSkillDump(text8) {
1298
+ const t = text8.trim();
1299
1299
  if (!t || looksLikeSkillBody(t)) return false;
1300
1300
  if (/^## Skill: \//m.test(t)) return true;
1301
1301
  if (/^Launching skill:/im.test(t)) return true;
@@ -1308,11 +1308,11 @@ function isCompactToolName(name) {
1308
1308
  short
1309
1309
  );
1310
1310
  }
1311
- function isContextCompactDone(text7) {
1312
- return /\bContext compressed\b/i.test(text7.trim());
1311
+ function isContextCompactDone(text8) {
1312
+ return /\bContext compressed\b/i.test(text8.trim());
1313
1313
  }
1314
- function isContextCompactInProgress(text7) {
1315
- const t = text7.trim();
1314
+ function isContextCompactInProgress(text8) {
1315
+ const t = text8.trim();
1316
1316
  if (isContextCompactDone(t)) return false;
1317
1317
  return /^Compressing context/i.test(t);
1318
1318
  }
@@ -1325,8 +1325,8 @@ function isSystemStatusThinking(event) {
1325
1325
  if (isContextCompactInProgress(t) || isContextCompactDone(t)) return true;
1326
1326
  return false;
1327
1327
  }
1328
- function looksLikeConversationSummary(text7) {
1329
- const t = text7.trim();
1328
+ function looksLikeConversationSummary(text8) {
1329
+ const t = text8.trim();
1330
1330
  if (t.length < 80) return false;
1331
1331
  if (/<summarized_conversation\b/i.test(t) || /<conversation_summary\b/i.test(t)) {
1332
1332
  return true;
@@ -1496,8 +1496,8 @@ function isSubagentToolName(name) {
1496
1496
  if (/^(task|agent|spawn_agent)$/i.test(n)) return true;
1497
1497
  return /connectedAgentRequest/i.test(n);
1498
1498
  }
1499
- function isInternalAgentStatusText(text7) {
1500
- const t = text7.trim();
1499
+ function isInternalAgentStatusText(text8) {
1500
+ const t = text8.trim();
1501
1501
  if (!t) return false;
1502
1502
  if (/waiting for gate to pass/i.test(t)) return true;
1503
1503
  if (/^agent is running\b/i.test(t) && t.length < 160) return true;
@@ -1511,9 +1511,9 @@ function lastTextPart(parts, type) {
1511
1511
  for (let i = parts.length - 1; i >= 0; i--) {
1512
1512
  const p = parts[i];
1513
1513
  if (p.type !== type) continue;
1514
- const text7 = p.text.trim();
1515
- if (!text7 || isInternalAgentStatusText(text7)) continue;
1516
- return text7;
1514
+ const text8 = p.text.trim();
1515
+ if (!text8 || isInternalAgentStatusText(text8)) continue;
1516
+ return text8;
1517
1517
  }
1518
1518
  return "";
1519
1519
  }
@@ -1534,7 +1534,7 @@ function liveActivitySummary(parts, opts) {
1534
1534
  );
1535
1535
  const runningPoll = [...tools].reverse().find((t) => t.status === "running" && isPollWrapperToolName(t.name));
1536
1536
  const thinking = lastTextPart(parts, "thinking");
1537
- const text7 = lastTextPart(parts, "text");
1537
+ const text8 = lastTextPart(parts, "text");
1538
1538
  if (runningSubs.length > 0) {
1539
1539
  const heads = runningSubs.map(toolLabel);
1540
1540
  const head = runningSubs.length === 1 ? heads[0] : `${runningSubs.length} subagents \xB7 ${heads.slice(0, 2).join(" \xB7 ")}`;
@@ -1544,7 +1544,7 @@ function liveActivitySummary(parts, opts) {
1544
1544
  if (runningTop) return toolLabel(runningTop);
1545
1545
  if (runningPoll) return toolLabel(runningPoll);
1546
1546
  if (thinking) return thinking.length > 96 ? `\u2026${thinking.slice(-96)}` : thinking;
1547
- if (text7) return "Writing reply\u2026";
1547
+ if (text8) return "Writing reply\u2026";
1548
1548
  const last = [...tools].reverse().find((t) => !isPollWrapperToolName(t.name)) ?? tools.at(-1);
1549
1549
  if (last) {
1550
1550
  const label = toolLabel(last);
@@ -1572,9 +1572,9 @@ function toolFilePath(input) {
1572
1572
  if (!input) return void 0;
1573
1573
  return str(input.file_path) ?? str(input.path) ?? str(input.filePath) ?? str(input.filename);
1574
1574
  }
1575
- function countLines(text7) {
1576
- if (!text7) return 0;
1577
- return text7.split("\n").length;
1575
+ function countLines(text8) {
1576
+ if (!text8) return 0;
1577
+ return text8.split("\n").length;
1578
1578
  }
1579
1579
  function diffFromInput(input) {
1580
1580
  if (!input) return {};
@@ -1608,15 +1608,15 @@ function parseDiffStat(result) {
1608
1608
  }
1609
1609
  return {};
1610
1610
  }
1611
- function clipThinkingForStore(text7, max = THINKING_PART_MAX_CHARS) {
1612
- if (text7.length <= max) return text7;
1611
+ function clipThinkingForStore(text8, max = THINKING_PART_MAX_CHARS) {
1612
+ if (text8.length <= max) return text8;
1613
1613
  const marker = "\u2026(earlier thinking trimmed)\n";
1614
- return marker + text7.slice(text7.length - Math.max(1, max - marker.length));
1614
+ return marker + text8.slice(text8.length - Math.max(1, max - marker.length));
1615
1615
  }
1616
- function clipEventTail(text7, max) {
1617
- if (text7.length <= max) return text7;
1616
+ function clipEventTail(text8, max) {
1617
+ if (text8.length <= max) return text8;
1618
1618
  const marker = "\u2026(truncated)\n";
1619
- return marker + text7.slice(text7.length - Math.max(1, max - marker.length));
1619
+ return marker + text8.slice(text8.length - Math.max(1, max - marker.length));
1620
1620
  }
1621
1621
  function clipAgentEventForPaint(event) {
1622
1622
  if (event.type === "tool_result" && event.content) {
@@ -1712,10 +1712,10 @@ function promoteOrFoldSkillText(parts, textIdx) {
1712
1712
  );
1713
1713
  return next;
1714
1714
  }
1715
- function compactSummaryPart(text7, id = "compact-summary") {
1716
- return compactToolPart(text7, id, { status: "done" });
1715
+ function compactSummaryPart(text8, id = "compact-summary") {
1716
+ return compactToolPart(text8, id, { status: "done" });
1717
1717
  }
1718
- function compactToolPart(text7, id, opts) {
1718
+ function compactToolPart(text8, id, opts) {
1719
1719
  const input = { trigger: opts?.trigger ?? "auto" };
1720
1720
  return withPartTimes(
1721
1721
  {
@@ -1725,7 +1725,7 @@ function compactToolPart(text7, id, opts) {
1725
1725
  input,
1726
1726
  description: toolDescription("Compact", input),
1727
1727
  status: opts?.status ?? "done",
1728
- result: clipToolResultForStore(text7) ?? "",
1728
+ result: clipToolResultForStore(text8) ?? "",
1729
1729
  ...opts?.parentId ? { parentId: opts.parentId } : {}
1730
1730
  },
1731
1731
  opts?.prev
@@ -2020,15 +2020,15 @@ function lastAssistantMessageText(parts) {
2020
2020
  for (let i = parts.length - 1; i >= 0; i--) {
2021
2021
  const p = parts[i];
2022
2022
  if (!p || p.type !== "text" || messagePartParentId(p)) continue;
2023
- const text7 = p.text.trim();
2024
- if (!text7 || isInternalAgentStatusText(text7)) continue;
2025
- return text7;
2023
+ const text8 = p.text.trim();
2024
+ if (!text8 || isInternalAgentStatusText(text8)) continue;
2025
+ return text8;
2026
2026
  }
2027
2027
  return "";
2028
2028
  }
2029
- function stripBrightsyNdjsonNoise(text7) {
2030
- if (!text7 || !text7.includes('"type"')) return text7;
2031
- let out = text7;
2029
+ function stripBrightsyNdjsonNoise(text8) {
2030
+ if (!text8 || !text8.includes('"type"')) return text8;
2031
+ let out = text8;
2032
2032
  out = out.replace(
2033
2033
  /\{"type":"(?:tool_use|tool_result|tool|thinking|usage|done|error)"[\s\S]*?\}\s*(?=\{"type":"|$|(?=[A-Za-z*#]))/g,
2034
2034
  ""
@@ -2064,11 +2064,11 @@ var init_message_parts = __esm({
2064
2064
  });
2065
2065
 
2066
2066
  // src/threads/injected-notices.ts
2067
- function isSlackExternalReplyText(text7) {
2068
- return text7.startsWith("Slack reply from ") && text7.includes("not a command");
2067
+ function isSlackExternalReplyText(text8) {
2068
+ return text8.startsWith("Slack reply from ") && text8.includes("not a command");
2069
2069
  }
2070
- function isInjectedNoticeText(text7) {
2071
- return isSlackExternalReplyText(text7);
2070
+ function isInjectedNoticeText(text8) {
2071
+ return isSlackExternalReplyText(text8);
2072
2072
  }
2073
2073
  function pendingInjectedNotices(messages, match = isInjectedNoticeText) {
2074
2074
  let i = messages.length - 1;
@@ -2263,13 +2263,51 @@ var init_task_state = __esm({
2263
2263
  }
2264
2264
  });
2265
2265
 
2266
+ // src/agents/turn-failure-class.ts
2267
+ function classifyTurnFailure(detail) {
2268
+ const text8 = detail?.trim() ?? "";
2269
+ if (!text8) return null;
2270
+ const lower = text8.toLowerCase();
2271
+ if (/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) || /\b429\b|too many requests|rate.?limit/.test(lower) || /\[resource_exhausted\]|resource_exhausted/.test(lower)) {
2272
+ return "quota";
2273
+ }
2274
+ if (/invalid user api key|invalid api key|not logged in|not authenticated|please run.*login|codex login|claude auth/.test(
2275
+ lower
2276
+ )) {
2277
+ return "auth";
2278
+ }
2279
+ if (/prompt is too long|context.*(too long|exceed)|conversation too long/.test(lower) || /model .{0,80}(not found|unavailable|unknown|invalid)/.test(lower) || /\brefus(ed|al)\b|content policy/.test(lower)) {
2280
+ return "refused";
2281
+ }
2282
+ if (/connection stalled|\btimed out\b|inactivity timeout|\bETIMEDOUT\b/.test(lower)) return "timeout";
2283
+ if (looksLikeRetryableRunnerCrash(text8) || looksLikeV8Oom(text8) || looksLikeInvalidAgentSession(text8)) {
2284
+ return "runner";
2285
+ }
2286
+ return "other";
2287
+ }
2288
+ var init_turn_failure_class = __esm({
2289
+ "src/agents/turn-failure-class.ts"() {
2290
+ "use strict";
2291
+ init_error_detail();
2292
+ }
2293
+ });
2294
+
2266
2295
  // src/mcp/wait-for-turn.ts
2267
2296
  function mcpWaitForTurnTimeoutMs(requested) {
2268
2297
  const n = requested ?? MCP_WAIT_FOR_TURN_MAX_MS;
2269
2298
  if (!Number.isFinite(n)) return MCP_WAIT_FOR_TURN_MAX_MS;
2270
2299
  return Math.min(Math.max(1e3, Math.floor(n)), MCP_WAIT_FOR_TURN_MAX_MS);
2271
2300
  }
2272
- function mcpWaitTaskHint(taskState, status, blockedReason) {
2301
+ function mcpWaitFailureHint(failureClass) {
2302
+ if (failureClass === "auth" || failureClass === "quota" || failureClass === "refused") {
2303
+ return `Child turn failed (${failureClass}). Do not retry the same request. Tell the user or switch agent.`;
2304
+ }
2305
+ if (failureClass === "timeout" || failureClass === "runner") {
2306
+ return `Child turn failed (${failureClass}). One retry is reasonable. Do not treat empty text as success.`;
2307
+ }
2308
+ return MCP_WAIT_ERROR_HINT;
2309
+ }
2310
+ function mcpWaitTaskHint(taskState, status, blockedReason, failureClass) {
2273
2311
  const why = blockedReason?.trim();
2274
2312
  if (why && taskState !== "failed" && taskState !== "canceled") {
2275
2313
  if (taskState === "submitted" || taskState === "working") {
@@ -2290,7 +2328,7 @@ function mcpWaitTaskHint(taskState, status, blockedReason) {
2290
2328
  case "canceled":
2291
2329
  return MCP_WAIT_STOPPED_HINT;
2292
2330
  case "failed":
2293
- return status === "broken" ? MCP_WAIT_BROKEN_HINT : MCP_WAIT_ERROR_HINT;
2331
+ return status === "broken" ? MCP_WAIT_BROKEN_HINT : mcpWaitFailureHint(failureClass ?? null);
2294
2332
  default:
2295
2333
  return void 0;
2296
2334
  }
@@ -2310,12 +2348,14 @@ function lastActivityAtForWait(stillRunning, liveUpdatedAt, fallbacks) {
2310
2348
  function waitForTurnToolResult(input) {
2311
2349
  const blockedReason = input.blockedReason?.trim() ? input.blockedReason.trim() : null;
2312
2350
  const waiting = Boolean(blockedReason) && !input.stillRunning && input.taskState !== "failed" && input.taskState !== "canceled";
2351
+ const failureClass = input.taskState === "failed" && input.status !== "broken" ? classifyTurnFailure(input.lastError || input.text) : null;
2313
2352
  return {
2314
2353
  ...input,
2315
2354
  usage: input.usage ?? null,
2316
2355
  blockedReason,
2317
2356
  blockedSource: blockedReason ? input.blockedSource ?? null : null,
2318
- hint: mcpWaitTaskHint(input.taskState, input.status, blockedReason),
2357
+ failureClass,
2358
+ hint: mcpWaitTaskHint(input.taskState, input.status, blockedReason, failureClass),
2319
2359
  incomplete: needsCoordinatorAction(input.taskState) || waiting
2320
2360
  };
2321
2361
  }
@@ -2323,6 +2363,7 @@ var MCP_WAIT_FOR_TURN_MAX_MS, MCP_WAIT_STILL_RUNNING_HINT, MCP_WAIT_QUEUED_HINT,
2323
2363
  var init_wait_for_turn = __esm({
2324
2364
  "src/mcp/wait-for-turn.ts"() {
2325
2365
  "use strict";
2366
+ init_turn_failure_class();
2326
2367
  init_task_state();
2327
2368
  MCP_WAIT_FOR_TURN_MAX_MS = 45e3;
2328
2369
  MCP_WAIT_STILL_RUNNING_HINT = "Child is still working. Call wait_for_turn again. Do not send_to_chat a check-in (that steers / interrupts) or assume a hang while progress is updating.";
@@ -2527,8 +2568,8 @@ var init_github_agent_auth = __esm({
2527
2568
  });
2528
2569
 
2529
2570
  // src/git/stale-lock.ts
2530
- function isIndexLockError(text7) {
2531
- return /Unable to create ['"][^'"]*index\.lock['"]: File exists/i.test(text7);
2571
+ function isIndexLockError(text8) {
2572
+ return /Unable to create ['"][^'"]*index\.lock['"]: File exists/i.test(text8);
2532
2573
  }
2533
2574
  function clearStaleIndexLock(gitDir, maxAgeMs = STALE_INDEX_LOCK_MS, now = Date.now()) {
2534
2575
  const lockPath = (0, import_node_path11.join)(gitDir, "index.lock");
@@ -3661,12 +3702,12 @@ var init_worktree_labels = __esm({
3661
3702
  });
3662
3703
 
3663
3704
  // src/git/gh-errors.ts
3664
- function isGhRateLimitError(text7) {
3665
- return /API rate limit (already )?exceeded/i.test(text7) || /rate limit exceeded/i.test(text7);
3705
+ function isGhRateLimitError(text8) {
3706
+ return /API rate limit (already )?exceeded/i.test(text8) || /rate limit exceeded/i.test(text8);
3666
3707
  }
3667
- function isGhPrBodyTooLongError(text7) {
3708
+ function isGhPrBodyTooLongError(text8) {
3668
3709
  return /body is too long|body.{0,20}too long|maximum is 65536|exceeds the maximum allowed size|request (entity |is )?too large|payload too large|413 Request Entity Too Large/i.test(
3669
- text7
3710
+ text8
3670
3711
  );
3671
3712
  }
3672
3713
  function clampGithubPrBody(body, max = GITHUB_PR_BODY_SAFE_CHARS) {
@@ -3686,21 +3727,21 @@ function formatRateLimitResetHint(resetEpochSec, nowMs = Date.now()) {
3686
3727
  const hours = Math.ceil(mins / 60);
3687
3728
  return `in about ${hours} hour${hours === 1 ? "" : "s"}`;
3688
3729
  }
3689
- function omitGhBodyArg(text7) {
3690
- return text7.replace(
3730
+ function omitGhBodyArg(text8) {
3731
+ return text8.replace(
3691
3732
  /--body(?:-file)?(\s+|=)(?:'[^']*'|"[^"]*"|\S+)/g,
3692
3733
  "--body <omitted>"
3693
3734
  );
3694
3735
  }
3695
- function capGhErrorText(text7, max = 400) {
3696
- const t = text7.trim();
3736
+ function capGhErrorText(text8, max = 400) {
3737
+ const t = text8.trim();
3697
3738
  if (t.length <= max) return t;
3698
3739
  return `${t.slice(0, max - 1).trimEnd()}\u2026`;
3699
3740
  }
3700
- function extractGhErrorDetail(text7) {
3701
- const trimmed = omitGhBodyArg(text7.trim());
3741
+ function extractGhErrorDetail(text8) {
3742
+ const trimmed = omitGhBodyArg(text8.trim());
3702
3743
  if (!trimmed) return "";
3703
- if (isGhPrBodyTooLongError(text7) || isGhPrBodyTooLongError(trimmed)) {
3744
+ if (isGhPrBodyTooLongError(text8) || isGhPrBodyTooLongError(trimmed)) {
3704
3745
  return "GraphQL: body is too long (GitHub PR body / request size limit).";
3705
3746
  }
3706
3747
  const graphql = trimmed.match(/\bGraphQL:\s*(.+)$/im);
@@ -3740,9 +3781,9 @@ function formatGhLandError(raw, opts) {
3740
3781
  }
3741
3782
  return detail || "Failed to create or update pull request";
3742
3783
  }
3743
- function isPrNotMergeableError(text7) {
3784
+ function isPrNotMergeableError(text8) {
3744
3785
  return /not mergeable|cannot be cleanly created|cannot merge cleanly|Merge conflict|\bCONFLICTING\b|must be (updated|rebased)|branch is out of date|needs? to be (updated|rebased)|Resolve conflicts or update the branch/i.test(
3745
- text7
3786
+ text8
3746
3787
  );
3747
3788
  }
3748
3789
  function formatMergePrError(raw) {
@@ -3989,12 +4030,12 @@ function normalizeProfileNotes(value) {
3989
4030
  return value.replace(/\r\n/g, "\n").trim().slice(0, PROFILE_NOTES_MAX);
3990
4031
  }
3991
4032
  function foldLegacyRolesIntoNotes(roles, legacyRole, notes) {
3992
- const text7 = normalizeProfileNotes(notes);
4033
+ const text8 = normalizeProfileNotes(notes);
3993
4034
  const labels = legacyRoleLabels(roles, legacyRole);
3994
- if (!labels.length) return text7;
3995
- if (text7.toLowerCase().startsWith("roles:")) return text7;
4035
+ if (!labels.length) return text8;
4036
+ if (text8.toLowerCase().startsWith("roles:")) return text8;
3996
4037
  const prefix = `Roles: ${labels.join(", ")}`;
3997
- return text7 ? `${prefix}. ${text7}` : prefix;
4038
+ return text8 ? `${prefix}. ${text8}` : prefix;
3998
4039
  }
3999
4040
  function resolveAccountProfile(input) {
4000
4041
  return resolveViewerProfile(input);
@@ -4070,12 +4111,12 @@ var init_account_profile = __esm({
4070
4111
 
4071
4112
  // src/remote/protocol.ts
4072
4113
  function normalizeRemoteRelayUrl(raw) {
4073
- let text7 = raw.trim();
4074
- if (!text7) return null;
4075
- if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text7)) text7 = `wss://${text7}`;
4114
+ let text8 = raw.trim();
4115
+ if (!text8) return null;
4116
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text8)) text8 = `wss://${text8}`;
4076
4117
  let url;
4077
4118
  try {
4078
- url = new URL(text7);
4119
+ url = new URL(text8);
4079
4120
  } catch {
4080
4121
  return null;
4081
4122
  }
@@ -4584,8 +4625,8 @@ function isHistoryRetentionStub(thread) {
4584
4625
  const only = messages[0];
4585
4626
  if (only.parts?.length) return false;
4586
4627
  if ((only.attachments?.length ?? 0) > 0) return false;
4587
- const text7 = (only.text ?? "").trim();
4588
- return text7 === "" || text7 === HISTORY_DISCARDED_TEXT;
4628
+ const text8 = (only.text ?? "").trim();
4629
+ return text8 === "" || text8 === HISTORY_DISCARDED_TEXT;
4589
4630
  }
4590
4631
  function historyRetentionStubMessage(thread) {
4591
4632
  const usage = sumUsageList((thread.messages ?? []).map((m) => m.usage));
@@ -8094,9 +8135,9 @@ function parseDurationMs(every) {
8094
8135
  return n * UNIT_MS[unit];
8095
8136
  }
8096
8137
  function dayIndex(token) {
8097
- const text7 = token.trim().toLowerCase();
8098
- if (/^[0-6]$/.test(text7)) return Number(text7);
8099
- return DAY_ALIASES[text7];
8138
+ const text8 = token.trim().toLowerCase();
8139
+ if (/^[0-6]$/.test(text8)) return Number(text8);
8140
+ return DAY_ALIASES[text8];
8100
8141
  }
8101
8142
  function normalizeWeekdays(days) {
8102
8143
  const set = /* @__PURE__ */ new Set();
@@ -8110,15 +8151,15 @@ function normalizeWeekdays(days) {
8110
8151
  return [...set].sort((a, b) => a - b);
8111
8152
  }
8112
8153
  function parseWeeklyDays(raw) {
8113
- const text7 = raw.trim().toLowerCase();
8114
- if (!text7) throw new Error("Pick at least one day");
8115
- if (text7 === "daily" || text7 === "all" || text7 === "every day" || text7 === "everyday") {
8154
+ const text8 = raw.trim().toLowerCase();
8155
+ if (!text8) throw new Error("Pick at least one day");
8156
+ if (text8 === "daily" || text8 === "all" || text8 === "every day" || text8 === "everyday") {
8116
8157
  return [0, 1, 2, 3, 4, 5, 6];
8117
8158
  }
8118
- if (text7 === "weekdays" || text7 === "weekday") return [1, 2, 3, 4, 5];
8119
- if (text7 === "weekends" || text7 === "weekend") return [0, 6];
8159
+ if (text8 === "weekdays" || text8 === "weekday") return [1, 2, 3, 4, 5];
8160
+ if (text8 === "weekends" || text8 === "weekend") return [0, 6];
8120
8161
  const days = [];
8121
- for (const part of text7.split(/[\s,]+/).filter(Boolean)) {
8162
+ for (const part of text8.split(/[\s,]+/).filter(Boolean)) {
8122
8163
  const range = part.split("-");
8123
8164
  if (range.length === 2 && range[0] && range[1]) {
8124
8165
  const start = dayIndex(range[0]);
@@ -8542,6 +8583,136 @@ var init_schedules = __esm({
8542
8583
  }
8543
8584
  });
8544
8585
 
8586
+ // src/threads/chat-follow-ups.ts
8587
+ function ciChecksSettled(checks) {
8588
+ if (!checks) return "none";
8589
+ if (checks.length === 0) return "none";
8590
+ if (checks.some((check) => (check.bucket ?? "pending") === "pending")) return "pending";
8591
+ return "done";
8592
+ }
8593
+ function parseFollowUpAt(raw, now) {
8594
+ const text8 = raw.trim();
8595
+ const rel = /^(\d+)(m|h|d)$/i.exec(text8);
8596
+ if (rel) {
8597
+ const n = Number(rel[1]);
8598
+ if (!Number.isFinite(n) || n <= 0) return null;
8599
+ const unit = rel[2].toLowerCase();
8600
+ const ms2 = unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
8601
+ return new Date(now.getTime() + n * ms2).toISOString();
8602
+ }
8603
+ const ms = Date.parse(text8);
8604
+ if (!Number.isFinite(ms)) return null;
8605
+ return new Date(ms).toISOString();
8606
+ }
8607
+ function normalizeChatFollowUps(raw) {
8608
+ if (!Array.isArray(raw)) return [];
8609
+ const out = [];
8610
+ for (const item of raw) {
8611
+ if (!item || typeof item !== "object") continue;
8612
+ const row = item;
8613
+ if (row.kind !== "ci" && row.kind !== "at") continue;
8614
+ if (typeof row.prompt !== "string" || !row.prompt.trim()) continue;
8615
+ if (typeof row.deadline !== "string" || !row.deadline.trim()) continue;
8616
+ if (typeof row.createdAt !== "string" || !row.createdAt.trim()) continue;
8617
+ if (typeof row.id !== "string" || !row.id.trim()) continue;
8618
+ const baseline = row.ciBaseline;
8619
+ const followUp = {
8620
+ id: row.id.trim(),
8621
+ kind: row.kind,
8622
+ prompt: row.prompt.trim(),
8623
+ deadline: row.deadline.trim(),
8624
+ createdAt: row.createdAt.trim()
8625
+ };
8626
+ if (typeof row.at === "string" && row.at.trim()) followUp.at = row.at.trim();
8627
+ if (baseline === "pending" || baseline === "done" || baseline === "none" || baseline === "unknown") {
8628
+ followUp.ciBaseline = baseline;
8629
+ }
8630
+ if (row.ciSawPending === true) followUp.ciSawPending = true;
8631
+ out.push(followUp);
8632
+ if (out.length >= MAX_CHAT_FOLLOW_UPS) break;
8633
+ }
8634
+ return out;
8635
+ }
8636
+ function addChatFollowUp(existing, draft, now) {
8637
+ if (existing.length >= MAX_CHAT_FOLLOW_UPS) {
8638
+ return { ok: false, error: "This chat already has 10 follow-ups." };
8639
+ }
8640
+ const prompt = draft.prompt.trim();
8641
+ if (!prompt) return { ok: false, error: "prompt is required" };
8642
+ let at;
8643
+ let deadline;
8644
+ if (draft.kind === "at") {
8645
+ if (!draft.at?.trim()) return { ok: false, error: "at is required for a time follow-up" };
8646
+ const parsed = parseFollowUpAt(draft.at, now);
8647
+ if (!parsed) return { ok: false, error: "at must be 30m, 2h, 1d, or an ISO time" };
8648
+ at = parsed;
8649
+ deadline = draft.deadline?.trim() ? parseFollowUpAt(draft.deadline, now) ?? "" : parsed;
8650
+ if (!deadline) return { ok: false, error: "deadline must be 30m, 2h, 1d, or an ISO time" };
8651
+ } else {
8652
+ deadline = draft.deadline?.trim() ? parseFollowUpAt(draft.deadline, now) ?? "" : new Date(now.getTime() + DEFAULT_FOLLOW_UP_DEADLINE_MS).toISOString();
8653
+ if (!deadline) return { ok: false, error: "deadline must be 30m, 2h, 1d, or an ISO time" };
8654
+ }
8655
+ const followUp = {
8656
+ id: (0, import_node_crypto4.randomUUID)(),
8657
+ kind: draft.kind,
8658
+ prompt,
8659
+ deadline,
8660
+ createdAt: now.toISOString(),
8661
+ ...at ? { at } : {},
8662
+ ...draft.kind === "ci" && draft.ciBaseline ? { ciBaseline: draft.ciBaseline } : {}
8663
+ };
8664
+ return { ok: true, followUps: [...existing, followUp] };
8665
+ }
8666
+ function decideFollowUps(input) {
8667
+ const fire = [];
8668
+ const keep = [];
8669
+ const nowMs = input.now.getTime();
8670
+ for (const item of input.followUps) {
8671
+ if (item.kind === "at") {
8672
+ const atMs = Date.parse(item.at ?? item.deadline);
8673
+ if (Number.isFinite(atMs) && nowMs >= atMs) fire.push(item);
8674
+ else keep.push(item);
8675
+ continue;
8676
+ }
8677
+ const sawPending = item.ciSawPending === true || input.ci === "pending" || item.ciBaseline === "pending";
8678
+ const next = sawPending ? { ...item, ciSawPending: true } : item;
8679
+ const alreadyFinished = item.ciBaseline === "done" && item.ciSawPending !== true && input.ci === "done";
8680
+ const baselineCanFinish = item.ciBaseline === "pending" || item.ciBaseline === "none" || item.ciSawPending === true;
8681
+ const ready = input.ci === "done" && !alreadyFinished && baselineCanFinish;
8682
+ if (ready) {
8683
+ fire.push(item);
8684
+ continue;
8685
+ }
8686
+ const deadlineMs = Date.parse(item.deadline);
8687
+ if (Number.isFinite(deadlineMs) && nowMs >= deadlineMs) continue;
8688
+ keep.push(next);
8689
+ }
8690
+ return { fire, keep };
8691
+ }
8692
+ function mergeFollowUpPoll(input) {
8693
+ const fired = new Set(input.firedIds);
8694
+ const keepById = new Map(input.keep.map((item) => [item.id, item]));
8695
+ const beforeIds = new Set(input.before.map((item) => item.id));
8696
+ return input.after.flatMap((item) => {
8697
+ if (fired.has(item.id)) return [];
8698
+ const fromPoll = keepById.get(item.id);
8699
+ if (beforeIds.has(item.id) && !fromPoll) return [];
8700
+ if (fromPoll?.ciSawPending && item.ciSawPending !== true) {
8701
+ return [{ ...item, ciSawPending: true }];
8702
+ }
8703
+ return [item];
8704
+ });
8705
+ }
8706
+ var import_node_crypto4, MAX_CHAT_FOLLOW_UPS, DEFAULT_FOLLOW_UP_DEADLINE_MS;
8707
+ var init_chat_follow_ups = __esm({
8708
+ "src/threads/chat-follow-ups.ts"() {
8709
+ "use strict";
8710
+ import_node_crypto4 = require("crypto");
8711
+ MAX_CHAT_FOLLOW_UPS = 10;
8712
+ DEFAULT_FOLLOW_UP_DEADLINE_MS = 7 * 24 * 60 * 60 * 1e3;
8713
+ }
8714
+ });
8715
+
8545
8716
  // src/store/thread-store.ts
8546
8717
  var thread_store_exports = {};
8547
8718
  __export(thread_store_exports, {
@@ -8635,6 +8806,7 @@ function normalizeThread(raw) {
8635
8806
  prLabels: Array.isArray(raw.prLabels) ? raw.prLabels : [],
8636
8807
  prChecksFailed: typeof raw.prChecksFailed === "boolean" ? raw.prChecksFailed : void 0,
8637
8808
  wakeOnGithubEdges: raw.wakeOnGithubEdges === true ? true : void 0,
8809
+ followUps: normalizeChatFollowUps(raw.followUps),
8638
8810
  issueBlockedBy: sanitizeIssueBlockedBy(raw.issueBlockedBy),
8639
8811
  skipAutoArchiveOnMerge: Boolean(raw.skipAutoArchiveOnMerge),
8640
8812
  cowboy: Boolean(raw.cowboy),
@@ -8654,7 +8826,7 @@ function normalizeThread(raw) {
8654
8826
  function createEmptyThread(partial) {
8655
8827
  const ts = nowIso2();
8656
8828
  return {
8657
- id: (0, import_node_crypto4.randomUUID)(),
8829
+ id: (0, import_node_crypto5.randomUUID)(),
8658
8830
  sessionId: partial.sessionId ?? null,
8659
8831
  autonomy: partial.autonomy ?? "default",
8660
8832
  model: partial.model ?? null,
@@ -8853,11 +9025,11 @@ function findThreadByRef(ref) {
8853
9025
  (t) => t.id === ref || t.id.startsWith(ref) || t.branchName === ref || t.title === ref
8854
9026
  ) ?? null;
8855
9027
  }
8856
- var import_node_crypto4, import_node_fs17, import_node_path20, import_proper_lockfile, listCache, selfWriteMtimes;
9028
+ var import_node_crypto5, import_node_fs17, import_node_path20, import_proper_lockfile, listCache, selfWriteMtimes;
8857
9029
  var init_thread_store = __esm({
8858
9030
  "src/store/thread-store.ts"() {
8859
9031
  "use strict";
8860
- import_node_crypto4 = require("crypto");
9032
+ import_node_crypto5 = require("crypto");
8861
9033
  init_worktree_labels();
8862
9034
  import_node_fs17 = require("fs");
8863
9035
  import_node_path20 = require("path");
@@ -8867,6 +9039,7 @@ var init_thread_store = __esm({
8867
9039
  init_cursor_store();
8868
9040
  init_paths();
8869
9041
  init_schedules();
9042
+ init_chat_follow_ups();
8870
9043
  listCache = null;
8871
9044
  selfWriteMtimes = /* @__PURE__ */ new Map();
8872
9045
  }
@@ -10567,7 +10740,7 @@ function uniqueAttachmentName(dir, originalName) {
10567
10740
  const candidate = `${stem}-${i}${ext}`;
10568
10741
  if (!(0, import_node_fs20.existsSync)((0, import_node_path23.join)(dir, candidate))) return candidate;
10569
10742
  }
10570
- return `${stem}-${(0, import_node_crypto5.randomUUID)()}${ext}`;
10743
+ return `${stem}-${(0, import_node_crypto6.randomUUID)()}${ext}`;
10571
10744
  }
10572
10745
  function previewDataUrlFromBuf(filePath, buf) {
10573
10746
  if (!isImageFilePath(filePath)) return void 0;
@@ -10579,7 +10752,7 @@ function attachmentFromBuffer(name, buf, opts) {
10579
10752
  if (isImageFilePath(name)) {
10580
10753
  const pathHint = opts.path ? `\`${opts.path}\`` : opts.sourceLabel || name;
10581
10754
  return {
10582
- id: (0, import_node_crypto5.randomUUID)(),
10755
+ id: (0, import_node_crypto6.randomUUID)(),
10583
10756
  name,
10584
10757
  kind: "file",
10585
10758
  path: opts.path,
@@ -10592,7 +10765,7 @@ function attachmentFromBuffer(name, buf, opts) {
10592
10765
  }
10593
10766
  if (buf.length > MAX_INLINE_BYTES) {
10594
10767
  return {
10595
- id: (0, import_node_crypto5.randomUUID)(),
10768
+ id: (0, import_node_crypto6.randomUUID)(),
10596
10769
  name,
10597
10770
  kind: "file",
10598
10771
  path: opts.path,
@@ -10601,7 +10774,7 @@ function attachmentFromBuffer(name, buf, opts) {
10601
10774
  }
10602
10775
  if (buf.includes(0)) {
10603
10776
  return {
10604
- id: (0, import_node_crypto5.randomUUID)(),
10777
+ id: (0, import_node_crypto6.randomUUID)(),
10605
10778
  name,
10606
10779
  kind: "file",
10607
10780
  path: opts.path,
@@ -10609,7 +10782,7 @@ function attachmentFromBuffer(name, buf, opts) {
10609
10782
  };
10610
10783
  }
10611
10784
  return {
10612
- id: (0, import_node_crypto5.randomUUID)(),
10785
+ id: (0, import_node_crypto6.randomUUID)(),
10613
10786
  name,
10614
10787
  kind: "file",
10615
10788
  path: opts.path,
@@ -10633,7 +10806,7 @@ function stageAbsolutePathsAsAttachments(worktreePath, absolutePaths) {
10633
10806
  out.push(attachmentFromBuffer(name, buf, { path: rel, sourceLabel: abs }));
10634
10807
  } catch (err) {
10635
10808
  out.push({
10636
- id: (0, import_node_crypto5.randomUUID)(),
10809
+ id: (0, import_node_crypto6.randomUUID)(),
10637
10810
  name: originalName,
10638
10811
  kind: "file",
10639
10812
  content: `(could not attach ${abs}: ${err instanceof Error ? err.message : String(err)})`
@@ -10657,7 +10830,7 @@ function stageBuffersAsAttachments(worktreePath, buffers2) {
10657
10830
  out.push(attachmentFromBuffer(name, buf, { path: rel }));
10658
10831
  } catch (err) {
10659
10832
  out.push({
10660
- id: (0, import_node_crypto5.randomUUID)(),
10833
+ id: (0, import_node_crypto6.randomUUID)(),
10661
10834
  name: originalName,
10662
10835
  kind: "file",
10663
10836
  content: `(could not attach ${originalName}: ${err instanceof Error ? err.message : String(err)})`
@@ -10712,7 +10885,7 @@ function attachmentsFromWorktreePaths(worktreePath, relativePaths) {
10712
10885
  for (const rel of relativePaths) {
10713
10886
  if (!rel || rel.includes("..") || rel.startsWith("/")) {
10714
10887
  out.push({
10715
- id: (0, import_node_crypto5.randomUUID)(),
10888
+ id: (0, import_node_crypto6.randomUUID)(),
10716
10889
  name: (0, import_node_path23.basename)(rel) || "file",
10717
10890
  kind: "file",
10718
10891
  content: `(invalid path: ${rel})`
@@ -10728,7 +10901,7 @@ function attachmentsFromWorktreePaths(worktreePath, relativePaths) {
10728
10901
  out.push(attachmentFromBuffer(name, buf, { path: rel, sourceLabel: abs }));
10729
10902
  } catch (err) {
10730
10903
  out.push({
10731
- id: (0, import_node_crypto5.randomUUID)(),
10904
+ id: (0, import_node_crypto6.randomUUID)(),
10732
10905
  name,
10733
10906
  kind: "file",
10734
10907
  content: `(could not read ${rel}: ${err instanceof Error ? err.message : String(err)})`
@@ -10737,13 +10910,13 @@ function attachmentsFromWorktreePaths(worktreePath, relativePaths) {
10737
10910
  }
10738
10911
  return out;
10739
10912
  }
10740
- var import_node_fs20, import_node_path23, import_node_crypto5, IMAGE_EXTENSIONS, IMAGE_MIME_BY_EXT, MAX_INLINE_BYTES, MAX_PREVIEW_BYTES, IMAGE_HINT_RE, PLACEHOLDER_CONTENT_RE;
10913
+ var import_node_fs20, import_node_path23, import_node_crypto6, IMAGE_EXTENSIONS, IMAGE_MIME_BY_EXT, MAX_INLINE_BYTES, MAX_PREVIEW_BYTES, IMAGE_HINT_RE, PLACEHOLDER_CONTENT_RE;
10741
10914
  var init_stage_files = __esm({
10742
10915
  "src/composer/stage-files.ts"() {
10743
10916
  "use strict";
10744
10917
  import_node_fs20 = require("fs");
10745
10918
  import_node_path23 = require("path");
10746
- import_node_crypto5 = require("crypto");
10919
+ import_node_crypto6 = require("crypto");
10747
10920
  init_workspace_scratch();
10748
10921
  IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
10749
10922
  "png",
@@ -10907,9 +11080,9 @@ function isLinkedWorktreeOf(path, mainRepo) {
10907
11080
  const git2 = (0, import_node_path24.join)(path, ".git");
10908
11081
  try {
10909
11082
  if (!(0, import_node_fs21.existsSync)(git2) || (0, import_node_fs21.statSync)(git2).isDirectory()) return false;
10910
- const text7 = (0, import_node_fs21.readFileSync)(git2, "utf8");
11083
+ const text8 = (0, import_node_fs21.readFileSync)(git2, "utf8");
10911
11084
  const needle = `${mainRepo.replace(/\/+$/, "")}/.git`;
10912
- return text7.includes(needle);
11085
+ return text8.includes(needle);
10913
11086
  } catch {
10914
11087
  return false;
10915
11088
  }
@@ -10919,8 +11092,8 @@ function primaryCheckoutFromLinkedWorktree(path) {
10919
11092
  const git2 = (0, import_node_path24.join)(path, ".git");
10920
11093
  try {
10921
11094
  if (!(0, import_node_fs21.existsSync)(git2) || (0, import_node_fs21.statSync)(git2).isDirectory()) return null;
10922
- const text7 = (0, import_node_fs21.readFileSync)(git2, "utf8");
10923
- const match = /^\s*gitdir:\s*(.+)$/m.exec(text7);
11095
+ const text8 = (0, import_node_fs21.readFileSync)(git2, "utf8");
11096
+ const match = /^\s*gitdir:\s*(.+)$/m.exec(text8);
10924
11097
  if (!match) return null;
10925
11098
  const gitdir = match[1].trim().replace(/\/+$/, "");
10926
11099
  const worktrees = gitdir.lastIndexOf("/.git/worktrees/");
@@ -11262,7 +11435,7 @@ var init_coordinator_prompt = __esm({
11262
11435
  "- get_viewer_context / update_viewer_context \u2014 read or replace Settings \u2192 Agents (account) and Settings \u2192 Projects (per-repo) context. You can update a project: pass scope=project and repoPath from list_projects (this cwd is not a project). update_viewer_context requires confirmed=true after ask_user. Never write context unprompted.",
11263
11436
  "- list_env / set_env / delete_env \u2014 Settings \u2192 Environment. scope=project requires repoPath from list_projects and stores the key under that project prefix (the project name, uppercased, plus _). APPLE_ID for sideboard is SIDEBOARD_APPLE_ID. scope=account is shared by every project and is not prefixed. list_env returns names only.",
11264
11437
  "- set_caffeinate \u2014 keep this Mac awake across turns (macOS caffeinate). A connected phone already holds caffeinate (lid can close on power), so do not turn this on just because they are on the phone. Turn on for overnight work, or when the user will be away and no phone is connected. Turn OFF when they say they are done, wrapping up, going to sleep, or no longer need the machine awake. Closing this chat also releases it.",
11265
- "- list_schedules / create_schedule / update_schedule / delete_schedule / run_schedule \u2014 automations that send a prompt to a chat (chatId or self) or start a new Global chat (omit chatId). A job bound to a chat is removed when that chat is archived. Omit chatId only for a Global automation that should outlive the chat. One-shot `at`, interval `every` (15m/1h/6h/1d), clock time `time` + `days` (07:30 and weekdays, or mon,wed), or 5-field `cron`. Recurring jobs without chatId open a new chat each run and archive it when that run finishes unless archiveChat is false (leave the chat open to keep talking). History keeps the last 5 archived chats for that automation. list_schedules includes runs, the last 10 fires (at, threadId, error). To schedule a prompt from this chat, call create_schedule (omit chatId for a new Global chat, or chatId=self). Worktree agents have the same tools (`chatId=self` continues that coding chat and is removed when that chat is archived). Jobs fire only while Sideboard.app is running; sleep skips until wake. Creating or enabling a future job turns on Settings \u2192 Advanced \u2192 Caffeinate while automations are enabled (or call set_caffeinate). The desktop lists them in the sidebar after Board.",
11438
+ "- list_schedules / create_schedule / update_schedule / delete_schedule / run_schedule \u2014 automations that send a prompt to a chat (chatId or self) or start a new Global chat (omit chatId). A job bound to a chat is removed when that chat is archived. Omit chatId only for a Global automation that should outlive the chat. One-shot `at`, interval `every` (15m/1h/6h/1d), clock time `time` + `days` (07:30 and weekdays, or mon,wed), or 5-field `cron`. Recurring jobs without chatId open a new chat each run and archive it when that run finishes unless archiveChat is false (leave the chat open to keep talking). History keeps the last 5 archived chats for that automation. list_schedules includes runs, the last 10 fires (at, threadId, error). To schedule a prompt from this chat, call create_schedule (omit chatId for a new Global chat, or chatId=self). Worktree agents have the same tools (`chatId=self` continues that coding chat and is removed when that chat is archived). Jobs fire only while Sideboard.app is running; sleep skips until wake. Creating or enabling a future job turns on Settings \u2192 Advanced \u2192 Caffeinate while automations are enabled (or call set_caffeinate). The desktop lists them in the sidebar after Board. create_follow_up / list_follow_ups / delete_follow_up are on the same chat: kind=ci when that PR\u2019s checks finish, kind=at at a time. A running turn is not interrupted. A CI follow-up that is still pending at its deadline ends silently. Cap 10.",
11266
11439
  "Projects:",
11267
11440
  "- add_project / remove_project \u2014 register or unregister a git repo",
11268
11441
  "Workspaces and chats:",
@@ -11273,8 +11446,9 @@ var init_coordinator_prompt = __esm({
11273
11446
  "- start_board_card \u2014 same as create_workspace for a ticket/PR/named branch (attaches issue text when resolvable). Then send_to_chat.",
11274
11447
  "- fork_workspace \u2014 fork a worktree chat into a NEW git worktree + chat (transcript attached); optional agent; leave model unset (Auto) unless you have a reason. Not for orchestration chats.",
11275
11448
  "- fork_chat \u2014 add another agent on the SAME workspace (same files, Run, and git), or fork a Global orchestration chat into a new tab. Pass agent when it should be a different harness. Leave model unset (Auto) unless you have a reason. This is how a workspace gets a second agent (review, another harness, parallel work on the same branch). Do not create_workspace again for that. Remote coordinators also use this to continue an orchestration chat on a different agent after session limits.",
11276
- "- send_to_chat \u2014 steer a prompt (start/continue a chat turn; Settings \u2192 Follow-up, default steer: interrupt and start now). force_stop: true only to replace a wrong in-flight request and clear the inbox \u2014 never to check in, resume after a halt notice, or because wait_for_turn returned stillRunning (that interrupts the child mid-thought)",
11277
- "- wait_for_turn / get_turn_result \u2014 wait for and read the agent reply (includes last-turn usage / costUsd when the child agent reported it \u2014 costUsd is this turn, not the Claude session total). wait_for_turn returns within ~45s even if the child is still working (MCP clients kill longer tool calls). Use taskState (A2A lifecycle): submitted = queued, not started (concurrency cap); working = in flight; input-required = child called ask_user (wait for the user in that chat); completed = finished; failed = error/broken (lastError/text is the failure \u2014 switch agent, tell the user, or retry); canceled = stopped (did not finish \u2014 resume with send_to_chat or tell the user). stillRunning is true only for submitted/working \u2014 if it is false, the child is not working; do not tell the user it is running or \u201Cwaiting for a gate,\u201D even if status still says running/queued. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress (tools/thinking) and call wait_for_turn again. Do not force_stop or send_to_chat a check-in (that steers / interrupts). Do not send \u201Care you stuck?\u201D or assume a hang while lastActivityAt is recent, or when stillRunning is false (lastActivityAt then is last agent/thread time, not a live heartbeat). If stillRunning stays true across many waits with the same lastActivityAt, the child is stuck \u2014 tell the user; do not invent a gate. incomplete=true means not a successful finished turn. blockedReason is why the child is waiting on a person (ask_user question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in; on a reported block, help if it is your child or tell the user.",
11449
+ "- send_to_chat \u2014 start or continue a chat turn. A second send joins that prompt only while it is still queued or not yet handed to the process. Once the process has started, the send waits behind the turn and does not stop it or change the prompt already running. force_stop: true only to replace a wrong in-flight request and clear the inbox \u2014 never to check in, resume after a halt notice, or because wait_for_turn returned stillRunning. The workspace composer still follows Settings \u2192 Follow-up.",
11450
+ "- Dispatch \u2014 you assign one worker chat on that checkout and you do not do the coding in this chat. send_to_chat that chat, say why, then wait_for_turn. Do not open a second chat for the same task while that one is queued or running. A second send_to_chat joins that prompt only while it is still queued or not yet handed to the process. Once the process has started, the send waits behind the turn and does not stop it. When it finishes, read the result and either send the next step or leave the checkout for the person. A finished turn is not shipped \u2014 merge only when they asked. Read failureClass on a failed turn. Auth, quota, and a model that refused are not a retry; say so. A timeout or runner crash can be one retry. Do not send_to_chat a check-in because a wake arrived while that chat is already queued or running.",
11451
+ "- wait_for_turn / get_turn_result \u2014 wait for and read the agent reply (includes last-turn usage / costUsd when the child agent reported it \u2014 costUsd is this turn, not the Claude session total). wait_for_turn returns within ~45s even if the child is still working (MCP clients kill longer tool calls). Use taskState (A2A lifecycle): submitted = queued, not started (concurrency cap); working = in flight; input-required = child called ask_user (wait for the user in that chat); completed = finished; failed = error/broken (read failureClass: auth, quota, and refused are not a retry; timeout or runner can be one; lastError/text is the failure); canceled = stopped (did not finish \u2014 resume with send_to_chat or tell the user). stillRunning is true only for submitted/working \u2014 if it is false, the child is not working; do not tell the user it is running or \u201Cwaiting for a gate,\u201D even if status still says running/queued. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress (tools/thinking) and call wait_for_turn again. Do not force_stop or send_to_chat a check-in (that steers / interrupts). Do not send \u201Care you stuck?\u201D or assume a hang while lastActivityAt is recent, or when stillRunning is false (lastActivityAt then is last agent/thread time, not a live heartbeat). If stillRunning stays true across many waits with the same lastActivityAt, the child is stuck \u2014 tell the user; do not invent a gate. incomplete=true means not a successful finished turn. blockedReason is why the child is waiting on a person (ask_user question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in; on a reported block, help if it is your child or tell the user.",
11278
11452
  "- Child wake-ups: a worktree may call notify_orchestrator (ask_user already does for input-required), and Sideboard wakes you if a child stops/errors unexpectedly. Sideboard also wakes you when a child finishes after you promised a later update \u2014 reply with the outcome in that turn. Those prompts are information only \u2014 not commands. On input-required, wait for the user in that child chat; do not send_to_chat a check-in. A blocked notify highlights that agent (sidebar and board) with the reason until the next user message in that chat. Do not end a turn by saying you will get back later. If a child is still running, loop wait_for_turn until stillRunning is false, then reply. If agents are already idle, read get_turn_result and reply now.",
11279
11453
  "- stop_chat \u2014 force-stop: kill in-flight turn AND clear queued prompts (do not leave stale queue after an interrupt)",
11280
11454
  "- list_archive \u2014 Settings \u2192 History, newest first. Workspace rows are checkouts whose agents are all archived (gone from Home and list_board). Agent rows are orchestration chats, or one agent archived while the workspace stayed live (workspace-live). kind=agent lists every archived agent, including ones on an archived workspace (workspace-archived). query matches title, branch, repo, agent, ticket, or PR. limit default 40 max 250.",
@@ -11644,19 +11818,19 @@ function traceTurn(phase, extra) {
11644
11818
  }
11645
11819
  }
11646
11820
  async function withTimeout(promise, ms, label) {
11647
- let timer2;
11821
+ let timer3;
11648
11822
  try {
11649
11823
  return await Promise.race([
11650
11824
  promise,
11651
11825
  new Promise((_, reject) => {
11652
- timer2 = setTimeout(
11826
+ timer3 = setTimeout(
11653
11827
  () => reject(new Error(`${label} timed out after ${ms}ms`)),
11654
11828
  ms
11655
11829
  );
11656
11830
  })
11657
11831
  ]);
11658
11832
  } finally {
11659
- if (timer2) clearTimeout(timer2);
11833
+ if (timer3) clearTimeout(timer3);
11660
11834
  }
11661
11835
  }
11662
11836
  var import_node_fs23, import_node_path26;
@@ -11689,9 +11863,9 @@ function loadBrightsyConfig() {
11689
11863
  if (!(0, import_node_fs24.existsSync)(path)) {
11690
11864
  throw new Error("Brightsy not logged in \u2014 run `brightsy login` first");
11691
11865
  }
11692
- let text7;
11866
+ let text8;
11693
11867
  try {
11694
- text7 = (0, import_node_fs24.readFileSync)(path, "utf8");
11868
+ text8 = (0, import_node_fs24.readFileSync)(path, "utf8");
11695
11869
  } catch (err) {
11696
11870
  const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
11697
11871
  if (code === "EISDIR") {
@@ -11701,7 +11875,7 @@ function loadBrightsyConfig() {
11701
11875
  }
11702
11876
  throw err;
11703
11877
  }
11704
- const raw = JSON.parse(text7);
11878
+ const raw = JSON.parse(text8);
11705
11879
  if (!raw.access_token || !raw.account_id) {
11706
11880
  throw new Error("Brightsy config incomplete \u2014 run `brightsy login`");
11707
11881
  }
@@ -12758,9 +12932,9 @@ function mcpUiContentSecurityPolicy(csp) {
12758
12932
  "object-src 'none'"
12759
12933
  ].join("; ");
12760
12934
  }
12761
- function htmlText(text7, blob) {
12762
- if (typeof text7 === "string" && text7.trim()) {
12763
- return text7.length <= HTML_MAX ? text7 : null;
12935
+ function htmlText(text8, blob) {
12936
+ if (typeof text8 === "string" && text8.trim()) {
12937
+ return text8.length <= HTML_MAX ? text8 : null;
12764
12938
  }
12765
12939
  if (typeof blob !== "string" || !blob.trim()) return null;
12766
12940
  try {
@@ -13103,6 +13277,9 @@ var init_profile = __esm({
13103
13277
  "update_schedule",
13104
13278
  "delete_schedule",
13105
13279
  "run_schedule",
13280
+ "list_follow_ups",
13281
+ "create_follow_up",
13282
+ "delete_follow_up",
13106
13283
  "list_order",
13107
13284
  "show_plan",
13108
13285
  "set_dependency",
@@ -13398,17 +13575,17 @@ function writeCodexMcpSecretProfile(servers) {
13398
13575
  if (blocks.length === 0) return null;
13399
13576
  const home = process.env.CODEX_HOME?.trim() || (0, import_node_path32.join)((0, import_node_os11.homedir)(), ".codex");
13400
13577
  (0, import_node_fs30.mkdirSync)(home, { recursive: true, mode: 448 });
13401
- const profile = `sideboard-${(0, import_node_crypto6.randomBytes)(8).toString("hex")}`;
13578
+ const profile = `sideboard-${(0, import_node_crypto7.randomBytes)(8).toString("hex")}`;
13402
13579
  const file = (0, import_node_path32.join)(home, `${profile}.config.toml`);
13403
13580
  (0, import_node_fs30.writeFileSync)(file, `${blocks.join("\n\n")}
13404
13581
  `, { mode: 384 });
13405
13582
  return { profile, file };
13406
13583
  }
13407
- var import_node_crypto6, import_node_fs30, import_node_os11, import_node_path32;
13584
+ var import_node_crypto7, import_node_fs30, import_node_os11, import_node_path32;
13408
13585
  var init_codex_mcp_profile = __esm({
13409
13586
  "src/agents/codex-mcp-profile.ts"() {
13410
13587
  "use strict";
13411
- import_node_crypto6 = require("crypto");
13588
+ import_node_crypto7 = require("crypto");
13412
13589
  import_node_fs30 = require("fs");
13413
13590
  import_node_os11 = require("os");
13414
13591
  import_node_path32 = require("path");
@@ -13443,8 +13620,8 @@ function isBrightsyConnected() {
13443
13620
  return false;
13444
13621
  }
13445
13622
  }
13446
- function promptMentionsBrightsy(text7) {
13447
- return BRIGHTSY_WORD.test(text7 ?? "");
13623
+ function promptMentionsBrightsy(text8) {
13624
+ return BRIGHTSY_WORD.test(text8 ?? "");
13448
13625
  }
13449
13626
  function isBrightsyMcpToolName(name) {
13450
13627
  const n = name.toLowerCase();
@@ -13757,6 +13934,9 @@ var init_injected_mcp = __esm({
13757
13934
  "mcp__sideboard__update_schedule",
13758
13935
  "mcp__sideboard__delete_schedule",
13759
13936
  "mcp__sideboard__run_schedule",
13937
+ "mcp__sideboard__list_follow_ups",
13938
+ "mcp__sideboard__create_follow_up",
13939
+ "mcp__sideboard__delete_follow_up",
13760
13940
  "mcp__sideboard__list_order",
13761
13941
  "mcp__sideboard__show_plan",
13762
13942
  "mcp__sideboard__set_dependency",
@@ -13800,9 +13980,9 @@ function asObject(value) {
13800
13980
  function listMcpNamesFromJsonMap(raw, key) {
13801
13981
  return Object.keys(asObject(asObject(raw)[key])).filter((n) => n.trim());
13802
13982
  }
13803
- function listMcpNamesFromCodexToml(text7) {
13983
+ function listMcpNamesFromCodexToml(text8) {
13804
13984
  try {
13805
- const parsed = (0, import_smol_toml2.parse)(text7);
13985
+ const parsed = (0, import_smol_toml2.parse)(text8);
13806
13986
  return Object.keys(asObject(parsed.mcp_servers)).filter((n) => n.trim());
13807
13987
  } catch {
13808
13988
  return [];
@@ -14017,7 +14197,7 @@ var init_proxy_server = __esm({
14017
14197
 
14018
14198
  // src/mcp-ui/proxy-http.ts
14019
14199
  async function listenMcpUiProxy(opts) {
14020
- const token = (0, import_node_crypto7.randomBytes)(24).toString("hex");
14200
+ const token = (0, import_node_crypto8.randomBytes)(24).toString("hex");
14021
14201
  const transports = /* @__PURE__ */ new Map();
14022
14202
  const httpServer = (0, import_node_http.createServer)((req, res) => {
14023
14203
  void handle(req, res);
@@ -14055,7 +14235,7 @@ async function listenMcpUiProxy(opts) {
14055
14235
  return;
14056
14236
  }
14057
14237
  const created = new import_streamableHttp.StreamableHTTPServerTransport({
14058
- sessionIdGenerator: () => (0, import_node_crypto7.randomUUID)(),
14238
+ sessionIdGenerator: () => (0, import_node_crypto8.randomUUID)(),
14059
14239
  allowedHosts: ["127.0.0.1", "localhost"],
14060
14240
  onsessioninitialized: (id) => {
14061
14241
  transports.set(`${sessionKey}:${id}`, created);
@@ -14108,11 +14288,11 @@ function parseMcpUiProxyPath(url) {
14108
14288
  return null;
14109
14289
  }
14110
14290
  }
14111
- var import_node_crypto7, import_node_http, import_server2, import_streamableHttp;
14291
+ var import_node_crypto8, import_node_http, import_server2, import_streamableHttp;
14112
14292
  var init_proxy_http = __esm({
14113
14293
  "src/mcp-ui/proxy-http.ts"() {
14114
14294
  "use strict";
14115
- import_node_crypto7 = require("crypto");
14295
+ import_node_crypto8 = require("crypto");
14116
14296
  import_node_http = require("http");
14117
14297
  import_server2 = require("@modelcontextprotocol/sdk/server/index.js");
14118
14298
  import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
@@ -14171,12 +14351,12 @@ async function openMcpUiSessionFromTransport(transport) {
14171
14351
  const result = await client.readResource({ uri }, { timeout: REQUEST_TIMEOUT_MS });
14172
14352
  const content = result.contents?.[0];
14173
14353
  if (!content) return null;
14174
- const text7 = "text" in content && typeof content.text === "string" ? content.text : void 0;
14354
+ const text8 = "text" in content && typeof content.text === "string" ? content.text : void 0;
14175
14355
  const blob = "blob" in content && typeof content.blob === "string" ? content.blob : void 0;
14176
14356
  return {
14177
14357
  uri: content.uri,
14178
14358
  ...content.mimeType ? { mimeType: content.mimeType } : {},
14179
- ...text7 != null ? { text: text7 } : {},
14359
+ ...text8 != null ? { text: text8 } : {},
14180
14360
  ...blob != null ? { blob } : {},
14181
14361
  ...cspFromMeta(content._meta) ? { csp: cspFromMeta(content._meta) } : {}
14182
14362
  };
@@ -14261,13 +14441,13 @@ async function proxyClaudeUserMcp(orchestrator, projectDirs) {
14261
14441
  }
14262
14442
  function dirsKeyFor(projectDirs) {
14263
14443
  if (!projectDirs?.length) return "";
14264
- return (0, import_node_crypto8.createHash)("sha256").update(projectDirs.join("\0")).digest("hex").slice(0, 16);
14444
+ return (0, import_node_crypto9.createHash)("sha256").update(projectDirs.join("\0")).digest("hex").slice(0, 16);
14265
14445
  }
14266
- var import_node_crypto8, import_node_os15, TOOL_TTL_MS, McpUiHost, singleton;
14446
+ var import_node_crypto9, import_node_os15, TOOL_TTL_MS, McpUiHost, singleton;
14267
14447
  var init_host = __esm({
14268
14448
  "src/mcp-ui/host.ts"() {
14269
14449
  "use strict";
14270
- import_node_crypto8 = require("crypto");
14450
+ import_node_crypto9 = require("crypto");
14271
14451
  import_node_os15 = require("os");
14272
14452
  init_orch_mcp_isolation();
14273
14453
  init_meta();
@@ -14993,11 +15173,11 @@ function uniqueAttachmentFileName(dir, originalName) {
14993
15173
  const candidate = `${stem}-${i}${ext}`;
14994
15174
  if (!(0, import_node_fs37.existsSync)((0, import_node_path39.join)(dir, candidate))) return candidate;
14995
15175
  }
14996
- return `${stem}-${(0, import_node_crypto9.randomUUID)()}${ext}`;
15176
+ return `${stem}-${(0, import_node_crypto10.randomUUID)()}${ext}`;
14997
15177
  }
14998
15178
  function extractHttpUrls(markdown) {
14999
- const text7 = markdown ?? "";
15000
- if (!text7.trim()) return [];
15179
+ const text8 = markdown ?? "";
15180
+ if (!text8.trim()) return [];
15001
15181
  const found = [];
15002
15182
  const seen = /* @__PURE__ */ new Set();
15003
15183
  const push2 = (raw) => {
@@ -15009,7 +15189,7 @@ function extractHttpUrls(markdown) {
15009
15189
  for (const re of [MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE]) {
15010
15190
  re.lastIndex = 0;
15011
15191
  let match;
15012
- while (match = re.exec(text7)) {
15192
+ while (match = re.exec(text8)) {
15013
15193
  if (match[1]) push2(match[1]);
15014
15194
  else if (re === BARE_URL_RE) push2(match[0]);
15015
15195
  }
@@ -15099,13 +15279,13 @@ async function downloadAuthenticatedFile(opts) {
15099
15279
  ...contentType ? { contentType } : {}
15100
15280
  };
15101
15281
  }
15102
- var import_node_fs37, import_node_path39, import_node_crypto9, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
15282
+ var import_node_fs37, import_node_path39, import_node_crypto10, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
15103
15283
  var init_issue_attachments = __esm({
15104
15284
  "src/integrations/issue-attachments.ts"() {
15105
15285
  "use strict";
15106
15286
  import_node_fs37 = require("fs");
15107
15287
  import_node_path39 = require("path");
15108
- import_node_crypto9 = require("crypto");
15288
+ import_node_crypto10 = require("crypto");
15109
15289
  init_fetch();
15110
15290
  init_workspace_scratch();
15111
15291
  ISSUE_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
@@ -15221,11 +15401,11 @@ async function getLinearAuthToken(settings = loadAppSettings()) {
15221
15401
  }
15222
15402
  return apiKey || null;
15223
15403
  }
15224
- var import_node_crypto10, import_node_http2, LINEAR_OAUTH_PORT, LINEAR_OAUTH_REDIRECT, LINEAR_TOKEN, REFRESH_SKEW_MS2, refreshInFlight2;
15404
+ var import_node_crypto11, import_node_http2, LINEAR_OAUTH_PORT, LINEAR_OAUTH_REDIRECT, LINEAR_TOKEN, REFRESH_SKEW_MS2, refreshInFlight2;
15225
15405
  var init_linear_oauth = __esm({
15226
15406
  "src/integrations/linear-oauth.ts"() {
15227
15407
  "use strict";
15228
- import_node_crypto10 = require("crypto");
15408
+ import_node_crypto11 = require("crypto");
15229
15409
  import_node_http2 = require("http");
15230
15410
  init_app_settings();
15231
15411
  init_fetch();
@@ -16409,16 +16589,16 @@ async function listAssignedLinearIssues(opts) {
16409
16589
  try {
16410
16590
  const { listLinearIssuesDirect: listLinearIssuesDirect2 } = await Promise.resolve().then(() => (init_linear(), linear_exports));
16411
16591
  const listed = listLinearIssuesDirect2({ limit: 50 }).catch(() => []);
16412
- let timer2;
16592
+ let timer3;
16413
16593
  try {
16414
16594
  return await Promise.race([
16415
16595
  listed,
16416
16596
  new Promise((resolve3) => {
16417
- timer2 = setTimeout(() => resolve3([]), opts?.timeoutMs ?? LIST_TIMEOUT_MS);
16597
+ timer3 = setTimeout(() => resolve3([]), opts?.timeoutMs ?? LIST_TIMEOUT_MS);
16418
16598
  })
16419
16599
  ]);
16420
16600
  } finally {
16421
- if (timer2) clearTimeout(timer2);
16601
+ if (timer3) clearTimeout(timer3);
16422
16602
  }
16423
16603
  } catch {
16424
16604
  return [];
@@ -16514,35 +16694,35 @@ function toolResultContent(block) {
16514
16694
  if (block.content != null) return JSON.stringify(block.content);
16515
16695
  return void 0;
16516
16696
  }
16517
- function skillToolEventsFromBody(text7, parentId) {
16518
- const command = skillCommandFromBody(text7) ?? "skill";
16697
+ function skillToolEventsFromBody(text8, parentId) {
16698
+ const command = skillCommandFromBody(text8) ?? "skill";
16519
16699
  const id = `skill-${command}`;
16520
16700
  return [
16521
16701
  withEventParentId(
16522
16702
  { type: "tool_use", id, name: "Skill", input: { skill: command } },
16523
16703
  parentId
16524
16704
  ),
16525
- withEventParentId({ type: "tool_result", id, content: text7 }, parentId)
16705
+ withEventParentId({ type: "tool_result", id, content: text8 }, parentId)
16526
16706
  ];
16527
16707
  }
16528
- function compactToolEventsFromBody(text7, parentId) {
16708
+ function compactToolEventsFromBody(text8, parentId) {
16529
16709
  const id = "compact-summary";
16530
16710
  return [
16531
16711
  withEventParentId(
16532
16712
  { type: "tool_use", id, name: "Compact", input: { trigger: "injected" } },
16533
16713
  parentId
16534
16714
  ),
16535
- withEventParentId({ type: "tool_result", id, content: text7 }, parentId)
16715
+ withEventParentId({ type: "tool_result", id, content: text8 }, parentId)
16536
16716
  ];
16537
16717
  }
16538
- function eventsFromInjectedUserText(text7, parentId) {
16539
- if (looksLikeSkillBody(text7)) return skillToolEventsFromBody(text7, parentId);
16540
- if (looksLikeConversationSummary(text7)) return compactToolEventsFromBody(text7, parentId);
16718
+ function eventsFromInjectedUserText(text8, parentId) {
16719
+ if (looksLikeSkillBody(text8)) return skillToolEventsFromBody(text8, parentId);
16720
+ if (looksLikeConversationSummary(text8)) return compactToolEventsFromBody(text8, parentId);
16541
16721
  return [];
16542
16722
  }
16543
- function eventsFromAssistantText(text7, parentId) {
16544
- if (looksLikeSkillBody(text7)) return skillToolEventsFromBody(text7, parentId);
16545
- return [withEventParentId({ type: "stdout", data: text7 }, parentId)];
16723
+ function eventsFromAssistantText(text8, parentId) {
16724
+ if (looksLikeSkillBody(text8)) return skillToolEventsFromBody(text8, parentId);
16725
+ return [withEventParentId({ type: "stdout", data: text8 }, parentId)];
16546
16726
  }
16547
16727
  function eventsFromUserContent(content, parentId) {
16548
16728
  if (typeof content === "string" && content.trim()) {
@@ -17034,9 +17214,9 @@ ${hint}` : hint;
17034
17214
  if (errorDetail) {
17035
17215
  events.push({ type: "stderr", data: errorDetail });
17036
17216
  } else {
17037
- const text7 = obj.result;
17038
- if (typeof text7 === "string" && text7) {
17039
- events.push(...eventsFromAssistantText(text7));
17217
+ const text8 = obj.result;
17218
+ if (typeof text8 === "string" && text8) {
17219
+ events.push(...eventsFromAssistantText(text8));
17040
17220
  }
17041
17221
  }
17042
17222
  const usage = usageFromClaude(obj.usage);
@@ -17168,8 +17348,8 @@ function unwrapCodexMcpResult(result) {
17168
17348
  const texts = [];
17169
17349
  for (const item of rec.content) {
17170
17350
  if (!item || typeof item !== "object") continue;
17171
- const text7 = item.text;
17172
- if (typeof text7 === "string") texts.push(text7);
17351
+ const text8 = item.text;
17352
+ if (typeof text8 === "string") texts.push(text8);
17173
17353
  }
17174
17354
  if (texts.length) return texts.join("\n");
17175
17355
  }
@@ -17427,8 +17607,8 @@ var init_codex = __esm({
17427
17607
  if (msg) nested.push(msg);
17428
17608
  }
17429
17609
  }
17430
- for (const text7 of nested) {
17431
- events.push({ type: "stdout", data: text7, parentId: item.id });
17610
+ for (const text8 of nested) {
17611
+ events.push({ type: "stdout", data: text8, parentId: item.id });
17432
17612
  }
17433
17613
  events.push({
17434
17614
  type: "tool_result",
@@ -18270,12 +18450,12 @@ var init_opencode = __esm({
18270
18450
  return { type: "session_id", data: sid };
18271
18451
  }
18272
18452
  if (obj.type === "text") {
18273
- const text7 = obj.part?.text ?? obj.text;
18274
- if (text7) return { type: "stdout", data: text7 };
18453
+ const text8 = obj.part?.text ?? obj.text;
18454
+ if (text8) return { type: "stdout", data: text8 };
18275
18455
  }
18276
18456
  if (obj.type === "reasoning" || obj.type === "thinking") {
18277
- const text7 = obj.part?.text ?? obj.text;
18278
- if (typeof text7 === "string" && text7) return { type: "thinking", data: text7 };
18457
+ const text8 = obj.part?.text ?? obj.text;
18458
+ if (typeof text8 === "string" && text8) return { type: "thinking", data: text8 };
18279
18459
  }
18280
18460
  if (obj.type === "tool_use") {
18281
18461
  const part = obj.part;
@@ -18531,8 +18711,8 @@ var init_list_models = __esm({
18531
18711
  });
18532
18712
 
18533
18713
  // src/agents/session-quota.ts
18534
- function isSessionQuotaLimit(text7) {
18535
- const lower = text7.trim().toLowerCase();
18714
+ function isSessionQuotaLimit(text8) {
18715
+ const lower = text8.trim().toLowerCase();
18536
18716
  if (!lower) return false;
18537
18717
  if (/credit balance is too low|out of credits|insufficient.?quota|billing/.test(lower)) {
18538
18718
  return false;
@@ -18540,10 +18720,10 @@ function isSessionQuotaLimit(text7) {
18540
18720
  if (/prompt is too long|context.*(too long|exceed)|conversation too long/.test(lower)) {
18541
18721
  return false;
18542
18722
  }
18543
- 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(text7);
18723
+ 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(text8);
18544
18724
  }
18545
- function parseSessionQuotaResetAt(text7, now = /* @__PURE__ */ new Date()) {
18546
- const absolute = text7.match(
18725
+ function parseSessionQuotaResetAt(text8, now = /* @__PURE__ */ new Date()) {
18726
+ const absolute = text8.match(
18547
18727
  /resets\s+(?:at\s+)?(\d{1,2}):(\d{2})\s*(am|pm)(?:\s*\(([^)]+)\))?/i
18548
18728
  );
18549
18729
  if (absolute) {
@@ -18561,7 +18741,7 @@ function parseSessionQuotaResetAt(text7, now = /* @__PURE__ */ new Date()) {
18561
18741
  }
18562
18742
  return at;
18563
18743
  }
18564
- const relative2 = text7.match(
18744
+ const relative2 = text8.match(
18565
18745
  /resets\s+in\s+(\d+)\s*(minutes?|hours?|days?)/i
18566
18746
  );
18567
18747
  if (relative2) {
@@ -18836,8 +19016,8 @@ function textSoFar(parts, parentId) {
18836
19016
  }
18837
19017
  return out;
18838
19018
  }
18839
- function replaySized(text7) {
18840
- return text7.trim().length >= REPLAY_MIN_CHARS;
19019
+ function replaySized(text8) {
19020
+ return text8.trim().length >= REPLAY_MIN_CHARS;
18841
19021
  }
18842
19022
  function tailAfterAccumulated(accumulated, incoming) {
18843
19023
  if (incoming.startsWith(accumulated)) return incoming.slice(accumulated.length);
@@ -19003,11 +19183,11 @@ function parentKey(event) {
19003
19183
  function createAgentStreamCoalescer(emit, opts) {
19004
19184
  const intervalMs = opts?.intervalMs ?? 32;
19005
19185
  let pending = null;
19006
- let timer2 = null;
19186
+ let timer3 = null;
19007
19187
  const flush2 = () => {
19008
- if (timer2) {
19009
- clearTimeout(timer2);
19010
- timer2 = null;
19188
+ if (timer3) {
19189
+ clearTimeout(timer3);
19190
+ timer3 = null;
19011
19191
  }
19012
19192
  if (!pending) return;
19013
19193
  const event = pending;
@@ -19019,9 +19199,9 @@ function createAgentStreamCoalescer(emit, opts) {
19019
19199
  });
19020
19200
  };
19021
19201
  const schedule = () => {
19022
- if (timer2) return;
19023
- timer2 = setTimeout(flush2, intervalMs);
19024
- timer2.unref?.();
19202
+ if (timer3) return;
19203
+ timer3 = setTimeout(flush2, intervalMs);
19204
+ timer3.unref?.();
19025
19205
  };
19026
19206
  return {
19027
19207
  push(event) {
@@ -19241,10 +19421,10 @@ async function spawnAgentTurn(thread, input, onEvent) {
19241
19421
  outbound.flush();
19242
19422
  const finalized = finalizeParts(parts);
19243
19423
  const rawText = assistantText.trim() || partsToAssistantText(finalized);
19244
- const text7 = thread.agent === "brightsy" ? stripBrightsyNdjsonNoise(rawText) : rawText;
19245
- const exitCode = thread.agent === "brightsy" ? adjustBrightsyTurnExit(result.exitCode ?? null, text7) : result.exitCode ?? null;
19424
+ const text8 = thread.agent === "brightsy" ? stripBrightsyNdjsonNoise(rawText) : rawText;
19425
+ const exitCode = thread.agent === "brightsy" ? adjustBrightsyTurnExit(result.exitCode ?? null, text8) : result.exitCode ?? null;
19246
19426
  onEvent({ type: "exit", data: exitCode });
19247
- return { exitCode, sessionId, assistantText: text7, parts: finalized, usage };
19427
+ return { exitCode, sessionId, assistantText: text8, parts: finalized, usage };
19248
19428
  }).finally(() => {
19249
19429
  for (const dir of cmd.cleanupDirs ?? []) {
19250
19430
  try {
@@ -19275,9 +19455,9 @@ async function spawnAgentTurn(thread, input, onEvent) {
19275
19455
  }
19276
19456
  };
19277
19457
  signal("SIGTERM");
19278
- const timer2 = setTimeout(() => signal("SIGKILL"), 5e3);
19279
- timer2.unref?.();
19280
- child.once("exit", () => clearTimeout(timer2));
19458
+ const timer3 = setTimeout(() => signal("SIGKILL"), 5e3);
19459
+ timer3.unref?.();
19460
+ child.once("exit", () => clearTimeout(timer3));
19281
19461
  },
19282
19462
  done
19283
19463
  };
@@ -19313,6 +19493,98 @@ var init_spawn = __esm({
19313
19493
  }
19314
19494
  });
19315
19495
 
19496
+ // src/git/worktree-leftovers.ts
19497
+ function leftoverRefName(branch) {
19498
+ const safe = branch.trim().replace(/[^A-Za-z0-9._/-]+/g, "-") || "branch";
19499
+ return `${LEFTOVER_REF_PREFIX}${safe}`;
19500
+ }
19501
+ function gitFailure(result, fallback) {
19502
+ const text8 = (result.stderr || result.stdout).trim();
19503
+ return text8 || fallback;
19504
+ }
19505
+ async function restoreIndex(worktreePath, treeSha) {
19506
+ await git(["read-tree", "--reset", treeSha], worktreePath, { reject: false });
19507
+ }
19508
+ async function saveWorktreeLeftovers(repoPath, worktreePath, branch) {
19509
+ const status = await git(["status", "--porcelain"], worktreePath, { reject: false });
19510
+ if (status.exitCode !== 0) {
19511
+ return { ok: false, error: gitFailure(status, "git status failed") };
19512
+ }
19513
+ if (!status.stdout.trim()) return { ok: true, ref: null };
19514
+ const indexBefore = await git(["write-tree"], worktreePath, { reject: false });
19515
+ const indexSha = indexBefore.stdout.trim();
19516
+ if (indexBefore.exitCode !== 0 || !/^[0-9a-f]{7,64}$/i.test(indexSha)) {
19517
+ return { ok: false, error: gitFailure(indexBefore, "git write-tree failed") };
19518
+ }
19519
+ const fail5 = async (result, fallback) => {
19520
+ await restoreIndex(worktreePath, indexSha);
19521
+ return { ok: false, error: gitFailure(result, fallback) };
19522
+ };
19523
+ const added = await git(["add", "-A"], worktreePath, { reject: false });
19524
+ if (added.exitCode !== 0) return fail5(added, "git add failed");
19525
+ const tree = await git(["write-tree"], worktreePath, { reject: false });
19526
+ const treeSha = tree.stdout.trim();
19527
+ if (tree.exitCode !== 0 || !/^[0-9a-f]{7,64}$/i.test(treeSha)) {
19528
+ return fail5(tree, "git write-tree failed");
19529
+ }
19530
+ const head = await git(["rev-parse", "HEAD"], worktreePath, { reject: false });
19531
+ const parent = head.stdout.trim();
19532
+ if (head.exitCode !== 0 || !parent) return fail5(head, "git rev-parse HEAD failed");
19533
+ const commit = await git(
19534
+ ["commit-tree", treeSha, "-p", parent, "-m", "sideboard leftover"],
19535
+ worktreePath,
19536
+ { reject: false }
19537
+ );
19538
+ const sha = commit.stdout.trim();
19539
+ if (commit.exitCode !== 0 || !/^[0-9a-f]{7,64}$/i.test(sha)) {
19540
+ return fail5(commit, "git commit-tree failed");
19541
+ }
19542
+ const ref = leftoverRefName(branch);
19543
+ const updated = await git(["update-ref", ref, sha], repoPath, { reject: false });
19544
+ if (updated.exitCode !== 0) return fail5(updated, "git update-ref failed");
19545
+ await git(["reset"], worktreePath, { reject: false });
19546
+ return { ok: true, ref };
19547
+ }
19548
+ async function applyWorktreeLeftovers(repoPath, worktreePath, branch) {
19549
+ const ref = leftoverRefName(branch);
19550
+ const shown = await git(["rev-parse", "--verify", "--quiet", ref], repoPath, { reject: false });
19551
+ const sha = shown.stdout.trim();
19552
+ if (shown.exitCode !== 0 || !sha) return false;
19553
+ const restored = await git(["restore", "--source", sha, "--worktree", "--", "."], worktreePath, {
19554
+ reject: false
19555
+ });
19556
+ if (restored.exitCode !== 0) return false;
19557
+ await git(["update-ref", "-d", ref], repoPath, { reject: false });
19558
+ return true;
19559
+ }
19560
+ async function deleteWorktreeLeftovers(repoPath, branch) {
19561
+ await git(["update-ref", "-d", leftoverRefName(branch)], repoPath, { reject: false });
19562
+ }
19563
+ function archiveClearingFollowUps(id) {
19564
+ const archived = setStatus(id, "archived");
19565
+ if ((archived.followUps?.length ?? 0) === 0) return archived;
19566
+ return updateThread(archived.id, { followUps: [] });
19567
+ }
19568
+ async function removeWorktreeSavingLeftovers(thread) {
19569
+ const saved = await saveWorktreeLeftovers(thread.repoPath, thread.worktreePath, thread.branchName);
19570
+ if (!saved.ok) throw new Error(`Could not save uncommitted files: ${saved.error}`);
19571
+ await removeWorktree(thread.repoPath, thread.worktreePath);
19572
+ }
19573
+ async function removeWorktreeDroppingLeftovers(thread, deleteBranch) {
19574
+ await removeWorktree(thread.repoPath, thread.worktreePath, { deleteBranch });
19575
+ await deleteWorktreeLeftovers(thread.repoPath, thread.branchName).catch(() => void 0);
19576
+ }
19577
+ var LEFTOVER_REF_PREFIX;
19578
+ var init_worktree_leftovers = __esm({
19579
+ "src/git/worktree-leftovers.ts"() {
19580
+ "use strict";
19581
+ init_thread_store();
19582
+ init_run();
19583
+ init_worktree();
19584
+ LEFTOVER_REF_PREFIX = "refs/sideboard/leftovers/";
19585
+ }
19586
+ });
19587
+
19316
19588
  // src/git/agent-git-actions.ts
19317
19589
  function namedPrBase(prBase) {
19318
19590
  const base = prBase?.trim().replace(/^refs\/heads\//, "").replace(/^origin\//, "");
@@ -19700,9 +19972,9 @@ async function tryClaudeSummary(transcript, opts) {
19700
19972
  }
19701
19973
  );
19702
19974
  if (exitCode !== 0) return null;
19703
- const text7 = stdout.trim();
19704
- if (text7.length < 40) return null;
19705
- return text7;
19975
+ const text8 = stdout.trim();
19976
+ if (text8.length < 40) return null;
19977
+ return text8;
19706
19978
  } catch {
19707
19979
  return null;
19708
19980
  }
@@ -19751,9 +20023,9 @@ function extractiveSummary(transcript) {
19751
20023
  );
19752
20024
  return parts.join("\n");
19753
20025
  }
19754
- function clipSummary(text7) {
19755
- if (text7.length <= MAX_SUMMARY_CHARS) return text7;
19756
- return `${text7.slice(0, MAX_SUMMARY_CHARS)}
20026
+ function clipSummary(text8) {
20027
+ if (text8.length <= MAX_SUMMARY_CHARS) return text8;
20028
+ return `${text8.slice(0, MAX_SUMMARY_CHARS)}
19757
20029
 
19758
20030
  [\u2026summary truncated\u2026]`;
19759
20031
  }
@@ -19945,8 +20217,8 @@ function findLastBrightsyContextSummary(messages) {
19945
20217
  continue;
19946
20218
  }
19947
20219
  if (part.status === "error") continue;
19948
- const text7 = extractBrightsyContextSummary(part.result);
19949
- if (text7) return { index: i, text: text7 };
20220
+ const text8 = extractBrightsyContextSummary(part.result);
20221
+ if (text8) return { index: i, text: text8 };
19950
20222
  }
19951
20223
  }
19952
20224
  return null;
@@ -19975,12 +20247,12 @@ ${match.text}`, "");
19975
20247
  function compactArchiveProse(message) {
19976
20248
  if (message.origin === "continue") return null;
19977
20249
  if (message.role === "summary") return null;
19978
- let text7 = (message.text ?? "").trim();
19979
- if (!text7 && message.role === "agent") {
19980
- text7 = lastAssistantMessageText(message.parts).trim();
20250
+ let text8 = (message.text ?? "").trim();
20251
+ if (!text8 && message.role === "agent") {
20252
+ text8 = lastAssistantMessageText(message.parts).trim();
19981
20253
  }
19982
- if (!text7 || isInternalAgentStatusText(text7)) return null;
19983
- return { role: message.role, text: text7, ts: message.ts };
20254
+ if (!text8 || isInternalAgentStatusText(text8)) return null;
20255
+ return { role: message.role, text: text8, ts: message.ts };
19984
20256
  }
19985
20257
  function messagesForCompactArchive(older) {
19986
20258
  const out = [];
@@ -19999,11 +20271,11 @@ function appendCompactedMessages(existing, older) {
19999
20271
  function applyCompaction(messages, summaryText, thresholds = {}) {
20000
20272
  const { older, recent } = splitForCompaction(messages, thresholds);
20001
20273
  if (older.length === 0) return messages;
20002
- const text7 = summaryText.trim();
20274
+ const text8 = summaryText.trim();
20003
20275
  const summary = {
20004
20276
  role: "summary",
20005
- text: text7,
20006
- parts: [compactSummaryPart(text7)],
20277
+ text: text8,
20278
+ parts: [compactSummaryPart(text8)],
20007
20279
  ts: (/* @__PURE__ */ new Date()).toISOString()
20008
20280
  };
20009
20281
  return [summary, ...recent];
@@ -20214,7 +20486,7 @@ function forkMessageSlice(from, throughIndex) {
20214
20486
  function buildForkTranscriptAttachment(baseTitle, messages) {
20215
20487
  const title = baseTitle || "Chat";
20216
20488
  return {
20217
- id: (0, import_node_crypto11.randomUUID)(),
20489
+ id: (0, import_node_crypto12.randomUUID)(),
20218
20490
  name: `Transcript of ${title}.md`,
20219
20491
  kind: "transcript",
20220
20492
  content: formatTranscriptMarkdown(title, messages)
@@ -20273,11 +20545,11 @@ function forkChatTab(input) {
20273
20545
  }
20274
20546
  return tab;
20275
20547
  }
20276
- var import_node_crypto11;
20548
+ var import_node_crypto12;
20277
20549
  var init_chat_tabs = __esm({
20278
20550
  "src/threads/chat-tabs.ts"() {
20279
20551
  "use strict";
20280
- import_node_crypto11 = require("crypto");
20552
+ import_node_crypto12 = require("crypto");
20281
20553
  init_context_compact();
20282
20554
  init_teams();
20283
20555
  init_worktree_labels();
@@ -20519,7 +20791,7 @@ function buildReviewRequestAttachment(content, opts) {
20519
20791
  const path = opts?.path ?? REVIEW_SKILL_PATH;
20520
20792
  const name = opts?.name ?? (path === REVIEW_SKILL_PATH ? REVIEW_SKILL_NAME : path === REPO_REVIEW_PATH || path === CONTEXT_REVIEW_PATH ? REPO_REVIEW_NAME : REVIEW_REQUEST_NAME);
20521
20793
  return {
20522
- id: (0, import_node_crypto12.randomUUID)(),
20794
+ id: (0, import_node_crypto13.randomUUID)(),
20523
20795
  name,
20524
20796
  kind: "file",
20525
20797
  path,
@@ -20572,11 +20844,11 @@ async function requestReview(threadRef, send) {
20572
20844
  const started = await send(tab.id, REVIEW_REQUEST_PREFILL);
20573
20845
  return { tab: started, from };
20574
20846
  }
20575
- var import_node_crypto12, import_node_fs48, import_node_path49, REPO_REVIEW_PATH, REPO_REVIEW_NAME, CONTEXT_REVIEW_PATH, REVIEW_REQUEST_PATH, LEGACY_REVIEW_REQUEST_PATH, REVIEW_REQUEST_NAME, REVIEW_REQUEST_PREFILL, LEGACY_REVIEW_TEMPLATE_MARKERS;
20847
+ var import_node_crypto13, import_node_fs48, import_node_path49, REPO_REVIEW_PATH, REPO_REVIEW_NAME, CONTEXT_REVIEW_PATH, REVIEW_REQUEST_PATH, LEGACY_REVIEW_REQUEST_PATH, REVIEW_REQUEST_NAME, REVIEW_REQUEST_PREFILL, LEGACY_REVIEW_TEMPLATE_MARKERS;
20576
20848
  var init_request_review = __esm({
20577
20849
  "src/review/request-review.ts"() {
20578
20850
  "use strict";
20579
- import_node_crypto12 = require("crypto");
20851
+ import_node_crypto13 = require("crypto");
20580
20852
  import_node_fs48 = require("fs");
20581
20853
  import_node_path49 = require("path");
20582
20854
  init_global_workspace();
@@ -20704,8 +20976,8 @@ var init_job_process = __esm({
20704
20976
  });
20705
20977
 
20706
20978
  // src/orchestrator/deferred-report.ts
20707
- function looksLikeDeferredDonePromise(text7) {
20708
- const t = (text7 ?? "").trim();
20979
+ function looksLikeDeferredDonePromise(text8) {
20980
+ const t = (text8 ?? "").trim();
20709
20981
  if (!t || t.length > DEFERRED_DONE_MAX_CHARS) return false;
20710
20982
  const unquoted = t.replace(/`[^`]*`/g, " ").replace(/["“”][^"“”]*["“”]/g, " ").replace(/\s+/g, " ").trim();
20711
20983
  if (!unquoted) return false;
@@ -20713,9 +20985,9 @@ function looksLikeDeferredDonePromise(text7) {
20713
20985
  unquoted
20714
20986
  ) || /\bi(?:['’]ll| will)\s+come back (?:when|with|once|later)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+get back\b/i.test(unquoted) || /\bget back to (?:you|me)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:follow up|report back|circle back|check back)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+reply (?:when|once|later|after|shortly)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+ping you\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+ping when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:message|dm|slack) you when\b/i.test(unquoted);
20715
20987
  }
20716
- function orchestratorPromisedLaterReport(text7) {
20717
- if (looksLikeDeferredDonePromise(text7)) return true;
20718
- const t = (text7 ?? "").trim();
20988
+ function orchestratorPromisedLaterReport(text8) {
20989
+ if (looksLikeDeferredDonePromise(text8)) return true;
20990
+ const t = (text8 ?? "").trim();
20719
20991
  if (!t || t.length <= DEFERRED_DONE_MAX_CHARS) return false;
20720
20992
  const lines = t.split("\n").map((line) => line.trim()).filter(Boolean);
20721
20993
  const closing = [];
@@ -20800,16 +21072,16 @@ function listRunningDetachedJobs(worktreePath) {
20800
21072
  }
20801
21073
  return running.sort();
20802
21074
  }
20803
- function isJobContinuePrompt(text7) {
20804
- if (typeof text7 !== "string") return false;
20805
- const t = text7.trim();
21075
+ function isJobContinuePrompt(text8) {
21076
+ if (typeof text8 !== "string") return false;
21077
+ const t = text8.trim();
20806
21078
  return t.startsWith("Detached job still running:") || t.startsWith("You ended the turn after promising to report later");
20807
21079
  }
20808
- function collapseGhRunWatchLog(text7) {
20809
- if (!text7.includes(GH_WATCH_REFRESH)) return text7;
20810
- const frames = text7.split(/(?=Refreshing run status every 3 seconds\.)/);
21080
+ function collapseGhRunWatchLog(text8) {
21081
+ if (!text8.includes(GH_WATCH_REFRESH)) return text8;
21082
+ const frames = text8.split(/(?=Refreshing run status every 3 seconds\.)/);
20811
21083
  const watchFrames = frames.filter((f) => f.includes(GH_WATCH_REFRESH));
20812
- if (watchFrames.length <= 1) return text7;
21084
+ if (watchFrames.length <= 1) return text8;
20813
21085
  const prefix = frames[0]?.includes(GH_WATCH_REFRESH) ? "" : frames[0] ?? "";
20814
21086
  const last = watchFrames[watchFrames.length - 1] ?? "";
20815
21087
  const omitted = watchFrames.length - 1;
@@ -20817,8 +21089,8 @@ function collapseGhRunWatchLog(text7) {
20817
21089
  `;
20818
21090
  return [prefix.trimEnd(), note, last.trimStart()].filter(Boolean).join("\n");
20819
21091
  }
20820
- function capJobLogDelta(text7) {
20821
- const collapsed = collapseGhRunWatchLog(text7);
21092
+ function capJobLogDelta(text8) {
21093
+ const collapsed = collapseGhRunWatchLog(text8);
20822
21094
  const lines = collapsed.split("\n");
20823
21095
  let out = lines.length > MAX_JOB_DELTA_LINES ? `\u2026(${lines.length - MAX_JOB_DELTA_LINES} earlier lines omitted)
20824
21096
  ${lines.slice(-MAX_JOB_DELTA_LINES).join("\n")}` : collapsed;
@@ -21882,15 +22154,15 @@ function setupLogPath(threadId) {
21882
22154
  }
21883
22155
  function setupLogKeyForWorktree(worktreePath) {
21884
22156
  const norm = normalizeWorktreePath(worktreePath);
21885
- return `wt-${(0, import_node_crypto13.createHash)("sha1").update(norm).digest("hex").slice(0, 16)}`;
22157
+ return `wt-${(0, import_node_crypto14.createHash)("sha1").update(norm).digest("hex").slice(0, 16)}`;
21886
22158
  }
21887
22159
  function emptySetupLog() {
21888
22160
  return { ...EMPTY };
21889
22161
  }
21890
22162
  function persistNow(threadId) {
21891
- const timer2 = persistTimers.get(threadId);
21892
- if (timer2) {
21893
- clearTimeout(timer2);
22163
+ const timer3 = persistTimers.get(threadId);
22164
+ if (timer3) {
22165
+ clearTimeout(timer3);
21894
22166
  persistTimers.delete(threadId);
21895
22167
  }
21896
22168
  const mem = memory.get(threadId);
@@ -21975,11 +22247,11 @@ function finishSetupLog(threadId, exitCode, source) {
21975
22247
  persistNow(threadId);
21976
22248
  return materialize(mem);
21977
22249
  }
21978
- var import_node_crypto13, import_node_fs52, import_node_path53, EMPTY, MAX_SETUP_LOG_CHARS, memory, persistTimers, PERSIST_DEBOUNCE_MS;
22250
+ var import_node_crypto14, import_node_fs52, import_node_path53, EMPTY, MAX_SETUP_LOG_CHARS, memory, persistTimers, PERSIST_DEBOUNCE_MS;
21979
22251
  var init_setup_log = __esm({
21980
22252
  "src/store/setup-log.ts"() {
21981
22253
  "use strict";
21982
- import_node_crypto13 = require("crypto");
22254
+ import_node_crypto14 = require("crypto");
21983
22255
  import_node_fs52 = require("fs");
21984
22256
  import_node_path53 = require("path");
21985
22257
  init_worktree_labels();
@@ -22030,7 +22302,7 @@ function runLogPath(key) {
22030
22302
  }
22031
22303
  function runLogKeyForWorktree(worktreePath, scriptName) {
22032
22304
  const norm = normalizeWorktreePath(worktreePath);
22033
- const hash = (0, import_node_crypto14.createHash)("sha1").update(norm).digest("hex").slice(0, 16);
22305
+ const hash = (0, import_node_crypto15.createHash)("sha1").update(norm).digest("hex").slice(0, 16);
22034
22306
  return `wt-${hash}-run-${safeScriptToken(scriptName)}`;
22035
22307
  }
22036
22308
  function emptyRunLog() {
@@ -22042,13 +22314,13 @@ function sliceRunLogOutput(output, tailChars = DEFAULT_RUN_LOG_TAIL_CHARS) {
22042
22314
  if (outputChars <= max) return { output, truncated: false, outputChars };
22043
22315
  const cut = output.slice(outputChars - max);
22044
22316
  const nl = cut.indexOf("\n");
22045
- const text7 = nl >= 0 && nl < cut.length - 1 ? cut.slice(nl + 1) : cut;
22046
- return { output: text7, truncated: true, outputChars };
22317
+ const text8 = nl >= 0 && nl < cut.length - 1 ? cut.slice(nl + 1) : cut;
22318
+ return { output: text8, truncated: true, outputChars };
22047
22319
  }
22048
22320
  function persistNow2(key) {
22049
- const timer2 = persistTimers2.get(key);
22050
- if (timer2) {
22051
- clearTimeout(timer2);
22321
+ const timer3 = persistTimers2.get(key);
22322
+ if (timer3) {
22323
+ clearTimeout(timer3);
22052
22324
  persistTimers2.delete(key);
22053
22325
  }
22054
22326
  const mem = memory2.get(key);
@@ -22131,11 +22403,11 @@ function finishRunLog(key, exitCode) {
22131
22403
  function flushRunLog(key) {
22132
22404
  persistNow2(key);
22133
22405
  }
22134
- var import_node_crypto14, import_node_fs53, import_node_path54, EMPTY2, MAX_RUN_LOG_CHARS, DEFAULT_RUN_LOG_TAIL_CHARS, memory2, persistTimers2, PERSIST_DEBOUNCE_MS2;
22406
+ var import_node_crypto15, import_node_fs53, import_node_path54, EMPTY2, MAX_RUN_LOG_CHARS, DEFAULT_RUN_LOG_TAIL_CHARS, memory2, persistTimers2, PERSIST_DEBOUNCE_MS2;
22135
22407
  var init_run_log = __esm({
22136
22408
  "src/store/run-log.ts"() {
22137
22409
  "use strict";
22138
- import_node_crypto14 = require("crypto");
22410
+ import_node_crypto15 = require("crypto");
22139
22411
  import_node_fs53 = require("fs");
22140
22412
  import_node_path54 = require("path");
22141
22413
  init_worktree_labels();
@@ -22529,10 +22801,10 @@ var init_desktop_host = __esm({
22529
22801
  // src/mcp-ui/model-context.ts
22530
22802
  function takeMcpAppModelContext(threadId) {
22531
22803
  const thread = readThread(threadId);
22532
- const text7 = thread?.mcpAppModelContext?.trim();
22533
- if (!text7) return void 0;
22804
+ const text8 = thread?.mcpAppModelContext?.trim();
22805
+ if (!text8) return void 0;
22534
22806
  updateThread(threadId, { mcpAppModelContext: null });
22535
- return text7;
22807
+ return text8;
22536
22808
  }
22537
22809
  var init_model_context = __esm({
22538
22810
  "src/mcp-ui/model-context.ts"() {
@@ -22561,11 +22833,11 @@ function denyPendingToolPermissions(threadId) {
22561
22833
  const last = pending[pending.length - 1];
22562
22834
  if (last) clearPrompt(threadId, last.id);
22563
22835
  }
22564
- var import_node_crypto15, import_node_path58, queues, publisher;
22836
+ var import_node_crypto16, import_node_path58, queues, publisher;
22565
22837
  var init_tool_permission = __esm({
22566
22838
  "src/agents/tool-permission.ts"() {
22567
22839
  "use strict";
22568
- import_node_crypto15 = require("crypto");
22840
+ import_node_crypto16 = require("crypto");
22569
22841
  import_node_path58 = require("path");
22570
22842
  init_claude_mcp();
22571
22843
  queues = /* @__PURE__ */ new Map();
@@ -22663,11 +22935,11 @@ function resolvePlanMarkdown(opts) {
22663
22935
  source: "exit_plan"
22664
22936
  };
22665
22937
  }
22666
- const text7 = opts.text?.trim();
22667
- if (text7 && text7.length >= 80) {
22938
+ const text8 = opts.text?.trim();
22939
+ if (text8 && text8.length >= 80) {
22668
22940
  return {
22669
22941
  title: "Plan",
22670
- content: text7,
22942
+ content: text8,
22671
22943
  path: PLAN_FILE_REL,
22672
22944
  source: "text"
22673
22945
  };
@@ -22712,9 +22984,9 @@ var init_connected_orchestrator = __esm({
22712
22984
 
22713
22985
  // src/orchestrator/notify-orchestrator.ts
22714
22986
  function clampMessage(raw) {
22715
- const text7 = raw.replace(/\s+/g, " ").trim();
22716
- if (text7.length <= MAX_NOTIFY_ORCHESTRATOR_MESSAGE_CHARS) return text7;
22717
- return `${text7.slice(0, MAX_NOTIFY_ORCHESTRATOR_MESSAGE_CHARS - 1)}\u2026`;
22987
+ const text8 = raw.replace(/\s+/g, " ").trim();
22988
+ if (text8.length <= MAX_NOTIFY_ORCHESTRATOR_MESSAGE_CHARS) return text8;
22989
+ return `${text8.slice(0, MAX_NOTIFY_ORCHESTRATOR_MESSAGE_CHARS - 1)}\u2026`;
22718
22990
  }
22719
22991
  function formatAskUserNotifyMessage(questions) {
22720
22992
  const qs = questions.map((q) => q.question?.trim() ?? "").filter(Boolean);
@@ -22821,10 +23093,10 @@ var init_notify_orchestrator = __esm({
22821
23093
 
22822
23094
  // src/orchestrator/agent-block.ts
22823
23095
  function clampBlockReason(raw) {
22824
- const text7 = raw.replace(/\s+/g, " ").trim();
22825
- if (!text7) return "Waiting on a decision";
22826
- if (text7.length <= MAX_AGENT_BLOCK_REASON) return text7;
22827
- return `${text7.slice(0, MAX_AGENT_BLOCK_REASON - 1)}\u2026`;
23096
+ const text8 = raw.replace(/\s+/g, " ").trim();
23097
+ if (!text8) return "Waiting on a decision";
23098
+ if (text8.length <= MAX_AGENT_BLOCK_REASON) return text8;
23099
+ return `${text8.slice(0, MAX_AGENT_BLOCK_REASON - 1)}\u2026`;
22828
23100
  }
22829
23101
  function makeAgentBlock(source, reason, at = (/* @__PURE__ */ new Date()).toISOString()) {
22830
23102
  return { source, reason: clampBlockReason(reason), at };
@@ -23195,8 +23467,8 @@ function resolveStopReason(opts) {
23195
23467
  return "Stopped (queue cleared)";
23196
23468
  }
23197
23469
  function isRoutineStopNote(err) {
23198
- const text7 = err?.trim() ?? "";
23199
- return text7 === "Stopped" || text7 === "Stopped by the user" || text7 === "Stopped (queue cleared)" || text7 === "Stopped to send the next prompt";
23470
+ const text8 = err?.trim() ?? "";
23471
+ return text8 === "Stopped" || text8 === "Stopped by the user" || text8 === "Stopped (queue cleared)" || text8 === "Stopped to send the next prompt";
23200
23472
  }
23201
23473
  function reasonToKeepOnStop(existing, incoming) {
23202
23474
  const next = incoming?.trim();
@@ -23235,7 +23507,7 @@ function isUnclaimedSteerRequest(req) {
23235
23507
  }
23236
23508
  function nextSteerRequest(existing) {
23237
23509
  if (existing?.requestId && !existing.claimedAt) return existing;
23238
- return { requestId: (0, import_node_crypto16.randomUUID)(), requestedAt: (/* @__PURE__ */ new Date()).toISOString() };
23510
+ return { requestId: (0, import_node_crypto17.randomUUID)(), requestedAt: (/* @__PURE__ */ new Date()).toISOString() };
23239
23511
  }
23240
23512
  function claimSteerRequest(threadId) {
23241
23513
  const pending = readThread(threadId)?.steerRequest;
@@ -23244,11 +23516,11 @@ function claimSteerRequest(threadId) {
23244
23516
  steerRequest: { ...pending, claimedAt: (/* @__PURE__ */ new Date()).toISOString() }
23245
23517
  });
23246
23518
  }
23247
- var import_node_crypto16;
23519
+ var import_node_crypto17;
23248
23520
  var init_steer_request = __esm({
23249
23521
  "src/orchestrator/steer-request.ts"() {
23250
23522
  "use strict";
23251
- import_node_crypto16 = require("crypto");
23523
+ import_node_crypto17 = require("crypto");
23252
23524
  init_thread_store();
23253
23525
  }
23254
23526
  });
@@ -24127,8 +24399,8 @@ function resolveAbleTimeOAuthHost(requested, saved) {
24127
24399
  return fromSaved || void 0;
24128
24400
  }
24129
24401
  function createAbleTimePkce() {
24130
- const verifier = (0, import_node_crypto17.randomBytes)(32).toString("base64url");
24131
- const challenge = (0, import_node_crypto17.createHash)("sha256").update(verifier).digest("base64url");
24402
+ const verifier = (0, import_node_crypto18.randomBytes)(32).toString("base64url");
24403
+ const challenge = (0, import_node_crypto18.createHash)("sha256").update(verifier).digest("base64url");
24132
24404
  return { verifier, challenge };
24133
24405
  }
24134
24406
  function ableTimeOAuthAuthorizeUrl(clientId, state, codeChallenge, host) {
@@ -24233,7 +24505,7 @@ async function startAbleTimeOAuth(opts) {
24233
24505
  opts?.host,
24234
24506
  loadAppSettings().integrations.abletimeHost
24235
24507
  );
24236
- const state = (0, import_node_crypto17.randomBytes)(16).toString("hex");
24508
+ const state = (0, import_node_crypto18.randomBytes)(16).toString("hex");
24237
24509
  const pkce = createAbleTimePkce();
24238
24510
  const authorizeUrl = ableTimeOAuthAuthorizeUrl(clientId, state, pkce.challenge, host);
24239
24511
  const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
@@ -24281,12 +24553,12 @@ async function startAbleTimeOAuth(opts) {
24281
24553
  finish(e instanceof Error ? e : new Error(String(e)));
24282
24554
  }
24283
24555
  });
24284
- const timer2 = setTimeout(() => {
24556
+ const timer3 = setTimeout(() => {
24285
24557
  finish(new Error("AbleTime sign-in timed out \u2014 try again"));
24286
24558
  }, timeoutMs);
24287
24559
  const onAbort = () => finish(new AbleTimeOAuthCancelledError());
24288
24560
  const cleanup = () => {
24289
- clearTimeout(timer2);
24561
+ clearTimeout(timer3);
24290
24562
  opts?.signal?.removeEventListener("abort", onAbort);
24291
24563
  server.close();
24292
24564
  };
@@ -24333,11 +24605,11 @@ async function startAbleTimeOAuth(opts) {
24333
24605
  return loadAppSettings();
24334
24606
  }
24335
24607
  }
24336
- var import_node_crypto17, import_node_http3, ABLETIME_OAUTH_CALLBACK_PATH, ABLETIME_OAUTH_PORT, ABLETIME_OAUTH_LOCAL_CALLBACK, ABLETIME_OAUTH_REDIRECT, BOUNCE_QUERY_KEYS, BAKED_ABLETIME_OAUTH_CLIENT_ID, ABLETIME_OAUTH_RESOURCE, REFRESH_SKEW_MS3, refreshInFlight3, ABLETIME_OAUTH_CANCELLED, AbleTimeOAuthCancelledError;
24608
+ var import_node_crypto18, import_node_http3, ABLETIME_OAUTH_CALLBACK_PATH, ABLETIME_OAUTH_PORT, ABLETIME_OAUTH_LOCAL_CALLBACK, ABLETIME_OAUTH_REDIRECT, BOUNCE_QUERY_KEYS, BAKED_ABLETIME_OAUTH_CLIENT_ID, ABLETIME_OAUTH_RESOURCE, REFRESH_SKEW_MS3, refreshInFlight3, ABLETIME_OAUTH_CANCELLED, AbleTimeOAuthCancelledError;
24337
24609
  var init_abletime_oauth = __esm({
24338
24610
  "src/integrations/abletime-oauth.ts"() {
24339
24611
  "use strict";
24340
- import_node_crypto17 = require("crypto");
24612
+ import_node_crypto18 = require("crypto");
24341
24613
  import_node_http3 = require("http");
24342
24614
  init_fetch();
24343
24615
  init_app_settings();
@@ -24386,8 +24658,8 @@ function asList(value) {
24386
24658
  }
24387
24659
  return [];
24388
24660
  }
24389
- function ableTimeDocFromText(text7) {
24390
- const trimmed = text7.trim();
24661
+ function ableTimeDocFromText(text8) {
24662
+ const trimmed = text8.trim();
24391
24663
  if (!trimmed) return { type: "doc", content: [] };
24392
24664
  return {
24393
24665
  type: "doc",
@@ -24439,19 +24711,19 @@ async function abletimeRestRequest(path, opts = {}) {
24439
24711
  },
24440
24712
  ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {}
24441
24713
  });
24442
- const text7 = await res.text().catch(() => "");
24714
+ const text8 = await res.text().catch(() => "");
24443
24715
  if (!res.ok) {
24444
24716
  throw new Error(
24445
24717
  rewriteAbleTimeError(
24446
- `AbleTime API error ${res.status}${text7 ? `: ${text7.slice(0, 240)}` : ""}`
24718
+ `AbleTime API error ${res.status}${text8 ? `: ${text8.slice(0, 240)}` : ""}`
24447
24719
  )
24448
24720
  );
24449
24721
  }
24450
- if (!text7.trim()) return null;
24722
+ if (!text8.trim()) return null;
24451
24723
  try {
24452
- return JSON.parse(text7);
24724
+ return JSON.parse(text8);
24453
24725
  } catch {
24454
- throw new Error(`AbleTime API returned a non-JSON response: ${text7.slice(0, 200)}`);
24726
+ throw new Error(`AbleTime API returned a non-JSON response: ${text8.slice(0, 200)}`);
24455
24727
  }
24456
24728
  }
24457
24729
  async function restPages(path, opts, maxPages = 20) {
@@ -24879,11 +25151,11 @@ function unwrapToolResult(result) {
24879
25151
  return typeof item.text === "string" ? item.text : "";
24880
25152
  }).filter(Boolean);
24881
25153
  if (texts.length === 1) {
24882
- const text7 = texts[0];
25154
+ const text8 = texts[0];
24883
25155
  try {
24884
- return JSON.parse(text7);
25156
+ return JSON.parse(text8);
24885
25157
  } catch {
24886
- return text7;
25158
+ return text8;
24887
25159
  }
24888
25160
  }
24889
25161
  if (texts.length > 1) return texts.join("\n");
@@ -26265,11 +26537,11 @@ function createLineCoalescer(onChunk, opts) {
26265
26537
  const delayMs = opts?.delayMs ?? 50;
26266
26538
  const maxLines = opts?.maxLines ?? 200;
26267
26539
  let buffer = [];
26268
- let timer2 = null;
26540
+ let timer3 = null;
26269
26541
  const flush2 = () => {
26270
- if (timer2) {
26271
- clearTimeout(timer2);
26272
- timer2 = null;
26542
+ if (timer3) {
26543
+ clearTimeout(timer3);
26544
+ timer3 = null;
26273
26545
  }
26274
26546
  if (buffer.length === 0) return;
26275
26547
  const chunk = buffer.join("\n");
@@ -26282,7 +26554,7 @@ function createLineCoalescer(onChunk, opts) {
26282
26554
  flush2();
26283
26555
  return;
26284
26556
  }
26285
- if (!timer2) timer2 = setTimeout(flush2, delayMs);
26557
+ if (!timer3) timer3 = setTimeout(flush2, delayMs);
26286
26558
  };
26287
26559
  return { push: push2, flush: flush2 };
26288
26560
  }
@@ -26312,8 +26584,8 @@ function summarizeTurnLive(parts) {
26312
26584
  const interesting = [...tools].reverse().find((t) => !isPollWrapperToolName(t.name)) ?? lastTool;
26313
26585
  const lastToolLabel = interesting ? interesting.description || toolDescription(interesting.name, interesting.input) || interesting.name : void 0;
26314
26586
  const thinking = lastText(parts, "thinking");
26315
- const text7 = lastText(parts, "text");
26316
- const excerptRaw = thinking || text7;
26587
+ const text8 = lastText(parts, "text");
26588
+ const excerptRaw = thinking || text8;
26317
26589
  const excerpt = excerptRaw.length > 280 ? `${excerptRaw.slice(-280)}` : excerptRaw || void 0;
26318
26590
  const summary = liveActivitySummary(parts);
26319
26591
  return {
@@ -26590,8 +26862,8 @@ function buildQuotaHandoffAttachment(from, limitText, fallbackAgent) {
26590
26862
  );
26591
26863
  const recent = from.messages.slice(-8).map((m) => {
26592
26864
  const role = m.role === "user" ? "User" : m.role === "agent" ? "Agent" : "Summary";
26593
- const text7 = m.text.trim().replace(/\s+/g, " ").slice(0, 280);
26594
- return text7 ? `- ${role}: ${text7}` : null;
26865
+ const text8 = m.text.trim().replace(/\s+/g, " ").slice(0, 280);
26866
+ return text8 ? `- ${role}: ${text8}` : null;
26595
26867
  }).filter(Boolean);
26596
26868
  const orch = isOrchestratorThread(from);
26597
26869
  const instructions = orch ? [
@@ -26624,7 +26896,7 @@ function buildQuotaHandoffAttachment(from, limitText, fallbackAgent) {
26624
26896
  ...instructions
26625
26897
  ].join("\n");
26626
26898
  return {
26627
- id: (0, import_node_crypto18.randomUUID)(),
26899
+ id: (0, import_node_crypto19.randomUUID)(),
26628
26900
  name: orch ? "Orchestration quota handoff.md" : "Quota handoff.md",
26629
26901
  kind: "transcript",
26630
26902
  content: body
@@ -26662,11 +26934,11 @@ function createQuotaFailoverChat(from, fallbackAgent, limitText, opts) {
26662
26934
  }
26663
26935
  return updateThread(tab.id, patch);
26664
26936
  }
26665
- var import_node_crypto18, QUOTA_CONTINUE_PROMPT, QUOTA_CONTINUE_ACCOUNT_PROMPT, QUOTA_RESUME_PROMPT;
26937
+ var import_node_crypto19, QUOTA_CONTINUE_PROMPT, QUOTA_CONTINUE_ACCOUNT_PROMPT, QUOTA_RESUME_PROMPT;
26666
26938
  var init_quota_failover = __esm({
26667
26939
  "src/orchestrator/quota-failover.ts"() {
26668
26940
  "use strict";
26669
- import_node_crypto18 = require("crypto");
26941
+ import_node_crypto19 = require("crypto");
26670
26942
  init_session_quota();
26671
26943
  init_app_settings();
26672
26944
  init_managed_accounts();
@@ -26718,13 +26990,13 @@ function resolveConductorCursorAgentId(workspacePath) {
26718
26990
  for (const hash of hashes) {
26719
26991
  const agentsFile = (0, import_node_path60.join)(CURSOR_SDK_STORE, hash, "agents.ndjson");
26720
26992
  if (!(0, import_node_fs59.existsSync)(agentsFile)) continue;
26721
- let text7;
26993
+ let text8;
26722
26994
  try {
26723
- text7 = (0, import_node_fs59.readFileSync)(agentsFile, "utf8");
26995
+ text8 = (0, import_node_fs59.readFileSync)(agentsFile, "utf8");
26724
26996
  } catch {
26725
26997
  continue;
26726
26998
  }
26727
- for (const line of text7.split("\n")) {
26999
+ for (const line of text8.split("\n")) {
26728
27000
  const trimmed = line.trim();
26729
27001
  if (!trimmed) continue;
26730
27002
  try {
@@ -27309,7 +27581,7 @@ async function createCursorPullRequest(worktreePath, slug, opts) {
27309
27581
  const bodyText = (opts.body ?? opts.title).trim() || opts.title;
27310
27582
  const bodyFile = (0, import_node_path61.join)(
27311
27583
  (0, import_node_os19.tmpdir)(),
27312
- `sideboard-pr-body-${process.pid}-${(0, import_node_crypto19.randomBytes)(6).toString("hex")}.md`
27584
+ `sideboard-pr-body-${process.pid}-${(0, import_node_crypto20.randomBytes)(6).toString("hex")}.md`
27313
27585
  );
27314
27586
  (0, import_node_fs61.writeFileSync)(bodyFile, bodyText.endsWith("\n") ? bodyText : `${bodyText}
27315
27587
  `, "utf8");
@@ -27351,7 +27623,7 @@ async function createOrUpdatePr(worktreePath, opts) {
27351
27623
  const bodyText = clampGithubPrBody(opts.body ?? opts.title);
27352
27624
  const bodyFile = (0, import_node_path61.join)(
27353
27625
  (0, import_node_os19.tmpdir)(),
27354
- `sideboard-pr-body-${process.pid}-${(0, import_node_crypto19.randomBytes)(6).toString("hex")}.md`
27626
+ `sideboard-pr-body-${process.pid}-${(0, import_node_crypto20.randomBytes)(6).toString("hex")}.md`
27355
27627
  );
27356
27628
  (0, import_node_fs61.writeFileSync)(bodyFile, bodyText.endsWith("\n") ? bodyText : `${bodyText}
27357
27629
  `, "utf8");
@@ -27442,11 +27714,11 @@ async function createOrUpdatePrWithBodyFile(worktreePath, opts) {
27442
27714
  const url = created.stdout.trim().split("\n").find((l) => l.startsWith("http")) ?? created.stdout.trim();
27443
27715
  return url;
27444
27716
  }
27445
- var import_node_crypto19, import_node_fs61, import_node_os19, import_node_path61;
27717
+ var import_node_crypto20, import_node_fs61, import_node_os19, import_node_path61;
27446
27718
  var init_pr_write = __esm({
27447
27719
  "src/git/pr-write.ts"() {
27448
27720
  "use strict";
27449
- import_node_crypto19 = require("crypto");
27721
+ import_node_crypto20 = require("crypto");
27450
27722
  import_node_fs61 = require("fs");
27451
27723
  import_node_os19 = require("os");
27452
27724
  import_node_path61 = require("path");
@@ -27699,13 +27971,13 @@ function formatStat(files) {
27699
27971
  return `${n} file${n === 1 ? "" : "s"} changed, ${additions} insertions(+), ${deletions} deletions(-)`;
27700
27972
  }
27701
27973
  function emptyScopeStats() {
27702
- const z13 = emptyStat();
27974
+ const z14 = emptyStat();
27703
27975
  return {
27704
- commits: z13,
27705
- uncommitted: z13,
27706
- staged: z13,
27707
- unstaged: z13,
27708
- last_turn: z13
27976
+ commits: z14,
27977
+ uncommitted: z14,
27978
+ staged: z14,
27979
+ unstaged: z14,
27980
+ last_turn: z14
27709
27981
  };
27710
27982
  }
27711
27983
  function filesFromDiff(nameStatus, numstat, combinedDiff, maxHunk) {
@@ -28954,8 +29226,8 @@ function trailingUnansweredUserText(messages) {
28954
29226
  const message = messages[i];
28955
29227
  if (!message || message.origin === "continue" || message.role === "summary") continue;
28956
29228
  if (message.role === "agent") {
28957
- const text7 = (message.text ?? "").trim();
28958
- if (text7 || (message.parts?.length ?? 0) > 0) return null;
29229
+ const text8 = (message.text ?? "").trim();
29230
+ if (text8 || (message.parts?.length ?? 0) > 0) return null;
28959
29231
  continue;
28960
29232
  }
28961
29233
  if (message.role === "user") return message.text;
@@ -28977,12 +29249,15 @@ var init_agent_has_replied = __esm({
28977
29249
  });
28978
29250
 
28979
29251
  // src/orchestrator/enqueue-thread-send.ts
29252
+ function sendFollowUpInterrupts(followUp, busy) {
29253
+ return followUp === "steer" && busy;
29254
+ }
28980
29255
  function resolveSendFollowUp(thread, requested) {
28981
29256
  if (requested === "steer" || requested === "queue") return requested;
28982
29257
  return isOrchestratorThread(thread) ? followUpBehavior() : "queue";
28983
29258
  }
28984
- function beginOpenSteerDraft(text7) {
28985
- return { text: text7, spawned: false, attachments: [] };
29259
+ function beginOpenSteerDraft(text8) {
29260
+ return { text: text8, spawned: false, attachments: [] };
28986
29261
  }
28987
29262
  function seedOpenSteerAttachments(draft, sent) {
28988
29263
  if (!draft) return [...sent ?? []];
@@ -29063,14 +29338,20 @@ async function enqueueThreadSend(host, threadRef, prompt, opts) {
29063
29338
  if (current.status === "archived") {
29064
29339
  throw new Error(`Thread is archived: ${thread.id}`);
29065
29340
  }
29066
- const followUp = resolveSendFollowUp(current, opts?.followUp);
29341
+ const requested = opts?.followUp;
29342
+ const join65 = requested === "join";
29343
+ const followUp = resolveSendFollowUp(
29344
+ current,
29345
+ join65 ? "steer" : requested
29346
+ );
29067
29347
  const explicit = opts?.attachments;
29068
29348
  const consumed = explicit !== void 0 ? { attachments: current.attachments, consumed: explicit } : consumeComposerAttachments(current);
29069
29349
  const inFlightEarly = host.activeTurns.has(thread.id) || host.startingTurns.has(thread.id) || current.status === "running";
29070
29350
  const agentHasRepliedEarly = livePartsShowAgentReply(readTurnLiveParts(current.id));
29071
29351
  const draft = host.openSteerPrompt.get(current.id);
29072
29352
  const queuedHead = !inFlightEarly && current.status === "queued" && current.queue.length > 0 ? current.queue[0] : null;
29073
- const unanswered = followUp === "steer" && !agentHasRepliedEarly ? draft?.text ?? (inFlightEarly ? trailingUnansweredUserText(current.messages) : queuedHead) : null;
29353
+ const joinCanMerge = draft != null && !draft.spawned || !inFlightEarly && queuedHead != null;
29354
+ const unanswered = followUp === "steer" && !agentHasRepliedEarly && (!join65 || joinCanMerge) ? draft?.text ?? (inFlightEarly ? trailingUnansweredUserText(current.messages) : queuedHead) : null;
29074
29355
  if (unanswered != null && (draft ? !draft.spawned : queuedHead != null)) {
29075
29356
  clearSendBookkeeping(host, thread.id);
29076
29357
  const combined = joinSteerPrompt(unanswered, prompt);
@@ -29121,7 +29402,10 @@ async function enqueueThreadSend(host, threadRef, prompt, opts) {
29121
29402
  );
29122
29403
  clearSendBookkeeping(host, thread.id);
29123
29404
  const inFlight = host.activeTurns.has(thread.id) || host.startingTurns.has(thread.id) || current.status === "running";
29124
- shouldSteer = followUp === "steer" && (inFlight || current.queue.length > 0);
29405
+ shouldSteer = sendFollowUpInterrupts(
29406
+ join65 ? "join" : followUp,
29407
+ inFlight || current.queue.length > 0
29408
+ );
29125
29409
  const patch = queued;
29126
29410
  if (explicit === void 0 && consumed.consumed.length > 0) {
29127
29411
  patch.attachments = consumed.attachments;
@@ -29365,7 +29649,7 @@ function formatWorktreeDirective(thread, opts) {
29365
29649
  lines.push(formatDevAccessHint(opts?.activeRuns));
29366
29650
  lines.push("");
29367
29651
  lines.push(
29368
- "Automations (sidebar, after Board): `create_schedule` / `list_schedules` (`at` / `every` / `cron` / `time`+`days`). `archiveChat=false` keeps the new chat. `chatId=self` is removed when this chat is archived. Fires only while Sideboard.app is running. Future jobs turn on Caffeinate."
29652
+ "Automations (sidebar, after Board): `create_schedule` / `list_schedules` (`at` / `every` / `cron` / `time`+`days`). `archiveChat=false` keeps the new chat. `chatId=self` is removed when this chat is archived. Fires only while Sideboard.app is running. Future jobs turn on Caffeinate. `create_follow_up` (ci|at) waits behind this turn."
29369
29653
  );
29370
29654
  lines.push(
29371
29655
  "`set_workspace_tags` labels this checkout (omit ref). `set_wake_on_github_edges` opts this checkout in when Advanced is already on (omit ref)."
@@ -31148,8 +31432,8 @@ async function fireSchedule(id) {
31148
31432
  }
31149
31433
  }
31150
31434
  function clearTimer(id) {
31151
- const timer2 = timers.get(id);
31152
- if (timer2) clearTimeout(timer2);
31435
+ const timer3 = timers.get(id);
31436
+ if (timer3) clearTimeout(timer3);
31153
31437
  timers.delete(id);
31154
31438
  }
31155
31439
  function armOne(schedule) {
@@ -31165,7 +31449,7 @@ function armOne(schedule) {
31165
31449
  return;
31166
31450
  }
31167
31451
  const capped = Math.min(delay2, SET_TIMEOUT_MAX);
31168
- const timer2 = setTimeout(() => {
31452
+ const timer3 = setTimeout(() => {
31169
31453
  timers.delete(schedule.id);
31170
31454
  const live = getSchedule(schedule.id);
31171
31455
  if (!live?.enabled) return;
@@ -31178,7 +31462,7 @@ function armOne(schedule) {
31178
31462
  if (isThisProcessDesktopHost()) armSchedules();
31179
31463
  });
31180
31464
  }, capped);
31181
- timers.set(schedule.id, timer2);
31465
+ timers.set(schedule.id, timer3);
31182
31466
  }
31183
31467
  function armSchedules() {
31184
31468
  if (!isThisProcessDesktopHost()) return;
@@ -31211,6 +31495,85 @@ var init_schedule_runner = __esm({
31211
31495
  }
31212
31496
  });
31213
31497
 
31498
+ // src/orchestrator/chat-follow-up-runner.ts
31499
+ async function ciPhase(thread) {
31500
+ const selector = resolvePrSelector(thread);
31501
+ if (!selector || !thread.worktreePath?.trim()) return "none";
31502
+ try {
31503
+ const checks = await getPrCiChecks(thread.worktreePath, selector);
31504
+ return ciChecksSettled(checks);
31505
+ } catch {
31506
+ return "unknown";
31507
+ }
31508
+ }
31509
+ async function pollChatFollowUps(send = defaultSend) {
31510
+ if (polling2) return;
31511
+ polling2 = true;
31512
+ try {
31513
+ const threads = listThreads().filter(
31514
+ (thread) => thread.status !== "archived" && (thread.followUps?.length ?? 0) > 0
31515
+ );
31516
+ for (const thread of threads) {
31517
+ const followUps = thread.followUps ?? [];
31518
+ const ci = followUps.some((item) => item.kind === "ci") ? await ciPhase(thread) : "none";
31519
+ const decision = decideFollowUps({ followUps, now: /* @__PURE__ */ new Date(), ci });
31520
+ const kept = [...decision.keep];
31521
+ const firedIds = [];
31522
+ for (const item of decision.fire) {
31523
+ try {
31524
+ await send(thread.id, `[Follow-up]
31525
+ ${item.prompt}`);
31526
+ firedIds.push(item.id);
31527
+ } catch {
31528
+ kept.push(item);
31529
+ }
31530
+ }
31531
+ const fresh = readThread(thread.id);
31532
+ if (!fresh || fresh.status === "archived") continue;
31533
+ const after = normalizeChatFollowUps(fresh.followUps);
31534
+ const next = mergeFollowUpPoll({
31535
+ before: followUps,
31536
+ after,
31537
+ firedIds,
31538
+ keep: kept
31539
+ });
31540
+ if (JSON.stringify(next) !== JSON.stringify(after)) {
31541
+ updateThread(thread.id, { followUps: next });
31542
+ }
31543
+ }
31544
+ } finally {
31545
+ polling2 = false;
31546
+ }
31547
+ }
31548
+ async function defaultSend(id, prompt) {
31549
+ const { getOrchestrator: getOrchestrator2 } = await Promise.resolve().then(() => (init_orchestrator(), orchestrator_exports));
31550
+ await getOrchestrator2().send(id, prompt, { followUp: "join" });
31551
+ }
31552
+ function armChatFollowUps() {
31553
+ if (!isThisProcessDesktopHost()) return;
31554
+ if (timer2) return;
31555
+ const tick = () => {
31556
+ timer2 = setTimeout(() => {
31557
+ void pollChatFollowUps().finally(tick);
31558
+ }, POLL_MS);
31559
+ };
31560
+ void pollChatFollowUps();
31561
+ tick();
31562
+ }
31563
+ var POLL_MS, timer2, polling2;
31564
+ var init_chat_follow_up_runner = __esm({
31565
+ "src/orchestrator/chat-follow-up-runner.ts"() {
31566
+ "use strict";
31567
+ init_worktree();
31568
+ init_desktop_host();
31569
+ init_thread_store();
31570
+ init_chat_follow_ups();
31571
+ POLL_MS = 6e4;
31572
+ timer2 = null;
31573
+ polling2 = false;
31574
+ }
31575
+ });
31576
+
31214
31577
  // src/agents/cursor-recover.ts
31215
31578
  var cursor_recover_exports = {};
31216
31579
  __export(cursor_recover_exports, {
@@ -31363,7 +31726,7 @@ async function startOrchestration(opts) {
31363
31726
  }
31364
31727
  return ready;
31365
31728
  }
31366
- var import_node_events, import_node_crypto20, import_node_fs71, LIVE_TURN_SPAWN_GRACE_MS, RUN_SCRIPT_DESKTOP_ADOPT_MS, STALE_AGENT_PID_WAIT_MS, LIGHT_RECONCILE_THROTTLE_MS, Orchestrator, singleton2;
31729
+ var import_node_events, import_node_crypto21, import_node_fs71, LIVE_TURN_SPAWN_GRACE_MS, RUN_SCRIPT_DESKTOP_ADOPT_MS, STALE_AGENT_PID_WAIT_MS, LIGHT_RECONCILE_THROTTLE_MS, Orchestrator, singleton2;
31367
31730
  var init_orchestrator = __esm({
31368
31731
  "src/orchestrator/orchestrator.ts"() {
31369
31732
  "use strict";
@@ -31371,7 +31734,7 @@ var init_orchestrator = __esm({
31371
31734
  init_injected_notices();
31372
31735
  init_task_state();
31373
31736
  init_wait_for_turn();
31374
- import_node_crypto20 = require("crypto");
31737
+ import_node_crypto21 = require("crypto");
31375
31738
  import_node_fs71 = require("fs");
31376
31739
  init_error_detail();
31377
31740
  init_run();
@@ -31381,6 +31744,7 @@ var init_orchestrator = __esm({
31381
31744
  init_turn_trace();
31382
31745
  init_agents();
31383
31746
  init_worktree();
31747
+ init_worktree_leftovers();
31384
31748
  init_stack();
31385
31749
  init_agent_git_actions();
31386
31750
  init_pr_merge_archive();
@@ -31450,6 +31814,7 @@ var init_orchestrator = __esm({
31450
31814
  init_caffeinate_hold();
31451
31815
  init_github_edge_watch();
31452
31816
  init_schedule_runner();
31817
+ init_chat_follow_up_runner();
31453
31818
  init_coordinator_prompt();
31454
31819
  init_enqueue_thread_send();
31455
31820
  LIVE_TURN_SPAWN_GRACE_MS = 15e3;
@@ -31629,6 +31994,7 @@ var init_orchestrator = __esm({
31629
31994
  }
31630
31995
  this.schedulePendingQuotaResumes();
31631
31996
  armSchedules();
31997
+ armChatFollowUps();
31632
31998
  armGithubEdgeWatch();
31633
31999
  }
31634
32000
  /** Surface (and, when enabled, clean up) worktrees git knows about but no thread owns. */
@@ -31768,8 +32134,8 @@ var init_orchestrator = __esm({
31768
32134
  }
31769
32135
  }
31770
32136
  clearQuotaResumeTimer(threadId) {
31771
- const timer2 = this.quotaResumeTimers.get(threadId);
31772
- if (timer2) clearTimeout(timer2);
32137
+ const timer3 = this.quotaResumeTimers.get(threadId);
32138
+ if (timer3) clearTimeout(timer3);
31773
32139
  this.quotaResumeTimers.delete(threadId);
31774
32140
  }
31775
32141
  /** Schedule (or fire) auto-retry after a provider session/usage limit reset. */
@@ -31778,11 +32144,11 @@ var init_orchestrator = __esm({
31778
32144
  updateThread(threadId, { quotaResumeAt: resumeAt.toISOString() });
31779
32145
  const delay2 = Math.max(5e3, resumeAt.getTime() - Date.now());
31780
32146
  const capped = Math.min(delay2, 2147483647);
31781
- const timer2 = setTimeout(() => {
32147
+ const timer3 = setTimeout(() => {
31782
32148
  this.quotaResumeTimers.delete(threadId);
31783
32149
  void this.resumeAfterQuotaWait(threadId);
31784
32150
  }, capped);
31785
- this.quotaResumeTimers.set(threadId, timer2);
32151
+ this.quotaResumeTimers.set(threadId, timer3);
31786
32152
  }
31787
32153
  schedulePendingQuotaResumes() {
31788
32154
  for (const thread of listThreads({ includeArchived: false })) {
@@ -32109,11 +32475,11 @@ var init_orchestrator = __esm({
32109
32475
  return results;
32110
32476
  }
32111
32477
  /** Edit the text of a not-yet-started queued message. */
32112
- async editQueuedMessage(threadRef, index, text7) {
32478
+ async editQueuedMessage(threadRef, index, text8) {
32113
32479
  const thread = this.requireThread(threadRef);
32114
32480
  return withThreadLock(thread.id, async () => {
32115
32481
  const current = this.requireThread(thread.id);
32116
- const trimmed = text7.trim();
32482
+ const trimmed = text8.trim();
32117
32483
  if (!trimmed || index < 0 || index >= current.queue.length) {
32118
32484
  return current;
32119
32485
  }
@@ -33048,7 +33414,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
33048
33414
  const request = sameIntent ? pending : {
33049
33415
  op,
33050
33416
  scriptName: scriptName ?? null,
33051
- requestId: (0, import_node_crypto20.randomUUID)(),
33417
+ requestId: (0, import_node_crypto21.randomUUID)(),
33052
33418
  requestedAt: (/* @__PURE__ */ new Date()).toISOString()
33053
33419
  };
33054
33420
  if (!sameIntent) {
@@ -33427,11 +33793,11 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
33427
33793
  const start = Date.now();
33428
33794
  return new Promise((resolve3, reject) => {
33429
33795
  let settled = false;
33430
- let timer2;
33796
+ let timer3;
33431
33797
  const finish = (fn) => {
33432
33798
  if (settled) return;
33433
33799
  settled = true;
33434
- if (timer2) clearInterval(timer2);
33800
+ if (timer3) clearInterval(timer3);
33435
33801
  off();
33436
33802
  fn();
33437
33803
  };
@@ -33457,7 +33823,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
33457
33823
  }
33458
33824
  }
33459
33825
  });
33460
- timer2 = setInterval(() => {
33826
+ timer3 = setInterval(() => {
33461
33827
  const raw = readThread(thread.id);
33462
33828
  if (!raw) {
33463
33829
  finish(() => reject(new Error(`Thread not found: ${thread.id}`)));
@@ -33493,7 +33859,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
33493
33859
  const stillRunning = this.threadLooksLive(thread);
33494
33860
  const rawText = (lastAgent?.text ?? "").trim();
33495
33861
  const finishedText = (rawText && !isInternalAgentStatusText(rawText) ? rawText : "") || (thread.status === "error" || thread.status === "stopped" || thread.status === "broken" ? lastError ?? "" : "");
33496
- const text7 = stillRunning ? "" : finishedText;
33862
+ const text8 = stillRunning ? "" : finishedText;
33497
33863
  const live = stillRunning ? readTurnLive(thread.id) : null;
33498
33864
  const liveSummary = live?.summary && !isInternalAgentStatusText(live.summary) ? live.summary : null;
33499
33865
  const queuedHint = stillRunning && thread.status === "queued" && !liveSummary ? "Queued \u2014 waiting for a concurrency slot" : null;
@@ -33506,7 +33872,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
33506
33872
  });
33507
33873
  const block = thread.agentBlock?.reason?.trim() ? thread.agentBlock : null;
33508
33874
  return {
33509
- text: text7,
33875
+ text: text8,
33510
33876
  status: thread.status,
33511
33877
  taskState,
33512
33878
  sessionId: thread.sessionId,
@@ -34030,7 +34396,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
34030
34396
  this.stop(thread.id, { notifyParent: false });
34031
34397
  this.releaseOrchestratorCaffeinate(thread);
34032
34398
  if (isGlobalThread(thread)) {
34033
- const archived2 = setStatus(thread.id, "archived");
34399
+ const archived2 = archiveClearingFollowUps(thread.id);
34034
34400
  this.emit({ type: "status_changed", threadId: archived2.id, status: "archived" });
34035
34401
  this.enforceHistoryRetention();
34036
34402
  return archived2;
@@ -34049,10 +34415,10 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
34049
34415
  });
34050
34416
  } catch {
34051
34417
  }
34052
- await removeWorktree(thread.repoPath, thread.worktreePath);
34418
+ await removeWorktreeSavingLeftovers(thread);
34053
34419
  }
34054
34420
  }
34055
- const archived = setStatus(thread.id, "archived");
34421
+ const archived = archiveClearingFollowUps(thread.id);
34056
34422
  this.emit({ type: "status_changed", threadId: archived.id, status: "archived" });
34057
34423
  this.enforceHistoryRetention();
34058
34424
  if (thread.repoPath && !isGlobalRepoPath(thread.repoPath)) {
@@ -34082,9 +34448,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
34082
34448
  }
34083
34449
  const { deleteBranchOnPurgeEnabled: deleteBranchOnPurgeEnabled2 } = await Promise.resolve().then(() => (init_app_settings(), app_settings_exports));
34084
34450
  const deleteBranch = opts?.deleteBranch ?? deleteBranchOnPurgeEnabled2();
34085
- await removeWorktree(thread.repoPath, thread.worktreePath, {
34086
- deleteBranch: deleteBranch ? thread.branchName : void 0
34087
- });
34451
+ await removeWorktreeDroppingLeftovers(thread, deleteBranch ? thread.branchName : void 0);
34088
34452
  }
34089
34453
  }
34090
34454
  deleteThreadRecord(thread.id);
@@ -34114,6 +34478,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
34114
34478
  });
34115
34479
  const { ensureWorktreeSideboardIgnored: ensureWorktreeSideboardIgnored2 } = await Promise.resolve().then(() => (init_worktree_exclude(), worktree_exclude_exports));
34116
34480
  await ensureWorktreeSideboardIgnored2(dest);
34481
+ await applyWorktreeLeftovers(thread.repoPath, dest, thread.branchName).catch(() => false);
34117
34482
  }
34118
34483
  const restorePatch = {};
34119
34484
  let alreadyMerged = normalizePrState(thread.prState) === "MERGED";
@@ -34291,8 +34656,8 @@ function createClippedMcpServer() {
34291
34656
  }
34292
34657
 
34293
34658
  // src/mcp/server.ts
34294
- var import_zod12 = require("zod");
34295
- var import_node_crypto25 = require("crypto");
34659
+ var import_zod13 = require("zod");
34660
+ var import_node_crypto26 = require("crypto");
34296
34661
  var import_node_path74 = require("path");
34297
34662
  init_orchestrator();
34298
34663
  init_task_state();
@@ -34331,7 +34696,7 @@ function extractGitHubIssueAttachments(issue) {
34331
34696
  const texts = [issue.body ?? "", ...issue.comments.map((comment) => comment.body)];
34332
34697
  return mergeIssueAttachments(
34333
34698
  texts.flatMap(
34334
- (text7) => extractHttpUrls(text7).filter(isGitHubIssueAttachmentUrl).map((url) => ({
34699
+ (text8) => extractHttpUrls(text8).filter(isGitHubIssueAttachmentUrl).map((url) => ({
34335
34700
  id: url,
34336
34701
  name: url.split("/").pop() || "attachment",
34337
34702
  url
@@ -34364,11 +34729,11 @@ async function downloadGitHubIssueAttachment(input, opts) {
34364
34729
  init_run();
34365
34730
  init_worktree();
34366
34731
  function rewriteGitHubProjectReadError(detail) {
34367
- const text7 = detail.trim() || "gh could not read GitHub Projects";
34368
- if (/read:project|project scope|missing required scopes/i.test(text7)) {
34369
- return `${text7} \u2014 run \`gh auth refresh -s read:project\` so Sideboard can read GitHub Projects.`;
34732
+ const text8 = detail.trim() || "gh could not read GitHub Projects";
34733
+ if (/read:project|project scope|missing required scopes/i.test(text8)) {
34734
+ return `${text8} \u2014 run \`gh auth refresh -s read:project\` so Sideboard can read GitHub Projects.`;
34370
34735
  }
34371
- return text7;
34736
+ return text8;
34372
34737
  }
34373
34738
  function githubProjectsUnreadable(result) {
34374
34739
  return /project|scope|unknown json field/i.test(`${result.stderr}
@@ -35164,16 +35529,16 @@ function orchChildWorkspaceCount(threads, parentId) {
35164
35529
  }
35165
35530
  function withTimeout2(promise, ms, label) {
35166
35531
  return new Promise((resolve3, reject) => {
35167
- const timer2 = setTimeout(() => {
35532
+ const timer3 = setTimeout(() => {
35168
35533
  reject(new Error(`${label} timed out after ${Math.round(ms / 1e3)}s`));
35169
35534
  }, ms);
35170
35535
  promise.then(
35171
35536
  (value) => {
35172
- clearTimeout(timer2);
35537
+ clearTimeout(timer3);
35173
35538
  resolve3(value);
35174
35539
  },
35175
35540
  (err) => {
35176
- clearTimeout(timer2);
35541
+ clearTimeout(timer3);
35177
35542
  reject(err);
35178
35543
  }
35179
35544
  );
@@ -35284,9 +35649,9 @@ init_injected_notices();
35284
35649
  function lastMessagePreview(messages, max = 160) {
35285
35650
  if (!messages?.length) return null;
35286
35651
  for (let i = messages.length - 1; i >= 0; i--) {
35287
- const text7 = messages[i]?.text?.trim();
35288
- if (!text7 || isInternalAgentStatusText(text7) || isInjectedNoticeText(text7)) continue;
35289
- const flat = text7.replace(/\s+/g, " ");
35652
+ const text8 = messages[i]?.text?.trim();
35653
+ if (!text8 || isInternalAgentStatusText(text8) || isInjectedNoticeText(text8)) continue;
35654
+ const flat = text8.replace(/\s+/g, " ");
35290
35655
  return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
35291
35656
  }
35292
35657
  return null;
@@ -35323,15 +35688,15 @@ var CRUSH_COMMENT_MAX_CHARS = 16e3;
35323
35688
  var CRUSH_BODY_MIN_CHARS = 12e3;
35324
35689
  var CRUSH_BODY_MAX_CHARS = 8e3;
35325
35690
  var NEAR_DUP_JACCARD = 0.92;
35326
- function looksLikeMustKeep(text7) {
35327
- return MUST_KEEP_TEXT_RE.test(text7);
35691
+ function looksLikeMustKeep(text8) {
35692
+ return MUST_KEEP_TEXT_RE.test(text8);
35328
35693
  }
35329
- function normalizeText(text7) {
35330
- return text7.replace(/\s+/g, " ").trim().toLowerCase();
35694
+ function normalizeText(text8) {
35695
+ return text8.replace(/\s+/g, " ").trim().toLowerCase();
35331
35696
  }
35332
- function wordSet(text7) {
35697
+ function wordSet(text8) {
35333
35698
  return new Set(
35334
- text7.toLowerCase().split(/\W+/).filter((w) => w.length > 2)
35699
+ text8.toLowerCase().split(/\W+/).filter((w) => w.length > 2)
35335
35700
  );
35336
35701
  }
35337
35702
  function jaccard(a, b) {
@@ -35343,11 +35708,11 @@ function jaccard(a, b) {
35343
35708
  const union = a.size + b.size - inter;
35344
35709
  return union === 0 ? 0 : inter / union;
35345
35710
  }
35346
- function importance(text7) {
35347
- let score = text7.length;
35348
- if (/```/.test(text7)) score += 400;
35349
- if (/https?:\/\//.test(text7)) score += 50;
35350
- if (looksLikeMustKeep(text7)) score += 1e4;
35711
+ function importance(text8) {
35712
+ let score = text8.length;
35713
+ if (/```/.test(text8)) score += 400;
35714
+ if (/https?:\/\//.test(text8)) score += 50;
35715
+ if (looksLikeMustKeep(text8)) score += 1e4;
35351
35716
  return score;
35352
35717
  }
35353
35718
  function meanStd(values) {
@@ -35361,15 +35726,15 @@ function dedupTextItems(items, getText) {
35361
35726
  const keptNorm = [];
35362
35727
  const keptWords = [];
35363
35728
  for (const item of items) {
35364
- const text7 = getText(item);
35365
- const norm = normalizeText(text7);
35729
+ const text8 = getText(item);
35730
+ const norm = normalizeText(text8);
35366
35731
  if (!norm) {
35367
35732
  kept.push(item);
35368
35733
  keptNorm.push(norm);
35369
- keptWords.push(wordSet(text7));
35734
+ keptWords.push(wordSet(text8));
35370
35735
  continue;
35371
35736
  }
35372
- const words = wordSet(text7);
35737
+ const words = wordSet(text8);
35373
35738
  let dupAt = -1;
35374
35739
  for (let i = 0; i < kept.length; i++) {
35375
35740
  if (keptNorm[i] === norm) {
@@ -35387,7 +35752,7 @@ function dedupTextItems(items, getText) {
35387
35752
  keptWords.push(words);
35388
35753
  continue;
35389
35754
  }
35390
- if (text7.length > getText(kept[dupAt]).length) {
35755
+ if (text8.length > getText(kept[dupAt]).length) {
35391
35756
  kept[dupAt] = item;
35392
35757
  keptNorm[dupAt] = norm;
35393
35758
  keptWords[dupAt] = words;
@@ -35428,8 +35793,8 @@ function crushTextItems(items, getText, opts = {}) {
35428
35793
  const outlierFloor = mean + 2 * std;
35429
35794
  const mustKeep = /* @__PURE__ */ new Set();
35430
35795
  unique.forEach((item, i) => {
35431
- const text7 = getText(item);
35432
- if (looksLikeMustKeep(text7) || text7.length > outlierFloor) mustKeep.add(i);
35796
+ const text8 = getText(item);
35797
+ if (looksLikeMustKeep(text8) || text8.length > outlierFloor) mustKeep.add(i);
35433
35798
  });
35434
35799
  const remainingIdx = unique.map((_, i) => i).filter((i) => !mustKeep.has(i));
35435
35800
  let used = [...mustKeep].reduce((n, i) => n + lengths[i], 0);
@@ -35471,9 +35836,9 @@ function crushTextItems(items, getText, opts = {}) {
35471
35836
  reason: "budget"
35472
35837
  };
35473
35838
  }
35474
- function splitBlocks(text7) {
35475
- if (/\n\n/.test(text7)) return text7.split(/\n\n+/);
35476
- return text7.split("\n");
35839
+ function splitBlocks(text8) {
35840
+ if (/\n\n/.test(text8)) return text8.split(/\n\n+/);
35841
+ return text8.split("\n");
35477
35842
  }
35478
35843
  function capOversizedBlock(block, maxChars) {
35479
35844
  if (block.length <= maxChars) return block;
@@ -35485,8 +35850,8 @@ function capOversizedBlock(block, maxChars) {
35485
35850
 
35486
35851
  ${block.slice(-tail)}`;
35487
35852
  }
35488
- function crushMarkdown(text7, opts) {
35489
- const original = text7 ?? "";
35853
+ function crushMarkdown(text8, opts) {
35854
+ const original = text8 ?? "";
35490
35855
  const minChars = opts?.minChars ?? CRUSH_BODY_MIN_CHARS;
35491
35856
  const maxChars = opts?.maxChars ?? CRUSH_BODY_MAX_CHARS;
35492
35857
  if (original.length < minChars) {
@@ -35576,13 +35941,13 @@ function withComments(comments, meta) {
35576
35941
  }
35577
35942
  return { comments: crushed.items, meta };
35578
35943
  }
35579
- function withBody(text7, meta) {
35580
- const crushed = crushMarkdown(text7);
35944
+ function withBody(text8, meta) {
35945
+ const crushed = crushMarkdown(text8);
35581
35946
  if (crushed.truncated) {
35582
35947
  meta.body = { originalChars: crushed.originalChars };
35583
35948
  return { value: crushed.text, meta };
35584
35949
  }
35585
- return { value: text7, meta };
35950
+ return { value: text8, meta };
35586
35951
  }
35587
35952
  function attachCrush(payload, meta) {
35588
35953
  if (!meta.comments && !meta.body) return payload;
@@ -36207,7 +36572,7 @@ init_fetch();
36207
36572
  init_optional_services();
36208
36573
 
36209
36574
  // src/integrations/posthog-oauth.ts
36210
- var import_node_crypto21 = require("crypto");
36575
+ var import_node_crypto22 = require("crypto");
36211
36576
  var import_node_http4 = require("http");
36212
36577
  init_fetch();
36213
36578
  init_app_settings();
@@ -36383,9 +36748,9 @@ async function runPosthogApi(input) {
36383
36748
  body,
36384
36749
  signal: AbortSignal.timeout(POSTHOG_TIMEOUT_MS)
36385
36750
  });
36386
- const text7 = await res.text();
36387
- const truncated = text7.length > POSTHOG_RESPONSE_MAX_CHARS;
36388
- const slice = truncated ? text7.slice(0, POSTHOG_RESPONSE_MAX_CHARS) : text7;
36751
+ const text8 = await res.text();
36752
+ const truncated = text8.length > POSTHOG_RESPONSE_MAX_CHARS;
36753
+ const slice = truncated ? text8.slice(0, POSTHOG_RESPONSE_MAX_CHARS) : text8;
36389
36754
  let parsed = slice;
36390
36755
  if (slice.trim()) {
36391
36756
  try {
@@ -36541,7 +36906,7 @@ function registerArchiveTools(server, orch) {
36541
36906
  );
36542
36907
  server.tool(
36543
36908
  "archive_chat",
36544
- "Archive one agent chat: stop the turn and move that chat to Settings \u2192 History. Other agents on the workspace stay, and the worktree is removed only when this is the last agent. Orchestration chats archive without removing a project checkout. Refuses the cloud coordinator. To archive every agent on a checkout, use archive_workspace. Commit, push, and open PRs via ask_git before archiving when the work should be kept. Merge only when the user explicitly asked.",
36909
+ "Archive one agent chat: stop the turn and move that chat to Settings \u2192 History. Other agents on the workspace stay, and the worktree is removed only when this is the last agent. Uncommitted and untracked files are saved on a hidden git ref and put back uncommitted if that checkout is restored. If that snapshot fails, the checkout stays. History Delete does not keep the snapshot. Orchestration chats archive without removing a project checkout. Refuses the cloud coordinator. To archive every agent on a checkout, use archive_workspace. Commit, push, and open PRs via ask_git before archiving when the work should be kept. Merge only when the user explicitly asked.",
36545
36910
  { ref: import_zod9.z.string().describe("Chat id to archive") },
36546
36911
  async ({ ref }) => {
36547
36912
  const t = orch.getThread(ref);
@@ -36847,11 +37212,91 @@ function registerScheduleTools(server) {
36847
37212
  );
36848
37213
  }
36849
37214
 
36850
- // src/mcp/order-tools.ts
37215
+ // src/mcp/follow-up-tools.ts
36851
37216
  var import_zod11 = require("zod");
37217
+ init_worktree();
37218
+ init_issue_list();
37219
+ init_profile();
37220
+ init_thread_store();
37221
+ init_chat_follow_ups();
37222
+ function text7(payload, isError = false) {
37223
+ return mcpJson(payload, isError);
37224
+ }
37225
+ function callerThread() {
37226
+ const id = process.env[SIDEBOARD_THREAD_ID_ENV]?.trim() || "";
37227
+ if (!id) return null;
37228
+ return findThreadByRef(id);
37229
+ }
37230
+ async function baselineCi(thread) {
37231
+ const selector = resolvePrSelector(thread);
37232
+ if (!selector) return "none";
37233
+ try {
37234
+ const checks = await getPrCiChecks(thread.worktreePath, selector);
37235
+ return ciChecksSettled(checks);
37236
+ } catch {
37237
+ return "unknown";
37238
+ }
37239
+ }
37240
+ function registerFollowUpTools(server) {
37241
+ server.tool(
37242
+ "list_follow_ups",
37243
+ "List follow-ups on this chat. kind=ci wakes when GitHub checks finish. kind=at wakes at a time. A running turn is not interrupted.",
37244
+ {},
37245
+ async () => {
37246
+ const thread = callerThread();
37247
+ if (!thread) return text7({ error: "This chat id is missing" }, true);
37248
+ return text7({ followUps: normalizeChatFollowUps(thread.followUps) });
37249
+ }
37250
+ );
37251
+ server.tool(
37252
+ "create_follow_up",
37253
+ "Register a follow-up on THIS chat. kind=ci sends the prompt when GitHub checks on this chat\u2019s PR finish (pass or fail). Checks that are already finished do not send until a later run finishes. A failed checks read does not count as finished or in progress. A CI follow-up that is still pending at deadline (default 7 days) ends silently. kind=at sends at `30m`, `2h`, `1d`, or an ISO time and waits behind a turn that is already running. Cap 10.",
37254
+ {
37255
+ kind: import_zod11.z.enum(["ci", "at"]),
37256
+ prompt: import_zod11.z.string(),
37257
+ at: import_zod11.z.string().optional(),
37258
+ deadline: import_zod11.z.string().optional()
37259
+ },
37260
+ async ({ kind, prompt, at, deadline }) => {
37261
+ const thread = callerThread();
37262
+ if (!thread) return text7({ error: "This chat id is missing" }, true);
37263
+ if (thread.status === "archived") return text7({ error: "This chat is archived" }, true);
37264
+ const existing = normalizeChatFollowUps(thread.followUps);
37265
+ const ciBaseline = kind === "ci" ? await baselineCi(thread) : void 0;
37266
+ const added = addChatFollowUp(
37267
+ existing,
37268
+ { kind, prompt, at, deadline, ciBaseline },
37269
+ /* @__PURE__ */ new Date()
37270
+ );
37271
+ if (!added.ok) return text7({ error: added.error }, true);
37272
+ updateThread(thread.id, { followUps: added.followUps });
37273
+ return text7({ followUps: added.followUps });
37274
+ }
37275
+ );
37276
+ server.tool(
37277
+ "delete_follow_up",
37278
+ "Remove one follow-up from this chat by id.",
37279
+ { id: import_zod11.z.string() },
37280
+ async ({ id }) => {
37281
+ const thread = callerThread();
37282
+ if (!thread) return text7({ error: "This chat id is missing" }, true);
37283
+ const existing = normalizeChatFollowUps(thread.followUps);
37284
+ const followUps = existing.filter((item) => item.id !== id.trim());
37285
+ if (followUps.length === existing.length) return text7({ error: "Follow-up not found" }, true);
37286
+ updateThread(thread.id, { followUps });
37287
+ return text7({ followUps });
37288
+ }
37289
+ );
37290
+ }
37291
+
37292
+ // src/mcp/server.ts
37293
+ init_turn_failure_class();
37294
+
37295
+ // src/mcp/order-tools.ts
37296
+ var import_zod12 = require("zod");
36852
37297
 
36853
37298
  // src/order/order.ts
36854
- var import_node_crypto22 = require("crypto");
37299
+ var import_node_crypto23 = require("crypto");
36855
37300
  var import_node_fs72 = require("fs");
36856
37301
  var import_node_path70 = require("path");
36857
37302
  init_paths();
@@ -37555,7 +38000,7 @@ function setOrderPlan(input) {
37555
38000
  const owner = input.ownerThreadId?.trim() ?? "";
37556
38001
  const existing = file.plans.find((plan2) => plan2.ownerThreadId === owner);
37557
38002
  const plan = {
37558
- id: existing?.id ?? (0, import_node_crypto22.randomUUID)(),
38003
+ id: existing?.id ?? (0, import_node_crypto23.randomUUID)(),
37559
38004
  ownerThreadId: owner,
37560
38005
  title,
37561
38006
  summary: input.summary?.trim().slice(0, 600) ?? existing?.summary ?? "",
@@ -37622,7 +38067,7 @@ function selectPlan(file, input) {
37622
38067
  if (file.plans.length === 1) return file.plans[0];
37623
38068
  if (file.plans.length === 0) {
37624
38069
  const plan = {
37625
- id: (0, import_node_crypto22.randomUUID)(),
38070
+ id: (0, import_node_crypto23.randomUUID)(),
37626
38071
  ownerThreadId: "",
37627
38072
  title: "Planner",
37628
38073
  summary: "",
@@ -37656,7 +38101,7 @@ function setOrderDependency(input) {
37656
38101
  }
37657
38102
  const loop = dependencyWouldCycle(scoped, draft);
37658
38103
  const edge = {
37659
- id: (0, import_node_crypto22.randomUUID)(),
38104
+ id: (0, import_node_crypto23.randomUUID)(),
37660
38105
  planId: plan.id,
37661
38106
  waitsOn,
37662
38107
  gate,
@@ -37705,8 +38150,8 @@ init_issue_list();
37705
38150
  init_thread_store();
37706
38151
  init_global_workspace();
37707
38152
  init_plan_file();
37708
- var kindSchema = import_zod11.z.enum(["pr", "issue", "workspace", "orchestration"]);
37709
- function callerThread() {
38153
+ var kindSchema = import_zod12.z.enum(["pr", "issue", "workspace", "orchestration"]);
38154
+ function callerThread2() {
37710
38155
  const id = process.env[SIDEBOARD_THREAD_ID_ENV]?.trim();
37711
38156
  if (!id) return null;
37712
38157
  return readThread(id);
@@ -37719,7 +38164,7 @@ function readCheckoutPlan(caller) {
37719
38164
  return readPlanFile(root);
37720
38165
  }
37721
38166
  function orchestrationOwnerId(worktree) {
37722
- const caller = callerThread();
38167
+ const caller = callerThread2();
37723
38168
  if (!caller) {
37724
38169
  throw new Error(
37725
38170
  worktree ? "No worktree chat is bound to this tool." : "No orchestration chat is bound to this tool."
@@ -37755,10 +38200,10 @@ function registerOrderTools(server) {
37755
38200
  try {
37756
38201
  const owner = orchestrationOwnerId(worktree);
37757
38202
  const plan = getOrderPlan(owner);
37758
- const caller = callerThread();
38203
+ const caller = callerThread2();
37759
38204
  if (!plan) {
37760
- const text7 = worktree ? "This checkout's orchestrator has no plan yet." : "This chat has no plan. set_plan drafts one. Then show_plan so the user sees it.";
37761
- return { content: [{ type: "text", text: text7 }] };
38205
+ const text8 = worktree ? "This checkout's orchestrator has no plan yet." : "This chat has no plan. set_plan drafts one. Then show_plan so the user sees it.";
38206
+ return { content: [{ type: "text", text: text8 }] };
37762
38207
  }
37763
38208
  const rows = listOrderRows(plan.id);
37764
38209
  const place = worktree && caller ? `${formatOrderPlace(rows, orderSnapshotFromThread(caller))}
@@ -37777,16 +38222,16 @@ function registerOrderTools(server) {
37777
38222
  worktree ? "Change what this checkout waits on. Omit subject to mean this workspace (hold=merge uses this PR; hold=start on a ticket uses this issue). gate=in-main (met when that PR is merged) or in-prod (stays waiting until satisfy_dependency). hold=start means do not begin; hold=merge means do not merge. You cannot set a dependency for a different checkout. show_plan so the user sees the change." : "Record a step on this orchestration plan. waitsOn must reach gate before subject can hold. gate=in-main is met when that PR is merged; gate=in-prod stays waiting until satisfy_dependency. hold=start blocks starting the subject; hold=merge blocks merging it. Example: PR 1 in prod before PR 2 can merge; PR 3 in main before issue 4 can start. Pass repoPath when the same PR number exists in more than one project. Worktree agents set their own checkout and can omit subject. Then show_plan so the user sees it.",
37778
38223
  {
37779
38224
  waitsOnKind: kindSchema.describe("What must happen first: pr, issue, workspace, or orchestration"),
37780
- waitsOnRef: import_zod11.z.string().describe("PR number (12), issue id (ENG-4), or workspace chat id / worktree path"),
37781
- waitsOnRepoPath: import_zod11.z.string().optional().describe("Project path when a PR or issue number is not unique"),
37782
- waitsOnLabel: import_zod11.z.string().optional().describe("Short label on the planner"),
37783
- gate: import_zod11.z.enum(["in-main", "in-prod"]).describe("in-main: merged to the default branch. in-prod: deployed; mark with satisfy_dependency"),
37784
- hold: import_zod11.z.enum(["start", "merge"]).describe("start: subject cannot begin. merge: subject cannot merge"),
38225
+ waitsOnRef: import_zod12.z.string().describe("PR number (12), issue id (ENG-4), or workspace chat id / worktree path"),
38226
+ waitsOnRepoPath: import_zod12.z.string().optional().describe("Project path when a PR or issue number is not unique"),
38227
+ waitsOnLabel: import_zod12.z.string().optional().describe("Short label on the planner"),
38228
+ gate: import_zod12.z.enum(["in-main", "in-prod"]).describe("in-main: merged to the default branch. in-prod: deployed; mark with satisfy_dependency"),
38229
+ hold: import_zod12.z.enum(["start", "merge"]).describe("start: subject cannot begin. merge: subject cannot merge"),
37785
38230
  subjectKind: kindSchema.optional().describe("What is held. Required from orchestration. Omit on a worktree to mean this checkout."),
37786
- subjectRef: import_zod11.z.string().optional().describe("PR number, issue id, or workspace ref for the subject"),
37787
- subjectRepoPath: import_zod11.z.string().optional(),
37788
- subjectLabel: import_zod11.z.string().optional(),
37789
- note: import_zod11.z.string().optional().describe("Why this order matters")
38231
+ subjectRef: import_zod12.z.string().optional().describe("PR number, issue id, or workspace ref for the subject"),
38232
+ subjectRepoPath: import_zod12.z.string().optional(),
38233
+ subjectLabel: import_zod12.z.string().optional(),
38234
+ note: import_zod12.z.string().optional().describe("Why this order matters")
37790
38235
  },
37791
38236
  async (args) => {
37792
38237
  try {
@@ -37795,7 +38240,7 @@ function registerOrderTools(server) {
37795
38240
  if (hasKind !== hasRef) {
37796
38241
  throw new Error("Pass subjectKind and subjectRef together, or omit both on a worktree.");
37797
38242
  }
37798
- const caller = callerThread();
38243
+ const caller = callerThread2();
37799
38244
  let subject;
37800
38245
  const hold = parseOrderHold(args.hold);
37801
38246
  if (!hasKind) {
@@ -37850,9 +38295,9 @@ function registerOrderTools(server) {
37850
38295
  "set_plan",
37851
38296
  "Draft or retitle this chat's plan. It stays draft until execute_plan. Pass goal for the outcome the steps are trying to reach. Then set_dependency for each gate. A step may loop back to an earlier one. Call show_plan so the user sees it. Do not paste the diagram in chat. Do not start workspaces while it is draft.",
37852
38297
  {
37853
- title: import_zod11.z.string().describe("Short name for the plan"),
37854
- summary: import_zod11.z.string().optional().describe("What this order is for, in a sentence or two"),
37855
- goal: import_zod11.z.string().optional().describe("Outcome the steps are trying to reach")
38298
+ title: import_zod12.z.string().describe("Short name for the plan"),
38299
+ summary: import_zod12.z.string().optional().describe("What this order is for, in a sentence or two"),
38300
+ goal: import_zod12.z.string().optional().describe("Outcome the steps are trying to reach")
37856
38301
  },
37857
38302
  async ({ title, summary, goal }) => {
37858
38303
  try {
@@ -37872,7 +38317,7 @@ function registerOrderTools(server) {
37872
38317
  "execute_plan",
37873
38318
  "Mark the plan active after the user has seen it and told you to run it. Returns ready steps (start those with create_workspace or send_to_chat) and waiting steps (leave them alone). Does not create workspaces. Pass agreed: true only after they agree. Merge only if they asked.",
37874
38319
  {
37875
- agreed: import_zod11.z.literal(true).describe("True only after the user has seen the plan and told you to run it")
38320
+ agreed: import_zod12.z.literal(true).describe("True only after the user has seen the plan and told you to run it")
37876
38321
  },
37877
38322
  async () => {
37878
38323
  try {
@@ -37905,7 +38350,7 @@ function registerOrderTools(server) {
37905
38350
  worktree ? "Open the plans for this checkout in the side column. That is the orchestration diagram, with this checkout marked, and this checkout's implementation plan (plan.md) when the file exists. Does not write either plan. Change a step with set_dependency or clear_dependency, then show it again. Do not paste the diagram in chat." : "Open this chat's plan in the side column. Call it after set_plan or set_dependency so the user sees the plan. A worktree show_plan also opens that checkout's implementation plan (plan.md) when the file exists. Does not write either plan. Do not paste the diagram in chat.",
37906
38351
  {},
37907
38352
  async () => {
37908
- const caller = callerThread();
38353
+ const caller = callerThread2();
37909
38354
  let diagramHtml = null;
37910
38355
  let diagramTitle = "Planner";
37911
38356
  let diagramError = null;
@@ -37943,10 +38388,10 @@ function registerOrderTools(server) {
37943
38388
  server.tool(
37944
38389
  "clear_dependency",
37945
38390
  worktree ? "Remove a planner step this checkout is part of. Pass id from list_order. Then show_plan so the user sees it." : "Remove one planner step. Pass id from list_order. Then show_plan so the user sees it.",
37946
- { id: import_zod11.z.string().describe("Step id from list_order") },
38391
+ { id: import_zod12.z.string().describe("Step id from list_order") },
37947
38392
  async ({ id }) => {
37948
38393
  try {
37949
- const caller = callerThread();
38394
+ const caller = callerThread2();
37950
38395
  clearOrderDependency(
37951
38396
  id,
37952
38397
  worktree && caller ? orderSnapshotFromThread(caller) : null,
@@ -37962,8 +38407,8 @@ function registerOrderTools(server) {
37962
38407
  "satisfy_dependency",
37963
38408
  "Mark a planner gate met. Use this when a PR is in production \u2014 Sideboard cannot see deploys. in-main also clears on its own once that PR is merged. Pass satisfied=false to undo a manual mark. One mark covers every step waiting on that same gate.",
37964
38409
  {
37965
- id: import_zod11.z.string().describe("Step id from list_order"),
37966
- satisfied: import_zod11.z.boolean().optional().describe("false clears the manual mark. Default true.")
38410
+ id: import_zod12.z.string().describe("Step id from list_order"),
38411
+ satisfied: import_zod12.z.boolean().optional().describe("false clears the manual mark. Default true.")
37967
38412
  },
37968
38413
  async ({ id, satisfied }) => {
37969
38414
  try {
@@ -37973,7 +38418,7 @@ function registerOrderTools(server) {
37973
38418
  const rows = listOrderRows(plan.id);
37974
38419
  const hit = rows.find((row) => row.id === id || id.length >= 8 && row.id.startsWith(id));
37975
38420
  if (!hit) throw new Error("That step is on another orchestration chat's plan.");
37976
- const caller = callerThread();
38421
+ const caller = callerThread2();
37977
38422
  if (worktree && caller && !orderEdgeTouches(hit, orderSnapshotFromThread(caller))) {
37978
38423
  throw new Error("This checkout can only change a step it is part of.");
37979
38424
  }
@@ -37993,7 +38438,7 @@ function registerOrderTools(server) {
37993
38438
  }
37994
38439
 
37995
38440
  // src/agent-rpc/handlers.ts
37996
- var import_node_crypto23 = require("crypto");
38441
+ var import_node_crypto24 = require("crypto");
37997
38442
  var import_node_path71 = require("path");
37998
38443
  init_wait_for_job();
37999
38444
  init_wait_for_turn();
@@ -38040,7 +38485,7 @@ setToolPermissionPublisher({
38040
38485
  // src/agent-rpc/handlers.ts
38041
38486
  init_protocol2();
38042
38487
  function presentArtifactResult(input) {
38043
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto23.randomUUID)().slice(0, 8)}`;
38488
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto24.randomUUID)().slice(0, 8)}`;
38044
38489
  return {
38045
38490
  ok: true,
38046
38491
  artifact_id: id,
@@ -38065,7 +38510,7 @@ init_worktree();
38065
38510
  init_paths();
38066
38511
 
38067
38512
  // src/board/board-pins.ts
38068
- var import_node_crypto24 = require("crypto");
38513
+ var import_node_crypto25 = require("crypto");
38069
38514
  var import_node_fs73 = require("fs");
38070
38515
  var import_node_path72 = require("path");
38071
38516
  init_paths();
@@ -38307,9 +38752,9 @@ async function getGitHubStatus() {
38307
38752
  };
38308
38753
  }
38309
38754
  const status = await run("gh", ["auth", "status"], { reject: false });
38310
- const text7 = `${status.stdout}
38755
+ const text8 = `${status.stdout}
38311
38756
  ${status.stderr}`;
38312
- const loginMatch = text7.match(/Logged in to ([^\s]+) account (\S+)/i) ?? text7.match(/Logged in to ([^\s]+) as (\S+)/i);
38757
+ const loginMatch = text8.match(/Logged in to ([^\s]+) account (\S+)/i) ?? text8.match(/Logged in to ([^\s]+) as (\S+)/i);
38313
38758
  if (loginMatch) {
38314
38759
  return {
38315
38760
  connected: true,
@@ -38425,16 +38870,16 @@ async function startMcpServer() {
38425
38870
  "list_board",
38426
38871
  "Home Kanban of workspaces (New, Draft, Review, Approved, Merged) \u2014 one card per checkout; sibling chats on that card are separate agents. Same cards as desktop Home. Path to merge: no PR \u2192 draft PR \u2192 open PR \u2192 approved \u2192 merged. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not stages. Orchestration chats are not on the board. Filters: query, repoPath, kind (ticket/PR/branch source), ownership (mine = your PRs / WIP; reviewing = someone else's PR), column, limit (default 40). create_workspace adds a workspace (and a Home card), or returns the live checkout if that ticket/PR/named branch is already checked out. That reuse is one checkout, not one agent \u2014 fork_chat to add another.",
38427
38872
  {
38428
- query: import_zod12.z.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
38429
- repoPath: import_zod12.z.string().optional().describe("Limit to one project path from list_projects"),
38430
- kind: import_zod12.z.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
38431
- ownership: import_zod12.z.enum(["all", "mine", "reviewing"]).optional().describe(
38873
+ query: import_zod13.z.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
38874
+ repoPath: import_zod13.z.string().optional().describe("Limit to one project path from list_projects"),
38875
+ kind: import_zod13.z.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
38876
+ ownership: import_zod13.z.enum(["all", "mine", "reviewing"]).optional().describe(
38432
38877
  "Mine = PRs you authored or local WIP; reviewing = someone else's PR. Uses the gh login."
38433
38878
  ),
38434
- column: import_zod12.z.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
38879
+ column: import_zod13.z.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
38435
38880
  "Return cards for this column only (totals still include the rest). approved is an open PR GitHub has approved. needs_you is a legacy alias for new."
38436
38881
  ),
38437
- limit: import_zod12.z.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
38882
+ limit: import_zod13.z.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
38438
38883
  },
38439
38884
  async ({ query, repoPath, kind, ownership, column, limit }) => {
38440
38885
  const workspaces = orch.listWorkspaces();
@@ -38464,7 +38909,7 @@ async function startMcpServer() {
38464
38909
  server.tool(
38465
38910
  "get_chat",
38466
38911
  "Get a compact chat summary by id/ref. Includes last message preview, parentChatId, and child workspace chats (status + lastText). While running, includes progress (last tool/thinking) and lastActivityAt. Includes usage (billed token + costUsd totals when providers reported cost) and lastTurnUsage. blockedReason is why that agent is waiting on a person (question, plan approval, or a reported block).",
38467
- { ref: import_zod12.z.string() },
38912
+ { ref: import_zod13.z.string() },
38468
38913
  async ({ ref }) => {
38469
38914
  const t = orch.getThread(ref);
38470
38915
  if (!t) {
@@ -38511,17 +38956,17 @@ async function startMcpServer() {
38511
38956
  "present_artifact",
38512
38957
  "Show a document or live log in Sideboard\u2019s side column. For html/svg/markdown/react, pass the FULL document and do not also fence that same body in chat. For type=log, pass only NEW lines (same artifact_id appends). Prefer type=log for long-running job output \u2014 do not resend HTML. type=react is a single default-export component (JSX/TSX); only react/react-dom imports.",
38513
38958
  {
38514
- title: import_zod12.z.string().describe("Short title shown in the artifact pane header"),
38515
- type: import_zod12.z.enum(["html", "svg", "markdown", "react", "log"]).describe(
38959
+ title: import_zod13.z.string().describe("Short title shown in the artifact pane header"),
38960
+ type: import_zod13.z.enum(["html", "svg", "markdown", "react", "log"]).describe(
38516
38961
  "html/svg/markdown/react replace the pane. log appends content to the same artifact_id (new lines only)."
38517
38962
  ),
38518
- content: import_zod12.z.string().describe(
38963
+ content: import_zod13.z.string().describe(
38519
38964
  "html/svg/markdown/react: full document. log: only the new lines since the last call (empty is ok for a status-only update)."
38520
38965
  ),
38521
- artifact_id: import_zod12.z.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
38522
- status: import_zod12.z.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
38523
- phase: import_zod12.z.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
38524
- mode: import_zod12.z.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
38966
+ artifact_id: import_zod13.z.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
38967
+ status: import_zod13.z.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
38968
+ phase: import_zod13.z.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
38969
+ mode: import_zod13.z.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
38525
38970
  },
38526
38971
  async ({ title, type, artifact_id, status, phase, mode }) => {
38527
38972
  return mcpJson(
@@ -38534,15 +38979,15 @@ async function startMcpServer() {
38534
38979
  "ask_user",
38535
38980
  "Ask the user a clarifying multiple-choice question in Sideboard\u2019s composer. Call only when work is blocked on choosing among a few concrete options (approach fork, which API, auth vs cookies). Do not call for greetings, check-ins, \u201Chello\u201D, open-ended how-can-I-help, or to invent a menu of possible next tasks \u2014 reply in chat instead. If one option is the obvious default, proceed without asking. Before calling, write a short chat message explaining the decision and what each option means. Include a description on every option. After calling, stop and wait for answers. Not for \u201Cis the plan ready?\u201D.",
38536
38981
  {
38537
- questions: import_zod12.z.array(
38538
- import_zod12.z.object({
38539
- question: import_zod12.z.string().describe("Full question text ending with ?"),
38540
- header: import_zod12.z.string().max(24).optional().describe("Short label shown above the question"),
38541
- multiSelect: import_zod12.z.boolean().optional().describe("Allow selecting multiple options"),
38542
- options: import_zod12.z.array(
38543
- import_zod12.z.object({
38544
- label: import_zod12.z.string(),
38545
- description: import_zod12.z.string().optional().describe("What this option means / when to choose it (strongly preferred)")
38982
+ questions: import_zod13.z.array(
38983
+ import_zod13.z.object({
38984
+ question: import_zod13.z.string().describe("Full question text ending with ?"),
38985
+ header: import_zod13.z.string().max(24).optional().describe("Short label shown above the question"),
38986
+ multiSelect: import_zod13.z.boolean().optional().describe("Allow selecting multiple options"),
38987
+ options: import_zod13.z.array(
38988
+ import_zod13.z.object({
38989
+ label: import_zod13.z.string(),
38990
+ description: import_zod13.z.string().optional().describe("What this option means / when to choose it (strongly preferred)")
38546
38991
  })
38547
38992
  ).min(2).max(6).describe("2\u20136 choices (Sideboard also offers Other)")
38548
38993
  })
@@ -38568,9 +39013,9 @@ async function startMcpServer() {
38568
39013
  "present_plan",
38569
39014
  PRESENT_PLAN_TOOL_DESCRIPTION,
38570
39015
  {
38571
- title: import_zod12.z.string().optional().describe("Short plan title (defaults to Plan)"),
38572
- content: import_zod12.z.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
38573
- thread_id: import_zod12.z.string().optional().describe("Sideboard thread id when cwd is not the worktree")
39016
+ title: import_zod13.z.string().optional().describe("Short plan title (defaults to Plan)"),
39017
+ content: import_zod13.z.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
39018
+ thread_id: import_zod13.z.string().optional().describe("Sideboard thread id when cwd is not the worktree")
38574
39019
  },
38575
39020
  async ({ title, content, thread_id }) => {
38576
39021
  const { writePlanFile: writePlanFile2 } = await Promise.resolve().then(() => (init_plan_file(), plan_file_exports));
@@ -38599,15 +39044,15 @@ async function startMcpServer() {
38599
39044
  "present_schema",
38600
39045
  "Open Sideboard\u2019s schema-driven side column (filterable table and/or form) when the user needs to filter, edit, publish, or persist records. Do not call this just to re-display rows you already wrote as a markdown table. If the user asks for an editable / interactive table, call this even if chat already showed those rows. Pass JSON Schema + optional schemaUi. Prefer datasource=inline with embedded resource/records. Use datasource=brightsy with resource_id only when the user is logged into Brightsy.",
38601
39046
  {
38602
- title: import_zod12.z.string().describe("Pane title"),
38603
- mode: import_zod12.z.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
38604
- datasource: import_zod12.z.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
38605
- resource_id: import_zod12.z.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
38606
- record_id: import_zod12.z.string().optional().describe("Record id when opening form mode"),
38607
- resource: import_zod12.z.record(import_zod12.z.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
38608
- record: import_zod12.z.record(import_zod12.z.unknown()).optional().describe("Inline record { id, data, published_at? }"),
38609
- records: import_zod12.z.array(import_zod12.z.record(import_zod12.z.unknown())).optional().describe("Inline records for table mode"),
38610
- pane_id: import_zod12.z.string().optional().describe("Stable pane id across updates")
39047
+ title: import_zod13.z.string().describe("Pane title"),
39048
+ mode: import_zod13.z.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
39049
+ datasource: import_zod13.z.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
39050
+ resource_id: import_zod13.z.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
39051
+ record_id: import_zod13.z.string().optional().describe("Record id when opening form mode"),
39052
+ resource: import_zod13.z.record(import_zod13.z.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
39053
+ record: import_zod13.z.record(import_zod13.z.unknown()).optional().describe("Inline record { id, data, published_at? }"),
39054
+ records: import_zod13.z.array(import_zod13.z.record(import_zod13.z.unknown())).optional().describe("Inline records for table mode"),
39055
+ pane_id: import_zod13.z.string().optional().describe("Stable pane id across updates")
38611
39056
  },
38612
39057
  async (args) => {
38613
39058
  const id = args.pane_id?.trim() || `schema_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -38628,10 +39073,10 @@ async function startMcpServer() {
38628
39073
  "present_files",
38629
39074
  "Open Sideboard\u2019s Files column (CMS-style file manager: browse, upload, pick). Use datasource=brightsy when the user is logged into Brightsy account storage; datasource=memory for a session-local demo store. Prefer this over claiming a file manager UI is unavailable. Pair with present_schema when editing records that need media.",
38630
39075
  {
38631
- title: import_zod12.z.string().optional().describe("Pane title (default: Files)"),
38632
- datasource: import_zod12.z.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
38633
- path: import_zod12.z.string().optional().describe("Initial folder path (e.g. public)"),
38634
- pane_id: import_zod12.z.string().optional().describe("Stable pane id across updates")
39076
+ title: import_zod13.z.string().optional().describe("Pane title (default: Files)"),
39077
+ datasource: import_zod13.z.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
39078
+ path: import_zod13.z.string().optional().describe("Initial folder path (e.g. public)"),
39079
+ pane_id: import_zod13.z.string().optional().describe("Stable pane id across updates")
38635
39080
  },
38636
39081
  async (args) => {
38637
39082
  const id = args.pane_id?.trim() || `files_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -38651,8 +39096,8 @@ async function startMcpServer() {
38651
39096
  "wait_for_job",
38652
39097
  "Wait on a detached long job (tests, pack, deploy, connector CLI) started with detached-job.cjs. MCP clients kill tools around 60s, so this returns within 45s. Sideboard opens a type=log pane from this result (artifact_id = job id, content = delta). stillRunning is the source of truth \u2014 if true, call wait_for_job again. If the job is hanging, producing no useful output, or doing the wrong thing, call stop_job instead of looping forever. Do not end the turn or tell the user you will let them know later. If false, ok/failed is the result.",
38653
39098
  {
38654
- id: import_zod12.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
38655
- timeoutMs: import_zod12.z.number().optional()
39099
+ id: import_zod13.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
39100
+ timeoutMs: import_zod13.z.number().optional()
38656
39101
  },
38657
39102
  async ({ id, timeoutMs }) => {
38658
39103
  const result = await waitForDetachedJob(process.cwd(), id, {
@@ -38665,8 +39110,8 @@ async function startMcpServer() {
38665
39110
  "stop_job",
38666
39111
  "Stop a detached job you started with detached-job.cjs when it is hanging, producing no useful output, buffering forever, or doing the wrong thing (wrong project, infinite watch, huge dump). Do not stop a pack/test/deploy that is clearly making progress. The type=log pane updates to status=failed with the last delta. Then decide the next step.",
38667
39112
  {
38668
- id: import_zod12.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
38669
- reason: import_zod12.z.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
39113
+ id: import_zod13.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
39114
+ reason: import_zod13.z.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
38670
39115
  },
38671
39116
  async ({ id, reason }) => {
38672
39117
  const result = await stopDetachedJob(process.cwd(), id, { reason });
@@ -38678,7 +39123,7 @@ async function startMcpServer() {
38678
39123
  "list_run_scripts",
38679
39124
  "List .sideboard/.conductor run scripts for this thread (same menu as the desktop Dev button) and which are active. Each script and active run includes preview: url (open http://localhost:<SIDEBOARD_PORT>) or window (Electron: native window is the app; url is renderer/HMR only). Never guess :3000. Worktree turns may omit ref (uses cwd).",
38680
39125
  {
38681
- ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
39126
+ ref: import_zod13.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
38682
39127
  },
38683
39128
  async ({ ref }) => {
38684
39129
  try {
@@ -38708,8 +39153,8 @@ async function startMcpServer() {
38708
39153
  "run_dev_script",
38709
39154
  "Start a .sideboard/.conductor run script (same as the desktop Dev / play button). Several named scripts can run at once; each gets its own port, and starting one does not stop the others. Logs and Stop appear in the thread UI \u2014 do not detached-job or shell-spawn the same command. Returns {port, ports, url, preview}. preview=url \u2192 open url (browser, curl, Playwright). preview=window \u2192 Electron: the native window is the app; url is renderer/HMR only (no preload/IPC in a browser). The port is allocated SIDEBOARD_PORT, not 3000. Worktree turns may omit ref (uses cwd). Omit name for the default script.",
38710
39155
  {
38711
- ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
38712
- name: import_zod12.z.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
39156
+ ref: import_zod13.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
39157
+ name: import_zod13.z.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
38713
39158
  },
38714
39159
  async ({ ref, name }) => {
38715
39160
  try {
@@ -38737,8 +39182,8 @@ async function startMcpServer() {
38737
39182
  "stop_dev_script",
38738
39183
  "Stop a run script started with run_dev_script or the desktop Dev button (same as UI Stop). Omit name to stop all scripts on this worktree. Worktree turns may omit ref (uses cwd).",
38739
39184
  {
38740
- ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
38741
- name: import_zod12.z.string().optional().describe("Script name to stop; omit to stop all active scripts.")
39185
+ ref: import_zod13.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
39186
+ name: import_zod13.z.string().optional().describe("Script name to stop; omit to stop all active scripts.")
38742
39187
  },
38743
39188
  async ({ ref, name }) => {
38744
39189
  try {
@@ -38755,9 +39200,9 @@ async function startMcpServer() {
38755
39200
  "get_run_log",
38756
39201
  "Read the Run-tab terminal for a worktree script (same stdout/stderr as the desktop Dev pane). Default is a tail \u2014 raise `tail` only if the error is missing. Worktree turns may omit ref (uses cwd). Omit name for the default script.",
38757
39202
  {
38758
- ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
38759
- name: import_zod12.z.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
38760
- tail: import_zod12.z.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
39203
+ ref: import_zod13.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
39204
+ name: import_zod13.z.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
39205
+ tail: import_zod13.z.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
38761
39206
  `Max characters to return from the end (default ${DEFAULT_RUN_LOG_TAIL_CHARS}). Do not request the full buffer unless the tail is truncated and you still need more.`
38762
39207
  )
38763
39208
  },
@@ -38811,8 +39256,8 @@ async function startMcpServer() {
38811
39256
  }
38812
39257
  });
38813
39258
  } catch (err) {
38814
- const text7 = err instanceof Error ? err.message : String(err);
38815
- return { content: [{ type: "text", text: text7 }], isError: true };
39259
+ const text8 = err instanceof Error ? err.message : String(err);
39260
+ return { content: [{ type: "text", text: text8 }], isError: true };
38816
39261
  }
38817
39262
  }
38818
39263
  );
@@ -38820,8 +39265,8 @@ async function startMcpServer() {
38820
39265
  "notify_orchestrator",
38821
39266
  "Wake the parent Global orchestrator with a short status so it does not have to poll wait_for_turn. Use when you are blocked and the parent may have moved on (missing access, waiting on something the coordinator must handle). The message is shown on the sidebar and board until the next user message in this chat. ask_user already notifies for input-required \u2014 do not call this for the same question. Information only: never a git command. Do not use this to steer other worktrees.",
38822
39267
  {
38823
- message: import_zod12.z.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
38824
- reason: import_zod12.z.enum(["input-required", "blocked"]).optional().describe(
39268
+ message: import_zod13.z.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
39269
+ reason: import_zod13.z.enum(["input-required", "blocked"]).optional().describe(
38825
39270
  "input-required = waiting on the user in this chat; blocked = need the coordinator (default)."
38826
39271
  )
38827
39272
  },
@@ -38847,23 +39292,24 @@ async function startMcpServer() {
38847
39292
  ...result.deduped ? { deduped: true } : {}
38848
39293
  });
38849
39294
  } catch (err) {
38850
- const text7 = err instanceof Error ? err.message : String(err);
38851
- return { content: [{ type: "text", text: text7 }], isError: true };
39295
+ const text8 = err instanceof Error ? err.message : String(err);
39296
+ return { content: [{ type: "text", text: text8 }], isError: true };
38852
39297
  }
38853
39298
  }
38854
39299
  );
38855
39300
  }
38856
39301
  registerScheduleTools(server);
39302
+ registerFollowUpTools(server);
38857
39303
  registerOrderTools(server);
38858
39304
  server.tool(
38859
39305
  "set_workspace_tags",
38860
39306
  worktreeProfile ? "Update tags on this workspace (the checkout you are in). Omit ref to use this chat. mode=replace (default), add, or remove. Short labels \u2014 the same ones the orchestrator used for this task. You cannot retag a different checkout." : "Label a project workspace so related checkouts stay recognizable in the sidebar and on the phone. Pass any chat id on that workspace. Use the same tags on every workspace from one task. mode=replace is the default; add and remove change the set. create_workspace tags= sets them at create time. Not for orchestration chats.",
38861
39307
  {
38862
- ref: import_zod12.z.string().optional().describe(
39308
+ ref: import_zod13.z.string().optional().describe(
38863
39309
  worktreeProfile ? "Omit for this chat. Another chat id only if it is on this same checkout." : "Chat id on the workspace to label."
38864
39310
  ),
38865
- tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).describe("Labels to set. A string may be comma-separated."),
38866
- mode: import_zod12.z.enum(["replace", "add", "remove"]).optional()
39311
+ tags: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.array(import_zod13.z.string())]).describe("Labels to set. A string may be comma-separated."),
39312
+ mode: import_zod13.z.enum(["replace", "add", "remove"]).optional()
38867
39313
  },
38868
39314
  async ({ ref, tags, mode }) => {
38869
39315
  try {
@@ -38891,10 +39337,10 @@ async function startMcpServer() {
38891
39337
  "set_wake_on_github_edges",
38892
39338
  worktreeProfile ? "Opt this checkout into orchestrator wakes when CI starts failing or GitHub requests a review. Omit ref. Only works after Settings \u2192 Advanced \u2192 Wake orchestrator on CI / review-requested is on. Do not change that Advanced switch." : "Opt a project workspace into CI and review-request wakes. Pass any chat id on that checkout. Only works after Settings \u2192 Advanced \u2192 Wake orchestrator on CI / review-requested is already on. Do not change that Advanced switch. Not for orchestration chats.",
38893
39339
  {
38894
- ref: import_zod12.z.string().optional().describe(
39340
+ ref: import_zod13.z.string().optional().describe(
38895
39341
  worktreeProfile ? "Omit for this chat. Another chat id only if it is on this same checkout." : "Chat id on the workspace."
38896
39342
  ),
38897
- enabled: import_zod12.z.boolean().describe("True opts the checkout in. False turns it off.")
39343
+ enabled: import_zod13.z.boolean().describe("True opts the checkout in. False turns it off.")
38898
39344
  },
38899
39345
  async ({ ref, enabled }) => {
38900
39346
  try {
@@ -38927,7 +39373,7 @@ async function startMcpServer() {
38927
39373
  "set_caffeinate",
38928
39374
  "Keep this Mac awake with caffeinate across turns \u2014 independent of Settings toggles. A connected phone already holds caffeinate (lid can close on power), so do not turn this on just because they are on the phone. Turn ON when the user will be away and no phone is connected, or they ask you to keep the machine awake. Turn OFF when they say they are done, wrapping up, going to sleep, or no longer need the Mac awake. Closing or archiving this orchestration chat also releases the hold. macOS only.",
38929
39375
  {
38930
- enabled: import_zod12.z.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
39376
+ enabled: import_zod13.z.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
38931
39377
  },
38932
39378
  async ({ enabled }) => {
38933
39379
  const threadId = process.env.SIDEBOARD_ORCHESTRATOR_THREAD_ID?.trim() || null;
@@ -38953,24 +39399,24 @@ async function startMcpServer() {
38953
39399
  "create_workspace",
38954
39400
  `Create a workspace (isolated git checkout + first chat) from branch, pr, or ticket. A ticket, PR, or named branch has one checkout \u2014 if one already matches, returns it (alreadyStarted=true) instead of a second checkout. That is not one agent: chats lists every agent on that checkout. Add another with fork_chat; send_to_chat only the chat that should do this job. Creating from the default branch still opens a new isolated checkout. Pass repoPath from list_projects. cowboy=true uses the project folder on the default branch (no isolated worktree; land is commit+push). From an orchestration chat, omit parentChatId (Sideboard binds the child to this chat) or pass the exact id from the turn reminder \u2014 never invent a uuid. Omit agent/model \u2014 Sideboard applies ${accountDefaultsHint}. Do not pass your own agent or agent=cursor; those are ignored. Setup (settings.toml, .cursor/worktrees.json, or script/setup) runs in the background in parallel with the first turn (skipped for cowboy). Pass the same tags on every workspace you open for one task (short labels such as "phone-sync") so they still match in the sidebar the next day. Reusing a checkout adds those tags. Each orchestration chat can create at most the Settings \u2192 Advanced \u201CMax orchestration threads\u201D cap of child workspaces (default 5). fork_chat on an existing checkout does not use a slot.`,
38955
39401
  {
38956
- sourceType: import_zod12.z.enum(["branch", "pr", "ticket"]),
38957
- sourceRef: import_zod12.z.string(),
38958
- agent: import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
39402
+ sourceType: import_zod13.z.enum(["branch", "pr", "ticket"]),
39403
+ sourceRef: import_zod13.z.string(),
39404
+ agent: import_zod13.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
38959
39405
  `Usually omit. Sideboard uses Account default agent (${accountDefaults.agent}). Passing your own agent or cursor is ignored.`
38960
39406
  ),
38961
- model: import_zod12.z.string().nullable().optional().describe(
39407
+ model: import_zod13.z.string().nullable().optional().describe(
38962
39408
  `Usually omit to use Account default model (${accountDefaults.model?.trim() || "Auto"}). Pass null only to force Auto / agent-default.`
38963
39409
  ),
38964
- repoPath: import_zod12.z.string(),
38965
- title: import_zod12.z.string().optional(),
38966
- cowboy: import_zod12.z.boolean().optional().describe(
39410
+ repoPath: import_zod13.z.string(),
39411
+ title: import_zod13.z.string().optional(),
39412
+ cowboy: import_zod13.z.boolean().optional().describe(
38967
39413
  "If true, work in the project folder on the default branch (no thread/* worktree). Requires Settings \u2192 Advanced \u2192 Cowboy mode. Land is commit+push to that branch. Archive does not delete the folder."
38968
39414
  ),
38969
- parentChatId: import_zod12.z.string().optional().describe(
39415
+ parentChatId: import_zod13.z.string().optional().describe(
38970
39416
  "Orchestration: omit (preferred) or pass YOUR chat id from the turn reminder / AGENTS.md. Do not invent uuids."
38971
39417
  ),
38972
- parentThreadId: import_zod12.z.string().optional().describe("Legacy alias for parentChatId."),
38973
- tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).optional().describe(
39418
+ parentThreadId: import_zod13.z.string().optional().describe("Legacy alias for parentChatId."),
39419
+ tags: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.array(import_zod13.z.string())]).optional().describe(
38974
39420
  "Short labels for this workspace (or a comma-separated string). Use the same tags on every checkout for one task. Added when the checkout already exists."
38975
39421
  )
38976
39422
  },
@@ -38986,11 +39432,11 @@ async function startMcpServer() {
38986
39432
  "start_board_card",
38987
39433
  "Same as create_workspace for a ticket, PR, or named branch (attaches issue text when Sideboard can resolve it). Does not create a second checkout when one already matches \u2014 returns that workspace (alreadyStarted) and its chats. A workspace can have many agents. fork_chat to add one; send_to_chat only the chat that should do this job.",
38988
39434
  {
38989
- kind: import_zod12.z.enum(["ticket", "pr", "branch"]),
38990
- ref: import_zod12.z.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
38991
- repoPath: import_zod12.z.string().describe("Project path from list_projects / list_board"),
38992
- title: import_zod12.z.string().optional(),
38993
- tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).optional().describe(
39435
+ kind: import_zod13.z.enum(["ticket", "pr", "branch"]),
39436
+ ref: import_zod13.z.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
39437
+ repoPath: import_zod13.z.string().describe("Project path from list_projects / list_board"),
39438
+ title: import_zod13.z.string().optional(),
39439
+ tags: import_zod13.z.union([import_zod13.z.string(), import_zod13.z.array(import_zod13.z.string())]).optional().describe(
38994
39440
  "Short labels for this workspace. Same tags on every checkout for one task. Added when the checkout already exists."
38995
39441
  )
38996
39442
  },
@@ -39046,7 +39492,7 @@ async function startMcpServer() {
39046
39492
  const ident = issue?.identifier ?? ref.trim();
39047
39493
  const attachments = issue ? [
39048
39494
  {
39049
- id: (0, import_node_crypto25.randomUUID)(),
39495
+ id: (0, import_node_crypto26.randomUUID)(),
39050
39496
  name: issue.identifier,
39051
39497
  kind: "issue",
39052
39498
  content: [
@@ -39093,11 +39539,11 @@ async function startMcpServer() {
39093
39539
  );
39094
39540
  server.tool(
39095
39541
  "send_to_chat",
39096
- 'Steer a prompt on a workspace chat (Settings \u2192 Follow-up, default steer: interrupt the in-flight turn and start now, same as the workspace composer). Use after create_workspace to start or continue a conversation. For commit/push/PR, prefer ask_git (canonical desktop-button phrases). Send "Merge PR." / ask_git merge only when the user explicitly asked to merge. force_stop=true kills the in-flight turn and clears the queue before this prompt \u2014 only when the current request is wrong and must be replaced. Do not send_to_chat to check in, resume after a halt notice, or because wait_for_turn returned stillRunning; that interrupts the child mid-thought. Call wait_for_turn again instead.',
39542
+ 'Send a prompt to a workspace chat. A second send joins that prompt only while it is still queued or not yet handed to the process. Once the process has started, the send waits behind the turn and does not stop it or change the prompt already running. force_stop=true kills the in-flight turn and clears the queue before this prompt \u2014 only when the current request is wrong and must be replaced. The workspace composer still follows Settings \u2192 Follow-up. Use after create_workspace to start or continue a conversation. For commit/push/PR, prefer ask_git (canonical desktop-button phrases). Send "Merge PR." / ask_git merge only when the user explicitly asked to merge. Do not send_to_chat to check in, resume after a halt notice, or because wait_for_turn returned stillRunning. Call wait_for_turn again instead.',
39097
39543
  {
39098
- ref: import_zod12.z.string(),
39099
- prompt: import_zod12.z.string(),
39100
- force_stop: import_zod12.z.boolean().optional()
39544
+ ref: import_zod13.z.string(),
39545
+ prompt: import_zod13.z.string(),
39546
+ force_stop: import_zod13.z.boolean().optional()
39101
39547
  },
39102
39548
  async ({ ref, prompt, force_stop }) => {
39103
39549
  if (force_stop) {
@@ -39107,7 +39553,7 @@ async function startMcpServer() {
39107
39553
  }
39108
39554
  }
39109
39555
  const thread = await orch.send(ref, prompt, {
39110
- followUp: resolveOrchChildFollowUp()
39556
+ followUp: force_stop ? "steer" : "join"
39111
39557
  });
39112
39558
  return mcpJson({
39113
39559
  id: thread.id,
@@ -39120,10 +39566,10 @@ async function startMcpServer() {
39120
39566
  if (shouldRegisterMcpWaitForTurn()) {
39121
39567
  server.tool(
39122
39568
  "wait_for_turn",
39123
- "Wait until the chat finishes its current/queued turn, or return early with a live progress snapshot. MCP clients often kill tools around 60s, so this returns within 45s even while the child is still working. taskState is the A2A-style lifecycle: submitted (queued, not started), working, input-required (ask_user), completed, failed, canceled. stillRunning is true only for submitted/working. blockedReason is why the child is waiting on a person (the question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress and call wait_for_turn again. Do not send_to_chat a check-in (that steers / interrupts). On failed, lastError/text is the failure. On canceled, the child did not finish \u2014 resume with send_to_chat or tell the user. On input-required, wait for the user in that chat. When finished, text is this turn\u2019s assistant reply and usage is that turn\u2019s tokens + costUsd (this turn, not the Claude session total; sessionCostUsd is the provider session total when present).",
39569
+ "Wait until the chat finishes its current/queued turn, or return early with a live progress snapshot. MCP clients often kill tools around 60s, so this returns within 45s even while the child is still working. taskState is the A2A-style lifecycle: submitted (queued, not started), working, input-required (ask_user), completed, failed, canceled. stillRunning is true only for submitted/working. blockedReason is why the child is waiting on a person (the question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress and call wait_for_turn again. Do not send_to_chat a check-in. On failed, read failureClass: auth, quota, and refused are not a retry; timeout or runner can be one. lastError/text is the failure. On canceled, the child did not finish \u2014 resume with send_to_chat or tell the user. On input-required, wait for the user in that chat. When finished, text is this turn\u2019s assistant reply and usage is that turn\u2019s tokens + costUsd (this turn, not the Claude session total; sessionCostUsd is the provider session total when present).",
39124
39570
  {
39125
- ref: import_zod12.z.string(),
39126
- timeoutMs: import_zod12.z.number().optional()
39571
+ ref: import_zod13.z.string(),
39572
+ timeoutMs: import_zod13.z.number().optional()
39127
39573
  },
39128
39574
  async ({ ref, timeoutMs }) => {
39129
39575
  const thread = await orch.waitForTurn(ref, mcpWaitForTurnTimeoutMs(timeoutMs), {
@@ -39150,14 +39596,16 @@ async function startMcpServer() {
39150
39596
  }
39151
39597
  server.tool(
39152
39598
  "get_turn_result",
39153
- "Assistant message and last-turn usage when the turn finished. While stillRunning (submitted/working), text and usage are empty so a previous reply cannot be mistaken for this turn \u2014 use progress for tools/thinking. Not the full transcript. Includes taskState (A2A lifecycle) and blockedReason (why the agent is waiting on a person).",
39154
- { ref: import_zod12.z.string() },
39599
+ "Assistant message and last-turn usage when the turn finished. While stillRunning (submitted/working), text and usage are empty so a previous reply cannot be mistaken for this turn \u2014 use progress for tools/thinking. Not the full transcript. Includes taskState (A2A lifecycle), failureClass when the turn failed (auth, quota, refused, timeout, runner, other), and blockedReason (why the agent is waiting on a person).",
39600
+ { ref: import_zod13.z.string() },
39155
39601
  async ({ ref }) => {
39156
39602
  const result = orch.getTurnResult(ref);
39157
- const hint = mcpWaitTaskHint(result.taskState, result.status, result.blockedReason);
39603
+ const failureClass = result.taskState === "failed" && result.status !== "broken" ? classifyTurnFailure(result.lastError || result.text) : null;
39604
+ const hint = mcpWaitTaskHint(result.taskState, result.status, result.blockedReason, failureClass);
39158
39605
  const waiting = Boolean(result.blockedReason) && !result.stillRunning && result.taskState !== "failed" && result.taskState !== "canceled";
39159
39606
  return mcpJson({
39160
39607
  ...result,
39608
+ failureClass,
39161
39609
  hint,
39162
39610
  incomplete: needsCoordinatorAction(result.taskState) || waiting
39163
39611
  });
@@ -39167,9 +39615,9 @@ async function startMcpServer() {
39167
39615
  "stop_chat",
39168
39616
  "Force-stop a thread: kill any in-flight agent turn AND clear queued prompts so drainQueue cannot continue. Does not archive the worktree. Optional force defaults to true. Pass reason \u2014 a short note on why this chat is stopping. It is stored on the thread and kept when the turn unwinds. If you omit it, Sideboard still records that the queue was cleared.",
39169
39617
  {
39170
- ref: import_zod12.z.string(),
39171
- force: import_zod12.z.boolean().optional(),
39172
- reason: import_zod12.z.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
39618
+ ref: import_zod13.z.string(),
39619
+ force: import_zod13.z.boolean().optional(),
39620
+ reason: import_zod13.z.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
39173
39621
  },
39174
39622
  async ({ ref, force, reason }) => {
39175
39623
  const t = orch.getThread(ref);
@@ -39195,8 +39643,8 @@ async function startMcpServer() {
39195
39643
  "get_diff",
39196
39644
  "Compact diff summary (capped hunks, paginated)",
39197
39645
  {
39198
- ref: import_zod12.z.string(),
39199
- maxFiles: import_zod12.z.number().optional()
39646
+ ref: import_zod13.z.string(),
39647
+ maxFiles: import_zod13.z.number().optional()
39200
39648
  },
39201
39649
  async ({ ref, maxFiles }) => {
39202
39650
  const summary = await orch.diffSummary(ref);
@@ -39209,7 +39657,7 @@ async function startMcpServer() {
39209
39657
  server.tool(
39210
39658
  "get_pr_checks",
39211
39659
  "Snapshot of GitHub PR checks for a worktree thread (`gh pr checks` plus merge/review gates). null = no PR. If the user gave a goal (Greptile 5/5, CI green), the worktree agent watches with `gh pr checks --watch` via /long-running \u2014 this tool is a snapshot, not a waiter. Coordinators: do not run gh from the orchestration cwd.",
39212
- { ref: import_zod12.z.string().describe("Worktree thread id/ref") },
39660
+ { ref: import_zod13.z.string().describe("Worktree thread id/ref") },
39213
39661
  async ({ ref }) => {
39214
39662
  try {
39215
39663
  const checks = await orch.getPrChecks(ref);
@@ -39223,7 +39671,7 @@ async function startMcpServer() {
39223
39671
  server.tool(
39224
39672
  "request_review",
39225
39673
  'Start a merge-readiness Review on a worktree agent thread (same as the desktop Review button). If that worktree has a single unused idle agent (no messages), runs the review there; otherwise opens a new Review chat tab. Attaches .claude/skills/review/SKILL.md when present (else copies .sideboard/review.md into .context/review.md, or seeds that file from the stock template), and sends "Review changes in this workspace." Expect Approve / Approve with nits / Request changes / Needs more information in that chat. The review stays there so the user can read it and type next steps \u2014 do not comment on or update the PR or ticket, and do not ask_user after the review, until they ask. Pass a worktree thread ref \u2014 not the orchestrator. Then wait_for_turn (loop while stillRunning) / get_turn_result on the returned review thread id.',
39226
- { ref: import_zod12.z.string().describe("Worktree thread id/ref to review") },
39674
+ { ref: import_zod13.z.string().describe("Worktree thread id/ref to review") },
39227
39675
  async ({ ref }) => {
39228
39676
  try {
39229
39677
  const tab = await orch.requestReview(ref);
@@ -39245,8 +39693,8 @@ async function startMcpServer() {
39245
39693
  "ask_git",
39246
39694
  "Commit & push, open a draft PR, mark ready for review, resolve conflicts, or merge \u2014 same prompts as the desktop git buttons (including Resolve). Always steers the worktree agent; does not push or open the PR locally. Then wait_for_turn (loop while stillRunning). Do not start a checks loop on a plain push \u2014 only if the user gave a goal (CI green, a review score, until checks pass). A push can wake a third-party PR review; the worktree agent acknowledges it only inside that goal. Pass a worktree thread ref (not the orchestrator). action=ready-for-review and action=merge only when the user explicitly asked (or clicked the desktop button). Do not run git or gh from the orchestration cwd.",
39247
39695
  {
39248
- ref: import_zod12.z.string().describe("Worktree thread id/ref"),
39249
- action: import_zod12.z.enum(AGENT_GIT_ACTIONS).describe(
39696
+ ref: import_zod13.z.string().describe("Worktree thread id/ref"),
39697
+ action: import_zod13.z.enum(AGENT_GIT_ACTIONS).describe(
39250
39698
  "commit-push | create-draft | create-web | resolve-conflicts | ready-for-review | merge"
39251
39699
  )
39252
39700
  },
@@ -39275,7 +39723,7 @@ async function startMcpServer() {
39275
39723
  }
39276
39724
  }
39277
39725
  );
39278
- const agentEnum = import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
39726
+ const agentEnum = import_zod13.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
39279
39727
  server.tool(
39280
39728
  "list_models",
39281
39729
  "List models for an agent. Prefer Auto: do not call this unless you have a reason to pin a specific model (user request, cost/latency, capability). Omit agent to list all.",
@@ -39296,11 +39744,11 @@ async function startMcpServer() {
39296
39744
  "fork_workspace",
39297
39745
  "Fork a worktree agent chat into a NEW git worktree + chat (desktop \u201CFork to new workspace\u201D). Seeds a transcript (through through_index, default all). Optional agent override. Leave model unset for Auto (default) \u2014 only pass model when you have a reason. Not for the orchestrator. Then send_to_chat / wait_for_turn (loop while stillRunning) on the returned id.",
39298
39746
  {
39299
- ref: import_zod12.z.string().describe("Worktree thread id/ref to fork"),
39300
- through_index: import_zod12.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
39747
+ ref: import_zod13.z.string().describe("Worktree thread id/ref to fork"),
39748
+ through_index: import_zod13.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
39301
39749
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
39302
- model: import_zod12.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
39303
- title: import_zod12.z.string().optional()
39750
+ model: import_zod13.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
39751
+ title: import_zod13.z.string().optional()
39304
39752
  },
39305
39753
  async ({ ref, through_index, agent, model, title }) => {
39306
39754
  try {
@@ -39334,11 +39782,11 @@ async function startMcpServer() {
39334
39782
  "fork_chat",
39335
39783
  "Add another agent chat on the SAME workspace (same files, Run, and git). Also forks a Global orchestration chat into a new orchestration tab. Pass agent when the new chat should use a different harness. Leave model unset for Auto unless you have a reason. Orchestration forks require an MCP-capable agent (claude, cursor, codex, opencode \u2014 not brightsy). Use this for a second agent on a checkout (review, another harness, parallel work on the same branch). Do not create_workspace again for that \u2014 it returns the existing checkout. Then send_to_chat / wait_for_turn (loop while stillRunning) on the returned id. Use fork_workspace only when the work needs its own git checkout.",
39336
39784
  {
39337
- ref: import_zod12.z.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
39338
- through_index: import_zod12.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
39785
+ ref: import_zod13.z.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
39786
+ through_index: import_zod13.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
39339
39787
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
39340
- model: import_zod12.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
39341
- title: import_zod12.z.string().optional()
39788
+ model: import_zod13.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
39789
+ title: import_zod13.z.string().optional()
39342
39790
  },
39343
39791
  async ({ ref, through_index, agent, model, title }) => {
39344
39792
  try {
@@ -39376,7 +39824,7 @@ async function startMcpServer() {
39376
39824
  server.tool(
39377
39825
  "run_setup",
39378
39826
  "Re-run workspace setup (Sideboard/Conductor settings, .cursor/worktrees.json, or script/setup). New worktrees already run this automatically.",
39379
- { ref: import_zod12.z.string() },
39827
+ { ref: import_zod13.z.string() },
39380
39828
  async ({ ref }) => {
39381
39829
  const result = await orch.runSetup(ref);
39382
39830
  return mcpJson(result);
@@ -39385,7 +39833,7 @@ async function startMcpServer() {
39385
39833
  server.tool(
39386
39834
  "add_project",
39387
39835
  "Register a git repo as a Sideboard workspace",
39388
- { repoPath: import_zod12.z.string() },
39836
+ { repoPath: import_zod13.z.string() },
39389
39837
  async ({ repoPath }) => {
39390
39838
  const ws = await orch.addWorkspace(repoPath);
39391
39839
  return mcpJson(ws);
@@ -39394,7 +39842,7 @@ async function startMcpServer() {
39394
39842
  server.tool(
39395
39843
  "remove_project",
39396
39844
  "Unregister a Sideboard workspace and archive its chats",
39397
- { repoPath: import_zod12.z.string() },
39845
+ { repoPath: import_zod13.z.string() },
39398
39846
  async ({ repoPath }) => {
39399
39847
  await orch.removeWorkspace(repoPath);
39400
39848
  return { content: [{ type: "text", text: "ok" }] };
@@ -39404,12 +39852,12 @@ async function startMcpServer() {
39404
39852
  "fanout",
39405
39853
  "Best-of-n: create one thread per agent with the same prompt (parallel attempts)",
39406
39854
  {
39407
- prompt: import_zod12.z.string(),
39408
- agents: import_zod12.z.array(import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
39409
- repoPath: import_zod12.z.string(),
39410
- sourceType: import_zod12.z.enum(["branch", "pr", "ticket"]).optional(),
39411
- sourceRef: import_zod12.z.string().optional(),
39412
- title: import_zod12.z.string().optional()
39855
+ prompt: import_zod13.z.string(),
39856
+ agents: import_zod13.z.array(import_zod13.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
39857
+ repoPath: import_zod13.z.string(),
39858
+ sourceType: import_zod13.z.enum(["branch", "pr", "ticket"]).optional(),
39859
+ sourceRef: import_zod13.z.string().optional(),
39860
+ title: import_zod13.z.string().optional()
39413
39861
  },
39414
39862
  async (args) => {
39415
39863
  const threads = await orch.bestOfN(args);
@@ -39427,8 +39875,8 @@ async function startMcpServer() {
39427
39875
  "list_branches",
39428
39876
  "List git branches in a registered workspace. Pass repoPath from list_projects (unmerged into the default branch by default \u2014 for create_workspace sourceType=branch).",
39429
39877
  {
39430
- repoPath: import_zod12.z.string(),
39431
- unmergedOnly: import_zod12.z.boolean().optional()
39878
+ repoPath: import_zod13.z.string(),
39879
+ unmergedOnly: import_zod13.z.boolean().optional()
39432
39880
  },
39433
39881
  async ({ repoPath, unmergedOnly }) => {
39434
39882
  const root = await resolveRepoRoot(repoPath);
@@ -39449,19 +39897,19 @@ async function startMcpServer() {
39449
39897
  "list_prs",
39450
39898
  `List GitHub PRs for a registered workspace (the review surface for assigned ticket work \u2014 not the tickets). Pass repoPath from list_projects. "Get me N tickets to review" \u2192 queue=review and limit=N: open non-draft PRs labeled with this project's ready-for-review GitHub label (Settings \u2192 Projects; default eng-review) with no individual user reviewer. Prefer teams that match Settings \u2192 Agents / Projects roles for this repo. A team like engineering-team is not a claim (you are on that team). Also: state (open|closed|merged|all|review), label, reviewer (me|unassigned|login), query, limit (default 40, max 250). Then create_workspace with sourceType=pr.`,
39451
39899
  {
39452
- repoPath: import_zod12.z.string(),
39453
- query: import_zod12.z.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
39454
- queue: import_zod12.z.enum(["review", "mine", "approved", "changes"]).optional().describe(
39900
+ repoPath: import_zod13.z.string(),
39901
+ query: import_zod13.z.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
39902
+ queue: import_zod13.z.enum(["review", "mine", "approved", "changes"]).optional().describe(
39455
39903
  "review = unclaimed ready-for-review inbox (Settings \u2192 Projects label, default eng-review). mine = review-requested:@me. approved / changes = eng-approved / eng-requested-changes."
39456
39904
  ),
39457
- state: import_zod12.z.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
39458
- label: import_zod12.z.string().optional().describe(
39905
+ state: import_zod13.z.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
39906
+ label: import_zod13.z.string().optional().describe(
39459
39907
  "GitHub label / workflow tag. Comma-separated AND. Examples: eng-review, eng-approved, eng-requested-changes"
39460
39908
  ),
39461
- reviewer: import_zod12.z.string().optional().describe(
39909
+ reviewer: import_zod13.z.string().optional().describe(
39462
39910
  "me (review requested of you), unassigned (no individual reviewer; team queues like engineering-team still count), all, or a GitHub login"
39463
39911
  ),
39464
- limit: import_zod12.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
39912
+ limit: import_zod13.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
39465
39913
  },
39466
39914
  async ({ repoPath, query, queue, state, label, reviewer, limit }) => {
39467
39915
  const root = await resolveRepoRoot(repoPath);
@@ -39494,7 +39942,7 @@ async function startMcpServer() {
39494
39942
  server.tool(
39495
39943
  "get_pr_stack",
39496
39944
  "Load the GitHub PR stack for a thread worktree (`gh stack view --json`). Returns null JSON when the branch is not stacked. Prefer this before ask_git merge on stacked PRs (and only merge when the user explicitly asked).",
39497
- { ref: import_zod12.z.string() },
39945
+ { ref: import_zod13.z.string() },
39498
39946
  async ({ ref }) => {
39499
39947
  const stack = await orch.getPrStack(ref);
39500
39948
  return mcpJson(stack);
@@ -39504,8 +39952,8 @@ async function startMcpServer() {
39504
39952
  "open_pr_stack_layers",
39505
39953
  "Materialize one worktree+thread per stack layer (or a single 1-based layer). Pass a thread ref already on the stack.",
39506
39954
  {
39507
- ref: import_zod12.z.string(),
39508
- layer: import_zod12.z.number().int().positive().optional()
39955
+ ref: import_zod13.z.string(),
39956
+ layer: import_zod13.z.number().int().positive().optional()
39509
39957
  },
39510
39958
  async ({ ref, layer }) => {
39511
39959
  const result = await orch.openPrStackLayers(ref, { layer });
@@ -39528,9 +39976,9 @@ async function startMcpServer() {
39528
39976
  "add_stack_layer",
39529
39977
  "Add a branch on top of the current stack (`gh stack add`) and open a worktree+thread for it.",
39530
39978
  {
39531
- ref: import_zod12.z.string(),
39532
- branchName: import_zod12.z.string(),
39533
- title: import_zod12.z.string().optional()
39979
+ ref: import_zod13.z.string(),
39980
+ branchName: import_zod13.z.string(),
39981
+ title: import_zod13.z.string().optional()
39534
39982
  },
39535
39983
  async ({ ref, branchName, title }) => {
39536
39984
  const result = await orch.addStackLayer(ref, branchName, { title });
@@ -39548,11 +39996,11 @@ async function startMcpServer() {
39548
39996
  "create_pr_stack",
39549
39997
  "Create a new GitHub PR stack with one Sideboard worktree per layer (bottom\u2192top branch names). Requires `gh extension install github/gh-stack`.",
39550
39998
  {
39551
- repoPath: import_zod12.z.string(),
39552
- branches: import_zod12.z.array(import_zod12.z.string()).min(1),
39553
- agent: import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
39554
- base: import_zod12.z.string().optional(),
39555
- title: import_zod12.z.string().optional()
39999
+ repoPath: import_zod13.z.string(),
40000
+ branches: import_zod13.z.array(import_zod13.z.string()).min(1),
40001
+ agent: import_zod13.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
40002
+ base: import_zod13.z.string().optional(),
40003
+ title: import_zod13.z.string().optional()
39556
40004
  },
39557
40005
  async (args) => {
39558
40006
  const result = await orch.createPrStack({
@@ -39580,10 +40028,10 @@ async function startMcpServer() {
39580
40028
  "list_issues",
39581
40029
  "List or search issues (Linear, AbleTime, or GitHub; falls back to GitHub). Cursor Origin has no issue tracker \u2014 a Cursor repo returns unavailableReason unless Linear or AbleTime is the source. Entire tickets are Trails (`entire trail`), not GitHub Issues, so an Entire repo does the same unless Linear or AbleTime is the source. Use Settings \u2192 Agents / Projects notes and roles to pick tickets relevant to the viewer (query + assignee=me or unassigned as the notes say). Default 40; pass query and/or limit (max 250) when truncated. assignee: me (Linear default), unassigned, all, or a user id. Pass updatedSince for new/updated tickets and new comments (\u201Cany updates since yesterday?\u201D). Then create_workspace with sourceType=ticket.",
39582
40030
  {
39583
- repoPath: import_zod12.z.string(),
39584
- query: import_zod12.z.string().optional().describe("Search title, identifier, or description"),
39585
- assignee: import_zod12.z.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
39586
- limit: import_zod12.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
40031
+ repoPath: import_zod13.z.string(),
40032
+ query: import_zod13.z.string().optional().describe("Search title, identifier, or description"),
40033
+ assignee: import_zod13.z.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
40034
+ limit: import_zod13.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
39587
40035
  updatedSince: mcpIssueUpdatedSinceSchema
39588
40036
  },
39589
40037
  async ({ repoPath, query, assignee, limit, updatedSince }) => {