agent-lyra 0.3.2 → 0.6.1
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 +394 -119
- package/bin/agent-lyra.js +16 -0
- package/package.json +60 -56
- package/src/app-builder/export.js +50 -0
- package/src/app-builder/init.js +40 -11
- package/src/app-builder/preview.js +8 -0
- 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 +6 -7
- package/src/memory/cli.js +49 -0
- package/src/memory/contract.json +28 -0
- package/src/memory/index.d.ts +49 -0
- package/src/memory/index.js +259 -0
- package/src/memory/lifecycle.js +29 -0
- package/src/memory/proposals.js +84 -0
- package/src/memory/skills-cli.js +26 -0
- package/src/memory/sync.js +85 -0
- package/src/memory/validation.js +25 -0
- package/src/runtime/local-cli.js +4 -3
- package/src/studio/agent-ui.css +43 -0
- package/src/studio/agent-ui.js +32 -0
- package/src/studio/browser.js +331 -0
- package/src/studio/export.js +80 -0
- package/src/studio/index.html +37 -0
- package/src/studio/memory-actions.js +37 -0
- package/src/studio/memory-panel.js +200 -0
- package/src/studio/project.js +197 -0
- package/src/studio/pull-agent.js +72 -0
- package/src/studio/push.js +54 -0
- package/src/studio/python-agent.js +47 -0
- package/src/studio/python-agent.py +25 -0
- package/src/studio/server.js +143 -0
- package/src/studio/session.js +83 -0
- package/src/studio/studio.css +10 -0
- package/src/studio/sync.js +42 -0
- package/src/studio/workflow-sync.js +157 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
export function mountMemoryPanel(api) {
|
|
2
|
+
const byId = id => document.getElementById(id);
|
|
3
|
+
const panel = byId("memory-panel");
|
|
4
|
+
const lists = byId("memory-list");
|
|
5
|
+
const detail = byId("memory-detail");
|
|
6
|
+
const status = byId("memory-status");
|
|
7
|
+
const query = byId("memory-query");
|
|
8
|
+
let busy = false;
|
|
9
|
+
|
|
10
|
+
function element(tag, text) {
|
|
11
|
+
const node = document.createElement(tag);
|
|
12
|
+
node.textContent = text;
|
|
13
|
+
return node;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function action(text, callback) {
|
|
17
|
+
const button = element("button", text);
|
|
18
|
+
button.type = "button";
|
|
19
|
+
button.addEventListener("click", event => run(button, () => callback(event)));
|
|
20
|
+
return button;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function run(button, callback) {
|
|
24
|
+
if (busy) return;
|
|
25
|
+
busy = true;
|
|
26
|
+
if (button) button.disabled = true;
|
|
27
|
+
status.textContent = "Working…";
|
|
28
|
+
try { status.textContent = await callback() || ""; }
|
|
29
|
+
catch (error) { status.textContent = error.message; }
|
|
30
|
+
finally { busy = false; if (button) button.disabled = false; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function reload() {
|
|
34
|
+
const { records, stats } = await api("memory/list", { query: query.value });
|
|
35
|
+
byId("memory-summary").textContent = stats.candidate + " candidates · " + stats.verified + " verified · " + stats.archived + " archived";
|
|
36
|
+
await loadProposals();
|
|
37
|
+
lists.replaceChildren();
|
|
38
|
+
detail.replaceChildren();
|
|
39
|
+
if (!records.length) lists.append(element("p", query.value.trim() ? "No matching memories." : "No memories yet. Record a lesson to get started."));
|
|
40
|
+
for (const record of records) {
|
|
41
|
+
const item = document.createElement("article");
|
|
42
|
+
item.className = "node";
|
|
43
|
+
item.append(element("strong", record.title), element("p", record.type + " · " + record.status),
|
|
44
|
+
action("View memory", () => show(record)));
|
|
45
|
+
lists.append(item);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function evidenceForm(fields, label, callback) {
|
|
50
|
+
const form = document.createElement("form");
|
|
51
|
+
for (const [name, caption, options] of fields) {
|
|
52
|
+
const field = element("label", caption);
|
|
53
|
+
const input = document.createElement(options ? "select" : "input");
|
|
54
|
+
input.name = name;
|
|
55
|
+
input.required = true;
|
|
56
|
+
for (const option of options ?? []) input.append(element("option", option));
|
|
57
|
+
field.append(input);
|
|
58
|
+
form.append(field);
|
|
59
|
+
}
|
|
60
|
+
const agreement = element("label", "I reviewed the evidence and confirmed it passed");
|
|
61
|
+
const checkbox = document.createElement("input");
|
|
62
|
+
checkbox.type = "checkbox";
|
|
63
|
+
checkbox.required = true;
|
|
64
|
+
agreement.prepend(checkbox);
|
|
65
|
+
const submit = element("button", label);
|
|
66
|
+
form.append(agreement, submit);
|
|
67
|
+
form.onsubmit = event => {
|
|
68
|
+
event.preventDefault();
|
|
69
|
+
const evidence = Object.fromEntries(new FormData(form));
|
|
70
|
+
return run(submit, () => callback({ ...evidence, result: "passed", reviewed: true }));
|
|
71
|
+
};
|
|
72
|
+
return form;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function loadProposals() {
|
|
76
|
+
const section = byId("memory-proposals");
|
|
77
|
+
const proposals = await api("memory/proposals", {});
|
|
78
|
+
section.replaceChildren();
|
|
79
|
+
if (!proposals.length) section.append(element("p", "No skill proposals in this project."));
|
|
80
|
+
for (const proposal of proposals) {
|
|
81
|
+
const item = document.createElement("details");
|
|
82
|
+
item.className = "node";
|
|
83
|
+
item.append(element("summary", proposal.title + " · " + proposal.status),
|
|
84
|
+
element("pre", proposal.markdown),
|
|
85
|
+
element("p", "Source evidence: " + proposal.sources.map(source => source.evidenceId).join(", ")));
|
|
86
|
+
const decide = async (decision, evidence) => {
|
|
87
|
+
await api("memory/proposal-decision", { id: proposal.id, decision, evidence });
|
|
88
|
+
await loadProposals();
|
|
89
|
+
return "Proposal " + decision + ".";
|
|
90
|
+
};
|
|
91
|
+
if (proposal.status === "pending") {
|
|
92
|
+
item.append(evidenceForm([["evidenceId", "Independent regression evidence ID"]], "Approve proposal",
|
|
93
|
+
evidence => decide("approved", { ...evidence, context: proposal.context })),
|
|
94
|
+
action("Reject proposal", () => decide("rejected")));
|
|
95
|
+
}
|
|
96
|
+
if (proposal.status === "approved") item.append(action("Withdraw approval", () => decide("withdrawn")));
|
|
97
|
+
section.append(item);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function show(record) {
|
|
102
|
+
detail.replaceChildren(element("h3", record.title), element("pre", record.learning),
|
|
103
|
+
element("p", "Evidence: " + (record.evidence.join(", ") || "None")), element("p", "Record ID: " + record.id));
|
|
104
|
+
if (record.status !== "archived") detail.append(action("Archive", async () => {
|
|
105
|
+
await api("memory/archive", { id: record.id });
|
|
106
|
+
await reload();
|
|
107
|
+
return "Archived memory.";
|
|
108
|
+
}));
|
|
109
|
+
if (record.status === "candidate") {
|
|
110
|
+
const review = document.createElement("details");
|
|
111
|
+
review.append(element("summary", "Review verification evidence"), evidenceForm([
|
|
112
|
+
["adapter", "Evidence type", ["coding", "practice"]], ["context", "Review context"],
|
|
113
|
+
["evidenceId", "Evidence ID"], ["description", "Test or exercise name"],
|
|
114
|
+
], "Verify memory", async ({ description, ...evidence }) => {
|
|
115
|
+
const field = evidence.adapter === "coding" ? "test" : "exercise";
|
|
116
|
+
const verified = await api("memory/verify", { id: record.id, evidence: { ...evidence, [field]: description } });
|
|
117
|
+
await reload();
|
|
118
|
+
show(verified);
|
|
119
|
+
return "Verified memory.";
|
|
120
|
+
}));
|
|
121
|
+
detail.append(review);
|
|
122
|
+
}
|
|
123
|
+
if (record.status !== "verified") return;
|
|
124
|
+
detail.append(action("Preview Cloud upload", async () => {
|
|
125
|
+
const preview = await api("memory/preview", { id: record.id });
|
|
126
|
+
const review = document.createElement("section");
|
|
127
|
+
review.className = "node";
|
|
128
|
+
review.append(element("h3", preview.destination), element("pre", JSON.stringify(preview.memory, null, 2)));
|
|
129
|
+
const push = action("Push this memory to Cloud", async () => {
|
|
130
|
+
await api("memory/push", { id: record.id, fingerprint: preview.fingerprint });
|
|
131
|
+
review.remove();
|
|
132
|
+
return "Pushed memory to Cloud.";
|
|
133
|
+
});
|
|
134
|
+
review.append(push, action("Cancel upload", () => review.remove()));
|
|
135
|
+
detail.querySelector("[data-preview]")?.remove();
|
|
136
|
+
review.dataset.preview = "";
|
|
137
|
+
detail.append(review);
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
byId("open-memory").onclick = () => {
|
|
142
|
+
panel.showModal();
|
|
143
|
+
return run(null, reload);
|
|
144
|
+
};
|
|
145
|
+
byId("close-memory").onclick = () => panel.close();
|
|
146
|
+
byId("memory-search").onsubmit = event => {
|
|
147
|
+
event.preventDefault();
|
|
148
|
+
return run(event.submitter, reload);
|
|
149
|
+
};
|
|
150
|
+
byId("memory-create").onsubmit = event => {
|
|
151
|
+
event.preventDefault();
|
|
152
|
+
const form = event.currentTarget;
|
|
153
|
+
return run(event.submitter, async () => {
|
|
154
|
+
await api("memory/record", Object.fromEntries(new FormData(form)));
|
|
155
|
+
form.reset();
|
|
156
|
+
query.value = "";
|
|
157
|
+
await reload();
|
|
158
|
+
return "Recorded a candidate.";
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
function compareCopies(id, copies) {
|
|
162
|
+
detail.replaceChildren(element("h3", "Both copies changed"),
|
|
163
|
+
element("h4", "Project copy"),
|
|
164
|
+
element("pre", copies.localDeleted ? "Deleted locally" : JSON.stringify(copies.local, null, 2)),
|
|
165
|
+
element("h4", "Cloud copy"),
|
|
166
|
+
element("pre", copies.cloudDeleted ? "Deleted in Cloud" : JSON.stringify(copies.cloud, null, 2)));
|
|
167
|
+
if (copies.localDeleted || copies.cloudDeleted) {
|
|
168
|
+
detail.append(element("p", "Automatic replacement is unavailable when one copy was deleted."));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const resolve = async choice => {
|
|
172
|
+
const result = await api("memory/resolve", { id, choice, fingerprint: copies.fingerprint });
|
|
173
|
+
await reload();
|
|
174
|
+
return result?.keptLocal
|
|
175
|
+
? "Kept the project copy. Preview a fresh upload to update Cloud."
|
|
176
|
+
: "Saved the Cloud copy as a candidate for local review.";
|
|
177
|
+
};
|
|
178
|
+
detail.append(action("Keep project copy", () => resolve("local")),
|
|
179
|
+
action("Replace project copy with Cloud copy", () => resolve("cloud")));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
byId("memory-pull").onsubmit = event => {
|
|
183
|
+
event.preventDefault();
|
|
184
|
+
const form = event.currentTarget;
|
|
185
|
+
return run(event.submitter, async () => {
|
|
186
|
+
const id = new FormData(form).get("id").trim();
|
|
187
|
+
let result;
|
|
188
|
+
try { result = await api("memory/pull", { id }); }
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (error.message !== "Both copies changed. Review before syncing.") throw error;
|
|
191
|
+
const copies = await api("memory/compare", { id });
|
|
192
|
+
if (!copies) return "The copies changed during comparison. Try pulling again.";
|
|
193
|
+
compareCopies(id, copies);
|
|
194
|
+
return "Review both copies before choosing which to keep in this project.";
|
|
195
|
+
}
|
|
196
|
+
await reload();
|
|
197
|
+
return result.deleted ? "Applied Cloud deletion." : result.updated ? "Pulled a candidate for local review." : "Already up to date.";
|
|
198
|
+
});
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
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 { readMode, readSdkKey, requireCloudMode } from "./session.js";
|
|
7
|
+
import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
|
|
8
|
+
import { withProjectMemory } from "../memory/lifecycle.js";
|
|
9
|
+
import { runAgent } from "../runtime/run-agent.js";
|
|
10
|
+
|
|
11
|
+
export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
|
|
12
|
+
const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
|
|
13
|
+
const cloudId = /^[a-f0-9]{24}$/i;
|
|
14
|
+
|
|
15
|
+
async function files(directory, extension) {
|
|
16
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
|
|
17
|
+
if (error.code === "ENOENT") return [];
|
|
18
|
+
throw error;
|
|
19
|
+
});
|
|
20
|
+
return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function markdownValue(source, name) {
|
|
24
|
+
const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
|
|
25
|
+
if (!raw) return "";
|
|
26
|
+
if (raw.startsWith('"')) {
|
|
27
|
+
try { return JSON.parse(raw); } catch { return ""; }
|
|
28
|
+
}
|
|
29
|
+
return raw.replace(/^'|'$/g, "");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function readLocalAgent(source) {
|
|
33
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
|
|
34
|
+
if (!front) return null;
|
|
35
|
+
const id = markdownValue(front[1], "id");
|
|
36
|
+
const name = markdownValue(front[1], "name");
|
|
37
|
+
const mode = markdownValue(front[1], "mode");
|
|
38
|
+
const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
|
|
39
|
+
if (typeof name !== "string" || !name || !safeId.test(id)) return null;
|
|
40
|
+
if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
|
|
41
|
+
if (mode && mode !== "standalone") return null;
|
|
42
|
+
if (!prompt || prompt.length > 16_000) return null;
|
|
43
|
+
return { id: "local:" + id, name, source: "local", prompt };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function readCatalog(root) {
|
|
47
|
+
const directory = join(root, ".lyra", "agents");
|
|
48
|
+
const agents = new Map();
|
|
49
|
+
for (const name of await files(directory, ".md")) {
|
|
50
|
+
const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
|
|
51
|
+
if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
|
|
52
|
+
}
|
|
53
|
+
async function records(kind) {
|
|
54
|
+
const folder = join(root, ".lyra", kind);
|
|
55
|
+
const rows = [];
|
|
56
|
+
for (const name of await files(folder, ".json")) {
|
|
57
|
+
try {
|
|
58
|
+
const item = JSON.parse(await readFile(join(folder, name), "utf8"));
|
|
59
|
+
if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return rows;
|
|
65
|
+
}
|
|
66
|
+
for (const name of await files(directory, ".json")) {
|
|
67
|
+
let item;
|
|
68
|
+
try {
|
|
69
|
+
item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof SyntaxError) continue;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
const descriptor = pythonDescriptor(item);
|
|
75
|
+
if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
|
|
76
|
+
typeof item.name !== "string" || !item.name.trim()) continue;
|
|
77
|
+
const id = "python:" + item.id;
|
|
78
|
+
if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
|
|
79
|
+
}
|
|
80
|
+
return { agents, workflows: await records("workflows"), teams: await records("teams"), skills: await records("skills") };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function validateLayout(layout) {
|
|
84
|
+
if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
|
|
85
|
+
const ids = new Set();
|
|
86
|
+
const checked = layout.map(node => {
|
|
87
|
+
if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
|
|
88
|
+
typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
|
|
89
|
+
ids.add(node.id);
|
|
90
|
+
return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
|
|
91
|
+
sourceId: String(node.sourceId ?? "").slice(0, 96),
|
|
92
|
+
outputId: String(node.outputId ?? "").slice(0, 96),
|
|
93
|
+
targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
|
|
94
|
+
} };
|
|
95
|
+
});
|
|
96
|
+
return checked;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function manifestFile(root) {
|
|
100
|
+
const path = join(root, "manifest.json");
|
|
101
|
+
try {
|
|
102
|
+
if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
|
|
103
|
+
const raw = await readFile(path, "utf8");
|
|
104
|
+
return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (error.code !== "ENOENT") throw error;
|
|
107
|
+
return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function readLayout(root) {
|
|
112
|
+
const { manifest, revision } = await manifestFile(root);
|
|
113
|
+
return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function saveLayout(root, layout, revision) {
|
|
117
|
+
const current = await manifestFile(root);
|
|
118
|
+
if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
|
|
119
|
+
if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
|
|
120
|
+
throw new Error("The existing manifest is not an App Builder manifest.");
|
|
121
|
+
}
|
|
122
|
+
const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
|
|
123
|
+
const temp = current.path + "." + randomUUID() + ".tmp";
|
|
124
|
+
await writeFile(temp, content, { flag: "wx" });
|
|
125
|
+
try {
|
|
126
|
+
if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
|
|
127
|
+
await rename(temp, current.path);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
return { revision: createHash("sha256").update(content).digest("hex") };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function resolveSequence(catalog, targets) {
|
|
136
|
+
if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
|
|
137
|
+
throw new Error("Choose one to eight agents or workflows.");
|
|
138
|
+
}
|
|
139
|
+
const sequence = targets.flatMap(target => {
|
|
140
|
+
if (typeof target !== "string") throw new Error("Invalid run target.");
|
|
141
|
+
if (!target.startsWith("workflow:")) return [{ agentId: target }];
|
|
142
|
+
const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
|
|
143
|
+
if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
|
|
144
|
+
return workflow.steps;
|
|
145
|
+
});
|
|
146
|
+
if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
|
|
147
|
+
throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
|
|
148
|
+
}
|
|
149
|
+
return sequence;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function runSelection(root, { targets, input, model }, catalog) {
|
|
153
|
+
if (typeof input !== "string" || !input.trim() || input.length > 4000) {
|
|
154
|
+
throw new Error("Enter up to 4,000 characters.");
|
|
155
|
+
}
|
|
156
|
+
const exported = Boolean(catalog);
|
|
157
|
+
catalog ??= await readCatalog(root);
|
|
158
|
+
const sequence = resolveSequence(catalog, targets);
|
|
159
|
+
const local = sequence.some(step => step.agentId.startsWith("local:"));
|
|
160
|
+
if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
|
|
161
|
+
throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
|
|
162
|
+
}
|
|
163
|
+
let cloud = null;
|
|
164
|
+
if (sequence.some(step => step.agentId.startsWith("cloud:"))) {
|
|
165
|
+
if (!exported) requireCloudMode(await readMode(root));
|
|
166
|
+
cloud = createSavedAgentClient(exported ? undefined : { key: await readSdkKey(root) });
|
|
167
|
+
}
|
|
168
|
+
const store = local ? await openStore(root) : null;
|
|
169
|
+
const answers = [];
|
|
170
|
+
const named = new Map();
|
|
171
|
+
try {
|
|
172
|
+
for (const step of sequence) {
|
|
173
|
+
const agent = catalog.agents.get(step.agentId);
|
|
174
|
+
const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
|
|
175
|
+
const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
|
|
176
|
+
let output;
|
|
177
|
+
if (agent.source === "cloud") {
|
|
178
|
+
output = await cloud.invoke(agent.id.slice("cloud:".length), text);
|
|
179
|
+
} else if (agent.source === "python") {
|
|
180
|
+
output = await runPythonAgent(root, agent, text, exported);
|
|
181
|
+
} else {
|
|
182
|
+
const request = { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] };
|
|
183
|
+
const event = await runAgent({
|
|
184
|
+
agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
|
|
185
|
+
request: exported ? request : await withProjectMemory(root, request),
|
|
186
|
+
});
|
|
187
|
+
if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
|
|
188
|
+
output = event.data.result.text;
|
|
189
|
+
}
|
|
190
|
+
if (step.output) named.set(step.output, output);
|
|
191
|
+
answers.push({ agent: agent.name, output });
|
|
192
|
+
}
|
|
193
|
+
return { answers };
|
|
194
|
+
} finally {
|
|
195
|
+
store?.close();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { readLocalAgent } from "./project.js";
|
|
5
|
+
import { readMode, readSdkKey, requireCloudMode } from "./session.js";
|
|
6
|
+
|
|
7
|
+
const hash = (name, systemPrompt) => createHash("sha256").update(JSON.stringify({ name, systemPrompt })).digest("hex");
|
|
8
|
+
const digest = /^[a-f0-9]{64}$/;
|
|
9
|
+
|
|
10
|
+
export async function pullAgentEdits(root, id, { request = fetch, key } = {}) {
|
|
11
|
+
requireCloudMode(await readMode(root));
|
|
12
|
+
if (!/^local:[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(id ?? "")) throw new Error("Choose a local Markdown text agent.");
|
|
13
|
+
const base = join(root, ".lyra");
|
|
14
|
+
const links = join(base, "agent-links");
|
|
15
|
+
const folder = join(base, "agents");
|
|
16
|
+
for (const directory of [base, links, folder]) {
|
|
17
|
+
if (!(await lstat(directory).catch(() => null))?.isDirectory()) throw new Error("Push this agent to Cloud once to link it.");
|
|
18
|
+
}
|
|
19
|
+
const metadata = join(links, id.slice(6) + ".json");
|
|
20
|
+
if (!(await lstat(metadata).catch(() => null))?.isFile()) throw new Error("Push this agent to Cloud once to link it.");
|
|
21
|
+
const link = JSON.parse(await readFile(metadata, "utf8"));
|
|
22
|
+
if (!digest.test(link?.linkId ?? "") || !digest.test(link?.revision ?? "")) throw new Error("Invalid Cloud link.");
|
|
23
|
+
|
|
24
|
+
const matches = [];
|
|
25
|
+
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
|
26
|
+
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
27
|
+
const path = join(folder, entry.name);
|
|
28
|
+
const content = await readFile(path, "utf8");
|
|
29
|
+
const parsed = readLocalAgent(content);
|
|
30
|
+
if (parsed?.id === id) matches.push({ path, content, parsed });
|
|
31
|
+
}
|
|
32
|
+
if (matches.length !== 1) throw new Error("Use a unique local agent ID before pulling edits.");
|
|
33
|
+
const [{ path, content, parsed }] = matches;
|
|
34
|
+
|
|
35
|
+
key ??= await readSdkKey(root);
|
|
36
|
+
if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before pulling edits.");
|
|
37
|
+
const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/agents/" + link.linkId, {
|
|
38
|
+
headers: { Authorization: "Bearer " + key }, redirect: "error", signal: AbortSignal.timeout(20_000),
|
|
39
|
+
});
|
|
40
|
+
const remote = await response.json();
|
|
41
|
+
if (!response.ok) throw new Error(remote.error || "Could not pull agent edits.");
|
|
42
|
+
if (remote.id !== link.cloudId || typeof remote.name !== "string" || typeof remote.prompt !== "string" ||
|
|
43
|
+
!digest.test(remote.revision ?? "")) throw new Error("The Cloud agent link no longer matches.");
|
|
44
|
+
const local = hash(parsed.name.trim(), parsed.prompt.trim());
|
|
45
|
+
if (remote.revision === link.revision || local === remote.revision) {
|
|
46
|
+
if (local !== remote.revision) return { name: parsed.name, updated: false };
|
|
47
|
+
} else {
|
|
48
|
+
if (local !== link.revision) throw new Error("Both copies changed. Review the Cloud agent and reconcile the edits before syncing.");
|
|
49
|
+
const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(content)[0];
|
|
50
|
+
const body = content.slice(front.length);
|
|
51
|
+
const next = front.replace(/^name:[^\r\n]*/m, () => "name: " + JSON.stringify(remote.name)) +
|
|
52
|
+
body.replace(/(^|\n)## System Prompt[^\S\r\n]*\r?\n[\s\S]*?(?=\r?\n## [^\n]+|$)/,
|
|
53
|
+
(_whole, prefix) => prefix + "## System Prompt\n" + remote.prompt + "\n");
|
|
54
|
+
const checked = readLocalAgent(next);
|
|
55
|
+
if (!checked || hash(checked.name, checked.prompt) !== remote.revision) {
|
|
56
|
+
throw new Error("The Cloud instructions cannot be represented in this Markdown agent. Copy them manually.");
|
|
57
|
+
}
|
|
58
|
+
if (await readFile(path, "utf8") !== content) throw new Error("The local agent changed during the pull. Try again.");
|
|
59
|
+
await replace(path, next);
|
|
60
|
+
}
|
|
61
|
+
if (link.revision !== remote.revision) {
|
|
62
|
+
await replace(metadata, JSON.stringify({ ...link, revision: remote.revision }) + "\n");
|
|
63
|
+
}
|
|
64
|
+
return { name: remote.name, updated: local !== remote.revision };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function replace(path, content) {
|
|
68
|
+
const temporary = path + "." + randomUUID() + ".tmp";
|
|
69
|
+
await writeFile(temporary, content, { flag: "wx", mode: 0o600 });
|
|
70
|
+
try { await rename(temporary, path); }
|
|
71
|
+
finally { await unlink(temporary).catch(() => {}); }
|
|
72
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { readCatalog } from "./project.js";
|
|
5
|
+
import { readMode, readSdkKey, requireCloudMode } from "./session.js";
|
|
6
|
+
|
|
7
|
+
export async function pushStudioAgent(root, id, { key, request = fetch } = {}) {
|
|
8
|
+
requireCloudMode(await readMode(root));
|
|
9
|
+
const base = join(root, ".lyra");
|
|
10
|
+
for (const directory of [base, join(base, "agents")]) {
|
|
11
|
+
if (!(await lstat(directory).catch(() => null))?.isDirectory()) throw new Error("Use a regular .lyra/agents folder.");
|
|
12
|
+
}
|
|
13
|
+
const agent = (await readCatalog(root)).agents.get(id);
|
|
14
|
+
if (agent?.source !== "local") throw new Error("Choose a local Markdown text agent to push.");
|
|
15
|
+
key ??= await readSdkKey(root);
|
|
16
|
+
if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before pushing.");
|
|
17
|
+
|
|
18
|
+
const links = join(base, "agent-links");
|
|
19
|
+
await mkdir(links, { recursive: true });
|
|
20
|
+
if (!(await lstat(links)).isDirectory()) throw new Error("Agent links must use a regular directory.");
|
|
21
|
+
const metadata = join(links, agent.id.slice("local:".length) + ".json");
|
|
22
|
+
let link;
|
|
23
|
+
try {
|
|
24
|
+
if (!(await lstat(metadata)).isFile()) throw new Error("An agent link must be a regular file.");
|
|
25
|
+
link = JSON.parse(await readFile(metadata, "utf8"));
|
|
26
|
+
if (!/^[a-f0-9]{64}$/.test(link?.linkId ?? "") || !/^[a-f0-9]{64}$/.test(link?.revision ?? "")) {
|
|
27
|
+
throw new Error("This agent has invalid Cloud link metadata.");
|
|
28
|
+
}
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error.code !== "ENOENT") throw error;
|
|
31
|
+
}
|
|
32
|
+
const linkId = link?.linkId ?? createHash("sha256").update(resolve(root) + "\0" + id).digest("hex");
|
|
33
|
+
const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/agents/" + linkId, {
|
|
34
|
+
method: "PUT", headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
|
|
35
|
+
body: JSON.stringify({ name: agent.name, prompt: agent.prompt, revision: link?.revision }),
|
|
36
|
+
redirect: "error", signal: AbortSignal.timeout(20_000),
|
|
37
|
+
});
|
|
38
|
+
const result = await response.json();
|
|
39
|
+
if (!response.ok) {
|
|
40
|
+
if (response.status === 401) throw new Error("The Cloud key was rejected. Run connect-cloud --replace-key.");
|
|
41
|
+
throw new Error(result.error || "Cloud push failed (HTTP " + response.status + ").");
|
|
42
|
+
}
|
|
43
|
+
if (!/^[a-f0-9]{24}$/i.test(result.id ?? "") || !/^[a-f0-9]{64}$/.test(result.revision ?? "")) {
|
|
44
|
+
throw new Error("Unexpected Cloud agent response.");
|
|
45
|
+
}
|
|
46
|
+
const temporary = metadata + "." + process.pid + ".tmp";
|
|
47
|
+
await writeFile(temporary, JSON.stringify({ linkId, cloudId: result.id, revision: result.revision }) + "\n", { flag: "wx", mode: 0o600 });
|
|
48
|
+
try {
|
|
49
|
+
await rename(temporary, metadata);
|
|
50
|
+
} finally {
|
|
51
|
+
await unlink(temporary).catch(() => {});
|
|
52
|
+
}
|
|
53
|
+
return { name: agent.name, created: response.status === 201 };
|
|
54
|
+
}
|
|
@@ -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()
|