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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -316,10 +316,10 @@ function readInjected(value) {
316
316
  }
317
317
  function getDaemonBuildInfo() {
318
318
  if (cached) return cached;
319
- const commit = readInjected(true ? "1428e9d027beefe860a77f34dea34d202db80f00" : void 0) ?? "unknown";
320
- const commitShort = readInjected(true ? "1428e9d0" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
- const version = readInjected(true ? "0.9.82-rc.364" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
- const builtAt = readInjected(true ? "2026-06-24T00:05:49.524Z" : void 0);
319
+ const commit = readInjected(true ? "fe24f3fb158efc949e806b79bca2479b1c29d753" : void 0) ?? "unknown";
320
+ const commitShort = readInjected(true ? "fe24f3fb" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
+ const version = readInjected(true ? "0.9.82-rc.365" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
+ const builtAt = readInjected(true ? "2026-06-24T00:47:57.092Z" : void 0);
323
323
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
324
324
  return cached;
325
325
  }
@@ -2193,6 +2193,21 @@ var init_recent_activity = __esm({
2193
2193
  }
2194
2194
  });
2195
2195
 
2196
+ // src/system/hash.ts
2197
+ function sha256Hex(input) {
2198
+ return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
2199
+ }
2200
+ function shortHash(input, length = 16) {
2201
+ return sha256Hex(input).slice(0, length);
2202
+ }
2203
+ var import_node_crypto;
2204
+ var init_hash = __esm({
2205
+ "src/system/hash.ts"() {
2206
+ "use strict";
2207
+ import_node_crypto = require("crypto");
2208
+ }
2209
+ });
2210
+
2196
2211
  // src/mesh/mesh-host-ownership.ts
2197
2212
  function readObject(value) {
2198
2213
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
@@ -2470,7 +2485,7 @@ function normalizeManualHostAddress(hostAddress) {
2470
2485
  return normalized;
2471
2486
  }
2472
2487
  function tokenIdForManualPairing(token) {
2473
- return `tok_${(0, import_crypto3.createHash)("sha256").update(token).digest("hex").slice(0, 16)}`;
2488
+ return `tok_${shortHash(token)}`;
2474
2489
  }
2475
2490
  function normalizeTokenExpiry(value) {
2476
2491
  if (typeof value !== "string" || !value.trim()) return void 0;
@@ -2705,6 +2720,7 @@ var init_mesh_config = __esm({
2705
2720
  import_fs3 = require("fs");
2706
2721
  import_path3 = require("path");
2707
2722
  import_crypto3 = require("crypto");
2723
+ init_hash();
2708
2724
  init_config();
2709
2725
  init_repo_mesh_types();
2710
2726
  init_mesh_host_ownership();
@@ -7087,7 +7103,7 @@ function replaceLegacyCliCommandMcpArgs(command, args) {
7087
7103
  function resolveHermesCoordinatorHome(meshId, workspace) {
7088
7104
  const key = `${meshId || "mesh"}
7089
7105
  ${(0, import_node_path.resolve)(workspace || os4.tmpdir())}`;
7090
- const hash = (0, import_node_crypto.createHash)("sha256").update(key).digest("hex").slice(0, 16);
7106
+ const hash = shortHash(key);
7091
7107
  return (0, import_node_path.join)(os4.tmpdir(), `adhdev-hermes-mesh-coordinator-${hash}`);
7092
7108
  }
7093
7109
  function resolveMcpConfigPath(configPath, workspace) {
@@ -7296,16 +7312,16 @@ async function execUnderPty(command, args, options = {}) {
7296
7312
  });
7297
7313
  });
7298
7314
  }
7299
- var import_node_crypto, import_node_fs3, os4, import_session_host_core, import_node_path, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH;
7315
+ var import_node_fs3, os4, import_session_host_core, import_node_path, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH;
7300
7316
  var init_mesh_coordinator = __esm({
7301
7317
  "src/commands/mesh-coordinator.ts"() {
7302
7318
  "use strict";
7303
- import_node_crypto = require("crypto");
7304
7319
  import_node_fs3 = require("fs");
7305
7320
  os4 = __toESM(require("os"));
7306
7321
  import_session_host_core = require("@adhdev/session-host-core");
7307
7322
  import_node_path = require("path");
7308
7323
  init_logger();
7324
+ init_hash();
7309
7325
  DEFAULT_SERVER_NAME = "adhdev-mesh";
7310
7326
  DEFAULT_ADHDEV_MCP_COMMAND = "adhdev";
7311
7327
  HERMES_CLI_TYPE = "hermes-cli";
@@ -8174,6 +8190,46 @@ function classifyDirectDispatch(params) {
8174
8190
  const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !liveStaleReason);
8175
8191
  return { ledgerOnlyStaleReason, isFreshUnacknowledged };
8176
8192
  }
8193
+ function buildLedgerDirectDispatchRecord(dispatch, ctx) {
8194
+ const taskId = directDispatchTaskId(dispatch);
8195
+ const terminal = ctx.terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8196
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8197
+ const live = sessionStatusFromNodes(ctx.nodes, dispatch.nodeId, dispatch.sessionId);
8198
+ const status = terminalStatus || live.status || "assigned";
8199
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8200
+ const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8201
+ status,
8202
+ isTerminalRow: terminalRow,
8203
+ hasTerminalStatus: Boolean(terminalStatus),
8204
+ liveStatus: live.status,
8205
+ liveStaleReason: live.staleReason,
8206
+ dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8207
+ });
8208
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8209
+ const { title, summary } = summarizeMessage(message);
8210
+ const record = {
8211
+ taskId,
8212
+ source: "direct",
8213
+ status,
8214
+ nodeId: dispatch.nodeId,
8215
+ sessionId: dispatch.sessionId,
8216
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8217
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8218
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary,
8219
+ message,
8220
+ taskMode: readString6(dispatch.payload?.taskMode),
8221
+ createdAt: dispatch.timestamp,
8222
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
8223
+ dispatchedAt: dispatch.timestamp,
8224
+ elapsedMs: elapsedSince(dispatch.timestamp, ctx.now),
8225
+ terminal: terminalRow,
8226
+ terminalKind: terminal?.kind,
8227
+ terminalAt: terminal?.timestamp,
8228
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
8229
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8230
+ };
8231
+ return { record, terminalRow };
8232
+ }
8177
8233
  function buildMeshActiveWorkSummary(activeWork) {
8178
8234
  const statusCounts = {
8179
8235
  pending: 0,
@@ -8279,49 +8335,13 @@ function buildMeshActiveWork(opts) {
8279
8335
  const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8280
8336
  const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
8281
8337
  for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
8282
- const taskId = directDispatchTaskId(dispatch);
8283
- if (dbTaskIds.has(taskId)) continue;
8284
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8285
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8286
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
8287
- const status = terminalStatus || live.status || "assigned";
8288
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8289
- const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8290
- status,
8291
- isTerminalRow: terminalRow,
8292
- hasTerminalStatus: Boolean(terminalStatus),
8293
- liveStatus: live.status,
8294
- liveStaleReason: live.staleReason,
8295
- dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8296
- });
8297
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8298
- const { title, summary: summary2 } = summarizeMessage(message);
8299
- const record = {
8300
- taskId,
8301
- source: "direct",
8302
- status,
8303
- nodeId: dispatch.nodeId,
8304
- sessionId: dispatch.sessionId,
8305
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8306
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8307
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
8308
- message,
8309
- taskMode: readString6(dispatch.payload?.taskMode),
8310
- createdAt: dispatch.timestamp,
8311
- updatedAt: terminal?.timestamp || dispatch.timestamp,
8312
- dispatchedAt: dispatch.timestamp,
8313
- elapsedMs: elapsedSince(dispatch.timestamp, now),
8314
- terminal: terminalRow,
8315
- terminalKind: terminal?.kind,
8316
- terminalAt: terminal?.timestamp,
8317
- staleReason: live.staleReason || ledgerOnlyStaleReason,
8318
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8319
- };
8338
+ if (dbTaskIds.has(directDispatchTaskId(dispatch))) continue;
8339
+ const { record, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
8320
8340
  if (terminalRow) {
8321
8341
  terminalDirectWork.push(record);
8322
8342
  if (opts.includeTerminalDirect !== true) continue;
8323
8343
  }
8324
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
8344
+ if (record.staleReason && !terminalRow) {
8325
8345
  staleDirectWork.push(record);
8326
8346
  continue;
8327
8347
  }
@@ -8331,48 +8351,12 @@ function buildMeshActiveWork(opts) {
8331
8351
  const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8332
8352
  const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
8333
8353
  for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
8334
- const taskId = directDispatchTaskId(dispatch);
8335
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8336
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8337
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
8338
- const status = terminalStatus || live.status || "assigned";
8339
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8340
- const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8341
- status,
8342
- isTerminalRow: terminalRow,
8343
- hasTerminalStatus: Boolean(terminalStatus),
8344
- liveStatus: live.status,
8345
- liveStaleReason: live.staleReason,
8346
- dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8347
- });
8348
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8349
- const { title, summary: summary2 } = summarizeMessage(message);
8350
- const record = {
8351
- taskId,
8352
- source: "direct",
8353
- status,
8354
- nodeId: dispatch.nodeId,
8355
- sessionId: dispatch.sessionId,
8356
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8357
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8358
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
8359
- message,
8360
- taskMode: readString6(dispatch.payload?.taskMode),
8361
- createdAt: dispatch.timestamp,
8362
- updatedAt: terminal?.timestamp || dispatch.timestamp,
8363
- dispatchedAt: dispatch.timestamp,
8364
- elapsedMs: elapsedSince(dispatch.timestamp, now),
8365
- terminal: terminalRow,
8366
- terminalKind: terminal?.kind,
8367
- terminalAt: terminal?.timestamp,
8368
- staleReason: live.staleReason || ledgerOnlyStaleReason,
8369
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8370
- };
8354
+ const { record, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
8371
8355
  if (terminalRow) {
8372
8356
  terminalDirectWork.push(record);
8373
8357
  if (opts.includeTerminalDirect !== true) continue;
8374
8358
  }
8375
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
8359
+ if (record.staleReason && !terminalRow) {
8376
8360
  staleDirectWork.push(record);
8377
8361
  continue;
8378
8362
  }
@@ -34739,6 +34723,9 @@ var lowFamilyRegistry = new Map(
34739
34723
  })
34740
34724
  );
34741
34725
 
34726
+ // src/commands/med-family/cli-agent.ts
34727
+ init_dist();
34728
+
34742
34729
  // src/commands/cli-manager.ts
34743
34730
  var os21 = __toESM(require("os"));
34744
34731
  var path27 = __toESM(require("path"));
@@ -34752,6 +34739,7 @@ init_config();
34752
34739
  init_state_store();
34753
34740
  init_workspaces();
34754
34741
  init_recent_activity();
34742
+ init_hash();
34755
34743
  init_coordinator_registry();
34756
34744
  init_summary_metadata();
34757
34745
 
@@ -41145,7 +41133,7 @@ function hasConfigOverride(args, key) {
41145
41133
  function ensureEmptyDelegatedMcpConfig(workspace) {
41146
41134
  const baseDir = path27.join(os21.tmpdir(), "adhdev-delegated-agent-empty-mcp");
41147
41135
  (0, import_fs15.mkdirSync)(baseDir, { recursive: true });
41148
- const workspaceHash = crypto5.createHash("sha256").update(path27.resolve(workspace || os21.tmpdir())).digest("hex").slice(0, 16);
41136
+ const workspaceHash = shortHash(path27.resolve(workspace || os21.tmpdir()));
41149
41137
  const filePath = path27.join(baseDir, `${workspaceHash}.json`);
41150
41138
  (0, import_fs15.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
41151
41139
  return filePath;
@@ -42113,6 +42101,156 @@ Run 'adhdev doctor' for detailed diagnostics.`
42113
42101
  }
42114
42102
  };
42115
42103
 
42104
+ // src/commands/med-family/cli-agent.ts
42105
+ init_state_store();
42106
+ init_recent_activity();
42107
+ init_mesh_events_utils();
42108
+ var cliAgentHandlers = {
42109
+ launch_cli: async (ctx, args) => {
42110
+ const launchResult = await ctx.deps.cliManager.handleCliCommand("launch_cli", args);
42111
+ const meshNodeId = readStringValue(args?.settings?.meshNodeId);
42112
+ const meshId = readStringValue(args?.settings?.meshNodeFor);
42113
+ if (meshNodeId && meshId && launchResult?.success !== false) {
42114
+ try {
42115
+ const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
42116
+ const meshObj = getMesh2(meshId) ?? ctx.getCachedInlineMesh(meshId);
42117
+ const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, meshNodeId)) : void 0;
42118
+ const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
42119
+ if (bootstrapStatus === "running") {
42120
+ return { success: true, ...launchResult, bootstrapPending: true };
42121
+ }
42122
+ } catch {
42123
+ }
42124
+ }
42125
+ return launchResult;
42126
+ },
42127
+ stop_cli: async (ctx, args) => {
42128
+ return ctx.deps.cliManager.handleCliCommand("stop_cli", args);
42129
+ },
42130
+ set_cli_view_mode: async (ctx, args) => {
42131
+ return ctx.deps.cliManager.handleCliCommand("set_cli_view_mode", args);
42132
+ },
42133
+ record_provider_pty: async (ctx, args) => {
42134
+ return ctx.deps.cliManager.handleCliCommand("record_provider_pty", args);
42135
+ },
42136
+ agent_command: async (ctx, args) => {
42137
+ {
42138
+ const dispatchSessionId = readStringValue(args?.targetSessionId, args?.sessionId, args?.instanceId);
42139
+ const dispatchMeshContext = args?.meshContext;
42140
+ if (dispatchSessionId && dispatchMeshContext) {
42141
+ try {
42142
+ const inst = ctx.deps.instanceManager.getInstance(dispatchSessionId);
42143
+ if (inst && typeof inst.updateSettings === "function") {
42144
+ const stamp = buildMeshWorkerRelayStamp(
42145
+ inst.getState?.()?.settings,
42146
+ {
42147
+ meshId: dispatchMeshContext.meshId,
42148
+ nodeId: dispatchMeshContext.nodeId,
42149
+ coordinatorDaemonId: dispatchMeshContext.coordinatorDaemonId,
42150
+ // Session-level anchor: preserved across the P2P dispatch to a
42151
+ // remote worker so its completion echoes back to the right session.
42152
+ coordinatorSessionId: dispatchMeshContext.coordinatorSessionId
42153
+ }
42154
+ );
42155
+ if (stamp) inst.updateSettings(stamp);
42156
+ }
42157
+ } catch {
42158
+ }
42159
+ }
42160
+ }
42161
+ const agentResult = await ctx.deps.cliManager.handleCliCommand("agent_command", args);
42162
+ const meshCtx = args?.meshContext;
42163
+ const dispatchNodeId = readStringValue(meshCtx?.nodeId);
42164
+ const dispatchMeshId = readStringValue(meshCtx?.meshId);
42165
+ if (dispatchNodeId && dispatchMeshId && agentResult?.success !== false) {
42166
+ try {
42167
+ const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
42168
+ const meshObj = getMesh2(dispatchMeshId) ?? ctx.getCachedInlineMesh(dispatchMeshId);
42169
+ const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, dispatchNodeId)) : void 0;
42170
+ const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
42171
+ if (bootstrapStatus === "running") {
42172
+ return {
42173
+ success: true,
42174
+ ...agentResult,
42175
+ dispatchAcknowledgementRisk: true,
42176
+ dispatchAcknowledgementRiskReason: "bootstrap_still_running",
42177
+ nextAction: "Wait for worktree_bootstrap_complete event before dispatching work to this node."
42178
+ };
42179
+ }
42180
+ } catch {
42181
+ }
42182
+ }
42183
+ return agentResult;
42184
+ },
42185
+ // ─── Logs ───
42186
+ list_saved_sessions: async (ctx, args) => {
42187
+ const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
42188
+ const kind = args?.kind === "acp" ? "acp" : "cli";
42189
+ if (!providerType) {
42190
+ return { success: false, error: "providerType required" };
42191
+ }
42192
+ const wantsAll = args?.all === true;
42193
+ const offset = wantsAll ? 0 : Math.max(0, Number(args?.offset) || 0);
42194
+ const limit = wantsAll ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.min(100, Number(args?.limit) || 30));
42195
+ const requestedWorkspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
42196
+ const requestedProviderSessionId = typeof args?.providerSessionId === "string" ? args.providerSessionId.trim() : typeof args?.activeProviderSessionId === "string" ? args.activeProviderSessionId.trim() : "";
42197
+ const providerMeta = ctx.deps.providerLoader.resolve?.(providerType) || ctx.deps.providerLoader.getMeta(providerType);
42198
+ const { sessions: historySessions, hasMore, source } = listProviderHistorySessions(providerType, {
42199
+ canonicalHistory: providerMeta?.nativeHistory,
42200
+ offset,
42201
+ limit,
42202
+ historyBehavior: providerMeta?.historyBehavior,
42203
+ scripts: providerMeta?.scripts
42204
+ });
42205
+ const state = loadState();
42206
+ const savedSessions = getSavedProviderSessions(state, { providerType, kind });
42207
+ const recentSessions = getRecentActivity(state, 200).filter((entry) => entry.providerType === providerType && entry.kind === kind && entry.providerSessionId);
42208
+ const savedSessionById = new Map(savedSessions.map((entry) => [entry.providerSessionId, entry]));
42209
+ const recentSessionById = new Map(recentSessions.map((entry) => [entry.providerSessionId, entry]));
42210
+ const canResumeById = supportsExplicitSessionResume(providerMeta?.resume);
42211
+ return {
42212
+ success: true,
42213
+ sessions: historySessions.map((session) => {
42214
+ const saved = savedSessionById.get(session.historySessionId);
42215
+ const recent = recentSessionById.get(session.historySessionId);
42216
+ const workspace = saved?.workspace || recent?.workspace || session.workspace || (requestedWorkspace && requestedProviderSessionId === session.historySessionId ? requestedWorkspace : void 0);
42217
+ return {
42218
+ id: session.historySessionId,
42219
+ providerSessionId: session.historySessionId,
42220
+ providerType,
42221
+ providerName: saved?.providerName || recent?.providerName || providerType,
42222
+ kind: saved?.kind || recent?.kind || kind,
42223
+ title: saved?.title || recent?.title || session.sessionTitle || session.preview || providerType,
42224
+ workspace,
42225
+ summaryMetadata: saved?.summaryMetadata || recent?.summaryMetadata,
42226
+ preview: session.preview,
42227
+ messageCount: session.messageCount,
42228
+ firstMessageAt: session.firstMessageAt,
42229
+ lastMessageAt: session.lastMessageAt,
42230
+ canResume: !!workspace && canResumeById,
42231
+ historySource: session.source,
42232
+ sourcePath: session.sourcePath,
42233
+ sourceMtimeMs: session.sourceMtimeMs
42234
+ };
42235
+ }),
42236
+ hasMore,
42237
+ source
42238
+ };
42239
+ },
42240
+ // ─── restart_session: IDE / CLI / ACP unified ───
42241
+ restart_session: async (ctx, args) => {
42242
+ const targetType = args?.cliType || args?.agentType || args?.ideType;
42243
+ if (!targetType) throw new Error("cliType or ideType required");
42244
+ const isIde = ctx.deps.cdpManagers.has(targetType) || ctx.deps.providerLoader.getMeta(targetType)?.category === "ide";
42245
+ if (isIde) {
42246
+ await ctx.stopIde(targetType, true);
42247
+ const launchResult = await ctx.launchIde({ ideType: targetType, enableCdp: true, workspace: args?.workspace });
42248
+ return { success: true, restarted: true, ideType: targetType, launch: launchResult };
42249
+ }
42250
+ return ctx.deps.cliManager.handleCliCommand("restart_session", args);
42251
+ }
42252
+ };
42253
+
42116
42254
  // src/launch.ts
42117
42255
  var import_child_process9 = require("child_process");
42118
42256
  var net = __toESM(require("net"));
@@ -45938,12 +46076,1342 @@ function getAvailableIdeIds() {
45938
46076
  return getProviderLoader().getAvailableIdeTypes();
45939
46077
  }
45940
46078
 
45941
- // src/commands/router.ts
46079
+ // src/commands/med-family/ide.ts
45942
46080
  init_config();
45943
46081
  init_state_store();
45944
46082
  init_workspaces();
45945
46083
  init_recent_activity();
45946
46084
  init_cli_detector();
46085
+ init_logger();
46086
+ async function launchIde(ctx, args) {
46087
+ const ideKey = args?.ideId || args?.ideType;
46088
+ const resolvedWorkspace = resolveIdeLaunchWorkspace(
46089
+ {
46090
+ workspace: args?.workspace,
46091
+ workspaceId: args?.workspaceId,
46092
+ useDefaultWorkspace: args?.useDefaultWorkspace
46093
+ },
46094
+ loadConfig()
46095
+ );
46096
+ const launchArgs = {
46097
+ ideId: ideKey,
46098
+ workspace: resolvedWorkspace,
46099
+ newWindow: args?.newWindow
46100
+ };
46101
+ LOG.info("LaunchIDE", `target=${ideKey || "auto"}`);
46102
+ const result = await launchWithCdp(launchArgs);
46103
+ if (result.success && result.port && result.ideId && !ctx.deps.cdpManagers.has(result.ideId)) {
46104
+ const logFn = ctx.deps.getCdpLogFn ? ctx.deps.getCdpLogFn(result.ideId) : LOG.forComponent(`CDP:${result.ideId}`).asLogFn();
46105
+ const provider = ctx.deps.providerLoader.getMeta(result.ideId);
46106
+ const manager = new DaemonCdpManager(result.port, logFn, void 0, provider?.targetFilter);
46107
+ const connected = await manager.connect();
46108
+ if (connected) {
46109
+ registerExtensionProviders(ctx.deps.providerLoader, manager, result.ideId);
46110
+ ctx.deps.cdpManagers.set(result.ideId, manager);
46111
+ LOG.info("CDP", `Connected: ${result.ideId} (port ${result.port})`);
46112
+ LOG.info("CDP", `${ctx.deps.cdpManagers.size} IDE(s) connected`);
46113
+ ctx.deps.onCdpManagerCreated?.(result.ideId, manager);
46114
+ }
46115
+ }
46116
+ ctx.deps.onIdeConnected?.();
46117
+ try {
46118
+ const results = await detectIDEs(ctx.deps.providerLoader);
46119
+ ctx.deps.detectedIdes.value = results;
46120
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
46121
+ } catch {
46122
+ }
46123
+ if (result.success && resolvedWorkspace) {
46124
+ try {
46125
+ const next = appendRecentActivity(loadState(), {
46126
+ kind: "ide",
46127
+ providerType: result.ideId || ideKey,
46128
+ providerName: result.ideId || ideKey,
46129
+ workspace: resolvedWorkspace,
46130
+ title: result.ideId || ideKey
46131
+ });
46132
+ saveState(next);
46133
+ } catch {
46134
+ }
46135
+ } else if (result.success && (result.ideId || ideKey)) {
46136
+ try {
46137
+ saveState(appendRecentActivity(loadState(), {
46138
+ kind: "ide",
46139
+ providerType: result.ideId || ideKey,
46140
+ providerName: result.ideId || ideKey,
46141
+ title: result.ideId || ideKey
46142
+ }));
46143
+ } catch {
46144
+ }
46145
+ }
46146
+ return { ...result };
46147
+ }
46148
+ var ideHandlers = {
46149
+ // ─── IDE stop ───
46150
+ stop_ide: async (ctx, args) => {
46151
+ const ideType = args?.ideType;
46152
+ if (!ideType) throw new Error("ideType required");
46153
+ const killProcess = args?.killProcess !== false;
46154
+ await ctx.stopIde(ideType, killProcess);
46155
+ try {
46156
+ const results = await detectIDEs(ctx.deps.providerLoader);
46157
+ ctx.deps.detectedIdes.value = results;
46158
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
46159
+ } catch {
46160
+ }
46161
+ return { success: true, ideType, stopped: true, processKilled: killProcess };
46162
+ },
46163
+ // ─── IDE restart ───
46164
+ restart_ide: async (ctx, args) => {
46165
+ const ideType = args?.ideType;
46166
+ if (!ideType) throw new Error("ideType required");
46167
+ await ctx.stopIde(ideType, true);
46168
+ const launchResult = await ctx.launchIde({ ideType, enableCdp: true, workspace: args?.workspace });
46169
+ return { success: true, ideType, restarted: true, launch: launchResult };
46170
+ },
46171
+ // ─── IDE launch + CDP connect ───
46172
+ launch_ide: async (ctx, args) => {
46173
+ return launchIde(ctx, args);
46174
+ },
46175
+ // ─── Detect providers ───
46176
+ detect_provider: async (ctx, args) => {
46177
+ const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : "";
46178
+ if (!providerType) return { success: false, error: "providerType is required" };
46179
+ const normalizedType = ctx.deps.providerLoader.resolveAlias(providerType);
46180
+ const provider = ctx.deps.providerLoader.getByAlias(providerType);
46181
+ if (!provider) return { success: false, error: `Provider not found: ${providerType}` };
46182
+ if (provider.category !== "cli" && provider.category !== "acp") {
46183
+ return { success: false, error: `Provider detection is only supported for CLI/ACP providers: ${providerType}` };
46184
+ }
46185
+ if (!ctx.deps.providerLoader.isMachineProviderEnabled(normalizedType)) {
46186
+ return { success: false, error: `Provider is disabled on this machine: ${providerType}` };
46187
+ }
46188
+ const detected = await detectCLI(normalizedType, ctx.deps.providerLoader, { includeVersion: false });
46189
+ ctx.deps.providerLoader.setCliDetectionResults([{
46190
+ id: normalizedType,
46191
+ installed: !!detected,
46192
+ path: detected?.path
46193
+ }], false);
46194
+ ctx.deps.onStatusChange?.();
46195
+ return {
46196
+ success: true,
46197
+ providerType: normalizedType,
46198
+ detected: !!detected,
46199
+ path: detected?.path || null
46200
+ };
46201
+ },
46202
+ // ─── Detect IDEs ───
46203
+ detect_ides: async (ctx, _args) => {
46204
+ const results = await detectIDEs(ctx.deps.providerLoader);
46205
+ ctx.deps.detectedIdes.value = results;
46206
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
46207
+ return { success: true, detectedInfo: results };
46208
+ }
46209
+ };
46210
+
46211
+ // src/commands/med-family/mesh-crud.ts
46212
+ init_dist();
46213
+ init_mesh_host_ownership();
46214
+ init_mesh_events();
46215
+ init_config();
46216
+ var meshCrudHandlers = {
46217
+ list_meshes: async (_ctx, _args) => {
46218
+ try {
46219
+ const { listMeshes: listMeshes2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46220
+ return { success: true, meshes: listMeshes2() };
46221
+ } catch (e) {
46222
+ return { success: false, error: e.message };
46223
+ }
46224
+ },
46225
+ get_mesh: async (ctx, args) => {
46226
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46227
+ if (!meshId) return { success: false, error: "meshId required" };
46228
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46229
+ if (!meshRecord?.mesh) return { success: false, error: "Mesh not found" };
46230
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
46231
+ const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
46232
+ const directTruth = await hydrateInlineMeshDirectTruth({
46233
+ mesh: meshRecord.mesh,
46234
+ meshSource: meshRecord.source,
46235
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
46236
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
46237
+ statusInstanceId: ctx.deps.statusInstanceId,
46238
+ localMachineId: loadConfig().machineId || "",
46239
+ probeRemotePeers,
46240
+ probeCache: ctx.meshGitProbeCache
46241
+ });
46242
+ const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
46243
+ const sourceOfTruth = {
46244
+ membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
46245
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
46246
+ directPeerTruth: {
46247
+ required: requireDirectPeerTruth,
46248
+ satisfied: directTruthSatisfied,
46249
+ directEvidenceCount: directTruth.directEvidenceCount,
46250
+ localConfirmedCount: directTruth.localConfirmedCount,
46251
+ peerAttemptedCount: directTruth.peerAttemptedCount,
46252
+ peerConfirmedCount: directTruth.peerConfirmedCount,
46253
+ unavailableNodeIds: directTruth.unavailableNodeIds
46254
+ }
46255
+ };
46256
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
46257
+ return {
46258
+ success: false,
46259
+ code: "mesh_direct_peer_truth_unavailable",
46260
+ error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.",
46261
+ sourceOfTruth
46262
+ };
46263
+ }
46264
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
46265
+ },
46266
+ create_mesh: async (_ctx, args) => {
46267
+ const name = typeof args?.name === "string" ? args.name.trim() : "";
46268
+ const repoIdentity = typeof args?.repoIdentity === "string" ? args.repoIdentity.trim() : "";
46269
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === "string" ? args.repoRemoteUrl.trim() : void 0;
46270
+ const defaultBranch = typeof args?.defaultBranch === "string" ? args.defaultBranch.trim() : void 0;
46271
+ if (!name) return { success: false, error: "name required" };
46272
+ try {
46273
+ const { createMesh: createMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46274
+ const meshHost = args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost) ? args.meshHost : void 0;
46275
+ const mesh = createMesh2({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
46276
+ return { success: true, mesh };
46277
+ } catch (e) {
46278
+ return { success: false, error: e.message };
46279
+ }
46280
+ },
46281
+ update_mesh: async (ctx, args) => {
46282
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46283
+ if (!meshId) return { success: false, error: "meshId required" };
46284
+ try {
46285
+ const { updateMesh: updateMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46286
+ const patch = {};
46287
+ if (typeof args?.name === "string") patch.name = args.name;
46288
+ if (typeof args?.defaultBranch === "string") patch.defaultBranch = args.defaultBranch;
46289
+ if (args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy)) patch.policy = args.policy;
46290
+ if (args?.coordinator && typeof args.coordinator === "object" && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
46291
+ if (args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
46292
+ if (!Object.keys(patch).length) return { success: false, error: "No updates provided" };
46293
+ const mesh = updateMesh2(meshId, patch);
46294
+ if (!mesh) return { success: false, error: "Mesh not found" };
46295
+ ctx.inlineMeshCache.set(meshId, mesh);
46296
+ ctx.invalidateAggregateMeshStatus(meshId);
46297
+ return { success: true, mesh };
46298
+ } catch (e) {
46299
+ return { success: false, error: e.message };
46300
+ }
46301
+ },
46302
+ delete_mesh: async (_ctx, args) => {
46303
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46304
+ if (!meshId) return { success: false, error: "meshId required" };
46305
+ try {
46306
+ const { deleteMesh: deleteMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46307
+ const deleted = deleteMesh2(meshId);
46308
+ return { success: true, deleted };
46309
+ } catch (e) {
46310
+ return { success: false, error: e.message };
46311
+ }
46312
+ },
46313
+ add_mesh_node: async (ctx, args) => {
46314
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46315
+ const workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
46316
+ if (!meshId) return { success: false, error: "meshId required" };
46317
+ if (!workspace) return { success: false, error: "workspace required" };
46318
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node addition");
46319
+ if (ownerFailure) return ownerFailure;
46320
+ try {
46321
+ const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46322
+ const providerPriority = Array.isArray(args?.providerPriority) ? args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean) : [];
46323
+ const readOnly = args?.readOnly === true;
46324
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
46325
+ const policy = {
46326
+ ...readOnly ? { readOnly: true } : {},
46327
+ ...providerPriority.length ? { providerPriority } : {},
46328
+ ...providerRoles.length ? { providerRoles } : {}
46329
+ };
46330
+ const role = normalizeMeshDaemonRole(args?.role);
46331
+ const daemonId = typeof args?.daemonId === "string" && args.daemonId.trim() ? args.daemonId.trim() : void 0;
46332
+ const machineId = typeof args?.machineId === "string" && args.machineId.trim() ? args.machineId.trim() : void 0;
46333
+ const repoRoot = typeof args?.repoRoot === "string" && args.repoRoot.trim() ? args.repoRoot.trim() : void 0;
46334
+ const node = addNode2(meshId, {
46335
+ workspace,
46336
+ ...repoRoot ? { repoRoot } : {},
46337
+ ...daemonId ? { daemonId } : {},
46338
+ ...machineId ? { machineId } : {},
46339
+ ...policy ? { policy } : {},
46340
+ ...role ? { role } : {}
46341
+ });
46342
+ if (!node) return { success: false, error: "Mesh not found" };
46343
+ ctx.invalidateAggregateMeshStatus(meshId);
46344
+ return { success: true, node };
46345
+ } catch (e) {
46346
+ return { success: false, error: e.message };
46347
+ }
46348
+ },
46349
+ update_mesh_node: async (ctx, args) => {
46350
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46351
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46352
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46353
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node update");
46354
+ if (ownerFailure) return ownerFailure;
46355
+ try {
46356
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46357
+ const policy = args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy) ? { ...args.policy } : {};
46358
+ if (Array.isArray(args?.providerPriority)) {
46359
+ const providerPriority = args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean);
46360
+ delete policy.provider_priority;
46361
+ if (providerPriority.length) {
46362
+ policy.providerPriority = providerPriority;
46363
+ } else {
46364
+ delete policy.providerPriority;
46365
+ }
46366
+ }
46367
+ if (Array.isArray(args?.providerRoles)) {
46368
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
46369
+ if (providerRoles.length) {
46370
+ policy.providerRoles = providerRoles;
46371
+ } else {
46372
+ delete policy.providerRoles;
46373
+ }
46374
+ }
46375
+ const patch = { policy };
46376
+ if (typeof args?.systemPrompt === "string") {
46377
+ const trimmed = args.systemPrompt.trim();
46378
+ patch.systemPrompt = trimmed || void 0;
46379
+ } else if (args?.systemPrompt === null) {
46380
+ patch.systemPrompt = void 0;
46381
+ }
46382
+ const node = updateNode2(meshId, nodeId, patch);
46383
+ if (!node) return { success: false, error: "Mesh node not found" };
46384
+ ctx.invalidateAggregateMeshStatus(meshId);
46385
+ return { success: true, node };
46386
+ } catch (e) {
46387
+ return { success: false, error: e.message };
46388
+ }
46389
+ },
46390
+ cleanup_mesh_sessions: async (ctx, args) => {
46391
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46392
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46393
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46394
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node removal");
46395
+ if (ownerFailure) return ownerFailure;
46396
+ try {
46397
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46398
+ const mesh = meshRecord?.mesh;
46399
+ if (!mesh) return { success: false, error: "Mesh not found" };
46400
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46401
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
46402
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
46403
+ const sessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : void 0;
46404
+ const result = await ctx.cleanupMeshSessions({
46405
+ meshId,
46406
+ nodeId,
46407
+ node,
46408
+ mode,
46409
+ sessionIds,
46410
+ dryRun: args?.dryRun === true,
46411
+ source: "mesh_cleanup_sessions"
46412
+ });
46413
+ return result;
46414
+ } catch (e) {
46415
+ return { success: false, error: e.message };
46416
+ }
46417
+ },
46418
+ remove_mesh_node: async (ctx, args) => {
46419
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46420
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46421
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46422
+ try {
46423
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46424
+ const mesh = meshRecord?.mesh;
46425
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46426
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
46427
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : "";
46428
+ const nodeMachineId = readMeshNodeMachineId(node) || "";
46429
+ const selfDaemonId = ctx.deps.statusInstanceId || "";
46430
+ const selfMachineId = (() => {
46431
+ try {
46432
+ return loadConfig().machineId || "";
46433
+ } catch {
46434
+ return "";
46435
+ }
46436
+ })();
46437
+ const isCoordinatorBaseNode = !!selfDaemonId && (nodeDaemonId === selfDaemonId || nodeMachineId === selfDaemonId) || !!selfMachineId && (nodeDaemonId === selfMachineId || nodeMachineId === selfMachineId);
46438
+ if (isCoordinatorBaseNode) {
46439
+ return {
46440
+ success: false,
46441
+ removed: false,
46442
+ code: "mesh_remove_coordinator_base_node_protected",
46443
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === "string" ? node.workspace : nodeId}'. It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
46444
+ recoveryHint: "Remove worktree clone nodes instead, or pass force:true only if you are intentionally tearing down this mesh and accept that the coordinator must be re-registered/restarted."
46445
+ };
46446
+ }
46447
+ }
46448
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
46449
+ args?.sessionCleanupMode ?? args?.session_cleanup_mode ?? mesh?.policy?.sessionCleanupOnNodeRemove
46450
+ );
46451
+ const explicitSessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
46452
+ let sessionCleanup;
46453
+ if (node && sessionCleanupMode !== "preserve") {
46454
+ sessionCleanup = await ctx.cleanupMeshSessions({
46455
+ meshId,
46456
+ nodeId,
46457
+ node,
46458
+ mode: sessionCleanupMode,
46459
+ ...explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {},
46460
+ source: "mesh_remove_node"
46461
+ });
46462
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
46463
+ }
46464
+ let worktreeCleanup;
46465
+ if (node?.isLocalWorktree) {
46466
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
46467
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch;
46468
+ if (isRemoteWorktree) {
46469
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "remove_mesh_node", {
46470
+ ...typeof args === "object" && args !== null ? args : {},
46471
+ _meshDirectDispatch: true
46472
+ });
46473
+ return forwarded ?? { success: false, error: "no response from remote node" };
46474
+ }
46475
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
46476
+ if (cleanupResult.success === false) {
46477
+ return {
46478
+ success: false,
46479
+ removed: false,
46480
+ code: cleanupResult.code,
46481
+ error: cleanupResult.error,
46482
+ recoveryHint: cleanupResult.recoveryHint,
46483
+ ...sessionCleanup ? { sessionCleanup } : {},
46484
+ worktreeCleanup: cleanupResult
46485
+ };
46486
+ }
46487
+ worktreeCleanup = cleanupResult;
46488
+ }
46489
+ let removed = false;
46490
+ if (meshRecord?.inline) {
46491
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
46492
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
46493
+ if (!removed && !node) removed = true;
46494
+ } else {
46495
+ const { removeNode: removeNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46496
+ removed = removeNode2(meshId, nodeId);
46497
+ if (!removed && !node) removed = true;
46498
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
46499
+ }
46500
+ if (removed) {
46501
+ try {
46502
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46503
+ appendLedgerEntry2(meshId, {
46504
+ kind: "node_removed",
46505
+ nodeId,
46506
+ payload: {
46507
+ worktree: !!node?.isLocalWorktree,
46508
+ sessionCleanupMode,
46509
+ workspace: typeof node?.workspace === "string" ? node.workspace : void 0,
46510
+ daemonId: typeof node?.daemonId === "string" ? node.daemonId : void 0,
46511
+ worktreeBranch: typeof node?.worktreeBranch === "string" ? node.worktreeBranch : void 0,
46512
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === "string" ? worktreeCleanup.fallback : void 0,
46513
+ forced: worktreeCleanup?.forced === true ? true : void 0,
46514
+ forceFallbackReason: typeof worktreeCleanup?.reason === "string" ? worktreeCleanup.reason : void 0
46515
+ }
46516
+ });
46517
+ } catch {
46518
+ }
46519
+ }
46520
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === "string" ? worktreeCleanup.residueWarning : void 0;
46521
+ return {
46522
+ success: true,
46523
+ removed,
46524
+ ...residueWarning ? { residueWarning } : {},
46525
+ ...sessionCleanup ? { sessionCleanup } : {},
46526
+ ...worktreeCleanup ? { worktreeCleanup } : {}
46527
+ };
46528
+ } catch (e) {
46529
+ return { success: false, error: e.message };
46530
+ }
46531
+ },
46532
+ clone_mesh_node: async (ctx, args) => {
46533
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46534
+ const sourceNodeId = typeof args?.sourceNodeId === "string" ? args.sourceNodeId.trim() : "";
46535
+ const branch = typeof args?.branch === "string" ? args.branch.trim() : "";
46536
+ const baseBranch = typeof args?.baseBranch === "string" ? args.baseBranch.trim() : void 0;
46537
+ if (!meshId) return { success: false, error: "meshId required" };
46538
+ if (!sourceNodeId) return { success: false, error: "sourceNodeId required" };
46539
+ if (!branch) return { success: false, error: "branch required" };
46540
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "worktree clone");
46541
+ if (ownerFailure) return ownerFailure;
46542
+ try {
46543
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46544
+ const mesh = meshRecord?.mesh;
46545
+ if (!mesh) return { success: false, error: "Mesh not found" };
46546
+ const sourceNode = mesh.nodes?.find((n) => meshNodeIdMatches(n, sourceNodeId));
46547
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
46548
+ const sourceDaemonId = typeof sourceNode.daemonId === "string" ? sourceNode.daemonId.trim() : void 0;
46549
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46550
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, "clone_mesh_node", {
46551
+ ...typeof args === "object" && args !== null ? args : {},
46552
+ _meshDirectDispatch: true
46553
+ });
46554
+ return forwarded ?? { success: false, error: "no response from remote node" };
46555
+ }
46556
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
46557
+ const { createWorktree: createWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
46558
+ const result = await createWorktree2({
46559
+ repoRoot,
46560
+ branch,
46561
+ baseBranch,
46562
+ meshName: mesh.name
46563
+ });
46564
+ let node;
46565
+ if (meshRecord.inline) {
46566
+ const { randomUUID: randomUUID15 } = await import("crypto");
46567
+ node = {
46568
+ id: `node_${randomUUID15().replace(/-/g, "")}`,
46569
+ workspace: result.worktreePath,
46570
+ repoRoot: result.worktreePath,
46571
+ daemonId: sourceNode.daemonId,
46572
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
46573
+ userOverrides: { ...sourceNode.userOverrides || {} },
46574
+ policy: { ...sourceNode.policy || {} },
46575
+ isLocalWorktree: true,
46576
+ worktreeBranch: result.branch,
46577
+ clonedFromNodeId: sourceNodeId
46578
+ };
46579
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46580
+ } else {
46581
+ const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46582
+ node = addNode2(meshId, {
46583
+ workspace: result.worktreePath,
46584
+ repoRoot: result.worktreePath,
46585
+ daemonId: sourceNode.daemonId,
46586
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
46587
+ userOverrides: { ...sourceNode.userOverrides || {} },
46588
+ isLocalWorktree: true,
46589
+ worktreeBranch: result.branch,
46590
+ clonedFromNodeId: sourceNodeId,
46591
+ policy: { ...sourceNode.policy || {} }
46592
+ });
46593
+ if (!node) return { success: false, error: "Failed to register worktree node" };
46594
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
46595
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
46596
+ ctx.invalidateAggregateMeshStatus(meshId);
46597
+ }
46598
+ const persistWorktreeSetupState = async (bootstrapState2) => {
46599
+ node.worktreeBootstrap = bootstrapState2;
46600
+ if (meshRecord.inline) {
46601
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46602
+ return;
46603
+ }
46604
+ try {
46605
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46606
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
46607
+ ctx.invalidateAggregateMeshStatus(meshId);
46608
+ } catch {
46609
+ }
46610
+ };
46611
+ const appendCloneLedger = async (initSubmodules2, bootstrapState2) => {
46612
+ try {
46613
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46614
+ appendLedgerEntry2(meshId, {
46615
+ kind: "node_cloned",
46616
+ nodeId: node.id,
46617
+ payload: {
46618
+ sourceNodeId,
46619
+ branch: result.branch,
46620
+ worktreePath: result.worktreePath,
46621
+ submodulesInitialized: initSubmodules2,
46622
+ worktreeBootstrap: {
46623
+ status: bootstrapState2.status,
46624
+ required: bootstrapState2.required,
46625
+ configSource: bootstrapState2.configSource,
46626
+ configSourceType: bootstrapState2.configSourceType,
46627
+ lastCommand: bootstrapState2.lastCommand,
46628
+ exitCode: bootstrapState2.exitCode
46629
+ }
46630
+ }
46631
+ });
46632
+ } catch {
46633
+ }
46634
+ };
46635
+ const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
46636
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
46637
+ const runningBootstrapState = {
46638
+ status: "running",
46639
+ required: loadedBootstrap.config?.required !== false,
46640
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
46641
+ configSourceType: loadedBootstrap.sourceType,
46642
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
46643
+ };
46644
+ await persistWorktreeSetupState(runningBootstrapState);
46645
+ const finishWorktreeSetup = async () => {
46646
+ let submodulesInitialized2 = false;
46647
+ if (initSubmodules) {
46648
+ try {
46649
+ const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
46650
+ await runGit3(
46651
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
46652
+ ["submodule", "update", "--init", "--recursive"],
46653
+ { timeoutMs: 12e4 }
46654
+ );
46655
+ submodulesInitialized2 = true;
46656
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
46657
+ if (sourceWorkspace) {
46658
+ try {
46659
+ const { runGit: rg } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
46660
+ const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
46661
+ const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
46662
+ const sourceStatusOut = await rg(sourceCtx, ["submodule", "status", "oss"], { timeoutMs: 1e4 });
46663
+ const sourceStatusLine = (typeof sourceStatusOut === "string" ? sourceStatusOut : sourceStatusOut?.stdout ?? "").trim();
46664
+ const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
46665
+ const sourceSha = sourceShaMatch?.[1];
46666
+ if (sourceSha) {
46667
+ const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
46668
+ const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
46669
+ const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
46670
+ if (worktreeOssSha !== sourceSha) {
46671
+ await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
46672
+ await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
46673
+ await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
46674
+ await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
46675
+ console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
46676
+ }
46677
+ }
46678
+ } catch (ossErr) {
46679
+ console.warn("[mesh] oss submodule sync to source HEAD failed (best-effort):", ossErr.message);
46680
+ }
46681
+ }
46682
+ } catch (subErr) {
46683
+ console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
46684
+ }
46685
+ }
46686
+ const bootstrapState2 = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
46687
+ await persistWorktreeSetupState(bootstrapState2);
46688
+ await appendCloneLedger(submodulesInitialized2, bootstrapState2);
46689
+ return { submodulesInitialized: submodulesInitialized2, bootstrapState: bootstrapState2 };
46690
+ };
46691
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8e3);
46692
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs) ? Math.min(Math.max(requestedSetupWaitMs, 0), 14e3) : 8e3;
46693
+ const setupPromise = finishWorktreeSetup();
46694
+ const setupResult = await Promise.race([
46695
+ setupPromise.then((value) => ({ completed: true, value })),
46696
+ new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
46697
+ ]);
46698
+ const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
46699
+ try {
46700
+ const durationMs = Date.now() - startedAtMs;
46701
+ const event = `worktree_${eventStatus2}`;
46702
+ const metadataEvent = {
46703
+ source: "clone_mesh_node_bootstrap",
46704
+ nodeId: node.id,
46705
+ status: eventStatus2,
46706
+ worktreePath: result.worktreePath,
46707
+ durationMs,
46708
+ bootstrapStatus: bootstrapState2.status,
46709
+ ...bootstrapState2.error ? { error: bootstrapState2.error } : {},
46710
+ ...bootstrapState2.exitCode !== void 0 ? { exitCode: bootstrapState2.exitCode } : {},
46711
+ ...extraPayload || {}
46712
+ };
46713
+ if (typeof ctx.deps.instanceManager?.getByCategory === "function") {
46714
+ const forwarded = handleMeshForwardEvent(
46715
+ { instanceManager: ctx.deps.instanceManager },
46716
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent }
46717
+ );
46718
+ if (forwarded?.success === true) return;
46719
+ }
46720
+ queuePendingMeshCoordinatorEvent({
46721
+ event,
46722
+ meshId,
46723
+ nodeLabel: node.id,
46724
+ nodeId: node.id,
46725
+ workspace: result.worktreePath,
46726
+ metadataEvent,
46727
+ queuedAt: Date.now()
46728
+ });
46729
+ } catch {
46730
+ }
46731
+ };
46732
+ const bootstrapStartedMs = Date.now();
46733
+ if (!setupResult.completed) {
46734
+ setupPromise.then(({ bootstrapState: bootstrapState2 }) => {
46735
+ emitBootstrapEvent("bootstrap_complete", bootstrapState2, bootstrapStartedMs);
46736
+ }).catch((error) => {
46737
+ const failedState = {
46738
+ ...runningBootstrapState,
46739
+ status: "failed",
46740
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
46741
+ error: error?.message || String(error)
46742
+ };
46743
+ void persistWorktreeSetupState(failedState);
46744
+ void appendCloneLedger(false, failedState);
46745
+ emitBootstrapEvent("bootstrap_failed", failedState, bootstrapStartedMs, { error: error?.message || String(error) });
46746
+ });
46747
+ return {
46748
+ success: true,
46749
+ async: true,
46750
+ status: "accepted",
46751
+ node,
46752
+ worktreePath: result.worktreePath,
46753
+ branch: result.branch,
46754
+ worktreeBootstrap: runningBootstrapState,
46755
+ worktreeSetup: {
46756
+ status: "running",
46757
+ setupWaitMs,
46758
+ message: "Worktree node is registered; submodule/bootstrap setup is continuing in the background."
46759
+ }
46760
+ };
46761
+ }
46762
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
46763
+ emitBootstrapEvent("bootstrap_complete", bootstrapState, bootstrapStartedMs);
46764
+ return {
46765
+ success: true,
46766
+ node,
46767
+ worktreePath: result.worktreePath,
46768
+ branch: result.branch,
46769
+ submodulesInitialized,
46770
+ worktreeBootstrap: bootstrapState
46771
+ };
46772
+ } catch (e) {
46773
+ return { success: false, error: e.message };
46774
+ }
46775
+ },
46776
+ retry_mesh_node_bootstrap: async (ctx, args) => {
46777
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46778
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46779
+ if (!meshId) return { success: false, error: "meshId required" };
46780
+ if (!nodeId) return { success: false, error: "nodeId required" };
46781
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "bootstrap retry");
46782
+ if (ownerFailure) return ownerFailure;
46783
+ try {
46784
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46785
+ const mesh = meshRecord?.mesh;
46786
+ if (!mesh) return { success: false, error: "Mesh not found" };
46787
+ const node = mesh.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46788
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
46789
+ if (!node.isLocalWorktree) return { success: false, error: "Node is not a local worktree node" };
46790
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
46791
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46792
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "retry_mesh_node_bootstrap", {
46793
+ ...typeof args === "object" && args !== null ? args : {},
46794
+ _meshDirectDispatch: true
46795
+ });
46796
+ return forwarded ?? { success: false, error: "no response from remote node" };
46797
+ }
46798
+ const currentBootstrap = node.worktreeBootstrap;
46799
+ if (currentBootstrap?.status === "running") {
46800
+ return { success: false, error: "Bootstrap is already running for this node" };
46801
+ }
46802
+ const worktreePath = node.workspace || node.repoRoot;
46803
+ if (!worktreePath) return { success: false, error: "Node has no workspace path" };
46804
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
46805
+ const runningState = {
46806
+ status: "running",
46807
+ required: loadedBootstrap.config?.required !== false,
46808
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
46809
+ configSourceType: loadedBootstrap.sourceType,
46810
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
46811
+ };
46812
+ const persistState = async (bootstrapState2) => {
46813
+ node.worktreeBootstrap = bootstrapState2;
46814
+ if (meshRecord.inline) {
46815
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46816
+ return;
46817
+ }
46818
+ try {
46819
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46820
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
46821
+ ctx.invalidateAggregateMeshStatus(meshId);
46822
+ } catch {
46823
+ }
46824
+ };
46825
+ await persistState(runningState);
46826
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
46827
+ await persistState(bootstrapState);
46828
+ return { success: true, bootstrapState };
46829
+ } catch (e) {
46830
+ return { success: false, error: e.message };
46831
+ }
46832
+ }
46833
+ };
46834
+
46835
+ // src/commands/med-family/mesh-host-pairing.ts
46836
+ init_mesh_host_ownership();
46837
+ var meshHostPairingHandlers = {
46838
+ get_mesh_host_pairing: async (ctx, args) => {
46839
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46840
+ if (!meshId) return { success: false, error: "meshId required" };
46841
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46842
+ const mesh = meshRecord?.mesh;
46843
+ if (!mesh) return { success: false, error: "Mesh not found" };
46844
+ const meshHost = resolveMeshHostStatus(mesh);
46845
+ const pairingStatus = meshHost.pairing?.status || "not_configured";
46846
+ return {
46847
+ success: true,
46848
+ code: pairingStatus === "not_configured" ? "mesh_host_pairing_not_configured" : "mesh_host_pairing_pending",
46849
+ meshId,
46850
+ hostAddress: meshHost.hostAddress,
46851
+ meshHost,
46852
+ manualPairing: {
46853
+ status: pairingStatus,
46854
+ joinImplemented: true,
46855
+ protocol: "standalone_command_direct_v1",
46856
+ description: "Standalone manual pairing can save address/token metadata, apply a host join over direct standalone command HTTP or injected mesh command dispatch, and check persisted status. P2P signaling remains outside this slice."
46857
+ }
46858
+ };
46859
+ },
46860
+ configure_mesh_host_pairing: async (ctx, args) => {
46861
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46862
+ const hostAddress = typeof args?.hostAddress === "string" ? args.hostAddress.trim() : "";
46863
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46864
+ if (!meshId) return { success: false, error: "meshId required" };
46865
+ if (!hostAddress || !token) return { success: false, error: "hostAddress and token required" };
46866
+ try {
46867
+ const { configureMeshHostPairing: configureMeshHostPairing2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46868
+ const configured = configureMeshHostPairing2(meshId, { hostAddress, token });
46869
+ if (!configured) return { success: false, error: "Mesh not found" };
46870
+ ctx.inlineMeshCache.set(meshId, configured.mesh);
46871
+ const meshHost = resolveMeshHostStatus(configured.mesh);
46872
+ return {
46873
+ success: true,
46874
+ code: "mesh_host_pairing_pending",
46875
+ meshId,
46876
+ hostAddress: configured.hostAddress,
46877
+ meshHost,
46878
+ manualPairing: {
46879
+ status: meshHost.pairing?.status || "pairing",
46880
+ joinImplemented: true,
46881
+ protocol: "standalone_command_direct_v1",
46882
+ description: "Manual Mesh Host pairing config was saved locally. Use join_mesh_host_pairing to apply it to the host. Raw token was not persisted."
46883
+ }
46884
+ };
46885
+ } catch (e) {
46886
+ return { success: false, code: "mesh_host_pairing_invalid", meshId, hostAddress, error: e.message };
46887
+ }
46888
+ },
46889
+ create_mesh_host_pairing_token: async (ctx, args) => {
46890
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46891
+ if (!meshId) return { success: false, error: "meshId required" };
46892
+ try {
46893
+ const { createMeshHostPairingToken: createMeshHostPairingToken2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46894
+ const created = createMeshHostPairingToken2(meshId, {
46895
+ token: typeof args?.token === "string" ? args.token : void 0,
46896
+ expiresAt: typeof args?.expiresAt === "string" ? args.expiresAt : void 0
46897
+ });
46898
+ if (!created) return { success: false, error: "Mesh not found" };
46899
+ ctx.inlineMeshCache.set(meshId, created.mesh);
46900
+ ctx.invalidateAggregateMeshStatus(meshId);
46901
+ return {
46902
+ success: true,
46903
+ code: "mesh_host_pairing_token_created",
46904
+ meshId,
46905
+ token: created.token,
46906
+ tokenId: created.tokenId,
46907
+ expiresAt: created.expiresAt,
46908
+ meshHost: resolveMeshHostStatus(created.mesh),
46909
+ warning: "Raw token is returned once and is not persisted; share it with member daemons over a trusted channel."
46910
+ };
46911
+ } catch (e) {
46912
+ return { success: false, code: "mesh_host_pairing_token_invalid", meshId, error: e.message };
46913
+ }
46914
+ },
46915
+ apply_mesh_host_join: async (ctx, args) => {
46916
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46917
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46918
+ const memberNode = args?.memberNode && typeof args.memberNode === "object" && !Array.isArray(args.memberNode) ? args.memberNode : null;
46919
+ if (!meshId) return { success: false, error: "meshId required" };
46920
+ if (!token || !memberNode) return { success: false, error: "token and memberNode required" };
46921
+ try {
46922
+ const { applyMeshHostJoinRequest: applyMeshHostJoinRequest2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46923
+ const applied = applyMeshHostJoinRequest2(meshId, {
46924
+ token,
46925
+ memberNode,
46926
+ memberMeshId: typeof args?.memberMeshId === "string" ? args.memberMeshId : void 0
46927
+ });
46928
+ if (!applied) return { success: false, error: "Mesh not found" };
46929
+ if (!applied.accepted) {
46930
+ return {
46931
+ success: false,
46932
+ code: "mesh_host_join_rejected",
46933
+ meshId,
46934
+ tokenId: applied.tokenId,
46935
+ meshHost: applied.meshHost ? resolveMeshHostStatus({ meshHost: applied.meshHost }) : void 0,
46936
+ error: applied.reason
46937
+ };
46938
+ }
46939
+ ctx.inlineMeshCache.set(meshId, applied.mesh);
46940
+ ctx.invalidateAggregateMeshStatus(meshId);
46941
+ try {
46942
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46943
+ appendLedgerEntry2(meshId, {
46944
+ kind: "node_joined",
46945
+ nodeId: applied.node.id,
46946
+ payload: { role: "member", tokenId: applied.tokenId, workspace: applied.node.workspace }
46947
+ });
46948
+ } catch {
46949
+ }
46950
+ return {
46951
+ success: true,
46952
+ code: "mesh_host_join_accepted",
46953
+ meshId,
46954
+ node: applied.node,
46955
+ tokenId: applied.tokenId,
46956
+ meshHost: resolveMeshHostStatus(applied.mesh)
46957
+ };
46958
+ } catch (e) {
46959
+ return { success: false, code: "mesh_host_join_failed", meshId, error: e.message };
46960
+ }
46961
+ },
46962
+ join_mesh_host_pairing: async (ctx, args) => {
46963
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46964
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46965
+ if (!meshId) return { success: false, error: "meshId required" };
46966
+ if (!token) return { success: false, error: "token required because raw pairing tokens are not persisted" };
46967
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46968
+ const mesh = meshRecord?.mesh;
46969
+ if (!mesh) return { success: false, error: "Mesh not found" };
46970
+ const meshHost = resolveMeshHostStatus(mesh);
46971
+ if (meshHost.role !== "member") {
46972
+ return { success: false, code: "mesh_host_join_not_member", meshId, meshHost, error: "join_mesh_host_pairing must run from a member daemon configured with a Mesh Host address/token." };
46973
+ }
46974
+ try {
46975
+ const { tokenIdForManualPairing: tokenIdForManualPairing2, markMeshHostPairingJoined: markMeshHostPairingJoined2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46976
+ const tokenId = tokenIdForManualPairing2(token);
46977
+ if (meshHost.pairing?.tokenId && meshHost.pairing.tokenId !== tokenId) {
46978
+ return { success: false, code: "mesh_host_join_rejected", meshId, tokenId, meshHost, error: "invalid pairing token" };
46979
+ }
46980
+ const memberNode = buildMemberJoinNode(mesh, args, ctx.deps.statusInstanceId);
46981
+ if (!memberNode) return { success: false, error: "member node metadata unavailable" };
46982
+ const hostMeshId = typeof args?.hostMeshId === "string" && args.hostMeshId.trim() ? args.hostMeshId.trim() : meshId;
46983
+ const hostDaemonId = typeof args?.hostDaemonId === "string" && args.hostDaemonId.trim() ? args.hostDaemonId.trim() : meshHost.hostDaemonId;
46984
+ let hostResult;
46985
+ let transport;
46986
+ if (hostDaemonId && ctx.deps.dispatchMeshCommand) {
46987
+ transport = "mesh_command_dispatch";
46988
+ hostResult = await ctx.deps.dispatchMeshCommand(hostDaemonId, "apply_mesh_host_join", {
46989
+ meshId: hostMeshId,
46990
+ token,
46991
+ memberMeshId: meshId,
46992
+ memberNode
46993
+ });
46994
+ } else if (meshHost.hostAddress) {
46995
+ transport = "standalone_http_command";
46996
+ const commandUrl = normalizeStandaloneHostCommandUrl(meshHost.hostAddress);
46997
+ const response = await fetch(commandUrl, {
46998
+ method: "POST",
46999
+ headers: { "Content-Type": "application/json" },
47000
+ body: JSON.stringify({ type: "apply_mesh_host_join", payload: { meshId: hostMeshId, token, memberMeshId: meshId, memberNode } })
47001
+ });
47002
+ hostResult = await response.json().catch(() => ({ success: false, error: `Host returned HTTP ${response.status}` }));
47003
+ if (!response.ok && hostResult?.success !== false) hostResult = { success: false, error: `Host returned HTTP ${response.status}` };
47004
+ } else {
47005
+ return {
47006
+ success: false,
47007
+ code: "mesh_host_join_transport_unavailable",
47008
+ meshId,
47009
+ meshHost,
47010
+ error: "No hostDaemonId dispatch path or hostAddress HTTP command path is available. P2P signaling join is not implemented in this slice."
47011
+ };
47012
+ }
47013
+ if (!hostResult?.success) {
47014
+ return { success: false, code: hostResult?.code || "mesh_host_join_rejected", meshId, meshHost, transport, error: hostResult?.error || "Mesh Host rejected join request", hostResult };
47015
+ }
47016
+ const joined = meshRecord.inline ? null : markMeshHostPairingJoined2(meshId, {
47017
+ tokenId: hostResult.tokenId || tokenId,
47018
+ hostDaemonId: hostResult.meshHost?.hostDaemonId || hostDaemonId,
47019
+ hostNodeId: hostResult.meshHost?.hostNodeId,
47020
+ joinedAt: hostResult.meshHost?.pairing?.joinedAt
47021
+ });
47022
+ if (joined) {
47023
+ ctx.inlineMeshCache.set(meshId, joined.mesh);
47024
+ ctx.invalidateAggregateMeshStatus(meshId);
47025
+ }
47026
+ return {
47027
+ success: true,
47028
+ code: "mesh_host_join_applied",
47029
+ meshId,
47030
+ hostMeshId,
47031
+ transport,
47032
+ node: hostResult.node,
47033
+ tokenId: hostResult.tokenId || tokenId,
47034
+ meshHost: joined ? resolveMeshHostStatus(joined.mesh) : { ...meshHost, pairing: { ...meshHost.pairing || {}, status: "paired", tokenId: hostResult.tokenId || tokenId } },
47035
+ hostResult,
47036
+ manualPairing: {
47037
+ status: "paired",
47038
+ joinImplemented: true,
47039
+ protocol: "standalone_command_direct_v1",
47040
+ description: "Mesh Host accepted the join and local member pairing status was marked paired. P2P runtime signaling remains outside this slice."
47041
+ }
47042
+ };
47043
+ } catch (e) {
47044
+ return { success: false, code: "mesh_host_join_failed", meshId, meshHost, error: e.message };
47045
+ }
47046
+ }
47047
+ };
47048
+
47049
+ // src/commands/med-family/mesh-queue.ts
47050
+ var meshQueueHandlers = {
47051
+ get_mesh_queue: async (_ctx, args) => {
47052
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47053
+ if (!meshId) return { success: false, error: "meshId required" };
47054
+ try {
47055
+ const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2, describeTaskDependencyState: describeTaskDependencyState2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
47056
+ const status = Array.isArray(args?.status) ? args.status.map((s2) => typeof s2 === "string" ? s2.trim() : "").filter(Boolean) : void 0;
47057
+ const rawQueue = getQueue2(meshId, { status });
47058
+ const statusById = new Map(getQueue2(meshId).map((task) => [task.id, task.status]));
47059
+ const queue = rawQueue.map((task) => Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? { ...task, ...describeTaskDependencyState2(task, statusById) } : task);
47060
+ const summary = getMeshQueueStats2(meshId);
47061
+ return {
47062
+ success: true,
47063
+ queue,
47064
+ summary,
47065
+ sourceOfTruth: {
47066
+ kind: "mesh_work_queue_file",
47067
+ activeStatuses: ["pending", "assigned"],
47068
+ historicalStatuses: ["completed", "failed", "cancelled"],
47069
+ notes: "pending/assigned are active work; completed/failed/cancelled are historical records."
47070
+ }
47071
+ };
47072
+ } catch (e) {
47073
+ return { success: false, error: e.message };
47074
+ }
47075
+ },
47076
+ cancel_mesh_queue_task: async (ctx, args) => {
47077
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47078
+ const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
47079
+ if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
47080
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue cancellation");
47081
+ if (ownerFailure) return ownerFailure;
47082
+ try {
47083
+ const { cancelTask: cancelTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
47084
+ const reason = typeof args?.reason === "string" ? args.reason : void 0;
47085
+ const task = cancelTask2(meshId, taskId, { reason });
47086
+ if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
47087
+ return { success: true, task };
47088
+ } catch (e) {
47089
+ return { success: false, error: e.message };
47090
+ }
47091
+ },
47092
+ requeue_mesh_queue_task: async (ctx, args) => {
47093
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47094
+ const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
47095
+ if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
47096
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue requeue");
47097
+ if (ownerFailure) return ownerFailure;
47098
+ try {
47099
+ const { requeueTask: requeueTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
47100
+ const task = requeueTask2(meshId, taskId, {
47101
+ reason: typeof args?.reason === "string" ? args.reason : void 0,
47102
+ targetNodeId: typeof args?.targetNodeId === "string" ? args.targetNodeId.trim() : void 0,
47103
+ targetSessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : void 0,
47104
+ clearTargetNode: args?.clearTargetNode === true,
47105
+ clearTargetSession: args?.clearTargetSession !== false
47106
+ });
47107
+ if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
47108
+ return { success: true, task };
47109
+ } catch (e) {
47110
+ return { success: false, error: e.message };
47111
+ }
47112
+ },
47113
+ trigger_mesh_queue: async (ctx, args) => {
47114
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47115
+ if (!meshId) return { success: false, error: "meshId required" };
47116
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue trigger");
47117
+ if (ownerFailure) return ownerFailure;
47118
+ try {
47119
+ const { triggerMeshQueue: triggerMeshQueue2, tryAssignQueueTask: tryAssignQueueTask2 } = await Promise.resolve().then(() => (init_mesh_events(), mesh_events_exports));
47120
+ const preferredNodeId = typeof args?.preferredNodeId === "string" ? args.preferredNodeId.trim() : "";
47121
+ if (preferredNodeId) {
47122
+ const cliInstances = ctx.deps.instanceManager.getByCategory("cli");
47123
+ const sorted = [...cliInstances].sort((a, b) => {
47124
+ const aSettings = a.getState().settings || {};
47125
+ const bSettings = b.getState().settings || {};
47126
+ const aNode = readStringValue(aSettings.meshNodeId, aSettings.nodeId);
47127
+ const bNode = readStringValue(bSettings.meshNodeId, bSettings.nodeId);
47128
+ return (aNode === preferredNodeId ? -1 : 0) - (bNode === preferredNodeId ? -1 : 0);
47129
+ });
47130
+ for (const inst of sorted) {
47131
+ const state = inst.getState();
47132
+ const settings = state.settings || {};
47133
+ const nodeId = readStringValue(settings.meshNodeId, settings.nodeId);
47134
+ if (!nodeId || nodeId !== preferredNodeId) continue;
47135
+ const meshNodeFor = readStringValue(settings.meshNodeFor);
47136
+ if (meshNodeFor !== meshId) continue;
47137
+ const status = (readStringValue(state.status) || "").toLowerCase();
47138
+ if (status !== "idle") continue;
47139
+ const sessionId = typeof state.instanceId === "string" ? state.instanceId : "";
47140
+ const providerType = readStringValue(state.type, settings.providerType) || "";
47141
+ if (sessionId && providerType) {
47142
+ tryAssignQueueTask2(ctx.deps, meshId, nodeId, sessionId, providerType);
47143
+ break;
47144
+ }
47145
+ }
47146
+ }
47147
+ const trigger = await triggerMeshQueue2(ctx.deps, meshId);
47148
+ return { success: true, trigger };
47149
+ } catch (e) {
47150
+ return { success: false, error: e.message };
47151
+ }
47152
+ }
47153
+ };
47154
+
47155
+ // src/commands/med-family/fast-forward.ts
47156
+ init_dist();
47157
+ init_mesh_fast_forward();
47158
+
47159
+ // src/mesh/mesh-init.ts
47160
+ var import_fs16 = require("fs");
47161
+ var import_path11 = require("path");
47162
+ var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
47163
+ var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
47164
+ var CANDIDATE_STALE_INPUTS = [
47165
+ "package-lock.json",
47166
+ "pnpm-lock.yaml",
47167
+ "yarn.lock",
47168
+ "bun.lockb",
47169
+ "Cargo.lock",
47170
+ "go.sum",
47171
+ "poetry.lock",
47172
+ "requirements.txt"
47173
+ ];
47174
+ function writeConfigFile(workspace, relativePath, config) {
47175
+ const target = (0, import_path11.join)(workspace, relativePath);
47176
+ (0, import_fs16.mkdirSync)((0, import_path11.dirname)(target), { recursive: true });
47177
+ (0, import_fs16.writeFileSync)(target, `${JSON.stringify(config, null, 2)}
47178
+ `, "utf-8");
47179
+ return target;
47180
+ }
47181
+ function suggestMeshWorktreeBootstrapConfig(workspace) {
47182
+ const commands = [];
47183
+ const hasPackageJson = (0, import_fs16.existsSync)((0, import_path11.join)(workspace, "package.json"));
47184
+ const hasNpmLock = (0, import_fs16.existsSync)((0, import_path11.join)(workspace, "package-lock.json"));
47185
+ if (hasPackageJson) {
47186
+ commands.push(
47187
+ hasNpmLock ? { command: "npm", args: ["ci"] } : { command: "npm", args: ["install"] }
47188
+ );
47189
+ }
47190
+ const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => (0, import_fs16.existsSync)((0, import_path11.join)(workspace, relative5)));
47191
+ if (!commands.length) {
47192
+ return { commands, staleInputs };
47193
+ }
47194
+ return {
47195
+ commands,
47196
+ staleInputs,
47197
+ suggestedConfig: {
47198
+ version: 1,
47199
+ enabled: true,
47200
+ runOnClone: true,
47201
+ required: false,
47202
+ commands,
47203
+ ...staleInputs.length ? { staleInputs } : {}
47204
+ }
47205
+ };
47206
+ }
47207
+ var PROVIDER_PRIORITY_PREFERENCE = ["claude-cli", "codex-cli", "gemini-cli"];
47208
+ function suggestNodeProviderPriority(detected) {
47209
+ const installed = detected.filter((cli) => cli.installed);
47210
+ const installedIds = installed.map((cli) => cli.id);
47211
+ const preferred = PROVIDER_PRIORITY_PREFERENCE.filter((id) => installedIds.includes(id));
47212
+ const rest = installedIds.filter((id) => !preferred.includes(id));
47213
+ const providerPriority = [...preferred, ...rest];
47214
+ return {
47215
+ providerPriority,
47216
+ installedProviders: installed.map((cli) => ({
47217
+ id: cli.id,
47218
+ displayName: cli.displayName,
47219
+ ...cli.version ? { version: cli.version } : {}
47220
+ }))
47221
+ };
47222
+ }
47223
+ function runMeshInit(mesh, workspace, detected, options = {}) {
47224
+ const write = options.write === true;
47225
+ const overwrite = options.overwrite === true;
47226
+ const refine = applyConfigSuggestion({
47227
+ workspace,
47228
+ relativePath: MESH_INIT_REFINE_CONFIG_PATH,
47229
+ existing: loadMeshRefineConfig(mesh, workspace).config,
47230
+ suggestedConfig: suggestMeshRefineConfig(mesh, workspace).suggestedConfig,
47231
+ validate: (config) => validateMeshRefineConfig(config, MESH_INIT_REFINE_CONFIG_PATH).valid,
47232
+ write,
47233
+ overwrite
47234
+ });
47235
+ const bootstrapSuggestion = suggestMeshWorktreeBootstrapConfig(workspace);
47236
+ const worktreeBootstrap = applyConfigSuggestion({
47237
+ workspace,
47238
+ relativePath: MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH,
47239
+ existing: loadMeshWorktreeBootstrapConfig(mesh, workspace).config,
47240
+ suggestedConfig: bootstrapSuggestion.suggestedConfig,
47241
+ validate: (config) => validateMeshWorktreeBootstrapConfig(config, MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH).valid,
47242
+ write,
47243
+ overwrite
47244
+ });
47245
+ const providers = suggestNodeProviderPriority(detected);
47246
+ return {
47247
+ success: true,
47248
+ workspace,
47249
+ dryRun: !write,
47250
+ refine,
47251
+ worktreeBootstrap,
47252
+ providers,
47253
+ note: write ? "Configs written to disk are the execution source of truth; suggestions are scaffold and only take effect once saved. providerPriority is a recommendation \u2014 apply it to node policy via clone/policy update." : "Dry-run: no files written. Re-run with write=true to persist the suggested configs. Heuristic suggestions never execute until saved as repo config."
47254
+ };
47255
+ }
47256
+ function applyConfigSuggestion(input) {
47257
+ const { workspace, relativePath, existing, suggestedConfig, validate, write, overwrite } = input;
47258
+ const absolute = (0, import_path11.join)(workspace, relativePath);
47259
+ if (existing !== void 0 && !overwrite) {
47260
+ return { path: absolute, relativePath, written: false, skippedReason: "already_exists", config: existing };
47261
+ }
47262
+ if (!suggestedConfig || !validate(suggestedConfig)) {
47263
+ return { path: absolute, relativePath, written: false, skippedReason: "no_suggestion" };
47264
+ }
47265
+ if (!write) {
47266
+ return { path: absolute, relativePath, written: false, config: suggestedConfig };
47267
+ }
47268
+ const writtenPath = writeConfigFile(workspace, relativePath, suggestedConfig);
47269
+ return { path: writtenPath, relativePath, written: true, config: suggestedConfig };
47270
+ }
47271
+
47272
+ // src/commands/med-family/fast-forward.ts
47273
+ init_cli_detector();
47274
+ var fastForwardHandlers = {
47275
+ mesh_init: async (ctx, args) => {
47276
+ const workspace = typeof args?.workspace === "string" && args.workspace.trim() ? args.workspace.trim() : process.cwd();
47277
+ const mesh = args?.inlineMesh || {};
47278
+ try {
47279
+ const detected = await detectCLIs(ctx.deps.providerLoader, { includeVersion: true });
47280
+ return { ...runMeshInit(mesh, workspace, detected, {
47281
+ write: args?.write === true,
47282
+ overwrite: args?.overwrite === true
47283
+ }) };
47284
+ } catch (e) {
47285
+ return { success: false, error: e?.message || String(e) };
47286
+ }
47287
+ },
47288
+ plan_mesh_refine_node: async (ctx, args) => {
47289
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47290
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
47291
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
47292
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47293
+ const mesh = meshRecord?.mesh;
47294
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
47295
+ if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
47296
+ return {
47297
+ success: true,
47298
+ dryRun: true,
47299
+ nodeId,
47300
+ workspace: node.workspace,
47301
+ validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
47302
+ mergeWillRun: false,
47303
+ cleanupWillRun: false
47304
+ };
47305
+ },
47306
+ fast_forward_mesh_node: async (ctx, args) => {
47307
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47308
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
47309
+ let workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
47310
+ let submoduleIgnorePaths = Array.isArray(args?.submoduleIgnorePaths) ? args.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0;
47311
+ let nodeDaemonId;
47312
+ let allowAutoPublishSubmoduleMainCommits = false;
47313
+ if (meshId && nodeId) {
47314
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47315
+ const mesh = meshRecord?.mesh;
47316
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
47317
+ if (!workspace) {
47318
+ workspace = typeof node?.workspace === "string" ? node.workspace.trim() : "";
47319
+ }
47320
+ if (!submoduleIgnorePaths && Array.isArray(node?.policy?.submoduleIgnorePaths)) {
47321
+ submoduleIgnorePaths = node.policy.submoduleIgnorePaths.filter((value) => typeof value === "string");
47322
+ }
47323
+ allowAutoPublishSubmoduleMainCommits = mesh?.policy?.allowAutoPublishSubmoduleMainCommits === true;
47324
+ nodeDaemonId = typeof node?.daemonId === "string" ? node.daemonId.trim() : void 0;
47325
+ }
47326
+ const selfDaemonId = ctx.deps.statusInstanceId;
47327
+ const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
47328
+ if (isRemote && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
47329
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "fast_forward_mesh_node", {
47330
+ ...typeof args === "object" && args !== null ? args : {},
47331
+ workspace,
47332
+ _meshDirectDispatch: true
47333
+ });
47334
+ return forwarded ?? { success: false, error: "no response from remote node" };
47335
+ }
47336
+ const result = await fastForwardMeshNode({
47337
+ meshId: meshId || void 0,
47338
+ nodeId: nodeId || void 0,
47339
+ workspace,
47340
+ branch: typeof args?.branch === "string" ? args.branch : void 0,
47341
+ execute: args?.execute === true,
47342
+ dryRun: args?.dryRun === true,
47343
+ updateSubmodules: args?.updateSubmodules === true,
47344
+ submoduleIgnorePaths,
47345
+ mode: args?.mode === "push" ? "push" : "merge",
47346
+ pushSubmodules: args?.pushSubmodules === true,
47347
+ allowAutoPublishSubmoduleMainCommits
47348
+ });
47349
+ return result;
47350
+ },
47351
+ refine_mesh_node: async (ctx, args) => {
47352
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47353
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
47354
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
47355
+ {
47356
+ const meshRecordForForward = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47357
+ const forwardNode = meshRecordForForward?.mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
47358
+ const nodeDaemonId = typeof forwardNode?.daemonId === "string" ? forwardNode.daemonId.trim() : void 0;
47359
+ const selfDaemonId = ctx.deps.statusInstanceId;
47360
+ const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
47361
+ if (isRemote && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
47362
+ const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
47363
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "refine_mesh_node", {
47364
+ ...typeof args === "object" && args !== null ? args : {},
47365
+ coordinatorDaemonId: callerCoordinatorDaemonId || selfDaemonId,
47366
+ _meshDirectDispatch: true
47367
+ });
47368
+ return forwarded ?? { success: false, error: "no response from remote node" };
47369
+ }
47370
+ }
47371
+ const isDryRun = args?.dryRun !== false && args?.execute !== true;
47372
+ if (isDryRun) {
47373
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47374
+ const mesh = meshRecord?.mesh;
47375
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
47376
+ if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
47377
+ return {
47378
+ success: true,
47379
+ dryRun: true,
47380
+ nodeId,
47381
+ workspace: node.workspace,
47382
+ validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
47383
+ mergeWillRun: false,
47384
+ cleanupWillRun: false,
47385
+ hint: "Dry-run only \u2014 no merge/push/cleanup performed. Re-invoke with execute:true to converge this node."
47386
+ };
47387
+ }
47388
+ return ctx.startMeshRefineJob(meshId, nodeId, args);
47389
+ },
47390
+ batch_refine_mesh_nodes: async (ctx, args) => {
47391
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47392
+ if (!meshId) return { success: false, error: "meshId required" };
47393
+ const requestedNodeIds = Array.isArray(args?.nodeIds) ? args.nodeIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
47394
+ const isDryRun = args?.dryRun !== false && args?.execute !== true;
47395
+ if (isDryRun) return ctx.batchRefineMeshNodes(meshId, requestedNodeIds, args);
47396
+ return ctx.startMeshRefineBatchJob(meshId, requestedNodeIds, args);
47397
+ }
47398
+ };
47399
+
47400
+ // src/commands/med-family/index.ts
47401
+ var medFamilyRegistry = new Map(
47402
+ Object.entries({
47403
+ ...cliAgentHandlers,
47404
+ ...ideHandlers,
47405
+ ...meshCrudHandlers,
47406
+ ...meshHostPairingHandlers,
47407
+ ...meshQueueHandlers,
47408
+ ...fastForwardHandlers
47409
+ })
47410
+ );
47411
+
47412
+ // src/commands/router.ts
47413
+ init_config();
47414
+ init_cli_detector();
45947
47415
  init_git_status();
45948
47416
  init_dist();
45949
47417
  init_logger();
@@ -46099,9 +47567,7 @@ init_mesh_coordinator();
46099
47567
  init_coordinator_registry();
46100
47568
  init_mesh_events();
46101
47569
  init_mesh_routing();
46102
- init_mesh_events_utils();
46103
47570
  init_mesh_host_ownership();
46104
- init_mesh_fast_forward();
46105
47571
 
46106
47572
  // src/mesh/mesh-refine-batch.ts
46107
47573
  var import_node_child_process4 = require("child_process");
@@ -46274,121 +47740,6 @@ function buildPreviewFreshness(repoRoot) {
46274
47740
 
46275
47741
  // src/commands/router.ts
46276
47742
  init_mesh_refine_status();
46277
-
46278
- // src/mesh/mesh-init.ts
46279
- var import_fs16 = require("fs");
46280
- var import_path11 = require("path");
46281
- var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
46282
- var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
46283
- var CANDIDATE_STALE_INPUTS = [
46284
- "package-lock.json",
46285
- "pnpm-lock.yaml",
46286
- "yarn.lock",
46287
- "bun.lockb",
46288
- "Cargo.lock",
46289
- "go.sum",
46290
- "poetry.lock",
46291
- "requirements.txt"
46292
- ];
46293
- function writeConfigFile(workspace, relativePath, config) {
46294
- const target = (0, import_path11.join)(workspace, relativePath);
46295
- (0, import_fs16.mkdirSync)((0, import_path11.dirname)(target), { recursive: true });
46296
- (0, import_fs16.writeFileSync)(target, `${JSON.stringify(config, null, 2)}
46297
- `, "utf-8");
46298
- return target;
46299
- }
46300
- function suggestMeshWorktreeBootstrapConfig(workspace) {
46301
- const commands = [];
46302
- const hasPackageJson = (0, import_fs16.existsSync)((0, import_path11.join)(workspace, "package.json"));
46303
- const hasNpmLock = (0, import_fs16.existsSync)((0, import_path11.join)(workspace, "package-lock.json"));
46304
- if (hasPackageJson) {
46305
- commands.push(
46306
- hasNpmLock ? { command: "npm", args: ["ci"] } : { command: "npm", args: ["install"] }
46307
- );
46308
- }
46309
- const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => (0, import_fs16.existsSync)((0, import_path11.join)(workspace, relative5)));
46310
- if (!commands.length) {
46311
- return { commands, staleInputs };
46312
- }
46313
- return {
46314
- commands,
46315
- staleInputs,
46316
- suggestedConfig: {
46317
- version: 1,
46318
- enabled: true,
46319
- runOnClone: true,
46320
- required: false,
46321
- commands,
46322
- ...staleInputs.length ? { staleInputs } : {}
46323
- }
46324
- };
46325
- }
46326
- var PROVIDER_PRIORITY_PREFERENCE = ["claude-cli", "codex-cli", "gemini-cli"];
46327
- function suggestNodeProviderPriority(detected) {
46328
- const installed = detected.filter((cli) => cli.installed);
46329
- const installedIds = installed.map((cli) => cli.id);
46330
- const preferred = PROVIDER_PRIORITY_PREFERENCE.filter((id) => installedIds.includes(id));
46331
- const rest = installedIds.filter((id) => !preferred.includes(id));
46332
- const providerPriority = [...preferred, ...rest];
46333
- return {
46334
- providerPriority,
46335
- installedProviders: installed.map((cli) => ({
46336
- id: cli.id,
46337
- displayName: cli.displayName,
46338
- ...cli.version ? { version: cli.version } : {}
46339
- }))
46340
- };
46341
- }
46342
- function runMeshInit(mesh, workspace, detected, options = {}) {
46343
- const write = options.write === true;
46344
- const overwrite = options.overwrite === true;
46345
- const refine = applyConfigSuggestion({
46346
- workspace,
46347
- relativePath: MESH_INIT_REFINE_CONFIG_PATH,
46348
- existing: loadMeshRefineConfig(mesh, workspace).config,
46349
- suggestedConfig: suggestMeshRefineConfig(mesh, workspace).suggestedConfig,
46350
- validate: (config) => validateMeshRefineConfig(config, MESH_INIT_REFINE_CONFIG_PATH).valid,
46351
- write,
46352
- overwrite
46353
- });
46354
- const bootstrapSuggestion = suggestMeshWorktreeBootstrapConfig(workspace);
46355
- const worktreeBootstrap = applyConfigSuggestion({
46356
- workspace,
46357
- relativePath: MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH,
46358
- existing: loadMeshWorktreeBootstrapConfig(mesh, workspace).config,
46359
- suggestedConfig: bootstrapSuggestion.suggestedConfig,
46360
- validate: (config) => validateMeshWorktreeBootstrapConfig(config, MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH).valid,
46361
- write,
46362
- overwrite
46363
- });
46364
- const providers = suggestNodeProviderPriority(detected);
46365
- return {
46366
- success: true,
46367
- workspace,
46368
- dryRun: !write,
46369
- refine,
46370
- worktreeBootstrap,
46371
- providers,
46372
- note: write ? "Configs written to disk are the execution source of truth; suggestions are scaffold and only take effect once saved. providerPriority is a recommendation \u2014 apply it to node policy via clone/policy update." : "Dry-run: no files written. Re-run with write=true to persist the suggested configs. Heuristic suggestions never execute until saved as repo config."
46373
- };
46374
- }
46375
- function applyConfigSuggestion(input) {
46376
- const { workspace, relativePath, existing, suggestedConfig, validate, write, overwrite } = input;
46377
- const absolute = (0, import_path11.join)(workspace, relativePath);
46378
- if (existing !== void 0 && !overwrite) {
46379
- return { path: absolute, relativePath, written: false, skippedReason: "already_exists", config: existing };
46380
- }
46381
- if (!suggestedConfig || !validate(suggestedConfig)) {
46382
- return { path: absolute, relativePath, written: false, skippedReason: "no_suggestion" };
46383
- }
46384
- if (!write) {
46385
- return { path: absolute, relativePath, written: false, config: suggestedConfig };
46386
- }
46387
- const writtenPath = writeConfigFile(workspace, relativePath, suggestedConfig);
46388
- return { path: writtenPath, relativePath, written: true, config: suggestedConfig };
46389
- }
46390
-
46391
- // src/commands/router.ts
46392
47743
  init_mesh_work_queue();
46393
47744
  init_repo_mesh_types();
46394
47745
  var import_os3 = require("os");
@@ -48940,6 +50291,37 @@ var DaemonCommandRouter = class {
48940
50291
  this.aggregateMeshStatusCache.delete(meshId);
48941
50292
  this.deps.onMeshStateChange?.(meshId);
48942
50293
  }
50294
+ /**
50295
+ * Build the MedFamilyContext handed to RF-ROUTER MED family handlers. Binds the
50296
+ * router-private collaborators those handlers need (mesh resolution, owner
50297
+ * gating, inline-cache mutation, worktree / session cleanup, refine job
50298
+ * starters, IDE stop/launch) plus the inline-mesh and git-probe caches. The
50299
+ * `launchIde` field closes over the freshly-built context so restart_session /
50300
+ * restart_ide invoke the IDE launch directly instead of recursing through
50301
+ * executeDaemonCommand('launch_ide').
50302
+ */
50303
+ buildMedFamilyContext() {
50304
+ const ctx = {
50305
+ deps: this.deps,
50306
+ getMeshForCommand: this.getMeshForCommand.bind(this),
50307
+ getCachedInlineMesh: this.getCachedInlineMesh.bind(this),
50308
+ requireMeshHostMutationOwner: this.requireMeshHostMutationOwner.bind(this),
50309
+ invalidateAggregateMeshStatus: this.invalidateAggregateMeshStatus.bind(this),
50310
+ updateInlineMeshNode: this.updateInlineMeshNode.bind(this),
50311
+ removeInlineMeshNode: this.removeInlineMeshNode.bind(this),
50312
+ normalizeMeshSessionCleanupMode: this.normalizeMeshSessionCleanupMode.bind(this),
50313
+ cleanupMeshSessions: this.cleanupMeshSessions.bind(this),
50314
+ cleanupLocalWorktreeNode: this.cleanupLocalWorktreeNode.bind(this),
50315
+ startMeshRefineJob: this.startMeshRefineJob.bind(this),
50316
+ batchRefineMeshNodes: this.batchRefineMeshNodes.bind(this),
50317
+ startMeshRefineBatchJob: this.startMeshRefineBatchJob.bind(this),
50318
+ stopIde: this.stopIde.bind(this),
50319
+ launchIde: (args) => launchIde(ctx, args),
50320
+ inlineMeshCache: this.inlineMeshCache,
50321
+ meshGitProbeCache: this.meshGitProbeCache
50322
+ };
50323
+ return ctx;
50324
+ }
48943
50325
  async requireMeshHostMutationOwner(meshId, inlineMesh, operation) {
48944
50326
  const meshRecord = await this.getMeshForCommand(meshId, inlineMesh, { preferInline: true });
48945
50327
  const mesh = meshRecord?.mesh;
@@ -50855,6 +52237,10 @@ ${hintLines.join("\n")}` : "",
50855
52237
  getMeshForCommand: this.getMeshForCommand.bind(this)
50856
52238
  }, args);
50857
52239
  }
52240
+ const medFamilyHandler = medFamilyRegistry.get(cmd);
52241
+ if (medFamilyHandler) {
52242
+ return await medFamilyHandler(this.buildMedFamilyContext(), args);
52243
+ }
50858
52244
  switch (cmd) {
50859
52245
  // ─── CLI / ACP commands ───
50860
52246
  case "mesh_forward_event": {
@@ -50875,1315 +52261,6 @@ ${hintLines.join("\n")}` : "",
50875
52261
  this.deps.instanceManager.sendEvent(sessionId, "interactive_prompt_response", response);
50876
52262
  return { success: true };
50877
52263
  }
50878
- case "launch_cli": {
50879
- const launchResult = await this.deps.cliManager.handleCliCommand(cmd, args);
50880
- const meshNodeId = readStringValue(args?.settings?.meshNodeId);
50881
- const meshId = readStringValue(args?.settings?.meshNodeFor);
50882
- if (meshNodeId && meshId && launchResult?.success !== false) {
50883
- try {
50884
- const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50885
- const meshObj = getMesh2(meshId) ?? this.getCachedInlineMesh(meshId);
50886
- const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, meshNodeId)) : void 0;
50887
- const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
50888
- if (bootstrapStatus === "running") {
50889
- return { success: true, ...launchResult, bootstrapPending: true };
50890
- }
50891
- } catch {
50892
- }
50893
- }
50894
- return launchResult;
50895
- }
50896
- case "stop_cli":
50897
- case "set_cli_view_mode":
50898
- case "record_provider_pty": {
50899
- return this.deps.cliManager.handleCliCommand(cmd, args);
50900
- }
50901
- case "agent_command": {
50902
- {
50903
- const dispatchSessionId = readStringValue(args?.targetSessionId, args?.sessionId, args?.instanceId);
50904
- const dispatchMeshContext = args?.meshContext;
50905
- if (dispatchSessionId && dispatchMeshContext) {
50906
- try {
50907
- const inst = this.deps.instanceManager.getInstance(dispatchSessionId);
50908
- if (inst && typeof inst.updateSettings === "function") {
50909
- const stamp = buildMeshWorkerRelayStamp(
50910
- inst.getState?.()?.settings,
50911
- {
50912
- meshId: dispatchMeshContext.meshId,
50913
- nodeId: dispatchMeshContext.nodeId,
50914
- coordinatorDaemonId: dispatchMeshContext.coordinatorDaemonId,
50915
- // Session-level anchor: preserved across the P2P dispatch to a
50916
- // remote worker so its completion echoes back to the right session.
50917
- coordinatorSessionId: dispatchMeshContext.coordinatorSessionId
50918
- }
50919
- );
50920
- if (stamp) inst.updateSettings(stamp);
50921
- }
50922
- } catch {
50923
- }
50924
- }
50925
- }
50926
- const agentResult = await this.deps.cliManager.handleCliCommand(cmd, args);
50927
- const meshCtx = args?.meshContext;
50928
- const dispatchNodeId = readStringValue(meshCtx?.nodeId);
50929
- const dispatchMeshId = readStringValue(meshCtx?.meshId);
50930
- if (dispatchNodeId && dispatchMeshId && agentResult?.success !== false) {
50931
- try {
50932
- const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50933
- const meshObj = getMesh2(dispatchMeshId) ?? this.getCachedInlineMesh(dispatchMeshId);
50934
- const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, dispatchNodeId)) : void 0;
50935
- const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
50936
- if (bootstrapStatus === "running") {
50937
- return {
50938
- success: true,
50939
- ...agentResult,
50940
- dispatchAcknowledgementRisk: true,
50941
- dispatchAcknowledgementRiskReason: "bootstrap_still_running",
50942
- nextAction: "Wait for worktree_bootstrap_complete event before dispatching work to this node."
50943
- };
50944
- }
50945
- } catch {
50946
- }
50947
- }
50948
- return agentResult;
50949
- }
50950
- // ─── Logs ───
50951
- case "list_saved_sessions": {
50952
- const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
50953
- const kind = args?.kind === "acp" ? "acp" : "cli";
50954
- if (!providerType) {
50955
- return { success: false, error: "providerType required" };
50956
- }
50957
- const wantsAll = args?.all === true;
50958
- const offset = wantsAll ? 0 : Math.max(0, Number(args?.offset) || 0);
50959
- const limit = wantsAll ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.min(100, Number(args?.limit) || 30));
50960
- const requestedWorkspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
50961
- const requestedProviderSessionId = typeof args?.providerSessionId === "string" ? args.providerSessionId.trim() : typeof args?.activeProviderSessionId === "string" ? args.activeProviderSessionId.trim() : "";
50962
- const providerMeta = this.deps.providerLoader.resolve?.(providerType) || this.deps.providerLoader.getMeta(providerType);
50963
- const { sessions: historySessions, hasMore, source } = listProviderHistorySessions(providerType, {
50964
- canonicalHistory: providerMeta?.nativeHistory,
50965
- offset,
50966
- limit,
50967
- historyBehavior: providerMeta?.historyBehavior,
50968
- scripts: providerMeta?.scripts
50969
- });
50970
- const state = loadState();
50971
- const savedSessions = getSavedProviderSessions(state, { providerType, kind });
50972
- const recentSessions = getRecentActivity(state, 200).filter((entry) => entry.providerType === providerType && entry.kind === kind && entry.providerSessionId);
50973
- const savedSessionById = new Map(savedSessions.map((entry) => [entry.providerSessionId, entry]));
50974
- const recentSessionById = new Map(recentSessions.map((entry) => [entry.providerSessionId, entry]));
50975
- const canResumeById = supportsExplicitSessionResume(providerMeta?.resume);
50976
- return {
50977
- success: true,
50978
- sessions: historySessions.map((session) => {
50979
- const saved = savedSessionById.get(session.historySessionId);
50980
- const recent = recentSessionById.get(session.historySessionId);
50981
- const workspace = saved?.workspace || recent?.workspace || session.workspace || (requestedWorkspace && requestedProviderSessionId === session.historySessionId ? requestedWorkspace : void 0);
50982
- return {
50983
- id: session.historySessionId,
50984
- providerSessionId: session.historySessionId,
50985
- providerType,
50986
- providerName: saved?.providerName || recent?.providerName || providerType,
50987
- kind: saved?.kind || recent?.kind || kind,
50988
- title: saved?.title || recent?.title || session.sessionTitle || session.preview || providerType,
50989
- workspace,
50990
- summaryMetadata: saved?.summaryMetadata || recent?.summaryMetadata,
50991
- preview: session.preview,
50992
- messageCount: session.messageCount,
50993
- firstMessageAt: session.firstMessageAt,
50994
- lastMessageAt: session.lastMessageAt,
50995
- canResume: !!workspace && canResumeById,
50996
- historySource: session.source,
50997
- sourcePath: session.sourcePath,
50998
- sourceMtimeMs: session.sourceMtimeMs
50999
- };
51000
- }),
51001
- hasMore,
51002
- source
51003
- };
51004
- }
51005
- // ─── restart_session: IDE / CLI / ACP unified ───
51006
- case "restart_session": {
51007
- const targetType = args?.cliType || args?.agentType || args?.ideType;
51008
- if (!targetType) throw new Error("cliType or ideType required");
51009
- const isIde = this.deps.cdpManagers.has(targetType) || this.deps.providerLoader.getMeta(targetType)?.category === "ide";
51010
- if (isIde) {
51011
- await this.stopIde(targetType, true);
51012
- const launchResult = await this.executeDaemonCommand("launch_ide", { ideType: targetType, enableCdp: true, workspace: args?.workspace });
51013
- return { success: true, restarted: true, ideType: targetType, launch: launchResult };
51014
- }
51015
- return this.deps.cliManager.handleCliCommand(cmd, args);
51016
- }
51017
- // ─── IDE stop ───
51018
- case "stop_ide": {
51019
- const ideType = args?.ideType;
51020
- if (!ideType) throw new Error("ideType required");
51021
- const killProcess = args?.killProcess !== false;
51022
- await this.stopIde(ideType, killProcess);
51023
- try {
51024
- const results = await detectIDEs(this.deps.providerLoader);
51025
- this.deps.detectedIdes.value = results;
51026
- this.deps.providerLoader.setIdeDetectionResults(results, true);
51027
- } catch {
51028
- }
51029
- return { success: true, ideType, stopped: true, processKilled: killProcess };
51030
- }
51031
- // ─── IDE restart ───
51032
- case "restart_ide": {
51033
- const ideType = args?.ideType;
51034
- if (!ideType) throw new Error("ideType required");
51035
- await this.stopIde(ideType, true);
51036
- const launchResult = await this.executeDaemonCommand("launch_ide", { ideType, enableCdp: true, workspace: args?.workspace });
51037
- return { success: true, ideType, restarted: true, launch: launchResult };
51038
- }
51039
- // ─── IDE launch + CDP connect ───
51040
- case "launch_ide": {
51041
- const ideKey = args?.ideId || args?.ideType;
51042
- const resolvedWorkspace = resolveIdeLaunchWorkspace(
51043
- {
51044
- workspace: args?.workspace,
51045
- workspaceId: args?.workspaceId,
51046
- useDefaultWorkspace: args?.useDefaultWorkspace
51047
- },
51048
- loadConfig()
51049
- );
51050
- const launchArgs = {
51051
- ideId: ideKey,
51052
- workspace: resolvedWorkspace,
51053
- newWindow: args?.newWindow
51054
- };
51055
- LOG.info("LaunchIDE", `target=${ideKey || "auto"}`);
51056
- const result = await launchWithCdp(launchArgs);
51057
- if (result.success && result.port && result.ideId && !this.deps.cdpManagers.has(result.ideId)) {
51058
- const logFn = this.deps.getCdpLogFn ? this.deps.getCdpLogFn(result.ideId) : LOG.forComponent(`CDP:${result.ideId}`).asLogFn();
51059
- const provider = this.deps.providerLoader.getMeta(result.ideId);
51060
- const manager = new DaemonCdpManager(result.port, logFn, void 0, provider?.targetFilter);
51061
- const connected = await manager.connect();
51062
- if (connected) {
51063
- registerExtensionProviders(this.deps.providerLoader, manager, result.ideId);
51064
- this.deps.cdpManagers.set(result.ideId, manager);
51065
- LOG.info("CDP", `Connected: ${result.ideId} (port ${result.port})`);
51066
- LOG.info("CDP", `${this.deps.cdpManagers.size} IDE(s) connected`);
51067
- this.deps.onCdpManagerCreated?.(result.ideId, manager);
51068
- }
51069
- }
51070
- this.deps.onIdeConnected?.();
51071
- try {
51072
- const results = await detectIDEs(this.deps.providerLoader);
51073
- this.deps.detectedIdes.value = results;
51074
- this.deps.providerLoader.setIdeDetectionResults(results, true);
51075
- } catch {
51076
- }
51077
- if (result.success && resolvedWorkspace) {
51078
- try {
51079
- const next = appendRecentActivity(loadState(), {
51080
- kind: "ide",
51081
- providerType: result.ideId || ideKey,
51082
- providerName: result.ideId || ideKey,
51083
- workspace: resolvedWorkspace,
51084
- title: result.ideId || ideKey
51085
- });
51086
- saveState(next);
51087
- } catch {
51088
- }
51089
- } else if (result.success && (result.ideId || ideKey)) {
51090
- try {
51091
- saveState(appendRecentActivity(loadState(), {
51092
- kind: "ide",
51093
- providerType: result.ideId || ideKey,
51094
- providerName: result.ideId || ideKey,
51095
- title: result.ideId || ideKey
51096
- }));
51097
- } catch {
51098
- }
51099
- }
51100
- return { ...result };
51101
- }
51102
- // ─── Detect providers ───
51103
- case "detect_provider": {
51104
- const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : "";
51105
- if (!providerType) return { success: false, error: "providerType is required" };
51106
- const normalizedType = this.deps.providerLoader.resolveAlias(providerType);
51107
- const provider = this.deps.providerLoader.getByAlias(providerType);
51108
- if (!provider) return { success: false, error: `Provider not found: ${providerType}` };
51109
- if (provider.category !== "cli" && provider.category !== "acp") {
51110
- return { success: false, error: `Provider detection is only supported for CLI/ACP providers: ${providerType}` };
51111
- }
51112
- if (!this.deps.providerLoader.isMachineProviderEnabled(normalizedType)) {
51113
- return { success: false, error: `Provider is disabled on this machine: ${providerType}` };
51114
- }
51115
- const detected = await detectCLI(normalizedType, this.deps.providerLoader, { includeVersion: false });
51116
- this.deps.providerLoader.setCliDetectionResults([{
51117
- id: normalizedType,
51118
- installed: !!detected,
51119
- path: detected?.path
51120
- }], false);
51121
- this.deps.onStatusChange?.();
51122
- return {
51123
- success: true,
51124
- providerType: normalizedType,
51125
- detected: !!detected,
51126
- path: detected?.path || null
51127
- };
51128
- }
51129
- // ─── Detect IDEs ───
51130
- case "detect_ides": {
51131
- const results = await detectIDEs(this.deps.providerLoader);
51132
- this.deps.detectedIdes.value = results;
51133
- this.deps.providerLoader.setIdeDetectionResults(results, true);
51134
- return { success: true, detectedInfo: results };
51135
- }
51136
- // ─── Mesh CRUD (local meshes.json) ───
51137
- case "list_meshes": {
51138
- try {
51139
- const { listMeshes: listMeshes2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51140
- return { success: true, meshes: listMeshes2() };
51141
- } catch (e) {
51142
- return { success: false, error: e.message };
51143
- }
51144
- }
51145
- case "get_mesh": {
51146
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51147
- if (!meshId) return { success: false, error: "meshId required" };
51148
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51149
- if (!meshRecord?.mesh) return { success: false, error: "Mesh not found" };
51150
- const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
51151
- const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
51152
- const directTruth = await hydrateInlineMeshDirectTruth({
51153
- mesh: meshRecord.mesh,
51154
- meshSource: meshRecord.source,
51155
- dispatchMeshCommand: this.deps.dispatchMeshCommand,
51156
- getMeshPeerConnectionStatus: this.deps.getMeshPeerConnectionStatus,
51157
- statusInstanceId: this.deps.statusInstanceId,
51158
- localMachineId: loadConfig().machineId || "",
51159
- probeRemotePeers,
51160
- probeCache: this.meshGitProbeCache
51161
- });
51162
- const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
51163
- const sourceOfTruth = {
51164
- membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
51165
- coordinatorOwnsLiveTruth: directTruthSatisfied,
51166
- directPeerTruth: {
51167
- required: requireDirectPeerTruth,
51168
- satisfied: directTruthSatisfied,
51169
- directEvidenceCount: directTruth.directEvidenceCount,
51170
- localConfirmedCount: directTruth.localConfirmedCount,
51171
- peerAttemptedCount: directTruth.peerAttemptedCount,
51172
- peerConfirmedCount: directTruth.peerConfirmedCount,
51173
- unavailableNodeIds: directTruth.unavailableNodeIds
51174
- }
51175
- };
51176
- if (requireDirectPeerTruth && !directTruthSatisfied) {
51177
- return {
51178
- success: false,
51179
- code: "mesh_direct_peer_truth_unavailable",
51180
- error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.",
51181
- sourceOfTruth
51182
- };
51183
- }
51184
- return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
51185
- }
51186
- case "create_mesh": {
51187
- const name = typeof args?.name === "string" ? args.name.trim() : "";
51188
- const repoIdentity = typeof args?.repoIdentity === "string" ? args.repoIdentity.trim() : "";
51189
- const repoRemoteUrl = typeof args?.repoRemoteUrl === "string" ? args.repoRemoteUrl.trim() : void 0;
51190
- const defaultBranch = typeof args?.defaultBranch === "string" ? args.defaultBranch.trim() : void 0;
51191
- if (!name) return { success: false, error: "name required" };
51192
- try {
51193
- const { createMesh: createMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51194
- const meshHost = args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost) ? args.meshHost : void 0;
51195
- const mesh = createMesh2({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
51196
- return { success: true, mesh };
51197
- } catch (e) {
51198
- return { success: false, error: e.message };
51199
- }
51200
- }
51201
- case "update_mesh": {
51202
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51203
- if (!meshId) return { success: false, error: "meshId required" };
51204
- try {
51205
- const { updateMesh: updateMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51206
- const patch = {};
51207
- if (typeof args?.name === "string") patch.name = args.name;
51208
- if (typeof args?.defaultBranch === "string") patch.defaultBranch = args.defaultBranch;
51209
- if (args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy)) patch.policy = args.policy;
51210
- if (args?.coordinator && typeof args.coordinator === "object" && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
51211
- if (args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
51212
- if (!Object.keys(patch).length) return { success: false, error: "No updates provided" };
51213
- const mesh = updateMesh2(meshId, patch);
51214
- if (!mesh) return { success: false, error: "Mesh not found" };
51215
- this.inlineMeshCache.set(meshId, mesh);
51216
- this.invalidateAggregateMeshStatus(meshId);
51217
- return { success: true, mesh };
51218
- } catch (e) {
51219
- return { success: false, error: e.message };
51220
- }
51221
- }
51222
- case "get_mesh_host_pairing": {
51223
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51224
- if (!meshId) return { success: false, error: "meshId required" };
51225
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51226
- const mesh = meshRecord?.mesh;
51227
- if (!mesh) return { success: false, error: "Mesh not found" };
51228
- const meshHost = resolveMeshHostStatus(mesh);
51229
- const pairingStatus = meshHost.pairing?.status || "not_configured";
51230
- return {
51231
- success: true,
51232
- code: pairingStatus === "not_configured" ? "mesh_host_pairing_not_configured" : "mesh_host_pairing_pending",
51233
- meshId,
51234
- hostAddress: meshHost.hostAddress,
51235
- meshHost,
51236
- manualPairing: {
51237
- status: pairingStatus,
51238
- joinImplemented: true,
51239
- protocol: "standalone_command_direct_v1",
51240
- description: "Standalone manual pairing can save address/token metadata, apply a host join over direct standalone command HTTP or injected mesh command dispatch, and check persisted status. P2P signaling remains outside this slice."
51241
- }
51242
- };
51243
- }
51244
- case "configure_mesh_host_pairing": {
51245
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51246
- const hostAddress = typeof args?.hostAddress === "string" ? args.hostAddress.trim() : "";
51247
- const token = typeof args?.token === "string" ? args.token.trim() : "";
51248
- if (!meshId) return { success: false, error: "meshId required" };
51249
- if (!hostAddress || !token) return { success: false, error: "hostAddress and token required" };
51250
- try {
51251
- const { configureMeshHostPairing: configureMeshHostPairing2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51252
- const configured = configureMeshHostPairing2(meshId, { hostAddress, token });
51253
- if (!configured) return { success: false, error: "Mesh not found" };
51254
- this.inlineMeshCache.set(meshId, configured.mesh);
51255
- const meshHost = resolveMeshHostStatus(configured.mesh);
51256
- return {
51257
- success: true,
51258
- code: "mesh_host_pairing_pending",
51259
- meshId,
51260
- hostAddress: configured.hostAddress,
51261
- meshHost,
51262
- manualPairing: {
51263
- status: meshHost.pairing?.status || "pairing",
51264
- joinImplemented: true,
51265
- protocol: "standalone_command_direct_v1",
51266
- description: "Manual Mesh Host pairing config was saved locally. Use join_mesh_host_pairing to apply it to the host. Raw token was not persisted."
51267
- }
51268
- };
51269
- } catch (e) {
51270
- return { success: false, code: "mesh_host_pairing_invalid", meshId, hostAddress, error: e.message };
51271
- }
51272
- }
51273
- case "create_mesh_host_pairing_token": {
51274
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51275
- if (!meshId) return { success: false, error: "meshId required" };
51276
- try {
51277
- const { createMeshHostPairingToken: createMeshHostPairingToken2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51278
- const created = createMeshHostPairingToken2(meshId, {
51279
- token: typeof args?.token === "string" ? args.token : void 0,
51280
- expiresAt: typeof args?.expiresAt === "string" ? args.expiresAt : void 0
51281
- });
51282
- if (!created) return { success: false, error: "Mesh not found" };
51283
- this.inlineMeshCache.set(meshId, created.mesh);
51284
- this.invalidateAggregateMeshStatus(meshId);
51285
- return {
51286
- success: true,
51287
- code: "mesh_host_pairing_token_created",
51288
- meshId,
51289
- token: created.token,
51290
- tokenId: created.tokenId,
51291
- expiresAt: created.expiresAt,
51292
- meshHost: resolveMeshHostStatus(created.mesh),
51293
- warning: "Raw token is returned once and is not persisted; share it with member daemons over a trusted channel."
51294
- };
51295
- } catch (e) {
51296
- return { success: false, code: "mesh_host_pairing_token_invalid", meshId, error: e.message };
51297
- }
51298
- }
51299
- case "apply_mesh_host_join": {
51300
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51301
- const token = typeof args?.token === "string" ? args.token.trim() : "";
51302
- const memberNode = args?.memberNode && typeof args.memberNode === "object" && !Array.isArray(args.memberNode) ? args.memberNode : null;
51303
- if (!meshId) return { success: false, error: "meshId required" };
51304
- if (!token || !memberNode) return { success: false, error: "token and memberNode required" };
51305
- try {
51306
- const { applyMeshHostJoinRequest: applyMeshHostJoinRequest2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51307
- const applied = applyMeshHostJoinRequest2(meshId, {
51308
- token,
51309
- memberNode,
51310
- memberMeshId: typeof args?.memberMeshId === "string" ? args.memberMeshId : void 0
51311
- });
51312
- if (!applied) return { success: false, error: "Mesh not found" };
51313
- if (!applied.accepted) {
51314
- return {
51315
- success: false,
51316
- code: "mesh_host_join_rejected",
51317
- meshId,
51318
- tokenId: applied.tokenId,
51319
- meshHost: applied.meshHost ? resolveMeshHostStatus({ meshHost: applied.meshHost }) : void 0,
51320
- error: applied.reason
51321
- };
51322
- }
51323
- this.inlineMeshCache.set(meshId, applied.mesh);
51324
- this.invalidateAggregateMeshStatus(meshId);
51325
- try {
51326
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51327
- appendLedgerEntry2(meshId, {
51328
- kind: "node_joined",
51329
- nodeId: applied.node.id,
51330
- payload: { role: "member", tokenId: applied.tokenId, workspace: applied.node.workspace }
51331
- });
51332
- } catch {
51333
- }
51334
- return {
51335
- success: true,
51336
- code: "mesh_host_join_accepted",
51337
- meshId,
51338
- node: applied.node,
51339
- tokenId: applied.tokenId,
51340
- meshHost: resolveMeshHostStatus(applied.mesh)
51341
- };
51342
- } catch (e) {
51343
- return { success: false, code: "mesh_host_join_failed", meshId, error: e.message };
51344
- }
51345
- }
51346
- case "join_mesh_host_pairing": {
51347
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51348
- const token = typeof args?.token === "string" ? args.token.trim() : "";
51349
- if (!meshId) return { success: false, error: "meshId required" };
51350
- if (!token) return { success: false, error: "token required because raw pairing tokens are not persisted" };
51351
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51352
- const mesh = meshRecord?.mesh;
51353
- if (!mesh) return { success: false, error: "Mesh not found" };
51354
- const meshHost = resolveMeshHostStatus(mesh);
51355
- if (meshHost.role !== "member") {
51356
- return { success: false, code: "mesh_host_join_not_member", meshId, meshHost, error: "join_mesh_host_pairing must run from a member daemon configured with a Mesh Host address/token." };
51357
- }
51358
- try {
51359
- const { tokenIdForManualPairing: tokenIdForManualPairing2, markMeshHostPairingJoined: markMeshHostPairingJoined2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51360
- const tokenId = tokenIdForManualPairing2(token);
51361
- if (meshHost.pairing?.tokenId && meshHost.pairing.tokenId !== tokenId) {
51362
- return { success: false, code: "mesh_host_join_rejected", meshId, tokenId, meshHost, error: "invalid pairing token" };
51363
- }
51364
- const memberNode = buildMemberJoinNode(mesh, args, this.deps.statusInstanceId);
51365
- if (!memberNode) return { success: false, error: "member node metadata unavailable" };
51366
- const hostMeshId = typeof args?.hostMeshId === "string" && args.hostMeshId.trim() ? args.hostMeshId.trim() : meshId;
51367
- const hostDaemonId = typeof args?.hostDaemonId === "string" && args.hostDaemonId.trim() ? args.hostDaemonId.trim() : meshHost.hostDaemonId;
51368
- let hostResult;
51369
- let transport;
51370
- if (hostDaemonId && this.deps.dispatchMeshCommand) {
51371
- transport = "mesh_command_dispatch";
51372
- hostResult = await this.deps.dispatchMeshCommand(hostDaemonId, "apply_mesh_host_join", {
51373
- meshId: hostMeshId,
51374
- token,
51375
- memberMeshId: meshId,
51376
- memberNode
51377
- });
51378
- } else if (meshHost.hostAddress) {
51379
- transport = "standalone_http_command";
51380
- const commandUrl = normalizeStandaloneHostCommandUrl(meshHost.hostAddress);
51381
- const response = await fetch(commandUrl, {
51382
- method: "POST",
51383
- headers: { "Content-Type": "application/json" },
51384
- body: JSON.stringify({ type: "apply_mesh_host_join", payload: { meshId: hostMeshId, token, memberMeshId: meshId, memberNode } })
51385
- });
51386
- hostResult = await response.json().catch(() => ({ success: false, error: `Host returned HTTP ${response.status}` }));
51387
- if (!response.ok && hostResult?.success !== false) hostResult = { success: false, error: `Host returned HTTP ${response.status}` };
51388
- } else {
51389
- return {
51390
- success: false,
51391
- code: "mesh_host_join_transport_unavailable",
51392
- meshId,
51393
- meshHost,
51394
- error: "No hostDaemonId dispatch path or hostAddress HTTP command path is available. P2P signaling join is not implemented in this slice."
51395
- };
51396
- }
51397
- if (!hostResult?.success) {
51398
- return { success: false, code: hostResult?.code || "mesh_host_join_rejected", meshId, meshHost, transport, error: hostResult?.error || "Mesh Host rejected join request", hostResult };
51399
- }
51400
- const joined = meshRecord.inline ? null : markMeshHostPairingJoined2(meshId, {
51401
- tokenId: hostResult.tokenId || tokenId,
51402
- hostDaemonId: hostResult.meshHost?.hostDaemonId || hostDaemonId,
51403
- hostNodeId: hostResult.meshHost?.hostNodeId,
51404
- joinedAt: hostResult.meshHost?.pairing?.joinedAt
51405
- });
51406
- if (joined) {
51407
- this.inlineMeshCache.set(meshId, joined.mesh);
51408
- this.invalidateAggregateMeshStatus(meshId);
51409
- }
51410
- return {
51411
- success: true,
51412
- code: "mesh_host_join_applied",
51413
- meshId,
51414
- hostMeshId,
51415
- transport,
51416
- node: hostResult.node,
51417
- tokenId: hostResult.tokenId || tokenId,
51418
- meshHost: joined ? resolveMeshHostStatus(joined.mesh) : { ...meshHost, pairing: { ...meshHost.pairing || {}, status: "paired", tokenId: hostResult.tokenId || tokenId } },
51419
- hostResult,
51420
- manualPairing: {
51421
- status: "paired",
51422
- joinImplemented: true,
51423
- protocol: "standalone_command_direct_v1",
51424
- description: "Mesh Host accepted the join and local member pairing status was marked paired. P2P runtime signaling remains outside this slice."
51425
- }
51426
- };
51427
- } catch (e) {
51428
- return { success: false, code: "mesh_host_join_failed", meshId, meshHost, error: e.message };
51429
- }
51430
- }
51431
- case "delete_mesh": {
51432
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51433
- if (!meshId) return { success: false, error: "meshId required" };
51434
- try {
51435
- const { deleteMesh: deleteMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51436
- const deleted = deleteMesh2(meshId);
51437
- return { success: true, deleted };
51438
- } catch (e) {
51439
- return { success: false, error: e.message };
51440
- }
51441
- }
51442
- case "get_mesh_queue": {
51443
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51444
- if (!meshId) return { success: false, error: "meshId required" };
51445
- try {
51446
- const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2, describeTaskDependencyState: describeTaskDependencyState2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51447
- const status = Array.isArray(args?.status) ? args.status.map((s2) => typeof s2 === "string" ? s2.trim() : "").filter(Boolean) : void 0;
51448
- const rawQueue = getQueue2(meshId, { status });
51449
- const statusById = new Map(getQueue2(meshId).map((task) => [task.id, task.status]));
51450
- const queue = rawQueue.map((task) => Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? { ...task, ...describeTaskDependencyState2(task, statusById) } : task);
51451
- const summary = getMeshQueueStats2(meshId);
51452
- return {
51453
- success: true,
51454
- queue,
51455
- summary,
51456
- sourceOfTruth: {
51457
- kind: "mesh_work_queue_file",
51458
- activeStatuses: ["pending", "assigned"],
51459
- historicalStatuses: ["completed", "failed", "cancelled"],
51460
- notes: "pending/assigned are active work; completed/failed/cancelled are historical records."
51461
- }
51462
- };
51463
- } catch (e) {
51464
- return { success: false, error: e.message };
51465
- }
51466
- }
51467
- case "cancel_mesh_queue_task": {
51468
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51469
- const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
51470
- if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
51471
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue cancellation");
51472
- if (ownerFailure) return ownerFailure;
51473
- try {
51474
- const { cancelTask: cancelTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51475
- const reason = typeof args?.reason === "string" ? args.reason : void 0;
51476
- const task = cancelTask2(meshId, taskId, { reason });
51477
- if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
51478
- return { success: true, task };
51479
- } catch (e) {
51480
- return { success: false, error: e.message };
51481
- }
51482
- }
51483
- case "requeue_mesh_queue_task": {
51484
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51485
- const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
51486
- if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
51487
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue requeue");
51488
- if (ownerFailure) return ownerFailure;
51489
- try {
51490
- const { requeueTask: requeueTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51491
- const task = requeueTask2(meshId, taskId, {
51492
- reason: typeof args?.reason === "string" ? args.reason : void 0,
51493
- targetNodeId: typeof args?.targetNodeId === "string" ? args.targetNodeId.trim() : void 0,
51494
- targetSessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : void 0,
51495
- clearTargetNode: args?.clearTargetNode === true,
51496
- clearTargetSession: args?.clearTargetSession !== false
51497
- });
51498
- if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
51499
- return { success: true, task };
51500
- } catch (e) {
51501
- return { success: false, error: e.message };
51502
- }
51503
- }
51504
- case "add_mesh_node": {
51505
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51506
- const workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
51507
- if (!meshId) return { success: false, error: "meshId required" };
51508
- if (!workspace) return { success: false, error: "workspace required" };
51509
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node addition");
51510
- if (ownerFailure) return ownerFailure;
51511
- try {
51512
- const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51513
- const providerPriority = Array.isArray(args?.providerPriority) ? args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean) : [];
51514
- const readOnly = args?.readOnly === true;
51515
- const providerRoles = normalizeProviderRoles(args?.providerRoles);
51516
- const policy = {
51517
- ...readOnly ? { readOnly: true } : {},
51518
- ...providerPriority.length ? { providerPriority } : {},
51519
- ...providerRoles.length ? { providerRoles } : {}
51520
- };
51521
- const role = normalizeMeshDaemonRole(args?.role);
51522
- const daemonId = typeof args?.daemonId === "string" && args.daemonId.trim() ? args.daemonId.trim() : void 0;
51523
- const machineId = typeof args?.machineId === "string" && args.machineId.trim() ? args.machineId.trim() : void 0;
51524
- const repoRoot = typeof args?.repoRoot === "string" && args.repoRoot.trim() ? args.repoRoot.trim() : void 0;
51525
- const node = addNode2(meshId, {
51526
- workspace,
51527
- ...repoRoot ? { repoRoot } : {},
51528
- ...daemonId ? { daemonId } : {},
51529
- ...machineId ? { machineId } : {},
51530
- ...policy ? { policy } : {},
51531
- ...role ? { role } : {}
51532
- });
51533
- if (!node) return { success: false, error: "Mesh not found" };
51534
- this.invalidateAggregateMeshStatus(meshId);
51535
- return { success: true, node };
51536
- } catch (e) {
51537
- return { success: false, error: e.message };
51538
- }
51539
- }
51540
- case "update_mesh_node": {
51541
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51542
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51543
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51544
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node update");
51545
- if (ownerFailure) return ownerFailure;
51546
- try {
51547
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51548
- const policy = args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy) ? { ...args.policy } : {};
51549
- if (Array.isArray(args?.providerPriority)) {
51550
- const providerPriority = args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean);
51551
- delete policy.provider_priority;
51552
- if (providerPriority.length) {
51553
- policy.providerPriority = providerPriority;
51554
- } else {
51555
- delete policy.providerPriority;
51556
- }
51557
- }
51558
- if (Array.isArray(args?.providerRoles)) {
51559
- const providerRoles = normalizeProviderRoles(args.providerRoles);
51560
- if (providerRoles.length) {
51561
- policy.providerRoles = providerRoles;
51562
- } else {
51563
- delete policy.providerRoles;
51564
- }
51565
- }
51566
- const patch = { policy };
51567
- if (typeof args?.systemPrompt === "string") {
51568
- const trimmed = args.systemPrompt.trim();
51569
- patch.systemPrompt = trimmed || void 0;
51570
- } else if (args?.systemPrompt === null) {
51571
- patch.systemPrompt = void 0;
51572
- }
51573
- const node = updateNode2(meshId, nodeId, patch);
51574
- if (!node) return { success: false, error: "Mesh node not found" };
51575
- this.invalidateAggregateMeshStatus(meshId);
51576
- return { success: true, node };
51577
- } catch (e) {
51578
- return { success: false, error: e.message };
51579
- }
51580
- }
51581
- case "cleanup_mesh_sessions": {
51582
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51583
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51584
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51585
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node removal");
51586
- if (ownerFailure) return ownerFailure;
51587
- try {
51588
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51589
- const mesh = meshRecord?.mesh;
51590
- if (!mesh) return { success: false, error: "Mesh not found" };
51591
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51592
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
51593
- const mode = this.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
51594
- const sessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : void 0;
51595
- const result = await this.cleanupMeshSessions({
51596
- meshId,
51597
- nodeId,
51598
- node,
51599
- mode,
51600
- sessionIds,
51601
- dryRun: args?.dryRun === true,
51602
- source: "mesh_cleanup_sessions"
51603
- });
51604
- return result;
51605
- } catch (e) {
51606
- return { success: false, error: e.message };
51607
- }
51608
- }
51609
- case "mesh_init": {
51610
- const workspace = typeof args?.workspace === "string" && args.workspace.trim() ? args.workspace.trim() : process.cwd();
51611
- const mesh = args?.inlineMesh || {};
51612
- try {
51613
- const detected = await detectCLIs(this.deps.providerLoader, { includeVersion: true });
51614
- return { ...runMeshInit(mesh, workspace, detected, {
51615
- write: args?.write === true,
51616
- overwrite: args?.overwrite === true
51617
- }) };
51618
- } catch (e) {
51619
- return { success: false, error: e?.message || String(e) };
51620
- }
51621
- }
51622
- case "plan_mesh_refine_node": {
51623
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51624
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51625
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51626
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51627
- const mesh = meshRecord?.mesh;
51628
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51629
- if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
51630
- return {
51631
- success: true,
51632
- dryRun: true,
51633
- nodeId,
51634
- workspace: node.workspace,
51635
- validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
51636
- mergeWillRun: false,
51637
- cleanupWillRun: false
51638
- };
51639
- }
51640
- case "fast_forward_mesh_node": {
51641
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51642
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51643
- let workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
51644
- let submoduleIgnorePaths = Array.isArray(args?.submoduleIgnorePaths) ? args.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0;
51645
- let nodeDaemonId;
51646
- let allowAutoPublishSubmoduleMainCommits = false;
51647
- if (meshId && nodeId) {
51648
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51649
- const mesh = meshRecord?.mesh;
51650
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51651
- if (!workspace) {
51652
- workspace = typeof node?.workspace === "string" ? node.workspace.trim() : "";
51653
- }
51654
- if (!submoduleIgnorePaths && Array.isArray(node?.policy?.submoduleIgnorePaths)) {
51655
- submoduleIgnorePaths = node.policy.submoduleIgnorePaths.filter((value) => typeof value === "string");
51656
- }
51657
- allowAutoPublishSubmoduleMainCommits = mesh?.policy?.allowAutoPublishSubmoduleMainCommits === true;
51658
- nodeDaemonId = typeof node?.daemonId === "string" ? node.daemonId.trim() : void 0;
51659
- }
51660
- const selfDaemonId = this.deps.statusInstanceId;
51661
- const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
51662
- if (isRemote && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51663
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "fast_forward_mesh_node", {
51664
- ...typeof args === "object" && args !== null ? args : {},
51665
- workspace,
51666
- _meshDirectDispatch: true
51667
- });
51668
- return forwarded ?? { success: false, error: "no response from remote node" };
51669
- }
51670
- const result = await fastForwardMeshNode({
51671
- meshId: meshId || void 0,
51672
- nodeId: nodeId || void 0,
51673
- workspace,
51674
- branch: typeof args?.branch === "string" ? args.branch : void 0,
51675
- execute: args?.execute === true,
51676
- dryRun: args?.dryRun === true,
51677
- updateSubmodules: args?.updateSubmodules === true,
51678
- submoduleIgnorePaths,
51679
- mode: args?.mode === "push" ? "push" : "merge",
51680
- pushSubmodules: args?.pushSubmodules === true,
51681
- allowAutoPublishSubmoduleMainCommits
51682
- });
51683
- return result;
51684
- }
51685
- case "refine_mesh_node": {
51686
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51687
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51688
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51689
- {
51690
- const meshRecordForForward = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51691
- const forwardNode = meshRecordForForward?.mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51692
- const nodeDaemonId = typeof forwardNode?.daemonId === "string" ? forwardNode.daemonId.trim() : void 0;
51693
- const selfDaemonId = this.deps.statusInstanceId;
51694
- const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
51695
- if (isRemote && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51696
- const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
51697
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "refine_mesh_node", {
51698
- ...typeof args === "object" && args !== null ? args : {},
51699
- coordinatorDaemonId: callerCoordinatorDaemonId || selfDaemonId,
51700
- _meshDirectDispatch: true
51701
- });
51702
- return forwarded ?? { success: false, error: "no response from remote node" };
51703
- }
51704
- }
51705
- const isDryRun = args?.dryRun !== false && args?.execute !== true;
51706
- if (isDryRun) {
51707
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51708
- const mesh = meshRecord?.mesh;
51709
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51710
- if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
51711
- return {
51712
- success: true,
51713
- dryRun: true,
51714
- nodeId,
51715
- workspace: node.workspace,
51716
- validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
51717
- mergeWillRun: false,
51718
- cleanupWillRun: false,
51719
- hint: "Dry-run only \u2014 no merge/push/cleanup performed. Re-invoke with execute:true to converge this node."
51720
- };
51721
- }
51722
- return this.startMeshRefineJob(meshId, nodeId, args);
51723
- }
51724
- case "batch_refine_mesh_nodes": {
51725
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51726
- if (!meshId) return { success: false, error: "meshId required" };
51727
- const requestedNodeIds = Array.isArray(args?.nodeIds) ? args.nodeIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
51728
- const isDryRun = args?.dryRun !== false && args?.execute !== true;
51729
- if (isDryRun) return this.batchRefineMeshNodes(meshId, requestedNodeIds, args);
51730
- return this.startMeshRefineBatchJob(meshId, requestedNodeIds, args);
51731
- }
51732
- case "remove_mesh_node": {
51733
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51734
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51735
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51736
- try {
51737
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51738
- const mesh = meshRecord?.mesh;
51739
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51740
- if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
51741
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : "";
51742
- const nodeMachineId = readMeshNodeMachineId(node) || "";
51743
- const selfDaemonId = this.deps.statusInstanceId || "";
51744
- const selfMachineId = (() => {
51745
- try {
51746
- return loadConfig().machineId || "";
51747
- } catch {
51748
- return "";
51749
- }
51750
- })();
51751
- const isCoordinatorBaseNode = !!selfDaemonId && (nodeDaemonId === selfDaemonId || nodeMachineId === selfDaemonId) || !!selfMachineId && (nodeDaemonId === selfMachineId || nodeMachineId === selfMachineId);
51752
- if (isCoordinatorBaseNode) {
51753
- return {
51754
- success: false,
51755
- removed: false,
51756
- code: "mesh_remove_coordinator_base_node_protected",
51757
- error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === "string" ? node.workspace : nodeId}'. It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
51758
- recoveryHint: "Remove worktree clone nodes instead, or pass force:true only if you are intentionally tearing down this mesh and accept that the coordinator must be re-registered/restarted."
51759
- };
51760
- }
51761
- }
51762
- const sessionCleanupMode = this.normalizeMeshSessionCleanupMode(
51763
- args?.sessionCleanupMode ?? args?.session_cleanup_mode ?? mesh?.policy?.sessionCleanupOnNodeRemove
51764
- );
51765
- const explicitSessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
51766
- let sessionCleanup;
51767
- if (node && sessionCleanupMode !== "preserve") {
51768
- sessionCleanup = await this.cleanupMeshSessions({
51769
- meshId,
51770
- nodeId,
51771
- node,
51772
- mode: sessionCleanupMode,
51773
- ...explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {},
51774
- source: "mesh_remove_node"
51775
- });
51776
- if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
51777
- }
51778
- let worktreeCleanup;
51779
- if (node?.isLocalWorktree) {
51780
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
51781
- const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch;
51782
- if (isRemoteWorktree) {
51783
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "remove_mesh_node", {
51784
- ...typeof args === "object" && args !== null ? args : {},
51785
- _meshDirectDispatch: true
51786
- });
51787
- return forwarded ?? { success: false, error: "no response from remote node" };
51788
- }
51789
- const cleanupResult = await this.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
51790
- if (cleanupResult.success === false) {
51791
- return {
51792
- success: false,
51793
- removed: false,
51794
- code: cleanupResult.code,
51795
- error: cleanupResult.error,
51796
- recoveryHint: cleanupResult.recoveryHint,
51797
- ...sessionCleanup ? { sessionCleanup } : {},
51798
- worktreeCleanup: cleanupResult
51799
- };
51800
- }
51801
- worktreeCleanup = cleanupResult;
51802
- }
51803
- let removed = false;
51804
- if (meshRecord?.inline) {
51805
- removed = this.removeInlineMeshNode(meshId, mesh, nodeId);
51806
- if (removed) this.invalidateAggregateMeshStatus(meshId);
51807
- if (!removed && !node) removed = true;
51808
- } else {
51809
- const { removeNode: removeNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51810
- removed = removeNode2(meshId, nodeId);
51811
- if (!removed && !node) removed = true;
51812
- if (removed) this.invalidateAggregateMeshStatus(meshId);
51813
- }
51814
- if (removed) {
51815
- try {
51816
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51817
- appendLedgerEntry2(meshId, {
51818
- kind: "node_removed",
51819
- nodeId,
51820
- payload: {
51821
- worktree: !!node?.isLocalWorktree,
51822
- sessionCleanupMode,
51823
- workspace: typeof node?.workspace === "string" ? node.workspace : void 0,
51824
- daemonId: typeof node?.daemonId === "string" ? node.daemonId : void 0,
51825
- worktreeBranch: typeof node?.worktreeBranch === "string" ? node.worktreeBranch : void 0,
51826
- worktreeCleanupFallback: typeof worktreeCleanup?.fallback === "string" ? worktreeCleanup.fallback : void 0,
51827
- forced: worktreeCleanup?.forced === true ? true : void 0,
51828
- forceFallbackReason: typeof worktreeCleanup?.reason === "string" ? worktreeCleanup.reason : void 0
51829
- }
51830
- });
51831
- } catch {
51832
- }
51833
- }
51834
- const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === "string" ? worktreeCleanup.residueWarning : void 0;
51835
- return {
51836
- success: true,
51837
- removed,
51838
- ...residueWarning ? { residueWarning } : {},
51839
- ...sessionCleanup ? { sessionCleanup } : {},
51840
- ...worktreeCleanup ? { worktreeCleanup } : {}
51841
- };
51842
- } catch (e) {
51843
- return { success: false, error: e.message };
51844
- }
51845
- }
51846
- case "clone_mesh_node": {
51847
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51848
- const sourceNodeId = typeof args?.sourceNodeId === "string" ? args.sourceNodeId.trim() : "";
51849
- const branch = typeof args?.branch === "string" ? args.branch.trim() : "";
51850
- const baseBranch = typeof args?.baseBranch === "string" ? args.baseBranch.trim() : void 0;
51851
- if (!meshId) return { success: false, error: "meshId required" };
51852
- if (!sourceNodeId) return { success: false, error: "sourceNodeId required" };
51853
- if (!branch) return { success: false, error: "branch required" };
51854
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "worktree clone");
51855
- if (ownerFailure) return ownerFailure;
51856
- try {
51857
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51858
- const mesh = meshRecord?.mesh;
51859
- if (!mesh) return { success: false, error: "Mesh not found" };
51860
- const sourceNode = mesh.nodes?.find((n) => meshNodeIdMatches(n, sourceNodeId));
51861
- if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
51862
- const sourceDaemonId = typeof sourceNode.daemonId === "string" ? sourceNode.daemonId.trim() : void 0;
51863
- if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51864
- const forwarded = await this.deps.dispatchMeshCommand(sourceDaemonId, "clone_mesh_node", {
51865
- ...typeof args === "object" && args !== null ? args : {},
51866
- _meshDirectDispatch: true
51867
- });
51868
- return forwarded ?? { success: false, error: "no response from remote node" };
51869
- }
51870
- const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
51871
- const { createWorktree: createWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
51872
- const result = await createWorktree2({
51873
- repoRoot,
51874
- branch,
51875
- baseBranch,
51876
- meshName: mesh.name
51877
- });
51878
- let node;
51879
- if (meshRecord.inline) {
51880
- const { randomUUID: randomUUID15 } = await import("crypto");
51881
- node = {
51882
- id: `node_${randomUUID15().replace(/-/g, "")}`,
51883
- workspace: result.worktreePath,
51884
- repoRoot: result.worktreePath,
51885
- daemonId: sourceNode.daemonId,
51886
- machineId: sourceNode.machineId ?? sourceNode.machine_id,
51887
- userOverrides: { ...sourceNode.userOverrides || {} },
51888
- policy: { ...sourceNode.policy || {} },
51889
- isLocalWorktree: true,
51890
- worktreeBranch: result.branch,
51891
- clonedFromNodeId: sourceNodeId
51892
- };
51893
- this.updateInlineMeshNode(meshId, mesh, node);
51894
- } else {
51895
- const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51896
- node = addNode2(meshId, {
51897
- workspace: result.worktreePath,
51898
- repoRoot: result.worktreePath,
51899
- daemonId: sourceNode.daemonId,
51900
- machineId: sourceNode.machineId ?? sourceNode.machine_id,
51901
- userOverrides: { ...sourceNode.userOverrides || {} },
51902
- isLocalWorktree: true,
51903
- worktreeBranch: result.branch,
51904
- clonedFromNodeId: sourceNodeId,
51905
- policy: { ...sourceNode.policy || {} }
51906
- });
51907
- if (!node) return { success: false, error: "Failed to register worktree node" };
51908
- const inlineForReconcile = this.getCachedInlineMesh(meshId);
51909
- if (inlineForReconcile) this.updateInlineMeshNode(meshId, inlineForReconcile, node);
51910
- this.invalidateAggregateMeshStatus(meshId);
51911
- }
51912
- const persistWorktreeSetupState = async (bootstrapState2) => {
51913
- node.worktreeBootstrap = bootstrapState2;
51914
- if (meshRecord.inline) {
51915
- this.updateInlineMeshNode(meshId, mesh, node);
51916
- return;
51917
- }
51918
- try {
51919
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51920
- updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
51921
- this.invalidateAggregateMeshStatus(meshId);
51922
- } catch {
51923
- }
51924
- };
51925
- const appendCloneLedger = async (initSubmodules2, bootstrapState2) => {
51926
- try {
51927
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51928
- appendLedgerEntry2(meshId, {
51929
- kind: "node_cloned",
51930
- nodeId: node.id,
51931
- payload: {
51932
- sourceNodeId,
51933
- branch: result.branch,
51934
- worktreePath: result.worktreePath,
51935
- submodulesInitialized: initSubmodules2,
51936
- worktreeBootstrap: {
51937
- status: bootstrapState2.status,
51938
- required: bootstrapState2.required,
51939
- configSource: bootstrapState2.configSource,
51940
- configSourceType: bootstrapState2.configSourceType,
51941
- lastCommand: bootstrapState2.lastCommand,
51942
- exitCode: bootstrapState2.exitCode
51943
- }
51944
- }
51945
- });
51946
- } catch {
51947
- }
51948
- };
51949
- const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
51950
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
51951
- const runningBootstrapState = {
51952
- status: "running",
51953
- required: loadedBootstrap.config?.required !== false,
51954
- configSource: loadedBootstrap.path || loadedBootstrap.source,
51955
- configSourceType: loadedBootstrap.sourceType,
51956
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
51957
- };
51958
- await persistWorktreeSetupState(runningBootstrapState);
51959
- const finishWorktreeSetup = async () => {
51960
- let submodulesInitialized2 = false;
51961
- if (initSubmodules) {
51962
- try {
51963
- const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
51964
- await runGit3(
51965
- { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
51966
- ["submodule", "update", "--init", "--recursive"],
51967
- { timeoutMs: 12e4 }
51968
- );
51969
- submodulesInitialized2 = true;
51970
- const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
51971
- if (sourceWorkspace) {
51972
- try {
51973
- const { runGit: rg } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
51974
- const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
51975
- const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
51976
- const sourceStatusOut = await rg(sourceCtx, ["submodule", "status", "oss"], { timeoutMs: 1e4 });
51977
- const sourceStatusLine = (typeof sourceStatusOut === "string" ? sourceStatusOut : sourceStatusOut?.stdout ?? "").trim();
51978
- const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
51979
- const sourceSha = sourceShaMatch?.[1];
51980
- if (sourceSha) {
51981
- const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
51982
- const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
51983
- const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
51984
- if (worktreeOssSha !== sourceSha) {
51985
- await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
51986
- await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
51987
- await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
51988
- await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
51989
- console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
51990
- }
51991
- }
51992
- } catch (ossErr) {
51993
- console.warn("[mesh] oss submodule sync to source HEAD failed (best-effort):", ossErr.message);
51994
- }
51995
- }
51996
- } catch (subErr) {
51997
- console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
51998
- }
51999
- }
52000
- const bootstrapState2 = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
52001
- await persistWorktreeSetupState(bootstrapState2);
52002
- await appendCloneLedger(submodulesInitialized2, bootstrapState2);
52003
- return { submodulesInitialized: submodulesInitialized2, bootstrapState: bootstrapState2 };
52004
- };
52005
- const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8e3);
52006
- const setupWaitMs = Number.isFinite(requestedSetupWaitMs) ? Math.min(Math.max(requestedSetupWaitMs, 0), 14e3) : 8e3;
52007
- const setupPromise = finishWorktreeSetup();
52008
- const setupResult = await Promise.race([
52009
- setupPromise.then((value) => ({ completed: true, value })),
52010
- new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
52011
- ]);
52012
- const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
52013
- try {
52014
- const durationMs = Date.now() - startedAtMs;
52015
- const event = `worktree_${eventStatus2}`;
52016
- const metadataEvent = {
52017
- source: "clone_mesh_node_bootstrap",
52018
- nodeId: node.id,
52019
- status: eventStatus2,
52020
- worktreePath: result.worktreePath,
52021
- durationMs,
52022
- bootstrapStatus: bootstrapState2.status,
52023
- ...bootstrapState2.error ? { error: bootstrapState2.error } : {},
52024
- ...bootstrapState2.exitCode !== void 0 ? { exitCode: bootstrapState2.exitCode } : {},
52025
- ...extraPayload || {}
52026
- };
52027
- if (typeof this.deps.instanceManager?.getByCategory === "function") {
52028
- const forwarded = handleMeshForwardEvent(
52029
- { instanceManager: this.deps.instanceManager },
52030
- { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent }
52031
- );
52032
- if (forwarded?.success === true) return;
52033
- }
52034
- queuePendingMeshCoordinatorEvent({
52035
- event,
52036
- meshId,
52037
- nodeLabel: node.id,
52038
- nodeId: node.id,
52039
- workspace: result.worktreePath,
52040
- metadataEvent,
52041
- queuedAt: Date.now()
52042
- });
52043
- } catch {
52044
- }
52045
- };
52046
- const bootstrapStartedMs = Date.now();
52047
- if (!setupResult.completed) {
52048
- setupPromise.then(({ bootstrapState: bootstrapState2 }) => {
52049
- emitBootstrapEvent("bootstrap_complete", bootstrapState2, bootstrapStartedMs);
52050
- }).catch((error) => {
52051
- const failedState = {
52052
- ...runningBootstrapState,
52053
- status: "failed",
52054
- completedAt: (/* @__PURE__ */ new Date()).toISOString(),
52055
- error: error?.message || String(error)
52056
- };
52057
- void persistWorktreeSetupState(failedState);
52058
- void appendCloneLedger(false, failedState);
52059
- emitBootstrapEvent("bootstrap_failed", failedState, bootstrapStartedMs, { error: error?.message || String(error) });
52060
- });
52061
- return {
52062
- success: true,
52063
- async: true,
52064
- status: "accepted",
52065
- node,
52066
- worktreePath: result.worktreePath,
52067
- branch: result.branch,
52068
- worktreeBootstrap: runningBootstrapState,
52069
- worktreeSetup: {
52070
- status: "running",
52071
- setupWaitMs,
52072
- message: "Worktree node is registered; submodule/bootstrap setup is continuing in the background."
52073
- }
52074
- };
52075
- }
52076
- const { submodulesInitialized, bootstrapState } = setupResult.value;
52077
- emitBootstrapEvent("bootstrap_complete", bootstrapState, bootstrapStartedMs);
52078
- return {
52079
- success: true,
52080
- node,
52081
- worktreePath: result.worktreePath,
52082
- branch: result.branch,
52083
- submodulesInitialized,
52084
- worktreeBootstrap: bootstrapState
52085
- };
52086
- } catch (e) {
52087
- return { success: false, error: e.message };
52088
- }
52089
- }
52090
- case "retry_mesh_node_bootstrap": {
52091
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
52092
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
52093
- if (!meshId) return { success: false, error: "meshId required" };
52094
- if (!nodeId) return { success: false, error: "nodeId required" };
52095
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "bootstrap retry");
52096
- if (ownerFailure) return ownerFailure;
52097
- try {
52098
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
52099
- const mesh = meshRecord?.mesh;
52100
- if (!mesh) return { success: false, error: "Mesh not found" };
52101
- const node = mesh.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
52102
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
52103
- if (!node.isLocalWorktree) return { success: false, error: "Node is not a local worktree node" };
52104
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
52105
- if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
52106
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "retry_mesh_node_bootstrap", {
52107
- ...typeof args === "object" && args !== null ? args : {},
52108
- _meshDirectDispatch: true
52109
- });
52110
- return forwarded ?? { success: false, error: "no response from remote node" };
52111
- }
52112
- const currentBootstrap = node.worktreeBootstrap;
52113
- if (currentBootstrap?.status === "running") {
52114
- return { success: false, error: "Bootstrap is already running for this node" };
52115
- }
52116
- const worktreePath = node.workspace || node.repoRoot;
52117
- if (!worktreePath) return { success: false, error: "Node has no workspace path" };
52118
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
52119
- const runningState = {
52120
- status: "running",
52121
- required: loadedBootstrap.config?.required !== false,
52122
- configSource: loadedBootstrap.path || loadedBootstrap.source,
52123
- configSourceType: loadedBootstrap.sourceType,
52124
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
52125
- };
52126
- const persistState = async (bootstrapState2) => {
52127
- node.worktreeBootstrap = bootstrapState2;
52128
- if (meshRecord.inline) {
52129
- this.updateInlineMeshNode(meshId, mesh, node);
52130
- return;
52131
- }
52132
- try {
52133
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
52134
- updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
52135
- this.invalidateAggregateMeshStatus(meshId);
52136
- } catch {
52137
- }
52138
- };
52139
- await persistState(runningState);
52140
- const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
52141
- await persistState(bootstrapState);
52142
- return { success: true, bootstrapState };
52143
- } catch (e) {
52144
- return { success: false, error: e.message };
52145
- }
52146
- }
52147
- case "trigger_mesh_queue": {
52148
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
52149
- if (!meshId) return { success: false, error: "meshId required" };
52150
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue trigger");
52151
- if (ownerFailure) return ownerFailure;
52152
- try {
52153
- const { triggerMeshQueue: triggerMeshQueue2, tryAssignQueueTask: tryAssignQueueTask2 } = await Promise.resolve().then(() => (init_mesh_events(), mesh_events_exports));
52154
- const preferredNodeId = typeof args?.preferredNodeId === "string" ? args.preferredNodeId.trim() : "";
52155
- if (preferredNodeId) {
52156
- const cliInstances = this.deps.instanceManager.getByCategory("cli");
52157
- const sorted = [...cliInstances].sort((a, b) => {
52158
- const aSettings = a.getState().settings || {};
52159
- const bSettings = b.getState().settings || {};
52160
- const aNode = readStringValue(aSettings.meshNodeId, aSettings.nodeId);
52161
- const bNode = readStringValue(bSettings.meshNodeId, bSettings.nodeId);
52162
- return (aNode === preferredNodeId ? -1 : 0) - (bNode === preferredNodeId ? -1 : 0);
52163
- });
52164
- for (const inst of sorted) {
52165
- const state = inst.getState();
52166
- const settings = state.settings || {};
52167
- const nodeId = readStringValue(settings.meshNodeId, settings.nodeId);
52168
- if (!nodeId || nodeId !== preferredNodeId) continue;
52169
- const meshNodeFor = readStringValue(settings.meshNodeFor);
52170
- if (meshNodeFor !== meshId) continue;
52171
- const status = (readStringValue(state.status) || "").toLowerCase();
52172
- if (status !== "idle") continue;
52173
- const sessionId = typeof state.instanceId === "string" ? state.instanceId : "";
52174
- const providerType = readStringValue(state.type, settings.providerType) || "";
52175
- if (sessionId && providerType) {
52176
- tryAssignQueueTask2(this.deps, meshId, nodeId, sessionId, providerType);
52177
- break;
52178
- }
52179
- }
52180
- }
52181
- const trigger = await triggerMeshQueue2(this.deps, meshId);
52182
- return { success: true, trigger };
52183
- } catch (e) {
52184
- return { success: false, error: e.message };
52185
- }
52186
- }
52187
52264
  // ─── Mesh Coordinator Launch ───
52188
52265
  case "launch_mesh_coordinator": {
52189
52266
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";