agent-lyra 0.11.2 → 0.13.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 (43) hide show
  1. package/README.md +58 -35
  2. package/bin/agent-lyra.js +4 -1
  3. package/bin/lyra-oss-preview.js +3 -1
  4. package/package.json +1 -1
  5. package/src/app-builder/init.js +3 -3
  6. package/src/framework/agent.js +19 -8
  7. package/src/framework/mda.js +5 -2
  8. package/src/framework/run.py +83 -11
  9. package/src/index.d.ts +1 -0
  10. package/src/index.js +1 -0
  11. package/src/init.js +13 -1
  12. package/src/intelligence/graph-setup.js +125 -0
  13. package/src/intelligence/lifecycle.js +4 -2
  14. package/src/memory/LICENSE +1 -1
  15. package/src/memory/UPSTREAM.json +6 -3
  16. package/src/memory/external-engine.js +35 -0
  17. package/src/memory/index.js +19 -1
  18. package/src/memory/lifecycle.js +2 -1
  19. package/src/runtime/programmatic.d.ts +84 -0
  20. package/src/runtime/programmatic.js +155 -0
  21. package/src/runtime/run-agent.js +10 -2
  22. package/src/standalone/init.js +4 -2
  23. package/src/studio/browser.js +219 -23
  24. package/src/studio/code-discovery.js +81 -0
  25. package/src/studio/export.js +8 -5
  26. package/src/studio/graphsnip-workbench.js +72 -0
  27. package/src/studio/history-panel.js +193 -0
  28. package/src/studio/ide-provider.js +65 -0
  29. package/src/studio/index.html +69 -10
  30. package/src/studio/intelligence.js +110 -0
  31. package/src/studio/local-provider.js +43 -0
  32. package/src/studio/memory-actions.js +28 -1
  33. package/src/studio/memory-panel.js +29 -5
  34. package/src/studio/mission-ui.css +52 -0
  35. package/src/studio/mission-ui.js +57 -0
  36. package/src/studio/programmatic-runner.mjs +21 -0
  37. package/src/studio/programmatic.js +54 -0
  38. package/src/studio/project.js +103 -25
  39. package/src/studio/python-agent.py +31 -4
  40. package/src/studio/run-history.js +128 -0
  41. package/src/studio/server.js +90 -10
  42. package/src/studio/session.js +1 -1
  43. package/src/studio/studio.css +128 -0
