@adhdev/daemon-core 0.9.82-rc.31 → 0.9.82-rc.311

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +23 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
  13. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  14. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  15. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  16. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  17. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  18. package/dist/commands/cli-manager.d.ts +2 -1
  19. package/dist/commands/handler.d.ts +110 -0
  20. package/dist/commands/mesh-coordinator.d.ts +85 -1
  21. package/dist/commands/router.d.ts +214 -1
  22. package/dist/config/chat-history.d.ts +9 -0
  23. package/dist/config/config.d.ts +5 -0
  24. package/dist/config/mesh-config.d.ts +72 -1
  25. package/dist/git/git-commands.d.ts +9 -1
  26. package/dist/git/git-diff.d.ts +6 -0
  27. package/dist/git/git-executor.d.ts +11 -0
  28. package/dist/git/git-status.d.ts +9 -0
  29. package/dist/git/git-types.d.ts +2 -50
  30. package/dist/index.d.ts +51 -12
  31. package/dist/index.js +34705 -11938
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +38412 -15757
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/installer.d.ts +1 -4
  36. package/dist/ipc/local-ipc-server.d.ts +91 -0
  37. package/dist/launch.d.ts +1 -1
  38. package/dist/logging/async-batch-writer.d.ts +10 -0
  39. package/dist/mesh/contracts.d.ts +164 -0
  40. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  41. package/dist/mesh/coordinator-registry.d.ts +59 -0
  42. package/dist/mesh/mesh-active-work.d.ts +108 -0
  43. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  44. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  45. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  46. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  47. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  48. package/dist/mesh/mesh-events.d.ts +6 -49
  49. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  50. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  51. package/dist/mesh/mesh-init.d.ts +86 -0
  52. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  53. package/dist/mesh/mesh-ledger.d.ts +77 -1
  54. package/dist/mesh/mesh-missions.d.ts +116 -0
  55. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  56. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  57. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  58. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  59. package/dist/mesh/mesh-routing.d.ts +70 -0
  60. package/dist/mesh/mesh-runtime-store.d.ts +395 -0
  61. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  62. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  63. package/dist/mesh/mesh-work-queue.d.ts +204 -5
  64. package/dist/mesh/preview-freshness.d.ts +18 -0
  65. package/dist/mesh/refine-config.d.ts +215 -0
  66. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  67. package/dist/providers/acp-provider-instance.d.ts +2 -0
  68. package/dist/providers/approval-utils.d.ts +13 -0
  69. package/dist/providers/cli-provider-instance.d.ts +61 -3
  70. package/dist/providers/contracts.d.ts +130 -6
  71. package/dist/providers/external-sources.d.ts +71 -0
  72. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  73. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  74. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  75. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  76. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  77. package/dist/providers/native-history/index.d.ts +13 -0
  78. package/dist/providers/provider-instance-manager.d.ts +13 -0
  79. package/dist/providers/provider-instance.d.ts +13 -1
  80. package/dist/providers/provider-loader.d.ts +26 -4
  81. package/dist/providers/provider-trust.d.ts +31 -0
  82. package/dist/providers/read-chat-contract.d.ts +29 -0
  83. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  84. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  85. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  86. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  87. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  88. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  89. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  90. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  91. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  92. package/dist/providers/sdk/v1/index.d.ts +30 -0
  93. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  94. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  95. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  96. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  97. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  98. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  99. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  100. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  101. package/dist/providers/spec/adapter.d.ts +59 -0
  102. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  103. package/dist/providers/spec/evaluator.d.ts +23 -0
  104. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  105. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  106. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  107. package/dist/providers/spec/fsm-types.d.ts +128 -0
  108. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  109. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  110. package/dist/providers/spec/route.d.ts +4 -0
  111. package/dist/providers/spec/types.d.ts +180 -0
  112. package/dist/providers/transcript-v2.d.ts +176 -0
  113. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  114. package/dist/repo-mesh-types.d.ts +291 -13
  115. package/dist/sessions/registry.d.ts +6 -0
  116. package/dist/shared-types-extra.d.ts +2 -4
  117. package/dist/shared-types.d.ts +42 -1
  118. package/dist/status/normalize.d.ts +1 -1
  119. package/dist/status/normalize.js +1 -0
  120. package/dist/status/normalize.js.map +1 -1
  121. package/dist/status/normalize.mjs +1 -0
  122. package/dist/status/normalize.mjs.map +1 -1
  123. package/dist/status/reporter.d.ts +2 -0
  124. package/dist/status/snapshot.d.ts +1 -0
  125. package/dist/types.d.ts +5 -0
  126. package/package.json +7 -3
  127. package/src/agent-stream/poller.ts +2 -3
  128. package/src/boot/daemon-lifecycle.ts +55 -12
  129. package/src/boot/process-hardening.ts +89 -0
  130. package/src/build-info.ts +73 -0
  131. package/src/chat/source-machine.ts +534 -0
  132. package/src/chat/source-resolver.ts +0 -0
  133. package/src/chat/subscription-updates.ts +20 -1
  134. package/src/cli-adapter-types.d.ts +1 -0
  135. package/src/cli-adapter-types.ts +22 -2
  136. package/src/cli-adapters/cli-script-runner.ts +421 -0
  137. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  138. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  139. package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
  140. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  141. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  142. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  143. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  144. package/src/cli-adapters/provider-cli-shared.ts +68 -11
  145. package/src/cli-adapters/pty-transport.ts +2 -1
  146. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  147. package/src/cli-adapters/resolve-executable.ts +45 -0
  148. package/src/cli-adapters/session-host-transport.ts +2 -1
  149. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  150. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  151. package/src/cli-adapters/terminal-screen.ts +16 -81
  152. package/src/commands/chat-commands.ts +1822 -61
  153. package/src/commands/cli-manager.ts +286 -14
  154. package/src/commands/handler.ts +809 -2
  155. package/src/commands/mesh-coordinator.ts +332 -122
  156. package/src/commands/router.ts +6041 -589
  157. package/src/commands/stream-commands.ts +8 -0
  158. package/src/commands/upgrade-helper.ts +29 -0
  159. package/src/config/chat-history.ts +483 -24
  160. package/src/config/config.ts +12 -0
  161. package/src/config/mesh-config.ts +320 -4
  162. package/src/config/recent-activity.ts +8 -2
  163. package/src/daemon/dev-auto-implement.ts +3 -2
  164. package/src/daemon/dev-cli-debug.ts +10 -1
  165. package/src/detection/ide-detector.ts +26 -16
  166. package/src/git/git-commands.ts +42 -12
  167. package/src/git/git-diff.ts +53 -0
  168. package/src/git/git-executor.ts +12 -0
  169. package/src/git/git-status.ts +302 -18
  170. package/src/git/git-types.ts +14 -62
  171. package/src/git/git-worktree.ts +8 -1
  172. package/src/index.ts +142 -11
  173. package/src/installer.d.ts +1 -1
  174. package/src/installer.ts +8 -6
  175. package/src/ipc/local-ipc-server.ts +278 -0
  176. package/src/launch.d.ts +1 -1
  177. package/src/launch.ts +37 -28
  178. package/src/logging/async-batch-writer.ts +55 -0
  179. package/src/logging/logger.ts +2 -1
  180. package/src/mesh/contracts.ts +329 -0
  181. package/src/mesh/coordinator-prompt.ts +234 -31
  182. package/src/mesh/coordinator-registry.ts +121 -0
  183. package/src/mesh/mesh-active-work.ts +469 -0
  184. package/src/mesh/mesh-delivery-policy.ts +315 -0
  185. package/src/mesh/mesh-events-coordinator.ts +1942 -0
  186. package/src/mesh/mesh-events-pending.ts +508 -0
  187. package/src/mesh/mesh-events-stale.ts +290 -0
  188. package/src/mesh/mesh-events-utils.ts +254 -0
  189. package/src/mesh/mesh-events.ts +30 -1035
  190. package/src/mesh/mesh-fast-forward.ts +839 -0
  191. package/src/mesh/mesh-host-ownership.ts +73 -0
  192. package/src/mesh/mesh-init.ts +260 -0
  193. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  194. package/src/mesh/mesh-ledger.ts +589 -102
  195. package/src/mesh/mesh-missions.ts +248 -0
  196. package/src/mesh/mesh-reconcile-loop.ts +466 -0
  197. package/src/mesh/mesh-refine-batch.ts +197 -0
  198. package/src/mesh/mesh-refine-status.ts +231 -0
  199. package/src/mesh/mesh-review-inbox.ts +307 -0
  200. package/src/mesh/mesh-routing.ts +291 -0
  201. package/src/mesh/mesh-runtime-store.ts +1565 -0
  202. package/src/mesh/mesh-task-stats.ts +154 -0
  203. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  204. package/src/mesh/mesh-work-queue.ts +703 -140
  205. package/src/mesh/preview-freshness.ts +118 -0
  206. package/src/mesh/refine-config.ts +403 -0
  207. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  208. package/src/providers/acp-provider-instance.ts +15 -1
  209. package/src/providers/approval-utils.d.ts +4 -0
  210. package/src/providers/approval-utils.ts +47 -5
  211. package/src/providers/chat-message-normalization.ts +4 -11
  212. package/src/providers/cli-provider-instance.ts +953 -87
  213. package/src/providers/contracts.d.ts +55 -0
  214. package/src/providers/contracts.ts +141 -6
  215. package/src/providers/extension-provider-instance.ts +5 -1
  216. package/src/providers/external-sources.ts +218 -0
  217. package/src/providers/ide-provider-instance.ts +25 -6
  218. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  219. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  220. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  221. package/src/providers/native-history/dispatcher.ts +340 -0
  222. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  223. package/src/providers/native-history/index.ts +30 -0
  224. package/src/providers/provider-instance-manager.ts +30 -0
  225. package/src/providers/provider-instance.ts +10 -1
  226. package/src/providers/provider-loader.ts +584 -50
  227. package/src/providers/provider-schema.ts +87 -14
  228. package/src/providers/provider-trust.ts +114 -0
  229. package/src/providers/read-chat-contract.ts +76 -16
  230. package/src/providers/sdk/README.md +49 -0
  231. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  232. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  233. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  234. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  235. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  236. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  237. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  238. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  239. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  240. package/src/providers/sdk/v1/index.ts +152 -0
  241. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  242. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  243. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  244. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  245. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  246. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  247. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  248. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  249. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  250. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  251. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  252. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  253. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  254. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  255. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  256. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  257. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  258. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  259. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  260. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  261. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  262. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  263. package/src/providers/sdk/v1/validators/index.ts +19 -0
  264. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  265. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  266. package/src/providers/spec/adapter.ts +155 -0
  267. package/src/providers/spec/cli-adapter.ts +980 -0
  268. package/src/providers/spec/evaluator.ts +345 -0
  269. package/src/providers/spec/fsm-driver.ts +888 -0
  270. package/src/providers/spec/fsm-evaluator.ts +255 -0
  271. package/src/providers/spec/fsm-loader.ts +112 -0
  272. package/src/providers/spec/fsm-types.ts +222 -0
  273. package/src/providers/spec/native-history-executor.ts +1035 -0
  274. package/src/providers/spec/pre-launch-trust.ts +104 -0
  275. package/src/providers/spec/route.ts +51 -0
  276. package/src/providers/spec/types.ts +226 -0
  277. package/src/providers/transcript-v2.ts +567 -0
  278. package/src/providers/types/interactive-prompt.ts +536 -0
  279. package/src/providers/version-archive.ts +38 -20
  280. package/src/repo-mesh-types.ts +376 -13
  281. package/src/sessions/registry.ts +6 -0
  282. package/src/shared-types-extra.ts +2 -4
  283. package/src/shared-types.ts +45 -1
  284. package/src/status/builders.ts +26 -6
  285. package/src/status/normalize.ts +2 -0
  286. package/src/status/reporter.ts +15 -0
  287. package/src/status/snapshot.ts +84 -25
  288. package/src/system/host-memory.ts +29 -12
  289. package/src/types.ts +5 -0
  290. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  291. package/dist/mesh/mesh-sync.d.ts +0 -53
  292. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  293. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  294. package/src/mesh/mesh-sync.ts +0 -111
