agent-lyra 0.12.0 → 0.14.0

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.
@@ -0,0 +1,167 @@
1
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+
5
+ const protocol = "2025-06-18";
6
+ const limit = 256 * 1024;
7
+ const safeName = /^[A-Za-z0-9_.-]{1,128}$/;
8
+
9
+ export function mcpEndpoint(value) {
10
+ let url;
11
+ try { url = new URL(value); } catch {}
12
+ if (url?.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port ||
13
+ url.username || url.password || url.search || url.hash || url.href.length > 512) {
14
+ throw new Error("Enter a local MCP HTTP URL with an explicit port, such as http://127.0.0.1:3001/mcp.");
15
+ }
16
+ return url.href;
17
+ }
18
+
19
+ async function withSession(endpoint, action, signal) {
20
+ const url = mcpEndpoint(endpoint);
21
+ const timeout = AbortSignal.timeout(8000);
22
+ const requestSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
23
+ let negotiated = protocol;
24
+ let sessionId;
25
+ let id = 0;
26
+ const headers = () => ({
27
+ "Content-Type": "application/json", Accept: "application/json, text/event-stream",
28
+ "MCP-Protocol-Version": negotiated, ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
29
+ });
30
+
31
+ async function request(method, params, notification = false) {
32
+ const messageId = notification ? undefined : ++id;
33
+ const response = await fetch(url, {
34
+ method: "POST", redirect: "error", headers: headers(), signal: requestSignal,
35
+ body: JSON.stringify({ jsonrpc: "2.0", id: messageId, method, params }),
36
+ });
37
+ try {
38
+ if (!response.ok) throw new Error("MCP HTTP request failed.");
39
+ if (method === "initialize") sessionId = response.headers.get("mcp-session-id") || undefined;
40
+ if (notification) return;
41
+ const reader = response.body?.getReader();
42
+ if (!reader) throw new Error("Empty MCP response.");
43
+ try {
44
+ const decoder = new TextDecoder();
45
+ const stream = response.headers.get("content-type")?.startsWith("text/event-stream");
46
+ let buffer = "";
47
+ let bytes = 0;
48
+ for (;;) {
49
+ const { value, done } = await reader.read();
50
+ bytes += value?.byteLength ?? 0;
51
+ if (bytes > limit) throw new Error("MCP response exceeded size limit.");
52
+ buffer += decoder.decode(value, { stream: !done });
53
+ if (stream) {
54
+ const frames = buffer.split(/\r?\n\r?\n/);
55
+ buffer = frames.pop();
56
+ if (done && buffer.trim()) frames.push(buffer);
57
+ for (const frame of frames) {
58
+ const data = frame.split(/\r?\n/).filter(line => line.startsWith("data:"))
59
+ .map(line => line.slice(5).trimStart()).join("\n");
60
+ if (!data) continue;
61
+ const result = JSON.parse(data);
62
+ if (result.id === messageId) return rpcResult(result, messageId);
63
+ }
64
+ if (done) throw new Error("MCP response did not contain the tool result.");
65
+ } else if (done) return rpcResult(JSON.parse(buffer), messageId);
66
+ }
67
+ } finally { void reader.cancel().catch(() => {}); }
68
+ } finally {
69
+ if (!response.bodyUsed) void response.body?.cancel().catch(() => {});
70
+ }
71
+ }
72
+
73
+ try {
74
+ const init = await request("initialize", {
75
+ protocolVersion: protocol, capabilities: {}, clientInfo: { name: "AgentLyra Workbench", version: "1" },
76
+ });
77
+ if (init.protocolVersion !== protocol && init.protocolVersion !== "2025-11-25") {
78
+ throw new Error("Unsupported MCP protocol version.");
79
+ }
80
+ negotiated = init.protocolVersion;
81
+ await request("notifications/initialized", undefined, true);
82
+ return await action(request);
83
+ } catch {
84
+ signal?.throwIfAborted();
85
+ throw new Error("The MCP request failed. Check the local server URL, protocol support, and server logs.");
86
+ } finally {
87
+ if (sessionId) {
88
+ try {
89
+ const response = await fetch(url, { method: "DELETE", redirect: "error", headers: headers(), signal: AbortSignal.timeout(1000) });
90
+ void response.body?.cancel().catch(() => {});
91
+ } catch { /* Session cleanup is best effort. */ }
92
+ }
93
+ }
94
+ }
95
+
96
+ function rpcResult(message, id) {
97
+ if (message?.jsonrpc !== "2.0" || message.id !== id || !message.result || message.error) {
98
+ throw new Error("Invalid MCP response.");
99
+ }
100
+ return message.result;
101
+ }
102
+
103
+ export async function inspectMcp(endpoint) {
104
+ return withSession(endpoint, async request => {
105
+ const tools = new Map();
106
+ let cursor;
107
+ for (let page = 0; page < 8; page++) {
108
+ const result = await request("tools/list", cursor ? { cursor } : {});
109
+ if (!Array.isArray(result.tools)) throw new Error("Invalid MCP tools list.");
110
+ for (const tool of result.tools) {
111
+ if (typeof tool?.name !== "string" || !safeName.test(tool.name)) continue;
112
+ const input = tool.inputSchema;
113
+ if (input?.type !== "object") continue;
114
+ if (tools.size >= 100) throw new Error("Too many MCP tools.");
115
+ tools.set(tool.name, {
116
+ name: tool.name,
117
+ description: typeof tool.description === "string" ? tool.description.slice(0, 512) : "",
118
+ inputSchema: JSON.stringify(input).length <= 8192 ? input : { type: "object" },
119
+ });
120
+ }
121
+ cursor = result.nextCursor;
122
+ if (!cursor) return [...tools.values()];
123
+ if (typeof cursor !== "string" || cursor.length > 1024) break;
124
+ }
125
+ throw new Error("MCP tool listing exceeded the page limit.");
126
+ });
127
+ }
128
+
129
+ export async function readMcpConfig(root) {
130
+ const directory = join(root, ".lyra");
131
+ const filename = join(directory, "workbench-mcp.json");
132
+ const directoryStat = await lstat(directory).catch(error => { if (error.code !== "ENOENT") throw error; });
133
+ if (!directoryStat) return null;
134
+ if (!directoryStat.isDirectory()) throw new Error("Use a regular .lyra directory.");
135
+ const stat = await lstat(filename).catch(error => { if (error.code !== "ENOENT") throw error; });
136
+ if (!stat) return null;
137
+ if (!stat.isFile() || stat.size > limit) throw new Error("Invalid Workbench MCP configuration.");
138
+ const config = JSON.parse(await readFile(filename, "utf8"));
139
+ if (config?.version !== 1 || !Array.isArray(config.grants) ||
140
+ config.grants.some(grant => typeof grant?.agentId !== "string" || !Array.isArray(grant.tools) ||
141
+ grant.tools.some(name => typeof name !== "string" || !safeName.test(name)))) {
142
+ throw new Error("Invalid Workbench MCP configuration.");
143
+ }
144
+ return { version: 1, endpoint: mcpEndpoint(config.endpoint), grants: config.grants };
145
+ }
146
+
147
+ export async function saveMcpConfig(root, config) {
148
+ const directory = join(root, ".lyra");
149
+ await mkdir(directory, { recursive: true });
150
+ if (!(await lstat(directory)).isDirectory()) throw new Error("Use a regular .lyra directory.");
151
+ const data = JSON.stringify(config, null, 2) + "\n";
152
+ if (Buffer.byteLength(data) > limit) throw new Error("Too many tool grants in this project.");
153
+ const temporary = join(directory, ".workbench-mcp-" + randomUUID());
154
+ try {
155
+ await writeFile(temporary, data, { flag: "wx", mode: 0o600 });
156
+ await rename(temporary, join(directory, "workbench-mcp.json"));
157
+ } finally { await rm(temporary, { force: true }); }
158
+ }
159
+
160
+ export async function callGrantedMcpTool(config, name, args, signal) {
161
+ if (!config?.tools?.includes(name)) throw new Error("This MCP tool has not been granted to the agent.");
162
+ return withSession(config.endpoint, request => request("tools/call", { name, arguments: args }), signal);
163
+ }
164
+
165
+ export async function clearMcpConfig(root) {
166
+ if (await readMcpConfig(root)) await rm(join(root, ".lyra", "workbench-mcp.json"));
167
+ }
@@ -0,0 +1,97 @@
1
+ export function mountMcpPanel(api, project) {
2
+ const $ = id => document.getElementById(id);
3
+ const form = $("mcp-connect");
4
+ const endpoint = $("mcp-endpoint");
5
+ const connect = $("mcp-inspect");
6
+ const disconnect = $("mcp-disconnect");
7
+ const status = $("mcp-status");
8
+ const agent = $("mcp-agent");
9
+ const list = $("mcp-tool-list");
10
+ const save = $("mcp-save");
11
+ let config;
12
+ let tools;
13
+ let busy = false;
14
+
15
+ const create = (tag, text) => Object.assign(document.createElement(tag), { textContent: text });
16
+ function render() {
17
+ const selected = agent.value;
18
+ const agents = project().agents.filter(item => item.source === "programmatic");
19
+ agent.replaceChildren(new Option("Choose an executable agent", ""), ...agents.map(item => new Option(item.name, item.id)));
20
+ if (agents.some(item => item.id === selected)) agent.value = selected;
21
+ agent.disabled = busy || !config || !agents.length;
22
+ connect.disabled = disconnect.disabled = endpoint.disabled = busy;
23
+ disconnect.hidden = !config;
24
+ save.disabled = busy || !agent.value || !tools;
25
+ list.replaceChildren();
26
+ if (!config) return;
27
+ if (!tools) {
28
+ list.append(create("p", "Server saved. Select Inspect server to refresh its tools and edit access."));
29
+ return;
30
+ }
31
+ if (!tools.length) list.append(create("p", "This server advertised no compatible tools."));
32
+ const granted = config.grants.find(item => item.agentId === agent.value)?.tools ?? [];
33
+ for (const tool of tools) {
34
+ const row = create("article", "");
35
+ row.className = "mcp-tool";
36
+ const label = create("label", "");
37
+ const check = document.createElement("input");
38
+ check.type = "checkbox";
39
+ check.value = tool.name;
40
+ check.disabled = busy || !agent.value;
41
+ check.checked = granted.includes(tool.name);
42
+ label.append(check, create("strong", tool.name));
43
+ const details = create("details", "");
44
+ details.append(create("summary", "Input schema"), create("pre", JSON.stringify(tool.inputSchema, null, 2)));
45
+ row.append(label);
46
+ if (tool.description) row.append(create("p", tool.description));
47
+ row.append(details);
48
+ list.append(row);
49
+ }
50
+ }
51
+
52
+ async function update(message, task) {
53
+ if (busy) return;
54
+ const checks = [...list.querySelectorAll("input[type=checkbox]:checked")].map(input => input.value);
55
+ busy = true;
56
+ status.textContent = message;
57
+ render();
58
+ try { status.textContent = await task(checks); }
59
+ catch (error) { status.textContent = error.message; }
60
+ finally { busy = false; render(); }
61
+ }
62
+
63
+ form.onsubmit = event => {
64
+ event.preventDefault();
65
+ const url = endpoint.value;
66
+ if (config && url !== config.endpoint && config.grants.length &&
67
+ !window.confirm("Replace this server and clear its saved agent grants?")) return;
68
+ void update("Inspecting the local server…", async () => {
69
+ ({ config, tools } = await api("mcp/connect", { endpoint: url }));
70
+ endpoint.value = config.endpoint;
71
+ return "Server saved. " + tools.length + (tools.length === 1 ? " tool found." : " tools found.");
72
+ });
73
+ };
74
+ agent.onchange = render;
75
+ save.onclick = () => update("Saving tool access…", async selected => {
76
+ ({ config } = await api("mcp/grant", { agentId: agent.value, tools: selected }));
77
+ return "Tool access saved.";
78
+ });
79
+ disconnect.onclick = () => {
80
+ if (!window.confirm("Disconnect this server and clear its saved agent grants?")) return;
81
+ void update("Disconnecting…", async () => {
82
+ await api("mcp/disconnect", {});
83
+ config = tools = undefined;
84
+ endpoint.value = "";
85
+ return "Server disconnected.";
86
+ });
87
+ };
88
+
89
+ return () => {
90
+ if (config) return render();
91
+ return update("Loading tool connections…", async () => {
92
+ ({ config } = await api("mcp"));
93
+ if (config) endpoint.value = config.endpoint;
94
+ return "";
95
+ });
96
+ };
97
+ }
@@ -1,34 +1,42 @@
1
+ import { readMcpConfig } from "./mcp-connection.js";
1
2
  import { execFile } from "node:child_process";
