agent-lyra 0.7.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +301 -276
  3. package/bin/agent-lyra.js +51 -51
  4. package/bin/lyra-oss-preview.js +16 -16
  5. package/package.json +60 -60
  6. package/src/app-builder/export.js +109 -109
  7. package/src/app-builder/gateway.js +62 -62
  8. package/src/app-builder/init.js +115 -72
  9. package/src/app-builder/manifest-contract.js +46 -46
  10. package/src/app-builder/native-adapter.js +29 -29
  11. package/src/app-builder/preview.js +35 -31
  12. package/src/app-builder/publish.js +14 -14
  13. package/src/app-builder/saved-app.js +70 -70
  14. package/src/app-builder/saved-preview-browser.js +33 -33
  15. package/src/app-builder/saved-preview.html +24 -24
  16. package/src/app-builder/saved-preview.js +61 -61
  17. package/src/app-builder/support-manifest.js +50 -50
  18. package/src/app-builder/support-template/manifest.json +55 -55
  19. package/src/app-builder/support-template/support-preview.html +56 -56
  20. package/src/app-builder/support-template/support-preview.js +37 -37
  21. package/src/app-builder/support-template/support-preview.mjs +67 -67
  22. package/src/app-builder/support-template/support-workflow.mjs +36 -36
  23. package/src/app-builder/use.js +37 -37
  24. package/src/app-builder/validate.js +31 -21
  25. package/src/app-builder/value-schema.js +37 -37
  26. package/src/catalog.js +147 -147
  27. package/src/coding/catalog.js +56 -56
  28. package/src/coding/cloud-catalog.js +64 -64
  29. package/src/coding/detect-stack.mjs +110 -110
  30. package/src/coding/export.js +133 -133
  31. package/src/coding/setup.js +175 -175
  32. package/src/coding/skills/lyra-android/SKILL.md +37 -37
  33. package/src/coding/skills/lyra-angular/SKILL.md +37 -37
  34. package/src/coding/skills/lyra-cucumber/SKILL.md +37 -37
  35. package/src/coding/skills/lyra-dbt/SKILL.md +37 -37
  36. package/src/coding/skills/lyra-django/SKILL.md +37 -37
  37. package/src/coding/skills/lyra-docker/SKILL.md +37 -37
  38. package/src/coding/skills/lyra-dotnet/SKILL.md +37 -37
  39. package/src/coding/skills/lyra-express/SKILL.md +37 -37
  40. package/src/coding/skills/lyra-fastapi/SKILL.md +37 -37
  41. package/src/coding/skills/lyra-flutter/SKILL.md +37 -37
  42. package/src/coding/skills/lyra-github-actions/SKILL.md +37 -37
  43. package/src/coding/skills/lyra-gitlab-ci/SKILL.md +37 -37
  44. package/src/coding/skills/lyra-go/SKILL.md +37 -37
  45. package/src/coding/skills/lyra-ios/SKILL.md +37 -37
  46. package/src/coding/skills/lyra-kubernetes/SKILL.md +37 -37
  47. package/src/coding/skills/lyra-mongodb/SKILL.md +37 -37
  48. package/src/coding/skills/lyra-mysql/SKILL.md +37 -37
  49. package/src/coding/skills/lyra-nextjs/SKILL.md +37 -37
  50. package/src/coding/skills/lyra-node/SKILL.md +37 -37
  51. package/src/coding/skills/lyra-playwright/SKILL.md +37 -37
  52. package/src/coding/skills/lyra-postgresql/SKILL.md +37 -37
  53. package/src/coding/skills/lyra-python/SKILL.md +37 -37
  54. package/src/coding/skills/lyra-react/SKILL.md +37 -37
  55. package/src/coding/skills/lyra-react-native/SKILL.md +37 -37
  56. package/src/coding/skills/lyra-redis/SKILL.md +37 -37
  57. package/src/coding/skills/lyra-rust/SKILL.md +37 -37
  58. package/src/coding/skills/lyra-spark/SKILL.md +37 -37
  59. package/src/coding/skills/lyra-spring-boot/SKILL.md +37 -37
  60. package/src/coding/skills/lyra-svelte/SKILL.md +37 -37
  61. package/src/coding/skills/lyra-terraform/SKILL.md +37 -37
  62. package/src/coding/skills/lyra-typescript/SKILL.md +37 -37
  63. package/src/coding/skills/lyra-vue/SKILL.md +37 -37
  64. package/src/framework/agent.js +181 -173
  65. package/src/framework/mda.js +65 -0
  66. package/src/framework/run.py +111 -111
  67. package/src/gated/hostedAgents.js +56 -56
  68. package/src/gated/index.d.ts +25 -25
  69. package/src/gated/index.js +5 -5
  70. package/src/index.d.ts +2 -2
  71. package/src/index.js +2 -2
  72. package/src/init.js +960 -960
  73. package/src/intelligence/graphsnip-provider.d.ts +5 -5
  74. package/src/intelligence/graphsnip-provider.js +57 -57
  75. package/src/intelligence/lifecycle.js +25 -0
  76. package/src/memory/LICENSE +21 -21
  77. package/src/memory/README.md +5 -5
  78. package/src/memory/UPSTREAM.json +24 -14
  79. package/src/memory/bridge-cli.js +16 -16
  80. package/src/memory/bridge.js +18 -18
  81. package/src/memory/cli.js +21 -21
  82. package/src/memory/cloud-sync-actions.js +61 -61
  83. package/src/memory/contract.json +45 -45
  84. package/src/memory/index.d.ts +50 -49
  85. package/src/memory/index.js +7 -7
  86. package/src/memory/lifecycle.js +29 -29
  87. package/src/memory/local-cli.js +34 -34
  88. package/src/memory/local-store.js +209 -209
  89. package/src/memory/package.json +33 -33
  90. package/src/memory/proposals.js +90 -90
  91. package/src/memory/skills-cli.js +26 -26
  92. package/src/memory/standalone.d.ts +50 -50
  93. package/src/memory/standalone.js +1 -1
  94. package/src/memory/sync.js +89 -89
  95. package/src/memory/validation.js +25 -25
  96. package/src/onboardingAgents.js +532 -532
  97. package/src/promptTemplates.js +178 -178
  98. package/src/resource-files.js +18 -18
  99. package/src/runtime/contracts.d.ts +47 -47
  100. package/src/runtime/local-cli.js +161 -160
  101. package/src/runtime/mcp-stdio.js +111 -111
  102. package/src/runtime/orchestration.js +59 -59
  103. package/src/runtime/run-agent.js +54 -53
  104. package/src/standalone/index.d.ts +45 -45
  105. package/src/standalone/index.js +13 -13
  106. package/src/standalone/init.js +12 -12
  107. package/src/standalone/orchestration.js +6 -6
  108. package/src/standalone/rag.js +113 -113
  109. package/src/studio/agent-ui.css +43 -43
  110. package/src/studio/agent-ui.js +32 -32
  111. package/src/studio/browser.js +542 -345
  112. package/src/studio/export.js +83 -85
  113. package/src/studio/index.html +74 -37
  114. package/src/studio/memory-actions.js +37 -37
  115. package/src/studio/memory-panel.js +200 -200
  116. package/src/studio/project.js +308 -240
  117. package/src/studio/pull-agent.js +72 -72
  118. package/src/studio/push.js +54 -54
  119. package/src/studio/python-agent.js +47 -47
  120. package/src/studio/python-agent.py +25 -25
  121. package/src/studio/server.js +164 -150
  122. package/src/studio/session.js +83 -83
  123. package/src/studio/studio.css +257 -10
  124. package/src/studio/sync.js +42 -42
  125. package/src/studio/workflow-editor.js +240 -0
  126. package/src/studio/workflow-sync.js +229 -157
