@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.mjs CHANGED
@@ -311,10 +311,10 @@ function readInjected(value) {
311
311
  }
312
312
  function getDaemonBuildInfo() {
313
313
  if (cached) return cached;
314
- const commit = readInjected(true ? "1428e9d027beefe860a77f34dea34d202db80f00" : void 0) ?? "unknown";
315
- const commitShort = readInjected(true ? "1428e9d0" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
- const version = readInjected(true ? "0.9.82-rc.364" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
- const builtAt = readInjected(true ? "2026-06-24T00:05:49.524Z" : void 0);
314
+ const commit = readInjected(true ? "fe24f3fb158efc949e806b79bca2479b1c29d753" : void 0) ?? "unknown";
315
+ const commitShort = readInjected(true ? "fe24f3fb" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
+ const version = readInjected(true ? "0.9.82-rc.365" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
+ const builtAt = readInjected(true ? "2026-06-24T00:47:57.092Z" : void 0);
318
318
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
319
319
  return cached;
320
320
  }
@@ -2188,6 +2188,20 @@ var init_recent_activity = __esm({
2188
2188
  }
2189
2189
  });
2190
2190
 
2191
+ // src/system/hash.ts
2192
+ import { createHash } from "crypto";
2193
+ function sha256Hex(input) {
2194
+ return createHash("sha256").update(input).digest("hex");
2195
+ }
2196
+ function shortHash(input, length = 16) {
2197
+ return sha256Hex(input).slice(0, length);
2198
+ }
2199
+ var init_hash = __esm({
2200
+ "src/system/hash.ts"() {
2201
+ "use strict";
2202
+ }
2203
+ });
2204
+
2191
2205
  // src/mesh/mesh-host-ownership.ts
2192
2206
  function readObject(value) {
2193
2207
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
@@ -2278,7 +2292,7 @@ __export(mesh_config_exports, {
2278
2292
  });
2279
2293
  import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2280
2294
  import { join as join5 } from "path";
2281
- import { createHash, randomBytes, randomUUID as randomUUID3 } from "crypto";
2295
+ import { randomBytes, randomUUID as randomUUID3 } from "crypto";
2282
2296
  function getMeshConfigPath() {
2283
2297
  return join5(getConfigDir(), "meshes.json");
2284
2298
  }
@@ -2468,7 +2482,7 @@ function normalizeManualHostAddress(hostAddress) {
2468
2482
  return normalized;
2469
2483
  }
2470
2484
  function tokenIdForManualPairing(token) {
2471
- return `tok_${createHash("sha256").update(token).digest("hex").slice(0, 16)}`;
2485
+ return `tok_${shortHash(token)}`;
2472
2486
  }
2473
2487
  function normalizeTokenExpiry(value) {
2474
2488
  if (typeof value !== "string" || !value.trim()) return void 0;
@@ -2700,6 +2714,7 @@ var SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES;
2700
2714
  var init_mesh_config = __esm({
2701
2715
  "src/config/mesh-config.ts"() {
2702
2716
  "use strict";
2717
+ init_hash();
2703
2718
  init_config();
2704
2719
  init_repo_mesh_types();
2705
2720
  init_mesh_host_ownership();
@@ -6916,7 +6931,6 @@ __export(mesh_coordinator_exports, {
6916
6931
  resolveMeshCoordinatorSetup: () => resolveMeshCoordinatorSetup,
6917
6932
  stripCoordinatorWrapperFile: () => stripCoordinatorWrapperFile
6918
6933
  });
6919
- import { createHash as createHash2 } from "crypto";
6920
6934
  import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "fs";
6921
6935
  import * as os4 from "os";
6922
6936
  import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from "@adhdev/session-host-core";
@@ -7086,7 +7100,7 @@ function replaceLegacyCliCommandMcpArgs(command, args) {
7086
7100
  function resolveHermesCoordinatorHome(meshId, workspace) {
7087
7101
  const key = `${meshId || "mesh"}
7088
7102
  ${resolve7(workspace || os4.tmpdir())}`;
7089
- const hash = createHash2("sha256").update(key).digest("hex").slice(0, 16);
7103
+ const hash = shortHash(key);
7090
7104
  return join10(os4.tmpdir(), `adhdev-hermes-mesh-coordinator-${hash}`);
7091
7105
  }
7092
7106
  function resolveMcpConfigPath(configPath, workspace) {
@@ -7300,6 +7314,7 @@ var init_mesh_coordinator = __esm({
7300
7314
  "src/commands/mesh-coordinator.ts"() {
7301
7315
  "use strict";
7302
7316
  init_logger();
7317
+ init_hash();
7303
7318
  DEFAULT_SERVER_NAME = "adhdev-mesh";
7304
7319
  DEFAULT_ADHDEV_MCP_COMMAND = "adhdev";
7305
7320
  HERMES_CLI_TYPE = "hermes-cli";
@@ -8168,6 +8183,46 @@ function classifyDirectDispatch(params) {
8168
8183
  const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !liveStaleReason);
8169
8184
  return { ledgerOnlyStaleReason, isFreshUnacknowledged };
8170
8185
  }
8186
+ function buildLedgerDirectDispatchRecord(dispatch, ctx) {
8187
+ const taskId = directDispatchTaskId(dispatch);
8188
+ const terminal = ctx.terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8189
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8190
+ const live = sessionStatusFromNodes(ctx.nodes, dispatch.nodeId, dispatch.sessionId);
8191
+ const status = terminalStatus || live.status || "assigned";
8192
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8193
+ const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8194
+ status,
8195
+ isTerminalRow: terminalRow,
8196
+ hasTerminalStatus: Boolean(terminalStatus),
8197
+ liveStatus: live.status,
8198
+ liveStaleReason: live.staleReason,
8199
+ dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8200
+ });
8201
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8202
+ const { title, summary } = summarizeMessage(message);
8203
+ const record = {
8204
+ taskId,
8205
+ source: "direct",
8206
+ status,
8207
+ nodeId: dispatch.nodeId,
8208
+ sessionId: dispatch.sessionId,
8209
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8210
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8211
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary,
8212
+ message,
8213
+ taskMode: readString6(dispatch.payload?.taskMode),
8214
+ createdAt: dispatch.timestamp,
8215
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
8216
+ dispatchedAt: dispatch.timestamp,
8217
+ elapsedMs: elapsedSince(dispatch.timestamp, ctx.now),
8218
+ terminal: terminalRow,
8219
+ terminalKind: terminal?.kind,
8220
+ terminalAt: terminal?.timestamp,
8221
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
8222
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8223
+ };
8224
+ return { record, terminalRow };
8225
+ }
8171
8226
  function buildMeshActiveWorkSummary(activeWork) {
8172
8227
  const statusCounts = {
8173
8228
  pending: 0,
@@ -8273,49 +8328,13 @@ function buildMeshActiveWork(opts) {
8273
8328
  const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8274
8329
  const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
8275
8330
  for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
8276
- const taskId = directDispatchTaskId(dispatch);
8277
- if (dbTaskIds.has(taskId)) continue;
8278
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8279
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8280
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
8281
- const status = terminalStatus || live.status || "assigned";
8282
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8283
- const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8284
- status,
8285
- isTerminalRow: terminalRow,
8286
- hasTerminalStatus: Boolean(terminalStatus),
8287
- liveStatus: live.status,
8288
- liveStaleReason: live.staleReason,
8289
- dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8290
- });
8291
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8292
- const { title, summary: summary2 } = summarizeMessage(message);
8293
- const record = {
8294
- taskId,
8295
- source: "direct",
8296
- status,
8297
- nodeId: dispatch.nodeId,
8298
- sessionId: dispatch.sessionId,
8299
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8300
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8301
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
8302
- message,
8303
- taskMode: readString6(dispatch.payload?.taskMode),
8304
- createdAt: dispatch.timestamp,
8305
- updatedAt: terminal?.timestamp || dispatch.timestamp,
8306
- dispatchedAt: dispatch.timestamp,
8307
- elapsedMs: elapsedSince(dispatch.timestamp, now),
8308
- terminal: terminalRow,
8309
- terminalKind: terminal?.kind,
8310
- terminalAt: terminal?.timestamp,
8311
- staleReason: live.staleReason || ledgerOnlyStaleReason,
8312
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8313
- };
8331
+ if (dbTaskIds.has(directDispatchTaskId(dispatch))) continue;
8332
+ const { record, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
8314
8333
  if (terminalRow) {
8315
8334
  terminalDirectWork.push(record);
8316
8335
  if (opts.includeTerminalDirect !== true) continue;
8317
8336
  }
8318
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
8337
+ if (record.staleReason && !terminalRow) {
8319
8338
  staleDirectWork.push(record);
8320
8339
  continue;
8321
8340
  }
@@ -8325,48 +8344,12 @@ function buildMeshActiveWork(opts) {
8325
8344
  const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
8326
8345
  const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
8327
8346
  for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
8328
- const taskId = directDispatchTaskId(dispatch);
8329
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
8330
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
8331
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
8332
- const status = terminalStatus || live.status || "assigned";
8333
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
8334
- const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
8335
- status,
8336
- isTerminalRow: terminalRow,
8337
- hasTerminalStatus: Boolean(terminalStatus),
8338
- liveStatus: live.status,
8339
- liveStaleReason: live.staleReason,
8340
- dispatchedToIdleSession: dispatch.payload?.dispatchedToIdleSession === true
8341
- });
8342
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
8343
- const { title, summary: summary2 } = summarizeMessage(message);
8344
- const record = {
8345
- taskId,
8346
- source: "direct",
8347
- status,
8348
- nodeId: dispatch.nodeId,
8349
- sessionId: dispatch.sessionId,
8350
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
8351
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
8352
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
8353
- message,
8354
- taskMode: readString6(dispatch.payload?.taskMode),
8355
- createdAt: dispatch.timestamp,
8356
- updatedAt: terminal?.timestamp || dispatch.timestamp,
8357
- dispatchedAt: dispatch.timestamp,
8358
- elapsedMs: elapsedSince(dispatch.timestamp, now),
8359
- terminal: terminalRow,
8360
- terminalKind: terminal?.kind,
8361
- terminalAt: terminal?.timestamp,
8362
- staleReason: live.staleReason || ledgerOnlyStaleReason,
8363
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
8364
- };
8347
+ const { record, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
8365
8348
  if (terminalRow) {
8366
8349
  terminalDirectWork.push(record);
8367
8350
  if (opts.includeTerminalDirect !== true) continue;
8368
8351
  }
8369
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
8352
+ if (record.staleReason && !terminalRow) {
8370
8353
  staleDirectWork.push(record);
8371
8354
  continue;
8372
8355
  }
@@ -22017,7 +22000,7 @@ init_resolve_executable();
22017
22000
  import { existsSync as existsSync13, readFileSync as readFileSync10 } from "fs";
22018
22001
  import { join as join14, resolve as pathResolve } from "path";
22019
22002
  import { execFile as execFile3 } from "child_process";
22020
- import { createHash as createHash3 } from "crypto";
22003
+ import { createHash as createHash2 } from "crypto";
22021
22004
  import { promisify as promisify3 } from "util";
22022
22005
  import * as yaml3 from "js-yaml";
22023
22006
  var MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS = [
@@ -22124,7 +22107,7 @@ function computeStaleInputsDigest(workspace, staleInputs) {
22124
22107
  for (const relative5 of staleInputs ?? []) {
22125
22108
  const filePath = join14(workspace, relative5);
22126
22109
  try {
22127
- digest[relative5] = createHash3("sha256").update(readFileSync10(filePath)).digest("hex");
22110
+ digest[relative5] = createHash2("sha256").update(readFileSync10(filePath)).digest("hex");
22128
22111
  } catch {
22129
22112
  digest[relative5] = "absent";
22130
22113
  }
@@ -34371,6 +34354,9 @@ var lowFamilyRegistry = new Map(
34371
34354
  })
34372
34355
  );
34373
34356
 
34357
+ // src/commands/med-family/cli-agent.ts
34358
+ init_dist();
34359
+
34374
34360
  // src/commands/cli-manager.ts
34375
34361
  init_provider_cli_adapter();
34376
34362
  init_cli_detector();
@@ -34378,6 +34364,7 @@ init_config();
34378
34364
  init_state_store();
34379
34365
  init_workspaces();
34380
34366
  init_recent_activity();
34367
+ init_hash();
34381
34368
  init_coordinator_registry();
34382
34369
  import * as os21 from "os";
34383
34370
  import * as path27 from "path";
@@ -40782,7 +40769,7 @@ function hasConfigOverride(args, key) {
40782
40769
  function ensureEmptyDelegatedMcpConfig(workspace) {
40783
40770
  const baseDir = path27.join(os21.tmpdir(), "adhdev-delegated-agent-empty-mcp");
40784
40771
  mkdirSync13(baseDir, { recursive: true });
40785
- const workspaceHash = crypto5.createHash("sha256").update(path27.resolve(workspace || os21.tmpdir())).digest("hex").slice(0, 16);
40772
+ const workspaceHash = shortHash(path27.resolve(workspace || os21.tmpdir()));
40786
40773
  const filePath = path27.join(baseDir, `${workspaceHash}.json`);
40787
40774
  writeFileSync16(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
40788
40775
  return filePath;
@@ -41750,6 +41737,156 @@ Run 'adhdev doctor' for detailed diagnostics.`
41750
41737
  }
41751
41738
  };
41752
41739
 
41740
+ // src/commands/med-family/cli-agent.ts
41741
+ init_state_store();
41742
+ init_recent_activity();
41743
+ init_mesh_events_utils();
41744
+ var cliAgentHandlers = {
41745
+ launch_cli: async (ctx, args) => {
41746
+ const launchResult = await ctx.deps.cliManager.handleCliCommand("launch_cli", args);
41747
+ const meshNodeId = readStringValue(args?.settings?.meshNodeId);
41748
+ const meshId = readStringValue(args?.settings?.meshNodeFor);
41749
+ if (meshNodeId && meshId && launchResult?.success !== false) {
41750
+ try {
41751
+ const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
41752
+ const meshObj = getMesh2(meshId) ?? ctx.getCachedInlineMesh(meshId);
41753
+ const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, meshNodeId)) : void 0;
41754
+ const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
41755
+ if (bootstrapStatus === "running") {
41756
+ return { success: true, ...launchResult, bootstrapPending: true };
41757
+ }
41758
+ } catch {
41759
+ }
41760
+ }
41761
+ return launchResult;
41762
+ },
41763
+ stop_cli: async (ctx, args) => {
41764
+ return ctx.deps.cliManager.handleCliCommand("stop_cli", args);
41765
+ },
41766
+ set_cli_view_mode: async (ctx, args) => {
41767
+ return ctx.deps.cliManager.handleCliCommand("set_cli_view_mode", args);
41768
+ },
41769
+ record_provider_pty: async (ctx, args) => {
41770
+ return ctx.deps.cliManager.handleCliCommand("record_provider_pty", args);
41771
+ },
41772
+ agent_command: async (ctx, args) => {
41773
+ {
41774
+ const dispatchSessionId = readStringValue(args?.targetSessionId, args?.sessionId, args?.instanceId);
41775
+ const dispatchMeshContext = args?.meshContext;
41776
+ if (dispatchSessionId && dispatchMeshContext) {
41777
+ try {
41778
+ const inst = ctx.deps.instanceManager.getInstance(dispatchSessionId);
41779
+ if (inst && typeof inst.updateSettings === "function") {
41780
+ const stamp = buildMeshWorkerRelayStamp(
41781
+ inst.getState?.()?.settings,
41782
+ {
41783
+ meshId: dispatchMeshContext.meshId,
41784
+ nodeId: dispatchMeshContext.nodeId,
41785
+ coordinatorDaemonId: dispatchMeshContext.coordinatorDaemonId,
41786
+ // Session-level anchor: preserved across the P2P dispatch to a
41787
+ // remote worker so its completion echoes back to the right session.
41788
+ coordinatorSessionId: dispatchMeshContext.coordinatorSessionId
41789
+ }
41790
+ );
41791
+ if (stamp) inst.updateSettings(stamp);
41792
+ }
41793
+ } catch {
41794
+ }
41795
+ }
41796
+ }
41797
+ const agentResult = await ctx.deps.cliManager.handleCliCommand("agent_command", args);
41798
+ const meshCtx = args?.meshContext;
41799
+ const dispatchNodeId = readStringValue(meshCtx?.nodeId);
41800
+ const dispatchMeshId = readStringValue(meshCtx?.meshId);
41801
+ if (dispatchNodeId && dispatchMeshId && agentResult?.success !== false) {
41802
+ try {
41803
+ const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
41804
+ const meshObj = getMesh2(dispatchMeshId) ?? ctx.getCachedInlineMesh(dispatchMeshId);
41805
+ const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, dispatchNodeId)) : void 0;
41806
+ const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
41807
+ if (bootstrapStatus === "running") {
41808
+ return {
41809
+ success: true,
41810
+ ...agentResult,
41811
+ dispatchAcknowledgementRisk: true,
41812
+ dispatchAcknowledgementRiskReason: "bootstrap_still_running",
41813
+ nextAction: "Wait for worktree_bootstrap_complete event before dispatching work to this node."
41814
+ };
41815
+ }
41816
+ } catch {
41817
+ }
41818
+ }
41819
+ return agentResult;
41820
+ },
41821
+ // ─── Logs ───
41822
+ list_saved_sessions: async (ctx, args) => {
41823
+ const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
41824
+ const kind = args?.kind === "acp" ? "acp" : "cli";
41825
+ if (!providerType) {
41826
+ return { success: false, error: "providerType required" };
41827
+ }
41828
+ const wantsAll = args?.all === true;
41829
+ const offset = wantsAll ? 0 : Math.max(0, Number(args?.offset) || 0);
41830
+ const limit = wantsAll ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.min(100, Number(args?.limit) || 30));
41831
+ const requestedWorkspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
41832
+ const requestedProviderSessionId = typeof args?.providerSessionId === "string" ? args.providerSessionId.trim() : typeof args?.activeProviderSessionId === "string" ? args.activeProviderSessionId.trim() : "";
41833
+ const providerMeta = ctx.deps.providerLoader.resolve?.(providerType) || ctx.deps.providerLoader.getMeta(providerType);
41834
+ const { sessions: historySessions, hasMore, source } = listProviderHistorySessions(providerType, {
41835
+ canonicalHistory: providerMeta?.nativeHistory,
41836
+ offset,
41837
+ limit,
41838
+ historyBehavior: providerMeta?.historyBehavior,
41839
+ scripts: providerMeta?.scripts
41840
+ });
41841
+ const state = loadState();
41842
+ const savedSessions = getSavedProviderSessions(state, { providerType, kind });
41843
+ const recentSessions = getRecentActivity(state, 200).filter((entry) => entry.providerType === providerType && entry.kind === kind && entry.providerSessionId);
41844
+ const savedSessionById = new Map(savedSessions.map((entry) => [entry.providerSessionId, entry]));
41845
+ const recentSessionById = new Map(recentSessions.map((entry) => [entry.providerSessionId, entry]));
41846
+ const canResumeById = supportsExplicitSessionResume(providerMeta?.resume);
41847
+ return {
41848
+ success: true,
41849
+ sessions: historySessions.map((session) => {
41850
+ const saved = savedSessionById.get(session.historySessionId);
41851
+ const recent = recentSessionById.get(session.historySessionId);
41852
+ const workspace = saved?.workspace || recent?.workspace || session.workspace || (requestedWorkspace && requestedProviderSessionId === session.historySessionId ? requestedWorkspace : void 0);
41853
+ return {
41854
+ id: session.historySessionId,
41855
+ providerSessionId: session.historySessionId,
41856
+ providerType,
41857
+ providerName: saved?.providerName || recent?.providerName || providerType,
41858
+ kind: saved?.kind || recent?.kind || kind,
41859
+ title: saved?.title || recent?.title || session.sessionTitle || session.preview || providerType,
41860
+ workspace,
41861
+ summaryMetadata: saved?.summaryMetadata || recent?.summaryMetadata,
41862
+ preview: session.preview,
41863
+ messageCount: session.messageCount,
41864
+ firstMessageAt: session.firstMessageAt,
41865
+ lastMessageAt: session.lastMessageAt,
41866
+ canResume: !!workspace && canResumeById,
41867
+ historySource: session.source,
41868
+ sourcePath: session.sourcePath,
41869
+ sourceMtimeMs: session.sourceMtimeMs
41870
+ };
41871
+ }),
41872
+ hasMore,
41873
+ source
41874
+ };
41875
+ },
41876
+ // ─── restart_session: IDE / CLI / ACP unified ───
41877
+ restart_session: async (ctx, args) => {
41878
+ const targetType = args?.cliType || args?.agentType || args?.ideType;
41879
+ if (!targetType) throw new Error("cliType or ideType required");
41880
+ const isIde = ctx.deps.cdpManagers.has(targetType) || ctx.deps.providerLoader.getMeta(targetType)?.category === "ide";
41881
+ if (isIde) {
41882
+ await ctx.stopIde(targetType, true);
41883
+ const launchResult = await ctx.launchIde({ ideType: targetType, enableCdp: true, workspace: args?.workspace });
41884
+ return { success: true, restarted: true, ideType: targetType, launch: launchResult };
41885
+ }
41886
+ return ctx.deps.cliManager.handleCliCommand("restart_session", args);
41887
+ }
41888
+ };
41889
+
41753
41890
  // src/launch.ts
41754
41891
  import { exec as exec4, spawn as spawn3 } from "child_process";
41755
41892
  import * as net from "net";
@@ -45575,12 +45712,1342 @@ function getAvailableIdeIds() {
45575
45712
  return getProviderLoader().getAvailableIdeTypes();
45576
45713
  }
45577
45714
 
45578
- // src/commands/router.ts
45715
+ // src/commands/med-family/ide.ts
45579
45716
  init_config();
45580
45717
  init_state_store();
45581
45718
  init_workspaces();
45582
45719
  init_recent_activity();
45583
45720
  init_cli_detector();
45721
+ init_logger();
45722
+ async function launchIde(ctx, args) {
45723
+ const ideKey = args?.ideId || args?.ideType;
45724
+ const resolvedWorkspace = resolveIdeLaunchWorkspace(
45725
+ {
45726
+ workspace: args?.workspace,
45727
+ workspaceId: args?.workspaceId,
45728
+ useDefaultWorkspace: args?.useDefaultWorkspace
45729
+ },
45730
+ loadConfig()
45731
+ );
45732
+ const launchArgs = {
45733
+ ideId: ideKey,
45734
+ workspace: resolvedWorkspace,
45735
+ newWindow: args?.newWindow
45736
+ };
45737
+ LOG.info("LaunchIDE", `target=${ideKey || "auto"}`);
45738
+ const result = await launchWithCdp(launchArgs);
45739
+ if (result.success && result.port && result.ideId && !ctx.deps.cdpManagers.has(result.ideId)) {
45740
+ const logFn = ctx.deps.getCdpLogFn ? ctx.deps.getCdpLogFn(result.ideId) : LOG.forComponent(`CDP:${result.ideId}`).asLogFn();
45741
+ const provider = ctx.deps.providerLoader.getMeta(result.ideId);
45742
+ const manager = new DaemonCdpManager(result.port, logFn, void 0, provider?.targetFilter);
45743
+ const connected = await manager.connect();
45744
+ if (connected) {
45745
+ registerExtensionProviders(ctx.deps.providerLoader, manager, result.ideId);
45746
+ ctx.deps.cdpManagers.set(result.ideId, manager);
45747
+ LOG.info("CDP", `Connected: ${result.ideId} (port ${result.port})`);
45748
+ LOG.info("CDP", `${ctx.deps.cdpManagers.size} IDE(s) connected`);
45749
+ ctx.deps.onCdpManagerCreated?.(result.ideId, manager);
45750
+ }
45751
+ }
45752
+ ctx.deps.onIdeConnected?.();
45753
+ try {
45754
+ const results = await detectIDEs(ctx.deps.providerLoader);
45755
+ ctx.deps.detectedIdes.value = results;
45756
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
45757
+ } catch {
45758
+ }
45759
+ if (result.success && resolvedWorkspace) {
45760
+ try {
45761
+ const next = appendRecentActivity(loadState(), {
45762
+ kind: "ide",
45763
+ providerType: result.ideId || ideKey,
45764
+ providerName: result.ideId || ideKey,
45765
+ workspace: resolvedWorkspace,
45766
+ title: result.ideId || ideKey
45767
+ });
45768
+ saveState(next);
45769
+ } catch {
45770
+ }
45771
+ } else if (result.success && (result.ideId || ideKey)) {
45772
+ try {
45773
+ saveState(appendRecentActivity(loadState(), {
45774
+ kind: "ide",
45775
+ providerType: result.ideId || ideKey,
45776
+ providerName: result.ideId || ideKey,
45777
+ title: result.ideId || ideKey
45778
+ }));
45779
+ } catch {
45780
+ }
45781
+ }
45782
+ return { ...result };
45783
+ }
45784
+ var ideHandlers = {
45785
+ // ─── IDE stop ───
45786
+ stop_ide: async (ctx, args) => {
45787
+ const ideType = args?.ideType;
45788
+ if (!ideType) throw new Error("ideType required");
45789
+ const killProcess = args?.killProcess !== false;
45790
+ await ctx.stopIde(ideType, killProcess);
45791
+ try {
45792
+ const results = await detectIDEs(ctx.deps.providerLoader);
45793
+ ctx.deps.detectedIdes.value = results;
45794
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
45795
+ } catch {
45796
+ }
45797
+ return { success: true, ideType, stopped: true, processKilled: killProcess };
45798
+ },
45799
+ // ─── IDE restart ───
45800
+ restart_ide: async (ctx, args) => {
45801
+ const ideType = args?.ideType;
45802
+ if (!ideType) throw new Error("ideType required");
45803
+ await ctx.stopIde(ideType, true);
45804
+ const launchResult = await ctx.launchIde({ ideType, enableCdp: true, workspace: args?.workspace });
45805
+ return { success: true, ideType, restarted: true, launch: launchResult };
45806
+ },
45807
+ // ─── IDE launch + CDP connect ───
45808
+ launch_ide: async (ctx, args) => {
45809
+ return launchIde(ctx, args);
45810
+ },
45811
+ // ─── Detect providers ───
45812
+ detect_provider: async (ctx, args) => {
45813
+ const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : "";
45814
+ if (!providerType) return { success: false, error: "providerType is required" };
45815
+ const normalizedType = ctx.deps.providerLoader.resolveAlias(providerType);
45816
+ const provider = ctx.deps.providerLoader.getByAlias(providerType);
45817
+ if (!provider) return { success: false, error: `Provider not found: ${providerType}` };
45818
+ if (provider.category !== "cli" && provider.category !== "acp") {
45819
+ return { success: false, error: `Provider detection is only supported for CLI/ACP providers: ${providerType}` };
45820
+ }
45821
+ if (!ctx.deps.providerLoader.isMachineProviderEnabled(normalizedType)) {
45822
+ return { success: false, error: `Provider is disabled on this machine: ${providerType}` };
45823
+ }
45824
+ const detected = await detectCLI(normalizedType, ctx.deps.providerLoader, { includeVersion: false });
45825
+ ctx.deps.providerLoader.setCliDetectionResults([{
45826
+ id: normalizedType,
45827
+ installed: !!detected,
45828
+ path: detected?.path
45829
+ }], false);
45830
+ ctx.deps.onStatusChange?.();
45831
+ return {
45832
+ success: true,
45833
+ providerType: normalizedType,
45834
+ detected: !!detected,
45835
+ path: detected?.path || null
45836
+ };
45837
+ },
45838
+ // ─── Detect IDEs ───
45839
+ detect_ides: async (ctx, _args) => {
45840
+ const results = await detectIDEs(ctx.deps.providerLoader);
45841
+ ctx.deps.detectedIdes.value = results;
45842
+ ctx.deps.providerLoader.setIdeDetectionResults(results, true);
45843
+ return { success: true, detectedInfo: results };
45844
+ }
45845
+ };
45846
+
45847
+ // src/commands/med-family/mesh-crud.ts
45848
+ init_dist();
45849
+ init_mesh_host_ownership();
45850
+ init_mesh_events();
45851
+ init_config();
45852
+ var meshCrudHandlers = {
45853
+ list_meshes: async (_ctx, _args) => {
45854
+ try {
45855
+ const { listMeshes: listMeshes2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45856
+ return { success: true, meshes: listMeshes2() };
45857
+ } catch (e) {
45858
+ return { success: false, error: e.message };
45859
+ }
45860
+ },
45861
+ get_mesh: async (ctx, args) => {
45862
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
45863
+ if (!meshId) return { success: false, error: "meshId required" };
45864
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
45865
+ if (!meshRecord?.mesh) return { success: false, error: "Mesh not found" };
45866
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
45867
+ const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
45868
+ const directTruth = await hydrateInlineMeshDirectTruth({
45869
+ mesh: meshRecord.mesh,
45870
+ meshSource: meshRecord.source,
45871
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
45872
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
45873
+ statusInstanceId: ctx.deps.statusInstanceId,
45874
+ localMachineId: loadConfig().machineId || "",
45875
+ probeRemotePeers,
45876
+ probeCache: ctx.meshGitProbeCache
45877
+ });
45878
+ const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
45879
+ const sourceOfTruth = {
45880
+ membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
45881
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
45882
+ directPeerTruth: {
45883
+ required: requireDirectPeerTruth,
45884
+ satisfied: directTruthSatisfied,
45885
+ directEvidenceCount: directTruth.directEvidenceCount,
45886
+ localConfirmedCount: directTruth.localConfirmedCount,
45887
+ peerAttemptedCount: directTruth.peerAttemptedCount,
45888
+ peerConfirmedCount: directTruth.peerConfirmedCount,
45889
+ unavailableNodeIds: directTruth.unavailableNodeIds
45890
+ }
45891
+ };
45892
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
45893
+ return {
45894
+ success: false,
45895
+ code: "mesh_direct_peer_truth_unavailable",
45896
+ error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.",
45897
+ sourceOfTruth
45898
+ };
45899
+ }
45900
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
45901
+ },
45902
+ create_mesh: async (_ctx, args) => {
45903
+ const name = typeof args?.name === "string" ? args.name.trim() : "";
45904
+ const repoIdentity = typeof args?.repoIdentity === "string" ? args.repoIdentity.trim() : "";
45905
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === "string" ? args.repoRemoteUrl.trim() : void 0;
45906
+ const defaultBranch = typeof args?.defaultBranch === "string" ? args.defaultBranch.trim() : void 0;
45907
+ if (!name) return { success: false, error: "name required" };
45908
+ try {
45909
+ const { createMesh: createMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45910
+ const meshHost = args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost) ? args.meshHost : void 0;
45911
+ const mesh = createMesh2({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
45912
+ return { success: true, mesh };
45913
+ } catch (e) {
45914
+ return { success: false, error: e.message };
45915
+ }
45916
+ },
45917
+ update_mesh: async (ctx, args) => {
45918
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
45919
+ if (!meshId) return { success: false, error: "meshId required" };
45920
+ try {
45921
+ const { updateMesh: updateMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45922
+ const patch = {};
45923
+ if (typeof args?.name === "string") patch.name = args.name;
45924
+ if (typeof args?.defaultBranch === "string") patch.defaultBranch = args.defaultBranch;
45925
+ if (args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy)) patch.policy = args.policy;
45926
+ if (args?.coordinator && typeof args.coordinator === "object" && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
45927
+ if (args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
45928
+ if (!Object.keys(patch).length) return { success: false, error: "No updates provided" };
45929
+ const mesh = updateMesh2(meshId, patch);
45930
+ if (!mesh) return { success: false, error: "Mesh not found" };
45931
+ ctx.inlineMeshCache.set(meshId, mesh);
45932
+ ctx.invalidateAggregateMeshStatus(meshId);
45933
+ return { success: true, mesh };
45934
+ } catch (e) {
45935
+ return { success: false, error: e.message };
45936
+ }
45937
+ },
45938
+ delete_mesh: async (_ctx, args) => {
45939
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
45940
+ if (!meshId) return { success: false, error: "meshId required" };
45941
+ try {
45942
+ const { deleteMesh: deleteMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45943
+ const deleted = deleteMesh2(meshId);
45944
+ return { success: true, deleted };
45945
+ } catch (e) {
45946
+ return { success: false, error: e.message };
45947
+ }
45948
+ },
45949
+ add_mesh_node: async (ctx, args) => {
45950
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
45951
+ const workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
45952
+ if (!meshId) return { success: false, error: "meshId required" };
45953
+ if (!workspace) return { success: false, error: "workspace required" };
45954
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node addition");
45955
+ if (ownerFailure) return ownerFailure;
45956
+ try {
45957
+ const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45958
+ const providerPriority = Array.isArray(args?.providerPriority) ? args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean) : [];
45959
+ const readOnly = args?.readOnly === true;
45960
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
45961
+ const policy = {
45962
+ ...readOnly ? { readOnly: true } : {},
45963
+ ...providerPriority.length ? { providerPriority } : {},
45964
+ ...providerRoles.length ? { providerRoles } : {}
45965
+ };
45966
+ const role = normalizeMeshDaemonRole(args?.role);
45967
+ const daemonId = typeof args?.daemonId === "string" && args.daemonId.trim() ? args.daemonId.trim() : void 0;
45968
+ const machineId = typeof args?.machineId === "string" && args.machineId.trim() ? args.machineId.trim() : void 0;
45969
+ const repoRoot = typeof args?.repoRoot === "string" && args.repoRoot.trim() ? args.repoRoot.trim() : void 0;
45970
+ const node = addNode2(meshId, {
45971
+ workspace,
45972
+ ...repoRoot ? { repoRoot } : {},
45973
+ ...daemonId ? { daemonId } : {},
45974
+ ...machineId ? { machineId } : {},
45975
+ ...policy ? { policy } : {},
45976
+ ...role ? { role } : {}
45977
+ });
45978
+ if (!node) return { success: false, error: "Mesh not found" };
45979
+ ctx.invalidateAggregateMeshStatus(meshId);
45980
+ return { success: true, node };
45981
+ } catch (e) {
45982
+ return { success: false, error: e.message };
45983
+ }
45984
+ },
45985
+ update_mesh_node: async (ctx, args) => {
45986
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
45987
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
45988
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
45989
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node update");
45990
+ if (ownerFailure) return ownerFailure;
45991
+ try {
45992
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
45993
+ const policy = args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy) ? { ...args.policy } : {};
45994
+ if (Array.isArray(args?.providerPriority)) {
45995
+ const providerPriority = args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean);
45996
+ delete policy.provider_priority;
45997
+ if (providerPriority.length) {
45998
+ policy.providerPriority = providerPriority;
45999
+ } else {
46000
+ delete policy.providerPriority;
46001
+ }
46002
+ }
46003
+ if (Array.isArray(args?.providerRoles)) {
46004
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
46005
+ if (providerRoles.length) {
46006
+ policy.providerRoles = providerRoles;
46007
+ } else {
46008
+ delete policy.providerRoles;
46009
+ }
46010
+ }
46011
+ const patch = { policy };
46012
+ if (typeof args?.systemPrompt === "string") {
46013
+ const trimmed = args.systemPrompt.trim();
46014
+ patch.systemPrompt = trimmed || void 0;
46015
+ } else if (args?.systemPrompt === null) {
46016
+ patch.systemPrompt = void 0;
46017
+ }
46018
+ const node = updateNode2(meshId, nodeId, patch);
46019
+ if (!node) return { success: false, error: "Mesh node not found" };
46020
+ ctx.invalidateAggregateMeshStatus(meshId);
46021
+ return { success: true, node };
46022
+ } catch (e) {
46023
+ return { success: false, error: e.message };
46024
+ }
46025
+ },
46026
+ cleanup_mesh_sessions: async (ctx, args) => {
46027
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46028
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46029
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46030
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node removal");
46031
+ if (ownerFailure) return ownerFailure;
46032
+ try {
46033
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46034
+ const mesh = meshRecord?.mesh;
46035
+ if (!mesh) return { success: false, error: "Mesh not found" };
46036
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46037
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
46038
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
46039
+ const sessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : void 0;
46040
+ const result = await ctx.cleanupMeshSessions({
46041
+ meshId,
46042
+ nodeId,
46043
+ node,
46044
+ mode,
46045
+ sessionIds,
46046
+ dryRun: args?.dryRun === true,
46047
+ source: "mesh_cleanup_sessions"
46048
+ });
46049
+ return result;
46050
+ } catch (e) {
46051
+ return { success: false, error: e.message };
46052
+ }
46053
+ },
46054
+ remove_mesh_node: async (ctx, args) => {
46055
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46056
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46057
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46058
+ try {
46059
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46060
+ const mesh = meshRecord?.mesh;
46061
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46062
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
46063
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : "";
46064
+ const nodeMachineId = readMeshNodeMachineId(node) || "";
46065
+ const selfDaemonId = ctx.deps.statusInstanceId || "";
46066
+ const selfMachineId = (() => {
46067
+ try {
46068
+ return loadConfig().machineId || "";
46069
+ } catch {
46070
+ return "";
46071
+ }
46072
+ })();
46073
+ const isCoordinatorBaseNode = !!selfDaemonId && (nodeDaemonId === selfDaemonId || nodeMachineId === selfDaemonId) || !!selfMachineId && (nodeDaemonId === selfMachineId || nodeMachineId === selfMachineId);
46074
+ if (isCoordinatorBaseNode) {
46075
+ return {
46076
+ success: false,
46077
+ removed: false,
46078
+ code: "mesh_remove_coordinator_base_node_protected",
46079
+ 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.`,
46080
+ 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."
46081
+ };
46082
+ }
46083
+ }
46084
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
46085
+ args?.sessionCleanupMode ?? args?.session_cleanup_mode ?? mesh?.policy?.sessionCleanupOnNodeRemove
46086
+ );
46087
+ const explicitSessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
46088
+ let sessionCleanup;
46089
+ if (node && sessionCleanupMode !== "preserve") {
46090
+ sessionCleanup = await ctx.cleanupMeshSessions({
46091
+ meshId,
46092
+ nodeId,
46093
+ node,
46094
+ mode: sessionCleanupMode,
46095
+ ...explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {},
46096
+ source: "mesh_remove_node"
46097
+ });
46098
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
46099
+ }
46100
+ let worktreeCleanup;
46101
+ if (node?.isLocalWorktree) {
46102
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
46103
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch;
46104
+ if (isRemoteWorktree) {
46105
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "remove_mesh_node", {
46106
+ ...typeof args === "object" && args !== null ? args : {},
46107
+ _meshDirectDispatch: true
46108
+ });
46109
+ return forwarded ?? { success: false, error: "no response from remote node" };
46110
+ }
46111
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
46112
+ if (cleanupResult.success === false) {
46113
+ return {
46114
+ success: false,
46115
+ removed: false,
46116
+ code: cleanupResult.code,
46117
+ error: cleanupResult.error,
46118
+ recoveryHint: cleanupResult.recoveryHint,
46119
+ ...sessionCleanup ? { sessionCleanup } : {},
46120
+ worktreeCleanup: cleanupResult
46121
+ };
46122
+ }
46123
+ worktreeCleanup = cleanupResult;
46124
+ }
46125
+ let removed = false;
46126
+ if (meshRecord?.inline) {
46127
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
46128
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
46129
+ if (!removed && !node) removed = true;
46130
+ } else {
46131
+ const { removeNode: removeNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46132
+ removed = removeNode2(meshId, nodeId);
46133
+ if (!removed && !node) removed = true;
46134
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
46135
+ }
46136
+ if (removed) {
46137
+ try {
46138
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46139
+ appendLedgerEntry2(meshId, {
46140
+ kind: "node_removed",
46141
+ nodeId,
46142
+ payload: {
46143
+ worktree: !!node?.isLocalWorktree,
46144
+ sessionCleanupMode,
46145
+ workspace: typeof node?.workspace === "string" ? node.workspace : void 0,
46146
+ daemonId: typeof node?.daemonId === "string" ? node.daemonId : void 0,
46147
+ worktreeBranch: typeof node?.worktreeBranch === "string" ? node.worktreeBranch : void 0,
46148
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === "string" ? worktreeCleanup.fallback : void 0,
46149
+ forced: worktreeCleanup?.forced === true ? true : void 0,
46150
+ forceFallbackReason: typeof worktreeCleanup?.reason === "string" ? worktreeCleanup.reason : void 0
46151
+ }
46152
+ });
46153
+ } catch {
46154
+ }
46155
+ }
46156
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === "string" ? worktreeCleanup.residueWarning : void 0;
46157
+ return {
46158
+ success: true,
46159
+ removed,
46160
+ ...residueWarning ? { residueWarning } : {},
46161
+ ...sessionCleanup ? { sessionCleanup } : {},
46162
+ ...worktreeCleanup ? { worktreeCleanup } : {}
46163
+ };
46164
+ } catch (e) {
46165
+ return { success: false, error: e.message };
46166
+ }
46167
+ },
46168
+ clone_mesh_node: async (ctx, args) => {
46169
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46170
+ const sourceNodeId = typeof args?.sourceNodeId === "string" ? args.sourceNodeId.trim() : "";
46171
+ const branch = typeof args?.branch === "string" ? args.branch.trim() : "";
46172
+ const baseBranch = typeof args?.baseBranch === "string" ? args.baseBranch.trim() : void 0;
46173
+ if (!meshId) return { success: false, error: "meshId required" };
46174
+ if (!sourceNodeId) return { success: false, error: "sourceNodeId required" };
46175
+ if (!branch) return { success: false, error: "branch required" };
46176
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "worktree clone");
46177
+ if (ownerFailure) return ownerFailure;
46178
+ try {
46179
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46180
+ const mesh = meshRecord?.mesh;
46181
+ if (!mesh) return { success: false, error: "Mesh not found" };
46182
+ const sourceNode = mesh.nodes?.find((n) => meshNodeIdMatches(n, sourceNodeId));
46183
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
46184
+ const sourceDaemonId = typeof sourceNode.daemonId === "string" ? sourceNode.daemonId.trim() : void 0;
46185
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46186
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, "clone_mesh_node", {
46187
+ ...typeof args === "object" && args !== null ? args : {},
46188
+ _meshDirectDispatch: true
46189
+ });
46190
+ return forwarded ?? { success: false, error: "no response from remote node" };
46191
+ }
46192
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
46193
+ const { createWorktree: createWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
46194
+ const result = await createWorktree2({
46195
+ repoRoot,
46196
+ branch,
46197
+ baseBranch,
46198
+ meshName: mesh.name
46199
+ });
46200
+ let node;
46201
+ if (meshRecord.inline) {
46202
+ const { randomUUID: randomUUID15 } = await import("crypto");
46203
+ node = {
46204
+ id: `node_${randomUUID15().replace(/-/g, "")}`,
46205
+ workspace: result.worktreePath,
46206
+ repoRoot: result.worktreePath,
46207
+ daemonId: sourceNode.daemonId,
46208
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
46209
+ userOverrides: { ...sourceNode.userOverrides || {} },
46210
+ policy: { ...sourceNode.policy || {} },
46211
+ isLocalWorktree: true,
46212
+ worktreeBranch: result.branch,
46213
+ clonedFromNodeId: sourceNodeId
46214
+ };
46215
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46216
+ } else {
46217
+ const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46218
+ node = addNode2(meshId, {
46219
+ workspace: result.worktreePath,
46220
+ repoRoot: result.worktreePath,
46221
+ daemonId: sourceNode.daemonId,
46222
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
46223
+ userOverrides: { ...sourceNode.userOverrides || {} },
46224
+ isLocalWorktree: true,
46225
+ worktreeBranch: result.branch,
46226
+ clonedFromNodeId: sourceNodeId,
46227
+ policy: { ...sourceNode.policy || {} }
46228
+ });
46229
+ if (!node) return { success: false, error: "Failed to register worktree node" };
46230
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
46231
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
46232
+ ctx.invalidateAggregateMeshStatus(meshId);
46233
+ }
46234
+ const persistWorktreeSetupState = async (bootstrapState2) => {
46235
+ node.worktreeBootstrap = bootstrapState2;
46236
+ if (meshRecord.inline) {
46237
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46238
+ return;
46239
+ }
46240
+ try {
46241
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46242
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
46243
+ ctx.invalidateAggregateMeshStatus(meshId);
46244
+ } catch {
46245
+ }
46246
+ };
46247
+ const appendCloneLedger = async (initSubmodules2, bootstrapState2) => {
46248
+ try {
46249
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46250
+ appendLedgerEntry2(meshId, {
46251
+ kind: "node_cloned",
46252
+ nodeId: node.id,
46253
+ payload: {
46254
+ sourceNodeId,
46255
+ branch: result.branch,
46256
+ worktreePath: result.worktreePath,
46257
+ submodulesInitialized: initSubmodules2,
46258
+ worktreeBootstrap: {
46259
+ status: bootstrapState2.status,
46260
+ required: bootstrapState2.required,
46261
+ configSource: bootstrapState2.configSource,
46262
+ configSourceType: bootstrapState2.configSourceType,
46263
+ lastCommand: bootstrapState2.lastCommand,
46264
+ exitCode: bootstrapState2.exitCode
46265
+ }
46266
+ }
46267
+ });
46268
+ } catch {
46269
+ }
46270
+ };
46271
+ const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
46272
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
46273
+ const runningBootstrapState = {
46274
+ status: "running",
46275
+ required: loadedBootstrap.config?.required !== false,
46276
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
46277
+ configSourceType: loadedBootstrap.sourceType,
46278
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
46279
+ };
46280
+ await persistWorktreeSetupState(runningBootstrapState);
46281
+ const finishWorktreeSetup = async () => {
46282
+ let submodulesInitialized2 = false;
46283
+ if (initSubmodules) {
46284
+ try {
46285
+ const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
46286
+ await runGit3(
46287
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
46288
+ ["submodule", "update", "--init", "--recursive"],
46289
+ { timeoutMs: 12e4 }
46290
+ );
46291
+ submodulesInitialized2 = true;
46292
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
46293
+ if (sourceWorkspace) {
46294
+ try {
46295
+ const { runGit: rg } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
46296
+ const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
46297
+ const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
46298
+ const sourceStatusOut = await rg(sourceCtx, ["submodule", "status", "oss"], { timeoutMs: 1e4 });
46299
+ const sourceStatusLine = (typeof sourceStatusOut === "string" ? sourceStatusOut : sourceStatusOut?.stdout ?? "").trim();
46300
+ const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
46301
+ const sourceSha = sourceShaMatch?.[1];
46302
+ if (sourceSha) {
46303
+ const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
46304
+ const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
46305
+ const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
46306
+ if (worktreeOssSha !== sourceSha) {
46307
+ await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
46308
+ await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
46309
+ await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
46310
+ await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
46311
+ console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
46312
+ }
46313
+ }
46314
+ } catch (ossErr) {
46315
+ console.warn("[mesh] oss submodule sync to source HEAD failed (best-effort):", ossErr.message);
46316
+ }
46317
+ }
46318
+ } catch (subErr) {
46319
+ console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
46320
+ }
46321
+ }
46322
+ const bootstrapState2 = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
46323
+ await persistWorktreeSetupState(bootstrapState2);
46324
+ await appendCloneLedger(submodulesInitialized2, bootstrapState2);
46325
+ return { submodulesInitialized: submodulesInitialized2, bootstrapState: bootstrapState2 };
46326
+ };
46327
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8e3);
46328
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs) ? Math.min(Math.max(requestedSetupWaitMs, 0), 14e3) : 8e3;
46329
+ const setupPromise = finishWorktreeSetup();
46330
+ const setupResult = await Promise.race([
46331
+ setupPromise.then((value) => ({ completed: true, value })),
46332
+ new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
46333
+ ]);
46334
+ const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
46335
+ try {
46336
+ const durationMs = Date.now() - startedAtMs;
46337
+ const event = `worktree_${eventStatus2}`;
46338
+ const metadataEvent = {
46339
+ source: "clone_mesh_node_bootstrap",
46340
+ nodeId: node.id,
46341
+ status: eventStatus2,
46342
+ worktreePath: result.worktreePath,
46343
+ durationMs,
46344
+ bootstrapStatus: bootstrapState2.status,
46345
+ ...bootstrapState2.error ? { error: bootstrapState2.error } : {},
46346
+ ...bootstrapState2.exitCode !== void 0 ? { exitCode: bootstrapState2.exitCode } : {},
46347
+ ...extraPayload || {}
46348
+ };
46349
+ if (typeof ctx.deps.instanceManager?.getByCategory === "function") {
46350
+ const forwarded = handleMeshForwardEvent(
46351
+ { instanceManager: ctx.deps.instanceManager },
46352
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent }
46353
+ );
46354
+ if (forwarded?.success === true) return;
46355
+ }
46356
+ queuePendingMeshCoordinatorEvent({
46357
+ event,
46358
+ meshId,
46359
+ nodeLabel: node.id,
46360
+ nodeId: node.id,
46361
+ workspace: result.worktreePath,
46362
+ metadataEvent,
46363
+ queuedAt: Date.now()
46364
+ });
46365
+ } catch {
46366
+ }
46367
+ };
46368
+ const bootstrapStartedMs = Date.now();
46369
+ if (!setupResult.completed) {
46370
+ setupPromise.then(({ bootstrapState: bootstrapState2 }) => {
46371
+ emitBootstrapEvent("bootstrap_complete", bootstrapState2, bootstrapStartedMs);
46372
+ }).catch((error) => {
46373
+ const failedState = {
46374
+ ...runningBootstrapState,
46375
+ status: "failed",
46376
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
46377
+ error: error?.message || String(error)
46378
+ };
46379
+ void persistWorktreeSetupState(failedState);
46380
+ void appendCloneLedger(false, failedState);
46381
+ emitBootstrapEvent("bootstrap_failed", failedState, bootstrapStartedMs, { error: error?.message || String(error) });
46382
+ });
46383
+ return {
46384
+ success: true,
46385
+ async: true,
46386
+ status: "accepted",
46387
+ node,
46388
+ worktreePath: result.worktreePath,
46389
+ branch: result.branch,
46390
+ worktreeBootstrap: runningBootstrapState,
46391
+ worktreeSetup: {
46392
+ status: "running",
46393
+ setupWaitMs,
46394
+ message: "Worktree node is registered; submodule/bootstrap setup is continuing in the background."
46395
+ }
46396
+ };
46397
+ }
46398
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
46399
+ emitBootstrapEvent("bootstrap_complete", bootstrapState, bootstrapStartedMs);
46400
+ return {
46401
+ success: true,
46402
+ node,
46403
+ worktreePath: result.worktreePath,
46404
+ branch: result.branch,
46405
+ submodulesInitialized,
46406
+ worktreeBootstrap: bootstrapState
46407
+ };
46408
+ } catch (e) {
46409
+ return { success: false, error: e.message };
46410
+ }
46411
+ },
46412
+ retry_mesh_node_bootstrap: async (ctx, args) => {
46413
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46414
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46415
+ if (!meshId) return { success: false, error: "meshId required" };
46416
+ if (!nodeId) return { success: false, error: "nodeId required" };
46417
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "bootstrap retry");
46418
+ if (ownerFailure) return ownerFailure;
46419
+ try {
46420
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46421
+ const mesh = meshRecord?.mesh;
46422
+ if (!mesh) return { success: false, error: "Mesh not found" };
46423
+ const node = mesh.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46424
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
46425
+ if (!node.isLocalWorktree) return { success: false, error: "Node is not a local worktree node" };
46426
+ const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
46427
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46428
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "retry_mesh_node_bootstrap", {
46429
+ ...typeof args === "object" && args !== null ? args : {},
46430
+ _meshDirectDispatch: true
46431
+ });
46432
+ return forwarded ?? { success: false, error: "no response from remote node" };
46433
+ }
46434
+ const currentBootstrap = node.worktreeBootstrap;
46435
+ if (currentBootstrap?.status === "running") {
46436
+ return { success: false, error: "Bootstrap is already running for this node" };
46437
+ }
46438
+ const worktreePath = node.workspace || node.repoRoot;
46439
+ if (!worktreePath) return { success: false, error: "Node has no workspace path" };
46440
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
46441
+ const runningState = {
46442
+ status: "running",
46443
+ required: loadedBootstrap.config?.required !== false,
46444
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
46445
+ configSourceType: loadedBootstrap.sourceType,
46446
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
46447
+ };
46448
+ const persistState = async (bootstrapState2) => {
46449
+ node.worktreeBootstrap = bootstrapState2;
46450
+ if (meshRecord.inline) {
46451
+ ctx.updateInlineMeshNode(meshId, mesh, node);
46452
+ return;
46453
+ }
46454
+ try {
46455
+ const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46456
+ updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
46457
+ ctx.invalidateAggregateMeshStatus(meshId);
46458
+ } catch {
46459
+ }
46460
+ };
46461
+ await persistState(runningState);
46462
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
46463
+ await persistState(bootstrapState);
46464
+ return { success: true, bootstrapState };
46465
+ } catch (e) {
46466
+ return { success: false, error: e.message };
46467
+ }
46468
+ }
46469
+ };
46470
+
46471
+ // src/commands/med-family/mesh-host-pairing.ts
46472
+ init_mesh_host_ownership();
46473
+ var meshHostPairingHandlers = {
46474
+ get_mesh_host_pairing: async (ctx, args) => {
46475
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46476
+ if (!meshId) return { success: false, error: "meshId required" };
46477
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46478
+ const mesh = meshRecord?.mesh;
46479
+ if (!mesh) return { success: false, error: "Mesh not found" };
46480
+ const meshHost = resolveMeshHostStatus(mesh);
46481
+ const pairingStatus = meshHost.pairing?.status || "not_configured";
46482
+ return {
46483
+ success: true,
46484
+ code: pairingStatus === "not_configured" ? "mesh_host_pairing_not_configured" : "mesh_host_pairing_pending",
46485
+ meshId,
46486
+ hostAddress: meshHost.hostAddress,
46487
+ meshHost,
46488
+ manualPairing: {
46489
+ status: pairingStatus,
46490
+ joinImplemented: true,
46491
+ protocol: "standalone_command_direct_v1",
46492
+ 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."
46493
+ }
46494
+ };
46495
+ },
46496
+ configure_mesh_host_pairing: async (ctx, args) => {
46497
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46498
+ const hostAddress = typeof args?.hostAddress === "string" ? args.hostAddress.trim() : "";
46499
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46500
+ if (!meshId) return { success: false, error: "meshId required" };
46501
+ if (!hostAddress || !token) return { success: false, error: "hostAddress and token required" };
46502
+ try {
46503
+ const { configureMeshHostPairing: configureMeshHostPairing2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46504
+ const configured = configureMeshHostPairing2(meshId, { hostAddress, token });
46505
+ if (!configured) return { success: false, error: "Mesh not found" };
46506
+ ctx.inlineMeshCache.set(meshId, configured.mesh);
46507
+ const meshHost = resolveMeshHostStatus(configured.mesh);
46508
+ return {
46509
+ success: true,
46510
+ code: "mesh_host_pairing_pending",
46511
+ meshId,
46512
+ hostAddress: configured.hostAddress,
46513
+ meshHost,
46514
+ manualPairing: {
46515
+ status: meshHost.pairing?.status || "pairing",
46516
+ joinImplemented: true,
46517
+ protocol: "standalone_command_direct_v1",
46518
+ 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."
46519
+ }
46520
+ };
46521
+ } catch (e) {
46522
+ return { success: false, code: "mesh_host_pairing_invalid", meshId, hostAddress, error: e.message };
46523
+ }
46524
+ },
46525
+ create_mesh_host_pairing_token: async (ctx, args) => {
46526
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46527
+ if (!meshId) return { success: false, error: "meshId required" };
46528
+ try {
46529
+ const { createMeshHostPairingToken: createMeshHostPairingToken2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46530
+ const created = createMeshHostPairingToken2(meshId, {
46531
+ token: typeof args?.token === "string" ? args.token : void 0,
46532
+ expiresAt: typeof args?.expiresAt === "string" ? args.expiresAt : void 0
46533
+ });
46534
+ if (!created) return { success: false, error: "Mesh not found" };
46535
+ ctx.inlineMeshCache.set(meshId, created.mesh);
46536
+ ctx.invalidateAggregateMeshStatus(meshId);
46537
+ return {
46538
+ success: true,
46539
+ code: "mesh_host_pairing_token_created",
46540
+ meshId,
46541
+ token: created.token,
46542
+ tokenId: created.tokenId,
46543
+ expiresAt: created.expiresAt,
46544
+ meshHost: resolveMeshHostStatus(created.mesh),
46545
+ warning: "Raw token is returned once and is not persisted; share it with member daemons over a trusted channel."
46546
+ };
46547
+ } catch (e) {
46548
+ return { success: false, code: "mesh_host_pairing_token_invalid", meshId, error: e.message };
46549
+ }
46550
+ },
46551
+ apply_mesh_host_join: async (ctx, args) => {
46552
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46553
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46554
+ const memberNode = args?.memberNode && typeof args.memberNode === "object" && !Array.isArray(args.memberNode) ? args.memberNode : null;
46555
+ if (!meshId) return { success: false, error: "meshId required" };
46556
+ if (!token || !memberNode) return { success: false, error: "token and memberNode required" };
46557
+ try {
46558
+ const { applyMeshHostJoinRequest: applyMeshHostJoinRequest2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46559
+ const applied = applyMeshHostJoinRequest2(meshId, {
46560
+ token,
46561
+ memberNode,
46562
+ memberMeshId: typeof args?.memberMeshId === "string" ? args.memberMeshId : void 0
46563
+ });
46564
+ if (!applied) return { success: false, error: "Mesh not found" };
46565
+ if (!applied.accepted) {
46566
+ return {
46567
+ success: false,
46568
+ code: "mesh_host_join_rejected",
46569
+ meshId,
46570
+ tokenId: applied.tokenId,
46571
+ meshHost: applied.meshHost ? resolveMeshHostStatus({ meshHost: applied.meshHost }) : void 0,
46572
+ error: applied.reason
46573
+ };
46574
+ }
46575
+ ctx.inlineMeshCache.set(meshId, applied.mesh);
46576
+ ctx.invalidateAggregateMeshStatus(meshId);
46577
+ try {
46578
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
46579
+ appendLedgerEntry2(meshId, {
46580
+ kind: "node_joined",
46581
+ nodeId: applied.node.id,
46582
+ payload: { role: "member", tokenId: applied.tokenId, workspace: applied.node.workspace }
46583
+ });
46584
+ } catch {
46585
+ }
46586
+ return {
46587
+ success: true,
46588
+ code: "mesh_host_join_accepted",
46589
+ meshId,
46590
+ node: applied.node,
46591
+ tokenId: applied.tokenId,
46592
+ meshHost: resolveMeshHostStatus(applied.mesh)
46593
+ };
46594
+ } catch (e) {
46595
+ return { success: false, code: "mesh_host_join_failed", meshId, error: e.message };
46596
+ }
46597
+ },
46598
+ join_mesh_host_pairing: async (ctx, args) => {
46599
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46600
+ const token = typeof args?.token === "string" ? args.token.trim() : "";
46601
+ if (!meshId) return { success: false, error: "meshId required" };
46602
+ if (!token) return { success: false, error: "token required because raw pairing tokens are not persisted" };
46603
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46604
+ const mesh = meshRecord?.mesh;
46605
+ if (!mesh) return { success: false, error: "Mesh not found" };
46606
+ const meshHost = resolveMeshHostStatus(mesh);
46607
+ if (meshHost.role !== "member") {
46608
+ 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." };
46609
+ }
46610
+ try {
46611
+ const { tokenIdForManualPairing: tokenIdForManualPairing2, markMeshHostPairingJoined: markMeshHostPairingJoined2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
46612
+ const tokenId = tokenIdForManualPairing2(token);
46613
+ if (meshHost.pairing?.tokenId && meshHost.pairing.tokenId !== tokenId) {
46614
+ return { success: false, code: "mesh_host_join_rejected", meshId, tokenId, meshHost, error: "invalid pairing token" };
46615
+ }
46616
+ const memberNode = buildMemberJoinNode(mesh, args, ctx.deps.statusInstanceId);
46617
+ if (!memberNode) return { success: false, error: "member node metadata unavailable" };
46618
+ const hostMeshId = typeof args?.hostMeshId === "string" && args.hostMeshId.trim() ? args.hostMeshId.trim() : meshId;
46619
+ const hostDaemonId = typeof args?.hostDaemonId === "string" && args.hostDaemonId.trim() ? args.hostDaemonId.trim() : meshHost.hostDaemonId;
46620
+ let hostResult;
46621
+ let transport;
46622
+ if (hostDaemonId && ctx.deps.dispatchMeshCommand) {
46623
+ transport = "mesh_command_dispatch";
46624
+ hostResult = await ctx.deps.dispatchMeshCommand(hostDaemonId, "apply_mesh_host_join", {
46625
+ meshId: hostMeshId,
46626
+ token,
46627
+ memberMeshId: meshId,
46628
+ memberNode
46629
+ });
46630
+ } else if (meshHost.hostAddress) {
46631
+ transport = "standalone_http_command";
46632
+ const commandUrl = normalizeStandaloneHostCommandUrl(meshHost.hostAddress);
46633
+ const response = await fetch(commandUrl, {
46634
+ method: "POST",
46635
+ headers: { "Content-Type": "application/json" },
46636
+ body: JSON.stringify({ type: "apply_mesh_host_join", payload: { meshId: hostMeshId, token, memberMeshId: meshId, memberNode } })
46637
+ });
46638
+ hostResult = await response.json().catch(() => ({ success: false, error: `Host returned HTTP ${response.status}` }));
46639
+ if (!response.ok && hostResult?.success !== false) hostResult = { success: false, error: `Host returned HTTP ${response.status}` };
46640
+ } else {
46641
+ return {
46642
+ success: false,
46643
+ code: "mesh_host_join_transport_unavailable",
46644
+ meshId,
46645
+ meshHost,
46646
+ error: "No hostDaemonId dispatch path or hostAddress HTTP command path is available. P2P signaling join is not implemented in this slice."
46647
+ };
46648
+ }
46649
+ if (!hostResult?.success) {
46650
+ return { success: false, code: hostResult?.code || "mesh_host_join_rejected", meshId, meshHost, transport, error: hostResult?.error || "Mesh Host rejected join request", hostResult };
46651
+ }
46652
+ const joined = meshRecord.inline ? null : markMeshHostPairingJoined2(meshId, {
46653
+ tokenId: hostResult.tokenId || tokenId,
46654
+ hostDaemonId: hostResult.meshHost?.hostDaemonId || hostDaemonId,
46655
+ hostNodeId: hostResult.meshHost?.hostNodeId,
46656
+ joinedAt: hostResult.meshHost?.pairing?.joinedAt
46657
+ });
46658
+ if (joined) {
46659
+ ctx.inlineMeshCache.set(meshId, joined.mesh);
46660
+ ctx.invalidateAggregateMeshStatus(meshId);
46661
+ }
46662
+ return {
46663
+ success: true,
46664
+ code: "mesh_host_join_applied",
46665
+ meshId,
46666
+ hostMeshId,
46667
+ transport,
46668
+ node: hostResult.node,
46669
+ tokenId: hostResult.tokenId || tokenId,
46670
+ meshHost: joined ? resolveMeshHostStatus(joined.mesh) : { ...meshHost, pairing: { ...meshHost.pairing || {}, status: "paired", tokenId: hostResult.tokenId || tokenId } },
46671
+ hostResult,
46672
+ manualPairing: {
46673
+ status: "paired",
46674
+ joinImplemented: true,
46675
+ protocol: "standalone_command_direct_v1",
46676
+ description: "Mesh Host accepted the join and local member pairing status was marked paired. P2P runtime signaling remains outside this slice."
46677
+ }
46678
+ };
46679
+ } catch (e) {
46680
+ return { success: false, code: "mesh_host_join_failed", meshId, meshHost, error: e.message };
46681
+ }
46682
+ }
46683
+ };
46684
+
46685
+ // src/commands/med-family/mesh-queue.ts
46686
+ var meshQueueHandlers = {
46687
+ get_mesh_queue: async (_ctx, args) => {
46688
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46689
+ if (!meshId) return { success: false, error: "meshId required" };
46690
+ try {
46691
+ const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2, describeTaskDependencyState: describeTaskDependencyState2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
46692
+ const status = Array.isArray(args?.status) ? args.status.map((s2) => typeof s2 === "string" ? s2.trim() : "").filter(Boolean) : void 0;
46693
+ const rawQueue = getQueue2(meshId, { status });
46694
+ const statusById = new Map(getQueue2(meshId).map((task) => [task.id, task.status]));
46695
+ const queue = rawQueue.map((task) => Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? { ...task, ...describeTaskDependencyState2(task, statusById) } : task);
46696
+ const summary = getMeshQueueStats2(meshId);
46697
+ return {
46698
+ success: true,
46699
+ queue,
46700
+ summary,
46701
+ sourceOfTruth: {
46702
+ kind: "mesh_work_queue_file",
46703
+ activeStatuses: ["pending", "assigned"],
46704
+ historicalStatuses: ["completed", "failed", "cancelled"],
46705
+ notes: "pending/assigned are active work; completed/failed/cancelled are historical records."
46706
+ }
46707
+ };
46708
+ } catch (e) {
46709
+ return { success: false, error: e.message };
46710
+ }
46711
+ },
46712
+ cancel_mesh_queue_task: async (ctx, args) => {
46713
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46714
+ const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
46715
+ if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
46716
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue cancellation");
46717
+ if (ownerFailure) return ownerFailure;
46718
+ try {
46719
+ const { cancelTask: cancelTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
46720
+ const reason = typeof args?.reason === "string" ? args.reason : void 0;
46721
+ const task = cancelTask2(meshId, taskId, { reason });
46722
+ if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
46723
+ return { success: true, task };
46724
+ } catch (e) {
46725
+ return { success: false, error: e.message };
46726
+ }
46727
+ },
46728
+ requeue_mesh_queue_task: async (ctx, args) => {
46729
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46730
+ const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
46731
+ if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
46732
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue requeue");
46733
+ if (ownerFailure) return ownerFailure;
46734
+ try {
46735
+ const { requeueTask: requeueTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
46736
+ const task = requeueTask2(meshId, taskId, {
46737
+ reason: typeof args?.reason === "string" ? args.reason : void 0,
46738
+ targetNodeId: typeof args?.targetNodeId === "string" ? args.targetNodeId.trim() : void 0,
46739
+ targetSessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : void 0,
46740
+ clearTargetNode: args?.clearTargetNode === true,
46741
+ clearTargetSession: args?.clearTargetSession !== false
46742
+ });
46743
+ if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
46744
+ return { success: true, task };
46745
+ } catch (e) {
46746
+ return { success: false, error: e.message };
46747
+ }
46748
+ },
46749
+ trigger_mesh_queue: async (ctx, args) => {
46750
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46751
+ if (!meshId) return { success: false, error: "meshId required" };
46752
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue trigger");
46753
+ if (ownerFailure) return ownerFailure;
46754
+ try {
46755
+ const { triggerMeshQueue: triggerMeshQueue2, tryAssignQueueTask: tryAssignQueueTask2 } = await Promise.resolve().then(() => (init_mesh_events(), mesh_events_exports));
46756
+ const preferredNodeId = typeof args?.preferredNodeId === "string" ? args.preferredNodeId.trim() : "";
46757
+ if (preferredNodeId) {
46758
+ const cliInstances = ctx.deps.instanceManager.getByCategory("cli");
46759
+ const sorted = [...cliInstances].sort((a, b) => {
46760
+ const aSettings = a.getState().settings || {};
46761
+ const bSettings = b.getState().settings || {};
46762
+ const aNode = readStringValue(aSettings.meshNodeId, aSettings.nodeId);
46763
+ const bNode = readStringValue(bSettings.meshNodeId, bSettings.nodeId);
46764
+ return (aNode === preferredNodeId ? -1 : 0) - (bNode === preferredNodeId ? -1 : 0);
46765
+ });
46766
+ for (const inst of sorted) {
46767
+ const state = inst.getState();
46768
+ const settings = state.settings || {};
46769
+ const nodeId = readStringValue(settings.meshNodeId, settings.nodeId);
46770
+ if (!nodeId || nodeId !== preferredNodeId) continue;
46771
+ const meshNodeFor = readStringValue(settings.meshNodeFor);
46772
+ if (meshNodeFor !== meshId) continue;
46773
+ const status = (readStringValue(state.status) || "").toLowerCase();
46774
+ if (status !== "idle") continue;
46775
+ const sessionId = typeof state.instanceId === "string" ? state.instanceId : "";
46776
+ const providerType = readStringValue(state.type, settings.providerType) || "";
46777
+ if (sessionId && providerType) {
46778
+ tryAssignQueueTask2(ctx.deps, meshId, nodeId, sessionId, providerType);
46779
+ break;
46780
+ }
46781
+ }
46782
+ }
46783
+ const trigger = await triggerMeshQueue2(ctx.deps, meshId);
46784
+ return { success: true, trigger };
46785
+ } catch (e) {
46786
+ return { success: false, error: e.message };
46787
+ }
46788
+ }
46789
+ };
46790
+
46791
+ // src/commands/med-family/fast-forward.ts
46792
+ init_dist();
46793
+ init_mesh_fast_forward();
46794
+
46795
+ // src/mesh/mesh-init.ts
46796
+ import { existsSync as existsSync37, mkdirSync as mkdirSync15, writeFileSync as writeFileSync18 } from "fs";
46797
+ import { dirname as dirname11, join as join40 } from "path";
46798
+ var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
46799
+ var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
46800
+ var CANDIDATE_STALE_INPUTS = [
46801
+ "package-lock.json",
46802
+ "pnpm-lock.yaml",
46803
+ "yarn.lock",
46804
+ "bun.lockb",
46805
+ "Cargo.lock",
46806
+ "go.sum",
46807
+ "poetry.lock",
46808
+ "requirements.txt"
46809
+ ];
46810
+ function writeConfigFile(workspace, relativePath, config) {
46811
+ const target = join40(workspace, relativePath);
46812
+ mkdirSync15(dirname11(target), { recursive: true });
46813
+ writeFileSync18(target, `${JSON.stringify(config, null, 2)}
46814
+ `, "utf-8");
46815
+ return target;
46816
+ }
46817
+ function suggestMeshWorktreeBootstrapConfig(workspace) {
46818
+ const commands = [];
46819
+ const hasPackageJson = existsSync37(join40(workspace, "package.json"));
46820
+ const hasNpmLock = existsSync37(join40(workspace, "package-lock.json"));
46821
+ if (hasPackageJson) {
46822
+ commands.push(
46823
+ hasNpmLock ? { command: "npm", args: ["ci"] } : { command: "npm", args: ["install"] }
46824
+ );
46825
+ }
46826
+ const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => existsSync37(join40(workspace, relative5)));
46827
+ if (!commands.length) {
46828
+ return { commands, staleInputs };
46829
+ }
46830
+ return {
46831
+ commands,
46832
+ staleInputs,
46833
+ suggestedConfig: {
46834
+ version: 1,
46835
+ enabled: true,
46836
+ runOnClone: true,
46837
+ required: false,
46838
+ commands,
46839
+ ...staleInputs.length ? { staleInputs } : {}
46840
+ }
46841
+ };
46842
+ }
46843
+ var PROVIDER_PRIORITY_PREFERENCE = ["claude-cli", "codex-cli", "gemini-cli"];
46844
+ function suggestNodeProviderPriority(detected) {
46845
+ const installed = detected.filter((cli) => cli.installed);
46846
+ const installedIds = installed.map((cli) => cli.id);
46847
+ const preferred = PROVIDER_PRIORITY_PREFERENCE.filter((id) => installedIds.includes(id));
46848
+ const rest = installedIds.filter((id) => !preferred.includes(id));
46849
+ const providerPriority = [...preferred, ...rest];
46850
+ return {
46851
+ providerPriority,
46852
+ installedProviders: installed.map((cli) => ({
46853
+ id: cli.id,
46854
+ displayName: cli.displayName,
46855
+ ...cli.version ? { version: cli.version } : {}
46856
+ }))
46857
+ };
46858
+ }
46859
+ function runMeshInit(mesh, workspace, detected, options = {}) {
46860
+ const write = options.write === true;
46861
+ const overwrite = options.overwrite === true;
46862
+ const refine = applyConfigSuggestion({
46863
+ workspace,
46864
+ relativePath: MESH_INIT_REFINE_CONFIG_PATH,
46865
+ existing: loadMeshRefineConfig(mesh, workspace).config,
46866
+ suggestedConfig: suggestMeshRefineConfig(mesh, workspace).suggestedConfig,
46867
+ validate: (config) => validateMeshRefineConfig(config, MESH_INIT_REFINE_CONFIG_PATH).valid,
46868
+ write,
46869
+ overwrite
46870
+ });
46871
+ const bootstrapSuggestion = suggestMeshWorktreeBootstrapConfig(workspace);
46872
+ const worktreeBootstrap = applyConfigSuggestion({
46873
+ workspace,
46874
+ relativePath: MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH,
46875
+ existing: loadMeshWorktreeBootstrapConfig(mesh, workspace).config,
46876
+ suggestedConfig: bootstrapSuggestion.suggestedConfig,
46877
+ validate: (config) => validateMeshWorktreeBootstrapConfig(config, MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH).valid,
46878
+ write,
46879
+ overwrite
46880
+ });
46881
+ const providers = suggestNodeProviderPriority(detected);
46882
+ return {
46883
+ success: true,
46884
+ workspace,
46885
+ dryRun: !write,
46886
+ refine,
46887
+ worktreeBootstrap,
46888
+ providers,
46889
+ 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."
46890
+ };
46891
+ }
46892
+ function applyConfigSuggestion(input) {
46893
+ const { workspace, relativePath, existing, suggestedConfig, validate, write, overwrite } = input;
46894
+ const absolute = join40(workspace, relativePath);
46895
+ if (existing !== void 0 && !overwrite) {
46896
+ return { path: absolute, relativePath, written: false, skippedReason: "already_exists", config: existing };
46897
+ }
46898
+ if (!suggestedConfig || !validate(suggestedConfig)) {
46899
+ return { path: absolute, relativePath, written: false, skippedReason: "no_suggestion" };
46900
+ }
46901
+ if (!write) {
46902
+ return { path: absolute, relativePath, written: false, config: suggestedConfig };
46903
+ }
46904
+ const writtenPath = writeConfigFile(workspace, relativePath, suggestedConfig);
46905
+ return { path: writtenPath, relativePath, written: true, config: suggestedConfig };
46906
+ }
46907
+
46908
+ // src/commands/med-family/fast-forward.ts
46909
+ init_cli_detector();
46910
+ var fastForwardHandlers = {
46911
+ mesh_init: async (ctx, args) => {
46912
+ const workspace = typeof args?.workspace === "string" && args.workspace.trim() ? args.workspace.trim() : process.cwd();
46913
+ const mesh = args?.inlineMesh || {};
46914
+ try {
46915
+ const detected = await detectCLIs(ctx.deps.providerLoader, { includeVersion: true });
46916
+ return { ...runMeshInit(mesh, workspace, detected, {
46917
+ write: args?.write === true,
46918
+ overwrite: args?.overwrite === true
46919
+ }) };
46920
+ } catch (e) {
46921
+ return { success: false, error: e?.message || String(e) };
46922
+ }
46923
+ },
46924
+ plan_mesh_refine_node: async (ctx, args) => {
46925
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46926
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46927
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46928
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46929
+ const mesh = meshRecord?.mesh;
46930
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46931
+ if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
46932
+ return {
46933
+ success: true,
46934
+ dryRun: true,
46935
+ nodeId,
46936
+ workspace: node.workspace,
46937
+ validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
46938
+ mergeWillRun: false,
46939
+ cleanupWillRun: false
46940
+ };
46941
+ },
46942
+ fast_forward_mesh_node: async (ctx, args) => {
46943
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46944
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46945
+ let workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
46946
+ let submoduleIgnorePaths = Array.isArray(args?.submoduleIgnorePaths) ? args.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0;
46947
+ let nodeDaemonId;
46948
+ let allowAutoPublishSubmoduleMainCommits = false;
46949
+ if (meshId && nodeId) {
46950
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46951
+ const mesh = meshRecord?.mesh;
46952
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46953
+ if (!workspace) {
46954
+ workspace = typeof node?.workspace === "string" ? node.workspace.trim() : "";
46955
+ }
46956
+ if (!submoduleIgnorePaths && Array.isArray(node?.policy?.submoduleIgnorePaths)) {
46957
+ submoduleIgnorePaths = node.policy.submoduleIgnorePaths.filter((value) => typeof value === "string");
46958
+ }
46959
+ allowAutoPublishSubmoduleMainCommits = mesh?.policy?.allowAutoPublishSubmoduleMainCommits === true;
46960
+ nodeDaemonId = typeof node?.daemonId === "string" ? node.daemonId.trim() : void 0;
46961
+ }
46962
+ const selfDaemonId = ctx.deps.statusInstanceId;
46963
+ const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
46964
+ if (isRemote && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46965
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "fast_forward_mesh_node", {
46966
+ ...typeof args === "object" && args !== null ? args : {},
46967
+ workspace,
46968
+ _meshDirectDispatch: true
46969
+ });
46970
+ return forwarded ?? { success: false, error: "no response from remote node" };
46971
+ }
46972
+ const result = await fastForwardMeshNode({
46973
+ meshId: meshId || void 0,
46974
+ nodeId: nodeId || void 0,
46975
+ workspace,
46976
+ branch: typeof args?.branch === "string" ? args.branch : void 0,
46977
+ execute: args?.execute === true,
46978
+ dryRun: args?.dryRun === true,
46979
+ updateSubmodules: args?.updateSubmodules === true,
46980
+ submoduleIgnorePaths,
46981
+ mode: args?.mode === "push" ? "push" : "merge",
46982
+ pushSubmodules: args?.pushSubmodules === true,
46983
+ allowAutoPublishSubmoduleMainCommits
46984
+ });
46985
+ return result;
46986
+ },
46987
+ refine_mesh_node: async (ctx, args) => {
46988
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
46989
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
46990
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
46991
+ {
46992
+ const meshRecordForForward = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
46993
+ const forwardNode = meshRecordForForward?.mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
46994
+ const nodeDaemonId = typeof forwardNode?.daemonId === "string" ? forwardNode.daemonId.trim() : void 0;
46995
+ const selfDaemonId = ctx.deps.statusInstanceId;
46996
+ const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
46997
+ if (isRemote && ctx.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
46998
+ const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
46999
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, "refine_mesh_node", {
47000
+ ...typeof args === "object" && args !== null ? args : {},
47001
+ coordinatorDaemonId: callerCoordinatorDaemonId || selfDaemonId,
47002
+ _meshDirectDispatch: true
47003
+ });
47004
+ return forwarded ?? { success: false, error: "no response from remote node" };
47005
+ }
47006
+ }
47007
+ const isDryRun = args?.dryRun !== false && args?.execute !== true;
47008
+ if (isDryRun) {
47009
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
47010
+ const mesh = meshRecord?.mesh;
47011
+ const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
47012
+ if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
47013
+ return {
47014
+ success: true,
47015
+ dryRun: true,
47016
+ nodeId,
47017
+ workspace: node.workspace,
47018
+ validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
47019
+ mergeWillRun: false,
47020
+ cleanupWillRun: false,
47021
+ hint: "Dry-run only \u2014 no merge/push/cleanup performed. Re-invoke with execute:true to converge this node."
47022
+ };
47023
+ }
47024
+ return ctx.startMeshRefineJob(meshId, nodeId, args);
47025
+ },
47026
+ batch_refine_mesh_nodes: async (ctx, args) => {
47027
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
47028
+ if (!meshId) return { success: false, error: "meshId required" };
47029
+ const requestedNodeIds = Array.isArray(args?.nodeIds) ? args.nodeIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
47030
+ const isDryRun = args?.dryRun !== false && args?.execute !== true;
47031
+ if (isDryRun) return ctx.batchRefineMeshNodes(meshId, requestedNodeIds, args);
47032
+ return ctx.startMeshRefineBatchJob(meshId, requestedNodeIds, args);
47033
+ }
47034
+ };
47035
+
47036
+ // src/commands/med-family/index.ts
47037
+ var medFamilyRegistry = new Map(
47038
+ Object.entries({
47039
+ ...cliAgentHandlers,
47040
+ ...ideHandlers,
47041
+ ...meshCrudHandlers,
47042
+ ...meshHostPairingHandlers,
47043
+ ...meshQueueHandlers,
47044
+ ...fastForwardHandlers
47045
+ })
47046
+ );
47047
+
47048
+ // src/commands/router.ts
47049
+ init_config();
47050
+ init_cli_detector();
45584
47051
  init_git_status();
45585
47052
  init_dist();
45586
47053
  init_logger();
@@ -45736,9 +47203,7 @@ init_mesh_coordinator();
45736
47203
  init_coordinator_registry();
45737
47204
  init_mesh_events();
45738
47205
  init_mesh_routing();
45739
- init_mesh_events_utils();
45740
47206
  init_mesh_host_ownership();
45741
- init_mesh_fast_forward();
45742
47207
 
45743
47208
  // src/mesh/mesh-refine-batch.ts
45744
47209
  import { execFile as execFile4 } from "child_process";
@@ -45829,7 +47294,7 @@ function orderMeshRefineBatchNodes(changeAreas) {
45829
47294
 
45830
47295
  // src/mesh/preview-freshness.ts
45831
47296
  import { execFileSync as execFileSync5 } from "child_process";
45832
- import { existsSync as existsSync38, readFileSync as readFileSync29 } from "fs";
47297
+ import { existsSync as existsSync39, readFileSync as readFileSync29 } from "fs";
45833
47298
  import { resolve as resolve19 } from "path";
45834
47299
  var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
45835
47300
  function runGit2(repoRoot, args) {
@@ -45846,7 +47311,7 @@ function runGit2(repoRoot, args) {
45846
47311
  }
45847
47312
  function readRecord5(repoRoot) {
45848
47313
  const path42 = resolve19(repoRoot, PREVIEW_DEPLOY_RECORD);
45849
- if (!existsSync38(path42)) return null;
47314
+ if (!existsSync39(path42)) return null;
45850
47315
  try {
45851
47316
  const parsed = JSON.parse(readFileSync29(path42, "utf8"));
45852
47317
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
@@ -45911,121 +47376,6 @@ function buildPreviewFreshness(repoRoot) {
45911
47376
 
45912
47377
  // src/commands/router.ts
45913
47378
  init_mesh_refine_status();
45914
-
45915
- // src/mesh/mesh-init.ts
45916
- import { existsSync as existsSync39, mkdirSync as mkdirSync16, writeFileSync as writeFileSync18 } from "fs";
45917
- import { dirname as dirname11, join as join41 } from "path";
45918
- var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
45919
- var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
45920
- var CANDIDATE_STALE_INPUTS = [
45921
- "package-lock.json",
45922
- "pnpm-lock.yaml",
45923
- "yarn.lock",
45924
- "bun.lockb",
45925
- "Cargo.lock",
45926
- "go.sum",
45927
- "poetry.lock",
45928
- "requirements.txt"
45929
- ];
45930
- function writeConfigFile(workspace, relativePath, config) {
45931
- const target = join41(workspace, relativePath);
45932
- mkdirSync16(dirname11(target), { recursive: true });
45933
- writeFileSync18(target, `${JSON.stringify(config, null, 2)}
45934
- `, "utf-8");
45935
- return target;
45936
- }
45937
- function suggestMeshWorktreeBootstrapConfig(workspace) {
45938
- const commands = [];
45939
- const hasPackageJson = existsSync39(join41(workspace, "package.json"));
45940
- const hasNpmLock = existsSync39(join41(workspace, "package-lock.json"));
45941
- if (hasPackageJson) {
45942
- commands.push(
45943
- hasNpmLock ? { command: "npm", args: ["ci"] } : { command: "npm", args: ["install"] }
45944
- );
45945
- }
45946
- const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => existsSync39(join41(workspace, relative5)));
45947
- if (!commands.length) {
45948
- return { commands, staleInputs };
45949
- }
45950
- return {
45951
- commands,
45952
- staleInputs,
45953
- suggestedConfig: {
45954
- version: 1,
45955
- enabled: true,
45956
- runOnClone: true,
45957
- required: false,
45958
- commands,
45959
- ...staleInputs.length ? { staleInputs } : {}
45960
- }
45961
- };
45962
- }
45963
- var PROVIDER_PRIORITY_PREFERENCE = ["claude-cli", "codex-cli", "gemini-cli"];
45964
- function suggestNodeProviderPriority(detected) {
45965
- const installed = detected.filter((cli) => cli.installed);
45966
- const installedIds = installed.map((cli) => cli.id);
45967
- const preferred = PROVIDER_PRIORITY_PREFERENCE.filter((id) => installedIds.includes(id));
45968
- const rest = installedIds.filter((id) => !preferred.includes(id));
45969
- const providerPriority = [...preferred, ...rest];
45970
- return {
45971
- providerPriority,
45972
- installedProviders: installed.map((cli) => ({
45973
- id: cli.id,
45974
- displayName: cli.displayName,
45975
- ...cli.version ? { version: cli.version } : {}
45976
- }))
45977
- };
45978
- }
45979
- function runMeshInit(mesh, workspace, detected, options = {}) {
45980
- const write = options.write === true;
45981
- const overwrite = options.overwrite === true;
45982
- const refine = applyConfigSuggestion({
45983
- workspace,
45984
- relativePath: MESH_INIT_REFINE_CONFIG_PATH,
45985
- existing: loadMeshRefineConfig(mesh, workspace).config,
45986
- suggestedConfig: suggestMeshRefineConfig(mesh, workspace).suggestedConfig,
45987
- validate: (config) => validateMeshRefineConfig(config, MESH_INIT_REFINE_CONFIG_PATH).valid,
45988
- write,
45989
- overwrite
45990
- });
45991
- const bootstrapSuggestion = suggestMeshWorktreeBootstrapConfig(workspace);
45992
- const worktreeBootstrap = applyConfigSuggestion({
45993
- workspace,
45994
- relativePath: MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH,
45995
- existing: loadMeshWorktreeBootstrapConfig(mesh, workspace).config,
45996
- suggestedConfig: bootstrapSuggestion.suggestedConfig,
45997
- validate: (config) => validateMeshWorktreeBootstrapConfig(config, MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH).valid,
45998
- write,
45999
- overwrite
46000
- });
46001
- const providers = suggestNodeProviderPriority(detected);
46002
- return {
46003
- success: true,
46004
- workspace,
46005
- dryRun: !write,
46006
- refine,
46007
- worktreeBootstrap,
46008
- providers,
46009
- 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."
46010
- };
46011
- }
46012
- function applyConfigSuggestion(input) {
46013
- const { workspace, relativePath, existing, suggestedConfig, validate, write, overwrite } = input;
46014
- const absolute = join41(workspace, relativePath);
46015
- if (existing !== void 0 && !overwrite) {
46016
- return { path: absolute, relativePath, written: false, skippedReason: "already_exists", config: existing };
46017
- }
46018
- if (!suggestedConfig || !validate(suggestedConfig)) {
46019
- return { path: absolute, relativePath, written: false, skippedReason: "no_suggestion" };
46020
- }
46021
- if (!write) {
46022
- return { path: absolute, relativePath, written: false, config: suggestedConfig };
46023
- }
46024
- const writtenPath = writeConfigFile(workspace, relativePath, suggestedConfig);
46025
- return { path: writtenPath, relativePath, written: true, config: suggestedConfig };
46026
- }
46027
-
46028
- // src/commands/router.ts
46029
47379
  init_mesh_work_queue();
46030
47380
  init_repo_mesh_types();
46031
47381
  import { homedir as homedir26, hostname as osHostname } from "os";
@@ -48577,6 +49927,37 @@ var DaemonCommandRouter = class {
48577
49927
  this.aggregateMeshStatusCache.delete(meshId);
48578
49928
  this.deps.onMeshStateChange?.(meshId);
48579
49929
  }
49930
+ /**
49931
+ * Build the MedFamilyContext handed to RF-ROUTER MED family handlers. Binds the
49932
+ * router-private collaborators those handlers need (mesh resolution, owner
49933
+ * gating, inline-cache mutation, worktree / session cleanup, refine job
49934
+ * starters, IDE stop/launch) plus the inline-mesh and git-probe caches. The
49935
+ * `launchIde` field closes over the freshly-built context so restart_session /
49936
+ * restart_ide invoke the IDE launch directly instead of recursing through
49937
+ * executeDaemonCommand('launch_ide').
49938
+ */
49939
+ buildMedFamilyContext() {
49940
+ const ctx = {
49941
+ deps: this.deps,
49942
+ getMeshForCommand: this.getMeshForCommand.bind(this),
49943
+ getCachedInlineMesh: this.getCachedInlineMesh.bind(this),
49944
+ requireMeshHostMutationOwner: this.requireMeshHostMutationOwner.bind(this),
49945
+ invalidateAggregateMeshStatus: this.invalidateAggregateMeshStatus.bind(this),
49946
+ updateInlineMeshNode: this.updateInlineMeshNode.bind(this),
49947
+ removeInlineMeshNode: this.removeInlineMeshNode.bind(this),
49948
+ normalizeMeshSessionCleanupMode: this.normalizeMeshSessionCleanupMode.bind(this),
49949
+ cleanupMeshSessions: this.cleanupMeshSessions.bind(this),
49950
+ cleanupLocalWorktreeNode: this.cleanupLocalWorktreeNode.bind(this),
49951
+ startMeshRefineJob: this.startMeshRefineJob.bind(this),
49952
+ batchRefineMeshNodes: this.batchRefineMeshNodes.bind(this),
49953
+ startMeshRefineBatchJob: this.startMeshRefineBatchJob.bind(this),
49954
+ stopIde: this.stopIde.bind(this),
49955
+ launchIde: (args) => launchIde(ctx, args),
49956
+ inlineMeshCache: this.inlineMeshCache,
49957
+ meshGitProbeCache: this.meshGitProbeCache
49958
+ };
49959
+ return ctx;
49960
+ }
48580
49961
  async requireMeshHostMutationOwner(meshId, inlineMesh, operation) {
48581
49962
  const meshRecord = await this.getMeshForCommand(meshId, inlineMesh, { preferInline: true });
48582
49963
  const mesh = meshRecord?.mesh;
@@ -50492,6 +51873,10 @@ ${hintLines.join("\n")}` : "",
50492
51873
  getMeshForCommand: this.getMeshForCommand.bind(this)
50493
51874
  }, args);
50494
51875
  }
51876
+ const medFamilyHandler = medFamilyRegistry.get(cmd);
51877
+ if (medFamilyHandler) {
51878
+ return await medFamilyHandler(this.buildMedFamilyContext(), args);
51879
+ }
50495
51880
  switch (cmd) {
50496
51881
  // ─── CLI / ACP commands ───
50497
51882
  case "mesh_forward_event": {
@@ -50512,1315 +51897,6 @@ ${hintLines.join("\n")}` : "",
50512
51897
  this.deps.instanceManager.sendEvent(sessionId, "interactive_prompt_response", response);
50513
51898
  return { success: true };
50514
51899
  }
50515
- case "launch_cli": {
50516
- const launchResult = await this.deps.cliManager.handleCliCommand(cmd, args);
50517
- const meshNodeId = readStringValue(args?.settings?.meshNodeId);
50518
- const meshId = readStringValue(args?.settings?.meshNodeFor);
50519
- if (meshNodeId && meshId && launchResult?.success !== false) {
50520
- try {
50521
- const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50522
- const meshObj = getMesh2(meshId) ?? this.getCachedInlineMesh(meshId);
50523
- const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, meshNodeId)) : void 0;
50524
- const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
50525
- if (bootstrapStatus === "running") {
50526
- return { success: true, ...launchResult, bootstrapPending: true };
50527
- }
50528
- } catch {
50529
- }
50530
- }
50531
- return launchResult;
50532
- }
50533
- case "stop_cli":
50534
- case "set_cli_view_mode":
50535
- case "record_provider_pty": {
50536
- return this.deps.cliManager.handleCliCommand(cmd, args);
50537
- }
50538
- case "agent_command": {
50539
- {
50540
- const dispatchSessionId = readStringValue(args?.targetSessionId, args?.sessionId, args?.instanceId);
50541
- const dispatchMeshContext = args?.meshContext;
50542
- if (dispatchSessionId && dispatchMeshContext) {
50543
- try {
50544
- const inst = this.deps.instanceManager.getInstance(dispatchSessionId);
50545
- if (inst && typeof inst.updateSettings === "function") {
50546
- const stamp = buildMeshWorkerRelayStamp(
50547
- inst.getState?.()?.settings,
50548
- {
50549
- meshId: dispatchMeshContext.meshId,
50550
- nodeId: dispatchMeshContext.nodeId,
50551
- coordinatorDaemonId: dispatchMeshContext.coordinatorDaemonId,
50552
- // Session-level anchor: preserved across the P2P dispatch to a
50553
- // remote worker so its completion echoes back to the right session.
50554
- coordinatorSessionId: dispatchMeshContext.coordinatorSessionId
50555
- }
50556
- );
50557
- if (stamp) inst.updateSettings(stamp);
50558
- }
50559
- } catch {
50560
- }
50561
- }
50562
- }
50563
- const agentResult = await this.deps.cliManager.handleCliCommand(cmd, args);
50564
- const meshCtx = args?.meshContext;
50565
- const dispatchNodeId = readStringValue(meshCtx?.nodeId);
50566
- const dispatchMeshId = readStringValue(meshCtx?.meshId);
50567
- if (dispatchNodeId && dispatchMeshId && agentResult?.success !== false) {
50568
- try {
50569
- const { getMesh: getMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50570
- const meshObj = getMesh2(dispatchMeshId) ?? this.getCachedInlineMesh(dispatchMeshId);
50571
- const nodeObj = Array.isArray(meshObj?.nodes) ? meshObj.nodes.find((n) => meshNodeIdMatches(n, dispatchNodeId)) : void 0;
50572
- const bootstrapStatus = readStringValue(nodeObj?.worktreeBootstrap?.status);
50573
- if (bootstrapStatus === "running") {
50574
- return {
50575
- success: true,
50576
- ...agentResult,
50577
- dispatchAcknowledgementRisk: true,
50578
- dispatchAcknowledgementRiskReason: "bootstrap_still_running",
50579
- nextAction: "Wait for worktree_bootstrap_complete event before dispatching work to this node."
50580
- };
50581
- }
50582
- } catch {
50583
- }
50584
- }
50585
- return agentResult;
50586
- }
50587
- // ─── Logs ───
50588
- case "list_saved_sessions": {
50589
- const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
50590
- const kind = args?.kind === "acp" ? "acp" : "cli";
50591
- if (!providerType) {
50592
- return { success: false, error: "providerType required" };
50593
- }
50594
- const wantsAll = args?.all === true;
50595
- const offset = wantsAll ? 0 : Math.max(0, Number(args?.offset) || 0);
50596
- const limit = wantsAll ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.min(100, Number(args?.limit) || 30));
50597
- const requestedWorkspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
50598
- const requestedProviderSessionId = typeof args?.providerSessionId === "string" ? args.providerSessionId.trim() : typeof args?.activeProviderSessionId === "string" ? args.activeProviderSessionId.trim() : "";
50599
- const providerMeta = this.deps.providerLoader.resolve?.(providerType) || this.deps.providerLoader.getMeta(providerType);
50600
- const { sessions: historySessions, hasMore, source } = listProviderHistorySessions(providerType, {
50601
- canonicalHistory: providerMeta?.nativeHistory,
50602
- offset,
50603
- limit,
50604
- historyBehavior: providerMeta?.historyBehavior,
50605
- scripts: providerMeta?.scripts
50606
- });
50607
- const state = loadState();
50608
- const savedSessions = getSavedProviderSessions(state, { providerType, kind });
50609
- const recentSessions = getRecentActivity(state, 200).filter((entry) => entry.providerType === providerType && entry.kind === kind && entry.providerSessionId);
50610
- const savedSessionById = new Map(savedSessions.map((entry) => [entry.providerSessionId, entry]));
50611
- const recentSessionById = new Map(recentSessions.map((entry) => [entry.providerSessionId, entry]));
50612
- const canResumeById = supportsExplicitSessionResume(providerMeta?.resume);
50613
- return {
50614
- success: true,
50615
- sessions: historySessions.map((session) => {
50616
- const saved = savedSessionById.get(session.historySessionId);
50617
- const recent = recentSessionById.get(session.historySessionId);
50618
- const workspace = saved?.workspace || recent?.workspace || session.workspace || (requestedWorkspace && requestedProviderSessionId === session.historySessionId ? requestedWorkspace : void 0);
50619
- return {
50620
- id: session.historySessionId,
50621
- providerSessionId: session.historySessionId,
50622
- providerType,
50623
- providerName: saved?.providerName || recent?.providerName || providerType,
50624
- kind: saved?.kind || recent?.kind || kind,
50625
- title: saved?.title || recent?.title || session.sessionTitle || session.preview || providerType,
50626
- workspace,
50627
- summaryMetadata: saved?.summaryMetadata || recent?.summaryMetadata,
50628
- preview: session.preview,
50629
- messageCount: session.messageCount,
50630
- firstMessageAt: session.firstMessageAt,
50631
- lastMessageAt: session.lastMessageAt,
50632
- canResume: !!workspace && canResumeById,
50633
- historySource: session.source,
50634
- sourcePath: session.sourcePath,
50635
- sourceMtimeMs: session.sourceMtimeMs
50636
- };
50637
- }),
50638
- hasMore,
50639
- source
50640
- };
50641
- }
50642
- // ─── restart_session: IDE / CLI / ACP unified ───
50643
- case "restart_session": {
50644
- const targetType = args?.cliType || args?.agentType || args?.ideType;
50645
- if (!targetType) throw new Error("cliType or ideType required");
50646
- const isIde = this.deps.cdpManagers.has(targetType) || this.deps.providerLoader.getMeta(targetType)?.category === "ide";
50647
- if (isIde) {
50648
- await this.stopIde(targetType, true);
50649
- const launchResult = await this.executeDaemonCommand("launch_ide", { ideType: targetType, enableCdp: true, workspace: args?.workspace });
50650
- return { success: true, restarted: true, ideType: targetType, launch: launchResult };
50651
- }
50652
- return this.deps.cliManager.handleCliCommand(cmd, args);
50653
- }
50654
- // ─── IDE stop ───
50655
- case "stop_ide": {
50656
- const ideType = args?.ideType;
50657
- if (!ideType) throw new Error("ideType required");
50658
- const killProcess = args?.killProcess !== false;
50659
- await this.stopIde(ideType, killProcess);
50660
- try {
50661
- const results = await detectIDEs(this.deps.providerLoader);
50662
- this.deps.detectedIdes.value = results;
50663
- this.deps.providerLoader.setIdeDetectionResults(results, true);
50664
- } catch {
50665
- }
50666
- return { success: true, ideType, stopped: true, processKilled: killProcess };
50667
- }
50668
- // ─── IDE restart ───
50669
- case "restart_ide": {
50670
- const ideType = args?.ideType;
50671
- if (!ideType) throw new Error("ideType required");
50672
- await this.stopIde(ideType, true);
50673
- const launchResult = await this.executeDaemonCommand("launch_ide", { ideType, enableCdp: true, workspace: args?.workspace });
50674
- return { success: true, ideType, restarted: true, launch: launchResult };
50675
- }
50676
- // ─── IDE launch + CDP connect ───
50677
- case "launch_ide": {
50678
- const ideKey = args?.ideId || args?.ideType;
50679
- const resolvedWorkspace = resolveIdeLaunchWorkspace(
50680
- {
50681
- workspace: args?.workspace,
50682
- workspaceId: args?.workspaceId,
50683
- useDefaultWorkspace: args?.useDefaultWorkspace
50684
- },
50685
- loadConfig()
50686
- );
50687
- const launchArgs = {
50688
- ideId: ideKey,
50689
- workspace: resolvedWorkspace,
50690
- newWindow: args?.newWindow
50691
- };
50692
- LOG.info("LaunchIDE", `target=${ideKey || "auto"}`);
50693
- const result = await launchWithCdp(launchArgs);
50694
- if (result.success && result.port && result.ideId && !this.deps.cdpManagers.has(result.ideId)) {
50695
- const logFn = this.deps.getCdpLogFn ? this.deps.getCdpLogFn(result.ideId) : LOG.forComponent(`CDP:${result.ideId}`).asLogFn();
50696
- const provider = this.deps.providerLoader.getMeta(result.ideId);
50697
- const manager = new DaemonCdpManager(result.port, logFn, void 0, provider?.targetFilter);
50698
- const connected = await manager.connect();
50699
- if (connected) {
50700
- registerExtensionProviders(this.deps.providerLoader, manager, result.ideId);
50701
- this.deps.cdpManagers.set(result.ideId, manager);
50702
- LOG.info("CDP", `Connected: ${result.ideId} (port ${result.port})`);
50703
- LOG.info("CDP", `${this.deps.cdpManagers.size} IDE(s) connected`);
50704
- this.deps.onCdpManagerCreated?.(result.ideId, manager);
50705
- }
50706
- }
50707
- this.deps.onIdeConnected?.();
50708
- try {
50709
- const results = await detectIDEs(this.deps.providerLoader);
50710
- this.deps.detectedIdes.value = results;
50711
- this.deps.providerLoader.setIdeDetectionResults(results, true);
50712
- } catch {
50713
- }
50714
- if (result.success && resolvedWorkspace) {
50715
- try {
50716
- const next = appendRecentActivity(loadState(), {
50717
- kind: "ide",
50718
- providerType: result.ideId || ideKey,
50719
- providerName: result.ideId || ideKey,
50720
- workspace: resolvedWorkspace,
50721
- title: result.ideId || ideKey
50722
- });
50723
- saveState(next);
50724
- } catch {
50725
- }
50726
- } else if (result.success && (result.ideId || ideKey)) {
50727
- try {
50728
- saveState(appendRecentActivity(loadState(), {
50729
- kind: "ide",
50730
- providerType: result.ideId || ideKey,
50731
- providerName: result.ideId || ideKey,
50732
- title: result.ideId || ideKey
50733
- }));
50734
- } catch {
50735
- }
50736
- }
50737
- return { ...result };
50738
- }
50739
- // ─── Detect providers ───
50740
- case "detect_provider": {
50741
- const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : "";
50742
- if (!providerType) return { success: false, error: "providerType is required" };
50743
- const normalizedType = this.deps.providerLoader.resolveAlias(providerType);
50744
- const provider = this.deps.providerLoader.getByAlias(providerType);
50745
- if (!provider) return { success: false, error: `Provider not found: ${providerType}` };
50746
- if (provider.category !== "cli" && provider.category !== "acp") {
50747
- return { success: false, error: `Provider detection is only supported for CLI/ACP providers: ${providerType}` };
50748
- }
50749
- if (!this.deps.providerLoader.isMachineProviderEnabled(normalizedType)) {
50750
- return { success: false, error: `Provider is disabled on this machine: ${providerType}` };
50751
- }
50752
- const detected = await detectCLI(normalizedType, this.deps.providerLoader, { includeVersion: false });
50753
- this.deps.providerLoader.setCliDetectionResults([{
50754
- id: normalizedType,
50755
- installed: !!detected,
50756
- path: detected?.path
50757
- }], false);
50758
- this.deps.onStatusChange?.();
50759
- return {
50760
- success: true,
50761
- providerType: normalizedType,
50762
- detected: !!detected,
50763
- path: detected?.path || null
50764
- };
50765
- }
50766
- // ─── Detect IDEs ───
50767
- case "detect_ides": {
50768
- const results = await detectIDEs(this.deps.providerLoader);
50769
- this.deps.detectedIdes.value = results;
50770
- this.deps.providerLoader.setIdeDetectionResults(results, true);
50771
- return { success: true, detectedInfo: results };
50772
- }
50773
- // ─── Mesh CRUD (local meshes.json) ───
50774
- case "list_meshes": {
50775
- try {
50776
- const { listMeshes: listMeshes2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50777
- return { success: true, meshes: listMeshes2() };
50778
- } catch (e) {
50779
- return { success: false, error: e.message };
50780
- }
50781
- }
50782
- case "get_mesh": {
50783
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50784
- if (!meshId) return { success: false, error: "meshId required" };
50785
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
50786
- if (!meshRecord?.mesh) return { success: false, error: "Mesh not found" };
50787
- const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
50788
- const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
50789
- const directTruth = await hydrateInlineMeshDirectTruth({
50790
- mesh: meshRecord.mesh,
50791
- meshSource: meshRecord.source,
50792
- dispatchMeshCommand: this.deps.dispatchMeshCommand,
50793
- getMeshPeerConnectionStatus: this.deps.getMeshPeerConnectionStatus,
50794
- statusInstanceId: this.deps.statusInstanceId,
50795
- localMachineId: loadConfig().machineId || "",
50796
- probeRemotePeers,
50797
- probeCache: this.meshGitProbeCache
50798
- });
50799
- const directTruthSatisfied = meshRecord.source !== "inline_bootstrap" || directTruth.directEvidenceCount > 0;
50800
- const sourceOfTruth = {
50801
- membership: meshRecord.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
50802
- coordinatorOwnsLiveTruth: directTruthSatisfied,
50803
- directPeerTruth: {
50804
- required: requireDirectPeerTruth,
50805
- satisfied: directTruthSatisfied,
50806
- directEvidenceCount: directTruth.directEvidenceCount,
50807
- localConfirmedCount: directTruth.localConfirmedCount,
50808
- peerAttemptedCount: directTruth.peerAttemptedCount,
50809
- peerConfirmedCount: directTruth.peerConfirmedCount,
50810
- unavailableNodeIds: directTruth.unavailableNodeIds
50811
- }
50812
- };
50813
- if (requireDirectPeerTruth && !directTruthSatisfied) {
50814
- return {
50815
- success: false,
50816
- code: "mesh_direct_peer_truth_unavailable",
50817
- error: "Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.",
50818
- sourceOfTruth
50819
- };
50820
- }
50821
- return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
50822
- }
50823
- case "create_mesh": {
50824
- const name = typeof args?.name === "string" ? args.name.trim() : "";
50825
- const repoIdentity = typeof args?.repoIdentity === "string" ? args.repoIdentity.trim() : "";
50826
- const repoRemoteUrl = typeof args?.repoRemoteUrl === "string" ? args.repoRemoteUrl.trim() : void 0;
50827
- const defaultBranch = typeof args?.defaultBranch === "string" ? args.defaultBranch.trim() : void 0;
50828
- if (!name) return { success: false, error: "name required" };
50829
- try {
50830
- const { createMesh: createMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50831
- const meshHost = args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost) ? args.meshHost : void 0;
50832
- const mesh = createMesh2({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
50833
- return { success: true, mesh };
50834
- } catch (e) {
50835
- return { success: false, error: e.message };
50836
- }
50837
- }
50838
- case "update_mesh": {
50839
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50840
- if (!meshId) return { success: false, error: "meshId required" };
50841
- try {
50842
- const { updateMesh: updateMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50843
- const patch = {};
50844
- if (typeof args?.name === "string") patch.name = args.name;
50845
- if (typeof args?.defaultBranch === "string") patch.defaultBranch = args.defaultBranch;
50846
- if (args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy)) patch.policy = args.policy;
50847
- if (args?.coordinator && typeof args.coordinator === "object" && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
50848
- if (args?.meshHost && typeof args.meshHost === "object" && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
50849
- if (!Object.keys(patch).length) return { success: false, error: "No updates provided" };
50850
- const mesh = updateMesh2(meshId, patch);
50851
- if (!mesh) return { success: false, error: "Mesh not found" };
50852
- this.inlineMeshCache.set(meshId, mesh);
50853
- this.invalidateAggregateMeshStatus(meshId);
50854
- return { success: true, mesh };
50855
- } catch (e) {
50856
- return { success: false, error: e.message };
50857
- }
50858
- }
50859
- case "get_mesh_host_pairing": {
50860
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50861
- if (!meshId) return { success: false, error: "meshId required" };
50862
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
50863
- const mesh = meshRecord?.mesh;
50864
- if (!mesh) return { success: false, error: "Mesh not found" };
50865
- const meshHost = resolveMeshHostStatus(mesh);
50866
- const pairingStatus = meshHost.pairing?.status || "not_configured";
50867
- return {
50868
- success: true,
50869
- code: pairingStatus === "not_configured" ? "mesh_host_pairing_not_configured" : "mesh_host_pairing_pending",
50870
- meshId,
50871
- hostAddress: meshHost.hostAddress,
50872
- meshHost,
50873
- manualPairing: {
50874
- status: pairingStatus,
50875
- joinImplemented: true,
50876
- protocol: "standalone_command_direct_v1",
50877
- 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."
50878
- }
50879
- };
50880
- }
50881
- case "configure_mesh_host_pairing": {
50882
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50883
- const hostAddress = typeof args?.hostAddress === "string" ? args.hostAddress.trim() : "";
50884
- const token = typeof args?.token === "string" ? args.token.trim() : "";
50885
- if (!meshId) return { success: false, error: "meshId required" };
50886
- if (!hostAddress || !token) return { success: false, error: "hostAddress and token required" };
50887
- try {
50888
- const { configureMeshHostPairing: configureMeshHostPairing2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50889
- const configured = configureMeshHostPairing2(meshId, { hostAddress, token });
50890
- if (!configured) return { success: false, error: "Mesh not found" };
50891
- this.inlineMeshCache.set(meshId, configured.mesh);
50892
- const meshHost = resolveMeshHostStatus(configured.mesh);
50893
- return {
50894
- success: true,
50895
- code: "mesh_host_pairing_pending",
50896
- meshId,
50897
- hostAddress: configured.hostAddress,
50898
- meshHost,
50899
- manualPairing: {
50900
- status: meshHost.pairing?.status || "pairing",
50901
- joinImplemented: true,
50902
- protocol: "standalone_command_direct_v1",
50903
- 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."
50904
- }
50905
- };
50906
- } catch (e) {
50907
- return { success: false, code: "mesh_host_pairing_invalid", meshId, hostAddress, error: e.message };
50908
- }
50909
- }
50910
- case "create_mesh_host_pairing_token": {
50911
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50912
- if (!meshId) return { success: false, error: "meshId required" };
50913
- try {
50914
- const { createMeshHostPairingToken: createMeshHostPairingToken2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50915
- const created = createMeshHostPairingToken2(meshId, {
50916
- token: typeof args?.token === "string" ? args.token : void 0,
50917
- expiresAt: typeof args?.expiresAt === "string" ? args.expiresAt : void 0
50918
- });
50919
- if (!created) return { success: false, error: "Mesh not found" };
50920
- this.inlineMeshCache.set(meshId, created.mesh);
50921
- this.invalidateAggregateMeshStatus(meshId);
50922
- return {
50923
- success: true,
50924
- code: "mesh_host_pairing_token_created",
50925
- meshId,
50926
- token: created.token,
50927
- tokenId: created.tokenId,
50928
- expiresAt: created.expiresAt,
50929
- meshHost: resolveMeshHostStatus(created.mesh),
50930
- warning: "Raw token is returned once and is not persisted; share it with member daemons over a trusted channel."
50931
- };
50932
- } catch (e) {
50933
- return { success: false, code: "mesh_host_pairing_token_invalid", meshId, error: e.message };
50934
- }
50935
- }
50936
- case "apply_mesh_host_join": {
50937
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50938
- const token = typeof args?.token === "string" ? args.token.trim() : "";
50939
- const memberNode = args?.memberNode && typeof args.memberNode === "object" && !Array.isArray(args.memberNode) ? args.memberNode : null;
50940
- if (!meshId) return { success: false, error: "meshId required" };
50941
- if (!token || !memberNode) return { success: false, error: "token and memberNode required" };
50942
- try {
50943
- const { applyMeshHostJoinRequest: applyMeshHostJoinRequest2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50944
- const applied = applyMeshHostJoinRequest2(meshId, {
50945
- token,
50946
- memberNode,
50947
- memberMeshId: typeof args?.memberMeshId === "string" ? args.memberMeshId : void 0
50948
- });
50949
- if (!applied) return { success: false, error: "Mesh not found" };
50950
- if (!applied.accepted) {
50951
- return {
50952
- success: false,
50953
- code: "mesh_host_join_rejected",
50954
- meshId,
50955
- tokenId: applied.tokenId,
50956
- meshHost: applied.meshHost ? resolveMeshHostStatus({ meshHost: applied.meshHost }) : void 0,
50957
- error: applied.reason
50958
- };
50959
- }
50960
- this.inlineMeshCache.set(meshId, applied.mesh);
50961
- this.invalidateAggregateMeshStatus(meshId);
50962
- try {
50963
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
50964
- appendLedgerEntry2(meshId, {
50965
- kind: "node_joined",
50966
- nodeId: applied.node.id,
50967
- payload: { role: "member", tokenId: applied.tokenId, workspace: applied.node.workspace }
50968
- });
50969
- } catch {
50970
- }
50971
- return {
50972
- success: true,
50973
- code: "mesh_host_join_accepted",
50974
- meshId,
50975
- node: applied.node,
50976
- tokenId: applied.tokenId,
50977
- meshHost: resolveMeshHostStatus(applied.mesh)
50978
- };
50979
- } catch (e) {
50980
- return { success: false, code: "mesh_host_join_failed", meshId, error: e.message };
50981
- }
50982
- }
50983
- case "join_mesh_host_pairing": {
50984
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
50985
- const token = typeof args?.token === "string" ? args.token.trim() : "";
50986
- if (!meshId) return { success: false, error: "meshId required" };
50987
- if (!token) return { success: false, error: "token required because raw pairing tokens are not persisted" };
50988
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
50989
- const mesh = meshRecord?.mesh;
50990
- if (!mesh) return { success: false, error: "Mesh not found" };
50991
- const meshHost = resolveMeshHostStatus(mesh);
50992
- if (meshHost.role !== "member") {
50993
- 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." };
50994
- }
50995
- try {
50996
- const { tokenIdForManualPairing: tokenIdForManualPairing2, markMeshHostPairingJoined: markMeshHostPairingJoined2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
50997
- const tokenId = tokenIdForManualPairing2(token);
50998
- if (meshHost.pairing?.tokenId && meshHost.pairing.tokenId !== tokenId) {
50999
- return { success: false, code: "mesh_host_join_rejected", meshId, tokenId, meshHost, error: "invalid pairing token" };
51000
- }
51001
- const memberNode = buildMemberJoinNode(mesh, args, this.deps.statusInstanceId);
51002
- if (!memberNode) return { success: false, error: "member node metadata unavailable" };
51003
- const hostMeshId = typeof args?.hostMeshId === "string" && args.hostMeshId.trim() ? args.hostMeshId.trim() : meshId;
51004
- const hostDaemonId = typeof args?.hostDaemonId === "string" && args.hostDaemonId.trim() ? args.hostDaemonId.trim() : meshHost.hostDaemonId;
51005
- let hostResult;
51006
- let transport;
51007
- if (hostDaemonId && this.deps.dispatchMeshCommand) {
51008
- transport = "mesh_command_dispatch";
51009
- hostResult = await this.deps.dispatchMeshCommand(hostDaemonId, "apply_mesh_host_join", {
51010
- meshId: hostMeshId,
51011
- token,
51012
- memberMeshId: meshId,
51013
- memberNode
51014
- });
51015
- } else if (meshHost.hostAddress) {
51016
- transport = "standalone_http_command";
51017
- const commandUrl = normalizeStandaloneHostCommandUrl(meshHost.hostAddress);
51018
- const response = await fetch(commandUrl, {
51019
- method: "POST",
51020
- headers: { "Content-Type": "application/json" },
51021
- body: JSON.stringify({ type: "apply_mesh_host_join", payload: { meshId: hostMeshId, token, memberMeshId: meshId, memberNode } })
51022
- });
51023
- hostResult = await response.json().catch(() => ({ success: false, error: `Host returned HTTP ${response.status}` }));
51024
- if (!response.ok && hostResult?.success !== false) hostResult = { success: false, error: `Host returned HTTP ${response.status}` };
51025
- } else {
51026
- return {
51027
- success: false,
51028
- code: "mesh_host_join_transport_unavailable",
51029
- meshId,
51030
- meshHost,
51031
- error: "No hostDaemonId dispatch path or hostAddress HTTP command path is available. P2P signaling join is not implemented in this slice."
51032
- };
51033
- }
51034
- if (!hostResult?.success) {
51035
- return { success: false, code: hostResult?.code || "mesh_host_join_rejected", meshId, meshHost, transport, error: hostResult?.error || "Mesh Host rejected join request", hostResult };
51036
- }
51037
- const joined = meshRecord.inline ? null : markMeshHostPairingJoined2(meshId, {
51038
- tokenId: hostResult.tokenId || tokenId,
51039
- hostDaemonId: hostResult.meshHost?.hostDaemonId || hostDaemonId,
51040
- hostNodeId: hostResult.meshHost?.hostNodeId,
51041
- joinedAt: hostResult.meshHost?.pairing?.joinedAt
51042
- });
51043
- if (joined) {
51044
- this.inlineMeshCache.set(meshId, joined.mesh);
51045
- this.invalidateAggregateMeshStatus(meshId);
51046
- }
51047
- return {
51048
- success: true,
51049
- code: "mesh_host_join_applied",
51050
- meshId,
51051
- hostMeshId,
51052
- transport,
51053
- node: hostResult.node,
51054
- tokenId: hostResult.tokenId || tokenId,
51055
- meshHost: joined ? resolveMeshHostStatus(joined.mesh) : { ...meshHost, pairing: { ...meshHost.pairing || {}, status: "paired", tokenId: hostResult.tokenId || tokenId } },
51056
- hostResult,
51057
- manualPairing: {
51058
- status: "paired",
51059
- joinImplemented: true,
51060
- protocol: "standalone_command_direct_v1",
51061
- description: "Mesh Host accepted the join and local member pairing status was marked paired. P2P runtime signaling remains outside this slice."
51062
- }
51063
- };
51064
- } catch (e) {
51065
- return { success: false, code: "mesh_host_join_failed", meshId, meshHost, error: e.message };
51066
- }
51067
- }
51068
- case "delete_mesh": {
51069
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51070
- if (!meshId) return { success: false, error: "meshId required" };
51071
- try {
51072
- const { deleteMesh: deleteMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51073
- const deleted = deleteMesh2(meshId);
51074
- return { success: true, deleted };
51075
- } catch (e) {
51076
- return { success: false, error: e.message };
51077
- }
51078
- }
51079
- case "get_mesh_queue": {
51080
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51081
- if (!meshId) return { success: false, error: "meshId required" };
51082
- try {
51083
- const { getMeshQueueStats: getMeshQueueStats2, getQueue: getQueue2, describeTaskDependencyState: describeTaskDependencyState2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51084
- const status = Array.isArray(args?.status) ? args.status.map((s2) => typeof s2 === "string" ? s2.trim() : "").filter(Boolean) : void 0;
51085
- const rawQueue = getQueue2(meshId, { status });
51086
- const statusById = new Map(getQueue2(meshId).map((task) => [task.id, task.status]));
51087
- const queue = rawQueue.map((task) => Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? { ...task, ...describeTaskDependencyState2(task, statusById) } : task);
51088
- const summary = getMeshQueueStats2(meshId);
51089
- return {
51090
- success: true,
51091
- queue,
51092
- summary,
51093
- sourceOfTruth: {
51094
- kind: "mesh_work_queue_file",
51095
- activeStatuses: ["pending", "assigned"],
51096
- historicalStatuses: ["completed", "failed", "cancelled"],
51097
- notes: "pending/assigned are active work; completed/failed/cancelled are historical records."
51098
- }
51099
- };
51100
- } catch (e) {
51101
- return { success: false, error: e.message };
51102
- }
51103
- }
51104
- case "cancel_mesh_queue_task": {
51105
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51106
- const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
51107
- if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
51108
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue cancellation");
51109
- if (ownerFailure) return ownerFailure;
51110
- try {
51111
- const { cancelTask: cancelTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51112
- const reason = typeof args?.reason === "string" ? args.reason : void 0;
51113
- const task = cancelTask2(meshId, taskId, { reason });
51114
- if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
51115
- return { success: true, task };
51116
- } catch (e) {
51117
- return { success: false, error: e.message };
51118
- }
51119
- }
51120
- case "requeue_mesh_queue_task": {
51121
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51122
- const taskId = typeof args?.taskId === "string" ? args.taskId.trim() : "";
51123
- if (!meshId || !taskId) return { success: false, error: "meshId and taskId required" };
51124
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue requeue");
51125
- if (ownerFailure) return ownerFailure;
51126
- try {
51127
- const { requeueTask: requeueTask2 } = await Promise.resolve().then(() => (init_mesh_work_queue(), mesh_work_queue_exports));
51128
- const task = requeueTask2(meshId, taskId, {
51129
- reason: typeof args?.reason === "string" ? args.reason : void 0,
51130
- targetNodeId: typeof args?.targetNodeId === "string" ? args.targetNodeId.trim() : void 0,
51131
- targetSessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : void 0,
51132
- clearTargetNode: args?.clearTargetNode === true,
51133
- clearTargetSession: args?.clearTargetSession !== false
51134
- });
51135
- if (!task) return { success: false, error: `Queue task '${taskId}' not found` };
51136
- return { success: true, task };
51137
- } catch (e) {
51138
- return { success: false, error: e.message };
51139
- }
51140
- }
51141
- case "add_mesh_node": {
51142
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51143
- const workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
51144
- if (!meshId) return { success: false, error: "meshId required" };
51145
- if (!workspace) return { success: false, error: "workspace required" };
51146
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node addition");
51147
- if (ownerFailure) return ownerFailure;
51148
- try {
51149
- const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51150
- const providerPriority = Array.isArray(args?.providerPriority) ? args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean) : [];
51151
- const readOnly = args?.readOnly === true;
51152
- const providerRoles = normalizeProviderRoles(args?.providerRoles);
51153
- const policy = {
51154
- ...readOnly ? { readOnly: true } : {},
51155
- ...providerPriority.length ? { providerPriority } : {},
51156
- ...providerRoles.length ? { providerRoles } : {}
51157
- };
51158
- const role = normalizeMeshDaemonRole(args?.role);
51159
- const daemonId = typeof args?.daemonId === "string" && args.daemonId.trim() ? args.daemonId.trim() : void 0;
51160
- const machineId = typeof args?.machineId === "string" && args.machineId.trim() ? args.machineId.trim() : void 0;
51161
- const repoRoot = typeof args?.repoRoot === "string" && args.repoRoot.trim() ? args.repoRoot.trim() : void 0;
51162
- const node = addNode2(meshId, {
51163
- workspace,
51164
- ...repoRoot ? { repoRoot } : {},
51165
- ...daemonId ? { daemonId } : {},
51166
- ...machineId ? { machineId } : {},
51167
- ...policy ? { policy } : {},
51168
- ...role ? { role } : {}
51169
- });
51170
- if (!node) return { success: false, error: "Mesh not found" };
51171
- this.invalidateAggregateMeshStatus(meshId);
51172
- return { success: true, node };
51173
- } catch (e) {
51174
- return { success: false, error: e.message };
51175
- }
51176
- }
51177
- case "update_mesh_node": {
51178
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51179
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51180
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51181
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node update");
51182
- if (ownerFailure) return ownerFailure;
51183
- try {
51184
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51185
- const policy = args?.policy && typeof args.policy === "object" && !Array.isArray(args.policy) ? { ...args.policy } : {};
51186
- if (Array.isArray(args?.providerPriority)) {
51187
- const providerPriority = args.providerPriority.map((type) => typeof type === "string" ? type.trim() : "").filter(Boolean);
51188
- delete policy.provider_priority;
51189
- if (providerPriority.length) {
51190
- policy.providerPriority = providerPriority;
51191
- } else {
51192
- delete policy.providerPriority;
51193
- }
51194
- }
51195
- if (Array.isArray(args?.providerRoles)) {
51196
- const providerRoles = normalizeProviderRoles(args.providerRoles);
51197
- if (providerRoles.length) {
51198
- policy.providerRoles = providerRoles;
51199
- } else {
51200
- delete policy.providerRoles;
51201
- }
51202
- }
51203
- const patch = { policy };
51204
- if (typeof args?.systemPrompt === "string") {
51205
- const trimmed = args.systemPrompt.trim();
51206
- patch.systemPrompt = trimmed || void 0;
51207
- } else if (args?.systemPrompt === null) {
51208
- patch.systemPrompt = void 0;
51209
- }
51210
- const node = updateNode2(meshId, nodeId, patch);
51211
- if (!node) return { success: false, error: "Mesh node not found" };
51212
- this.invalidateAggregateMeshStatus(meshId);
51213
- return { success: true, node };
51214
- } catch (e) {
51215
- return { success: false, error: e.message };
51216
- }
51217
- }
51218
- case "cleanup_mesh_sessions": {
51219
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51220
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51221
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51222
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "node removal");
51223
- if (ownerFailure) return ownerFailure;
51224
- try {
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 node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51229
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
51230
- const mode = this.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
51231
- const sessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : void 0;
51232
- const result = await this.cleanupMeshSessions({
51233
- meshId,
51234
- nodeId,
51235
- node,
51236
- mode,
51237
- sessionIds,
51238
- dryRun: args?.dryRun === true,
51239
- source: "mesh_cleanup_sessions"
51240
- });
51241
- return result;
51242
- } catch (e) {
51243
- return { success: false, error: e.message };
51244
- }
51245
- }
51246
- case "mesh_init": {
51247
- const workspace = typeof args?.workspace === "string" && args.workspace.trim() ? args.workspace.trim() : process.cwd();
51248
- const mesh = args?.inlineMesh || {};
51249
- try {
51250
- const detected = await detectCLIs(this.deps.providerLoader, { includeVersion: true });
51251
- return { ...runMeshInit(mesh, workspace, detected, {
51252
- write: args?.write === true,
51253
- overwrite: args?.overwrite === true
51254
- }) };
51255
- } catch (e) {
51256
- return { success: false, error: e?.message || String(e) };
51257
- }
51258
- }
51259
- case "plan_mesh_refine_node": {
51260
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51261
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51262
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51263
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51264
- const mesh = meshRecord?.mesh;
51265
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51266
- if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
51267
- return {
51268
- success: true,
51269
- dryRun: true,
51270
- nodeId,
51271
- workspace: node.workspace,
51272
- validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
51273
- mergeWillRun: false,
51274
- cleanupWillRun: false
51275
- };
51276
- }
51277
- case "fast_forward_mesh_node": {
51278
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51279
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51280
- let workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
51281
- let submoduleIgnorePaths = Array.isArray(args?.submoduleIgnorePaths) ? args.submoduleIgnorePaths.filter((value) => typeof value === "string") : void 0;
51282
- let nodeDaemonId;
51283
- let allowAutoPublishSubmoduleMainCommits = false;
51284
- if (meshId && nodeId) {
51285
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51286
- const mesh = meshRecord?.mesh;
51287
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51288
- if (!workspace) {
51289
- workspace = typeof node?.workspace === "string" ? node.workspace.trim() : "";
51290
- }
51291
- if (!submoduleIgnorePaths && Array.isArray(node?.policy?.submoduleIgnorePaths)) {
51292
- submoduleIgnorePaths = node.policy.submoduleIgnorePaths.filter((value) => typeof value === "string");
51293
- }
51294
- allowAutoPublishSubmoduleMainCommits = mesh?.policy?.allowAutoPublishSubmoduleMainCommits === true;
51295
- nodeDaemonId = typeof node?.daemonId === "string" ? node.daemonId.trim() : void 0;
51296
- }
51297
- const selfDaemonId = this.deps.statusInstanceId;
51298
- const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
51299
- if (isRemote && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51300
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "fast_forward_mesh_node", {
51301
- ...typeof args === "object" && args !== null ? args : {},
51302
- workspace,
51303
- _meshDirectDispatch: true
51304
- });
51305
- return forwarded ?? { success: false, error: "no response from remote node" };
51306
- }
51307
- const result = await fastForwardMeshNode({
51308
- meshId: meshId || void 0,
51309
- nodeId: nodeId || void 0,
51310
- workspace,
51311
- branch: typeof args?.branch === "string" ? args.branch : void 0,
51312
- execute: args?.execute === true,
51313
- dryRun: args?.dryRun === true,
51314
- updateSubmodules: args?.updateSubmodules === true,
51315
- submoduleIgnorePaths,
51316
- mode: args?.mode === "push" ? "push" : "merge",
51317
- pushSubmodules: args?.pushSubmodules === true,
51318
- allowAutoPublishSubmoduleMainCommits
51319
- });
51320
- return result;
51321
- }
51322
- case "refine_mesh_node": {
51323
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51324
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51325
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51326
- {
51327
- const meshRecordForForward = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51328
- const forwardNode = meshRecordForForward?.mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51329
- const nodeDaemonId = typeof forwardNode?.daemonId === "string" ? forwardNode.daemonId.trim() : void 0;
51330
- const selfDaemonId = this.deps.statusInstanceId;
51331
- const isRemote = nodeDaemonId && selfDaemonId && !daemonIdsEquivalent(nodeDaemonId, selfDaemonId);
51332
- if (isRemote && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51333
- const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : void 0;
51334
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "refine_mesh_node", {
51335
- ...typeof args === "object" && args !== null ? args : {},
51336
- coordinatorDaemonId: callerCoordinatorDaemonId || selfDaemonId,
51337
- _meshDirectDispatch: true
51338
- });
51339
- return forwarded ?? { success: false, error: "no response from remote node" };
51340
- }
51341
- }
51342
- const isDryRun = args?.dryRun !== false && args?.execute !== true;
51343
- if (isDryRun) {
51344
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51345
- const mesh = meshRecord?.mesh;
51346
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51347
- if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
51348
- return {
51349
- success: true,
51350
- dryRun: true,
51351
- nodeId,
51352
- workspace: node.workspace,
51353
- validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
51354
- mergeWillRun: false,
51355
- cleanupWillRun: false,
51356
- hint: "Dry-run only \u2014 no merge/push/cleanup performed. Re-invoke with execute:true to converge this node."
51357
- };
51358
- }
51359
- return this.startMeshRefineJob(meshId, nodeId, args);
51360
- }
51361
- case "batch_refine_mesh_nodes": {
51362
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51363
- if (!meshId) return { success: false, error: "meshId required" };
51364
- const requestedNodeIds = Array.isArray(args?.nodeIds) ? args.nodeIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
51365
- const isDryRun = args?.dryRun !== false && args?.execute !== true;
51366
- if (isDryRun) return this.batchRefineMeshNodes(meshId, requestedNodeIds, args);
51367
- return this.startMeshRefineBatchJob(meshId, requestedNodeIds, args);
51368
- }
51369
- case "remove_mesh_node": {
51370
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51371
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51372
- if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
51373
- try {
51374
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51375
- const mesh = meshRecord?.mesh;
51376
- const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51377
- if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
51378
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : "";
51379
- const nodeMachineId = readMeshNodeMachineId(node) || "";
51380
- const selfDaemonId = this.deps.statusInstanceId || "";
51381
- const selfMachineId = (() => {
51382
- try {
51383
- return loadConfig().machineId || "";
51384
- } catch {
51385
- return "";
51386
- }
51387
- })();
51388
- const isCoordinatorBaseNode = !!selfDaemonId && (nodeDaemonId === selfDaemonId || nodeMachineId === selfDaemonId) || !!selfMachineId && (nodeDaemonId === selfMachineId || nodeMachineId === selfMachineId);
51389
- if (isCoordinatorBaseNode) {
51390
- return {
51391
- success: false,
51392
- removed: false,
51393
- code: "mesh_remove_coordinator_base_node_protected",
51394
- 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.`,
51395
- 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."
51396
- };
51397
- }
51398
- }
51399
- const sessionCleanupMode = this.normalizeMeshSessionCleanupMode(
51400
- args?.sessionCleanupMode ?? args?.session_cleanup_mode ?? mesh?.policy?.sessionCleanupOnNodeRemove
51401
- );
51402
- const explicitSessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim()) : void 0;
51403
- let sessionCleanup;
51404
- if (node && sessionCleanupMode !== "preserve") {
51405
- sessionCleanup = await this.cleanupMeshSessions({
51406
- meshId,
51407
- nodeId,
51408
- node,
51409
- mode: sessionCleanupMode,
51410
- ...explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {},
51411
- source: "mesh_remove_node"
51412
- });
51413
- if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
51414
- }
51415
- let worktreeCleanup;
51416
- if (node?.isLocalWorktree) {
51417
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
51418
- const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch;
51419
- if (isRemoteWorktree) {
51420
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "remove_mesh_node", {
51421
- ...typeof args === "object" && args !== null ? args : {},
51422
- _meshDirectDispatch: true
51423
- });
51424
- return forwarded ?? { success: false, error: "no response from remote node" };
51425
- }
51426
- const cleanupResult = await this.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
51427
- if (cleanupResult.success === false) {
51428
- return {
51429
- success: false,
51430
- removed: false,
51431
- code: cleanupResult.code,
51432
- error: cleanupResult.error,
51433
- recoveryHint: cleanupResult.recoveryHint,
51434
- ...sessionCleanup ? { sessionCleanup } : {},
51435
- worktreeCleanup: cleanupResult
51436
- };
51437
- }
51438
- worktreeCleanup = cleanupResult;
51439
- }
51440
- let removed = false;
51441
- if (meshRecord?.inline) {
51442
- removed = this.removeInlineMeshNode(meshId, mesh, nodeId);
51443
- if (removed) this.invalidateAggregateMeshStatus(meshId);
51444
- if (!removed && !node) removed = true;
51445
- } else {
51446
- const { removeNode: removeNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51447
- removed = removeNode2(meshId, nodeId);
51448
- if (!removed && !node) removed = true;
51449
- if (removed) this.invalidateAggregateMeshStatus(meshId);
51450
- }
51451
- if (removed) {
51452
- try {
51453
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51454
- appendLedgerEntry2(meshId, {
51455
- kind: "node_removed",
51456
- nodeId,
51457
- payload: {
51458
- worktree: !!node?.isLocalWorktree,
51459
- sessionCleanupMode,
51460
- workspace: typeof node?.workspace === "string" ? node.workspace : void 0,
51461
- daemonId: typeof node?.daemonId === "string" ? node.daemonId : void 0,
51462
- worktreeBranch: typeof node?.worktreeBranch === "string" ? node.worktreeBranch : void 0,
51463
- worktreeCleanupFallback: typeof worktreeCleanup?.fallback === "string" ? worktreeCleanup.fallback : void 0,
51464
- forced: worktreeCleanup?.forced === true ? true : void 0,
51465
- forceFallbackReason: typeof worktreeCleanup?.reason === "string" ? worktreeCleanup.reason : void 0
51466
- }
51467
- });
51468
- } catch {
51469
- }
51470
- }
51471
- const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === "string" ? worktreeCleanup.residueWarning : void 0;
51472
- return {
51473
- success: true,
51474
- removed,
51475
- ...residueWarning ? { residueWarning } : {},
51476
- ...sessionCleanup ? { sessionCleanup } : {},
51477
- ...worktreeCleanup ? { worktreeCleanup } : {}
51478
- };
51479
- } catch (e) {
51480
- return { success: false, error: e.message };
51481
- }
51482
- }
51483
- case "clone_mesh_node": {
51484
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51485
- const sourceNodeId = typeof args?.sourceNodeId === "string" ? args.sourceNodeId.trim() : "";
51486
- const branch = typeof args?.branch === "string" ? args.branch.trim() : "";
51487
- const baseBranch = typeof args?.baseBranch === "string" ? args.baseBranch.trim() : void 0;
51488
- if (!meshId) return { success: false, error: "meshId required" };
51489
- if (!sourceNodeId) return { success: false, error: "sourceNodeId required" };
51490
- if (!branch) return { success: false, error: "branch required" };
51491
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "worktree clone");
51492
- if (ownerFailure) return ownerFailure;
51493
- try {
51494
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51495
- const mesh = meshRecord?.mesh;
51496
- if (!mesh) return { success: false, error: "Mesh not found" };
51497
- const sourceNode = mesh.nodes?.find((n) => meshNodeIdMatches(n, sourceNodeId));
51498
- if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
51499
- const sourceDaemonId = typeof sourceNode.daemonId === "string" ? sourceNode.daemonId.trim() : void 0;
51500
- if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51501
- const forwarded = await this.deps.dispatchMeshCommand(sourceDaemonId, "clone_mesh_node", {
51502
- ...typeof args === "object" && args !== null ? args : {},
51503
- _meshDirectDispatch: true
51504
- });
51505
- return forwarded ?? { success: false, error: "no response from remote node" };
51506
- }
51507
- const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
51508
- const { createWorktree: createWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
51509
- const result = await createWorktree2({
51510
- repoRoot,
51511
- branch,
51512
- baseBranch,
51513
- meshName: mesh.name
51514
- });
51515
- let node;
51516
- if (meshRecord.inline) {
51517
- const { randomUUID: randomUUID15 } = await import("crypto");
51518
- node = {
51519
- id: `node_${randomUUID15().replace(/-/g, "")}`,
51520
- workspace: result.worktreePath,
51521
- repoRoot: result.worktreePath,
51522
- daemonId: sourceNode.daemonId,
51523
- machineId: sourceNode.machineId ?? sourceNode.machine_id,
51524
- userOverrides: { ...sourceNode.userOverrides || {} },
51525
- policy: { ...sourceNode.policy || {} },
51526
- isLocalWorktree: true,
51527
- worktreeBranch: result.branch,
51528
- clonedFromNodeId: sourceNodeId
51529
- };
51530
- this.updateInlineMeshNode(meshId, mesh, node);
51531
- } else {
51532
- const { addNode: addNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51533
- node = addNode2(meshId, {
51534
- workspace: result.worktreePath,
51535
- repoRoot: result.worktreePath,
51536
- daemonId: sourceNode.daemonId,
51537
- machineId: sourceNode.machineId ?? sourceNode.machine_id,
51538
- userOverrides: { ...sourceNode.userOverrides || {} },
51539
- isLocalWorktree: true,
51540
- worktreeBranch: result.branch,
51541
- clonedFromNodeId: sourceNodeId,
51542
- policy: { ...sourceNode.policy || {} }
51543
- });
51544
- if (!node) return { success: false, error: "Failed to register worktree node" };
51545
- const inlineForReconcile = this.getCachedInlineMesh(meshId);
51546
- if (inlineForReconcile) this.updateInlineMeshNode(meshId, inlineForReconcile, node);
51547
- this.invalidateAggregateMeshStatus(meshId);
51548
- }
51549
- const persistWorktreeSetupState = async (bootstrapState2) => {
51550
- node.worktreeBootstrap = bootstrapState2;
51551
- if (meshRecord.inline) {
51552
- this.updateInlineMeshNode(meshId, mesh, node);
51553
- return;
51554
- }
51555
- try {
51556
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51557
- updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
51558
- this.invalidateAggregateMeshStatus(meshId);
51559
- } catch {
51560
- }
51561
- };
51562
- const appendCloneLedger = async (initSubmodules2, bootstrapState2) => {
51563
- try {
51564
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
51565
- appendLedgerEntry2(meshId, {
51566
- kind: "node_cloned",
51567
- nodeId: node.id,
51568
- payload: {
51569
- sourceNodeId,
51570
- branch: result.branch,
51571
- worktreePath: result.worktreePath,
51572
- submodulesInitialized: initSubmodules2,
51573
- worktreeBootstrap: {
51574
- status: bootstrapState2.status,
51575
- required: bootstrapState2.required,
51576
- configSource: bootstrapState2.configSource,
51577
- configSourceType: bootstrapState2.configSourceType,
51578
- lastCommand: bootstrapState2.lastCommand,
51579
- exitCode: bootstrapState2.exitCode
51580
- }
51581
- }
51582
- });
51583
- } catch {
51584
- }
51585
- };
51586
- const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
51587
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
51588
- const runningBootstrapState = {
51589
- status: "running",
51590
- required: loadedBootstrap.config?.required !== false,
51591
- configSource: loadedBootstrap.path || loadedBootstrap.source,
51592
- configSourceType: loadedBootstrap.sourceType,
51593
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
51594
- };
51595
- await persistWorktreeSetupState(runningBootstrapState);
51596
- const finishWorktreeSetup = async () => {
51597
- let submodulesInitialized2 = false;
51598
- if (initSubmodules) {
51599
- try {
51600
- const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
51601
- await runGit3(
51602
- { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
51603
- ["submodule", "update", "--init", "--recursive"],
51604
- { timeoutMs: 12e4 }
51605
- );
51606
- submodulesInitialized2 = true;
51607
- const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
51608
- if (sourceWorkspace) {
51609
- try {
51610
- const { runGit: rg } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
51611
- const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
51612
- const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
51613
- const sourceStatusOut = await rg(sourceCtx, ["submodule", "status", "oss"], { timeoutMs: 1e4 });
51614
- const sourceStatusLine = (typeof sourceStatusOut === "string" ? sourceStatusOut : sourceStatusOut?.stdout ?? "").trim();
51615
- const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
51616
- const sourceSha = sourceShaMatch?.[1];
51617
- if (sourceSha) {
51618
- const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
51619
- const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
51620
- const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
51621
- if (worktreeOssSha !== sourceSha) {
51622
- await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
51623
- await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
51624
- await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
51625
- await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
51626
- console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
51627
- }
51628
- }
51629
- } catch (ossErr) {
51630
- console.warn("[mesh] oss submodule sync to source HEAD failed (best-effort):", ossErr.message);
51631
- }
51632
- }
51633
- } catch (subErr) {
51634
- console.warn("[mesh] Submodule init failed for worktree:", subErr.message);
51635
- }
51636
- }
51637
- const bootstrapState2 = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
51638
- await persistWorktreeSetupState(bootstrapState2);
51639
- await appendCloneLedger(submodulesInitialized2, bootstrapState2);
51640
- return { submodulesInitialized: submodulesInitialized2, bootstrapState: bootstrapState2 };
51641
- };
51642
- const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8e3);
51643
- const setupWaitMs = Number.isFinite(requestedSetupWaitMs) ? Math.min(Math.max(requestedSetupWaitMs, 0), 14e3) : 8e3;
51644
- const setupPromise = finishWorktreeSetup();
51645
- const setupResult = await Promise.race([
51646
- setupPromise.then((value) => ({ completed: true, value })),
51647
- new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
51648
- ]);
51649
- const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
51650
- try {
51651
- const durationMs = Date.now() - startedAtMs;
51652
- const event = `worktree_${eventStatus2}`;
51653
- const metadataEvent = {
51654
- source: "clone_mesh_node_bootstrap",
51655
- nodeId: node.id,
51656
- status: eventStatus2,
51657
- worktreePath: result.worktreePath,
51658
- durationMs,
51659
- bootstrapStatus: bootstrapState2.status,
51660
- ...bootstrapState2.error ? { error: bootstrapState2.error } : {},
51661
- ...bootstrapState2.exitCode !== void 0 ? { exitCode: bootstrapState2.exitCode } : {},
51662
- ...extraPayload || {}
51663
- };
51664
- if (typeof this.deps.instanceManager?.getByCategory === "function") {
51665
- const forwarded = handleMeshForwardEvent(
51666
- { instanceManager: this.deps.instanceManager },
51667
- { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent }
51668
- );
51669
- if (forwarded?.success === true) return;
51670
- }
51671
- queuePendingMeshCoordinatorEvent({
51672
- event,
51673
- meshId,
51674
- nodeLabel: node.id,
51675
- nodeId: node.id,
51676
- workspace: result.worktreePath,
51677
- metadataEvent,
51678
- queuedAt: Date.now()
51679
- });
51680
- } catch {
51681
- }
51682
- };
51683
- const bootstrapStartedMs = Date.now();
51684
- if (!setupResult.completed) {
51685
- setupPromise.then(({ bootstrapState: bootstrapState2 }) => {
51686
- emitBootstrapEvent("bootstrap_complete", bootstrapState2, bootstrapStartedMs);
51687
- }).catch((error) => {
51688
- const failedState = {
51689
- ...runningBootstrapState,
51690
- status: "failed",
51691
- completedAt: (/* @__PURE__ */ new Date()).toISOString(),
51692
- error: error?.message || String(error)
51693
- };
51694
- void persistWorktreeSetupState(failedState);
51695
- void appendCloneLedger(false, failedState);
51696
- emitBootstrapEvent("bootstrap_failed", failedState, bootstrapStartedMs, { error: error?.message || String(error) });
51697
- });
51698
- return {
51699
- success: true,
51700
- async: true,
51701
- status: "accepted",
51702
- node,
51703
- worktreePath: result.worktreePath,
51704
- branch: result.branch,
51705
- worktreeBootstrap: runningBootstrapState,
51706
- worktreeSetup: {
51707
- status: "running",
51708
- setupWaitMs,
51709
- message: "Worktree node is registered; submodule/bootstrap setup is continuing in the background."
51710
- }
51711
- };
51712
- }
51713
- const { submodulesInitialized, bootstrapState } = setupResult.value;
51714
- emitBootstrapEvent("bootstrap_complete", bootstrapState, bootstrapStartedMs);
51715
- return {
51716
- success: true,
51717
- node,
51718
- worktreePath: result.worktreePath,
51719
- branch: result.branch,
51720
- submodulesInitialized,
51721
- worktreeBootstrap: bootstrapState
51722
- };
51723
- } catch (e) {
51724
- return { success: false, error: e.message };
51725
- }
51726
- }
51727
- case "retry_mesh_node_bootstrap": {
51728
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51729
- const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
51730
- if (!meshId) return { success: false, error: "meshId required" };
51731
- if (!nodeId) return { success: false, error: "nodeId required" };
51732
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "bootstrap retry");
51733
- if (ownerFailure) return ownerFailure;
51734
- try {
51735
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
51736
- const mesh = meshRecord?.mesh;
51737
- if (!mesh) return { success: false, error: "Mesh not found" };
51738
- const node = mesh.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
51739
- if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
51740
- if (!node.isLocalWorktree) return { success: false, error: "Node is not a local worktree node" };
51741
- const nodeDaemonId = typeof node.daemonId === "string" ? node.daemonId.trim() : void 0;
51742
- if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, this.deps.statusInstanceId) && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
51743
- const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId, "retry_mesh_node_bootstrap", {
51744
- ...typeof args === "object" && args !== null ? args : {},
51745
- _meshDirectDispatch: true
51746
- });
51747
- return forwarded ?? { success: false, error: "no response from remote node" };
51748
- }
51749
- const currentBootstrap = node.worktreeBootstrap;
51750
- if (currentBootstrap?.status === "running") {
51751
- return { success: false, error: "Bootstrap is already running for this node" };
51752
- }
51753
- const worktreePath = node.workspace || node.repoRoot;
51754
- if (!worktreePath) return { success: false, error: "Node has no workspace path" };
51755
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
51756
- const runningState = {
51757
- status: "running",
51758
- required: loadedBootstrap.config?.required !== false,
51759
- configSource: loadedBootstrap.path || loadedBootstrap.source,
51760
- configSourceType: loadedBootstrap.sourceType,
51761
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
51762
- };
51763
- const persistState = async (bootstrapState2) => {
51764
- node.worktreeBootstrap = bootstrapState2;
51765
- if (meshRecord.inline) {
51766
- this.updateInlineMeshNode(meshId, mesh, node);
51767
- return;
51768
- }
51769
- try {
51770
- const { updateNode: updateNode2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
51771
- updateNode2(meshId, node.id, { worktreeBootstrap: bootstrapState2 });
51772
- this.invalidateAggregateMeshStatus(meshId);
51773
- } catch {
51774
- }
51775
- };
51776
- await persistState(runningState);
51777
- const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
51778
- await persistState(bootstrapState);
51779
- return { success: true, bootstrapState };
51780
- } catch (e) {
51781
- return { success: false, error: e.message };
51782
- }
51783
- }
51784
- case "trigger_mesh_queue": {
51785
- const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
51786
- if (!meshId) return { success: false, error: "meshId required" };
51787
- const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "queue trigger");
51788
- if (ownerFailure) return ownerFailure;
51789
- try {
51790
- const { triggerMeshQueue: triggerMeshQueue2, tryAssignQueueTask: tryAssignQueueTask2 } = await Promise.resolve().then(() => (init_mesh_events(), mesh_events_exports));
51791
- const preferredNodeId = typeof args?.preferredNodeId === "string" ? args.preferredNodeId.trim() : "";
51792
- if (preferredNodeId) {
51793
- const cliInstances = this.deps.instanceManager.getByCategory("cli");
51794
- const sorted = [...cliInstances].sort((a, b) => {
51795
- const aSettings = a.getState().settings || {};
51796
- const bSettings = b.getState().settings || {};
51797
- const aNode = readStringValue(aSettings.meshNodeId, aSettings.nodeId);
51798
- const bNode = readStringValue(bSettings.meshNodeId, bSettings.nodeId);
51799
- return (aNode === preferredNodeId ? -1 : 0) - (bNode === preferredNodeId ? -1 : 0);
51800
- });
51801
- for (const inst of sorted) {
51802
- const state = inst.getState();
51803
- const settings = state.settings || {};
51804
- const nodeId = readStringValue(settings.meshNodeId, settings.nodeId);
51805
- if (!nodeId || nodeId !== preferredNodeId) continue;
51806
- const meshNodeFor = readStringValue(settings.meshNodeFor);
51807
- if (meshNodeFor !== meshId) continue;
51808
- const status = (readStringValue(state.status) || "").toLowerCase();
51809
- if (status !== "idle") continue;
51810
- const sessionId = typeof state.instanceId === "string" ? state.instanceId : "";
51811
- const providerType = readStringValue(state.type, settings.providerType) || "";
51812
- if (sessionId && providerType) {
51813
- tryAssignQueueTask2(this.deps, meshId, nodeId, sessionId, providerType);
51814
- break;
51815
- }
51816
- }
51817
- }
51818
- const trigger = await triggerMeshQueue2(this.deps, meshId);
51819
- return { success: true, trigger };
51820
- } catch (e) {
51821
- return { success: false, error: e.message };
51822
- }
51823
- }
51824
51900
  // ─── Mesh Coordinator Launch ───
51825
51901
  case "launch_mesh_coordinator": {
51826
51902
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";