2
- import { lstat } from "node:fs/promises";
3
- import { join } from "node:path";
3
+ import { resolveAgentSource } from "./code-discovery.js";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
6
  export function programmaticDescriptor(item) {
7
7
  if (!["lyra-node", "lyra-python"].includes(item?.runtime)) return null;
8
8
  const file = item.file;
9
- const extension = item.runtime === "lyra-python" ? /\.py$/ : /\.(?:mjs|js)$/;
10
- if (typeof file !== "string" || !/^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.[a-z]+$/.test(file) ||
9
+ const extension = item.runtime === "lyra-python" ? /\.py$/ : /\.(?:mjs|js|mts|ts)$/;
10
+ const projectRelative = item.projectRelative === true;
11
+ const validPath = projectRelative ? /^(?:[a-zA-Z0-9_.-]+\/)*[a-zA-Z0-9_-]+\.[a-z]+$/ : /^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.[a-z]+$/;
12
+ if (typeof file !== "string" || !validPath.test(file) || file.split("/").some(part => part === "." || part === "..") ||
11
13
  !extension.test(file) || !["text", "json", undefined].includes(item.input)) return null;
12
- return { runtime: item.runtime, file, input: item.input ?? "text" };
14
+ return { runtime: item.runtime, file, input: item.input ?? "text", ...(projectRelative ? { projectRelative } : {}) };
13
15
  }
14
16
 
15
17
  export async function runProgrammatic(root, agent, input, onActivity, onLearning) {
16
- let directory = root;
17
- for (const part of [".lyra", "agents"]) {
18
- directory = join(directory, part);
19
- if (!(await lstat(directory)).isDirectory()) throw new Error("Use regular .lyra/agents directories.");
20
- }
21
- const source = join(directory, agent.file);
22
- if (!(await lstat(source)).isFile()) throw new Error("Use a regular registered agent file.");
18
+ const source = await resolveAgentSource(root, agent.file, agent.projectRelative);
23
19
  const python = agent.runtime === "lyra-python";
24
20
  const executable = python
25
21
  ? process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3")
26
22
  : process.execPath;
27
23
  const runner = fileURLToPath(new URL(python ? "./python-agent.py" : "./programmatic-runner.mjs", import.meta.url));
28
- const args = python ? [runner, source, "--programmatic"] : [runner, source];
24
+ const args = python ? [runner, source, "--programmatic"]
25
+ : [...(/\.m?ts$/.test(source) ? ["--experimental-strip-types"] : []), runner, source];
26
+ const config = await readMcpConfig(root);
27
+ const grant = config?.grants.find(item => item.agentId === agent.id);
28
+ const env = { ...process.env };
29
+ delete env.LYRA_WORKBENCH_MCP_GRANT;
30
+ delete env.LYRA_WORKBENCH_MCP_BRIDGE;
31
+ delete env.LYRA_WORKBENCH_MCP_NODE;
32
+ if (grant) {
33
+ env.LYRA_WORKBENCH_MCP_GRANT = JSON.stringify({ endpoint: config.endpoint, tools: grant.tools });
34
+ env.LYRA_WORKBENCH_MCP_BRIDGE = fileURLToPath(new URL("./mcp-bridge.mjs", import.meta.url));
35
+ env.LYRA_WORKBENCH_MCP_NODE = process.execPath;
36
+ }
29
37
  return new Promise((resolve, reject) => {
30
38
  const child = execFile(executable, args, {
31
- cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
39
+ cwd: root, env, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
32
40
  }, (error, stdout) => {
33
41
  if (error?.code === "ENOENT" && python) {
34
42
  return reject(new Error("Install the Python SDK in your environment and set LYRA_PYTHON to its interpreter."));
@@ -55,7 +55,7 @@ export function readLocalAgent(source) {
55
55
  if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
56
56
  if (mode && mode !== "standalone") return null;
57
57
  if (!prompt || prompt.length > 16_000) return null;
58
- return { id: "local:" + id, name, source: "local", prompt };
58
+ return { id: "local:" + id, name, source: "local", description: markdownValue(front[1], "description"), prompt };
59
59
  }
60
60
 
61
61
  export async function readCatalog(root, { includeSkillInstructions = false } = {}) {
@@ -335,7 +335,7 @@ export async function runSelection(root, { targets, input, model, provider }, ca
335
335
  steps.push(status);
336
336
  console.info('[Lyra Studio]', JSON.stringify({ event: 'step.started', traceId: status.traceId, agent: agent.name, source: agent.source }));
337
337
  const started = Date.now();
338
- record("step.started", stepEventFields(agent.id, status));
338
+ record("step.started", { ...stepEventFields(agent.id, status), agentName: agent.name.slice(0, 160) });
339
339
  let output;
340
340
  let run;
341
341
  let activityCount = 0;
@@ -3,6 +3,7 @@ import asyncio
3
3
  import json
4
4
  import runpy
5
5
  import sys
6
+ from pathlib import Path
6
7
  from contextlib import redirect_stdout
7
8
 
8
9
 
@@ -11,6 +12,8 @@ def main():
11
12
  payload = json.load(sys.stdin)
12
13
  with redirect_stdout(sys.stderr):
13
14
  if skill == "--programmatic":
15
+ sys.path.insert(0, str(Path.cwd()))
16
+ sys.path.insert(0, str(Path(source).parent))
14
17
  from lyra import Agent
15
18
  else:
16
19
  from lyra.standalone import Agent
@@ -51,7 +51,13 @@ export async function openRunHistory(root) {
51
51
  const insertEvent = db.prepare("INSERT INTO studio_run_events (run_id, sequence, body) VALUES (?, ?, ?)");
52
52
  const finishRun = db.prepare("UPDATE studio_runs SET status = ?, ended_at = ? WHERE id = ? AND status = 'running'");
53
53
  const prune = db.prepare("DELETE FROM studio_runs WHERE started_at < ?");
54
- const list = db.prepare("SELECT id, started_at AS startedAt, status, ended_at AS endedAt FROM studio_runs ORDER BY started_at DESC, id LIMIT 100");
54
+ const list = db.prepare(`
55
+ SELECT r.id, r.started_at AS startedAt, r.status, r.ended_at AS endedAt,
56
+ (SELECT e.body FROM studio_run_events e WHERE e.run_id = r.id
57
+ AND json_extract(e.body, '$.type') = 'step.started' ORDER BY e.sequence LIMIT 1) AS firstStep,
58
+ (SELECT COUNT(*) FROM studio_run_events e WHERE e.run_id = r.id
59
+ AND json_extract(e.body, '$.type') = 'step.started') AS steps
60
+ FROM studio_runs r ORDER BY r.started_at DESC, r.id LIMIT 100`);
55
61
  const detail = db.prepare("SELECT id, started_at AS startedAt, status, ended_at AS endedAt FROM studio_runs WHERE id = ?");
56
62
  const insertLearning = db.prepare("INSERT INTO studio_run_learnings (run_id, position, body) VALUES (?, ?, ?)");
57
63
  const readLearnings = db.prepare("SELECT body FROM studio_run_learnings WHERE run_id = ? ORDER BY position");
@@ -86,7 +92,10 @@ export async function openRunHistory(root) {
86
92
  }
87
93
  });
88
94
  },
89
- list: () => list.all(),
95
+ list: () => list.all().map(({ firstStep, ...run }) => {
96
+ const step = firstStep && JSON.parse(firstStep);
97
+ return { ...run, agentName: step?.agentName ?? step?.agentId, source: step?.source };
98
+ }),
90
99
  suggestions(id) {
91
100
  if (detail.get(id)?.status !== "completed") return [];
92
101
  return readLearnings.all(id).map(row => JSON.parse(row.body));
@@ -1,6 +1,8 @@
1
+ import { clearMcpConfig, inspectMcp, mcpEndpoint, readMcpConfig, saveMcpConfig } from "./mcp-connection.js";
1
2
  import { discoverFrameworkAgents, syncFrameworkAgent } from "../framework/agent.js";
2
3
  import { memoryActions } from "./memory-actions.js";
3
- import { buildKnowledgeGraph, graphTokenLedger, knowledgeGraph } from "./graphsnip-workbench.js";
4
+ import { discoverCodeAgents, registerCodeAgents } from "./code-discovery.js";
5
+ import { buildKnowledgeGraph, graphTokenLedger, knowledgeGraph, readGraphReport } from "./graphsnip-workbench.js";
4
6
  import { openRunHistory } from "./run-history.js";
5
7
  import { createServer } from "node:http";
6
8
  import { readFile } from "node:fs/promises";
@@ -16,6 +18,7 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
16
18
  for (const [route, name, mime] of [
17
19
  ["/lyra-icon.png", "lyra-icon.png", "image/png"],
18
20
  ["/mission-ui.js", "mission-ui.js", "text/javascript"], ["/mission-ui.css", "mission-ui.css", "text/css"],
21
+ ["/mcp-panel.js", "mcp-panel.js", "text/javascript"],
19
22
  ["/intelligence.js", "intelligence.js", "text/javascript"],
20
23
  ["/history-panel.js", "history-panel.js", "text/javascript"],
21
24
  ["/memory-panel.js", "memory-panel.js", "text/javascript"],
@@ -35,6 +38,31 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
35
38
  await saveOpenAIKey(key);
36
39
  return { configured: true };
37
40
  }],
41
+ ["/api/mcp/connect", async ({ endpoint }) => {
42
+ endpoint = mcpEndpoint(endpoint);
43
+ const tools = await inspectMcp(endpoint);
44
+ const current = await readMcpConfig(root);
45
+ const config = current?.endpoint === endpoint ? current : { version: 1, endpoint, grants: [] };
46
+ await saveMcpConfig(root, config);
47
+ return { config, tools };
48
+ }],
49
+ ["/api/mcp/disconnect", async () => {
50
+ await clearMcpConfig(root);
51
+ return {};
52
+ }],
53
+ ["/api/mcp/grant", async ({ agentId, tools }) => {
54
+ const config = await readMcpConfig(root);
55
+ const agent = (await readCatalog(root)).agents.get(agentId);
56
+ if (!config || agent?.source !== "programmatic") throw new Error("Choose a registered executable agent and connect a server.");
57
+ if (!Array.isArray(tools) || tools.length > 100) throw new Error("Choose tools from the connected server.");
58
+ const advertised = tools.length ? new Set((await inspectMcp(config.endpoint)).map(tool => tool.name)) : new Set();
59
+ if (tools.some(name => !advertised.has(name))) throw new Error("The server tool list changed. Inspect the server again.");
60
+ config.grants = config.grants.filter(grant => grant.agentId !== agentId);
61
+ if (tools.length) config.grants.push({ agentId, tools: [...new Set(tools)] });
62
+ await saveMcpConfig(root, config);
63
+ return { config };
64
+ }],
65
+ ["/api/code-agents/add", async ({ ids }) => registerCodeAgents(root, ids, (await readCatalog(root)).agents)],
38
66
  ["/api/graphsnip/build", () => buildKnowledgeGraph(root)],
39
67
  ["/api/work-locally", async () => {
40
68
  await switchMode(root, "standalone", [], { output: { write() {} } });
@@ -86,7 +114,7 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
86
114
  const send = (status, data, type = "application/json", headers = {}) => {
87
115
  res.writeHead(status, {
88
116
  "Content-Type": type.startsWith("image/") ? type : type + "; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
89
- "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'none'",
117
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'",
90
118
  ...headers,
91
119
  });
92
120
  res.end(type === "application/json" ? JSON.stringify(data) : data);
@@ -109,8 +137,8 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
109
137
  mode,
110
138
  hasCloudKey,
111
139
  cloudConnected: mode !== "standalone" && hasCloudKey,
112
- agents: [...catalog.agents.values()].map(({ id, name, source, framework, syncStatus, linkedLocalId }) =>
113
- ({ id, name, source, framework, syncStatus, linkedLocalId })),
140
+ agents: [...catalog.agents.values()].map(({ id, name, source, framework, syncStatus, linkedLocalId, file, description }) =>
141
+ ({ id, name, source, framework, syncStatus, linkedLocalId, file, description })),
114
142
  frameworkCandidates: appCatalog ? [] : await discoverFrameworkAgents(root).catch(() => []),
115
143
  workflows: catalog.workflows.map(({ id, name, runnable, source }) => ({ id, name, runnable, source })),
116
144
  skills: (catalog.skills ?? []).map(({ id, name, source }) => ({ id, name, source })),
@@ -119,6 +147,16 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
119
147
  });
120
148
  }
121
149
  if (!readOnly && req.method === "GET") {
150
+ if (req.url === "/api/mcp") return send(200, { config: await readMcpConfig(root) });
151
+ if (req.url === "/api/code-agents") return send(200, { candidates: await discoverCodeAgents(root, (await readCatalog(root)).agents) });
152
+ if (req.url === "/api/graphsnip/report") {
153
+ const report = await readGraphReport(root);
154
+ if (!report) return send(404, { error: "GraphSnip report is missing or too large to preview." });
155
+ return send(200, report, "text/html", {
156
+ "Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'; frame-ancestors 'self'",
157
+ "Referrer-Policy": "no-referrer",
158
+ });
159
+ }
122
160
  if (req.url === "/api/graphsnip/graph") return send(200, await knowledgeGraph(root));
123
161
  if (req.url === "/api/graphsnip/tokens") return send(200, await graphTokenLedger(root));
124
162
  }
@@ -222,9 +260,9 @@ export async function startStudio(root, { port = 0, run = runSelection, pull = p
222
260
  return { server, url: "http://127.0.0.1:" + server.address().port + "/" };
223
261
  }
224
262
 
225
- export async function runStudio(args, output = process.stdout, { legacy = false } = {}) {
263
+ export async function runStudio(args, output = process.stdout) {
226
264
  if (args[0] === "--help") {
227
- output.write("Usage: agent-lyra workbench | agent-lyra workbench pull | agent-lyra workbench push <local-agent-id> | agent-lyra workbench pull-agent <local-agent-id> | agent-lyra workbench push-workflow <workflow-id> | agent-lyra workbench pull-workflow <workflow-id> | agent-lyra workbench push-team <team-id> | agent-lyra workbench pull-team <team-id> | agent-lyra workbench push-skill <skill-id> | agent-lyra workbench pull-skill <skill-id>\nWorkbench listens on 127.0.0.1:4174. The studio command is a compatibility alias. Set LYRA_STUDIO_PORT to override it, or use 0 to pick a free port.\n");
265
+ output.write("Usage: agent-lyra workbench | agent-lyra workbench pull | agent-lyra workbench push <local-agent-id> | agent-lyra workbench pull-agent <local-agent-id> | agent-lyra workbench push-workflow <workflow-id> | agent-lyra workbench pull-workflow <workflow-id> | agent-lyra workbench push-team <team-id> | agent-lyra workbench pull-team <team-id> | agent-lyra workbench push-skill <skill-id> | agent-lyra workbench pull-skill <skill-id>\nWorkbench listens on 127.0.0.1:4174. Set LYRA_STUDIO_PORT to override it, or use 0 to pick a free port.\n");
228
266
  return;
229
267
  }
230
268
  if (args.length === 1 && args[0] === "pull") {
@@ -264,5 +302,5 @@ export async function runStudio(args, output = process.stdout, { legacy = false
264
302
  }
265
303
  throw error;
266
304
  });
267
- output.write((legacy ? "AgentLyra Studio: " : "AgentLyra Workbench: ") + url + "\n");
305
+ output.write("AgentLyra Workbench: " + url + "\n");
268
306
  }
@@ -534,3 +534,65 @@ main > aside, main > section { border-color: var(--studio-line); border-radius:
534
534
 
535
535
  .learning-suggestions { margin: .7rem 0; padding: .65rem; background: var(--studio-tint); border-radius: 8px; }
536
536
  .learning-suggestions button { margin: .3rem .35rem 0 0; }
537
+
538
+ .graphsnip-report { display: block; width: 100%; min-height: 32rem; border: 1px solid #dce7df; border-radius: 8px; background: white; }
539
+ /* Workbench uses the same compact surfaces for local and connected projects. */
540
+ :root { --wb-blue:#245ce5; --wb-ink:#15243a; --wb-muted:#54657f; --wb-line:#dce4f0; --wb-tint:#edf3ff; }
541
+ body { font-family: "Inter", "Segoe UI", system-ui, sans-serif; }
542
+ .studio-header { color:var(--wb-ink); border-color:var(--wb-line); }
543
+ #studio-views button[aria-pressed="true"], .workbench-filters button[aria-pressed="true"] { color:#164abf; background:var(--wb-tint); border-color:#c7d8fc; }
544
+ #library.registry-view #library-content { max-width:none; }
545
+ .registry-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,15rem),1fr)); gap:1rem; margin-top:.9rem; }
546
+ .registry-grid .lyra-run-card { display:flex; flex-direction:column; min-width:0; border:1px solid var(--wb-line); border-top:2px solid var(--wb-blue); padding:1rem; border-radius:12px; background:#fff; }
547
+ .registry-grid .lyra-run-card > p { color:var(--wb-muted); flex:1; overflow-wrap:anywhere; margin:.8rem 0 1rem; }
548
+ .registry-grid .lyra-run-action { background:var(--wb-blue); color:white; flex:1; }
549
+ .registry-card-heading { display:flex; gap:.7rem; align-items:center; color:var(--wb-ink); overflow-wrap:anywhere; }
550
+ .registry-card-heading .agent-meta { color:var(--wb-muted); }
551
+ .registry-icon { display:grid; place-items:center; flex:0 0 2.3rem; height:2.3rem; border-radius:9px; background:#e5edff; color:#174fc6; font-weight:700; }
552
+ .workbench-filters { display:flex; gap:.5rem; flex-wrap:wrap; align-items:center; margin:.8rem 0; }
553
+ .workbench-filters input { width:min(100%,18rem); }
554
+ .discovery-callout { display:flex; align-items:center; justify-content:space-between; gap:.8rem; flex-wrap:wrap; border:1px solid #d2defc; background:var(--wb-tint); border-radius:10px; margin:.7rem 0; padding:.75rem 1rem; color:var(--wb-ink); }
555
+ .discovery-callout p { margin:.2rem 0 0; color:var(--wb-muted); }
556
+ .discovery-callout button, #add-discovered { background:var(--wb-blue); border-color:var(--wb-blue); color:#fff; }
557
+ .discovery-option { display:flex; align-items:center; gap:.7rem; padding:.85rem; margin:.5rem 0; border:1px solid var(--wb-line); border-radius:10px; }
558
+ .discovery-option code { display:block; color:var(--wb-muted); overflow-wrap:anywhere; }
559
+ #discovery-review[open], #history-detail[open] { position:fixed; inset:0 0 0 auto; width:min(100%,30rem); height:100dvh; max-height:none; margin:0; padding:1.15rem; background:white; color:var(--wb-ink); border-left:1px solid var(--wb-line); box-shadow:-8px 0 36px #15243a1a; z-index:8; overflow:auto; }
560
+ #discovery-review header, #history-detail header { border-bottom:1px solid var(--wb-line); margin-bottom:1rem; }
561
+ #add-discovered { width:100%; }
562
+ .workbench-metrics { display:grid; grid-template-columns:repeat(auto-fit,minmax(9rem,1fr)); gap:.7rem; }
563
+ .workbench-metrics > div { display:grid; gap:.3rem; padding:.85rem 1rem; border:1px solid var(--wb-line); border-radius:10px; background:#f5f7fb; color:var(--wb-muted); }
564
+ .workbench-metrics strong { font-size:1.65rem; line-height:1.2; color:var(--wb-ink); }
565
+ #history-panel .history-content { display:block; max-width:none; }
566
+ #history-list { overflow:auto; border:1px solid var(--wb-line); border-radius:11px; }
567
+ #history-list > p { padding:.65rem; }
568
+ .workbench-run-table { width:100%; border-collapse:collapse; font-size:.88rem; color:var(--wb-ink); }
569
+ .workbench-run-table th, .workbench-run-table td { padding:.8rem .9rem; border-bottom:1px solid var(--wb-line); text-align:left; }
570
+ .workbench-run-table th { background:#f5f7fb; color:var(--wb-muted); font-size:.76rem; }
571
+ .workbench-run-table td small { display:block; color:var(--wb-muted); }
572
+ .workbench-run-table a { color:#1849b4; font-weight:650; }
573
+ .workbench-run-table .selected-run { background:var(--wb-tint); }
574
+ #history-detail .history-detail-tabs button[aria-pressed="true"] { background:var(--wb-tint); color:#164abf; border-color:#c7d8fc; }
575
+ #drawer .primary { background:var(--wb-blue); border-color:var(--wb-blue); }
576
+
577
+ #drawer { border-left:1px solid var(--wb-line); box-shadow:-8px 0 36px #15243a18; color:var(--wb-ink); }
578
+ #drawer #run-plan { background:#f5f7fb; border-color:var(--wb-line); }
579
+ @media (min-width: 1060px) {
580
+ body:not(.exported) { padding-left:14rem; }
581
+ body:not(.exported) .studio-header { min-height:3.9rem; grid-template-columns:1fr; justify-items:end; }
582
+ body:not(.exported) .studio-brand { position:fixed; inset:0 auto auto 0; width:14rem; height:3.9rem; padding:.85rem; background:white; border-right:1px solid var(--wb-line); border-bottom:1px solid var(--wb-line); z-index:4; }
583
+ body:not(.exported) #studio-views { position:fixed; inset:3.9rem auto 0 0; width:14rem; display:flex; flex-direction:column; flex-wrap:nowrap; align-items:stretch; justify-content:flex-start; gap:.85rem; background:white; border:0; border-right:1px solid var(--wb-line); padding:.9rem; overflow-y:auto; z-index:4; }
584
+ #studio-views > div { flex-direction:column; align-items:stretch; }
585
+ #studio-views > div > span { padding:.2rem .45rem; }
586
+ #studio-views button { text-align:left; }
587
+ #library { top:5rem; }
588
+ }
589
+
590
+ #mcp-panel { grid-column:1 / -1; }
591
+ .mcp-connect { display:grid; gap:.55rem; max-width:35rem; }
592
+ #mcp-agent { display:block; max-width:35rem; margin:.35rem 0 1rem; }
593
+ #mcp-tool-list { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,18rem),1fr)); gap:.7rem; margin-bottom:1rem; }
594
+ .mcp-tool { padding:1rem; border:1px solid var(--wb-line); border-radius:.65rem; }
595
+ .mcp-tool label { display:flex; align-items:center; gap:.6rem; overflow-wrap:anywhere; }
596
+ .mcp-tool input { width:auto; }
597
+ .mcp-tool p { overflow-wrap:anywhere; }
598
+ .mcp-tool pre { max-height:14rem; overflow:auto; font-size:.8rem; }