agent-lyra 0.6.4 → 0.7.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 CHANGED
@@ -120,6 +120,47 @@ npx agent-lyra setup coding export --to claude,codex,copilot --preview
120
120
 
121
121
  These commands are available in npm and Python. Both setup commands accept `--dir <folder>`. After setup, you can run `node .lyra/scripts/detect-stack.mjs` for a read-only JSON report. The GitHub source edition includes the guide files for reading and reuse.
122
122
 
123
+ ## Run a registered agent from Cloud
124
+
125
+ A private IDE agent card runs in Studio by default. To enable **Run now** in Cloud, deploy your own HTTPS endpoint and have the AgentLyra Cloud operator associate it with your account and registration ID. Keep model credentials and agent code in your runtime. The operator configures `LYRA_FRAMEWORK_ENDPOINTS` as a JSON array of objects with `ownerId`, `agentId`, `url`, and a dedicated `token` of at least 32 URL-safe characters.
126
+
127
+ The endpoint handles an authenticated JSON POST. Verify the bearer token before running code. The request carries `schemaVersion: 1`, `agentId`, `traceId`, and `input`. Return JSON with the same `traceId` and an `output` matching the registered text or JSON type. The endpoint has 25 seconds to respond. Use the incoming trace ID in your runtime logs. Cloud retains status, timing and failure category for 30 days. The trace history excludes prompts and replies.
128
+
129
+ ## Register an existing Python agent
130
+
131
+ Keep the agent in its existing repository and install its framework in the Python environment Studio uses. Set `LYRA_PYTHON` to that interpreter if needed.
132
+
133
+ | Framework in the descriptor | Python object to register |
134
+ | --- | --- |
135
+ | `langchain` | A LangChain agent with async `ainvoke` that accepts a messages state |
136
+ | `langgraph` | A compiled LangGraph graph with async `ainvoke` that accepts a messages state |
137
+ | `google-adk` | A Google ADK agent. Studio creates a fresh in-memory session per run |
138
+ | `openai-agents` | An OpenAI Agents SDK agent |
139
+ | `custom` | A sync or async callable with signature `invoke(payload, context)` |
140
+
141
+ The named framework adapters receive text and return the final text. For a custom callable, set `"input": "json"` or `"output": "json"` in the descriptor to use structured values on that side. For example, an async callable can return `{"text": payload["text"].strip()}` with JSON input and output. In Studio, provide a JSON value in the input component or pass valid JSON from the preceding step. The callable receives the Lyra trace ID as `context["trace_id"]`. Framework packages and model credentials stay in your project environment.
142
+
143
+ Create `agent-registration.json` in your project with a relative Python file and the name of an exported object:
144
+
145
+ ```json
146
+ {
147
+ "name": "Research agent",
148
+ "framework": "langgraph",
149
+ "entry": "agents/research.py:graph"
150
+ }
151
+ ```
152
+
153
+ | Command | Purpose |
154
+ | --- | --- |
155
+ | `agent discover` | Read candidates from `langgraph.json` without importing project code |
156
+ | `agent register <descriptor.json>` | Save a stable registration under `.lyra/agents/coding/` |
157
+ | `agent trace <run-id>` | Inspect the local run timeline and trace ID |
158
+ | `agent sync <registration-id>` | Preview the private registration |
159
+ | `agent sync <registration-id> --yes` | Sync the preview to **Cloud → Agents** as a local-only card |
160
+ | `app init --local <registration-id>` | Create a local Studio manifest with input, agent, and output bindings |
161
+
162
+ These commands work in the npm and Python distributions. Launch Studio and reload its catalog after registering. Run only code you trust and use text inputs and outputs for this adapter. Studio returns run and trace IDs, and local run history stores status and duration for framework runs. Sync sends registration metadata. Agent code, local paths, and run contents remain in the project environment. The framework controls any external telemetry it emits.
163
+
123
164
  ## Lyra Studio
124
165
 
125
166
  Studio is a **local browser canvas** that you launch from your IDE terminal. Add a text input, agent card or run button, and an output. Use the Inspector to bind inputs and outputs, then run an agent or workflow from the canvas.
@@ -138,7 +179,7 @@ App Builder turns an **app manifest** into a browser preview or editable applica
138
179
  | --- | --- |
139
180
  | `app init [manifest.json]` | Create a manifest using saved Cloud agents. Connect to Cloud first |
140
181
  | `app validate <manifest.json>` | Check the manifest |
