@adhdev/daemon-core 0.9.82-rc.364 → 0.9.82-rc.366

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/commands/high-family/index.d.ts +3 -0
  2. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  3. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  4. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  5. package/dist/commands/high-family/types.d.ts +60 -0
  6. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  7. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  8. package/dist/commands/med-family/ide.d.ts +10 -0
  9. package/dist/commands/med-family/index.d.ts +3 -0
  10. package/dist/commands/med-family/mesh-crud.d.ts +2 -0
  11. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  12. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  13. package/dist/commands/med-family/types.d.ts +116 -0
  14. package/dist/commands/router.d.ts +291 -0
  15. package/dist/index.js +3824 -3565
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +3811 -3553
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/mesh/mesh-events-coordinator.d.ts +8 -0
  20. package/dist/system/hash.d.ts +8 -0
  21. package/package.json +2 -2
  22. package/src/commands/cli-manager.ts +30 -3
  23. package/src/commands/high-family/index.ts +28 -0
  24. package/src/commands/high-family/mesh-coordinator-launch.ts +592 -0
  25. package/src/commands/high-family/mesh-events.ts +47 -0
  26. package/src/commands/high-family/mesh-status.ts +639 -0
  27. package/src/commands/high-family/types.ts +76 -0
  28. package/src/commands/med-family/cli-agent.ts +218 -0
  29. package/src/commands/med-family/fast-forward.ts +198 -0
  30. package/src/commands/med-family/ide.ts +163 -0
  31. package/src/commands/med-family/index.ts +35 -0
  32. package/src/commands/med-family/mesh-crud.ts +788 -0
  33. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  34. package/src/commands/med-family/mesh-queue.ts +131 -0
  35. package/src/commands/med-family/types.ts +120 -0
  36. package/src/commands/mesh-coordinator.ts +2 -2
  37. package/src/commands/router.ts +328 -2847
  38. package/src/config/mesh-config.ts +3 -2
  39. package/src/mesh/mesh-active-work.ts +59 -81
  40. package/src/mesh/mesh-events-coordinator.ts +35 -1
  41. package/src/system/hash.ts +23 -0