@@ -0,0 +1,193 @@
1
+ import { formatMissionDuration, missionStatusLabel, renderMissionStatus, renderMissionTimeline } from "./mission-ui.js";
2
+
3
+ const runIdPattern = /^[a-f0-9-]{36}$/i;
4
+
5
+ function element(tag, text, className) {
6
+ const node = document.createElement(tag);
7
+ if (text !== undefined) node.textContent = text;
8
+ if (className) node.className = className;
9
+ return node;
10
+ }
11
+
12
+ function link(text, href) {
13
+ const node = element("a", text);
14
+ node.href = href;
15
+ return node;
16
+ }
17
+
18
+ const date = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "medium" });
19
+ const historyHash = id => "#run=" + id;
20
+
21
+ function timeline(h, events) {
22
+ return renderMissionTimeline(h, events.map(event => {
23
+ const [scope, status] = event.type.split(".");
24
+ const title = scope === "step" ? "Step " + event.index : scope[0].toUpperCase() + scope.slice(1);
25
+ const description = [event.activityId,
26
+ Number.isSafeInteger(event.bytes) ? event.bytes + " context bytes" : undefined,
27
+ Number.isSafeInteger(event.tokenBudget) ? event.tokenBudget + " token budget" : undefined, Number.isSafeInteger(event.count) ? event.count + " matched" : undefined,
28
+ scope !== "step" && event.index ? "Step " + event.index : undefined, event.agentId, event.source, event.provider, event.model,
29
+ Number.isFinite(event.usage?.inputTokens) ? event.usage.inputTokens + " input tokens" : undefined,
30
+ Number.isFinite(event.usage?.outputTokens) ? event.usage.outputTokens + " output tokens" : undefined,
31
+ ].filter(Boolean).join(" · ");
32
+ return {
33
+ id: event.sequence, title, status, statusLabel: missionStatusLabel(status), description,
34
+ duration: Number.isFinite(event.durationMs) ? formatMissionDuration(event.durationMs, { showMilliseconds: true }) : undefined,
35
+ timestamp: event.timestamp, timestampLabel: date.format(new Date(event.timestamp)),
36
+ reference: event.runtimeRunId ? "Runtime run " + event.runtimeRunId : undefined,
37
+ };
38
+ }));
39
+ }
40
+
41
+ const detailSections = [
42
+ { id: "steps", title: "Steps", matches: event => /^(run|step)\./.test(event.type), empty: "No steps recorded for this run." },
43
+ { id: "activity", title: "Activity", matches: event => /^(tool|model|skill|memory|context)\./.test(event.type), empty: "No model, tool, skill, or memory activity was recorded." },
44
+ { id: "tokens", title: "Tokens", matches: event => event.type === "step.completed" &&
45
+ [event.usage?.inputTokens, event.usage?.outputTokens].some(Number.isSafeInteger), empty: "The provider did not report token usage for this run." },
46
+ { id: "evaluations", title: "Evaluations", matches: event => event.type.startsWith("evaluation."), empty: "No evaluations were recorded for this run." },
47
+ ];
48
+
49
+ function renderDetailSections(h, report, selected, choose) {
50
+ const controls = element("nav", undefined, "history-detail-tabs");
51
+ controls.setAttribute("aria-label", "Run details");
52
+ const content = element("div");
53
+ const buttons = detailSections.map(section => {
54
+ const button = element("button", section.title);
55
+ button.type = "button";
56
+ button.onclick = () => {
57
+ choose(section.id);
58
+ render(section.id);
59
+ };
60
+ return button;
61
+ });
62
+ function render(id) {
63
+ const section = detailSections.find(item => item.id === id);
64
+ for (const [index, button] of buttons.entries()) {
65
+ button.setAttribute("aria-pressed", String(detailSections[index] === section));
66
+ }
67
+ const events = report.events.filter(section.matches);
68
+ content.replaceChildren(events.length
69
+ ? timeline(h, events)
70
+ : element("p", section.empty, "lyra-mission-empty"));
71
+ }
72
+ controls.append(...buttons);
73
+ render(selected);
74
+ return [controls, content];
75
+ }
76
+
77
+ export function mountHistoryPanel(api, showMissionControl, h, openMemory) {
78
+ const panel = document.querySelector("#history-panel");
79
+ const list = panel.querySelector("#history-list");
80
+ const detail = panel.querySelector("#history-detail");
81
+ const status = panel.querySelector("#history-status");
82
+ const open = document.querySelector("#open-history");
83
+ const summary = panel.querySelector("#history-summary");
84
+ const search = panel.querySelector("#history-search");
85
+ const filter = panel.querySelector("#history-filter");
86
+ let runs = [];
87
+ let selection;
88
+ function duration(run) { return run.endedAt ? Date.parse(run.endedAt) - Date.parse(run.startedAt) : undefined; }
89
+ function renderRuns() {
90
+ const today = new Date().toDateString();
91
+ const current = runs.filter(run => new Date(run.endedAt).toDateString() === today);
92
+ const durations = current.map(duration).filter(Number.isFinite);
93
+ const mean = durations.length ? formatMissionDuration(durations.reduce((sum, value) => sum + value, 0) / durations.length) : "—";
94
+ summary.replaceChildren(...[
95
+ ["Running", runs.filter(run => run.status === "running").length],
96
+ ["Completed today", current.filter(run => run.status === "completed").length],
97
+ ["Failed today", current.filter(run => run.status === "failed").length], ["Avg duration today", mean],
98
+ ].map(([label, value]) => h("div", {}, element("span", label), element("strong", String(value)))));
99
+ const query = search.value.trim().toLowerCase();
100
+ const visible = runs.filter(run => (!filter.value || filter.value === run.status) &&
101
+ [run.agentName, run.id, run.source].some(value => value?.toLowerCase().includes(query)));
102
+ list.replaceChildren();
103
+ if (!visible.length) {
104
+ list.append(element("p", runs.length ? "No matching runs." : "No runs in this project yet."));
105
+ return;
106
+ }
107
+ const table = element("table", undefined, "workbench-run-table");
108
+ table.append(h("thead", {}, h("tr", {}, ...["Run", "Source", "Status", "Started", "Duration"].map(title => h("th", { scope: "col" }, title)))));
109
+ table.append(h("tbody", {}, ...visible.map(run => {
110
+ const item = link(run.agentName || "Run " + run.id.slice(0, 8), historyHash(run.id));
111
+ if (run.id === selection) item.setAttribute("aria-current", "true");
112
+ return h("tr", { className: run.id === selection ? "selected-run" : "" },
113
+ h("td", {}, item, run.steps > 1 ? element("small", run.steps + " steps") : undefined),
114
+ h("td", {}, ({ cloud: "Cloud agent", local: "Local text", programmatic: "Local code", framework: "Local framework", python: "Python" })[run.source] ?? "—"),
115
+ h("td", {}, renderMissionStatus(h, run.status)),
116
+ h("td", {}, date.format(new Date(run.startedAt))), h("td", {}, formatMissionDuration(duration(run))));
117
+ })));
118
+ list.append(table);
119
+ }
120
+ search.oninput = filter.onchange = renderRuns;
121
+ let section = "steps";
122
+ let request = 0;
123
+
124
+ async function refresh(id) {
125
+ const current = ++request;
126
+ if (selection !== id) section = "steps";
127
+ selection = id;
128
+ status.textContent = "Loading run history…";
129
+ try {
130
+ const [history, report] = await Promise.all([api("history"), id ? api("history/" + id) : undefined]);
131
+ if (current !== request) return;
132
+ runs = history.runs;
133
+ renderRuns();
134
+ detail.replaceChildren();
135
+ if (!report && detail.open) detail.close();
136
+ if (report) {
137
+ const run = runs.find(item => item.id === id);
138
+ const close = h("button", { type: "button", onClick: () => detail.close() }, "Close");
139
+ if (!detail.open) detail.show();
140
+ detail.append(h("header", {}, element("h2", run?.agentName || "Run details"), close),
141
+ renderMissionStatus(h, report.run.status),
142
+ element("code", report.run.id),
143
+ link("Download JSON report", "/api/history/" + report.run.id + "/report"),
144
+ report.run.status === "completed" ? h("button", {
145
+ type: "button", onClick: () => openMemory(report.run.id),
146
+ }, "Record learning") : element("span"),
147
+ ...renderDetailSections(h, report, section, id => { section = id; }));
148
+ if (report.run.status === "completed") {
149
+ const { suggestions } = await api("memory/suggestions", { runId: report.run.id }).catch(() => ({ suggestions: [] }));
150
+ if (current !== request) return;
151
+ if (suggestions.length) {
152
+ const box = element("section", undefined, "learning-suggestions");
153
+ box.append(element("h3", "Suggested learnings"));
154
+ for (const suggestion of suggestions) {
155
+ box.append(h("button", { type: "button", onClick: () => openMemory(report.run.id, suggestion) },
156
+ "Review " + suggestion.title));
157
+ }
158
+ detail.insertBefore(box, detail.querySelector(".history-detail-tabs"));
159
+ }
160
+ }
161
+ }
162
+ status.textContent = "";
163
+ } catch (error) {
164
+ if (current !== request) return;
165
+ detail.replaceChildren();
166
+ status.textContent = error.message;
167
+ }
168
+ }
169
+
170
+ detail.addEventListener("close", () => {
171
+ if (location.hash.startsWith("#run=")) history.replaceState(history.state, "", location.pathname + location.search);
172
+ selection = undefined;
173
+ renderRuns();
174
+ });
175
+
176
+ function syncLocation() {
177
+ if (open.hidden) return;
178
+ const id = location.hash.startsWith("#run=") ? location.hash.slice(5) : "";
179
+ if (runIdPattern.test(id)) {
180
+ showMissionControl();
181
+ return refresh(id);
182
+ }
183
+ if (!panel.hidden) return refresh();
184
+ }
185
+
186
+ open.onclick = () => {
187
+ showMissionControl();
188
+ void syncLocation();
189
+ };
190
+ panel.querySelector("#refresh-history").onclick = () => void refresh(selection);
191
+ window.addEventListener("hashchange", syncLocation);
192
+ return syncLocation;
193
+ }
@@ -0,0 +1,65 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export function ideModel() {
4
+ if (!process.connected || typeof process.send !== "function") return undefined;
5
+ try {
6
+ const model = JSON.parse(process.env.LYRA_IDE_MODEL ?? "null");
7
+ if (typeof model?.id === "string" && model.id && typeof model.name === "string" && model.name) return model;
8
+ } catch {
9
+ // The IDE provider is available only in a valid extension session.
10
+ }
11
+ return undefined;
12
+ }
13
+
14
+ export function completeIde(request, { signal, onDelta, onActivity } = {}) {
15
+ signal?.throwIfAborted();
16
+ const model = ideModel();
17
+ if (!model || request.model !== model.id) throw new Error("Choose an active VS Code model.");
18
+ const prompt = request.messages.map(({ role, content }) => role + ":\n" + content).join("\n\n");
19
+ return new Promise((resolve, reject) => {
20
+ const id = randomUUID();
21
+ const cleanup = () => {
22
+ clearTimeout(timer);
23
+ signal?.removeEventListener("abort", cancel);
24
+ process.off("message", receive);
25
+ process.off("disconnect", disconnect);
26
+ };
27
+ const receive = message => {
28
+ if (message?.id !== id) return;
29
+ if (message.type === "lyra.ide.delta" && typeof message.text === "string") {
30
+ onDelta?.(message.text);
31
+ return;
32
+ }
33
+ if (message.type === "lyra.ide.activity") {
34
+ try { onActivity?.(message.event); } catch {}
35
+ return;
36
+ }
37
+ if (message.type !== "lyra.ide.result") return;
38
+ cleanup();
39
+ if (typeof message.text === "string" && message.text.trim()) resolve({ text: message.text });
40
+ else reject(new Error("VS Code did not return model output. Check model access in the editor."));
41
+ };
42
+ const disconnect = () => {
43
+ cleanup();
44
+ reject(new Error("The VS Code session disconnected."));
45
+ };
46
+ const cancel = () => {
47
+ cleanup();
48
+ if (process.connected) process.send({ type: "lyra.ide.cancel", id }, () => {});
49
+ reject(signal.reason);
50
+ };
51
+ const timer = setTimeout(() => {
52
+ cleanup();
53
+ if (process.connected) process.send({ type: "lyra.ide.cancel", id }, () => {});
54
+ reject(new Error("The VS Code model request timed out."));
55
+ }, 60_000);
56
+ signal?.addEventListener("abort", cancel, { once: true });
57
+ process.on("message", receive);
58
+ process.once("disconnect", disconnect);
59
+ process.send({ type: "lyra.ide.request", id, prompt }, error => {
60
+ if (!error) return;
61
+ cleanup();
62
+ reject(new Error("Could not reach the VS Code model session."));
63
+ });
64
+ });
65
+ }
@@ -2,15 +2,37 @@
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
- <title>AgentLyra Studio</title><link rel="stylesheet" href="/studio.css"><link rel="stylesheet" href="/agent-ui.css"><script src="/studio.js" type="module"></script>
5
+ <title>AgentLyra Workbench</title><link rel="stylesheet" href="/studio.css"><link rel="stylesheet" href="/agent-ui.css"><link rel="stylesheet" href="/mission-ui.css"><script src="/studio.js" type="module"></script>
6
6
  </head>
