agent-lyra 0.3.1 → 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.
- package/README.md +110 -97
- package/bin/agent-lyra.js +4 -1
- package/package.json +1 -1
- package/src/app-builder/export.js +109 -59
- package/src/app-builder/init.js +52 -23
- package/src/app-builder/preview.js +22 -14
- package/src/app-builder/saved-app.js +70 -0
- package/src/app-builder/saved-preview-browser.js +33 -0
- package/src/app-builder/saved-preview.html +24 -0
- package/src/app-builder/saved-preview.js +61 -0
- package/src/app-builder/validate.js +64 -65
- package/src/runtime/local-cli.js +2 -2
- package/src/studio/agent-ui.css +43 -0
- package/src/studio/agent-ui.js +32 -0
- package/src/studio/browser.js +289 -0
- package/src/studio/export.js +79 -0
- package/src/studio/index.html +16 -0
- package/src/studio/project.js +190 -0
- package/src/studio/python-agent.js +47 -0
- package/src/studio/python-agent.py +25 -0
- package/src/studio/server.js +102 -0
- package/src/studio/studio.css +7 -0
- package/src/studio/sync.js +39 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { renderAgentCard, renderRunHeader } from "./agent-ui.js";
|
|
2
|
+
|
|
3
|
+
const $ = selector => document.querySelector(selector);
|
|
4
|
+
const element = (tag, text) => Object.assign(document.createElement(tag), text === undefined ? {} : { textContent: text });
|
|
5
|
+
function dom(tag, props, ...children) {
|
|
6
|
+
const node = document.createElement(tag);
|
|
7
|
+
for (const [key, value] of Object.entries(props)) {
|
|
8
|
+
if (value == null) continue;
|
|
9
|
+
if (key === "onClick") node.onclick = value;
|
|
10
|
+
else if (key === "aria-label") node.setAttribute(key, value);
|
|
11
|
+
else node[key] = value;
|
|
12
|
+
}
|
|
13
|
+
node.append(...children.filter(child => child != null && child !== false && child !== ""));
|
|
14
|
+
return node;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const agentSources = { local: "Local agent", cloud: "Cloud agent", python: "Python agent" };
|
|
18
|
+
const names = { heading:"Heading", text:"Text", input:"Text input", textarea:"Text area", button:"Run button", "agent-card":"Agent card", output:"Output" };
|
|
19
|
+
let project = { layout: [], agents: [], workflows: [], teams: [], models: [] };
|
|
20
|
+
let selected, pending;
|
|
21
|
+
let dirty = false;
|
|
22
|
+
const values = new Map();
|
|
23
|
+
const outputs = new Map();
|
|
24
|
+
|
|
25
|
+
function button(text, click) {
|
|
26
|
+
const control = element("button", text);
|
|
27
|
+
control.type = "button";
|
|
28
|
+
control.onclick = click;
|
|
29
|
+
return control;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function api(path, data) {
|
|
33
|
+
const response = await fetch("/api/" + path, data === undefined ? {} : {
|
|
34
|
+
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data),
|
|
35
|
+
});
|
|
36
|
+
const payload = await response.json();
|
|
37
|
+
if (!response.ok) throw new Error(payload.error);
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function announce(message) { $("#status").textContent = message; }
|
|
42
|
+
function change() { dirty = true; renderCanvas(); renderInspector(); }
|
|
43
|
+
|
|
44
|
+
function add(kind) {
|
|
45
|
+
if (!Object.hasOwn(names, kind) || project.layout.length >= 60) return;
|
|
46
|
+
const node = { id: crypto.randomUUID(), kind, label: names[kind] };
|
|
47
|
+
if (["button", "agent-card"].includes(kind)) node.targets = [];
|
|
48
|
+
project.layout.push(node);
|
|
49
|
+
selected = node.id;
|
|
50
|
+
change();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function move(node, offset) {
|
|
54
|
+
const index = project.layout.indexOf(node);
|
|
55
|
+
const next = index + offset;
|
|
56
|
+
if (next < 0 || next >= project.layout.length) return;
|
|
57
|
+
[project.layout[index], project.layout[next]] = [project.layout[next], node];
|
|
58
|
+
change();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function renderCanvas() {
|
|
62
|
+
const canvas = $("#canvas");
|
|
63
|
+
canvas.replaceChildren();
|
|
64
|
+
if (!project.layout.length) canvas.append(element("p", "Your canvas is empty."));
|
|
65
|
+
for (const node of project.layout) {
|
|
66
|
+
const card = element("div");
|
|
67
|
+
card.className = "node" + (node.id === selected ? " selected" : "");
|
|
68
|
+
const select = button("Edit " + names[node.kind], () => { selected = node.id; renderCanvas(); renderInspector(); });
|
|
69
|
+
if (!project.exported) card.append(select);
|
|
70
|
+
if (node.kind === "heading" || node.kind === "text") card.append(element(node.kind === "heading" ? "h2" : "p", node.label));
|
|
71
|
+
if (["input", "textarea"].includes(node.kind)) {
|
|
72
|
+
const id = "component-" + node.id;
|
|
73
|
+
const label = element("label", node.label);
|
|
74
|
+
label.htmlFor = id;
|
|
75
|
+
const input = element(node.kind);
|
|
76
|
+
input.id = id;
|
|
77
|
+
input.maxLength = 4000;
|
|
78
|
+
input.value = values.get(node.id) ?? "";
|
|
79
|
+
input.oninput = () => values.set(node.id, input.value);
|
|
80
|
+
card.append(label, input);
|
|
81
|
+
}
|
|
82
|
+
if (node.kind === "output") card.append(element("h2", node.label), element("pre", outputs.get(node.id) ?? "Run a workflow to see a result."));
|
|
83
|
+
if (node.kind === "agent-card") {
|
|
84
|
+
const agent = project.agents.find(item => item.id === node.targets[0]);
|
|
85
|
+
card.append(renderAgentCard(dom, {
|
|
86
|
+
name: node.label, source: agent ? agentSources[agent.source] : "Choose an agent in the inspector",
|
|
87
|
+
onRun: agent ? () => openRun(node.targets, values.get(node.sourceId) ?? "", node.outputId, node.id) : undefined,
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
if (node.kind === "button") {
|
|
91
|
+
const trigger = button(node.label, () => {
|
|
92
|
+
if (!node.targets.length) return announce("Assign an agent or workflow in the inspector first.");
|
|
93
|
+
openRun(node.targets, values.get(node.sourceId) ?? "", node.outputId, node.id);
|
|
94
|
+
});
|
|
95
|
+
if (!node.targets.length) trigger.title = "Assign a target in the inspector";
|
|
96
|
+
trigger.className = "primary";
|
|
97
|
+
card.append(trigger);
|
|
98
|
+
}
|
|
99
|
+
canvas.append(card);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function addSelect(parent, label, choices, value, onChange) {
|
|
104
|
+
const wrap = element("label", label);
|
|
105
|
+
const select = element("select");
|
|
106
|
+
for (const [id, title] of choices) select.add(new Option(title, id));
|
|
107
|
+
select.value = value ?? "";
|
|
108
|
+
select.onchange = () => onChange(select.value);
|
|
109
|
+
wrap.append(select);
|
|
110
|
+
parent.append(wrap);
|
|
111
|
+
return select;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function labelFor(id) {
|
|
115
|
+
return project.agents.find(agent => agent.id === id)?.name ??
|
|
116
|
+
project.workflows.find(workflow => "workflow:" + workflow.id === id)?.name ?? id;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function renderInspector() {
|
|
120
|
+
const box = $("#inspector");
|
|
121
|
+
box.replaceChildren();
|
|
122
|
+
const node = project.layout.find(item => item.id === selected);
|
|
123
|
+
if (!node) { box.append(element("p", "Select a component to configure it.")); return; }
|
|
124
|
+
|
|
125
|
+
const label = element("label", "Label");
|
|
126
|
+
const field = element("input");
|
|
127
|
+
field.value = node.label;
|
|
128
|
+
field.maxLength = 160;
|
|
129
|
+
field.oninput = () => { node.label = field.value; dirty = true; renderCanvas(); };
|
|
130
|
+
label.append(field);
|
|
131
|
+
const actions = element("div");
|
|
132
|
+
actions.className = "actions";
|
|
133
|
+
actions.append(button("Move up", () => move(node, -1)), button("Move down", () => move(node, 1)), button("Remove", () => {
|
|
134
|
+
project.layout = project.layout.filter(item => item !== node);
|
|
135
|
+
for (const item of project.layout) {
|
|
136
|
+
if (item.sourceId === node.id) item.sourceId = "";
|
|
137
|
+
if (item.outputId === node.id) item.outputId = "";
|
|
138
|
+
}
|
|
139
|
+
selected = null;
|
|
140
|
+
change();
|
|
141
|
+
}));
|
|
142
|
+
box.append(label, actions);
|
|
143
|
+
if (!["button", "agent-card"].includes(node.kind)) return;
|
|
144
|
+
|
|
145
|
+
const fields = project.layout.filter(item => ["input", "textarea"].includes(item.kind));
|
|
146
|
+
const results = project.layout.filter(item => item.kind === "output");
|
|
147
|
+
addSelect(box, "Input component", [["", "Enter in run drawer"], ...fields.map(item => [item.id, item.label])], node.sourceId, id => {
|
|
148
|
+
node.sourceId = id; dirty = true;
|
|
149
|
+
});
|
|
150
|
+
addSelect(box, "Output component", [["", "Show in run drawer"], ...results.map(item => [item.id, item.label])], node.outputId, id => {
|
|
151
|
+
node.outputId = id; dirty = true;
|
|
152
|
+
});
|
|
153
|
+
if (node.kind === "agent-card") {
|
|
154
|
+
addSelect(box, "Agent", [["", "Choose an agent"], ...project.agents.map(agent => [agent.id, agent.name])], node.targets[0], id => {
|
|
155
|
+
if (node.label === names["agent-card"] || node.label === labelFor(node.targets[0])) {
|
|
156
|
+
node.label = id ? labelFor(id) : names["agent-card"];
|
|
157
|
+
}
|
|
158
|
+
node.targets = id ? [id] : [];
|
|
159
|
+
change();
|
|
160
|
+
});
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
box.append(element("h2", "Run order"));
|
|
164
|
+
node.targets.forEach((target, index) => {
|
|
165
|
+
const row = element("div", labelFor(target));
|
|
166
|
+
row.className = "binding";
|
|
167
|
+
row.append(button("Remove", () => { node.targets.splice(index, 1); change(); }));
|
|
168
|
+
box.append(row);
|
|
169
|
+
});
|
|
170
|
+
const options = [
|
|
171
|
+
...project.agents.map(agent => [agent.id, agent.name]),
|
|
172
|
+
...project.workflows.filter(item => item.runnable).map(item => ["workflow:" + item.id, item.name + " (workflow)"]),
|
|
173
|
+
];
|
|
174
|
+
addSelect(box, "Add next step", [["", "Choose agent or workflow"], ...options], "", id => {
|
|
175
|
+
if (id && node.targets.length < 8) { node.targets.push(id); change(); }
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function renderCatalog() {
|
|
180
|
+
for (const [id, rows] of [["agents", project.agents], ["workflows", project.workflows], ["teams", project.teams]]) {
|
|
181
|
+
const section = $("#" + id);
|
|
182
|
+
section.replaceChildren();
|
|
183
|
+
if (!rows.length) section.append(element("p", "None in this project."));
|
|
184
|
+
for (const row of rows) {
|
|
185
|
+
if (id === "agents") {
|
|
186
|
+
section.append(renderAgentCard(dom, { name: row.name, source: agentSources[row.source], onRun: () => openRun([row.id]) }));
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const card = element("article");
|
|
190
|
+
card.className = "agent-card";
|
|
191
|
+
card.append(element("strong", row.name));
|
|
192
|
+
if (id === "workflows") card.append(row.runnable
|
|
193
|
+
? button("Run now", () => openRun(["workflow:" + row.id]))
|
|
194
|
+
: element("span", "Cloud workflow requires the console"));
|
|
195
|
+
if (id === "teams") card.append(element("span", "Cloud team"));
|
|
196
|
+
section.append(card);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function openRun(targets, input = "", outputId = "", buttonId) {
|
|
202
|
+
pending = { targets, outputId, buttonId };
|
|
203
|
+
$("#run-header").replaceChildren(renderRunHeader(dom, {
|
|
204
|
+
title: targets.map(labelFor).join(" → "), kind: targets.length > 1 || targets[0].startsWith("workflow:") ? "Workflow" : "Agent",
|
|
205
|
+
closeId: "close-run", onClose: () => $("#drawer").close(),
|
|
206
|
+
}));
|
|
207
|
+
$("#prompt").value = input;
|
|
208
|
+
$("#run-result").textContent = "";
|
|
209
|
+
$("#run-status").textContent = "";
|
|
210
|
+
const picker = $("#model");
|
|
211
|
+
picker.replaceChildren(...project.models.map(model => new Option(model, model)));
|
|
212
|
+
const needsLocalModel = targets.some(id => id.startsWith("local:"));
|
|
213
|
+
picker.hidden = !needsLocalModel;
|
|
214
|
+
document.querySelector('label[for="model"]').hidden = !needsLocalModel;
|
|
215
|
+
$("#drawer").showModal();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
$("#runner").onsubmit = async event => {
|
|
219
|
+
event.preventDefault();
|
|
220
|
+
$("#run").disabled = true;
|
|
221
|
+
$("#close-run").disabled = true;
|
|
222
|
+
$("#run-status").textContent = "Running workflow…";
|
|
223
|
+
try {
|
|
224
|
+
const { answers } = await api("run", { targets: pending.targets, buttonId: pending.buttonId, input: $("#prompt").value, model: $("#model").value });
|
|
225
|
+
const text = answers.map(({ agent, output }) => agent + "\n" + output).join("\n\n");
|
|
226
|
+
$("#run-result").textContent = text;
|
|
227
|
+
if (pending.outputId) outputs.set(pending.outputId, answers.at(-1).output);
|
|
228
|
+
renderCanvas();
|
|
229
|
+
$("#run-status").textContent = "Run completed.";
|
|
230
|
+
} catch (error) {
|
|
231
|
+
$("#run-status").textContent = error.message;
|
|
232
|
+
} finally {
|
|
233
|
+
$("#run").disabled = false;
|
|
234
|
+
$("#close-run").disabled = false;
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
$("#drawer").oncancel = event => { if ($("#run").disabled) event.preventDefault(); };
|
|
238
|
+
|
|
239
|
+
async function load({ catalogOnly = false } = {}) {
|
|
240
|
+
const next = await api("project");
|
|
241
|
+
if (catalogOnly) {
|
|
242
|
+
for (const key of ["agents", "workflows", "teams", "models"]) project[key] = next[key];
|
|
243
|
+
} else {
|
|
244
|
+
project = next;
|
|
245
|
+
dirty = false;
|
|
246
|
+
}
|
|
247
|
+
$("#project-name").textContent = project.name;
|
|
248
|
+
if (project.exported) {
|
|
249
|
+
document.body.classList.add("exported");
|
|
250
|
+
document.title = project.name;
|
|
251
|
+
$("main h1").textContent = project.name;
|
|
252
|
+
} else {
|
|
253
|
+
renderCatalog();
|
|
254
|
+
renderInspector();
|
|
255
|
+
}
|
|
256
|
+
renderCanvas();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
for (const [kind, title] of Object.entries(names)) {
|
|
260
|
+
const item = button(title, () => add(kind));
|
|
261
|
+
item.draggable = true;
|
|
262
|
+
item.ondragstart = event => event.dataTransfer.setData("text/lyra-component", kind);
|
|
263
|
+
$("#palette").append(item);
|
|
264
|
+
}
|
|
265
|
+
$("#canvas").ondragover = event => { if (event.dataTransfer.types.includes("text/lyra-component")) event.preventDefault(); };
|
|
266
|
+
$("#canvas").ondrop = event => { event.preventDefault(); add(event.dataTransfer.getData("text/lyra-component")); };
|
|
267
|
+
$("#refresh").onclick = () => load({ catalogOnly: dirty }).then(() => announce("Project refreshed.")).catch(error => announce(error.message));
|
|
268
|
+
$("#pull").onclick = async () => {
|
|
269
|
+
$("#pull").disabled = true;
|
|
270
|
+
try {
|
|
271
|
+
const result = await api("pull", {});
|
|
272
|
+
await load({ catalogOnly: true });
|
|
273
|
+
announce(result.added + " added. " + result.preserved + " existing files preserved.");
|
|
274
|
+
} catch (error) { announce(error.message); }
|
|
275
|
+
finally { $("#pull").disabled = false; }
|
|
276
|
+
};
|
|
277
|
+
$("#save").onclick = async () => {
|
|
278
|
+
$("#save").disabled = true;
|
|
279
|
+
const snapshot = JSON.stringify(project.layout);
|
|
280
|
+
try {
|
|
281
|
+
const result = await api("save", { layout: JSON.parse(snapshot), revision: project.revision });
|
|
282
|
+
project.revision = result.revision;
|
|
283
|
+
dirty = snapshot !== JSON.stringify(project.layout);
|
|
284
|
+
announce(dirty ? "Saved. You have newer canvas edits." : "Saved to manifest.json.");
|
|
285
|
+
} catch (error) { announce(error.message); }
|
|
286
|
+
finally { $("#save").disabled = false; }
|
|
287
|
+
};
|
|
288
|
+
window.addEventListener("beforeunload", event => { if (dirty) { event.preventDefault(); event.returnValue = ""; } });
|
|
289
|
+
load().catch(error => announce(error.message));
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { pythonSource } from "./python-agent.js";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { readCatalog, resolveSequence, validateLayout } from "./project.js";
|
|
5
|
+
|
|
6
|
+
const runtime = [
|
|
7
|
+
"studio/server.js", "studio/project.js", "studio/sync.js", "studio/index.html",
|
|
8
|
+
"studio/browser.js", "studio/studio.css", "studio/agent-ui.js", "studio/agent-ui.css", "app-builder/saved-app.js",
|
|
9
|
+
"runtime/local-cli.js", "runtime/run-agent.js", "studio/python-agent.js", "studio/python-agent.py",
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export async function exportStudioApp(app, root, directory) {
|
|
13
|
+
const layout = validateLayout(app.studio.layout);
|
|
14
|
+
if (!layout.length) throw new Error("Add components to the Studio canvas and save before exporting.");
|
|
15
|
+
const catalog = await readCatalog(root);
|
|
16
|
+
const agents = new Map();
|
|
17
|
+
const workflows = new Map();
|
|
18
|
+
const buttons = layout.filter(node => ["button", "agent-card"].includes(node.kind));
|
|
19
|
+
for (const button of buttons) {
|
|
20
|
+
if ((button.sourceId && !layout.some(node => node.id === button.sourceId && ["input", "textarea"].includes(node.kind))) ||
|
|
21
|
+
(button.outputId && !layout.some(node => node.id === button.outputId && node.kind === "output"))) {
|
|
22
|
+
throw new Error("Fix the input or output binding for " + button.label + " in Studio.");
|
|
23
|
+
}
|
|
24
|
+
let sequence;
|
|
25
|
+
try {
|
|
26
|
+
sequence = resolveSequence(catalog, button.targets);
|
|
27
|
+
if (button.kind === "agent-card" && !catalog.agents.has(button.targets[0])) {
|
|
28
|
+
throw new Error("Choose one agent for this card.");
|
|
29
|
+
}
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new Error("Fix the run targets for " + button.label + ": " + error.message);
|
|
32
|
+
}
|
|
33
|
+
for (const { agentId } of sequence) agents.set(agentId, catalog.agents.get(agentId));
|
|
34
|
+
for (const target of button.targets.filter(id => id.startsWith("workflow:"))) {
|
|
35
|
+
const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
|
|
36
|
+
workflows.set(workflow.id, {
|
|
37
|
+
id: workflow.id, name: workflow.name, runnable: true,
|
|
38
|
+
steps: workflow.steps.map(({ agentId, task, input, output }) => ({ agentId, task, input, output })),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const name = typeof app.application?.name === "string" ? app.application.name : "Lyra app";
|
|
43
|
+
const files = await Promise.all(runtime.map(async file => [
|
|
44
|
+
"runtime/" + file, await readFile(new URL("../" + file, import.meta.url)),
|
|
45
|
+
]));
|
|
46
|
+
const pythonAgents = [...agents.values()].filter(agent => agent.source === "python");
|
|
47
|
+
const pythonFiles = new Map();
|
|
48
|
+
for (const agent of pythonAgents) {
|
|
49
|
+
if (pythonFiles.has(agent.file)) continue;
|
|
50
|
+
const path = await pythonSource(root, agent, false);
|
|
51
|
+
pythonFiles.set(agent.file, await readFile(path));
|
|
52
|
+
}
|
|
53
|
+
for (const [filename, source] of pythonFiles) files.push(["python-agents/" + filename, source]);
|
|
54
|
+
const pythonNotes = pythonAgents.length
|
|
55
|
+
? "\nInstall the Python SDK and any agent dependencies in your Python environment. Set LYRA_PYTHON to its interpreter if needed. The python-agents folder contains the source of the bound agents.\n"
|
|
56
|
+
: "";
|
|
57
|
+
files.push(
|
|
58
|
+
["LICENSE", await readFile(new URL("../../LICENSE", import.meta.url))],
|
|
59
|
+
["package.json", { name: "lyra-app", version: "1.0.0", private: true, type: "module", engines: { node: ">=22.13.0" }, scripts: { start: "node server.js" } }],
|
|
60
|
+
["manifest.json", { version: "3.0", application: { id: "lyra-app", name }, studio: { layout } }],
|
|
61
|
+
["catalog.json", { agents: [...agents.values()], workflows: [...workflows.values()] }],
|
|
62
|
+
[".gitignore", ".lyra/\n.env\n"],
|
|
63
|
+
["README.md", "# Run the exported Lyra app\n\nUse Node.js 22.13 or newer. Run `npm start` and open the loopback URL printed in the terminal.\n\nLocal agents require `OPENAI_API_KEY`. Cloud agents require `LYRA_API_KEY`, plus an OpenAI key configured in Cloud Models. Set credentials in the environment. The export includes system prompts for referenced local agents. The server is intended for local use.\n" + pythonNotes],
|
|
64
|
+
["server.js", 'import { readFile } from "node:fs/promises";\nimport { fileURLToPath } from "node:url";\nimport { startStudio } from "./runtime/studio/server.js";\n\nconst snapshot = JSON.parse(await readFile(new URL("./catalog.json", import.meta.url), "utf8"));\nconst catalog = { agents: new Map(snapshot.agents.map(agent => [agent.id, agent])), workflows: snapshot.workflows, teams: [] };\nconst { url } = await startStudio(fileURLToPath(new URL(".", import.meta.url)), { appCatalog: catalog });\nconsole.log("Lyra app: " + url);\n'],
|
|
65
|
+
);
|
|
66
|
+
try {
|
|
67
|
+
await mkdir(directory);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error.code === "EEXIST") throw new Error("Choose a new directory. Existing files were preserved.");
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
for (const [file, contents] of files) {
|
|
73
|
+
const path = join(directory, file);
|
|
74
|
+
await mkdir(dirname(path), { recursive: true });
|
|
75
|
+
await writeFile(path, typeof contents === "string" || Buffer.isBuffer(contents)
|
|
76
|
+
? contents
|
|
77
|
+
: JSON.stringify(contents, null, 2) + "\n", { flag: "wx" });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -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()
|