agent-lyra 0.6.0 → 0.6.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.
Files changed (47) hide show
  1. package/README.md +435 -173
  2. package/bin/agent-lyra.js +21 -3
  3. package/bin/lyra-oss-preview.js +14 -0
  4. package/package.json +60 -56
  5. package/src/app-builder/export.js +109 -109
  6. package/src/app-builder/init.js +52 -52
  7. package/src/app-builder/manifest-contract.js +46 -0
  8. package/src/app-builder/preview.js +22 -22
  9. package/src/app-builder/saved-app.js +70 -70
  10. package/src/app-builder/saved-preview-browser.js +33 -33
  11. package/src/app-builder/saved-preview.html +24 -24
  12. package/src/app-builder/saved-preview.js +61 -61
  13. package/src/app-builder/validate.js +21 -64
  14. package/src/coding/catalog.js +56 -0
  15. package/src/coding/cloud-catalog.js +44 -0
  16. package/src/coding/detect-stack.mjs +110 -0
  17. package/src/coding/export.js +130 -0
  18. package/src/coding/setup.js +174 -0
  19. package/src/init.js +32 -4
  20. package/src/memory/cli.js +21 -0
  21. package/src/memory/contract.json +28 -0
  22. package/src/memory/index.d.ts +49 -0
  23. package/src/memory/index.js +259 -0
  24. package/src/memory/lifecycle.js +29 -0
  25. package/src/memory/local-cli.js +34 -0
  26. package/src/memory/proposals.js +84 -0
  27. package/src/memory/skills-cli.js +26 -0
  28. package/src/memory/sync.js +89 -0
  29. package/src/memory/validation.js +25 -0
  30. package/src/runtime/local-cli.js +2 -1
  31. package/src/studio/agent-ui.css +43 -43
  32. package/src/studio/agent-ui.js +32 -32
  33. package/src/studio/browser.js +331 -289
  34. package/src/studio/export.js +80 -79
  35. package/src/studio/index.html +37 -16
  36. package/src/studio/memory-actions.js +37 -0
  37. package/src/studio/memory-panel.js +200 -0
  38. package/src/studio/project.js +216 -190
  39. package/src/studio/pull-agent.js +72 -0
  40. package/src/studio/push.js +54 -0
  41. package/src/studio/python-agent.js +47 -47
  42. package/src/studio/python-agent.py +25 -25
  43. package/src/studio/server.js +143 -102
  44. package/src/studio/session.js +83 -0
  45. package/src/studio/studio.css +10 -7
  46. package/src/studio/sync.js +42 -39
  47. package/src/studio/workflow-sync.js +157 -0