7
7
  <body>
8
8
  <header class="studio-header">
9
- <div class="studio-brand"><img class="studio-mark" src="/lyra-icon.png" width="34" height="34" alt=""><div><strong>AgentLyra Studio</strong><span id="project-name"></span></div></div>
10
- <nav id="studio-views" aria-label="Studio views">
11
- <button id="show-layout" type="button" aria-pressed="true">Layout</button>
12
- <button id="show-workflow" type="button" aria-pressed="false">Workflow</button>
13
- </nav><div class="toolbar"><span id="cloud-state" class="pill"></span><button id="open-memory" type="button" hidden>Memory</button> <button id="refresh">Reload agents</button> <button id="connect-cloud" type="button" hidden>Connect to Cloud</button> <button id="pull" type="button" hidden>Pull from Cloud</button> <button class="primary" id="save">Save layout</button></div></header>
9
+ <div class="studio-brand"><img class="studio-mark" src="/lyra-icon.png" width="34" height="34" alt=""><div><strong>AgentLyra Workbench</strong><span id="project-name"></span></div></div>
10
+ <div class="toolbar"><span id="cloud-state" class="pill"></span><button class="primary" id="save">Save layout</button></div>
11
+ <nav id="studio-views" aria-label="Workbench views">
12
+ <div role="group" aria-labelledby="nav-observability">
13
+ <span id="nav-observability">Observability</span>
14
+ <button id="open-history" type="button" aria-pressed="false">Mission Control</button>
15
+ </div>
16
+ <div role="group" aria-labelledby="nav-development">
17
+ <span id="nav-development">Development</span>
18
+ <button id="show-registry" type="button" aria-pressed="false">Agent Registry</button>
19
+ </div>
20
+ <div role="group" aria-labelledby="nav-app-builder">
21
+ <span id="nav-app-builder">App Builder</span>
22
+ <button id="show-layout" type="button" aria-pressed="true">Layout</button>
23
+ <button id="show-workflow" type="button" aria-pressed="false">Workflow</button>
24
+ </div>
25
+ <div role="group" aria-labelledby="nav-intelligence">
26
+ <span id="nav-intelligence">Intelligence</span>
27
+ <button id="show-graph" type="button" aria-pressed="false">Knowledge Graph</button>
28
+ <button id="show-tokens" type="button" aria-pressed="false">Token Intelligence</button>
29
+ <button id="open-memory" type="button" hidden>Memory &amp; Learnings</button>
30
+ </div>
31
+ <div role="group" aria-labelledby="nav-configuration">
32
+ <span id="nav-configuration">Configuration</span>
33
+ <button id="show-cloud" type="button" aria-pressed="false">Cloud Sync</button>
34
+ </div>
35
+ </nav></header>
14
36
  <p role="status" id="status"></p>