141
- | `app preview <manifest.json>` | Open a local browser preview. Set `LYRA_PREVIEW_PORT` if you need a different port |
182
+ | `app preview <manifest.json>` | Open a local browser preview. Framework agents run from their source project. Set `LYRA_PREVIEW_PORT` if you need a different port |
142
183
  | `app export <manifest.json> <new-directory>` | Export editable source to a new directory |
143
184
 
144
185
  These commands are available in npm and Python. To import an app or preview a public listing, see [Marketplace](#marketplace).
package/bin/agent-lyra.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { runFrameworkCli } from "../src/framework/agent.js";
3
4
  import { runSkillProposals } from "../src/memory/skills-cli.js";
4
5
  import { runMemory } from "../src/memory/cli.js";
5
6
  import { runCli } from "../src/init.js";
@@ -22,12 +23,13 @@ async function main() {
22
23
  if (argv[0] === "setup" && argv[1] === "coding") {
23
24
  return argv[2] === "export" ? runCodingExport(argv.slice(3)) : runCodingSetup(argv.slice(2));
24
25
  }
26
+ if (argv[0] === "agent" && argv[1] !== "run") return runFrameworkCli(argv.slice(1));
25
27
  if (argv[0] === "skills") return runSkillProposals(argv.slice(1));
26
28
  if (argv[0] === "memory") return runMemory(argv.slice(1));
27
29
  if (argv[0] === "connect-cloud") return switchMode(process.cwd(), "gated", argv.slice(1));
28
30
  if (argv[0] === "work-locally") return switchMode(process.cwd(), "standalone", argv.slice(1));
29
31
  if (["gated", "standalone"].includes(argv[0])) return switchMode(process.cwd(), argv[0], argv.slice(1));
30
- if (argv[0] === "app" && ["init", "preview"].includes(argv[1]) && !argv.includes("--help")) {
32
+ if (argv[0] === "app" && ["init", "preview"].includes(argv[1]) && argv[2] !== "--local" && !argv.includes("--help")) {
31
33
  if (argv[1] === "init") requireCloudMode(await readMode(process.cwd()));
32
34
  const key = await readSdkKey(process.cwd());
33
35
  if (key) process.env.LYRA_API_KEY = key;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyra",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
4
4
  "description": "Two-layer Lyra SDK with standalone local primitives and gated hosted agents.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -1,6 +1,7 @@
1
1
  import { access, mkdir, writeFile } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { createInterface } from "node:readline/promises";
4
+ import { readFrameworkAgent } from "../framework/agent.js";
4
5
  import { createSavedAgentClient, SAVED_VERSION, validateSavedApp } from "./saved-app.js";
5
6
 
6
7
  export async function runAppInit(args, output = process.stdout, {
@@ -11,7 +12,26 @@ export async function runAppInit(args, output = process.stdout, {
11
12
  },
12
13
  } = {}) {
13
14
  if (args.length === 1 && args[0] === "--help") {
14
- output.write("Usage: agent-lyra app init [manifest.json]\nSelect two saved agents. Requires LYRA_API_KEY. Default: manifest.json\n");
15
+ output.write("Usage: agent-lyra app init [manifest.json]\nSelect two saved agents. Requires LYRA_API_KEY. Default: manifest.json\nUse app init --local <registration-id> for a project framework agent.\n");
16
+ return;
17
+ }
18
+ if (args[0] === "--local") {
19
+ if (args.length !== 2) throw new Error("Usage: agent-lyra app init --local <registration-id>");
20
+ const agent = await readFrameworkAgent(process.cwd(), args[1]);
21
+ if (!agent) throw new Error("Register the framework agent in this project first.");
22
+ const layout = [
23
+ { id: "prompt", kind: "textarea", label: "Input" },
24
+ { id: "run", kind: "agent-card", label: agent.name, targets: ["framework:" + agent.id], sourceId: "prompt", outputId: "output" },
25
+ { id: "output", kind: "output", label: "Result" },
26
+ ];
27
+ const target = resolve("manifest.json");
28
+ await writeFile(target, JSON.stringify({
29
+ version: "3.0", application: { id: "lyra-app", name: agent.name }, studio: { layout },
30
+ }, null, 2) + "\n", { flag: "wx" }).catch(error => {
31
+ if (error.code === "EEXIST") throw new Error("manifest.json already exists. Bind the agent in Studio to keep your layout.");
32
+ throw error;
33
+ });
34
+ output.write("Created " + target + "\n");
15
35
  return;
16
36
  }
17
37
  if (args.length > 1 || args[0]?.startsWith("-")) {
@@ -1,3 +1,5 @@
1
+ import { basename, dirname, resolve } from "node:path";
2
+ import { startStudio } from "../studio/server.js";
1
3
  import { readAppManifest, SAVED_VERSION } from "./saved-app.js";
2
4
  import { startSavedPreview } from "./saved-preview.js";
3
5
  import { readSupportManifest } from "./support-manifest.js";
@@ -12,6 +14,13 @@ export async function runAppPreview(args, output = process.stdout) {
12
14
  throw new Error("Provide a manifest path. See agent-lyra app preview --help.");
13
15
  }
14
16
  const app = await readAppManifest(args[0]);
17
+ if (app?.version === "3.0" && app.studio) {
18
+ const path = resolve(args[0]);
19
+ if (basename(path) !== "manifest.json") throw new Error("Use the project manifest.json for a Studio app preview.");
20
+ const { url } = await startStudio(dirname(path));
21
+ output.write("App preview: " + url + "\n");
22
+ return;
23
+ }
15
24
  if (app?.version === SAVED_VERSION) {
16
25
  const { url } = await startSavedPreview(app);
17
26
  output.write("App preview: " + url + "\n");
@@ -1,5 +1,6 @@
1
1
  import { lstat, readFile, readdir } from "node:fs/promises";
2
- import { join, resolve } from "node:path";
2
+ import { join, resolve, basename, dirname } from "node:path";
3
+ import { resourceFiles } from "../resource-files.js";
3
4
  import { createInterface } from "node:readline/promises";
4
5
  import { parseArgs } from "node:util";
5
6
  import { readLocalAgent } from "../studio/project.js";
@@ -44,9 +45,9 @@ async function sources(root, output) {
44
45
  const agents = new Map();
45
46
  const skills = new Map();
46
47
  const agentDir = join(root, ".lyra", "agents");
47
- for (const entry of await entries(agentDir)) {
48
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
49
- const source = await text(join(agentDir, entry.name));
48
+ for (const name of await resourceFiles(agentDir, ".md")) {
49
+ const entry = { name };
50
+ const source = await text(join(agentDir, name));
50
51
  const item = readLocalAgent(source);
51
52
  if (!item || item.source !== "local" || !safeName.test(item.id.slice(6))) {
52
53
  output.write("Skip unsupported agent " + JSON.stringify(entry.name) + "\n");
@@ -57,9 +58,11 @@ async function sources(root, output) {
57
58
  agents.set(id, item);
58
59
  }
59
60
  const skillDir = join(root, ".lyra", "skills");
60
- for (const entry of await entries(skillDir)) {
61
- if (!entry.isDirectory() || !safeName.test(entry.name)) continue;
62
- const source = await text(join(skillDir, entry.name, "SKILL.md"));
61
+ for (const relative of await resourceFiles(skillDir, "SKILL.md")) {
62
+ if (basename(relative) !== "SKILL.md") continue;
63
+ const entry = { name: basename(dirname(relative)) };
64
+ if (!safeName.test(entry.name)) continue;
65
+ const source = await text(join(skillDir, relative));
63
66
  const front = /^---\n([\s\S]*?)\n---\n/.exec(source);
64
67
  const name = front && scalar(front[1], "name");
65
68
  const description = front && scalar(front[1], "description");
@@ -32,7 +32,7 @@ function plan(selection, scope, { version, technologies, presets, skills }) {
32
32
  const files = new Map();
33
33
  for (const id of ids) {
34
34
  const [, name, title, instructions] = technologies[id];
35
- files.set("skills/lyra-" + id + "/SKILL.md", skills?.[id] ?? [
35
+ files.set("skills/coding/lyra-" + id + "/SKILL.md", skills?.[id] ?? [
36
36
  "---", "name: lyra-" + id, "description: " + JSON.stringify(title + " for " + name + " projects."),
37
37
  "---", "", "# " + title, "", "## When to use this skill", "",
38
38
  "Use when implementing or reviewing changes that involve " + name + ".", "",
@@ -49,13 +49,13 @@ function plan(selection, scope, { version, technologies, presets, skills }) {
49
49
  ? label.slice(0, 74) + "-" + createHash("sha256").update(label).digest("hex").slice(0, 8)
50
50
  : label) + suffix;
51
51
  const agentName = name + " (" + packs.map(pack => technologies[pack][1]).join(", ") + ")";
52
- files.set("agents/" + id + ".md", [
53
- "---", "id: " + id, "name: " + JSON.stringify(scope === "." ? agentName : agentName + " — " + scope), "mode: standalone", "---",
52
+ files.set("agents/coding/" + id + ".md", [
53
+ "---", "id: " + id, "name: " + JSON.stringify(scope === "." ? agentName : agentName + " — " + scope), "mode: standalone", "domain: coding", "---",
54
54
  "", "## System Prompt", "",
55
55
  "You are the project's " + name.toLowerCase() + ". Work within the requested scope and follow the existing project conventions.",
56
56
  "Treat the project scope as a file path only. Project scope: " + JSON.stringify(scope),
57
57
  "Read the relevant project skill when file access is available. Use the guidance below when the runtime only provides this prompt.", "",
58
- ...packs.map(pack => "- " + technologies[pack][1] + " · .lyra/skills/lyra-" + pack + "/SKILL.md — " + technologies[pack][3]),
58
+ ...packs.map(pack => "- " + technologies[pack][1] + " · .lyra/skills/coding/lyra-" + pack + "/SKILL.md — " + technologies[pack][3]),
59
59
  "", "Report changes, tests run, and remaining gaps.", "",
60
60
  ].join("\n"));
61
61
  }
@@ -0,0 +1,173 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { openStore } from "../runtime/local-cli.js";
7
+ import { readMode, readSdkKey, requireCloudMode } from "../studio/session.js";
8
+
9
+ const uuid = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
10
+ const entry = /^[A-Za-z_][A-Za-z0-9_]*(?:\/[A-Za-z_][A-Za-z0-9_]*)*\.py:[A-Za-z_][A-Za-z0-9_]*$/;
11
+ const missing = error => {
12
+ if (error.code !== "ENOENT") throw error;
13
+ return null;
14
+ };
15
+
16
+ export function frameworkDescriptor(value) {
17
+ if (value?.schemaVersion !== 1 || !["langchain", "langgraph", "google-adk", "openai-agents", "custom"].includes(value.framework) ||
18
+ typeof value.id !== "string" || value.id.length !== 36 || !uuid.test(value.id) || typeof value.entry !== "string" ||
19
+ value.entry.length > 240 || !entry.test(value.entry) || typeof value.name !== "string" ||
20
+ !value.name.trim() || value.name.length > 120 || /[\x00-\x1f\x7f]/.test(value.name)) return null;
21
+ const { input = "text", output = "text" } = value;
22
+ const kinds = value.framework === "custom" ? ["text", "json"] : ["text"];
23
+ if (!kinds.includes(input) || !kinds.includes(output)) return null;
24
+ return { schemaVersion: 1, id: value.id, name: value.name.trim(), framework: value.framework, entry: value.entry, input, output };
25
+
26
+ }
27
+
28
+ async function directory(path, create) {
29
+ if (create) await mkdir(path).catch(error => { if (error.code !== "EEXIST") throw error; });
30
+ if (!(await lstat(path)).isDirectory()) throw new Error("Use regular project folders for agent registrations.");
31
+ return path;
32
+ }
33
+
34
+ async function registrationDirectory(root, folder, create) {
35
+ await directory(root, false);
36
+ return directory(join(await directory(join(root, ".lyra"), create), folder), create);
37
+ }
38
+
39
+ export async function readFrameworkAgent(root, id) {
40
+ if (typeof id !== "string" || id.length !== 36 || !uuid.test(id)) return null;
41
+ const path = join(await directory(join(await registrationDirectory(root, "agents", false), "coding"), false), id + ".json");
42
+ const stat = await lstat(path).catch(missing);
43
+ if (!stat?.isFile() || stat.size > 8_192) return null;
44
+ const value = frameworkDescriptor(JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, "")));
45
+ return value?.id === id ? value : null;
46
+ }
47
+
48
+ async function sourceFile(root, value) {
49
+ if (typeof value?.entry !== "string" || !entry.test(value.entry)) throw new Error("Invalid local framework entry point.");
50
+ const [file] = value.entry.split(":");
51
+ const parts = file.split("/");
52
+ let folder = root;
53
+ await directory(folder, false);
54
+ for (const part of parts.slice(0, -1)) folder = await directory(join(folder, part), false);
55
+ const path = join(folder, parts.at(-1));
56
+ if (!(await lstat(path)).isFile()) throw new Error("The agent entry must be a regular Python file in this project.");
57
+ return path;
58
+ }
59
+
60
+ export async function discoverFrameworkAgents(root) {
61
+ const path = join(root, "langgraph.json");
62
+ const stat = await lstat(path).catch(missing);
63
+ if (!stat?.isFile() || stat.size > 65_536) return [];
64
+ const { graphs } = JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, ""));
65
+ return Object.entries(graphs ?? {}).filter(([name, value]) =>
66
+ name.trim() && name.length <= 120 && !/[\x00-\x1f\x7f]/.test(name) &&
67
+ typeof value === "string" && value.length <= 240 && entry.test(value.replace(/^\.\//, "")))
68
+ .map(([name, value]) => ({ name, framework: "langgraph", entry: value.replace(/^\.\//, "") }));
69
+ }
70
+
71
+ export function publicRegistration(agent) {
72
+ const { id, name, framework, input = "text", output = "text" } = agent;
73
+ return { schemaVersion: 1, id, name, framework, input, output, execution: "local" };
74
+ }
75
+
76
+ export async function syncFrameworkAgent(root, id, confirmation, { request = fetch, key } = {}) {
77
+ requireCloudMode(await readMode(root));
78
+ const agent = await readFrameworkAgent(root, id);
79
+ if (!agent) throw new Error("Register this agent before syncing.");
80
+ const payload = publicRegistration(agent);
81
+ const fingerprint = createHash("sha256").update(JSON.stringify(payload)).digest("hex");
82
+ if (confirmation === undefined) return { payload, fingerprint };
83
+ if (confirmation !== fingerprint) throw new Error("Registration changed. Preview it before syncing.");
84
+ key ??= await readSdkKey(root);
85
+ if (!key) throw new Error("Connect to Cloud with an API key that has resource sync permission.");
86
+ const path = join(await registrationDirectory(root, "framework-links", true), id + ".json");
87
+ const stat = await lstat(path).catch(missing);
88
+ if (stat && !stat.isFile()) throw new Error("Agent sync link must be a regular file.");
89
+ const prior = stat ? JSON.parse(await readFile(path, "utf8")) : null;
90
+ const baseRevision = prior?.revision ?? 0;
91
+ if (!Number.isSafeInteger(baseRevision) || baseRevision < 0) throw new Error("Invalid local sync revision.");
92
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/framework-agents/" + id, {
93
+ method: "PUT", redirect: "error", signal: AbortSignal.timeout(15_000),
94
+ headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
95
+ body: JSON.stringify({ ...payload, baseRevision }),
96
+ });
97
+ if (response.status === 409) throw new Error("Cloud has a newer registration. Review the project link before retrying.");
98
+ if (!response.ok) throw new Error("Could not sync the registration. Check your Cloud resource sync permission.");
99
+ const result = await response.json();
100
+ if (result.id !== id || !Number.isSafeInteger(result.revision) || result.revision < 1) throw new Error("Invalid Cloud registration response.");
101
+ const temp = path + "." + randomUUID() + ".tmp";
102
+ try {
103
+ await writeFile(temp, JSON.stringify({ revision: result.revision }), { flag: "wx" });
104
+ await rename(temp, path);
105
+ } finally { await unlink(temp).catch(missing); }
106
+ return result;
107
+ }
108
+
109
+ export async function runFrameworkAgent(root, agent, input, traceId) {
110
+ const path = await sourceFile(root, agent);
111
+ const python = process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3");
112
+ const runner = fileURLToPath(new URL("./run.py", import.meta.url));
113
+ return new Promise((resolve, reject) => {
114
+ const child = execFile(python, [runner, path, agent.entry.split(":")[1], traceId, agent.framework, agent.output], {
115
+ cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
116
+ }, (error, stdout) => {
117
+ if (error) {
118
+ if (error.code === 20 || error.code === 21) {
119
+ const failure = new Error(error.code === 20 ? "Install the framework in the selected Python environment." : "Framework agent returned an invalid output.");
120
+ failure.code = error.code === 20 ? "FRAMEWORK_DEPENDENCY" : "FRAMEWORK_OUTPUT";
121
+ return reject(failure);
122
+ }
123
+ const failed = new Error(error.killed ? "Framework agent timed out." : "Framework run failed. Check the entry point and Python environment.");
124
+ if (error.killed) failed.code = "FRAMEWORK_TIMEOUT";
125
+ return reject(failed);
126
+ }
127
+ try {
128
+ const { output } = JSON.parse(stdout);
129
+ if (typeof output !== "string") throw new Error();
130
+ resolve(output);
131
+ } catch { reject(new Error("Framework agent returned an invalid text response.")); }
132
+ });
133
+ child.stdin.on("error", () => {});
134
+ child.stdin.end(JSON.stringify({ input }));
135
+ });
136
+ }
137
+
138
+ export async function runFrameworkCli(args, output = process.stdout, root = process.cwd()) {
139
+ const [action, value, confirm] = args;
140
+ if (!action || action === "--help" || value === "--help") {
141
+ output.write("Usage: agent-lyra agent discover | register <descriptor.json> | sync <id> [--yes] | trace <run-id>\n");
142
+ return;
143
+ }
144
+ if (action === "discover" && !value) {
145
+ output.write(JSON.stringify(await discoverFrameworkAgents(root), null, 2) + "\n");
146
+ return;
147
+ }
148
+ if (action === "register" && value && !confirm && args.length === 2) {
149
+ const source = JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""));
150
+ const agent = frameworkDescriptor({ ...source, schemaVersion: 1, id: source.id ?? randomUUID() });
151
+ if (!agent) throw new Error("Provide a name, framework (langchain, langgraph, google-adk, openai-agents, or custom), and entry (relative/file.py:object).");
152
+ await sourceFile(root, agent);
153
+ const path = join(await directory(join(await registrationDirectory(root, "agents", true), "coding"), true), agent.id + ".json");
154
+ await writeFile(path, JSON.stringify(agent, null, 2) + "\n", { flag: "wx" });
155
+ output.write(JSON.stringify({ id: agent.id, name: agent.name, file: ".lyra/agents/coding/" + agent.id + ".json" }) + "\n");
156
+ return;
157
+ }
158
+ if (action === "trace" && typeof value === "string" && value.length === 36 && uuid.test(value) && args.length === 2) {
159
+ const store = await openStore(root);
160
+ try {
161
+ const events = await store.list(value);
162
+ if (!events[0]?.data.framework) throw new Error("No framework run with that ID in this project.");
163
+ output.write(JSON.stringify(events, null, 2) + "\n");
164
+ } finally { store.close(); }
165
+ return;
166
+ }
167
+ if (action === "sync" && value && (!confirm || confirm === "--yes") && args.length <= 3) {
168
+ const preview = await syncFrameworkAgent(root, value);
169
+ output.write(JSON.stringify(confirm ? await syncFrameworkAgent(root, value, preview.fingerprint) : preview.payload, null, 2) + "\n");
170
+ return;
171
+ }
172
+ throw new Error("Use agent-lyra agent --help.");
173
+ }
@@ -0,0 +1,111 @@
1
+ """Run a registered Python agent and emit a bounded JSON response to Studio."""
2
+ import asyncio
3
+ import importlib.util
4
+ import inspect
5
+ import json
6
+ from contextlib import redirect_stdout
7
+ from pathlib import Path
8
+ import runpy
9
+ import sys
10
+
11
+
12
+ async def invoke_langchain(target, prompt, trace_id):
13
+ result = await target.ainvoke(
14
+ {"messages": [{"role": "user", "content": prompt}]},
15
+ config={"metadata": {"lyra_trace_id": trace_id}},
16
+ )
17
+ if isinstance(result, dict) and result.get("messages"):
18
+ result = result["messages"][-1]
19
+ if getattr(result, "type", None) == "human" or (isinstance(result, dict) and result.get("role") == "user"):
20
+ raise InvalidOutput("The agent did not return a reply.")
21
+ if isinstance(result, dict) and isinstance(result.get("content"), str):
22
+ result = result["content"]
23
+ elif hasattr(result, "content"):
24
+ result = result.content
25
+ if not isinstance(result, str):
26
+ raise InvalidOutput("Expected a text response.")
27
+ return result
28
+
29
+
30
+ async def invoke_adk(target, prompt, trace_id):
31
+ from google.adk.runners import InMemoryRunner
32
+ from google.genai import types
33
+
34
+ runner = InMemoryRunner(agent=target, app_name="lyra")
35
+ try:
36
+ session = await runner.session_service.create_session(
37
+ app_name=runner.app_name, user_id="lyra-local", session_id=trace_id
38
+ )
39
+ chunks = []
40
+ length = 0
41
+ async for event in runner.run_async(
42
+ user_id=session.user_id,
43
+ session_id=session.id,
44
+ new_message=types.Content(role="user", parts=[types.Part(text=prompt)]),
45
+ ):
46
+ if event.is_final_response() and event.content:
47
+ for part in event.content.parts or []:
48
+ if part.text and not part.thought:
49
+ length += len(part.text)
50
+ if length > 65536:
51
+ raise InvalidOutput
52
+ chunks.append(part.text)
53
+ return "\n".join(chunks)
54
+ finally:
55
+ await runner.close()
56
+
57
+
58
+ async def invoke_openai(target, prompt, trace_id):
59
+ from agents import RunConfig, Runner
60
+
61
+ config = RunConfig(trace_include_sensitive_data=False, trace_metadata={"lyra_trace_id": trace_id})
62
+ return (await Runner.run(target, prompt, run_config=config)).final_output
63
+
64
+
65
+ async def invoke_custom(target, payload, trace_id):
66
+ result = target(payload, {"trace_id": trace_id})
67
+ return await result if inspect.isawaitable(result) else result
68
+
69
+
70
+ class InvalidOutput(ValueError):
71
+ pass
72
+
73
+
74
+ adapters = {
75
+ "langchain": invoke_langchain,
76
+ "langgraph": invoke_langchain,
77
+ "google-adk": invoke_adk,
78
+ "openai-agents": invoke_openai,
79
+ "custom": invoke_custom,
80
+ }
81
+
82
+
83
+ def main():
84
+ file, symbol, trace_id, framework, output_kind = sys.argv[1:]
85
+ payload = json.load(sys.stdin)
86
+ sys.path.insert(0, str(Path.cwd()))
87
+ with redirect_stdout(sys.stderr):
88
+ root = Path.cwd()
89
+ module = ".".join(Path(file).relative_to(root).with_suffix("").parts)
90
+ spec = importlib.util.find_spec(module)
91
+ if not spec or not spec.origin or Path(spec.origin).resolve() != Path(file).resolve():
92
+ raise ImportError("The Python module does not match the registered file.")
93
+ target = runpy.run_module(module)[symbol]
94
+ reply = asyncio.run(adapters[framework](target, payload["input"], trace_id))
95
+ if output_kind == "json":
96
+ try:
97
+ reply = json.dumps(reply, ensure_ascii=False, allow_nan=False)
98
+ except (TypeError, ValueError, OverflowError) as error:
99
+ raise InvalidOutput("Expected serializable JSON.") from error
100
+ if not isinstance(reply, str) or not reply.strip() or len(reply) > 65536:
101
+ raise InvalidOutput("Expected a bounded, nonempty reply.")
102
+ print(json.dumps({"output": reply}, ensure_ascii=True))
103
+
104
+
105
+ if __name__ == "__main__":
106
+ try:
107
+ main()
108
+ except ModuleNotFoundError:
109
+ sys.exit(20)
110
+ except InvalidOutput:
111
+ sys.exit(21)
package/src/init.js CHANGED
@@ -637,6 +637,7 @@ async function writeDomainManifest(rootDir, mode, domain) {
637
637
  mode,
638
638
  generatedFrom: domain.generatedFrom || (mode === "gated" ? "gated-vertical-catalog" : "onboarding-catalog"),
639
639
  agentCount: (domain.agents || []).length,
640
+ agentIds: (domain.agents || []).map(agent => agent.id),
640
641
  skills: [...skillSet].sort(),
641
642
  integrations: [...integrationSet].sort(),
642
643
  repoIntelligence: {
@@ -655,14 +656,6 @@ async function writeDomainManifest(rootDir, mode, domain) {
655
656
  async function writeDomainFiles(rootDir, mode, selectedDomains) {
656
657
  for (const domain of selectedDomains) {
657
658
  await writeDomainManifest(rootDir, mode, domain);
658
- const domainDir = path.join(rootDir, "domains", domain.id, "agents");
659
- await fs.mkdir(domainDir, { recursive: true });
660
-
661
- for (const agent of domain.agents) {
662
- const filePath = path.join(domainDir, `${agent.slug}.md`);
663
- const body = buildAgentSpec(domain, mode, agent);
664
- await fs.writeFile(filePath, buildAgentMarkdown(body), "utf8");
665
- }
666
659
  }
667
660
  }
668
661
 
@@ -708,10 +701,12 @@ async function writeTopLevelManifest(rootDir, mode, selectedDomains) {
708
701
  }));
709
702
 
710
703
  for (const domain of selectedDomains) {
704
+ const domainDir = path.join(agentsDir, domain.id);
705
+ await fs.mkdir(domainDir, { recursive: true });
711
706
  for (const agent of domain.agents || []) {
712
707
  const spec = buildAgentSpec(domain, mode, agent);
713
708
  const fileName = `${spec.slug}.md`;
714
- await fs.writeFile(path.join(agentsDir, fileName), buildAgentMarkdown(spec), "utf8");
709
+ await fs.writeFile(path.join(domainDir, fileName), buildAgentMarkdown(spec), "utf8");
715
710
  }
716
711
  }
717
712
 
@@ -0,0 +1,5 @@
1
+ export class GraphSnipProvider {
2
+ constructor(options: { root: string; executable?: string; timeout?: number });
3
+ call(name: "gs_pack" | "gs_find" | "gs_symbol" | "gs_impact" | "gs_outline", args?: Record<string, unknown>): Promise<{content: string; source: "graphsnip"; trusted: false}>;
4
+ pack(task: string, budget?: number): Promise<{content: string; source: "graphsnip"; trusted: false}>;
5
+ }
@@ -0,0 +1,57 @@
1
+ import { spawn } from "node:child_process";
2
+ import { realpath, stat } from "node:fs/promises";
3
+
4
+ const READ_TOOLS = new Set(["gs_pack", "gs_find", "gs_symbol", "gs_impact", "gs_outline"]);
5
+
6
+ // Optional local provider. No cloud credentials or runtime registration required.
7
+ export class GraphSnipProvider {
8
+ constructor({ root, executable = "graphsnip", timeout = 30000 } = {}) {
9
+ if (!root || typeof root !== "string") throw new Error("Project root required.");
10
+ if (!Number.isFinite(timeout) || timeout <= 0) throw new Error("Invalid timeout.");
11
+ this.root = root;
12
+ this.executable = executable;
13
+ this.timeout = timeout;
14
+ }
15
+
16
+ async call(name, args = {}) {
17
+ if (!READ_TOOLS.has(name)) throw new Error("Unsupported GraphSnip read operation.");
18
+ const root = await realpath(this.root);
19
+ if (!(await stat(root)).isDirectory()) throw new Error("Project root must be a directory.");
20
+ const request = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
21
+ if (Buffer.byteLength(request) > 65536) throw new Error("GraphSnip request too large.");
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn(this.executable, ["serve"], { cwd: root, shell: false, stdio: ["pipe", "pipe", "ignore"] });
24
+ let output = "";
25
+ let settled = false;
26
+ const finish = (error, value) => {
27
+ if (settled) return;
28
+ settled = true;
29
+ clearTimeout(timer);
30
+ if (error) { child.kill(); reject(error); } else resolve(value);
31
+ };
32
+ const timer = setTimeout(() => finish(new Error("GraphSnip timed out.")), this.timeout);
33
+ child.on("error", () => finish(new Error("GraphSnip executable unavailable.")));
34
+ child.stdin.on("error", () => finish(new Error("GraphSnip request failed.")));
35
+ child.stdout.setEncoding("utf8");
36
+ child.stdout.on("data", chunk => {
37
+ output += chunk;
38
+ if (Buffer.byteLength(output) > 1048576) finish(new Error("GraphSnip response too large."));
39
+ });
40
+ child.on("close", code => {
41
+ if (code !== 0) return finish(new Error("GraphSnip execution failed."));
42
+ try {
43
+ const response = output.trim().split("\n").map(line => JSON.parse(line)).find(item => item.id === 1);
44
+ if (!response || response.error || response.result?.isError || !Array.isArray(response.result?.content)) throw new Error();
45
+ const content = response.result.content.filter(item => item.type === "text" && typeof item.text === "string").map(item => item.text).join("\n");
46
+ finish(null, { content, source: "graphsnip", trusted: false });
47
+ } catch { finish(new Error("GraphSnip returned an invalid or unsuccessful response.")); }
48
+ });
49
+ child.stdin.end(request + "\n");
50
+ });
51
+ }
52
+
53
+ pack(task, budget = 4000) {
54
+ if (typeof task !== "string" || !task.trim() || !Number.isInteger(budget) || budget < 1 || budget > 32000) throw new Error("Invalid task or budget.");
55
+ return this.call("gs_pack", { task, budget });
56
+ }
57
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lyra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ # Standalone Memory Engine (staging)
2
+
3
+ Local SQLite memory, verification and skill proposals. Node 22.13+. No cloud service required. This private staging package is not published. The package files allowlist excludes Lyra sync and runtime modules.
4
+
5
+ Run `node bridge-cli.js` from a project directory with a version 1 JSON request on stdin. The response is JSON on stdout. Data lives under `.memory-engine/memory/`.
@@ -0,0 +1,14 @@
1
+ {
2
+ "repository": "https://github.com/naubadnithinkumar/memory-engine",
3
+ "commit": "befb5607a7109d8bcc8160a1947878de09a3d807",
4
+ "files": [
5
+ "local-store.js",
6
+ "contract.json",
7
+ "validation.js",
8
+ "proposals.js",
9
+ "bridge.js",
10
+ "bridge-cli.js",
11
+ "standalone.js",
12
+ "standalone.d.ts"
13
+ ]
14
+ }