@adhdev/daemon-core 0.9.82-rc.445 → 0.9.82-rc.447

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.mjs CHANGED
@@ -404,10 +404,10 @@ function readInjected(value) {
404
404
  }
405
405
  function getDaemonBuildInfo() {
406
406
  if (cached) return cached;
407
- const commit = readInjected(true ? "92b0714a88a4e1e253a40fa5a8c49602d087a5b3" : void 0) ?? "unknown";
408
- const commitShort = readInjected(true ? "92b0714a" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
409
- const version = readInjected(true ? "0.9.82-rc.445" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
410
- const builtAt = readInjected(true ? "2026-07-01T12:57:54.212Z" : void 0);
407
+ const commit = readInjected(true ? "fb4b6fd9ffb70781692aceb7eea162dd92606fad" : void 0) ?? "unknown";
408
+ const commitShort = readInjected(true ? "fb4b6fd9" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
409
+ const version = readInjected(true ? "0.9.82-rc.447" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
410
+ const builtAt = readInjected(true ? "2026-07-01T16:13:26.252Z" : void 0);
411
411
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
412
412
  return cached;
413
413
  }
@@ -1497,6 +1497,255 @@ var init_git_diff = __esm({
1497
1497
  }
1498
1498
  });
1499
1499
 
1500
+ // src/config/config.ts
1501
+ var config_exports = {};
1502
+ __export(config_exports, {
1503
+ generateMachineId: () => generateMachineId,
1504
+ getConfigDir: () => getConfigDir,
1505
+ getDaemonDataDir: () => getDaemonDataDir,
1506
+ isSetupComplete: () => isSetupComplete,
1507
+ isStableMachineId: () => isStableMachineId,
1508
+ loadConfig: () => loadConfig,
1509
+ markSetupComplete: () => markSetupComplete,
1510
+ resetConfig: () => resetConfig,
1511
+ resolveProviderSourceMode: () => resolveProviderSourceMode,
1512
+ saveConfig: () => saveConfig,
1513
+ updateConfig: () => updateConfig
1514
+ });
1515
+ import { homedir } from "os";
1516
+ import { join as join2 } from "path";
1517
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, chmodSync } from "fs";
1518
+ import { randomUUID } from "crypto";
1519
+ function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
1520
+ if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
1521
+ return providerSourceMode;
1522
+ }
1523
+ return legacyDisableUpstream === true ? "no-upstream" : "normal";
1524
+ }
1525
+ function isPlainObject(value) {
1526
+ return !!value && typeof value === "object" && !Array.isArray(value);
1527
+ }
1528
+ function asStringArray(value) {
1529
+ if (!Array.isArray(value)) return [];
1530
+ return value.filter((item) => typeof item === "string");
1531
+ }
1532
+ function asNullableString(value) {
1533
+ return typeof value === "string" ? value : null;
1534
+ }
1535
+ function asOptionalString(value) {
1536
+ return typeof value === "string" && value.trim() ? value : void 0;
1537
+ }
1538
+ function asBoolean(value, fallback) {
1539
+ return typeof value === "boolean" ? value : fallback;
1540
+ }
1541
+ function normalizeMachineProviders(value) {
1542
+ if (!isPlainObject(value)) return {};
1543
+ const result = {};
1544
+ for (const [providerType, raw] of Object.entries(value)) {
1545
+ if (!isPlainObject(raw)) continue;
1546
+ const entry = {};
1547
+ if (raw.enabled === true) entry.enabled = true;
1548
+ if (typeof raw.executable === "string" && raw.executable.trim()) {
1549
+ entry.executable = raw.executable.trim();
1550
+ }
1551
+ if (Array.isArray(raw.args)) {
1552
+ entry.args = raw.args.filter((arg) => typeof arg === "string");
1553
+ }
1554
+ if (isPlainObject(raw.lastDetection)) {
1555
+ entry.lastDetection = raw.lastDetection;
1556
+ }
1557
+ if (isPlainObject(raw.lastVerification)) {
1558
+ entry.lastVerification = raw.lastVerification;
1559
+ }
1560
+ result[providerType] = entry;
1561
+ }
1562
+ return result;
1563
+ }
1564
+ function normalizeConfig(raw) {
1565
+ const parsed = isPlainObject(raw) ? raw : {};
1566
+ return {
1567
+ serverUrl: typeof parsed.serverUrl === "string" && parsed.serverUrl.trim() ? parsed.serverUrl : DEFAULT_CONFIG.serverUrl,
1568
+ allowServerApiProxy: asBoolean(parsed.allowServerApiProxy, DEFAULT_CONFIG.allowServerApiProxy ?? false),
1569
+ selectedIde: asNullableString(parsed.selectedIde),
1570
+ configuredIdes: asStringArray(parsed.configuredIdes),
1571
+ installedExtensions: asStringArray(parsed.installedExtensions),
1572
+ userEmail: asNullableString(parsed.userEmail),
1573
+ userName: asNullableString(parsed.userName),
1574
+ setupCompleted: asBoolean(parsed.setupCompleted, DEFAULT_CONFIG.setupCompleted),
1575
+ setupDate: asNullableString(parsed.setupDate),
1576
+ enabledIdes: asStringArray(parsed.enabledIdes),
1577
+ workspaces: Array.isArray(parsed.workspaces) ? parsed.workspaces : [],
1578
+ defaultWorkspaceId: asNullableString(parsed.defaultWorkspaceId) ?? asNullableString(parsed.activeWorkspaceId),
1579
+ machineNickname: asNullableString(parsed.machineNickname),
1580
+ machineId: asOptionalString(parsed.machineId),
1581
+ machineSecret: parsed.machineSecret === null ? null : asOptionalString(parsed.machineSecret),
1582
+ registeredMachineId: asOptionalString(parsed.registeredMachineId),
1583
+ providerSettings: isPlainObject(parsed.providerSettings) ? parsed.providerSettings : {},
1584
+ machineProviders: normalizeMachineProviders(parsed.machineProviders),
1585
+ ideSettings: isPlainObject(parsed.ideSettings) ? parsed.ideSettings : {},
1586
+ providerSourceMode: resolveProviderSourceMode(parsed.providerSourceMode, parsed.disableUpstream),
1587
+ providerDir: asOptionalString(parsed.providerDir),
1588
+ updateChannel: parsed.updateChannel === "preview" ? "preview" : "stable",
1589
+ terminalSizingMode: parsed.terminalSizingMode === "fit" ? "fit" : "measured"
1590
+ };
1591
+ }
1592
+ function generateMachineId() {
1593
+ return `${MACHINE_ID_PREFIX}${randomUUID().replace(/-/g, "")}`;
1594
+ }
1595
+ function isStableMachineId(machineId) {
1596
+ return typeof machineId === "string" && machineId.startsWith(MACHINE_ID_PREFIX);
1597
+ }
1598
+ function ensureMachineId(config) {
1599
+ if (isStableMachineId(config.machineId)) {
1600
+ return { config, changed: false };
1601
+ }
1602
+ return {
1603
+ config: {
1604
+ ...config,
1605
+ machineId: generateMachineId()
1606
+ },
1607
+ changed: true
1608
+ };
1609
+ }
1610
+ function getConfigDir() {
1611
+ const override = process.env.ADHDEV_CONFIG_DIR;
1612
+ const dir = override && override.trim() ? override.trim() : join2(homedir(), ".adhdev");
1613
+ if (!existsSync2(dir)) {
1614
+ mkdirSync(dir, { recursive: true });
1615
+ }
1616
+ return dir;
1617
+ }
1618
+ function getDaemonDataDir() {
1619
+ const dir = join2(getConfigDir(), "daemon");
1620
+ if (!existsSync2(dir)) {
1621
+ mkdirSync(dir, { recursive: true });
1622
+ }
1623
+ return dir;
1624
+ }
1625
+ function getConfigPath() {
1626
+ return join2(getConfigDir(), "config.json");
1627
+ }
1628
+ function migrateStateToStateFile(raw) {
1629
+ const statePath = join2(getConfigDir(), "state.json");
1630
+ if (existsSync2(statePath)) return;
1631
+ const recentActivity = Array.isArray(raw.recentActivity) ? raw.recentActivity : [];
1632
+ const savedProviderSessions = Array.isArray(raw.savedProviderSessions) ? raw.savedProviderSessions : [];
1633
+ const legacySessionReads = isPlainObject(raw.recentSessionReads) ? raw.recentSessionReads : {};
1634
+ const sessionReads = isPlainObject(raw.sessionReads) ? raw.sessionReads : {};
1635
+ const sessionReadMarkers = isPlainObject(raw.sessionReadMarkers) ? raw.sessionReadMarkers : {};
1636
+ const hasData = recentActivity.length > 0 || savedProviderSessions.length > 0 || Object.keys(sessionReads).length > 0 || Object.keys(legacySessionReads).length > 0 || Object.keys(sessionReadMarkers).length > 0;
1637
+ if (!hasData) return;
1638
+ const mergedReads = Object.fromEntries(
1639
+ Object.entries({ ...legacySessionReads, ...sessionReads }).filter(([, v]) => typeof v === "number" && Number.isFinite(v))
1640
+ );
1641
+ const cleanedMarkers = Object.fromEntries(
1642
+ Object.entries(sessionReadMarkers).filter(([, v]) => typeof v === "string")
1643
+ );
1644
+ const state = {
1645
+ recentActivity,
1646
+ savedProviderSessions,
1647
+ sessionReads: mergedReads,
1648
+ sessionReadMarkers: cleanedMarkers
1649
+ };
1650
+ writeFileSync(statePath, JSON.stringify(state, null, 2), { encoding: "utf-8", mode: 384 });
1651
+ }
1652
+ function loadConfig() {
1653
+ const configPath = getConfigPath();
1654
+ if (!existsSync2(configPath)) {
1655
+ const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1656
+ try {
1657
+ saveConfig(initialized.config);
1658
+ } catch {
1659
+ }
1660
+ return initialized.config;
1661
+ }
1662
+ try {
1663
+ const raw = readFileSync2(configPath, "utf-8");
1664
+ const parsed = JSON.parse(raw);
1665
+ migrateStateToStateFile(parsed);
1666
+ const normalizedInput = normalizeConfig(parsed);
1667
+ const ensured = ensureMachineId(normalizedInput);
1668
+ const normalized = ensured.config;
1669
+ if (ensured.changed || JSON.stringify(parsed) !== JSON.stringify(normalized)) {
1670
+ try {
1671
+ saveConfig(normalized);
1672
+ } catch {
1673
+ }
1674
+ }
1675
+ return normalized;
1676
+ } catch {
1677
+ const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1678
+ return initialized.config;
1679
+ }
1680
+ }
1681
+ function saveConfig(config) {
1682
+ const configPath = getConfigPath();
1683
+ const dir = getConfigDir();
1684
+ const normalized = normalizeConfig(config);
1685
+ if (!existsSync2(dir)) {
1686
+ mkdirSync(dir, { recursive: true, mode: 448 });
1687
+ }
1688
+ writeFileSync(configPath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
1689
+ try {
1690
+ chmodSync(configPath, 384);
1691
+ } catch {
1692
+ }
1693
+ }
1694
+ function updateConfig(updates) {
1695
+ const config = loadConfig();
1696
+ const updated = { ...config, ...updates };
1697
+ saveConfig(updated);
1698
+ return updated;
1699
+ }
1700
+ function markSetupComplete(ideId, extensions) {
1701
+ const ideIds = Array.isArray(ideId) ? ideId : [ideId];
1702
+ return updateConfig({
1703
+ selectedIde: ideIds[0],
1704
+ configuredIdes: ideIds,
1705
+ installedExtensions: extensions,
1706
+ setupCompleted: true,
1707
+ setupDate: (/* @__PURE__ */ new Date()).toISOString()
1708
+ });
1709
+ }
1710
+ function isSetupComplete() {
1711
+ const config = loadConfig();
1712
+ return config.setupCompleted;
1713
+ }
1714
+ function resetConfig() {
1715
+ saveConfig({ ...DEFAULT_CONFIG });
1716
+ }
1717
+ var DEFAULT_CONFIG, MACHINE_ID_PREFIX;
1718
+ var init_config = __esm({
1719
+ "src/config/config.ts"() {
1720
+ "use strict";
1721
+ DEFAULT_CONFIG = {
1722
+ serverUrl: "https://api.adhf.dev",
1723
+ allowServerApiProxy: false,
1724
+ selectedIde: null,
1725
+ configuredIdes: [],
1726
+ installedExtensions: [],
1727
+ userEmail: null,
1728
+ userName: null,
1729
+ setupCompleted: false,
1730
+ setupDate: null,
1731
+ enabledIdes: [],
1732
+ workspaces: [],
1733
+ defaultWorkspaceId: null,
1734
+ machineNickname: null,
1735
+ machineId: void 0,
1736
+ machineSecret: null,
1737
+ registeredMachineId: void 0,
1738
+ providerSettings: {},
1739
+ machineProviders: {},
1740
+ ideSettings: {},
1741
+ providerSourceMode: "normal",
1742
+ updateChannel: "stable",
1743
+ terminalSizingMode: "measured"
1744
+ };
1745
+ MACHINE_ID_PREFIX = "mach_";
1746
+ }
1747
+ });
1748
+
1500
1749
  // src/git/git-worktree.ts
1501
1750
  var git_worktree_exports = {};
1502
1751
  __export(git_worktree_exports, {
@@ -1509,7 +1758,7 @@ __export(git_worktree_exports, {
1509
1758
  });
1510
1759
  import * as path4 from "path";
1511
1760
  import { mkdir } from "fs/promises";
1512
- import { existsSync as existsSync2 } from "fs";
1761
+ import { existsSync as existsSync3 } from "fs";
1513
1762
  import { execFile as execFile2 } from "child_process";
1514
1763
  import { promisify as promisify2 } from "util";
1515
1764
  function resolveWorktreePath(repoRoot, meshName, branch) {
@@ -1602,7 +1851,7 @@ async function createWorktree(opts) {
1602
1851
  const { repoRoot, branch, baseBranch, meshName } = opts;
1603
1852
  const remote = (opts.remote || "origin").trim() || "origin";
1604
1853
  const targetDir = opts.targetDir || resolveWorktreePath(repoRoot, meshName, branch);
1605
- if (existsSync2(targetDir)) {
1854
+ if (existsSync3(targetDir)) {
1606
1855
  throw new Error(`Worktree target directory already exists: ${targetDir}`);
1607
1856
  }
1608
1857
  await mkdir(path4.dirname(targetDir), { recursive: true });
@@ -1627,7 +1876,7 @@ async function createWorktree(opts) {
1627
1876
  } catch (error) {
1628
1877
  const stderr = typeof error.stderr === "string" ? error.stderr : "";
1629
1878
  if (/already exists/i.test(stderr)) {
1630
- if (existsSync2(targetDir)) {
1879
+ if (existsSync3(targetDir)) {
1631
1880
  throw new Error(`Worktree target directory was created concurrently: ${targetDir}`);
1632
1881
  }
1633
1882
  throw new Error(`Branch '${branch}' already exists or is checked out in another worktree`);
@@ -1642,7 +1891,7 @@ async function createWorktree(opts) {
1642
1891
  };
1643
1892
  }
1644
1893
  async function removeWorktree(repoRoot, worktreePath, opts = {}) {
1645
- if (!existsSync2(worktreePath)) {
1894
+ if (!existsSync3(worktreePath)) {
1646
1895
  await pruneWorktrees(repoRoot);
1647
1896
  return { success: true, removedPath: worktreePath };
1648
1897
  }
@@ -1807,255 +2056,6 @@ var init_git_worktree = __esm({
1807
2056
  }
1808
2057
  });
1809
2058
 
1810
- // src/config/config.ts
1811
- var config_exports = {};
1812
- __export(config_exports, {
1813
- generateMachineId: () => generateMachineId,
1814
- getConfigDir: () => getConfigDir,
1815
- getDaemonDataDir: () => getDaemonDataDir,
1816
- isSetupComplete: () => isSetupComplete,
1817
- isStableMachineId: () => isStableMachineId,
1818
- loadConfig: () => loadConfig,
1819
- markSetupComplete: () => markSetupComplete,
1820
- resetConfig: () => resetConfig,
1821
- resolveProviderSourceMode: () => resolveProviderSourceMode,
1822
- saveConfig: () => saveConfig,
1823
- updateConfig: () => updateConfig
1824
- });
1825
- import { homedir } from "os";
1826
- import { join as join3 } from "path";
1827
- import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync, chmodSync } from "fs";
1828
- import { randomUUID } from "crypto";
1829
- function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
1830
- if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
1831
- return providerSourceMode;
1832
- }
1833
- return legacyDisableUpstream === true ? "no-upstream" : "normal";
1834
- }
1835
- function isPlainObject(value) {
1836
- return !!value && typeof value === "object" && !Array.isArray(value);
1837
- }
1838
- function asStringArray(value) {
1839
- if (!Array.isArray(value)) return [];
1840
- return value.filter((item) => typeof item === "string");
1841
- }
1842
- function asNullableString(value) {
1843
- return typeof value === "string" ? value : null;
1844
- }
1845
- function asOptionalString(value) {
1846
- return typeof value === "string" && value.trim() ? value : void 0;
1847
- }
1848
- function asBoolean(value, fallback) {
1849
- return typeof value === "boolean" ? value : fallback;
1850
- }
1851
- function normalizeMachineProviders(value) {
1852
- if (!isPlainObject(value)) return {};
1853
- const result = {};
1854
- for (const [providerType, raw] of Object.entries(value)) {
1855
- if (!isPlainObject(raw)) continue;
1856
- const entry = {};
1857
- if (raw.enabled === true) entry.enabled = true;
1858
- if (typeof raw.executable === "string" && raw.executable.trim()) {
1859
- entry.executable = raw.executable.trim();
1860
- }
1861
- if (Array.isArray(raw.args)) {
1862
- entry.args = raw.args.filter((arg) => typeof arg === "string");
1863
- }
1864
- if (isPlainObject(raw.lastDetection)) {
1865
- entry.lastDetection = raw.lastDetection;
1866
- }
1867
- if (isPlainObject(raw.lastVerification)) {
1868
- entry.lastVerification = raw.lastVerification;
1869
- }
1870
- result[providerType] = entry;
1871
- }
1872
- return result;
1873
- }
1874
- function normalizeConfig(raw) {
1875
- const parsed = isPlainObject(raw) ? raw : {};
1876
- return {
1877
- serverUrl: typeof parsed.serverUrl === "string" && parsed.serverUrl.trim() ? parsed.serverUrl : DEFAULT_CONFIG.serverUrl,
1878
- allowServerApiProxy: asBoolean(parsed.allowServerApiProxy, DEFAULT_CONFIG.allowServerApiProxy ?? false),
1879
- selectedIde: asNullableString(parsed.selectedIde),
1880
- configuredIdes: asStringArray(parsed.configuredIdes),
1881
- installedExtensions: asStringArray(parsed.installedExtensions),
1882
- userEmail: asNullableString(parsed.userEmail),
1883
- userName: asNullableString(parsed.userName),
1884
- setupCompleted: asBoolean(parsed.setupCompleted, DEFAULT_CONFIG.setupCompleted),
1885
- setupDate: asNullableString(parsed.setupDate),
1886
- enabledIdes: asStringArray(parsed.enabledIdes),
1887
- workspaces: Array.isArray(parsed.workspaces) ? parsed.workspaces : [],
1888
- defaultWorkspaceId: asNullableString(parsed.defaultWorkspaceId) ?? asNullableString(parsed.activeWorkspaceId),
1889
- machineNickname: asNullableString(parsed.machineNickname),
1890
- machineId: asOptionalString(parsed.machineId),
1891
- machineSecret: parsed.machineSecret === null ? null : asOptionalString(parsed.machineSecret),
1892
- registeredMachineId: asOptionalString(parsed.registeredMachineId),
1893
- providerSettings: isPlainObject(parsed.providerSettings) ? parsed.providerSettings : {},
1894
- machineProviders: normalizeMachineProviders(parsed.machineProviders),
1895
- ideSettings: isPlainObject(parsed.ideSettings) ? parsed.ideSettings : {},
1896
- providerSourceMode: resolveProviderSourceMode(parsed.providerSourceMode, parsed.disableUpstream),
1897
- providerDir: asOptionalString(parsed.providerDir),
1898
- updateChannel: parsed.updateChannel === "preview" ? "preview" : "stable",
1899
- terminalSizingMode: parsed.terminalSizingMode === "fit" ? "fit" : "measured"
1900
- };
1901
- }
1902
- function generateMachineId() {
1903
- return `${MACHINE_ID_PREFIX}${randomUUID().replace(/-/g, "")}`;
1904
- }
1905
- function isStableMachineId(machineId) {
1906
- return typeof machineId === "string" && machineId.startsWith(MACHINE_ID_PREFIX);
1907
- }
1908
- function ensureMachineId(config) {
1909
- if (isStableMachineId(config.machineId)) {
1910
- return { config, changed: false };
1911
- }
1912
- return {
1913
- config: {
1914
- ...config,
1915
- machineId: generateMachineId()
1916
- },
1917
- changed: true
1918
- };
1919
- }
1920
- function getConfigDir() {
1921
- const override = process.env.ADHDEV_CONFIG_DIR;
1922
- const dir = override && override.trim() ? override.trim() : join3(homedir(), ".adhdev");
1923
- if (!existsSync3(dir)) {
1924
- mkdirSync(dir, { recursive: true });
1925
- }
1926
- return dir;
1927
- }
1928
- function getDaemonDataDir() {
1929
- const dir = join3(getConfigDir(), "daemon");
1930
- if (!existsSync3(dir)) {
1931
- mkdirSync(dir, { recursive: true });
1932
- }
1933
- return dir;
1934
- }
1935
- function getConfigPath() {
1936
- return join3(getConfigDir(), "config.json");
1937
- }
1938
- function migrateStateToStateFile(raw) {
1939
- const statePath = join3(getConfigDir(), "state.json");
1940
- if (existsSync3(statePath)) return;
1941
- const recentActivity = Array.isArray(raw.recentActivity) ? raw.recentActivity : [];
1942
- const savedProviderSessions = Array.isArray(raw.savedProviderSessions) ? raw.savedProviderSessions : [];
1943
- const legacySessionReads = isPlainObject(raw.recentSessionReads) ? raw.recentSessionReads : {};
1944
- const sessionReads = isPlainObject(raw.sessionReads) ? raw.sessionReads : {};
1945
- const sessionReadMarkers = isPlainObject(raw.sessionReadMarkers) ? raw.sessionReadMarkers : {};
1946
- const hasData = recentActivity.length > 0 || savedProviderSessions.length > 0 || Object.keys(sessionReads).length > 0 || Object.keys(legacySessionReads).length > 0 || Object.keys(sessionReadMarkers).length > 0;
1947
- if (!hasData) return;
1948
- const mergedReads = Object.fromEntries(
1949
- Object.entries({ ...legacySessionReads, ...sessionReads }).filter(([, v]) => typeof v === "number" && Number.isFinite(v))
1950
- );
1951
- const cleanedMarkers = Object.fromEntries(
1952
- Object.entries(sessionReadMarkers).filter(([, v]) => typeof v === "string")
1953
- );
1954
- const state = {
1955
- recentActivity,
1956
- savedProviderSessions,
1957
- sessionReads: mergedReads,
1958
- sessionReadMarkers: cleanedMarkers
1959
- };
1960
- writeFileSync(statePath, JSON.stringify(state, null, 2), { encoding: "utf-8", mode: 384 });
1961
- }
1962
- function loadConfig() {
1963
- const configPath = getConfigPath();
1964
- if (!existsSync3(configPath)) {
1965
- const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1966
- try {
1967
- saveConfig(initialized.config);
1968
- } catch {
1969
- }
1970
- return initialized.config;
1971
- }
1972
- try {
1973
- const raw = readFileSync2(configPath, "utf-8");
1974
- const parsed = JSON.parse(raw);
1975
- migrateStateToStateFile(parsed);
1976
- const normalizedInput = normalizeConfig(parsed);
1977
- const ensured = ensureMachineId(normalizedInput);
1978
- const normalized = ensured.config;
1979
- if (ensured.changed || JSON.stringify(parsed) !== JSON.stringify(normalized)) {
1980
- try {
1981
- saveConfig(normalized);
1982
- } catch {
1983
- }
1984
- }
1985
- return normalized;
1986
- } catch {
1987
- const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
1988
- return initialized.config;
1989
- }
1990
- }
1991
- function saveConfig(config) {
1992
- const configPath = getConfigPath();
1993
- const dir = getConfigDir();
1994
- const normalized = normalizeConfig(config);
1995
- if (!existsSync3(dir)) {
1996
- mkdirSync(dir, { recursive: true, mode: 448 });
1997
- }
1998
- writeFileSync(configPath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
1999
- try {
2000
- chmodSync(configPath, 384);
2001
- } catch {
2002
- }
2003
- }
2004
- function updateConfig(updates) {
2005
- const config = loadConfig();
2006
- const updated = { ...config, ...updates };
2007
- saveConfig(updated);
2008
- return updated;
2009
- }
2010
- function markSetupComplete(ideId, extensions) {
2011
- const ideIds = Array.isArray(ideId) ? ideId : [ideId];
2012
- return updateConfig({
2013
- selectedIde: ideIds[0],
2014
- configuredIdes: ideIds,
2015
- installedExtensions: extensions,
2016
- setupCompleted: true,
2017
- setupDate: (/* @__PURE__ */ new Date()).toISOString()
2018
- });
2019
- }
2020
- function isSetupComplete() {
2021
- const config = loadConfig();
2022
- return config.setupCompleted;
2023
- }
2024
- function resetConfig() {
2025
- saveConfig({ ...DEFAULT_CONFIG });
2026
- }
2027
- var DEFAULT_CONFIG, MACHINE_ID_PREFIX;
2028
- var init_config = __esm({
2029
- "src/config/config.ts"() {
2030
- "use strict";
2031
- DEFAULT_CONFIG = {
2032
- serverUrl: "https://api.adhf.dev",
2033
- allowServerApiProxy: false,
2034
- selectedIde: null,
2035
- configuredIdes: [],
2036
- installedExtensions: [],
2037
- userEmail: null,
2038
- userName: null,
2039
- setupCompleted: false,
2040
- setupDate: null,
2041
- enabledIdes: [],
2042
- workspaces: [],
2043
- defaultWorkspaceId: null,
2044
- machineNickname: null,
2045
- machineId: void 0,
2046
- machineSecret: null,
2047
- registeredMachineId: void 0,
2048
- providerSettings: {},
2049
- machineProviders: {},
2050
- ideSettings: {},
2051
- providerSourceMode: "normal",
2052
- updateChannel: "stable",
2053
- terminalSizingMode: "measured"
2054
- };
2055
- MACHINE_ID_PREFIX = "mach_";
2056
- }
2057
- });
2058
-
2059
2059
  // src/config/workspaces.ts
2060
2060
  import * as fs from "fs";
2061
2061
  import * as os from "os";
@@ -3198,12 +3198,23 @@ function addNode(meshId, opts) {
3198
3198
  if (mesh.nodes.some((n) => n.workspace === opts.workspace)) {
3199
3199
  throw new Error("This workspace is already in the mesh");
3200
3200
  }
3201
+ const machineNickname = (() => {
3202
+ const explicit = typeof opts.machineNickname === "string" ? opts.machineNickname.trim() : "";
3203
+ if (explicit) return explicit;
3204
+ try {
3205
+ const local = loadConfig().machineNickname;
3206
+ return typeof local === "string" && local.trim() ? local.trim() : void 0;
3207
+ } catch {
3208
+ return void 0;
3209
+ }
3210
+ })();
3201
3211
  const node = {
3202
3212
  id: `node_${randomUUID3().replace(/-/g, "")}`,
3203
3213
  workspace: opts.workspace.trim(),
3204
3214
  repoRoot: opts.repoRoot,
3205
3215
  daemonId: opts.daemonId,
3206
3216
  machineId: opts.machineId,
3217
+ ...machineNickname ? { machineNickname } : {},
3207
3218
  capabilities: normalizeCapabilityTags(opts.capabilities),
3208
3219
  userOverrides: opts.userOverrides || {},
3209
3220
  policy: opts.policy || {},
@@ -3238,6 +3249,7 @@ function updateNode(meshId, nodeId, opts) {
3238
3249
  if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
3239
3250
  if (opts.reportedPlatform && opts.reportedPlatform.trim()) node.reportedPlatform = opts.reportedPlatform.trim();
3240
3251
  if (opts.reportedArch && opts.reportedArch.trim()) node.reportedArch = opts.reportedArch.trim();
3252
+ if (opts.reportedMachineNickname && opts.reportedMachineNickname.trim()) node.machineNickname = opts.reportedMachineNickname.trim();
3241
3253
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
3242
3254
  if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
3243
3255
  if (Object.prototype.hasOwnProperty.call(opts, "systemPrompt")) {
@@ -24534,6 +24546,7 @@ init_git_diff();
24534
24546
  init_git_executor();
24535
24547
  import * as path3 from "path";
24536
24548
  init_git_status();
24549
+ init_config();
24537
24550
  var GIT_COMMAND_NAMES = /* @__PURE__ */ new Set([
24538
24551
  "git_status",
24539
24552
  "git_diff_summary",
@@ -24673,7 +24686,21 @@ async function handleGitCommand(command, args, services = defaultGitCommandServi
24673
24686
  if (submoduleIgnorePaths && submoduleIgnorePaths.length > 0) statusParams.submoduleIgnorePaths = submoduleIgnorePaths;
24674
24687
  const status = await runService(() => services.getStatus(statusParams));
24675
24688
  if ("success" in status) return status;
24676
- return { success: true, status, reporterPlatform: process.platform, reporterArch: process.arch };
24689
+ const reporterMachineNickname = (() => {
24690
+ try {
24691
+ const nick = loadConfig().machineNickname;
24692
+ return typeof nick === "string" && nick.trim() ? nick.trim() : void 0;
24693
+ } catch {
24694
+ return void 0;
24695
+ }
24696
+ })();
24697
+ return {
24698
+ success: true,
24699
+ status,
24700
+ reporterPlatform: process.platform,
24701
+ reporterArch: process.arch,
24702
+ ...reporterMachineNickname ? { reporterMachineNickname } : {}
24703
+ };
24677
24704
  }
24678
24705
  case "git_diff_summary": {
24679
24706
  if (!services.getDiffSummary) return serviceNotImplemented(command);
@@ -42202,19 +42229,41 @@ var CliProviderInstance = class _CliProviderInstance {
42202
42229
  if (shortFinalSummary) {
42203
42230
  this.pushEvent({ event: "agent:generating_started", chatTitle, timestamp: now - shortDurationMs });
42204
42231
  }
42232
+ const shortEngineTurnStart = typeof this.adapter?.currentTurnStartedAt === "number" && Number.isFinite(this.adapter.currentTurnStartedAt) ? this.adapter.currentTurnStartedAt : 0;
42233
+ const shortTurnStartedAt = shortEngineTurnStart || this.generatingStartedAt || 0;
42234
+ const shortTaskId = this.completingTurnTaskId();
42205
42235
  this.generatingDebouncePending = null;
42206
42236
  this.generatingStartedAt = 0;
42207
- const missingEvidence = (this.provider.requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === "external-native") && !shortFinalSummary;
42237
+ const missingEvidence = (this.provider.requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === "external-native" || shortEvidenceSource === "unavailable") && !shortFinalSummary;
42208
42238
  if (missingEvidence) {
42209
42239
  LOG.warn("CLI", `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
42210
42240
  }
42211
- const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
42212
- if (missingEvidence && !hasMeshContext) {
42213
- LOG.info("CLI", `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
42214
- } else {
42241
+ if (this.isAutonomousMeshSession()) {
42242
+ this.completedDebouncePending = {
42243
+ chatTitle,
42244
+ duration: Math.round(shortDurationMs / 1e3),
42245
+ timestamp: now,
42246
+ firstObservedAt: now,
42247
+ // Short-gen enters from generating→idle (or waiting_approval→idle); the
42248
+ // completedDebounce finalization gate treats previousStatus for its
42249
+ // approval-resolution / inter-approval-valley handling. lastStatus is the
42250
+ // status we transitioned FROM here.
42251
+ previousStatus: this.lastStatus,
42252
+ ...shortTaskId ? { taskId: shortTaskId } : {},
42253
+ ...shortTurnStartedAt ? { turnStartedAt: shortTurnStartedAt } : {},
42254
+ // FALSE-IDLE continuity: same arm-time snapshots as the normal branch so the
42255
+ // flush guard can prove continuous idle across the settle window.
42256
+ busyEpochAtArm: this.busyEpoch,
42257
+ ...typeof adapterStatus?.lastOutputAt === "number" && Number.isFinite(adapterStatus.lastOutputAt) ? { lastOutputAtArm: adapterStatus.lastOutputAt } : {}
42258
+ };
42259
+ LOG.info("CLI", `[${this.type}] short-generating routed through settle window (${shortDurationMs}ms, source=${shortEvidenceSource}, missingEvidence=${missingEvidence}) \u2014 arming completedDebouncePending instead of inline fire`);
42215
42260
  if (this.isMeshWorkerSession()) {
42216
- traceMeshEventStage("fired", this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
42261
+ traceMeshEventStage("arm", this.meshTraceCtx(), `short-generating settle-arm (source=${shortEvidenceSource}, missingEvidence=${missingEvidence})`);
42217
42262
  }
42263
+ this.scheduleCompletedDebounceFlush(NATIVE_HISTORY_MESH_IDLE_SETTLE_MS);
42264
+ } else if (missingEvidence) {
42265
+ LOG.info("CLI", `[${this.type}] short completion suppressed: missing final assistant evidence, non-mesh session (source=${shortEvidenceSource})`);
42266
+ } else {
42218
42267
  this.pushEvent({
42219
42268
  event: "agent:generating_completed",
42220
42269
  chatTitle,
@@ -42224,8 +42273,7 @@ var CliProviderInstance = class _CliProviderInstance {
42224
42273
  completionDiagnostic: {
42225
42274
  reason: "short_generating_suppressed",
42226
42275
  shortDurationMs,
42227
- finalAssistantEvidenceSource: shortEvidenceSource,
42228
- ...missingEvidence ? { blockReason: "missing_final_assistant" } : {}
42276
+ finalAssistantEvidenceSource: shortEvidenceSource
42229
42277
  }
42230
42278
  });
42231
42279
  }
@@ -46578,38 +46626,75 @@ function extractUserPrompt(payload) {
46578
46626
  if (!text) return "";
46579
46627
  return extractUserRequestContent(text);
46580
46628
  }
46629
+ function isSqliteBusyError(err) {
46630
+ if (!err) return false;
46631
+ const code = err.code;
46632
+ if (typeof code === "string" && code.includes("SQLITE_BUSY")) return true;
46633
+ const msg = err instanceof Error ? err.message : String(err);
46634
+ return /SQLITE_BUSY|database is locked|database table is locked/i.test(msg);
46635
+ }
46636
+ var AGY_DB_BUSY_TIMEOUT_MS = 3e3;
46637
+ var AGY_DB_MAX_ATTEMPTS = 4;
46638
+ var AGY_DB_RETRY_BACKOFF_MS = [50, 100, 150];
46639
+ function sleepBusy(ms) {
46640
+ const end = Date.now() + ms;
46641
+ while (Date.now() < end) {
46642
+ }
46643
+ }
46581
46644
  function parseConversationDb(filePath, sessionId, workspace) {
46582
- let db;
46645
+ let Database;
46583
46646
  try {
46584
- const Database = loadBetterSqlite3();
46585
- db = new Database(filePath, { readonly: true, fileMustExist: true });
46647
+ Database = loadBetterSqlite3();
46586
46648
  } catch (err) {
46587
46649
  LOG.warn(
46588
46650
  "NativeHistory",
46589
- `antigravity .db reader could not open ${path31.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (better-sqlite3 load/open failed \u2014 assistant answers in this .db will not surface)`
46651
+ `antigravity .db reader could not load better-sqlite3 for ${path31.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (native binding unavailable \u2014 assistant answers in this .db will not surface)`
46590
46652
  );
46591
46653
  return null;
46592
46654
  }
46593
- let rows;
46594
- try {
46595
- rows = db.prepare(
46596
- `SELECT idx, step_type, step_payload
46597
- FROM steps
46598
- WHERE step_type IN (${AGY_STEP_TYPE_USER}, ${AGY_STEP_TYPE_MODEL})
46599
- ORDER BY idx ASC`
46600
- ).all();
46601
- } catch (err) {
46602
- LOG.debug(
46603
- "NativeHistory",
46604
- `antigravity .db ${path31.basename(filePath)} has no readable steps table: ${err instanceof Error ? err.message : String(err)}`
46605
- );
46606
- return null;
46607
- } finally {
46655
+ let rows = null;
46656
+ let lastBusyErr;
46657
+ for (let attempt = 1; attempt <= AGY_DB_MAX_ATTEMPTS; attempt++) {
46658
+ let db;
46608
46659
  try {
46609
- db.close();
46610
- } catch {
46660
+ db = new Database(filePath, { readonly: true, fileMustExist: true });
46661
+ try {
46662
+ db.pragma(`busy_timeout = ${AGY_DB_BUSY_TIMEOUT_MS}`);
46663
+ } catch {
46664
+ }
46665
+ rows = db.prepare(
46666
+ `SELECT idx, step_type, step_payload
46667
+ FROM steps
46668
+ WHERE step_type IN (${AGY_STEP_TYPE_USER}, ${AGY_STEP_TYPE_MODEL})
46669
+ ORDER BY idx ASC`
46670
+ ).all();
46671
+ break;
46672
+ } catch (err) {
46673
+ if (isSqliteBusyError(err)) {
46674
+ lastBusyErr = err;
46675
+ if (attempt < AGY_DB_MAX_ATTEMPTS) {
46676
+ sleepBusy(AGY_DB_RETRY_BACKOFF_MS[attempt - 1] ?? 150);
46677
+ continue;
46678
+ }
46679
+ LOG.warn(
46680
+ "NativeHistory",
46681
+ `antigravity .db ${path31.basename(filePath)} stayed locked (SQLITE_BUSY) after ${AGY_DB_MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)} (WAL write/checkpoint lock contention \u2014 assistant answers may transiently not surface this read)`
46682
+ );
46683
+ return null;
46684
+ }
46685
+ LOG.debug(
46686
+ "NativeHistory",
46687
+ `antigravity .db ${path31.basename(filePath)} not readable: ${err instanceof Error ? err.message : String(err)}`
46688
+ );
46689
+ return null;
46690
+ } finally {
46691
+ try {
46692
+ db?.close();
46693
+ } catch {
46694
+ }
46611
46695
  }
46612
46696
  }
46697
+ void lastBusyErr;
46613
46698
  if (!Array.isArray(rows) || rows.length === 0) return null;
46614
46699
  const normalizedWorkspace = typeof workspace === "string" ? workspace.trim() : "";
46615
46700
  const baseTs = statMtimeMs3(filePath) || Date.now();
@@ -51962,6 +52047,10 @@ var meshStatusHandlers = {
51962
52047
  const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions ? await ctx.deps.sessionHostControl.listSessions().catch(() => []) : [];
51963
52048
  const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
51964
52049
  const localMachineId = loadConfig().machineId || "";
52050
+ const localMachineNickname = (() => {
52051
+ const nick = loadConfig().machineNickname;
52052
+ return typeof nick === "string" && nick.trim() ? nick.trim() : "";
52053
+ })();
51965
52054
  const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
51966
52055
  const meshGitProbeCache = ctx.meshGitProbeCache;
51967
52056
  const directTruth = requireDirectPeerTruth ? await hydrateInlineMeshDirectTruth({
@@ -52042,6 +52131,9 @@ var meshStatusHandlers = {
52042
52131
  ) || Boolean(
52043
52132
  daemonId && (daemonIdsEquivalent(daemonId, localMachineId) || daemonIdsEquivalent(daemonId, ctx.deps.statusInstanceId))
52044
52133
  ) || Boolean(meshRecord?.inline && nodeIndex === 0) || sparseConfiguredCoordinatorNode;
52134
+ if (isSelfNode && localMachineNickname && !readStringValue(node.machineNickname, node.machine_nickname)) {
52135
+ node.machineNickname = localMachineNickname;
52136
+ }
52045
52137
  const machineIdentity = buildMeshNodeMachineIdentity(node, {
52046
52138
  localMachineId,
52047
52139
  localDaemonId: ctx.deps.statusInstanceId,
@@ -52930,7 +53022,7 @@ function buildLivePeerGitConnection(connection, timestamp = (/* @__PURE__ */ new
52930
53022
  }
52931
53023
  function recordInlineMeshDirectGitTruth(node, git, source) {
52932
53024
  if (!node || typeof node !== "object" || Array.isArray(node)) {
52933
- return { reporterPlatform: null, reporterArch: null };
53025
+ return { reporterPlatform: null, reporterArch: null, reporterMachineNickname: null };
52934
53026
  }
52935
53027
  const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
52936
53028
  const updatedAt = new Date(checkedAt).toISOString();
@@ -52955,7 +53047,9 @@ function recordInlineMeshDirectGitTruth(node, git, source) {
52955
53047
  stampNodeReporterPlatform(node, reporterPlatform, reporterArch);
52956
53048
  if (reporterPlatform) node.reportedPlatform = reporterPlatform;
52957
53049
  if (reporterArch) node.reportedArch = reporterArch;
52958
- return { reporterPlatform, reporterArch };
53050
+ const reporterMachineNickname = readStringValue(git.reporterMachineNickname) ?? null;
53051
+ if (reporterMachineNickname) node.machineNickname = reporterMachineNickname;
53052
+ return { reporterPlatform, reporterArch, reporterMachineNickname };
52959
53053
  }
52960
53054
  function stampNodeReporterPlatform(node, platform10, arch2) {
52961
53055
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
@@ -52978,8 +53072,9 @@ function persistNodeReporterPlatform(meshSource, mesh, nodeId, reporter) {
52978
53072
  if (!meshId || !nodeId) return;
52979
53073
  const reportedPlatform = reporter.reporterPlatform ?? void 0;
52980
53074
  const reportedArch = reporter.reporterArch ?? void 0;
52981
- if (!reportedPlatform && !reportedArch) return;
52982
- void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch })).catch(() => {
53075
+ const reportedMachineNickname = reporter.reporterMachineNickname ?? void 0;
53076
+ if (!reportedPlatform && !reportedArch && !reportedMachineNickname) return;
53077
+ void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch, reportedMachineNickname })).catch(() => {
52983
53078
  });
52984
53079
  }
52985
53080
  function buildCachedInlineMeshGitStatus(node) {
@@ -53631,9 +53726,11 @@ async function probeRemoteMeshGitStatus(args) {
53631
53726
  if (!remoteGit || typeof remoteGit !== "object" || typeof remoteGit.isGitRepo !== "boolean") return null;
53632
53727
  const reporterPlatform = readStringValue(remoteResult?.reporterPlatform);
53633
53728
  const reporterArch = readStringValue(remoteResult?.reporterArch);
53729
+ const reporterMachineNickname = readStringValue(remoteResult?.reporterMachineNickname);
53634
53730
  const git = remoteGit;
53635
53731
  if (reporterPlatform) git.reporterPlatform = reporterPlatform;
53636
53732
  if (reporterArch) git.reporterArch = reporterArch;
53733
+ if (reporterMachineNickname) git.reporterMachineNickname = reporterMachineNickname;
53637
53734
  return git;
53638
53735
  }
53639
53736
  var MESH_DIRECT_PROBE_MAX_RETRIES = 2;