agent-lyra 0.7.0 → 0.10.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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +301 -276
  3. package/bin/agent-lyra.js +51 -51
  4. package/bin/lyra-oss-preview.js +16 -16
  5. package/package.json +60 -60
  6. package/src/app-builder/export.js +109 -109
  7. package/src/app-builder/gateway.js +62 -62
  8. package/src/app-builder/init.js +115 -72
  9. package/src/app-builder/manifest-contract.js +46 -46
  10. package/src/app-builder/native-adapter.js +29 -29
  11. package/src/app-builder/preview.js +35 -31
  12. package/src/app-builder/publish.js +14 -14
  13. package/src/app-builder/saved-app.js +70 -70
  14. package/src/app-builder/saved-preview-browser.js +33 -33
  15. package/src/app-builder/saved-preview.html +24 -24
  16. package/src/app-builder/saved-preview.js +61 -61
  17. package/src/app-builder/support-manifest.js +50 -50
  18. package/src/app-builder/support-template/manifest.json +55 -55
  19. package/src/app-builder/support-template/support-preview.html +56 -56
  20. package/src/app-builder/support-template/support-preview.js +37 -37
  21. package/src/app-builder/support-template/support-preview.mjs +67 -67
  22. package/src/app-builder/support-template/support-workflow.mjs +36 -36
  23. package/src/app-builder/use.js +37 -37
  24. package/src/app-builder/validate.js +31 -21
  25. package/src/app-builder/value-schema.js +37 -37
  26. package/src/catalog.js +147 -147
  27. package/src/coding/catalog.js +56 -56
  28. package/src/coding/cloud-catalog.js +64 -64
  29. package/src/coding/detect-stack.mjs +110 -110
  30. package/src/coding/export.js +133 -133
  31. package/src/coding/setup.js +175 -175
  32. package/src/coding/skills/lyra-android/SKILL.md +37 -37
  33. package/src/coding/skills/lyra-angular/SKILL.md +37 -37
  34. package/src/coding/skills/lyra-cucumber/SKILL.md +37 -37
  35. package/src/coding/skills/lyra-dbt/SKILL.md +37 -37
  36. package/src/coding/skills/lyra-django/SKILL.md +37 -37
  37. package/src/coding/skills/lyra-docker/SKILL.md +37 -37
  38. package/src/coding/skills/lyra-dotnet/SKILL.md +37 -37
  39. package/src/coding/skills/lyra-express/SKILL.md +37 -37
  40. package/src/coding/skills/lyra-fastapi/SKILL.md +37 -37
  41. package/src/coding/skills/lyra-flutter/SKILL.md +37 -37
  42. package/src/coding/skills/lyra-github-actions/SKILL.md +37 -37
  43. package/src/coding/skills/lyra-gitlab-ci/SKILL.md +37 -37
  44. package/src/coding/skills/lyra-go/SKILL.md +37 -37
  45. package/src/coding/skills/lyra-ios/SKILL.md +37 -37
  46. package/src/coding/skills/lyra-kubernetes/SKILL.md +37 -37
  47. package/src/coding/skills/lyra-mongodb/SKILL.md +37 -37
  48. package/src/coding/skills/lyra-mysql/SKILL.md +37 -37
  49. package/src/coding/skills/lyra-nextjs/SKILL.md +37 -37
  50. package/src/coding/skills/lyra-node/SKILL.md +37 -37
  51. package/src/coding/skills/lyra-playwright/SKILL.md +37 -37
  52. package/src/coding/skills/lyra-postgresql/SKILL.md +37 -37
  53. package/src/coding/skills/lyra-python/SKILL.md +37 -37
  54. package/src/coding/skills/lyra-react/SKILL.md +37 -37
  55. package/src/coding/skills/lyra-react-native/SKILL.md +37 -37
  56. package/src/coding/skills/lyra-redis/SKILL.md +37 -37
  57. package/src/coding/skills/lyra-rust/SKILL.md +37 -37
  58. package/src/coding/skills/lyra-spark/SKILL.md +37 -37
  59. package/src/coding/skills/lyra-spring-boot/SKILL.md +37 -37
  60. package/src/coding/skills/lyra-svelte/SKILL.md +37 -37
  61. package/src/coding/skills/lyra-terraform/SKILL.md +37 -37
  62. package/src/coding/skills/lyra-typescript/SKILL.md +37 -37
  63. package/src/coding/skills/lyra-vue/SKILL.md +37 -37
  64. package/src/framework/agent.js +181 -173
  65. package/src/framework/mda.js +65 -0
  66. package/src/framework/run.py +111 -111
  67. package/src/gated/hostedAgents.js +56 -56
  68. package/src/gated/index.d.ts +25 -25
  69. package/src/gated/index.js +5 -5
  70. package/src/index.d.ts +2 -2
  71. package/src/index.js +2 -2
  72. package/src/init.js +960 -960
  73. package/src/intelligence/graphsnip-provider.d.ts +5 -5
  74. package/src/intelligence/graphsnip-provider.js +57 -57
  75. package/src/intelligence/lifecycle.js +25 -0
  76. package/src/memory/LICENSE +21 -21
  77. package/src/memory/README.md +5 -5
  78. package/src/memory/UPSTREAM.json +24 -14
  79. package/src/memory/bridge-cli.js +16 -16
  80. package/src/memory/bridge.js +18 -18
  81. package/src/memory/cli.js +21 -21
  82. package/src/memory/cloud-sync-actions.js +61 -61
  83. package/src/memory/contract.json +45 -45
  84. package/src/memory/index.d.ts +50 -49
  85. package/src/memory/index.js +7 -7
  86. package/src/memory/lifecycle.js +29 -29
  87. package/src/memory/local-cli.js +34 -34
  88. package/src/memory/local-store.js +209 -209
  89. package/src/memory/package.json +33 -33
  90. package/src/memory/proposals.js +90 -90
  91. package/src/memory/skills-cli.js +26 -26
  92. package/src/memory/standalone.d.ts +50 -50
  93. package/src/memory/standalone.js +1 -1
  94. package/src/memory/sync.js +89 -89
  95. package/src/memory/validation.js +25 -25
  96. package/src/onboardingAgents.js +532 -532
  97. package/src/promptTemplates.js +178 -178
  98. package/src/resource-files.js +18 -18
  99. package/src/runtime/contracts.d.ts +47 -47
  100. package/src/runtime/local-cli.js +161 -160
  101. package/src/runtime/mcp-stdio.js +111 -111
  102. package/src/runtime/orchestration.js +59 -59
  103. package/src/runtime/run-agent.js +54 -53
  104. package/src/standalone/index.d.ts +45 -45
  105. package/src/standalone/index.js +13 -13
  106. package/src/standalone/init.js +12 -12
  107. package/src/standalone/orchestration.js +6 -6
  108. package/src/standalone/rag.js +113 -113
  109. package/src/studio/agent-ui.css +43 -43
  110. package/src/studio/agent-ui.js +32 -32
  111. package/src/studio/browser.js +542 -345
  112. package/src/studio/export.js +83 -85
  113. package/src/studio/index.html +74 -37
  114. package/src/studio/memory-actions.js +37 -37
  115. package/src/studio/memory-panel.js +200 -200
  116. package/src/studio/project.js +308 -240
  117. package/src/studio/pull-agent.js +72 -72
  118. package/src/studio/push.js +54 -54
  119. package/src/studio/python-agent.js +47 -47
  120. package/src/studio/python-agent.py +25 -25
  121. package/src/studio/server.js +164 -150
  122. package/src/studio/session.js +83 -83
  123. package/src/studio/studio.css +257 -10
  124. package/src/studio/sync.js +42 -42
  125. package/src/studio/workflow-editor.js +240 -0
  126. package/src/studio/workflow-sync.js +229 -157
