@adhdev/daemon-core 0.9.82-rc.15 → 0.9.82-rc.151
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/process-hardening.d.ts +50 -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 +5 -1
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +104 -63
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +27 -0
- package/dist/commands/handler.d.ts +66 -0
- package/dist/commands/router.d.ts +22 -0
- package/dist/config/chat-history.d.ts +5 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +68 -1
- package/dist/git/git-commands.d.ts +5 -1
- package/dist/index.d.ts +20 -6
- package/dist/index.js +13153 -3031
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13099 -3023
- 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/beads-db.d.ts +72 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-registry.d.ts +25 -0
- package/dist/mesh/mesh-active-work.d.ts +90 -0
- package/dist/mesh/mesh-events.d.ts +77 -5
- package/dist/mesh/mesh-fast-forward.d.ts +39 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-ledger.d.ts +58 -1
- package/dist/mesh/mesh-refine-status.d.ts +26 -0
- package/dist/mesh/mesh-work-queue.d.ts +44 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +193 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +113 -0
- package/dist/providers/approval-utils.d.ts +9 -0
- package/dist/providers/cli-provider-instance.d.ts +6 -1
- package/dist/providers/contracts.d.ts +50 -5
- 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/index.d.ts +11 -0
- package/dist/providers/provider-loader.d.ts +19 -1
- 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 +64 -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 +169 -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/transcript-v2.d.ts +176 -0
- package/dist/repo-mesh-types.d.ts +67 -0
- package/dist/shared-types.d.ts +12 -0
- 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 +6 -2
- package/src/boot/daemon-lifecycle.ts +17 -10
- package/src/boot/process-hardening.ts +89 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +14 -1
- package/src/cli-adapter-types.d.ts +1 -0
- package/src/cli-adapter-types.ts +3 -1
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1086 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +664 -1137
- 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 +57 -11
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +17 -1
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +8 -1
- package/src/commands/chat-commands.ts +1451 -52
- package/src/commands/cli-manager.ts +184 -3
- package/src/commands/handler.ts +547 -2
- package/src/commands/mesh-coordinator.ts +13 -143
- package/src/commands/router.ts +3273 -428
- package/src/config/chat-history.ts +79 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +249 -2
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/detection/ide-detector.ts +26 -16
- package/src/git/git-commands.ts +17 -5
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +72 -5
- 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/beads-db.ts +479 -0
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +40 -22
- package/src/mesh/coordinator-registry.ts +75 -0
- package/src/mesh/mesh-active-work.ts +437 -0
- package/src/mesh/mesh-events.ts +820 -61
- package/src/mesh/mesh-fast-forward.ts +430 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-ledger.ts +457 -104
- package/src/mesh/mesh-refine-status.ts +144 -0
- package/src/mesh/mesh-work-queue.ts +216 -158
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +366 -0
- package/src/mesh/worktree-bootstrap-config.ts +247 -0
- package/src/providers/approval-utils.ts +39 -5
- package/src/providers/chat-message-normalization.ts +4 -11
- package/src/providers/cli-provider-instance.ts +380 -44
- package/src/providers/contracts.ts +52 -5
- package/src/providers/ide-provider-instance.ts +17 -3
- 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 +419 -0
- package/src/providers/native-history/index.ts +23 -0
- package/src/providers/provider-loader.ts +294 -28
- package/src/providers/provider-schema.ts +31 -13
- 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 +245 -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 +444 -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 +119 -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 +210 -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/transcript-v2.ts +567 -0
- package/src/providers/version-archive.ts +38 -20
- package/src/repo-mesh-types.ts +77 -0
- package/src/shared-types.ts +9 -0
- package/src/status/builders.ts +23 -6
- package/src/status/reporter.ts +15 -0
- package/src/status/snapshot.ts +35 -11
- package/src/system/host-memory.ts +29 -12
- package/src/types.ts +5 -0
package/src/mesh/mesh-events.ts
CHANGED
|
@@ -1,31 +1,69 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
1
3
|
import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
|
|
2
4
|
import { loadConfig } from '../config/config.js';
|
|
3
5
|
import { getMesh, getMeshByRepo } from '../config/mesh-config.js';
|
|
4
6
|
import { detectCLI } from '../detection/cli-detector.js';
|
|
5
7
|
import { LOG } from '../logging/logger.js';
|
|
6
|
-
import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
|
|
8
|
+
import { appendLedgerEntry, buildTaskCompletionEvidence, getLedgerDir, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
|
|
7
9
|
import type { MeshLedgerKind, SessionRecoveryContext } from './mesh-ledger.js';
|
|
8
|
-
import { claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch } from './mesh-work-queue.js';
|
|
10
|
+
import { claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches } from './mesh-work-queue.js';
|
|
11
|
+
import { BeadsDB } from './beads-db.js';
|
|
9
12
|
|
|
10
13
|
// ---------------------------------------------------------------------------
|
|
11
14
|
// Remote Node Idle Session Tracking
|
|
12
15
|
// ---------------------------------------------------------------------------
|
|
13
|
-
// Tracks remote sessions that emitted 'agent:ready' so triggerMeshQueue
|
|
14
|
-
// can assign tasks to them.
|
|
16
|
+
// Tracks remote sessions that emitted 'agent:ready' so triggerMeshQueue
|
|
17
|
+
// can assign tasks to them. Each entry carries an expiresAt timestamp;
|
|
18
|
+
// entries are swept on insertion to prevent unbounded growth.
|
|
15
19
|
// ---------------------------------------------------------------------------
|
|
16
20
|
interface RemoteIdleSession {
|
|
17
21
|
nodeId: string;
|
|
18
22
|
sessionId: string;
|
|
19
23
|
providerType: string;
|
|
24
|
+
expiresAt: number;
|
|
20
25
|
}
|
|
26
|
+
const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
21
27
|
const remoteIdleSessions = new Map<string, RemoteIdleSession>(); // key: `${nodeId}:${sessionId}`
|
|
22
28
|
|
|
23
29
|
// ---------------------------------------------------------------------------
|
|
24
|
-
//
|
|
30
|
+
// Workspace-to-mesh lookup cache
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// getMeshByRepo is called on every coordinator event for sessions without
|
|
33
|
+
// meshNodeFor. Cache results for 5 seconds to avoid repeated config reads.
|
|
34
|
+
const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
|
|
35
|
+
const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
|
|
36
|
+
|
|
37
|
+
function getCachedMeshByWorkspace(workspace: string): any {
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
const cached = meshByWorkspaceCache.get(workspace);
|
|
40
|
+
if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
|
|
41
|
+
const mesh = getMeshByRepo(workspace);
|
|
42
|
+
meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
|
|
43
|
+
return mesh;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function readWorkerResultMetadata(event: Record<string, unknown>): Record<string, unknown> | undefined {
|
|
47
|
+
return readRecord(event.workerResult) || readRecord(event.meshWorkerResult) || readRecord(event.structuredResult);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function sweepExpiredRemoteIdleSessions(): void {
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
for (const [key, session] of remoteIdleSessions) {
|
|
53
|
+
if (session.expiresAt <= now) remoteIdleSessions.delete(key);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
// MCP coordinator pending-event queue — FILE-BASED PERSISTENCE
|
|
25
59
|
// ---------------------------------------------------------------------------
|
|
26
60
|
// When a mesh event fires but no CLI coordinator session is registered (e.g.
|
|
27
|
-
// the coordinator is Claude Code running via MCP), we
|
|
28
|
-
//
|
|
61
|
+
// the coordinator is Claude Code running via MCP), we persist the event to a
|
|
62
|
+
// per-mesh JSONL file so it survives daemon restarts. The 50-entry hard cap
|
|
63
|
+
// is removed; the file is drained atomically on each get_pending_mesh_events
|
|
64
|
+
// call and limited to 100 KB to prevent runaway growth.
|
|
65
|
+
//
|
|
66
|
+
// File: <ledgerDir>/<meshId>.pending-events.jsonl
|
|
29
67
|
// ---------------------------------------------------------------------------
|
|
30
68
|
|
|
31
69
|
export interface PendingMeshCoordinatorEvent {
|
|
@@ -35,39 +73,272 @@ export interface PendingMeshCoordinatorEvent {
|
|
|
35
73
|
nodeId?: string;
|
|
36
74
|
workspace?: string;
|
|
37
75
|
metadataEvent: Record<string, unknown>;
|
|
76
|
+
coordinatorMessage?: string;
|
|
38
77
|
queuedAt: number;
|
|
78
|
+
/**
|
|
79
|
+
* When set, this event is intended for a specific coordinator daemon.
|
|
80
|
+
* Coordinators on other daemons should ignore it during drain.
|
|
81
|
+
* Absent on legacy events — treated as broadcast to any coordinator.
|
|
82
|
+
*/
|
|
83
|
+
targetCoordinatorDaemonId?: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const REFINE_TERMINAL_EVENTS = new Set(['refine:completed', 'refine:failed']);
|
|
87
|
+
|
|
88
|
+
function readRefineJobId(event: { metadataEvent?: Record<string, unknown> } | Record<string, unknown>): string {
|
|
89
|
+
const metadata = readRecord((event as any).metadataEvent) || event as Record<string, unknown>;
|
|
90
|
+
const result = readRecord(metadata.result);
|
|
91
|
+
const refineJob = readRecord(result?.refineJob);
|
|
92
|
+
return readNonEmptyString(metadata.jobId) || readNonEmptyString(refineJob?.jobId);
|
|
39
93
|
}
|
|
40
94
|
|
|
41
|
-
|
|
42
|
-
const
|
|
95
|
+
function buildRefineTerminalEventFingerprint(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): string {
|
|
96
|
+
const jobId = readRefineJobId({ metadataEvent });
|
|
97
|
+
return jobId && REFINE_TERMINAL_EVENTS.has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function hasPendingRefineTerminalEventDuplicate(event: PendingMeshCoordinatorEvent): boolean {
|
|
101
|
+
if (!REFINE_TERMINAL_EVENTS.has(event.event)) return false;
|
|
102
|
+
const jobId = readRefineJobId(event);
|
|
103
|
+
if (!jobId) return false;
|
|
104
|
+
return readPendingMeshCoordinatorEventsFromDisk(event.meshId).some((pending) =>
|
|
105
|
+
pending.event === event.event && readRefineJobId(pending) === jobId,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function buildPendingEventFingerprint(event: PendingMeshCoordinatorEvent): string {
|
|
110
|
+
const metadata = readRecord(event.metadataEvent) || {};
|
|
111
|
+
const sessionId = resolveEventSessionId(metadata);
|
|
112
|
+
const providerSessionId = readNonEmptyString(metadata.providerSessionId);
|
|
113
|
+
const taskId = readNonEmptyString(metadata.taskId) || readNonEmptyString(readRecord(metadata.payload)?.taskId);
|
|
114
|
+
const jobId = readRefineJobId(event);
|
|
115
|
+
const timestamp = metadata.timestamp !== undefined && metadata.timestamp !== null ? String(metadata.timestamp) : '';
|
|
116
|
+
return [
|
|
117
|
+
event.meshId,
|
|
118
|
+
event.event,
|
|
119
|
+
event.nodeId || '',
|
|
120
|
+
sessionId || '',
|
|
121
|
+
providerSessionId || '',
|
|
122
|
+
taskId || '',
|
|
123
|
+
jobId || '',
|
|
124
|
+
timestamp || '',
|
|
125
|
+
].join('::');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function hasPendingCoordinatorEventDuplicate(event: PendingMeshCoordinatorEvent): boolean {
|
|
129
|
+
const fingerprint = buildPendingEventFingerprint(event);
|
|
130
|
+
if (!fingerprint.trim()) return false;
|
|
131
|
+
return readPendingMeshCoordinatorEventsFromDisk(event.meshId).some((pending) => buildPendingEventFingerprint(pending) === fingerprint);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function getPendingEventsPath(meshId: string, coordinatorDaemonId?: string): string {
|
|
135
|
+
const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
136
|
+
if (coordinatorDaemonId) {
|
|
137
|
+
const safeDaemon = coordinatorDaemonId.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
138
|
+
return join(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
|
|
139
|
+
}
|
|
140
|
+
return join(getLedgerDir(), `${safe}.pending-events.jsonl`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function readPendingMeshCoordinatorEventsFromDisk(meshId?: string, coordinatorDaemonId?: string): PendingMeshCoordinatorEvent[] {
|
|
144
|
+
if (!meshId) return [];
|
|
145
|
+
// Read coordinator-scoped file first; fall back to legacy shared file.
|
|
146
|
+
const paths = coordinatorDaemonId
|
|
147
|
+
? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)]
|
|
148
|
+
: [getPendingEventsPath(meshId)];
|
|
149
|
+
const events: PendingMeshCoordinatorEvent[] = [];
|
|
150
|
+
for (const path of paths) {
|
|
151
|
+
if (!existsSync(path)) continue;
|
|
152
|
+
try {
|
|
153
|
+
const raw = readFileSync(path, 'utf-8');
|
|
154
|
+
const parsed = raw.split('\n').filter(Boolean).flatMap(line => {
|
|
155
|
+
try { return [JSON.parse(line) as PendingMeshCoordinatorEvent]; } catch { return []; }
|
|
156
|
+
});
|
|
157
|
+
// If reading the shared file, filter to events that target this coordinator or are unscoped.
|
|
158
|
+
const filtered = (coordinatorDaemonId && path === getPendingEventsPath(meshId))
|
|
159
|
+
? parsed.filter(e => !e.targetCoordinatorDaemonId || e.targetCoordinatorDaemonId === coordinatorDaemonId)
|
|
160
|
+
: parsed;
|
|
161
|
+
events.push(...filtered);
|
|
162
|
+
} catch { /* skip unreadable files */ }
|
|
163
|
+
}
|
|
164
|
+
return events;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function refineTerminalEventFromLedger(meshId: string, pending: readonly PendingMeshCoordinatorEvent[]): PendingMeshCoordinatorEvent[] {
|
|
168
|
+
const acceptedJobIds = new Set(
|
|
169
|
+
pending
|
|
170
|
+
.filter(event => event.event === 'refine:accepted')
|
|
171
|
+
.map(event => readRefineJobId(event))
|
|
172
|
+
.filter(Boolean),
|
|
173
|
+
);
|
|
174
|
+
if (acceptedJobIds.size === 0) return [];
|
|
175
|
+
const existingTerminalJobIds = new Set(
|
|
176
|
+
pending
|
|
177
|
+
.filter(event => REFINE_TERMINAL_EVENTS.has(event.event))
|
|
178
|
+
.map(event => `${event.event}:${readRefineJobId(event)}`)
|
|
179
|
+
.filter(value => !value.endsWith(':')),
|
|
180
|
+
);
|
|
181
|
+
const backfilled: PendingMeshCoordinatorEvent[] = [];
|
|
182
|
+
const entries = readLedgerEntries(meshId, { tail: 200 });
|
|
183
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
184
|
+
const entry = entries[i];
|
|
185
|
+
if (entry.kind !== 'task_completed' && entry.kind !== 'task_failed') continue;
|
|
186
|
+
const payload = readRecord(entry.payload);
|
|
187
|
+
if (payload?.source !== 'refine_mesh_node_async_job') continue;
|
|
188
|
+
const refineJob = readRecord(payload.refineJob);
|
|
189
|
+
const jobId = readNonEmptyString(refineJob?.jobId);
|
|
190
|
+
if (!jobId || !acceptedJobIds.has(jobId)) continue;
|
|
191
|
+
const eventName = entry.kind === 'task_completed' ? 'refine:completed' : 'refine:failed';
|
|
192
|
+
if (existingTerminalJobIds.has(`${eventName}:${jobId}`)) continue;
|
|
193
|
+
existingTerminalJobIds.add(`${eventName}:${jobId}`);
|
|
194
|
+
const result = readRecord(payload.result);
|
|
195
|
+
const metadataEvent = {
|
|
196
|
+
source: 'refine_mesh_node_async_job',
|
|
197
|
+
jobId,
|
|
198
|
+
interactionId: readNonEmptyString(refineJob?.interactionId),
|
|
199
|
+
meshId,
|
|
200
|
+
nodeId: readNonEmptyString(refineJob?.nodeId) || entry.nodeId,
|
|
201
|
+
targetDaemonId: readNonEmptyString(refineJob?.targetDaemonId),
|
|
202
|
+
workspace: readNonEmptyString(refineJob?.workspace),
|
|
203
|
+
status: eventName === 'refine:completed' ? 'completed' : 'failed',
|
|
204
|
+
startedAt: readNonEmptyString(refineJob?.startedAt),
|
|
205
|
+
completedAt: readNonEmptyString(refineJob?.completedAt) || entry.timestamp,
|
|
206
|
+
retryOfJobId: readNonEmptyString(refineJob?.retryOfJobId) || readNonEmptyString(payload.retryOfJobId),
|
|
207
|
+
...(result ? { result } : {}),
|
|
208
|
+
};
|
|
209
|
+
backfilled.push({
|
|
210
|
+
event: eventName,
|
|
211
|
+
meshId,
|
|
212
|
+
nodeLabel: readNonEmptyString(refineJob?.nodeId) || entry.nodeId || 'refine job',
|
|
213
|
+
nodeId: readNonEmptyString(refineJob?.nodeId) || entry.nodeId,
|
|
214
|
+
workspace: readNonEmptyString(refineJob?.workspace),
|
|
215
|
+
metadataEvent,
|
|
216
|
+
coordinatorMessage: buildMeshSystemMessage({
|
|
217
|
+
event: eventName,
|
|
218
|
+
nodeLabel: readNonEmptyString(refineJob?.nodeId) || entry.nodeId || 'refine job',
|
|
219
|
+
metadataEvent,
|
|
220
|
+
}),
|
|
221
|
+
queuedAt: Date.now(),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return backfilled.reverse();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function reconcilePendingMeshCoordinatorEvents(meshId: string, events: PendingMeshCoordinatorEvent[]): PendingMeshCoordinatorEvent[] {
|
|
228
|
+
const backfilled = refineTerminalEventFromLedger(meshId, events);
|
|
229
|
+
if (backfilled.length === 0) return events;
|
|
230
|
+
const terminalJobIds = new Set(backfilled.map(event => readRefineJobId(event)).filter(Boolean));
|
|
231
|
+
return [
|
|
232
|
+
...events.filter(event => !(event.event === 'refine:accepted' && terminalJobIds.has(readRefineJobId(event)))),
|
|
233
|
+
...backfilled,
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const MAX_PENDING_EVENTS_BYTES = 100 * 1024; // 100 KB — keep the pending file small
|
|
238
|
+
const MAX_PENDING_EVENTS_KEEP = 50; // keep the last 50 events when trimming
|
|
239
|
+
|
|
240
|
+
function trimPendingEventsIfNeeded(path: string): void {
|
|
241
|
+
try {
|
|
242
|
+
if (!existsSync(path)) return;
|
|
243
|
+
if (statSync(path).size <= MAX_PENDING_EVENTS_BYTES) return;
|
|
244
|
+
const lines = readFileSync(path, 'utf-8').split('\n').filter(Boolean);
|
|
245
|
+
if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
|
|
246
|
+
writeFileSync(path, lines.slice(-MAX_PENDING_EVENTS_KEEP).join('\n') + '\n', 'utf-8');
|
|
247
|
+
} catch { /* best-effort; if trim fails, append still proceeds */ }
|
|
248
|
+
}
|
|
43
249
|
|
|
44
250
|
export function queuePendingMeshCoordinatorEvent(event: PendingMeshCoordinatorEvent): boolean {
|
|
45
|
-
|
|
251
|
+
try {
|
|
252
|
+
if (hasPendingRefineTerminalEventDuplicate(event)) {
|
|
253
|
+
LOG.info('MeshEvents', `Suppressed duplicate pending ${event.event} for refine job ${readRefineJobId(event)}`);
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
if (hasPendingCoordinatorEventDuplicate(event)) {
|
|
257
|
+
LOG.info('MeshEvents', `Suppressed duplicate pending ${event.event} for mesh ${event.meshId}`);
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
// Write to the coordinator-scoped file when the target coordinator is known;
|
|
261
|
+
// fall back to the shared file for legacy/unscoped events.
|
|
262
|
+
const path = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
|
|
263
|
+
trimPendingEventsIfNeeded(path);
|
|
264
|
+
appendFileSync(path, JSON.stringify(event) + '\n', 'utf-8');
|
|
265
|
+
return true;
|
|
266
|
+
} catch (e: any) {
|
|
267
|
+
LOG.warn('MeshEvents', `Failed to persist pending coordinator event: ${e?.message || e}`);
|
|
46
268
|
return false;
|
|
47
269
|
}
|
|
48
|
-
pendingMeshCoordinatorEvents.push(event);
|
|
49
|
-
return true;
|
|
50
270
|
}
|
|
51
271
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
272
|
+
// Atomically rename the file before reading so concurrent drains can't both consume
|
|
273
|
+
// the same events. renameSync is atomic on POSIX (same filesystem); only one caller
|
|
274
|
+
// wins the rename — the other gets ENOENT and returns null, preventing duplicate delivery.
|
|
275
|
+
function atomicDrainFile(path: string): string | null {
|
|
276
|
+
const tmpPath = `${path}.draining`;
|
|
277
|
+
try {
|
|
278
|
+
renameSync(path, tmpPath);
|
|
279
|
+
} catch {
|
|
280
|
+
return null; // another drain already renamed it, or file doesn't exist
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
const content = readFileSync(tmpPath, 'utf-8');
|
|
284
|
+
try { unlinkSync(tmpPath); } catch { /* already cleaned up */ }
|
|
285
|
+
return content;
|
|
286
|
+
} catch {
|
|
287
|
+
try { unlinkSync(tmpPath); } catch { /* best-effort cleanup */ }
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Drain and return all pending coordinator events for meshId, removing them from disk. */
|
|
293
|
+
export function drainPendingMeshCoordinatorEvents(meshId?: string, coordinatorDaemonId?: string): PendingMeshCoordinatorEvent[] {
|
|
294
|
+
if (!meshId) return [];
|
|
295
|
+
const paths = coordinatorDaemonId
|
|
296
|
+
? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)]
|
|
297
|
+
: [getPendingEventsPath(meshId)];
|
|
298
|
+
const all: PendingMeshCoordinatorEvent[] = [];
|
|
299
|
+
for (const path of paths) {
|
|
300
|
+
const content = atomicDrainFile(path);
|
|
301
|
+
if (!content) continue;
|
|
302
|
+
const parsed = content.split('\n').filter(Boolean).flatMap(line => {
|
|
303
|
+
try { return [JSON.parse(line) as PendingMeshCoordinatorEvent]; } catch { return []; }
|
|
304
|
+
});
|
|
305
|
+
// If reading the shared file, filter to events that target this coordinator or are unscoped.
|
|
306
|
+
const filtered = (coordinatorDaemonId && path === getPendingEventsPath(meshId))
|
|
307
|
+
? parsed.filter(e => !e.targetCoordinatorDaemonId || e.targetCoordinatorDaemonId === coordinatorDaemonId)
|
|
308
|
+
: parsed;
|
|
309
|
+
all.push(...filtered);
|
|
310
|
+
}
|
|
311
|
+
if (all.length === 0) return [];
|
|
312
|
+
return reconcilePendingMeshCoordinatorEvents(meshId, all);
|
|
55
313
|
}
|
|
56
314
|
|
|
57
315
|
/** Peek at pending coordinator events without draining (non-destructive). */
|
|
58
|
-
export function getPendingMeshCoordinatorEvents(): readonly PendingMeshCoordinatorEvent[] {
|
|
59
|
-
|
|
316
|
+
export function getPendingMeshCoordinatorEvents(meshId?: string, coordinatorDaemonId?: string): readonly PendingMeshCoordinatorEvent[] {
|
|
317
|
+
if (!meshId) return [];
|
|
318
|
+
return reconcilePendingMeshCoordinatorEvents(meshId, readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId));
|
|
60
319
|
}
|
|
61
320
|
|
|
62
|
-
/** Explicitly clear all pending coordinator events. */
|
|
63
|
-
export function clearPendingMeshCoordinatorEvents(): void {
|
|
64
|
-
|
|
321
|
+
/** Explicitly clear all pending coordinator events for a mesh (and coordinator if scoped). */
|
|
322
|
+
export function clearPendingMeshCoordinatorEvents(meshId?: string, coordinatorDaemonId?: string): void {
|
|
323
|
+
if (!meshId) return;
|
|
324
|
+
const paths = coordinatorDaemonId
|
|
325
|
+
? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)]
|
|
326
|
+
: [getPendingEventsPath(meshId)];
|
|
327
|
+
for (const path of paths) {
|
|
328
|
+
if (existsSync(path)) try { unlinkSync(path); } catch { /* already removed */ }
|
|
329
|
+
}
|
|
65
330
|
}
|
|
66
331
|
|
|
67
332
|
function readNonEmptyString(value: unknown): string {
|
|
68
333
|
return typeof value === 'string' && value.trim() ? value.trim() : '';
|
|
69
334
|
}
|
|
70
335
|
|
|
336
|
+
function readRecord(value: unknown): Record<string, unknown> | undefined {
|
|
337
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
338
|
+
? value as Record<string, unknown>
|
|
339
|
+
: undefined;
|
|
340
|
+
}
|
|
341
|
+
|
|
71
342
|
function resolveEventSessionId(event: Record<string, unknown>, fallback?: unknown): string {
|
|
72
343
|
return readNonEmptyString(event.targetSessionId)
|
|
73
344
|
|| readNonEmptyString(event.sessionId)
|
|
@@ -82,6 +353,9 @@ const MESH_COORDINATOR_EVENTS = new Set([
|
|
|
82
353
|
'agent:stopped',
|
|
83
354
|
'agent:ready',
|
|
84
355
|
'monitor:long_generating',
|
|
356
|
+
'refine:accepted',
|
|
357
|
+
'refine:completed',
|
|
358
|
+
'refine:failed',
|
|
85
359
|
]);
|
|
86
360
|
|
|
87
361
|
const EVENT_TO_LEDGER_KIND: Record<string, MeshLedgerKind> = {
|
|
@@ -96,10 +370,21 @@ function isMeshCoordinatorEvent(eventName: unknown): eventName is string {
|
|
|
96
370
|
}
|
|
97
371
|
|
|
98
372
|
function formatCompletionMetadata(event: Record<string, unknown>): string {
|
|
373
|
+
const completionDiagnostic = event.completionDiagnostic && typeof event.completionDiagnostic === 'object'
|
|
374
|
+
? event.completionDiagnostic as Record<string, unknown>
|
|
375
|
+
: null;
|
|
376
|
+
const diagnosticReason = completionDiagnostic
|
|
377
|
+
? readNonEmptyString(completionDiagnostic.blockReason) || 'present'
|
|
378
|
+
: '';
|
|
379
|
+
const finalAssistantPresent = typeof completionDiagnostic?.finalAssistantPresent === 'boolean'
|
|
380
|
+
? String(completionDiagnostic.finalAssistantPresent)
|
|
381
|
+
: '';
|
|
99
382
|
const parts = [
|
|
100
383
|
readNonEmptyString(event.targetSessionId) ? `session_id=${readNonEmptyString(event.targetSessionId)}` : '',
|
|
101
384
|
readNonEmptyString(event.providerType) ? `provider=${readNonEmptyString(event.providerType)}` : '',
|
|
102
385
|
readNonEmptyString(event.providerSessionId) ? `provider_session_id=${readNonEmptyString(event.providerSessionId)}` : '',
|
|
386
|
+
diagnosticReason ? `completion_diagnostic=${diagnosticReason}` : '',
|
|
387
|
+
finalAssistantPresent ? `final_assistant=${finalAssistantPresent}` : '',
|
|
103
388
|
].filter(Boolean);
|
|
104
389
|
return parts.length > 0 ? ` (${parts.join('; ')})` : '';
|
|
105
390
|
}
|
|
@@ -126,7 +411,7 @@ function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boole
|
|
|
126
411
|
function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
|
|
127
412
|
if (!sessionId && !nodeId) return false;
|
|
128
413
|
const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
|
|
129
|
-
const entries = readLedgerEntries(meshId);
|
|
414
|
+
const entries = readLedgerEntries(meshId, { tail: 200 });
|
|
130
415
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
131
416
|
const entry = entries[i];
|
|
132
417
|
const timestamp = new Date(entry.timestamp).getTime();
|
|
@@ -150,6 +435,181 @@ function shouldSuppressIntentionalCleanupStop(args: {
|
|
|
150
435
|
return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
|
|
151
436
|
}
|
|
152
437
|
|
|
438
|
+
const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
|
|
439
|
+
|
|
440
|
+
function hasFingerprintSeen(fingerprint: string): boolean {
|
|
441
|
+
try {
|
|
442
|
+
return BeadsDB.getInstance().hasCompletionFingerprint(fingerprint);
|
|
443
|
+
} catch {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function recordFingerprintSeen(fingerprint: string): void {
|
|
449
|
+
try {
|
|
450
|
+
const db = BeadsDB.getInstance();
|
|
451
|
+
db.recordCompletionFingerprint(fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
|
|
452
|
+
db.sweepExpiredFingerprints();
|
|
453
|
+
} catch { /* best-effort; duplicate events are preferable to a crash */ }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function readEventTimestamp(value: unknown): number | null {
|
|
457
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
458
|
+
if (typeof value === 'string' && value.trim()) {
|
|
459
|
+
const numeric = Number(value);
|
|
460
|
+
if (Number.isFinite(numeric)) return numeric;
|
|
461
|
+
const parsed = Date.parse(value);
|
|
462
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
463
|
+
}
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function buildMeshCompletionFingerprint(args: {
|
|
468
|
+
meshId: string;
|
|
469
|
+
event: string;
|
|
470
|
+
sessionId: string;
|
|
471
|
+
providerType?: string;
|
|
472
|
+
providerSessionId?: string;
|
|
473
|
+
timestamp?: number | null;
|
|
474
|
+
finalSummary?: string;
|
|
475
|
+
/** When set, scopes the fingerprint to a specific coordinator daemon so
|
|
476
|
+
* two coordinators processing events from their respective workers don't
|
|
477
|
+
* suppress each other's completion events. */
|
|
478
|
+
coordinatorDaemonId?: string;
|
|
479
|
+
}): string {
|
|
480
|
+
const timestampPart = Number.isFinite(args.timestamp)
|
|
481
|
+
? String(args.timestamp)
|
|
482
|
+
: readNonEmptyString(args.finalSummary).slice(0, 200);
|
|
483
|
+
return [
|
|
484
|
+
args.meshId,
|
|
485
|
+
args.event,
|
|
486
|
+
args.sessionId,
|
|
487
|
+
args.providerType || '',
|
|
488
|
+
args.providerSessionId || '',
|
|
489
|
+
timestampPart,
|
|
490
|
+
args.coordinatorDaemonId || '',
|
|
491
|
+
].join('::');
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function isDuplicateMeshCompletionEvent(args: {
|
|
495
|
+
meshId: string;
|
|
496
|
+
event: string;
|
|
497
|
+
sessionId: string;
|
|
498
|
+
providerType?: string;
|
|
499
|
+
providerSessionId?: string;
|
|
500
|
+
timestamp?: number | null;
|
|
501
|
+
finalSummary?: string;
|
|
502
|
+
coordinatorDaemonId?: string;
|
|
503
|
+
}): boolean {
|
|
504
|
+
const fingerprint = buildMeshCompletionFingerprint(args);
|
|
505
|
+
if (!fingerprint) return false;
|
|
506
|
+
if (hasFingerprintSeen(fingerprint)) return true;
|
|
507
|
+
recordFingerprintSeen(fingerprint);
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
|
|
512
|
+
const fingerprint = buildRefineTerminalEventFingerprint(meshId, eventName, metadataEvent);
|
|
513
|
+
if (!fingerprint) return false;
|
|
514
|
+
if (hasFingerprintSeen(fingerprint)) return true;
|
|
515
|
+
recordFingerprintSeen(fingerprint);
|
|
516
|
+
return false;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function findRecentTerminalLedgerEvidence(args: {
|
|
520
|
+
meshId: string;
|
|
521
|
+
sessionId?: string;
|
|
522
|
+
nodeId?: string;
|
|
523
|
+
}): { id: string; kind: MeshLedgerKind; payload: Record<string, unknown>; timestamp: string } | null {
|
|
524
|
+
if (!args.sessionId && !args.nodeId) return null;
|
|
525
|
+
// Tail-limit: 200 entries gives a wide enough window to catch terminal events for active
|
|
526
|
+
// sessions while avoiding a full O(n) scan. If a terminal is older than 200 entries,
|
|
527
|
+
// the BeadsDB fingerprint dedup will still block duplicate processing downstream.
|
|
528
|
+
const entries = readLedgerEntries(args.meshId, { tail: 200 });
|
|
529
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
530
|
+
const entry = entries[i];
|
|
531
|
+
if (entry.kind !== 'task_completed' && entry.kind !== 'task_failed' && entry.kind !== 'task_stalled') continue;
|
|
532
|
+
if (args.sessionId && entry.sessionId === args.sessionId) {
|
|
533
|
+
return { id: entry.id, kind: entry.kind, payload: entry.payload || {}, timestamp: entry.timestamp };
|
|
534
|
+
}
|
|
535
|
+
if (!args.sessionId && args.nodeId && entry.nodeId === args.nodeId) {
|
|
536
|
+
return { id: entry.id, kind: entry.kind, payload: entry.payload || {}, timestamp: entry.timestamp };
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Returns true when a task_dispatched entry for the given session appears AFTER the terminal
|
|
543
|
+
// entry (identified by terminalId) in ledger order. Positional (append) order is used rather
|
|
544
|
+
// than timestamp comparison because both entries may share the same millisecond.
|
|
545
|
+
function hasDispatchAfterTerminal(meshId: string, sessionId: string, terminalId: string): boolean {
|
|
546
|
+
// 200-entry window matches findRecentTerminalLedgerEvidence for consistency.
|
|
547
|
+
const entries = readLedgerEntries(meshId, { tail: 200 });
|
|
548
|
+
let pastTerminal = false;
|
|
549
|
+
for (const entry of entries) {
|
|
550
|
+
if (!pastTerminal) {
|
|
551
|
+
if (entry.id === terminalId) pastTerminal = true;
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
if (entry.kind === 'task_dispatched' && entry.sessionId === sessionId) return true;
|
|
555
|
+
}
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function buildLongGeneratingCompletionReconciliation(args: {
|
|
560
|
+
meshId: string;
|
|
561
|
+
nodeId?: string;
|
|
562
|
+
nodeLabel: string;
|
|
563
|
+
metadataEvent: Record<string, unknown>;
|
|
564
|
+
sourceInstanceId?: string;
|
|
565
|
+
}): Record<string, unknown> | null {
|
|
566
|
+
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
567
|
+
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
568
|
+
const providerType = readNonEmptyString(args.metadataEvent.providerType);
|
|
569
|
+
const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
|
|
570
|
+
const workerResult = readWorkerResultMetadata(args.metadataEvent);
|
|
571
|
+
const completionDiagnostic = readRecord(args.metadataEvent.completionDiagnostic);
|
|
572
|
+
const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
|
|
573
|
+
const status = readNonEmptyString(args.metadataEvent.status).toLowerCase();
|
|
574
|
+
const explicitCompletionEvidence = Boolean(
|
|
575
|
+
finalSummary
|
|
576
|
+
|| workerResult
|
|
577
|
+
|| completionDiagnostic?.finalAssistantPresent === true
|
|
578
|
+
|| status === 'idle'
|
|
579
|
+
|| status === 'ready'
|
|
580
|
+
|| status === 'completed',
|
|
581
|
+
);
|
|
582
|
+
if (explicitCompletionEvidence) {
|
|
583
|
+
return {
|
|
584
|
+
...args.metadataEvent,
|
|
585
|
+
targetSessionId: sessionId,
|
|
586
|
+
providerType,
|
|
587
|
+
providerSessionId,
|
|
588
|
+
finalSummary,
|
|
589
|
+
source: 'long_generating_reconciliation',
|
|
590
|
+
reconciledFromEvent: 'monitor:long_generating',
|
|
591
|
+
timestamp: args.metadataEvent.timestamp ?? Date.now(),
|
|
592
|
+
completionDiagnostic: {
|
|
593
|
+
...(completionDiagnostic || {}),
|
|
594
|
+
reconciliationReason: 'provider_completion_evidence',
|
|
595
|
+
},
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const terminal = findRecentTerminalLedgerEvidence({
|
|
600
|
+
meshId: args.meshId,
|
|
601
|
+
sessionId: sessionId || undefined,
|
|
602
|
+
nodeId: nodeId || undefined,
|
|
603
|
+
});
|
|
604
|
+
if (!terminal) return null;
|
|
605
|
+
return {
|
|
606
|
+
...args.metadataEvent,
|
|
607
|
+
source: 'long_generating_terminal_ledger_suppression',
|
|
608
|
+
terminalLedgerKind: terminal.kind,
|
|
609
|
+
terminalLedgerAt: terminal.timestamp,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
153
613
|
|
|
154
614
|
export function tryAssignQueueTask(
|
|
155
615
|
components: DaemonComponents,
|
|
@@ -180,7 +640,16 @@ export function tryAssignQueueTask(
|
|
|
180
640
|
message: task.message,
|
|
181
641
|
}).catch((e: any) => {
|
|
182
642
|
LOG.error('MeshQueue', `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
|
|
183
|
-
|
|
643
|
+
// Revert to pending so the task can be retried rather than permanently failing
|
|
644
|
+
updateTaskStatus(meshId, task.id, 'pending');
|
|
645
|
+
try {
|
|
646
|
+
appendLedgerEntry(meshId, {
|
|
647
|
+
kind: 'dispatch_failed' as any,
|
|
648
|
+
nodeId,
|
|
649
|
+
sessionId,
|
|
650
|
+
payload: { taskId: task.id, error: e?.message, retryable: true },
|
|
651
|
+
});
|
|
652
|
+
} catch { /* ledger write is best-effort */ }
|
|
184
653
|
});
|
|
185
654
|
return true;
|
|
186
655
|
}
|
|
@@ -204,6 +673,13 @@ const autoLaunchInProgress = new Set<string>();
|
|
|
204
673
|
const autoLaunchCooldownUntil = new Map<string, number>();
|
|
205
674
|
const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
|
|
206
675
|
|
|
676
|
+
function sweepExpiredCooldowns(): void {
|
|
677
|
+
const now = Date.now();
|
|
678
|
+
for (const [key, until] of autoLaunchCooldownUntil) {
|
|
679
|
+
if (now >= until) autoLaunchCooldownUntil.delete(key);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
207
683
|
function normalizeProviderPriority(policy: unknown): string[] {
|
|
208
684
|
const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
209
685
|
? (policy as Record<string, unknown>).providerPriority
|
|
@@ -277,6 +753,10 @@ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
|
|
|
277
753
|
return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
|
|
278
754
|
}
|
|
279
755
|
|
|
756
|
+
function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
|
|
757
|
+
return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId);
|
|
758
|
+
}
|
|
759
|
+
|
|
280
760
|
function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
|
|
281
761
|
return components.instanceManager.getByCategory('cli').filter((inst: any) => {
|
|
282
762
|
const state = inst.getState();
|
|
@@ -406,12 +886,14 @@ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, mesh
|
|
|
406
886
|
const nodeId = readNonEmptyString(node?.id);
|
|
407
887
|
if (!nodeId) continue;
|
|
408
888
|
const launchKey = `${meshId}:${nodeId}`;
|
|
889
|
+
const now = Date.now();
|
|
409
890
|
const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
|
|
891
|
+
if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
|
|
410
892
|
if (autoLaunchInProgress.has(launchKey)) {
|
|
411
893
|
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
|
|
412
894
|
continue;
|
|
413
895
|
}
|
|
414
|
-
if (
|
|
896
|
+
if (now < cooldownUntil) {
|
|
415
897
|
markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
|
|
416
898
|
continue;
|
|
417
899
|
}
|
|
@@ -461,13 +943,13 @@ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, mesh
|
|
|
461
943
|
if (!launchResult?.success) {
|
|
462
944
|
const reason = launchResult?.error || 'launch_cli_failed';
|
|
463
945
|
markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
|
|
464
|
-
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
|
|
946
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
465
947
|
return false;
|
|
466
948
|
}
|
|
467
949
|
const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
|
|
468
950
|
if (!sessionId) {
|
|
469
951
|
markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
|
|
470
|
-
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
|
|
952
|
+
autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
|
|
471
953
|
return false;
|
|
472
954
|
}
|
|
473
955
|
markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
|
|
@@ -542,6 +1024,9 @@ function buildMeshSystemMessage(args: {
|
|
|
542
1024
|
}): string {
|
|
543
1025
|
const metadata = formatCompletionMetadata(args.metadataEvent);
|
|
544
1026
|
if (args.event === 'agent:generating_completed') {
|
|
1027
|
+
if (args.metadataEvent.source === 'long_generating_reconciliation') {
|
|
1028
|
+
return `[System] ${args.nodeLabel} already has completion evidence${metadata}. The long-generating monitor reconciled the terminal handoff and marked the session complete; wait for the queued completion event/status refresh before doing any manual transcript check.`;
|
|
1029
|
+
}
|
|
545
1030
|
return `[System] ${args.nodeLabel} has completed its task and is now idle${metadata}. This completion came from the agent status event path; use mesh_read_chat once to review its final progress, but do not poll repeatedly.`;
|
|
546
1031
|
}
|
|
547
1032
|
if (args.event === 'agent:waiting_approval') {
|
|
@@ -573,7 +1058,72 @@ function buildMeshSystemMessage(args: {
|
|
|
573
1058
|
return `[System] ${args.nodeLabel} has stopped${metadata}. Use mesh_read_chat once if you need to inspect its last output.`;
|
|
574
1059
|
}
|
|
575
1060
|
if (args.event === 'monitor:long_generating') {
|
|
576
|
-
return `[System] ${args.nodeLabel}
|
|
1061
|
+
return `[System] ${args.nodeLabel} is still reported as generating after a long interval${metadata}. Wait for pendingCoordinatorEvents or a completion/status event; if the user explicitly asks for status, make one bounded status check and then wait again.`;
|
|
1062
|
+
}
|
|
1063
|
+
if (args.event === 'refine:accepted') {
|
|
1064
|
+
const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
|
|
1065
|
+
return `[System] Refinery accepted async job${jobId ? ` ${jobId}` : ''} for ${args.nodeLabel}. Completion/failure will be delivered as a terminal refine event; do not poll repeatedly.`;
|
|
1066
|
+
}
|
|
1067
|
+
if (args.event === 'refine:completed') {
|
|
1068
|
+
const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
|
|
1069
|
+
const result = readRecord(args.metadataEvent.result);
|
|
1070
|
+
const validationSummary = readRecord(result?.validationSummary);
|
|
1071
|
+
const patchEquivalence = readRecord(result?.patchEquivalence);
|
|
1072
|
+
const finalConvergence = readRecord(result?.finalBranchConvergenceState);
|
|
1073
|
+
const validationStatus = readNonEmptyString(validationSummary?.status);
|
|
1074
|
+
const patchStatus = readNonEmptyString(patchEquivalence?.status)
|
|
1075
|
+
|| (patchEquivalence?.equivalent === true ? 'passed' : '');
|
|
1076
|
+
const into = readNonEmptyString(result?.into);
|
|
1077
|
+
const branch = readNonEmptyString(result?.branch);
|
|
1078
|
+
const mergeStatus = result?.merged === true ? 'merged' : readNonEmptyString(finalConvergence?.status);
|
|
1079
|
+
const convergenceStatus = readNonEmptyString(finalConvergence?.status);
|
|
1080
|
+
const nextStep = readNonEmptyString(result?.nextStep)
|
|
1081
|
+
|| readNonEmptyString(finalConvergence?.nextStep)
|
|
1082
|
+
|| 'Continue from the updated mesh state.';
|
|
1083
|
+
const details = [
|
|
1084
|
+
jobId ? `job_id=${jobId}` : '',
|
|
1085
|
+
branch && into ? `${branch}→${into}` : '',
|
|
1086
|
+
validationStatus ? `validation=${validationStatus}` : '',
|
|
1087
|
+
patchStatus ? `patch_equivalence=${patchStatus}` : '',
|
|
1088
|
+
mergeStatus ? `merge=${mergeStatus}` : '',
|
|
1089
|
+
convergenceStatus ? `final_convergence=${convergenceStatus}` : '',
|
|
1090
|
+
].filter(Boolean).join('; ');
|
|
1091
|
+
return `[System] Refinery async job for ${args.nodeLabel} completed successfully${details ? ` (${details})` : ''}.\nNext step: ${nextStep}`;
|
|
1092
|
+
}
|
|
1093
|
+
if (args.event === 'refine:failed') {
|
|
1094
|
+
const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
|
|
1095
|
+
const result = readRecord(args.metadataEvent.result);
|
|
1096
|
+
const validationSummary = readRecord(result?.validationSummary);
|
|
1097
|
+
const patchEquivalence = readRecord(result?.patchEquivalence);
|
|
1098
|
+
const finalConvergence = readRecord(result?.finalBranchConvergenceState);
|
|
1099
|
+
const code = readNonEmptyString(result?.code);
|
|
1100
|
+
const error = readNonEmptyString(result?.error);
|
|
1101
|
+
const validationStatus = readNonEmptyString(validationSummary?.status);
|
|
1102
|
+
const patchStatus = readNonEmptyString(patchEquivalence?.status)
|
|
1103
|
+
|| (patchEquivalence?.equivalent === true ? 'passed' : '');
|
|
1104
|
+
const mergeStatus = result?.merged === true
|
|
1105
|
+
? 'merged'
|
|
1106
|
+
: finalConvergence?.merged === false
|
|
1107
|
+
? 'not_merged'
|
|
1108
|
+
: '';
|
|
1109
|
+
const convergenceStatus = readNonEmptyString(result?.convergenceStatus)
|
|
1110
|
+
|| readNonEmptyString(finalConvergence?.status);
|
|
1111
|
+
const blockedReason = readNonEmptyString(result?.blockedReason);
|
|
1112
|
+
const nextStep = readNonEmptyString(result?.nextStep) || readNonEmptyString(finalConvergence?.nextStep);
|
|
1113
|
+
const details = [
|
|
1114
|
+
jobId ? `job_id=${jobId}` : '',
|
|
1115
|
+
code ? `code=${code}` : '',
|
|
1116
|
+
validationStatus ? `validation=${validationStatus}` : '',
|
|
1117
|
+
patchStatus ? `patch_equivalence=${patchStatus}` : '',
|
|
1118
|
+
mergeStatus ? `merge=${mergeStatus}` : '',
|
|
1119
|
+
convergenceStatus ? `convergence=${convergenceStatus}` : '',
|
|
1120
|
+
blockedReason ? `reason=${blockedReason}` : '',
|
|
1121
|
+
].filter(Boolean).join('; ');
|
|
1122
|
+
const parts = [
|
|
1123
|
+
`[System] Refinery async job for ${args.nodeLabel} failed${details ? ` (${details})` : ''}${error ? `: ${error}` : '.'}`,
|
|
1124
|
+
nextStep ? `Next step: ${nextStep}` : 'Review the terminal refine event/ledger before retrying.',
|
|
1125
|
+
];
|
|
1126
|
+
return parts.join('\n');
|
|
577
1127
|
}
|
|
578
1128
|
return '';
|
|
579
1129
|
}
|
|
@@ -588,6 +1138,15 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
588
1138
|
}) {
|
|
589
1139
|
const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
590
1140
|
const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
1141
|
+
|
|
1142
|
+
// Resolve coordinator ownership early — used in fingerprinting and coordinator routing.
|
|
1143
|
+
const sourceSession = args.sourceInstanceId
|
|
1144
|
+
? components.instanceManager.getInstance(args.sourceInstanceId)
|
|
1145
|
+
: undefined;
|
|
1146
|
+
const workerCoordinatorDaemonId = readNonEmptyString(
|
|
1147
|
+
(sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
|
|
1148
|
+
);
|
|
1149
|
+
const localDaemonId = readNonEmptyString(loadConfig().machineId);
|
|
591
1150
|
const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
|
|
592
1151
|
event: args.event,
|
|
593
1152
|
meshId: args.meshId,
|
|
@@ -603,6 +1162,83 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
603
1162
|
return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
|
|
604
1163
|
}
|
|
605
1164
|
|
|
1165
|
+
if (args.event === 'monitor:long_generating') {
|
|
1166
|
+
const reconciledCompletion = buildLongGeneratingCompletionReconciliation({
|
|
1167
|
+
meshId: args.meshId,
|
|
1168
|
+
nodeId: args.nodeId,
|
|
1169
|
+
nodeLabel: args.nodeLabel,
|
|
1170
|
+
metadataEvent: args.metadataEvent,
|
|
1171
|
+
sourceInstanceId: args.sourceInstanceId,
|
|
1172
|
+
});
|
|
1173
|
+
if (reconciledCompletion?.source === 'long_generating_reconciliation') {
|
|
1174
|
+
LOG.info('MeshEvents', `Reconciled long-generating monitor to completion for session ${eventSessionId || '(unknown session)'}`);
|
|
1175
|
+
return injectMeshSystemMessage(components, {
|
|
1176
|
+
...args,
|
|
1177
|
+
event: 'agent:generating_completed',
|
|
1178
|
+
metadataEvent: reconciledCompletion,
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
if (reconciledCompletion?.source === 'long_generating_terminal_ledger_suppression') {
|
|
1182
|
+
LOG.info('MeshEvents', `Suppressed long-generating monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
|
|
1183
|
+
return {
|
|
1184
|
+
success: true,
|
|
1185
|
+
forwarded: 0,
|
|
1186
|
+
suppressed: true,
|
|
1187
|
+
terminalLedgerEvidence: true,
|
|
1188
|
+
terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
|
|
1194
|
+
LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
|
|
1195
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
|
|
1199
|
+
if (args.event === 'agent:generating_completed' && eventSessionId) {
|
|
1200
|
+
const terminal = findRecentTerminalLedgerEvidence({
|
|
1201
|
+
meshId: args.meshId,
|
|
1202
|
+
sessionId: eventSessionId,
|
|
1203
|
+
nodeId: eventNodeId || undefined,
|
|
1204
|
+
});
|
|
1205
|
+
if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
|
|
1206
|
+
// If a new task_dispatched was recorded for this session after the prior terminal,
|
|
1207
|
+
// this completion belongs to the new task — never suppress it as a duplicate.
|
|
1208
|
+
const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
|
|
1209
|
+
if (!newDispatchAfterTerminal) {
|
|
1210
|
+
const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
|
|
1211
|
+
const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
|
|
1212
|
+
const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
|
|
1213
|
+
const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
|
|
1214
|
+
if (
|
|
1215
|
+
(terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
|
|
1216
|
+
|| (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
|
|
1217
|
+
|| args.metadataEvent.source === 'long_generating_reconciliation'
|
|
1218
|
+
) {
|
|
1219
|
+
LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1220
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
const duplicateCompletion = isDuplicateMeshCompletionEvent({
|
|
1225
|
+
meshId: args.meshId,
|
|
1226
|
+
event: args.event,
|
|
1227
|
+
sessionId: eventSessionId,
|
|
1228
|
+
providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
|
|
1229
|
+
providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
|
|
1230
|
+
timestamp: eventTimestamp,
|
|
1231
|
+
finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
|
|
1232
|
+
// Scope dedup to the coordinator daemon so two coordinators for the same mesh
|
|
1233
|
+
// don't suppress each other's completion events via shared fingerprint table.
|
|
1234
|
+
coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
|
|
1235
|
+
});
|
|
1236
|
+
if (duplicateCompletion) {
|
|
1237
|
+
LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
|
|
1238
|
+
return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
|
|
606
1242
|
// ── Task Queue & Ledger ──
|
|
607
1243
|
let completedTaskForLedger: { id?: string } | null = null;
|
|
608
1244
|
if (args.event === 'agent:generating_completed') {
|
|
@@ -611,24 +1247,33 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
611
1247
|
const providerType = readNonEmptyString(args.metadataEvent.providerType);
|
|
612
1248
|
|
|
613
1249
|
if (sessionId) {
|
|
614
|
-
const completedTask = updateSessionTaskStatus(args.meshId, sessionId, 'completed'
|
|
1250
|
+
const completedTask = updateSessionTaskStatus(args.meshId, sessionId, 'completed', {
|
|
1251
|
+
occurredAt: eventTimestamp !== null ? new Date(eventTimestamp).toISOString() : undefined,
|
|
1252
|
+
});
|
|
615
1253
|
completedTaskForLedger = completedTask ? { id: completedTask.id } : null;
|
|
1254
|
+
updateDirectDispatchStatus(args.meshId, sessionId, 'completed');
|
|
1255
|
+
setImmediate(() => cleanupTerminalDirectDispatches());
|
|
616
1256
|
if (nodeId && providerType) {
|
|
617
|
-
|
|
618
|
-
setTimeout(() => {
|
|
1257
|
+
setImmediate(() => {
|
|
619
1258
|
tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
|
|
620
|
-
}
|
|
1259
|
+
});
|
|
621
1260
|
}
|
|
622
1261
|
}
|
|
623
1262
|
} else if (args.event === 'agent:ready') {
|
|
624
1263
|
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
625
1264
|
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
626
1265
|
const providerType = readNonEmptyString(args.metadataEvent.providerType);
|
|
627
|
-
const
|
|
1266
|
+
const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
|
|
1267
|
+
const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
|
|
1268
|
+
const workerResult = readWorkerResultMetadata(args.metadataEvent);
|
|
1269
|
+
const hasCompletionEvidence = !!finalSummary || !!workerResult;
|
|
1270
|
+
const completedTask = sessionId && hasCompletionEvidence
|
|
628
1271
|
? updateSessionTaskStatus(args.meshId, sessionId, 'completed')
|
|
629
1272
|
: null;
|
|
630
|
-
if (completedTask) {
|
|
1273
|
+
if (completedTask && sessionId) {
|
|
631
1274
|
completedTaskForLedger = { id: completedTask.id };
|
|
1275
|
+
updateDirectDispatchStatus(args.meshId, sessionId, 'completed');
|
|
1276
|
+
setImmediate(() => cleanupTerminalDirectDispatches());
|
|
632
1277
|
try {
|
|
633
1278
|
appendLedgerEntry(args.meshId, {
|
|
634
1279
|
kind: 'task_completed',
|
|
@@ -640,15 +1285,17 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
640
1285
|
nodeLabel: args.nodeLabel,
|
|
641
1286
|
taskId: completedTask.id,
|
|
642
1287
|
completedViaReady: true,
|
|
643
|
-
providerSessionId
|
|
644
|
-
finalSummary
|
|
1288
|
+
providerSessionId,
|
|
1289
|
+
finalSummary,
|
|
1290
|
+
workerResult,
|
|
645
1291
|
evidence: buildTaskCompletionEvidence({
|
|
646
1292
|
event: 'agent:ready',
|
|
647
1293
|
nodeId,
|
|
648
1294
|
sessionId,
|
|
649
1295
|
providerType: providerType || undefined,
|
|
650
|
-
providerSessionId
|
|
651
|
-
finalSummary
|
|
1296
|
+
providerSessionId,
|
|
1297
|
+
finalSummary,
|
|
1298
|
+
workerResult,
|
|
652
1299
|
}),
|
|
653
1300
|
},
|
|
654
1301
|
});
|
|
@@ -658,13 +1305,15 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
658
1305
|
}
|
|
659
1306
|
|
|
660
1307
|
if (sessionId && nodeId && providerType) {
|
|
661
|
-
|
|
662
|
-
|
|
1308
|
+
sweepExpiredRemoteIdleSessions();
|
|
1309
|
+
remoteIdleSessions.set(`${nodeId}:${sessionId}`, {
|
|
1310
|
+
nodeId, sessionId, providerType,
|
|
1311
|
+
expiresAt: Date.now() + REMOTE_IDLE_SESSION_TTL_MS,
|
|
1312
|
+
});
|
|
1313
|
+
setImmediate(() => {
|
|
663
1314
|
const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
|
|
664
|
-
if (assigned) {
|
|
665
|
-
|
|
666
|
-
}
|
|
667
|
-
}, 500);
|
|
1315
|
+
if (assigned) remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
|
|
1316
|
+
});
|
|
668
1317
|
}
|
|
669
1318
|
} else if (args.event === 'agent:generating_started') {
|
|
670
1319
|
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
@@ -672,6 +1321,10 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
672
1321
|
if (sessionId && nodeId) {
|
|
673
1322
|
remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
|
|
674
1323
|
}
|
|
1324
|
+
if (sessionId) {
|
|
1325
|
+
// Mark direct dispatch as acknowledged — the session started generating.
|
|
1326
|
+
updateDirectDispatchStatus(args.meshId, sessionId, 'acked');
|
|
1327
|
+
}
|
|
675
1328
|
} else if (args.event === 'agent:stopped') {
|
|
676
1329
|
const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
|
|
677
1330
|
const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
|
|
@@ -679,7 +1332,9 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
679
1332
|
remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
|
|
680
1333
|
}
|
|
681
1334
|
if (sessionId) {
|
|
682
|
-
updateSessionTaskStatus(args.meshId, sessionId, 'failed');
|
|
1335
|
+
const failedTask = updateSessionTaskStatus(args.meshId, sessionId, 'failed');
|
|
1336
|
+
completedTaskForLedger = failedTask ? { id: failedTask.id } : null;
|
|
1337
|
+
updateDirectDispatchStatus(args.meshId, sessionId, 'failed');
|
|
683
1338
|
}
|
|
684
1339
|
}
|
|
685
1340
|
|
|
@@ -689,14 +1344,18 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
689
1344
|
const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
|
|
690
1345
|
const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
|
|
691
1346
|
const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
|
|
1347
|
+
const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
|
|
1348
|
+
const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
|
|
1349
|
+
const workerResult = readWorkerResultMetadata(args.metadataEvent);
|
|
692
1350
|
const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
|
|
693
1351
|
? buildTaskCompletionEvidence({
|
|
694
1352
|
event: 'agent:generating_completed',
|
|
695
1353
|
nodeId: ledgerNodeId,
|
|
696
1354
|
sessionId: ledgerSessionId,
|
|
697
1355
|
providerType: ledgerProviderType,
|
|
698
|
-
providerSessionId
|
|
699
|
-
finalSummary
|
|
1356
|
+
providerSessionId,
|
|
1357
|
+
finalSummary,
|
|
1358
|
+
workerResult,
|
|
700
1359
|
})
|
|
701
1360
|
: undefined;
|
|
702
1361
|
appendLedgerEntry(args.meshId, {
|
|
@@ -708,8 +1367,12 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
708
1367
|
event: args.event,
|
|
709
1368
|
nodeLabel: args.nodeLabel,
|
|
710
1369
|
taskId: completedTaskForLedger?.id || undefined,
|
|
711
|
-
providerSessionId
|
|
712
|
-
finalSummary
|
|
1370
|
+
providerSessionId,
|
|
1371
|
+
finalSummary,
|
|
1372
|
+
workerResult,
|
|
1373
|
+
completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
|
|
1374
|
+
? args.metadataEvent.completionDiagnostic
|
|
1375
|
+
: undefined,
|
|
713
1376
|
evidence: completionEvidence,
|
|
714
1377
|
},
|
|
715
1378
|
});
|
|
@@ -782,15 +1445,33 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
782
1445
|
}
|
|
783
1446
|
}
|
|
784
1447
|
|
|
1448
|
+
const messageText = buildMeshSystemMessage({
|
|
1449
|
+
event: args.event,
|
|
1450
|
+
nodeLabel: args.nodeLabel,
|
|
1451
|
+
metadataEvent: args.metadataEvent,
|
|
1452
|
+
recoveryContext,
|
|
1453
|
+
});
|
|
1454
|
+
if (!messageText) return { success: false, error: 'unsupported mesh event' };
|
|
1455
|
+
|
|
785
1456
|
const coordinatorInstances = components.instanceManager.getByCategory('cli').filter((inst) => {
|
|
786
1457
|
const instState = inst.getState();
|
|
787
1458
|
if (instState.settings?.meshCoordinatorFor !== args.meshId) return false;
|
|
788
1459
|
if (args.sourceInstanceId && instState.instanceId === args.sourceInstanceId) return false;
|
|
1460
|
+
// If the worker knows which coordinator daemon launched it, only route to coordinators
|
|
1461
|
+
// on that specific daemon. This prevents cross-contamination when multiple coordinator
|
|
1462
|
+
// sessions run simultaneously for the same mesh on different daemons.
|
|
1463
|
+
if (workerCoordinatorDaemonId && localDaemonId && workerCoordinatorDaemonId !== localDaemonId) return false;
|
|
789
1464
|
return true;
|
|
790
1465
|
});
|
|
791
1466
|
|
|
1467
|
+
// Refine terminal events (refine:completed, refine:failed) are coordinator-delivered
|
|
1468
|
+
// synchronously; only buffer them for MCP when no CLI coordinator is present.
|
|
1469
|
+
// Agent runtime events (agent:*) use dual delivery so both CLI and MCP coordinators
|
|
1470
|
+
// receive them regardless of whether a live CLI coordinator session is active.
|
|
1471
|
+
const isRefineTerminalEvent = REFINE_TERMINAL_EVENTS.has(args.event);
|
|
1472
|
+
|
|
792
1473
|
if (coordinatorInstances.length === 0) {
|
|
793
|
-
// No CLI coordinator
|
|
1474
|
+
// No local CLI coordinator — buffer for MCP-based coordinator on the target daemon.
|
|
794
1475
|
if (queuePendingMeshCoordinatorEvent({
|
|
795
1476
|
event: args.event,
|
|
796
1477
|
meshId: args.meshId,
|
|
@@ -801,20 +1482,69 @@ function injectMeshSystemMessage(components: DaemonComponents, args: {
|
|
|
801
1482
|
...args.metadataEvent,
|
|
802
1483
|
...(recoveryContext ? { recoveryContext } : {}),
|
|
803
1484
|
},
|
|
1485
|
+
coordinatorMessage: messageText,
|
|
804
1486
|
queuedAt: Date.now(),
|
|
1487
|
+
// Scope to the coordinator daemon that launched this worker so drain
|
|
1488
|
+
// by other coordinators on the same daemon doesn't consume this event.
|
|
1489
|
+
...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
|
|
805
1490
|
})) {
|
|
806
|
-
LOG.info('MeshEvents', `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
|
|
1491
|
+
LOG.info('MeshEvents', `Queued ${args.event} for MCP coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''})`);
|
|
807
1492
|
}
|
|
808
1493
|
return { success: true, forwarded: 0 };
|
|
809
1494
|
}
|
|
810
1495
|
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1496
|
+
// CLI coordinator is present. For non-refine events, also buffer for MCP coordinators
|
|
1497
|
+
// that poll via get_pending_mesh_events (dual delivery). Refine terminal events are
|
|
1498
|
+
// forwarded directly only — they must not accumulate in the pending queue when a live
|
|
1499
|
+
// coordinator already received them.
|
|
1500
|
+
//
|
|
1501
|
+
// Exception: if ALL live CLI coordinator instances are in a generating/active state
|
|
1502
|
+
// when a refine terminal event fires (e.g. a Codex CLI coordinator that triggered an
|
|
1503
|
+
// async refine job and is still in the generating turn that sent it), the coordinator
|
|
1504
|
+
// cannot immediately receive send_message input. Buffer the event to the pending queue
|
|
1505
|
+
// so it is available via get_pending_mesh_events when the coordinator returns to idle.
|
|
1506
|
+
// Critically: do NOT attempt send_message injection into a generating PTY coordinator for
|
|
1507
|
+
// terminal refine events — injecting text into an active PTY can corrupt the input stream
|
|
1508
|
+
// and leave the coordinator stuck in generating state, unable to process the refine result.
|
|
1509
|
+
const allCoordinatorsGenerating = isRefineTerminalEvent && coordinatorInstances.every((inst) => {
|
|
1510
|
+
const s = inst.getState();
|
|
1511
|
+
const status = readNonEmptyString(s.status).toLowerCase();
|
|
1512
|
+
const activeChatStatus = readNonEmptyString(s.activeChat?.status).toLowerCase();
|
|
1513
|
+
return status === 'generating' || status === 'streaming' || status === 'long_generating'
|
|
1514
|
+
|| activeChatStatus === 'generating' || activeChatStatus === 'streaming';
|
|
816
1515
|
});
|
|
817
|
-
|
|
1516
|
+
|
|
1517
|
+
if (!isRefineTerminalEvent || allCoordinatorsGenerating) {
|
|
1518
|
+
if (queuePendingMeshCoordinatorEvent({
|
|
1519
|
+
event: args.event,
|
|
1520
|
+
meshId: args.meshId,
|
|
1521
|
+
nodeLabel: args.nodeLabel,
|
|
1522
|
+
nodeId: args.nodeId || undefined,
|
|
1523
|
+
workspace: readNonEmptyString(args.metadataEvent.workspace),
|
|
1524
|
+
metadataEvent: {
|
|
1525
|
+
...args.metadataEvent,
|
|
1526
|
+
...(recoveryContext ? { recoveryContext } : {}),
|
|
1527
|
+
},
|
|
1528
|
+
coordinatorMessage: messageText,
|
|
1529
|
+
queuedAt: Date.now(),
|
|
1530
|
+
...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
|
|
1531
|
+
})) {
|
|
1532
|
+
if (allCoordinatorsGenerating) {
|
|
1533
|
+
LOG.info('MeshEvents', `Queued ${args.event} for generating CLI coordinator (mesh ${args.meshId}) — will be delivered via get_pending_mesh_events when coordinator returns to idle`);
|
|
1534
|
+
} else {
|
|
1535
|
+
LOG.info('MeshEvents', `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// When all CLI coordinators are actively generating and a terminal refine event fires,
|
|
1541
|
+
// skip send_message injection entirely. The event is already buffered to the pending queue.
|
|
1542
|
+
// Injecting into a generating PTY coordinator can corrupt its input stream and cause it to
|
|
1543
|
+
// remain stuck in generating state, never processing the refine result.
|
|
1544
|
+
// The coordinator will drain pending events via get_pending_mesh_events on its next idle cycle.
|
|
1545
|
+
if (allCoordinatorsGenerating) {
|
|
1546
|
+
return { success: true, forwarded: 0, bufferedForGeneratingCoordinator: true };
|
|
1547
|
+
}
|
|
818
1548
|
|
|
819
1549
|
for (const coord of coordinatorInstances) {
|
|
820
1550
|
const coordState = coord.getState();
|
|
@@ -845,6 +1575,19 @@ export function handleMeshForwardEvent(components: DaemonComponents, payload: Re
|
|
|
845
1575
|
providerType: readNonEmptyString(payload.providerType),
|
|
846
1576
|
providerSessionId: readNonEmptyString(payload.providerSessionId),
|
|
847
1577
|
finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
|
|
1578
|
+
jobId: readNonEmptyString(payload.jobId),
|
|
1579
|
+
interactionId: readNonEmptyString(payload.interactionId),
|
|
1580
|
+
status: readNonEmptyString(payload.status),
|
|
1581
|
+
targetDaemonId: readNonEmptyString(payload.targetDaemonId),
|
|
1582
|
+
startedAt: readNonEmptyString(payload.startedAt),
|
|
1583
|
+
completedAt: readNonEmptyString(payload.completedAt),
|
|
1584
|
+
retryOfJobId: readNonEmptyString(payload.retryOfJobId),
|
|
1585
|
+
...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
|
|
1586
|
+
...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
|
|
1587
|
+
...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
|
|
1588
|
+
...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
|
|
1589
|
+
...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
|
|
1590
|
+
...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
|
|
848
1591
|
intentional: payload.intentional === true,
|
|
849
1592
|
intentionalStop: payload.intentionalStop === true,
|
|
850
1593
|
operatorCleanup: payload.operatorCleanup === true,
|
|
@@ -872,21 +1615,37 @@ export function setupMeshEventForwarding(components: DaemonComponents) {
|
|
|
872
1615
|
if (!workspace) return;
|
|
873
1616
|
const settings = state.settings && typeof state.settings === 'object' ? state.settings as Record<string, unknown> : {};
|
|
874
1617
|
|
|
875
|
-
// Coordinator sessions must
|
|
876
|
-
//
|
|
877
|
-
|
|
1618
|
+
// Coordinator sessions normally must not inject events into themselves, but a
|
|
1619
|
+
// coordinator session can also be the direct-dispatch target of mesh_send_task
|
|
1620
|
+
// issued by another coordinator (e.g. a remote orchestrator delegated a task to
|
|
1621
|
+
// this local coordinator). In that case the completion event must still flow into
|
|
1622
|
+
// injectMeshSystemMessage so the ledger records task_completed and the *other*
|
|
1623
|
+
// coordinator's pendingCoordinatorEvents queue is populated. Skip only when this
|
|
1624
|
+
// session is purely a coordinator with no in-flight direct dispatch waiting on it.
|
|
1625
|
+
const coordinatorMeshId = readNonEmptyString(settings.meshCoordinatorFor);
|
|
1626
|
+
let meshIdFromDirectDispatch = '';
|
|
1627
|
+
if (coordinatorMeshId) {
|
|
1628
|
+
try {
|
|
1629
|
+
const activeDispatches = getActiveDirectDispatches(coordinatorMeshId);
|
|
1630
|
+
if (activeDispatches.some(d => d.sessionId === instanceId)) {
|
|
1631
|
+
meshIdFromDirectDispatch = coordinatorMeshId;
|
|
1632
|
+
}
|
|
1633
|
+
} catch { /* best-effort */ }
|
|
1634
|
+
if (!meshIdFromDirectDispatch) return;
|
|
1635
|
+
}
|
|
878
1636
|
|
|
879
|
-
const meshIdFromRuntime = readNonEmptyString(settings.meshNodeFor);
|
|
1637
|
+
const meshIdFromRuntime = readNonEmptyString(settings.meshNodeFor) || meshIdFromDirectDispatch;
|
|
880
1638
|
|
|
881
1639
|
// Only forward events for sessions that were explicitly launched as mesh-node delegates
|
|
882
|
-
// (meshNodeFor set by mesh_launch_session)
|
|
1640
|
+
// (meshNodeFor set by mesh_launch_session), carry the launchedByCoordinator flag, or
|
|
1641
|
+
// have an active direct-dispatch entry (mesh_send_task to a pre-existing session).
|
|
883
1642
|
// Do NOT fall back to workspace-based mesh lookup: that would pick up coordinator sessions
|
|
884
1643
|
// and any other CLI session that happens to share the same workspace, causing spurious
|
|
885
1644
|
// system-message injection into the coordinator's own conversation.
|
|
886
1645
|
const isMeshDelegate = Boolean(meshIdFromRuntime || settings.launchedByCoordinator);
|
|
887
1646
|
if (!isMeshDelegate) return;
|
|
888
1647
|
|
|
889
|
-
const mesh = meshIdFromRuntime ? getMeshWithCache(components, meshIdFromRuntime) :
|
|
1648
|
+
const mesh = meshIdFromRuntime ? getMeshWithCache(components, meshIdFromRuntime) : getCachedMeshByWorkspace(workspace);
|
|
890
1649
|
const meshId = meshIdFromRuntime || readNonEmptyString(mesh?.id);
|
|
891
1650
|
if (!meshId) return;
|
|
892
1651
|
|