agent-lyra 0.3.2 → 0.6.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,16 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <title>AgentLyra Studio</title><link rel="stylesheet" href="/studio.css"><link rel="stylesheet" href="/agent-ui.css"><script src="/studio.js" type="module"></script>
6
+ </head>
7
+ <body>
8
+ <header><strong>AgentLyra Studio</strong><span id="project-name"></span><div><button id="refresh">Reload agents</button> <button id="pull">Pull from Cloud</button> <button class="primary" id="save">Save layout</button></div></header>
9
+ <p role="status" id="status"></p>
10
+ <main>
11
+ <aside><h2>Components</h2><div id="palette"></div><h2>Agents</h2><div id="agents"></div><h2>Workflows</h2><div id="workflows"></div><h2>Teams</h2><div id="teams"></div></aside>
12
+ <section><h1>App canvas</h1><p>Drop a component here or select it from the palette. Use the inspector to bind an Agent card or Run button to your inputs and outputs.</p><div id="canvas"></div></section>
13
+ <aside><h2>Inspector</h2><div id="inspector"></div></aside>
14
+ </main>
15
+ <dialog id="drawer" aria-labelledby="run-title"><form id="runner"><div id="run-header"></div><label for="model">Local model</label><select id="model"></select><label for="prompt">Input</label><textarea id="prompt" maxlength="4000" rows="6" required></textarea><button class="primary" id="run">Run</button><p role="status" id="run-status"></p><pre id="run-result"></pre></form></dialog>
16
+ </body></html>
@@ -0,0 +1,190 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createSavedAgentClient } from "../app-builder/saved-app.js";
5
+ import { createOpenAIProvider, openStore } from "../runtime/local-cli.js";
6
+ import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
7
+ import { runAgent } from "../runtime/run-agent.js";
8
+
9
+ export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
10
+ const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
11
+ const cloudId = /^[a-f0-9]{24}$/i;
12
+
13
+ async function files(directory, extension) {
14
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
15
+ if (error.code === "ENOENT") return [];
16
+ throw error;
17
+ });
18
+ return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
19
+ }
20
+
21
+ function markdownValue(source, name) {
22
+ const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
23
+ if (!raw) return "";
24
+ if (raw.startsWith('"')) {
25
+ try { return JSON.parse(raw); } catch { return ""; }
26
+ }
27
+ return raw.replace(/^'|'$/g, "");
28
+ }
29
+
30
+ export function readLocalAgent(source) {
31
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
32
+ if (!front) return null;
33
+ const id = markdownValue(front[1], "id");
34
+ const name = markdownValue(front[1], "name");
35
+ const mode = markdownValue(front[1], "mode");
36
+ const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
37
+ if (typeof name !== "string" || !name || !safeId.test(id)) return null;
38
+ if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
39
+ if (mode && mode !== "standalone") return null;
40
+ if (!prompt || prompt.length > 16_000) return null;
41
+ return { id: "local:" + id, name, source: "local", prompt };
42
+ }
43
+
44
+ export async function readCatalog(root) {
45
+ const directory = join(root, ".lyra", "agents");
46
+ const agents = new Map();
47
+ for (const name of await files(directory, ".md")) {
48
+ const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
49
+ if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
50
+ }
51
+ async function records(kind) {
52
+ const folder = join(root, ".lyra", kind);
53
+ const rows = [];
54
+ for (const name of await files(folder, ".json")) {
55
+ try {
56
+ const item = JSON.parse(await readFile(join(folder, name), "utf8"));
57
+ if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
58
+ } catch (error) {
59
+ if (!(error instanceof SyntaxError)) throw error;
60
+ }
61
+ }
62
+ return rows;
63
+ }
64
+ for (const name of await files(directory, ".json")) {
65
+ let item;
66
+ try {
67
+ item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
68
+ } catch (error) {
69
+ if (error instanceof SyntaxError) continue;
70
+ throw error;
71
+ }
72
+ const descriptor = pythonDescriptor(item);
73
+ if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
74
+ typeof item.name !== "string" || !item.name.trim()) continue;
75
+ const id = "python:" + item.id;
76
+ if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
77
+ }
78
+ return { agents, workflows: await records("workflows"), teams: await records("teams") };
79
+ }
80
+
81
+ export function validateLayout(layout) {
82
+ if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
83
+ const ids = new Set();
84
+ const checked = layout.map(node => {
85
+ if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
86
+ typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
87
+ ids.add(node.id);
88
+ return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
89
+ sourceId: String(node.sourceId ?? "").slice(0, 96),
90
+ outputId: String(node.outputId ?? "").slice(0, 96),
91
+ targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
92
+ } };
93
+ });
94
+ return checked;
95
+ }
96
+
97
+ async function manifestFile(root) {
98
+ const path = join(root, "manifest.json");
99
+ try {
100
+ if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
101
+ const raw = await readFile(path, "utf8");
102
+ return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
103
+ } catch (error) {
104
+ if (error.code !== "ENOENT") throw error;
105
+ return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
106
+ }
107
+ }
108
+
109
+ export async function readLayout(root) {
110
+ const { manifest, revision } = await manifestFile(root);
111
+ return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
112
+ }
113
+
114
+ export async function saveLayout(root, layout, revision) {
115
+ const current = await manifestFile(root);
116
+ if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
117
+ if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
118
+ throw new Error("The existing manifest is not an App Builder manifest.");
119
+ }
120
+ const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
121
+ const temp = current.path + "." + randomUUID() + ".tmp";
122
+ await writeFile(temp, content, { flag: "wx" });
123
+ try {
124
+ if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
125
+ await rename(temp, current.path);
126
+ } catch (error) {
127
+ await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
128
+ throw error;
129
+ }
130
+ return { revision: createHash("sha256").update(content).digest("hex") };
131
+ }
132
+
133
+ export function resolveSequence(catalog, targets) {
134
+ if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
135
+ throw new Error("Choose one to eight agents or workflows.");
136
+ }
137
+ const sequence = targets.flatMap(target => {
138
+ if (typeof target !== "string") throw new Error("Invalid run target.");
139
+ if (!target.startsWith("workflow:")) return [{ agentId: target }];
140
+ const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
141
+ if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
142
+ return workflow.steps;
143
+ });
144
+ if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
145
+ throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
146
+ }
147
+ return sequence;
148
+ }
149
+
150
+ export async function runSelection(root, { targets, input, model }, catalog) {
151
+ if (typeof input !== "string" || !input.trim() || input.length > 4000) {
152
+ throw new Error("Enter up to 4,000 characters.");
153
+ }
154
+ const exported = Boolean(catalog);
155
+ catalog ??= await readCatalog(root);
156
+ const sequence = resolveSequence(catalog, targets);
157
+ const local = sequence.some(step => step.agentId.startsWith("local:"));
158
+ if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
159
+ throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
160
+ }
161
+ const cloud = sequence.some(step => step.agentId.startsWith("cloud:")) ? createSavedAgentClient() : null;
162
+ const store = local ? await openStore(root) : null;
163
+ const answers = [];
164
+ const named = new Map();
165
+ try {
166
+ for (const step of sequence) {
167
+ const agent = catalog.agents.get(step.agentId);
168
+ const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
169
+ const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
170
+ let output;
171
+ if (agent.source === "cloud") {
172
+ output = await cloud.invoke(agent.id.slice("cloud:".length), text);
173
+ } else if (agent.source === "python") {
174
+ output = await runPythonAgent(root, agent, text, exported);
175
+ } else {
176
+ const event = await runAgent({
177
+ agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
178
+ request: { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] },
179
+ });
180
+ if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
181
+ output = event.data.result.text;
182
+ }
183
+ if (step.output) named.set(step.output, output);
184
+ answers.push({ agent: agent.name, output });
185
+ }
186
+ return { answers };
187
+ } finally {
188
+ store?.close();
189
+ }
190
+ }
@@ -0,0 +1,47 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+
5
+ const filename = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.py$/;
6
+ const skillId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/;
7
+
8
+ export function pythonDescriptor(item) {
9
+ if (item?.runtime !== "python" || !filename.test(item.file ?? "") || !skillId.test(item.skill ?? "")) return null;
10
+ return { file: item.file, skill: item.skill };
11
+ }
12
+
13
+ export async function pythonSource(root, agent, exported) {
14
+ if (!pythonDescriptor({ ...agent, runtime: "python" })) throw new Error("Invalid Python agent descriptor.");
15
+ let directory = root;
16
+ for (const part of exported ? ["python-agents"] : [".lyra", "agents"]) {
17
+ directory = join(directory, part);
18
+ if (!(await lstat(directory)).isDirectory()) throw new Error("Python agent folders must be regular directories.");
19
+ }
20
+ const source = join(directory, agent.file);
21
+ if (!(await lstat(source)).isFile()) throw new Error("Python agent source must be a regular file.");
22
+ return source;
23
+ }
24
+
25
+ export async function runPythonAgent(root, agent, input, exported) {
26
+ const file = await pythonSource(root, agent, exported);
27
+ const python = process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3");
28
+ const runner = new URL("./python-agent.py", import.meta.url);
29
+ const { fileURLToPath } = await import("node:url");
30
+ return new Promise((resolve, reject) => {
31
+ const child = execFile(python, [fileURLToPath(runner), file, agent.skill], {
32
+ cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
33
+ }, (error, stdout) => {
34
+ if (error?.code === "ENOENT") return reject(new Error("Install Python 3.9+ and agent-lyra, or set LYRA_PYTHON to your virtual environment's interpreter."));
35
+ if (error) return reject(new Error("Python agent " + agent.name + " failed. Check its dependencies and skill registration."));
36
+ try {
37
+ const result = JSON.parse(stdout);
38
+ if (typeof result.output !== "string") throw new Error();
39
+ resolve(result.output);
40
+ } catch {
41
+ reject(new Error("Python agent " + agent.name + " returned an invalid response."));
42
+ }
43
+ });
44
+ child.stdin.on("error", () => {});
45
+ child.stdin.end(JSON.stringify({ input }));
46
+ });
47
+ }
@@ -0,0 +1,25 @@
1
+ """Run a registered Lyra skill from a trusted project agent file."""
2
+ import asyncio
3
+ import json
4
+ import runpy
5
+ import sys
6
+ from contextlib import redirect_stdout
7
+
8
+
9
+ def main():
10
+ source, skill = sys.argv[1:]
11
+ payload = json.load(sys.stdin)
12
+ with redirect_stdout(sys.stderr):
13
+ from lyra.standalone import Agent
14
+
15
+ agent = runpy.run_path(source).get("agent")
16
+ if not isinstance(agent, Agent):
17
+ raise TypeError("Export a lyra.standalone.Agent named 'agent'.")
18
+ output = asyncio.run(agent.run(skill, payload["input"]))
19
+ if not isinstance(output, str):
20
+ output = json.dumps(output, allow_nan=False)
21
+ print(json.dumps({"output": output}))
22
+
23
+
24
+ if __name__ == "__main__":
25
+ main()
@@ -0,0 +1,102 @@
1
+ import { createServer } from "node:http";
2
+ import { readFile } from "node:fs/promises";
3
+ import { readCatalog, readLayout, runSelection, saveLayout } from "./project.js";
4
+ import { pullStudio } from "./sync.js";
5
+
6
+ export async function startStudio(root, { port = 0, run = runSelection, pull = pullStudio, appCatalog } = {}) {
7
+ const assets = new Map();
8
+ for (const [route, name, mime] of [
9
+ ["/agent-ui.js", "agent-ui.js", "text/javascript"], ["/agent-ui.css", "agent-ui.css", "text/css"],
10
+ ["/", "index.html", "text/html"], ["/studio.js", "browser.js", "text/javascript"], ["/studio.css", "studio.css", "text/css"],
11
+ ]) assets.set(route, [await readFile(new URL("./" + name, import.meta.url)), mime]);
12
+
13
+ let running = false;
14
+ let writing = false;
15
+ const server = createServer(async (req, res) => {
16
+ const send = (status, data, type = "application/json") => {
17
+ res.writeHead(status, {
18
+ "Content-Type": type + "; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
19
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'",
20
+ });
21
+ res.end(type === "application/json" ? JSON.stringify(data) : data);
22
+ };
23
+ const host = "127.0.0.1:" + server.address().port;
24
+ if (req.headers.host !== host) return send(403, { error: "Use the Studio loopback URL." });
25
+ if (req.method === "GET" && assets.has(req.url)) {
26
+ const [data, mime] = assets.get(req.url);
27
+ return send(200, data, mime);
28
+ }
29
+ try {
30
+ if (req.method === "GET" && req.url === "/api/project") {
31
+ const catalog = appCatalog ?? await readCatalog(root);
32
+ return send(200, {
33
+ ...await readLayout(root),
34
+ exported: Boolean(appCatalog),
35
+ agents: [...catalog.agents.values()].map(({ id, name, source }) => ({ id, name, source })),
36
+ workflows: catalog.workflows.map(({ id, name, runnable }) => ({ id, name, runnable })),
37
+ teams: catalog.teams.map(({ id, name }) => ({ id, name })),
38
+ models: (process.env.LYRA_STUDIO_MODELS || "gpt-4o-mini").split(",").map(value => value.trim()).filter(Boolean),
39
+ });
40
+ }
41
+ if (req.method !== "POST" || !["/api/save", "/api/run", "/api/pull"].includes(req.url)) {
42
+ return send(404, { error: "Not found." });
43
+ }
44
+ if (appCatalog && req.url !== "/api/run") return send(404, { error: "Not found." });
45
+ if (req.headers.origin !== "http://" + host) return send(403, { error: "Use the Studio page to submit requests." });
46
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") return send(415, { error: "Use application/json." });
47
+ const chunks = [];
48
+ let size = 0;
49
+ for await (const chunk of req) {
50
+ size += chunk.length;
51
+ if (size > 65_536) return send(413, { error: "Studio request is too large." });
52
+ chunks.push(chunk);
53
+ }
54
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
55
+ if (req.url === "/api/run") {
56
+ if (running) return send(409, { error: "A Studio run is already in progress." });
57
+ running = true;
58
+ try {
59
+ if (appCatalog) {
60
+ const { layout } = await readLayout(root);
61
+ const button = layout.find(node => ["button", "agent-card"].includes(node.kind) && node.id === body.buttonId);
62
+ if (!button) return send(400, { error: "Choose a run button from the app." });
63
+ body.targets = button.targets;
64
+ }
65
+ return send(200, await run(root, body, appCatalog));
66
+ } finally { running = false; }
67
+ }
68
+ if (writing) return send(409, { error: "Studio is already saving or pulling files." });
69
+ writing = true;
70
+ try {
71
+ return send(200, req.url === "/api/save"
72
+ ? await saveLayout(root, body.layout, body.revision)
73
+ : await pull(root));
74
+ } finally { writing = false; }
75
+ } catch (error) {
76
+ const message = error.code ? "Studio could not read or write the project." : error.message;
77
+ return send(400, { error: message });
78
+ }
79
+ });
80
+
81
+ server.requestTimeout = 10_000;
82
+ await new Promise((resolve, reject) => {
83
+ server.once("error", reject);
84
+ server.listen(port, "127.0.0.1", resolve);
85
+ });
86
+ return { server, url: "http://127.0.0.1:" + server.address().port + "/" };
87
+ }
88
+
89
+ export async function runStudio(args, output = process.stdout) {
90
+ if (args[0] === "--help") {
91
+ output.write("Usage: agent-lyra studio | agent-lyra studio pull\n");
92
+ return;
93
+ }
94
+ if (args.length === 1 && args[0] === "pull") {
95
+ const { added, preserved } = await pullStudio(process.cwd());
96
+ output.write("Cloud pull: " + added + " added, " + preserved + " existing preserved.\n");
97
+ return;
98
+ }
99
+ if (args.length) throw new Error("See agent-lyra studio --help.");
100
+ const { url } = await startStudio(process.cwd());
101
+ output.write("AgentLyra Studio: " + url + "\n");
102
+ }
@@ -0,0 +1,7 @@
1
+ *{box-sizing:border-box}body{margin:0;background:#f6f8f6;color:#173328;font:0.95rem/1.5 system-ui,sans-serif}header{display:flex;align-items:center;justify-content:space-between;gap:.8rem;padding:1rem 1.25rem;border-bottom:1px solid #d9e4dd;background:#fff}header strong{white-space:nowrap}h1,h2,p{margin:.2rem 0 .65rem}h1{font-size:1.45rem}h2{font-size:1rem}main{display:grid;grid-template-columns:minmax(13rem,1fr) minmax(18rem,2.6fr) minmax(14rem,1.1fr);gap:1rem;padding:0 1.25rem 1rem}main>aside,main>section{min-width:0;padding:1rem;border:1px solid #d9e4dd;border-radius:.65rem;background:#fff}button,input,select,textarea{font:inherit}button{border:1px solid #b4cabe;border-radius:.35rem;background:#fff;color:#174b38;padding:.35rem .65rem;cursor:pointer}button:hover{background:#e6f0e9}.primary{background:#174b38;color:#fff;border-color:#174b38}.primary:hover{background:#246449}button:disabled{opacity:.5;cursor:wait}input,textarea,select{display:block;padding:.45rem;border:1px solid #a8c0b1;border-radius:.35rem;background:#fff;color:#173328;width:100%;margin-bottom:.65rem}label{display:block;margin-top:.65rem}#status{min-height:1.5rem;padding:0 1.25rem}#palette{display:grid;grid-template-columns:1fr 1fr;gap:.4rem;margin-bottom:1.15rem}.agent-card,.node{padding:.6rem;margin:.5rem 0;border:1px solid #cbdcd1;border-radius:.45rem}.agent-card span{display:block;color:#47675a;font-size:.8rem}.agent-card button{margin-top:.35rem}#canvas{min-height:18rem;border:1px dashed #8aa99a;border-radius:.6rem;background:#f9fcfa;padding:.65rem}.node{background:#fff}.node.selected{border-color:#2f7658;outline:1px solid #2f7658}.node>button:first-child{margin-bottom:.35rem}.actions{display:flex;flex-wrap:wrap;gap:.35rem}.binding{margin:.35rem 0;display:flex;justify-content:space-between;gap:.35rem}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#eff5f1;padding:.6rem;border-radius:.35rem}dialog{border:0;margin:0 0 0 auto;height:100%;max-height:100%;width:min(29rem,100%);max-width:100%;padding:1rem;color:#173328}dialog::backdrop{background:#203a3266}dialog header{padding:0 0 .5rem;margin-bottom:1rem}@media(max-width:860px){main{grid-template-columns:1fr 2fr}main>aside:last-child{grid-column:1/-1}}@media(max-width:600px){main{grid-template-columns:1fr}header{flex-wrap:wrap}main>aside:last-child{grid-column:auto}}
2
+
3
+ [hidden]{display:none!important}
4
+ .exported > header,.exported main > aside,.exported main > section > p{display:none}
5
+ .exported main{display:block;max-width:52rem;margin:1rem auto}
6
+ .exported #canvas{border:0;background:transparent;padding:0;min-height:0}
7
+ .exported .node{border:0;padding:0;margin:1rem 0}
@@ -0,0 +1,39 @@
1
+ import { lstat, mkdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ export async function pullStudio(root, { key = process.env.LYRA_API_KEY, request = fetch } = {}) {
5
+ if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) throw new Error("Set LYRA_API_KEY to your AgentLyra SDK key.");
6
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/catalog", {
7
+ headers: { Authorization: "Bearer " + key }, redirect: "error", signal: AbortSignal.timeout(20_000),
8
+ });
9
+ if (!response.ok) throw new Error("Cloud pull failed (HTTP " + response.status + ").");
10
+ const catalog = await response.json();
11
+ const count = { added: 0, preserved: 0 };
12
+ const base = join(root, ".lyra");
13
+ await mkdir(base, { recursive: true });
14
+ if (!(await lstat(base)).isDirectory()) throw new Error(".lyra must be a regular directory.");
15
+
16
+ for (const [kind, rows] of Object.entries({ agents: catalog.agents, workflows: catalog.workflows, teams: catalog.teams })) {
17
+ if (!Array.isArray(rows) || rows.length > 100) throw new Error("Unexpected Cloud catalog response.");
18
+ const folder = join(base, kind);
19
+ await mkdir(folder, { recursive: true });
20
+ if (!(await lstat(folder)).isDirectory()) throw new Error("Catalog paths must be regular directories.");
21
+ for (const row of rows) {
22
+ if (typeof row?.id !== "string" || !/^[a-f0-9]{24}$/i.test(row.id) || typeof row.name !== "string") {
23
+ throw new Error("Unexpected Cloud catalog entry.");
24
+ }
25
+ const name = "cloud-" + row.id + (kind === "agents" ? ".md" : ".json");
26
+ const content = kind === "agents"
27
+ ? "---\nid: " + row.id + "\nname: " + JSON.stringify(row.name) + "\nmode: cloud\n---\n"
28
+ : JSON.stringify(row, null, 2) + "\n";
29
+ try {
30
+ await writeFile(join(folder, name), content, { flag: "wx" });
31
+ count.added++;
32
+ } catch (error) {
33
+ if (error.code !== "EEXIST") throw error;
34
+ count.preserved++;
35
+ }
36
+ }
37
+ }
38
+ return count;
39
+ }