@clagentic/console 1.0.3 → 1.0.4-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/README.md CHANGED
@@ -15,6 +15,26 @@ A self-hosted browser console for Claude Code and ChatGPT Codex. Run AI sessions
15
15
 
16
16
  No extras bolted on. No opinionated workflows. The floor is solid; you build what you need on top.
17
17
 
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install -g @clagentic/console
22
+ ```
23
+
24
+ Then run from anywhere:
25
+
26
+ ```bash
27
+ clagentic
28
+ ```
29
+
30
+ Or try it without installing:
31
+
32
+ ```bash
33
+ npx @clagentic/console
34
+ ```
35
+
36
+ **Requirements:** Node.js 20+. Authenticated Claude Code CLI, Codex CLI, or both.
37
+
18
38
  ## What it does
19
39
 
20
40
  - **Browser access to your AI runtimes.** The goal is full parity with the CLI for both Claude Code and Codex — tool approvals, model selection, context management, session history. Most things work; see the FAQ for current gaps.
@@ -27,12 +47,6 @@ No extras bolted on. No opinionated workflows. The floor is solid; you build wha
27
47
 
28
48
  ## Getting Started
29
49
 
30
- **Requirements:** Node.js 20+. Authenticated Claude Code CLI, Codex CLI, or both.
31
-
32
- ```bash
33
- npx @clagentic/console
34
- ```
35
-
36
50
  On first run you'll be asked for a port and whether you're running solo or multi-user. Open the URL from any device on your network.
37
51
 
38
52
  For remote access, use a tunnel — Tailscale, Cloudflare Tunnel, or your existing VPN.
@@ -1,22 +1,20 @@
1
- // Agent favorites — Clay-side list of agents the user has marked as
2
- // chat-eligible. Surfaces in the "Start agent chat" picker on the project
3
- // view; everything not on this list is discovered but not promoted.
1
+ // Agent favorites — list of agents the user has marked as chat-eligible.
2
+ // Surfaces in the "Start agent chat" picker on the project view.
4
3
  //
5
- // Storage: ~/.clay/agents/chattable.json. Schema:
6
- // {
7
- // "version": 1,
8
- // "favorites": [
9
- // { "name": "gemini-researcher", "kind": "user", "addedAt": 1735000000000 },
10
- // { "name": "amos", "kind": "plugin", "pluginName": "amos", "addedAt": 1735000000001 }
11
- // ],
12
- // "recents": [
13
- // { "name": "gemini-researcher", "kind": "user", "lastUsedAt": 1735000000500 }
14
- // ]
15
- // }
4
+ // Storage: ~/.clagentic/agents/chattable.json.
16
5
  //
17
- // Identity key for an agent across the file is (kind, pluginName, name).
18
- // Built-in agents are not eligible — they have no source .md and the
19
- // favorites surface is for user-installed agents.
6
+ // Schema v1 (legacy, plugin-marketplace era):
7
+ // { "version": 1, "favorites": [{ "name", "kind", "pluginName", "addedAt" }],
8
+ // "recents": [{ "name", "kind", "pluginName", "lastUsedAt" }] }
9
+ //
10
+ // Schema v2 (lr-8e39, flat catalog — plugin marketplace removed in lr-635a):
11
+ // { "version": 2, "favorites": [{ "name", "addedAt" }],
12
+ // "recents": [{ "name", "lastUsedAt" }] }
13
+ //
14
+ // Identity key is `name` only. kind/pluginName are dropped because the SDK
15
+ // catalog (supportedAgents()) exposes a flat list with no plugin distinction.
16
+ // Migration from v1 → v2 runs automatically on first readStore(): entries
17
+ // are deduplicated by name (earliest addedAt wins), kind/pluginName dropped.
20
18
  //
21
19
  // Concurrency: single-process daemon; no locking. Writes are atomic via
22
20
  // rename() to avoid torn reads if a reader races with a writer.
@@ -30,7 +28,7 @@ var REAL_HOME = process.env.SUDO_USER
30
28
  : os.homedir();
31
29
 
32
30
  var FAVORITES_PATH = path.join(REAL_HOME, ".clagentic", "agents", "chattable.json");
33
- var SCHEMA_VERSION = 1;
31
+ var SCHEMA_VERSION = 2;
34
32
  var RECENTS_LIMIT = 8;
35
33
 
36
34
  function ensureDir() {
@@ -41,6 +39,55 @@ function emptyStore() {
41
39
  return { version: SCHEMA_VERSION, favorites: [], recents: [] };
42
40
  }
43
41
 
42
+ // Migrate v1 (kind/pluginName keyed) entries to v2 (name-only).
43
+ // Deduplicates by name — for favorites, keeps the entry with the earliest
44
+ // addedAt; for recents, keeps the entry with the latest lastUsedAt.
45
+ // Returns a new store object at version 2. Writes it back to disk.
46
+ function migrateV1toV2(store) {
47
+ var seen = {};
48
+ var newFavs = [];
49
+ for (var i = 0; i < store.favorites.length; i++) {
50
+ var f = store.favorites[i];
51
+ if (!f || !f.name) continue;
52
+ var n = f.name;
53
+ if (seen[n] === undefined) {
54
+ seen[n] = newFavs.length;
55
+ newFavs.push({ name: n, addedAt: f.addedAt || Date.now() });
56
+ } else {
57
+ // Keep earliest addedAt
58
+ var existing = newFavs[seen[n]];
59
+ if (f.addedAt && f.addedAt < existing.addedAt) {
60
+ existing.addedAt = f.addedAt;
61
+ }
62
+ }
63
+ }
64
+ var seenR = {};
65
+ var newRecents = [];
66
+ for (var j = 0; j < store.recents.length; j++) {
67
+ var r = store.recents[j];
68
+ if (!r || !r.name) continue;
69
+ var rn = r.name;
70
+ if (seenR[rn] === undefined) {
71
+ seenR[rn] = newRecents.length;
72
+ newRecents.push({ name: rn, lastUsedAt: r.lastUsedAt || Date.now() });
73
+ } else {
74
+ // Keep latest lastUsedAt
75
+ var existingR = newRecents[seenR[rn]];
76
+ if (r.lastUsedAt && r.lastUsedAt > existingR.lastUsedAt) {
77
+ existingR.lastUsedAt = r.lastUsedAt;
78
+ }
79
+ }
80
+ }
81
+ var migrated = { version: SCHEMA_VERSION, favorites: newFavs, recents: newRecents };
82
+ try {
83
+ writeStore(migrated);
84
+ console.log("[agents-favorites] migrated chattable.json v1→v2 (" + newFavs.length + " favorites, " + newRecents.length + " recents)");
85
+ } catch (e) {
86
+ console.error("[agents-favorites] migration write failed:", e.message);
87
+ }
88
+ return migrated;
89
+ }
90
+
44
91
  function readStore() {
45
92
  var raw;
46
93
  try { raw = fs.readFileSync(FAVORITES_PATH, "utf8"); }
@@ -58,7 +105,9 @@ function readStore() {
58
105
  if (!parsed || typeof parsed !== "object") return emptyStore();
59
106
  if (!Array.isArray(parsed.favorites)) parsed.favorites = [];
60
107
  if (!Array.isArray(parsed.recents)) parsed.recents = [];
61
- if (typeof parsed.version !== "number") parsed.version = SCHEMA_VERSION;
108
+ if (typeof parsed.version !== "number") parsed.version = 1;
109
+ // Migrate v1 → v2 on first read.
110
+ if (parsed.version < 2) return migrateV1toV2(parsed);
62
111
  return parsed;
63
112
  }
64
113
 
@@ -69,13 +118,10 @@ function writeStore(store) {
69
118
  fs.renameSync(tmp, FAVORITES_PATH);
70
119
  }
71
120
 
72
- // Identity match. pluginName is only meaningful for kind="plugin".
121
+ // Identity match: name is the sole key in v2.
73
122
  function sameAgent(a, b) {
74
123
  if (!a || !b) return false;
75
- if (a.name !== b.name) return false;
76
- if (a.kind !== b.kind) return false;
77
- if (a.kind === "plugin" && (a.pluginName || null) !== (b.pluginName || null)) return false;
78
- return true;
124
+ return a.name === b.name;
79
125
  }
80
126
 
81
127
  function listFavorites() {
@@ -93,18 +139,12 @@ function isFavorite(agent) {
93
139
  // Add an agent to favorites. No-op if already present. Returns true if added,
94
140
  // false if already present or input invalid.
95
141
  function addFavorite(agent) {
96
- if (!agent || !agent.name || !agent.kind) return false;
97
- if (agent.kind === "builtin") return false;
142
+ if (!agent || !agent.name) return false;
98
143
  var store = readStore();
99
144
  for (var i = 0; i < store.favorites.length; i++) {
100
145
  if (sameAgent(store.favorites[i], agent)) return false;
101
146
  }
102
- store.favorites.push({
103
- name: agent.name,
104
- kind: agent.kind,
105
- pluginName: agent.kind === "plugin" ? (agent.pluginName || null) : null,
106
- addedAt: Date.now(),
107
- });
147
+ store.favorites.push({ name: agent.name, addedAt: Date.now() });
108
148
  writeStore(store);
109
149
  return true;
110
150
  }
@@ -136,15 +176,10 @@ function listRecents() {
136
176
 
137
177
  // Bump usage. Moves the agent to the head of recents and trims to RECENTS_LIMIT.
138
178
  function touchRecent(agent) {
139
- if (!agent || !agent.name || !agent.kind) return;
179
+ if (!agent || !agent.name) return;
140
180
  var store = readStore();
141
181
  store.recents = store.recents.filter(function (r) { return !sameAgent(r, agent); });
142
- store.recents.unshift({
143
- name: agent.name,
144
- kind: agent.kind,
145
- pluginName: agent.kind === "plugin" ? (agent.pluginName || null) : null,
146
- lastUsedAt: Date.now(),
147
- });
182
+ store.recents.unshift({ name: agent.name, lastUsedAt: Date.now() });
148
183
  if (store.recents.length > RECENTS_LIMIT) {
149
184
  store.recents = store.recents.slice(0, RECENTS_LIMIT);
150
185
  }
package/lib/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- // Named agents — Claude CLI catalog discovery and SDK AgentDefinition lookup.
1
+ // Named agents — SDK-based catalog discovery.
2
2
  //
3
3
  // History: an earlier path (chadbyte/clay#332) registered each chat-enabled
4
4
  // agent as its own Clay project rooted at ~/.clay/agents/<slug>/, with the
@@ -8,42 +8,45 @@
8
8
  // proved out — sessions now carry an `agentName` and the SDK applies the
9
9
  // agent identity itself.
10
10
  //
11
- // What's left here is the catalog + definition surface the picker and the
12
- // SDK bridge need:
13
- // - listClaudeAgents() — parse `claude agents` output
14
- // - resolveAgentSourcePath() — locate the .md for a catalog entry
15
- // - discoverAllAgents() — full non-builtin catalog for the picker
16
- // - getAgentDefinition(name) — build the in-band SDK AgentDefinition
11
+ // lr-8e39: replaced CLI text-parse path (claude agents --setting-sources …)
12
+ // with the SDK supportedAgents() surface. The CLI subcommand was retasked in
13
+ // Claude Code 2.1.x to "Manage background agents" and returns an error when
14
+ // invoked non-interactively. supportedAgents() is a stable SDK Query API that
15
+ // returns AgentInfo[] (name, description, model?) and follows the same
16
+ // settingSources as the prior CLI call.
17
+ //
18
+ // Discovery is async and cached. Call refresh() at daemon startup; getAll()
19
+ // returns the last-known cache synchronously. An empty cache (before the first
20
+ // refresh completes, or if discovery fails) returns [].
21
+ //
22
+ // Implementation: we open a streaming-input SDK session (sdk.query with a
23
+ // no-message async iterable), await initialization, call supportedAgents(),
24
+ // then abort the session. The Query object's supportedAgents() method awaits
25
+ // the internal initialization promise — no user prompt is ever sent.
17
26
  //
18
27
  // This implementation lives only on our fork; we are not pushing it upstream.
19
28
 
20
- var fs = require("fs");
21
29
  var path = require("path");
22
30
  var os = require("os");
23
- var { execFileSync } = require("child_process");
24
31
 
25
32
  var REAL_HOME = process.env.SUDO_USER
26
33
  ? path.join("/home", process.env.SUDO_USER)
27
34
  : os.homedir();
28
35
 
36
+ // Still exported for callers that referenced them (backwards compat).
29
37
  var AGENTS_SOURCE_DIR = path.join(REAL_HOME, ".claude", "agents");
30
38
  var PLUGINS_CACHE_DIR = path.join(REAL_HOME, ".claude", "plugins", "cache");
31
39
 
32
- // Minimal frontmatter parser. Reads YAML-ish key/value pairs between leading
33
- // '---' fences. No nesting, no lists — agent frontmatter is flat.
34
- // Returns { meta: {...}, body: "..." } or null if no frontmatter fence.
40
+ // Minimal frontmatter parser — kept for any callers that still use it.
35
41
  function parseFrontmatter(raw) {
36
42
  if (typeof raw !== "string") return null;
37
- // Allow optional UTF-8 BOM and leading whitespace before the fence.
38
43
  var stripped = raw.replace(/^/, "");
39
44
  if (stripped.indexOf("---") !== 0) return { meta: {}, body: stripped };
40
45
  var rest = stripped.slice(3);
41
- // The fence terminator must start a line.
42
46
  var endIdx = rest.indexOf("\n---");
43
47
  if (endIdx === -1) return { meta: {}, body: stripped };
44
48
  var fmText = rest.slice(0, endIdx);
45
- var afterFence = rest.slice(endIdx + 4); // skip "\n---"
46
- // Trim a single leading newline after the closing fence.
49
+ var afterFence = rest.slice(endIdx + 4);
47
50
  if (afterFence.charAt(0) === "\n") afterFence = afterFence.slice(1);
48
51
  var meta = {};
49
52
  var lines = fmText.split("\n");
@@ -55,12 +58,10 @@ function parseFrontmatter(raw) {
55
58
  var key = line.slice(0, colon).trim();
56
59
  var val = line.slice(colon + 1).trim();
57
60
  if (!key) continue;
58
- // Strip matching surrounding quotes.
59
61
  if ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') ||
60
62
  (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'")) {
61
63
  val = val.slice(1, -1);
62
64
  }
63
- // Coerce booleans.
64
65
  if (val === "true") val = true;
65
66
  else if (val === "false") val = false;
66
67
  meta[key] = val;
@@ -68,8 +69,7 @@ function parseFrontmatter(raw) {
68
69
  return { meta: meta, body: afterFence };
69
70
  }
70
71
 
71
- // Normalize an agent name to a filesystem-safe slug. Keeps lowercase letters,
72
- // numbers, and dashes; collapses everything else.
72
+ // Normalize an agent name to a filesystem-safe slug.
73
73
  function slugifyAgentName(name) {
74
74
  if (!name) return "";
75
75
  return String(name)
@@ -79,195 +79,102 @@ function slugifyAgentName(name) {
79
79
  .slice(0, 64);
80
80
  }
81
81
 
82
- // Ask Claude CLI for the canonical agent catalog (user + plugin + built-in
83
- // agents). Output is human-readable text, sectioned. Returns array of
84
- // { name, kind, modelLabel } where kind is "user" | "plugin" | "builtin".
85
- // Plugin agents arrive prefixed like "amos:amos" — we keep both the raw
86
- // label and a parsed agent name.
87
- function listClaudeAgents() {
88
- var out;
89
- try {
90
- out = execFileSync("claude", ["agents", "--setting-sources", "user,project,local"], {
91
- encoding: "utf8",
92
- timeout: 10000,
93
- stdio: ["ignore", "pipe", "pipe"],
94
- });
95
- } catch (e) {
96
- console.error("[agents] claude agents command failed:", e.message);
97
- return [];
98
- }
99
- var lines = out.split("\n");
100
- var agents = [];
101
- var section = null;
102
- for (var i = 0; i < lines.length; i++) {
103
- var line = lines[i];
104
- if (/^User agents:/i.test(line)) { section = "user"; continue; }
105
- if (/^Plugin agents:/i.test(line)) { section = "plugin"; continue; }
106
- if (/^Built-?in agents:/i.test(line)) { section = "builtin"; continue; }
107
- if (!section) continue;
108
- var m = line.match(/^\s+(\S.*?)\s+·\s+(\S+)\s*$/);
109
- if (!m) continue;
110
- var label = m[1].trim();
111
- var modelLabel = m[2].trim();
112
- // Plugin entries are "<plugin>:<agent>"; user/builtin are bare names.
113
- var name = label;
114
- var pluginName = null;
115
- if (section === "plugin") {
116
- var parts = label.split(":");
117
- if (parts.length === 2) { pluginName = parts[0]; name = parts[1]; }
118
- }
119
- agents.push({ label: label, name: name, kind: section, modelLabel: modelLabel, pluginName: pluginName });
120
- }
121
- return agents;
82
+ // --- SDK-backed discovery cache ---
83
+
84
+ // Module-level cache. Populated by refresh(); read by getAll().
85
+ var _cache = [];
86
+ // In-flight refresh promise (deduplicate concurrent calls).
87
+ var _refreshPromise = null;
88
+
89
+ // Map AgentInfo (SDK shape) → picker-facing shape.
90
+ // AgentInfo: { name: string; description?: string; model?: string }
91
+ function agentInfoToEntry(info) {
92
+ var name = info.name || "";
93
+ var slug = slugifyAgentName(name);
94
+ return {
95
+ name: name,
96
+ slug: slug,
97
+ description: info.description || "",
98
+ model: info.model || "",
99
+ // Retained for backwards compat with consumers that read these fields.
100
+ // Always null/agent since the plugin marketplace is gone (lr-635a).
101
+ kind: "agent",
102
+ pluginName: null,
103
+ sourcePath: null,
104
+ };
122
105
  }
123
106
 
124
- // Resolve an agent entry from `claude agents` to its source .md file.
125
- // Returns the absolute path or null if not found. Built-ins have no .md and
126
- // always return null (we don't surface them as chat sessions).
127
- function resolveAgentSourcePath(agent) {
128
- if (agent.kind === "user") {
129
- var p = path.join(AGENTS_SOURCE_DIR, agent.name + ".md");
130
- if (fs.existsSync(p)) return p;
131
- return null;
132
- }
133
- if (agent.kind === "plugin") {
134
- // Walk ~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/agents/<name>.md
135
- if (!fs.existsSync(PLUGINS_CACHE_DIR)) return null;
136
- var marketplaces;
137
- try { marketplaces = fs.readdirSync(PLUGINS_CACHE_DIR); }
138
- catch (e) { return null; }
139
- for (var mi = 0; mi < marketplaces.length; mi++) {
140
- var marketplaceDir = path.join(PLUGINS_CACHE_DIR, marketplaces[mi]);
141
- var pluginCandidate = agent.pluginName ? path.join(marketplaceDir, agent.pluginName) : null;
142
- var pluginDirs = [];
143
- if (pluginCandidate && fs.existsSync(pluginCandidate)) {
144
- pluginDirs.push(pluginCandidate);
107
+ // Build an async iterable that emits no messages, allowing the SDK session
108
+ // to initialize without sending a user prompt.
109
+ async function* _emptyIterable() {
110
+ // Yield nothing. The AbortController will terminate the session after we
111
+ // read supportedAgents() from the initialization result.
112
+ }
113
+
114
+ // Kick off an async SDK discovery session and update the cache.
115
+ // Returns a promise that never rejects — failures are logged and the cache
116
+ // retains its last-known value.
117
+ //
118
+ // settingSources: comma-separated string, defaults to 'user,project,local'
119
+ // to match the prior CLI --setting-sources flag.
120
+ function refresh(settingSources) {
121
+ if (_refreshPromise) return _refreshPromise;
122
+
123
+ _refreshPromise = (async function () {
124
+ var sdk;
125
+ try {
126
+ sdk = await import("@anthropic-ai/claude-agent-sdk");
127
+ } catch (e) {
128
+ console.error("[agents] failed to import SDK:", e.message);
129
+ _refreshPromise = null;
130
+ return;
131
+ }
132
+
133
+ var sources = settingSources || "user,project,local";
134
+ var abortController = new AbortController();
135
+ var queryInstance = null;
136
+ try {
137
+ // Open a streaming-input session with an empty iterable. The SDK
138
+ // initializes its subprocess and completes the handshake before
139
+ // surfacing any events — supportedAgents() awaits that handshake.
140
+ queryInstance = sdk.query({
141
+ prompt: _emptyIterable(),
142
+ options: {
143
+ settingSources: sources,
144
+ abortController: abortController,
145
+ },
146
+ });
147
+
148
+ var agents = await queryInstance.supportedAgents();
149
+ if (Array.isArray(agents)) {
150
+ _cache = agents.map(agentInfoToEntry).filter(function (e) { return e.slug; });
151
+ console.log("[agents] discovered " + _cache.length + " agents via SDK");
145
152
  } else {
146
- // Fallback: scan all plugins under this marketplace.
147
- try {
148
- var pls = fs.readdirSync(marketplaceDir);
149
- for (var pi = 0; pi < pls.length; pi++) {
150
- pluginDirs.push(path.join(marketplaceDir, pls[pi]));
151
- }
152
- } catch (e) { /* skip */ }
153
- }
154
- for (var pd = 0; pd < pluginDirs.length; pd++) {
155
- // Each plugin has versioned subdirs.
156
- var versions;
157
- try { versions = fs.readdirSync(pluginDirs[pd]); } catch (e) { continue; }
158
- for (var vi = 0; vi < versions.length; vi++) {
159
- var candidate = path.join(pluginDirs[pd], versions[vi], "agents", agent.name + ".md");
160
- if (fs.existsSync(candidate)) return candidate;
161
- }
153
+ console.warn("[agents] supportedAgents() returned non-array:", agents);
162
154
  }
155
+ } catch (e) {
156
+ console.error("[agents] SDK discovery failed:", (e && e.message) || e);
157
+ // Keep last-known cache on failure.
158
+ } finally {
159
+ // Abort the session subprocess — we don't need it anymore.
160
+ try { abortController.abort(); } catch (e) { /* best-effort */ }
161
+ _refreshPromise = null;
163
162
  }
164
- return null;
165
- }
166
- // Built-ins: no source file.
167
- return null;
163
+ })();
164
+
165
+ return _refreshPromise;
168
166
  }
169
167
 
170
- // Discover all non-builtin agents from the Claude CLI catalog. This is the
171
- // catalog surface for the SDK-agent path (lr-7db0): we hand the full list to
172
- // the UI and let the user decide which to favorite (chattable.json), then
173
- // pass the chosen agent name through the SDK `agent` option per session.
174
- //
175
- // Builtins are excluded because they have no source .md (resolved by name
176
- // inside the Claude CLI itself) and the SDK still recognizes them by name —
177
- // callers that want builtins should pass the name through directly.
178
- //
179
- // Returns an array of { name, slug, description, model, sourcePath, kind, pluginName }.
180
- // Body is intentionally NOT loaded here — the SDK applies the agent's system
181
- // prompt itself; we only need metadata for display.
182
- function discoverAllAgents() {
183
- var found = [];
184
- var catalog = listClaudeAgents();
185
- for (var i = 0; i < catalog.length; i++) {
186
- var entry = catalog[i];
187
- if (entry.kind === "builtin") continue;
188
- var sourcePath = resolveAgentSourcePath(entry);
189
- var description = "";
190
- var model = entry.modelLabel || "";
191
- if (sourcePath) {
192
- try {
193
- var raw = fs.readFileSync(sourcePath, "utf8");
194
- var parsed = parseFrontmatter(raw);
195
- if (parsed) {
196
- if (parsed.meta.description) description = parsed.meta.description;
197
- if (parsed.meta.model) model = parsed.meta.model;
198
- }
199
- } catch (e) { /* metadata best-effort */ }
200
- }
201
- var name = entry.name;
202
- var slugBase = entry.kind === "plugin" && entry.pluginName
203
- ? entry.pluginName + "-" + name
204
- : name;
205
- var slug = slugifyAgentName(slugBase);
206
- if (!slug) continue;
207
- found.push({
208
- name: name,
209
- slug: slug,
210
- description: description,
211
- model: model,
212
- sourcePath: sourcePath,
213
- kind: entry.kind,
214
- pluginName: entry.pluginName || null,
215
- });
216
- }
217
- return found;
168
+ // Return the last-known cached agent list. Synchronous; never throws.
169
+ // Returns [] before the first refresh completes or if discovery failed.
170
+ function getAll() {
171
+ return _cache.slice();
218
172
  }
219
173
 
220
- // Build an SDK-shaped AgentDefinition from a discovered agent's source .md.
221
- // The Claude SDK's `agent` option only resolves names against the in-band
222
- // `agents` map (or settings.json) — file/plugin discovery via `claude agents`
223
- // is a CLI-side convenience that the SDK does not honor at query time. So
224
- // when we cast a session as a named agent, we must also hand the SDK the
225
- // definition it needs to apply the system prompt, tool restrictions, and
226
- // model.
227
- //
228
- // Returns null if the name can't be resolved (no source file, parse failure)
229
- // — the caller treats null as "agent unknown, fall back to default identity".
230
- function getAgentDefinition(name) {
231
- if (!name) return null;
232
- // Re-walk the catalog to find the entry for this name. Cheap; the catalog
233
- // is short and `claude agents` runs in well under 100ms.
234
- var catalog = listClaudeAgents();
235
- var entry = null;
236
- for (var i = 0; i < catalog.length; i++) {
237
- if (catalog[i].kind === "builtin") continue;
238
- if (catalog[i].name === name) { entry = catalog[i]; break; }
239
- }
240
- if (!entry) return null;
241
- var sourcePath = resolveAgentSourcePath(entry);
242
- if (!sourcePath) return null;
243
- var raw;
244
- try { raw = fs.readFileSync(sourcePath, "utf8"); }
245
- catch (e) {
246
- console.error("[agents] getAgentDefinition: failed to read " + sourcePath + ":", e.message);
247
- return null;
248
- }
249
- var parsed = parseFrontmatter(raw);
250
- if (!parsed) return null;
251
- var meta = parsed.meta || {};
252
- var def = {
253
- description: meta.description || "",
254
- prompt: (parsed.body || "").trim(),
255
- };
256
- if (meta.model && meta.model !== "inherit") def.model = meta.model;
257
- // Frontmatter `tools` is a comma-separated string; SDK wants a string array.
258
- if (typeof meta.tools === "string" && meta.tools.trim()) {
259
- var toolsArr = meta.tools.split(",")
260
- .map(function (t) { return t.trim(); })
261
- .filter(function (t) { return t.length > 0; });
262
- if (toolsArr.length > 0) def.tools = toolsArr;
263
- }
264
- if (typeof meta.disallowedTools === "string" && meta.disallowedTools.trim()) {
265
- var disArr = meta.disallowedTools.split(",")
266
- .map(function (t) { return t.trim(); })
267
- .filter(function (t) { return t.length > 0; });
268
- if (disArr.length > 0) def.disallowedTools = disArr;
269
- }
270
- return def;
174
+ // Legacy alias. Returns the same as getAll() — kept so callers that used
175
+ // discoverAllAgents() still work without changes.
176
+ function discoverAllAgents() {
177
+ return getAll();
271
178
  }
272
179
 
273
180
  module.exports = {
@@ -275,8 +182,9 @@ module.exports = {
275
182
  PLUGINS_CACHE_DIR: PLUGINS_CACHE_DIR,
276
183
  parseFrontmatter: parseFrontmatter,
277
184
  slugifyAgentName: slugifyAgentName,
278
- listClaudeAgents: listClaudeAgents,
279
- resolveAgentSourcePath: resolveAgentSourcePath,
185
+ // New SDK-backed surface:
186
+ refresh: refresh,
187
+ getAll: getAll,
188
+ // Legacy compat alias (no longer shells out to claude CLI):
280
189
  discoverAllAgents: discoverAllAgents,
281
- getAgentDefinition: getAgentDefinition,
282
190
  };
@@ -5,6 +5,13 @@ var { CODEX_DEFAULTS, getCodexConfig } = require("./codex-defaults");
5
5
  var agentsModule = require("./agents");
6
6
  var agentsFavorites = require("./agents-favorites");
7
7
 
8
+ // Kick off SDK agent discovery in the background at module load.
9
+ // Errors are swallowed inside refresh(); the cache starts empty and fills
10
+ // when the SDK subprocess completes initialization (~9s on this box).
11
+ agentsModule.refresh().catch(function (e) {
12
+ console.error("[project-sessions] initial agent refresh failed:", e && e.message ? e.message : e);
13
+ });
14
+
8
15
  // Format a user's answer to an ask_user_questions card as a plain user
9
16
  // message so the MCP path can feed it back to the agent on the next turn.
10
17
  // The agent sees: its own question text, then the selected answer(s).
@@ -129,7 +136,7 @@ function attachSessions(ctx) {
129
136
  if (msg.vendor) sessionOpts.vendor = msg.vendor;
130
137
  if (msg.agentName && typeof msg.agentName === "string") {
131
138
  sessionOpts.agentName = msg.agentName;
132
- try { agentsFavorites.touchRecent({ name: msg.agentName, kind: msg.agentKind || "user", pluginName: msg.agentPluginName || null }); }
139
+ try { agentsFavorites.touchRecent({ name: msg.agentName }); }
133
140
  catch (e) { /* recents are best-effort */ }
134
141
  }
135
142
  var newSess = sm.createSession(sessionOpts, ws);
@@ -163,19 +170,13 @@ function attachSessions(ctx) {
163
170
  // because the daemon shouldn't make UX decisions that the client already
164
171
  // owns. UI gates the surface; daemon stays a data plane.
165
172
  if (msg.type === "list_agents") {
166
- var allAgents;
167
- try { allAgents = agentsModule.discoverAllAgents(); }
168
- catch (e) {
169
- console.error("[project-sessions] list_agents discovery failed:", e.message);
170
- allAgents = [];
171
- }
172
173
  var favorites = [];
173
174
  var recents = [];
174
175
  try { favorites = agentsFavorites.listFavorites(); recents = agentsFavorites.listRecents(); }
175
176
  catch (e) { /* favorites are best-effort */ }
176
177
  sendTo(ws, {
177
178
  type: "agents_list",
178
- agents: allAgents,
179
+ agents: agentsModule.getAll(),
179
180
  favorites: favorites,
180
181
  recents: recents,
181
182
  });
@@ -183,10 +184,10 @@ function attachSessions(ctx) {
183
184
  }
184
185
 
185
186
  // toggle_agent_favorite flips an agent's membership in chattable.json.
186
- // Required fields: name, kind. Optional: pluginName (for kind=plugin).
187
+ // Required field: name.
187
188
  if (msg.type === "toggle_agent_favorite") {
188
- if (!msg.name || !msg.kind) return true;
189
- var entry = { name: msg.name, kind: msg.kind, pluginName: msg.pluginName || null };
189
+ if (!msg.name) return true;
190
+ var entry = { name: msg.name };
190
191
  var nowFav;
191
192
  try { nowFav = agentsFavorites.toggleFavorite(entry); }
192
193
  catch (e) {
@@ -197,11 +198,11 @@ function attachSessions(ctx) {
197
198
  // pull on demand; favorites is per-machine state, not multi-user shared.
198
199
  sendTo(ws, {
199
200
  type: "agents_list",
200
- agents: agentsModule.discoverAllAgents(),
201
+ agents: agentsModule.getAll(),
201
202
  favorites: agentsFavorites.listFavorites(),
202
203
  recents: agentsFavorites.listRecents(),
203
204
  });
204
- sendTo(ws, { type: "agent_favorite_toggled", name: msg.name, kind: msg.kind, pluginName: msg.pluginName || null, favorite: nowFav });
205
+ sendTo(ws, { type: "agent_favorite_toggled", name: msg.name, favorite: nowFav });
205
206
  return true;
206
207
  }
207
208
 
@@ -220,7 +221,7 @@ function attachSessions(ctx) {
220
221
  agentTarget.agentName = nextAgent;
221
222
  sm.saveSessionFile(agentTarget);
222
223
  if (nextAgent) {
223
- try { agentsFavorites.touchRecent({ name: nextAgent, kind: msg.agentKind || "user", pluginName: msg.agentPluginName || null }); }
224
+ try { agentsFavorites.touchRecent({ name: nextAgent }); }
224
225
  catch (e) { /* best-effort */ }
225
226
  }
226
227
  sm.broadcastSessionList();
@@ -31,13 +31,10 @@ var favorites = [];
31
31
  var recents = [];
32
32
  var activeTab = "favorites"; // "favorites" | "all"
33
33
 
34
- // Agent-identity match. pluginName only meaningful for kind="plugin".
34
+ // Identity match: name is the sole key (lr-8e39, flat SDK catalog).
35
35
  function sameAgent(a, b) {
36
36
  if (!a || !b) return false;
37
- if (a.name !== b.name) return false;
38
- if (a.kind !== b.kind) return false;
39
- if (a.kind === "plugin" && (a.pluginName || null) !== (b.pluginName || null)) return false;
40
- return true;
37
+ return a.name === b.name;
41
38
  }
42
39
 
43
40
  function isFavorite(agent) {
@@ -238,8 +235,7 @@ function render() {
238
235
  function matches(a) {
239
236
  if (!f) return true;
240
237
  return (a.name || "").toLowerCase().indexOf(f) !== -1
241
- || (a.description || "").toLowerCase().indexOf(f) !== -1
242
- || (a.pluginName || "").toLowerCase().indexOf(f) !== -1;
238
+ || (a.description || "").toLowerCase().indexOf(f) !== -1;
243
239
  }
244
240
 
245
241
  // Resolve recents/favorites against the catalog so we always render fresh
@@ -282,25 +278,15 @@ function render() {
282
278
  '</div>';
283
279
  }
284
280
  } else {
285
- // All agents — group by source.
286
- var groups = { user: [], plugin: [], project: [] };
281
+ // All agents — flat list from SDK catalog (lr-8e39).
282
+ var filtered = [];
287
283
  for (var ai = 0; ai < allAgents.length; ai++) {
288
- var ag = allAgents[ai];
289
- if (!matches(ag)) continue;
290
- var bucket = ag.kind === "plugin" ? "plugin" : (ag.kind === "project" ? "project" : "user");
291
- groups[bucket].push(ag);
284
+ if (matches(allAgents[ai])) filtered.push(allAgents[ai]);
292
285
  }
293
- var groupOrder = [
294
- { key: "user", label: "User" },
295
- { key: "project", label: "Project" },
296
- { key: "plugin", label: "Plugins" },
297
- ];
298
- for (var gi = 0; gi < groupOrder.length; gi++) {
299
- var g = groupOrder[gi];
300
- if (groups[g.key].length === 0) continue;
301
- html += '<div class="cmd-palette-group-label">' + g.label + '</div>';
302
- for (var ii = 0; ii < groups[g.key].length; ii++) {
303
- var aa = groups[g.key][ii];
286
+ if (filtered.length > 0) {
287
+ html += '<div class="cmd-palette-group-label">All agents</div>';
288
+ for (var ii = 0; ii < filtered.length; ii++) {
289
+ var aa = filtered[ii];
304
290
  items.push({ type: "agent", data: aa });
305
291
  html += renderRow(flatIndex, aa);
306
292
  flatIndex++;
@@ -322,9 +308,7 @@ function render() {
322
308
 
323
309
  function renderRow(index, agent) {
324
310
  var fav = isFavorite(agent);
325
- var sourceLabel = agent.kind === "plugin"
326
- ? (agent.pluginName ? "plugin · " + escapeHtml(agent.pluginName) : "plugin")
327
- : (agent.kind === "project" ? "project" : "user");
311
+ var sourceLabel = "agent";
328
312
  var modelChip = agent.model
329
313
  ? '<span class="agent-picker-model">' + escapeHtml(agent.model) + '</span>'
330
314
  : '';
@@ -400,18 +384,12 @@ function activateItem(entry) {
400
384
  ws.send(JSON.stringify({
401
385
  type: "set_project_preferred_agent",
402
386
  slug: _preferredTargetSlug,
403
- agent: {
404
- name: entry.data.name,
405
- kind: entry.data.kind,
406
- pluginName: entry.data.pluginName || null,
407
- },
387
+ agent: { name: entry.data.name },
408
388
  }));
409
389
  } else {
410
390
  ws.send(JSON.stringify({
411
391
  type: "new_session",
412
392
  agentName: entry.data.name,
413
- agentKind: entry.data.kind,
414
- agentPluginName: entry.data.pluginName || null,
415
393
  }));
416
394
  }
417
395
  closeAgentPicker();
@@ -420,10 +398,5 @@ function activateItem(entry) {
420
398
  function toggleFavorite(agent) {
421
399
  var ws = getWs();
422
400
  if (!ws || ws.readyState !== 1) return;
423
- ws.send(JSON.stringify({
424
- type: "toggle_agent_favorite",
425
- name: agent.name,
426
- kind: agent.kind,
427
- pluginName: agent.pluginName || null,
428
- }));
401
+ ws.send(JSON.stringify({ type: "toggle_agent_favorite", name: agent.name }));
429
402
  }
@@ -89,7 +89,15 @@ export function initConnection() {
89
89
  if (state.processing !== prev.processing) {
90
90
  if (state.processing) {
91
91
  setSendBtnMode(hasSendableContent() ? "send" : "stop");
92
- } else if (state.connected) {
92
+ } else {
93
+ // Always reset to send when processing stops — even on disconnect.
94
+ // Without this, if the WS drops while Claude is running, the button
95
+ // stays in stop mode: the reconnect path skips setSendBtnMode because
96
+ // processing is already false (unchanged) by then, and the
97
+ // _sendBtnMode cache prevents the DOM from self-correcting.
98
+ // Calling setSendBtnMode when disconnected is harmless — the button
99
+ // is already disabled — but it ensures the cache is "send" so the
100
+ // button shows correctly when the connection is restored. (lr-e6b5-2)
93
101
  setSendBtnMode("send");
94
102
  }
95
103
  }
@@ -215,7 +215,7 @@ export function showMentionMenu(query) {
215
215
  var menuEl = document.getElementById("mention-menu");
216
216
  if (!menuEl) return;
217
217
 
218
- menuEl.innerHTML = '<div class="mention-hint">Mention a Mate or teammate &mdash; the coding agent stays out of this exchange until your next message<button class="mention-close-btn" aria-label="Close">&times;</button></div>' +
218
+ menuEl.innerHTML = '<div class="mention-hint">Mention a teammate or side channel &mdash; the coding agent stays out of this exchange until your next message<button class="mention-close-btn" aria-label="Close">&times;</button></div>' +
219
219
  mentionFiltered.map(function (c, i) {
220
220
  var vendorIcons = { claude: "/claude-code-avatar.png", codex: "/codex-avatar.png" };
221
221
  var vendorBadge = (c.kind === "mate" && vendorIcons[c.vendor]) ? '<img class="mention-item-vendor-badge" src="' + vendorIcons[c.vendor] + '" alt="' + escapeHtml(c.vendor) + '">' : '';
package/lib/sdk-bridge.js CHANGED
@@ -8,7 +8,6 @@ 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 agentsModule = require("./agents");
12
11
 
13
12
  // Extract serializable tool descriptors from MCP server instances.
14
13
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
@@ -1159,37 +1158,18 @@ function createSDKBridge(opts) {
1159
1158
  agentProgressSummaries: true,
1160
1159
  };
1161
1160
 
1162
- // lr-7db0 — surface per-session agent identity into the SDK `agent` option.
1163
- // When set, the Claude SDK applies the named agent's system prompt, tool
1164
- // restrictions, and model for the main thread of this session. The session
1165
- // still belongs to the project at `cwd`; only identity is shifted.
1166
- //
1167
- // The SDK only resolves `agent` against in-band `agents:{}` (or settings),
1168
- // not file/plugin discovery — so we materialize the discovered agent's
1169
- // definition and pass it alongside the name. If the agent can't be
1170
- // resolved (renamed, missing, parse failure) we fall through silently;
1171
- // the badge stays on the session for diagnosability but the session uses
1172
- // default identity.
1161
+ // lr-7db0 / lr-8e39 — surface per-session agent identity into the SDK
1162
+ // `agent` option. The SDK resolves the named agent from the same
1163
+ // settingSources catalog it uses internally — no in-band AgentDefinition
1164
+ // map is needed (that was a workaround for the old CLI-parse path).
1173
1165
  //
1174
1166
  // Agent injection is Claude Code-only. The Codex adapter has no equivalent
1175
- // API surface for in-band agent definition injection, so we skip this block
1176
- // entirely for Codex sessions. The UI already hides the Agent Chat entry
1177
- // point for Codex projects; this guard is belt-and-suspenders for sessions
1178
- // that carry agentName from a prior vendor or from a direct ws message.
1167
+ // API surface, so we skip this block for Codex sessions. The UI already
1168
+ // hides the Agent Chat entry point for Codex projects; this guard is
1169
+ // belt-and-suspenders for sessions that carry agentName from a prior
1170
+ // vendor switch or a direct ws message.
1179
1171
  if (session.agentName && sessionAdapter.vendor !== 'codex') {
1180
- var agentDef = null;
1181
- try { agentDef = agentsModule.getAgentDefinition(session.agentName); }
1182
- catch (e) {
1183
- console.error("[sdk-bridge] getAgentDefinition failed for " + session.agentName + ":", e.message);
1184
- }
1185
- if (agentDef) {
1186
- claudeOpts.agent = session.agentName;
1187
- var agentsMap = {};
1188
- agentsMap[session.agentName] = agentDef;
1189
- claudeOpts.agents = agentsMap;
1190
- } else {
1191
- console.warn("[sdk-bridge] session.agentName=" + session.agentName + " unresolved; not applying SDK agent option");
1192
- }
1172
+ claudeOpts.agent = session.agentName;
1193
1173
  }
1194
1174
 
1195
1175
  // Per-loop settings override global defaults when present
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.0.3",
6
+ "version": "1.0.4-beta.2",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic": "./bin/cli.js",