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
@@ -1,4 +1,6 @@
1
+ import { mountIntelligence } from "./intelligence.js";
1
2
  import { mountWorkflowEditor } from "./workflow-editor.js";
3
+ import { mountHistoryPanel } from "./history-panel.js";
2
4
  import { mountMemoryPanel } from "./memory-panel.js";
3
5
  import { renderAgentCard, renderRunHeader } from "./agent-ui.js";
4
6
 
@@ -7,16 +9,16 @@ const element = (tag, text) => Object.assign(document.createElement(tag), text =
7
9
  function dom(tag, props, ...children) {
8
10
  const node = document.createElement(tag);
9
11
  for (const [key, value] of Object.entries(props)) {
10
- if (value == null) continue;
12
+ if (value == null || key === "key") continue;
11
13
  if (key === "onClick") node.onclick = value;
12
- else if (key === "aria-label") node.setAttribute(key, value);
14
+ else if (key.startsWith("aria-") || key.startsWith("data-")) node.setAttribute(key, value);
13
15
  else node[key] = value;
14
16
  }
15
17
  node.append(...children.filter(child => child != null && child !== false && child !== ""));
16
18
  return node;
17
19
  }
18
20
 
19
- const agentSources = { local: "Local agent", cloud: "Cloud agent", python: "Python agent", framework: "Registered framework agent" };
21
+ const agentSources = { local: "Local agent", cloud: "Cloud agent", python: "Python agent", programmatic: "Executable Lyra agent", framework: "Registered framework agent" };
20
22
  const names = { heading:"Heading", text:"Text", input:"Text input", textarea:"Text area", button:"Run button", "agent-card":"Agent card", output:"Output" };
21
23
  const componentMarks = {
22
24
  heading: "H", text: "≡", input: "▏", textarea: "▤",
@@ -46,18 +48,120 @@ async function api(path, data) {
46
48
  return payload;
47
49
  }
48
50
 
49
- mountMemoryPanel(api);
51
+ const openMemoryPanel = mountMemoryPanel(api);
52
+ const workbenchViews = {
53
+ mission: ["open-history", "history-panel"],
54
+ registry: ["show-registry", "library"],
55
+ layout: ["show-layout", "canvas-panel"],
56
+ workflow: ["show-workflow", "workflow-panel"],
57
+ cloud: ["show-cloud", "cloud-settings"],
58
+ graph: ["show-graph", "graph-panel"],
59
+ tokens: ["show-tokens", "token-panel"],
60
+ };
61
+ let view = "layout";
62
+ let layoutLibraryView = libraryView;
63
+ let layoutSearch = "";
64
+ let registrySource = "";
65
+ let discoveryRequest = 0;
66
+
67
+ async function refreshDiscovery() {
68
+ const current = ++discoveryRequest;
69
+ const region = $("#discovery-status");
70
+ region.replaceChildren(element("p", "Discovering code-defined agents…"));
71
+ try {
72
+ const { candidates } = await api("code-agents");
73
+ if (current !== discoveryRequest) return;
74
+ region.replaceChildren();
75
+ if (!candidates.length) return;
76
+ const review = $("#discovery-review");
77
+ region.append(dom("div", { className: "discovery-callout" },
78
+ dom("div", {}, element("strong", candidates.length + (candidates.length === 1 ? " agent ready to add" : " agents ready to add")),
79
+ element("p", "Found code-defined agents in this project.")),
80
+ button("Review and add", () => {
81
+ const items = $("#discovery-items");
82
+ const submit = $("#add-discovered");
83
+ const close = $("#close-discovery");
84
+ const error = $("#discovery-error");
85
+ items.replaceChildren();
86
+ error.textContent = "";
87
+ const checks = candidates.map(candidate => {
88
+ const input = dom("input", { type: "checkbox", value: candidate.id });
89
+ input.checked = true;
90
+ items.append(dom("label", { className: "discovery-option" }, input,
91
+ dom("span", {}, element("strong", candidate.name), element("code", candidate.file))));
92
+ return input;
93
+ });
94
+ const selected = () => checks.filter(input => input.checked).map(input => input.value);
95
+ const update = () => {
96
+ const count = selected().length;
97
+ submit.disabled = !count;
98
+ submit.textContent = "Add " + count + (count === 1 ? " agent" : " agents");
99
+ };
100
+ checks.forEach(input => { input.onchange = update; });
101
+ close.onclick = () => review.close();
102
+ submit.onclick = async () => {
103
+ const ids = selected();
104
+ submit.disabled = close.disabled = true;
105
+ checks.forEach(input => { input.disabled = true; });
106
+ submit.textContent = "Adding " + ids.length + (ids.length === 1 ? " agent…" : " agents…");
107
+ error.textContent = "";
108
+ try {
109
+ const { added } = await api("code-agents/add", { ids });
110
+ await load({ catalogOnly: true });
111
+ review.close();
112
+ announce(added ? "Added " + added + " to Agent Registry." : "Registry is already up to date.");
113
+ void refreshDiscovery();
114
+ } catch (failure) { error.textContent = failure.message; }
115
+ finally {
116
+ close.disabled = false;
117
+ checks.forEach(input => { input.disabled = false; });
118
+ update();
119
+ }
120
+ };
121
+ update();
122
+ review.showModal();
123
+ })));
124
+ } catch (error) {
125
+ if (current === discoveryRequest) region.replaceChildren(element("p", error.message));
126
+ }
127
+ }
128
+
129
+ function showView(next) {
130
+ const search = $("#library-search");
131
+ if (view === "layout" && next !== "layout") {
132
+ layoutLibraryView = libraryView;
133
+ layoutSearch = search.value;
134
+ }
135
+ if (next !== view && (next === "layout" || next === "registry")) {
136
+ libraryView = next === "registry" ? "agents" : layoutLibraryView;
137
+ search.value = next === "registry" ? "" : layoutSearch;
138
+ }
139
+ view = next;
140
+ if (next !== "mission" && location.hash.startsWith("#run=")) {
141
+ history.replaceState(history.state, "", location.pathname + location.search);
142
+ }
143
+ for (const [key, [control, panel]] of Object.entries(workbenchViews)) {
144
+ $("#" + control).setAttribute("aria-pressed", String(next === key));
145
+ $("#" + panel).hidden = next !== key;
146
+ }
147
+ $("#library").hidden = next !== "layout" && next !== "registry";
148
+ $("#library").classList.toggle("registry-view", next === "registry");
149
+ $("#library-title").textContent = next === "registry" ? "Agent Registry" : "Project library";
150
+ $("#library-tabs").hidden = next === "registry";
151
+ $("#discovery-status").hidden = next !== "registry";
152
+ if (next === "registry") void refreshDiscovery();
153
+ $("#refresh").hidden = next !== "registry";
154
+ $("#save").hidden = next !== "layout";
155
+ if (next !== "layout") closeInspector();
156
+ if (next === "registry" || next === "layout") renderCatalog();
157
+ }
158
+
159
+ mountIntelligence(api, showView);
160
+ const syncHistoryLocation = mountHistoryPanel(api, () => showView("mission"), dom, openMemoryPanel);
50
161
  const workflowEditor = mountWorkflowEditor({
51
162
  api, project: () => project, reloadCatalog: () => load({ catalogOnly: true }),
52
163
  run: id => openRun(["workflow:" + id]),
53
- switchView: editing => {
54
- $("#save").hidden = $("#canvas-panel").hidden = editing;
55
- $("#library").hidden = editing;
56
- if (editing) closeInspector();
57
- $("#workflow-panel").hidden = !editing;
58
- $("#show-layout").setAttribute("aria-pressed", String(!editing));
59
- $("#show-workflow").setAttribute("aria-pressed", String(editing));
60
- },
164
+ switchView: editing => showView(editing ? "workflow" : "layout"),
61
165
  });
62
166
 
63
167
  function announce(message) { $("#status").textContent = message; }
@@ -237,14 +341,25 @@ function renderCatalog() {
237
341
  const id = libraryView;
238
342
  const section = $("#" + id);
239
343
  const query = search.value.trim().toLowerCase();
240
- const rows = project[id].filter(row => !row.linkedLocalId && [row.name, row.source, row.framework, agentSources[row.source]]
344
+ const inRegistry = view === "registry" && id === "agents";
345
+ const rows = project[id].filter(row => !row.linkedLocalId && (!inRegistry || !registrySource || (registrySource === "cloud" ? row.source === "cloud" : row.source !== "cloud")) && [row.name, row.source, row.framework, agentSources[row.source]]
241
346
  .some(value => value?.toLowerCase().includes(query)));
242
347
  const expanded = new Set([...section.querySelectorAll(".agent-options[open]")].map(item => item.dataset.agent));
243
348
  section.replaceChildren();
244
- if (id === "agents" && !project.cloudConnected) {
349
+ const grid = inRegistry ? dom("div", { className: "registry-grid" }) : section;
350
+ if (inRegistry) {
351
+ const filters = dom("div", { className: "workbench-filters", "aria-label": "Agent source filters" });
352
+ for (const [value, label] of [["", "All"], ["local", "Local"], ["cloud", "Cloud"]]) {
353
+ const control = button(label, () => { registrySource = value; renderCatalog(); });
354
+ control.setAttribute("aria-pressed", String(registrySource === value));
355
+ filters.append(control);
356
+ }
357
+ section.append(filters, grid);
358
+ }
359
+ if (id === "agents" && !project.cloudConnected && !inRegistry) {
245
360
  const callout = dom("div", { className: "cloud-callout" },
246
361
  element("p", "Connect to AgentLyra Cloud to pull, push, and sync agents."),
247
- button("Connect to Cloud", openCloudSetup));
362
+ button("Open Cloud Sync", () => showView("cloud")));
248
363
  section.append(callout);
249
364
  }
250
365
  if (id === "skills" && rows.length) section.append(element("p",
@@ -297,15 +412,28 @@ function renderCatalog() {
297
412
  run.append(dom("span", { className: "play-icon" }));
298
413
  const entry = dom("article", { className: "library-entry" },
299
414
  dom("div", { className: "agent-row" }, dom("div", { className: "agent-label" }, name, metadata), run));
415
+ let options;
300
416
  if (push || pull || sync) {
301
417
  const control = dom("summary", { className: "agent-icon", title: "Cloud actions",
302
418
  "aria-label": "Cloud actions for " + row.name }, "⋯");
303
- const options = dom("details", { className: "agent-options", open: expanded.has(row.id) },
419
+ options = dom("details", { className: "agent-options", open: expanded.has(row.id) },
304
420
  control, dom("div", { className: "actions" }, push, pull, sync));
305
421
  options.dataset.agent = row.id;
306
422
  entry.append(options);
307
423
  }
308
- section.append(entry);
424
+ if (inRegistry) {
425
+ const description = row.description || row.file || ({
426
+ local: "Text agent in this project", cloud: "Agent from your Cloud workspace",
427
+ programmatic: "Code-defined agent in this project", framework: "Registered framework agent", python: "Python agent in this project",
428
+ })[row.source];
429
+ grid.append(renderAgentCard(dom, { name: row.name, source,
430
+ header: dom("div", { className: "registry-card-heading" },
431
+ dom("span", { className: "registry-icon", "aria-hidden": "true" }, row.file ? "‹/›" : "◇"),
432
+ dom("div", {}, name, metadata)),
433
+ details: element("p", description), extraAction: options,
434
+ runIcon: dom("span", { className: "play-icon", "aria-hidden": "true" }), onRun: () => openRun([row.id]),
435
+ }));
436
+ } else section.append(entry);
309
437
  continue;
310
438
  }
311
439
  const card = element("article");
@@ -415,15 +543,18 @@ async function openRun(targets, input = "", outputId = "", buttonId) {
415
543
  }
416
544
  plan.replaceChildren(element("h2", "Execution steps"), list);
417
545
  plan.hidden = false;
418
- providerPicker.replaceChildren(...(setup.providers || []).map(id => new Option(id === "openai" ? "Local OpenAI API" : id === "cloud" ? "Lyra Cloud" : id + " CLI", id)));
546
+ providerPicker.replaceChildren(...(setup.providers || []).map(id => new Option(id === "openai" ? "Local OpenAI API" : id === "cloud" ? "Lyra Cloud" : id === "vscode" ? "VS Code model" : id === "local-model" ? "Local model server" : id + " CLI", id)));
419
547
  providerPicker.value = setup.provider || "";
420
548
  providerPicker.hidden = providerLabel.hidden = !setup.providers?.length;
421
549
  const previousModel = picker.value;
422
- picker.replaceChildren(...setup.models.map(model => new Option(model, model)));
550
+ modelLabel.textContent = setup.provider === "vscode" ? "Authorized VS Code model" : setup.provider === "local-model" ? "Local model" : "Local OpenAI model";
551
+ picker.replaceChildren(...setup.models.map(model => new Option(setup.ideModelName && setup.provider === "vscode"
552
+ ? setup.ideModelName : model, model)));
423
553
  if (setup.models.includes(previousModel)) picker.value = previousModel;
424
554
  picker.hidden = modelLabel.hidden = !setup.needsModel;
425
555
  $("#openai-setup").hidden = !setup.needsOpenAIKey || project.preview || project.exported;
426
556
  action.inputKind = setup.inputKind;
557
+ action.frameworkOnly = setup.frameworkOnly;
427
558
  if (setup.inputKind === "json") $("#run-input-label").textContent = "JSON input";
428
559
  action.ready = setup.issues.length === 0;
429
560
  $("#run-status").textContent = setup.issues.join(" ");
@@ -470,6 +601,35 @@ function showRunResults({ answers, traceId, steps }) {
470
601
  $("#run-result").textContent = lines.join("\n\n");
471
602
  }
472
603
 
604
+ async function streamRun(body) {
605
+ const response = await fetch("/api/run", {
606
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
607
+ });
608
+ if (!response.ok) throw new Error((await response.json()).error);
609
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
610
+ let remaining = "";
611
+ try {
612
+ for (;;) {
613
+ const { value, done } = await reader.read();
614
+ if (done) break;
615
+ const lines = (remaining + value).split("\n");
616
+ remaining = lines.pop();
617
+ for (const line of lines) {
618
+ const event = JSON.parse(line);
619
+ if (event.type === "event" && event.event.type === "step.started") {
620
+ $("#run-status").textContent = "Running step " + event.event.index + "…";
621
+ }
622
+ if (event.type === "delta") $("#run-result").append(document.createTextNode(event.text));
623
+ if (event.type === "result") return event.result;
624
+ if (event.type === "error") throw Object.assign(new Error(event.message), { progress: event.progress });
625
+ }
626
+ }
627
+ throw new Error("The run stream ended before completion.");
628
+ } finally {
629
+ await reader.cancel().catch(() => {});
630
+ }
631
+ }
632
+
473
633
  $("#runner").onsubmit = async event => {
474
634
  event.preventDefault();
475
635
  if (!pending?.ready || runInProgress) return;
@@ -487,8 +647,21 @@ $("#runner").onsubmit = async event => {
487
647
  $("#close-run").disabled = true;
488
648
  $("#run-status").textContent = "Running…";
489
649
  $("#run-result").textContent = "";
650
+ const body = { targets: pending.targets, buttonId: pending.buttonId, revision: pending.revision,
651
+ input: prompt.value, model: $("#model").value, provider: $("#execution-provider").value };
652
+ const cancel = $("#cancel-run");
653
+ body.streamId = crypto.randomUUID();
654
+ if (body.provider === "vscode" || pending.frameworkOnly) {
655
+ cancel.hidden = false;
656
+ cancel.disabled = false;
657
+ cancel.onclick = async () => {
658
+ cancel.disabled = true;
659
+ try { await api("cancel-run", { streamId: body.streamId }); }
660
+ catch (error) { if (runInProgress) $("#run-status").textContent = error.message; }
661
+ };
662
+ }
490
663
  try {
491
- const result = await api("run", { targets: pending.targets, buttonId: pending.buttonId, revision: pending.revision, input: prompt.value, model: $("#model").value, provider: $("#execution-provider").value });
664
+ const result = await streamRun(body);
492
665
  showRunResults(result);
493
666
  if (pending.outputId) outputs.set(pending.outputId, result.answers.at(-1).output);
494
667
  renderCanvas();
@@ -498,6 +671,8 @@ $("#runner").onsubmit = async event => {
498
671
  $("#run-status").textContent = error.message;
499
672
  } finally {
500
673
  runInProgress = false;
674
+ cancel.hidden = true;
675
+ cancel.onclick = null;
501
676
  $("#run").disabled = false;
502
677
  $("#close-run").disabled = false;
503
678
  }
@@ -535,11 +710,16 @@ async function load({ catalogOnly = false } = {}) {
535
710
  $("#cloud-state").textContent = project.cloudConnected ? "Cloud connected" : "Working locally";
536
711
  $("#pull").hidden = !project.cloudConnected;
537
712
  $("#connect-cloud").hidden = project.cloudConnected;
713
+ $("#pause-cloud").hidden = !project.cloudConnected;
714
+ $("#cloud-settings-description").textContent = project.cloudConnected
715
+ ? "Pull your Cloud catalog or sync edits from the Agent Registry. Work locally pauses Cloud actions and keeps your saved key."
716
+ : "Your project is working locally. Connect your AgentLyra account to sync supported agents, workflows, teams, and skills.";
538
717
  $("#open-memory").hidden = Boolean(project.exported || project.preview);
718
+ $("#open-history").hidden = Boolean(project.exported || project.preview);
539
719
  if (project.exported || project.preview) {
540
720
  document.body.classList.add("exported");
541
721
  document.title = project.name;
542
- $("main h1").textContent = project.name;
722
+ $("#canvas-panel h1").textContent = project.name;
543
723
  } else {
544
724
  renderCatalog();
545
725
  renderInspector();
@@ -608,7 +788,9 @@ $("#canvas").ondrop = event => {
608
788
  selected = node.id;
609
789
  change();
610
790
  };
611
- $("#refresh").onclick = () => load({ catalogOnly: dirty }).then(() => announce("Project refreshed.")).catch(error => announce(error.message));
791
+ $("#show-registry").onclick = () => showView("registry");
792
+ $("#show-cloud").onclick = () => showView("cloud");
793
+ $("#refresh").onclick = () => load({ catalogOnly: true }).then(() => { announce("Project refreshed."); if (view === "registry") void refreshDiscovery(); }).catch(error => announce(error.message));
612
794
  function openCloudSetup() {
613
795
  $("#cloud-key").value = "";
614
796
  $("#cloud-key").required = !project.hasCloudKey;
@@ -619,6 +801,16 @@ function openCloudSetup() {
619
801
  $("#cloud-setup").showModal();
620
802
  }
621
803
  $("#connect-cloud").onclick = openCloudSetup;
804
+ $("#pause-cloud").onclick = async () => {
805
+ const control = $("#pause-cloud");
806
+ control.disabled = true;
807
+ try {
808
+ await api("work-locally", {});
809
+ await load({ catalogOnly: true });
810
+ announce("Working locally. Cloud sync is paused.");
811
+ } catch (error) { announce(error.message); }
812
+ finally { control.disabled = false; }
813
+ };
622
814
  $("#close-cloud").onclick = () => $("#cloud-setup").close();
623
815
  $("#cloud-setup").addEventListener("close", () => { $("#cloud-key").value = ""; });
624
816
  $("#cloud-form").onsubmit = async event => {
@@ -654,4 +846,8 @@ $("#save").onclick = async () => {
654
846
  finally { $("#save").disabled = false; }
655
847
  };
656
848
  window.addEventListener("beforeunload", event => { if (dirty || workflowEditor.dirty()) { event.preventDefault(); event.returnValue = ""; } });
657
- load().catch(error => announce(error.message));
849
+ load().then(() => {
850
+ if (project.exported || project.preview) return;
851
+ showView("mission");
852
+ return syncHistoryLocation();
853
+ }).catch(error => announce(error.message));
@@ -0,0 +1,81 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
+ import { basename, join } from "node:path";
4
+
5
+ const excluded = new Set(["node_modules", "vendor", "dist", "build", "coverage", "graphify-out", "__pycache__"]);
6
+ const sourcePath = /^(?:[a-zA-Z0-9_.-]+\/)*[a-zA-Z0-9_-]+\.(?:mjs|js|mts|ts|py)$/;
7
+
8
+ export async function resolveAgentSource(root, file, projectRelative = false) {
9
+ if (!sourcePath.test(file) || file.split("/").some(part => part === "." || part === "..")) {
10
+ throw new Error("Use a project-relative agent source path.");
11
+ }
12
+ const parts = projectRelative ? file.split("/") : [".lyra", "agents", file];
13
+ let current = root;
14
+ for (const [index, part] of parts.entries()) {
15
+ current = join(current, part);
16
+ const stat = await lstat(current);
17
+ if (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory()) {
18
+ throw new Error("Use a regular agent source file inside this project.");
19
+ }
20
+ }
21
+ return current;
22
+ }
23
+
24
+ export async function discoverCodeAgents(root, agents) {
25
+ const entries = new Set([...agents.values()].filter(agent => agent.source === "programmatic")
26
+ .map(agent => agent.projectRelative ? agent.file : ".lyra/agents/" + agent.file));
27
+ const found = [];
28
+ let scanned = 0;
29
+ const queue = [{ path: "", depth: 0 }];
30
+ while (queue.length && found.length < 40 && scanned < 1500) {
31
+ const { path, depth } = queue.shift();
32
+ const directory = join(root, path);
33
+ if (!(await lstat(directory).catch(() => null))?.isDirectory()) continue;
34
+ for (const entry of await readdir(directory, { withFileTypes: true }).catch(() => [])) {
35
+ if (++scanned > 1500 || found.length >= 40) break;
36
+ const file = path ? path + "/" + entry.name : entry.name;
37
+ if (entry.isDirectory() && depth < 5 && queue.length < 300 && !excluded.has(entry.name) &&
38
+ (!entry.name.startsWith(".") || [".lyra", ".lyra/agents"].includes(file)) &&
39
+ (path !== ".lyra" || entry.name === "agents")) queue.push({ path: file, depth: depth + 1 });
40
+ if (!entry.isFile() || !sourcePath.test(file) || entries.has(file)) continue;
41
+ const full = join(root, file);
42
+ const stat = await lstat(full).catch(() => null);
43
+ if (!stat?.isFile() || stat.size > 128 * 1024) continue;
44
+ const source = await readFile(full, "utf8").catch(() => "");
45
+ const python = file.endsWith(".py");
46
+ if (python ? !/^from lyra import [^\n]*\bAgent\b/m.test(source) || !/^agent\s*=\s*Agent\(/m.test(source)
47
+ : !/import\s*\{[^}]*\bAgent\b[^}]*\}\s*from\s*["']agent-lyra["']/.test(source) ||
48
+ !/^\s*export\s+const\s+agent\s*=\s*new\s+Agent(?:<[^\r\n>]{1,200}>)?\s*\(/m.test(source)) continue;
49
+ const id = "code-" + createHash("sha256").update(file).digest("hex").slice(0, 20);
50
+ const name = basename(file).replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ");
51
+ found.push({ id, name, file, runtime: python ? "lyra-python" : "lyra-node", projectRelative: true,
52
+ input: /\b(?:inputSchema\s*:|input_schema\s*=)\s*\{\s*["']?type["']?\s*:\s*["'](?:object|array|number|integer|boolean|null)["']/.test(source) ? "json" : "text" });
53
+ }
54
+ }
55
+ return found;
56
+ }
57
+
58
+ export async function registerCodeAgents(root, ids, agents) {
59
+ if (!Array.isArray(ids) || !ids.length || ids.length > 40 || ids.some(id => !/^code-[a-f\d]{20}$/.test(id))) {
60
+ throw new Error("Select discovered agents to add.");
61
+ }
62
+ const candidates = await discoverCodeAgents(root, agents);
63
+ const chosen = candidates.filter(candidate => ids.includes(candidate.id));
64
+ const folder = join(root, ".lyra");
65
+ const directory = join(folder, "agents");
66
+ for (const path of [folder, directory]) {
67
+ await mkdir(path).catch(error => { if (error.code !== "EEXIST") throw error; });
68
+ if (!(await lstat(path)).isDirectory()) throw new Error("Use regular .lyra/agents directories.");
69
+ }
70
+ let added = 0;
71
+ for (const candidate of chosen) {
72
+ try {
73
+ await resolveAgentSource(root, candidate.file, true);
74
+ await writeFile(join(directory, candidate.id + ".json"), JSON.stringify(candidate, null, 2) + "\n", { flag: "wx" });
75
+ added++;
76
+ } catch (error) {
77
+ if (!["EEXIST", "ENOENT"].includes(error.code)) throw error;
78
+ }
79
+ }
80
+ return { added };
81
+ }
@@ -5,12 +5,12 @@ import { readCatalog, resolveSequence, validateLayout, validateRunBindings } fro
5
5
 
6
6
  const runtime = [
7
7
  "resource-files.js",
8
- "studio/server.js", "studio/memory-actions.js", "studio/memory-panel.js", "studio/project.js", "studio/sync.js", "studio/index.html", "studio/lyra-icon.png",
9
- "studio/browser.js", "studio/workflow-editor.js", "studio/cli-providers.js", "studio/studio.css", "studio/agent-ui.js", "studio/agent-ui.css", "app-builder/saved-app.js",
10
- "memory/index.js", "memory/local-store.js", "memory/cloud-sync-actions.js", "memory/validation.js", "memory/proposals.js", "memory/sync.js", "memory/lifecycle.js", "memory/contract.json",
8
+ "studio/server.js", "studio/memory-actions.js", "studio/memory-panel.js", "studio/history-panel.js", "studio/intelligence.js", "studio/graphsnip-workbench.js", "studio/mission-ui.js", "studio/mission-ui.css", "studio/project.js", "studio/sync.js", "studio/index.html", "studio/lyra-icon.png",
9
+ "studio/browser.js", "studio/workflow-editor.js", "studio/cli-providers.js", "studio/ide-provider.js", "studio/local-provider.js", "studio/run-history.js", "studio/studio.css", "studio/agent-ui.js", "studio/agent-ui.css", "studio/code-discovery.js", "app-builder/saved-app.js",
10
+ "memory/index.js", "memory/external-engine.js", "memory/UPSTREAM.json", "memory/local-store.js", "memory/cloud-sync-actions.js", "memory/validation.js", "memory/proposals.js", "memory/sync.js", "memory/lifecycle.js", "memory/contract.json",
11
11
  "framework/agent.js", "framework/run.py", "framework/mda.js",
12
- "intelligence/lifecycle.js", "intelligence/graphsnip-provider.js",
13
- "runtime/local-cli.js", "runtime/run-agent.js", "studio/session.js", "studio/push.js", "studio/workflow-sync.js", "studio/pull-agent.js", "studio/python-agent.js", "studio/python-agent.py",
12
+ "intelligence/lifecycle.js", "intelligence/graphsnip-provider.js", "intelligence/graph-setup.js",
13
+ "runtime/local-cli.js", "runtime/run-agent.js", "studio/session.js", "studio/push.js", "studio/workflow-sync.js", "studio/pull-agent.js", "studio/python-agent.js", "studio/python-agent.py", "studio/programmatic.js", "studio/programmatic-runner.mjs",
14
14
  ];
15
15
 
16
16
  export async function exportStudioApp(app, root, directory) {
@@ -40,6 +40,9 @@ export async function exportStudioApp(app, root, directory) {
40
40
  });
41
41
  }
42
42
  }
43
+ if ([...agents.values()].some(agent => agent.source === "programmatic")) {
44
+ throw new Error("Executable Lyra agents run from their source project. Use Studio or app preview there.");
45
+ }
43
46
  if ([...agents.values()].some(agent => agent.source === "framework")) {
44
47
  throw new Error("Registered framework agents run from their source project. Use Studio or app preview there.");
45
48
  }
@@ -0,0 +1,72 @@
1
+ import { lstat, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { graphSnipCommand, graphSnipStatus, refreshGraphSnip } from "../intelligence/graph-setup.js";
4
+
5
+ const name = value => typeof value === "string" ? value.slice(0, 160) : String(value ?? "").slice(0, 160);
6
+
7
+ async function graphReportFile(root) {
8
+ const folder = join(root, ".graphsnip");
9
+ const path = join(folder, "dashboard.html");
10
+ try {
11
+ if (!(await lstat(folder)).isDirectory()) return null;
12
+ const stat = await lstat(path);
13
+ if (!stat.isFile() || stat.size > 4 * 1024 * 1024) return null;
14
+ return { path, updatedAt: stat.mtimeMs };
15
+ } catch { return null; }
16
+ }
17
+
18
+ export async function readGraphReport(root) {
19
+ const report = await graphReportFile(root);
20
+ return report ? readFile(report.path, "utf8") : null;
21
+ }
22
+
23
+ export async function knowledgeGraph(root) {
24
+ const dependency = await graphSnipStatus(root);
25
+ const folder = join(root, "graphify-out");
26
+ const path = join(folder, "graph.json");
27
+ try {
28
+ if (!(await lstat(folder)).isDirectory()) throw new Error();
29
+ const file = await lstat(path);
30
+ if (!file.isFile() || file.size > 16 * 1024 * 1024) throw new Error();
31
+ const graph = JSON.parse(await readFile(path, "utf8"));
32
+ const edges = graph.links ?? graph.edges;
33
+ if (!Array.isArray(graph.nodes) || !Array.isArray(edges)) throw new Error();
34
+ const nodes = graph.nodes.slice(0, 100).map(node => ({ id: name(node.id), label: name(node.label ?? node.id) }));
35
+ const ids = new Set(nodes.map(node => node.id));
36
+ const links = [];
37
+ for (const edge of edges) {
38
+ const source = name(edge.source);
39
+ const target = name(edge.target);
40
+ if (ids.has(source) && ids.has(target)) links.push({ source, target });
41
+ if (links.length >= 300) break;
42
+ }
43
+ const report = await graphReportFile(root);
44
+ return { ...dependency, report: report && { updatedAt: report.updatedAt, stale: report.updatedAt < file.mtimeMs }, graph: { nodeCount: graph.nodes.length, edgeCount: edges.length, nodes, links } };
45
+ } catch (error) {
46
+ return { ...dependency, graph: null, ...(error.code === "ENOENT" ? {} : { graphIssue: "The graph is unreadable or exceeds the Workbench size limit." }) };
47
+ }
48
+ }
49
+
50
+ export async function buildKnowledgeGraph(root) {
51
+ const dependency = await graphSnipStatus(root);
52
+ if (!dependency.installed) throw new Error(dependency.issue);
53
+ try {
54
+ await refreshGraphSnip(root);
55
+ } catch {
56
+ throw new Error("GraphSnip could not update the graph or report. Run agent-lyra graph build and agent-lyra graph report in the project terminal for details.");
57
+ }
58
+ return knowledgeGraph(root);
59
+ }
60
+
61
+ export async function graphTokenLedger(root) {
62
+ const dependency = await graphSnipStatus(root);
63
+ if (!dependency.installed) return dependency;
64
+ try {
65
+ const result = JSON.parse(await graphSnipCommand(root, ["stats", "--json"]));
66
+ const projectLedger = group => Object.fromEntries(["calls", "baseline", "returned", "saved", "pct", "usd_saved"]
67
+ .filter(key => Number.isFinite(group?.[key])).map(key => [key, group[key]]));
68
+ return { ...dependency, live: projectLedger(result.live), benchmark: projectLedger(result.bench) };
69
+ } catch {
70
+ return { ...dependency, issue: "GraphSnip's project ledger could not be read." };
71
+ }
72
+ }