@@ -6,69 +6,21 @@
6
6
  * infer these values from agent transcripts in frontend code.
7
7
  */
8
8
 
9
- export type GitFailureReason =
10
- | 'not_git_repo'
11
- | 'git_not_installed'
12
- | 'timeout'
13
- | 'path_outside_repo'
14
- | 'dirty_index_required'
15
- | 'conflict'
16
- | 'invalid_args'
17
- | 'nothing_to_commit'
18
- | 'git_command_failed';
9
+ // Pure shape types now live in @adhdev/mesh-shared so the cloud (web-core) and
10
+ // standalone (daemon-core) transports share ONE definition instead of hand-syncing
11
+ // two. Re-exported here so existing `from './git-types'` / package imports keep
12
+ // working unchanged. Daemon-specific types (GitSnapshot, GitCommandName, …) stay
13
+ // local below and consume these re-exports.
14
+ export type {
15
+ GitFailureReason,
16
+ GitRepoIdentity,
17
+ GitSubmoduleStatus,
18
+ GitUpstreamFreshness,
19
+ GitRepoStatus,
20
+ DaemonBuildBehind,
21
+ } from '@adhdev/mesh-shared';
19
22
 
20
- export interface GitRepoIdentity {
21
- workspace: string;
22
- repoRoot: string | null;
23
- isGitRepo: boolean;
24
- }
25
-
26
- export interface GitSubmoduleStatus {
27
- /** Submodule path relative to repo root */
28
- path: string;
29
- /** Current commit SHA the submodule is at */
30
- commit: string;
31
- /** Path to the submodule repo (absolute) */
32
- repoPath: string;
33
- /** Whether the submodule has uncommitted changes */
34
- dirty: boolean;
35
- /** Whether the submodule commit differs from what the parent repo expects */
36
- outOfSync: boolean;
37
- /** Last checked timestamp */
38
- lastCheckedAt: number;
39
- /** Error message if submodule status could not be read */
40
- error?: string;
41
- }
42
-
43
- export type GitUpstreamFreshness = 'fresh' | 'unchecked' | 'stale' | 'no_upstream' | 'unavailable';
44
-
45
- export interface GitRepoStatus extends GitRepoIdentity {
46
- branch: string | null;
47
- headCommit: string | null;
48
- headMessage: string | null;
49
- upstream: string | null;
50
- /** Whether ahead/behind was verified against a freshly fetched upstream ref. */
51
- upstreamStatus: GitUpstreamFreshness;
52
- /** Timestamp for the fetch that refreshed upstream refs when upstreamStatus === 'fresh'. */
53
- upstreamFetchedAt?: number;
54
- /** Error from the last refresh attempt when upstreamStatus === 'stale'. */
55
- upstreamFetchError?: string;
56
- ahead: number;
57
- behind: number;
58
- staged: number;
59
- modified: number;
60
- untracked: number;
61
- deleted: number;
62
- renamed: number;
63
- hasConflicts: boolean;
64
- conflictFiles: string[];
65
- stashCount: number;
66
- lastCheckedAt: number;
67
- /** Submodule statuses when auto-discover is enabled */
68
- submodules?: GitSubmoduleStatus[];
69
- error?: string;
70
- reason?: GitFailureReason;
71
- }
23
+ import type { GitRepoIdentity, GitRepoStatus, GitFailureReason, GitUpstreamFreshness } from '@adhdev/mesh-shared';
72
24
 
