@adhdev/daemon-core 0.9.82-rc.446 → 0.9.82-rc.448

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -409,10 +409,10 @@ function readInjected(value) {
409
409
  }
410
410
  function getDaemonBuildInfo() {
411
411
  if (cached) return cached;
412
- const commit = readInjected(true ? "c70a1cf556d27bbee6f81e64ea13699887f50ecc" : void 0) ?? "unknown";
413
- const commitShort = readInjected(true ? "c70a1cf5" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
- const version = readInjected(true ? "0.9.82-rc.446" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
- const builtAt = readInjected(true ? "2026-07-01T15:09:11.778Z" : void 0);
412
+ const commit = readInjected(true ? "7636b9d4fc6c456ebfe178b9b0a7b81664b02257" : void 0) ?? "unknown";
413
+ const commitShort = readInjected(true ? "7636b9d4" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
+ const version = readInjected(true ? "0.9.82-rc.448" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
+ const builtAt = readInjected(true ? "2026-07-02T00:30:54.215Z" : void 0);
416
416
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
417
417
  return cached;
418
418
  }
@@ -486,8 +486,8 @@ function validateChangeImpactConfig(raw, source = "inline") {
486
486
  }
487
487
  return { valid: errors.length === 0, errors, config: errors.length === 0 ? config : void 0 };
488
488
  }
489
- function parseConfigText(path43, text) {
490
- if (/\.json$/i.test(path43)) return JSON.parse(text);
489
+ function parseConfigText(path44, text) {
490
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
491
491
  return yaml.load(text);
492
492
  }
493
493
  function loadChangeImpactConfig(repoRoot) {
@@ -1104,14 +1104,14 @@ async function deriveSubmoduleGitlinkStatuses(repo, options) {
1104
1104
  const lastCheckedAt = Date.now();
1105
1105
  const headOidByPath = /* @__PURE__ */ new Map();
1106
1106
  const entries = await Promise.all(
1107
- paths.filter((path43) => !ignoreSet.has(path43)).map(async (path43) => {
1108
- const repoPath = repo.repoRoot + "/" + path43;
1109
- const expected = await readGitlinkExpectedSha(repo, path43, options);
1107
+ paths.filter((path44) => !ignoreSet.has(path44)).map(async (path44) => {
1108
+ const repoPath = repo.repoRoot + "/" + path44;
1109
+ const expected = await readGitlinkExpectedSha(repo, path44, options);
1110
1110
  const actual = await readSubmoduleHeadSha(repo, repoPath, options);
1111
- if (actual) headOidByPath.set(path43, actual);
1111
+ if (actual) headOidByPath.set(path44, actual);
1112
1112
  const outOfSync = actual === null ? true : expected !== null && expected !== actual;
1113
1113
  return {
1114
- path: path43,
1114
+ path: path44,
1115
1115
  // Prefer the recorded gitlink SHA (matches the legacy column); fall back
1116
1116
  // to the checked-out SHA so the field is never empty when both are known.
1117
1117
  commit: expected ?? actual ?? "",
@@ -1502,6 +1502,255 @@ var init_git_diff = __esm({
1502
1502
  }
1503
1503
  });
1504
1504
 
1505
+ // src/config/config.ts
1506
+ var config_exports = {};
1507
+ __export(config_exports, {
1508
+ generateMachineId: () => generateMachineId,
1509
+ getConfigDir: () => getConfigDir,
1510
+ getDaemonDataDir: () => getDaemonDataDir,
1511
+ isSetupComplete: () => isSetupComplete,
1512
+ isStableMachineId: () => isStableMachineId,
1513
+ loadConfig: () => loadConfig,
1514
+ markSetupComplete: () => markSetupComplete,
1515
+ resetConfig: () => resetConfig,
1516
+ resolveProviderSourceMode: () => resolveProviderSourceMode,
1517
+ saveConfig: () => saveConfig,
1518
+ updateConfig: () => updateConfig
1519
+ });
1520
+ function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
1521
+ if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
1522
+ return providerSourceMode;
1523
+ }
1524
+ return legacyDisableUpstream === true ? "no-upstream" : "normal";
1525
+ }
1526
+ function isPlainObject(value) {
1527
+ return !!value && typeof value === "object" && !Array.isArray(value);
1528
+ }
1529
+ function asStringArray(value) {
1530
+ if (!Array.isArray(value)) return [];
1531
+ return value.filter((item) => typeof item === "string");
1532
+ }
1533
+ function asNullableString(value) {
1534
+ return typeof value === "string" ? value : null;
1535
+ }
1536
+ function asOptionalString(value) {
1537
+ return typeof value === "string" && value.trim() ? value : void 0;
1538
+ }
1539
+ function asBoolean(value, fallback) {
1540
+ return typeof value === "boolean" ? value : fallback;
1541
+ }
1542
+ function normalizeMachineProviders(value) {
1543
+ if (!isPlainObject(value)) return {};
1544
+ const result = {};
1545
+ for (const [providerType, raw] of Object.entries(value)) {
1546
+ if (!isPlainObject(raw)) continue;
1547
+ const entry = {};
1548
+ if (raw.enabled === true) entry.enabled = true;
1549
+ if (typeof raw.executable === "string" && raw.executable.trim()) {
1550
+ entry.executable = raw.executable.trim();
1551
+ }
1552
+ if (Array.isArray(raw.args)) {
1553
+ entry.args = raw.args.filter((arg) => typeof arg === "string");
1554
+ }
1555
+ if (isPlainObject(raw.lastDetection)) {
1556
+ entry.lastDetection = raw.lastDetection;
1557
+ }
1558
+ if (isPlainObject(raw.lastVerification)) {
1559
+ entry.lastVerification = raw.lastVerification;
1560
+ }
1561
+ result[providerType] = entry;
1562
+ }
1563
+ return result;
1564
+ }
1565
+ function normalizeConfig(raw) {
1566
+ const parsed = isPlainObject(raw) ? raw : {};
1567
+ return {
1568
+ serverUrl: typeof parsed.serverUrl === "string" && parsed.serverUrl.trim() ? parsed.serverUrl : DEFAULT_CONFIG.serverUrl,
1569
+ allowServerApiProxy: asBoolean(parsed.allowServerApiProxy, DEFAULT_CONFIG.allowServerApiProxy ?? false),
1570
+ selectedIde: asNullableString(parsed.selectedIde),
1571
+ configuredIdes: asStringArray(parsed.configuredIdes),
1572
+ installedExtensions: asStringArray(parsed.installedExtensions),
1573
+ userEmail: asNullableString(parsed.userEmail),
1574
+ userName: asNullableString(parsed.userName),
1575
+ setupCompleted: asBoolean(parsed.setupCompleted, DEFAULT_CONFIG.setupCompleted),
1576
+ setupDate: asNullableString(parsed.setupDate),
1577
+ enabledIdes: asStringArray(parsed.enabledIdes),
1578
+ workspaces: Array.isArray(parsed.workspaces) ? parsed.workspaces : [],
1579
+ defaultWorkspaceId: asNullableString(parsed.defaultWorkspaceId) ?? asNullableString(parsed.activeWorkspaceId),
1580
+ machineNickname: asNullableString(parsed.machineNickname),
1581
+ machineId: asOptionalString(parsed.machineId),
1582
+ machineSecret: parsed.machineSecret === null ? null : asOptionalString(parsed.machineSecret),
1583
+ registeredMachineId: asOptionalString(parsed.registeredMachineId),
1584
+ providerSettings: isPlainObject(parsed.providerSettings) ? parsed.providerSettings : {},
1585
+ machineProviders: normalizeMachineProviders(parsed.machineProviders),
1586
+ ideSettings: isPlainObject(parsed.ideSettings) ? parsed.ideSettings : {},
1587
+ providerSourceMode: resolveProviderSourceMode(parsed.providerSourceMode, parsed.disableUpstream),
1588
+ providerDir: asOptionalString(parsed.providerDir),
1589
+ updateChannel: parsed.updateChannel === "preview" ? "preview" : "stable",
1590
+ terminalSizingMode: parsed.terminalSizingMode === "fit" ? "fit" : "measured"
1591
+ };
1592
+ }
1593
+ function generateMachineId() {
1594
+ return `${MACHINE_ID_PREFIX}${(0, import_crypto.randomUUID)().replace(/-/g, "")}`;
1595
+ }
1596
+ function isStableMachineId(machineId) {
1597
+ return typeof machineId === "string" && machineId.startsWith(MACHINE_ID_PREFIX);
1598
+ }
1599
+ function ensureMachineId(config) {
1600
+ if (isStableMachineId(config.machineId)) {
1601
+ return { config, changed: false };
1602
+ }
1603
+ return {
1604
+ config: {
1605
+ ...config,
1606
+ machineId: generateMachineId()
1607
+ },
1608
+ changed: true
1609
+ };
1610
+ }
1611
+ function getConfigDir() {
1612
+ const override = process.env.ADHDEV_CONFIG_DIR;
1613
+ const dir = override && override.trim() ? override.trim() : (0, import_path2.join)((0, import_os.homedir)(), ".adhdev");
1614
+ if (!(0, import_fs2.existsSync)(dir)) {
1615
+ (0, import_fs2.mkdirSync)(dir, { recursive: true });
1616
+ }
1617
+ return dir;
1618
+ }
1619
+ function getDaemonDataDir() {
1620
+ const dir = (0, import_path2.join)(getConfigDir(), "daemon");
1621
+ if (!(0, import_fs2.existsSync)(dir)) {
1622
+ (0, import_fs2.mkdirSync)(dir, { recursive: true });
1623
+ }
1624
+ return dir;
1625
+ }
1626
+ function getConfigPath() {
1627
+ return (0, import_path2.join)(getConfigDir(), "config.json");
1628
+ }
1629
+ function migrateStateToStateFile(raw) {
1630
+ const statePath = (0, import_path2.join)(getConfigDir(), "state.json");
1631
+ if ((0, import_fs2.existsSync)(statePath)) return;
1632
+ const recentActivity = Array.isArray(raw.recentActivity) ? raw.recentActivity : [];
1633
+ const savedProviderSessions = Array.isArray(raw.savedProviderSessions) ? raw.savedProviderSessions : [];
1634
+ const legacySessionReads = isPlainObject(raw.recentSessionReads) ? raw.recentSessionReads : {};
1635
+ const sessionReads = isPlainObject(raw.sessionReads) ? raw.sessionReads : {};
1636
+ const sessionReadMarkers = isPlainObject(raw.sessionReadMarkers) ? raw.sessionReadMarkers : {};
1637
+ const hasData = recentActivity.length > 0 || savedProviderSessions.length > 0 || Object.keys(sessionReads).length > 0 || Object.keys(legacySessionReads).length > 0 || Object.keys(sessionReadMarkers).length > 0;
1638
+ if (!hasData) return;
1639
+ const mergedReads = Object.fromEntries(
1640
+ Object.entries({ ...legacySessionReads, ...sessionReads }).filter(([, v]) => typeof v === "number" && Number.isFinite(v))
1641
+ );
1642
+ const cleanedMarkers = Object.fromEntries(
1643
+ Object.entries(sessionReadMarkers).filter(([, v]) => typeof v === "string")
1644
+ );
1645
+ const state = {
1646
+ recentActivity,
1647
+ savedProviderSessions,
1648
+ sessionReads: mergedReads,
1649
+ sessionReadMarkers: cleanedMarkers
1650
+ };
1651
+ (0, import_fs2.writeFileSync)(statePath, JSON.stringify(state, null, 2), { encoding: "utf-8", mode: 384 });
1652
+ }
1653
+ function loadConfig() {
1654
+ const configPath = getConfigPath();
1655
+ if (!(0, import_fs2.existsSync)(configPath)) {
1656
+ const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1657
+ try {
1658
+ saveConfig(initialized.config);
1659
+ } catch {
1660
+ }
1661
+ return initialized.config;
1662
+ }
1663
+ try {
1664
+ const raw = (0, import_fs2.readFileSync)(configPath, "utf-8");
1665
+ const parsed = JSON.parse(raw);
1666
+ migrateStateToStateFile(parsed);
1667
+ const normalizedInput = normalizeConfig(parsed);
1668
+ const ensured = ensureMachineId(normalizedInput);
1669
+ const normalized = ensured.config;
1670
+ if (ensured.changed || JSON.stringify(parsed) !== JSON.stringify(normalized)) {
1671
+ try {
1672
+ saveConfig(normalized);
1673
+ } catch {
1674
+ }
1675
+ }
1676
+ return normalized;
1677
+ } catch {
1678
+ const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1679
+ return initialized.config;
1680
+ }
1681
+ }
1682
+ function saveConfig(config) {
1683
+ const configPath = getConfigPath();
1684
+ const dir = getConfigDir();
1685
+ const normalized = normalizeConfig(config);
1686
+ if (!(0, import_fs2.existsSync)(dir)) {
1687
+ (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
1688
+ }
1689
+ (0, import_fs2.writeFileSync)(configPath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
1690
+ try {
1691
+ (0, import_fs2.chmodSync)(configPath, 384);
1692
+ } catch {
1693
+ }
1694
+ }
1695
+ function updateConfig(updates) {
1696
+ const config = loadConfig();
1697
+ const updated = { ...config, ...updates };
1698
+ saveConfig(updated);
1699
+ return updated;
1700
+ }
1701
+ function markSetupComplete(ideId, extensions) {
1702
+ const ideIds = Array.isArray(ideId) ? ideId : [ideId];
1703
+ return updateConfig({
1704
+ selectedIde: ideIds[0],
1705
+ configuredIdes: ideIds,
1706
+ installedExtensions: extensions,
1707
+ setupCompleted: true,
1708
+ setupDate: (/* @__PURE__ */ new Date()).toISOString()
1709
+ });
1710
+ }
1711
+ function isSetupComplete() {
1712
+ const config = loadConfig();
1713
+ return config.setupCompleted;
1714
+ }
1715
+ function resetConfig() {
1716
+ saveConfig({ ...DEFAULT_CONFIG });
1717
+ }
1718
+ var import_os, import_path2, import_fs2, import_crypto, DEFAULT_CONFIG, MACHINE_ID_PREFIX;
1719
+ var init_config = __esm({
1720
+ "src/config/config.ts"() {
1721
+ "use strict";
1722
+ import_os = require("os");
1723
+ import_path2 = require("path");
1724
+ import_fs2 = require("fs");
1725
+ import_crypto = require("crypto");
1726
+ DEFAULT_CONFIG = {
1727
+ serverUrl: "https://api.adhf.dev",
1728
+ allowServerApiProxy: false,
1729
+ selectedIde: null,
1730
+ configuredIdes: [],
1731
+ installedExtensions: [],
1732
+ userEmail: null,
1733
+ userName: null,
1734
+ setupCompleted: false,
1735
+ setupDate: null,
1736
+ enabledIdes: [],
1737
+ workspaces: [],
1738
+ defaultWorkspaceId: null,
1739
+ machineNickname: null,
1740
+ machineId: void 0,
1741
+ machineSecret: null,
1742
+ registeredMachineId: void 0,
1743
+ providerSettings: {},
1744
+ machineProviders: {},
1745
+ ideSettings: {},
1746
+ providerSourceMode: "normal",
1747
+ updateChannel: "stable",
1748
+ terminalSizingMode: "measured"
1749
+ };
1750
+ MACHINE_ID_PREFIX = "mach_";
1751
+ }
1752
+ });
1753
+
1505
1754
  // src/git/git-worktree.ts
1506
1755
  var git_worktree_exports = {};
1507
1756
  __export(git_worktree_exports, {
@@ -1812,255 +2061,6 @@ var init_git_worktree = __esm({
1812
2061
  }
1813
2062
  });
1814
2063
 
1815
- // src/config/config.ts
1816
- var config_exports = {};
1817
- __export(config_exports, {
1818
- generateMachineId: () => generateMachineId,
1819
- getConfigDir: () => getConfigDir,
1820
- getDaemonDataDir: () => getDaemonDataDir,
1821
- isSetupComplete: () => isSetupComplete,
1822
- isStableMachineId: () => isStableMachineId,
1823
- loadConfig: () => loadConfig,
1824
- markSetupComplete: () => markSetupComplete,
1825
- resetConfig: () => resetConfig,
1826
- resolveProviderSourceMode: () => resolveProviderSourceMode,
1827
- saveConfig: () => saveConfig,
1828
- updateConfig: () => updateConfig
1829
- });
1830
- function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
1831
- if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
1832
- return providerSourceMode;
1833
- }
1834
- return legacyDisableUpstream === true ? "no-upstream" : "normal";
1835
- }
1836
- function isPlainObject(value) {
1837
- return !!value && typeof value === "object" && !Array.isArray(value);
1838
- }
1839
- function asStringArray(value) {
1840
- if (!Array.isArray(value)) return [];
1841
- return value.filter((item) => typeof item === "string");
1842
- }
1843
- function asNullableString(value) {
1844
- return typeof value === "string" ? value : null;
1845
- }
1846
- function asOptionalString(value) {
1847
- return typeof value === "string" && value.trim() ? value : void 0;
1848
- }
1849
- function asBoolean(value, fallback) {
1850
- return typeof value === "boolean" ? value : fallback;
1851
- }
1852
- function normalizeMachineProviders(value) {
1853
- if (!isPlainObject(value)) return {};
1854
- const result = {};
1855
- for (const [providerType, raw] of Object.entries(value)) {
1856
- if (!isPlainObject(raw)) continue;
1857
- const entry = {};
1858
- if (raw.enabled === true) entry.enabled = true;
1859
- if (typeof raw.executable === "string" && raw.executable.trim()) {
1860
- entry.executable = raw.executable.trim();
1861
- }
1862
- if (Array.isArray(raw.args)) {
1863
- entry.args = raw.args.filter((arg) => typeof arg === "string");
1864
- }
1865
- if (isPlainObject(raw.lastDetection)) {
1866
- entry.lastDetection = raw.lastDetection;
1867
- }
1868
- if (isPlainObject(raw.lastVerification)) {
1869
- entry.lastVerification = raw.lastVerification;
1870
- }
1871
- result[providerType] = entry;
1872
- }
1873
- return result;
1874
- }
1875
- function normalizeConfig(raw) {
1876
- const parsed = isPlainObject(raw) ? raw : {};
1877
- return {
1878
- serverUrl: typeof parsed.serverUrl === "string" && parsed.serverUrl.trim() ? parsed.serverUrl : DEFAULT_CONFIG.serverUrl,
1879
- allowServerApiProxy: asBoolean(parsed.allowServerApiProxy, DEFAULT_CONFIG.allowServerApiProxy ?? false),
1880
- selectedIde: asNullableString(parsed.selectedIde),
1881
- configuredIdes: asStringArray(parsed.configuredIdes),
1882
- installedExtensions: asStringArray(parsed.installedExtensions),
1883
- userEmail: asNullableString(parsed.userEmail),
1884
- userName: asNullableString(parsed.userName),
1885
- setupCompleted: asBoolean(parsed.setupCompleted, DEFAULT_CONFIG.setupCompleted),
1886
- setupDate: asNullableString(parsed.setupDate),
1887
- enabledIdes: asStringArray(parsed.enabledIdes),
1888
- workspaces: Array.isArray(parsed.workspaces) ? parsed.workspaces : [],
1889
- defaultWorkspaceId: asNullableString(parsed.defaultWorkspaceId) ?? asNullableString(parsed.activeWorkspaceId),
1890
- machineNickname: asNullableString(parsed.machineNickname),
1891
- machineId: asOptionalString(parsed.machineId),
1892
- machineSecret: parsed.machineSecret === null ? null : asOptionalString(parsed.machineSecret),
1893
- registeredMachineId: asOptionalString(parsed.registeredMachineId),
1894
- providerSettings: isPlainObject(parsed.providerSettings) ? parsed.providerSettings : {},
1895
- machineProviders: normalizeMachineProviders(parsed.machineProviders),
1896
- ideSettings: isPlainObject(parsed.ideSettings) ? parsed.ideSettings : {},
1897
- providerSourceMode: resolveProviderSourceMode(parsed.providerSourceMode, parsed.disableUpstream),
1898
- providerDir: asOptionalString(parsed.providerDir),
1899
- updateChannel: parsed.updateChannel === "preview" ? "preview" : "stable",
1900
- terminalSizingMode: parsed.terminalSizingMode === "fit" ? "fit" : "measured"
1901
- };
1902
- }
1903
- function generateMachineId() {
1904
- return `${MACHINE_ID_PREFIX}${(0, import_crypto.randomUUID)().replace(/-/g, "")}`;
1905
- }
1906
- function isStableMachineId(machineId) {
1907
- return typeof machineId === "string" && machineId.startsWith(MACHINE_ID_PREFIX);
1908
- }
1909
- function ensureMachineId(config) {
1910
- if (isStableMachineId(config.machineId)) {
1911
- return { config, changed: false };
1912
- }
1913
- return {
1914
- config: {
1915
- ...config,
1916
- machineId: generateMachineId()
1917
- },
1918
- changed: true
1919
- };
1920
- }
1921
- function getConfigDir() {
1922
- const override = process.env.ADHDEV_CONFIG_DIR;
1923
- const dir = override && override.trim() ? override.trim() : (0, import_path2.join)((0, import_os.homedir)(), ".adhdev");
1924
- if (!(0, import_fs2.existsSync)(dir)) {
1925
- (0, import_fs2.mkdirSync)(dir, { recursive: true });
1926
- }
1927
- return dir;
1928
- }
1929
- function getDaemonDataDir() {
1930
- const dir = (0, import_path2.join)(getConfigDir(), "daemon");
1931
- if (!(0, import_fs2.existsSync)(dir)) {
1932
- (0, import_fs2.mkdirSync)(dir, { recursive: true });
1933
- }
1934
- return dir;
1935
- }
1936
- function getConfigPath() {
1937
- return (0, import_path2.join)(getConfigDir(), "config.json");
1938
- }
1939
- function migrateStateToStateFile(raw) {
1940
- const statePath = (0, import_path2.join)(getConfigDir(), "state.json");
1941
- if ((0, import_fs2.existsSync)(statePath)) return;
1942
- const recentActivity = Array.isArray(raw.recentActivity) ? raw.recentActivity : [];
1943
- const savedProviderSessions = Array.isArray(raw.savedProviderSessions) ? raw.savedProviderSessions : [];
1944
- const legacySessionReads = isPlainObject(raw.recentSessionReads) ? raw.recentSessionReads : {};
1945
- const sessionReads = isPlainObject(raw.sessionReads) ? raw.sessionReads : {};
1946
- const sessionReadMarkers = isPlainObject(raw.sessionReadMarkers) ? raw.sessionReadMarkers : {};
1947
- const hasData = recentActivity.length > 0 || savedProviderSessions.length > 0 || Object.keys(sessionReads).length > 0 || Object.keys(legacySessionReads).length > 0 || Object.keys(sessionReadMarkers).length > 0;
1948
- if (!hasData) return;
1949
- const mergedReads = Object.fromEntries(
1950
- Object.entries({ ...legacySessionReads, ...sessionReads }).filter(([, v]) => typeof v === "number" && Number.isFinite(v))
1951
- );
1952
- const cleanedMarkers = Object.fromEntries(
1953
- Object.entries(sessionReadMarkers).filter(([, v]) => typeof v === "string")
1954
- );
1955
- const state = {
1956
- recentActivity,
1957
- savedProviderSessions,
1958
- sessionReads: mergedReads,
1959
- sessionReadMarkers: cleanedMarkers
1960
- };
1961
- (0, import_fs2.writeFileSync)(statePath, JSON.stringify(state, null, 2), { encoding: "utf-8", mode: 384 });
1962
- }
1963
- function loadConfig() {
1964
- const configPath = getConfigPath();
1965
- if (!(0, import_fs2.existsSync)(configPath)) {
1966
- const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1967
- try {
1968
- saveConfig(initialized.config);
1969
- } catch {
1970
- }
1971
- return initialized.config;
1972
- }
1973
- try {
1974
- const raw = (0, import_fs2.readFileSync)(configPath, "utf-8");
1975
- const parsed = JSON.parse(raw);
1976
- migrateStateToStateFile(parsed);
1977
- const normalizedInput = normalizeConfig(parsed);
1978
- const ensured = ensureMachineId(normalizedInput);
1979
- const normalized = ensured.config;
1980
- if (ensured.changed || JSON.stringify(parsed) !== JSON.stringify(normalized)) {
1981
- try {
1982
- saveConfig(normalized);
1983
- } catch {
1984
- }
1985
- }
1986
- return normalized;
1987
- } catch {
1988
- const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1989
- return initialized.config;
1990
- }
1991
- }
1992
- function saveConfig(config) {
1993
- const configPath = getConfigPath();
1994
- const dir = getConfigDir();
1995
- const normalized = normalizeConfig(config);
1996
- if (!(0, import_fs2.existsSync)(dir)) {
1997
- (0, import_fs2.mkdirSync)(dir, { recursive: true, mode: 448 });
1998
- }
1999
- (0, import_fs2.writeFileSync)(configPath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
2000
- try {
2001
- (0, import_fs2.chmodSync)(configPath, 384);
2002
- } catch {
2003
- }
2004
- }
2005
- function updateConfig(updates) {
2006
- const config = loadConfig();
2007
- const updated = { ...config, ...updates };
2008
- saveConfig(updated);
2009
- return updated;
2010
- }
2011
- function markSetupComplete(ideId, extensions) {
2012
- const ideIds = Array.isArray(ideId) ? ideId : [ideId];
2013
- return updateConfig({
2014
- selectedIde: ideIds[0],
2015
- configuredIdes: ideIds,
2016
- installedExtensions: extensions,
2017
- setupCompleted: true,
2018
- setupDate: (/* @__PURE__ */ new Date()).toISOString()
2019
- });
2020
- }
2021
- function isSetupComplete() {
2022
- const config = loadConfig();
2023
- return config.setupCompleted;
2024
- }
2025
- function resetConfig() {
2026
- saveConfig({ ...DEFAULT_CONFIG });
2027
- }
2028
- var import_os, import_path2, import_fs2, import_crypto, DEFAULT_CONFIG, MACHINE_ID_PREFIX;
2029
- var init_config = __esm({
2030
- "src/config/config.ts"() {
2031
- "use strict";
2032
- import_os = require("os");
2033
- import_path2 = require("path");
2034
- import_fs2 = require("fs");
2035
- import_crypto = require("crypto");
2036
- DEFAULT_CONFIG = {
2037
- serverUrl: "https://api.adhf.dev",
2038
- allowServerApiProxy: false,
2039
- selectedIde: null,
2040
- configuredIdes: [],
2041
- installedExtensions: [],
2042
- userEmail: null,
2043
- userName: null,
2044
- setupCompleted: false,
2045
- setupDate: null,
2046
- enabledIdes: [],
2047
- workspaces: [],
2048
- defaultWorkspaceId: null,
2049
- machineNickname: null,
2050
- machineId: void 0,
2051
- machineSecret: null,
2052
- registeredMachineId: void 0,
2053
- providerSettings: {},
2054
- machineProviders: {},
2055
- ideSettings: {},
2056
- providerSourceMode: "normal",
2057
- updateChannel: "stable",
2058
- terminalSizingMode: "measured"
2059
- };
2060
- MACHINE_ID_PREFIX = "mach_";
2061
- }
2062
- });
2063
-
2064
2064
  // src/config/workspaces.ts
2065
2065
  function expandPath(p) {
2066
2066
  const t = (p || "").trim();
@@ -2557,12 +2557,12 @@ function readGitSubmodules(value, parentRepoRoot) {
2557
2557
  if (!Array.isArray(value)) return void 0;
2558
2558
  const submodules = value.map((entry) => {
2559
2559
  const submodule = readRecord(entry);
2560
- const path43 = readString2(submodule.path);
2560
+ const path44 = readString2(submodule.path);
2561
2561
  const commit = readString2(submodule.commit);
2562
- const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path43);
2563
- if (!path43 || !commit) return null;
2562
+ const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path44);
2563
+ if (!path44 || !commit) return null;
2564
2564
  const result = {
2565
- path: path43,
2565
+ path: path44,
2566
2566
  commit,
2567
2567
  dirty: readBoolean(submodule.dirty) ?? false,
2568
2568
  outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
@@ -2887,10 +2887,10 @@ function getMeshConfigPath() {
2887
2887
  return (0, import_path3.join)(getConfigDir(), "meshes.json");
2888
2888
  }
2889
2889
  function loadMeshConfig() {
2890
- const path43 = getMeshConfigPath();
2891
- if (!(0, import_fs3.existsSync)(path43)) return { meshes: [] };
2890
+ const path44 = getMeshConfigPath();
2891
+ if (!(0, import_fs3.existsSync)(path44)) return { meshes: [] };
2892
2892
  try {
2893
- const raw = JSON.parse((0, import_fs3.readFileSync)(path43, "utf-8"));
2893
+ const raw = JSON.parse((0, import_fs3.readFileSync)(path44, "utf-8"));
2894
2894
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
2895
2895
  const config = raw;
2896
2896
  const migrated = migrateLoadedMeshConfig(config);
@@ -2939,16 +2939,16 @@ function normalizeCapabilityTags(value) {
2939
2939
  return tags.length ? tags : void 0;
2940
2940
  }
2941
2941
  function saveMeshConfig(config) {
2942
- const path43 = getMeshConfigPath();
2943
- (0, import_fs3.writeFileSync)(path43, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2942
+ const path44 = getMeshConfigPath();
2943
+ (0, import_fs3.writeFileSync)(path44, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2944
2944
  }
2945
2945
  function normalizeRepoIdentity(remoteUrl) {
2946
2946
  let identity = remoteUrl.trim();
2947
2947
  if (identity.startsWith("http://") || identity.startsWith("https://")) {
2948
2948
  try {
2949
2949
  const url = new URL(identity);
2950
- const path43 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2951
- return `${url.hostname}/${path43}`;
2950
+ const path44 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2951
+ return `${url.hostname}/${path44}`;
2952
2952
  } catch {
2953
2953
  }
2954
2954
  }
@@ -3201,12 +3201,23 @@ function addNode(meshId, opts) {
3201
3201
  if (mesh.nodes.some((n) => n.workspace === opts.workspace)) {
3202
3202
  throw new Error("This workspace is already in the mesh");
3203
3203
  }
3204
+ const machineNickname = (() => {
3205
+ const explicit = typeof opts.machineNickname === "string" ? opts.machineNickname.trim() : "";
3206
+ if (explicit) return explicit;
3207
+ try {
3208
+ const local = loadConfig().machineNickname;
3209
+ return typeof local === "string" && local.trim() ? local.trim() : void 0;
3210
+ } catch {
3211
+ return void 0;
3212
+ }
3213
+ })();
3204
3214
  const node = {
3205
3215
  id: `node_${(0, import_crypto3.randomUUID)().replace(/-/g, "")}`,
3206
3216
  workspace: opts.workspace.trim(),
3207
3217
  repoRoot: opts.repoRoot,
3208
3218
  daemonId: opts.daemonId,
3209
3219
  machineId: opts.machineId,
3220
+ ...machineNickname ? { machineNickname } : {},
3210
3221
  capabilities: normalizeCapabilityTags(opts.capabilities),
3211
3222
  userOverrides: opts.userOverrides || {},
3212
3223
  policy: opts.policy || {},
@@ -3241,6 +3252,7 @@ function updateNode(meshId, nodeId, opts) {
3241
3252
  if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
3242
3253
  if (opts.reportedPlatform && opts.reportedPlatform.trim()) node.reportedPlatform = opts.reportedPlatform.trim();
3243
3254
  if (opts.reportedArch && opts.reportedArch.trim()) node.reportedArch = opts.reportedArch.trim();
3255
+ if (opts.reportedMachineNickname && opts.reportedMachineNickname.trim()) node.machineNickname = opts.reportedMachineNickname.trim();
3244
3256
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
3245
3257
  if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
3246
3258
  if (Object.prototype.hasOwnProperty.call(opts, "systemPrompt")) {
@@ -4175,10 +4187,10 @@ function rotateArchiveFile(meshId, archivePath) {
4175
4187
  }
4176
4188
  }
4177
4189
  function readArchivedCounts(meshId) {
4178
- const path43 = getArchivedCountsPath(meshId);
4179
- if (!(0, import_fs4.existsSync)(path43)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4190
+ const path44 = getArchivedCountsPath(meshId);
4191
+ if (!(0, import_fs4.existsSync)(path44)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4180
4192
  try {
4181
- return JSON.parse((0, import_fs4.readFileSync)(path43, "utf-8"));
4193
+ return JSON.parse((0, import_fs4.readFileSync)(path44, "utf-8"));
4182
4194
  } catch {
4183
4195
  return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4184
4196
  }
@@ -5388,11 +5400,11 @@ function readNodeReporter(node, key2) {
5388
5400
  function buildMeshNodeCapabilityTags(node, providerType) {
5389
5401
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
5390
5402
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
5391
- const os30 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5403
+ const os31 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5392
5404
  const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
5393
5405
  return normalizeMeshCapabilityTags([
5394
5406
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
5395
- `os=${os30}`,
5407
+ `os=${os31}`,
5396
5408
  `arch=${arch2}`,
5397
5409
  ...provider ? [`provider=${provider}`] : [],
5398
5410
  // Worktree nodes automatically expose a "worktree=<branch>" tag so that
@@ -6286,10 +6298,10 @@ var init_mesh_runtime_store = __esm({
6286
6298
  this.migratedMeshIds.add(meshId);
6287
6299
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
6288
6300
  if (count.count > 0) return;
6289
- const path43 = legacyQueuePath(meshId);
6290
- if (!(0, import_fs5.existsSync)(path43)) return;
6301
+ const path44 = legacyQueuePath(meshId);
6302
+ if (!(0, import_fs5.existsSync)(path44)) return;
6291
6303
  try {
6292
- const entries = JSON.parse((0, import_fs5.readFileSync)(path43, "utf-8"));
6304
+ const entries = JSON.parse((0, import_fs5.readFileSync)(path44, "utf-8"));
6293
6305
  if (!Array.isArray(entries)) return;
6294
6306
  const insert = this.db.prepare(`
6295
6307
  INSERT OR REPLACE INTO mesh_queue (
@@ -8113,8 +8125,8 @@ function resolveMeshCoordinatorSetup(options) {
8113
8125
  }
8114
8126
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
8115
8127
  if (mcpConfig.mode === "auto_import") {
8116
- const path43 = mcpConfig.path?.trim();
8117
- if (!path43) {
8128
+ const path44 = mcpConfig.path?.trim();
8129
+ if (!path44) {
8118
8130
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
8119
8131
  }
8120
8132
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -8134,7 +8146,7 @@ function resolveMeshCoordinatorSetup(options) {
8134
8146
  return {
8135
8147
  kind: "auto_import",
8136
8148
  serverName,
8137
- configPath: resolveMcpConfigPath(path43, workspace),
8149
+ configPath: resolveMcpConfigPath(path44, workspace),
8138
8150
  configFormat: mcpConfig.format,
8139
8151
  mcpServer
8140
8152
  };
@@ -8335,8 +8347,8 @@ function stripCoordinatorWrapperFile(filePath) {
8335
8347
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
8336
8348
  if (!remaining.trim()) {
8337
8349
  try {
8338
- const fs38 = require("fs");
8339
- fs38.unlinkSync(filePath);
8350
+ const fs39 = require("fs");
8351
+ fs39.unlinkSync(filePath);
8340
8352
  } catch {
8341
8353
  }
8342
8354
  } else {
@@ -8438,10 +8450,10 @@ function getRegistryPath() {
8438
8450
  return (0, import_path6.join)(getDaemonDataDir(), "mesh-coordinators.json");
8439
8451
  }
8440
8452
  function loadMeshCoordinatorRegistry() {
8441
- const path43 = getRegistryPath();
8442
- if (!(0, import_fs6.existsSync)(path43)) return;
8453
+ const path44 = getRegistryPath();
8454
+ if (!(0, import_fs6.existsSync)(path44)) return;
8443
8455
  try {
8444
- const raw = JSON.parse((0, import_fs6.readFileSync)(path43, "utf-8"));
8456
+ const raw = JSON.parse((0, import_fs6.readFileSync)(path44, "utf-8"));
8445
8457
  if (!Array.isArray(raw)) return;
8446
8458
  _registry.clear();
8447
8459
  for (const entry of raw) {
@@ -8612,8 +8624,8 @@ function validateMeshRefineConfig(config, source = "inline") {
8612
8624
  if (rejectedCommands.length) errors.push("one or more validation commands are invalid");
8613
8625
  return { valid: errors.length === 0, errors, bootstrapCommands, commands, rejectedCommands, bootstrapMode, deprecationWarnings };
8614
8626
  }
8615
- function parseConfigText2(path43, text) {
8616
- if (/\.json$/i.test(path43)) return JSON.parse(text);
8627
+ function parseConfigText2(path44, text) {
8628
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
8617
8629
  return yaml2.load(text);
8618
8630
  }
8619
8631
  function loadMeshRefineConfig(mesh, workspace) {
@@ -8940,8 +8952,8 @@ function isCleanIgnoringSubmoduleGitlinks(porcelain, submodulePaths) {
8940
8952
  const lines = porcelain.split(/\r?\n/).filter((line) => line.length > 0);
8941
8953
  for (const line of lines) {
8942
8954
  const status = line.slice(0, 2);
8943
- const path43 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
8944
- const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path43);
8955
+ const path44 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
8956
+ const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path44);
8945
8957
  if (!isGitlinkPointerMove) return false;
8946
8958
  }
8947
8959
  return true;
@@ -8972,8 +8984,8 @@ function isWorktreeBootstrapStaleRunning(node, nowMs = Date.now()) {
8972
8984
  return false;
8973
8985
  }
8974
8986
  }
8975
- function parseConfigText3(path43, text) {
8976
- if (/\.json$/i.test(path43)) return JSON.parse(text);
8987
+ function parseConfigText3(path44, text) {
8988
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
8977
8989
  return yaml3.load(text);
8978
8990
  }
8979
8991
  function truncateOutput(value) {
@@ -9118,16 +9130,16 @@ async function runMeshWorktreeBootstrap(mesh, workspace) {
9118
9130
  const startedAt = Date.now();
9119
9131
  state.lastCommand = command.displayCommand;
9120
9132
  const resolvedCommand = resolveWin32Executable(command.command);
9121
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, command.args);
9133
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, command.args);
9122
9134
  try {
9123
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
9135
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
9124
9136
  cwd,
9125
9137
  encoding: "utf8",
9126
9138
  timeout: command.timeoutMs || DEFAULT_TIMEOUT_MS2,
9127
9139
  maxBuffer: command.outputLimitBytes || DEFAULT_OUTPUT_LIMIT_BYTES,
9128
9140
  env: { ...process.env, CI: process.env.CI || "1", ...command.env || {} },
9129
9141
  windowsHide: true,
9130
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9142
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9131
9143
  });
9132
9144
  state.commandsRun?.push({
9133
9145
  command: command.command,
@@ -9250,8 +9262,8 @@ __export(mesh_json_config_exports, {
9250
9262
  function isRecord3(value) {
9251
9263
  return !!value && typeof value === "object" && !Array.isArray(value);
9252
9264
  }
9253
- function parseConfigText4(path43, text) {
9254
- if (/\.json$/i.test(path43)) return JSON.parse(text);
9265
+ function parseConfigText4(path44, text) {
9266
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
9255
9267
  return yaml4.load(text);
9256
9268
  }
9257
9269
  function normalizeOperatingNote(value) {
@@ -11057,10 +11069,10 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11057
11069
  const primaryDaemonId = daemonIds[0];
11058
11070
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11059
11071
  const events = [];
11060
- for (const path43 of paths) {
11061
- if (!(0, import_fs11.existsSync)(path43)) continue;
11072
+ for (const path44 of paths) {
11073
+ if (!(0, import_fs11.existsSync)(path44)) continue;
11062
11074
  try {
11063
- const raw = (0, import_fs11.readFileSync)(path43, "utf-8");
11075
+ const raw = (0, import_fs11.readFileSync)(path44, "utf-8");
11064
11076
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
11065
11077
  try {
11066
11078
  return [JSON.parse(line)];
@@ -11068,7 +11080,7 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11068
11080
  return [];
11069
11081
  }
11070
11082
  });
11071
- const filtered = primaryDaemonId && path43 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11083
+ const filtered = primaryDaemonId && path44 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11072
11084
  events.push(...filtered);
11073
11085
  } catch {
11074
11086
  }
@@ -11133,11 +11145,11 @@ function reconcilePendingMeshCoordinatorEvents(meshId, events) {
11133
11145
  const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
11134
11146
  return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
11135
11147
  }
11136
- function trimPendingEventsIfNeeded(path43) {
11148
+ function trimPendingEventsIfNeeded(path44) {
11137
11149
  try {
11138
- if (!(0, import_fs11.existsSync)(path43)) return;
11139
- if ((0, import_fs11.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
11140
- const lines = (0, import_fs11.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
11150
+ if (!(0, import_fs11.existsSync)(path44)) return;
11151
+ if ((0, import_fs11.statSync)(path44).size <= MAX_PENDING_EVENTS_BYTES) return;
11152
+ const lines = (0, import_fs11.readFileSync)(path44, "utf-8").split("\n").filter(Boolean);
11141
11153
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
11142
11154
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
11143
11155
  for (const line of dropped) {
@@ -11170,7 +11182,7 @@ function trimPendingEventsIfNeeded(path43) {
11170
11182
  LOG.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
11171
11183
  }
11172
11184
  }
11173
- (0, import_fs11.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11185
+ (0, import_fs11.writeFileSync)(path44, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11174
11186
  } catch {
11175
11187
  }
11176
11188
  }
@@ -11200,9 +11212,9 @@ function queuePendingMeshCoordinatorEvent(event) {
11200
11212
  } catch {
11201
11213
  }
11202
11214
  try {
11203
- const path43 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11204
- trimPendingEventsIfNeeded(path43);
11205
- (0, import_fs11.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
11215
+ const path44 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11216
+ trimPendingEventsIfNeeded(path44);
11217
+ (0, import_fs11.appendFileSync)(path44, JSON.stringify(event) + "\n", "utf-8");
11206
11218
  } catch (e) {
11207
11219
  if (!sqliteOk) throw e;
11208
11220
  LOG.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -11213,10 +11225,10 @@ function queuePendingMeshCoordinatorEvent(event) {
11213
11225
  return false;
11214
11226
  }
11215
11227
  }
11216
- function atomicDrainFile(path43) {
11217
- const tmpPath = `${path43}.draining`;
11228
+ function atomicDrainFile(path44) {
11229
+ const tmpPath = `${path44}.draining`;
11218
11230
  try {
11219
- (0, import_fs11.renameSync)(path43, tmpPath);
11231
+ (0, import_fs11.renameSync)(path44, tmpPath);
11220
11232
  } catch {
11221
11233
  return null;
11222
11234
  }
@@ -11235,10 +11247,10 @@ function atomicDrainFile(path43) {
11235
11247
  return null;
11236
11248
  }
11237
11249
  }
11238
- function selectiveDrainFile(path43, predicate) {
11239
- const tmpPath = `${path43}.draining`;
11250
+ function selectiveDrainFile(path44, predicate) {
11251
+ const tmpPath = `${path44}.draining`;
11240
11252
  try {
11241
- (0, import_fs11.renameSync)(path43, tmpPath);
11253
+ (0, import_fs11.renameSync)(path44, tmpPath);
11242
11254
  } catch {
11243
11255
  return [];
11244
11256
  }
@@ -11270,12 +11282,12 @@ function selectiveDrainFile(path43, predicate) {
11270
11282
  }
11271
11283
  try {
11272
11284
  if (keptLines.length > 0) {
11273
- (0, import_fs11.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
11285
+ (0, import_fs11.writeFileSync)(path44, keptLines.join("\n") + "\n", "utf-8");
11274
11286
  }
11275
11287
  (0, import_fs11.unlinkSync)(tmpPath);
11276
11288
  } catch {
11277
11289
  try {
11278
- if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path43)) (0, import_fs11.renameSync)(tmpPath, path43);
11290
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path44)) (0, import_fs11.renameSync)(tmpPath, path44);
11279
11291
  } catch {
11280
11292
  }
11281
11293
  return [];
@@ -11310,16 +11322,16 @@ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId, opts) {
11310
11322
  LOG.warn("MeshEvents", `SQLite pending-event drain failed for mesh ${meshId}; JSONL fallback only: ${e?.message || e}`);
11311
11323
  }
11312
11324
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11313
- for (const path43 of paths) {
11314
- const isSharedFile = !!primaryDaemonId && path43 === getPendingEventsPath(meshId);
11325
+ for (const path44 of paths) {
11326
+ const isSharedFile = !!primaryDaemonId && path44 === getPendingEventsPath(meshId);
11315
11327
  const targets = (e) => !isSharedFile || !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId);
11316
11328
  if (onlyEvents) {
11317
- for (const event of selectiveDrainFile(path43, (e) => targets(e) && matchesFilter(e.event))) {
11329
+ for (const event of selectiveDrainFile(path44, (e) => targets(e) && matchesFilter(e.event))) {
11318
11330
  pushUnique(event);
11319
11331
  }
11320
11332
  continue;
11321
11333
  }
11322
- const content = atomicDrainFile(path43);
11334
+ const content = atomicDrainFile(path44);
11323
11335
  if (!content) continue;
11324
11336
  const parsed = content.split("\n").filter(Boolean).flatMap((line) => {
11325
11337
  try {
@@ -11355,9 +11367,9 @@ function retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId)
11355
11367
  const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
11356
11368
  const primaryDaemonId = daemonIds[0];
11357
11369
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11358
- for (const path43 of paths) {
11370
+ for (const path44 of paths) {
11359
11371
  try {
11360
- removed += selectiveDrainFile(path43, matchesTask).length;
11372
+ removed += selectiveDrainFile(path44, matchesTask).length;
11361
11373
  } catch {
11362
11374
  }
11363
11375
  }
@@ -11398,9 +11410,9 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
11398
11410
  } catch {
11399
11411
  }
11400
11412
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11401
- for (const path43 of paths) {
11402
- if ((0, import_fs11.existsSync)(path43)) try {
11403
- (0, import_fs11.unlinkSync)(path43);
11413
+ for (const path44 of paths) {
11414
+ if ((0, import_fs11.existsSync)(path44)) try {
11415
+ (0, import_fs11.unlinkSync)(path44);
11404
11416
  } catch {
11405
11417
  }
11406
11418
  }
@@ -11872,9 +11884,9 @@ function findBinary(name) {
11872
11884
  for (const ext of exes) {
11873
11885
  const fullPath = path11.join(p, trimmed + ext);
11874
11886
  try {
11875
- const fs38 = require("fs");
11876
- if (fs38.existsSync(fullPath)) {
11877
- const stat2 = fs38.statSync(fullPath);
11887
+ const fs39 = require("fs");
11888
+ if (fs39.existsSync(fullPath)) {
11889
+ const stat2 = fs39.statSync(fullPath);
11878
11890
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
11879
11891
  return fullPath;
11880
11892
  }
@@ -11888,12 +11900,12 @@ function findBinary(name) {
11888
11900
  function isScriptBinary(binaryPath) {
11889
11901
  if (!path11.isAbsolute(binaryPath)) return false;
11890
11902
  try {
11891
- const fs38 = require("fs");
11892
- const resolved = fs38.realpathSync(binaryPath);
11903
+ const fs39 = require("fs");
11904
+ const resolved = fs39.realpathSync(binaryPath);
11893
11905
  const head = Buffer.alloc(8);
11894
- const fd = fs38.openSync(resolved, "r");
11895
- fs38.readSync(fd, head, 0, 8, 0);
11896
- fs38.closeSync(fd);
11906
+ const fd = fs39.openSync(resolved, "r");
11907
+ fs39.readSync(fd, head, 0, 8, 0);
11908
+ fs39.closeSync(fd);
11897
11909
  let i = 0;
11898
11910
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
11899
11911
  return head[i] === 35 && head[i + 1] === 33;
@@ -11904,12 +11916,12 @@ function isScriptBinary(binaryPath) {
11904
11916
  function looksLikeMachOOrElf(filePath) {
11905
11917
  if (!path11.isAbsolute(filePath)) return false;
11906
11918
  try {
11907
- const fs38 = require("fs");
11908
- const resolved = fs38.realpathSync(filePath);
11919
+ const fs39 = require("fs");
11920
+ const resolved = fs39.realpathSync(filePath);
11909
11921
  const buf = Buffer.alloc(8);
11910
- const fd = fs38.openSync(resolved, "r");
11911
- fs38.readSync(fd, buf, 0, 8, 0);
11912
- fs38.closeSync(fd);
11922
+ const fd = fs39.openSync(resolved, "r");
11923
+ fs39.readSync(fd, buf, 0, 8, 0);
11924
+ fs39.closeSync(fd);
11913
11925
  let i = 0;
11914
11926
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
11915
11927
  const b = buf.subarray(i);
@@ -12196,19 +12208,19 @@ async function resolveDetectionPath(command, whichCmd) {
12196
12208
  return null;
12197
12209
  }
12198
12210
  function execAsync(cmd, timeoutMs = 5e3) {
12199
- return new Promise((resolve24) => {
12211
+ return new Promise((resolve25) => {
12200
12212
  const child = (0, import_child_process2.exec)(cmd, {
12201
12213
  encoding: "utf-8",
12202
12214
  timeout: timeoutMs,
12203
12215
  ...process.platform === "win32" ? { windowsHide: true } : {}
12204
12216
  }, (err, stdout) => {
12205
12217
  if (err || !stdout?.trim()) {
12206
- resolve24(null);
12218
+ resolve25(null);
12207
12219
  } else {
12208
- resolve24(stdout.trim());
12220
+ resolve25(stdout.trim());
12209
12221
  }
12210
12222
  });
12211
- child.on("error", () => resolve24(null));
12223
+ child.on("error", () => resolve25(null));
12212
12224
  });
12213
12225
  }
12214
12226
  async function detectCLIs(providerLoader, options) {
@@ -12334,7 +12346,7 @@ var init_mesh_event_trace = __esm({
12334
12346
  // src/mesh/mesh-warmup-deadline.ts
12335
12347
  function awaitWithWarmupDeadline(work, opts) {
12336
12348
  const pollMs = Math.max(1, Math.min(opts.pollIntervalMs ?? 200, opts.connectTimeoutMs));
12337
- return new Promise((resolve24, reject) => {
12349
+ return new Promise((resolve25, reject) => {
12338
12350
  let done = false;
12339
12351
  let poll;
12340
12352
  let responseTimer;
@@ -12384,7 +12396,7 @@ function awaitWithWarmupDeadline(work, opts) {
12384
12396
  if (typeof poll.unref === "function") poll.unref();
12385
12397
  }
12386
12398
  work.then(
12387
- (val) => settle(() => resolve24(val)),
12399
+ (val) => settle(() => resolve25(val)),
12388
12400
  (err) => settle(() => reject(err))
12389
12401
  );
12390
12402
  });
@@ -12487,7 +12499,7 @@ async function waitForLocalSessionReady(components, sessionId) {
12487
12499
  const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
12488
12500
  while (Date.now() < deadline) {
12489
12501
  if (adapter.isReady() || adapter.currentStatus === "idle") return;
12490
- await new Promise((resolve24) => setTimeout(resolve24, LOCAL_LAUNCH_READY_POLL_MS));
12502
+ await new Promise((resolve25) => setTimeout(resolve25, LOCAL_LAUNCH_READY_POLL_MS));
12491
12503
  }
12492
12504
  LOG.warn("MeshQueue", `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
12493
12505
  }
@@ -18918,7 +18930,7 @@ function getCliValidator() {
18918
18930
  return _cliValidator;
18919
18931
  }
18920
18932
  function formatIssue(err) {
18921
- const path43 = err.instancePath || "";
18933
+ const path44 = err.instancePath || "";
18922
18934
  const params = err.params;
18923
18935
  let message = err.message || "validation failed";
18924
18936
  let allowed;
@@ -18936,7 +18948,7 @@ function formatIssue(err) {
18936
18948
  } else if (err.keyword === "type") {
18937
18949
  message = `must be ${params.type}`;
18938
18950
  }
18939
- return { path: path43, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
18951
+ return { path: path44, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
18940
18952
  }
18941
18953
  function validateCliProviderManifest(manifest) {
18942
18954
  const validator = getCliValidator();
@@ -19232,40 +19244,40 @@ function validateFsmSpec(raw) {
19232
19244
  }
19233
19245
  return errs;
19234
19246
  }
19235
- function validateCondition(c, sectionIds, path43) {
19247
+ function validateCondition(c, sectionIds, path44) {
19236
19248
  const errs = [];
19237
19249
  const w = c;
19238
19250
  if ("all" in w) {
19239
- w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path43}.all[${i}]`)));
19251
+ w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.all[${i}]`)));
19240
19252
  return errs;
19241
19253
  }
19242
19254
  if ("any" in w) {
19243
- w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path43}.any[${i}]`)));
19255
+ w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.any[${i}]`)));
19244
19256
  return errs;
19245
19257
  }
19246
19258
  if ("not" in w) {
19247
- errs.push(...validateCondition(w.not, sectionIds, `${path43}.not`));
19259
+ errs.push(...validateCondition(w.not, sectionIds, `${path44}.not`));
19248
19260
  return errs;
19249
19261
  }
19250
19262
  if ("matches" in w) {
19251
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path43}.section "${w.section}" unknown`);
19263
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
19252
19264
  try {
19253
19265
  new RegExp(w.matches, w.flags ?? "i");
19254
19266
  } catch (e) {
19255
- errs.push(`${path43}.matches invalid regex: ${e.message}`);
19267
+ errs.push(`${path44}.matches invalid regex: ${e.message}`);
19256
19268
  }
19257
19269
  return errs;
19258
19270
  }
19259
19271
  if ("cursor_above" in w && "changed" in w) return errs;
19260
19272
  if ("elapsed_ms" in w) {
19261
- if (typeof w.elapsed_ms !== "number") errs.push(`${path43}.elapsed_ms must be a number`);
19273
+ if (typeof w.elapsed_ms !== "number") errs.push(`${path44}.elapsed_ms must be a number`);
19262
19274
  return errs;
19263
19275
  }
19264
19276
  if ("stable_ms" in w) {
19265
- if (typeof w.stable_ms !== "number") errs.push(`${path43}.stable_ms must be a number`);
19277
+ if (typeof w.stable_ms !== "number") errs.push(`${path44}.stable_ms must be a number`);
19266
19278
  return errs;
19267
19279
  }
19268
- errs.push(`${path43} is not a recognized condition`);
19280
+ errs.push(`${path44} is not a recognized condition`);
19269
19281
  return errs;
19270
19282
  }
19271
19283
  var fs10;
@@ -19760,8 +19772,8 @@ var init_pty_transport = __esm({
19760
19772
  let cwd = options.cwd;
19761
19773
  if (cwd) {
19762
19774
  try {
19763
- const fs38 = require("fs");
19764
- const stat2 = fs38.statSync(cwd);
19775
+ const fs39 = require("fs");
19776
+ const stat2 = fs39.statSync(cwd);
19765
19777
  if (!stat2.isDirectory()) cwd = os14.homedir();
19766
19778
  } catch {
19767
19779
  cwd = os14.homedir();
@@ -22309,7 +22321,7 @@ ${lastSnapshot}`;
22309
22321
  `[${this.cliType}] Waiting for interactive prompt: status=${status} stableMs=${stableMs} recentOutputMs=${recentlyOutput} screen=${JSON.stringify(summarizeCliTraceText(screenText, 220)).slice(0, 260)}`
22310
22322
  );
22311
22323
  }
22312
- await new Promise((resolve24) => setTimeout(resolve24, 50));
22324
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
22313
22325
  }
22314
22326
  const finalScreenText = this.terminalScreen.getText() || "";
22315
22327
  LOG.warn(
@@ -22604,7 +22616,7 @@ ${lastSnapshot}`;
22604
22616
  if (!this.ptyProcess) throw new Error(`${this.cliName} is not running`);
22605
22617
  await this.ptyProcess.write(chunks[i]);
22606
22618
  if (i + 1 < chunks.length) {
22607
- await new Promise((resolve24) => setTimeout(resolve24, WIN32_PTY_WRITE_CHUNK_GAP_MS));
22619
+ await new Promise((resolve25) => setTimeout(resolve25, WIN32_PTY_WRITE_CHUNK_GAP_MS));
22608
22620
  }
22609
22621
  }
22610
22622
  }
@@ -22772,7 +22784,7 @@ ${lastSnapshot}`;
22772
22784
  this.onStatusChange?.();
22773
22785
  }
22774
22786
  async waitForForceSubmitSettle() {
22775
- await new Promise((resolve24) => setTimeout(resolve24, FORCE_SUBMIT_SETTLE_MS));
22787
+ await new Promise((resolve25) => setTimeout(resolve25, FORCE_SUBMIT_SETTLE_MS));
22776
22788
  }
22777
22789
  enqueuePendingOutboundMessage(text, reason, meshTaskId) {
22778
22790
  const content = String(text || "");
@@ -22851,7 +22863,7 @@ ${lastSnapshot}`;
22851
22863
  const deadline = Date.now() + 1e4;
22852
22864
  while (this.startupParseGate && Date.now() < deadline) {
22853
22865
  this.resolveStartupState("send_wait");
22854
- await new Promise((resolve24) => setTimeout(resolve24, 50));
22866
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
22855
22867
  }
22856
22868
  }
22857
22869
  const parsedStatusBeforeSend = !allowInputDuringGeneration ? (() => {
@@ -22944,13 +22956,13 @@ ${lastSnapshot}`;
22944
22956
  isFirstTurn: !this.firstTurnSent
22945
22957
  };
22946
22958
  this.engine.responseSettleIgnoreUntil = Date.now() + submitDelayMs + this.timeouts.outputSettle + 250;
22947
- await new Promise((resolve24, reject) => {
22959
+ await new Promise((resolve25, reject) => {
22948
22960
  let resolved = false;
22949
22961
  const completion = {
22950
22962
  resolveOnce: () => {
22951
22963
  if (resolved) return;
22952
22964
  resolved = true;
22953
- resolve24();
22965
+ resolve25();
22954
22966
  },
22955
22967
  rejectOnce: (error) => {
22956
22968
  if (resolved) return;
@@ -23138,17 +23150,17 @@ ${lastSnapshot}`;
23138
23150
  }
23139
23151
  }
23140
23152
  waitForStopped(timeoutMs) {
23141
- return new Promise((resolve24) => {
23153
+ return new Promise((resolve25) => {
23142
23154
  const startedAt = Date.now();
23143
23155
  const timer = setInterval(() => {
23144
23156
  if (!this.ptyProcess || this.engine.currentStatus === "stopped") {
23145
23157
  clearInterval(timer);
23146
- resolve24(true);
23158
+ resolve25(true);
23147
23159
  return;
23148
23160
  }
23149
23161
  if (Date.now() - startedAt >= timeoutMs) {
23150
23162
  clearInterval(timer);
23151
- resolve24(false);
23163
+ resolve25(false);
23152
23164
  }
23153
23165
  }, 100);
23154
23166
  });
@@ -24008,6 +24020,7 @@ __export(index_exports, {
24008
24020
  createGitSnapshotStore: () => createGitSnapshotStore,
24009
24021
  createGitWorkspaceMonitor: () => createGitWorkspaceMonitor,
24010
24022
  createInteractionId: () => createInteractionId,
24023
+ createManagedSessionHost: () => createManagedSessionHost,
24011
24024
  createMesh: () => createMesh,
24012
24025
  createNativeHistoryDispatcher: () => createNativeHistoryDispatcher,
24013
24026
  createSessionDelivery: () => createSessionDelivery,
@@ -24946,6 +24959,7 @@ var path3 = __toESM(require("path"));
24946
24959
  init_git_diff();
24947
24960
  init_git_executor();
24948
24961
  init_git_status();
24962
+ init_config();
24949
24963
  var GIT_COMMAND_NAMES = /* @__PURE__ */ new Set([
24950
24964
  "git_status",
24951
24965
  "git_diff_summary",
@@ -25085,7 +25099,21 @@ async function handleGitCommand(command, args, services = defaultGitCommandServi
25085
25099
  if (submoduleIgnorePaths && submoduleIgnorePaths.length > 0) statusParams.submoduleIgnorePaths = submoduleIgnorePaths;
25086
25100
  const status = await runService(() => services.getStatus(statusParams));
25087
25101
  if ("success" in status) return status;
25088
- return { success: true, status, reporterPlatform: process.platform, reporterArch: process.arch };
25102
+ const reporterMachineNickname = (() => {
25103
+ try {
25104
+ const nick = loadConfig().machineNickname;
25105
+ return typeof nick === "string" && nick.trim() ? nick.trim() : void 0;
25106
+ } catch {
25107
+ return void 0;
25108
+ }
25109
+ })();
25110
+ return {
25111
+ success: true,
25112
+ status,
25113
+ reporterPlatform: process.platform,
25114
+ reporterArch: process.arch,
25115
+ ...reporterMachineNickname ? { reporterMachineNickname } : {}
25116
+ };
25089
25117
  }
25090
25118
  case "git_diff_summary": {
25091
25119
  if (!services.getDiffSummary) return serviceNotImplemented(command);
@@ -25841,17 +25869,17 @@ function checkPathExists(paths) {
25841
25869
  return null;
25842
25870
  }
25843
25871
  async function detectIDEs(providerLoader) {
25844
- const os30 = (0, import_os2.platform)();
25872
+ const os31 = (0, import_os2.platform)();
25845
25873
  const results = [];
25846
25874
  for (const def of getMergedDefinitions()) {
25847
25875
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
25848
- const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os30] || []) || []);
25876
+ const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os31] || []) || []);
25849
25877
  let resolvedCli = cliPath;
25850
- if (!resolvedCli && appPath && os30 === "darwin") {
25878
+ if (!resolvedCli && appPath && os31 === "darwin") {
25851
25879
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
25852
25880
  if ((0, import_fs15.existsSync)(bundledCli)) resolvedCli = bundledCli;
25853
25881
  }
25854
- if (!resolvedCli && appPath && os30 === "win32") {
25882
+ if (!resolvedCli && appPath && os31 === "win32") {
25855
25883
  const { dirname: dirname17 } = await import("path");
25856
25884
  const appDir = dirname17(appPath);
25857
25885
  const candidates = [
@@ -25868,7 +25896,7 @@ async function detectIDEs(providerLoader) {
25868
25896
  }
25869
25897
  }
25870
25898
  }
25871
- const installed = os30 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
25899
+ const installed = os31 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
25872
25900
  const version = null;
25873
25901
  results.push({
25874
25902
  id: def.id,
@@ -26127,7 +26155,7 @@ var DaemonCdpManager = class {
26127
26155
  * Returns multiple entries if multiple IDE windows are open on same port
26128
26156
  */
26129
26157
  static listAllTargets(port) {
26130
- return new Promise((resolve24) => {
26158
+ return new Promise((resolve25) => {
26131
26159
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
26132
26160
  let data = "";
26133
26161
  res.on("data", (chunk) => data += chunk.toString());
@@ -26143,16 +26171,16 @@ var DaemonCdpManager = class {
26143
26171
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
26144
26172
  );
26145
26173
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
26146
- resolve24(mainPages.length > 0 ? mainPages : fallbackPages);
26174
+ resolve25(mainPages.length > 0 ? mainPages : fallbackPages);
26147
26175
  } catch {
26148
- resolve24([]);
26176
+ resolve25([]);
26149
26177
  }
26150
26178
  });
26151
26179
  });
26152
- req.on("error", () => resolve24([]));
26180
+ req.on("error", () => resolve25([]));
26153
26181
  req.setTimeout(2e3, () => {
26154
26182
  req.destroy();
26155
- resolve24([]);
26183
+ resolve25([]);
26156
26184
  });
26157
26185
  });
26158
26186
  }
@@ -26192,7 +26220,7 @@ var DaemonCdpManager = class {
26192
26220
  }
26193
26221
  }
26194
26222
  findTargetOnPort(port) {
26195
- return new Promise((resolve24) => {
26223
+ return new Promise((resolve25) => {
26196
26224
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
26197
26225
  let data = "";
26198
26226
  res.on("data", (chunk) => data += chunk.toString());
@@ -26203,7 +26231,7 @@ var DaemonCdpManager = class {
26203
26231
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
26204
26232
  );
26205
26233
  if (pages.length === 0) {
26206
- resolve24(targets.find((t) => t.webSocketDebuggerUrl) || null);
26234
+ resolve25(targets.find((t) => t.webSocketDebuggerUrl) || null);
26207
26235
  return;
26208
26236
  }
26209
26237
  const titleFilteredPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -26222,25 +26250,25 @@ var DaemonCdpManager = class {
26222
26250
  this._targetId = selected.target.id;
26223
26251
  }
26224
26252
  this._pageTitle = selected.target.title || "";
26225
- resolve24(selected.target);
26253
+ resolve25(selected.target);
26226
26254
  return;
26227
26255
  }
26228
26256
  if (previousTargetId) {
26229
26257
  this.log(`[CDP] Target ${previousTargetId} not found in page list`);
26230
- resolve24(null);
26258
+ resolve25(null);
26231
26259
  return;
26232
26260
  }
26233
26261
  this._pageTitle = list[0]?.title || "";
26234
- resolve24(list[0]);
26262
+ resolve25(list[0]);
26235
26263
  } catch {
26236
- resolve24(null);
26264
+ resolve25(null);
26237
26265
  }
26238
26266
  });
26239
26267
  });
26240
- req.on("error", () => resolve24(null));
26268
+ req.on("error", () => resolve25(null));
26241
26269
  req.setTimeout(2e3, () => {
26242
26270
  req.destroy();
26243
- resolve24(null);
26271
+ resolve25(null);
26244
26272
  });
26245
26273
  });
26246
26274
  }
@@ -26251,7 +26279,7 @@ var DaemonCdpManager = class {
26251
26279
  this.extensionProviders = providers;
26252
26280
  }
26253
26281
  connectToTarget(wsUrl) {
26254
- return new Promise((resolve24) => {
26282
+ return new Promise((resolve25) => {
26255
26283
  this.ws = new import_ws.default(wsUrl);
26256
26284
  this.ws.on("open", async () => {
26257
26285
  this._connected = true;
@@ -26261,17 +26289,17 @@ var DaemonCdpManager = class {
26261
26289
  }
26262
26290
  this.connectBrowserWs().catch(() => {
26263
26291
  });
26264
- resolve24(true);
26292
+ resolve25(true);
26265
26293
  });
26266
26294
  this.ws.on("message", (data) => {
26267
26295
  try {
26268
26296
  const msg = JSON.parse(data.toString());
26269
26297
  if (msg.id && this.pending.has(msg.id)) {
26270
- const { resolve: resolve25, reject } = this.pending.get(msg.id);
26298
+ const { resolve: resolve26, reject } = this.pending.get(msg.id);
26271
26299
  this.pending.delete(msg.id);
26272
26300
  this.failureCount = 0;
26273
26301
  if (msg.error) reject(new Error(msg.error.message));
26274
- else resolve25(msg.result);
26302
+ else resolve26(msg.result);
26275
26303
  } else if (msg.method === "Runtime.executionContextCreated") {
26276
26304
  this.contexts.add(msg.params.context.id);
26277
26305
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -26294,7 +26322,7 @@ var DaemonCdpManager = class {
26294
26322
  this.ws.on("error", (err) => {
26295
26323
  this.log(`[CDP] WebSocket error: ${err.message}`);
26296
26324
  this._connected = false;
26297
- resolve24(false);
26325
+ resolve25(false);
26298
26326
  });
26299
26327
  });
26300
26328
  }
@@ -26308,7 +26336,7 @@ var DaemonCdpManager = class {
26308
26336
  return;
26309
26337
  }
26310
26338
  this.log(`[CDP] Connecting browser WS for target discovery...`);
26311
- await new Promise((resolve24, reject) => {
26339
+ await new Promise((resolve25, reject) => {
26312
26340
  this.browserWs = new import_ws.default(browserWsUrl);
26313
26341
  this.browserWs.on("open", async () => {
26314
26342
  this._browserConnected = true;
@@ -26318,16 +26346,16 @@ var DaemonCdpManager = class {
26318
26346
  } catch (e) {
26319
26347
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
26320
26348
  }
26321
- resolve24();
26349
+ resolve25();
26322
26350
  });
26323
26351
  this.browserWs.on("message", (data) => {
26324
26352
  try {
26325
26353
  const msg = JSON.parse(data.toString());
26326
26354
  if (msg.id && this.browserPending.has(msg.id)) {
26327
- const { resolve: resolve25, reject: reject2 } = this.browserPending.get(msg.id);
26355
+ const { resolve: resolve26, reject: reject2 } = this.browserPending.get(msg.id);
26328
26356
  this.browserPending.delete(msg.id);
26329
26357
  if (msg.error) reject2(new Error(msg.error.message));
26330
- else resolve25(msg.result);
26358
+ else resolve26(msg.result);
26331
26359
  }
26332
26360
  } catch {
26333
26361
  }
@@ -26347,31 +26375,31 @@ var DaemonCdpManager = class {
26347
26375
  }
26348
26376
  }
26349
26377
  getBrowserWsUrl() {
26350
- return new Promise((resolve24) => {
26378
+ return new Promise((resolve25) => {
26351
26379
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
26352
26380
  let data = "";
26353
26381
  res.on("data", (chunk) => data += chunk.toString());
26354
26382
  res.on("end", () => {
26355
26383
  try {
26356
26384
  const info = JSON.parse(data);
26357
- resolve24(info.webSocketDebuggerUrl || null);
26385
+ resolve25(info.webSocketDebuggerUrl || null);
26358
26386
  } catch {
26359
- resolve24(null);
26387
+ resolve25(null);
26360
26388
  }
26361
26389
  });
26362
26390
  });
26363
- req.on("error", () => resolve24(null));
26391
+ req.on("error", () => resolve25(null));
26364
26392
  req.setTimeout(3e3, () => {
26365
26393
  req.destroy();
26366
- resolve24(null);
26394
+ resolve25(null);
26367
26395
  });
26368
26396
  });
26369
26397
  }
26370
26398
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
26371
- return new Promise((resolve24, reject) => {
26399
+ return new Promise((resolve25, reject) => {
26372
26400
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
26373
26401
  const id = this.browserMsgId++;
26374
- this.browserPending.set(id, { resolve: resolve24, reject });
26402
+ this.browserPending.set(id, { resolve: resolve25, reject });
26375
26403
  this.browserWs.send(JSON.stringify({ id, method, params }));
26376
26404
  setTimeout(() => {
26377
26405
  if (this.browserPending.has(id)) {
@@ -26411,11 +26439,11 @@ var DaemonCdpManager = class {
26411
26439
  }
26412
26440
  // ─── CDP Protocol ────────────────────────────────────────
26413
26441
  sendInternal(method, params = {}, timeoutMs = 15e3) {
26414
- return new Promise((resolve24, reject) => {
26442
+ return new Promise((resolve25, reject) => {
26415
26443
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
26416
26444
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
26417
26445
  const id = this.msgId++;
26418
- this.pending.set(id, { resolve: resolve24, reject });
26446
+ this.pending.set(id, { resolve: resolve25, reject });
26419
26447
  this.ws.send(JSON.stringify({ id, method, params }));
26420
26448
  setTimeout(() => {
26421
26449
  if (this.pending.has(id)) {
@@ -26664,7 +26692,7 @@ var DaemonCdpManager = class {
26664
26692
  const browserWs = this.browserWs;
26665
26693
  let msgId = this.browserMsgId;
26666
26694
  const sendWs = (method, params = {}, sessionId) => {
26667
- return new Promise((resolve24, reject) => {
26695
+ return new Promise((resolve25, reject) => {
26668
26696
  const mid = msgId++;
26669
26697
  this.browserMsgId = msgId;
26670
26698
  const handler = (raw) => {
@@ -26673,7 +26701,7 @@ var DaemonCdpManager = class {
26673
26701
  if (msg.id === mid) {
26674
26702
  browserWs.removeListener("message", handler);
26675
26703
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
26676
- else resolve24(msg.result);
26704
+ else resolve25(msg.result);
26677
26705
  }
26678
26706
  } catch {
26679
26707
  }
@@ -26874,14 +26902,14 @@ var DaemonCdpManager = class {
26874
26902
  if (!ws || ws.readyState !== import_ws.default.OPEN) {
26875
26903
  throw new Error("CDP not connected");
26876
26904
  }
26877
- return new Promise((resolve24, reject) => {
26905
+ return new Promise((resolve25, reject) => {
26878
26906
  const id = getNextId();
26879
26907
  pendingMap.set(id, {
26880
26908
  resolve: (result) => {
26881
26909
  if (result?.result?.subtype === "error") {
26882
26910
  reject(new Error(result.result.description));
26883
26911
  } else {
26884
- resolve24(result?.result?.value);
26912
+ resolve25(result?.result?.value);
26885
26913
  }
26886
26914
  },
26887
26915
  reject
@@ -26913,10 +26941,10 @@ var DaemonCdpManager = class {
26913
26941
  throw new Error("CDP not connected");
26914
26942
  }
26915
26943
  const sendViaSession = (method, params = {}) => {
26916
- return new Promise((resolve24, reject) => {
26944
+ return new Promise((resolve25, reject) => {
26917
26945
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
26918
26946
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
26919
- pendingMap.set(id, { resolve: resolve24, reject });
26947
+ pendingMap.set(id, { resolve: resolve25, reject });
26920
26948
  ws.send(JSON.stringify({ id, sessionId, method, params }));
26921
26949
  setTimeout(() => {
26922
26950
  if (pendingMap.has(id)) {
@@ -33146,7 +33174,7 @@ function getSendChatInputEnvelope(args) {
33146
33174
  return normalizeInputEnvelope(args?.input ? { input: args.input } : args);
33147
33175
  }
33148
33176
  function sleep(ms) {
33149
- return new Promise((resolve24) => setTimeout(resolve24, ms));
33177
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
33150
33178
  }
33151
33179
  async function waitOnceForFreshHermesCliStart(adapter, log) {
33152
33180
  if (adapter.cliType !== "hermes-cli") return;
@@ -33201,7 +33229,7 @@ function getStateLastSignature(state) {
33201
33229
  async function getStableExtensionBaseline(h) {
33202
33230
  const first = await readExtensionChatState(h);
33203
33231
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
33204
- await new Promise((resolve24) => setTimeout(resolve24, 150));
33232
+ await new Promise((resolve25) => setTimeout(resolve25, 150));
33205
33233
  const second = await readExtensionChatState(h);
33206
33234
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
33207
33235
  }
@@ -33209,7 +33237,7 @@ async function verifyExtensionSendObserved(h, before) {
33209
33237
  const beforeCount = getStateMessageCount(before);
33210
33238
  const beforeSignature = getStateLastSignature(before);
33211
33239
  for (let attempt = 0; attempt < 12; attempt += 1) {
33212
- await new Promise((resolve24) => setTimeout(resolve24, 250));
33240
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
33213
33241
  const state = await readExtensionChatState(h);
33214
33242
  if (state?.status === "waiting_approval") return true;
33215
33243
  const afterCount = getStateMessageCount(state);
@@ -34611,7 +34639,7 @@ async function executeProviderScript(h, args, scriptName) {
34611
34639
  const enterCount = cliCommand.enterCount || 1;
34612
34640
  await adapter.writeRaw(cliCommand.text + "\r");
34613
34641
  for (let i = 1; i < enterCount; i += 1) {
34614
- await new Promise((resolve24) => setTimeout(resolve24, 50));
34642
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
34615
34643
  await adapter.writeRaw("\r");
34616
34644
  }
34617
34645
  }
@@ -35388,9 +35416,9 @@ var DaemonCommandHandler = class {
35388
35416
  * point at a sibling git checkout.
35389
35417
  */
35390
35418
  getUpstreamInstallRoot() {
35391
- const os30 = require("os");
35392
- const path43 = require("path");
35393
- return path43.join(os30.homedir(), ".adhdev", "providers", ".upstream");
35419
+ const os31 = require("os");
35420
+ const path44 = require("path");
35421
+ return path44.join(os31.homedir(), ".adhdev", "providers", ".upstream");
35394
35422
  }
35395
35423
  /**
35396
35424
  * Download a single provider manifest from the registry and write it to
@@ -35414,11 +35442,11 @@ var DaemonCommandHandler = class {
35414
35442
  return { success: false, error: "invalid type" };
35415
35443
  }
35416
35444
  const https = require("https");
35417
- const fs38 = require("fs");
35418
- const path43 = require("path");
35445
+ const fs39 = require("fs");
35446
+ const path44 = require("path");
35419
35447
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
35420
35448
  function fetchText(url, timeoutMs) {
35421
- return new Promise((resolve24, reject) => {
35449
+ return new Promise((resolve25, reject) => {
35422
35450
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: timeoutMs }, (res) => {
35423
35451
  if (res.statusCode !== 200) {
35424
35452
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -35426,7 +35454,7 @@ var DaemonCommandHandler = class {
35426
35454
  }
35427
35455
  const chunks = [];
35428
35456
  res.on("data", (c) => chunks.push(c));
35429
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
35457
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
35430
35458
  });
35431
35459
  req.on("error", reject);
35432
35460
  req.on("timeout", () => {
@@ -35452,12 +35480,12 @@ var DaemonCommandHandler = class {
35452
35480
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
35453
35481
  }
35454
35482
  const installRoot = this.getUpstreamInstallRoot();
35455
- const installRootResolved = path43.resolve(installRoot);
35456
- const targetDir = path43.resolve(path43.join(installRoot, category, type));
35457
- if (!targetDir.startsWith(installRootResolved + path43.sep)) {
35483
+ const installRootResolved = path44.resolve(installRoot);
35484
+ const targetDir = path44.resolve(path44.join(installRoot, category, type));
35485
+ if (!targetDir.startsWith(installRootResolved + path44.sep)) {
35458
35486
  return { success: false, error: "install path escaped upstream root" };
35459
35487
  }
35460
- fs38.mkdirSync(targetDir, { recursive: true });
35488
+ fs39.mkdirSync(targetDir, { recursive: true });
35461
35489
  let manifestProbe = {};
35462
35490
  try {
35463
35491
  manifestProbe = JSON.parse(manifestBody);
@@ -35481,8 +35509,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35481
35509
  }
35482
35510
  }
35483
35511
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
35484
- const targetPath = path43.join(targetDir, targetFile);
35485
- fs38.writeFileSync(targetPath, manifestBody, "utf-8");
35512
+ const targetPath = path44.join(targetDir, targetFile);
35513
+ fs39.writeFileSync(targetPath, manifestBody, "utf-8");
35486
35514
  const manifestJson = JSON.parse(manifestBody);
35487
35515
  const scriptFetch = await this.fetchProviderSources(
35488
35516
  manifestJson,
@@ -35552,10 +35580,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35552
35580
  const repo = source.repo;
35553
35581
  const ref = source.ref;
35554
35582
  const https = require("https");
35555
- const fs38 = require("fs");
35556
- const path43 = require("path");
35583
+ const fs39 = require("fs");
35584
+ const path44 = require("path");
35557
35585
  function fetchJson(url, timeoutMs) {
35558
- return new Promise((resolve24, reject) => {
35586
+ return new Promise((resolve25, reject) => {
35559
35587
  const req = https.get(url, {
35560
35588
  headers: { "User-Agent": "adhdev-daemon", "Accept": "application/vnd.github+json" },
35561
35589
  timeout: timeoutMs
@@ -35568,7 +35596,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35568
35596
  res.on("data", (c) => chunks.push(c));
35569
35597
  res.on("end", () => {
35570
35598
  try {
35571
- resolve24(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35599
+ resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35572
35600
  } catch (e) {
35573
35601
  reject(e);
35574
35602
  }
@@ -35582,14 +35610,14 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35582
35610
  });
35583
35611
  }
35584
35612
  function fetchBinary(url, timeoutMs) {
35585
- return new Promise((resolve24, reject) => {
35613
+ return new Promise((resolve25, reject) => {
35586
35614
  const req = https.get(url, {
35587
35615
  headers: { "User-Agent": "adhdev-daemon" },
35588
35616
  timeout: timeoutMs
35589
35617
  }, (res) => {
35590
35618
  if (res.statusCode === 301 || res.statusCode === 302) {
35591
35619
  if (res.headers.location) {
35592
- return fetchBinary(res.headers.location, timeoutMs).then(resolve24, reject);
35620
+ return fetchBinary(res.headers.location, timeoutMs).then(resolve25, reject);
35593
35621
  }
35594
35622
  }
35595
35623
  if (res.statusCode !== 200) {
@@ -35598,7 +35626,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35598
35626
  }
35599
35627
  const chunks = [];
35600
35628
  res.on("data", (c) => chunks.push(c));
35601
- res.on("end", () => resolve24(Buffer.concat(chunks)));
35629
+ res.on("end", () => resolve25(Buffer.concat(chunks)));
35602
35630
  });
35603
35631
  req.on("error", reject);
35604
35632
  req.on("timeout", () => {
@@ -35609,9 +35637,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35609
35637
  }
35610
35638
  let fetchedCount = 0;
35611
35639
  const sharedDirRel = `${category}/_shared`;
35612
- const sharedTargetDir = path43.resolve(path43.join(targetDir, "../_shared"));
35613
- const installRootResolved = path43.resolve(path43.join(targetDir, "../.."));
35614
- if (sharedTargetDir.startsWith(installRootResolved + path43.sep)) {
35640
+ const sharedTargetDir = path44.resolve(path44.join(targetDir, "../_shared"));
35641
+ const installRootResolved = path44.resolve(path44.join(targetDir, "../.."));
35642
+ if (sharedTargetDir.startsWith(installRootResolved + path44.sep)) {
35615
35643
  const sharedStack = [sharedDirRel];
35616
35644
  while (sharedStack.length) {
35617
35645
  const relDir = sharedStack.pop();
@@ -35634,10 +35662,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35634
35662
  try {
35635
35663
  const body = await fetchBinary(entry.download_url, 3e4);
35636
35664
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
35637
- const outPath = path43.resolve(path43.join(sharedTargetDir, relInside));
35638
- if (!outPath.startsWith(path43.resolve(sharedTargetDir) + path43.sep)) continue;
35639
- fs38.mkdirSync(path43.dirname(outPath), { recursive: true });
35640
- fs38.writeFileSync(outPath, body);
35665
+ const outPath = path44.resolve(path44.join(sharedTargetDir, relInside));
35666
+ if (!outPath.startsWith(path44.resolve(sharedTargetDir) + path44.sep)) continue;
35667
+ fs39.mkdirSync(path44.dirname(outPath), { recursive: true });
35668
+ fs39.writeFileSync(outPath, body);
35641
35669
  fetchedCount++;
35642
35670
  } catch (e) {
35643
35671
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -35670,13 +35698,13 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35670
35698
  try {
35671
35699
  const body = await fetchBinary(entry.download_url, 3e4);
35672
35700
  const relInsideProvider = entry.path.startsWith(subdir + "/") ? entry.path.slice(subdir.length + 1) : entry.path;
35673
- const outPath = path43.resolve(path43.join(targetDir, relInsideProvider));
35674
- if (!outPath.startsWith(path43.resolve(targetDir) + path43.sep)) {
35701
+ const outPath = path44.resolve(path44.join(targetDir, relInsideProvider));
35702
+ if (!outPath.startsWith(path44.resolve(targetDir) + path44.sep)) {
35675
35703
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
35676
35704
  continue;
35677
35705
  }
35678
- fs38.mkdirSync(path43.dirname(outPath), { recursive: true });
35679
- fs38.writeFileSync(outPath, body);
35706
+ fs39.mkdirSync(path44.dirname(outPath), { recursive: true });
35707
+ fs39.writeFileSync(outPath, body);
35680
35708
  fetchedCount++;
35681
35709
  } catch (e) {
35682
35710
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -35704,19 +35732,19 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35704
35732
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
35705
35733
  return { success: false, error: `unknown category: ${category}` };
35706
35734
  }
35707
- const fs38 = require("fs");
35708
- const path43 = require("path");
35735
+ const fs39 = require("fs");
35736
+ const path44 = require("path");
35709
35737
  try {
35710
35738
  const installRoot = this.getUpstreamInstallRoot();
35711
- const installRootResolved = path43.resolve(installRoot);
35712
- const targetDir = path43.resolve(path43.join(installRoot, category, type));
35713
- if (!targetDir.startsWith(installRootResolved + path43.sep)) {
35739
+ const installRootResolved = path44.resolve(installRoot);
35740
+ const targetDir = path44.resolve(path44.join(installRoot, category, type));
35741
+ if (!targetDir.startsWith(installRootResolved + path44.sep)) {
35714
35742
  return { success: false, error: "refusing to delete outside upstream root" };
35715
35743
  }
35716
- if (!fs38.existsSync(targetDir)) {
35744
+ if (!fs39.existsSync(targetDir)) {
35717
35745
  return { success: false, error: "not installed" };
35718
35746
  }
35719
- fs38.rmSync(targetDir, { recursive: true, force: true });
35747
+ fs39.rmSync(targetDir, { recursive: true, force: true });
35720
35748
  if (this._ctx.providerLoader) {
35721
35749
  this._ctx.providerLoader.reload();
35722
35750
  this._ctx.providerLoader.registerToDetector();
@@ -35732,28 +35760,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35732
35760
  * the UI and by the update checker.
35733
35761
  */
35734
35762
  handleListInstalledProviders(_args) {
35735
- const fs38 = require("fs");
35736
- const path43 = require("path");
35763
+ const fs39 = require("fs");
35764
+ const path44 = require("path");
35737
35765
  const installRoot = this.getUpstreamInstallRoot();
35738
- if (!fs38.existsSync(installRoot)) return { success: true, providers: [] };
35766
+ if (!fs39.existsSync(installRoot)) return { success: true, providers: [] };
35739
35767
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
35740
35768
  const items = [];
35741
35769
  for (const category of CATEGORIES) {
35742
- const categoryDir = path43.join(installRoot, category);
35743
- if (!fs38.existsSync(categoryDir)) continue;
35770
+ const categoryDir = path44.join(installRoot, category);
35771
+ if (!fs39.existsSync(categoryDir)) continue;
35744
35772
  let entries;
35745
35773
  try {
35746
- entries = fs38.readdirSync(categoryDir);
35774
+ entries = fs39.readdirSync(categoryDir);
35747
35775
  } catch {
35748
35776
  continue;
35749
35777
  }
35750
35778
  for (const type of entries) {
35751
- const v1Path = path43.join(categoryDir, type, "provider.v1.json");
35752
- const v0Path = path43.join(categoryDir, type, "provider.json");
35753
- const manifestPath = fs38.existsSync(v1Path) ? v1Path : fs38.existsSync(v0Path) ? v0Path : null;
35779
+ const v1Path = path44.join(categoryDir, type, "provider.v1.json");
35780
+ const v0Path = path44.join(categoryDir, type, "provider.json");
35781
+ const manifestPath = fs39.existsSync(v1Path) ? v1Path : fs39.existsSync(v0Path) ? v0Path : null;
35754
35782
  if (!manifestPath) continue;
35755
35783
  try {
35756
- const m = JSON.parse(fs38.readFileSync(manifestPath, "utf-8"));
35784
+ const m = JSON.parse(fs39.readFileSync(manifestPath, "utf-8"));
35757
35785
  items.push({
35758
35786
  type,
35759
35787
  category,
@@ -35780,7 +35808,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35780
35808
  const https = require("https");
35781
35809
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
35782
35810
  function fetchJson(url) {
35783
- return new Promise((resolve24, reject) => {
35811
+ return new Promise((resolve25, reject) => {
35784
35812
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
35785
35813
  if (res.statusCode !== 200) {
35786
35814
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -35790,7 +35818,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35790
35818
  res.on("data", (c) => chunks.push(c));
35791
35819
  res.on("end", () => {
35792
35820
  try {
35793
- resolve24(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35821
+ resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35794
35822
  } catch (e) {
35795
35823
  reject(e);
35796
35824
  }
@@ -35864,8 +35892,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35864
35892
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
35865
35893
  return { success: false, error: "name must match @[a-z0-9_-]+" };
35866
35894
  }
35867
- const fs38 = require("fs");
35868
- const path43 = require("path");
35895
+ const fs39 = require("fs");
35896
+ const path44 = require("path");
35869
35897
  const { spawnSync: spawnSync2 } = require("child_process");
35870
35898
  const file = ext.loadExternalSources();
35871
35899
  if (file.sources.some((s2) => s2.name === requestedName)) {
@@ -35874,9 +35902,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35874
35902
  if (file.sources.some((s2) => s2.url === url && s2.ref === ref)) {
35875
35903
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
35876
35904
  }
35877
- const sourceDir = path43.join(ext.externalRoot(), requestedName);
35878
- if (!fs38.existsSync(ext.externalRoot())) fs38.mkdirSync(ext.externalRoot(), { recursive: true });
35879
- if (fs38.existsSync(sourceDir)) {
35905
+ const sourceDir = path44.join(ext.externalRoot(), requestedName);
35906
+ if (!fs39.existsSync(ext.externalRoot())) fs39.mkdirSync(ext.externalRoot(), { recursive: true });
35907
+ if (fs39.existsSync(sourceDir)) {
35880
35908
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
35881
35909
  }
35882
35910
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -35886,7 +35914,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35886
35914
  });
35887
35915
  if (clone.status !== 0) {
35888
35916
  try {
35889
- fs38.rmSync(sourceDir, { recursive: true, force: true });
35917
+ fs39.rmSync(sourceDir, { recursive: true, force: true });
35890
35918
  } catch {
35891
35919
  }
35892
35920
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -35930,15 +35958,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35930
35958
  const name = typeof args?.name === "string" ? args.name.trim() : "";
35931
35959
  if (!name) return { success: false, error: "name is required" };
35932
35960
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
35933
- const fs38 = require("fs");
35934
- const path43 = require("path");
35961
+ const fs39 = require("fs");
35962
+ const path44 = require("path");
35935
35963
  const file = ext.loadExternalSources();
35936
35964
  const match = file.sources.find((s2) => s2.name === name);
35937
35965
  if (!match) return { success: false, error: `source "${name}" not registered` };
35938
- const sourceDir = path43.join(ext.externalRoot(), name);
35939
- if (fs38.existsSync(sourceDir)) {
35966
+ const sourceDir = path44.join(ext.externalRoot(), name);
35967
+ if (fs39.existsSync(sourceDir)) {
35940
35968
  try {
35941
- fs38.rmSync(sourceDir, { recursive: true, force: true });
35969
+ fs39.rmSync(sourceDir, { recursive: true, force: true });
35942
35970
  } catch (e) {
35943
35971
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
35944
35972
  }
@@ -36028,7 +36056,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36028
36056
  try {
36029
36057
  const http3 = await import("http");
36030
36058
  const postData = JSON.stringify(body);
36031
- const result = await new Promise((resolve24, reject) => {
36059
+ const result = await new Promise((resolve25, reject) => {
36032
36060
  const req = http3.request({
36033
36061
  hostname: "127.0.0.1",
36034
36062
  port: 19280,
@@ -36040,9 +36068,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36040
36068
  res.on("data", (chunk) => data += chunk);
36041
36069
  res.on("end", () => {
36042
36070
  try {
36043
- resolve24(JSON.parse(data));
36071
+ resolve25(JSON.parse(data));
36044
36072
  } catch {
36045
- resolve24({ raw: data });
36073
+ resolve25({ raw: data });
36046
36074
  }
36047
36075
  });
36048
36076
  });
@@ -36060,15 +36088,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36060
36088
  if (!providerType) return { success: false, error: "providerType required" };
36061
36089
  try {
36062
36090
  const http3 = await import("http");
36063
- const result = await new Promise((resolve24, reject) => {
36091
+ const result = await new Promise((resolve25, reject) => {
36064
36092
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
36065
36093
  let data = "";
36066
36094
  res.on("data", (chunk) => data += chunk);
36067
36095
  res.on("end", () => {
36068
36096
  try {
36069
- resolve24(JSON.parse(data));
36097
+ resolve25(JSON.parse(data));
36070
36098
  } catch {
36071
- resolve24({ raw: data });
36099
+ resolve25({ raw: data });
36072
36100
  }
36073
36101
  });
36074
36102
  }).on("error", reject);
@@ -36082,7 +36110,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36082
36110
  try {
36083
36111
  const http3 = await import("http");
36084
36112
  const postData = JSON.stringify(args || {});
36085
- const result = await new Promise((resolve24, reject) => {
36113
+ const result = await new Promise((resolve25, reject) => {
36086
36114
  const req = http3.request({
36087
36115
  hostname: "127.0.0.1",
36088
36116
  port: 19280,
@@ -36094,9 +36122,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36094
36122
  res.on("data", (chunk) => data += chunk);
36095
36123
  res.on("end", () => {
36096
36124
  try {
36097
- resolve24(JSON.parse(data));
36125
+ resolve25(JSON.parse(data));
36098
36126
  } catch {
36099
- resolve24({ raw: data });
36127
+ resolve25({ raw: data });
36100
36128
  }
36101
36129
  });
36102
36130
  });
@@ -36721,24 +36749,24 @@ var statusMetaHandlers = {
36721
36749
  // src/commands/low-family/coordinator-prompt.ts
36722
36750
  var coordinatorPromptHandlers = {
36723
36751
  list_coordinator_prompts: async (_ctx, _args) => {
36724
- const fs38 = await import("fs");
36725
- const path43 = await import("path");
36726
- const os30 = await import("os");
36727
- const dir = path43.join(os30.homedir(), ".adhdev", "coordinator-prompts");
36752
+ const fs39 = await import("fs");
36753
+ const path44 = await import("path");
36754
+ const os31 = await import("os");
36755
+ const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
36728
36756
  const entries = {};
36729
36757
  try {
36730
- if (fs38.existsSync(dir)) {
36731
- for (const name of fs38.readdirSync(dir)) {
36758
+ if (fs39.existsSync(dir)) {
36759
+ for (const name of fs39.readdirSync(dir)) {
36732
36760
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
36733
36761
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
36734
36762
  const m = matchAppend || matchOverride;
36735
36763
  if (!m) continue;
36736
36764
  const isAppend = !!matchAppend;
36737
36765
  const key2 = m[1];
36738
- const full = path43.join(dir, name);
36766
+ const full = path44.join(dir, name);
36739
36767
  let content = "";
36740
36768
  try {
36741
- content = fs38.readFileSync(full, "utf8");
36769
+ content = fs39.readFileSync(full, "utf8");
36742
36770
  } catch {
36743
36771
  }
36744
36772
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -36752,24 +36780,24 @@ var coordinatorPromptHandlers = {
36752
36780
  return { success: true, dir, entries };
36753
36781
  },
36754
36782
  write_coordinator_prompt: async (_ctx, args) => {
36755
- const fs38 = await import("fs");
36756
- const path43 = await import("path");
36757
- const os30 = await import("os");
36783
+ const fs39 = await import("fs");
36784
+ const path44 = await import("path");
36785
+ const os31 = await import("os");
36758
36786
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
36759
36787
  const kind = args?.kind === "append" ? "append" : "override";
36760
36788
  const content = typeof args?.content === "string" ? args.content : "";
36761
36789
  if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
36762
36790
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
36763
36791
  }
36764
- const dir = path43.join(os30.homedir(), ".adhdev", "coordinator-prompts");
36792
+ const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
36765
36793
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
36766
- const full = path43.join(dir, filename);
36794
+ const full = path44.join(dir, filename);
36767
36795
  try {
36768
- fs38.mkdirSync(dir, { recursive: true });
36796
+ fs39.mkdirSync(dir, { recursive: true });
36769
36797
  if (content.trim()) {
36770
- fs38.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
36771
- } else if (fs38.existsSync(full)) {
36772
- fs38.unlinkSync(full);
36798
+ fs39.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
36799
+ } else if (fs39.existsSync(full)) {
36800
+ fs39.unlinkSync(full);
36773
36801
  }
36774
36802
  return { success: true, path: full, kind, key: key2 };
36775
36803
  } catch (error) {
@@ -37086,7 +37114,7 @@ async function waitForPidExit(pid, timeoutMs) {
37086
37114
  while (Date.now() - start < timeoutMs) {
37087
37115
  try {
37088
37116
  process.kill(pid, 0);
37089
- await new Promise((resolve24) => setTimeout(resolve24, 250));
37117
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
37090
37118
  } catch {
37091
37119
  return;
37092
37120
  }
@@ -37312,7 +37340,7 @@ async function runDaemonUpgradeHelper(payload) {
37312
37340
  appendUpgradeLog(`Install attempt ${attempt} hit a file lock (${error?.code || "lock"}); clearing holders + staging and retrying after backoff`);
37313
37341
  await stopForeignNativeAddonHolders(installCommand.surface.packageRoot, { parentPid: payload.parentPid });
37314
37342
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
37315
- await new Promise((resolve24) => setTimeout(resolve24, attempt * 1500));
37343
+ await new Promise((resolve25) => setTimeout(resolve25, attempt * 1500));
37316
37344
  continue;
37317
37345
  }
37318
37346
  if (isRetriableInstallLockError(error)) {
@@ -37340,7 +37368,7 @@ async function runDaemonUpgradeHelper(payload) {
37340
37368
  appendUpgradeLog(installOutput.trim());
37341
37369
  }
37342
37370
  if (process.platform === "win32") {
37343
- await new Promise((resolve24) => setTimeout(resolve24, 500));
37371
+ await new Promise((resolve25) => setTimeout(resolve25, 500));
37344
37372
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
37345
37373
  appendUpgradeLog("Post-install staging cleanup complete");
37346
37374
  }
@@ -39988,7 +40016,7 @@ function stripAnsi3(text) {
39988
40016
  return String(text || "").replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
39989
40017
  }
39990
40018
  function delay(ms) {
39991
- return new Promise((resolve24) => setTimeout(resolve24, ms));
40019
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
39992
40020
  }
39993
40021
  var SpecCliAdapter = class _SpecCliAdapter {
39994
40022
  cliType;
@@ -40187,7 +40215,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
40187
40215
  const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
40188
40216
  for (const step of steps) {
40189
40217
  this.driver.dispatch({ kind: "pty_write", data: step });
40190
- await new Promise((resolve24) => setTimeout(resolve24, 180));
40218
+ await new Promise((resolve25) => setTimeout(resolve25, 180));
40191
40219
  }
40192
40220
  } else {
40193
40221
  this.driver.dispatch({ kind: "pty_write", data: `${buildClaudeInteractiveToolResult(response)}
@@ -40738,7 +40766,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
40738
40766
  let screenText = this.driver.snapshot();
40739
40767
  const deadline = Date.now() + _SpecCliAdapter.CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS;
40740
40768
  while (!detectClaudeTuiMultiSelect(screenText) && Date.now() < deadline) {
40741
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40769
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40742
40770
  screenText = this.driver.snapshot();
40743
40771
  }
40744
40772
  return screenText;
@@ -40747,12 +40775,12 @@ var SpecCliAdapter = class _SpecCliAdapter {
40747
40775
  const pages = [{ screenText: firstScreen, header: headers[0] }];
40748
40776
  for (let index = 1; index < headers.length; index += 1) {
40749
40777
  this.driver.dispatch({ kind: "pty_write", data: " " });
40750
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40778
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40751
40779
  pages.push({ screenText: await this.snapshotSettledClaudeTuiPage(), header: headers[index] });
40752
40780
  }
40753
40781
  for (let index = headers.length - 1; index > 0; index -= 1) {
40754
40782
  this.driver.dispatch({ kind: "pty_write", data: "\x1B[Z" });
40755
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40783
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40756
40784
  const reread = await this.snapshotSettledClaudeTuiPage();
40757
40785
  const landed = pages[index - 1];
40758
40786
  if (landed && !detectClaudeTuiMultiSelect(landed.screenText) && detectClaudeTuiMultiSelect(reread)) {
@@ -41107,7 +41135,7 @@ async function waitForCliAdapterReady(adapter, options) {
41107
41135
  if (status === "stopped") {
41108
41136
  throw new Error("CLI runtime stopped before it became ready");
41109
41137
  }
41110
- await new Promise((resolve24) => setTimeout(resolve24, pollMs));
41138
+ await new Promise((resolve25) => setTimeout(resolve25, pollMs));
41111
41139
  }
41112
41140
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
41113
41141
  }
@@ -41856,7 +41884,7 @@ var CliProviderInstance = class _CliProviderInstance {
41856
41884
  const enterCount = cliCommand.enterCount || 1;
41857
41885
  await this.adapter.writeRaw(cliCommand.text + "\r");
41858
41886
  for (let i = 1; i < enterCount; i += 1) {
41859
- await new Promise((resolve24) => setTimeout(resolve24, 50));
41887
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
41860
41888
  await this.adapter.writeRaw("\r");
41861
41889
  }
41862
41890
  }
@@ -43930,13 +43958,13 @@ var AcpProviderInstance = class {
43930
43958
  }
43931
43959
  this.currentStatus = "waiting_approval";
43932
43960
  this.detectStatusTransition();
43933
- const approved = await new Promise((resolve24) => {
43934
- this.permissionResolvers.push(resolve24);
43961
+ const approved = await new Promise((resolve25) => {
43962
+ this.permissionResolvers.push(resolve25);
43935
43963
  setTimeout(() => {
43936
- const idx = this.permissionResolvers.indexOf(resolve24);
43964
+ const idx = this.permissionResolvers.indexOf(resolve25);
43937
43965
  if (idx >= 0) {
43938
43966
  this.permissionResolvers.splice(idx, 1);
43939
- resolve24(false);
43967
+ resolve25(false);
43940
43968
  }
43941
43969
  }, 3e5);
43942
43970
  });
@@ -44672,7 +44700,7 @@ async function waitForZeroMessageStartingLaunch(adapter) {
44672
44700
  } catch {
44673
44701
  return false;
44674
44702
  }
44675
- await new Promise((resolve24) => setTimeout(resolve24, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
44703
+ await new Promise((resolve25) => setTimeout(resolve25, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
44676
44704
  try {
44677
44705
  return hasZeroMessageStartingLaunch(adapter);
44678
44706
  } catch {
@@ -46013,9 +46041,9 @@ function validateProviderDefinition(raw) {
46013
46041
  const typedProvider = provider;
46014
46042
  const controls = Array.isArray(provider.controls) ? provider.controls : [];
46015
46043
  if (category === "cli" || category === "acp") {
46016
- const spawn4 = provider.spawn;
46017
- const command = spawn4 && typeof spawn4 === "object" ? spawn4.command : void 0;
46018
- if (!spawn4 || typeof spawn4 !== "object") {
46044
+ const spawn5 = provider.spawn;
46045
+ const command = spawn5 && typeof spawn5 === "object" ? spawn5.command : void 0;
46046
+ if (!spawn5 || typeof spawn5 !== "object") {
46019
46047
  errors.push(`${String(category).toUpperCase()}/CLI providers must have spawn config`);
46020
46048
  } else if (typeof command !== "string" || !command.trim()) {
46021
46049
  errors.push("spawn.command is required");
@@ -48536,25 +48564,25 @@ var ProviderLoader = class _ProviderLoader {
48536
48564
  }
48537
48565
  if (providerDir) {
48538
48566
  try {
48539
- const fs38 = require("fs");
48540
- const path43 = require("path");
48567
+ const fs39 = require("fs");
48568
+ const path44 = require("path");
48541
48569
  const candidates = [];
48542
48570
  if (Array.isArray(base.compatibility)) {
48543
48571
  for (const entry of base.compatibility) {
48544
48572
  if (typeof entry?.spec !== "string") continue;
48545
48573
  const matches = !entry.ideVersion || currentVersion && this.matchesVersion(currentVersion, entry.ideVersion) || !currentVersion;
48546
- if (matches) candidates.push(path43.join(providerDir, entry.spec));
48574
+ if (matches) candidates.push(path44.join(providerDir, entry.spec));
48547
48575
  }
48548
48576
  }
48549
- candidates.push(path43.join(providerDir, "specs", "default.json"));
48550
- candidates.push(path43.join(providerDir, "spec.json"));
48551
- const specPath = candidates.find((p) => fs38.existsSync(p));
48577
+ candidates.push(path44.join(providerDir, "specs", "default.json"));
48578
+ candidates.push(path44.join(providerDir, "spec.json"));
48579
+ const specPath = candidates.find((p) => fs39.existsSync(p));
48552
48580
  if (specPath) {
48553
48581
  resolved._resolvedSpecPath = specPath;
48554
48582
  let specControls;
48555
48583
  let nh;
48556
48584
  try {
48557
- const rawSpec = JSON.parse(fs38.readFileSync(specPath, "utf8"));
48585
+ const rawSpec = JSON.parse(fs39.readFileSync(specPath, "utf8"));
48558
48586
  specControls = rawSpec.control_bar;
48559
48587
  nh = rawSpec.native_history;
48560
48588
  } catch {
@@ -48585,10 +48613,10 @@ var ProviderLoader = class _ProviderLoader {
48585
48613
  format = `spec-${nh.source.kind}`;
48586
48614
  reader = (input) => executeNativeHistory(nh, input);
48587
48615
  } else if (nh.override_path) {
48588
- const overrideFile = path43.resolve(providerDir, nh.override_path);
48589
- if (fs38.existsSync(overrideFile)) {
48616
+ const overrideFile = path44.resolve(providerDir, nh.override_path);
48617
+ if (fs39.existsSync(overrideFile)) {
48590
48618
  try {
48591
- registerProviderScriptRootSafely(path43.dirname(path43.dirname(providerDir)));
48619
+ registerProviderScriptRootSafely(path44.dirname(path44.dirname(providerDir)));
48592
48620
  delete require.cache[require.resolve(overrideFile)];
48593
48621
  const mod = require(overrideFile);
48594
48622
  const fn = typeof mod === "function" ? mod : mod && typeof mod.default === "function" ? mod.default : null;
@@ -48762,7 +48790,7 @@ var ProviderLoader = class _ProviderLoader {
48762
48790
  }
48763
48791
  try {
48764
48792
  const listUrl = `${_ProviderLoader.REGISTRY_BASE_URL}/providers`;
48765
- const listBody = await new Promise((resolve24, reject) => {
48793
+ const listBody = await new Promise((resolve25, reject) => {
48766
48794
  const req = https.get(listUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
48767
48795
  if (res.statusCode !== 200) {
48768
48796
  reject(new Error(`registry list HTTP ${res.statusCode}`));
@@ -48770,7 +48798,7 @@ var ProviderLoader = class _ProviderLoader {
48770
48798
  }
48771
48799
  const chunks = [];
48772
48800
  res.on("data", (c) => chunks.push(c));
48773
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
48801
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
48774
48802
  });
48775
48803
  req.on("error", reject);
48776
48804
  req.on("timeout", () => {
@@ -48786,7 +48814,7 @@ var ProviderLoader = class _ProviderLoader {
48786
48814
  const cacheKey = `${category}/${type}`;
48787
48815
  if (cachedChecksums[cacheKey] === checksum) continue;
48788
48816
  const dlUrl = `${_ProviderLoader.REGISTRY_BASE_URL}/providers/${type}/${version}/download`;
48789
- const manifestBody = await new Promise((resolve24, reject) => {
48817
+ const manifestBody = await new Promise((resolve25, reject) => {
48790
48818
  const req = https.get(dlUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 3e4 }, (res) => {
48791
48819
  if (res.statusCode !== 200) {
48792
48820
  reject(new Error(`registry download HTTP ${res.statusCode} for ${type}@${version}`));
@@ -48794,7 +48822,7 @@ var ProviderLoader = class _ProviderLoader {
48794
48822
  }
48795
48823
  const chunks = [];
48796
48824
  res.on("data", (c) => chunks.push(c));
48797
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
48825
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
48798
48826
  });
48799
48827
  req.on("error", reject);
48800
48828
  req.on("timeout", () => {
@@ -48853,7 +48881,7 @@ var ProviderLoader = class _ProviderLoader {
48853
48881
  return { updated: false };
48854
48882
  }
48855
48883
  try {
48856
- const etag = await new Promise((resolve24, reject) => {
48884
+ const etag = await new Promise((resolve25, reject) => {
48857
48885
  const options = {
48858
48886
  method: "HEAD",
48859
48887
  hostname: "github.com",
@@ -48871,7 +48899,7 @@ var ProviderLoader = class _ProviderLoader {
48871
48899
  headers: { "User-Agent": "adhdev-launcher" },
48872
48900
  timeout: 1e4
48873
48901
  }, (res2) => {
48874
- resolve24(res2.headers.etag || res2.headers["last-modified"] || "");
48902
+ resolve25(res2.headers.etag || res2.headers["last-modified"] || "");
48875
48903
  });
48876
48904
  req2.on("error", reject);
48877
48905
  req2.on("timeout", () => {
@@ -48880,7 +48908,7 @@ var ProviderLoader = class _ProviderLoader {
48880
48908
  });
48881
48909
  req2.end();
48882
48910
  } else {
48883
- resolve24(res.headers.etag || res.headers["last-modified"] || "");
48911
+ resolve25(res.headers.etag || res.headers["last-modified"] || "");
48884
48912
  }
48885
48913
  });
48886
48914
  req.on("error", reject);
@@ -48944,7 +48972,7 @@ var ProviderLoader = class _ProviderLoader {
48944
48972
  downloadFile(url, destPath) {
48945
48973
  const https = require("https");
48946
48974
  const http3 = require("http");
48947
- return new Promise((resolve24, reject) => {
48975
+ return new Promise((resolve25, reject) => {
48948
48976
  const doRequest = (reqUrl, redirectCount = 0) => {
48949
48977
  if (redirectCount > 5) {
48950
48978
  reject(new Error("Too many redirects"));
@@ -48964,7 +48992,7 @@ var ProviderLoader = class _ProviderLoader {
48964
48992
  res.pipe(ws);
48965
48993
  ws.on("finish", () => {
48966
48994
  ws.close();
48967
- resolve24();
48995
+ resolve25();
48968
48996
  });
48969
48997
  ws.on("error", reject);
48970
48998
  });
@@ -49520,10 +49548,10 @@ function findMacAppProcessPids(psOutput, appPaths) {
49520
49548
 
49521
49549
  // src/launch.ts
49522
49550
  async function execQuiet(command, options = {}) {
49523
- return new Promise((resolve24) => {
49551
+ return new Promise((resolve25) => {
49524
49552
  (0, import_child_process9.exec)(command, options, (error, stdout) => {
49525
- if (error) return resolve24("");
49526
- resolve24(stdout.toString());
49553
+ if (error) return resolve25("");
49554
+ resolve25(stdout.toString());
49527
49555
  });
49528
49556
  });
49529
49557
  }
@@ -49604,17 +49632,17 @@ async function findFreePort(ports) {
49604
49632
  throw new Error("No free port found");
49605
49633
  }
49606
49634
  function checkPortFree(port) {
49607
- return new Promise((resolve24) => {
49635
+ return new Promise((resolve25) => {
49608
49636
  const server = net.createServer();
49609
49637
  server.unref();
49610
- server.on("error", () => resolve24(false));
49638
+ server.on("error", () => resolve25(false));
49611
49639
  server.listen(port, "127.0.0.1", () => {
49612
- server.close(() => resolve24(true));
49640
+ server.close(() => resolve25(true));
49613
49641
  });
49614
49642
  });
49615
49643
  }
49616
49644
  async function isCdpActive(port) {
49617
- return new Promise((resolve24) => {
49645
+ return new Promise((resolve25) => {
49618
49646
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
49619
49647
  timeout: 2e3
49620
49648
  }, (res) => {
@@ -49623,16 +49651,16 @@ async function isCdpActive(port) {
49623
49651
  res.on("end", () => {
49624
49652
  try {
49625
49653
  const info = JSON.parse(data);
49626
- resolve24(!!info["WebKit-Version"] || !!info["Browser"]);
49654
+ resolve25(!!info["WebKit-Version"] || !!info["Browser"]);
49627
49655
  } catch {
49628
- resolve24(false);
49656
+ resolve25(false);
49629
49657
  }
49630
49658
  });
49631
49659
  });
49632
- req.on("error", () => resolve24(false));
49660
+ req.on("error", () => resolve25(false));
49633
49661
  req.on("timeout", () => {
49634
49662
  req.destroy();
49635
- resolve24(false);
49663
+ resolve25(false);
49636
49664
  });
49637
49665
  });
49638
49666
  }
@@ -49768,7 +49796,7 @@ async function detectCurrentWorkspace(ideId) {
49768
49796
  }
49769
49797
  } else if (plat === "win32") {
49770
49798
  try {
49771
- const fs38 = require("fs");
49799
+ const fs39 = require("fs");
49772
49800
  const appNameMap = getMacAppIdentifiers();
49773
49801
  const appName = appNameMap[ideId];
49774
49802
  if (appName) {
@@ -49777,8 +49805,8 @@ async function detectCurrentWorkspace(ideId) {
49777
49805
  appName,
49778
49806
  "storage.json"
49779
49807
  );
49780
- if (fs38.existsSync(storagePath)) {
49781
- const data = JSON.parse(fs38.readFileSync(storagePath, "utf-8"));
49808
+ if (fs39.existsSync(storagePath)) {
49809
+ const data = JSON.parse(fs39.readFileSync(storagePath, "utf-8"));
49782
49810
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
49783
49811
  if (workspaces.length > 0) {
49784
49812
  const recent = workspaces[0];
@@ -50256,12 +50284,12 @@ var meshCrudHandlers = {
50256
50284
  normalizeRepoMeshDeclarativeConfig: normalizeRepoMeshDeclarativeConfig2,
50257
50285
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
50258
50286
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
50259
- const { mkdirSync: mkdirSync21, writeFileSync: writeFileSync24 } = await import("fs");
50260
- const { dirname: dirname17, join: join49 } = await import("path");
50287
+ const { mkdirSync: mkdirSync22, writeFileSync: writeFileSync24 } = await import("fs");
50288
+ const { dirname: dirname17, join: join50 } = await import("path");
50261
50289
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
50262
50290
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
50263
50291
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
50264
- const absolutePath = join49(workspace, relativePath);
50292
+ const absolutePath = join50(workspace, relativePath);
50265
50293
  const validation = normalizeRepoMeshDeclarativeConfig2(scaffold);
50266
50294
  if (!validation.valid) {
50267
50295
  return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join("; ")}` };
@@ -50297,7 +50325,7 @@ var meshCrudHandlers = {
50297
50325
  note: "Dry-run: nothing written. Re-run with write=true to persist to the repo (commit target). meshes.json is untouched."
50298
50326
  };
50299
50327
  }
50300
- mkdirSync21(dirname17(absolutePath), { recursive: true });
50328
+ mkdirSync22(dirname17(absolutePath), { recursive: true });
50301
50329
  writeFileSync24(absolutePath, `${scaffoldJson}
50302
50330
  `, "utf-8");
50303
50331
  return {
@@ -50861,7 +50889,7 @@ var meshCrudHandlers = {
50861
50889
  const setupPromise = finishWorktreeSetup();
50862
50890
  const setupResult = await Promise.race([
50863
50891
  setupPromise.then((value) => ({ completed: true, value })),
50864
- new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
50892
+ new Promise((resolve25) => setTimeout(() => resolve25({ completed: false }), setupWaitMs))
50865
50893
  ]);
50866
50894
  const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
50867
50895
  try {
@@ -52098,7 +52126,7 @@ ${ptyResult.output.slice(-2e3)}`);
52098
52126
  workspace
52099
52127
  };
52100
52128
  }
52101
- const { existsSync: existsSync53, readFileSync: readFileSync41, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
52129
+ const { existsSync: existsSync54, readFileSync: readFileSync42, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync22 } = await import("fs");
52102
52130
  const { dirname: dirname17 } = await import("path");
52103
52131
  const mcpConfigPath = coordinatorSetup.configPath;
52104
52132
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -52134,21 +52162,21 @@ ${ptyResult.output.slice(-2e3)}`);
52134
52162
  };
52135
52163
  }
52136
52164
  try {
52137
- mkdirSync21(dirname17(mcpConfigPath), { recursive: true });
52165
+ mkdirSync22(dirname17(mcpConfigPath), { recursive: true });
52138
52166
  } catch (error) {
52139
52167
  const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
52140
52168
  LOG.error("MeshCoordinator", message);
52141
52169
  if (hermesManualFallback) return returnManualFallback(message);
52142
52170
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
52143
52171
  }
52144
- const hadExistingMcpConfig = existsSync53(mcpConfigPath);
52172
+ const hadExistingMcpConfig = existsSync54(mcpConfigPath);
52145
52173
  let existingMcpConfig = hermesBaseConfig?.config || {};
52146
52174
  if (hermesBaseConfig) {
52147
52175
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname17(mcpConfigPath));
52148
52176
  }
52149
52177
  if (hadExistingMcpConfig) {
52150
52178
  try {
52151
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync41(mcpConfigPath, "utf-8"), configFormat);
52179
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync42(mcpConfigPath, "utf-8"), configFormat);
52152
52180
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
52153
52181
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
52154
52182
  copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
@@ -52292,10 +52320,10 @@ function runGit2(repoRoot, args) {
52292
52320
  }
52293
52321
  }
52294
52322
  function readRecord6(repoRoot) {
52295
- const path43 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
52296
- if (!(0, import_node_fs4.existsSync)(path43)) return null;
52323
+ const path44 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
52324
+ if (!(0, import_node_fs4.existsSync)(path44)) return null;
52297
52325
  try {
52298
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path43, "utf8"));
52326
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path44, "utf8"));
52299
52327
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
52300
52328
  } catch {
52301
52329
  return null;
@@ -52427,6 +52455,10 @@ var meshStatusHandlers = {
52427
52455
  const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions ? await ctx.deps.sessionHostControl.listSessions().catch(() => []) : [];
52428
52456
  const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
52429
52457
  const localMachineId = loadConfig().machineId || "";
52458
+ const localMachineNickname = (() => {
52459
+ const nick = loadConfig().machineNickname;
52460
+ return typeof nick === "string" && nick.trim() ? nick.trim() : "";
52461
+ })();
52430
52462
  const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
52431
52463
  const meshGitProbeCache = ctx.meshGitProbeCache;
52432
52464
  const directTruth = requireDirectPeerTruth ? await hydrateInlineMeshDirectTruth({
@@ -52507,6 +52539,9 @@ var meshStatusHandlers = {
52507
52539
  ) || Boolean(
52508
52540
  daemonId && (daemonIdsEquivalent(daemonId, localMachineId) || daemonIdsEquivalent(daemonId, ctx.deps.statusInstanceId))
52509
52541
  ) || Boolean(meshRecord?.inline && nodeIndex === 0) || sparseConfiguredCoordinatorNode;
52542
+ if (isSelfNode && localMachineNickname && !readStringValue(node.machineNickname, node.machine_nickname)) {
52543
+ node.machineNickname = localMachineNickname;
52544
+ }
52510
52545
  const machineIdentity = buildMeshNodeMachineIdentity(node, {
52511
52546
  localMachineId,
52512
52547
  localDaemonId: ctx.deps.statusInstanceId,
@@ -52843,7 +52878,7 @@ var meshStatusHandlers = {
52843
52878
  const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
52844
52879
  const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52845
52880
  const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
52846
- const { existsSync: existsSync53 } = await import("fs");
52881
+ const { existsSync: existsSync54 } = await import("fs");
52847
52882
  const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
52848
52883
  const mesh = meshRecord?.mesh;
52849
52884
  if (!mesh) return { success: false, error: "Mesh not found" };
@@ -52862,7 +52897,7 @@ var meshStatusHandlers = {
52862
52897
  const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
52863
52898
  for (const item of derivation.items) {
52864
52899
  const workspace = item.workspace;
52865
- if (!workspace || !existsSync53(workspace)) continue;
52900
+ if (!workspace || !existsSync54(workspace)) continue;
52866
52901
  const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
52867
52902
  try {
52868
52903
  const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
@@ -53070,9 +53105,9 @@ init_resolve_executable();
53070
53105
  var execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
53071
53106
  var GIT = process.platform === "win32" ? resolveWin32Executable("git") : "git";
53072
53107
  var MAX_CHANGED_FILES2 = 500;
53073
- function topLevel(path43) {
53074
- const slash = path43.indexOf("/");
53075
- return slash === -1 ? path43 : path43.slice(0, slash);
53108
+ function topLevel(path44) {
53109
+ const slash = path44.indexOf("/");
53110
+ return slash === -1 ? path44 : path44.slice(0, slash);
53076
53111
  }
53077
53112
  async function analyzeMeshRefineNodeChangeArea(args) {
53078
53113
  const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
@@ -53395,7 +53430,7 @@ function buildLivePeerGitConnection(connection, timestamp = (/* @__PURE__ */ new
53395
53430
  }
53396
53431
  function recordInlineMeshDirectGitTruth(node, git, source) {
53397
53432
  if (!node || typeof node !== "object" || Array.isArray(node)) {
53398
- return { reporterPlatform: null, reporterArch: null };
53433
+ return { reporterPlatform: null, reporterArch: null, reporterMachineNickname: null };
53399
53434
  }
53400
53435
  const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
53401
53436
  const updatedAt = new Date(checkedAt).toISOString();
@@ -53420,7 +53455,9 @@ function recordInlineMeshDirectGitTruth(node, git, source) {
53420
53455
  stampNodeReporterPlatform(node, reporterPlatform, reporterArch);
53421
53456
  if (reporterPlatform) node.reportedPlatform = reporterPlatform;
53422
53457
  if (reporterArch) node.reportedArch = reporterArch;
53423
- return { reporterPlatform, reporterArch };
53458
+ const reporterMachineNickname = readStringValue(git.reporterMachineNickname) ?? null;
53459
+ if (reporterMachineNickname) node.machineNickname = reporterMachineNickname;
53460
+ return { reporterPlatform, reporterArch, reporterMachineNickname };
53424
53461
  }
53425
53462
  function stampNodeReporterPlatform(node, platform10, arch2) {
53426
53463
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
@@ -53443,8 +53480,9 @@ function persistNodeReporterPlatform(meshSource, mesh, nodeId, reporter) {
53443
53480
  if (!meshId || !nodeId) return;
53444
53481
  const reportedPlatform = reporter.reporterPlatform ?? void 0;
53445
53482
  const reportedArch = reporter.reporterArch ?? void 0;
53446
- if (!reportedPlatform && !reportedArch) return;
53447
- void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch })).catch(() => {
53483
+ const reportedMachineNickname = reporter.reporterMachineNickname ?? void 0;
53484
+ if (!reportedPlatform && !reportedArch && !reportedMachineNickname) return;
53485
+ void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch, reportedMachineNickname })).catch(() => {
53448
53486
  });
53449
53487
  }
53450
53488
  function buildCachedInlineMeshGitStatus(node) {
@@ -54096,9 +54134,11 @@ async function probeRemoteMeshGitStatus(args) {
54096
54134
  if (!remoteGit || typeof remoteGit !== "object" || typeof remoteGit.isGitRepo !== "boolean") return null;
54097
54135
  const reporterPlatform = readStringValue(remoteResult?.reporterPlatform);
54098
54136
  const reporterArch = readStringValue(remoteResult?.reporterArch);
54137
+ const reporterMachineNickname = readStringValue(remoteResult?.reporterMachineNickname);
54099
54138
  const git = remoteGit;
54100
54139
  if (reporterPlatform) git.reporterPlatform = reporterPlatform;
54101
54140
  if (reporterArch) git.reporterArch = reporterArch;
54141
+ if (reporterMachineNickname) git.reporterMachineNickname = reporterMachineNickname;
54102
54142
  return git;
54103
54143
  }
54104
54144
  var MESH_DIRECT_PROBE_MAX_RETRIES = 2;
@@ -54125,7 +54165,7 @@ async function probeRemoteMeshGitStatusWithRetry(args) {
54125
54165
  const connection = args.getConnection?.(args.daemonId);
54126
54166
  if (args.getConnection && readMeshConnectionState(connection) !== "connected") break;
54127
54167
  if (connection) args.onConnection?.(connection);
54128
- await new Promise((resolve24) => setTimeout(resolve24, 250 * 2 ** (attempt - 1)));
54168
+ await new Promise((resolve25) => setTimeout(resolve25, 250 * 2 ** (attempt - 1)));
54129
54169
  }
54130
54170
  try {
54131
54171
  const remoteGit = await probeRemoteMeshGitStatus({
@@ -54502,18 +54542,18 @@ function resolveRefineryAutoPublishSubmoduleMainCommits(mesh, workspace) {
54502
54542
  return { enabled: false };
54503
54543
  }
54504
54544
  async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
54505
- const { execFileSync: execFileSync9 } = await import("child_process");
54545
+ const { execFileSync: execFileSync10 } = await import("child_process");
54506
54546
  const diffArgs = ["diff", "--patch", "--full-index", fromRef, toRef];
54507
54547
  if (excludePaths.length > 0) {
54508
- diffArgs.push("--", ".", ...excludePaths.map((path43) => `:(exclude)${path43}`));
54548
+ diffArgs.push("--", ".", ...excludePaths.map((path44) => `:(exclude)${path44}`));
54509
54549
  }
54510
- const diff = execFileSync9(GIT2, diffArgs, {
54550
+ const diff = execFileSync10(GIT2, diffArgs, {
54511
54551
  cwd,
54512
54552
  encoding: "utf8",
54513
54553
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
54514
54554
  });
54515
54555
  if (!diff.trim()) return "";
54516
- const patchId = execFileSync9(GIT2, ["patch-id", "--stable"], {
54556
+ const patchId = execFileSync10(GIT2, ["patch-id", "--stable"], {
54517
54557
  cwd,
54518
54558
  input: diff,
54519
54559
  encoding: "utf8",
@@ -54524,8 +54564,8 @@ async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
54524
54564
  async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead) {
54525
54565
  const startedAt = Date.now();
54526
54566
  try {
54527
- const { execFileSync: execFileSync9 } = await import("child_process");
54528
- const git = (args) => execFileSync9(GIT2, args, {
54567
+ const { execFileSync: execFileSync10 } = await import("child_process");
54568
+ const git = (args) => execFileSync10(GIT2, args, {
54529
54569
  cwd: repoRoot,
54530
54570
  encoding: "utf8",
54531
54571
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54616,8 +54656,8 @@ ${e?.stderr || ""}`
54616
54656
  async function checkWorktreeChangesPatchEquivalentInRef(repoRoot, ref, worktreeHead) {
54617
54657
  const startedAt = Date.now();
54618
54658
  try {
54619
- const { execFileSync: execFileSync9 } = await import("child_process");
54620
- const git = (gitArgs) => execFileSync9(GIT2, gitArgs, {
54659
+ const { execFileSync: execFileSync10 } = await import("child_process");
54660
+ const git = (gitArgs) => execFileSync10(GIT2, gitArgs, {
54621
54661
  cwd: repoRoot,
54622
54662
  encoding: "utf8",
54623
54663
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54680,8 +54720,8 @@ ${mergeTreeErr?.stderr || ""}`;
54680
54720
  async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54681
54721
  const startedAt = Date.now();
54682
54722
  try {
54683
- const { execFileSync: execFileSync9 } = await import("child_process");
54684
- const git = (args, opts) => execFileSync9(GIT2, args, {
54723
+ const { execFileSync: execFileSync10 } = await import("child_process");
54724
+ const git = (args, opts) => execFileSync10(GIT2, args, {
54685
54725
  cwd: opts?.cwd || repoRoot,
54686
54726
  encoding: "utf8",
54687
54727
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54706,9 +54746,9 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54706
54746
  if (!trimmed) continue;
54707
54747
  if (trimmed.startsWith("+")) {
54708
54748
  const parts = trimmed.slice(1).trim().split(/\s+/);
54709
- const path43 = parts[1] || parts[0] || "(unknown)";
54749
+ const path44 = parts[1] || parts[0] || "(unknown)";
54710
54750
  submoduleHints.push({
54711
- path: path43,
54751
+ path: path44,
54712
54752
  reason: "submodule checked-out commit differs from the committed gitlink (pointer bump not committed on the root branch)"
54713
54753
  });
54714
54754
  }
@@ -54738,10 +54778,10 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54738
54778
  }
54739
54779
  function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
54740
54780
  if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
54741
- const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path43) => ({
54742
- path: path43,
54743
- baseCommit: readTreeObject(repoRoot, baseHead, path43),
54744
- branchCommit: readTreeObject(repoRoot, branchHead, path43)
54781
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => ({
54782
+ path: path44,
54783
+ baseCommit: readTreeObject(repoRoot, baseHead, path44),
54784
+ branchCommit: readTreeObject(repoRoot, branchHead, path44)
54745
54785
  }));
54746
54786
  if (conflicts.length === 0) return void 0;
54747
54787
  return {
@@ -54767,11 +54807,11 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
54767
54807
  if (!line.trim()) continue;
54768
54808
  const metaAndPath = line.split(" ");
54769
54809
  const meta = metaAndPath[0] || "";
54770
- const path43 = metaAndPath[metaAndPath.length - 1]?.trim();
54771
- if (!path43) continue;
54810
+ const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
54811
+ if (!path44) continue;
54772
54812
  const parts = meta.split(/\s+/);
54773
54813
  if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
54774
- paths.add(path43);
54814
+ paths.add(path44);
54775
54815
  }
54776
54816
  }
54777
54817
  return [...paths].sort();
@@ -54779,9 +54819,9 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
54779
54819
  return [];
54780
54820
  }
54781
54821
  }
54782
- function readTreeObject(repoRoot, ref, path43) {
54822
+ function readTreeObject(repoRoot, ref, path44) {
54783
54823
  try {
54784
- const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path43], {
54824
+ const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path44], {
54785
54825
  cwd: repoRoot,
54786
54826
  encoding: "utf8",
54787
54827
  maxBuffer: 1024 * 1024
@@ -54826,12 +54866,12 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
54826
54866
  if (!line.trim()) continue;
54827
54867
  const metaAndPath = line.split(" ");
54828
54868
  const meta = metaAndPath[0] || "";
54829
- const path43 = metaAndPath[metaAndPath.length - 1]?.trim();
54830
- if (!path43 || seen.has(path43)) continue;
54831
- seen.add(path43);
54869
+ const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
54870
+ if (!path44 || seen.has(path44)) continue;
54871
+ seen.add(path44);
54832
54872
  const parts = meta.split(/\s+/);
54833
54873
  const isGitlink = !!(parts[0]?.includes("160000") || parts[1]?.includes("160000"));
54834
- result.push({ path: path43, isGitlink });
54874
+ result.push({ path: path44, isGitlink });
54835
54875
  }
54836
54876
  return result;
54837
54877
  } catch {
@@ -54839,20 +54879,20 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
54839
54879
  }
54840
54880
  }
54841
54881
  function collectFastForwardGitlinkPaths(repoRoot, baseHead, branchHead) {
54842
- return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path43) => {
54843
- const baseCommit = readTreeObject(repoRoot, baseHead, path43);
54844
- const branchCommit = readTreeObject(repoRoot, branchHead, path43);
54882
+ return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path44) => {
54883
+ const baseCommit = readTreeObject(repoRoot, baseHead, path44);
54884
+ const branchCommit = readTreeObject(repoRoot, branchHead, path44);
54845
54885
  if (!baseCommit || !branchCommit) return false;
54846
- return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path43), baseCommit, branchCommit);
54886
+ return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path44), baseCommit, branchCommit);
54847
54887
  });
54848
54888
  }
54849
54889
  function evaluateGitlinkTrivialFastForward(repoRoot, baseHead, branchHead) {
54850
- const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path43) => {
54851
- const baseCommit = readTreeObject(repoRoot, baseHead, path43);
54852
- const branchCommit = readTreeObject(repoRoot, branchHead, path43);
54853
- const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path43);
54890
+ const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => {
54891
+ const baseCommit = readTreeObject(repoRoot, baseHead, path44);
54892
+ const branchCommit = readTreeObject(repoRoot, branchHead, path44);
54893
+ const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path44);
54854
54894
  const fastForward = !!baseCommit && !!branchCommit && isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit);
54855
- return { path: path43, baseCommit, branchCommit, fastForward };
54895
+ return { path: path44, baseCommit, branchCommit, fastForward };
54856
54896
  });
54857
54897
  if (changedGitlinks.length === 0) {
54858
54898
  return { trivial: false, reason: "no_changed_gitlinks", gitlinks: changedGitlinks };
@@ -54903,7 +54943,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
54903
54943
  maxBuffer: 1024 * 1024
54904
54944
  }).trim();
54905
54945
  if (!tree) return void 0;
54906
- const updates = paths.map((path43) => `160000 commit ${placeholderCommit} ${path43}`).join("\n");
54946
+ const updates = paths.map((path44) => `160000 commit ${placeholderCommit} ${path44}`).join("\n");
54907
54947
  if (!updates) return tree;
54908
54948
  const tmpIndex = (0, import_path14.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
54909
54949
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
@@ -55006,7 +55046,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
55006
55046
  }
55007
55047
  async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
55008
55048
  const startedAt = Date.now();
55009
- const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path43) => !(options.submoduleIgnorePaths || []).includes(path43));
55049
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path44) => !(options.submoduleIgnorePaths || []).includes(path44));
55010
55050
  const preStatus = await getGitRepoStatus(repoRoot, {
55011
55051
  includeSubmodules: true,
55012
55052
  submoduleIgnorePaths: options.submoduleIgnorePaths,
@@ -55053,7 +55093,7 @@ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, cur
55053
55093
  changedGitlinkPaths,
55054
55094
  outOfSyncPaths,
55055
55095
  updatedPaths: updatePaths,
55056
- verifiedPaths: updatePaths.filter((path43) => !remaining.some((submodule) => submodule.path === path43)),
55096
+ verifiedPaths: updatePaths.filter((path44) => !remaining.some((submodule) => submodule.path === path44)),
55057
55097
  durationMs: Date.now() - startedAt,
55058
55098
  command: `git ${commandArgs.join(" ")}`,
55059
55099
  stdout: truncateValidationOutput(result.stdout),
@@ -55379,15 +55419,15 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
55379
55419
  const cwd = candidate.cwd ? (0, import_path14.resolve)(workspace, candidate.cwd) : workspace;
55380
55420
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
55381
55421
  const resolvedCommand = resolveWin32Executable(candidate.command);
55382
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55422
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55383
55423
  try {
55384
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
55424
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
55385
55425
  cwd,
55386
55426
  encoding: "utf8",
55387
55427
  timeout,
55388
55428
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
55389
55429
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} },
55390
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55430
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55391
55431
  });
55392
55432
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
55393
55433
  } catch (error) {
@@ -55425,15 +55465,15 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
55425
55465
  return summary;
55426
55466
  }
55427
55467
  const resolvedCommand = resolveWin32Executable(candidate.command);
55428
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55468
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55429
55469
  try {
55430
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
55470
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
55431
55471
  cwd,
55432
55472
  encoding: "utf8",
55433
55473
  timeout,
55434
55474
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
55435
55475
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} },
55436
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55476
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55437
55477
  });
55438
55478
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
55439
55479
  } catch (error) {
@@ -56142,7 +56182,7 @@ var DaemonCommandRouter = class {
56142
56182
  */
56143
56183
  async bestEffortRemoveWorktreeDir(dir) {
56144
56184
  if (!dir || !fs32.existsSync(dir)) return { removed: true, residue: false };
56145
- const sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
56185
+ const sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
56146
56186
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
56147
56187
  let lastErr;
56148
56188
  for (let attempt = 0; attempt < 4; attempt++) {
@@ -58900,7 +58940,7 @@ var ProviderStreamAdapter = class {
58900
58940
  const beforeCount = this.messageCount(before);
58901
58941
  const beforeSignature = this.lastMessageSignature(before);
58902
58942
  for (let attempt = 0; attempt < 12; attempt += 1) {
58903
- await new Promise((resolve24) => setTimeout(resolve24, 250));
58943
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
58904
58944
  let state;
58905
58945
  try {
58906
58946
  state = await this.readChat(evaluate);
@@ -58922,7 +58962,7 @@ var ProviderStreamAdapter = class {
58922
58962
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
58923
58963
  return first;
58924
58964
  }
58925
- await new Promise((resolve24) => setTimeout(resolve24, 150));
58965
+ await new Promise((resolve25) => setTimeout(resolve25, 150));
58926
58966
  const second = await this.readChat(evaluate);
58927
58967
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
58928
58968
  }
@@ -59073,7 +59113,7 @@ var ProviderStreamAdapter = class {
59073
59113
  if (typeof data.error === "string" && data.error.trim()) return false;
59074
59114
  }
59075
59115
  for (let attempt = 0; attempt < 6; attempt += 1) {
59076
- await new Promise((resolve24) => setTimeout(resolve24, 250));
59116
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
59077
59117
  const state = await this.readChat(evaluate);
59078
59118
  const title = this.getStateTitle(state);
59079
59119
  if (this.titlesMatch(title, sessionId)) return true;
@@ -60065,13 +60105,13 @@ var VersionArchive = class {
60065
60105
  }
60066
60106
  };
60067
60107
  async function runCommand(cmd, timeout = 1e4) {
60068
- return new Promise((resolve24) => {
60108
+ return new Promise((resolve25) => {
60069
60109
  (0, import_child_process10.exec)(cmd, {
60070
60110
  encoding: "utf-8",
60071
60111
  timeout
60072
60112
  }, (error, stdout) => {
60073
- if (error) return resolve24(null);
60074
- resolve24(stdout.trim());
60113
+ if (error) return resolve25(null);
60114
+ resolve25(stdout.trim());
60075
60115
  });
60076
60116
  });
60077
60117
  }
@@ -61771,7 +61811,7 @@ function getCliTargetBundle(ctx, type, instanceId) {
61771
61811
  return { target, instance, adapter };
61772
61812
  }
61773
61813
  function sleep2(ms) {
61774
- return new Promise((resolve24) => setTimeout(resolve24, ms));
61814
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
61775
61815
  }
61776
61816
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
61777
61817
  const startedAt = Date.now();
@@ -62747,8 +62787,8 @@ async function handleAutoImplement(ctx, type, req, res) {
62747
62787
  fs36.writeFileSync(promptFile, prompt, "utf-8");
62748
62788
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
62749
62789
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
62750
- const spawn4 = agentProvider?.spawn;
62751
- if (!spawn4?.command) {
62790
+ const spawn5 = agentProvider?.spawn;
62791
+ if (!spawn5?.command) {
62752
62792
  try {
62753
62793
  fs36.unlinkSync(promptFile);
62754
62794
  } catch {
@@ -62758,22 +62798,22 @@ async function handleAutoImplement(ctx, type, req, res) {
62758
62798
  }
62759
62799
  const agentCategory = agentProvider?.category;
62760
62800
  if (agentCategory === "acp") {
62761
- sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn4.command} ${(spawn4.args || []).join(" ")}` } });
62801
+ sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn5.command} ${(spawn5.args || []).join(" ")}` } });
62762
62802
  ctx.autoImplStatus.running = true;
62763
62803
  ctx.autoImplStatus.type = type;
62764
62804
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await import("@agentclientprotocol/sdk");
62765
62805
  const { Readable: Readable2, Writable: Writable2 } = await import("stream");
62766
62806
  const { spawn: spawnFn2 } = await import("child_process");
62767
- const acpArgs = [...spawn4.args || []];
62807
+ const acpArgs = [...spawn5.args || []];
62768
62808
  if (model) {
62769
62809
  acpArgs.push("--model", model);
62770
62810
  ctx.log(`Auto-implement ACP using model: ${model}`);
62771
62811
  }
62772
- const child2 = spawnFn2(spawn4.command, acpArgs, {
62812
+ const child2 = spawnFn2(spawn5.command, acpArgs, {
62773
62813
  cwd: providerDir,
62774
62814
  stdio: ["pipe", "pipe", "pipe"],
62775
- shell: spawn4.shell ?? false,
62776
- env: { ...process.env, ...spawn4.env || {} }
62815
+ shell: spawn5.shell ?? false,
62816
+ env: { ...process.env, ...spawn5.env || {} }
62777
62817
  });
62778
62818
  ctx.autoImplProcess = child2;
62779
62819
  child2.stderr?.on("data", (d) => {
@@ -62883,7 +62923,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62883
62923
  ctx.json(res, 202, {
62884
62924
  started: true,
62885
62925
  type,
62886
- agent: spawn4.command,
62926
+ agent: spawn5.command,
62887
62927
  functions,
62888
62928
  providerDir,
62889
62929
  message: "ACP Auto-implement started. Connect to SSE for progress.",
@@ -62891,10 +62931,10 @@ async function handleAutoImplement(ctx, type, req, res) {
62891
62931
  });
62892
62932
  return;
62893
62933
  }
62894
- const command = spawn4.command;
62895
- const autoImpl = spawn4.autoImpl;
62934
+ const command = spawn5.command;
62935
+ const autoImpl = spawn5.autoImpl;
62896
62936
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
62897
- const baseArgs = [...spawn4.args || []].filter((a) => !interactiveFlags.includes(a));
62937
+ const baseArgs = [...spawn5.args || []].filter((a) => !interactiveFlags.includes(a));
62898
62938
  let shellCmd;
62899
62939
  const isWin = os29.platform() === "win32";
62900
62940
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
@@ -62941,7 +62981,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62941
62981
  cols: import_session_host_core8.DEFAULT_SESSION_HOST_COLS,
62942
62982
  rows: import_session_host_core8.DEFAULT_SESSION_HOST_ROWS,
62943
62983
  cwd: providerDir,
62944
- env: { ...process.env, ...spawn4.env || {} }
62984
+ env: { ...process.env, ...spawn5.env || {} }
62945
62985
  });
62946
62986
  isPty = true;
62947
62987
  } catch (err) {
@@ -62953,7 +62993,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62953
62993
  stdio: ["pipe", "pipe", "pipe"],
62954
62994
  env: {
62955
62995
  ...process.env,
62956
- ...spawn4.env || {}
62996
+ ...spawn5.env || {}
62957
62997
  }
62958
62998
  });
62959
62999
  child.on("error", (err2) => {
@@ -63995,8 +64035,8 @@ var DevServer = class _DevServer {
63995
64035
  }
63996
64036
  getEndpointList() {
63997
64037
  return this.routes.map((r) => {
63998
- const path43 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
63999
- return `${r.method.padEnd(5)} ${path43}`;
64038
+ const path44 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
64039
+ return `${r.method.padEnd(5)} ${path44}`;
64000
64040
  });
64001
64041
  }
64002
64042
  async start(port = DEV_SERVER_PORT) {
@@ -64027,15 +64067,15 @@ var DevServer = class _DevServer {
64027
64067
  this.json(res, 500, { error: e.message });
64028
64068
  }
64029
64069
  });
64030
- return new Promise((resolve24, reject) => {
64070
+ return new Promise((resolve25, reject) => {
64031
64071
  this.server.listen(port, "127.0.0.1", () => {
64032
64072
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
64033
- resolve24();
64073
+ resolve25();
64034
64074
  });
64035
64075
  this.server.on("error", (e) => {
64036
64076
  if (e.code === "EADDRINUSE") {
64037
64077
  this.log(`Port ${port} in use, skipping dev server`);
64038
- resolve24();
64078
+ resolve25();
64039
64079
  } else {
64040
64080
  reject(e);
64041
64081
  }
@@ -64096,16 +64136,16 @@ var DevServer = class _DevServer {
64096
64136
  this.json(res, 404, { error: `Provider not found: ${type}` });
64097
64137
  return;
64098
64138
  }
64099
- const spawn4 = provider.spawn;
64100
- if (!spawn4) {
64139
+ const spawn5 = provider.spawn;
64140
+ if (!spawn5) {
64101
64141
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
64102
64142
  return;
64103
64143
  }
64104
64144
  const { spawn: spawnFn } = await import("child_process");
64105
64145
  const start = Date.now();
64106
64146
  try {
64107
- const child = spawnFn(spawn4.command, [...spawn4.args || []], {
64108
- shell: spawn4.shell ?? false,
64147
+ const child = spawnFn(spawn5.command, [...spawn5.args || []], {
64148
+ shell: spawn5.shell ?? false,
64109
64149
  timeout: 5e3,
64110
64150
  stdio: ["pipe", "pipe", "pipe"]
64111
64151
  });
@@ -64117,27 +64157,27 @@ var DevServer = class _DevServer {
64117
64157
  child.stderr?.on("data", (d) => {
64118
64158
  stderr += d.toString().slice(0, 2e3);
64119
64159
  });
64120
- await new Promise((resolve24) => {
64160
+ await new Promise((resolve25) => {
64121
64161
  const timer = setTimeout(() => {
64122
64162
  child.kill();
64123
- resolve24();
64163
+ resolve25();
64124
64164
  }, 3e3);
64125
64165
  child.on("exit", () => {
64126
64166
  clearTimeout(timer);
64127
- resolve24();
64167
+ resolve25();
64128
64168
  });
64129
64169
  child.stdout?.once("data", () => {
64130
64170
  setTimeout(() => {
64131
64171
  child.kill();
64132
64172
  clearTimeout(timer);
64133
- resolve24();
64173
+ resolve25();
64134
64174
  }, 500);
64135
64175
  });
64136
64176
  });
64137
64177
  const elapsed = Date.now() - start;
64138
64178
  this.json(res, 200, {
64139
64179
  success: true,
64140
- command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
64180
+ command: `${spawn5.command} ${(spawn5.args || []).join(" ")}`,
64141
64181
  elapsed,
64142
64182
  stdout: stdout.trim(),
64143
64183
  stderr: stderr.trim(),
@@ -64147,7 +64187,7 @@ var DevServer = class _DevServer {
64147
64187
  const elapsed = Date.now() - start;
64148
64188
  this.json(res, 200, {
64149
64189
  success: false,
64150
- command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
64190
+ command: `${spawn5.command} ${(spawn5.args || []).join(" ")}`,
64151
64191
  elapsed,
64152
64192
  error: e.message
64153
64193
  });
@@ -64610,20 +64650,20 @@ var DevServer = class _DevServer {
64610
64650
  this.json(res, 404, { error: `Provider not found: ${type}` });
64611
64651
  return;
64612
64652
  }
64613
- const spawn4 = provider.spawn;
64614
- if (!spawn4) {
64653
+ const spawn5 = provider.spawn;
64654
+ if (!spawn5) {
64615
64655
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
64616
64656
  return;
64617
64657
  }
64618
64658
  const { spawn: spawnFn } = await import("child_process");
64619
64659
  const start = Date.now();
64620
64660
  try {
64621
- const args = [...spawn4.args || [], message];
64622
- const child = spawnFn(spawn4.command, args, {
64623
- shell: spawn4.shell ?? false,
64661
+ const args = [...spawn5.args || [], message];
64662
+ const child = spawnFn(spawn5.command, args, {
64663
+ shell: spawn5.shell ?? false,
64624
64664
  timeout,
64625
64665
  stdio: ["pipe", "pipe", "pipe"],
64626
- env: { ...process.env, ...spawn4.env || {} }
64666
+ env: { ...process.env, ...spawn5.env || {} }
64627
64667
  });
64628
64668
  let stdout = "";
64629
64669
  let stderr = "";
@@ -64633,14 +64673,14 @@ var DevServer = class _DevServer {
64633
64673
  child.stderr?.on("data", (d) => {
64634
64674
  stderr += d.toString();
64635
64675
  });
64636
- await new Promise((resolve24) => {
64676
+ await new Promise((resolve25) => {
64637
64677
  const timer = setTimeout(() => {
64638
64678
  child.kill();
64639
- resolve24();
64679
+ resolve25();
64640
64680
  }, timeout);
64641
64681
  child.on("exit", () => {
64642
64682
  clearTimeout(timer);
64643
- resolve24();
64683
+ resolve25();
64644
64684
  });
64645
64685
  });
64646
64686
  const elapsed = Date.now() - start;
@@ -64839,14 +64879,14 @@ data: ${JSON.stringify(msg.data)}
64839
64879
  res.end(JSON.stringify(data, null, 2));
64840
64880
  }
64841
64881
  async readBody(req) {
64842
- return new Promise((resolve24) => {
64882
+ return new Promise((resolve25) => {
64843
64883
  let body = "";
64844
64884
  req.on("data", (chunk) => body += chunk);
64845
64885
  req.on("end", () => {
64846
64886
  try {
64847
- resolve24(JSON.parse(body));
64887
+ resolve25(JSON.parse(body));
64848
64888
  } catch {
64849
- resolve24({});
64889
+ resolve25({});
64850
64890
  }
64851
64891
  });
64852
64892
  });
@@ -65581,7 +65621,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS, requiredRe
65581
65621
  const deadline = Date.now() + timeoutMs;
65582
65622
  while (Date.now() < deadline) {
65583
65623
  if (await canConnect(endpoint, requiredRequestTypes)) return;
65584
- await new Promise((resolve24) => setTimeout(resolve24, STARTUP_POLL_MS));
65624
+ await new Promise((resolve25) => setTimeout(resolve25, STARTUP_POLL_MS));
65585
65625
  }
65586
65626
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
65587
65627
  }
@@ -65622,6 +65662,148 @@ async function listHostedCliRuntimes(endpoint) {
65622
65662
  }
65623
65663
  }
65624
65664
 
65665
+ // src/session-host/managed-host.ts
65666
+ var import_child_process11 = require("child_process");
65667
+ var fs38 = __toESM(require("fs"));
65668
+ var os30 = __toESM(require("os"));
65669
+ var path43 = __toESM(require("path"));
65670
+ var import_session_host_core12 = require("@adhdev/session-host-core");
65671
+ init_runtime_defaults();
65672
+ function createManagedSessionHost(options) {
65673
+ const appName = options.appName;
65674
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_HOST_READY_TIMEOUT_MS;
65675
+ const endpoint = (0, import_session_host_core12.getDefaultSessionHostEndpoint)(appName);
65676
+ const isManagedPid = options.isManagedPid ?? (() => true);
65677
+ function buildEnv(baseEnv) {
65678
+ const env = (0, import_session_host_core12.sanitizeSpawnEnv)(baseEnv);
65679
+ env.ADHDEV_SESSION_HOST_NAME = appName;
65680
+ return env;
65681
+ }
65682
+ function resolveEntry() {
65683
+ const packagedCandidates = [
65684
+ path43.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
65685
+ path43.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
65686
+ ];
65687
+ for (const candidate of packagedCandidates) {
65688
+ if (fs38.existsSync(candidate)) {
65689
+ return candidate;
65690
+ }
65691
+ }
65692
+ return require.resolve("@adhdev/session-host-daemon");
65693
+ }
65694
+ function getPidFile() {
65695
+ return path43.join(os30.homedir(), ".adhdev", `${appName}-session-host.pid`);
65696
+ }
65697
+ function getPid() {
65698
+ try {
65699
+ const pidFile = getPidFile();
65700
+ if (!fs38.existsSync(pidFile)) return null;
65701
+ const pid = Number.parseInt(fs38.readFileSync(pidFile, "utf8").trim(), 10);
65702
+ return Number.isFinite(pid) ? pid : null;
65703
+ } catch {
65704
+ return null;
65705
+ }
65706
+ }
65707
+ function killPid2(pid) {
65708
+ try {
65709
+ if (process.platform === "win32") {
65710
+ const spawnOpts = { stdio: "ignore" };
65711
+ if (options.killWindowsHide) spawnOpts.windowsHide = true;
65712
+ (0, import_child_process11.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], spawnOpts);
65713
+ } else {
65714
+ process.kill(pid, "SIGTERM");
65715
+ }
65716
+ return true;
65717
+ } catch {
65718
+ return false;
65719
+ }
65720
+ }
65721
+ function spawnHost() {
65722
+ const entry = resolveEntry();
65723
+ let stdio = "ignore";
65724
+ let logFd = null;
65725
+ if (options.spawnStdio === "logfile") {
65726
+ const logDir = path43.join(os30.homedir(), ".adhdev", "logs");
65727
+ fs38.mkdirSync(logDir, { recursive: true });
65728
+ logFd = fs38.openSync(path43.join(logDir, "session-host.log"), "a");
65729
+ stdio = ["ignore", logFd, logFd];
65730
+ }
65731
+ const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
65732
+ detached: true,
65733
+ stdio,
65734
+ windowsHide: true,
65735
+ env: buildEnv(process.env)
65736
+ });
65737
+ child.unref();
65738
+ if (logFd !== null) {
65739
+ try {
65740
+ fs38.closeSync(logFd);
65741
+ } catch {
65742
+ }
65743
+ }
65744
+ }
65745
+ function stopManagedSessionHostProcess() {
65746
+ let stopped = false;
65747
+ const pidFile = getPidFile();
65748
+ try {
65749
+ if (fs38.existsSync(pidFile)) {
65750
+ const pid = Number.parseInt(fs38.readFileSync(pidFile, "utf8").trim(), 10);
65751
+ if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
65752
+ stopped = killPid2(pid) || stopped;
65753
+ }
65754
+ }
65755
+ } catch {
65756
+ } finally {
65757
+ try {
65758
+ fs38.unlinkSync(pidFile);
65759
+ } catch {
65760
+ }
65761
+ }
65762
+ if (options.extraStop) {
65763
+ stopped = options.extraStop(endpoint) || stopped;
65764
+ }
65765
+ return stopped;
65766
+ }
65767
+ async function ensureReady() {
65768
+ options.beforeEnsureReady?.();
65769
+ try {
65770
+ return await ensureSessionHostReady({
65771
+ appName,
65772
+ spawnHost,
65773
+ timeoutMs,
65774
+ requiredRequestTypes: options.requiredRequestTypes
65775
+ });
65776
+ } catch (error) {
65777
+ stopManagedSessionHostProcess();
65778
+ return ensureSessionHostReady({
65779
+ appName,
65780
+ spawnHost,
65781
+ timeoutMs,
65782
+ requiredRequestTypes: options.requiredRequestTypes
65783
+ }).catch((retryError) => {
65784
+ const initialMessage = error instanceof Error ? error.message : String(error);
65785
+ const retryMessage = retryError instanceof Error ? retryError.message : String(retryError);
65786
+ throw new Error(`Session host failed to start after retry (${initialMessage}; retry: ${retryMessage})`);
65787
+ });
65788
+ }
65789
+ }
65790
+ return {
65791
+ appName,
65792
+ endpoint,
65793
+ getPidFile,
65794
+ getPid,
65795
+ buildEnv,
65796
+ resolveEntry,
65797
+ killPid: killPid2,
65798
+ spawnHost,
65799
+ stopManagedSessionHostProcess,
65800
+ ensureReady,
65801
+ getStatusPaths() {
65802
+ return { pidFile: getPidFile(), endpoint };
65803
+ }
65804
+ };
65805
+ }
65806
+
65625
65807
  // src/session-host/startup-restore-policy.js
65626
65808
  function shouldAutoRestoreHostedSessionsOnStartup(env = process.env) {
65627
65809
  const raw = typeof env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP === "string" ? env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP.trim().toLowerCase() : "";
@@ -65631,7 +65813,7 @@ function shouldAutoRestoreHostedSessionsOnStartup(env = process.env) {
65631
65813
  }
65632
65814
 
65633
65815
  // src/installer.ts
65634
- var import_child_process11 = require("child_process");
65816
+ var import_child_process12 = require("child_process");
65635
65817
  var import_util3 = require("util");
65636
65818
  var EXTENSION_CATALOG = [
65637
65819
  // AI Agent extensions
@@ -65719,7 +65901,7 @@ var EXTENSION_CATALOG = [
65719
65901
  apiKeyName: "OpenAI/Anthropic API key"
65720
65902
  }
65721
65903
  ];
65722
- var execAsync4 = (0, import_util3.promisify)(import_child_process11.exec);
65904
+ var execAsync4 = (0, import_util3.promisify)(import_child_process12.exec);
65723
65905
  async function isExtensionInstalled(ide, marketplaceId) {
65724
65906
  if (!ide.cliCommand) return false;
65725
65907
  try {
@@ -65759,12 +65941,12 @@ async function installExtension(ide, extension) {
65759
65941
  const res = await fetch(extension.vsixUrl);
65760
65942
  if (res.ok) {
65761
65943
  const buffer = Buffer.from(await res.arrayBuffer());
65762
- const fs38 = await import("fs");
65763
- fs38.writeFileSync(vsixPath, buffer);
65764
- return new Promise((resolve24) => {
65944
+ const fs39 = await import("fs");
65945
+ fs39.writeFileSync(vsixPath, buffer);
65946
+ return new Promise((resolve25) => {
65765
65947
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
65766
- (0, import_child_process11.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
65767
- resolve24({
65948
+ (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
65949
+ resolve25({
65768
65950
  extensionId: extension.id,
65769
65951
  marketplaceId: extension.marketplaceId,
65770
65952
  success: !error,
@@ -65777,11 +65959,11 @@ async function installExtension(ide, extension) {
65777
65959
  } catch (e) {
65778
65960
  }
65779
65961
  }
65780
- return new Promise((resolve24) => {
65962
+ return new Promise((resolve25) => {
65781
65963
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
65782
- (0, import_child_process11.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
65964
+ (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
65783
65965
  if (error) {
65784
- resolve24({
65966
+ resolve25({
65785
65967
  extensionId: extension.id,
65786
65968
  marketplaceId: extension.marketplaceId,
65787
65969
  success: false,
@@ -65789,7 +65971,7 @@ async function installExtension(ide, extension) {
65789
65971
  error: stderr || error.message
65790
65972
  });
65791
65973
  } else {
65792
- resolve24({
65974
+ resolve25({
65793
65975
  extensionId: extension.id,
65794
65976
  marketplaceId: extension.marketplaceId,
65795
65977
  success: true,
@@ -65816,7 +65998,7 @@ function launchIDE(ide, workspacePath) {
65816
65998
  if (!ide.cliCommand) return false;
65817
65999
  try {
65818
66000
  const args = workspacePath ? `"${workspacePath}"` : "";
65819
- (0, import_child_process11.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
66001
+ (0, import_child_process12.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
65820
66002
  return true;
65821
66003
  } catch {
65822
66004
  return false;
@@ -66278,7 +66460,7 @@ async function startLocalIpcServer(opts) {
66278
66460
  }));
66279
66461
  }
66280
66462
  }
66281
- await new Promise((resolve24, reject) => {
66463
+ await new Promise((resolve25, reject) => {
66282
66464
  const onError = (error) => {
66283
66465
  httpServer?.off("listening", onListening);
66284
66466
  reject(error);
@@ -66286,7 +66468,7 @@ async function startLocalIpcServer(opts) {
66286
66468
  const onListening = () => {
66287
66469
  httpServer?.off("error", onError);
66288
66470
  listening = true;
66289
- resolve24();
66471
+ resolve25();
66290
66472
  };
66291
66473
  httpServer.once("error", onError);
66292
66474
  httpServer.once("listening", onListening);
@@ -66313,12 +66495,12 @@ async function startLocalIpcServer(opts) {
66313
66495
  }
66314
66496
  }
66315
66497
  clients.clear();
66316
- await new Promise((resolve24) => {
66498
+ await new Promise((resolve25) => {
66317
66499
  if (!httpServer) {
66318
- resolve24();
66500
+ resolve25();
66319
66501
  return;
66320
66502
  }
66321
- httpServer.close(() => resolve24());
66503
+ httpServer.close(() => resolve25());
66322
66504
  });
66323
66505
  httpServer = null;
66324
66506
  wss = null;
@@ -66570,6 +66752,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
66570
66752
  createGitSnapshotStore,
66571
66753
  createGitWorkspaceMonitor,
66572
66754
  createInteractionId,
66755
+ createManagedSessionHost,
66573
66756
  createMesh,
66574
66757
  createNativeHistoryDispatcher,
66575
66758
  createSessionDelivery,