agent-lyra 0.6.5 → 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 +42 -1
- package/bin/agent-lyra.js +3 -1
- package/package.json +1 -1
- package/src/app-builder/init.js +21 -1
- package/src/app-builder/preview.js +9 -0
- package/src/framework/agent.js +173 -0
- package/src/framework/run.py +111 -0
- package/src/intelligence/graphsnip-provider.d.ts +5 -0
- package/src/intelligence/graphsnip-provider.js +57 -0
- package/src/memory/LICENSE +21 -0
- package/src/memory/README.md +5 -0
- package/src/memory/UPSTREAM.json +14 -0
- package/src/memory/bridge-cli.js +16 -0
- package/src/memory/bridge.js +18 -0
- package/src/memory/cloud-sync-actions.js +61 -0
- package/src/memory/contract.json +19 -2
- package/src/memory/index.js +3 -255
- package/src/memory/local-store.js +209 -0
- package/src/memory/package.json +33 -0
- package/src/memory/proposals.js +6 -0
- package/src/memory/standalone.d.ts +50 -0
- package/src/memory/standalone.js +1 -0
- package/src/runtime/run-agent.js +16 -6
- package/src/studio/browser.js +19 -5
- package/src/studio/export.js +5 -1
- package/src/studio/project.js +27 -2
- package/src/studio/server.js +8 -1
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
package/src/app-builder/init.js
CHANGED
|
@@ -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");
|
|
@@ -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)
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { dispatchMemoryRequest } from "./bridge.js";
|
|
3
|
+
const chunks = [];
|
|
4
|
+
let size = 0;
|
|
5
|
+
try {
|
|
6
|
+
for await (const chunk of process.stdin) {
|
|
7
|
+
size += chunk.length;
|
|
8
|
+
if (size > 65536) throw new Error("Request too large.");
|
|
9
|
+
chunks.push(chunk);
|
|
10
|
+
}
|
|
11
|
+
const result = await dispatchMemoryRequest(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
12
|
+
process.stdout.write(JSON.stringify({ version: 1, ok: true, result }) + "\n");
|
|
13
|
+
} catch (error) {
|
|
14
|
+
process.stdout.write(JSON.stringify({ version: 1, ok: false, error: error.message }) + "\n");
|
|
15
|
+
process.exitCode = 1;
|
|
16
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { openLocalMemoryStore } from "./local-store.js";
|
|
2
|
+
|
|
3
|
+
// One request per invocation; stdout is reserved for the versioned response.
|
|
4
|
+
const operations = new Map([
|
|
5
|
+
["record", ["value"]], ["get", ["id"]], ["list", ["limit"]],
|
|
6
|
+
["search", ["query", "limit"]], ["retrieve", ["query", "context", "adapter"]],
|
|
7
|
+
["verify", ["id", "evidence"]], ["archive", ["id"]], ["stats", []],
|
|
8
|
+
["consolidate", ["context"]], ["propose", ["context", "memoryId"]],
|
|
9
|
+
["approvedSkills", ["context"]], ["proposal", ["id"]], ["proposals", []], ["decideProposal", ["id", "decision", "evidence"]]
|
|
10
|
+
]);
|
|
11
|
+
export async function dispatchMemoryRequest(request, root = process.cwd()) {
|
|
12
|
+
if (request?.version !== 1 || !operations.has(request.operation)) throw new Error("Unsupported memory protocol or operation.");
|
|
13
|
+
const params = request.params ?? {};
|
|
14
|
+
if (typeof params !== "object" || Array.isArray(params)) throw new Error("Invalid parameters.");
|
|
15
|
+
const store = await openLocalMemoryStore(root);
|
|
16
|
+
try { return store[request.operation](...operations.get(request.operation).map(key => params[key])); }
|
|
17
|
+
finally { store.close(); }
|
|
18
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Lyra-specific synchronization adapter. Local memory operations remain in index.js.
|
|
2
|
+
export function cloudSyncActions({ db, transaction, get, erase, dirty, record, eligibleText, limits, time }) {
|
|
3
|
+
transaction(() => db.exec("CREATE TABLE IF NOT EXISTS memory_cloud_links (id TEXT PRIMARY KEY, cloud_revision INTEGER NOT NULL, local_revision INTEGER NOT NULL, cloud_account TEXT NOT NULL);"));
|
|
4
|
+
const syncBase = id => {
|
|
5
|
+
const item = get(id);
|
|
6
|
+
const tombstone = db.prepare("SELECT revision FROM memory_tombstones WHERE id=?").get(id);
|
|
7
|
+
const link = db.prepare("SELECT * FROM memory_cloud_links WHERE id=?").get(id) ?? null;
|
|
8
|
+
return { item, deleted: Boolean(tombstone), revision: item?.revision ?? tombstone?.revision ?? 0, link };
|
|
9
|
+
};
|
|
10
|
+
const saveLink = (remote, revision) => {
|
|
11
|
+
db.prepare("INSERT INTO memory_cloud_links VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET " +
|
|
12
|
+
"cloud_revision=excluded.cloud_revision,local_revision=excluded.local_revision " +
|
|
13
|
+
"WHERE cloud_account=excluded.cloud_account AND cloud_revision<=excluded.cloud_revision")
|
|
14
|
+
.run(remote.id, remote.revision, revision, remote.account);
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
syncBase,
|
|
18
|
+
rememberCloudRevision: (remote, revision) => transaction(() => saveLink(remote, revision)),
|
|
19
|
+
applyCloudMemory(remote, expected, choice) {
|
|
20
|
+
return transaction(() => {
|
|
21
|
+
const local = syncBase(remote.id);
|
|
22
|
+
if (local.revision !== expected.revision ||
|
|
23
|
+
local.link?.cloud_revision !== expected.link?.cloud_revision ||
|
|
24
|
+
local.link?.cloud_account !== expected.link?.cloud_account) {
|
|
25
|
+
throw new Error("The local record changed during sync. Pull again.");
|
|
26
|
+
}
|
|
27
|
+
if (local.link?.cloud_revision === remote.revision) return { id: remote.id, updated: false };
|
|
28
|
+
const different = local.link ? local.revision !== local.link.local_revision : local.revision !== 0;
|
|
29
|
+
if (different && !(local.deleted && remote.deleted)) {
|
|
30
|
+
if (!choice || local.deleted || remote.deleted || !local.item) throw new Error("Both copies changed. Review before syncing.");
|
|
31
|
+
if (choice === "local") {
|
|
32
|
+
saveLink(remote, 0);
|
|
33
|
+
return { id: remote.id, keptLocal: true };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (remote.deleted) {
|
|
37
|
+
if (!local.deleted) erase(remote.id, local.revision + 1);
|
|
38
|
+
saveLink(remote, syncBase(remote.id).revision);
|
|
39
|
+
return { id: remote.id, deleted: true };
|
|
40
|
+
}
|
|
41
|
+
if (local.deleted) throw new Error("This memory was forgotten locally. It cannot be restored by a pull.");
|
|
42
|
+
const incoming = record(remote.memory);
|
|
43
|
+
if (!eligibleText([incoming.title, incoming.learning, ...incoming.evidence].join(" "))) {
|
|
44
|
+
throw new Error("The remote memory contains unsafe content.");
|
|
45
|
+
}
|
|
46
|
+
if (!local.item && db.prepare("SELECT count(*) AS count FROM memories").get().count >= limits.records) {
|
|
47
|
+
throw new Error("Memory is full. Forget a record before importing one.");
|
|
48
|
+
}
|
|
49
|
+
const now = time();
|
|
50
|
+
const revision = local.revision + 1;
|
|
51
|
+
db.prepare("INSERT INTO memories (id,type,title,learning,evidence,revision,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) " +
|
|
52
|
+
"ON CONFLICT(id) DO UPDATE SET type=excluded.type,title=excluded.title,learning=excluded.learning,evidence=excluded.evidence," +
|
|
53
|
+
"revision=excluded.revision,updated_at=excluded.updated_at,status='candidate',verification=NULL")
|
|
54
|
+
.run(remote.id, incoming.type, incoming.title, incoming.learning, JSON.stringify(incoming.evidence), revision, now, now);
|
|
55
|
+
dirty();
|
|
56
|
+
saveLink(remote, revision);
|
|
57
|
+
return { id: remote.id, updated: true, status: "candidate" };
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|