@@ -1,47 +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
- }
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
+ }
@@ -1,25 +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()
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()
@@ -1,102 +1,143 @@
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
- }
1
+ import { memoryActions } from "./memory-actions.js";
2
+ import { createServer } from "node:http";
3
+ import { readFile } from "node:fs/promises";
4
+ import { readCatalog, readLayout, runSelection, saveLayout } from "./project.js";
5
+ import { readMode } from "./session.js";
6
+ import { syncSkill, syncTeam, syncWorkflow } from "./workflow-sync.js";
7
+ import { pullAgentEdits } from "./pull-agent.js";
8
+ import { pushStudioAgent } from "./push.js";
9
+ import { pullStudio } from "./sync.js";
10
+
11
+ export async function startStudio(root, { port = 0, run = runSelection, pull = pullStudio, appCatalog } = {}) {
12
+ const assets = new Map();
13
+ for (const [route, name, mime] of [
14
+ ["/memory-panel.js", "memory-panel.js", "text/javascript"],
15
+ ["/agent-ui.js", "agent-ui.js", "text/javascript"], ["/agent-ui.css", "agent-ui.css", "text/css"],
16
+ ["/", "index.html", "text/html"], ["/studio.js", "browser.js", "text/javascript"], ["/studio.css", "studio.css", "text/css"],
17
+ ]) assets.set(route, [await readFile(new URL("./" + name, import.meta.url)), mime]);
18
+
19
+ const updates = new Map([
20
+ ...(appCatalog ? [] : memoryActions(root)),
21
+ ["/api/save", ({ layout, revision }) => saveLayout(root, layout, revision)],
22
+ ["/api/pull", () => pull(root)],
23
+ ["/api/push", ({ id }) => pushStudioAgent(root, id)],
24
+ ["/api/pull-agent", ({ id }) => pullAgentEdits(root, id)],
25
+ ["/api/push-workflow", ({ id }) => syncWorkflow(root, id, "push")],
26
+ ["/api/pull-workflow", ({ id }) => syncWorkflow(root, id, "pull")],
27
+ ["/api/push-team", ({ id }) => syncTeam(root, id, "push")],
28
+ ["/api/pull-team", ({ id }) => syncTeam(root, id, "pull")],
29
+ ["/api/push-skill", ({ id }) => syncSkill(root, id, "push")],
30
+ ["/api/pull-skill", ({ id }) => syncSkill(root, id, "pull")],
31
+ ]);
32
+
33
+ let running = false;
34
+ let writing = false;
35
+ const server = createServer(async (req, res) => {
36
+ const send = (status, data, type = "application/json") => {
37
+ res.writeHead(status, {
38
+ "Content-Type": type + "; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
39
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'",
40
+ });
41
+ res.end(type === "application/json" ? JSON.stringify(data) : data);
42
+ };
43
+ const host = "127.0.0.1:" + server.address().port;
44
+ if (req.headers.host !== host) return send(403, { error: "Use the Studio loopback URL." });
45
+ if (req.method === "GET" && assets.has(req.url)) {
46
+ const [data, mime] = assets.get(req.url);
47
+ return send(200, data, mime);
48
+ }
49
+ try {
50
+ if (req.method === "GET" && req.url === "/api/project") {
51
+ const catalog = appCatalog ?? await readCatalog(root);
52
+ return send(200, {
53
+ ...await readLayout(root),
54
+ exported: Boolean(appCatalog),
55
+ mode: appCatalog ? undefined : await readMode(root),
56
+ agents: [...catalog.agents.values()].map(({ id, name, source }) => ({ id, name, source })),
57
+ workflows: catalog.workflows.map(({ id, name, runnable, source }) => ({ id, name, runnable, source })),
58
+ skills: (catalog.skills ?? []).map(({ id, name, source }) => ({ id, name, source })),
59
+ teams: catalog.teams.map(({ id, name, source }) => ({ id, name, source })),
60
+ models: (process.env.LYRA_STUDIO_MODELS || "gpt-4o-mini").split(",").map(value => value.trim()).filter(Boolean),
61
+ });
62
+ }
63
+ if (req.method !== "POST" || (req.url !== "/api/run" && !updates.has(req.url))) {
64
+ return send(404, { error: "Not found." });
65
+ }
66
+ if (appCatalog && req.url !== "/api/run") return send(404, { error: "Not found." });
67
+ if (req.headers.origin !== "http://" + host) return send(403, { error: "Use the Studio page to submit requests." });
68
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") return send(415, { error: "Use application/json." });
69
+ const chunks = [];
70
+ let size = 0;
71
+ for await (const chunk of req) {
72
+ size += chunk.length;
73
+ if (size > 65_536) return send(413, { error: "Studio request is too large." });
74
+ chunks.push(chunk);
75
+ }
76
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
77
+ if (req.url === "/api/run") {
78
+ if (running) return send(409, { error: "A Studio run is already in progress." });
79
+ running = true;
80
+ try {
81
+ if (appCatalog) {
82
+ const { layout } = await readLayout(root);
83
+ const button = layout.find(node => ["button", "agent-card"].includes(node.kind) && node.id === body.buttonId);
84
+ if (!button) return send(400, { error: "Choose a run button from the app." });
85
+ body.targets = button.targets;
86
+ }
87
+ return send(200, await run(root, body, appCatalog));
88
+ } finally { running = false; }
89
+ }
90
+ if (writing) return send(409, { error: "Studio is already saving or pulling files." });
91
+ writing = true;
92
+ try {
93
+ return send(200, await updates.get(req.url)(body));
94
+ } finally { writing = false; }
95
+ } catch (error) {
96
+ const message = error.code ? "Studio could not read or write the project." : error.message;
97
+ return send(400, { error: message });
98
+ }
99
+ });
100
+
101
+ server.requestTimeout = 10_000;
102
+ await new Promise((resolve, reject) => {
103
+ server.once("error", reject);
104
+ server.listen(port, "127.0.0.1", resolve);
105
+ });
106
+ return { server, url: "http://127.0.0.1:" + server.address().port + "/" };
107
+ }
108
+
109
+ export async function runStudio(args, output = process.stdout) {
110
+ if (args[0] === "--help") {
111
+ output.write("Usage: agent-lyra studio | agent-lyra studio pull | agent-lyra studio push <local-agent-id> | agent-lyra studio pull-agent <local-agent-id> | agent-lyra studio push-workflow <workflow-id> | agent-lyra studio pull-workflow <workflow-id> | agent-lyra studio push-team <team-id> | agent-lyra studio pull-team <team-id> | agent-lyra studio push-skill <skill-id> | agent-lyra studio pull-skill <skill-id>\n");
112
+ return;
113
+ }
114
+ if (args.length === 1 && args[0] === "pull") {
115
+ const { added, preserved } = await pullStudio(process.cwd());
116
+ output.write("Cloud pull: " + added + " added, " + preserved + " existing preserved.\n");
117
+ return;
118
+ }
119
+ if (args.length === 2 && args[0] === "push") {
120
+ const id = args[1].startsWith("local:") ? args[1] : "local:" + args[1];
121
+ const result = await pushStudioAgent(process.cwd(), id);
122
+ output.write((result.created ? "Created " : "Synced ") + result.name + " in AgentLyra Cloud.\n");
123
+ return;
124
+ }
125
+ if (args.length === 2 && args[0] === "pull-agent") {
126
+ const id = args[1].startsWith("local:") ? args[1] : "local:" + args[1];
127
+ const result = await pullAgentEdits(process.cwd(), id);
128
+ output.write(result.updated ? "Updated " + result.name + " from Cloud.\n" : "No Cloud edits to pull.\n");
129
+ return;
130
+ }
131
+ if (args.length === 2 && ["push-workflow", "pull-workflow", "push-team", "pull-team", "push-skill", "pull-skill"].includes(args[0])) {
132
+ const [action, resource] = args[0].split("-");
133
+ const push = action === "push";
134
+ const sync = { team: syncTeam, workflow: syncWorkflow, skill: syncSkill }[resource];
135
+ const result = await sync(process.cwd(), args[1], action);
136
+ output.write(push ? "Saved " + result.name + " in Cloud.\n"
137
+ : result.updated ? "Updated " + result.name + " from Cloud.\n" : "No Cloud edits to pull.\n");
138
+ return;
139
+ }
140
+ if (args.length) throw new Error("See agent-lyra studio --help.");
141
+ const { url } = await startStudio(process.cwd());
142
+ output.write("AgentLyra Studio: " + url + "\n");
143
+ }
@@ -0,0 +1,83 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { Writable } from "node:stream";
7
+
8
+ const validKey = key => typeof key === "string" && /^lyra_sdk_[a-f0-9]{64}$/.test(key);
9
+ const account = () => join(homedir(), ".agent-lyra");
10
+ const workspace = root => join(root, ".lyra");
11
+
12
+ async function readJson(path) {
13
+ try {
14
+ if (!(await lstat(path)).isFile()) throw new Error("Lyra settings must be a regular file.");
15
+ return JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, ""));
16
+ } catch (error) {
17
+ if (error.code === "ENOENT") return {};
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ async function saveJson(directory, name, data) {
23
+ await mkdir(directory, { recursive: true, mode: 0o700 });
24
+ if (!(await lstat(directory)).isDirectory()) throw new Error("Lyra settings must use a regular directory.");
25
+ const target = join(directory, name);
26
+ const temporary = target + "." + randomUUID() + ".tmp";
27
+ await writeFile(temporary, JSON.stringify(data, null, 2) + "\n", { flag: "wx", mode: 0o600 });
28
+ try {
29
+ await rename(temporary, target);
30
+ } finally {
31
+ await unlink(temporary).catch(() => {});
32
+ }
33
+ }
34
+
35
+ export async function readMode(root) {
36
+ const { mode } = await readJson(join(workspace(root), "session.json"));
37
+ return ["gated", "standalone"].includes(mode) ? mode : "automatic";
38
+ }
39
+
40
+ export async function readSdkKey(root, { home = account() } = {}) {
41
+ const env = process.env.LYRA_API_KEY;
42
+ if (validKey(env)) return env;
43
+ const saved = (await readJson(join(home, "credentials.json"))).LYRA_API_KEY;
44
+ if (validKey(saved)) return saved;
45
+ const workspaceKey = (await readJson(join(workspace(root), "credentials.json"))).LYRA_API_KEY;
46
+ return validKey(workspaceKey) ? workspaceKey : undefined;
47
+ }
48
+
49
+ async function promptKey() {
50
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
51
+ throw new Error("Run this command in your IDE terminal to enter an AgentLyra API key, or supply LYRA_API_KEY in the environment.");
52
+ }
53
+ const silent = new Writable({ write(_chunk, _encoding, done) { done(); } });
54
+ const prompt = createInterface({ input: process.stdin, output: silent, terminal: true, historySize: 0 });
55
+ const cancel = new AbortController();
56
+ prompt.once("SIGINT", () => cancel.abort());
57
+ process.stdout.write("Paste your AgentLyra API key and press Enter (input hidden): ");
58
+ try {
59
+ return (await prompt.question("", { signal: cancel.signal })).trim();
60
+ } finally {
61
+ prompt.close();
62
+ process.stdout.write("\n");
63
+ }
64
+ }
65
+
66
+ export async function switchMode(root, mode, args, { output = process.stdout, prompt = promptKey, home = account() } = {}) {
67
+ const replace = mode === "gated" && args.length === 1 && args[0] === "--replace-key";
68
+ if (args.length && !replace) throw new Error("Usage: agent-lyra work-locally | agent-lyra connect-cloud [--replace-key]");
69
+ if (mode === "gated" && (replace || !(await readSdkKey(root, { home })))) {
70
+ output.write("Generate an AgentLyra API key at https://console.agentlyra.in/mcp-servers\n");
71
+ const key = await prompt();
72
+ if (!validKey(key)) throw new Error("Enter an AgentLyra API key beginning with lyra_sdk_.");
73
+ await saveJson(home, "credentials.json", { LYRA_API_KEY: key });
74
+ }
75
+ await saveJson(workspace(root), "session.json", { mode });
76
+ output.write(mode === "gated"
77
+ ? "Connected to Cloud. Open Studio and choose Pull from Cloud.\n"
78
+ : "Working locally. Studio Cloud actions are paused.\n");
79
+ }
80
+
81
+ export function requireCloudMode(mode) {
82
+ if (mode === "standalone") throw new Error("You’re working locally. Run connect-cloud in your project terminal to use Cloud resources.");
83
+ }
@@ -1,7 +1,10 @@
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}
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
+ #memory-panel{width:min(48rem,100vw)}
4
+ #memory-panel details{margin:1rem 0}
5
+ #memory-panel pre{white-space:pre-wrap;overflow-wrap:anywhere}
6
+ [hidden]{display:none!important}
7
+ .exported > header,.exported main > aside,.exported main > section > p{display:none}
8
+ .exported main{display:block;max-width:52rem;margin:1rem auto}
9
+ .exported #canvas{border:0;background:transparent;padding:0;min-height:0}
10
+ .exported .node{border:0;padding:0;margin:1rem 0}
@@ -1,39 +1,42 @@
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
- }
1
+ import { lstat, mkdir, writeFile } from "node:fs/promises";
2
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
3
+ import { join } from "node:path";
4
+
5
+ export async function pullStudio(root, { key, request = fetch } = {}) {
6
+ requireCloudMode(await readMode(root));
7
+ key ??= await readSdkKey(root);
8
+ if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) throw new Error("Run connect-cloud to enter your SDK key, then pull again.");
9
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/catalog", {
10
+ headers: { Authorization: "Bearer " + key }, redirect: "error", signal: AbortSignal.timeout(20_000),
11
+ });
12
+ if (!response.ok) throw new Error("Cloud pull failed (HTTP " + response.status + ").");
13
+ const catalog = await response.json();
14
+ const count = { added: 0, preserved: 0 };
15
+ const base = join(root, ".lyra");
16
+ await mkdir(base, { recursive: true });
17
+ if (!(await lstat(base)).isDirectory()) throw new Error(".lyra must be a regular directory.");
18
+
19
+ for (const [kind, rows] of Object.entries({ agents: catalog.agents, workflows: catalog.workflows, teams: catalog.teams, skills: catalog.skills ?? [] })) {
20
+ if (!Array.isArray(rows) || rows.length > 100) throw new Error("Unexpected Cloud catalog response.");
21
+ const folder = join(base, kind);
22
+ await mkdir(folder, { recursive: true });
23
+ if (!(await lstat(folder)).isDirectory()) throw new Error("Catalog paths must be regular directories.");
24
+ for (const row of rows) {
25
+ if (typeof row?.id !== "string" || !/^[a-f0-9]{24}$/i.test(row.id) || typeof row.name !== "string") {
26
+ throw new Error("Unexpected Cloud catalog entry.");
27
+ }
28
+ const name = "cloud-" + row.id + (kind === "agents" ? ".md" : ".json");
29
+ const content = kind === "agents"
30
+ ? "---\nid: " + row.id + "\nname: " + JSON.stringify(row.name) + "\nmode: cloud\n---\n"
31
+ : JSON.stringify(row, null, 2) + "\n";
32
+ try {
33
+ await writeFile(join(folder, name), content, { flag: "wx" });
34
+ count.added++;
35
+ } catch (error) {
36
+ if (error.code !== "EEXIST") throw error;
37
+ count.preserved++;
38
+ }
39
+ }
40
+ }
41
+ return count;
42
+ }