@sideboard-ai/core 0.1.337 → 0.1.339

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 (29) hide show
  1. package/dist/{agents-VTLFLMMT.js → agents-6MSZHZOM.js} +3 -3
  2. package/dist/{agents-ISEAOZD5.js → agents-QFXIBIKJ.js} +3 -3
  3. package/dist/{chunk-5MXLDDYF.js → chunk-5KH3EQ2C.js} +7 -0
  4. package/dist/{chunk-NB4U75TJ.js → chunk-6ABL7HZN.js} +14 -4
  5. package/dist/{chunk-CDRGQ6GX.js → chunk-BD7QARIJ.js} +5 -3
  6. package/dist/{chunk-OOXRMTU6.js → chunk-DYUAVL5S.js} +7 -0
  7. package/dist/{chunk-EKI7D2AJ.js → chunk-ELDHERAD.js} +81 -17
  8. package/dist/{chunk-MGEUXR6E.js → chunk-EVYOONTE.js} +5 -3
  9. package/dist/{chunk-PSXBOMXI.js → chunk-EZZY3EAZ.js} +80 -16
  10. package/dist/{chunk-4O7436ZH.js → chunk-NHLTTT5G.js} +55 -14
  11. package/dist/{chunk-B6TPN624.js → chunk-PEJ3N5VE.js} +55 -14
  12. package/dist/{chunk-54GBJC6J.js → chunk-VHHEQP5V.js} +14 -4
  13. package/dist/{conductor-JH26KU3W.js → conductor-AUUXCJZT.js} +3 -3
  14. package/dist/{conductor-77L3QTZ2.js → conductor-LEPTWN2U.js} +3 -3
  15. package/dist/{coordinator-prompt-WVVC2TLP.js → coordinator-prompt-CIWWP2P6.js} +1 -1
  16. package/dist/{coordinator-prompt-UKJJAMBG.js → coordinator-prompt-VO42IZWS.js} +1 -1
  17. package/dist/{global-workspace-B5IHENCP.js → global-workspace-FKXLFKYX.js} +1 -1
  18. package/dist/{global-workspace-QDIPRW6G.js → global-workspace-MCAREQI7.js} +1 -1
  19. package/dist/index.cjs +2530 -1016
  20. package/dist/index.d.cts +273 -8
  21. package/dist/index.d.ts +273 -8
  22. package/dist/index.js +1541 -216
  23. package/dist/mcp/run-stdio.cjs +1469 -182
  24. package/dist/mcp/run-stdio.js +1294 -152
  25. package/dist/{orchestrator-BOLYQZO7.js → orchestrator-JTFCNXVR.js} +5 -5
  26. package/dist/{orchestrator-ZUIU667R.js → orchestrator-NOQDMYLB.js} +5 -5
  27. package/dist/{workspaces-VXE2MBKD.js → workspaces-D6FQCZRK.js} +1 -1
  28. package/dist/{workspaces-WZZNNUJL.js → workspaces-Y25L2EPV.js} +1 -1
  29. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -219,7 +219,7 @@ import {
219
219
  worktreeCleanupSettings,
220
220
  writeAgentBlock,
221
221
  writeWorktreeFile
222
- } from "./chunk-EKI7D2AJ.js";
222
+ } from "./chunk-ELDHERAD.js";
223
223
  import {
224
224
  OPTIONAL_SERVICES,
225
225
  OPTIONAL_SERVICE_IDS,
@@ -380,7 +380,7 @@ import {
380
380
  userMcpNamesToDisable,
381
381
  worktreeMcpToolNames,
382
382
  writeInjectedMcpConfig
383
- } from "./chunk-NB4U75TJ.js";
383
+ } from "./chunk-6ABL7HZN.js";
384
384
  import {
385
385
  getAgentSetupInfo,
386
386
  installAgent,
@@ -483,6 +483,7 @@ import {
483
483
  messagesForCompactArchive,
484
484
  messagesSinceLastBrightsyContextSummary,
485
485
  needsCoordinatorAction,
486
+ orchestratorPromisedLaterReport,
486
487
  readExistingReviewRequestFile,
487
488
  readWorktreeInclude,
488
489
  requestReview,
@@ -513,7 +514,7 @@ import {
513
514
  workspaceAgentChatSummaries,
514
515
  worktreeRunPortsPath,
515
516
  wrapReviewSkillMarkdown
516
- } from "./chunk-B6TPN624.js";
517
+ } from "./chunk-PEJ3N5VE.js";
517
518
  import {
518
519
  STDERR_EVENT_MAX_CHARS,
519
520
  STDOUT_EVENT_MAX_CHARS,
@@ -555,7 +556,7 @@ import {
555
556
  visibleToolRowDetail,
556
557
  withEventParentId,
557
558
  withEventsParentId
558
- } from "./chunk-OOXRMTU6.js";
559
+ } from "./chunk-DYUAVL5S.js";
559
560
  import "./chunk-7H655NEW.js";
560
561
  import {
561
562
  ABLETIME_OAUTH_CALLBACK_PATH,
@@ -656,7 +657,7 @@ import {
656
657
  stageBuffersAsAttachments,
657
658
  syncWorkspacesFromThreads,
658
659
  takenTeamSlugsForOrchestration
659
- } from "./chunk-CDRGQ6GX.js";
660
+ } from "./chunk-BD7QARIJ.js";
660
661
  import {
661
662
  GITHUB_PR_BODY_MAX_CHARS,
662
663
  GITHUB_PR_BODY_SAFE_CHARS,
@@ -1602,6 +1603,943 @@ function agentStub(source, text5, usage) {
1602
1603
  };
1603
1604
  }
1604
1605
 
1606
+ // src/order/order.ts
1607
+ import { randomUUID as randomUUID2 } from "crypto";
1608
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1609
+ import { join as join2 } from "path";
1610
+
1611
+ // src/order/order-model.ts
1612
+ function parseOrderGate(value) {
1613
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
1614
+ if (s === "inmain" || s === "main" || s === "merged") return "in-main";
1615
+ if (s === "inprod" || s === "prod" || s === "production") return "in-prod";
1616
+ throw new Error("gate must be in-main or in-prod");
1617
+ }
1618
+ function parseOrderHold(value) {
1619
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
1620
+ if (s === "start" || s === "beforestart") return "start";
1621
+ if (s === "merge" || s === "beforemerge") return "merge";
1622
+ throw new Error("hold must be start or merge");
1623
+ }
1624
+ function parseOrderKind(value) {
1625
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
1626
+ if (s === "pr" || s === "pull" || s === "pullrequest") return "pr";
1627
+ if (s === "issue" || s === "ticket" || s === "task") return "issue";
1628
+ if (s === "workspace" || s === "worktree" || s === "checkout") return "workspace";
1629
+ if (s === "orchestration" || s === "orchestrator" || s === "agent") return "orchestration";
1630
+ throw new Error("kind must be pr, issue, workspace, or orchestration");
1631
+ }
1632
+ function normalizeOrderTarget(input) {
1633
+ const kind = parseOrderKind(input.kind);
1634
+ const raw = input.ref.trim();
1635
+ if (!raw) throw new Error(`${kind} ref is required`);
1636
+ let ref = raw;
1637
+ if (kind === "pr") {
1638
+ const match = raw.match(/(\d+)/);
1639
+ if (!match) throw new Error("PR ref must be a number");
1640
+ ref = match[1];
1641
+ } else if (kind === "issue") {
1642
+ ref = raw.replace(/^#/, "");
1643
+ }
1644
+ const repoPath = input.repoPath?.trim().replace(/\/+$/, "") || void 0;
1645
+ const label = input.label?.trim() || void 0;
1646
+ const target = { kind, ref };
1647
+ if (repoPath) target.repoPath = repoPath;
1648
+ if (label) target.label = label;
1649
+ return target;
1650
+ }
1651
+ function targetKey(target) {
1652
+ const ref = target.ref.trim().replace(/^#/, "").toLowerCase();
1653
+ const repo = (target.repoPath ?? "").replace(/\/+$/, "").toLowerCase();
1654
+ if (target.kind === "issue" && !repo) return `issue:${ref}`;
1655
+ if (target.kind === "orchestration") return `orchestration:${ref}`;
1656
+ return `${target.kind}:${repo}:${ref}`;
1657
+ }
1658
+ function samePath(a, b) {
1659
+ return a.trim().replace(/\/+$/, "") === b.trim().replace(/\/+$/, "");
1660
+ }
1661
+ function repoMatches(target, thread) {
1662
+ if (!target.repoPath || !thread.repoPath) return true;
1663
+ return samePath(target.repoPath, thread.repoPath);
1664
+ }
1665
+ function orderPrNumber(thread) {
1666
+ if (thread.sourceType === "pr") {
1667
+ const n = Number(String(thread.sourceRef).replace(/^#/, ""));
1668
+ if (Number.isInteger(n) && n >= 1) return n;
1669
+ }
1670
+ const match = (thread.prUrl ?? "").match(/\/pull\/(\d+)(?:\/|$|[?#])/i);
1671
+ return match ? Number(match[1]) : null;
1672
+ }
1673
+ function orderTargetMatches(target, thread) {
1674
+ if (!repoMatches(target, thread)) return false;
1675
+ if (target.kind === "pr") {
1676
+ const n = Number(target.ref);
1677
+ return Number.isInteger(n) && orderPrNumber(thread) === n;
1678
+ }
1679
+ if (target.kind === "issue") {
1680
+ if (thread.sourceType !== "ticket") return false;
1681
+ return thread.sourceRef.trim().replace(/^#/, "").toLowerCase() === target.ref.trim().toLowerCase();
1682
+ }
1683
+ if (target.kind === "orchestration") {
1684
+ const orchestrator = thread.sourceType === "orchestration" || thread.repoPath === "__global__";
1685
+ if (!orchestrator) return false;
1686
+ const ref2 = target.ref.trim();
1687
+ if (thread.id === ref2) return true;
1688
+ return ref2.length >= 8 && !ref2.includes("/") && thread.id.startsWith(ref2);
1689
+ }
1690
+ const ref = target.ref.trim();
1691
+ if (thread.id === ref) return true;
1692
+ if (thread.worktreePath && samePath(thread.worktreePath, ref)) return true;
1693
+ return ref.length >= 8 && !ref.includes("/") && thread.id.startsWith(ref);
1694
+ }
1695
+ function orderSnapshotFromThread(thread) {
1696
+ return {
1697
+ id: thread.id,
1698
+ title: thread.title,
1699
+ sourceType: thread.sourceType,
1700
+ sourceRef: thread.sourceRef,
1701
+ repoPath: thread.repoPath,
1702
+ worktreePath: thread.worktreePath,
1703
+ prUrl: thread.prUrl ?? null,
1704
+ prState: thread.prState ?? null,
1705
+ prTitle: thread.prTitle ?? null,
1706
+ status: thread.status,
1707
+ parentThreadId: "parentThreadId" in thread ? thread.parentThreadId ?? null : null
1708
+ };
1709
+ }
1710
+ function defaultOrderSubject(thread, hold) {
1711
+ const pr = orderPrNumber(thread);
1712
+ if (hold === "merge" && pr) {
1713
+ const target2 = {
1714
+ kind: "pr",
1715
+ ref: String(pr),
1716
+ label: thread.prTitle || thread.title
1717
+ };
1718
+ if (thread.repoPath) target2.repoPath = thread.repoPath;
1719
+ return target2;
1720
+ }
1721
+ if (hold === "start" && thread.sourceType === "ticket" && thread.sourceRef.trim()) {
1722
+ const target2 = {
1723
+ kind: "issue",
1724
+ ref: thread.sourceRef.trim().replace(/^#/, ""),
1725
+ label: thread.title
1726
+ };
1727
+ if (thread.repoPath) target2.repoPath = thread.repoPath;
1728
+ return target2;
1729
+ }
1730
+ const target = {
1731
+ kind: "workspace",
1732
+ ref: thread.worktreePath || thread.id,
1733
+ label: thread.title
1734
+ };
1735
+ if (thread.repoPath) target.repoPath = thread.repoPath;
1736
+ return target;
1737
+ }
1738
+ function assertCallerOwnsSubject(caller, subject) {
1739
+ if (!orderTargetMatches(subject, caller)) {
1740
+ throw new Error(
1741
+ "This checkout can only set a dependency on its own workspace, PR, or ticket."
1742
+ );
1743
+ }
1744
+ }
1745
+ function shortName(target) {
1746
+ if (target.label?.trim()) return target.label.trim();
1747
+ if (target.kind === "pr") return `PR #${target.ref}`;
1748
+ if (target.kind === "issue") return target.ref;
1749
+ if (target.kind === "orchestration") return "that orchestration";
1750
+ return "that workspace";
1751
+ }
1752
+ function dependencyIdentity(edge) {
1753
+ return `${targetKey(edge.waitsOn)}|${edge.gate}|${targetKey(edge.subject)}|${edge.hold}`;
1754
+ }
1755
+ function dependencyWouldCycle(edges, next) {
1756
+ const start = targetKey(next.subject);
1757
+ const goal = targetKey(next.waitsOn);
1758
+ if (start === goal) return true;
1759
+ const adj = /* @__PURE__ */ new Map();
1760
+ for (const edge of edges) {
1761
+ const from = targetKey(edge.waitsOn);
1762
+ const to = targetKey(edge.subject);
1763
+ const list = adj.get(from) ?? [];
1764
+ list.push(to);
1765
+ adj.set(from, list);
1766
+ }
1767
+ const seen = /* @__PURE__ */ new Set();
1768
+ const stack = [start];
1769
+ while (stack.length) {
1770
+ const cur = stack.pop();
1771
+ if (cur === goal) return true;
1772
+ if (seen.has(cur)) continue;
1773
+ seen.add(cur);
1774
+ for (const nextKey of adj.get(cur) ?? []) stack.push(nextKey);
1775
+ }
1776
+ return false;
1777
+ }
1778
+ function cycleDependencyMessage(next) {
1779
+ if (targetKey(next.subject) === targetKey(next.waitsOn)) {
1780
+ return "A step cannot wait on itself.";
1781
+ }
1782
+ return `That dependency loops: ${shortName(next.subject)} already has to finish before ${shortName(next.waitsOn)}.`;
1783
+ }
1784
+ function subjectDepths(edges) {
1785
+ const depth = /* @__PURE__ */ new Map();
1786
+ const touch = (key) => {
1787
+ if (!depth.has(key)) depth.set(key, 0);
1788
+ };
1789
+ for (const edge of edges) {
1790
+ touch(targetKey(edge.waitsOn));
1791
+ touch(targetKey(edge.subject));
1792
+ }
1793
+ for (let pass = 0; pass < depth.size; pass++) {
1794
+ let changed = false;
1795
+ for (const edge of edges) {
1796
+ const from = targetKey(edge.waitsOn);
1797
+ const to = targetKey(edge.subject);
1798
+ const next = (depth.get(from) ?? 0) + 1;
1799
+ if (next > (depth.get(to) ?? 0)) {
1800
+ depth.set(to, next);
1801
+ changed = true;
1802
+ }
1803
+ }
1804
+ if (!changed) break;
1805
+ }
1806
+ return depth;
1807
+ }
1808
+ function threadFor(target, threads) {
1809
+ const live = threads.filter((thread) => thread.status !== "archived");
1810
+ return live.find((thread) => orderTargetMatches(target, thread)) ?? threads.find((thread) => orderTargetMatches(target, thread));
1811
+ }
1812
+ function orderTargetLabel(target, threads) {
1813
+ const hit = threadFor(target, threads);
1814
+ if (target.kind === "pr") {
1815
+ const title = target.label?.trim() || hit?.prTitle?.trim() || "";
1816
+ const base = `PR #${target.ref}`;
1817
+ return title && title !== base ? `${base} \xB7 ${title}` : base;
1818
+ }
1819
+ if (target.kind === "issue") {
1820
+ const title = target.label?.trim() || (hit?.sourceType === "ticket" ? hit.title.trim() : "");
1821
+ return title && title !== target.ref ? `${target.ref} \xB7 ${title}` : target.ref;
1822
+ }
1823
+ if (target.kind === "orchestration") {
1824
+ return target.label?.trim() || hit?.title?.trim() || "Orchestration";
1825
+ }
1826
+ return target.label?.trim() || hit?.title?.trim() || "Workspace";
1827
+ }
1828
+ function prMerged(target, threads) {
1829
+ return threads.some(
1830
+ (thread) => orderTargetMatches(target, thread) && (thread.prState ?? "").toUpperCase() === "MERGED"
1831
+ );
1832
+ }
1833
+ function orderGateStatus(edge, threads, marks) {
1834
+ const key = targetKey(edge.waitsOn);
1835
+ const marked = marks.some((mark) => mark.key === key && mark.gate === edge.gate);
1836
+ if (edge.gate === "in-prod") {
1837
+ return marked ? { met: true, marked: true, detail: "marked in production" } : { met: false, marked: false, detail: "waiting to be marked in production" };
1838
+ }
1839
+ if (marked) return { met: true, marked: true, detail: "marked in main" };
1840
+ if (prMerged(edge.waitsOn, threads)) {
1841
+ return { met: true, marked: false, detail: "merged to main" };
1842
+ }
1843
+ const known = threads.some((thread) => orderTargetMatches(edge.waitsOn, thread));
1844
+ return known ? { met: false, marked: false, detail: "open \u2014 not in main" } : { met: false, marked: false, detail: "not on the board yet" };
1845
+ }
1846
+ function resolveOrderRows(edges, threads, marks = []) {
1847
+ const depths = subjectDepths(edges);
1848
+ return edges.map((edge) => {
1849
+ const status = orderGateStatus(edge, threads, marks);
1850
+ return {
1851
+ id: edge.id,
1852
+ waitsOn: edge.waitsOn,
1853
+ subject: edge.subject,
1854
+ gate: edge.gate,
1855
+ hold: edge.hold,
1856
+ note: edge.note,
1857
+ loop: edge.loop === true,
1858
+ depth: depths.get(targetKey(edge.subject)) ?? 1,
1859
+ met: status.met,
1860
+ marked: status.marked,
1861
+ detail: status.detail,
1862
+ waitsOnLabel: orderTargetLabel(edge.waitsOn, threads),
1863
+ subjectLabel: orderTargetLabel(edge.subject, threads)
1864
+ };
1865
+ }).sort(
1866
+ (a, b) => a.depth - b.depth || a.waitsOnLabel.localeCompare(b.waitsOnLabel) || a.subjectLabel.localeCompare(b.subjectLabel)
1867
+ );
1868
+ }
1869
+
1870
+ // src/order/order-board.ts
1871
+ function buildWaterfall(rows) {
1872
+ const nodes = /* @__PURE__ */ new Map();
1873
+ const links = [];
1874
+ const depthOf = /* @__PURE__ */ new Map();
1875
+ for (const row2 of rows) {
1876
+ const to = targetKey(row2.subject);
1877
+ depthOf.set(to, Math.max(depthOf.get(to) ?? 0, row2.depth));
1878
+ if (!depthOf.has(targetKey(row2.waitsOn))) depthOf.set(targetKey(row2.waitsOn), 0);
1879
+ }
1880
+ function ensure(target, label) {
1881
+ const key = targetKey(target);
1882
+ let node = nodes.get(key);
1883
+ if (!node) {
1884
+ node = {
1885
+ key,
1886
+ label,
1887
+ kind: target.kind,
1888
+ ref: target.ref,
1889
+ ...target.repoPath ? { repoPath: target.repoPath } : {},
1890
+ depth: depthOf.get(key) ?? 0,
1891
+ incoming: []
1892
+ };
1893
+ nodes.set(key, node);
1894
+ }
1895
+ return node;
1896
+ }
1897
+ for (const row2 of rows) {
1898
+ ensure(row2.waitsOn, row2.waitsOnLabel);
1899
+ const subject = ensure(row2.subject, row2.subjectLabel);
1900
+ subject.depth = Math.max(subject.depth, row2.depth);
1901
+ subject.incoming.push({
1902
+ edgeId: row2.id,
1903
+ fromKey: targetKey(row2.waitsOn),
1904
+ gate: row2.gate,
1905
+ hold: row2.hold,
1906
+ met: row2.met,
1907
+ marked: row2.marked,
1908
+ detail: row2.detail,
1909
+ fromLabel: row2.waitsOnLabel,
1910
+ note: row2.note,
1911
+ loop: row2.loop === true
1912
+ });
1913
+ links.push({ from: targetKey(row2.waitsOn), to: targetKey(row2.subject) });
1914
+ }
1915
+ const parent = /* @__PURE__ */ new Map();
1916
+ const find = (key) => {
1917
+ const current = parent.get(key) ?? key;
1918
+ if (current === key) return key;
1919
+ const root = find(current);
1920
+ parent.set(key, root);
1921
+ return root;
1922
+ };
1923
+ for (const key of nodes.keys()) parent.set(key, key);
1924
+ for (const link of links) {
1925
+ const left = find(link.from);
1926
+ const right = find(link.to);
1927
+ if (left !== right) parent.set(left, right);
1928
+ }
1929
+ const groups = /* @__PURE__ */ new Map();
1930
+ for (const node of nodes.values()) {
1931
+ const root = find(node.key);
1932
+ const list = groups.get(root) ?? [];
1933
+ list.push(node);
1934
+ groups.set(root, list);
1935
+ }
1936
+ return [...groups.values()].map((list) => ({
1937
+ nodes: list.sort(
1938
+ (a, b) => a.depth - b.depth || a.label.localeCompare(b.label)
1939
+ )
1940
+ })).sort((a, b) => (a.nodes[0]?.label ?? "").localeCompare(b.nodes[0]?.label ?? ""));
1941
+ }
1942
+ function gatePhrase(gate) {
1943
+ return gate === "in-prod" ? "in production" : "in main";
1944
+ }
1945
+ function holdPhrase(hold) {
1946
+ return hold === "merge" ? "can merge" : "can start";
1947
+ }
1948
+ function ownerMatches(ref, ownerThreadId) {
1949
+ const left = ref.trim();
1950
+ const right = ownerThreadId.trim();
1951
+ if (!left || !right) return false;
1952
+ if (left === right) return true;
1953
+ return left.length >= 8 && !left.includes("/") && right.startsWith(left);
1954
+ }
1955
+ function resolveOrchestrationGates(plans, edges, threads, marks = []) {
1956
+ const rows = resolveOrderRows(edges, threads, marks);
1957
+ const planOf = new Map(edges.map((edge) => [edge.id, edge.planId ?? ""]));
1958
+ for (let pass = 0; pass < 8; pass++) {
1959
+ let changed = false;
1960
+ const clearByOwner = /* @__PURE__ */ new Map();
1961
+ for (const plan of plans) {
1962
+ if (!plan.ownerThreadId) continue;
1963
+ const mine = rows.filter((row2) => planOf.get(row2.id) === plan.id);
1964
+ clearByOwner.set(plan.ownerThreadId, mine.length > 0 && mine.every((row2) => row2.met));
1965
+ }
1966
+ for (const row2 of rows) {
1967
+ if (row2.gate !== "in-main" || row2.waitsOn.kind !== "orchestration" || row2.marked) continue;
1968
+ const plan = plans.find((item) => ownerMatches(row2.waitsOn.ref, item.ownerThreadId));
1969
+ const count = plan ? rows.filter((item) => planOf.get(item.id) === plan.id).length : 0;
1970
+ const clear = plan ? clearByOwner.get(plan.ownerThreadId) === true : false;
1971
+ const detail = !plan ? "no plan yet" : count === 0 ? "plan has no steps" : clear ? "plan is clear" : "plan still waiting";
1972
+ if (row2.met !== clear || row2.detail !== detail) {
1973
+ row2.met = clear;
1974
+ row2.detail = detail;
1975
+ row2.marked = false;
1976
+ changed = true;
1977
+ }
1978
+ }
1979
+ if (!changed) break;
1980
+ }
1981
+ return rows;
1982
+ }
1983
+ function buildPlanMap(boards, threads = []) {
1984
+ const nodes = boards.map((item) => {
1985
+ const subjects = item.chains.flatMap(
1986
+ (chain) => chain.nodes.filter((node) => node.incoming.length > 0)
1987
+ );
1988
+ return {
1989
+ id: item.plan.id,
1990
+ ownerThreadId: item.plan.ownerThreadId,
1991
+ title: item.plan.title,
1992
+ summary: item.plan.summary,
1993
+ status: item.plan.status,
1994
+ depth: 0,
1995
+ steps: subjects.length,
1996
+ waiting: subjects.filter((node) => node.incoming.some((edge) => !edge.met && !edge.loop)).length
1997
+ };
1998
+ });
1999
+ const byOwner = new Map(
2000
+ nodes.filter((node) => node.ownerThreadId).map((node) => [node.ownerThreadId, node])
2001
+ );
2002
+ function planForRef(ref) {
2003
+ return nodes.find((node) => ownerMatches(ref, node.ownerThreadId));
2004
+ }
2005
+ const links = /* @__PURE__ */ new Map();
2006
+ function add(fromId, toId, label) {
2007
+ if (!fromId || !toId || fromId === toId) return;
2008
+ const key = `${fromId}->${toId}`;
2009
+ const existing = links.get(key);
2010
+ if (!existing) links.set(key, { fromId, toId, label });
2011
+ else if (!existing.label.split(" \xB7 ").includes(label)) {
2012
+ existing.label = `${existing.label} \xB7 ${label}`;
2013
+ }
2014
+ }
2015
+ for (const item of boards) {
2016
+ for (const chain of item.chains) {
2017
+ for (const node of chain.nodes) {
2018
+ if (node.kind !== "orchestration") continue;
2019
+ const other = planForRef(node.ref);
2020
+ if (!other || other.id === item.plan.id) continue;
2021
+ if (node.incoming.length === 0) add(other.id, item.plan.id, "Waits on");
2022
+ else add(item.plan.id, other.id, node.incoming.every((edge) => edge.met || edge.loop) ? "Ready" : "Spawns");
2023
+ }
2024
+ }
2025
+ }
2026
+ for (const thread of threads) {
2027
+ const child = byOwner.get(thread.id);
2028
+ const parentId = thread.parentThreadId?.trim() ?? "";
2029
+ const parent = parentId ? byOwner.get(parentId) : void 0;
2030
+ if (!child || !parent) continue;
2031
+ add(parent.id, child.id, "Spawned");
2032
+ }
2033
+ const depth = new Map(nodes.map((node) => [node.id, 0]));
2034
+ for (let pass = 0; pass < 12; pass++) {
2035
+ let changed = false;
2036
+ for (const link of links.values()) {
2037
+ const next = (depth.get(link.fromId) ?? 0) + 1;
2038
+ if (next < 12 && next > (depth.get(link.toId) ?? 0)) {
2039
+ depth.set(link.toId, next);
2040
+ changed = true;
2041
+ }
2042
+ }
2043
+ if (!changed) break;
2044
+ }
2045
+ for (const node of nodes) node.depth = depth.get(node.id) ?? 0;
2046
+ return { nodes, links: [...links.values()] };
2047
+ }
2048
+
2049
+ // src/order/order-present.ts
2050
+ function formatOrderPlace(rows, you) {
2051
+ const mine = (target) => orderTargetMatches(target, you);
2052
+ const waitingOn = rows.filter((row2) => mine(row2.subject) && !row2.met && !row2.loop);
2053
+ const looping = rows.filter((row2) => mine(row2.subject) && row2.loop && !row2.met);
2054
+ const ready = rows.filter((row2) => mine(row2.subject) && row2.met);
2055
+ const blocking = rows.filter((row2) => mine(row2.waitsOn) && !row2.met && !row2.loop);
2056
+ if (!waitingOn.length && !looping.length && !ready.length && !blocking.length) {
2057
+ return "This checkout is not in the planner. set_dependency records what you wait on (omit subject). clear_dependency removes a step you are part of.";
2058
+ }
2059
+ const gate = (row2) => row2.gate === "in-prod" ? "in prod" : "in main";
2060
+ const lines = ["Where you are in the planner:"];
2061
+ for (const row2 of waitingOn) {
2062
+ lines.push(
2063
+ `- Waiting: ${row2.waitsOnLabel} must be ${gate(row2)} before you can ${row2.hold}. id: ${row2.id.slice(0, 8)}`
2064
+ );
2065
+ }
2066
+ for (const row2 of looping) {
2067
+ lines.push(
2068
+ `- Loop: returns to ${row2.waitsOnLabel} once you are ${gate(row2)}. The first pass is not blocked. id: ${row2.id.slice(0, 8)}`
2069
+ );
2070
+ }
2071
+ for (const row2 of ready) {
2072
+ lines.push(`- Clear: you can ${row2.hold}. ${row2.detail}. id: ${row2.id.slice(0, 8)}`);
2073
+ }
2074
+ for (const row2 of blocking) {
2075
+ lines.push(
2076
+ `- Blocking: ${row2.subjectLabel} cannot ${row2.hold} until you are ${gate(row2)}. id: ${row2.id.slice(0, 8)}`
2077
+ );
2078
+ }
2079
+ return lines.join("\n");
2080
+ }
2081
+ function executionSlice(rows) {
2082
+ return {
2083
+ ready: rows.filter((row2) => row2.met || row2.loop),
2084
+ waiting: rows.filter((row2) => !row2.met && !row2.loop)
2085
+ };
2086
+ }
2087
+ function orderEdgeTouches(edge, you) {
2088
+ return orderTargetMatches(edge.subject, you) || orderTargetMatches(edge.waitsOn, you);
2089
+ }
2090
+ function formatOrderText(rows, plan) {
2091
+ if (rows.length === 0) {
2092
+ if (plan) {
2093
+ const goal = plan.goal ? ` Goal: ${plan.goal}.` : "";
2094
+ const summary = plan.summary ? ` ${plan.summary}` : "";
2095
+ return `Plan \u201C${plan.title}\u201D is ${plan.status}.${goal}${summary} No steps yet. set_dependency records each gate.`.replace(/\s+/g, " ").trim();
2096
+ }
2097
+ return "No orchestration plan yet. set_dependency records an order \u2014 for example PR 1 in prod before PR 2 can merge, or PR 3 in main before issue 4 can start. The Orchestration row in the sidebar opens that chat.";
2098
+ }
2099
+ const lines = [
2100
+ plan ? `Plan \u201C${plan.title}\u201D is ${plan.status}. ${plan.goal ? `Goal: ${plan.goal}. ` : ""}${plan.summary}`.trim() : "Orchestration. Steps can wait on a gate or loop back to an earlier step. in-main clears when that PR is merged. in-prod stays waiting until satisfy_dependency.",
2101
+ ""
2102
+ ];
2103
+ rows.forEach((row2, index) => {
2104
+ const gate = row2.gate === "in-prod" ? "in prod" : "in main";
2105
+ const hold = row2.hold === "merge" ? "merge" : "start";
2106
+ const state = row2.loop ? "loop" : row2.met ? "clear" : "waiting";
2107
+ lines.push(
2108
+ row2.loop ? `${index + 1}. ${state} ${row2.subjectLabel} returns to ${row2.waitsOnLabel} once it is ${gate}` : `${index + 1}. ${state} ${row2.waitsOnLabel} must be ${gate} before ${row2.subjectLabel} can ${hold}`
2109
+ );
2110
+ lines.push(` ${row2.detail}`);
2111
+ if (row2.note) lines.push(` ${row2.note}`);
2112
+ lines.push(` id: ${row2.id.slice(0, 8)}`);
2113
+ });
2114
+ return lines.join("\n");
2115
+ }
2116
+ function escapeHtml(value) {
2117
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2118
+ }
2119
+ var WATERFALL_KIND = {
2120
+ pr: "Pull request",
2121
+ issue: "Issue",
2122
+ workspace: "Workspace",
2123
+ orchestration: "Orchestration"
2124
+ };
2125
+ function markWorkingChains(chains, threads) {
2126
+ const active = threads.filter(
2127
+ (thread) => thread.status === "running" || thread.status === "queued"
2128
+ );
2129
+ if (active.length === 0) return chains;
2130
+ return chains.map((chain) => ({
2131
+ nodes: chain.nodes.map((node) => {
2132
+ const working = active.some(
2133
+ (thread) => orderTargetMatches(
2134
+ {
2135
+ kind: node.kind,
2136
+ ref: node.ref,
2137
+ ...node.repoPath ? { repoPath: node.repoPath } : {}
2138
+ },
2139
+ thread
2140
+ )
2141
+ );
2142
+ return working ? { ...node, working: true } : node;
2143
+ })
2144
+ }));
2145
+ }
2146
+ function nodeIsYou(node, you) {
2147
+ if (!you) return false;
2148
+ return orderTargetMatches(
2149
+ {
2150
+ kind: node.kind,
2151
+ ref: node.ref,
2152
+ ...node.repoPath ? { repoPath: node.repoPath } : {}
2153
+ },
2154
+ you
2155
+ );
2156
+ }
2157
+ function formatWaterfallHtml(chains, opts) {
2158
+ const plan = opts?.plan ?? null;
2159
+ const you = opts?.you ?? null;
2160
+ const title = plan?.title?.trim() || "Planner";
2161
+ const status = plan ? plan.status === "active" ? "Running. Ready steps can start. Waiting steps stay held." : "Draft. Discuss this and change it. Nothing runs until you agree." : "Later steps wait until the one above reaches its gate. In main clears when that pull request is merged. In production stays waiting until it is marked.";
2162
+ const body = chains.length === 0 ? '<p class="empty">No order yet.</p>' : chains.map((chain) => {
2163
+ const nodes = chain.nodes.map((node) => {
2164
+ const waiting = node.incoming.some((edge) => !edge.met && !edge.loop);
2165
+ const clear = node.incoming.some((edge) => !edge.loop) && !waiting;
2166
+ const yours = nodeIsYou(node, you);
2167
+ const working = node.working === true;
2168
+ const state = `${waiting ? " waiting" : clear ? " clear" : ""}${yours ? " you" : ""}${working ? " current" : ""}`;
2169
+ const drops = node.incoming.map((edge) => {
2170
+ const tone = edge.loop ? "loop" : edge.met ? "clear" : "waiting";
2171
+ const note = edge.note ? `<span>${escapeHtml(edge.note)}</span>` : "";
2172
+ return `<div class="drop"><span>After ${escapeHtml(edge.fromLabel)} is ${escapeHtml(gatePhrase(edge.gate))}, this ${escapeHtml(holdPhrase(edge.hold))}</span><span class="${tone}">${escapeHtml(edge.detail)}</span>${note}</div>`;
2173
+ }).join("");
2174
+ const kicker = `${WATERFALL_KIND[node.kind]}${working ? " \xB7 Working" : ""}${yours ? " \xB7 You" : ""}`;
2175
+ return `<li class="node" style="margin-left:${node.depth * 28}px">${drops}<div class="bar${state}"><span class="kicker">${kicker}</span><strong>${escapeHtml(node.label)}</strong></div></li>`;
2176
+ }).join("");
2177
+ return `<ol class="chain">${nodes}</ol>`;
2178
+ }).join("");
2179
+ const summary = plan?.summary?.trim() ? `<p class="lead">${escapeHtml(plan.summary.trim())}</p>` : "";
2180
+ return `<!DOCTYPE html>
2181
+ <html lang="en">
2182
+ <head>
2183
+ <meta charset="utf-8">
2184
+ <title>${escapeHtml(title)}</title>
2185
+ <style>
2186
+ :root { color-scheme: dark; }
2187
+ body { margin: 0; padding: 20px 22px 32px; background: #141414; color: #ececec; font: 13px/1.4 ui-sans-serif, system-ui, sans-serif; }
2188
+ h1 { font-size: 15px; font-weight: 600; margin: 0 0 6px; }
2189
+ .lead, .empty, .status { color: #9a9a9a; margin: 0 0 18px; max-width: 62ch; }
2190
+ .chain { list-style: none; margin: 0 0 28px; padding: 0; }
2191
+ .drop { margin: 0 0 0 16px; padding: 8px 0 8px 12px; border-left: 1px solid #333; color: #9a9a9a; font-size: 12px; display: flex; flex-direction: column; gap: 3px; }
2192
+ .drop .waiting { color: #e2b340; }
2193
+ .drop .clear, .drop .loop { color: #6fbf73; }
2194
+ .bar { border: 1px solid #333; border-radius: 10px; padding: 10px 12px; background: #1c1c1c; display: flex; flex-direction: column; gap: 2px; }
2195
+ .bar.waiting { border-color: #6a5420; background: #221c10; }
2196
+ .bar.clear { border-color: #2d5a32; background: #142016; }
2197
+ .bar.you { outline: 1px solid #8ab4ff; }
2198
+ .bar.current { border-color: #8ab4ff; box-shadow: inset 3px 0 0 #8ab4ff; }
2199
+ .bar.current .kicker { color: #ececec; }
2200
+ .kicker { font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; color: #9a9a9a; }
2201
+ </style>
2202
+ </head>
2203
+ <body>
2204
+ <h1>${escapeHtml(title)}</h1>
2205
+ <p class="status">${escapeHtml(status)}</p>
2206
+ ${summary}
2207
+ ${body}
2208
+ </body>
2209
+ </html>`;
2210
+ }
2211
+ function checkoutPlanTitle(markdown) {
2212
+ const match = /^#{1,6}[ \t]+(.+?)[ \t]*$/m.exec(markdown);
2213
+ const title = match?.[1]?.replace(/\s+#+\s*$/, "").trim() ?? "";
2214
+ return title.slice(0, 80) || "Implementation plan";
2215
+ }
2216
+ function showPlanDocuments(input) {
2217
+ const docs = [];
2218
+ const markdown = input.checkoutMarkdown ?? "";
2219
+ if (markdown.trim()) {
2220
+ docs.push({
2221
+ title: checkoutPlanTitle(markdown),
2222
+ type: "markdown",
2223
+ artifact_id: "checkout-plan",
2224
+ content: markdown
2225
+ });
2226
+ }
2227
+ const html = input.diagramHtml ?? "";
2228
+ if (html.trim()) {
2229
+ docs.push({
2230
+ title: input.diagramTitle?.trim() || "Planner",
2231
+ type: "html",
2232
+ artifact_id: "plan",
2233
+ content: html
2234
+ });
2235
+ }
2236
+ return docs;
2237
+ }
2238
+ function showPlanMessage(docs, worktree) {
2239
+ const diagram = docs.some((doc) => doc.artifact_id === "plan");
2240
+ const checkout = docs.some((doc) => doc.artifact_id === "checkout-plan");
2241
+ if (diagram && checkout) {
2242
+ return "Opened the orchestration plan and this checkout's implementation plan.";
2243
+ }
2244
+ if (checkout) return "Opened this checkout's implementation plan.";
2245
+ return worktree ? "Opened the orchestration plan in the side column, with this checkout marked." : "Opened the plan in the side column.";
2246
+ }
2247
+
2248
+ // src/order/order.ts
2249
+ function orderPath() {
2250
+ return join2(appDataDir(), "order.json");
2251
+ }
2252
+ function emptyFile() {
2253
+ return { plans: [], edges: [], marks: [] };
2254
+ }
2255
+ function asPlan(value, fallbackId) {
2256
+ if (!value || typeof value !== "object") return null;
2257
+ const row2 = value;
2258
+ const title = typeof row2.title === "string" ? row2.title.trim().slice(0, 120) : "";
2259
+ if (!title) return null;
2260
+ const summary = typeof row2.summary === "string" ? row2.summary.trim().slice(0, 600) : "";
2261
+ const goal = typeof row2.goal === "string" ? row2.goal.trim().slice(0, 400) : "";
2262
+ const status = row2.status === "active" ? "active" : "draft";
2263
+ const updatedAt = typeof row2.updatedAt === "string" && row2.updatedAt ? row2.updatedAt : (/* @__PURE__ */ new Date()).toISOString();
2264
+ const id = typeof row2.id === "string" && row2.id.trim() ? row2.id.trim() : fallbackId;
2265
+ const ownerThreadId = typeof row2.ownerThreadId === "string" ? row2.ownerThreadId.trim() : "";
2266
+ return { id, ownerThreadId, title, summary, goal, status, updatedAt };
2267
+ }
2268
+ function asTarget(value) {
2269
+ if (!value || typeof value !== "object") return null;
2270
+ const row2 = value;
2271
+ if (row2.kind !== "pr" && row2.kind !== "issue" && row2.kind !== "workspace" && row2.kind !== "orchestration") {
2272
+ return null;
2273
+ }
2274
+ if (typeof row2.ref !== "string" || !row2.ref.trim()) return null;
2275
+ try {
2276
+ return normalizeOrderTarget(row2);
2277
+ } catch {
2278
+ return null;
2279
+ }
2280
+ }
2281
+ function asEdge(value) {
2282
+ if (!value || typeof value !== "object") return null;
2283
+ const row2 = value;
2284
+ if (typeof row2.id !== "string" || !row2.id.trim()) return null;
2285
+ const waitsOn = asTarget(row2.waitsOn);
2286
+ const subject = asTarget(row2.subject);
2287
+ if (!waitsOn || !subject) return null;
2288
+ if (row2.gate !== "in-main" && row2.gate !== "in-prod") return null;
2289
+ if (row2.hold !== "start" && row2.hold !== "merge") return null;
2290
+ return {
2291
+ id: row2.id,
2292
+ waitsOn,
2293
+ gate: row2.gate,
2294
+ subject,
2295
+ hold: row2.hold,
2296
+ ...row2.loop === true ? { loop: true } : {},
2297
+ note: typeof row2.note === "string" ? row2.note.slice(0, 400) : "",
2298
+ createdByThreadId: row2.createdByThreadId?.trim() || null,
2299
+ createdAt: typeof row2.createdAt === "string" ? row2.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
2300
+ ...typeof row2.planId === "string" && row2.planId.trim() ? { planId: row2.planId.trim() } : {}
2301
+ };
2302
+ }
2303
+ function asMark(value) {
2304
+ if (!value || typeof value !== "object") return null;
2305
+ const row2 = value;
2306
+ if (typeof row2.key !== "string" || !row2.key.trim()) return null;
2307
+ if (row2.gate !== "in-main" && row2.gate !== "in-prod") return null;
2308
+ if (typeof row2.at !== "string" || !row2.at) return null;
2309
+ return { key: row2.key, gate: row2.gate, at: row2.at };
2310
+ }
2311
+ function readFile() {
2312
+ const path2 = orderPath();
2313
+ if (!existsSync2(path2)) return emptyFile();
2314
+ try {
2315
+ const parsed = JSON.parse(readFileSync2(path2, "utf8"));
2316
+ if (!parsed || typeof parsed !== "object") return emptyFile();
2317
+ const raw = parsed;
2318
+ const edges = Array.isArray(raw.edges) ? raw.edges.map(asEdge).filter((row2) => Boolean(row2)) : [];
2319
+ const listed = Array.isArray(raw.plans) ? raw.plans.map((row2, index) => asPlan(row2, `plan-${index + 1}`)).filter((row2) => Boolean(row2)) : [];
2320
+ const legacy = listed.length ? null : asPlan(raw.plan, "legacy");
2321
+ let plans = legacy ? [legacy] : listed;
2322
+ if (!plans.length && edges.length) {
2323
+ plans = [
2324
+ {
2325
+ id: "legacy",
2326
+ ownerThreadId: "",
2327
+ title: "Planner",
2328
+ summary: "",
2329
+ goal: "",
2330
+ status: "draft",
2331
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2332
+ }
2333
+ ];
2334
+ }
2335
+ const fallbackId = plans[0]?.id ?? "";
2336
+ return {
2337
+ plans,
2338
+ edges: edges.map((edge) => ({ ...edge, planId: edge.planId || fallbackId })),
2339
+ marks: Array.isArray(raw.marks) ? raw.marks.map(asMark).filter((row2) => Boolean(row2)) : []
2340
+ };
2341
+ } catch {
2342
+ return emptyFile();
2343
+ }
2344
+ }
2345
+ function pruneMarks(edges, marks) {
2346
+ const live = new Set(edges.map((edge) => `${targetKey(edge.waitsOn)}|${edge.gate}`));
2347
+ return marks.filter((mark) => live.has(`${mark.key}|${mark.gate}`));
2348
+ }
2349
+ function writeFile(file) {
2350
+ const next = {
2351
+ plans: file.plans,
2352
+ edges: file.edges,
2353
+ marks: pruneMarks(file.edges, file.marks)
2354
+ };
2355
+ writePrivateFile(orderPath(), `${JSON.stringify(next, null, 2)}
2356
+ `);
2357
+ }
2358
+ function planByOwner(file, ownerThreadId) {
2359
+ const owner = ownerThreadId?.trim() ?? "";
2360
+ if (owner) return file.plans.find((plan) => plan.ownerThreadId === owner) ?? null;
2361
+ return file.plans.length === 1 ? file.plans[0] : null;
2362
+ }
2363
+ function getOrderPlan(ownerThreadId) {
2364
+ return planByOwner(readFile(), ownerThreadId);
2365
+ }
2366
+ function listOrderPlans() {
2367
+ return readFile().plans;
2368
+ }
2369
+ function setOrderPlan(input) {
2370
+ const title = input.title.trim().slice(0, 120);
2371
+ if (!title) throw new Error("Plan title is required");
2372
+ const file = readFile();
2373
+ const owner = input.ownerThreadId?.trim() ?? "";
2374
+ const existing = file.plans.find((plan2) => plan2.ownerThreadId === owner);
2375
+ const plan = {
2376
+ id: existing?.id ?? randomUUID2(),
2377
+ ownerThreadId: owner,
2378
+ title,
2379
+ summary: input.summary?.trim().slice(0, 600) ?? existing?.summary ?? "",
2380
+ goal: input.goal === void 0 ? existing?.goal ?? "" : input.goal?.trim().slice(0, 400) ?? "",
2381
+ status: existing?.status === "active" ? "active" : "draft",
2382
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2383
+ };
2384
+ if (existing) {
2385
+ const index = file.plans.findIndex((row2) => row2.id === existing.id);
2386
+ file.plans[index] = plan;
2387
+ } else {
2388
+ file.plans.push(plan);
2389
+ }
2390
+ writeFile(file);
2391
+ return plan;
2392
+ }
2393
+ function executeOrderPlan(ownerThreadId) {
2394
+ const file = readFile();
2395
+ const current = planByOwner(file, ownerThreadId);
2396
+ if (!current) throw new Error("set_plan first. This chat has no plan yet.");
2397
+ const edges = file.edges.filter((edge) => edge.planId === current.id);
2398
+ if (edges.length === 0) {
2399
+ throw new Error("The planner is empty. set_plan and set_dependency first.");
2400
+ }
2401
+ const plan = { ...current, status: "active", updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2402
+ const index = file.plans.findIndex((row2) => row2.id === current.id);
2403
+ file.plans[index] = plan;
2404
+ writeFile(file);
2405
+ const ids = new Set(edges.map((edge) => edge.id));
2406
+ const rows = resolveOrchestrationGates(file.plans, file.edges, threadSnapshots(), file.marks);
2407
+ const slice = executionSlice(rows.filter((row2) => ids.has(row2.id)));
2408
+ return { plan, ready: slice.ready, waiting: slice.waiting };
2409
+ }
2410
+ function listOrderEdges() {
2411
+ return readFile().edges;
2412
+ }
2413
+ function listOrderMarks() {
2414
+ return readFile().marks;
2415
+ }
2416
+ function threadSnapshots() {
2417
+ try {
2418
+ return listThreads({ includeArchived: true }).map(orderSnapshotFromThread);
2419
+ } catch {
2420
+ return [];
2421
+ }
2422
+ }
2423
+ function listOrderRows(planId) {
2424
+ const file = readFile();
2425
+ const rows = resolveOrchestrationGates(file.plans, file.edges, threadSnapshots(), file.marks);
2426
+ if (!planId) return rows;
2427
+ const ids = new Set(file.edges.filter((edge) => edge.planId === planId).map((edge) => edge.id));
2428
+ return rows.filter((row2) => ids.has(row2.id));
2429
+ }
2430
+ function listWaterfall(planId) {
2431
+ return markWorkingChains(buildWaterfall(listOrderRows(planId)), threadSnapshots());
2432
+ }
2433
+ function listOrderBoard() {
2434
+ const file = readFile();
2435
+ const threads = threadSnapshots();
2436
+ const rows = resolveOrchestrationGates(file.plans, file.edges, threads, file.marks);
2437
+ const plans = file.plans.map((plan) => ({
2438
+ plan,
2439
+ chains: markWorkingChains(
2440
+ buildWaterfall(rows.filter((row2) => {
2441
+ const edge = file.edges.find((item) => item.id === row2.id);
2442
+ return edge?.planId === plan.id;
2443
+ })),
2444
+ threads
2445
+ )
2446
+ }));
2447
+ plans.sort((a, b) => a.plan.title.localeCompare(b.plan.title));
2448
+ return { plans };
2449
+ }
2450
+ function selectPlan(file, input) {
2451
+ const planId = input.planId?.trim();
2452
+ if (planId) {
2453
+ const hit = file.plans.find((plan) => plan.id === planId);
2454
+ if (!hit) throw new Error("No plan with that id.");
2455
+ return hit;
2456
+ }
2457
+ const owner = input.ownerThreadId?.trim();
2458
+ if (owner) {
2459
+ const hit = file.plans.find((plan) => plan.ownerThreadId === owner);
2460
+ if (!hit) throw new Error("set_plan first. This chat has no plan yet.");
2461
+ return hit;
2462
+ }
2463
+ if (file.plans.length === 1) return file.plans[0];
2464
+ if (file.plans.length === 0) {
2465
+ const plan = {
2466
+ id: randomUUID2(),
2467
+ ownerThreadId: "",
2468
+ title: "Planner",
2469
+ summary: "",
2470
+ goal: "",
2471
+ status: "draft",
2472
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2473
+ };
2474
+ file.plans.push(plan);
2475
+ return plan;
2476
+ }
2477
+ throw new Error("More than one plan is open. Pass the orchestration chat.");
2478
+ }
2479
+ function findEdge(id, edges) {
2480
+ const key = id.trim();
2481
+ if (!key) return null;
2482
+ return edges.find((edge) => edge.id === key || key.length >= 8 && edge.id.startsWith(key)) ?? null;
2483
+ }
2484
+ function setOrderDependency(input) {
2485
+ const waitsOn = normalizeOrderTarget(input.waitsOn);
2486
+ const subject = normalizeOrderTarget(input.subject);
2487
+ const gate = parseOrderGate(input.gate);
2488
+ const hold = parseOrderHold(input.hold);
2489
+ const file = readFile();
2490
+ const plan = selectPlan(file, input);
2491
+ const scoped = file.edges.filter((edge2) => edge2.planId === plan.id);
2492
+ const draft = { waitsOn, subject, gate, hold };
2493
+ const existing = scoped.find((edge2) => dependencyIdentity(edge2) === dependencyIdentity(draft));
2494
+ if (existing) return { edge: existing, created: false };
2495
+ if (targetKey(subject) === targetKey(waitsOn)) {
2496
+ throw new Error(cycleDependencyMessage(draft));
2497
+ }
2498
+ const loop = dependencyWouldCycle(scoped, draft);
2499
+ const edge = {
2500
+ id: randomUUID2(),
2501
+ planId: plan.id,
2502
+ waitsOn,
2503
+ gate,
2504
+ subject,
2505
+ hold,
2506
+ ...loop ? { loop: true } : {},
2507
+ note: input.note?.trim().slice(0, 400) ?? "",
2508
+ createdByThreadId: input.createdByThreadId?.trim() || null,
2509
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2510
+ };
2511
+ file.edges.push(edge);
2512
+ writeFile(file);
2513
+ return { edge, created: true };
2514
+ }
2515
+ function clearOrderDependency(id, caller, ownerThreadId) {
2516
+ const file = readFile();
2517
+ const edge = findEdge(id, file.edges);
2518
+ if (!edge) throw new Error(`No planner step ${id}`);
2519
+ if (caller && !orderEdgeTouches(edge, caller)) {
2520
+ throw new Error("This checkout can only change a step it is part of.");
2521
+ }
2522
+ const owner = ownerThreadId?.trim();
2523
+ if (owner) {
2524
+ const plan = file.plans.find((row2) => row2.ownerThreadId === owner);
2525
+ if (!plan || edge.planId !== plan.id) {
2526
+ throw new Error("This plan belongs to another orchestration chat.");
2527
+ }
2528
+ }
2529
+ file.edges = file.edges.filter((row2) => row2.id !== edge.id);
2530
+ writeFile(file);
2531
+ }
2532
+ function satisfyOrderDependency(id, satisfied = true) {
2533
+ const file = readFile();
2534
+ const edge = findEdge(id, file.edges);
2535
+ if (!edge) throw new Error(`No planner step ${id}`);
2536
+ const key = targetKey(edge.waitsOn);
2537
+ file.marks = file.marks.filter((mark) => !(mark.key === key && mark.gate === edge.gate));
2538
+ if (satisfied) file.marks.push({ key, gate: edge.gate, at: (/* @__PURE__ */ new Date()).toISOString() });
2539
+ writeFile(file);
2540
+ return edge;
2541
+ }
2542
+
1605
2543
  // src/host/awake.ts
1606
2544
  function hostKeepsMacAwake(input) {
1607
2545
  if (input.phoneConnected) return true;
@@ -1744,7 +2682,7 @@ function buildPathRefAttachment(input) {
1744
2682
  }
1745
2683
 
1746
2684
  // src/remote/phone-chats.ts
1747
- import { randomUUID as randomUUID2 } from "crypto";
2685
+ import { randomUUID as randomUUID3 } from "crypto";
1748
2686
 
1749
2687
  // src/remote/phone-artifact.ts
1750
2688
  var FENCE_RE = /```([a-zA-Z0-9_+-]*)[^\n]*\n([\s\S]*?)(?:```|$)/g;
@@ -2233,7 +3171,8 @@ function row(resolved) {
2233
3171
  function phoneAccountDefaults() {
2234
3172
  return {
2235
3173
  orchestration: row(resolveOrchestratorDefaults()),
2236
- worktree: row(resolveThreadDefaults())
3174
+ worktree: row(resolveThreadDefaults()),
3175
+ followUp: followUpBehavior()
2237
3176
  };
2238
3177
  }
2239
3178
 
@@ -2831,13 +3770,13 @@ function phoneComposerOptions(thread) {
2831
3770
  }
2832
3771
  function phoneTurnAttachments(draft) {
2833
3772
  const links = (draft.links ?? []).map((link) => ({
2834
- id: randomUUID2(),
3773
+ id: randomUUID3(),
2835
3774
  name: link.ref,
2836
3775
  kind: "issue",
2837
3776
  content: [`Linked issue: ${link.ref} \u2014 ${link.title}`, link.url ? `URL: ${link.url}` : null].filter(Boolean).join("\n")
2838
3777
  }));
2839
3778
  const files = (draft.files ?? []).map((file) => ({
2840
- id: randomUUID2(),
3779
+ id: randomUUID3(),
2841
3780
  name: file.name,
2842
3781
  kind: "file",
2843
3782
  previewDataUrl: `data:application/octet-stream;base64,${file.dataBase64}`,
@@ -3222,8 +4161,8 @@ function dispatchPhoneMcpUi(cmd, opts) {
3222
4161
  }
3223
4162
 
3224
4163
  // src/remote/phone-media.ts
3225
- import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
3226
- import { join as join2 } from "path";
4164
+ import { readdirSync as readdirSync2, readFileSync as readFileSync3 } from "fs";
4165
+ import { join as join3 } from "path";
3227
4166
  var PHONE_IMAGE_MAX_BYTES = 15e5;
3228
4167
  var PHONE_TEXT_MAX_BYTES = 18e4;
3229
4168
  var PHONE_DIR_MAX = 200;
@@ -3275,7 +4214,7 @@ function phoneImageDataUrl(worktreePath, raw) {
3275
4214
  }
3276
4215
  function phoneDirectoryListing(worktreePath, relative) {
3277
4216
  try {
3278
- const entries = readdirSync2(join2(worktreePath, relative), { withFileTypes: true });
4217
+ const entries = readdirSync2(join3(worktreePath, relative), { withFileTypes: true });
3279
4218
  const dirs = new Set(entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name));
3280
4219
  const names = entries.map((entry) => entry.name).filter((name) => name && !name.includes("/") && !name.includes("\0")).sort((a, b) => a.localeCompare(b));
3281
4220
  const shown = names.slice(0, PHONE_DIR_MAX);
@@ -3301,7 +4240,7 @@ function phoneFilePreview(worktreePath, relative, kind) {
3301
4240
  }
3302
4241
  if (relative.toLowerCase().endsWith(".svg")) {
3303
4242
  try {
3304
- const buf = readFileSync2(join2(worktreePath, relative));
4243
+ const buf = readFileSync3(join3(worktreePath, relative));
3305
4244
  const truncated = buf.length > PHONE_TEXT_MAX_BYTES;
3306
4245
  return {
3307
4246
  content: buf.subarray(0, PHONE_TEXT_MAX_BYTES).toString("utf8"),
@@ -4843,7 +5782,10 @@ function phoneBoardKey(sidebar) {
4843
5782
  ${trees}`;
4844
5783
  }).join("\n---\n");
4845
5784
  const defaults = sidebar.defaults;
4846
- const defaultsKey = defaults ? [defaults.orchestration, defaults.worktree].map((row2) => [row2.agent, row2.model ?? "", row2.effort, row2.fast ? "1" : "0"].join(" ")).join("\n") : "";
5785
+ const defaultsKey = defaults ? [
5786
+ defaults.followUp,
5787
+ [defaults.orchestration, defaults.worktree].map((row2) => [row2.agent, row2.model ?? "", row2.effort, row2.fast ? "1" : "0"].join(" ")).join("\n")
5788
+ ].join("\n") : "";
4847
5789
  return `${orchestration}
4848
5790
  ===
4849
5791
  ${projects}
@@ -5251,7 +6193,7 @@ function oauthReturnPage(title, body) {
5251
6193
  <meta charset="utf-8">
5252
6194
  <meta name="viewport" content="width=device-width, initial-scale=1">
5253
6195
  <meta name="robots" content="noindex">
5254
- <title>${escapeHtml(title)}</title>
6196
+ <title>${escapeHtml2(title)}</title>
5255
6197
  <style>
5256
6198
  :root {
5257
6199
  --bg: #09090b;
@@ -5310,7 +6252,7 @@ function oauthReturnPage(title, body) {
5310
6252
  </body>
5311
6253
  </html>`;
5312
6254
  }
5313
- function escapeHtml(value) {
6255
+ function escapeHtml2(value) {
5314
6256
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5315
6257
  }
5316
6258
 
@@ -5324,7 +6266,7 @@ var SLACK_OAUTH_REDIRECT = `https://relay.sideboard.build${SLACK_OAUTH_CALLBACK_
5324
6266
  function slackOAuthRedirectUri() {
5325
6267
  return process.env.SIDEBOARD_SLACK_OAUTH_REDIRECT?.trim() || SLACK_OAUTH_REDIRECT;
5326
6268
  }
5327
- function escapeHtml2(value) {
6269
+ function escapeHtml3(value) {
5328
6270
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5329
6271
  }
5330
6272
  function slackOAuthHtmlPage(title, body) {
@@ -5814,9 +6756,9 @@ function clientIdFromOAuthState(state) {
5814
6756
  }
5815
6757
 
5816
6758
  // src/slack/workspaces.ts
5817
- import { join as join3 } from "path";
6759
+ import { join as join4 } from "path";
5818
6760
  function storePath() {
5819
- return join3(appDataDir(), "slack-workspaces.json");
6761
+ return join4(appDataDir(), "slack-workspaces.json");
5820
6762
  }
5821
6763
  function readStore() {
5822
6764
  try {
@@ -6225,7 +7167,7 @@ async function handleCallback(ctx, url) {
6225
7167
  const code = url.searchParams.get("code")?.trim() ?? "";
6226
7168
  if (error) {
6227
7169
  if (state) ctx.pending.put(state, { ok: false, error: `Slack OAuth: ${error}` });
6228
- sendHtml(ctx.res, 400, "Slack", `<h1>Authorization cancelled</h1><p>${escapeHtml2(error)}</p>`);
7170
+ sendHtml(ctx.res, 400, "Slack", `<h1>Authorization cancelled</h1><p>${escapeHtml3(error)}</p>`);
6229
7171
  return true;
6230
7172
  }
6231
7173
  if (!state || !code) {
@@ -6270,7 +7212,7 @@ async function handleCallback(ctx, url) {
6270
7212
  } catch (err) {
6271
7213
  const message = err instanceof Error ? err.message : String(err);
6272
7214
  ctx.pending.put(state, { ok: false, error: message });
6273
- sendHtml(ctx.res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml2(message)}</p>`);
7215
+ sendHtml(ctx.res, 400, "Slack", `<h1>Could not connect Slack</h1><p>${escapeHtml3(message)}</p>`);
6274
7216
  }
6275
7217
  return true;
6276
7218
  }
@@ -6364,7 +7306,7 @@ function sendJson(res, status, body) {
6364
7306
  import { createHash, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
6365
7307
  import { mkdirSync as mkdirSync2 } from "fs";
6366
7308
  import { createRequire } from "module";
6367
- import { dirname, join as join4 } from "path";
7309
+ import { dirname, join as join5 } from "path";
6368
7310
  var SlackAppStore = class {
6369
7311
  db;
6370
7312
  key;
@@ -6531,7 +7473,7 @@ function sameHash(stored, presented) {
6531
7473
  }
6532
7474
  function thisModuleFile() {
6533
7475
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6534
- return cjsFile || process.argv[1] || join4(process.cwd(), "package.json");
7476
+ return cjsFile || process.argv[1] || join5(process.cwd(), "package.json");
6535
7477
  }
6536
7478
  function openDatabase(filePath) {
6537
7479
  const req = createRequire(thisModuleFile());
@@ -6545,7 +7487,7 @@ function openDatabase(filePath) {
6545
7487
  import { randomBytes as randomBytes6 } from "crypto";
6546
7488
  import { mkdirSync as mkdirSync3 } from "fs";
6547
7489
  import { createRequire as createRequire2 } from "module";
6548
- import { dirname as dirname2, join as join5 } from "path";
7490
+ import { dirname as dirname2, join as join6 } from "path";
6549
7491
 
6550
7492
  // src/slack/listen-grant.ts
6551
7493
  import { createHash as createHash2, randomBytes as randomBytes5 } from "crypto";
@@ -6628,7 +7570,7 @@ var SlackListenGrantStore = class {
6628
7570
  };
6629
7571
  function thisModuleFile2() {
6630
7572
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
6631
- return cjsFile || process.argv[1] || join5(process.cwd(), "package.json");
7573
+ return cjsFile || process.argv[1] || join6(process.cwd(), "package.json");
6632
7574
  }
6633
7575
  function openDatabase2(filePath) {
6634
7576
  const req = createRequire2(thisModuleFile2());
@@ -7629,16 +8571,16 @@ var RemoteHub = class {
7629
8571
  };
7630
8572
 
7631
8573
  // src/relay/accounts.ts
7632
- import { createHash as createHash3, randomBytes as randomBytes9, randomUUID as randomUUID3, timingSafeEqual as timingSafeEqual3 } from "crypto";
7633
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync3, realpathSync } from "fs";
8574
+ import { createHash as createHash3, randomBytes as randomBytes9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual3 } from "crypto";
8575
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, realpathSync } from "fs";
7634
8576
  import { createRequire as createRequire3 } from "module";
7635
- import { dirname as dirname3, join as join6 } from "path";
8577
+ import { dirname as dirname3, join as join7 } from "path";
7636
8578
  var GITHUB_ACCOUNT_ISSUER = "https://github.com";
7637
8579
  var CURSOR_ACCOUNT_ISSUER = "https://api.cursor.com/v1/origin";
7638
8580
  var RELAY_DEVICE_CAP = 3;
7639
8581
  function thisModuleFile3() {
7640
8582
  const cjsFile = typeof __filename !== "undefined" ? __filename : "";
7641
- return cjsFile || process.argv[1] || join6(process.cwd(), "package.json");
8583
+ return cjsFile || process.argv[1] || join7(process.cwd(), "package.json");
7642
8584
  }
7643
8585
  function openDatabase3(filePath) {
7644
8586
  const req = createRequire3(thisModuleFile3());
@@ -7676,7 +8618,7 @@ function assertRelayAccountsDurable(filePath) {
7676
8618
  if (process.env.NODE_ENV !== "production") return;
7677
8619
  if (process.platform !== "linux") return;
7678
8620
  const dir = realpathSync(dirname3(filePath));
7679
- const mounts = readFileSync3("/proc/mounts", "utf8");
8621
+ const mounts = readFileSync4("/proc/mounts", "utf8");
7680
8622
  const point = longestMountPoint(dir, mounts);
7681
8623
  if (point === "/") {
7682
8624
  throw new Error(
@@ -7759,7 +8701,7 @@ var RelayAccountStore = class {
7759
8701
  this.insertIdentity(issuer, subject, accountId, email, verified);
7760
8702
  } else {
7761
8703
  const byEmail = verified ? this.accountIdForVerifiedEmail(email) : void 0;
7762
- accountId = byEmail ?? randomUUID3();
8704
+ accountId = byEmail ?? randomUUID4();
7763
8705
  if (!byEmail) {
7764
8706
  this.db.prepare("INSERT INTO accounts (id, created_at, device_cap) VALUES (?, ?, ?)").run(accountId, Date.now(), RELAY_DEVICE_CAP);
7765
8707
  }
@@ -8295,7 +9237,7 @@ async function handleRelayAccountHttp(opts) {
8295
9237
  if (providerError || !credential) {
8296
9238
  const message = providerError || "Sign-in was cancelled.";
8297
9239
  opts.sessions.putResult(state, { ok: false, error: message });
8298
- sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
9240
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml3(message)}</p>`);
8299
9241
  return true;
8300
9242
  }
8301
9243
  const client = opts.oauth[pending.provider];
@@ -8330,7 +9272,7 @@ async function handleRelayAccountHttp(opts) {
8330
9272
  } catch (err) {
8331
9273
  const message = err instanceof Error ? err.message : String(err);
8332
9274
  opts.sessions.putResult(state, { ok: false, error: message });
8333
- sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml2(message)}</p>`);
9275
+ sendHtml2(opts.res, 400, "Sideboard", `<h1>Could not sign in</h1><p>${escapeHtml3(message)}</p>`);
8334
9276
  }
8335
9277
  return true;
8336
9278
  }
@@ -8752,7 +9694,7 @@ async function startHeadlessHost(opts) {
8752
9694
  };
8753
9695
  const refreshRunning = async () => {
8754
9696
  try {
8755
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
9697
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-NOQDMYLB.js");
8756
9698
  agentsRunning = getOrchestrator2().getRuntime().running;
8757
9699
  } catch {
8758
9700
  agentsRunning = 0;
@@ -9009,7 +9951,7 @@ function buildDiffCommentAttachment(input) {
9009
9951
  }
9010
9952
 
9011
9953
  // src/composer/pasted-text.ts
9012
- import { randomUUID as randomUUID4 } from "crypto";
9954
+ import { randomUUID as randomUUID5 } from "crypto";
9013
9955
  var PASTE_ATTACH_MIN_CHARS = 1200;
9014
9956
  var PASTE_ATTACH_MIN_LINES = 15;
9015
9957
  var PASTED_NAME_RE = /^Pasted text #(\d+)\.txt$/i;
@@ -9036,7 +9978,7 @@ function nextPastedTextName(existing) {
9036
9978
  }
9037
9979
  function buildPastedTextAttachment(text5, opts) {
9038
9980
  return {
9039
- id: opts?.id ?? randomUUID4(),
9981
+ id: opts?.id ?? randomUUID5(),
9040
9982
  name: opts?.name ?? "Pasted text #1.txt",
9041
9983
  kind: "file",
9042
9984
  path: opts?.path,
@@ -9117,8 +10059,8 @@ function createClippedMcpServer() {
9117
10059
  }
9118
10060
 
9119
10061
  // src/mcp/server.ts
9120
- import { z as z8 } from "zod";
9121
- import { randomUUID as randomUUID7 } from "crypto";
10062
+ import { z as z9 } from "zod";
10063
+ import { randomUUID as randomUUID8 } from "crypto";
9122
10064
  import { basename as basename3 } from "path";
9123
10065
 
9124
10066
  // src/mcp/run-script-ref.ts
@@ -10735,8 +11677,297 @@ function registerScheduleTools(server) {
10735
11677
  );
10736
11678
  }
10737
11679
 
11680
+ // src/mcp/order-tools.ts
11681
+ import { z as z8 } from "zod";
11682
+ var kindSchema = z8.enum(["pr", "issue", "workspace", "orchestration"]);
11683
+ function callerThread() {
11684
+ const id = process.env[SIDEBOARD_THREAD_ID_ENV]?.trim();
11685
+ if (!id) return null;
11686
+ return readThread(id);
11687
+ }
11688
+ function readCheckoutPlan(caller) {
11689
+ if (!caller) return null;
11690
+ if (caller.sourceType === "orchestration" || caller.repoPath === GLOBAL_WORKSPACE_ID) return null;
11691
+ const root = caller.worktreePath?.trim();
11692
+ if (!root) return null;
11693
+ return readPlanFile(root);
11694
+ }
11695
+ function orchestrationOwnerId(worktree) {
11696
+ const caller = callerThread();
11697
+ if (!caller) {
11698
+ throw new Error(
11699
+ worktree ? "No worktree chat is bound to this tool." : "No orchestration chat is bound to this tool."
11700
+ );
11701
+ }
11702
+ if (!worktree) return caller.id;
11703
+ let current = caller.parentThreadId?.trim() || "";
11704
+ const seen = /* @__PURE__ */ new Set([caller.id]);
11705
+ for (let hop = 0; hop < 6 && current && !seen.has(current); hop++) {
11706
+ seen.add(current);
11707
+ const row2 = readThread(current);
11708
+ if (!row2) break;
11709
+ if (row2.sourceType === "orchestration" || row2.repoPath === GLOBAL_WORKSPACE_ID) return row2.id;
11710
+ current = row2.parentThreadId?.trim() || "";
11711
+ }
11712
+ throw new Error("This checkout is not connected to an orchestration chat.");
11713
+ }
11714
+ function targetFrom(kind, ref, repoPath, label) {
11715
+ return {
11716
+ kind: parseOrderKind(kind),
11717
+ ref: ref.trim(),
11718
+ ...repoPath?.trim() ? { repoPath: repoPath.trim() } : {},
11719
+ ...label?.trim() ? { label: label.trim() } : {}
11720
+ };
11721
+ }
11722
+ function registerOrderTools(server) {
11723
+ const worktree = sideboardMcpProfile() === "worktree";
11724
+ server.tool(
11725
+ "list_order",
11726
+ worktree ? "Read where this checkout sits in its orchestrator's plan: what you are waiting on, what is clear, and what you are blocking. Call show_plan when the user should see it. Change your step with set_dependency or clear_dependency." : "Read this chat's plan. Call show_plan when the user should see it. Draft with set_plan and set_dependency, revise from their feedback, then execute_plan only after they agree. Do not start planned work while the plan is draft.",
11727
+ {},
11728
+ async () => {
11729
+ try {
11730
+ const owner = orchestrationOwnerId(worktree);
11731
+ const plan = getOrderPlan(owner);
11732
+ const caller = callerThread();
11733
+ if (!plan) {
11734
+ const text5 = 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.";
11735
+ return { content: [{ type: "text", text: text5 }] };
11736
+ }
11737
+ const rows = listOrderRows(plan.id);
11738
+ const place = worktree && caller ? `${formatOrderPlace(rows, orderSnapshotFromThread(caller))}
11739
+
11740
+ ` : "";
11741
+ return {
11742
+ content: [{ type: "text", text: `${place}${formatOrderText(rows, plan)}` }]
11743
+ };
11744
+ } catch (err) {
11745
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11746
+ }
11747
+ }
11748
+ );
11749
+ server.tool(
11750
+ "set_dependency",
11751
+ 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.",
11752
+ {
11753
+ waitsOnKind: kindSchema.describe("What must happen first: pr, issue, workspace, or orchestration"),
11754
+ waitsOnRef: z8.string().describe("PR number (12), issue id (ENG-4), or workspace chat id / worktree path"),
11755
+ waitsOnRepoPath: z8.string().optional().describe("Project path when a PR or issue number is not unique"),
11756
+ waitsOnLabel: z8.string().optional().describe("Short label on the planner"),
11757
+ gate: z8.enum(["in-main", "in-prod"]).describe("in-main: merged to the default branch. in-prod: deployed; mark with satisfy_dependency"),
11758
+ hold: z8.enum(["start", "merge"]).describe("start: subject cannot begin. merge: subject cannot merge"),
11759
+ subjectKind: kindSchema.optional().describe("What is held. Required from orchestration. Omit on a worktree to mean this checkout."),
11760
+ subjectRef: z8.string().optional().describe("PR number, issue id, or workspace ref for the subject"),
11761
+ subjectRepoPath: z8.string().optional(),
11762
+ subjectLabel: z8.string().optional(),
11763
+ note: z8.string().optional().describe("Why this order matters")
11764
+ },
11765
+ async (args) => {
11766
+ try {
11767
+ const hasKind = Boolean(args.subjectKind);
11768
+ const hasRef = Boolean(args.subjectRef?.trim());
11769
+ if (hasKind !== hasRef) {
11770
+ throw new Error("Pass subjectKind and subjectRef together, or omit both on a worktree.");
11771
+ }
11772
+ const caller = callerThread();
11773
+ let subject;
11774
+ const hold = parseOrderHold(args.hold);
11775
+ if (!hasKind) {
11776
+ if (!worktree) {
11777
+ throw new Error(
11778
+ "Pass subjectKind and subjectRef. A worktree agent can omit them to mean this checkout."
11779
+ );
11780
+ }
11781
+ if (!caller) throw new Error("No worktree chat is bound to this tool.");
11782
+ subject = defaultOrderSubject(orderSnapshotFromThread(caller), hold);
11783
+ } else {
11784
+ subject = targetFrom(
11785
+ args.subjectKind,
11786
+ args.subjectRef,
11787
+ args.subjectRepoPath,
11788
+ args.subjectLabel
11789
+ );
11790
+ if (worktree) {
11791
+ if (!caller) throw new Error("No worktree chat is bound to this tool.");
11792
+ assertCallerOwnsSubject(orderSnapshotFromThread(caller), subject);
11793
+ }
11794
+ }
11795
+ const result = setOrderDependency({
11796
+ waitsOn: targetFrom(
11797
+ args.waitsOnKind,
11798
+ args.waitsOnRef,
11799
+ args.waitsOnRepoPath,
11800
+ args.waitsOnLabel
11801
+ ),
11802
+ gate: parseOrderGate(args.gate),
11803
+ subject,
11804
+ hold,
11805
+ note: args.note,
11806
+ createdByThreadId: caller?.id ?? null,
11807
+ ownerThreadId: orchestrationOwnerId(worktree)
11808
+ });
11809
+ return mcpJson({
11810
+ created: result.created,
11811
+ id: result.edge.id,
11812
+ gate: result.edge.gate,
11813
+ hold: result.edge.hold,
11814
+ waitsOn: result.edge.waitsOn,
11815
+ subject: result.edge.subject
11816
+ });
11817
+ } catch (err) {
11818
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11819
+ }
11820
+ }
11821
+ );
11822
+ if (!worktree) {
11823
+ server.tool(
11824
+ "set_plan",
11825
+ "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.",
11826
+ {
11827
+ title: z8.string().describe("Short name for the plan"),
11828
+ summary: z8.string().optional().describe("What this order is for, in a sentence or two"),
11829
+ goal: z8.string().optional().describe("Outcome the steps are trying to reach")
11830
+ },
11831
+ async ({ title, summary, goal }) => {
11832
+ try {
11833
+ const plan = setOrderPlan({
11834
+ title,
11835
+ summary,
11836
+ goal,
11837
+ ownerThreadId: orchestrationOwnerId(false)
11838
+ });
11839
+ return mcpJson({ ok: true, ...plan });
11840
+ } catch (err) {
11841
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11842
+ }
11843
+ }
11844
+ );
11845
+ server.tool(
11846
+ "execute_plan",
11847
+ "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.",
11848
+ {
11849
+ agreed: z8.literal(true).describe("True only after the user has seen the plan and told you to run it")
11850
+ },
11851
+ async () => {
11852
+ try {
11853
+ const result = executeOrderPlan(orchestrationOwnerId(false));
11854
+ const brief = (row2) => ({
11855
+ id: row2.id,
11856
+ hold: row2.hold,
11857
+ gate: row2.gate,
11858
+ waitsOn: row2.waitsOnLabel,
11859
+ subject: row2.subjectLabel,
11860
+ detail: row2.detail,
11861
+ ...row2.loop ? { loop: true } : {}
11862
+ });
11863
+ return mcpJson({
11864
+ ok: true,
11865
+ status: result.plan.status,
11866
+ title: result.plan.title,
11867
+ ready: result.ready.map(brief),
11868
+ waiting: result.waiting.map(brief),
11869
+ message: "Plan is active. Start ready steps with create_workspace or send_to_chat. Leave waiting steps alone. Merge only if the user asked."
11870
+ });
11871
+ } catch (err) {
11872
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11873
+ }
11874
+ }
11875
+ );
11876
+ }
11877
+ server.tool(
11878
+ "show_plan",
11879
+ 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.",
11880
+ {},
11881
+ async () => {
11882
+ const caller = callerThread();
11883
+ let diagramHtml = null;
11884
+ let diagramTitle = "Planner";
11885
+ let diagramError = null;
11886
+ try {
11887
+ const owner = orchestrationOwnerId(worktree);
11888
+ const plan = getOrderPlan(owner);
11889
+ diagramTitle = plan?.title || "Planner";
11890
+ diagramHtml = formatWaterfallHtml(plan ? listWaterfall(plan.id) : [], {
11891
+ plan,
11892
+ you: caller ? orderSnapshotFromThread(caller) : null
11893
+ });
11894
+ } catch (err) {
11895
+ diagramError = err instanceof Error ? err.message : String(err);
11896
+ }
11897
+ const artifacts = showPlanDocuments({
11898
+ diagramTitle,
11899
+ diagramHtml,
11900
+ checkoutMarkdown: readCheckoutPlan(caller)
11901
+ });
11902
+ if (!artifacts.length) {
11903
+ return mcpJson({ error: diagramError || "Nothing to show." }, true);
11904
+ }
11905
+ const primary = artifacts.find((doc) => doc.artifact_id === "plan") ?? artifacts[0];
11906
+ return mcpJson({
11907
+ ok: true,
11908
+ title: primary.title,
11909
+ type: primary.type,
11910
+ artifact_id: primary.artifact_id,
11911
+ content: primary.content,
11912
+ artifacts,
11913
+ message: showPlanMessage(artifacts, worktree)
11914
+ });
11915
+ }
11916
+ );
11917
+ server.tool(
11918
+ "clear_dependency",
11919
+ 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.",
11920
+ { id: z8.string().describe("Step id from list_order") },
11921
+ async ({ id }) => {
11922
+ try {
11923
+ const caller = callerThread();
11924
+ clearOrderDependency(
11925
+ id,
11926
+ worktree && caller ? orderSnapshotFromThread(caller) : null,
11927
+ orchestrationOwnerId(worktree)
11928
+ );
11929
+ return mcpJson({ ok: true, id });
11930
+ } catch (err) {
11931
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11932
+ }
11933
+ }
11934
+ );
11935
+ server.tool(
11936
+ "satisfy_dependency",
11937
+ "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.",
11938
+ {
11939
+ id: z8.string().describe("Step id from list_order"),
11940
+ satisfied: z8.boolean().optional().describe("false clears the manual mark. Default true.")
11941
+ },
11942
+ async ({ id, satisfied }) => {
11943
+ try {
11944
+ const owner = orchestrationOwnerId(worktree);
11945
+ const plan = getOrderPlan(owner);
11946
+ if (!plan) throw new Error("set_plan first. This chat has no plan yet.");
11947
+ const rows = listOrderRows(plan.id);
11948
+ const hit = rows.find((row2) => row2.id === id || id.length >= 8 && row2.id.startsWith(id));
11949
+ if (!hit) throw new Error("That step is on another orchestration chat's plan.");
11950
+ const caller = callerThread();
11951
+ if (worktree && caller && !orderEdgeTouches(hit, orderSnapshotFromThread(caller))) {
11952
+ throw new Error("This checkout can only change a step it is part of.");
11953
+ }
11954
+ const edge = satisfyOrderDependency(id, satisfied !== false);
11955
+ return mcpJson({
11956
+ ok: true,
11957
+ id: edge.id,
11958
+ satisfied: satisfied !== false,
11959
+ gate: edge.gate,
11960
+ waitsOn: edge.waitsOn
11961
+ });
11962
+ } catch (err) {
11963
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
11964
+ }
11965
+ }
11966
+ );
11967
+ }
11968
+
10738
11969
  // src/agent-rpc/handlers.ts
10739
- import { randomUUID as randomUUID5 } from "crypto";
11970
+ import { randomUUID as randomUUID6 } from "crypto";
10740
11971
  import { isAbsolute } from "path";
10741
11972
 
10742
11973
  // src/agent-rpc/permission-handler.ts
@@ -10812,7 +12043,7 @@ var handlePermissionAsk = async (params, _ctx) => {
10812
12043
 
10813
12044
  // src/agent-rpc/handlers.ts
10814
12045
  function presentArtifactResult(input) {
10815
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${randomUUID5().slice(0, 8)}`;
12046
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${randomUUID6().slice(0, 8)}`;
10816
12047
  return {
10817
12048
  ok: true,
10818
12049
  artifact_id: id,
@@ -10903,7 +12134,7 @@ async function handleJobStop(params, _ctx) {
10903
12134
  return stopDetachedJob(jobCwd(rec), id, reason ? { reason } : void 0);
10904
12135
  }
10905
12136
  async function defaultTurnWait(ref, timeoutMs) {
10906
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
12137
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-NOQDMYLB.js");
10907
12138
  const orch = getOrchestrator2();
10908
12139
  const thread = await orch.waitForTurn(ref, timeoutMs, {
10909
12140
  resolveIfStillRunning: true
@@ -10965,23 +12196,23 @@ function createAgentRpcDispatcher() {
10965
12196
  }
10966
12197
 
10967
12198
  // src/board/load-home-board.ts
10968
- import { existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
10969
- import { join as join8 } from "path";
12199
+ import { existsSync as existsSync4, mkdirSync as mkdirSync6, readFileSync as readFileSync6, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "fs";
12200
+ import { join as join9 } from "path";
10970
12201
 
10971
12202
  // src/board/board-pins.ts
10972
- import { randomUUID as randomUUID6 } from "crypto";
10973
- import { existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync4, unlinkSync as unlinkSync2, writeFileSync } from "fs";
10974
- import { join as join7 } from "path";
12203
+ import { randomUUID as randomUUID7 } from "crypto";
12204
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync5, unlinkSync as unlinkSync2, writeFileSync } from "fs";
12205
+ import { join as join8 } from "path";
10975
12206
  var FILE = "home-board-pins.json";
10976
12207
  var VERSION2 = 1;
10977
12208
  function pinsFile() {
10978
- return join7(appDataDir(), FILE);
12209
+ return join8(appDataDir(), FILE);
10979
12210
  }
10980
12211
  function readDisk() {
10981
12212
  const path2 = pinsFile();
10982
- if (!existsSync2(path2)) return [];
12213
+ if (!existsSync3(path2)) return [];
10983
12214
  try {
10984
- const raw = JSON.parse(readFileSync4(path2, "utf8"));
12215
+ const raw = JSON.parse(readFileSync5(path2, "utf8"));
10985
12216
  if (raw?.version !== VERSION2 || !Array.isArray(raw.items)) return [];
10986
12217
  return raw.items.filter((item) => item?.id && item.kind && item.ref);
10987
12218
  } catch {
@@ -10999,7 +12230,7 @@ function addBoardPin(input) {
10999
12230
  const ref = input.ref.trim();
11000
12231
  if (!ref) throw new Error("Board item needs a ref");
11001
12232
  const pin = {
11002
- id: randomUUID6(),
12233
+ id: randomUUID7(),
11003
12234
  kind: input.kind,
11004
12235
  ref,
11005
12236
  repoPath: input.repoPath.trim(),
@@ -11058,7 +12289,7 @@ function homeBoardWorkspaceKey(workspaces) {
11058
12289
  return workspaces.map((w) => w.path).filter(Boolean).sort().join("\n");
11059
12290
  }
11060
12291
  function cacheFile() {
11061
- return join8(appDataDir(), "home-board-cache.json");
12292
+ return join9(appDataDir(), "home-board-cache.json");
11062
12293
  }
11063
12294
  function emptyInputs() {
11064
12295
  return {
@@ -11084,9 +12315,9 @@ function shouldCacheHomeBoardInputs(inputs) {
11084
12315
  }
11085
12316
  function readDiskCache() {
11086
12317
  const path2 = cacheFile();
11087
- if (!existsSync3(path2)) return null;
12318
+ if (!existsSync4(path2)) return null;
11088
12319
  try {
11089
- const raw = JSON.parse(readFileSync5(path2, "utf8"));
12320
+ const raw = JSON.parse(readFileSync6(path2, "utf8"));
11090
12321
  if (raw?.version !== CACHE_VERSION || typeof raw.fetchedAt !== "number") {
11091
12322
  return null;
11092
12323
  }
@@ -11338,18 +12569,18 @@ async function startMcpServer() {
11338
12569
  );
11339
12570
  server.tool(
11340
12571
  "list_board",
11341
- "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 columns. 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.",
12572
+ "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.",
11342
12573
  {
11343
- query: z8.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
11344
- repoPath: z8.string().optional().describe("Limit to one project path from list_projects"),
11345
- kind: z8.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
11346
- ownership: z8.enum(["all", "mine", "reviewing"]).optional().describe(
12574
+ query: z9.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
12575
+ repoPath: z9.string().optional().describe("Limit to one project path from list_projects"),
12576
+ kind: z9.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
12577
+ ownership: z9.enum(["all", "mine", "reviewing"]).optional().describe(
11347
12578
  "Mine = PRs you authored or local WIP; reviewing = someone else's PR. Uses the gh login."
11348
12579
  ),
11349
- column: z8.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
12580
+ column: z9.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
11350
12581
  "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."
11351
12582
  ),
11352
- limit: z8.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
12583
+ limit: z9.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
11353
12584
  },
11354
12585
  async ({ query, repoPath, kind, ownership, column, limit }) => {
11355
12586
  const workspaces = orch.listWorkspaces();
@@ -11379,7 +12610,7 @@ async function startMcpServer() {
11379
12610
  server.tool(
11380
12611
  "get_chat",
11381
12612
  "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).",
11382
- { ref: z8.string() },
12613
+ { ref: z9.string() },
11383
12614
  async ({ ref }) => {
11384
12615
  const t = orch.getThread(ref);
11385
12616
  if (!t) {
@@ -11426,17 +12657,17 @@ async function startMcpServer() {
11426
12657
  "present_artifact",
11427
12658
  "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.",
11428
12659
  {
11429
- title: z8.string().describe("Short title shown in the artifact pane header"),
11430
- type: z8.enum(["html", "svg", "markdown", "react", "log"]).describe(
12660
+ title: z9.string().describe("Short title shown in the artifact pane header"),
12661
+ type: z9.enum(["html", "svg", "markdown", "react", "log"]).describe(
11431
12662
  "html/svg/markdown/react replace the pane. log appends content to the same artifact_id (new lines only)."
11432
12663
  ),
11433
- content: z8.string().describe(
12664
+ content: z9.string().describe(
11434
12665
  "html/svg/markdown/react: full document. log: only the new lines since the last call (empty is ok for a status-only update)."
11435
12666
  ),
11436
- artifact_id: z8.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
11437
- status: z8.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
11438
- phase: z8.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
11439
- mode: z8.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
12667
+ artifact_id: z9.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
12668
+ status: z9.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
12669
+ phase: z9.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
12670
+ mode: z9.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
11440
12671
  },
11441
12672
  async ({ title, type, artifact_id, status, phase, mode }) => {
11442
12673
  return mcpJson(
@@ -11449,15 +12680,15 @@ async function startMcpServer() {
11449
12680
  "ask_user",
11450
12681
  "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.",
11451
12682
  {
11452
- questions: z8.array(
11453
- z8.object({
11454
- question: z8.string().describe("Full question text ending with ?"),
11455
- header: z8.string().max(24).optional().describe("Short label shown above the question"),
11456
- multiSelect: z8.boolean().optional().describe("Allow selecting multiple options"),
11457
- options: z8.array(
11458
- z8.object({
11459
- label: z8.string(),
11460
- description: z8.string().optional().describe("What this option means / when to choose it (strongly preferred)")
12683
+ questions: z9.array(
12684
+ z9.object({
12685
+ question: z9.string().describe("Full question text ending with ?"),
12686
+ header: z9.string().max(24).optional().describe("Short label shown above the question"),
12687
+ multiSelect: z9.boolean().optional().describe("Allow selecting multiple options"),
12688
+ options: z9.array(
12689
+ z9.object({
12690
+ label: z9.string(),
12691
+ description: z9.string().optional().describe("What this option means / when to choose it (strongly preferred)")
11461
12692
  })
11462
12693
  ).min(2).max(6).describe("2\u20136 choices (Sideboard also offers Other)")
11463
12694
  })
@@ -11483,9 +12714,9 @@ async function startMcpServer() {
11483
12714
  "present_plan",
11484
12715
  PRESENT_PLAN_TOOL_DESCRIPTION,
11485
12716
  {
11486
- title: z8.string().optional().describe("Short plan title (defaults to Plan)"),
11487
- content: z8.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
11488
- thread_id: z8.string().optional().describe("Sideboard thread id when cwd is not the worktree")
12717
+ title: z9.string().optional().describe("Short plan title (defaults to Plan)"),
12718
+ content: z9.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
12719
+ thread_id: z9.string().optional().describe("Sideboard thread id when cwd is not the worktree")
11489
12720
  },
11490
12721
  async ({ title, content, thread_id }) => {
11491
12722
  const { writePlanFile: writePlanFile2 } = await import("./plan-file-7MMIPV7Y.js");
@@ -11514,15 +12745,15 @@ async function startMcpServer() {
11514
12745
  "present_schema",
11515
12746
  "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.",
11516
12747
  {
11517
- title: z8.string().describe("Pane title"),
11518
- mode: z8.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
11519
- datasource: z8.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
11520
- resource_id: z8.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
11521
- record_id: z8.string().optional().describe("Record id when opening form mode"),
11522
- resource: z8.record(z8.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
11523
- record: z8.record(z8.unknown()).optional().describe("Inline record { id, data, published_at? }"),
11524
- records: z8.array(z8.record(z8.unknown())).optional().describe("Inline records for table mode"),
11525
- pane_id: z8.string().optional().describe("Stable pane id across updates")
12748
+ title: z9.string().describe("Pane title"),
12749
+ mode: z9.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
12750
+ datasource: z9.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
12751
+ resource_id: z9.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
12752
+ record_id: z9.string().optional().describe("Record id when opening form mode"),
12753
+ resource: z9.record(z9.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
12754
+ record: z9.record(z9.unknown()).optional().describe("Inline record { id, data, published_at? }"),
12755
+ records: z9.array(z9.record(z9.unknown())).optional().describe("Inline records for table mode"),
12756
+ pane_id: z9.string().optional().describe("Stable pane id across updates")
11526
12757
  },
11527
12758
  async (args) => {
11528
12759
  const id = args.pane_id?.trim() || `schema_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -11543,10 +12774,10 @@ async function startMcpServer() {
11543
12774
  "present_files",
11544
12775
  "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.",
11545
12776
  {
11546
- title: z8.string().optional().describe("Pane title (default: Files)"),
11547
- datasource: z8.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
11548
- path: z8.string().optional().describe("Initial folder path (e.g. public)"),
11549
- pane_id: z8.string().optional().describe("Stable pane id across updates")
12777
+ title: z9.string().optional().describe("Pane title (default: Files)"),
12778
+ datasource: z9.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
12779
+ path: z9.string().optional().describe("Initial folder path (e.g. public)"),
12780
+ pane_id: z9.string().optional().describe("Stable pane id across updates")
11550
12781
  },
11551
12782
  async (args) => {
11552
12783
  const id = args.pane_id?.trim() || `files_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -11566,8 +12797,8 @@ async function startMcpServer() {
11566
12797
  "wait_for_job",
11567
12798
  "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.",
11568
12799
  {
11569
- id: z8.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
11570
- timeoutMs: z8.number().optional()
12800
+ id: z9.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
12801
+ timeoutMs: z9.number().optional()
11571
12802
  },
11572
12803
  async ({ id, timeoutMs }) => {
11573
12804
  const result = await waitForDetachedJob(process.cwd(), id, {
@@ -11580,8 +12811,8 @@ async function startMcpServer() {
11580
12811
  "stop_job",
11581
12812
  "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.",
11582
12813
  {
11583
- id: z8.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
11584
- reason: z8.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
12814
+ id: z9.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
12815
+ reason: z9.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
11585
12816
  },
11586
12817
  async ({ id, reason }) => {
11587
12818
  const result = await stopDetachedJob(process.cwd(), id, { reason });
@@ -11593,7 +12824,7 @@ async function startMcpServer() {
11593
12824
  "list_run_scripts",
11594
12825
  "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).",
11595
12826
  {
11596
- ref: z8.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
12827
+ ref: z9.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
11597
12828
  },
11598
12829
  async ({ ref }) => {
11599
12830
  try {
@@ -11623,8 +12854,8 @@ async function startMcpServer() {
11623
12854
  "run_dev_script",
11624
12855
  "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.",
11625
12856
  {
11626
- ref: z8.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
11627
- name: z8.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
12857
+ ref: z9.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
12858
+ name: z9.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
11628
12859
  },
11629
12860
  async ({ ref, name }) => {
11630
12861
  try {
@@ -11652,8 +12883,8 @@ async function startMcpServer() {
11652
12883
  "stop_dev_script",
11653
12884
  "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).",
11654
12885
  {
11655
- ref: z8.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
11656
- name: z8.string().optional().describe("Script name to stop; omit to stop all active scripts.")
12886
+ ref: z9.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
12887
+ name: z9.string().optional().describe("Script name to stop; omit to stop all active scripts.")
11657
12888
  },
11658
12889
  async ({ ref, name }) => {
11659
12890
  try {
@@ -11670,9 +12901,9 @@ async function startMcpServer() {
11670
12901
  "get_run_log",
11671
12902
  "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.",
11672
12903
  {
11673
- ref: z8.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
11674
- name: z8.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
11675
- tail: z8.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
12904
+ ref: z9.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
12905
+ name: z9.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
12906
+ tail: z9.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
11676
12907
  `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.`
11677
12908
  )
11678
12909
  },
@@ -11735,8 +12966,8 @@ async function startMcpServer() {
11735
12966
  "notify_orchestrator",
11736
12967
  "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.",
11737
12968
  {
11738
- message: z8.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
11739
- reason: z8.enum(["input-required", "blocked"]).optional().describe(
12969
+ message: z9.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
12970
+ reason: z9.enum(["input-required", "blocked"]).optional().describe(
11740
12971
  "input-required = waiting on the user in this chat; blocked = need the coordinator (default)."
11741
12972
  )
11742
12973
  },
@@ -11769,15 +13000,16 @@ async function startMcpServer() {
11769
13000
  );
11770
13001
  }
11771
13002
  registerScheduleTools(server);
13003
+ registerOrderTools(server);
11772
13004
  server.tool(
11773
13005
  "set_workspace_tags",
11774
13006
  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.",
11775
13007
  {
11776
- ref: z8.string().optional().describe(
13008
+ ref: z9.string().optional().describe(
11777
13009
  worktreeProfile ? "Omit for this chat. Another chat id only if it is on this same checkout." : "Chat id on the workspace to label."
11778
13010
  ),
11779
- tags: z8.union([z8.string(), z8.array(z8.string())]).describe("Labels to set. A string may be comma-separated."),
11780
- mode: z8.enum(["replace", "add", "remove"]).optional()
13011
+ tags: z9.union([z9.string(), z9.array(z9.string())]).describe("Labels to set. A string may be comma-separated."),
13012
+ mode: z9.enum(["replace", "add", "remove"]).optional()
11781
13013
  },
11782
13014
  async ({ ref, tags, mode }) => {
11783
13015
  try {
@@ -11811,7 +13043,7 @@ async function startMcpServer() {
11811
13043
  "set_caffeinate",
11812
13044
  "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.",
11813
13045
  {
11814
- enabled: z8.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
13046
+ enabled: z9.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
11815
13047
  },
11816
13048
  async ({ enabled }) => {
11817
13049
  const threadId = process.env.SIDEBOARD_ORCHESTRATOR_THREAD_ID?.trim() || null;
@@ -11837,24 +13069,24 @@ async function startMcpServer() {
11837
13069
  "create_workspace",
11838
13070
  `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.`,
11839
13071
  {
11840
- sourceType: z8.enum(["branch", "pr", "ticket"]),
11841
- sourceRef: z8.string(),
11842
- agent: z8.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
13072
+ sourceType: z9.enum(["branch", "pr", "ticket"]),
13073
+ sourceRef: z9.string(),
13074
+ agent: z9.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
11843
13075
  `Usually omit. Sideboard uses Account default agent (${accountDefaults.agent}). Passing your own agent or cursor is ignored.`
11844
13076
  ),
11845
- model: z8.string().nullable().optional().describe(
13077
+ model: z9.string().nullable().optional().describe(
11846
13078
  `Usually omit to use Account default model (${accountDefaults.model?.trim() || "Auto"}). Pass null only to force Auto / agent-default.`
11847
13079
  ),
11848
- repoPath: z8.string(),
11849
- title: z8.string().optional(),
11850
- cowboy: z8.boolean().optional().describe(
13080
+ repoPath: z9.string(),
13081
+ title: z9.string().optional(),
13082
+ cowboy: z9.boolean().optional().describe(
11851
13083
  "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."
11852
13084
  ),
11853
- parentChatId: z8.string().optional().describe(
13085
+ parentChatId: z9.string().optional().describe(
11854
13086
  "Orchestration: omit (preferred) or pass YOUR chat id from the turn reminder / AGENTS.md. Do not invent uuids."
11855
13087
  ),
11856
- parentThreadId: z8.string().optional().describe("Legacy alias for parentChatId."),
11857
- tags: z8.union([z8.string(), z8.array(z8.string())]).optional().describe(
13088
+ parentThreadId: z9.string().optional().describe("Legacy alias for parentChatId."),
13089
+ tags: z9.union([z9.string(), z9.array(z9.string())]).optional().describe(
11858
13090
  "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."
11859
13091
  )
11860
13092
  },
@@ -11870,11 +13102,11 @@ async function startMcpServer() {
11870
13102
  "start_board_card",
11871
13103
  "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.",
11872
13104
  {
11873
- kind: z8.enum(["ticket", "pr", "branch"]),
11874
- ref: z8.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
11875
- repoPath: z8.string().describe("Project path from list_projects / list_board"),
11876
- title: z8.string().optional(),
11877
- tags: z8.union([z8.string(), z8.array(z8.string())]).optional().describe(
13105
+ kind: z9.enum(["ticket", "pr", "branch"]),
13106
+ ref: z9.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
13107
+ repoPath: z9.string().describe("Project path from list_projects / list_board"),
13108
+ title: z9.string().optional(),
13109
+ tags: z9.union([z9.string(), z9.array(z9.string())]).optional().describe(
11878
13110
  "Short labels for this workspace. Same tags on every checkout for one task. Added when the checkout already exists."
11879
13111
  )
11880
13112
  },
@@ -11930,7 +13162,7 @@ async function startMcpServer() {
11930
13162
  const ident = issue?.identifier ?? ref.trim();
11931
13163
  const attachments = issue ? [
11932
13164
  {
11933
- id: randomUUID7(),
13165
+ id: randomUUID8(),
11934
13166
  name: issue.identifier,
11935
13167
  kind: "issue",
11936
13168
  content: [
@@ -11979,9 +13211,9 @@ async function startMcpServer() {
11979
13211
  "send_to_chat",
11980
13212
  '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.',
11981
13213
  {
11982
- ref: z8.string(),
11983
- prompt: z8.string(),
11984
- force_stop: z8.boolean().optional()
13214
+ ref: z9.string(),
13215
+ prompt: z9.string(),
13216
+ force_stop: z9.boolean().optional()
11985
13217
  },
11986
13218
  async ({ ref, prompt, force_stop }) => {
11987
13219
  if (force_stop) {
@@ -12006,8 +13238,8 @@ async function startMcpServer() {
12006
13238
  "wait_for_turn",
12007
13239
  "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).",
12008
13240
  {
12009
- ref: z8.string(),
12010
- timeoutMs: z8.number().optional()
13241
+ ref: z9.string(),
13242
+ timeoutMs: z9.number().optional()
12011
13243
  },
12012
13244
  async ({ ref, timeoutMs }) => {
12013
13245
  const thread = await orch.waitForTurn(ref, mcpWaitForTurnTimeoutMs(timeoutMs), {
@@ -12035,7 +13267,7 @@ async function startMcpServer() {
12035
13267
  server.tool(
12036
13268
  "get_turn_result",
12037
13269
  "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).",
12038
- { ref: z8.string() },
13270
+ { ref: z9.string() },
12039
13271
  async ({ ref }) => {
12040
13272
  const result = orch.getTurnResult(ref);
12041
13273
  const hint = mcpWaitTaskHint(result.taskState, result.status, result.blockedReason);
@@ -12051,9 +13283,9 @@ async function startMcpServer() {
12051
13283
  "stop_chat",
12052
13284
  "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.",
12053
13285
  {
12054
- ref: z8.string(),
12055
- force: z8.boolean().optional(),
12056
- reason: z8.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
13286
+ ref: z9.string(),
13287
+ force: z9.boolean().optional(),
13288
+ reason: z9.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
12057
13289
  },
12058
13290
  async ({ ref, force, reason }) => {
12059
13291
  const t = orch.getThread(ref);
@@ -12079,8 +13311,8 @@ async function startMcpServer() {
12079
13311
  "get_diff",
12080
13312
  "Compact diff summary (capped hunks, paginated)",
12081
13313
  {
12082
- ref: z8.string(),
12083
- maxFiles: z8.number().optional()
13314
+ ref: z9.string(),
13315
+ maxFiles: z9.number().optional()
12084
13316
  },
12085
13317
  async ({ ref, maxFiles }) => {
12086
13318
  const summary = await orch.diffSummary(ref);
@@ -12093,7 +13325,7 @@ async function startMcpServer() {
12093
13325
  server.tool(
12094
13326
  "get_pr_checks",
12095
13327
  "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.",
12096
- { ref: z8.string().describe("Worktree thread id/ref") },
13328
+ { ref: z9.string().describe("Worktree thread id/ref") },
12097
13329
  async ({ ref }) => {
12098
13330
  try {
12099
13331
  const checks = await orch.getPrChecks(ref);
@@ -12107,7 +13339,7 @@ async function startMcpServer() {
12107
13339
  server.tool(
12108
13340
  "request_review",
12109
13341
  '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.',
12110
- { ref: z8.string().describe("Worktree thread id/ref to review") },
13342
+ { ref: z9.string().describe("Worktree thread id/ref to review") },
12111
13343
  async ({ ref }) => {
12112
13344
  try {
12113
13345
  const tab = await orch.requestReview(ref);
@@ -12129,8 +13361,8 @@ async function startMcpServer() {
12129
13361
  "ask_git",
12130
13362
  "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.",
12131
13363
  {
12132
- ref: z8.string().describe("Worktree thread id/ref"),
12133
- action: z8.enum(AGENT_GIT_ACTIONS).describe(
13364
+ ref: z9.string().describe("Worktree thread id/ref"),
13365
+ action: z9.enum(AGENT_GIT_ACTIONS).describe(
12134
13366
  "commit-push | create-draft | create-web | resolve-conflicts | ready-for-review | merge"
12135
13367
  )
12136
13368
  },
@@ -12159,7 +13391,7 @@ async function startMcpServer() {
12159
13391
  }
12160
13392
  }
12161
13393
  );
12162
- const agentEnum = z8.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
13394
+ const agentEnum = z9.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
12163
13395
  server.tool(
12164
13396
  "list_models",
12165
13397
  "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.",
@@ -12180,11 +13412,11 @@ async function startMcpServer() {
12180
13412
  "fork_workspace",
12181
13413
  "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.",
12182
13414
  {
12183
- ref: z8.string().describe("Worktree thread id/ref to fork"),
12184
- through_index: z8.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
13415
+ ref: z9.string().describe("Worktree thread id/ref to fork"),
13416
+ through_index: z9.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
12185
13417
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
12186
- model: z8.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
12187
- title: z8.string().optional()
13418
+ model: z9.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
13419
+ title: z9.string().optional()
12188
13420
  },
12189
13421
  async ({ ref, through_index, agent, model, title }) => {
12190
13422
  try {
@@ -12218,11 +13450,11 @@ async function startMcpServer() {
12218
13450
  "fork_chat",
12219
13451
  "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.",
12220
13452
  {
12221
- ref: z8.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
12222
- through_index: z8.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
13453
+ ref: z9.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
13454
+ through_index: z9.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
12223
13455
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
12224
- model: z8.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
12225
- title: z8.string().optional()
13456
+ model: z9.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
13457
+ title: z9.string().optional()
12226
13458
  },
12227
13459
  async ({ ref, through_index, agent, model, title }) => {
12228
13460
  try {
@@ -12260,7 +13492,7 @@ async function startMcpServer() {
12260
13492
  server.tool(
12261
13493
  "run_setup",
12262
13494
  "Re-run workspace setup (Sideboard/Conductor settings, .cursor/worktrees.json, or script/setup). New worktrees already run this automatically.",
12263
- { ref: z8.string() },
13495
+ { ref: z9.string() },
12264
13496
  async ({ ref }) => {
12265
13497
  const result = await orch.runSetup(ref);
12266
13498
  return mcpJson(result);
@@ -12269,7 +13501,7 @@ async function startMcpServer() {
12269
13501
  server.tool(
12270
13502
  "add_project",
12271
13503
  "Register a git repo as a Sideboard workspace",
12272
- { repoPath: z8.string() },
13504
+ { repoPath: z9.string() },
12273
13505
  async ({ repoPath }) => {
12274
13506
  const ws = await orch.addWorkspace(repoPath);
12275
13507
  return mcpJson(ws);
@@ -12278,7 +13510,7 @@ async function startMcpServer() {
12278
13510
  server.tool(
12279
13511
  "remove_project",
12280
13512
  "Unregister a Sideboard workspace and archive its chats",
12281
- { repoPath: z8.string() },
13513
+ { repoPath: z9.string() },
12282
13514
  async ({ repoPath }) => {
12283
13515
  await orch.removeWorkspace(repoPath);
12284
13516
  return { content: [{ type: "text", text: "ok" }] };
@@ -12288,12 +13520,12 @@ async function startMcpServer() {
12288
13520
  "fanout",
12289
13521
  "Best-of-n: create one thread per agent with the same prompt (parallel attempts)",
12290
13522
  {
12291
- prompt: z8.string(),
12292
- agents: z8.array(z8.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
12293
- repoPath: z8.string(),
12294
- sourceType: z8.enum(["branch", "pr", "ticket"]).optional(),
12295
- sourceRef: z8.string().optional(),
12296
- title: z8.string().optional()
13523
+ prompt: z9.string(),
13524
+ agents: z9.array(z9.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
13525
+ repoPath: z9.string(),
13526
+ sourceType: z9.enum(["branch", "pr", "ticket"]).optional(),
13527
+ sourceRef: z9.string().optional(),
13528
+ title: z9.string().optional()
12297
13529
  },
12298
13530
  async (args) => {
12299
13531
  const threads = await orch.bestOfN(args);
@@ -12311,8 +13543,8 @@ async function startMcpServer() {
12311
13543
  "list_branches",
12312
13544
  "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).",
12313
13545
  {
12314
- repoPath: z8.string(),
12315
- unmergedOnly: z8.boolean().optional()
13546
+ repoPath: z9.string(),
13547
+ unmergedOnly: z9.boolean().optional()
12316
13548
  },
12317
13549
  async ({ repoPath, unmergedOnly }) => {
12318
13550
  const root = await resolveRepoRoot(repoPath);
@@ -12333,19 +13565,19 @@ async function startMcpServer() {
12333
13565
  "list_prs",
12334
13566
  `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.`,
12335
13567
  {
12336
- repoPath: z8.string(),
12337
- query: z8.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
12338
- queue: z8.enum(["review", "mine", "approved", "changes"]).optional().describe(
13568
+ repoPath: z9.string(),
13569
+ query: z9.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
13570
+ queue: z9.enum(["review", "mine", "approved", "changes"]).optional().describe(
12339
13571
  "review = unclaimed ready-for-review inbox (Settings \u2192 Projects label, default eng-review). mine = review-requested:@me. approved / changes = eng-approved / eng-requested-changes."
12340
13572
  ),
12341
- state: z8.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
12342
- label: z8.string().optional().describe(
13573
+ state: z9.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
13574
+ label: z9.string().optional().describe(
12343
13575
  "GitHub label / workflow tag. Comma-separated AND. Examples: eng-review, eng-approved, eng-requested-changes"
12344
13576
  ),
12345
- reviewer: z8.string().optional().describe(
13577
+ reviewer: z9.string().optional().describe(
12346
13578
  "me (review requested of you), unassigned (no individual reviewer; team queues like engineering-team still count), all, or a GitHub login"
12347
13579
  ),
12348
- limit: z8.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
13580
+ limit: z9.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
12349
13581
  },
12350
13582
  async ({ repoPath, query, queue, state, label, reviewer, limit }) => {
12351
13583
  const root = await resolveRepoRoot(repoPath);
@@ -12378,7 +13610,7 @@ async function startMcpServer() {
12378
13610
  server.tool(
12379
13611
  "get_pr_stack",
12380
13612
  "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).",
12381
- { ref: z8.string() },
13613
+ { ref: z9.string() },
12382
13614
  async ({ ref }) => {
12383
13615
  const stack = await orch.getPrStack(ref);
12384
13616
  return mcpJson(stack);
@@ -12388,8 +13620,8 @@ async function startMcpServer() {
12388
13620
  "open_pr_stack_layers",
12389
13621
  "Materialize one worktree+thread per stack layer (or a single 1-based layer). Pass a thread ref already on the stack.",
12390
13622
  {
12391
- ref: z8.string(),
12392
- layer: z8.number().int().positive().optional()
13623
+ ref: z9.string(),
13624
+ layer: z9.number().int().positive().optional()
12393
13625
  },
12394
13626
  async ({ ref, layer }) => {
12395
13627
  const result = await orch.openPrStackLayers(ref, { layer });
@@ -12412,9 +13644,9 @@ async function startMcpServer() {
12412
13644
  "add_stack_layer",
12413
13645
  "Add a branch on top of the current stack (`gh stack add`) and open a worktree+thread for it.",
12414
13646
  {
12415
- ref: z8.string(),
12416
- branchName: z8.string(),
12417
- title: z8.string().optional()
13647
+ ref: z9.string(),
13648
+ branchName: z9.string(),
13649
+ title: z9.string().optional()
12418
13650
  },
12419
13651
  async ({ ref, branchName, title }) => {
12420
13652
  const result = await orch.addStackLayer(ref, branchName, { title });
@@ -12432,11 +13664,11 @@ async function startMcpServer() {
12432
13664
  "create_pr_stack",
12433
13665
  "Create a new GitHub PR stack with one Sideboard worktree per layer (bottom\u2192top branch names). Requires `gh extension install github/gh-stack`.",
12434
13666
  {
12435
- repoPath: z8.string(),
12436
- branches: z8.array(z8.string()).min(1),
12437
- agent: z8.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
12438
- base: z8.string().optional(),
12439
- title: z8.string().optional()
13667
+ repoPath: z9.string(),
13668
+ branches: z9.array(z9.string()).min(1),
13669
+ agent: z9.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
13670
+ base: z9.string().optional(),
13671
+ title: z9.string().optional()
12440
13672
  },
12441
13673
  async (args) => {
12442
13674
  const result = await orch.createPrStack({
@@ -12464,10 +13696,10 @@ async function startMcpServer() {
12464
13696
  "list_issues",
12465
13697
  "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.",
12466
13698
  {
12467
- repoPath: z8.string(),
12468
- query: z8.string().optional().describe("Search title, identifier, or description"),
12469
- assignee: z8.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
12470
- limit: z8.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
13699
+ repoPath: z9.string(),
13700
+ query: z9.string().optional().describe("Search title, identifier, or description"),
13701
+ assignee: z9.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
13702
+ limit: z9.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
12471
13703
  updatedSince: mcpIssueUpdatedSinceSchema
12472
13704
  },
12473
13705
  async ({ repoPath, query, assignee, limit, updatedSince }) => {
@@ -12488,7 +13720,7 @@ async function startMcpServer() {
12488
13720
  }
12489
13721
 
12490
13722
  // src/agent-rpc/server.ts
12491
- import { randomBytes as randomBytes11, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual4 } from "crypto";
13723
+ import { randomBytes as randomBytes11, randomUUID as randomUUID9, timingSafeEqual as timingSafeEqual4 } from "crypto";
12492
13724
  import { createServer as createServer2 } from "http";
12493
13725
  import { WebSocketServer as WebSocketServer2 } from "ws";
12494
13726
  function tokensEqual(a, b) {
@@ -12530,7 +13762,7 @@ var AgentRpcServer = class {
12530
13762
  const port = opts.port ?? 0;
12531
13763
  const authToken = randomBytes11(24).toString("base64url");
12532
13764
  this.meta = {
12533
- runtimeId: randomUUID8(),
13765
+ runtimeId: randomUUID9(),
12534
13766
  pid: process.pid,
12535
13767
  protocolVersion: AGENT_RPC_PROTOCOL_VERSION,
12536
13768
  authToken,
@@ -13337,17 +14569,81 @@ async function saveSlackOrgCredentials(opts) {
13337
14569
  if (!res.ok) throw new Error(await readError(res));
13338
14570
  }
13339
14571
 
14572
+ // src/slack/deferred-reply.ts
14573
+ var SLACK_LISTEN_STOPPED_REPLY = "Sideboard stopped the in-progress turn. Send another message when you want to continue.";
14574
+ var SLACK_LISTEN_TIMEOUT_REPLY = [
14575
+ "Sideboard timed out waiting for the local agent turn to finish.",
14576
+ 'Send another message to interrupt and retry, or send "stop".'
14577
+ ].join(" ");
14578
+ var SLACK_LISTEN_INPUT_REQUIRED_REPLY = [
14579
+ "Sideboard is waiting for an answer on the Mac (the coordinator called ask_user).",
14580
+ "The picker is in the Sideboard app \u2014 not in Slack.",
14581
+ 'Reply here after you answer it on the Mac, or send "stop".'
14582
+ ].join(" ");
14583
+ function slackShouldHoldDeferredReply(opts) {
14584
+ if (!orchestratorPromisedLaterReport(opts.reply)) return false;
14585
+ if (opts.queue.some((item) => isJobContinuePrompt(item))) return true;
14586
+ return opts.status === "running" || opts.status === "queued";
14587
+ }
14588
+ var SLACK_DEFERRED_HOLD_LIMIT = 3;
14589
+ async function waitUntilOrchestratorContinueSettles(orch, threadId, timeoutMs) {
14590
+ const start = Date.now();
14591
+ while (Date.now() - start < timeoutMs) {
14592
+ const thread = readThread(threadId);
14593
+ if (!thread || thread.status === "stopped" || thread.status === "archived") return;
14594
+ if (thread.status === "running" || thread.status === "queued") {
14595
+ const remaining = Math.max(1, timeoutMs - (Date.now() - start));
14596
+ await orch.waitForTurn(threadId, remaining);
14597
+ return;
14598
+ }
14599
+ if (!thread.queue.some((item) => isJobContinuePrompt(item))) return;
14600
+ await new Promise((resolve) => setTimeout(resolve, 40));
14601
+ }
14602
+ throw new Error("wait_for_turn timed out");
14603
+ }
14604
+ async function awaitDeferredOrchestratorReply(orch, threadId, initial, timeoutMs, aborted) {
14605
+ let reply = initial;
14606
+ const deadline = Date.now() + timeoutMs;
14607
+ for (let i = 0; i < SLACK_DEFERRED_HOLD_LIMIT; i++) {
14608
+ if (aborted?.()) return { reply: "", interrupted: true };
14609
+ const thread = readThread(threadId);
14610
+ if (!thread || thread.status === "stopped" || thread.status === "archived") {
14611
+ return { reply: "", interrupted: true };
14612
+ }
14613
+ if (!slackShouldHoldDeferredReply({ reply, queue: thread.queue, status: thread.status })) {
14614
+ return { reply, interrupted: false };
14615
+ }
14616
+ const remaining = deadline - Date.now();
14617
+ if (remaining <= 0) return { reply, interrupted: false };
14618
+ await waitUntilOrchestratorContinueSettles(orch, threadId, remaining);
14619
+ const latest = readThread(threadId);
14620
+ if (!latest || latest.status === "stopped" || latest.status === "archived") {
14621
+ return { reply: "", interrupted: true };
14622
+ }
14623
+ reply = formatSlackTurnReply(orch.getTurnResult(threadId));
14624
+ }
14625
+ return { reply, interrupted: false };
14626
+ }
14627
+ function formatSlackTurnReply(result) {
14628
+ return outboundReplyFromTurn(result, {
14629
+ inputRequired: SLACK_LISTEN_INPUT_REQUIRED_REPLY,
14630
+ canceled: SLACK_LISTEN_STOPPED_REPLY,
14631
+ completedEmpty: () => "",
14632
+ failed: (detail) => detail ? `Sideboard coordinator failed: ${detail}` : "Sideboard coordinator failed before producing a result."
14633
+ });
14634
+ }
14635
+
13340
14636
  // src/slack/reply-target.ts
13341
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
13342
- import { join as join9 } from "path";
14637
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
14638
+ import { join as join10 } from "path";
13343
14639
  function storePath2() {
13344
- return join9(appDataDir(), "slack-reply-to.json");
14640
+ return join10(appDataDir(), "slack-reply-to.json");
13345
14641
  }
13346
14642
  function readStore2() {
13347
14643
  const path2 = storePath2();
13348
- if (!existsSync4(path2)) return {};
14644
+ if (!existsSync5(path2)) return {};
13349
14645
  try {
13350
- const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse(readFileSync6(path2, "utf8"));
14646
+ const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse(readFileSync7(path2, "utf8"));
13351
14647
  return parsed?.targets && typeof parsed.targets === "object" ? parsed.targets : {};
13352
14648
  } catch {
13353
14649
  return {};
@@ -13595,24 +14891,6 @@ function connectSession2(ws, opts, log) {
13595
14891
  }
13596
14892
 
13597
14893
  // src/slack/listen.ts
13598
- var SLACK_LISTEN_STOPPED_REPLY = "Sideboard stopped the in-progress turn. Send another message when you want to continue.";
13599
- var SLACK_LISTEN_TIMEOUT_REPLY = [
13600
- "Sideboard timed out waiting for the local agent turn to finish.",
13601
- 'Send another message to interrupt and retry, or send "stop".'
13602
- ].join(" ");
13603
- var SLACK_LISTEN_INPUT_REQUIRED_REPLY = [
13604
- "Sideboard is waiting for an answer on the Mac (the coordinator called ask_user).",
13605
- "The picker is in the Sideboard app \u2014 not in Slack.",
13606
- 'Reply here after you answer it on the Mac, or send "stop".'
13607
- ].join(" ");
13608
- function formatSlackTurnReply(result) {
13609
- return outboundReplyFromTurn(result, {
13610
- inputRequired: SLACK_LISTEN_INPUT_REQUIRED_REPLY,
13611
- canceled: SLACK_LISTEN_STOPPED_REPLY,
13612
- completedEmpty: () => "",
13613
- failed: (detail) => detail ? `Sideboard coordinator failed: ${detail}` : "Sideboard coordinator failed before producing a result."
13614
- });
13615
- }
13616
14894
  var handleChain2 = Promise.resolve();
13617
14895
  function enqueueHandle(fn) {
13618
14896
  const run2 = handleChain2.then(fn, fn);
@@ -13922,7 +15200,9 @@ async function relayCoordinatorReplyToSlack(threadId, opts) {
13922
15200
  if (!target) return;
13923
15201
  const thread = readThread(threadId);
13924
15202
  const lastUser = thread ? [...thread.messages].reverse().find((m) => m.role === "user") : void 0;
13925
- if (lastUser && isSlackInboundUserPrompt(lastUser.text)) return;
15203
+ if (lastUser && (isSlackInboundUserPrompt(lastUser.text) || isJobContinuePrompt(lastUser.text))) {
15204
+ return;
15205
+ }
13926
15206
  const result = getOrchestrator().getTurnResult(threadId);
13927
15207
  const text5 = formatSlackTurnReply(result);
13928
15208
  if (!text5) return;
@@ -14046,6 +15326,18 @@ async function handleSlackInbound(msg, opts) {
14046
15326
  }
14047
15327
  }
14048
15328
  reply = formatSlackTurnReply(orch.getTurnResult(fresh.id));
15329
+ const held = await awaitDeferredOrchestratorReply(
15330
+ orch,
15331
+ fresh.id,
15332
+ reply,
15333
+ 14 * 60 * 1e3,
15334
+ () => slackInboundSuperseded(opts)
15335
+ );
15336
+ if (held.interrupted) {
15337
+ await dropProgress(`turn finished ${msg.ts} (deferred reply interrupted)`);
15338
+ return;
15339
+ }
15340
+ reply = held.reply;
14049
15341
  } catch (err) {
14050
15342
  if (slackInboundSuperseded(opts)) {
14051
15343
  await dropProgress(`turn error ${msg.ts} (superseded)`);
@@ -14310,8 +15602,8 @@ async function disconnectRemoteAccount(opts) {
14310
15602
  }
14311
15603
 
14312
15604
  // src/slack/outbound-watch.ts
14313
- import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
14314
- import { join as join10 } from "path";
15605
+ import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
15606
+ import { join as join11 } from "path";
14315
15607
  var MAX_WATCHES = 40;
14316
15608
  var MAX_REPLIES_PER_WATCH = 30;
14317
15609
  var WATCH_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -14319,7 +15611,7 @@ var POLL_INTERVAL_MS = 12e3;
14319
15611
  var lastPollMs = 0;
14320
15612
  var nameCache = /* @__PURE__ */ new Map();
14321
15613
  function storePath3() {
14322
- return join10(appDataDir(), "slack-outbound-watch.json");
15614
+ return join11(appDataDir(), "slack-outbound-watch.json");
14323
15615
  }
14324
15616
  function watchId(teamId, channelId, ts) {
14325
15617
  return `${teamId}:${channelId}:${ts}`;
@@ -14332,9 +15624,9 @@ function tsNewer(a, b) {
14332
15624
  }
14333
15625
  function readStore3() {
14334
15626
  const path2 = storePath3();
14335
- if (!existsSync5(path2)) return [];
15627
+ if (!existsSync6(path2)) return [];
14336
15628
  try {
14337
- const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse(readFileSync7(path2, "utf8"));
15629
+ const parsed = isSecureFileEncrypted(path2) ? readSecureJson(path2) : JSON.parse(readFileSync8(path2, "utf8"));
14338
15630
  return Array.isArray(parsed?.watches) ? parsed.watches : [];
14339
15631
  } catch {
14340
15632
  return [];
@@ -14386,7 +15678,7 @@ async function continueSourceThread(threadId, prompt) {
14386
15678
  await continueOnReply(threadId, prompt);
14387
15679
  return;
14388
15680
  }
14389
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZUIU667R.js");
15681
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-NOQDMYLB.js");
14390
15682
  await getOrchestrator2().send(threadId, prompt);
14391
15683
  } catch {
14392
15684
  }
@@ -14858,6 +16150,7 @@ export {
14858
16150
  askBlockStillWaiting,
14859
16151
  assertAbleTimeCredential,
14860
16152
  assertAbleTimeMcpCredential,
16153
+ assertCallerOwnsSubject,
14861
16154
  assertOrchestratorCapableAgent,
14862
16155
  attachmentFromAbsolutePath,
14863
16156
  attachmentsFromBuffers,
@@ -14887,8 +16180,10 @@ export {
14887
16180
  buildLinearIssueFilter,
14888
16181
  buildPastedTextAttachment,
14889
16182
  buildPathRefAttachment,
16183
+ buildPlanMap,
14890
16184
  buildReviewRequestAttachment,
14891
16185
  buildSessionSeed,
16186
+ buildWaterfall,
14892
16187
  buildWorkspaceScriptEnv,
14893
16188
  caffeinateHoldPath,
14894
16189
  caffeinateWhileCloudConnectEnabled,
@@ -14923,6 +16218,7 @@ export {
14923
16218
  clearBoardPins,
14924
16219
  clearHomeBoardCache,
14925
16220
  clearOptionalCliPresenceCache,
16221
+ clearOrderDependency,
14926
16222
  clipAgentEventForPaint,
14927
16223
  clipThinkingForStore,
14928
16224
  cloneRepoIntoSideboard,
@@ -14980,6 +16276,7 @@ export {
14980
16276
  cursorIssuesUnavailableReason,
14981
16277
  cursorSdkMessageToEvents,
14982
16278
  decodeBrightsyTarget,
16279
+ defaultOrderSubject,
14983
16280
  defaultScheduleName,
14984
16281
  deleteBranchOnPurgeEnabled,
14985
16282
  deleteSchedule,
@@ -15033,6 +16330,8 @@ export {
15033
16330
  estimateOccupancyTokens,
15034
16331
  estimateThreadChars,
15035
16332
  examplePrefixedBranch,
16333
+ executeOrderPlan,
16334
+ executionSlice,
15036
16335
  expandComposerPrompt,
15037
16336
  extractBrightsyContextSummary,
15038
16337
  extractGhErrorDetail,
@@ -15101,6 +16400,8 @@ export {
15101
16400
  formatOptionalServicesDirectiveForTurn,
15102
16401
  formatOptionalServicesReminder,
15103
16402
  formatOptionalServicesReminderForTurn,
16403
+ formatOrderPlace,
16404
+ formatOrderText,
15104
16405
  formatPlanQuestionAnswers,
15105
16406
  formatPlanQuestionsForChat,
15106
16407
  formatPrGateDirective,
@@ -15122,6 +16423,7 @@ export {
15122
16423
  formatUiReminder,
15123
16424
  formatViewerContextDirective,
15124
16425
  formatViewerContextReminder,
16426
+ formatWaterfallHtml,
15125
16427
  formatWeeklyDays,
15126
16428
  formatWorkspaceInventory,
15127
16429
  formatWorkspaceProfileSuffix,
@@ -15130,6 +16432,7 @@ export {
15130
16432
  forwardContextUsage,
15131
16433
  forwardOccupancyTokens,
15132
16434
  fromInclusiveInputUsage,
16435
+ gatePhrase,
15133
16436
  getAbleTimeAccessToken,
15134
16437
  getAbleTimeHost,
15135
16438
  getAbleTimeOrientation,
@@ -15161,6 +16464,7 @@ export {
15161
16464
  getLinearIssue,
15162
16465
  getMcpUiHost,
15163
16466
  getOrchestrator,
16467
+ getOrderPlan,
15164
16468
  getPr,
15165
16469
  getPrChecks,
15166
16470
  getPrDetails,
@@ -15202,6 +16506,7 @@ export {
15202
16506
  healOrchestrationSoccerTitles,
15203
16507
  historyMaxCount,
15204
16508
  historyMaxDays,
16509
+ holdPhrase,
15205
16510
  hostKeepsMacAwake,
15206
16511
  hottestClaudeWindow,
15207
16512
  httpFetch,
@@ -15346,12 +16651,18 @@ export {
15346
16651
  listLinearTeams,
15347
16652
  listModelsForAgent,
15348
16653
  listOpencodeModels,
16654
+ listOrderBoard,
16655
+ listOrderEdges,
16656
+ listOrderMarks,
16657
+ listOrderPlans,
16658
+ listOrderRows,
15349
16659
  listPrs,
15350
16660
  listRunScripts,
15351
16661
  listSchedules,
15352
16662
  listSlackOutboundWatches,
15353
16663
  listSlackWorkspaces,
15354
16664
  listThreads,
16665
+ listWaterfall,
15355
16666
  listWorkspaces,
15356
16667
  listWorktreeFiles,
15357
16668
  listWorktrees,
@@ -15440,6 +16751,10 @@ export {
15440
16751
  orchestrationQuotaOnLimit,
15441
16752
  orchestrationTitleNeedsSoccerNickname,
15442
16753
  orchestratorSessionPoisonedByBuiltins,
16754
+ orderEdgeTouches,
16755
+ orderPath,
16756
+ orderSnapshotFromThread,
16757
+ orderTargetMatches,
15443
16758
  originCli,
15444
16759
  originFetchBranch,
15445
16760
  originGhRepoEnv,
@@ -15457,6 +16772,9 @@ export {
15457
16772
  parseGitHubIssueNumber,
15458
16773
  parseGithubSlugFromRemoteUrl,
15459
16774
  parseMcpList,
16775
+ parseOrderGate,
16776
+ parseOrderHold,
16777
+ parseOrderKind,
15460
16778
  parseOriginAuthStatus,
15461
16779
  parsePlanQuestionsInput,
15462
16780
  parsePrDetailsView,
@@ -15560,7 +16878,9 @@ export {
15560
16878
  resolveNewOrchestratorOptions,
15561
16879
  resolveNewThreadOptions,
15562
16880
  resolveOrchChildFollowUp,
16881
+ resolveOrchestrationGates,
15563
16882
  resolveOrchestratorDefaults,
16883
+ resolveOrderRows,
15564
16884
  resolveOriginRemote,
15565
16885
  resolvePlanMarkdown,
15566
16886
  resolvePrSelector,
@@ -15600,6 +16920,7 @@ export {
15600
16920
  sanitizeGitBranchPrefix,
15601
16921
  sanitizeMcpServerName,
15602
16922
  sanitizeReadAloudVoiceURI,
16923
+ satisfyOrderDependency,
15603
16924
  saveAbleTimeConnection,
15604
16925
  saveAppSettings,
15605
16926
  saveLinearOAuth,
@@ -15614,6 +16935,8 @@ export {
15614
16935
  selectManagedAccount,
15615
16936
  setCaffeinateHold,
15616
16937
  setHttpFetchImpl,
16938
+ setOrderDependency,
16939
+ setOrderPlan,
15617
16940
  setStatus,
15618
16941
  setVaultMasterKey,
15619
16942
  settingsSourceLabel,
@@ -15631,6 +16954,8 @@ export {
15631
16954
  shouldRunWorktreeCleanup,
15632
16955
  shouldStampSetupLastError,
15633
16956
  showCostEnabled,
16957
+ showPlanDocuments,
16958
+ showPlanMessage,
15634
16959
  sidebarParentSelectId,
15635
16960
  sidebarQuestionThreadId,
15636
16961
  sidebarRowAgentBlock,