@@ -0,0 +1,592 @@
1
+ /**
2
+ * RF-ROUTER HIGH family — mesh coordinator launch.
3
+ *
4
+ * launch_mesh_coordinator: resolve the coordinator node + workspace, gate on Mesh
5
+ * Host ownership, resolve the provider's MCP coordinator setup (cli_command vs
6
+ * auto-import config), register the ADHDev mesh MCP server, build + inject the
7
+ * coordinator system prompt, launch the CLI session and record it in the
8
+ * coordinator registry + task ledger. Extracted verbatim from
9
+ * executeDaemonCommand — only `this.deps`/`this.inlineMeshCache` became
10
+ * `ctx.deps`/`ctx.inlineMeshCache`.
11
+ */
12
+ import { join as pathJoin } from 'path';
13
+ import * as fs from 'fs';
14
+ import { LOG } from '../../logging/logger.js';
15
+ import { resolveMeshHostStatus, buildMeshHostRequiredFailure } from '../../mesh/mesh-host-ownership.js';
16
+ import { registerMeshCoordinator } from '../../mesh/coordinator-registry.js';
17
+ import { partitionSessionHostRecords } from '../../session-host/runtime-surface.js';
18
+ import { createHermesManualMeshCoordinatorSetup, resolveMeshCoordinatorSetup } from '../mesh-coordinator.js';
19
+ import { normalizeMeshNodeId } from '@adhdev/mesh-shared';
20
+ import {
21
+ readProviderPriorityFromPolicy,
22
+ resolveProviderTypeFromPriority,
23
+ readLiveMeshNodeWorkspace,
24
+ getMcpServersKey,
25
+ parseMeshCoordinatorMcpConfig,
26
+ serializeMeshCoordinatorMcpConfig,
27
+ loadHermesCoordinatorBaseConfig,
28
+ stripHermesCoordinatorTempModelProviderOverrides,
29
+ copyHermesCoordinatorCredentialFiles,
30
+ type MeshCoordinatorConfigFormat,
31
+ } from '../router.js';
32
+ import type { HighFamilyContext, HighFamilyHandler } from './types.js';
33
+
34
+ export const meshCoordinatorLaunchHandlers: Record<string, HighFamilyHandler> = {
35
+ launch_mesh_coordinator: async (ctx: HighFamilyContext, args: any) => {
36
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
37
+ let cliType = typeof args?.cliType === 'string' ? args.cliType.trim() : '';
38
+ // Optional per-launch system-prompt addition. Dashboard or API
39
+ // callers (e.g. when spawning a mesh-node-specific coordinator)
40
+ // can pass extra context that gets appended to the rendered
41
+ // default prompt under the "## Additional Context" section.
42
+ // Going through buildCoordinatorSystemPrompt's userInstruction
43
+ // means user-level override files (~/.adhdev/coordinator-prompts)
44
+ // and this per-launch addition compose cleanly: an override
45
+ // wins outright, but if there's no override, the default
46
+ // prompt + the optional append.md file + this extra context
47
+ // all stack in declared order.
48
+ const extraSystemPrompt = typeof args?.extraSystemPrompt === 'string'
49
+ ? args.extraSystemPrompt.trim()
50
+ : '';
51
+ if (!meshId) return { success: false, error: 'meshId required' };
52
+
53
+ try {
54
+ const { buildCoordinatorSystemPrompt } = await import('../../mesh/coordinator-prompt.js');
55
+ const { buildMissionPromptSection } = await import('../../mesh/mesh-missions.js');
56
+ // M3-3: inject the active mission summary into the coordinator prompt.
57
+ // Best-effort — a store failure must not block coordinator launch.
58
+ const buildMissionSectionBestEffort = (id: string): string => {
59
+ try { return buildMissionPromptSection(id); } catch { return ''; }
60
+ };
61
+
62
+ // Support inline mesh data from cloud (bypasses local meshes.json lookup)
63
+ let mesh: any;
64
+ if (args?.inlineMesh && typeof args.inlineMesh === 'object') {
65
+ mesh = args.inlineMesh;
66
+ // Cache cloud mesh so the MCP server can retrieve it via get_mesh
67
+ ctx.inlineMeshCache.set(meshId, mesh);
68
+ } else {
69
+ const { getMesh } = await import('../../config/mesh-config.js');
70
+ mesh = getMesh(meshId);
71
+ }
72
+ if (!mesh) return { success: false, error: 'Mesh not found' };
73
+ const meshHost = resolveMeshHostStatus(mesh);
74
+ if (!meshHost.canOwnCoordinator) {
75
+ return {
76
+ success: false,
77
+ ...buildMeshHostRequiredFailure(mesh, 'coordinator launch'),
78
+ meshId,
79
+ cliType,
80
+ };
81
+ }
82
+ if (!Array.isArray(mesh.nodes) || mesh.nodes.length === 0) return { success: false, error: 'No nodes in mesh' };
83
+
84
+ const requestedCoordinatorNodeId = typeof args?.coordinatorNodeId === 'string'
85
+ ? args.coordinatorNodeId.trim()
86
+ : '';
87
+ const preferredCoordinatorNodeId = requestedCoordinatorNodeId
88
+ || (typeof mesh.coordinator?.preferredNodeId === 'string' ? mesh.coordinator.preferredNodeId.trim() : '');
89
+ const coordinatorNode = preferredCoordinatorNodeId
90
+ ? mesh.nodes.find((node: any) => node?.id === preferredCoordinatorNodeId || node?.nodeId === preferredCoordinatorNodeId)
91
+ : mesh.nodes[0];
92
+ if (!coordinatorNode) {
93
+ return {
94
+ success: false,
95
+ code: 'mesh_coordinator_node_not_found',
96
+ error: `Coordinator node ${preferredCoordinatorNodeId} was not found in mesh`,
97
+ meshId,
98
+ cliType,
99
+ };
100
+ }
101
+ const sessionHostRecords = ctx.deps.sessionHostControl?.listSessions
102
+ ? await ctx.deps.sessionHostControl.listSessions().catch(() => [])
103
+ : [];
104
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
105
+ const workspace = readLiveMeshNodeWorkspace({
106
+ meshId,
107
+ nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || ''),
108
+ liveSessionRecords: liveMeshSessions,
109
+ allowCoordinatorSession: true,
110
+ }) || (typeof coordinatorNode.workspace === 'string' ? coordinatorNode.workspace.trim() : '');
111
+ if (!workspace) return { success: false, error: 'Coordinator node workspace required', meshId, cliType };
112
+ if (!cliType) {
113
+ const resolved = await resolveProviderTypeFromPriority({
114
+ nodeId: String(normalizeMeshNodeId(coordinatorNode) || preferredCoordinatorNodeId || 'coordinator'),
115
+ providerPriority: readProviderPriorityFromPolicy(coordinatorNode.policy),
116
+ providerLoader: ctx.deps.providerLoader,
117
+ onStatusChange: ctx.deps.onStatusChange,
118
+ });
119
+ if (!resolved.providerType) {
120
+ return {
121
+ success: false,
122
+ code: 'mesh_coordinator_provider_priority_unusable',
123
+ error: resolved.error || 'No usable provider found from node providerPriority',
124
+ meshId,
125
+ cliType,
126
+ workspace,
127
+ };
128
+ }
129
+ cliType = resolved.providerType;
130
+ }
131
+ const providerMeta = ctx.deps.providerLoader.resolve?.(cliType) || ctx.deps.providerLoader.getMeta(cliType);
132
+ const coordinatorSetup = resolveMeshCoordinatorSetup({
133
+ provider: providerMeta,
134
+ cliType,
135
+ meshId,
136
+ workspace,
137
+ });
138
+
139
+ if (coordinatorSetup.kind === 'unsupported') {
140
+ return {
141
+ success: false,
142
+ code: 'mesh_coordinator_unsupported',
143
+ error: coordinatorSetup.reason,
144
+ meshId,
145
+ cliType,
146
+ workspace,
147
+ };
148
+ }
149
+
150
+ if (coordinatorSetup.kind === 'manual') {
151
+ return {
152
+ success: false,
153
+ code: 'mesh_coordinator_manual_mcp_setup_required',
154
+ error: coordinatorSetup.instructions,
155
+ meshId,
156
+ cliType,
157
+ workspace,
158
+ meshCoordinatorSetup: coordinatorSetup,
159
+ };
160
+ }
161
+
162
+ // ─── CLI-command MCP registration (Codex, Gemini CLI) ───────────
163
+ if (coordinatorSetup.kind === 'cli_command') {
164
+ // Build coordinator prompt first — fail closed on errors.
165
+ let cliCmdSystemPrompt = '';
166
+ try {
167
+ cliCmdSystemPrompt = buildCoordinatorSystemPrompt({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || undefined, missionSection: buildMissionSectionBestEffort(mesh.id) });
168
+ } catch (error: any) {
169
+ const message = error?.message || String(error);
170
+ LOG.error('MeshCoordinator', `Failed to build coordinator prompt: ${message}`);
171
+ return {
172
+ success: false,
173
+ code: 'mesh_coordinator_prompt_failed',
174
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
175
+ meshId, cliType, workspace,
176
+ };
177
+ }
178
+
179
+ // Run the provider's MCP registration command under a
180
+ // PTY. Some providers (agy, future bubbletea CLIs)
181
+ // refuse to run without /dev/tty, so pipe-only
182
+ // execFileSync silently no-ops the registration and
183
+ // the coordinator ends up without any mcp tools. With
184
+ // a real PTY the registration goes through and the
185
+ // exit code tells us whether it actually persisted.
186
+ let mcpRegistrationOk = false;
187
+ let mcpRegistrationFailure: {
188
+ command: string;
189
+ output: string;
190
+ exitCode: number | null;
191
+ signal: number | null;
192
+ timedOut: boolean;
193
+ } | null = null;
194
+ try {
195
+ const { buildMeshCoordinatorRegistrationPlan, execUnderPty } = await import('../mesh-coordinator.js');
196
+ const registrationPlan = buildMeshCoordinatorRegistrationPlan(
197
+ cliType,
198
+ coordinatorSetup.serverName,
199
+ coordinatorSetup.command,
200
+ );
201
+ for (const step of registrationPlan) {
202
+ const renderedCommand = [step.command, ...step.args].join(' ');
203
+ LOG.info('MeshCoordinator', `Running MCP ${step.label} (pty): ${renderedCommand}`);
204
+ const ptyResult = await execUnderPty(step.command, step.args, { cwd: workspace, timeoutMs: 20_000 });
205
+ if (ptyResult.exitCode === 0 && !ptyResult.timedOut) {
206
+ if (step.required) mcpRegistrationOk = true;
207
+ continue;
208
+ }
209
+ LOG.warn('MeshCoordinator', `MCP ${step.label} failed exit=${ptyResult.exitCode} signal=${ptyResult.signal} timedOut=${ptyResult.timedOut} — output:\n${ptyResult.output.slice(-2000)}`);
210
+ if (step.required) {
211
+ mcpRegistrationFailure = {
212
+ command: renderedCommand,
213
+ output: ptyResult.output.slice(-2000),
214
+ exitCode: ptyResult.exitCode,
215
+ signal: ptyResult.signal,
216
+ timedOut: ptyResult.timedOut,
217
+ };
218
+ break;
219
+ }
220
+ }
221
+ } catch (error: any) {
222
+ LOG.warn('MeshCoordinator', `MCP registration command failed: ${error?.message || error}`);
223
+ mcpRegistrationFailure = {
224
+ command: coordinatorSetup.command,
225
+ output: error?.message || String(error),
226
+ exitCode: null,
227
+ signal: null,
228
+ timedOut: false,
229
+ };
230
+ }
231
+
232
+ if (!mcpRegistrationOk) {
233
+ return {
234
+ success: false,
235
+ code: 'mesh_coordinator_mcp_registration_failed',
236
+ error: `Could not register ${coordinatorSetup.serverName}; coordinator session was not launched`,
237
+ meshId,
238
+ cliType,
239
+ workspace,
240
+ registration: mcpRegistrationFailure,
241
+ };
242
+ }
243
+
244
+ // Codex gives repo-local .mcp.json precedence over its
245
+ // global `codex mcp add` registration. Refresh an
246
+ // existing ADHDev entry so a stale workspace command
247
+ // cannot shadow the registration we just verified.
248
+ if (cliType === 'codex-cli') {
249
+ const repoMcpConfigPath = pathJoin(workspace, '.mcp.json');
250
+ if (fs.existsSync(repoMcpConfigPath)) {
251
+ try {
252
+ const repoMcpConfig = parseMeshCoordinatorMcpConfig(
253
+ fs.readFileSync(repoMcpConfigPath, 'utf-8'),
254
+ 'claude_mcp_json',
255
+ );
256
+ const existingServers = repoMcpConfig.mcpServers;
257
+ if (
258
+ existingServers
259
+ && typeof existingServers === 'object'
260
+ && !Array.isArray(existingServers)
261
+ && existingServers[coordinatorSetup.serverName]
262
+ ) {
263
+ fs.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
264
+ ...repoMcpConfig,
265
+ mcpServers: {
266
+ ...existingServers,
267
+ [coordinatorSetup.serverName]: coordinatorSetup.mcpServer,
268
+ },
269
+ }, 'claude_mcp_json'), 'utf-8');
270
+ LOG.info('MeshCoordinator', `Refreshed repo-local ${repoMcpConfigPath} entry for ${coordinatorSetup.serverName}`);
271
+ }
272
+ } catch (error: any) {
273
+ return {
274
+ success: false,
275
+ code: 'mesh_coordinator_config_write_failed',
276
+ error: `Could not refresh repo-local MCP config: ${error?.message || error}`,
277
+ meshId,
278
+ cliType,
279
+ workspace,
280
+ };
281
+ }
282
+ }
283
+ }
284
+
285
+ // Inject system prompt declaratively from provider.v1.json.
286
+ const cliCmdArgs: string[] = [];
287
+ const cliCmdEnv: Record<string, string> = {};
288
+ let cliCmdContextFilePath: string | undefined;
289
+ if (cliCmdSystemPrompt) {
290
+ const { applyMeshCoordinatorSystemPromptInjection } = await import('../mesh-coordinator.js');
291
+ const effect = applyMeshCoordinatorSystemPromptInjection(
292
+ cliCmdSystemPrompt,
293
+ providerMeta?.meshCoordinator?.systemPromptInjection,
294
+ { cliArgs: cliCmdArgs, launchEnv: cliCmdEnv, workspace, cliType },
295
+ );
296
+ cliCmdContextFilePath = effect.contextFilePath;
297
+ }
298
+
299
+ const cliCmdLaunch: any = await ctx.deps.cliManager.handleCliCommand('launch_cli', {
300
+ cliType,
301
+ dir: workspace,
302
+ cliArgs: cliCmdArgs.length > 0 ? cliCmdArgs : undefined,
303
+ env: Object.keys(cliCmdEnv).length > 0 ? cliCmdEnv : undefined,
304
+ settings: { meshCoordinatorFor: meshId },
305
+ });
306
+
307
+ // R48 inject-then-remove. Spawn was just kicked off above; agy and
308
+ // gemini-cli read AGENTS.md / GEMINI.md exactly once at startup and
309
+ // cache it for the rest of the session, so we can safely strip
310
+ // the wrapper from disk shortly after launch. That keeps any
311
+ // worker session launched into the same workspace later from
312
+ // picking up our wrapper block.
313
+ if (cliCmdLaunch?.success && cliCmdContextFilePath) {
314
+ const stripPath = cliCmdContextFilePath;
315
+ setTimeout(() => {
316
+ void import('../mesh-coordinator.js').then(({ stripCoordinatorWrapperFile }) => {
317
+ stripCoordinatorWrapperFile(stripPath);
318
+ LOG.info('MeshCoordinator', `Stripped wrapper from ${stripPath} after launch settle (cli_command)`);
319
+ }).catch(() => { /* best-effort */ });
320
+ }, 5000);
321
+ }
322
+
323
+ if (!cliCmdLaunch?.success) {
324
+ return { success: false, error: cliCmdLaunch?.error || 'Failed to launch CLI session' };
325
+ }
326
+
327
+ LOG.info('MeshCoordinator', `Launched ${cliType} coordinator (cli_command) for mesh ${meshId}`);
328
+ const cliCmdSessionId = cliCmdLaunch.sessionId || cliCmdLaunch.id;
329
+ if (cliCmdSessionId) {
330
+ const cliCmdInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
331
+ registerMeshCoordinator({
332
+ meshId,
333
+ sessionId: cliCmdSessionId,
334
+ workspace,
335
+ startedAt: Date.now(),
336
+ cliType,
337
+ systemPrompt: cliCmdSystemPrompt || undefined,
338
+ extraSystemPrompt: extraSystemPrompt || undefined,
339
+ injection: cliCmdInjectionDecl ? {
340
+ mode: cliCmdInjectionDecl.mode,
341
+ target: 'flag' in cliCmdInjectionDecl ? cliCmdInjectionDecl.flag
342
+ : 'name' in cliCmdInjectionDecl ? cliCmdInjectionDecl.name
343
+ : 'path' in cliCmdInjectionDecl ? cliCmdInjectionDecl.path
344
+ : undefined,
345
+ } : undefined,
346
+ });
347
+ }
348
+ try {
349
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
350
+ appendLedgerEntry(meshId, {
351
+ kind: 'coordinator_started',
352
+ sessionId: cliCmdSessionId,
353
+ providerType: cliType,
354
+ payload: { workspace },
355
+ });
356
+ } catch { /* best-effort */ }
357
+
358
+ return {
359
+ success: true,
360
+ meshId,
361
+ cliType,
362
+ workspace,
363
+ sessionId: cliCmdSessionId,
364
+ mcpRegistered: mcpRegistrationOk,
365
+ };
366
+ }
367
+
368
+ const configFormat = coordinatorSetup.configFormat as MeshCoordinatorConfigFormat;
369
+ if (configFormat !== 'claude_mcp_json' && configFormat !== 'hermes_config_yaml') {
370
+ return {
371
+ success: false,
372
+ code: 'mesh_coordinator_unsupported',
373
+ error: `Unsupported auto-import MCP config format: ${String(coordinatorSetup.configFormat)}`,
374
+ meshId,
375
+ cliType,
376
+ workspace,
377
+ };
378
+ }
379
+
380
+ // Build the coordinator prompt before mutating workspace config or launching.
381
+ // Prompt generation failures are configuration/data-shape errors; fail closed so
382
+ // broken mesh state is visible instead of silently launching with weaker rules.
383
+ let systemPrompt = '';
384
+ try {
385
+ systemPrompt = buildCoordinatorSystemPrompt({ mesh, coordinatorCliType: cliType, userInstruction: extraSystemPrompt || undefined, missionSection: buildMissionSectionBestEffort(mesh.id) });
386
+ } catch (error: any) {
387
+ const message = error?.message || String(error);
388
+ LOG.error('MeshCoordinator', `Failed to build coordinator prompt: ${message}`);
389
+ return {
390
+ success: false,
391
+ code: 'mesh_coordinator_prompt_failed',
392
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
393
+ meshId,
394
+ cliType,
395
+ workspace,
396
+ };
397
+ }
398
+
399
+ // 1. Write provider-declared MCP config for CLIs that auto-import it.
400
+ const { existsSync, readFileSync, writeFileSync, copyFileSync, mkdirSync } = await import('fs');
401
+ const { dirname } = await import('path');
402
+ const mcpConfigPath = coordinatorSetup.configPath;
403
+ const hermesManualFallback = cliType === 'hermes-cli' && configFormat === 'hermes_config_yaml'
404
+ ? createHermesManualMeshCoordinatorSetup(meshId, workspace)
405
+ : null;
406
+ let hermesBaseConfig: { config: Record<string, any>; sourceHome: string; sourceConfigPath: string } | null = null;
407
+ if (hermesManualFallback) {
408
+ try {
409
+ hermesBaseConfig = loadHermesCoordinatorBaseConfig(mcpConfigPath);
410
+ } catch (error: any) {
411
+ const message = `Failed to parse Hermes base config for automatic coordinator setup: ${error?.message || error}`;
412
+ LOG.error('MeshCoordinator', message);
413
+ return { success: false, code: 'mesh_coordinator_config_parse_failed', error: message, meshId, cliType, workspace };
414
+ }
415
+ }
416
+ const returnManualFallback = (message: string) => ({
417
+ success: false,
418
+ code: 'mesh_coordinator_manual_mcp_setup_required',
419
+ error: message,
420
+ meshId,
421
+ cliType,
422
+ workspace,
423
+ meshCoordinatorSetup: hermesManualFallback,
424
+ });
425
+
426
+ // Merge ADHDev mesh server into existing config.
427
+ // Pass full mesh data as env var so the MCP server can bootstrap
428
+ // without depending on meshes.json or a running daemon.
429
+ const mcpServerEntry: Record<string, any> = {
430
+ command: coordinatorSetup.mcpServer.command,
431
+ args: coordinatorSetup.mcpServer.args,
432
+ };
433
+ if (args?.inlineMesh) {
434
+ const modeArgIndex = coordinatorSetup.mcpServer.args.findIndex((value: string) => value === '--mode');
435
+ const mcpTransport = modeArgIndex >= 0 ? coordinatorSetup.mcpServer.args[modeArgIndex + 1] : 'ipc';
436
+ mcpServerEntry.env = {
437
+ ADHDEV_INLINE_MESH: JSON.stringify(mesh),
438
+ ADHDEV_MCP_TRANSPORT: mcpTransport === 'local' ? 'local' : 'ipc',
439
+ };
440
+ }
441
+
442
+ try {
443
+ mkdirSync(dirname(mcpConfigPath), { recursive: true });
444
+ } catch (error: any) {
445
+ const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
446
+ LOG.error('MeshCoordinator', message);
447
+ if (hermesManualFallback) return returnManualFallback(message);
448
+ return { success: false, code: 'mesh_coordinator_config_write_failed', error: message, meshId, cliType, workspace };
449
+ }
450
+
451
+ // Backup existing MCP config if present.
452
+ const hadExistingMcpConfig = existsSync(mcpConfigPath);
453
+ let existingMcpConfig: Record<string, any> = hermesBaseConfig?.config || {};
454
+ if (hermesBaseConfig) {
455
+ copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname(mcpConfigPath));
456
+ }
457
+ if (hadExistingMcpConfig) {
458
+ try {
459
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync(mcpConfigPath, 'utf-8'), configFormat);
460
+ const existingCoordinatorConfig = hermesManualFallback
461
+ ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig)
462
+ : parsedExistingMcpConfig;
463
+ existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
464
+ copyFileSync(mcpConfigPath, mcpConfigPath + '.backup');
465
+ } catch (error: any) {
466
+ LOG.error('MeshCoordinator', `Failed to parse existing MCP config ${mcpConfigPath}: ${error?.message || error}`);
467
+ return {
468
+ success: false,
469
+ code: 'mesh_coordinator_config_parse_failed',
470
+ error: `Failed to parse existing MCP config at ${mcpConfigPath}`,
471
+ };
472
+ }
473
+ }
474
+
475
+ const mcpServersKey = getMcpServersKey(configFormat);
476
+ const existingServers = existingMcpConfig[mcpServersKey];
477
+ const mcpConfig = {
478
+ ...existingMcpConfig,
479
+ [mcpServersKey]: {
480
+ ...(existingServers && typeof existingServers === 'object' && !Array.isArray(existingServers) ? existingServers : {}),
481
+ [coordinatorSetup.serverName]: mcpServerEntry,
482
+ },
483
+ };
484
+ try {
485
+ writeFileSync(mcpConfigPath, serializeMeshCoordinatorMcpConfig(mcpConfig, configFormat), 'utf-8');
486
+ } catch (error: any) {
487
+ const message = `Could not write MCP config for automatic setup: ${error?.message || error}`;
488
+ LOG.error('MeshCoordinator', message);
489
+ if (hermesManualFallback) return returnManualFallback(message);
490
+ return { success: false, code: 'mesh_coordinator_config_write_failed', error: message, meshId, cliType, workspace };
491
+ }
492
+ LOG.info('MeshCoordinator', `Wrote ${mcpConfigPath} with ${coordinatorSetup.serverName} server`);
493
+
494
+ const cliArgs: string[] = [];
495
+ const launchEnv: Record<string, string> = {};
496
+ if (configFormat === 'hermes_config_yaml') {
497
+ launchEnv.HERMES_HOME = dirname(mcpConfigPath);
498
+ launchEnv.HERMES_IGNORE_USER_CONFIG = '';
499
+ }
500
+ let autoImportContextFilePath: string | undefined;
501
+ if (systemPrompt) {
502
+ const { applyMeshCoordinatorSystemPromptInjection } = await import('../mesh-coordinator.js');
503
+ const effect = applyMeshCoordinatorSystemPromptInjection(
504
+ systemPrompt,
505
+ providerMeta?.meshCoordinator?.systemPromptInjection,
506
+ { cliArgs, launchEnv, workspace, cliType },
507
+ );
508
+ autoImportContextFilePath = effect.contextFilePath;
509
+ }
510
+ if (cliType === 'claude-cli') {
511
+ cliArgs.push('--mcp-config', coordinatorSetup.configPath);
512
+ }
513
+
514
+ // 3. Launch CLI session via existing cliManager.
515
+ // Provider-specific prompt injection remains fail-closed: Claude gets
516
+ // explicit CLI args, while Hermes reads HERMES_EPHEMERAL_SYSTEM_PROMPT.
517
+ const launchResult: any = await ctx.deps.cliManager.handleCliCommand('launch_cli', {
518
+ cliType,
519
+ dir: workspace,
520
+ cliArgs: cliArgs.length > 0 ? cliArgs : undefined,
521
+ env: Object.keys(launchEnv).length > 0 ? launchEnv : undefined,
522
+ settings: {
523
+ meshCoordinatorFor: meshId
524
+ }
525
+ });
526
+
527
+ // R48 inject-then-remove. See the cli_command branch for context;
528
+ // same idea: strip the wrapper from disk ~5s after launch so the
529
+ // user's AGENTS.md / GEMINI.md is untouched the moment any
530
+ // worker session opens up in the same workspace.
531
+ if (launchResult?.success && autoImportContextFilePath) {
532
+ const stripPath = autoImportContextFilePath;
533
+ setTimeout(() => {
534
+ void import('../mesh-coordinator.js').then(({ stripCoordinatorWrapperFile }) => {
535
+ stripCoordinatorWrapperFile(stripPath);
536
+ LOG.info('MeshCoordinator', `Stripped wrapper from ${stripPath} after launch settle (auto_import)`);
537
+ }).catch(() => { /* best-effort */ });
538
+ }, 5000);
539
+ }
540
+
541
+ if (!launchResult?.success) {
542
+ return { success: false, error: launchResult?.error || 'Failed to launch CLI session' };
543
+ }
544
+
545
+ LOG.info('MeshCoordinator', `Launched ${cliType} coordinator for mesh ${meshId} in ${workspace}`);
546
+ const launchSessionId = launchResult.sessionId || launchResult.id;
547
+ if (launchSessionId) {
548
+ const autoImportInjectionDecl = providerMeta?.meshCoordinator?.systemPromptInjection;
549
+ registerMeshCoordinator({
550
+ meshId,
551
+ sessionId: launchSessionId,
552
+ workspace,
553
+ startedAt: Date.now(),
554
+ cliType,
555
+ systemPrompt: systemPrompt || undefined,
556
+ extraSystemPrompt: extraSystemPrompt || undefined,
557
+ mcpConfigPath,
558
+ injection: autoImportInjectionDecl ? {
559
+ mode: autoImportInjectionDecl.mode,
560
+ target: 'flag' in autoImportInjectionDecl ? autoImportInjectionDecl.flag
561
+ : 'name' in autoImportInjectionDecl ? autoImportInjectionDecl.name
562
+ : 'path' in autoImportInjectionDecl ? autoImportInjectionDecl.path
563
+ : undefined,
564
+ } : undefined,
565
+ });
566
+ }
567
+
568
+ // Record coordinator launch in task ledger
569
+ try {
570
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
571
+ appendLedgerEntry(meshId, {
572
+ kind: 'coordinator_started',
573
+ sessionId: launchSessionId,
574
+ providerType: cliType,
575
+ payload: { workspace },
576
+ });
577
+ } catch { /* ledger append is best-effort */ }
578
+
579
+ return {
580
+ success: true,
581
+ meshId,
582
+ cliType,
583
+ workspace,
584
+ sessionId: launchSessionId,
585
+ mcpConfigWritten: true,
586
+ };
587
+ } catch (e: any) {
588
+ LOG.error('MeshCoordinator', `Failed: ${e.message}`);
589
+ return { success: false, error: e.message };
590
+ }
591
+ },
592
+ };
@@ -0,0 +1,47 @@
1
+ /**
2
+ * RF-ROUTER HIGH family — mesh coordinator-event relay + interactive prompt.
3
+ *
4
+ * mesh_forward_event (relay a worker event to the local instance manager),
5
+ * get_pending_mesh_events (drain queued coordinator events, optionally scoped to
6
+ * a coordinator daemon), and interactive_prompt_response (deliver a prompt reply
7
+ * to a running instance). Extracted verbatim from executeDaemonCommand — only
8
+ * `this.deps` became `ctx.deps`.
9
+ */
10
+ import {
11
+ handleMeshForwardEvent,
12
+ drainPendingMeshCoordinatorEvents,
13
+ } from '../../mesh/mesh-events.js';
14
+ import { normalizeInteractivePromptResponse } from '../../providers/types/interactive-prompt.js';
15
+ import type { HighFamilyContext, HighFamilyHandler } from './types.js';
16
+
17
+ export const meshEventsHandlers: Record<string, HighFamilyHandler> = {
18
+ mesh_forward_event: async (ctx: HighFamilyContext, args: any) => {
19
+ return handleMeshForwardEvent({ instanceManager: ctx.deps.instanceManager } as any, args as Record<string, unknown>);
20
+ },
21
+
22
+ get_pending_mesh_events: async (_ctx: HighFamilyContext, args: any) => {
23
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
24
+ // (B3) Respect coordinatorDaemonId when the caller declares it
25
+ // so unicast events route to the right coordinator instead of
26
+ // being silently consumed by the first drainer.
27
+ const coordinatorDaemonId = typeof args?.coordinatorDaemonId === 'string' && args.coordinatorDaemonId.trim()
28
+ ? args.coordinatorDaemonId.trim()
29
+ : undefined;
30
+ const events = drainPendingMeshCoordinatorEvents(meshId || undefined, coordinatorDaemonId);
31
+ return { success: true, events };
32
+ },
33
+
34
+ interactive_prompt_response: async (ctx: HighFamilyContext, args: any) => {
35
+ const sessionId = typeof args?.targetSessionId === 'string' && args.targetSessionId.trim()
36
+ ? args.targetSessionId.trim()
37
+ : typeof args?.sessionId === 'string' && args.sessionId.trim()
38
+ ? args.sessionId.trim()
39
+ : '';
40
+ if (!sessionId) return { success: false, error: 'targetSessionId required' };
41
+ const response = normalizeInteractivePromptResponse(args?.response ?? args);
42
+ const instance = ctx.deps.instanceManager.getInstance(sessionId);
43
+ if (!instance) return { success: false, error: `No running instance for session ${sessionId}` };
44
+ ctx.deps.instanceManager.sendEvent(sessionId, 'interactive_prompt_response', response);
45
+ return { success: true };
46
+ },
47
+ };