@adhdev/daemon-core 0.9.82-rc.28 → 0.9.82-rc.281
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/boot/daemon-lifecycle.d.ts +8 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/build-info.d.ts +37 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +23 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/cli-manager.d.ts +2 -1
- package/dist/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +160 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +72 -1
- package/dist/git/git-commands.d.ts +9 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-status.d.ts +7 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/index.d.ts +51 -12
- package/dist/index.js +34388 -12966
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +38052 -16731
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +36 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +108 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +133 -0
- package/dist/mesh/mesh-events-pending.d.ts +45 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +47 -0
- package/dist/mesh/mesh-events.d.ts +6 -49
- package/dist/mesh/mesh-fast-forward.d.ts +81 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +68 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +345 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-work-queue.d.ts +166 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +215 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
- package/dist/providers/acp-provider-instance.d.ts +2 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/cli-provider-instance.d.ts +61 -3
- package/dist/providers/contracts.d.ts +130 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/dispatcher.d.ts +27 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +13 -0
- package/dist/providers/provider-instance.d.ts +13 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +59 -0
- package/dist/providers/spec/cli-adapter.d.ts +140 -0
- package/dist/providers/spec/evaluator.d.ts +23 -0
- package/dist/providers/spec/fsm-driver.d.ts +278 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +106 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +144 -0
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +48 -0
- package/dist/repo-mesh-types.d.ts +154 -13
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +42 -1
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +1 -0
- package/dist/types.d.ts +5 -0
- package/package.json +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/boot/daemon-lifecycle.ts +55 -12
- package/src/boot/process-hardening.ts +89 -0
- package/src/build-info.ts +73 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +1 -0
- package/src/cli-adapter-types.ts +22 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1215 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
- package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
- package/src/cli-adapters/provider-cli-parse.ts +13 -0
- package/src/cli-adapters/provider-cli-runtime.ts +3 -1
- package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
- package/src/cli-adapters/provider-cli-shared.ts +68 -11
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
- package/src/cli-adapters/terminal-backends/types.ts +10 -3
- package/src/cli-adapters/terminal-screen.ts +16 -81
- package/src/commands/chat-commands.ts +1813 -60
- package/src/commands/cli-manager.ts +286 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +5739 -566
- package/src/config/chat-history.ts +229 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +303 -3
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/detection/ide-detector.ts +26 -16
- package/src/git/git-commands.ts +42 -12
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-status.ts +198 -7
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +131 -11
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +219 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +468 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +1592 -0
- package/src/mesh/mesh-events-pending.ts +508 -0
- package/src/mesh/mesh-events-stale.ts +283 -0
- package/src/mesh/mesh-events-utils.ts +254 -0
- package/src/mesh/mesh-events.ts +30 -1035
- package/src/mesh/mesh-fast-forward.ts +839 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
- package/src/mesh/mesh-ledger.ts +589 -102
- package/src/mesh/mesh-missions.ts +172 -0
- package/src/mesh/mesh-reconcile-loop.ts +298 -0
- package/src/mesh/mesh-refine-batch.ts +197 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-routing.ts +272 -0
- package/src/mesh/mesh-runtime-store.ts +1399 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-work-queue.ts +586 -145
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +403 -0
- package/src/mesh/worktree-bootstrap-config.ts +326 -0
- package/src/providers/acp-provider-instance.ts +15 -1
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +4 -11
- package/src/providers/cli-provider-instance.ts +920 -81
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +141 -6
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +19 -5
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/dispatcher.ts +340 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +30 -0
- package/src/providers/provider-instance.ts +10 -1
- package/src/providers/provider-loader.ts +584 -50
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +155 -0
- package/src/providers/spec/cli-adapter.ts +730 -0
- package/src/providers/spec/evaluator.ts +345 -0
- package/src/providers/spec/fsm-driver.ts +868 -0
- package/src/providers/spec/fsm-evaluator.ts +255 -0
- package/src/providers/spec/fsm-loader.ts +102 -0
- package/src/providers/spec/fsm-types.ts +199 -0
- package/src/providers/spec/native-history-executor.ts +943 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/types.ts +189 -0
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +446 -0
- package/src/providers/version-archive.ts +38 -20
- package/src/repo-mesh-types.ts +183 -13
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.ts +45 -1
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +15 -0
- package/src/status/snapshot.ts +84 -25
- package/src/system/host-memory.ts +29 -12
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -0,0 +1,1592 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
|
|
3
|
+
import { loadConfig } from '../config/config.js';
|
|
4
|
+
import { getMesh, getMeshByRepo } from '../config/mesh-config.js';
|
|
5
|
+
import { detectCLI } from '../detection/cli-detector.js';
|
|
6
|
+
import { LOG } from '../logging/logger.js';
|
|
7
|
+
import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
|
|
8
|
+
import type { MeshLedgerKind, SessionRecoveryContext } from './mesh-ledger.js';
|
|
9
|
+
import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches, hasPendingDependents } from './mesh-work-queue.js';
|
|
10
|
+
import { fastForwardMeshNode } from './mesh-fast-forward.js';
|
|
11
|
+
import { createSessionDelivery, markSessionDeliveriesTerminal, updateSessionDeliveryStatus, recordCompletionConflict } from './mesh-delivery-policy.js';
|
|
12
|
+
import { MeshRuntimeStore } from './mesh-runtime-store.js';
|
|
13
|
+
import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
|
|
14
|
+
import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
|
|
15
|
+
import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent } from './mesh-routing.js';
|
|
16
|
+
import { resolveDelegatedWorkerAutoApprove } from '../repo-mesh-types.js';
|
|
17
|
+
import {
|
|
18
|
+
findRecentTerminalLedgerEvidence,
|
|
19
|
+
hasDispatchAfterTerminal,
|
|
20
|
+
hasUnterminalDirectDispatchLedgerEntry,
|
|
21
|
+
buildLongGeneratingCompletionReconciliation,
|
|
22
|
+
} from './mesh-events-stale.js';
|
|
23
|
+
import {
|
|
24
|
+
buildMeshSystemMessage,
|
|
25
|
+
readNonEmptyString,
|
|
26
|
+
readRecord,
|
|
27
|
+
resolveEventSessionId,
|
|
28
|
+
readRefineJobId,
|
|
29
|
+
readWorkerResultMetadata,
|
|
30
|
+
} from './mesh-events-utils.js';
|
|
31
|
+
|
|
32
|
+
// The set of coordinator-daemon ids this daemon answers to when draining the
|
|
33
|
+
// pending-events queue (canonical status id + bare machineId). Mirrors
|
|
34
|
+
// resolveCoordinatorDaemonIds in mesh-reconcile-loop — a unicast event may be
|
|
35
|
+
// stamped with either id depending on which dispatch path created the worker.
|
|
36
|
+
function resolveCoordinatorDrainDaemonIds(components: DaemonComponents): string[] {
|
|
37
|
+
const ids = new Set<string>();
|
|
38
|
+
const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
|
|
39
|
+
if (statusInstanceId) ids.add(statusInstanceId);
|
|
40
|
+
const machineId = readNonEmptyString(loadConfig().machineId);
|
|
41
|
+
if (machineId) ids.add(machineId);
|
|
42
|
+
return [...ids];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// Remote Node Idle Session Tracking
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
49
|
+
|
|
50
|
+
// ---------------------------------------------------------------------------
|
|
51
|
+
// Workspace-to-mesh lookup cache
|
|
52
|
+
// ---------------------------------------------------------------------------
|
|
53
|
+
const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
|
|
54
|
+
const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
|
|
55
|
+
const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
|
|
56
|
+
const idleAutoFastForwardLastAttempt = new Map<string, number>();
|
|
57
|
+
|
|
58
|
+
function getCachedMeshByWorkspace(workspace: string): any {
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
const cached = meshByWorkspaceCache.get(workspace);
|
|
61
|
+
if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
|
|
62
|
+
const mesh = getMeshByRepo(workspace);
|
|
63
|
+
meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
|
|
64
|
+
return mesh;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function __resetIdleAutoFastForwardForTests(): void {
|
|
68
|
+
idleAutoFastForwardLastAttempt.clear();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function __resetMeshWorkspaceCacheForTests(): void {
|
|
72
|
+
meshByWorkspaceCache.clear();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sweepExpiredRemoteIdleSessions(): void {
|
|
76
|
+
try {
|
|
77
|
+
MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
|
|
78
|
+
} catch { /* best-effort */ }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
|
|
82
|
+
const localMesh = getMesh(meshId);
|
|
83
|
+
if (localMesh) return localMesh;
|
|
84
|
+
return components.router?.getCachedInlineMesh(meshId);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1000;
|
|
88
|
+
|
|
89
|
+
function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boolean {
|
|
90
|
+
return event.intentional === true
|
|
91
|
+
|| event.intentionalStop === true
|
|
92
|
+
|| event.operatorCleanup === true
|
|
93
|
+
|| event.reason === 'operator_cleanup'
|
|
94
|
+
|| event.stopReason === 'operator_cleanup'
|
|
95
|
+
|| event.cleanupReason === 'operator_cleanup'
|
|
96
|
+
|| event.source === 'mesh_cleanup_sessions'
|
|
97
|
+
|| event.source === 'mesh_remove_node';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
|
|
101
|
+
if (!sessionId && !nodeId) return false;
|
|
102
|
+
const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
|
|
103
|
+
const entries = readLedgerEntries(meshId, { tail: 200 });
|
|
104
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
105
|
+
const entry = entries[i];
|
|
106
|
+
const timestamp = new Date(entry.timestamp).getTime();
|
|
107
|
+
if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
|
|
108
|
+
if (!isIntentionalCleanupStopEntry(entry)) continue;
|
|
109
|
+
if (sessionId && entry.sessionId === sessionId) return true;
|
|
110
|
+
if (!sessionId && nodeId && entry.nodeId === nodeId) return true;
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function shouldSuppressIntentionalCleanupStop(args: {
|
|
116
|
+
event: string;
|
|
117
|
+
meshId: string;
|
|
118
|
+
metadataEvent: Record<string, unknown>;
|
|
119
|
+
sessionId?: string;
|
|
120
|
+
nodeId?: string;
|
|
121
|
+
}): boolean {
|
|
122
|
+
if (args.event !== 'agent:stopped' && args.event !== 'monitor:long_generating') return false;
|
|
123
|
+
if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
|
|
124
|
+
return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
|
|
128
|
+
|
|
129
|
+
function hasFingerprintSeen(fingerprint: string): boolean {
|
|
130
|
+
try {
|
|
131
|
+
return MeshRuntimeStore.getInstance().hasCompletionFingerprint(fingerprint);
|
|
132
|
+
} catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function recordFingerprintSeen(fingerprint: string): void {
|
|
138
|
+
try {
|
|
139
|
+
const db = MeshRuntimeStore.getInstance();
|
|
140
|
+
db.recordCompletionFingerprint(fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
|
|
141
|
+
db.sweepExpiredFingerprints();
|
|
142
|
+
} catch { /* best-effort; duplicate events are preferable to a crash */ }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function readEventTimestamp(value: unknown): number | null {
|
|
146
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
147
|
+
if (typeof value === 'string' && value.trim()) {
|
|
148
|
+
const numeric = Number(value);
|
|
149
|
+
if (Number.isFinite(numeric)) return numeric;
|
|
150
|
+
const parsed = Date.parse(value);
|
|
151
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
152
|
+
}
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function buildMeshCompletionFingerprint(args: {
|
|
157
|
+
meshId: string;
|
|
158
|
+
event: string;
|
|
159
|
+
sessionId: string;
|
|
160
|
+
providerType?: string;
|
|
161
|
+
providerSessionId?: string;
|
|
162
|
+
timestamp?: number | null;
|
|
163
|
+
finalSummary?: string;
|
|
164
|
+
coordinatorDaemonId?: string;
|
|
165
|
+
}): string {
|
|
166
|
+
const timestampPart = Number.isFinite(args.timestamp)
|
|
167
|
+
? String(args.timestamp)
|
|
168
|
+
: readNonEmptyString(args.finalSummary).slice(0, 200);
|
|
169
|
+
return [
|
|
170
|
+
args.meshId,
|
|
171
|
+
args.event,
|
|
172
|
+
args.sessionId,
|
|
173
|
+
args.providerType || '',
|
|
174
|
+
args.providerSessionId || '',
|
|
175
|
+
timestampPart,
|
|
176
|
+
args.coordinatorDaemonId || '',
|
|
177
|
+
].join('::');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isDuplicateMeshCompletionEvent(args: {
|
|
181
|
+
meshId: string;
|
|
182
|
+
event: string;
|
|
183
|
+
sessionId: string;
|
|
184
|
+
providerType?: string;
|
|
185
|
+
providerSessionId?: string;
|
|
186
|
+
timestamp?: number | null;
|
|
187
|
+
finalSummary?: string;
|
|
188
|
+
coordinatorDaemonId?: string;
|
|
189
|
+
taskId?: string;
|
|
190
|
+
nodeId?: string;
|
|
191
|
+
}): boolean {
|
|
192
|
+
const fingerprint = buildMeshCompletionFingerprint(args);
|
|
193
|
+
if (!fingerprint) return false;
|
|
194
|
+
if (hasFingerprintSeen(fingerprint)) {
|
|
195
|
+
if (args.taskId) {
|
|
196
|
+
recordCompletionConflict({
|
|
197
|
+
meshId: args.meshId,
|
|
198
|
+
fingerprint,
|
|
199
|
+
conflictingTaskId: args.taskId,
|
|
200
|
+
conflictingSessionId: args.sessionId,
|
|
201
|
+
event: args.event,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
recordFingerprintSeen(fingerprint);
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function isDuplicateMeshApprovalEvent(args: {
|
|
211
|
+
meshId: string;
|
|
212
|
+
sessionId: string;
|
|
213
|
+
providerType?: string;
|
|
214
|
+
timestamp?: number | null;
|
|
215
|
+
modalMessage?: string;
|
|
216
|
+
modalButtons?: unknown;
|
|
217
|
+
}): boolean {
|
|
218
|
+
const modalButtons = Array.isArray(args.modalButtons)
|
|
219
|
+
? args.modalButtons.map(button => String(button).trim()).filter(Boolean)
|
|
220
|
+
: [];
|
|
221
|
+
const approvalIdentity = Number.isFinite(args.timestamp)
|
|
222
|
+
? String(args.timestamp)
|
|
223
|
+
: JSON.stringify({ message: args.modalMessage || '', buttons: modalButtons });
|
|
224
|
+
if (!approvalIdentity || approvalIdentity === '{"message":"","buttons":[]}') return false;
|
|
225
|
+
const fingerprint = [
|
|
226
|
+
args.meshId,
|
|
227
|
+
'agent:waiting_approval',
|
|
228
|
+
args.sessionId,
|
|
229
|
+
args.providerType || '',
|
|
230
|
+
approvalIdentity,
|
|
231
|
+
].join('::');
|
|
232
|
+
if (hasFingerprintSeen(fingerprint)) return true;
|
|
233
|
+
recordFingerprintSeen(fingerprint);
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
|
|
238
|
+
const jobId = readRefineJobId({ metadataEvent });
|
|
239
|
+
const fingerprint = jobId && new Set(['refine:completed', 'refine:failed']).has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
|
|
240
|
+
if (!fingerprint) return false;
|
|
241
|
+
if (hasFingerprintSeen(fingerprint)) return true;
|
|
242
|
+
recordFingerprintSeen(fingerprint);
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---------------------------------------------------------------------------
|
|
247
|
+
// Queue assignment
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
export function tryAssignQueueTask(
|
|
251
|
+
components: DaemonComponents,
|
|
252
|
+
meshId: string,
|
|
253
|
+
nodeId: string,
|
|
254
|
+
sessionId: string,
|
|
255
|
+
providerType: string
|
|
256
|
+
): boolean {
|
|
257
|
+
const mesh = getMeshWithCache(components, meshId);
|
|
258
|
+
const node = mesh?.nodes.find((n: any) => n.id === nodeId);
|
|
259
|
+
const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
|
|
260
|
+
const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags);
|
|
261
|
+
if (!task) {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
|
|
266
|
+
|
|
267
|
+
if (node?.daemonId && components.dispatchMeshCommand) {
|
|
268
|
+
const isLocalNode = components.cliManager.adapters.has(sessionId);
|
|
269
|
+
if (!isLocalNode) {
|
|
270
|
+
const delivery = createSessionDelivery({
|
|
271
|
+
meshId,
|
|
272
|
+
nodeId,
|
|
273
|
+
sessionId,
|
|
274
|
+
providerType,
|
|
275
|
+
taskId: task.id,
|
|
276
|
+
kind: 'task',
|
|
277
|
+
message: task.message,
|
|
278
|
+
status: 'delivering',
|
|
279
|
+
});
|
|
280
|
+
const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
|
|
281
|
+
components.dispatchMeshCommand(node.daemonId, 'agent_command', {
|
|
282
|
+
targetSessionId: sessionId,
|
|
283
|
+
cliType: providerType,
|
|
284
|
+
action: 'send_chat',
|
|
285
|
+
message: task.message,
|
|
286
|
+
meshContext: {
|
|
287
|
+
meshId,
|
|
288
|
+
nodeId,
|
|
289
|
+
taskId: task.id,
|
|
290
|
+
...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
|
|
291
|
+
},
|
|
292
|
+
}).then(() => {
|
|
293
|
+
updateSessionDeliveryStatus(delivery.id, 'delivered');
|
|
294
|
+
}).catch((e: any) => {
|
|
295
|
+
LOG.error('MeshQueue', `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
|
|
296
|
+
updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
|
|
297
|
+
updateTaskStatus(meshId, task.id, 'pending');
|
|
298
|
+
try {
|
|
299
|
+
appendLedgerEntry(meshId, {
|
|
300
|
+
kind: 'dispatch_failed' as any,
|
|
301
|
+
nodeId,
|
|
302
|
+
sessionId,
|
|
303
|
+
payload: { taskId: task.id, deliveryId: delivery.id, error: e?.message, retryable: true },
|
|
304
|
+
});
|
|
305
|
+
} catch { /* ledger write is best-effort */ }
|
|
306
|
+
});
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Stamp mesh context onto the session so completion events route correctly
|
|
312
|
+
// via setupMeshEventForwarding. Without this, manually-opened idle sessions
|
|
313
|
+
// (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
|
|
314
|
+
// agent:generating_completed is silently dropped as isMeshDelegate=false.
|
|
315
|
+
try {
|
|
316
|
+
const inst = components.instanceManager.getInstance(sessionId);
|
|
317
|
+
if (inst && typeof inst.updateSettings === 'function') {
|
|
318
|
+
// Adopting a (possibly manually-opened) local session as a worker: apply the
|
|
319
|
+
// delegated-worker auto-approve policy here too, so a session that was launched
|
|
320
|
+
// without autoApprove still auto-approves once the coordinator dispatches a task
|
|
321
|
+
// to it (the "approval notification fires only for certain delegated sessions"
|
|
322
|
+
// case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
|
|
323
|
+
//
|
|
324
|
+
// This local-dispatch branch also runs on the coordinator daemon for a co-located
|
|
325
|
+
// session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
|
|
326
|
+
// the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
|
|
327
|
+
// the anchor the forwarder keys on), matching what mesh_launch_session stamps.
|
|
328
|
+
const localDaemonId = readNonEmptyString(loadConfig().machineId);
|
|
329
|
+
inst.updateSettings({
|
|
330
|
+
meshNodeFor: meshId,
|
|
331
|
+
meshNodeId: nodeId,
|
|
332
|
+
launchedByCoordinator: true,
|
|
333
|
+
autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
|
|
334
|
+
...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
} catch { /* best-effort — dispatch still proceeds */ }
|
|
338
|
+
|
|
339
|
+
const delivery = createSessionDelivery({
|
|
340
|
+
meshId,
|
|
341
|
+
nodeId,
|
|
342
|
+
sessionId,
|
|
343
|
+
providerType,
|
|
344
|
+
taskId: task.id,
|
|
345
|
+
kind: 'task',
|
|
346
|
+
message: task.message,
|
|
347
|
+
status: 'delivering',
|
|
348
|
+
});
|
|
349
|
+
components.cliManager.handleCliCommand('agent_command', {
|
|
350
|
+
targetSessionId: sessionId,
|
|
351
|
+
cliType: providerType,
|
|
352
|
+
action: 'send_chat',
|
|
353
|
+
message: task.message,
|
|
354
|
+
}).then(() => {
|
|
355
|
+
updateSessionDeliveryStatus(delivery.id, 'delivered');
|
|
356
|
+
}).catch((e: any) => {
|
|
357
|
+
LOG.error('MeshQueue', `Failed to dispatch task locally to node ${nodeId}: ${e?.message}`);
|
|
358
|
+
updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
|
|
359
|
+
updateTaskStatus(meshId, task.id, 'failed');
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const autoLaunchInProgress = new Set<string>();
|
|
366
|
+
const autoLaunchCooldownUntil = new Map<string, number>();
|
|
367
|
+
const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
|
|
368
|
+
|
|
369
|
+
function sweepExpiredCooldowns(): void {
|
|
370
|
+
const now = Date.now();
|
|
371
|
+
for (const [key, until] of autoLaunchCooldownUntil) {
|
|
372
|
+
if (now >= until) autoLaunchCooldownUntil.delete(key);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function normalizeProviderPriority(policy: unknown): string[] {
|
|
377
|
+
const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
378
|
+
? (policy as Record<string, unknown>).providerPriority
|
|
379
|
+
: undefined;
|
|
380
|
+
if (!Array.isArray(raw)) return [];
|
|
381
|
+
const seen = new Set<string>();
|
|
382
|
+
return raw
|
|
383
|
+
.map(type => typeof type === 'string' ? type.trim() : '')
|
|
384
|
+
.filter(Boolean)
|
|
385
|
+
.filter(type => {
|
|
386
|
+
if (seen.has(type)) return false;
|
|
387
|
+
seen.add(type);
|
|
388
|
+
return true;
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function isTerminalSessionStatus(status: string): boolean {
|
|
393
|
+
return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function isIdleSessionState(state: any): boolean {
|
|
397
|
+
const status = readNonEmptyString(state?.status).toLowerCase();
|
|
398
|
+
if (isTerminalSessionStatus(status)) return false;
|
|
399
|
+
return status === 'idle' || state?.activeChat?.status === 'waiting_input';
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function isDirtyNode(node: any): boolean {
|
|
403
|
+
return node?.health === 'dirty' || node?.git?.dirty === true;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
|
|
407
|
+
const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
|
|
408
|
+
? mesh.policy.autoFastForward as Record<string, unknown>
|
|
409
|
+
: {};
|
|
410
|
+
const maxBehind = Number(record.maxBehind);
|
|
411
|
+
return {
|
|
412
|
+
enabled: record.enabled !== false,
|
|
413
|
+
...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
|
|
414
|
+
requireCleanSubmodules: record.requireCleanSubmodules !== false,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function sessionStateLooksActive(state: any): boolean {
|
|
419
|
+
const status = readNonEmptyString(state?.status).toLowerCase();
|
|
420
|
+
const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
|
|
421
|
+
const active = new Set(['generating', 'streaming', 'long_generating', 'working', 'starting', 'waiting_approval']);
|
|
422
|
+
return active.has(status) || active.has(chatStatus);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
|
|
426
|
+
if (nodeHasActiveAssignment(meshId, nodeId)) return true;
|
|
427
|
+
return components.instanceManager.getByCategory('cli').some((inst: any) => {
|
|
428
|
+
const state = inst.getState();
|
|
429
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
430
|
+
if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
|
|
431
|
+
const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
432
|
+
if (instNodeId !== nodeId) return false;
|
|
433
|
+
const sessionId = readNonEmptyString(state.instanceId);
|
|
434
|
+
if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
|
|
435
|
+
return sessionStateLooksActive(state);
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function isLaunchableNode(node: any): boolean {
|
|
440
|
+
if (!node || node.status === 'disabled' || node.status === 'removed') return false;
|
|
441
|
+
const health = readNonEmptyString(node.health).toLowerCase();
|
|
442
|
+
if (!health) return true;
|
|
443
|
+
return health === 'online' || health === 'unknown';
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function localAutoLaunchSkipReason(node: any): string | null {
|
|
447
|
+
const daemonId = readNonEmptyString(node?.daemonId);
|
|
448
|
+
const machineId = readNonEmptyString(node?.machineId);
|
|
449
|
+
const appConfig = loadConfig();
|
|
450
|
+
const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
|
|
451
|
+
const cloudDaemonId = localMachineId ? `daemon_${localMachineId}` : '';
|
|
452
|
+
const standaloneDaemonId = localMachineId ? `standalone_${localMachineId}` : '';
|
|
453
|
+
|
|
454
|
+
const daemonMatchesLocal = !daemonId || daemonId === cloudDaemonId || daemonId === standaloneDaemonId;
|
|
455
|
+
const machineMatchesLocal = !machineId || (localMachineId && machineId === localMachineId);
|
|
456
|
+
|
|
457
|
+
if (node?.isLocalWorktree === true) {
|
|
458
|
+
return daemonMatchesLocal && machineMatchesLocal ? null : 'remote_auto_launch_unsupported';
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (daemonId || machineId) {
|
|
462
|
+
return daemonMatchesLocal && machineMatchesLocal ? null : 'remote_auto_launch_unsupported';
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function activeAssignedCount(meshId: string): number {
|
|
469
|
+
return getQueue(meshId, { status: ['assigned'] as any }).length;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
|
|
473
|
+
return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
|
|
477
|
+
if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
// Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
|
|
481
|
+
// work queue. A session completing a still-active direct dispatch IS an active
|
|
482
|
+
// assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
|
|
483
|
+
// the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
|
|
484
|
+
// so the coordinator polling get_pending_mesh_events never observes task_completed and the
|
|
485
|
+
// session goes silently idle. This check runs before markSessionTerminal marks the
|
|
486
|
+
// dispatch terminal, so the in-flight dispatch is still observable here.
|
|
487
|
+
try {
|
|
488
|
+
if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
|
|
489
|
+
if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
|
|
490
|
+
} catch { /* best-effort — fall through to false */ }
|
|
491
|
+
return false;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
|
|
495
|
+
return components.instanceManager.getByCategory('cli').filter((inst: any) => {
|
|
496
|
+
const state = inst.getState();
|
|
497
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
498
|
+
if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
|
|
499
|
+
const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
500
|
+
if (instNodeId !== nodeId) return false;
|
|
501
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
502
|
+
return !isTerminalSessionStatus(status);
|
|
503
|
+
}).length;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function recordAutoLaunchEvent(meshId: string, args: {
|
|
507
|
+
phase: 'skipped' | 'started' | 'failed' | 'completed';
|
|
508
|
+
taskId: string;
|
|
509
|
+
nodeId?: string;
|
|
510
|
+
providerType?: string;
|
|
511
|
+
sessionId?: string;
|
|
512
|
+
reason?: string;
|
|
513
|
+
error?: string;
|
|
514
|
+
}) {
|
|
515
|
+
try {
|
|
516
|
+
appendLedgerEntry(meshId, {
|
|
517
|
+
kind: 'session_auto_launch',
|
|
518
|
+
nodeId: args.nodeId,
|
|
519
|
+
sessionId: args.sessionId,
|
|
520
|
+
providerType: args.providerType,
|
|
521
|
+
payload: {
|
|
522
|
+
phase: args.phase,
|
|
523
|
+
taskId: args.taskId,
|
|
524
|
+
reason: args.reason,
|
|
525
|
+
error: args.error,
|
|
526
|
+
},
|
|
527
|
+
});
|
|
528
|
+
} catch (e: any) {
|
|
529
|
+
LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function markAutoLaunch(meshId: string, taskId: string, args: {
|
|
534
|
+
status: 'skipped' | 'started' | 'failed' | 'completed';
|
|
535
|
+
reason?: string;
|
|
536
|
+
nodeId?: string;
|
|
537
|
+
providerType?: string;
|
|
538
|
+
sessionId?: string;
|
|
539
|
+
error?: string;
|
|
540
|
+
}) {
|
|
541
|
+
recordTaskAutoLaunch(meshId, taskId, {
|
|
542
|
+
status: args.status,
|
|
543
|
+
reason: args.reason || args.error,
|
|
544
|
+
nodeId: args.nodeId,
|
|
545
|
+
providerType: args.providerType,
|
|
546
|
+
sessionId: args.sessionId,
|
|
547
|
+
});
|
|
548
|
+
recordAutoLaunchEvent(meshId, {
|
|
549
|
+
phase: args.status,
|
|
550
|
+
taskId,
|
|
551
|
+
nodeId: args.nodeId,
|
|
552
|
+
providerType: args.providerType,
|
|
553
|
+
sessionId: args.sessionId,
|
|
554
|
+
reason: args.reason,
|
|
555
|
+
error: args.error,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function resolveUsableProvider(
|
|
560
|
+
components: DaemonComponents,
|
|
561
|
+
nodeId: string,
|
|
562
|
+
node: any,
|
|
563
|
+
requiredTags?: string[],
|
|
564
|
+
): Promise<{ providerType?: string; reason?: string }> {
|
|
565
|
+
const providerPriority = normalizeProviderPriority(node?.policy);
|
|
566
|
+
if (!providerPriority.length) return { reason: 'missing_provider_priority' };
|
|
567
|
+
const providerLoader = components.providerLoader;
|
|
568
|
+
if (!providerLoader) return { reason: 'provider_loader_unavailable' };
|
|
569
|
+
|
|
570
|
+
const failed: string[] = [];
|
|
571
|
+
for (const requestedType of providerPriority) {
|
|
572
|
+
const normalizedType = typeof providerLoader.resolveAlias === 'function'
|
|
573
|
+
? providerLoader.resolveAlias(requestedType)
|
|
574
|
+
: requestedType;
|
|
575
|
+
// Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
|
|
576
|
+
// means only hermes-cli qualifies, not any other type in providerPriority).
|
|
577
|
+
if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
|
|
578
|
+
failed.push(`${requestedType}: required_tags_mismatch`);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
|
|
582
|
+
failed.push(`${requestedType}: disabled`);
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
let detected: any;
|
|
586
|
+
try {
|
|
587
|
+
detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
|
|
588
|
+
} catch (e: any) {
|
|
589
|
+
failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
if (typeof providerLoader.setCliDetectionResults === 'function') {
|
|
593
|
+
providerLoader.setCliDetectionResults([{
|
|
594
|
+
id: normalizedType,
|
|
595
|
+
installed: !!detected,
|
|
596
|
+
path: detected?.path,
|
|
597
|
+
}], false);
|
|
598
|
+
}
|
|
599
|
+
(components as any).onStatusChange?.();
|
|
600
|
+
if (detected) return { providerType: normalizedType };
|
|
601
|
+
failed.push(`${requestedType}: not detected`);
|
|
602
|
+
}
|
|
603
|
+
return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
|
|
607
|
+
const queue = getQueue(meshId);
|
|
608
|
+
const pending = queue.filter(task => task.status === 'pending');
|
|
609
|
+
if (!pending.length) return false;
|
|
610
|
+
|
|
611
|
+
const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
|
|
612
|
+
for (const task of pending) {
|
|
613
|
+
if (activeAssignedCount(meshId) >= maxParallelTasks) {
|
|
614
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
if (task.targetSessionId) {
|
|
618
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const candidateNodes = Array.isArray(mesh?.nodes)
|
|
623
|
+
? mesh.nodes.filter((node: any) => {
|
|
624
|
+
if (task.targetNodeId && node?.id !== task.targetNodeId) return false;
|
|
625
|
+
// Skip nodes that can never satisfy requiredTags regardless of which provider
|
|
626
|
+
// from providerPriority is selected. A node satisfies tags if at least one
|
|
627
|
+
// provider in its priority list would produce matching capability tags.
|
|
628
|
+
if (task.requiredTags?.length) {
|
|
629
|
+
const priorities = normalizeProviderPriority(node?.policy);
|
|
630
|
+
const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
|
|
631
|
+
return providerCandidates.some(p =>
|
|
632
|
+
nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
return true;
|
|
636
|
+
})
|
|
637
|
+
: [];
|
|
638
|
+
if (!candidateNodes.length) {
|
|
639
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'no_node_satisfies_required_tags', nodeId: task.targetNodeId });
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
for (const node of candidateNodes) {
|
|
644
|
+
const nodeId = readNonEmptyString(node?.id);
|
|
645
|
+
if (!nodeId) continue;
|
|
646
|
+
const launchKey = `${meshId}:${nodeId}`;
|
|
647
|
+
const now = Date.now();
|
|
648
|
+
const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
|
|
649
|
+
if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
|
|
650
|
+
if (autoLaunchInProgress.has(launchKey)) {
|
|
651
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (now < cooldownUntil) {
|
|
655
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (isDirtyNode(node)) {
|
|
659
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
if (!isLaunchableNode(node)) {
|
|
663
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
const localSkipReason = localAutoLaunchSkipReason(node);
|
|
667
|
+
if (localSkipReason) {
|
|
668
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: localSkipReason, nodeId });
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
if (nodeHasActiveAssignment(meshId, nodeId)) {
|
|
672
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
|
|
676
|
+
if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
|
|
677
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
autoLaunchInProgress.add(launchKey);
|
|
682
|
+
try {
|
|
683
|
+
const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
|
|
684
|
+
if (!resolved.providerType) {
|
|
685
|
+
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
|
|
690
|
+
const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
|
|
691
|
+
cliType: resolved.providerType,
|
|
692
|
+
dir: node.workspace,
|
|
693
|
+
settings: {
|
|
694
|
+
// Worker launch envelope: role + mesh context so worker can route completion events.
|
|
695
|
+
role: 'worker',
|
|
696
|
+
meshNodeFor: meshId,
|
|
697
|
+
meshNodeId: nodeId,
|
|
698
|
+
spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
|
|
699
|
+
// Coordinator-dispatched worker: auto-approve unless mesh/node policy
|
|
700
|
+
// opts out (default true). Lands in settingsOverride and beats the
|
|
701
|
+
// global per-provider-type autoApprove config (see shouldAutoApprove).
|
|
702
|
+
autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
|
|
703
|
+
launchedByCoordinator: true,
|
|
704
|
+
autoLaunchedForQueueTaskId: task.id,
|
|
705
|
+
},
|
|
706
|
+
});
|
|
707
|
+
if (!launchResult?.success) {
|
|
708
|
+
const reason = launchResult?.error || 'launch_cli_failed';
|
|
709
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
|
|
710
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
711
|
+
return false;
|
|
712
|
+
}
|
|
713
|
+
const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
|
|
714
|
+
if (!sessionId) {
|
|
715
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
|
|
716
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
|
|
720
|
+
tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
|
|
721
|
+
return true;
|
|
722
|
+
} catch (e: any) {
|
|
723
|
+
markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
|
|
724
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
|
|
725
|
+
return false;
|
|
726
|
+
} finally {
|
|
727
|
+
autoLaunchInProgress.delete(launchKey);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
return false;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
export interface MeshQueueTriggerResult {
|
|
735
|
+
success: true;
|
|
736
|
+
meshId: string;
|
|
737
|
+
pendingBefore: number;
|
|
738
|
+
assignedBefore: number;
|
|
739
|
+
pendingAfter: number;
|
|
740
|
+
assignedAfter: number;
|
|
741
|
+
claimed: boolean;
|
|
742
|
+
newlyAssignedTasks: Array<{
|
|
743
|
+
id: string;
|
|
744
|
+
nodeId?: string;
|
|
745
|
+
sessionId?: string;
|
|
746
|
+
}>;
|
|
747
|
+
localIdleSessionsChecked: number;
|
|
748
|
+
remoteIdleSessionsChecked: number;
|
|
749
|
+
skippedSessions: Array<{
|
|
750
|
+
nodeId?: string;
|
|
751
|
+
sessionId?: string;
|
|
752
|
+
reason: string;
|
|
753
|
+
status?: string;
|
|
754
|
+
}>;
|
|
755
|
+
autoLaunchStarted: boolean;
|
|
756
|
+
noIdleMeshSessionAvailable?: boolean;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
|
|
760
|
+
return getQueue(meshId, { status: [status] as any }).length;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function getQueueStatusById(meshId: string): Map<string, string> {
|
|
764
|
+
return new Map(getQueue(meshId).map(task => [task.id, task.status]));
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
|
|
768
|
+
const mesh = getMeshWithCache(components, meshId);
|
|
769
|
+
const pendingBefore = countQueueStatus(meshId, 'pending');
|
|
770
|
+
const assignedBefore = countQueueStatus(meshId, 'assigned');
|
|
771
|
+
const beforeStatus = getQueueStatusById(meshId);
|
|
772
|
+
const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
|
|
773
|
+
let localIdleSessionsChecked = 0;
|
|
774
|
+
let remoteIdleSessionsChecked = 0;
|
|
775
|
+
let autoLaunchStarted = false;
|
|
776
|
+
if (!mesh) {
|
|
777
|
+
return {
|
|
778
|
+
success: true,
|
|
779
|
+
meshId,
|
|
780
|
+
pendingBefore,
|
|
781
|
+
assignedBefore,
|
|
782
|
+
pendingAfter: pendingBefore,
|
|
783
|
+
assignedAfter: assignedBefore,
|
|
784
|
+
claimed: false,
|
|
785
|
+
newlyAssignedTasks: [],
|
|
786
|
+
localIdleSessionsChecked,
|
|
787
|
+
remoteIdleSessionsChecked,
|
|
788
|
+
skippedSessions: [{ reason: 'mesh_not_found' }],
|
|
789
|
+
autoLaunchStarted,
|
|
790
|
+
noIdleMeshSessionAvailable: true,
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const cliInstances = components.instanceManager.getByCategory('cli');
|
|
795
|
+
for (const inst of cliInstances) {
|
|
796
|
+
const state = inst.getState();
|
|
797
|
+
const settings = state.settings as Record<string, unknown> || {};
|
|
798
|
+
|
|
799
|
+
const instMeshId = readNonEmptyString(settings.meshNodeFor);
|
|
800
|
+
if (instMeshId !== meshId) continue;
|
|
801
|
+
|
|
802
|
+
const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
|
|
803
|
+
if (!nodeId) continue;
|
|
804
|
+
|
|
805
|
+
if (!isIdleSessionState(state)) {
|
|
806
|
+
const status = readNonEmptyString(state.status).toLowerCase();
|
|
807
|
+
skippedSessions.push({
|
|
808
|
+
nodeId,
|
|
809
|
+
sessionId: readNonEmptyString(state.instanceId),
|
|
810
|
+
reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
|
|
811
|
+
status: status || undefined,
|
|
812
|
+
});
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const sessionId = state.instanceId;
|
|
817
|
+
const providerType = state.type || readNonEmptyString(settings.providerType);
|
|
818
|
+
|
|
819
|
+
if (providerType) {
|
|
820
|
+
localIdleSessionsChecked += 1;
|
|
821
|
+
tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
|
|
822
|
+
} else {
|
|
823
|
+
skippedSessions.push({
|
|
824
|
+
nodeId,
|
|
825
|
+
sessionId,
|
|
826
|
+
reason: 'provider_type_missing',
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
|
|
832
|
+
try {
|
|
833
|
+
remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions();
|
|
834
|
+
} catch { /* best-effort */ }
|
|
835
|
+
|
|
836
|
+
for (const idle of remoteSessions) {
|
|
837
|
+
const node = mesh.nodes.find((n: any) => n.id === idle.nodeId);
|
|
838
|
+
if (node) {
|
|
839
|
+
remoteIdleSessionsChecked += 1;
|
|
840
|
+
const assigned = tryAssignQueueTask(components, meshId, idle.nodeId, idle.sessionId, idle.providerType);
|
|
841
|
+
if (assigned) {
|
|
842
|
+
try {
|
|
843
|
+
MeshRuntimeStore.getInstance().deleteRemoteIdleSession(idle.nodeId, idle.sessionId);
|
|
844
|
+
} catch { /* best-effort */ }
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
|
|
850
|
+
const afterQueue = getQueue(meshId);
|
|
851
|
+
const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
|
|
852
|
+
const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
|
|
853
|
+
const newlyAssignedTasks = afterQueue
|
|
854
|
+
.filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
|
|
855
|
+
.map(task => ({
|
|
856
|
+
id: task.id,
|
|
857
|
+
nodeId: task.assignedNodeId,
|
|
858
|
+
sessionId: task.assignedSessionId,
|
|
859
|
+
}));
|
|
860
|
+
return {
|
|
861
|
+
success: true,
|
|
862
|
+
meshId,
|
|
863
|
+
pendingBefore,
|
|
864
|
+
assignedBefore,
|
|
865
|
+
pendingAfter,
|
|
866
|
+
assignedAfter,
|
|
867
|
+
claimed: newlyAssignedTasks.length > 0,
|
|
868
|
+
newlyAssignedTasks,
|
|
869
|
+
localIdleSessionsChecked,
|
|
870
|
+
remoteIdleSessionsChecked,
|
|
871
|
+
skippedSessions,
|
|
872
|
+
autoLaunchStarted,
|
|
873
|
+
...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchStarted
|
|
874
|
+
? { noIdleMeshSessionAvailable: true }
|
|
875
|
+
: {}),
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
|
|
880
|
+
meshId: string;
|
|
881
|
+
nodeId: string;
|
|
882
|
+
sessionId?: string;
|
|
883
|
+
providerType?: string;
|
|
884
|
+
}): Promise<void> {
|
|
885
|
+
const mesh = getMeshWithCache(components, args.meshId);
|
|
886
|
+
const node = mesh?.nodes?.find((candidate: any) => candidate?.id === args.nodeId || candidate?.nodeId === args.nodeId);
|
|
887
|
+
const workspace = readNonEmptyString(node?.workspace);
|
|
888
|
+
if (!workspace) return;
|
|
889
|
+
if (!existsSync(workspace)) return;
|
|
890
|
+
|
|
891
|
+
const policy = resolveAutoFastForwardPolicy(mesh);
|
|
892
|
+
if (!policy.enabled) return;
|
|
893
|
+
if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
|
|
894
|
+
|
|
895
|
+
const throttleKey = `${args.meshId}:${args.nodeId}`;
|
|
896
|
+
const now = Date.now();
|
|
897
|
+
const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
|
|
898
|
+
if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
|
|
899
|
+
idleAutoFastForwardLastAttempt.set(throttleKey, now);
|
|
900
|
+
|
|
901
|
+
const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
|
|
902
|
+
? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
|
|
903
|
+
: undefined;
|
|
904
|
+
try {
|
|
905
|
+
const dryRun = await fastForwardMeshNode({
|
|
906
|
+
meshId: args.meshId,
|
|
907
|
+
nodeId: args.nodeId,
|
|
908
|
+
workspace,
|
|
909
|
+
execute: false,
|
|
910
|
+
dryRun: true,
|
|
911
|
+
updateSubmodules: false,
|
|
912
|
+
submoduleIgnorePaths,
|
|
913
|
+
trigger: 'idle_auto',
|
|
914
|
+
});
|
|
915
|
+
if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
|
|
916
|
+
const behind = Number(dryRun.current?.behind);
|
|
917
|
+
if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
|
|
918
|
+
if (policy.requireCleanSubmodules) {
|
|
919
|
+
const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
|
|
920
|
+
if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
|
|
921
|
+
}
|
|
922
|
+
await fastForwardMeshNode({
|
|
923
|
+
meshId: args.meshId,
|
|
924
|
+
nodeId: args.nodeId,
|
|
925
|
+
workspace,
|
|
926
|
+
execute: true,
|
|
927
|
+
dryRun: false,
|
|
928
|
+
updateSubmodules: false,
|
|
929
|
+
submoduleIgnorePaths,
|
|
930
|
+
trigger: 'idle_auto',
|
|
931
|
+
});
|
|
932
|
+
} catch (e: any) {
|
|
933
|
+
LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
|
|
938
|
+
meshId: string;
|
|
939
|
+
nodeId: string;
|
|
940
|
+
sessionId: string;
|
|
941
|
+
providerType: string;
|
|
942
|
+
}): void {
|
|
943
|
+
setImmediate(() => {
|
|
944
|
+
maybeAutoFastForwardIdleNode(components, args)
|
|
945
|
+
.finally(() => {
|
|
946
|
+
try {
|
|
947
|
+
tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
|
|
948
|
+
} catch (e: any) {
|
|
949
|
+
LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
|
|
950
|
+
}
|
|
951
|
+
});
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// ---------------------------------------------------------------------------
|
|
956
|
+
// Core event injection
|
|
957
|
+
// ---------------------------------------------------------------------------
|
|
958
|
+
|
|
959
|
+
const MESH_COORDINATOR_EVENTS = new Set([
|
|
960
|
+
'agent:generating_started',
|
|
961
|
+
'agent:generating_completed',
|
|
962
|
+
'agent:waiting_approval',
|
|
963
|
+
'agent:stopped',
|
|
964
|
+
'agent:ready',
|
|
965
|
+
'monitor:long_generating',
|
|
966
|
+
'refine:accepted',
|
|
967
|
+
'refine:completed',
|
|
968
|
+
'refine:failed',
|
|
969
|
+
'worktree_bootstrap_complete',
|
|
970
|
+
'worktree_bootstrap_failed',
|
|
971
|
+
]);
|
|
972
|
+
|
|
973
|
+
const EVENT_TO_LEDGER_KIND: Record<string, MeshLedgerKind> = {
|
|
974
|
+
'agent:generating_completed': 'task_completed',
|
|
975
|
+
'agent:waiting_approval': 'task_approval_needed',
|
|
976
|
+
'agent:stopped': 'task_failed',
|
|
977
|
+
'monitor:long_generating': 'task_stalled',
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
export function isMeshCoordinatorEvent(eventName: unknown): eventName is string {
|
|
981
|
+
return typeof eventName === 'string' && MESH_COORDINATOR_EVENTS.has(eventName);
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// Terminal events that the coordinator is actively blocked waiting on. When the
|
|
985
|
+
// coordinator CLI session dispatches a task (e.g. mesh_send_task) it stays in
|
|
986
|
+
// `generating` until the result arrives — but a generating coordinator queues
|
|
987
|
+
// incoming send_message calls into its adapter's pendingOutboundQueue, which is
|
|
988
|
+
// only flushed on the coordinator's OWN idle transition. That transition can't
|
|
989
|
+
// happen until it receives this very event → deadlock. We force-inject these so
|
|
990
|
+
// they bypass the busy send-guard and land in the PTY while generating.
|
|
991
|
+
export const MESH_FORCE_INJECT_EVENTS: ReadonlySet<string> = new Set([
|
|
992
|
+
'agent:generating_completed',
|
|
993
|
+
'agent:stopped',
|
|
994
|
+
'agent:waiting_approval',
|
|
995
|
+
'refine:completed',
|
|
996
|
+
'refine:failed',
|
|
997
|
+
'worktree_bootstrap_complete',
|
|
998
|
+
'worktree_bootstrap_failed',
|
|
999
|
+
]);
|
|
1000
|
+
|
|
1001
|
+
export function shouldForceInjectMeshEvent(eventName: unknown): boolean {
|
|
1002
|
+
return typeof eventName === 'string' && MESH_FORCE_INJECT_EVENTS.has(eventName);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
1006
|
+
meshId: string;
|
|
1007
|
+
sourceInstanceId?: string;
|
|
1008
|
+
nodeId?: string;
|
|
1009
|
+
nodeLabel: string;
|
|
1010
|
+
event: string;
|
|
1011
|
+
metadataEvent: Record<string, unknown>;
|
|
1012
|
+
}) {
|
|
1013
|
+
const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
1014
|
+
const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1015
|
+
|
|
1016
|
+
const sourceSession = args.sourceInstanceId
|
|
1017
|
+
? components.instanceManager.getInstance(args.sourceInstanceId)
|
|
1018
|
+
: undefined;
|
|
1019
|
+
const workerCoordinatorDaemonId = readNonEmptyString(
|
|
1020
|
+
(sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
|
|
1021
|
+
);
|
|
1022
|
+
|
|
1023
|
+
// R2: cloud P2P dashboard metadata sync. The cloud daemon used to do this from its own
|
|
1024
|
+
// relay listener; now the single core forwarder invokes the injected hook (no-op on
|
|
1025
|
+
// standalone) so the event path stays single-listener and the local code path is identical
|
|
1026
|
+
// across standalone and cloud.
|
|
1027
|
+
if (components.onMeshCoordinatorEventForwarded) {
|
|
1028
|
+
try {
|
|
1029
|
+
components.onMeshCoordinatorEventForwarded({
|
|
1030
|
+
event: args.event,
|
|
1031
|
+
meshId: args.meshId,
|
|
1032
|
+
nodeId: eventNodeId || undefined,
|
|
1033
|
+
...args.metadataEvent,
|
|
1034
|
+
});
|
|
1035
|
+
} catch { /* dashboard metadata sync is best-effort */ }
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
|
|
1039
|
+
event: args.event,
|
|
1040
|
+
meshId: args.meshId,
|
|
1041
|
+
metadataEvent: args.metadataEvent,
|
|
1042
|
+
sessionId: eventSessionId || undefined,
|
|
1043
|
+
nodeId: eventNodeId || undefined,
|
|
1044
|
+
});
|
|
1045
|
+
if (intentionalCleanupStop) {
|
|
1046
|
+
if (eventSessionId && eventNodeId) {
|
|
1047
|
+
try {
|
|
1048
|
+
MeshRuntimeStore.getInstance().deleteRemoteIdleSession(eventNodeId, eventSessionId);
|
|
1049
|
+
} catch { /* best-effort */ }
|
|
1050
|
+
}
|
|
1051
|
+
LOG.info('MeshEvents', `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || '(unknown session)'}`);
|
|
1052
|
+
return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
if (args.event === 'monitor:long_generating') {
|
|
1056
|
+
const reconciledCompletion = buildLongGeneratingCompletionReconciliation({
|
|
1057
|
+
meshId: args.meshId,
|
|
1058
|
+
nodeId: args.nodeId,
|
|
1059
|
+
nodeLabel: args.nodeLabel,
|
|
1060
|
+
metadataEvent: args.metadataEvent,
|
|
1061
|
+
sourceInstanceId: args.sourceInstanceId,
|
|
1062
|
+
});
|
|
1063
|
+
if (reconciledCompletion?.source === 'long_generating_reconciliation') {
|
|
1064
|
+
LOG.info('MeshEvents', `Reconciled long-generating monitor to completion for session ${eventSessionId || '(unknown session)'}`);
|
|
1065
|
+
return injectMeshSystemMessage(components, {
|
|
1066
|
+
...args,
|
|
1067
|
+
event: 'agent:generating_completed',
|
|
1068
|
+
metadataEvent: reconciledCompletion,
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
if (reconciledCompletion?.source === 'long_generating_terminal_ledger_suppression') {
|
|
1072
|
+
LOG.info('MeshEvents', `Suppressed long-generating monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
|
|
1073
|
+
return {
|
|
1074
|
+
success: true,
|
|
1075
|
+
forwarded: 0,
|
|
1076
|
+
suppressed: true,
|
|
1077
|
+
terminalLedgerEvidence: true,
|
|
1078
|
+
terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
|
|
1084
|
+
LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
|
|
1085
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
|
|
1089
|
+
if (args.event === 'agent:waiting_approval' && eventSessionId) {
|
|
1090
|
+
const duplicateApproval = isDuplicateMeshApprovalEvent({
|
|
1091
|
+
meshId: args.meshId,
|
|
1092
|
+
sessionId: eventSessionId,
|
|
1093
|
+
providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
|
|
1094
|
+
timestamp: eventTimestamp,
|
|
1095
|
+
modalMessage: readNonEmptyString(args.metadataEvent.modalMessage) || undefined,
|
|
1096
|
+
modalButtons: args.metadataEvent.modalButtons,
|
|
1097
|
+
});
|
|
1098
|
+
if (duplicateApproval) {
|
|
1099
|
+
LOG.info('MeshEvents', `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1100
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateApproval: true };
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
if (args.event === 'agent:generating_completed' && eventSessionId) {
|
|
1104
|
+
const terminal = findRecentTerminalLedgerEvidence({
|
|
1105
|
+
meshId: args.meshId,
|
|
1106
|
+
sessionId: eventSessionId,
|
|
1107
|
+
nodeId: eventNodeId || undefined,
|
|
1108
|
+
});
|
|
1109
|
+
if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
|
|
1110
|
+
const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
|
|
1111
|
+
if (!newDispatchAfterTerminal) {
|
|
1112
|
+
const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
|
|
1113
|
+
const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
|
|
1114
|
+
const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
|
|
1115
|
+
const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
|
|
1116
|
+
if (
|
|
1117
|
+
(terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
|
|
1118
|
+
|| (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
|
|
1119
|
+
|| args.metadataEvent.source === 'long_generating_reconciliation'
|
|
1120
|
+
) {
|
|
1121
|
+
LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1122
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
const duplicateCompletion = isDuplicateMeshCompletionEvent({
|
|
1127
|
+
meshId: args.meshId,
|
|
1128
|
+
event: args.event,
|
|
1129
|
+
sessionId: eventSessionId,
|
|
1130
|
+
providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
|
|
1131
|
+
providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
|
|
1132
|
+
timestamp: eventTimestamp,
|
|
1133
|
+
finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
|
|
1134
|
+
coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
|
|
1135
|
+
taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
|
|
1136
|
+
nodeId: eventNodeId || undefined,
|
|
1137
|
+
});
|
|
1138
|
+
if (duplicateCompletion) {
|
|
1139
|
+
LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1140
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
if (args.event === 'agent:stopped' && eventSessionId) {
|
|
1144
|
+
const duplicateStopped = isDuplicateMeshCompletionEvent({
|
|
1145
|
+
meshId: args.meshId,
|
|
1146
|
+
event: args.event,
|
|
1147
|
+
sessionId: eventSessionId,
|
|
1148
|
+
providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
|
|
1149
|
+
providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
|
|
1150
|
+
timestamp: eventTimestamp,
|
|
1151
|
+
finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
|
|
1152
|
+
coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
|
|
1153
|
+
taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
|
|
1154
|
+
nodeId: eventNodeId || undefined,
|
|
1155
|
+
});
|
|
1156
|
+
if (duplicateStopped) {
|
|
1157
|
+
LOG.info('MeshEvents', `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1158
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateStopped: true };
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
function markSessionTerminal(sessionId: string, outcome: 'completed' | 'failed', occurredAtMs?: number | null): { id?: string } | null {
|
|
1163
|
+
const task = updateSessionTaskStatus(args.meshId, sessionId, outcome, {
|
|
1164
|
+
occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : undefined,
|
|
1165
|
+
});
|
|
1166
|
+
updateDirectDispatchStatus(args.meshId, sessionId, outcome);
|
|
1167
|
+
markSessionDeliveriesTerminal(args.meshId, sessionId, outcome);
|
|
1168
|
+
setImmediate(() => cleanupTerminalDirectDispatches());
|
|
1169
|
+
return task ? { id: task.id } : null;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
let completedTaskForLedger: { id?: string } | null = null;
|
|
1173
|
+
if (args.event === 'agent:generating_completed') {
|
|
1174
|
+
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
1175
|
+
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1176
|
+
const providerType = readNonEmptyString(args.metadataEvent.providerType);
|
|
1177
|
+
|
|
1178
|
+
if (sessionId) {
|
|
1179
|
+
completedTaskForLedger = markSessionTerminal(sessionId, 'completed', eventTimestamp);
|
|
1180
|
+
if (nodeId && providerType) {
|
|
1181
|
+
runIdleMaintenanceThenAssignQueue(components, { meshId: args.meshId, nodeId, sessionId, providerType });
|
|
1182
|
+
}
|
|
1183
|
+
// M1-3: wake dependents of the completed task. The maintenance path above
|
|
1184
|
+
// only assigns to the completing session; dependents may be claimable by
|
|
1185
|
+
// other idle sessions, so run a full queue trigger when any are waiting.
|
|
1186
|
+
const completedTaskId = completedTaskForLedger?.id;
|
|
1187
|
+
if (completedTaskId && hasPendingDependents(args.meshId, completedTaskId)) {
|
|
1188
|
+
setImmediate(() => {
|
|
1189
|
+
triggerMeshQueue(components, args.meshId).catch((e: any) => {
|
|
1190
|
+
LOG.warn('MeshQueue', `Dependent wake after task ${completedTaskId} failed: ${e?.message || e}`);
|
|
1191
|
+
});
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
} else if (args.event === 'agent:ready') {
|
|
1196
|
+
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
1197
|
+
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1198
|
+
const providerType = readNonEmptyString(args.metadataEvent.providerType);
|
|
1199
|
+
const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
|
|
1200
|
+
const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
|
|
1201
|
+
const workerResult = readWorkerResultMetadata(args.metadataEvent);
|
|
1202
|
+
const hasCompletionEvidence = !!finalSummary || !!workerResult;
|
|
1203
|
+
if (sessionId && hasCompletionEvidence) {
|
|
1204
|
+
completedTaskForLedger = markSessionTerminal(sessionId, 'completed');
|
|
1205
|
+
if (completedTaskForLedger) {
|
|
1206
|
+
try {
|
|
1207
|
+
appendLedgerEntry(args.meshId, {
|
|
1208
|
+
kind: 'task_completed',
|
|
1209
|
+
nodeId: nodeId || undefined,
|
|
1210
|
+
sessionId,
|
|
1211
|
+
providerType: providerType || undefined,
|
|
1212
|
+
payload: {
|
|
1213
|
+
event: args.event,
|
|
1214
|
+
nodeLabel: args.nodeLabel,
|
|
1215
|
+
taskId: completedTaskForLedger.id,
|
|
1216
|
+
completedViaReady: true,
|
|
1217
|
+
providerSessionId,
|
|
1218
|
+
finalSummary,
|
|
1219
|
+
workerResult,
|
|
1220
|
+
evidence: buildTaskCompletionEvidence({
|
|
1221
|
+
event: 'agent:ready',
|
|
1222
|
+
nodeId,
|
|
1223
|
+
sessionId,
|
|
1224
|
+
providerType: providerType || undefined,
|
|
1225
|
+
providerSessionId,
|
|
1226
|
+
finalSummary,
|
|
1227
|
+
workerResult,
|
|
1228
|
+
}),
|
|
1229
|
+
},
|
|
1230
|
+
});
|
|
1231
|
+
} catch (e: any) {
|
|
1232
|
+
LOG.warn('MeshLedger', `Failed to record task_completed from ready: ${e?.message || e}`);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
if (sessionId && nodeId && providerType) {
|
|
1238
|
+
sweepExpiredRemoteIdleSessions();
|
|
1239
|
+
try {
|
|
1240
|
+
MeshRuntimeStore.getInstance().setRemoteIdleSession(nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
|
|
1241
|
+
} catch { /* best-effort */ }
|
|
1242
|
+
setImmediate(() => {
|
|
1243
|
+
maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
|
|
1244
|
+
.finally(() => {
|
|
1245
|
+
try {
|
|
1246
|
+
const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
|
|
1247
|
+
if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
|
|
1248
|
+
} catch (e: any) {
|
|
1249
|
+
LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${nodeId}: ${e?.message || e}`);
|
|
1250
|
+
}
|
|
1251
|
+
});
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
} else if (args.event === 'agent:generating_started') {
|
|
1255
|
+
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
1256
|
+
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1257
|
+
if (sessionId && nodeId) {
|
|
1258
|
+
try {
|
|
1259
|
+
MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
|
|
1260
|
+
} catch { /* best-effort */ }
|
|
1261
|
+
}
|
|
1262
|
+
if (sessionId) {
|
|
1263
|
+
updateDirectDispatchStatus(args.meshId, sessionId, 'acked');
|
|
1264
|
+
const activeDeliveries = ((): { id: string }[] => {
|
|
1265
|
+
try { return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId); }
|
|
1266
|
+
catch { return []; }
|
|
1267
|
+
})();
|
|
1268
|
+
for (const d of activeDeliveries) {
|
|
1269
|
+
updateSessionDeliveryStatus(d.id, 'acked');
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
} else if (args.event === 'agent:stopped') {
|
|
1273
|
+
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
1274
|
+
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1275
|
+
if (sessionId && nodeId) {
|
|
1276
|
+
try {
|
|
1277
|
+
MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
|
|
1278
|
+
} catch { /* best-effort */ }
|
|
1279
|
+
}
|
|
1280
|
+
if (sessionId) {
|
|
1281
|
+
completedTaskForLedger = markSessionTerminal(sessionId, 'failed');
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
const ledgerKind = EVENT_TO_LEDGER_KIND[args.event];
|
|
1286
|
+
if (ledgerKind) {
|
|
1287
|
+
try {
|
|
1288
|
+
const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
|
|
1289
|
+
const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
|
|
1290
|
+
const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
|
|
1291
|
+
const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
|
|
1292
|
+
const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
|
|
1293
|
+
const workerResult = readWorkerResultMetadata(args.metadataEvent);
|
|
1294
|
+
const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
|
|
1295
|
+
? buildTaskCompletionEvidence({
|
|
1296
|
+
event: 'agent:generating_completed',
|
|
1297
|
+
nodeId: ledgerNodeId,
|
|
1298
|
+
sessionId: ledgerSessionId,
|
|
1299
|
+
providerType: ledgerProviderType,
|
|
1300
|
+
providerSessionId,
|
|
1301
|
+
finalSummary,
|
|
1302
|
+
workerResult,
|
|
1303
|
+
})
|
|
1304
|
+
: undefined;
|
|
1305
|
+
appendLedgerEntry(args.meshId, {
|
|
1306
|
+
kind: ledgerKind,
|
|
1307
|
+
nodeId: ledgerNodeId,
|
|
1308
|
+
sessionId: ledgerSessionId,
|
|
1309
|
+
providerType: ledgerProviderType,
|
|
1310
|
+
payload: {
|
|
1311
|
+
event: args.event,
|
|
1312
|
+
nodeLabel: args.nodeLabel,
|
|
1313
|
+
taskId: completedTaskForLedger?.id || undefined,
|
|
1314
|
+
providerSessionId,
|
|
1315
|
+
finalSummary,
|
|
1316
|
+
workerResult,
|
|
1317
|
+
completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
|
|
1318
|
+
? args.metadataEvent.completionDiagnostic
|
|
1319
|
+
: undefined,
|
|
1320
|
+
evidence: completionEvidence,
|
|
1321
|
+
// B2: evidenceLevel lets coordinator know when completion evidence is insufficient.
|
|
1322
|
+
...(completionEvidence
|
|
1323
|
+
? completionEvidence.workerResult.source === 'default'
|
|
1324
|
+
? { evidenceLevel: 'insufficient', reviewRecommended: true }
|
|
1325
|
+
: { evidenceLevel: 'sufficient' }
|
|
1326
|
+
: {}),
|
|
1327
|
+
},
|
|
1328
|
+
});
|
|
1329
|
+
} catch (e: any) {
|
|
1330
|
+
LOG.warn('MeshLedger', `Failed to record ${ledgerKind}: ${e?.message || e}`);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
let recoveryContext: SessionRecoveryContext | null = null;
|
|
1335
|
+
if (args.event === 'agent:stopped') {
|
|
1336
|
+
try {
|
|
1337
|
+
const mesh = getMesh(args.meshId);
|
|
1338
|
+
const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
|
|
1339
|
+
|
|
1340
|
+
recoveryContext = getSessionRecoveryContext(args.meshId, {
|
|
1341
|
+
sessionId: resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined,
|
|
1342
|
+
nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
|
|
1343
|
+
maxRetries,
|
|
1344
|
+
});
|
|
1345
|
+
recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
|
|
1346
|
+
|
|
1347
|
+
if (recoveryContext.retryRecommended && recoveryContext.consecutiveNodeFailures > 0) {
|
|
1348
|
+
appendLedgerEntry(args.meshId, {
|
|
1349
|
+
kind: 'recovery_attempted',
|
|
1350
|
+
nodeId: recoveryContext.failedNodeId || undefined,
|
|
1351
|
+
sessionId: recoveryContext.failedSessionId || undefined,
|
|
1352
|
+
providerType: recoveryContext.failedProviderType || undefined,
|
|
1353
|
+
payload: {
|
|
1354
|
+
consecutiveFailures: recoveryContext.consecutiveNodeFailures,
|
|
1355
|
+
taskAttemptCount: recoveryContext.taskAttemptCount,
|
|
1356
|
+
retryRecommended: recoveryContext.retryRecommended,
|
|
1357
|
+
advice: recoveryContext.advice,
|
|
1358
|
+
},
|
|
1359
|
+
});
|
|
1360
|
+
|
|
1361
|
+
if (recoveryContext.lastTaskMessage && recoveryContext.failedNodeId && recoveryContext.failedProviderType) {
|
|
1362
|
+
const autoNodeId = recoveryContext.failedNodeId;
|
|
1363
|
+
try {
|
|
1364
|
+
const task = enqueueTask(args.meshId, recoveryContext.lastTaskMessage, {
|
|
1365
|
+
targetNodeId: autoNodeId
|
|
1366
|
+
});
|
|
1367
|
+
LOG.info('MeshRecovery', `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
|
|
1368
|
+
|
|
1369
|
+
const node = mesh?.nodes.find((n: any) => n.id === autoNodeId);
|
|
1370
|
+
if (node) {
|
|
1371
|
+
components.cliManager.handleCliCommand('launch_cli', {
|
|
1372
|
+
cliType: recoveryContext.failedProviderType,
|
|
1373
|
+
dir: node.workspace,
|
|
1374
|
+
settings: {
|
|
1375
|
+
role: 'worker',
|
|
1376
|
+
meshNodeFor: args.meshId,
|
|
1377
|
+
meshNodeId: node.id,
|
|
1378
|
+
spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
|
|
1379
|
+
// Coordinator-dispatched recovery relaunch: same auto-approve
|
|
1380
|
+
// policy as the primary worker launch path.
|
|
1381
|
+
autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
|
|
1382
|
+
launchedByCoordinator: true,
|
|
1383
|
+
}
|
|
1384
|
+
}).catch((e: any) => LOG.error('MeshRecovery', `Failed to auto-relaunch session for ${node.id}: ${e?.message}`));
|
|
1385
|
+
}
|
|
1386
|
+
} catch (e: any) {
|
|
1387
|
+
LOG.warn('MeshRecovery', `Failed to execute auto-recovery: ${e?.message}`);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
LOG.info('MeshRecovery', `Recovery context for ${args.nodeLabel}: ${recoveryContext.advice}`);
|
|
1393
|
+
} catch (e: any) {
|
|
1394
|
+
LOG.warn('MeshRecovery', `Failed to build recovery context: ${e?.message || e}`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
const messageText = buildMeshSystemMessage({
|
|
1399
|
+
event: args.event,
|
|
1400
|
+
nodeLabel: args.nodeLabel,
|
|
1401
|
+
metadataEvent: args.metadataEvent,
|
|
1402
|
+
recoveryContext,
|
|
1403
|
+
});
|
|
1404
|
+
if (!messageText) return { success: false, error: 'unsupported mesh event' };
|
|
1405
|
+
|
|
1406
|
+
// ── Queue-only delivery (single-model: queue + periodic poll) ──────────────
|
|
1407
|
+
// Every mesh coordinator event — terminal or not, local-coordinator or
|
|
1408
|
+
// remote — is persisted to the pending-events queue (SQLite + JSONL) and
|
|
1409
|
+
// NOTHING is pushed here. The old spontaneous-forward paths were removed:
|
|
1410
|
+
// - F1 remote P2P `mesh_forward_event` dispatch (network/stamp-dependent,
|
|
1411
|
+
// silently dropped on P2P failure or missing meshCoordinatorDaemonId)
|
|
1412
|
+
// - F3 live-CLI PTY `send_message` fire-and-forget inject (silently
|
|
1413
|
+
// dropped when the coordinator was generating)
|
|
1414
|
+
// Delivery to a live CLI coordinator now happens via setupMeshReconcileLoop,
|
|
1415
|
+
// which drains this queue on a fixed interval and injects into the coordinator
|
|
1416
|
+
// only when it is idle. A pure stdio MCP (LLM) coordinator — which has no live
|
|
1417
|
+
// CLI session to inject into — drains the queue itself when it calls a mesh
|
|
1418
|
+
// tool (mesh_status / mesh_read_chat). Either way the queue is the single
|
|
1419
|
+
// source of truth and the only thing this function writes to.
|
|
1420
|
+
//
|
|
1421
|
+
// targetCoordinatorDaemonId scopes the event to a specific coordinator daemon
|
|
1422
|
+
// (unicast) when the worker carries one, so the reconcile loop on the right
|
|
1423
|
+
// daemon drains it and other daemons skip it. Absent → broadcast/backfill.
|
|
1424
|
+
const pendingEvent = {
|
|
1425
|
+
event: args.event,
|
|
1426
|
+
meshId: args.meshId,
|
|
1427
|
+
nodeLabel: args.nodeLabel,
|
|
1428
|
+
nodeId: args.nodeId || undefined,
|
|
1429
|
+
workspace: readNonEmptyString(args.metadataEvent.workspace),
|
|
1430
|
+
metadataEvent: {
|
|
1431
|
+
...args.metadataEvent,
|
|
1432
|
+
...(recoveryContext ? { recoveryContext } : {}),
|
|
1433
|
+
},
|
|
1434
|
+
coordinatorMessage: messageText,
|
|
1435
|
+
queuedAt: Date.now(),
|
|
1436
|
+
...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
|
|
1437
|
+
};
|
|
1438
|
+
if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
|
|
1439
|
+
LOG.info('MeshEvents', `Queued ${args.event} for coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''})`);
|
|
1440
|
+
}
|
|
1441
|
+
return { success: true, forwarded: 0 };
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
export function handleMeshForwardEvent(components: DaemonComponents, payload: Record<string, unknown>) {
|
|
1445
|
+
const eventName = readNonEmptyString(payload.event);
|
|
1446
|
+
if (!isMeshCoordinatorEvent(eventName)) {
|
|
1447
|
+
return { success: false, error: 'unsupported mesh event' };
|
|
1448
|
+
}
|
|
1449
|
+
const meshId = readNonEmptyString(payload.meshId);
|
|
1450
|
+
if (!meshId) return { success: false, error: 'meshId required' };
|
|
1451
|
+
|
|
1452
|
+
const nodeId = readNonEmptyString(payload.nodeId);
|
|
1453
|
+
const workspace = readNonEmptyString(payload.workspace);
|
|
1454
|
+
const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : 'Remote agent';
|
|
1455
|
+
const relayModalMessage = readNonEmptyString(payload.modalMessage);
|
|
1456
|
+
const relayModalButtons = Array.isArray(payload.modalButtons)
|
|
1457
|
+
? (payload.modalButtons as unknown[]).filter((b): b is string => typeof b === 'string' && b.trim().length > 0)
|
|
1458
|
+
: null;
|
|
1459
|
+
|
|
1460
|
+
return injectMeshSystemMessage(components, {
|
|
1461
|
+
meshId,
|
|
1462
|
+
nodeId,
|
|
1463
|
+
nodeLabel,
|
|
1464
|
+
event: eventName,
|
|
1465
|
+
metadataEvent: {
|
|
1466
|
+
targetSessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.instanceId),
|
|
1467
|
+
providerType: readNonEmptyString(payload.providerType),
|
|
1468
|
+
providerSessionId: readNonEmptyString(payload.providerSessionId),
|
|
1469
|
+
finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
|
|
1470
|
+
jobId: readNonEmptyString(payload.jobId),
|
|
1471
|
+
interactionId: readNonEmptyString(payload.interactionId),
|
|
1472
|
+
status: readNonEmptyString(payload.status),
|
|
1473
|
+
targetDaemonId: readNonEmptyString(payload.targetDaemonId),
|
|
1474
|
+
startedAt: readNonEmptyString(payload.startedAt),
|
|
1475
|
+
completedAt: readNonEmptyString(payload.completedAt),
|
|
1476
|
+
retryOfJobId: readNonEmptyString(payload.retryOfJobId),
|
|
1477
|
+
...(relayModalMessage ? { modalMessage: relayModalMessage } : {}),
|
|
1478
|
+
...(relayModalButtons && relayModalButtons.length > 0 ? { modalButtons: relayModalButtons } : {}),
|
|
1479
|
+
...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
|
|
1480
|
+
...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
|
|
1481
|
+
...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
|
|
1482
|
+
...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
|
|
1483
|
+
...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
|
|
1484
|
+
...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
|
|
1485
|
+
intentional: payload.intentional === true,
|
|
1486
|
+
intentionalStop: payload.intentionalStop === true,
|
|
1487
|
+
operatorCleanup: payload.operatorCleanup === true,
|
|
1488
|
+
reason: readNonEmptyString(payload.reason),
|
|
1489
|
+
stopReason: readNonEmptyString(payload.stopReason),
|
|
1490
|
+
cleanupReason: readNonEmptyString(payload.cleanupReason),
|
|
1491
|
+
source: readNonEmptyString(payload.source),
|
|
1492
|
+
},
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
export function setupMeshEventForwarding(components: DaemonComponents) {
|
|
1497
|
+
components.instanceManager.onEvent((event) => {
|
|
1498
|
+
// --- Coordinator idle auto-flush (fast path) ---
|
|
1499
|
+
// When a coordinator session becomes idle, immediately flush any pending
|
|
1500
|
+
// coordinator events that accumulated while it was generating, rather than
|
|
1501
|
+
// waiting up to one reconcile interval for setupMeshReconcileLoop to do it.
|
|
1502
|
+
// Both paths drain the SAME queue via drainPendingMeshCoordinatorEvents,
|
|
1503
|
+
// whose SQLite drained=1 marking is atomic — whichever fires first consumes
|
|
1504
|
+
// the events and the other gets nothing, so there is no double-delivery.
|
|
1505
|
+
// This runs before the delegate routing below so that coordinator-own idle
|
|
1506
|
+
// transitions are handled first.
|
|
1507
|
+
// Exception: a coordinator that is itself a direct-dispatch target still needs
|
|
1508
|
+
// to go through delegate routing so that the dispatching coordinator receives a
|
|
1509
|
+
// pendingCoordinatorEvents entry for the completion.
|
|
1510
|
+
if (event.event === 'agent:ready' || event.event === 'agent:generating_completed') {
|
|
1511
|
+
const flushInstanceId = readNonEmptyString(event.instanceId);
|
|
1512
|
+
if (flushInstanceId) {
|
|
1513
|
+
const flushSource = components.instanceManager.getInstance(flushInstanceId);
|
|
1514
|
+
if (flushSource && flushSource.category === 'cli') {
|
|
1515
|
+
const flushState = flushSource.getState();
|
|
1516
|
+
const flushSettings = flushState.settings && typeof flushState.settings === 'object' ? flushState.settings as Record<string, unknown> : {};
|
|
1517
|
+
const coordinatorMeshId = readNonEmptyString(flushSettings.meshCoordinatorFor);
|
|
1518
|
+
if (coordinatorMeshId) {
|
|
1519
|
+
const status = readNonEmptyString(flushState.status).toLowerCase();
|
|
1520
|
+
if (status === 'idle') {
|
|
1521
|
+
try {
|
|
1522
|
+
// Drain with the daemon's full coordinator-id set (status id + machineId).
|
|
1523
|
+
// The MCP layer stamps the prefixed status id (`standalone_<machineId>` /
|
|
1524
|
+
// `daemon_<machineId>`) as the worker's meshCoordinatorDaemonId; draining
|
|
1525
|
+
// with bare machineId alone would miss those unicast events. Mirrors
|
|
1526
|
+
// resolveCoordinatorDaemonIds in mesh-reconcile-loop.
|
|
1527
|
+
const drainDaemonIds = resolveCoordinatorDrainDaemonIds(components);
|
|
1528
|
+
const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
|
|
1529
|
+
if (pendingEvents.length > 0) {
|
|
1530
|
+
LOG.info('MeshEvents', `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
|
|
1531
|
+
for (const pending of pendingEvents) {
|
|
1532
|
+
if (!pending.coordinatorMessage) continue;
|
|
1533
|
+
const forcePending = shouldForceInjectMeshEvent(pending.event);
|
|
1534
|
+
flushSource.onEvent('send_message', {
|
|
1535
|
+
input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
|
|
1536
|
+
...(forcePending ? { force: true } : {}),
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
} catch (e: any) {
|
|
1541
|
+
LOG.warn('MeshEvents', `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
// Skip delegate routing unless this coordinator session is itself
|
|
1545
|
+
// a direct-dispatch target — in that case fall through so the
|
|
1546
|
+
// dispatching coordinator gets a pendingCoordinatorEvents entry.
|
|
1547
|
+
let hasDirectDispatch = false;
|
|
1548
|
+
try {
|
|
1549
|
+
hasDirectDispatch =
|
|
1550
|
+
getActiveDirectDispatches(coordinatorMeshId).some(d => d.sessionId === flushInstanceId)
|
|
1551
|
+
|| hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
|
|
1552
|
+
} catch { /* best-effort */ }
|
|
1553
|
+
if (!hasDirectDispatch) return;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
// --- Delegate event routing ---
|
|
1560
|
+
if (!isMeshCoordinatorEvent(event.event)) return;
|
|
1561
|
+
|
|
1562
|
+
const instanceId = readNonEmptyString(event.instanceId);
|
|
1563
|
+
if (!instanceId) return;
|
|
1564
|
+
|
|
1565
|
+
// R1: all session→node→mesh→coordinator interpretation is folded into the single
|
|
1566
|
+
// resolveWorkerDelegateRouting() resolver. No stamp (meshNodeFor / meshNodeId /
|
|
1567
|
+
// meshCoordinatorDaemonId / meshCoordinatorNodeId / launchedByCoordinator) is read
|
|
1568
|
+
// here to make a routing decision — the resolver is the one authority, and the
|
|
1569
|
+
// forwarder consumes its typed result only.
|
|
1570
|
+
const routing = resolveWorkerDelegateRouting(components, instanceId, {
|
|
1571
|
+
getMeshById: (meshId) => getMeshWithCache(components, meshId),
|
|
1572
|
+
getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace),
|
|
1573
|
+
});
|
|
1574
|
+
if (!routing.isDelegate) {
|
|
1575
|
+
// R4: a worker that presented a valid envelope but resolved to no mesh used to be
|
|
1576
|
+
// dropped silently. Leave a fail-loud diagnostic so the missing completion is
|
|
1577
|
+
// traceable. Benign non-delegate rejections (not_cli / no_workspace / etc.) are
|
|
1578
|
+
// no-ops inside recordUnroutableDelegateEvent.
|
|
1579
|
+
recordUnroutableDelegateEvent(routing, event.event);
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
injectMeshSystemMessage(components, {
|
|
1584
|
+
meshId: routing.meshId,
|
|
1585
|
+
sourceInstanceId: instanceId,
|
|
1586
|
+
nodeId: routing.nodeId,
|
|
1587
|
+
nodeLabel: routing.nodeLabel,
|
|
1588
|
+
event: event.event,
|
|
1589
|
+
metadataEvent: event,
|
|
1590
|
+
});
|
|
1591
|
+
});
|
|
1592
|
+
}
|