@@ -1,160 +1,161 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { parseArgs } from "node:util";
4
- import { withProjectMemory } from "../memory/lifecycle.js";
5
- import { runAgent } from "./run-agent.js";
6
-
7
- export async function openStore(cwd) {
8
- const { DatabaseSync } = await import("node:sqlite").catch(() => {
9
- throw new Error("Local agent runs require Node.js 22.13 or newer.");
10
- });
11
- const directory = join(cwd, ".lyra", "state");
12
- await mkdir(directory, { recursive: true, mode: 0o700 });
13
- await writeFile(join(directory, ".gitignore"), "*\n", { flag: "wx" }).catch((error) => {
14
- if (error.code !== "EEXIST") throw error;
15
- });
16
- const db = new DatabaseSync(join(directory, "runs.sqlite"));
17
- db.exec(`
18
- PRAGMA busy_timeout = 5000;
19
- CREATE TABLE IF NOT EXISTS events (
20
- run_id TEXT NOT NULL,
21
- seq INTEGER NOT NULL,
22
- body TEXT NOT NULL,
23
- PRIMARY KEY (run_id, seq)
24
- );
25
- `);
26
- return {
27
- async append(event) {
28
- const body = JSON.stringify(event);
29
- db.exec("BEGIN IMMEDIATE");
30
- try {
31
- const existing = db.prepare("SELECT body FROM events WHERE run_id = ? AND seq = ?")
32
- .get(event.run_id, event.seq);
33
- if (existing) {
34
- if (existing.body !== body) throw new Error("Conflicting run event.");
35
- } else {
36
- const previous = db.prepare("SELECT seq, body FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1")
37
- .get(event.run_id);
38
- const valid = previous
39
- ? event.seq === previous.seq + 1 && JSON.parse(previous.body).type === "run.started"
40
- && event.type !== "run.started"
41
- : event.seq === 0 && event.type === "run.started";
42
- if (!valid) throw new Error("Invalid run event sequence.");
43
- db.prepare("INSERT INTO events (run_id, seq, body) VALUES (?, ?, ?)")
44
- .run(event.run_id, event.seq, body);
45
- }
46
- db.exec("COMMIT");
47
- } catch (error) {
48
- db.exec("ROLLBACK");
49
- throw error;
50
- }
51
- },
52
- async list(runId) {
53
- return db.prepare("SELECT body FROM events WHERE run_id = ? ORDER BY seq").all(runId)
54
- .map(({ body }) => JSON.parse(body));
55
- },
56
- close() {
57
- db.close();
58
- },
59
- };
60
- }
61
-
62
- export function createOpenAIProvider(apiKey, fetchRequest) {
63
- return {
64
- async complete(request) {
65
- const response = await fetchRequest("https://api.openai.com/v1/chat/completions", {
66
- method: "POST",
67
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
68
- redirect: "error",
69
- signal: AbortSignal.timeout(60_000),
70
- body: JSON.stringify({ ...request, max_completion_tokens: 1024 }),
71
- });
72
- if (!response.ok) throw new Error(`OpenAI request failed (HTTP ${response.status}).`);
73
- const result = await response.json();
74
- const text = result.choices?.[0]?.message?.content;
75
- if (typeof text !== "string" || !text.trim()) throw new Error("OpenAI returned no text.");
76
- return {
77
- text,
78
- usage: { inputTokens: result.usage?.prompt_tokens, outputTokens: result.usage?.completion_tokens },
79
- };
80
- },
81
- };
82
- }
83
-
84
- export async function runLocalCli(argv, {
85
- cwd = process.cwd(),
86
- env = process.env,
87
- output = process.stdout,
88
- diagnostics = process.stderr,
89
- fetchRequest = globalThis.fetch,
90
- } = {}) {
91
- const [group, command, ...args] = argv;
92
- const statusCommand = group === "run" && command === "status";
93
- const agentCommand = group === "agent" && command === "run";
94
- const teamCommand = group === "team" && command === "run";
95
- if (!statusCommand && !agentCommand && !teamCommand) return false;
96
-
97
- if (args.includes("--help")) {
98
- const usage = statusCommand
99
- ? "agent-lyra run status <run-id>"
100
- : teamCommand
101
- ? "agent-lyra team run draft-review --model <model> --prompt <text>"
102
- : "agent-lyra agent run --model <model> --prompt <text>";
103
- output.write(`Usage: ${usage}\n`);
104
- return true;
105
- }
106
-
107
- if (statusCommand) {
108
- if (args.length !== 1 || !/^[0-9a-f-]{36}$/i.test(args[0])) throw new Error("Provide a valid run ID.");
109
- const store = await openStore(cwd);
110
- try {
111
- const events = await store.list(args[0]);
112
- if (!events.length) throw new Error(`Run not found: ${args[0]}`);
113
- output.write(`${JSON.stringify(events.at(-1))}\n`);
114
- } finally {
115
- store.close();
116
- }
117
- return true;
118
- }
119
-
120
- if (teamCommand && args.shift() !== "draft-review") {
121
- throw new Error("Choose the draft-review team. See agent-lyra team run --help.");
122
- }
123
- const { values } = parseArgs({
124
- args,
125
- options: { model: { type: "string" }, prompt: { type: "string" } },
126
- });
127
- if (!values.model?.trim() || !values.prompt?.trim()) throw new Error("--model and --prompt are required.");
128
- if (!env.OPENAI_API_KEY?.trim()) throw new Error("Set OPENAI_API_KEY in your terminal environment.");
129
- const provider = createOpenAIProvider(env.OPENAI_API_KEY.trim(), fetchRequest);
130
- const stages = teamCommand
131
- ? [
132
- { agentId: "draft-writer", system: "Write a first draft that addresses the user's request." },
133
- { agentId: "draft-reviewer", system: "Review the draft against the user's request and return the improved final text." },
134
- ]
135
- : [{ agentId: "local-assistant", system: "You are a helpful local assistant." }];
136
-
137
- const store = await openStore(cwd);
138
- try {
139
- const messages = [{ role: "user", content: values.prompt }];
140
- let text;
141
- for (const { agentId, system } of stages) {
142
- const event = await runAgent({
143
- agentId,
144
- request: await withProjectMemory(cwd, { model: values.model, messages: [{ role: "system", content: system }, ...messages] }, { env }),
145
- provider,
146
- store,
147
- onStarted: (runId) => diagnostics.write(teamCommand ? `${agentId} run ID: ${runId}\n` : `Run ID: ${runId}\n`),
148
- });
149
- if (event.type === "run.failed") {
150
- throw new Error("Model request failed. Check your OpenAI key, model access, and network.");
151
- }
152
- text = event.data.result.text;
153
- messages.push({ role: "assistant", content: text });
154
- }
155
- output.write(`${text}\n`);
156
- } finally {
157
- store.close();
158
- }
159
- return true;
160
- }
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { withProjectMemory } from "../memory/lifecycle.js";
5
+ import { withGraphSnipContext } from "../intelligence/lifecycle.js";
6
+ import { runAgent } from "./run-agent.js";
7
+
8
+ export async function openStore(cwd) {
9
+ const { DatabaseSync } = await import("node:sqlite").catch(() => {
10
+ throw new Error("Local agent runs require Node.js 22.13 or newer.");
11
+ });
12
+ const directory = join(cwd, ".lyra", "state");
13
+ await mkdir(directory, { recursive: true, mode: 0o700 });
14
+ await writeFile(join(directory, ".gitignore"), "*\n", { flag: "wx" }).catch((error) => {
15
+ if (error.code !== "EEXIST") throw error;
16
+ });
17
+ const db = new DatabaseSync(join(directory, "runs.sqlite"));
18
+ db.exec(`
19
+ PRAGMA busy_timeout = 5000;
20
+ CREATE TABLE IF NOT EXISTS events (
21
+ run_id TEXT NOT NULL,
22
+ seq INTEGER NOT NULL,
23
+ body TEXT NOT NULL,
24
+ PRIMARY KEY (run_id, seq)
25
+ );
26
+ `);
27
+ return {
28
+ async append(event) {
29
+ const body = JSON.stringify(event);
30
+ db.exec("BEGIN IMMEDIATE");
31
+ try {
32
+ const existing = db.prepare("SELECT body FROM events WHERE run_id = ? AND seq = ?")
33
+ .get(event.run_id, event.seq);
34
+ if (existing) {
35
+ if (existing.body !== body) throw new Error("Conflicting run event.");
36
+ } else {
37
+ const previous = db.prepare("SELECT seq, body FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1")
38
+ .get(event.run_id);
39
+ const valid = previous
40
+ ? event.seq === previous.seq + 1 && JSON.parse(previous.body).type === "run.started"
41
+ && event.type !== "run.started"
42
+ : event.seq === 0 && event.type === "run.started";
43
+ if (!valid) throw new Error("Invalid run event sequence.");
44
+ db.prepare("INSERT INTO events (run_id, seq, body) VALUES (?, ?, ?)")
45
+ .run(event.run_id, event.seq, body);
46
+ }
47
+ db.exec("COMMIT");
48
+ } catch (error) {
49
+ db.exec("ROLLBACK");
50
+ throw error;
51
+ }
52
+ },
53
+ async list(runId) {
54
+ return db.prepare("SELECT body FROM events WHERE run_id = ? ORDER BY seq").all(runId)
55
+ .map(({ body }) => JSON.parse(body));
56
+ },
57
+ close() {
58
+ db.close();
59
+ },
60
+ };
61
+ }
62
+
63
+ export function createOpenAIProvider(apiKey, fetchRequest) {
64
+ return {
65
+ async complete(request) {
66
+ const response = await fetchRequest("https://api.openai.com/v1/chat/completions", {
67
+ method: "POST",
68
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
69
+ redirect: "error",
70
+ signal: AbortSignal.timeout(60_000),
71
+ body: JSON.stringify({ ...request, max_completion_tokens: 1024 }),
72
+ });
73
+ if (!response.ok) throw new Error(`OpenAI request failed (HTTP ${response.status}).`);
74
+ const result = await response.json();
75
+ const text = result.choices?.[0]?.message?.content;
76
+ if (typeof text !== "string" || !text.trim()) throw new Error("OpenAI returned no text.");
77
+ return {
78
+ text,
79
+ usage: { inputTokens: result.usage?.prompt_tokens, outputTokens: result.usage?.completion_tokens },
80
+ };
81
+ },
82
+ };
83
+ }
84
+
85
+ export async function runLocalCli(argv, {
86
+ cwd = process.cwd(),
87
+ env = process.env,
88
+ output = process.stdout,
89
+ diagnostics = process.stderr,
90
+ fetchRequest = globalThis.fetch,
91
+ } = {}) {
92
+ const [group, command, ...args] = argv;
93
+ const statusCommand = group === "run" && command === "status";
94
+ const agentCommand = group === "agent" && command === "run";
95
+ const teamCommand = group === "team" && command === "run";
96
+ if (!statusCommand && !agentCommand && !teamCommand) return false;
97
+
98
+ if (args.includes("--help")) {
99
+ const usage = statusCommand
100
+ ? "agent-lyra run status <run-id>"
101
+ : teamCommand
102
+ ? "agent-lyra team run draft-review --model <model> --prompt <text>"
103
+ : "agent-lyra agent run --model <model> --prompt <text>";
104
+ output.write(`Usage: ${usage}\n`);
105
+ return true;
106
+ }
107
+
108
+ if (statusCommand) {
109
+ if (args.length !== 1 || !/^[0-9a-f-]{36}$/i.test(args[0])) throw new Error("Provide a valid run ID.");
110
+ const store = await openStore(cwd);
111
+ try {
112
+ const events = await store.list(args[0]);
113
+ if (!events.length) throw new Error(`Run not found: ${args[0]}`);
114
+ output.write(`${JSON.stringify(events.at(-1))}\n`);
115
+ } finally {
116
+ store.close();
117
+ }
118
+ return true;
119
+ }
120
+
121
+ if (teamCommand && args.shift() !== "draft-review") {
122
+ throw new Error("Choose the draft-review team. See agent-lyra team run --help.");
123
+ }
124
+ const { values } = parseArgs({
125
+ args,
126
+ options: { model: { type: "string" }, prompt: { type: "string" } },
127
+ });
128
+ if (!values.model?.trim() || !values.prompt?.trim()) throw new Error("--model and --prompt are required.");
129
+ if (!env.OPENAI_API_KEY?.trim()) throw new Error("Set OPENAI_API_KEY in your terminal environment.");
130
+ const provider = createOpenAIProvider(env.OPENAI_API_KEY.trim(), fetchRequest);
131
+ const stages = teamCommand
132
+ ? [
133
+ { agentId: "draft-writer", system: "Write a first draft that addresses the user's request." },
134
+ { agentId: "draft-reviewer", system: "Review the draft against the user's request and return the improved final text." },
135
+ ]
136
+ : [{ agentId: "local-assistant", system: "You are a helpful local assistant." }];
137
+
138
+ const store = await openStore(cwd);
139
+ try {
140
+ const messages = [{ role: "user", content: values.prompt }];
141
+ let text;
142
+ for (const { agentId, system } of stages) {
143
+ const event = await runAgent({
144
+ agentId,
145
+ request: await withProjectMemory(cwd, await withGraphSnipContext(cwd, { model: values.model, messages: [{ role: "system", content: system }, ...messages] }, { env }), { env }),
146
+ provider,
147
+ store,
148
+ onStarted: (runId) => diagnostics.write(teamCommand ? `${agentId} run ID: ${runId}\n` : `Run ID: ${runId}\n`),
149
+ });
150
+ if (event.type === "run.failed") {
151
+ throw new Error("Model request failed. Check your OpenAI key, model access, and network.");
152
+ }
153
+ text = event.data.result.text;
154
+ messages.push({ role: "assistant", content: text });
155
+ }
156
+ output.write(`${text}\n`);
157
+ } finally {
158
+ store.close();
159
+ }
160
+ return true;
161
+ }
@@ -1,111 +1,111 @@
1
- import { existsSync } from "node:fs";
2
- import { createRequire } from "node:module";
3
- import { isAbsolute, join } from "node:path";
4
- import { createInterface } from "node:readline";
5
-
6
- const { version } = createRequire(import.meta.url)("../../package.json");
7
- const protocolVersions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
8
- const uuidPattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
9
- const runIdPattern = new RegExp(uuidPattern);
10
- const tool = {
11
- name: "get_saved_run",
12
- description: "Read the latest event for a Lyra run in this project. Successful events can contain generated text.",
13
- inputSchema: {
14
- type: "object",
15
- properties: { runId: { type: "string", pattern: uuidPattern } },
16
- required: ["runId"],
17
- additionalProperties: false,
18
- },
19
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
20
- };
21
-
22
- function toolResult(text, isError = false) {
23
- return { content: [{ type: "text", text }], ...(isError && { isError: true }) };
24
- }
25
-
26
- export async function serveSavedRuns(argv, { input = process.stdin, output = process.stdout } = {}) {
27
- if (argv.length === 1 && argv[0] === "--help") {
28
- output.write("Usage: agent-lyra mcp serve --dir <absolute-project-directory>\n");
29
- return;
30
- }
31
- const [flag, directory] = argv;
32
- if (argv.length !== 2 || flag !== "--dir" || !isAbsolute(directory)) {
33
- throw new Error("Pass --dir with the absolute path of your Lyra project.");
34
- }
35
- const { DatabaseSync } = await import("node:sqlite").catch(() => {
36
- throw new Error("Local MCP requires Node.js 22.13 or newer.");
37
- });
38
- const database = join(directory, ".lyra", "state", "runs.sqlite");
39
- const send = (message) => output.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
40
- const error = (id, code, message) => send({ id, error: { code, message } });
41
- let initialized = false;
42
- let ready = false;
43
-
44
- for await (const line of createInterface({ input, crlfDelay: Infinity })) {
45
- let request;
46
- try {
47
- request = JSON.parse(line);
48
- } catch {
49
- error(null, -32700, "Parse error.");
50
- continue;
51
- }
52
- const { id, method, params } = request ?? {};
53
- if (request?.jsonrpc !== "2.0" || typeof method !== "string") {
54
- error(null, -32600, "Invalid request.");
55
- continue;
56
- }
57
- if (id === undefined) {
58
- if (initialized && method === "notifications/initialized") ready = true;
59
- continue;
60
- }
61
- if (typeof id !== "string" && !Number.isInteger(id)) {
62
- error(null, -32600, "Invalid request ID.");
63
- continue;
64
- }
65
- if (method === "initialize" && !initialized) {
66
- const requested = params?.protocolVersion;
67
- if (typeof requested !== "string") {
68
- error(id, -32602, "Provide a protocol version.");
69
- continue;
70
- }
71
- initialized = true;
72
- send({ id, result: {
73
- protocolVersion: protocolVersions.includes(requested) ? requested : protocolVersions[0],
74
- capabilities: { tools: {} },
75
- serverInfo: { name: "agent-lyra-local", version },
76
- } });
77
- } else if (method === "ping") {
78
- send({ id, result: {} });
79
- } else if (!ready) {
80
- error(id, -32000, "Initialize the MCP session first.");
81
- } else if (method === "tools/list") {
82
- send({ id, result: { tools: [tool] } });
83
- } else if (method === "tools/call") {
84
- const args = params?.arguments;
85
- if (params?.name !== tool.name || typeof args?.runId !== "string" ||
86
- !runIdPattern.test(args.runId) || Object.keys(args).length !== 1) {
87
- error(id, -32602, "Call get_saved_run with a valid runId.");
88
- continue;
89
- }
90
- let result;
91
- try {
92
- let row;
93
- if (existsSync(database)) {
94
- const db = new DatabaseSync(database, { readOnly: true });
95
- try {
96
- row = db.prepare("SELECT body FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1")
97
- .get(args.runId.toLowerCase());
98
- } finally {
99
- db.close();
100
- }
101
- }
102
- result = row ? toolResult(row.body) : toolResult("Run not found.", true);
103
- } catch {
104
- result = toolResult("Could not read the local run database.", true);
105
- }
106
- send({ id, result });
107
- } else {
108
- error(id, -32601, "Method not found.");
109
- }
110
- }
111
- }
1
+ import { existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+
6
+ const { version } = createRequire(import.meta.url)("../../package.json");
7
+ const protocolVersions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
8
+ const uuidPattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
9
+ const runIdPattern = new RegExp(uuidPattern);
10
+ const tool = {
11
+ name: "get_saved_run",
12
+ description: "Read the latest event for a Lyra run in this project. Successful events can contain generated text.",
13
+ inputSchema: {
14
+ type: "object",
15
+ properties: { runId: { type: "string", pattern: uuidPattern } },
16
+ required: ["runId"],
17
+ additionalProperties: false,
18
+ },
19
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
20
+ };
21
+
22
+ function toolResult(text, isError = false) {
23
+ return { content: [{ type: "text", text }], ...(isError && { isError: true }) };
24
+ }
25
+
26
+ export async function serveSavedRuns(argv, { input = process.stdin, output = process.stdout } = {}) {
27
+ if (argv.length === 1 && argv[0] === "--help") {
28
+ output.write("Usage: agent-lyra mcp serve --dir <absolute-project-directory>\n");
29
+ return;
30
+ }
31
+ const [flag, directory] = argv;
32
+ if (argv.length !== 2 || flag !== "--dir" || !isAbsolute(directory)) {
33
+ throw new Error("Pass --dir with the absolute path of your Lyra project.");
34
+ }
35
+ const { DatabaseSync } = await import("node:sqlite").catch(() => {
36
+ throw new Error("Local MCP requires Node.js 22.13 or newer.");
37
+ });
38
+ const database = join(directory, ".lyra", "state", "runs.sqlite");
39
+ const send = (message) => output.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
40
+ const error = (id, code, message) => send({ id, error: { code, message } });
41
+ let initialized = false;
42
+ let ready = false;
43
+
44
+ for await (const line of createInterface({ input, crlfDelay: Infinity })) {
45
+ let request;
46
+ try {
47
+ request = JSON.parse(line);
48
+ } catch {
49
+ error(null, -32700, "Parse error.");
50
+ continue;
51
+ }
52
+ const { id, method, params } = request ?? {};
53
+ if (request?.jsonrpc !== "2.0" || typeof method !== "string") {
54
+ error(null, -32600, "Invalid request.");
55
+ continue;
56
+ }
57
+ if (id === undefined) {
58
+ if (initialized && method === "notifications/initialized") ready = true;
59
+ continue;
60
+ }
61
+ if (typeof id !== "string" && !Number.isInteger(id)) {
62
+ error(null, -32600, "Invalid request ID.");
63
+ continue;
64
+ }
65
+ if (method === "initialize" && !initialized) {
66
+ const requested = params?.protocolVersion;
67
+ if (typeof requested !== "string") {
68
+ error(id, -32602, "Provide a protocol version.");
69
+ continue;
70
+ }
71
+ initialized = true;
72
+ send({ id, result: {
73
+ protocolVersion: protocolVersions.includes(requested) ? requested : protocolVersions[0],
74
+ capabilities: { tools: {} },
75
+ serverInfo: { name: "agent-lyra-local", version },
76
+ } });
77
+ } else if (method === "ping") {
78
+ send({ id, result: {} });
79
+ } else if (!ready) {
80
+ error(id, -32000, "Initialize the MCP session first.");
81
+ } else if (method === "tools/list") {
82
+ send({ id, result: { tools: [tool] } });
83
+ } else if (method === "tools/call") {
84
+ const args = params?.arguments;
85
+ if (params?.name !== tool.name || typeof args?.runId !== "string" ||
86
+ !runIdPattern.test(args.runId) || Object.keys(args).length !== 1) {
87
+ error(id, -32602, "Call get_saved_run with a valid runId.");
88
+ continue;
89
+ }
90
+ let result;
91
+ try {
92
+ let row;
93
+ if (existsSync(database)) {
94
+ const db = new DatabaseSync(database, { readOnly: true });
95
+ try {
96
+ row = db.prepare("SELECT body FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1")
97
+ .get(args.runId.toLowerCase());
98
+ } finally {
99
+ db.close();
100
+ }
101
+ }
102
+ result = row ? toolResult(row.body) : toolResult("Run not found.", true);
103
+ } catch {
104
+ result = toolResult("Could not read the local run database.", true);
105
+ }
106
+ send({ id, result });
107
+ } else {
108
+ error(id, -32601, "Method not found.");
109
+ }
110
+ }
111
+ }