15
37
  <dialog id="cloud-setup" aria-labelledby="cloud-title">
16
38
  <header><h2 id="cloud-title">Connect to AgentLyra Cloud</h2><button id="close-cloud" type="button">Close</button></header>
@@ -23,8 +45,42 @@
23
45
  <p id="cloud-error" role="status"></p>
24
46
  </form></dialog>
25
47
  <main>
48
+ <section id="history-panel" aria-labelledby="history-title" hidden>
49
+ <div class="history-heading"><div><h1 id="history-title">Mission Control</h1><p>Local run history for this project.</p></div>
50
+ <button id="refresh-history" type="button">Refresh runs</button></div>
51
+ <div id="history-summary" class="workbench-metrics"></div>
52
+ <div class="workbench-filters"><input id="history-search" type="search" aria-label="Search runs" placeholder="Search runs…"><select id="history-filter" aria-label="Filter runs"><option value="">All runs</option><option value="running">Running</option><option value="completed">Completed</option><option value="failed">Failed</option></select></div>
53
+ <p id="history-status" role="status"></p>
54
+ <div class="history-content">
55
+ <nav id="history-list" aria-label="Recent runs"></nav>
56
+ <dialog id="history-detail" aria-label="Run details"></dialog>
57
+ </div>
58
+ </section>
59
+ <section id="graph-panel" class="intelligence-panel" aria-labelledby="graph-title" hidden>
60
+ <div class="history-heading"><h1 id="graph-title">Knowledge Graph</h1>
61
+ <button id="build-graph" type="button" disabled>Build graph and report</button></div>
62
+ <div id="graph-content" aria-live="polite"></div>
63
+ </section>
64
+ <section id="token-panel" class="intelligence-panel" aria-labelledby="token-title" hidden>
65
+ <div class="history-heading"><h1 id="token-title">Token Intelligence</h1>
66
+ <button id="refresh-tokens" type="button">Refresh ledger</button></div>
67
+ <p>GraphSnip estimates context tokens against its baseline. Provider-reported usage is shown per run in Mission Control.</p>
68
+ <div id="token-content" aria-live="polite"></div>
69
+ </section>
70
+ <section id="cloud-settings" aria-labelledby="cloud-settings-title" hidden>
71
+ <h1 id="cloud-settings-title">Cloud Sync</h1>
72
+ <p id="cloud-settings-description"></p>
73
+ <div class="actions">
74
+ <button id="connect-cloud" type="button" class="primary" hidden>Connect to Cloud</button>
75
+ <button id="pull" type="button" class="primary" hidden>Pull from Cloud</button>
76
+ <button id="pause-cloud" type="button" hidden>Work locally</button>
77
+ </div>
78
+ </section>
26
79
  <aside id="library" aria-labelledby="library-title">
