@clagentic/console 1.1.0 → 1.2.0-beta.1
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/lib/project-sessions.js
CHANGED
|
@@ -4,6 +4,7 @@ var { execFileSync } = require("child_process");
|
|
|
4
4
|
var { CODEX_DEFAULTS, getCodexConfig } = require("./codex-defaults");
|
|
5
5
|
var agentsModule = require("./agents");
|
|
6
6
|
var agentsFavorites = require("./agents-favorites");
|
|
7
|
+
var relayClaims = require("./relay-agent-claims");
|
|
7
8
|
|
|
8
9
|
// Kick off SDK agent discovery in the background at module load.
|
|
9
10
|
// Errors are swallowed inside refresh(); the cache starts empty and fills
|
|
@@ -159,6 +160,15 @@ function attachSessions(ctx) {
|
|
|
159
160
|
if (usersModule.isMultiUser()) {
|
|
160
161
|
broadcastPresence();
|
|
161
162
|
}
|
|
163
|
+
// Wire relay live-claim for named-agent sessions (lr-9cfc).
|
|
164
|
+
// Fire-and-forget; degrades silently when relay is absent.
|
|
165
|
+
if (newSess.agentName) {
|
|
166
|
+
(function (sessLocalId, agentName) {
|
|
167
|
+
relayClaims.attachAgentSession(newSess, agentName, function (obj) {
|
|
168
|
+
sendToSession(sessLocalId, obj);
|
|
169
|
+
});
|
|
170
|
+
})(newSess.localId, newSess.agentName);
|
|
171
|
+
}
|
|
162
172
|
return true;
|
|
163
173
|
}
|
|
164
174
|
|
|
@@ -218,12 +228,25 @@ function attachSessions(ctx) {
|
|
|
218
228
|
if (!usersModule.canAccessSession(ws._clayUser.id, agentTarget, { visibility: "public" })) return true;
|
|
219
229
|
}
|
|
220
230
|
var nextAgent = (msg.agentName && typeof msg.agentName === "string") ? msg.agentName : null;
|
|
231
|
+
var prevAgent = agentTarget.agentName || null;
|
|
221
232
|
agentTarget.agentName = nextAgent;
|
|
222
233
|
sm.saveSessionFile(agentTarget);
|
|
223
234
|
if (nextAgent) {
|
|
224
235
|
try { agentsFavorites.touchRecent({ name: nextAgent }); }
|
|
225
236
|
catch (e) { /* best-effort */ }
|
|
226
237
|
}
|
|
238
|
+
// Relay live-claim lifecycle for agent changes (lr-9cfc).
|
|
239
|
+
// Release old claims; attach for new agent if set.
|
|
240
|
+
if (prevAgent) {
|
|
241
|
+
relayClaims.detachAgentSession(agentTarget.localId);
|
|
242
|
+
}
|
|
243
|
+
if (nextAgent) {
|
|
244
|
+
(function (sessLocalId, agentName) {
|
|
245
|
+
relayClaims.attachAgentSession(agentTarget, agentName, function (obj) {
|
|
246
|
+
sendToSession(sessLocalId, obj);
|
|
247
|
+
});
|
|
248
|
+
})(agentTarget.localId, nextAgent);
|
|
249
|
+
}
|
|
227
250
|
sm.broadcastSessionList();
|
|
228
251
|
return true;
|
|
229
252
|
}
|
|
@@ -275,6 +298,13 @@ function attachSessions(ctx) {
|
|
|
275
298
|
deletableIds.push(bulkId);
|
|
276
299
|
}
|
|
277
300
|
if (deletableIds.length > 0) {
|
|
301
|
+
// Release relay claims for any agent sessions in the bulk-delete set (lr-9cfc).
|
|
302
|
+
for (var ri = 0; ri < deletableIds.length; ri++) {
|
|
303
|
+
var relayBulkSess = sm.sessions.get(deletableIds[ri]);
|
|
304
|
+
if (relayBulkSess && relayBulkSess.agentName) {
|
|
305
|
+
relayClaims.detachAgentSession(deletableIds[ri]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
278
308
|
sm.deleteSessionsBulk(deletableIds, ws);
|
|
279
309
|
}
|
|
280
310
|
return true;
|
|
@@ -466,6 +496,11 @@ function attachSessions(ctx) {
|
|
|
466
496
|
}
|
|
467
497
|
}
|
|
468
498
|
if (msg.id && sm.sessions.has(msg.id)) {
|
|
499
|
+
// Release relay claims for agent sessions before deletion (lr-9cfc).
|
|
500
|
+
var sdSess = sm.sessions.get(msg.id);
|
|
501
|
+
if (sdSess && sdSess.agentName) {
|
|
502
|
+
relayClaims.detachAgentSession(msg.id);
|
|
503
|
+
}
|
|
469
504
|
sm.deleteSession(msg.id, ws);
|
|
470
505
|
}
|
|
471
506
|
return true;
|
|
@@ -2,27 +2,15 @@ var _iconTimer = null;
|
|
|
2
2
|
var _iconTimerScoped = null;
|
|
3
3
|
|
|
4
4
|
// refreshIcons() — no scope: deferred full-document icon scan (one per frame)
|
|
5
|
-
// refreshIcons(el) — scoped:
|
|
6
|
-
//
|
|
5
|
+
// refreshIcons(el) — scoped: synchronous scan of el subtree only; also cancels
|
|
6
|
+
// any pending deferred scan since the sync pass covers the whole visible need.
|
|
7
7
|
export function refreshIcons(scope) {
|
|
8
8
|
if (scope) {
|
|
9
|
-
//
|
|
10
|
-
if (
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
_iconTimerScoped = null;
|
|
15
|
-
_iconTimer = requestAnimationFrame(function () {
|
|
16
|
-
_iconTimer = null;
|
|
17
|
-
lucide.createIcons();
|
|
18
|
-
});
|
|
19
|
-
return;
|
|
20
|
-
}
|
|
21
|
-
_iconTimerScoped = requestAnimationFrame(function () {
|
|
22
|
-
_iconTimerScoped = null;
|
|
23
|
-
// lucide.createIcons accepts { nodes } to limit scope
|
|
24
|
-
lucide.createIcons({ nodes: [scope] });
|
|
25
|
-
});
|
|
9
|
+
// Cancel any pending deferred scans — the synchronous pass below covers them.
|
|
10
|
+
if (_iconTimerScoped) { cancelAnimationFrame(_iconTimerScoped); _iconTimerScoped = null; }
|
|
11
|
+
if (_iconTimer) { cancelAnimationFrame(_iconTimer); _iconTimer = null; }
|
|
12
|
+
// Resolve icons immediately so no paint can occur with unresolved placeholders.
|
|
13
|
+
lucide.createIcons({ root: scope });
|
|
26
14
|
return;
|
|
27
15
|
}
|
|
28
16
|
// Full-document scan — cancel any pending scoped scan (redundant)
|
|
@@ -1324,6 +1324,10 @@ export function renderSessionList(sessions) {
|
|
|
1324
1324
|
stickyTop.appendChild(renderSessionTopActions());
|
|
1325
1325
|
stickyTop.appendChild(favoritesContainer);
|
|
1326
1326
|
stickyTop.appendChild(divider);
|
|
1327
|
+
// Resolve top-action icons synchronously before the first paint so they
|
|
1328
|
+
// never appear as blank placeholders. The deferred refreshIcons() at the
|
|
1329
|
+
// end of this function covers the rest of the list.
|
|
1330
|
+
lucide.createIcons({ root: stickyTop });
|
|
1327
1331
|
getSessionListEl().appendChild(stickyTop);
|
|
1328
1332
|
|
|
1329
1333
|
var currentGroup = "";
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
// relay-agent-claims.js — optional relay live-claim integration for UI-path agent sessions.
|
|
2
|
+
//
|
|
3
|
+
// When an operator opens a named-agent session via the clagentic-console Agents
|
|
4
|
+
// sidebar, the session gets a relay live claim so that inbound relay messages
|
|
5
|
+
// addressed to that agent route to this operator session instead of spawning a
|
|
6
|
+
// subprocess. (lr-9cfc)
|
|
7
|
+
//
|
|
8
|
+
// Design constraints:
|
|
9
|
+
// - clagentic-relay is OPTIONAL infrastructure. This module MUST degrade
|
|
10
|
+
// gracefully when the relay socket is absent. No error should surface to
|
|
11
|
+
// the operator when relay is not running.
|
|
12
|
+
// - All public functions are fire-and-forget or return Promises that never
|
|
13
|
+
// reject (errors are logged and swallowed). Callers must not await them
|
|
14
|
+
// for correctness.
|
|
15
|
+
// - No new external dependencies. Uses only Node.js built-ins: http, net, os, fs.
|
|
16
|
+
//
|
|
17
|
+
// Relay socket: CLAGENTIC_RELAY_SOCKET env > ~/.lore/relay.sock (same default
|
|
18
|
+
// as the clagentic CLI — conversation.go defaultSocketPath()).
|
|
19
|
+
//
|
|
20
|
+
// Wire shape: POST /conversations/live-claim/register|heartbeat|release
|
|
21
|
+
// Body: { conversation_id, participant, claim_id, [session_label], [force] }
|
|
22
|
+
// Response: { claim_id, heartbeat_ts, effective }
|
|
23
|
+
// All requests over HTTP/1.1 on the Unix domain socket, no TLS.
|
|
24
|
+
// Identity header: X-Relay-Caller-Lead: "andy" (operator bypass).
|
|
25
|
+
//
|
|
26
|
+
// Conversation list: read ~/.lore/conversation-sidecars/ directly (same as
|
|
27
|
+
// clagentic conversation list). No relay round-trip needed for listing — the
|
|
28
|
+
// sidecar files are written by the relay daemon and available on disk.
|
|
29
|
+
//
|
|
30
|
+
// Heartbeat: setInterval every HEARTBEAT_INTERVAL_MS. Relay claim TTL is 90s;
|
|
31
|
+
// we heartbeat every 30s to stay well within the window.
|
|
32
|
+
//
|
|
33
|
+
// Release: called on session deletion or agentName clear. Best-effort; the relay
|
|
34
|
+
// will expire the claim after TTL if release fails.
|
|
35
|
+
//
|
|
36
|
+
// lr-9cfc. Referenced: lr-ce19 (claim redesign), lr-aa68 (live-claim routing),
|
|
37
|
+
// tome #488 §2.4, tome #493.
|
|
38
|
+
|
|
39
|
+
var fs = require("fs");
|
|
40
|
+
var http = require("http");
|
|
41
|
+
var net = require("net");
|
|
42
|
+
var os = require("os");
|
|
43
|
+
var path = require("path");
|
|
44
|
+
var crypto = require("crypto");
|
|
45
|
+
|
|
46
|
+
var HEARTBEAT_INTERVAL_MS = 30 * 1000; // 30 seconds — relay TTL is 90s
|
|
47
|
+
var SOCKET_CONNECT_TIMEOUT_MS = 2000; // 2s timeout for connectivity check
|
|
48
|
+
var REQUEST_TIMEOUT_MS = 8000; // 8s max per relay call
|
|
49
|
+
|
|
50
|
+
// --- Relay socket path ---
|
|
51
|
+
|
|
52
|
+
function relaySocketPath() {
|
|
53
|
+
if (process.env.CLAGENTIC_RELAY_SOCKET) return process.env.CLAGENTIC_RELAY_SOCKET;
|
|
54
|
+
var home = os.homedir() || "/root";
|
|
55
|
+
return path.join(home, ".lore", "relay.sock");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// --- Low-level HTTP-over-UDS helpers ---
|
|
59
|
+
|
|
60
|
+
// Try a quick connect to the relay socket. Resolves true/false; never rejects.
|
|
61
|
+
function isRelayReachable() {
|
|
62
|
+
return new Promise(function (resolve) {
|
|
63
|
+
var sockPath = relaySocketPath();
|
|
64
|
+
var conn = net.createConnection({ path: sockPath });
|
|
65
|
+
var settled = false;
|
|
66
|
+
function done(ok) {
|
|
67
|
+
if (settled) return;
|
|
68
|
+
settled = true;
|
|
69
|
+
try { conn.destroy(); } catch (e) {}
|
|
70
|
+
resolve(ok);
|
|
71
|
+
}
|
|
72
|
+
var timer = setTimeout(function () { done(false); }, SOCKET_CONNECT_TIMEOUT_MS);
|
|
73
|
+
conn.on("connect", function () { clearTimeout(timer); done(true); });
|
|
74
|
+
conn.on("error", function () { clearTimeout(timer); done(false); });
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// POST JSON body to the relay, return parsed response body. Rejects on HTTP error
|
|
79
|
+
// or network failure. Callers wrap in try/catch.
|
|
80
|
+
function relayPost(urlPath, body) {
|
|
81
|
+
return new Promise(function (resolve, reject) {
|
|
82
|
+
var sockPath = relaySocketPath();
|
|
83
|
+
var data = JSON.stringify(body);
|
|
84
|
+
|
|
85
|
+
var opts = {
|
|
86
|
+
socketPath: sockPath,
|
|
87
|
+
method: "POST",
|
|
88
|
+
path: urlPath,
|
|
89
|
+
headers: {
|
|
90
|
+
"Content-Type": "application/json",
|
|
91
|
+
"Content-Length": Buffer.byteLength(data),
|
|
92
|
+
"X-Relay-Caller-Lead": "andy",
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
var req = http.request(opts, function (res) {
|
|
97
|
+
var chunks = [];
|
|
98
|
+
res.on("data", function (c) { chunks.push(c); });
|
|
99
|
+
res.on("end", function () {
|
|
100
|
+
var raw = Buffer.concat(chunks).toString("utf8");
|
|
101
|
+
if (res.statusCode !== 200) {
|
|
102
|
+
var msg = raw;
|
|
103
|
+
try {
|
|
104
|
+
var parsed = JSON.parse(raw);
|
|
105
|
+
if (parsed.message) msg = parsed.error + ": " + parsed.message;
|
|
106
|
+
} catch (e) {}
|
|
107
|
+
return reject(new Error("relay " + urlPath + " HTTP " + res.statusCode + ": " + msg));
|
|
108
|
+
}
|
|
109
|
+
try { resolve(JSON.parse(raw)); }
|
|
110
|
+
catch (e) { reject(new Error("relay " + urlPath + ": invalid JSON response")); }
|
|
111
|
+
});
|
|
112
|
+
res.on("error", reject);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
req.setTimeout(REQUEST_TIMEOUT_MS, function () {
|
|
116
|
+
req.destroy(new Error("relay " + urlPath + ": request timeout"));
|
|
117
|
+
});
|
|
118
|
+
req.on("error", reject);
|
|
119
|
+
req.write(data);
|
|
120
|
+
req.end();
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// --- Sidecar-based conversation listing (mirrors clagentic conversation list) ---
|
|
125
|
+
//
|
|
126
|
+
// The relay writes a JSON sidecar for each conversation at:
|
|
127
|
+
// ~/.lore/conversation-sidecars/<conv_id>.json
|
|
128
|
+
// Each sidecar has: conversation_id, topic, kind, status, opened_by,
|
|
129
|
+
// participants[{name, role}], message_count, last_seq, opened_at.
|
|
130
|
+
//
|
|
131
|
+
// We read these directly — no relay round-trip needed.
|
|
132
|
+
|
|
133
|
+
function loreHomeDir() {
|
|
134
|
+
var home = os.homedir() || "/root";
|
|
135
|
+
return path.join(home, ".lore");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Returns array of sidecar objects for open conversations where agentName is
|
|
139
|
+
// a participant. Returns [] on any error (relay absent, dir missing, etc.).
|
|
140
|
+
function listOpenConversationsForAgent(agentName) {
|
|
141
|
+
var sidecarDir = path.join(loreHomeDir(), "conversation-sidecars");
|
|
142
|
+
try {
|
|
143
|
+
var entries = fs.readdirSync(sidecarDir);
|
|
144
|
+
var results = [];
|
|
145
|
+
for (var i = 0; i < entries.length; i++) {
|
|
146
|
+
var name = entries[i];
|
|
147
|
+
if (!name.endsWith(".json")) continue;
|
|
148
|
+
var fullPath = path.join(sidecarDir, name);
|
|
149
|
+
var raw;
|
|
150
|
+
try { raw = fs.readFileSync(fullPath, "utf8"); } catch (e) { continue; }
|
|
151
|
+
var obj;
|
|
152
|
+
try { obj = JSON.parse(raw); } catch (e) { continue; }
|
|
153
|
+
if (!obj || typeof obj !== "object") continue;
|
|
154
|
+
if (obj.status !== "open") continue;
|
|
155
|
+
var participants = Array.isArray(obj.participants) ? obj.participants : [];
|
|
156
|
+
var isParticipant = participants.some(function (p) { return p && p.name === agentName; });
|
|
157
|
+
if (!isParticipant) continue;
|
|
158
|
+
results.push(obj);
|
|
159
|
+
}
|
|
160
|
+
return results;
|
|
161
|
+
} catch (e) {
|
|
162
|
+
// Directory missing (relay never ran) or any other error — return empty.
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// --- Per-session claim state ---
|
|
168
|
+
//
|
|
169
|
+
// Map from session.localId -> { agentName, claims: Map<convId, claimId>, timer }
|
|
170
|
+
// where timer is the heartbeat setInterval handle.
|
|
171
|
+
|
|
172
|
+
var _sessionClaims = new Map(); // localId -> { agentName, claims, timer }
|
|
173
|
+
|
|
174
|
+
// Generate a UUID for use as claimId. Uses crypto.randomUUID if available
|
|
175
|
+
// (Node 14.17+), falls back to a hex blob.
|
|
176
|
+
function generateClaimId() {
|
|
177
|
+
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
178
|
+
return crypto.randomBytes(16).toString("hex");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Register a single live claim for agentName on convId. Resolves with claim_id
|
|
182
|
+
// or null on failure. Never rejects.
|
|
183
|
+
function registerClaim(agentName, convId, sessionLabel) {
|
|
184
|
+
var claimId = generateClaimId();
|
|
185
|
+
var body = {
|
|
186
|
+
conversation_id: convId,
|
|
187
|
+
participant: agentName,
|
|
188
|
+
claim_id: claimId,
|
|
189
|
+
};
|
|
190
|
+
if (sessionLabel) body.session_label = sessionLabel;
|
|
191
|
+
|
|
192
|
+
return relayPost("/conversations/live-claim/register", body).then(function (resp) {
|
|
193
|
+
if (resp && resp.effective) {
|
|
194
|
+
return resp.claim_id || claimId;
|
|
195
|
+
}
|
|
196
|
+
// effective=false means claim was superseded — not an error for us; return
|
|
197
|
+
// the claim_id anyway (we may get heartbeat rejections later and handle then).
|
|
198
|
+
return resp && resp.claim_id ? resp.claim_id : claimId;
|
|
199
|
+
}).catch(function (e) {
|
|
200
|
+
// 409 claim-already-held: another session holds this claim. Log and skip.
|
|
201
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
202
|
+
if (msg.indexOf("claim-already-held") !== -1) {
|
|
203
|
+
console.log("[relay-agent-claims] claim already held for " + agentName + " on " + convId + " — skip (use --force to supersede)");
|
|
204
|
+
} else {
|
|
205
|
+
console.warn("[relay-agent-claims] register failed for " + agentName + " on " + convId + ":", msg);
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Send a heartbeat for an existing claim. Resolves true if effective, false if
|
|
212
|
+
// superseded. Never rejects.
|
|
213
|
+
function heartbeatClaim(agentName, convId, claimId) {
|
|
214
|
+
return relayPost("/conversations/live-claim/heartbeat", {
|
|
215
|
+
conversation_id: convId,
|
|
216
|
+
participant: agentName,
|
|
217
|
+
claim_id: claimId,
|
|
218
|
+
}).then(function (resp) {
|
|
219
|
+
return !!(resp && resp.effective);
|
|
220
|
+
}).catch(function (e) {
|
|
221
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
222
|
+
console.warn("[relay-agent-claims] heartbeat failed for " + agentName + " on " + convId + ":", msg);
|
|
223
|
+
return false;
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Release a live claim. Best-effort; never rejects, never throws.
|
|
228
|
+
function releaseClaim(agentName, convId, claimId) {
|
|
229
|
+
return relayPost("/conversations/live-claim/release", {
|
|
230
|
+
conversation_id: convId,
|
|
231
|
+
participant: agentName,
|
|
232
|
+
claim_id: claimId,
|
|
233
|
+
}).then(function () {
|
|
234
|
+
// success
|
|
235
|
+
}).catch(function (e) {
|
|
236
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
237
|
+
console.warn("[relay-agent-claims] release failed for " + agentName + " on " + convId + ":", msg);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Start the 30s heartbeat loop for a session's claims. Restores claims after
|
|
242
|
+
// relay restart by re-registering when heartbeat returns effective=false.
|
|
243
|
+
function startHeartbeatLoop(localId) {
|
|
244
|
+
var state = _sessionClaims.get(localId);
|
|
245
|
+
if (!state) return;
|
|
246
|
+
if (state.timer) return; // already running
|
|
247
|
+
|
|
248
|
+
var timer = setInterval(function () {
|
|
249
|
+
var st = _sessionClaims.get(localId);
|
|
250
|
+
if (!st) {
|
|
251
|
+
clearInterval(timer);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
var convIds = Array.from(st.claims.keys());
|
|
255
|
+
for (var i = 0; i < convIds.length; i++) {
|
|
256
|
+
(function (convId) {
|
|
257
|
+
var claimId = st.claims.get(convId);
|
|
258
|
+
if (!claimId) return;
|
|
259
|
+
heartbeatClaim(st.agentName, convId, claimId).then(function (effective) {
|
|
260
|
+
if (effective) return; // still alive
|
|
261
|
+
// Superseded or expired — attempt re-register.
|
|
262
|
+
var sessState = _sessionClaims.get(localId);
|
|
263
|
+
if (!sessState) return;
|
|
264
|
+
registerClaim(st.agentName, convId, "console-reregister").then(function (newId) {
|
|
265
|
+
var s2 = _sessionClaims.get(localId);
|
|
266
|
+
if (!s2 || !newId) return;
|
|
267
|
+
s2.claims.set(convId, newId);
|
|
268
|
+
console.log("[relay-agent-claims] re-registered claim for " + st.agentName + " on " + convId);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
})(convIds[i]);
|
|
272
|
+
}
|
|
273
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
274
|
+
|
|
275
|
+
state.timer = timer;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// --- Public API ---
|
|
279
|
+
|
|
280
|
+
// Called when a new session is opened with agentName set.
|
|
281
|
+
// 1. Checks relay reachability; if absent, returns immediately (no-op).
|
|
282
|
+
// 2. Lists open conversations for agentName from sidecars.
|
|
283
|
+
// 3. For each open conv: registers a live claim (catches 409 silently).
|
|
284
|
+
// 4. Starts heartbeat loop.
|
|
285
|
+
// 5. Surfaces open conv list to operator via sendToSessionFn (system message).
|
|
286
|
+
// Does NOT auto-claim new conversations here — that is handled by onNewConversation.
|
|
287
|
+
//
|
|
288
|
+
// sendToSessionFn: function(obj) — sends to all clients viewing this session.
|
|
289
|
+
//
|
|
290
|
+
// Returns immediately; all relay calls are async and non-blocking.
|
|
291
|
+
function attachAgentSession(session, agentName, sendToSessionFn) {
|
|
292
|
+
if (!agentName || typeof agentName !== "string") return;
|
|
293
|
+
var localId = session.localId;
|
|
294
|
+
|
|
295
|
+
// Initialize state entry.
|
|
296
|
+
_sessionClaims.set(localId, {
|
|
297
|
+
agentName: agentName,
|
|
298
|
+
claims: new Map(),
|
|
299
|
+
timer: null,
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
isRelayReachable().then(function (reachable) {
|
|
303
|
+
if (!reachable) {
|
|
304
|
+
// Relay not running — clean up and exit silently.
|
|
305
|
+
_sessionClaims.delete(localId);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
var state = _sessionClaims.get(localId);
|
|
310
|
+
if (!state) return; // session already deleted
|
|
311
|
+
|
|
312
|
+
// List open conversations for this agent.
|
|
313
|
+
var openConvs = listOpenConversationsForAgent(agentName);
|
|
314
|
+
|
|
315
|
+
// Surface open conversations to operator (display-only, per task spec).
|
|
316
|
+
if (openConvs.length > 0 && typeof sendToSessionFn === "function") {
|
|
317
|
+
var lines = ["Open conversations where " + agentName + " is a participant:"];
|
|
318
|
+
for (var k = 0; k < openConvs.length; k++) {
|
|
319
|
+
var c = openConvs[k];
|
|
320
|
+
var short = (c.conversation_id || "").substring(0, 8);
|
|
321
|
+
lines.push(" " + short + " [" + (c.kind || "?") + "] " + (c.topic || "(no topic)") + " (msgs: " + (c.message_count || 0) + ")");
|
|
322
|
+
}
|
|
323
|
+
lines.push("To claim: clagentic claim register --conv <id> --participant " + agentName);
|
|
324
|
+
sendToSessionFn({
|
|
325
|
+
type: "system_message",
|
|
326
|
+
text: lines.join("\n"),
|
|
327
|
+
role: "system",
|
|
328
|
+
_ts: Date.now(),
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Register a live claim for each open conversation.
|
|
333
|
+
var sessionLabel = "console-ui-" + agentName + "-" + Date.now();
|
|
334
|
+
var registerPromises = openConvs.map(function (c) {
|
|
335
|
+
var convId = c.conversation_id;
|
|
336
|
+
if (!convId) return Promise.resolve();
|
|
337
|
+
return registerClaim(agentName, convId, sessionLabel).then(function (claimId) {
|
|
338
|
+
if (!claimId) return;
|
|
339
|
+
var s = _sessionClaims.get(localId);
|
|
340
|
+
if (!s) return;
|
|
341
|
+
s.claims.set(convId, claimId);
|
|
342
|
+
console.log("[relay-agent-claims] claimed conv " + convId.substring(0, 8) + " for session " + localId + " (" + agentName + ")");
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
Promise.all(registerPromises).then(function () {
|
|
347
|
+
var s = _sessionClaims.get(localId);
|
|
348
|
+
if (!s) return;
|
|
349
|
+
// Start heartbeat loop (even if no claims yet — new convs may be added).
|
|
350
|
+
startHeartbeatLoop(localId);
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Called when a new conversation is opened where agentName is a participant
|
|
356
|
+
// AND this agent has an active UI session. Auto-registers a live claim without
|
|
357
|
+
// prompting the operator (new convs only — not pre-existing, per lr-9cfc spec).
|
|
358
|
+
//
|
|
359
|
+
// convId: the newly-opened conversation ID.
|
|
360
|
+
// agentName: the participant name (must match the session's agentName).
|
|
361
|
+
// localId: the session's localId.
|
|
362
|
+
//
|
|
363
|
+
// Returns a Promise that resolves with the claim_id or null. Never rejects.
|
|
364
|
+
function onNewConversation(localId, agentName, convId) {
|
|
365
|
+
var state = _sessionClaims.get(localId);
|
|
366
|
+
if (!state || state.agentName !== agentName) return Promise.resolve(null);
|
|
367
|
+
if (!convId) return Promise.resolve(null);
|
|
368
|
+
if (state.claims.has(convId)) return Promise.resolve(state.claims.get(convId));
|
|
369
|
+
|
|
370
|
+
var sessionLabel = "console-ui-new-" + agentName + "-" + Date.now();
|
|
371
|
+
return registerClaim(agentName, convId, sessionLabel).then(function (claimId) {
|
|
372
|
+
if (!claimId) return null;
|
|
373
|
+
var s = _sessionClaims.get(localId);
|
|
374
|
+
if (!s) return null;
|
|
375
|
+
s.claims.set(convId, claimId);
|
|
376
|
+
console.log("[relay-agent-claims] auto-claimed new conv " + convId.substring(0, 8) + " for session " + localId + " (" + agentName + ")");
|
|
377
|
+
return claimId;
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Called when a session is deleted or its agentName is cleared.
|
|
382
|
+
// Releases all live claims and stops the heartbeat loop.
|
|
383
|
+
// Best-effort — never throws.
|
|
384
|
+
function detachAgentSession(localId) {
|
|
385
|
+
var state = _sessionClaims.get(localId);
|
|
386
|
+
if (!state) return;
|
|
387
|
+
|
|
388
|
+
// Stop heartbeat loop.
|
|
389
|
+
if (state.timer) {
|
|
390
|
+
clearInterval(state.timer);
|
|
391
|
+
state.timer = null;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Release all claims (best-effort, async).
|
|
395
|
+
var agentName = state.agentName;
|
|
396
|
+
var entries = Array.from(state.claims.entries());
|
|
397
|
+
_sessionClaims.delete(localId);
|
|
398
|
+
|
|
399
|
+
for (var i = 0; i < entries.length; i++) {
|
|
400
|
+
(function (convId, claimId) {
|
|
401
|
+
releaseClaim(agentName, convId, claimId).then(function () {
|
|
402
|
+
console.log("[relay-agent-claims] released claim for " + agentName + " on " + convId.substring(0, 8));
|
|
403
|
+
});
|
|
404
|
+
})(entries[i][0], entries[i][1]);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Returns true if this session has an active relay claim state (relay was
|
|
409
|
+
// reachable when the session was attached).
|
|
410
|
+
function hasClaimState(localId) {
|
|
411
|
+
return _sessionClaims.has(localId);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Exported for testing: get the current claims for a session.
|
|
415
|
+
function getClaimsForSession(localId) {
|
|
416
|
+
var state = _sessionClaims.get(localId);
|
|
417
|
+
if (!state) return null;
|
|
418
|
+
return { agentName: state.agentName, claims: Object.fromEntries(state.claims) };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
module.exports = {
|
|
422
|
+
attachAgentSession: attachAgentSession,
|
|
423
|
+
detachAgentSession: detachAgentSession,
|
|
424
|
+
onNewConversation: onNewConversation,
|
|
425
|
+
hasClaimState: hasClaimState,
|
|
426
|
+
getClaimsForSession: getClaimsForSession,
|
|
427
|
+
// exported for tests
|
|
428
|
+
listOpenConversationsForAgent: listOpenConversationsForAgent,
|
|
429
|
+
isRelayReachable: isRelayReachable,
|
|
430
|
+
};
|
package/lib/sdk-bridge.js
CHANGED
|
@@ -884,6 +884,19 @@ function createSDKBridge(opts) {
|
|
|
884
884
|
} catch (e) {}
|
|
885
885
|
session.queryInstance = null;
|
|
886
886
|
}
|
|
887
|
+
// lr-b61b: In the in-process path, close() ends the messageQueue but the
|
|
888
|
+
// underlying claude child process may survive in epoll_wait on its stdin
|
|
889
|
+
// socket. Aborting via the AbortController signals the SDK to terminate
|
|
890
|
+
// the child process. We always abort our own controller — even if the
|
|
891
|
+
// session.abortController reference was already replaced by a newer query
|
|
892
|
+
// (e.g. after a rewind), myAbortController is our local capture and
|
|
893
|
+
// aborting it only affects this query's child, not the newer one.
|
|
894
|
+
if (myAbortController && typeof myAbortController.abort === "function") {
|
|
895
|
+
try {
|
|
896
|
+
myAbortController.abort();
|
|
897
|
+
console.log("[sdk-bridge] processQueryStream finally: aborted AbortController for session " + session.localId);
|
|
898
|
+
} catch (e) {}
|
|
899
|
+
}
|
|
887
900
|
session.messageQueue = null;
|
|
888
901
|
if (session.abortController === myAbortController) session.abortController = null;
|
|
889
902
|
session.taskStopRequested = false;
|
|
@@ -1343,6 +1356,18 @@ function createSDKBridge(opts) {
|
|
|
1343
1356
|
// Push initial user message through the QueryHandle
|
|
1344
1357
|
console.log("[sdk-bridge] pushing initial message via handle.pushMessage...");
|
|
1345
1358
|
handle.pushMessage(text, images);
|
|
1359
|
+
|
|
1360
|
+
// lr-b61b: Flush any messages that arrived between turns (after the previous
|
|
1361
|
+
// finally block nulled queryInstance and before this startQuery call).
|
|
1362
|
+
if (session.pendingMessages && session.pendingMessages.length > 0) {
|
|
1363
|
+
console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for session " + session.localId);
|
|
1364
|
+
for (var pi = 0; pi < session.pendingMessages.length; pi++) {
|
|
1365
|
+
var pm = session.pendingMessages[pi];
|
|
1366
|
+
handle.pushMessage(pm.text, pm.images);
|
|
1367
|
+
}
|
|
1368
|
+
session.pendingMessages = [];
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1346
1371
|
console.log("[sdk-bridge] pushMessage done, starting processQueryStream...");
|
|
1347
1372
|
|
|
1348
1373
|
// For single-turn sessions (Ralph Loop), end the message queue so the SDK
|
|
@@ -1366,6 +1391,13 @@ function createSDKBridge(opts) {
|
|
|
1366
1391
|
// Route through QueryHandle (works for both in-process and worker paths)
|
|
1367
1392
|
if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
|
|
1368
1393
|
session.queryInstance.pushMessage(text, images);
|
|
1394
|
+
} else {
|
|
1395
|
+
// lr-b61b: queryInstance is null between turns (finally block has run but
|
|
1396
|
+
// startQuery has not been called yet). Buffer the message so it is not
|
|
1397
|
+
// silently dropped; startQuery will flush it after the handle is created.
|
|
1398
|
+
if (!session.pendingMessages) session.pendingMessages = [];
|
|
1399
|
+
session.pendingMessages.push({ text: text, images: images });
|
|
1400
|
+
console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
|
|
1369
1401
|
}
|
|
1370
1402
|
}
|
|
1371
1403
|
|
package/package.json
CHANGED