@@ -1,240 +1,308 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
- import { join, dirname, basename } from "node:path";
4
- import { resourceFiles } from "../resource-files.js";
5
- import { frameworkDescriptor, runFrameworkAgent } from "../framework/agent.js";
6
- import { createSavedAgentClient } from "../app-builder/saved-app.js";
7
- import { createOpenAIProvider, openStore } from "../runtime/local-cli.js";
8
- import { readMode, readSdkKey, requireCloudMode } from "./session.js";
9
- import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
10
- import { withProjectMemory } from "../memory/lifecycle.js";
11
- import { runAgent } from "../runtime/run-agent.js";
12
-
13
- export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
14
- const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
15
- const cloudId = /^[a-f0-9]{24}$/i;
16
-
17
- async function files(directory, extension) {
18
- const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
19
- if (error.code === "ENOENT") return [];
20
- throw error;
21
- });
22
- return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
23
- }
24
-
25
- function markdownValue(source, name) {
26
- const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
27
- if (!raw) return "";
28
- if (raw.startsWith('"')) {
29
- try { return JSON.parse(raw); } catch { return ""; }
30
- }
31
- return raw.replace(/^'|'$/g, "");
32
- }
33
-
34
- export function readLocalAgent(source) {
35
- const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
36
- if (!front) return null;
37
- const id = markdownValue(front[1], "id");
38
- const name = markdownValue(front[1], "name");
39
- const mode = markdownValue(front[1], "mode");
40
- const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
41
- if (typeof name !== "string" || !name || !safeId.test(id)) return null;
42
- if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
43
- if (mode && mode !== "standalone") return null;
44
- if (!prompt || prompt.length > 16_000) return null;
45
- return { id: "local:" + id, name, source: "local", prompt };
46
- }
47
-
48
- export async function readCatalog(root) {
49
- const directory = join(root, ".lyra", "agents");
50
- const agents = new Map();
51
- for (const name of await resourceFiles(directory, ".md")) {
52
- const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
53
- if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
54
- }
55
- async function records(kind) {
56
- const folder = join(root, ".lyra", kind);
57
- const rows = [];
58
- for (const name of await resourceFiles(folder, ".json")) {
59
- try {
60
- const item = JSON.parse(await readFile(join(folder, name), "utf8"));
61
- if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
62
- } catch (error) {
63
- if (!(error instanceof SyntaxError)) throw error;
64
- }
65
- }
66
- return rows;
67
- }
68
- for (const name of await resourceFiles(directory, ".json")) {
69
- let item;
70
- try {
71
- item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
72
- } catch (error) {
73
- if (error instanceof SyntaxError) continue;
74
- throw error;
75
- }
76
- const external = frameworkDescriptor(item);
77
- if (external && name === join("coding", external.id + ".json")) {
78
- const id = "framework:" + external.id;
79
- agents.set(id, { ...external, id, source: "framework" });
80
- continue;
81
- }
82
- const descriptor = pythonDescriptor(item);
83
- if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
84
- typeof item.name !== "string" || !item.name.trim()) continue;
85
- const id = "python:" + item.id;
86
- if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
87
- }
88
- const skills = await records("skills");
89
- const skillRoot = join(root, ".lyra", "skills");
90
- for (const relative of await resourceFiles(skillRoot, "SKILL.md")) {
91
- if (basename(relative) !== "SKILL.md") continue;
92
- const folder = { name: basename(dirname(relative)) };
93
- if (!safeId.test(folder.name)) continue;
94
- const metadata = join(skillRoot, relative);
95
- const stat = await lstat(metadata).catch(error => {
96
- if (error.code === "ENOENT") return null;
97
- throw error;
98
- });
99
- if (!stat?.isFile() || stat.size > 64_000) continue;
100
- const source = await readFile(metadata, "utf8");
101
- const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
102
- const name = front && markdownValue(front[1], "name");
103
- if (name) skills.push({ id: "markdown:" + folder.name, name, source: "markdown" });
104
- }
105
- return { agents, workflows: await records("workflows"), teams: await records("teams"), skills };
106
- }
107
-
108
- export function validateLayout(layout) {
109
- if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
110
- const ids = new Set();
111
- const checked = layout.map(node => {
112
- if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
113
- typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
114
- ids.add(node.id);
115
- return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
116
- sourceId: String(node.sourceId ?? "").slice(0, 96),
117
- outputId: String(node.outputId ?? "").slice(0, 96),
118
- targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
119
- } };
120
- });
121
- return checked;
122
- }
123
-
124
- async function manifestFile(root) {
125
- const path = join(root, "manifest.json");
126
- try {
127
- if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
128
- const raw = await readFile(path, "utf8");
129
- return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
130
- } catch (error) {
131
- if (error.code !== "ENOENT") throw error;
132
- return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
133
- }
134
- }
135
-
136
- export async function readLayout(root) {
137
- const { manifest, revision } = await manifestFile(root);
138
- return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
139
- }
140
-
141
- export async function saveLayout(root, layout, revision) {
142
- const current = await manifestFile(root);
143
- if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
144
- if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
145
- throw new Error("The existing manifest is not an App Builder manifest.");
146
- }
147
- const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
148
- const temp = current.path + "." + randomUUID() + ".tmp";
149
- await writeFile(temp, content, { flag: "wx" });
150
- try {
151
- if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
152
- await rename(temp, current.path);
153
- } catch (error) {
154
- await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
155
- throw error;
156
- }
157
- return { revision: createHash("sha256").update(content).digest("hex") };
158
- }
159
-
160
- export function resolveSequence(catalog, targets) {
161
- if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
162
- throw new Error("Choose one to eight agents or workflows.");
163
- }
164
- const sequence = targets.flatMap(target => {
165
- if (typeof target !== "string") throw new Error("Invalid run target.");
166
- if (!target.startsWith("workflow:")) return [{ agentId: target }];
167
- const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
168
- if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
169
- return workflow.steps;
170
- });
171
- if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
172
- throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
173
- }
174
- return sequence;
175
- }
176
-
177
- export async function runSelection(root, { targets, input, model }, catalog) {
178
- if (typeof input !== "string" || !input.trim() || input.length > 4000) {
179
- throw new Error("Enter up to 4,000 characters.");
180
- }
181
- const exported = Boolean(catalog);
182
- catalog ??= await readCatalog(root);
183
- const sequence = resolveSequence(catalog, targets);
184
- const local = sequence.some(step => step.agentId.startsWith("local:"));
185
- if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
186
- throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
187
- }
188
- let cloud = null;
189
- if (sequence.some(step => step.agentId.startsWith("cloud:"))) {
190
- if (!exported) requireCloudMode(await readMode(root));
191
- cloud = createSavedAgentClient(exported ? undefined : { key: await readSdkKey(root) });
192
- }
193
- const store = local || sequence.some(step => step.agentId.startsWith("framework:")) ? await openStore(root) : null;
194
- const answers = [];
195
- const named = new Map();
196
- try {
197
- for (const step of sequence) {
198
- const agent = catalog.agents.get(step.agentId);
199
- const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
200
- const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
201
- let output;
202
- let run;
203
- if (agent.source === "cloud") {
204
- output = await cloud.invoke(agent.id.slice("cloud:".length), text);
205
- } else if (agent.source === "python") {
206
- output = await runPythonAgent(root, agent, text, exported);
207
- } else if (agent.source === "framework") {
208
- let payload = text;
209
- if (agent.input === "json") {
210
- try { payload = JSON.parse(previous ?? input); }
211
- catch { throw new Error("Provide valid JSON for " + agent.name + "."); }
212
- }
213
- const traceId = randomUUID();
214
- const revision = createHash("sha256").update(JSON.stringify(agent)).digest("hex");
215
- const event = await runAgent({
216
- agentId: agent.id, store, traceId, framework: agent.framework, revision,
217
- request: { model: "framework-managed", messages: [] },
218
- provider: { complete: async () => ({ text: await runFrameworkAgent(root, agent, payload, traceId) }) },
219
- });
220
- if (event.type !== "run.completed") throw new Error(event.data.message + " Run " + event.run_id + " · Trace " + traceId + ".");
221
-
222
- output = event.data.result.text;
223
- run = { runId: event.run_id, traceId, framework: agent.framework };
224
- } else {
225
- const request = { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] };
226
- const event = await runAgent({
227
- agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
228
- request: exported ? request : await withProjectMemory(root, request),
229
- });
230
- if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
231
- output = event.data.result.text;
232
- }
233
- if (step.output) named.set(step.output, output);
234
- answers.push({ agent: agent.name, output, ...(run ? { run } : {}) });
235
- }
236
- return { answers };
237
- } finally {
238
- store?.close();
239
- }
240
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
+ import { join, dirname, basename } from "node:path";
4
+ import { resourceFiles } from "../resource-files.js";
5
+ import { frameworkDescriptor, runFrameworkAgent } from "../framework/agent.js";
6
+ import { createSavedAgentClient } from "../app-builder/saved-app.js";
7
+ import { createOpenAIProvider, openStore } from "../runtime/local-cli.js";
8
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
9
+ import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
10
+ import { withProjectMemory } from "../memory/lifecycle.js";
11
+ import { runAgent } from "../runtime/run-agent.js";
12
+
13
+ export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
14
+ const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
15
+ const cloudId = /^[a-f0-9]{24}$/i;
16
+ const modelId = /^[\w.:-]{1,120}$/;
17
+
18
+ export function studioModels() {
19
+ return [...new Set((process.env.LYRA_STUDIO_MODELS || "gpt-4o-mini").split(",")
20
+ .map(value => value.trim()).filter(value => modelId.test(value)))];
21
+ }
22
+
23
+ async function files(directory, extension) {
24
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
25
+ if (error.code === "ENOENT") return [];
26
+ throw error;
27
+ });
28
+ return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
29
+ }
30
+
31
+ function markdownValue(source, name) {
32
+ const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
33
+ if (!raw) return "";
34
+ if (raw.startsWith('"')) {
35
+ try { return JSON.parse(raw); } catch { return ""; }
36
+ }
37
+ return raw.replace(/^'|'$/g, "");
38
+ }
39
+
40
+ export function readLocalAgent(source) {
41
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
42
+ if (!front) return null;
43
+ const id = markdownValue(front[1], "id");
44
+ const name = markdownValue(front[1], "name");
45
+ const mode = markdownValue(front[1], "mode");
46
+ const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
47
+ if (typeof name !== "string" || !name || !safeId.test(id)) return null;
48
+ if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
49
+ if (mode && mode !== "standalone") return null;
50
+ if (!prompt || prompt.length > 16_000) return null;
51
+ return { id: "local:" + id, name, source: "local", prompt };
52
+ }
53
+
54
+ export async function readCatalog(root) {
55
+ const directory = join(root, ".lyra", "agents");
56
+ const agents = new Map();
57
+ for (const name of await resourceFiles(directory, ".md")) {
58
+ const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
59
+ if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
60
+ }
61
+ async function records(kind) {
62
+ const folder = join(root, ".lyra", kind);
63
+ const rows = [];
64
+ for (const name of await resourceFiles(folder, ".json")) {
65
+ try {
66
+ const item = JSON.parse(await readFile(join(folder, name), "utf8"));
67
+ if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
68
+ } catch (error) {
69
+ if (!(error instanceof SyntaxError)) throw error;
70
+ }
71
+ }
72
+ return rows;
73
+ }
74
+ for (const name of await resourceFiles(directory, ".json")) {
75
+ let item;
76
+ try {
77
+ item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
78
+ } catch (error) {
79
+ if (error instanceof SyntaxError) continue;
80
+ throw error;
81
+ }
82
+ const external = frameworkDescriptor(item);
83
+ if (external && name === join("coding", external.id + ".json")) {
84
+ const id = "framework:" + external.id;
85
+ agents.set(id, { ...external, id, source: "framework" });
86
+ continue;
87
+ }
88
+ const descriptor = pythonDescriptor(item);
89
+ if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
90
+ typeof item.name !== "string" || !item.name.trim()) continue;
91
+ const id = "python:" + item.id;
92
+ if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
93
+ }
94
+ const skills = await records("skills");
95
+ const skillRoot = join(root, ".lyra", "skills");
96
+ for (const relative of await resourceFiles(skillRoot, "SKILL.md")) {
97
+ if (basename(relative) !== "SKILL.md") continue;
98
+ const folder = { name: basename(dirname(relative)) };
99
+ if (!safeId.test(folder.name)) continue;
100
+ const metadata = join(skillRoot, relative);
101
+ const stat = await lstat(metadata).catch(error => {
102
+ if (error.code === "ENOENT") return null;
103
+ throw error;
104
+ });
105
+ if (!stat?.isFile() || stat.size > 64_000) continue;
106
+ const source = await readFile(metadata, "utf8");
107
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
108
+ const name = front && markdownValue(front[1], "name");
109
+ if (name) skills.push({ id: "markdown:" + folder.name, name, source: "markdown" });
110
+ }
111
+ return { agents, workflows: await records("workflows"), teams: await records("teams"), skills };
112
+ }
113
+
114
+ export function validateLayout(layout) {
115
+ if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
116
+ const ids = new Set();
117
+ const checked = layout.map(node => {
118
+ if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
119
+ typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
120
+ if (node.span !== undefined && ![3, 4, 6, 8, 9, 12].includes(node.span)) {
121
+ throw new Error("Invalid component width.");
122
+ }
123
+ ids.add(node.id);
124
+ return { id: node.id, kind: node.kind, label: node.label,
125
+ ...(node.span === undefined ? {} : { span: node.span }), ...["button", "agent-card"].includes(node.kind) && {
126
+ sourceId: String(node.sourceId ?? "").slice(0, 96),
127
+ outputId: String(node.outputId ?? "").slice(0, 96),
128
+ targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
129
+ } };
130
+ });
131
+ return checked;
132
+ }
133
+
134
+ async function manifestFile(root) {
135
+ const path = join(root, "manifest.json");
136
+ try {
137
+ if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
138
+ const raw = await readFile(path, "utf8");
139
+ return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
140
+ } catch (error) {
141
+ if (error.code !== "ENOENT") throw error;
142
+ return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
143
+ }
144
+ }
145
+
146
+ export async function readLayout(root) {
147
+ const { manifest, revision } = await manifestFile(root);
148
+ return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
149
+ }
150
+
151
+ export async function saveLayout(root, layout, revision) {
152
+ const current = await manifestFile(root);
153
+ if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
154
+ if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
155
+ throw new Error("The existing manifest is not an App Builder manifest.");
156
+ }
157
+ const content = JSON.stringify({ ...current.manifest, studio: { ...current.manifest.studio, layout: validateLayout(layout) } }, null, 2) + "\n";
158
+ const temp = current.path + "." + randomUUID() + ".tmp";
159
+ await writeFile(temp, content, { flag: "wx" });
160
+ try {
161
+ if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
162
+ await rename(temp, current.path);
163
+ } catch (error) {
164
+ await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
165
+ throw error;
166
+ }
167
+ return { revision: createHash("sha256").update(content).digest("hex") };
168
+ }
169
+
170
+ export function validateRunBindings(layout, component) {
171
+ if ((component.sourceId && !layout.some(node => node.id === component.sourceId && ["input", "textarea"].includes(node.kind))) ||
172
+ (component.outputId && !layout.some(node => node.id === component.outputId && node.kind === "output"))) {
173
+ throw new Error("Fix the input or output binding for " + component.label + " in Studio.");
174
+ }
175
+ }
176
+
177
+ export function resolveSequence(catalog, targets) {
178
+ if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
179
+ throw new Error("Choose one to eight agents or workflows.");
180
+ }
181
+ const sequence = targets.flatMap(target => {
182
+ if (typeof target !== "string") throw new Error("Invalid run target.");
183
+ if (!target.startsWith("workflow:")) return [{ agentId: target }];
184
+ const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
185
+ if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
186
+ return workflow.steps;
187
+ });
188
+ if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
189
+ throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
190
+ }
191
+ return sequence;
192
+ }
193
+
194
+ const runtimeLabels = {
195
+ local: { location: "Local project", provider: "OpenAI · selected in Studio" },
196
+ cloud: { location: "Lyra Cloud", provider: "OpenAI · configured in Lyra Cloud" },
197
+ python: { location: "Local Python", provider: "Managed by the Python agent" },
198
+ framework: { location: "Local framework runtime", provider: "Managed by the framework agent" },
199
+ };
200
+
201
+ async function cloudKey(root, exported) {
202
+ if (!exported) requireCloudMode(await readMode(root));
203
+ return exported ? process.env.LYRA_API_KEY : readSdkKey(root);
204
+ }
205
+
206
+ export async function describeRun(root, targets, appCatalog) {
207
+ const catalog = appCatalog ?? await readCatalog(root);
208
+ const agents = resolveSequence(catalog, targets).map(step => catalog.agents.get(step.agentId));
209
+ const needsModel = agents.some(agent => agent.source === "local");
210
+ const models = needsModel ? studioModels() : [];
211
+ const issues = [];
212
+ if (needsModel && !process.env.OPENAI_API_KEY?.trim()) {
213
+ issues.push("Set OPENAI_API_KEY in the terminal that starts Studio, then restart Studio.");
214
+ }
215
+ if (needsModel && !models.length) issues.push("Set LYRA_STUDIO_MODELS to a comma-separated list of OpenAI model IDs.");
216
+ if (agents.some(agent => agent.source === "cloud")) {
217
+ try {
218
+ createSavedAgentClient({ key: await cloudKey(root, Boolean(appCatalog)) ?? "" });
219
+ } catch (error) {
220
+ issues.push(error.message);
221
+ }
222
+ }
223
+ const steps = agents.map(agent => ({
224
+ name: agent.name, framework: agent.framework, ...runtimeLabels[agent.source],
225
+ }));
226
+ return { steps, models, needsModel, issues, inputKind: agents[0].source === "framework" ? agents[0].input : "text" };
227
+ }
228
+
229
+ export async function runSelection(root, { targets, input, model }, catalog) {
230
+ if (typeof input !== "string" || !input.trim() || input.length > 4000) {
231
+ throw new Error("Enter up to 4,000 characters.");
232
+ }
233
+ const exported = Boolean(catalog);
234
+ catalog ??= await readCatalog(root);
235
+ const sequence = resolveSequence(catalog, targets);
236
+ const agents = sequence.map(step => catalog.agents.get(step.agentId));
237
+ const local = agents.some(agent => agent.source === "local");
238
+ if (local && (!process.env.OPENAI_API_KEY?.trim() || !modelId.test(model ?? ""))) {
239
+ throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
240
+ }
241
+ let cloud = null;
242
+ if (agents.some(agent => agent.source === "cloud")) {
243
+ cloud = createSavedAgentClient({ key: await cloudKey(root, exported) ?? "" });
244
+ }
245
+ const store = local || agents.some(agent => agent.source === "framework") ? await openStore(root) : null;
246
+ const traceId = randomUUID();
247
+ const answers = [];
248
+ const steps = [];
249
+ const named = new Map();
250
+ try {
251
+ for (const step of sequence) {
252
+ const agent = catalog.agents.get(step.agentId);
253
+ const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
254
+ const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
255
+ const status = { index: steps.length + 1, agent: agent.name, source: agent.source, traceId: randomUUID() };
256
+ steps.push(status);
257
+ const started = Date.now();
258
+ let output;
259
+ let run;
260
+ try {
261
+ if (agent.source === "cloud") {
262
+ output = await cloud.invoke(agent.id.slice("cloud:".length), text);
263
+ } else if (agent.source === "python") {
264
+ output = await runPythonAgent(root, agent, text, exported);
265
+ } else if (agent.source === "framework") {
266
+ let payload = text;
267
+ if (agent.input === "json") {
268
+ try { payload = JSON.parse(previous ?? input); }
269
+ catch { throw new Error("Provide valid JSON for " + agent.name + "."); }
270
+ }
271
+ const traceId = status.traceId;
272
+ const revision = createHash("sha256").update(JSON.stringify(agent)).digest("hex");
273
+ const event = await runAgent({
274
+ agentId: agent.id, store, traceId, framework: agent.framework, revision,
275
+ request: { model: "framework-managed", messages: [] },
276
+ provider: { complete: async () => ({ text: await runFrameworkAgent(root, agent, payload, traceId) }) },
277
+ });
278
+ status.runId = event.run_id;
279
+ if (event.type !== "run.completed") throw new Error(event.data.message + " Run " + event.run_id + " · Trace " + traceId + ".");
280
+
281
+ output = event.data.result.text;
282
+ run = { runId: event.run_id, traceId, framework: agent.framework };
283
+ } else {
284
+ const request = { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] };
285
+ const event = await runAgent({
286
+ agentId: agent.id, store, traceId: status.traceId, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
287
+ request: exported ? request : await withProjectMemory(root, request),
288
+ });
289
+ status.runId = event.run_id;
290
+ if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
291
+ output = event.data.result.text;
292
+ }
293
+ status.state = "completed";
294
+ } catch (error) {
295
+ status.state = "failed";
296
+ const message = error.code ? "Check the project files for " + agent.name + "." : error.message;
297
+ throw Object.assign(new Error(message, { cause: error }), { progress: { traceId, steps, answers } });
298
+ } finally {
299
+ status.durationMs = Date.now() - started;
300
+ }
301
+ if (step.output) named.set(step.output, output);
302
+ answers.push({ agent: agent.name, output, ...(run ? { run } : {}) });
303
+ }
304
+ return { answers, traceId, steps };
305
+ } finally {
306
+ store?.close();
307
+ }
308
+ }