27
- <h2 id="library-title">Project library</h2>
80
+ <div class="history-heading">
81
+ <h2 id="library-title">Project library</h2>
82
+ <button id="refresh" type="button" hidden>Reload agents</button>
83
+ </div>
28
84
  <nav id="library-tabs" aria-label="Library categories">
29
85
  <button type="button" data-library="palette" aria-pressed="true">Components</button>
30
86
  <button type="button" data-library="agents" aria-pressed="false">Agents</button>
@@ -34,6 +90,8 @@
34
90
  </nav>
35
91
  <label id="library-search-label" for="library-search" hidden>Search library</label>
36
92
  <input id="library-search" type="search" placeholder="Search by name or source" hidden>
93
+ <div id="discovery-status" aria-live="polite" hidden></div>
94
+ <dialog id="discovery-review" aria-labelledby="discovery-title"><header><h2 id="discovery-title">Add to Registry</h2><button id="close-discovery" type="button">Close</button></header><p>These registrations are saved in this project.</p><div id="discovery-items"></div><p id="discovery-error" role="status"></p><button id="add-discovered" type="button" class="primary">Add selected agents</button></dialog>
37
95
  <div id="library-content"><div id="palette"></div><div id="agents" hidden></div><div id="workflows" hidden></div><div id="teams" hidden></div><div id="skills" hidden></div></div>
38
96
  </aside>
39
97
  <section id="workflow-panel" aria-labelledby="workflow-title" hidden>
@@ -60,9 +118,10 @@
60
118
  <aside id="inspector-panel" aria-labelledby="inspector-title" hidden><div class="inspector-heading"><h2 id="inspector-title">Inspector</h2><button id="close-inspector" type="button">Close</button></div><div id="inspector"></div></aside>
61
119
  </main>
