@clagentic/console 1.1.1-beta.1 → 1.2.0-beta.2
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/agents.js +47 -0
- package/lib/project-sessions.js +35 -0
- package/lib/relay-agent-claims.js +480 -0
- package/lib/sdk-bridge.js +12 -0
- package/package.json +1 -1
package/lib/agents.js
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
//
|
|
27
27
|
// This implementation lives only on our fork; we are not pushing it upstream.
|
|
28
28
|
|
|
29
|
+
var fs = require("fs");
|
|
29
30
|
var path = require("path");
|
|
30
31
|
var os = require("os");
|
|
31
32
|
|
|
@@ -79,6 +80,51 @@ function slugifyAgentName(name) {
|
|
|
79
80
|
.slice(0, 64);
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
// lr-4c90 — Read the tools list for a named agent directly from its on-disk
|
|
84
|
+
// frontmatter. The SDK AgentInfo surface (supportedAgents()) does not expose
|
|
85
|
+
// the tools field — only name, description, and model are returned. Reading
|
|
86
|
+
// the file directly is the only synchronous path for belt-and-suspenders
|
|
87
|
+
// enforcement in the query setup path.
|
|
88
|
+
//
|
|
89
|
+
// agentName: the agent identity string (e.g. "agentic-director").
|
|
90
|
+
// Returns: string[] of tool names if the tools field is a valid JSON array,
|
|
91
|
+
// null if the file is absent, the frontmatter is missing, or the
|
|
92
|
+
// tools field cannot be parsed.
|
|
93
|
+
//
|
|
94
|
+
// Failures are silent (logged at debug level) — callers treat null as "no
|
|
95
|
+
// restriction from this source" and fall through to whatever the SDK applies
|
|
96
|
+
// via claudeOpts.agent.
|
|
97
|
+
function readAgentToolsFromFile(agentName) {
|
|
98
|
+
if (!agentName || typeof agentName !== "string") return null;
|
|
99
|
+
var slug = slugifyAgentName(agentName);
|
|
100
|
+
if (!slug) return null;
|
|
101
|
+
var filePath = path.join(AGENTS_SOURCE_DIR, slug + ".md");
|
|
102
|
+
var raw;
|
|
103
|
+
try {
|
|
104
|
+
raw = fs.readFileSync(filePath, "utf8");
|
|
105
|
+
} catch (e) {
|
|
106
|
+
// File not found is expected for agents with no on-disk definition.
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
var parsed = parseFrontmatter(raw);
|
|
110
|
+
if (!parsed || !parsed.meta) return null;
|
|
111
|
+
var toolsVal = parsed.meta.tools;
|
|
112
|
+
if (!toolsVal || typeof toolsVal !== "string") return null;
|
|
113
|
+
var trimmed = toolsVal.trim();
|
|
114
|
+
if (trimmed.charAt(0) !== "[") return null; // not a JSON array — skip
|
|
115
|
+
try {
|
|
116
|
+
var arr = JSON.parse(trimmed);
|
|
117
|
+
if (!Array.isArray(arr)) return null;
|
|
118
|
+
var result = [];
|
|
119
|
+
for (var i = 0; i < arr.length; i++) {
|
|
120
|
+
if (typeof arr[i] === "string" && arr[i]) result.push(arr[i]);
|
|
121
|
+
}
|
|
122
|
+
return result.length > 0 ? result : null;
|
|
123
|
+
} catch (e) {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
82
128
|
// --- SDK-backed discovery cache ---
|
|
83
129
|
|
|
84
130
|
// Module-level cache. Populated by refresh(); read by getAll().
|
|
@@ -182,6 +228,7 @@ module.exports = {
|
|
|
182
228
|
PLUGINS_CACHE_DIR: PLUGINS_CACHE_DIR,
|
|
183
229
|
parseFrontmatter: parseFrontmatter,
|
|
184
230
|
slugifyAgentName: slugifyAgentName,
|
|
231
|
+
readAgentToolsFromFile: readAgentToolsFromFile,
|
|
185
232
|
// New SDK-backed surface:
|
|
186
233
|
refresh: refresh,
|
|
187
234
|
getAll: getAll,
|
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;
|
|
@@ -0,0 +1,480 @@
|
|
|
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 sourced from CLAGENTIC_OPERATOR_LEAD env
|
|
25
|
+
// (set by per-installation config). Falls back to empty string — relay treats
|
|
26
|
+
// an absent header as anonymous operator access, which is safe for UI-path sessions.
|
|
27
|
+
//
|
|
28
|
+
// Conversation list: read ~/.lore/conversation-sidecars/ directly (same as
|
|
29
|
+
// clagentic conversation list). No relay round-trip needed for listing — the
|
|
30
|
+
// sidecar files are written by the relay daemon and available on disk.
|
|
31
|
+
//
|
|
32
|
+
// Heartbeat: setInterval every HEARTBEAT_INTERVAL_MS. Relay claim TTL is 90s;
|
|
33
|
+
// we heartbeat every 30s to stay well within the window.
|
|
34
|
+
//
|
|
35
|
+
// Release: called on session deletion or agentName clear. Best-effort; the relay
|
|
36
|
+
// will expire the claim after TTL if release fails.
|
|
37
|
+
//
|
|
38
|
+
// lr-9cfc. Referenced: lr-ce19 (claim redesign), lr-aa68 (live-claim routing),
|
|
39
|
+
// tome #488 §2.4, tome #493.
|
|
40
|
+
|
|
41
|
+
var fs = require("fs");
|
|
42
|
+
var http = require("http");
|
|
43
|
+
var net = require("net");
|
|
44
|
+
var os = require("os");
|
|
45
|
+
var path = require("path");
|
|
46
|
+
var crypto = require("crypto");
|
|
47
|
+
|
|
48
|
+
var HEARTBEAT_INTERVAL_MS = 30 * 1000; // 30 seconds — relay TTL is 90s
|
|
49
|
+
var SOCKET_CONNECT_TIMEOUT_MS = 2000; // 2s timeout for connectivity check
|
|
50
|
+
var REQUEST_TIMEOUT_MS = 8000; // 8s max per relay call
|
|
51
|
+
|
|
52
|
+
// --- Relay socket path ---
|
|
53
|
+
|
|
54
|
+
function relaySocketPath() {
|
|
55
|
+
if (process.env.CLAGENTIC_RELAY_SOCKET) return process.env.CLAGENTIC_RELAY_SOCKET;
|
|
56
|
+
var home = os.homedir();
|
|
57
|
+
return path.join(home, ".lore", "relay.sock");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// --- Low-level HTTP-over-UDS helpers ---
|
|
61
|
+
|
|
62
|
+
// Try a quick connect to the relay socket. Resolves true/false; never rejects.
|
|
63
|
+
function isRelayReachable() {
|
|
64
|
+
return new Promise(function (resolve) {
|
|
65
|
+
var sockPath = relaySocketPath();
|
|
66
|
+
var conn = net.createConnection({ path: sockPath });
|
|
67
|
+
var settled = false;
|
|
68
|
+
function done(ok) {
|
|
69
|
+
if (settled) return;
|
|
70
|
+
settled = true;
|
|
71
|
+
try { conn.destroy(); } catch (e) {}
|
|
72
|
+
resolve(ok);
|
|
73
|
+
}
|
|
74
|
+
var timer = setTimeout(function () { done(false); }, SOCKET_CONNECT_TIMEOUT_MS);
|
|
75
|
+
conn.on("connect", function () { clearTimeout(timer); done(true); });
|
|
76
|
+
conn.on("error", function () { clearTimeout(timer); done(false); });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// POST JSON body to the relay, return parsed response body. Rejects on HTTP error
|
|
81
|
+
// or network failure. Callers wrap in try/catch.
|
|
82
|
+
function relayPost(urlPath, body) {
|
|
83
|
+
return new Promise(function (resolve, reject) {
|
|
84
|
+
var sockPath = relaySocketPath();
|
|
85
|
+
var data = JSON.stringify(body);
|
|
86
|
+
|
|
87
|
+
var opts = {
|
|
88
|
+
socketPath: sockPath,
|
|
89
|
+
method: "POST",
|
|
90
|
+
path: urlPath,
|
|
91
|
+
headers: {
|
|
92
|
+
"Content-Type": "application/json",
|
|
93
|
+
"Content-Length": Buffer.byteLength(data),
|
|
94
|
+
"X-Relay-Caller-Lead": process.env.CLAGENTIC_OPERATOR_LEAD || "",
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
var req = http.request(opts, function (res) {
|
|
99
|
+
var chunks = [];
|
|
100
|
+
res.on("data", function (c) { chunks.push(c); });
|
|
101
|
+
res.on("end", function () {
|
|
102
|
+
var raw = Buffer.concat(chunks).toString("utf8");
|
|
103
|
+
if (res.statusCode !== 200) {
|
|
104
|
+
var msg = raw;
|
|
105
|
+
try {
|
|
106
|
+
var parsed = JSON.parse(raw);
|
|
107
|
+
if (parsed.message) msg = (parsed.error ? parsed.error + ": " : "") + parsed.message;
|
|
108
|
+
} catch (e) {}
|
|
109
|
+
return reject(new Error("relay " + urlPath + " HTTP " + res.statusCode + ": " + msg));
|
|
110
|
+
}
|
|
111
|
+
try { resolve(JSON.parse(raw)); }
|
|
112
|
+
catch (e) { reject(new Error("relay " + urlPath + ": invalid JSON response")); }
|
|
113
|
+
});
|
|
114
|
+
res.on("error", reject);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
req.setTimeout(REQUEST_TIMEOUT_MS, function () {
|
|
118
|
+
req.destroy(new Error("relay " + urlPath + ": request timeout"));
|
|
119
|
+
});
|
|
120
|
+
req.on("error", reject);
|
|
121
|
+
req.write(data);
|
|
122
|
+
req.end();
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// --- Sidecar-based conversation listing (mirrors clagentic conversation list) ---
|
|
127
|
+
//
|
|
128
|
+
// The relay writes a JSON sidecar for each conversation at:
|
|
129
|
+
// ~/.lore/conversation-sidecars/<conv_id>.json
|
|
130
|
+
// Each sidecar has: conversation_id, topic, kind, status, opened_by,
|
|
131
|
+
// participants[{name, role}], message_count, last_seq, opened_at.
|
|
132
|
+
//
|
|
133
|
+
// We read these directly — no relay round-trip needed.
|
|
134
|
+
|
|
135
|
+
function loreHomeDir() {
|
|
136
|
+
var home = os.homedir();
|
|
137
|
+
return path.join(home, ".lore");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Returns array of sidecar objects for open conversations where agentName is
|
|
141
|
+
// a participant. Returns [] on any error (relay absent, dir missing, etc.).
|
|
142
|
+
function listOpenConversationsForAgent(agentName) {
|
|
143
|
+
var sidecarDir = path.join(loreHomeDir(), "conversation-sidecars");
|
|
144
|
+
try {
|
|
145
|
+
var entries = fs.readdirSync(sidecarDir);
|
|
146
|
+
var results = [];
|
|
147
|
+
for (var i = 0; i < entries.length; i++) {
|
|
148
|
+
var name = entries[i];
|
|
149
|
+
if (!name.endsWith(".json")) continue;
|
|
150
|
+
var fullPath = path.join(sidecarDir, name);
|
|
151
|
+
var raw;
|
|
152
|
+
try { raw = fs.readFileSync(fullPath, "utf8"); } catch (e) { continue; }
|
|
153
|
+
var obj;
|
|
154
|
+
try { obj = JSON.parse(raw); } catch (e) { continue; }
|
|
155
|
+
if (!obj || typeof obj !== "object") continue;
|
|
156
|
+
if (obj.status !== "open") continue;
|
|
157
|
+
var participants = Array.isArray(obj.participants) ? obj.participants : [];
|
|
158
|
+
var isParticipant = participants.some(function (p) { return p && p.name === agentName; });
|
|
159
|
+
if (!isParticipant) continue;
|
|
160
|
+
results.push(obj);
|
|
161
|
+
}
|
|
162
|
+
return results;
|
|
163
|
+
} catch (e) {
|
|
164
|
+
// Directory missing (relay never ran) or any other error — return empty.
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// --- Per-session claim state ---
|
|
170
|
+
//
|
|
171
|
+
// Map from session.localId -> { agentName, claims: Map<convId, claimId>, timer, watcher }
|
|
172
|
+
// where timer is the heartbeat setInterval handle and watcher is the fs.watch
|
|
173
|
+
// handle for the sidecar directory (stops on detach).
|
|
174
|
+
|
|
175
|
+
var _sessionClaims = new Map(); // localId -> { agentName, claims, timer, watcher }
|
|
176
|
+
|
|
177
|
+
// Generate a UUID for use as claimId. Uses crypto.randomUUID if available
|
|
178
|
+
// (Node 14.17+), falls back to a hex blob.
|
|
179
|
+
function generateClaimId() {
|
|
180
|
+
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
181
|
+
return crypto.randomBytes(16).toString("hex");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Register a single live claim for agentName on convId. Resolves with claim_id
|
|
185
|
+
// or null on failure. Never rejects.
|
|
186
|
+
function registerClaim(agentName, convId, sessionLabel) {
|
|
187
|
+
var claimId = generateClaimId();
|
|
188
|
+
var body = {
|
|
189
|
+
conversation_id: convId,
|
|
190
|
+
participant: agentName,
|
|
191
|
+
claim_id: claimId,
|
|
192
|
+
};
|
|
193
|
+
if (sessionLabel) body.session_label = sessionLabel;
|
|
194
|
+
|
|
195
|
+
return relayPost("/conversations/live-claim/register", body).then(function (resp) {
|
|
196
|
+
if (resp && resp.effective) {
|
|
197
|
+
return resp.claim_id || claimId;
|
|
198
|
+
}
|
|
199
|
+
// effective=false means claim was superseded — not an error for us; return
|
|
200
|
+
// the claim_id anyway (we may get heartbeat rejections later and handle then).
|
|
201
|
+
return resp && resp.claim_id ? resp.claim_id : claimId;
|
|
202
|
+
}).catch(function (e) {
|
|
203
|
+
// 409 claim-already-held: another session holds this claim. Log and skip.
|
|
204
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
205
|
+
if (msg.indexOf("claim-already-held") !== -1) {
|
|
206
|
+
console.log("[relay-agent-claims] claim already held for " + agentName + " on " + convId + " — skip (use --force to supersede)");
|
|
207
|
+
} else {
|
|
208
|
+
console.warn("[relay-agent-claims] register failed for " + agentName + " on " + convId + ":", msg);
|
|
209
|
+
}
|
|
210
|
+
return null;
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Send a heartbeat for an existing claim. Resolves true if effective, false if
|
|
215
|
+
// superseded. Never rejects.
|
|
216
|
+
function heartbeatClaim(agentName, convId, claimId) {
|
|
217
|
+
return relayPost("/conversations/live-claim/heartbeat", {
|
|
218
|
+
conversation_id: convId,
|
|
219
|
+
participant: agentName,
|
|
220
|
+
claim_id: claimId,
|
|
221
|
+
}).then(function (resp) {
|
|
222
|
+
return !!(resp && resp.effective);
|
|
223
|
+
}).catch(function (e) {
|
|
224
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
225
|
+
console.warn("[relay-agent-claims] heartbeat failed for " + agentName + " on " + convId + ":", msg);
|
|
226
|
+
return false;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Release a live claim. Best-effort; never rejects, never throws.
|
|
231
|
+
function releaseClaim(agentName, convId, claimId) {
|
|
232
|
+
return relayPost("/conversations/live-claim/release", {
|
|
233
|
+
conversation_id: convId,
|
|
234
|
+
participant: agentName,
|
|
235
|
+
claim_id: claimId,
|
|
236
|
+
}).then(function () {
|
|
237
|
+
// success
|
|
238
|
+
}).catch(function (e) {
|
|
239
|
+
var msg = (e && e.message) ? e.message : String(e);
|
|
240
|
+
console.warn("[relay-agent-claims] release failed for " + agentName + " on " + convId + ":", msg);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Start the 30s heartbeat loop for a session's claims. Restores claims after
|
|
245
|
+
// relay restart by re-registering when heartbeat returns effective=false.
|
|
246
|
+
function startHeartbeatLoop(localId) {
|
|
247
|
+
var state = _sessionClaims.get(localId);
|
|
248
|
+
if (!state) return;
|
|
249
|
+
if (state.timer) return; // already running
|
|
250
|
+
|
|
251
|
+
var timer = setInterval(function () {
|
|
252
|
+
var st = _sessionClaims.get(localId);
|
|
253
|
+
if (!st) {
|
|
254
|
+
clearInterval(timer);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
var convIds = Array.from(st.claims.keys());
|
|
258
|
+
for (var i = 0; i < convIds.length; i++) {
|
|
259
|
+
(function (convId) {
|
|
260
|
+
var claimId = st.claims.get(convId);
|
|
261
|
+
if (!claimId) return;
|
|
262
|
+
heartbeatClaim(st.agentName, convId, claimId).then(function (effective) {
|
|
263
|
+
if (effective) return; // still alive
|
|
264
|
+
// Superseded or expired — attempt re-register.
|
|
265
|
+
var sessState = _sessionClaims.get(localId);
|
|
266
|
+
if (!sessState) return;
|
|
267
|
+
registerClaim(st.agentName, convId, "console-reregister").then(function (newId) {
|
|
268
|
+
var s2 = _sessionClaims.get(localId);
|
|
269
|
+
if (!s2 || !newId) return;
|
|
270
|
+
s2.claims.set(convId, newId);
|
|
271
|
+
console.log("[relay-agent-claims] re-registered claim for " + st.agentName + " on " + convId);
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
})(convIds[i]);
|
|
275
|
+
}
|
|
276
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
277
|
+
|
|
278
|
+
state.timer = timer;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Watch the sidecar directory for new conversation files. When a new sidecar
|
|
282
|
+
// appears where agentName is a participant, auto-claims via onNewConversation.
|
|
283
|
+
// Called from attachAgentSession after relay reachability is confirmed.
|
|
284
|
+
//
|
|
285
|
+
// preExistingConvIds: Set of conversation_id strings that existed at watcher-start
|
|
286
|
+
// time. Events for these are ignored — operator decides whether to claim them,
|
|
287
|
+
// per lr-9cfc spec. Only sidecar files not in this set trigger auto-claim.
|
|
288
|
+
//
|
|
289
|
+
// Returns the fs.FSWatcher instance, or null if the directory is absent.
|
|
290
|
+
function startSidecarWatcher(localId, agentName, preExistingConvIds) {
|
|
291
|
+
var sidecarDir = path.join(loreHomeDir(), "conversation-sidecars");
|
|
292
|
+
// Keyed by filename so concurrent events for different files don't cancel each other.
|
|
293
|
+
var debounceMap = new Map();
|
|
294
|
+
var watcher;
|
|
295
|
+
try {
|
|
296
|
+
watcher = fs.watch(sidecarDir, function (eventType, filename) {
|
|
297
|
+
if (!filename || !filename.endsWith(".json")) return;
|
|
298
|
+
// Debounce per filename to avoid double-fire from write + rename events.
|
|
299
|
+
var prev = debounceMap.get(filename);
|
|
300
|
+
if (prev) clearTimeout(prev);
|
|
301
|
+
debounceMap.set(filename, setTimeout(function () {
|
|
302
|
+
debounceMap.delete(filename);
|
|
303
|
+
var fullPath = path.join(sidecarDir, filename);
|
|
304
|
+
var raw;
|
|
305
|
+
try { raw = fs.readFileSync(fullPath, "utf8"); } catch (e) { return; }
|
|
306
|
+
var obj;
|
|
307
|
+
try { obj = JSON.parse(raw); } catch (e) { return; }
|
|
308
|
+
if (!obj || obj.status !== "open") return;
|
|
309
|
+
var convId = obj.conversation_id;
|
|
310
|
+
if (!convId) return;
|
|
311
|
+
// Skip conversations that existed before the watcher started — those are
|
|
312
|
+
// display-only; the operator must explicitly claim them (lr-9cfc spec).
|
|
313
|
+
if (preExistingConvIds && preExistingConvIds.has(convId)) return;
|
|
314
|
+
var participants = Array.isArray(obj.participants) ? obj.participants : [];
|
|
315
|
+
var isParticipant = participants.some(function (p) { return p && p.name === agentName; });
|
|
316
|
+
if (!isParticipant) return;
|
|
317
|
+
onNewConversation(localId, agentName, convId);
|
|
318
|
+
}, 50));
|
|
319
|
+
});
|
|
320
|
+
} catch (e) {
|
|
321
|
+
// Sidecar dir absent or watch not supported — silently ignore.
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
return watcher;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// --- Public API ---
|
|
328
|
+
|
|
329
|
+
// Called when a new session is opened with agentName set.
|
|
330
|
+
// 1. Checks relay reachability; if absent, returns immediately (no-op).
|
|
331
|
+
// 2. Lists open conversations for agentName from sidecars.
|
|
332
|
+
// 3. Surfaces open conv list to operator (display-only — operator decides to claim).
|
|
333
|
+
// 4. Starts heartbeat loop and sidecar watcher for auto-claiming new conversations.
|
|
334
|
+
//
|
|
335
|
+
// sendToSessionFn: function(obj) — sends to all clients viewing this session.
|
|
336
|
+
//
|
|
337
|
+
// Returns immediately; all relay calls are async and non-blocking.
|
|
338
|
+
function attachAgentSession(session, agentName, sendToSessionFn) {
|
|
339
|
+
if (!agentName || typeof agentName !== "string") return;
|
|
340
|
+
var localId = session.localId;
|
|
341
|
+
|
|
342
|
+
// Initialize state entry.
|
|
343
|
+
_sessionClaims.set(localId, {
|
|
344
|
+
agentName: agentName,
|
|
345
|
+
claims: new Map(),
|
|
346
|
+
timer: null,
|
|
347
|
+
watcher: null,
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
isRelayReachable().then(function (reachable) {
|
|
351
|
+
if (!reachable) {
|
|
352
|
+
// Relay not running — clean up and exit silently.
|
|
353
|
+
_sessionClaims.delete(localId);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
var state = _sessionClaims.get(localId);
|
|
358
|
+
if (!state) return; // session already deleted
|
|
359
|
+
|
|
360
|
+
// List open conversations for this agent.
|
|
361
|
+
var openConvs = listOpenConversationsForAgent(agentName);
|
|
362
|
+
|
|
363
|
+
// Surface open conversations to operator (display-only, per task spec lr-9cfc).
|
|
364
|
+
// Pre-existing conversations are NOT auto-claimed — operator decides per-conversation
|
|
365
|
+
// to avoid recreating the stale-claim/zombie-blocking problem fixed 2026-05-19.
|
|
366
|
+
if (openConvs.length > 0 && typeof sendToSessionFn === "function") {
|
|
367
|
+
var lines = ["Open conversations where " + agentName + " is a participant (not claimed — operator decides):"];
|
|
368
|
+
for (var k = 0; k < openConvs.length; k++) {
|
|
369
|
+
var c = openConvs[k];
|
|
370
|
+
var short = (c.conversation_id || "").substring(0, 8);
|
|
371
|
+
lines.push(" " + short + " [" + (c.kind || "?") + "] " + (c.topic || "(no topic)") + " (msgs: " + (c.message_count || 0) + ")");
|
|
372
|
+
}
|
|
373
|
+
lines.push("New conversations opened after this session starts will be auto-claimed.");
|
|
374
|
+
sendToSessionFn({
|
|
375
|
+
type: "system_message",
|
|
376
|
+
text: lines.join("\n"),
|
|
377
|
+
role: "system",
|
|
378
|
+
_ts: Date.now(),
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Do NOT auto-claim pre-existing conversations (lr-9cfc spec).
|
|
383
|
+
// Start the heartbeat loop and sidecar watcher so new conversations are
|
|
384
|
+
// auto-claimed via onNewConversation as they appear.
|
|
385
|
+
// Pass the pre-existing conv IDs so the watcher can ignore sidecar rewrites
|
|
386
|
+
// for conversations that were open before this session started.
|
|
387
|
+
var preExistingIds = new Set(openConvs.map(function (c) { return c.conversation_id; }));
|
|
388
|
+
var s = _sessionClaims.get(localId);
|
|
389
|
+
if (s) {
|
|
390
|
+
startHeartbeatLoop(localId);
|
|
391
|
+
s.watcher = startSidecarWatcher(localId, agentName, preExistingIds);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Called when a new conversation is opened where agentName is a participant
|
|
397
|
+
// AND this agent has an active UI session. Auto-registers a live claim without
|
|
398
|
+
// prompting the operator (new convs only — not pre-existing, per lr-9cfc spec).
|
|
399
|
+
//
|
|
400
|
+
// convId: the newly-opened conversation ID.
|
|
401
|
+
// agentName: the participant name (must match the session's agentName).
|
|
402
|
+
// localId: the session's localId.
|
|
403
|
+
//
|
|
404
|
+
// Returns a Promise that resolves with the claim_id or null. Never rejects.
|
|
405
|
+
function onNewConversation(localId, agentName, convId) {
|
|
406
|
+
var state = _sessionClaims.get(localId);
|
|
407
|
+
if (!state || state.agentName !== agentName) return Promise.resolve(null);
|
|
408
|
+
if (!convId) return Promise.resolve(null);
|
|
409
|
+
if (state.claims.has(convId)) return Promise.resolve(state.claims.get(convId));
|
|
410
|
+
|
|
411
|
+
var sessionLabel = "console-ui-new-" + agentName + "-" + Date.now();
|
|
412
|
+
return registerClaim(agentName, convId, sessionLabel).then(function (claimId) {
|
|
413
|
+
if (!claimId) return null;
|
|
414
|
+
var s = _sessionClaims.get(localId);
|
|
415
|
+
if (!s) return null;
|
|
416
|
+
s.claims.set(convId, claimId);
|
|
417
|
+
console.log("[relay-agent-claims] auto-claimed new conv " + convId.substring(0, 8) + " for session " + localId + " (" + agentName + ")");
|
|
418
|
+
return claimId;
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Called when a session is deleted or its agentName is cleared.
|
|
423
|
+
// Releases all live claims, stops the heartbeat loop, and closes the sidecar watcher.
|
|
424
|
+
// Best-effort — never throws.
|
|
425
|
+
function detachAgentSession(localId) {
|
|
426
|
+
var state = _sessionClaims.get(localId);
|
|
427
|
+
if (!state) return;
|
|
428
|
+
|
|
429
|
+
// Stop heartbeat loop.
|
|
430
|
+
if (state.timer) {
|
|
431
|
+
clearInterval(state.timer);
|
|
432
|
+
state.timer = null;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Stop sidecar watcher.
|
|
436
|
+
if (state.watcher) {
|
|
437
|
+
try { state.watcher.close(); } catch (e) {}
|
|
438
|
+
state.watcher = null;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Release all claims (best-effort, async).
|
|
442
|
+
var agentName = state.agentName;
|
|
443
|
+
var entries = Array.from(state.claims.entries());
|
|
444
|
+
_sessionClaims.delete(localId);
|
|
445
|
+
|
|
446
|
+
for (var i = 0; i < entries.length; i++) {
|
|
447
|
+
(function (convId, claimId) {
|
|
448
|
+
releaseClaim(agentName, convId, claimId).then(function () {
|
|
449
|
+
console.log("[relay-agent-claims] released claim for " + agentName + " on " + convId.substring(0, 8));
|
|
450
|
+
});
|
|
451
|
+
})(entries[i][0], entries[i][1]);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// Returns true if this session has an active relay claim state (relay was
|
|
456
|
+
// reachable when the session was attached).
|
|
457
|
+
function hasClaimState(localId) {
|
|
458
|
+
return _sessionClaims.has(localId);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Exported for testing: get the current claims for a session.
|
|
462
|
+
function getClaimsForSession(localId) {
|
|
463
|
+
var state = _sessionClaims.get(localId);
|
|
464
|
+
if (!state) return null;
|
|
465
|
+
return { agentName: state.agentName, claims: Object.fromEntries(state.claims) };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
module.exports = {
|
|
469
|
+
attachAgentSession: attachAgentSession,
|
|
470
|
+
detachAgentSession: detachAgentSession,
|
|
471
|
+
onNewConversation: onNewConversation,
|
|
472
|
+
hasClaimState: hasClaimState,
|
|
473
|
+
getClaimsForSession: getClaimsForSession,
|
|
474
|
+
// exported for tests
|
|
475
|
+
listOpenConversationsForAgent: listOpenConversationsForAgent,
|
|
476
|
+
isRelayReachable: isRelayReachable,
|
|
477
|
+
registerClaim: registerClaim,
|
|
478
|
+
heartbeatClaim: heartbeatClaim,
|
|
479
|
+
releaseClaim: releaseClaim,
|
|
480
|
+
};
|
package/lib/sdk-bridge.js
CHANGED
|
@@ -8,6 +8,7 @@ var { getCodexConfig } = require("./codex-defaults");
|
|
|
8
8
|
var { splitShellSegments, attachSkillDiscovery } = require("./sdk-skill-discovery");
|
|
9
9
|
var { createMessageQueue } = require("./sdk-message-queue");
|
|
10
10
|
var { attachMessageProcessor } = require("./sdk-message-processor");
|
|
11
|
+
var { readAgentToolsFromFile } = require("./agents");
|
|
11
12
|
|
|
12
13
|
// Extract serializable tool descriptors from MCP server instances.
|
|
13
14
|
// Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
|
|
@@ -1193,8 +1194,19 @@ function createSDKBridge(opts) {
|
|
|
1193
1194
|
// hides the Agent Chat entry point for Codex projects; this guard is
|
|
1194
1195
|
// belt-and-suspenders for sessions that carry agentName from a prior
|
|
1195
1196
|
// vendor switch or a direct ws message.
|
|
1197
|
+
//
|
|
1198
|
+
// lr-4c90 — belt-and-suspenders tool enforcement: the SDK's `agent` option
|
|
1199
|
+
// should apply tool restrictions, but only does so when the agent file uses
|
|
1200
|
+
// JSON array syntax for the tools field. We read the tools list directly
|
|
1201
|
+
// from disk and set claudeOpts.tools explicitly so restriction is enforced
|
|
1202
|
+
// even if the SDK's parsing path has any quirks.
|
|
1196
1203
|
if (session.agentName && sessionAdapter.vendor !== 'codex') {
|
|
1197
1204
|
claudeOpts.agent = session.agentName;
|
|
1205
|
+
var agentTools = readAgentToolsFromFile(session.agentName);
|
|
1206
|
+
if (agentTools) {
|
|
1207
|
+
claudeOpts.tools = agentTools;
|
|
1208
|
+
console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
|
|
1209
|
+
}
|
|
1198
1210
|
}
|
|
1199
1211
|
|
|
1200
1212
|
// Per-loop settings override global defaults when present
|
package/package.json
CHANGED