73
25
  export type GitFileChangeStatus =
74
26
  | 'added'
@@ -116,8 +116,11 @@ export async function createWorktree(opts: WorktreeCreateOptions): Promise<Workt
116
116
  });
117
117
  } catch (error: any) {
118
118
  const stderr = typeof error.stderr === 'string' ? error.stderr : '';
119
- // Clean error messages for common failures
120
119
  if (/already exists/i.test(stderr)) {
120
+ // Distinguish directory-collision (TOCTOU race) from branch-already-exists
121
+ if (existsSync(targetDir)) {
122
+ throw new Error(`Worktree target directory was created concurrently: ${targetDir}`);
123
+ }
121
124
  throw new Error(`Branch '${branch}' already exists or is checked out in another worktree`);
122
125
  }
123
126
  throw new Error(`git worktree add failed: ${stderr.trim() || error.message}`);
@@ -170,6 +173,10 @@ export async function removeWorktree(repoRoot: string, worktreePath: string, opt
170
173
  const stdout = typeof error.stdout === 'string' ? error.stdout : '';
171
174
  const detail = `${stderr}\n${stdout}\n${error.message || ''}`;
172
175
  if (opts.allowSubmoduleForceFallback && SUBMODULE_WORKTREE_REMOVE_RE.test(detail)) {
176
+ process.stderr.write(
177
+ `[adhdev-mesh] WARNING: git worktree remove --force fallback for submodule worktree '${worktreePath}'. `
178
+ + `Any uncommitted changes inside submodules will be lost.\n`,
179
+ );
173
180
  try {
174
181
  await execFileAsync('git', ['worktree', 'remove', '--force', worktreePath], {
175
182
  cwd: repoRoot,
package/src/index.ts CHANGED
@@ -85,9 +85,28 @@ export type {
85
85
  InputMediaType,
86
86
  } from './shared-types.js';
87
87
 
88
+ export type {
89
+ InteractivePrompt,
90
+ InteractiveQuestion,
91
+ InteractiveOption,
92
+ InteractivePromptResponse,
93
+ InteractiveAnswer,
94
+ } from './providers/types/interactive-prompt.js';
95
+ export {
96
+ normalizeInteractivePrompt,
97
+ normalizeInteractivePromptResponse,
98
+ buildClaudeInteractiveToolResult,
99
+ interactivePromptFromClaudeAskUserQuestion,
100
+ detectClaudeAskUserQuestionPromptFromJson,
101
+ } from './providers/types/interactive-prompt.js';
102
+
88
103
  // ── Repo Mesh Types (cross-package) ──
89
104
  export type {
90
105
  RepoMesh,
106
+ RepoMeshDaemonRole,
107
+ RepoMeshHostMetadata,
108
+ RepoMeshHostPairingMetadata,
109
+ RepoMeshHostStatus,
91
110
  RepoMeshNode,
92
111
  RepoMeshNodeHealth,
93
112
  RepoMeshPolicy,
@@ -111,8 +130,20 @@ export type {
111
130
  RepoMeshLedgerEntryStatus,
112
131
  RepoMeshLedgerSummaryStatus,
113
132
  RepoMeshLedgerStatus,
133
+ MeshAsyncJobLifecycle,
134
+ RepoMeshSchedulingStrategy,
135
+ } from './repo-mesh-types.js';
136
+ export {
137
+ DEFAULT_MESH_POLICY,
138
+ resolveDelegatedWorkerAutoApprove,
139
+ MESH_SCHEDULING_STRATEGIES,
140
+ DEFAULT_MESH_SCHEDULING_STRATEGY,
141
+ normalizeMeshSchedulingStrategy,
142
+ resolveNodeSchedulingPriority,
143
+ MESH_CONVERGE_REFINE_TAG,
144
+ MESH_CONVERGE_FAST_FORWARD_TAG,
145
+ resolveAutoConvergeCodeChange,
114
146
  } from './repo-mesh-types.js';
115
- export { DEFAULT_MESH_POLICY } from './repo-mesh-types.js';
116
147
 
117
148
  // ── Git Surface ──
118
149
  export * from './git/index.js';
@@ -138,7 +169,7 @@ export type RecentSessionBucket = 'needs_attention' | 'working' | 'task_complete
138
169
  export type { IDaemonCore, DaemonCoreOptions } from './daemon-core.js';
139
170
 
140
171
  // ── Config ──
141
- export { loadConfig, saveConfig, resetConfig, isSetupComplete, markSetupComplete, updateConfig } from './config/config.js';
172
+ export { loadConfig, saveConfig, resetConfig, isSetupComplete, markSetupComplete, updateConfig, getDaemonDataDir } from './config/config.js';
142
173
  export { getWorkspaceState } from './config/workspaces.js';
143
174
  export { appendRecentActivity, getRecentActivity } from './config/recent-activity.js';
144
175
  export type { RecentActivityEntry } from './config/recent-activity.js';
@@ -154,19 +185,59 @@ export type { CreateMeshOptions, UpdateMeshOptions, AddNodeOptions } from './con
154
185
 
155
186
  // ── Mesh Coordinator ──
156
187
  export { buildCoordinatorSystemPrompt } from './mesh/coordinator-prompt.js';
188
+ export { upsertMeshMission, getMeshMissions, getMeshMission, summarizeMissionTasks, summarizeMeshMission, getActiveMeshMissionSummaries, getMeshStatusMissionSummaries, listMeshMissionSummaries, buildMissionPromptSection, GOAL_PREVIEW_MAX, MESH_MISSION_STATUSES } from './mesh/mesh-missions.js';
189
+ export type { MeshMissionRecord, MeshMissionStatus, MeshMissionSummary, MeshMissionSlimSummary, MeshMissionTaskAggregate } from './mesh/mesh-missions.js';
190
+ export { computeMeshTaskStats, computeMeshMissionStats } from './mesh/mesh-task-stats.js';
191
+ export type { MeshTaskStats, MeshMissionStats } from './mesh/mesh-task-stats.js';
192
+ export { deriveMeshReviewInboxItems } from './mesh/mesh-review-inbox.js';
193
+ export type { MeshReviewInboxItem, MeshReviewInboxDerivation, MeshReviewInboxEvidence, MeshReviewInboxDiffSummary, MeshReviewInboxDiffFile, MeshReviewInboxReason, MeshReviewInboxConvergence } from './mesh/mesh-review-inbox.js';
157
194
  export type { CoordinatorPromptContext } from './mesh/coordinator-prompt.js';
158
- export { syncMeshes } from './mesh/mesh-sync.js';
159
- export type { MeshSyncTransport, MeshSyncResult, RemoteMeshRecord } from './mesh/mesh-sync.js';
195
+ export { loadMeshCoordinatorRegistry, registerMeshCoordinator, unregisterMeshCoordinator, getCoordinatorForSession, listCoordinatorsForWorkspace } from './mesh/coordinator-registry.js';
196
+ export type { CoordinatorRegistryEntry } from './mesh/coordinator-registry.js';
197
+ export {
198
+ MESH_REFINE_CONFIG_LOCATIONS,
199
+ MESH_REFINE_CONFIG_SCHEMA,
200
+ loadMeshRefineConfig,
201
+ resolveMeshRefineValidationPlan,
202
+ suggestMeshRefineConfig,
203
+ validateMeshRefineConfig,
204
+ } from './mesh/refine-config.js';
205
+ export {
206
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS,
207
+ MESH_WORKTREE_BOOTSTRAP_CONFIG_SCHEMA,
208
+ loadMeshWorktreeBootstrapConfig,
209
+ runMeshWorktreeBootstrap,
210
+ validateMeshWorktreeBootstrapConfig,
211
+ type RepoMeshWorktreeBootstrapConfig,
212
+ type WorktreeBootstrapState,
213
+ } from './mesh/worktree-bootstrap-config.js';
214
+ export type {
215
+ MeshRefineValidationCategory,
216
+ MeshRefineValidationCommandPlan,
217
+ MeshRefineValidationPlan,
218
+ RepoMeshRefineConfig,
219
+ RepoMeshRefineValidationCommandConfig,
220
+ } from './mesh/refine-config.js';
160
221
 
161
222
  // ── Mesh Task Ledger ──
162
- export { appendLedgerEntry, appendRemoteLedgerEntries, readLedgerEntries, readLedgerSlice, getLedgerSummary, getLedgerDir, getSessionRecoveryContext, MAX_LEDGER_SLICE_LIMIT } from './mesh/mesh-ledger.js';
163
- export type { AppendRemoteLedgerResult, MeshLedgerEntry, MeshLedgerKind, MeshLedgerSlice, MeshLedgerSummary, ReadLedgerOptions, ReadLedgerSliceOptions, SessionRecoveryContext } from './mesh/mesh-ledger.js';
223
+ export { appendLedgerEntry, appendRemoteLedgerEntries, buildTaskCompletionEvidence, normalizeMeshWorkerResult, readLedgerEntries, readLedgerSlice, readLedgerSliceFromStore, getLedgerSummary, getLedgerDir, getSessionRecoveryContext, MAX_LEDGER_SLICE_LIMIT } from './mesh/mesh-ledger.js';
224
+ export type { AppendRemoteLedgerResult, MeshLedgerEntry, MeshLedgerKind, MeshLedgerSlice, MeshLedgerSummary, ReadLedgerOptions, ReadLedgerSliceOptions, SessionRecoveryContext, MeshTaskCompletionEvidence, MeshWorkerResultArtifact, MeshProcessArtifact, MeshValidationResultArtifact } from './mesh/mesh-ledger.js';
225
+ export { fastForwardMeshNode } from './mesh/mesh-fast-forward.js';
226
+ export type { MeshFastForwardNodeArgs, MeshFastForwardPlannedStep, MeshFastForwardResult } from './mesh/mesh-fast-forward.js';
164
227
  export { buildMeshLedgerReconciliationEvidence, buildMeshLedgerReplicaEvidence } from './mesh/mesh-ledger-reconciliation.js';
165
- export type { MeshLedgerReconciliationEvidence, MeshLedgerReplicaEvidence, MeshLedgerReplicaStatus } from './mesh/mesh-ledger-reconciliation.js';
228
+ export type { AnyLedgerSlice, MeshLedgerReconciliationEvidence, MeshLedgerReplicaEvidence, MeshLedgerReplicaStatus } from './mesh/mesh-ledger-reconciliation.js';
166
229
 
167
230
  // ── Mesh Work Queue (GUPP) ──
168
- export { enqueueTask, getQueue, claimNextTask, updateTaskStatus, updateSessionTaskStatus, cancelTask, requeueTask, getMeshQueueStats } from './mesh/mesh-work-queue.js';
169
- export type { MeshWorkQueueEntry, MeshTaskStatus, MeshWorkQueueStats } from './mesh/mesh-work-queue.js';
231
+ export { enqueueTask, recordDirectDispatchTask, getQueue, claimNextTask, updateTaskStatus, updateSessionTaskStatus, cancelTask, requeueTask, getMeshQueueStats, getMeshQueueRevision, normalizeMeshTaskMode, validateMeshTaskModeRequest, buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, normalizeMeshCapabilityTags, resolveConvergeRequiredTags, insertDirectDispatch, getActiveDirectDispatches, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, markStaleDirectDispatches, deleteDirectDispatchesByTaskId, recordMeshToolCall, assertNoDependencyCycle, hasPendingDependents, describeTaskDependencyState } from './mesh/mesh-work-queue.js';
232
+ export type { MeshWorkQueueEntry, MeshTaskStatus, MeshTaskMode, MeshWorkQueueStats, MeshQueueMutationOptions, MeshTaskModeValidationResult, DirectDispatchRecord, MeshToolCallRateResult } from './mesh/mesh-work-queue.js';
233
+ export { buildCompactStaleDirectWorkSummary, buildMeshActiveWork, buildMeshActiveWorkSummary, classifyStaleDirectForPrune, PRUNABLE_ORPHAN_STALE_REASONS } from './mesh/mesh-active-work.js';
234
+ export type { StaleDirectPruneClassification } from './mesh/mesh-active-work.js';
235
+ export type { MeshActiveWorkRecord, MeshActiveWorkStatus, MeshActiveWorkSummary, MeshActiveWorkSource, MeshStaleDirectWorkSummary } from './mesh/mesh-active-work.js';
236
+ export { buildMeshAsyncRefineJobs, summarizeMeshAsyncRefineJobs, STALE_TERMINAL_REFINE_WINDOW_MS, RECENT_TERMINAL_REFINE_CAP } from './mesh/mesh-refine-status.js';
237
+ export type { MeshAsyncRefineJobStatus, MeshAsyncRefineJobSummary, MeshAsyncRefineJobsSummary } from './mesh/mesh-refine-status.js';
238
+
239
+ // ── Mesh Host Ownership ──
240
+ export { buildMeshHostRequiredFailure, createDefaultMeshHostMetadata, isMeshHostOwner, normalizeMeshDaemonRole, requireMeshHostQueueOwner, resolveMeshHostStatus } from './mesh/mesh-host-ownership.js';
170
241
 
171
242
  // ── Mesh Visualization ──
172
243
  // buildMeshGraph and MeshGraph types moved to @adhdev/web-core to avoid
@@ -176,9 +247,13 @@ export type { MeshWorkQueueEntry, MeshTaskStatus, MeshWorkQueueStats } from './m
176
247
  // export type { MeshGraph, MeshGraphNode, MeshGraphEdge, MeshGraphNodeType, MeshGraphEdgeType } from './mesh/mesh-visualization.js';
177
248
 
178
249
  // ── Mesh Events ──
179
- export { triggerMeshQueue, drainPendingMeshCoordinatorEvents, getPendingMeshCoordinatorEvents, clearPendingMeshCoordinatorEvents, queuePendingMeshCoordinatorEvent } from './mesh/mesh-events.js';
250
+ export { triggerMeshQueue, drainPendingMeshCoordinatorEvents, getPendingMeshCoordinatorEvents, clearPendingMeshCoordinatorEvents, queuePendingMeshCoordinatorEvent, reconcileDirectDispatchCompletionFromTranscript } from './mesh/mesh-events.js';
180
251
  export type { PendingMeshCoordinatorEvent } from './mesh/mesh-events.js';
181
252
 
253
+ // ── Mesh Delivery Policy ──
254
+ export { resolveDeliveryDecision, createSessionDelivery, updateSessionDeliveryStatus, getActiveSessionDeliveries, markSessionDeliveriesTerminal, recordCompletionConflict, getRecentCompletionConflicts } from './mesh/mesh-delivery-policy.js';
255
+ export type { MeshSessionDeliveryStatus, MeshSessionDeliveryKind, MeshDeliveryDecision, MeshDeliveryPolicyResult, SessionDeliveryRecord } from './mesh/mesh-delivery-policy.js';
256
+
182
257
  // ── Mesh P2P Relay Failure Classification ──
183
258
  export {
184
259
  P2pRelayFailureError,
@@ -222,7 +297,7 @@ export type { CdpInitializerConfig } from './cdp/initializer.js';
222
297
  // ── Commands ──
223
298
  export { DaemonCommandHandler } from './commands/handler.js';
224
299
  export type { CommandResult, CommandContext } from './commands/handler.js';
225
- export { DaemonCommandRouter } from './commands/router.js';
300
+ export { DaemonCommandRouter, readCachedInlineMeshActiveSessionDetails } from './commands/router.js';
226
301
  export type { CommandRouterDeps, CommandRouterResult } from './commands/router.js';
227
302
  export {
228
303
  maybeRunDaemonUpgradeHelperFromEnv,
@@ -243,6 +318,8 @@ export type {
243
318
  export { DaemonStatusReporter } from './status/reporter.js';
244
319
  export { buildSessionEntries, findCdpManager, hasCdpManager, isCdpConnected } from './status/builders.js';
245
320
  export { buildStatusSnapshot, buildMachineInfo } from './status/snapshot.js';
321
+ export { getDaemonBuildInfo } from './build-info.js';
322
+ export type { DaemonBuildInfo } from './build-info.js';
246
323
  export { normalizeManagedStatus, isManagedStatusWorking, isManagedStatusWaiting, normalizeActiveChatData } from './status/normalize.js';
247
324
  export type { ManagedStatus } from './status/normalize.js';
248
325
  export type { StatusSnapshotOptions, StatusSnapshot } from './status/snapshot.js';
@@ -388,6 +465,13 @@ export type { CliAdapter } from './cli-adapter-types.js';
388
465
  export { NodePtyTransportFactory } from './cli-adapters/pty-transport.js';
389
466
  export type { PtyRuntimeTransport, PtyTransportFactory, PtySpawnOptions } from './cli-adapters/pty-transport.js';
390
467
  export { SessionHostPtyTransportFactory } from './cli-adapters/session-host-transport.js';
468
+ export {
469
+ RawTerminalAttachment,
470
+ namedKeyToAnsi,
471
+ namedKeysToAnsi,
472
+ withRawTerminalAttachment,
473
+ } from './cli-adapters/raw-terminal-io.js';
474
+ export type { NamedKey, RawTerminalAttachmentOptions, RawTerminalSessionHostClient } from './cli-adapters/raw-terminal-io.js';
391
475
  export type { HostedCliRuntimeDescriptor, CliTransportFactoryParams } from './commands/cli-manager.js';
392
476
  export {
393
477
  DEFAULT_SESSION_HOST_APP_NAME,
@@ -415,3 +499,50 @@ export type { ExtensionInfo as InstallerExtensionInfo } from './installer.js';
415
499
  // ── Boot / Lifecycle ──
416
500
  export { initDaemonComponents, startDaemonDevSupport, shutdownDaemonComponents } from './boot/daemon-lifecycle.js';
417
501
  export type { DaemonInitConfig, DaemonComponents, DaemonDevSupportOptions } from './boot/daemon-lifecycle.js';
502
+
503
+ // ── Local IPC server (shared between cloud + standalone daemons) ──
504
+ export {
505
+ startLocalIpcServer,
506
+ buildIpcStatusHttpResponse,
507
+ type LocalIpcServerOptions,
508
+ type LocalIpcServerHandle,
509
+ type IpcCommandContext,
510
+ type IpcCommandResult,
511
+ type IpcStatusPayload,
512
+ } from './ipc/local-ipc-server.js';
513
+
514
+ // ── CLI Spec (adhdev:cli/spec@4) ──
515
+ export { createNativeHistoryDispatcher } from './providers/native-history/index.js';
516
+ export type { ReaderId } from './providers/native-history/index.js';
517
+ export {
518
+ readClaudeCliSession, readCodexCliSession,
519
+ readAntigravityCliSession, readHermesCliSession,
520
+ } from './providers/native-history/index.js';
521
+ export type {
522
+ ControlAction, Control,
523
+ NotificationRule, DelegateTrigger,
524
+ } from './providers/spec/types.js';
525
+ export type { TraceEntry } from './providers/spec/evaluator.js';
526
+ export { evaluateFsm } from './providers/spec/fsm-evaluator.js';
527
+ export type { FsmClock } from './providers/spec/fsm-evaluator.js';
528
+ export { validateFsmSpec } from './providers/spec/fsm-loader.js';
529
+ export { FsmDriver } from './providers/spec/fsm-driver.js';
530
+ export type { DashboardEvent, DashboardCommand, SpecDriverOpts, ISpecDriver } from './providers/spec/fsm-driver.js';
531
+ export { TerminalAdapter } from './providers/spec/adapter.js';
532
+ export type { TerminalAdapterOpts, TerminalAdapterHandlers } from './providers/spec/adapter.js';
533
+
534
+ // ── Provider SDK (v1) — selective re-exports for external tooling ──
535
+ // Tooling (registry publish, dashboard validators, the e2e harness) needs
536
+ // the manifest validator, the builder catalog, and the contract version.
537
+ // We don't re-export *everything* from the SDK to keep the public surface
538
+ // stable; consumers that need internal SDK types still import from the
539
+ // sdk/v1 subpath.
540
+ export {
541
+ validateCliProviderManifest,
542
+ formatManifestValidationIssues,
543
+ type ManifestValidationIssue,
544
+ type ManifestValidationResult,
545
+ V1_CONTRACT_VERSION,
546
+ V1_PRIMITIVE_CATALOG,
547
+ V1_ALL_PRIMITIVES,
548
+ } from './providers/sdk/v1/index.js';
@@ -31,7 +31,7 @@ export interface InstallResult {
31
31
  /**
32
32
  * Check if an extension is already installed
33
33
  */
34
- export declare function isExtensionInstalled(ide: IDEInfo, marketplaceId: string): boolean;
34
+ export declare function isExtensionInstalled(ide: IDEInfo, marketplaceId: string): Promise<boolean>;
35
35
  /**
36
36
  * Install a single extension
37
37
  */
package/src/installer.ts CHANGED
@@ -122,20 +122,22 @@ export interface InstallResult {
122
122
  /**
123
123
  * Check if an extension is already installed
124
124
  */
125
- export function isExtensionInstalled(
125
+ import { promisify } from 'util';
126
+ const execAsync = promisify(exec);
127
+
128
+ export async function isExtensionInstalled(
126
129
  ide: IDEInfo,
127
130
  marketplaceId: string
128
- ): boolean {
131
+ ): Promise<boolean> {
129
132
  if (!ide.cliCommand) return false;
130
133
 
131
134
  try {
132
- const result = execSync(`"${ide.cliCommand}" --list-extensions`, {
135
+ const { stdout } = await execAsync(`"${ide.cliCommand}" --list-extensions`, {
133
136
  encoding: 'utf-8',
134
137
  timeout: 15000,
135
- stdio: ['pipe', 'pipe', 'pipe'],
136
138
  });
137
139
 
138
- const installed = result
140
+ const installed = stdout
139
141
  .trim()
140
142
  .split('\n')
141
143
  .map((e) => e.trim().toLowerCase());
@@ -163,7 +165,7 @@ export async function installExtension(
163
165
  }
164
166
 
165
167
  // Check if already installed
166
- const alreadyInstalled = isExtensionInstalled(ide, extension.marketplaceId);
168
+ const alreadyInstalled = await isExtensionInstalled(ide, extension.marketplaceId);
167
169
  if (alreadyInstalled) {
168
170
  return {
169
171
  extensionId: extension.id,
@@ -0,0 +1,278 @@
1
+ /**
2
+ * LocalIpcServer — generic HTTP + WebSocket IPC endpoint for daemon processes.
3
+ *
4
+ * Both daemon-cloud and daemon-standalone need a local IPC surface so
5
+ * external tools — the `adhdev mcp --mode ipc` MCP server and anything
6
+ * else that wants to issue commands without going through the cloud
7
+ * Worker — can connect over `ws://127.0.0.1:<port>/ipc`.
8
+ *
9
+ * Until now the implementation lived only in daemon-cloud. Standalone
10
+ * sessions therefore couldn't host MCP mesh tools — codex/claude config
11
+ * pointing at `--mode ipc` got `Cannot reach ipc daemon`. This module
12
+ * moves the transport into daemon-core so both daemons can mount it.
13
+ *
14
+ * The transport itself is daemon-agnostic. Cloud-specific behaviors
15
+ * (mesh relay, mandatory update gates) are injected via the caller's
16
+ * `handleCommand` hook; the IPC layer just frames/unframes JSON and
17
+ * routes messages.
18
+ */
19
+
20
+ import { createServer, type IncomingMessage, type Server as HttpServer } from 'http';
21
+ import { WebSocketServer, WebSocket } from 'ws';
22
+ import { LOG } from '../logging/logger.js';
23
+ import { DAEMON_WS_PATH } from '../ipc-protocol.js';
24
+
25
+ /** Parameters passed to `handleCommand` for each incoming ext:command frame. */
26
+ export interface IpcCommandContext {
27
+ /** The raw `command` field from the message — caller decides routing. */
28
+ command: string;
29
+ /** Args provided by the client; may have been normalized by the caller. */
30
+ args: Record<string, unknown>;
31
+ /** Stable id correlating the request and the eventual ext:command_result. */
32
+ requestId: string;
33
+ /** The connected WebSocket — only needed if the caller wants to send extra events. */
34
+ ws: WebSocket;
35
+ }
36
+
37
+ /** Result reported back to the client. `result` is optional context for success. */
38
+ export interface IpcCommandResult {
39
+ success: boolean;
40
+ result?: unknown;
41
+ error?: string;
42
+ /**
43
+ * Additional fields the caller wants merged into the response payload
44
+ * (e.g. the cloud daemon's mandatory-update-block fields). Reserved.
45
+ */
46
+ extra?: Record<string, unknown>;
47
+ }
48
+
49
+ /** Status payload returned from GET / on the IPC HTTP port. */
50
+ export interface IpcStatusPayload {
51
+ ok: true;
52
+ pid: number;
53
+ wsPath: string;
54
+ port: number;
55
+ /** Arbitrary daemon-specific summary. Cloud daemon includes mesh state, etc. */
56
+ status: Record<string, unknown> | null;
57
+ }
58
+
59
+ export interface LocalIpcServerOptions {
60
+ /** TCP port to listen on. 19222 is the conventional default. */
61
+ port: number;
62
+ /** Build the GET / status payload. Called on every health probe. */
63
+ buildStatusPayload: () => Record<string, unknown> | null;
64
+ /** Build the welcome message sent to a freshly-connected client. */
65
+ buildWelcomePayload: () => Record<string, unknown>;
66
+ /** Handle a single ext:command frame. Caller decides routing and returns the result. */
67
+ handleCommand: (ctx: IpcCommandContext) => Promise<IpcCommandResult>;
68
+ /** Optional notification when a new client connects (lets daemon track them for broadcasts). */
69
+ onClientConnected?: (ws: WebSocket) => void;
70
+ /** Optional notification when a client disconnects. */
71
+ onClientDisconnected?: (ws: WebSocket) => void;
72
+ /** Optional logger label (defaults to "IPC"). */
73
+ logCategory?: string;
74
+ }
75
+
76
+ /**
77
+ * Returned controller for stopping the server and broadcasting to clients.
78
+ * Stored by the daemon and torn down at shutdown.
79
+ */
80
+ export interface LocalIpcServerHandle {
81
+ /** True once `listen()` succeeded. */
82
+ isListening(): boolean;
83
+ /** Push a message to every connected client. */
84
+ broadcast(type: string, payload: unknown): void;
85
+ /** Close all client sockets + the HTTP server. */
86
+ close(): Promise<void>;
87
+ }
88
+
89
+ /**
90
+ * Build a JSON HTTP response describing the IPC endpoint. Exposed so caller
91
+ * code (and tests) can build the same shape without spinning a real server.
92
+ */
93
+ export function buildIpcStatusHttpResponse(
94
+ method: string | undefined,
95
+ url: string | undefined,
96
+ payload: IpcStatusPayload,
97
+ ): { statusCode: number; body: Record<string, unknown> } {
98
+ if (method && method.toUpperCase() !== 'GET') {
99
+ return { statusCode: 405, body: { ok: false, error: 'method not allowed' } };
100
+ }
101
+ // `/health` is the probe path used by the MCP IpcTransport ping —
102
+ // mirror cloud daemon behavior so `adhdev mcp --mode ipc` recognizes
103
+ // us as a live IPC host. `/` and `/status` return the same shape.
104
+ if (url && url !== '/' && url !== '/status' && url !== '/health') {
105
+ return { statusCode: 404, body: { ok: false, error: 'not found' } };
106
+ }
107
+ return { statusCode: 200, body: payload as unknown as Record<string, unknown> };
108
+ }
109
+
110
+ /**
111
+ * Start the local IPC server. Returns a handle the caller can use to broadcast
112
+ * events and tear down at shutdown.
113
+ */
114
+ export async function startLocalIpcServer(opts: LocalIpcServerOptions): Promise<LocalIpcServerHandle> {
115
+ const logCategory = opts.logCategory || 'IPC';
116
+ const clients = new Set<WebSocket>();
117
+ let httpServer: HttpServer | null = null;
118
+ let wss: WebSocketServer | null = null;
119
+ let listening = false;
120
+
121
+ httpServer = createServer((req, res) => {
122
+ const payload: IpcStatusPayload = {
123
+ ok: true,
124
+ pid: process.pid,
125
+ wsPath: DAEMON_WS_PATH,
126
+ port: opts.port,
127
+ status: opts.buildStatusPayload(),
128
+ };
129
+ const response = buildIpcStatusHttpResponse(req.method, req.url, payload);
130
+ const body = JSON.stringify(response.body);
131
+ res.writeHead(response.statusCode, {
132
+ 'Content-Type': 'application/json',
133
+ 'Content-Length': Buffer.byteLength(body),
134
+ 'Connection': 'close',
135
+ });
136
+ res.end(body);
137
+ });
138
+
139
+ wss = new WebSocketServer({ noServer: true });
140
+ wss.on('connection', (ws) => handleConnection(ws));
141
+
142
+ httpServer.on('upgrade', (req: IncomingMessage, socket, head) => {
143
+ const wsUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
144
+ if (wsUrl.pathname !== DAEMON_WS_PATH) {
145
+ socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
146
+ socket.destroy();
147
+ return;
148
+ }
149
+ wss!.handleUpgrade(req, socket, head, (ws) => {
150
+ wss!.emit('connection', ws, req);
151
+ });
152
+ });
153
+
154
+ function handleConnection(ws: WebSocket): void {
155
+ clients.add(ws);
156
+ sendWelcome(ws);
157
+ opts.onClientConnected?.(ws);
158
+
159
+ ws.on('message', (raw) => {
160
+ void handleMessage(ws, raw.toString());
161
+ });
162
+ ws.on('close', () => {
163
+ clients.delete(ws);
164
+ opts.onClientDisconnected?.(ws);
165
+ });
166
+ ws.on('error', () => {
167
+ clients.delete(ws);
168
+ opts.onClientDisconnected?.(ws);
169
+ });
170
+ }
171
+
172
+ function sendWelcome(ws: WebSocket): void {
173
+ try {
174
+ ws.send(JSON.stringify({
175
+ type: 'daemon:welcome',
176
+ payload: opts.buildWelcomePayload(),
177
+ }));
178
+ } catch (error: any) {
179
+ LOG.warn(logCategory, `Failed to send welcome: ${error?.message || error}`);
180
+ }
181
+ }
182
+
183
+ async function handleMessage(ws: WebSocket, raw: string): Promise<void> {
184
+ let msg: any;
185
+ try { msg = JSON.parse(raw); } catch { return; }
186
+ if (!msg || typeof msg !== 'object') return;
187
+
188
+ // Re-issue welcome on client request (used by reconnecting MCP servers).
189
+ if (msg.type === 'ext:register') {
190
+ sendWelcome(ws);
191
+ return;
192
+ }
193
+ if (msg.type !== 'ext:command') return;
194
+
195
+ const payload = msg.payload && typeof msg.payload === 'object' ? msg.payload : {};
196
+ const command = typeof payload.command === 'string' ? payload.command : '';
197
+ const args = payload.args && typeof payload.args === 'object'
198
+ ? payload.args as Record<string, unknown>
199
+ : {};
200
+ const requestId = typeof payload.requestId === 'string'
201
+ ? payload.requestId
202
+ : typeof payload.messageId === 'string'
203
+ ? payload.messageId
204
+ : `ipc-${Date.now()}`;
205
+
206
+ if (!command) {
207
+ ws.send(JSON.stringify({
208
+ type: 'ext:command_result',
209
+ payload: { requestId, success: false, error: 'command required' },
210
+ }));
211
+ return;
212
+ }
213
+
214
+ try {
215
+ const result = await opts.handleCommand({ command, args, requestId, ws });
216
+ ws.send(JSON.stringify({
217
+ type: 'ext:command_result',
218
+ payload: {
219
+ requestId,
220
+ success: result.success,
221
+ result: result.result,
222
+ error: result.error,
223
+ ...(result.extra || {}),
224
+ },
225
+ }));
226
+ } catch (error: any) {
227
+ ws.send(JSON.stringify({
228
+ type: 'ext:command_result',
229
+ payload: {
230
+ requestId,
231
+ success: false,
232
+ error: error?.message || String(error),
233
+ },
234
+ }));
235
+ }
236
+ }
237
+
238
+ await new Promise<void>((resolve, reject) => {
239
+ const onError = (error: Error) => {
240
+ httpServer?.off('listening', onListening);
241
+ reject(error);
242
+ };
243
+ const onListening = () => {
244
+ httpServer?.off('error', onError);
245
+ listening = true;
246
+ resolve();
247
+ };
248
+ httpServer!.once('error', onError);
249
+ httpServer!.once('listening', onListening);
250
+ httpServer!.listen(opts.port, '127.0.0.1');
251
+ });
252
+
253
+ LOG.info(logCategory, `Local IPC listening on ws://127.0.0.1:${opts.port}${DAEMON_WS_PATH}`);
254
+
255
+ return {
256
+ isListening: () => listening,
257
+ broadcast(type, payload) {
258
+ const message = JSON.stringify({ type, payload });
259
+ for (const client of clients) {
260
+ if (client.readyState !== WebSocket.OPEN) continue;
261
+ try { client.send(message); } catch { /* drop silently */ }
262
+ }
263
+ },
264
+ async close() {
265
+ for (const client of clients) {
266
+ try { client.close(); } catch { /* ignore */ }
267
+ }
268
+ clients.clear();
269
+ await new Promise<void>((resolve) => {
270
+ if (!httpServer) { resolve(); return; }
271
+ httpServer.close(() => resolve());
272
+ });
273
+ httpServer = null;
274
+ wss = null;
275
+ listening = false;
276
+ },
277
+ };
278
+ }
package/src/launch.d.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  /** Kill IDE process (graceful → force) */
19
19
  export declare function killIdeProcess(ideId: string): Promise<boolean>;
20
20
  /** Check if IDE process is running */
21
- export declare function isIdeRunning(ideId: string): boolean;
21
+ export declare function isIdeRunning(ideId: string): Promise<boolean>;
22
22
  export interface LaunchOptions {
23
23
  ideId?: string;
24
24
  workspace?: string;