62
120
  <dialog id="memory-panel" aria-labelledby="memory-title">
63
- <header><h2 id="memory-title">Memory</h2><button id="close-memory" type="button">Close</button></header>
121
+ <header><h2 id="memory-title">Memory &amp; Learnings</h2><button id="close-memory" type="button">Close</button></header>
64
122
  <p>Project memories stay local until you choose to upload a verified record.</p>
65
123
  <p id="memory-status" role="status"></p>
124
+ <p id="memory-engine"></p>
66
125
  <p id="memory-summary"></p>
67
126
  <form id="memory-search"><label for="memory-query">Search project memories</label><input id="memory-query" maxlength="240"><button type="submit">Search</button></form>
68
127
  <details><summary>Record a candidate</summary><form id="memory-create">
@@ -81,10 +140,10 @@
81
140
  <details><summary>Skill proposals</summary><section id="memory-proposals" aria-label="Skill proposals"></section></details>
82
141
  </dialog>
83
142
  <button id="resume-run" type="button" class="primary" hidden>Resume run</button>
84
- <dialog id="drawer" aria-labelledby="run-title"><form id="runner"><div id="run-header"></div><button id="minimize-run" type="button">Minimize</button><section id="run-plan" aria-label="Execution steps" hidden></section><label for="execution-provider" hidden>Local execution provider</label><select id="execution-provider" hidden></select><label for="model" hidden>Local OpenAI model</label><select id="model" hidden></select><details id="openai-setup" hidden><summary>Add OpenAI API key</summary>
143
+ <dialog id="drawer" aria-labelledby="run-title"><form id="runner"><div id="run-header"></div><button id="minimize-run" type="button">Minimize</button><section id="run-plan" aria-label="Execution steps" hidden></section><label for="execution-provider" hidden>Execution provider</label><select id="execution-provider" hidden></select><label for="model" hidden>Local OpenAI model</label><select id="model" hidden></select><details id="openai-setup" hidden><summary>Add OpenAI API key</summary>
85
144
  <p>Save the key on this computer for Studio and Lyra SDK commands run from your VS Code terminal.</p>
86
145
  <label for="openai-key">OpenAI API key</label>
87
146
  <input id="openai-key" type="password" maxlength="503" autocomplete="off" spellcheck="false">
88
147
  <button id="save-openai" type="button">Save key</button><p id="openai-status" role="status"></p>
89
- </details><label id="run-input-label" for="prompt">Input</label><textarea id="prompt" maxlength="4000" rows="6" required></textarea><button class="primary" id="run">Run</button><p role="status" id="run-status"></p><pre id="run-result"></pre></form></dialog>
148
+ </details><label id="run-input-label" for="prompt">Input</label><textarea id="prompt" maxlength="4000" rows="6" required></textarea><button class="primary" id="run">Run</button><button id="cancel-run" type="button" hidden>Cancel run</button><p role="status" id="run-status"></p><pre id="run-result"></pre></form></dialog>
90
149
  </body></html>
