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.
@@ -0,0 +1,70 @@
1
+ import { readFile } from "node:fs/promises";
2
+
3
+ export const SAVED_VERSION = "2.0";
4
+ const idPattern = /^[a-f0-9]{24}$/i;
5
+ const appIdPattern = /^[a-z][a-z0-9-]{0,79}$/;
6
+
7
+ export function validateSavedApp(manifest) {
8
+ if (manifest?.version !== SAVED_VERSION || !appIdPattern.test(manifest.application?.id ?? "") ||
9
+ typeof manifest.application.name !== "string" || !manifest.application.name.trim() ||
10
+ manifest.application.name.length > 120) {
11
+ throw new Error('Version "2.0" requires an application ID and name.');
12
+ }
13
+ const { steps } = manifest.workflow ?? {};
14
+ if (!Array.isArray(steps) || steps.length !== 2 ||
15
+ !steps.every(step => typeof step?.agentId === "string" && idPattern.test(step.agentId)) ||
16
+ steps[0].agentId.toLowerCase() === steps[1].agentId.toLowerCase()) {
17
+ throw new Error("A workflow requires two distinct saved Lyra agent IDs.");
18
+ }
19
+ return manifest;
20
+ }
21
+
22
+ export async function readAppManifest(path) {
23
+ const source = await readFile(path, "utf8");
24
+ try {
25
+ return JSON.parse(source.replace(/^\uFEFF/, ""));
26
+ } catch {
27
+ throw new Error("Application manifest is not valid JSON.");
28
+ }
29
+ }
30
+
31
+ export function createSavedAgentClient({ key = process.env.LYRA_API_KEY, fetchRequest = fetch } = {}) {
32
+ if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) {
33
+ throw new Error("Set LYRA_API_KEY to a dedicated SDK key from AgentLyra Console.");
34
+ }
35
+
36
+ async function request(path, prompt) {
37
+ const response = await fetchRequest("https://api.agentlyra.in/api/sdk/v1/saved-agents" + path, {
38
+ method: prompt === undefined ? "GET" : "POST",
39
+ headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
40
+ body: prompt === undefined ? undefined : JSON.stringify({ prompt }),
41
+ redirect: "error",
42
+ signal: AbortSignal.timeout(65_000),
43
+ });
44
+ if (!response.ok) {
45
+ if (response.status === 401) throw new Error("The SDK key is invalid or revoked.");
46
+ if (response.status === 403) throw new Error("Add your OpenAI key in AgentLyra Console → Models.");
47
+ if (response.status === 404) throw new Error("A selected agent is unavailable to this SDK key.");
48
+ throw new Error("AgentLyra Cloud request failed (HTTP " + response.status + ").");
49
+ }
50
+ return response.json();
51
+ }
52
+
53
+ return {
54
+ list: async () => (await request("")).agents,
55
+ invoke: async (id, prompt) => (await request("/" + encodeURIComponent(id) + "/invoke", prompt)).output,
56
+ };
57
+ }
58
+
59
+ export async function runSavedApp(manifest, input, client = createSavedAgentClient()) {
60
+ const [first, second] = validateSavedApp(manifest).workflow.steps;
61
+ if (typeof input !== "string" || !input.trim() || input.length > 4000) {
62
+ throw new Error("Enter between 1 and 4,000 characters.");
63
+ }
64
+ const firstOutput = await client.invoke(first.agentId, input.trim());
65
+ const output = await client.invoke(second.agentId, JSON.stringify({
66
+ input: input.trim(),
67
+ previousAgentOutput: firstOutput,
68
+ }).slice(0, 12_000));
69
+ return { firstOutput, output };
70
+ }
@@ -0,0 +1,33 @@
1
+ const form = document.querySelector("form");
2
+ const button = form.querySelector("button");
3
+ const status = document.querySelector("#status");
4
+ const result = document.querySelector("#result");
5
+
6
+ fetch("/api/app").then(response => response.json()).then(({ name }) => {
7
+ document.title = name;
8
+ document.querySelector("h1").textContent = name;
9
+ }).catch(() => { status.textContent = "Could not load application details."; });
10
+
11
+ form.addEventListener("submit", async event => {
12
+ event.preventDefault();
13
+ button.disabled = true;
14
+ result.hidden = true;
15
+ status.textContent = "Running both agents…";
16
+ try {
17
+ const response = await fetch("/api/run", {
18
+ method: "POST",
19
+ headers: { "Content-Type": "application/json" },
20
+ body: JSON.stringify({ input: document.querySelector("#input").value }),
21
+ });
22
+ const data = await response.json();
23
+ if (!response.ok) throw new Error(data.error);
24
+ document.querySelector("#output").textContent = data.output;
25
+ document.querySelector("#first").textContent = data.firstOutput;
26
+ result.hidden = false;
27
+ status.textContent = "Workflow completed.";
28
+ } catch (error) {
29
+ status.textContent = error.message;
30
+ } finally {
31
+ button.disabled = false;
32
+ }
33
+ });
@@ -0,0 +1,24 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Lyra application</title>
7
+ <style>
8
+ body { background:#f6f9f7;color:#152c23;font:1rem/1.6 system-ui,sans-serif;margin:0 }
9
+ main { max-width:50rem;margin:4rem auto;padding:0 1.25rem }
10
+ label,textarea,button { display:block;font:inherit }
11
+ textarea { box-sizing:border-box;width:100%;min-height:8rem;margin:.45rem 0 1rem;padding:.75rem;border:1px solid #8ea99c;border-radius:.5rem }
12
+ button { background:#174b38;color:white;border:0;border-radius:.5rem;padding:.6rem 1rem;cursor:pointer }
13
+ button:disabled { opacity:.65;cursor:wait }
14
+ pre { white-space:pre-wrap;overflow-wrap:anywhere;background:white;padding:1rem;border:1px solid #cfddd5;border-radius:.5rem;font:inherit }
15
+ </style>
16
+ <script src="/preview.js" defer></script>
17
+ </head>
18
+ <body><main>
19
+ <h1>Lyra application</h1>
20
+ <form><label for="input">Workflow input</label><textarea id="input" required maxlength="4000"></textarea><button>Run workflow</button></form>
21
+ <p role="status" id="status"></p>
22
+ <section hidden id="result"><h2>Final result</h2><pre id="output"></pre><details><summary>First agent output</summary><pre id="first"></pre></details></section>
23
+ </main></body>
24
+ </html>
@@ -0,0 +1,61 @@
1
+ import { createServer } from "node:http";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createSavedAgentClient, runSavedApp, validateSavedApp } from "./saved-app.js";
4
+
5
+ export async function startSavedPreview(manifest, { port = Number(process.env.LYRA_PREVIEW_PORT ?? 4173), client } = {}) {
6
+ validateSavedApp(manifest);
7
+ client ??= createSavedAgentClient();
8
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid preview port.");
9
+ const [html, script] = await Promise.all(["saved-preview.html", "saved-preview-browser.js"].map(
10
+ name => readFile(new URL("./" + name, import.meta.url)),
11
+ ));
12
+ const server = createServer(async (req, res) => {
13
+ const send = (status, body, type = "application/json; charset=utf-8") => {
14
+ res.writeHead(status, {
15
+ "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
16
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'",
17
+ });
18
+ res.end(type.startsWith("application/json") ? JSON.stringify(body) : body);
19
+ };
20
+ const authority = "127.0.0.1:" + server.address().port;
21
+ if (req.headers.host !== authority) return send(403, { error: "Use the loopback address." });
22
+ if (req.method === "GET" && req.url === "/") return send(200, html, "text/html; charset=utf-8");
23
+ if (req.method === "GET" && req.url === "/preview.js") return send(200, script, "text/javascript; charset=utf-8");
24
+ if (req.method === "GET" && req.url === "/api/app") return send(200, { name: manifest.application.name });
25
+ if (req.method !== "POST" || req.url !== "/api/run") return send(404, { error: "Not found." });
26
+ if (req.headers.origin !== "http://" + authority) return send(403, { error: "Use the application page to run agents." });
27
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") return send(415, { error: "Use application/json." });
28
+
29
+ const chunks = [];
30
+ let size = 0;
31
+ let input;
32
+ try {
33
+ for await (const chunk of req) {
34
+ size += chunk.length;
35
+ if (size > 24_576) return send(413, { error: "Input is too large." });
36
+ chunks.push(chunk);
37
+ }
38
+ input = JSON.parse(Buffer.concat(chunks).toString("utf8"))?.input;
39
+ } catch {
40
+ return send(400, { error: "Invalid request." });
41
+ }
42
+ if (typeof input !== "string" || !input.trim() || input.length > 4000) {
43
+ return send(400, { error: "Enter between 1 and 4,000 characters." });
44
+ }
45
+ try {
46
+ send(200, await runSavedApp(manifest, input, client));
47
+ } catch (error) {
48
+ send(502, { error: error.message });
49
+ }
50
+ });
51
+
52
+ server.requestTimeout = 10_000;
53
+ await new Promise((resolve, reject) => {
54
+ server.once("error", reject);
55
+ server.listen(port, "127.0.0.1", resolve);
56
+ }).catch(error => {
57
+ if (error.code === "EADDRINUSE") throw new Error("Preview port is busy. Set LYRA_PREVIEW_PORT=0 to pick a free port.");
58
+ throw error;
59
+ });
60
+ return { server, url: "http://127.0.0.1:" + server.address().port + "/" };
61
+ }
@@ -1,65 +1,64 @@
1
- import { readFile } from "node:fs/promises";
2
- import { assertValueSchema } from "./value-schema.js";
3
-
4
- const modes = new Set(["in-process", "local-process", "remote"]);
5
- const identifier = /^[a-z][a-z0-9-]*$/;
6
- const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
- const isIdentifier = (value) => typeof value === "string" && identifier.test(value);
8
-
9
- export function validateAppManifest(manifest) {
10
- if (!isRecord(manifest) || manifest.version !== "1.0") {
11
- throw new Error('Application manifest requires version "1.0".');
12
- }
13
- const { application, capabilities, actions } = manifest;
14
- if (!isRecord(application) || !isIdentifier(application.id) ||
15
- typeof application.name !== "string" || !application.name.trim()) {
16
- throw new Error("Application requires a valid id and a name.");
17
- }
18
- if (!Array.isArray(capabilities) || !Array.isArray(actions)) {
19
- throw new Error("Capabilities and actions must be arrays.");
20
- }
21
-
22
- const capabilityIds = new Set();
23
- for (const capability of capabilities) {
24
- if (!isRecord(capability) || !isIdentifier(capability.id) || !isIdentifier(capability.adapterId) ||
25
- !modes.has(capability.executionMode)) {
26
- throw new Error("Each capability requires an id, adapterId, and supported executionMode.");
27
- }
28
- if (capabilityIds.has(capability.id)) throw new Error(`Duplicate capability: ${capability.id}.`);
29
- for (const key of ["inputSchema", "outputSchema"]) {
30
- if (Object.hasOwn(capability, key)) assertValueSchema(capability[key], `${capability.id} ${key}`);
31
- }
32
- capabilityIds.add(capability.id);
33
- }
34
- const actionIds = new Set();
35
- for (const action of actions) {
36
- if (!isRecord(action) || !isIdentifier(action.id) || !isIdentifier(action.capabilityId)) {
37
- throw new Error("Each action requires an id and capabilityId.");
38
- }
39
- if (actionIds.has(action.id)) throw new Error(`Duplicate action: ${action.id}.`);
40
- if (!capabilityIds.has(action.capabilityId)) {
41
- throw new Error(`Action ${action.id} refers to unknown capability ${action.capabilityId}.`);
42
- }
43
- actionIds.add(action.id);
44
- }
45
- return { id: application.id, capabilityCount: capabilityIds.size, actionCount: actionIds.size };
46
- }
47
-
48
- export async function runAppValidation(args, output = process.stdout) {
49
- if (args.length === 1 && args[0] === "--help") {
50
- output.write("Usage: agent-lyra app validate <manifest.json>\n");
51
- return;
52
- }
53
- if (args.length !== 1 || args[0].startsWith("-")) {
54
- throw new Error("Provide a manifest path. See agent-lyra app validate --help.");
55
- }
56
- const source = await readFile(args[0], "utf8");
57
- let manifest;
58
- try {
59
- manifest = JSON.parse(source.replace(/^\uFEFF/, ""));
60
- } catch {
61
- throw new Error("Application manifest is not valid JSON.");
62
- }
63
- const { id, capabilityCount, actionCount } = validateAppManifest(manifest);
64
- output.write(`Valid app ${id} (${capabilityCount} capabilities, ${actionCount} actions).\n`);
65
- }
1
+ import { readAppManifest, SAVED_VERSION, validateSavedApp } from "./saved-app.js";
2
+ import { assertValueSchema } from "./value-schema.js";
3
+
4
+ const modes = new Set(["in-process", "local-process", "remote"]);
5
+ const identifier = /^[a-z][a-z0-9-]*$/;
6
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
+ const isIdentifier = (value) => typeof value === "string" && identifier.test(value);
8
+
9
+ export function validateAppManifest(manifest) {
10
+ if (!isRecord(manifest) || manifest.version !== "1.0") {
11
+ throw new Error('Application manifest requires version "1.0".');
12
+ }
13
+ const { application, capabilities, actions } = manifest;
14
+ if (!isRecord(application) || !isIdentifier(application.id) ||
15
+ typeof application.name !== "string" || !application.name.trim()) {
16
+ throw new Error("Application requires a valid id and a name.");
17
+ }
18
+ if (!Array.isArray(capabilities) || !Array.isArray(actions)) {
19
+ throw new Error("Capabilities and actions must be arrays.");
20
+ }
21
+
22
+ const capabilityIds = new Set();
23
+ for (const capability of capabilities) {
24
+ if (!isRecord(capability) || !isIdentifier(capability.id) || !isIdentifier(capability.adapterId) ||
25
+ !modes.has(capability.executionMode)) {
26
+ throw new Error("Each capability requires an id, adapterId, and supported executionMode.");
27
+ }
28
+ if (capabilityIds.has(capability.id)) throw new Error(`Duplicate capability: ${capability.id}.`);
29
+ for (const key of ["inputSchema", "outputSchema"]) {
30
+ if (Object.hasOwn(capability, key)) assertValueSchema(capability[key], `${capability.id} ${key}`);
31
+ }
32
+ capabilityIds.add(capability.id);
33
+ }
34
+ const actionIds = new Set();
35
+ for (const action of actions) {
36
+ if (!isRecord(action) || !isIdentifier(action.id) || !isIdentifier(action.capabilityId)) {
37
+ throw new Error("Each action requires an id and capabilityId.");
38
+ }
39
+ if (actionIds.has(action.id)) throw new Error(`Duplicate action: ${action.id}.`);
40
+ if (!capabilityIds.has(action.capabilityId)) {
41
+ throw new Error(`Action ${action.id} refers to unknown capability ${action.capabilityId}.`);
42
+ }
43
+ actionIds.add(action.id);
44
+ }
45
+ return { id: application.id, capabilityCount: capabilityIds.size, actionCount: actionIds.size };
46
+ }
47
+
48
+ export async function runAppValidation(args, output = process.stdout) {
49
+ if (args.length === 1 && args[0] === "--help") {
50
+ output.write("Usage: agent-lyra app validate <manifest.json>\n");
51
+ return;
52
+ }
53
+ if (args.length !== 1 || args[0].startsWith("-")) {
54
+ throw new Error("Provide a manifest path. See agent-lyra app validate --help.");
55
+ }
56
+ const manifest = await readAppManifest(args[0]);
57
+ if (manifest?.version === SAVED_VERSION) {
58
+ validateSavedApp(manifest);
59
+ output.write("Valid app " + manifest.application.id + " (2 saved agents).\n");
60
+ return;
61
+ }
62
+ const { id, capabilityCount, actionCount } = validateAppManifest(manifest);
63
+ output.write(`Valid app ${id} (${capabilityCount} capabilities, ${actionCount} actions).\n`);
64
+ }
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { runAgent } from "./run-agent.js";
5
5
 
6
- async function openStore(cwd) {
6
+ export async function openStore(cwd) {
7
7
  const { DatabaseSync } = await import("node:sqlite").catch(() => {
8
8
  throw new Error("Local agent runs require Node.js 22.13 or newer.");
9
9
  });
@@ -58,7 +58,7 @@ async function openStore(cwd) {
58
58
  };
59
59
  }
60
60
 
61
- function createOpenAIProvider(apiKey, fetchRequest) {
61
+ export function createOpenAIProvider(apiKey, fetchRequest) {
62
62
  return {
63
63
  async complete(request) {
64
64
  const response = await fetchRequest("https://api.openai.com/v1/chat/completions", {
@@ -0,0 +1,43 @@
1
+ .lyra-run-card {
2
+ display: flex;
3
+ flex-direction: column;
4
+ gap: 8px;
5
+ min-width: 0;
6
+ padding: 14px;
7
+ border: 1px solid var(--lyra-color-border, #cbdcd1);
8
+ border-top: 3px solid var(--lyra-color-primary, #174b38);
9
+ border-radius: 12px;
10
+ background: var(--lyra-color-surface, #fff);
11
+ color: var(--lyra-color-text, #173328);
12
+ }
13
+ .lyra-run-card-clickable { min-height: 350px; padding: 20px; cursor: pointer; }
14
+ .lyra-run-card-heading { display: grid; gap: 3px; }
15
+ .lyra-run-card-source { font-size: 11px; color: var(--lyra-color-text-muted, #47675a); }
16
+ .lyra-run-card-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; }
17
+ .lyra-run-card-actions .lyra-run-action {
18
+ display: inline-flex;
19
+ align-items: center;
20
+ justify-content: center;
21
+ gap: 8px;
22
+ min-height: 36px;
23
+ padding: 0 12px;
24
+ border: 0;
25
+ border-radius: 8px;
26
+ background: var(--lyra-color-primary, #174b38);
27
+ color: var(--app-on-accent, #fff);
28
+ font: inherit;
29
+ font-size: 12px;
30
+ font-weight: 600;
31
+ cursor: pointer;
32
+ }
33
+ .lyra-run-card-clickable .lyra-run-action { flex: 1; min-height: 40px; }
34
+ .lyra-run-action:hover:not(:disabled) { filter: brightness(.94); }
35
+ .lyra-run-action:disabled { opacity: .5; cursor: default; }
36
+ .lyra-run-header { display: flex; align-items: center; gap: 10px; }
37
+ .lyra-run-heading { flex: 1; min-width: 0; }
38
+ .lyra-run-heading-line { display: flex; align-items: center; gap: 8px; }
39
+ .lyra-run-header .lyra-run-title { font-size: 14px; font-weight: 650; line-height: 1.3; margin: 0; }
40
+ .lyra-run-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
41
+ .lyra-run-header .lyra-run-card-source { flex-shrink: 0; }
42
+ .lyra-run-close { display: inline-flex; align-items: center; justify-content: center; min-height: 32px; cursor: pointer; }
43
+ .rd-header .lyra-run-close { width: 32px; border: 0; border-radius: 8px; background: transparent; color: var(--lyra-color-text-muted); }
@@ -0,0 +1,32 @@
1
+ export function renderAgentCard(h, { name, source, onRun, onOpen, header, details, extraAction, runIcon }) {
2
+ return h("article", { className: "lyra-run-card" + (onOpen ? " lyra-run-card-clickable" : ""), onClick: onOpen },
3
+ header ?? h("div", { className: "lyra-run-card-heading" },
4
+ h("span", { className: "lyra-run-card-source" }, source),
5
+ h("strong", { className: "lyra-run-title", title: name }, name)),
6
+ details,
7
+ h("div", { className: "lyra-run-card-actions" },
8
+ h("button", {
9
+ type: "button", className: "lyra-run-action", disabled: !onRun,
10
+ onClick: event => { event.stopPropagation(); onRun?.(); },
11
+ }, runIcon, "Run now"),
12
+ extraAction));
13
+ }
14
+
15
+ export function renderRunHeader(h, { title, kind, icon, details, actions, onClose, closeIcon, closeId, className, style }) {
16
+ return h("header", { className: ["lyra-run-header", className].filter(Boolean).join(" "), style },
17
+ icon,
18
+ h("div", { className: "lyra-run-heading" },
19
+ title && h("div", { className: "lyra-run-heading-line" },
20
+ h("h2", { className: "lyra-run-title", id: closeId ? "run-title" : undefined }, title),
21
+ kind && h("span", { className: "lyra-run-card-source" }, kind)),
22
+ details),
23
+ actions,
24
+ onClose && renderRunClose(h, { onClose, closeIcon, closeId }));
25
+ }
26
+
27
+ export function renderRunClose(h, { onClose, closeIcon, closeId }) {
28
+ return h("button", {
29
+ type: "button", className: "lyra-run-close", id: closeId,
30
+ onClick: onClose, title: "Close run drawer", "aria-label": "Close run drawer",
31
+ }, closeIcon ?? "Close");
32
+ }