agent-lyra 0.1.4 → 0.2.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.
@@ -1,178 +1,178 @@
1
- const BASE_GUARDRAILS = [
2
- "Do not invent repository facts. If scan data is missing, state that explicitly and propose how to gather it.",
3
- "Ground every recommendation in concrete repository signals: paths, configs, language stats, CI files, and discovered patterns.",
4
- "Prefer small, reviewable changes and produce a PR-ready plan with scope and risk.",
5
- "When suggesting code or tests, reference exact file paths and likely ownership boundaries.",
6
- ];
7
-
8
- const REPO_CONTEXT_KEYS = [
9
- "repository.name",
10
- "repository.provider",
11
- "repository.defaultBranch",
12
- "stack.languages",
13
- "stack.frameworks",
14
- "stack.packageManager",
15
- "structure.workspaces",
16
- "structure.scopedPaths",
17
- "ci.workflows",
18
- "quality.testFramework",
19
- "quality.testToSourceRatio",
20
- "findingsAtScanTime",
21
- ];
22
-
23
- function list(items) {
24
- if (!Array.isArray(items) || items.length === 0) return "(none)";
25
- return items.map((item) => `- ${item}`).join("\n");
26
- }
27
-
28
- function rolePromptHeader(role, domain) {
29
- return [
30
- `You are Lyra ${role} for the ${domain} domain.`,
31
- "Operate as a repository-aware specialist that adapts to any stack.",
32
- "",
33
- "Use this runtime context contract (injected by Repo Intelligence):",
34
- list(REPO_CONTEXT_KEYS),
35
- "",
36
- "Global guardrails:",
37
- list(BASE_GUARDRAILS),
38
- "",
39
- ].join("\n");
40
- }
41
-
42
- export function createDynamicRolePrompt({ role, domain, mission, responsibilities, deliverables }) {
43
- return [
44
- rolePromptHeader(role, domain),
45
- "Mission:",
46
- mission,
47
- "",
48
- "Responsibilities:",
49
- list(responsibilities),
50
- "",
51
- "Required output:",
52
- list(deliverables),
53
- "",
54
- "Response protocol:",
55
- "- Start with a compact repository diagnosis from available scan signals.",
56
- "- Provide prioritized actions with impact, risk, and confidence levels.",
57
- "- Provide a PR-ready implementation plan with file scope.",
58
- "- If confidence is low, ask for exactly the missing artifact (never generic questions).",
59
- ].join("\n");
60
- }
61
-
62
- export const ENGINEERING_BOOTSTRAP_ROLES = [
63
- {
64
- id: "eng-dev-lead",
65
- slug: "engineering-dev-lead",
66
- name: "Engineering Dev Lead",
67
- icon: "Code2",
68
- role: "Developer Lead",
69
- kind: "dev",
70
- skills: ["web-search", "file-processor"],
71
- mission:
72
- "Drive implementation quality by mapping architecture boundaries, identifying high-leverage refactors, and planning incremental code changes aligned to the detected stack.",
73
- responsibilities: [
74
- "Infer module boundaries from folder structure and import topology.",
75
- "Propose implementation plans that match project conventions and dependency graph.",
76
- "Flag risky refactors and sequence changes into small reviewable commits.",
77
- "Tie every recommendation to concrete files and scan evidence.",
78
- ],
79
- deliverables: [
80
- "Architecture snapshot (current state)",
81
- "Top 5 engineering improvements with rationale",
82
- "PR plan with step-by-step file edits",
83
- "Rollback/mitigation notes for risky changes",
84
- ],
85
- },
86
- {
87
- id: "eng-qa-lead",
88
- slug: "engineering-qa-lead",
89
- name: "Engineering QA Lead",
90
- icon: "Bug",
91
- role: "QA Lead",
92
- kind: "qa",
93
- skills: ["web-search", "file-processor"],
94
- mission:
95
- "Increase confidence in delivery by mapping test gaps, risk hotspots, and regression exposure using actual repo structure and test signal quality.",
96
- responsibilities: [
97
- "Assess test-to-source coverage and map missing tests by critical path.",
98
- "Define risk-based test matrix per changed module and interface.",
99
- "Recommend automation additions aligned to current CI/test frameworks.",
100
- "Prioritize flaky or fragile suites that block reliable releases.",
101
- ],
102
- deliverables: [
103
- "Coverage gap map",
104
- "Regression test plan",
105
- "CI quality gate recommendations",
106
- "Defect prevention checklist",
107
- ],
108
- },
109
- {
110
- id: "eng-product-manager",
111
- slug: "engineering-product-manager",
112
- name: "Engineering Product Manager",
113
- icon: "Kanban",
114
- role: "Product Manager",
115
- kind: "product",
116
- skills: ["web-search"],
117
- mission:
118
- "Translate repository reality into product-delivery decisions by aligning backlog priorities to technical constraints, dependencies, and delivery risk.",
119
- responsibilities: [
120
- "Derive feature feasibility signals from architecture and dependency map.",
121
- "Split roadmap items into implementation slices with acceptance criteria.",
122
- "Prioritize work using impact vs complexity grounded in repo evidence.",
123
- "Highlight cross-team dependencies inferred from folder/workspace boundaries.",
124
- ],
125
- deliverables: [
126
- "Prioritized engineering backlog",
127
- "Acceptance criteria by feature",
128
- "Dependency-aware milestone plan",
129
- "Release risk summary",
130
- ],
131
- },
132
- {
133
- id: "eng-scrum-master",
134
- slug: "engineering-scrum-master",
135
- name: "Engineering Scrum Master",
136
- icon: "Activity",
137
- role: "Scrum Master",
138
- kind: "delivery",
139
- skills: ["web-search"],
140
- mission:
141
- "Optimize execution flow by identifying delivery bottlenecks in branching, CI, test reliability, and review process using repository evidence.",
142
- responsibilities: [
143
- "Detect cycle-time bottlenecks from CI and PR workflow structure.",
144
- "Define sprint execution policies tailored to the current stack and team constraints.",
145
- "Recommend WIP and review guardrails tied to observed risk hotspots.",
146
- "Create a cadence for retrospectives grounded in measurable repo signals.",
147
- ],
148
- deliverables: [
149
- "Sprint operating model",
150
- "Definition of ready/done",
151
- "Flow bottleneck remediation plan",
152
- "Delivery KPI dashboard spec",
153
- ],
154
- },
155
- {
156
- id: "eng-architect",
157
- slug: "engineering-architect",
158
- name: "Engineering Architect",
159
- icon: "Network",
160
- role: "Software Architect",
161
- kind: "architecture",
162
- skills: ["web-search", "url-scraper"],
163
- mission:
164
- "Shape long-term architecture by evaluating modularity, boundaries, and scalability tradeoffs from real project topology and configuration signals.",
165
- responsibilities: [
166
- "Assess architecture fitness against current stack and growth goals.",
167
- "Propose target-state architecture with migration path.",
168
- "Identify coupling hotspots and define boundary contracts.",
169
- "Recommend governance for reliability, observability, and security baselines.",
170
- ],
171
- deliverables: [
172
- "Current vs target architecture map",
173
- "Migration roadmap with phases",
174
- "Boundary/interface contract recommendations",
175
- "Architecture decision log template",
176
- ],
177
- },
178
- ];
1
+ const BASE_GUARDRAILS = [
2
+ "Do not invent repository facts. If scan data is missing, state that explicitly and propose how to gather it.",
3
+ "Ground every recommendation in concrete repository signals: paths, configs, language stats, CI files, and discovered patterns.",
4
+ "Prefer small, reviewable changes and produce a PR-ready plan with scope and risk.",
5
+ "When suggesting code or tests, reference exact file paths and likely ownership boundaries.",
6
+ ];
7
+
8
+ const REPO_CONTEXT_KEYS = [
9
+ "repository.name",
10
+ "repository.provider",
11
+ "repository.defaultBranch",
12
+ "stack.languages",
13
+ "stack.frameworks",
14
+ "stack.packageManager",
15
+ "structure.workspaces",
16
+ "structure.scopedPaths",
17
+ "ci.workflows",
18
+ "quality.testFramework",
19
+ "quality.testToSourceRatio",
20
+ "findingsAtScanTime",
21
+ ];
22
+
23
+ function list(items) {
24
+ if (!Array.isArray(items) || items.length === 0) return "(none)";
25
+ return items.map((item) => `- ${item}`).join("\n");
26
+ }
27
+
28
+ function rolePromptHeader(role, domain) {
29
+ return [
30
+ `You are Lyra ${role} for the ${domain} domain.`,
31
+ "Operate as a repository-aware specialist that adapts to any stack.",
32
+ "",
33
+ "Use this runtime context contract (injected by Repo Intelligence):",
34
+ list(REPO_CONTEXT_KEYS),
35
+ "",
36
+ "Global guardrails:",
37
+ list(BASE_GUARDRAILS),
38
+ "",
39
+ ].join("\n");
40
+ }
41
+
42
+ export function createDynamicRolePrompt({ role, domain, mission, responsibilities, deliverables }) {
43
+ return [
44
+ rolePromptHeader(role, domain),
45
+ "Mission:",
46
+ mission,
47
+ "",
48
+ "Responsibilities:",
49
+ list(responsibilities),
50
+ "",
51
+ "Required output:",
52
+ list(deliverables),
53
+ "",
54
+ "Response protocol:",
55
+ "- Start with a compact repository diagnosis from available scan signals.",
56
+ "- Provide prioritized actions with impact, risk, and confidence levels.",
57
+ "- Provide a PR-ready implementation plan with file scope.",
58
+ "- If confidence is low, ask for exactly the missing artifact (never generic questions).",
59
+ ].join("\n");
60
+ }
61
+
62
+ export const ENGINEERING_BOOTSTRAP_ROLES = [
63
+ {
64
+ id: "eng-dev-lead",
65
+ slug: "engineering-dev-lead",
66
+ name: "Engineering Dev Lead",
67
+ icon: "Code2",
68
+ role: "Developer Lead",
69
+ kind: "dev",
70
+ skills: ["web-search", "file-processor"],
71
+ mission:
72
+ "Drive implementation quality by mapping architecture boundaries, identifying high-leverage refactors, and planning incremental code changes aligned to the detected stack.",
73
+ responsibilities: [
74
+ "Infer module boundaries from folder structure and import topology.",
75
+ "Propose implementation plans that match project conventions and dependency graph.",
76
+ "Flag risky refactors and sequence changes into small reviewable commits.",
77
+ "Tie every recommendation to concrete files and scan evidence.",
78
+ ],
79
+ deliverables: [
80
+ "Architecture snapshot (current state)",
81
+ "Top 5 engineering improvements with rationale",
82
+ "PR plan with step-by-step file edits",
83
+ "Rollback/mitigation notes for risky changes",
84
+ ],
85
+ },
86
+ {
87
+ id: "eng-qa-lead",
88
+ slug: "engineering-qa-lead",
89
+ name: "Engineering QA Lead",
90
+ icon: "Bug",
91
+ role: "QA Lead",
92
+ kind: "qa",
93
+ skills: ["web-search", "file-processor"],
94
+ mission:
95
+ "Increase confidence in delivery by mapping test gaps, risk hotspots, and regression exposure using actual repo structure and test signal quality.",
96
+ responsibilities: [
97
+ "Assess test-to-source coverage and map missing tests by critical path.",
98
+ "Define risk-based test matrix per changed module and interface.",
99
+ "Recommend automation additions aligned to current CI/test frameworks.",
100
+ "Prioritize flaky or fragile suites that block reliable releases.",
101
+ ],
102
+ deliverables: [
103
+ "Coverage gap map",
104
+ "Regression test plan",
105
+ "CI quality gate recommendations",
106
+ "Defect prevention checklist",
107
+ ],
108
+ },
109
+ {
110
+ id: "eng-product-manager",
111
+ slug: "engineering-product-manager",
112
+ name: "Engineering Product Manager",
113
+ icon: "Kanban",
114
+ role: "Product Manager",
115
+ kind: "product",
116
+ skills: ["web-search"],
117
+ mission:
118
+ "Translate repository reality into product-delivery decisions by aligning backlog priorities to technical constraints, dependencies, and delivery risk.",
119
+ responsibilities: [
120
+ "Derive feature feasibility signals from architecture and dependency map.",
121
+ "Split roadmap items into implementation slices with acceptance criteria.",
122
+ "Prioritize work using impact vs complexity grounded in repo evidence.",
123
+ "Highlight cross-team dependencies inferred from folder/workspace boundaries.",
124
+ ],
125
+ deliverables: [
126
+ "Prioritized engineering backlog",
127
+ "Acceptance criteria by feature",
128
+ "Dependency-aware milestone plan",
129
+ "Release risk summary",
130
+ ],
131
+ },
132
+ {
133
+ id: "eng-scrum-master",
134
+ slug: "engineering-scrum-master",
135
+ name: "Engineering Scrum Master",
136
+ icon: "Activity",
137
+ role: "Scrum Master",
138
+ kind: "delivery",
139
+ skills: ["web-search"],
140
+ mission:
141
+ "Optimize execution flow by identifying delivery bottlenecks in branching, CI, test reliability, and review process using repository evidence.",
142
+ responsibilities: [
143
+ "Detect cycle-time bottlenecks from CI and PR workflow structure.",
144
+ "Define sprint execution policies tailored to the current stack and team constraints.",
145
+ "Recommend WIP and review guardrails tied to observed risk hotspots.",
146
+ "Create a cadence for retrospectives grounded in measurable repo signals.",
147
+ ],
148
+ deliverables: [
149
+ "Sprint operating model",
150
+ "Definition of ready/done",
151
+ "Flow bottleneck remediation plan",
152
+ "Delivery KPI dashboard spec",
153
+ ],
154
+ },
155
+ {
156
+ id: "eng-architect",
157
+ slug: "engineering-architect",
158
+ name: "Engineering Architect",
159
+ icon: "Network",
160
+ role: "Software Architect",
161
+ kind: "architecture",
162
+ skills: ["web-search", "url-scraper"],
163
+ mission:
164
+ "Shape long-term architecture by evaluating modularity, boundaries, and scalability tradeoffs from real project topology and configuration signals.",
165
+ responsibilities: [
166
+ "Assess architecture fitness against current stack and growth goals.",
167
+ "Propose target-state architecture with migration path.",
168
+ "Identify coupling hotspots and define boundary contracts.",
169
+ "Recommend governance for reliability, observability, and security baselines.",
170
+ ],
171
+ deliverables: [
172
+ "Current vs target architecture map",
173
+ "Migration roadmap with phases",
174
+ "Boundary/interface contract recommendations",
175
+ "Architecture decision log template",
176
+ ],
177
+ },
178
+ ];
@@ -0,0 +1,47 @@
1
+ /** A provider adapter owns authentication, transport, and response normalization. */
2
+ export interface ModelProvider {
3
+ complete(request: ModelRequest, options?: { signal?: AbortSignal }): Promise<ModelResult>;
4
+ }
5
+
6
+ export interface ModelRequest {
7
+ model: string;
8
+ messages: readonly { role: "system" | "user" | "assistant"; content: string }[];
9
+ }
10
+
11
+ export interface ModelResult {
12
+ text: string;
13
+ usage?: { inputTokens?: number; outputTokens?: number };
14
+ }
15
+
16
+ interface RunEventData {
17
+ "run.started": { agentId: string; model: string };
18
+ "run.completed": { result: ModelResult };
19
+ "run.failed": { message: string };
20
+ "run.cancelled": { reason?: string };
21
+ }
22
+
23
+ /** Local events share the cloud event names. A cloud adapter supplies tenant metadata. */
24
+ export type RunEvent = {
25
+ [Type in keyof RunEventData]: {
26
+ id: string;
27
+ run_id: string;
28
+ /** Contiguous sequence, starting at zero within each run. */
29
+ seq: number;
30
+ /** ISO 8601 timestamp. */
31
+ ts: string;
32
+ type: Type;
33
+ data: RunEventData[Type];
34
+ };
35
+ }[keyof RunEventData];
36
+
37
+ /** A run's ordered event stream is the source of truth for its status. */
38
+ export interface RunStore {
39
+ /**
40
+ * Atomically append an event. Require started at seq 0, reject sequence
41
+ * conflicts and appends after a terminal event, and accept exact retries
42
+ * of already stored events without creating duplicates.
43
+ */
44
+ append(event: RunEvent): Promise<void>;
45
+ /** Read events in sequence order. Unknown runs return an empty array. */
46
+ list(runId: string): Promise<readonly RunEvent[]>;
47
+ }
@@ -0,0 +1,159 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { runAgent } from "./run-agent.js";
5
+
6
+ async function openStore(cwd) {
7
+ const { DatabaseSync } = await import("node:sqlite").catch(() => {
8
+ throw new Error("Local agent runs require Node.js 22.13 or newer.");
9
+ });
10
+ const directory = join(cwd, ".lyra", "state");
11
+ await mkdir(directory, { recursive: true, mode: 0o700 });
12
+ await writeFile(join(directory, ".gitignore"), "*\n", { flag: "wx" }).catch((error) => {
13
+ if (error.code !== "EEXIST") throw error;
14
+ });
15
+ const db = new DatabaseSync(join(directory, "runs.sqlite"));
16
+ db.exec(`
17
+ PRAGMA busy_timeout = 5000;
18
+ CREATE TABLE IF NOT EXISTS events (
19
+ run_id TEXT NOT NULL,
20
+ seq INTEGER NOT NULL,
21
+ body TEXT NOT NULL,
22
+ PRIMARY KEY (run_id, seq)
23
+ );
24
+ `);
25
+ return {
26
+ async append(event) {
27
+ const body = JSON.stringify(event);
28
+ db.exec("BEGIN IMMEDIATE");
29
+ try {
30
+ const existing = db.prepare("SELECT body FROM events WHERE run_id = ? AND seq = ?")
31
+ .get(event.run_id, event.seq);
32
+ if (existing) {
33
+ if (existing.body !== body) throw new Error("Conflicting run event.");
34
+ } else {
35
+ const previous = db.prepare("SELECT seq, body FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1")
36
+ .get(event.run_id);
37
+ const valid = previous
38
+ ? event.seq === previous.seq + 1 && JSON.parse(previous.body).type === "run.started"
39
+ && event.type !== "run.started"
40
+ : event.seq === 0 && event.type === "run.started";
41
+ if (!valid) throw new Error("Invalid run event sequence.");
42
+ db.prepare("INSERT INTO events (run_id, seq, body) VALUES (?, ?, ?)")
43
+ .run(event.run_id, event.seq, body);
44
+ }
45
+ db.exec("COMMIT");
46
+ } catch (error) {
47
+ db.exec("ROLLBACK");
48
+ throw error;
49
+ }
50
+ },
51
+ async list(runId) {
52
+ return db.prepare("SELECT body FROM events WHERE run_id = ? ORDER BY seq").all(runId)
53
+ .map(({ body }) => JSON.parse(body));
54
+ },
55
+ close() {
56
+ db.close();
57
+ },
58
+ };
59
+ }
60
+
61
+ function createOpenAIProvider(apiKey, fetchRequest) {
62
+ return {
63
+ async complete(request) {
64
+ const response = await fetchRequest("https://api.openai.com/v1/chat/completions", {
65
+ method: "POST",
66
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
67
+ redirect: "error",
68
+ signal: AbortSignal.timeout(60_000),
69
+ body: JSON.stringify({ ...request, max_completion_tokens: 1024 }),
70
+ });
71
+ if (!response.ok) throw new Error(`OpenAI request failed (HTTP ${response.status}).`);
72
+ const result = await response.json();
73
+ const text = result.choices?.[0]?.message?.content;
74
+ if (typeof text !== "string" || !text.trim()) throw new Error("OpenAI returned no text.");
75
+ return {
76
+ text,
77
+ usage: { inputTokens: result.usage?.prompt_tokens, outputTokens: result.usage?.completion_tokens },
78
+ };
79
+ },
80
+ };
81
+ }
82
+
83
+ export async function runLocalCli(argv, {
84
+ cwd = process.cwd(),
85
+ env = process.env,
86
+ output = process.stdout,
87
+ diagnostics = process.stderr,
88
+ fetchRequest = globalThis.fetch,
89
+ } = {}) {
90
+ const [group, command, ...args] = argv;
91
+ const statusCommand = group === "run" && command === "status";
92
+ const agentCommand = group === "agent" && command === "run";
93
+ const teamCommand = group === "team" && command === "run";
94
+ if (!statusCommand && !agentCommand && !teamCommand) return false;
95
+
96
+ if (args.includes("--help")) {
97
+ const usage = statusCommand
98
+ ? "agent-lyra run status <run-id>"
99
+ : teamCommand
100
+ ? "agent-lyra team run draft-review --model <model> --prompt <text>"
101
+ : "agent-lyra agent run --model <model> --prompt <text>";
102
+ output.write(`Usage: ${usage}\n`);
103
+ return true;
104
+ }
105
+
106
+ if (statusCommand) {
107
+ if (args.length !== 1 || !/^[0-9a-f-]{36}$/i.test(args[0])) throw new Error("Provide a valid run ID.");
108
+ const store = await openStore(cwd);
109
+ try {
110
+ const events = await store.list(args[0]);
111
+ if (!events.length) throw new Error(`Run not found: ${args[0]}`);
112
+ output.write(`${JSON.stringify(events.at(-1))}\n`);
113
+ } finally {
114
+ store.close();
115
+ }
116
+ return true;
117
+ }
118
+
119
+ if (teamCommand && args.shift() !== "draft-review") {
120
+ throw new Error("Choose the draft-review team. See agent-lyra team run --help.");
121
+ }
122
+ const { values } = parseArgs({
123
+ args,
124
+ options: { model: { type: "string" }, prompt: { type: "string" } },
125
+ });
126
+ if (!values.model?.trim() || !values.prompt?.trim()) throw new Error("--model and --prompt are required.");
127
+ if (!env.OPENAI_API_KEY?.trim()) throw new Error("Set OPENAI_API_KEY in your terminal environment.");
128
+ const provider = createOpenAIProvider(env.OPENAI_API_KEY.trim(), fetchRequest);
129
+ const stages = teamCommand
130
+ ? [
131
+ { agentId: "draft-writer", system: "Write a first draft that addresses the user's request." },
132
+ { agentId: "draft-reviewer", system: "Review the draft against the user's request and return the improved final text." },
133
+ ]
134
+ : [{ agentId: "local-assistant", system: "You are a helpful local assistant." }];
135
+
136
+ const store = await openStore(cwd);
137
+ try {
138
+ const messages = [{ role: "user", content: values.prompt }];
139
+ let text;
140
+ for (const { agentId, system } of stages) {
141
+ const event = await runAgent({
142
+ agentId,
143
+ request: { model: values.model, messages: [{ role: "system", content: system }, ...messages] },
144
+ provider,
145
+ store,
146
+ onStarted: (runId) => diagnostics.write(teamCommand ? `${agentId} run ID: ${runId}\n` : `Run ID: ${runId}\n`),
147
+ });
148
+ if (event.type === "run.failed") {
149
+ throw new Error("Model request failed. Check your OpenAI key, model access, and network.");
150
+ }
151
+ text = event.data.result.text;
152
+ messages.push({ role: "assistant", content: text });
153
+ }
154
+ output.write(`${text}\n`);
155
+ } finally {
156
+ store.close();
157
+ }
158
+ return true;
159
+ }
@@ -0,0 +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
+ }