@@ -0,0 +1,110 @@
1
+ function node(tag, text) {
2
+ const element = document.createElement(tag);
3
+ element.textContent = text;
4
+ return element;
5
+ }
6
+
7
+ const numbers = new Intl.NumberFormat();
8
+
9
+ export function mountIntelligence(api, showView) {
10
+ const graphContent = document.querySelector("#graph-content");
11
+ const tokenContent = document.querySelector("#token-content");
12
+ const build = document.querySelector("#build-graph");
13
+ let graphRequest = 0;
14
+ let tokenRequest = 0;
15
+
16
+ function renderGraph(result) {
17
+ graphContent.replaceChildren();
18
+ build.disabled = !result.installed;
19
+ if (result.issue || result.graphIssue) graphContent.append(node("p", result.issue ?? result.graphIssue));
20
+ if (!result.graph) {
21
+ if (!result.graphIssue) graphContent.append(node("p", "Build a graph to explore repository symbols and their connections."));
22
+ return;
23
+ }
24
+ const report = node("section", "");
25
+ report.append(node("h2", "GraphSnip report"));
26
+ if (result.report) {
27
+ const updated = new Date(result.report.updatedAt).toLocaleString();
28
+ report.append(node("p", "Generated " + updated + (result.report.stale ? " · Graph has changed since this report." : "")));
29
+ const frame = document.createElement("iframe");
30
+ frame.title = "GraphSnip report";
31
+ frame.className = "graphsnip-report";
32
+ frame.setAttribute("sandbox", "");
33
+ frame.referrerPolicy = "no-referrer";
34
+ frame.src = "/api/graphsnip/report";
35
+ report.append(frame);
36
+ } else {
37
+ report.append(node("p", "Refresh the graph and report, or run agent-lyra graph report in the project terminal."));
38
+ }
39
+ const graph = result.graph;
40
+ graphContent.append(node("p", numbers.format(graph.nodeCount) + " nodes · " + numbers.format(graph.edgeCount) + " connections"));
41
+ if (!graph.nodes.length) { graphContent.append(report); return; }
42
+ const details = node("p", "");
43
+ const related = document.createElement("ul");
44
+ const label = node("label", "Graph node");
45
+ const picker = document.createElement("select");
46
+ picker.replaceChildren(...graph.nodes.map(entry => new Option(entry.label, entry.id)));
47
+ label.append(picker);
48
+ graphContent.append(label, details, related);
49
+ const update = () => {
50
+ const id = picker.value;
51
+ const byId = new Map(graph.nodes.map(entry => [entry.id, entry.label]));
52
+ const neighbors = new Set(graph.links.flatMap(edge => edge.source === id ? [edge.target] : edge.target === id ? [edge.source] : []));
53
+ details.textContent = neighbors.size ? "Connections in this view" : "No connections in this view.";
54
+ related.replaceChildren(...[...neighbors].map(neighbor => node("li", byId.get(neighbor) ?? neighbor)));
55
+ };
56
+ picker.onchange = update;
57
+ update();
58
+ if (graph.nodes.length < graph.nodeCount || graph.links.length < graph.edgeCount) {
59
+ graphContent.append(node("p", "Showing up to 100 nodes and 300 connections. GraphSnip retains the full graph in the project."));
60
+ }
61
+ graphContent.append(report);
62
+ }
63
+
64
+ async function loadGraph(rebuild = false) {
65
+ const request = ++graphRequest;
66
+ build.disabled = true;
67
+ graphContent.replaceChildren(node("p", rebuild ? "Updating graph and report…" : "Checking repository graph…"));
68
+ try {
69
+ const result = await api(rebuild ? "graphsnip/build" : "graphsnip/graph", rebuild ? {} : undefined);
70
+ if (request === graphRequest) renderGraph(result);
71
+ } catch (error) {
72
+ if (request !== graphRequest) return;
73
+ graphContent.replaceChildren(node("p", error.message));
74
+ build.disabled = false;
75
+ }
76
+ }
77
+
78
+ function ledgerSection(title, stats) {
79
+ const section = node("section", "");
80
+ section.append(node("h2", title));
81
+ if (!stats?.calls) {
82
+ section.append(node("p", "No GraphSnip calls recorded."));
83
+ return section;
84
+ }
85
+ for (const [key, label] of [["calls", "Calls"], ["baseline", "Baseline estimated tokens"],
86
+ ["returned", "Returned estimated tokens"], ["saved", "Estimated tokens saved"]]) {
87
+ if (Number.isFinite(stats[key])) section.append(node("p", label + " · " + numbers.format(stats[key])));
88
+ }
89
+ return section;
90
+ }
91
+
92
+ async function loadTokens() {
93
+ const request = ++tokenRequest;
94
+ tokenContent.replaceChildren(node("p", "Reading GraphSnip ledger…"));
95
+ try {
96
+ const result = await api("graphsnip/tokens");
97
+ if (request !== tokenRequest) return;
98
+ tokenContent.replaceChildren();
99
+ if (result.issue) tokenContent.append(node("p", result.issue));
100
+ else tokenContent.append(ledgerSection("Project activity", result.live), ledgerSection("Benchmark activity", result.benchmark));
101
+ } catch (error) {
102
+ if (request === tokenRequest) tokenContent.replaceChildren(node("p", error.message));
103
+ }
104
+ }
105
+
106
+ document.querySelector("#show-graph").onclick = () => { showView("graph"); void loadGraph(); };
107
+ document.querySelector("#show-tokens").onclick = () => { showView("tokens"); void loadTokens(); };
108
+ build.onclick = () => void loadGraph(true);
109
+ document.querySelector("#refresh-tokens").onclick = () => void loadTokens();
110
+ }
@@ -0,0 +1,43 @@
1
+ export function localModelConfiguration(env = process.env) {
2
+ const address = env.LYRA_LOCAL_MODEL_URL?.trim();
3
+ if (!address) return undefined;
4
+ let url;
5
+ try { url = new URL(address); } catch {}
6
+ if (!url || !["http:", "https:"].includes(url.protocol) ||
7
+ !["127.0.0.1", "[::1]"].includes(url.hostname) || url.username || url.password ||
8
+ url.search || url.hash || !["/v1", "/v1/"].includes(url.pathname)) {
9
+ return { issue: "Set LYRA_LOCAL_MODEL_URL to a loopback OpenAI-compatible base URL ending in /v1." };
10
+ }
11
+ const models = [...new Set((env.LYRA_LOCAL_MODELS ?? "").split(",").map(value => value.trim())
12
+ .filter(value => /^[\w./:-]{1,120}$/.test(value)))];
13
+ return {
14
+ endpoint: new URL("chat/completions", url.origin + "/v1/").href,
15
+ models,
16
+ issue: models.length ? undefined : "Set LYRA_LOCAL_MODELS to the installed local model IDs.",
17
+ };
18
+ }
19
+
20
+ export function createLocalModelProvider(configuration, request = fetch) {
21
+ return {
22
+ async complete(payload, { signal } = {}) {
23
+ if (!configuration?.models?.includes(payload.model)) throw new Error("Choose a configured local model.");
24
+ const deadline = AbortSignal.timeout(60_000);
25
+ const response = await request(configuration.endpoint, {
26
+ method: "POST",
27
+ headers: { "Content-Type": "application/json" },
28
+ redirect: "error",
29
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
30
+ body: JSON.stringify({ ...payload, max_tokens: 1024, stream: false }),
31
+ });
32
+ if (!response.ok) throw new Error("Local model request failed (HTTP " + response.status + ").");
33
+ const result = await response.json();
34
+ const text = result.choices?.[0]?.message?.content;
35
+ if (typeof text !== "string" || !text.trim()) throw new Error("The local model returned no text.");
36
+ const { prompt_tokens: inputTokens, completion_tokens: outputTokens } = result.usage ?? {};
37
+ const usage = {};
38
+ if (Number.isSafeInteger(inputTokens) && inputTokens >= 0) usage.inputTokens = inputTokens;
39
+ if (Number.isSafeInteger(outputTokens) && outputTokens >= 0) usage.outputTokens = outputTokens;
40
+ return Object.keys(usage).length ? { text, usage } : { text };
41
+ },
42
+ };
43
+ }
@@ -1,14 +1,41 @@
1
1
  import { openMemoryStore } from "../memory/index.js";
2
+ import { eligibleText } from "../memory/validation.js";
3
+ import { openRunHistory } from "./run-history.js";
2
4
  import { syncMemory } from "../memory/sync.js";
3
5
 
4
6
  export function memoryActions(root) {
5
7
  return new Map([
6
8
  ["/api/memory/list", ({ query = "" }) => useStore(root, store => ({
7
- records: query.trim() ? store.search(query, 50) : store.list(50), stats: store.stats(),
9
+ records: query.trim() ? store.search(query, 50) : store.list(50), stats: store.stats(), engine: store.engine,
8
10
  }))],
9
11
  ["/api/memory/record", body => useStore(root, store => store.record({
10
12
  ...body, evidence: typeof body.evidence === "string" ? body.evidence.split(",").map(value => value.trim()).filter(Boolean) : body.evidence,
11
13
  }))],
14
+ ["/api/memory/suggestions", async ({ runId }) => {
15
+ if (process.env.LYRA_MEMORY === "off" || typeof runId !== "string" || !/^[a-f0-9-]{36}$/i.test(runId)) return { suggestions: [] };
16
+ const history = await openRunHistory(root);
17
+ try { return { suggestions: history.suggestions(runId) }; }
18
+ finally { history.close(); }
19
+ }],
20
+ ["/api/memory/record-run", async ({ runId, type, title, learning, evidence }) => {
21
+ if (!/^[a-f0-9-]{36}$/i.test(runId ?? "")) throw new Error("Choose a completed local run.");
22
+ if (!["corrective", "episodic", "semantic", "procedural"].includes(type)) {
23
+ throw new Error("Choose a supported memory type.");
24
+ }
25
+ if (typeof title !== "string" || typeof learning !== "string" || !eligibleText(title + " " + learning)) {
26
+ throw new Error("Use reviewed learning text without credentials or instruction overrides.");
27
+ }
28
+ const extra = typeof evidence === "string" ? evidence.split(",").map(value => value.trim()).filter(Boolean) : [];
29
+ const history = await openRunHistory(root);
30
+ try {
31
+ return await useStore(root, store => history.withCompletedRun(runId, () => {
32
+ const value = { type, title: title.trim(), learning: learning.trim() };
33
+ const existing = store.findLearning(value);
34
+ if (existing) return { ...existing, reused: true };
35
+ return store.record({ ...value, evidence: [...new Set(["run:" + runId, ...extra])] });
36
+ }));
37
+ } finally { history.close(); }
38
+ }],
12
39
  ["/api/memory/archive", ({ id }) => useStore(root, store => {
13
40
  const record = store.archive(id);
14
41
  if (!record) throw new Error("Memory record was not found.");