agent-lyra 0.6.1 → 0.6.3

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 (108) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +435 -395
  3. package/bin/agent-lyra.js +49 -44
  4. package/bin/lyra-oss-preview.js +16 -0
  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 +52 -52
  9. package/src/app-builder/manifest-contract.js +46 -0
  10. package/src/app-builder/native-adapter.js +29 -29
  11. package/src/app-builder/preview.js +22 -22
  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 +21 -64
  25. package/src/app-builder/value-schema.js +37 -37
  26. package/src/catalog.js +147 -147
  27. package/src/coding/catalog.js +56 -0
  28. package/src/coding/cloud-catalog.js +64 -0
  29. package/src/coding/detect-stack.mjs +110 -0
  30. package/src/coding/export.js +130 -0
  31. package/src/coding/setup.js +175 -0
  32. package/src/coding/skills/lyra-android/SKILL.md +37 -0
  33. package/src/coding/skills/lyra-angular/SKILL.md +37 -0
  34. package/src/coding/skills/lyra-cucumber/SKILL.md +37 -0
  35. package/src/coding/skills/lyra-dbt/SKILL.md +37 -0
  36. package/src/coding/skills/lyra-django/SKILL.md +37 -0
  37. package/src/coding/skills/lyra-docker/SKILL.md +37 -0
  38. package/src/coding/skills/lyra-dotnet/SKILL.md +37 -0
  39. package/src/coding/skills/lyra-express/SKILL.md +37 -0
  40. package/src/coding/skills/lyra-fastapi/SKILL.md +37 -0
  41. package/src/coding/skills/lyra-flutter/SKILL.md +37 -0
  42. package/src/coding/skills/lyra-github-actions/SKILL.md +37 -0
  43. package/src/coding/skills/lyra-gitlab-ci/SKILL.md +37 -0
  44. package/src/coding/skills/lyra-go/SKILL.md +37 -0
  45. package/src/coding/skills/lyra-ios/SKILL.md +37 -0
  46. package/src/coding/skills/lyra-kubernetes/SKILL.md +37 -0
  47. package/src/coding/skills/lyra-mongodb/SKILL.md +37 -0
  48. package/src/coding/skills/lyra-mysql/SKILL.md +37 -0
  49. package/src/coding/skills/lyra-nextjs/SKILL.md +37 -0
  50. package/src/coding/skills/lyra-node/SKILL.md +37 -0
  51. package/src/coding/skills/lyra-playwright/SKILL.md +37 -0
  52. package/src/coding/skills/lyra-postgresql/SKILL.md +37 -0
  53. package/src/coding/skills/lyra-python/SKILL.md +37 -0
  54. package/src/coding/skills/lyra-react/SKILL.md +37 -0
  55. package/src/coding/skills/lyra-react-native/SKILL.md +37 -0
  56. package/src/coding/skills/lyra-redis/SKILL.md +37 -0
  57. package/src/coding/skills/lyra-rust/SKILL.md +37 -0
  58. package/src/coding/skills/lyra-spark/SKILL.md +37 -0
  59. package/src/coding/skills/lyra-spring-boot/SKILL.md +37 -0
  60. package/src/coding/skills/lyra-svelte/SKILL.md +37 -0
  61. package/src/coding/skills/lyra-terraform/SKILL.md +37 -0
  62. package/src/coding/skills/lyra-typescript/SKILL.md +37 -0
  63. package/src/coding/skills/lyra-vue/SKILL.md +37 -0
  64. package/src/gated/hostedAgents.js +56 -56
  65. package/src/gated/index.d.ts +25 -25
  66. package/src/gated/index.js +5 -5
  67. package/src/index.d.ts +2 -2
  68. package/src/index.js +2 -2
  69. package/src/init.js +965 -937
  70. package/src/memory/cli.js +21 -49
  71. package/src/memory/contract.json +28 -28
  72. package/src/memory/index.d.ts +49 -49
  73. package/src/memory/index.js +259 -259
  74. package/src/memory/lifecycle.js +29 -29
  75. package/src/memory/local-cli.js +34 -0
  76. package/src/memory/proposals.js +84 -84
  77. package/src/memory/skills-cli.js +26 -26
  78. package/src/memory/sync.js +89 -85
  79. package/src/memory/validation.js +25 -25
  80. package/src/onboardingAgents.js +532 -532
  81. package/src/promptTemplates.js +178 -178
  82. package/src/runtime/contracts.d.ts +47 -47
  83. package/src/runtime/local-cli.js +160 -160
  84. package/src/runtime/mcp-stdio.js +111 -111
  85. package/src/runtime/orchestration.js +59 -59
  86. package/src/runtime/run-agent.js +43 -43
  87. package/src/standalone/index.d.ts +45 -45
  88. package/src/standalone/index.js +13 -13
  89. package/src/standalone/init.js +12 -0
  90. package/src/standalone/orchestration.js +6 -6
  91. package/src/standalone/rag.js +113 -113
  92. package/src/studio/agent-ui.css +43 -43
  93. package/src/studio/agent-ui.js +32 -32
  94. package/src/studio/browser.js +331 -331
  95. package/src/studio/export.js +80 -80
  96. package/src/studio/index.html +37 -37
  97. package/src/studio/memory-actions.js +37 -37
  98. package/src/studio/memory-panel.js +200 -200
  99. package/src/studio/project.js +216 -197
  100. package/src/studio/pull-agent.js +72 -72
  101. package/src/studio/push.js +54 -54
  102. package/src/studio/python-agent.js +47 -47
  103. package/src/studio/python-agent.py +25 -25
  104. package/src/studio/server.js +143 -143
  105. package/src/studio/session.js +83 -83
  106. package/src/studio/studio.css +10 -10
  107. package/src/studio/sync.js +42 -42
  108. package/src/studio/workflow-sync.js +157 -157
@@ -1,197 +1,216 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { createSavedAgentClient } from "../app-builder/saved-app.js";
5
- import { createOpenAIProvider, openStore } from "../runtime/local-cli.js";
6
- import { readMode, readSdkKey, requireCloudMode } from "./session.js";
7
- import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
8
- import { withProjectMemory } from "../memory/lifecycle.js";
9
- import { runAgent } from "../runtime/run-agent.js";
10
-
11
- export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
12
- const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
13
- const cloudId = /^[a-f0-9]{24}$/i;
14
-
15
- async function files(directory, extension) {
16
- const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
17
- if (error.code === "ENOENT") return [];
18
- throw error;
19
- });
20
- return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
21
- }
22
-
23
- function markdownValue(source, name) {
24
- const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
25
- if (!raw) return "";
26
- if (raw.startsWith('"')) {
27
- try { return JSON.parse(raw); } catch { return ""; }
28
- }
29
- return raw.replace(/^'|'$/g, "");
30
- }
31
-
32
- export function readLocalAgent(source) {
33
- const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
34
- if (!front) return null;
35
- const id = markdownValue(front[1], "id");
36
- const name = markdownValue(front[1], "name");
37
- const mode = markdownValue(front[1], "mode");
38
- const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
39
- if (typeof name !== "string" || !name || !safeId.test(id)) return null;
40
- if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
41
- if (mode && mode !== "standalone") return null;
42
- if (!prompt || prompt.length > 16_000) return null;
43
- return { id: "local:" + id, name, source: "local", prompt };
44
- }
45
-
46
- export async function readCatalog(root) {
47
- const directory = join(root, ".lyra", "agents");
48
- const agents = new Map();
49
- for (const name of await files(directory, ".md")) {
50
- const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
51
- if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
52
- }
53
- async function records(kind) {
54
- const folder = join(root, ".lyra", kind);
55
- const rows = [];
56
- for (const name of await files(folder, ".json")) {
57
- try {
58
- const item = JSON.parse(await readFile(join(folder, name), "utf8"));
59
- if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
60
- } catch (error) {
61
- if (!(error instanceof SyntaxError)) throw error;
62
- }
63
- }
64
- return rows;
65
- }
66
- for (const name of await files(directory, ".json")) {
67
- let item;
68
- try {
69
- item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
70
- } catch (error) {
71
- if (error instanceof SyntaxError) continue;
72
- throw error;
73
- }
74
- const descriptor = pythonDescriptor(item);
75
- if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
76
- typeof item.name !== "string" || !item.name.trim()) continue;
77
- const id = "python:" + item.id;
78
- if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
79
- }
80
- return { agents, workflows: await records("workflows"), teams: await records("teams"), skills: await records("skills") };
81
- }
82
-
83
- export function validateLayout(layout) {
84
- if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
85
- const ids = new Set();
86
- const checked = layout.map(node => {
87
- if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
88
- typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
89
- ids.add(node.id);
90
- return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
91
- sourceId: String(node.sourceId ?? "").slice(0, 96),
92
- outputId: String(node.outputId ?? "").slice(0, 96),
93
- targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
94
- } };
95
- });
96
- return checked;
97
- }
98
-
99
- async function manifestFile(root) {
100
- const path = join(root, "manifest.json");
101
- try {
102
- if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
103
- const raw = await readFile(path, "utf8");
104
- return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
105
- } catch (error) {
106
- if (error.code !== "ENOENT") throw error;
107
- return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
108
- }
109
- }
110
-
111
- export async function readLayout(root) {
112
- const { manifest, revision } = await manifestFile(root);
113
- return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
114
- }
115
-
116
- export async function saveLayout(root, layout, revision) {
117
- const current = await manifestFile(root);
118
- if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
119
- if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
120
- throw new Error("The existing manifest is not an App Builder manifest.");
121
- }
122
- const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
123
- const temp = current.path + "." + randomUUID() + ".tmp";
124
- await writeFile(temp, content, { flag: "wx" });
125
- try {
126
- if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
127
- await rename(temp, current.path);
128
- } catch (error) {
129
- await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
130
- throw error;
131
- }
132
- return { revision: createHash("sha256").update(content).digest("hex") };
133
- }
134
-
135
- export function resolveSequence(catalog, targets) {
136
- if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
137
- throw new Error("Choose one to eight agents or workflows.");
138
- }
139
- const sequence = targets.flatMap(target => {
140
- if (typeof target !== "string") throw new Error("Invalid run target.");
141
- if (!target.startsWith("workflow:")) return [{ agentId: target }];
142
- const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
143
- if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
144
- return workflow.steps;
145
- });
146
- if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
147
- throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
148
- }
149
- return sequence;
150
- }
151
-
152
- export async function runSelection(root, { targets, input, model }, catalog) {
153
- if (typeof input !== "string" || !input.trim() || input.length > 4000) {
154
- throw new Error("Enter up to 4,000 characters.");
155
- }
156
- const exported = Boolean(catalog);
157
- catalog ??= await readCatalog(root);
158
- const sequence = resolveSequence(catalog, targets);
159
- const local = sequence.some(step => step.agentId.startsWith("local:"));
160
- if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
161
- throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
162
- }
163
- let cloud = null;
164
- if (sequence.some(step => step.agentId.startsWith("cloud:"))) {
165
- if (!exported) requireCloudMode(await readMode(root));
166
- cloud = createSavedAgentClient(exported ? undefined : { key: await readSdkKey(root) });
167
- }
168
- const store = local ? await openStore(root) : null;
169
- const answers = [];
170
- const named = new Map();
171
- try {
172
- for (const step of sequence) {
173
- const agent = catalog.agents.get(step.agentId);
174
- const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
175
- const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
176
- let output;
177
- if (agent.source === "cloud") {
178
- output = await cloud.invoke(agent.id.slice("cloud:".length), text);
179
- } else if (agent.source === "python") {
180
- output = await runPythonAgent(root, agent, text, exported);
181
- } else {
182
- const request = { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] };
183
- const event = await runAgent({
184
- agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
185
- request: exported ? request : await withProjectMemory(root, request),
186
- });
187
- if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
188
- output = event.data.result.text;
189
- }
190
- if (step.output) named.set(step.output, output);
191
- answers.push({ agent: agent.name, output });
192
- }
193
- return { answers };
194
- } finally {
195
- store?.close();
196
- }
197
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createSavedAgentClient } from "../app-builder/saved-app.js";
5
+ import { createOpenAIProvider, openStore } from "../runtime/local-cli.js";
6
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
7
+ import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
8
+ import { withProjectMemory } from "../memory/lifecycle.js";
9
+ import { runAgent } from "../runtime/run-agent.js";
10
+
11
+ export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
12
+ const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
13
+ const cloudId = /^[a-f0-9]{24}$/i;
14
+
15
+ async function files(directory, extension) {
16
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
17
+ if (error.code === "ENOENT") return [];
18
+ throw error;
19
+ });
20
+ return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
21
+ }
22
+
23
+ function markdownValue(source, name) {
24
+ const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
25
+ if (!raw) return "";
26
+ if (raw.startsWith('"')) {
27
+ try { return JSON.parse(raw); } catch { return ""; }
28
+ }
29
+ return raw.replace(/^'|'$/g, "");
30
+ }
31
+
32
+ export function readLocalAgent(source) {
33
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
34
+ if (!front) return null;
35
+ const id = markdownValue(front[1], "id");
36
+ const name = markdownValue(front[1], "name");
37
+ const mode = markdownValue(front[1], "mode");
38
+ const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
39
+ if (typeof name !== "string" || !name || !safeId.test(id)) return null;
40
+ if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
41
+ if (mode && mode !== "standalone") return null;
42
+ if (!prompt || prompt.length > 16_000) return null;
43
+ return { id: "local:" + id, name, source: "local", prompt };
44
+ }
45
+
46
+ export async function readCatalog(root) {
47
+ const directory = join(root, ".lyra", "agents");
48
+ const agents = new Map();
49
+ for (const name of await files(directory, ".md")) {
50
+ const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
51
+ if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
52
+ }
53
+ async function records(kind) {
54
+ const folder = join(root, ".lyra", kind);
55
+ const rows = [];
56
+ for (const name of await files(folder, ".json")) {
57
+ try {
58
+ const item = JSON.parse(await readFile(join(folder, name), "utf8"));
59
+ if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
60
+ } catch (error) {
61
+ if (!(error instanceof SyntaxError)) throw error;
62
+ }
63
+ }
64
+ return rows;
65
+ }
66
+ for (const name of await files(directory, ".json")) {
67
+ let item;
68
+ try {
69
+ item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
70
+ } catch (error) {
71
+ if (error instanceof SyntaxError) continue;
72
+ throw error;
73
+ }
74
+ const descriptor = pythonDescriptor(item);
75
+ if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
76
+ typeof item.name !== "string" || !item.name.trim()) continue;
77
+ const id = "python:" + item.id;
78
+ if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
79
+ }
80
+ const skills = await records("skills");
81
+ const skillRoot = join(root, ".lyra", "skills");
82
+ const folders = await readdir(skillRoot, { withFileTypes: true }).catch(error => {
83
+ if (error.code === "ENOENT") return [];
84
+ throw error;
85
+ });
86
+ for (const folder of folders) {
87
+ if (!folder.isDirectory() || !safeId.test(folder.name)) continue;
88
+ const metadata = join(skillRoot, folder.name, "SKILL.md");
89
+ const stat = await lstat(metadata).catch(error => {
90
+ if (error.code === "ENOENT") return null;
91
+ throw error;
92
+ });
93
+ if (!stat?.isFile() || stat.size > 64_000) continue;
94
+ const source = await readFile(metadata, "utf8");
95
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
96
+ const name = front && markdownValue(front[1], "name");
97
+ if (name) skills.push({ id: "markdown:" + folder.name, name, source: "markdown" });
98
+ }
99
+ return { agents, workflows: await records("workflows"), teams: await records("teams"), skills };
100
+ }
101
+
102
+ export function validateLayout(layout) {
103
+ if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
104
+ const ids = new Set();
105
+ const checked = layout.map(node => {
106
+ if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
107
+ typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
108
+ ids.add(node.id);
109
+ return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
110
+ sourceId: String(node.sourceId ?? "").slice(0, 96),
111
+ outputId: String(node.outputId ?? "").slice(0, 96),
112
+ targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
113
+ } };
114
+ });
115
+ return checked;
116
+ }
117
+
118
+ async function manifestFile(root) {
119
+ const path = join(root, "manifest.json");
120
+ try {
121
+ if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
122
+ const raw = await readFile(path, "utf8");
123
+ return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
124
+ } catch (error) {
125
+ if (error.code !== "ENOENT") throw error;
126
+ return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
127
+ }
128
+ }
129
+
130
+ export async function readLayout(root) {
131
+ const { manifest, revision } = await manifestFile(root);
132
+ return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
133
+ }
134
+
135
+ export async function saveLayout(root, layout, revision) {
136
+ const current = await manifestFile(root);
137
+ if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
138
+ if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
139
+ throw new Error("The existing manifest is not an App Builder manifest.");
140
+ }
141
+ const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
142
+ const temp = current.path + "." + randomUUID() + ".tmp";
143
+ await writeFile(temp, content, { flag: "wx" });
144
+ try {
145
+ if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
146
+ await rename(temp, current.path);
147
+ } catch (error) {
148
+ await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
149
+ throw error;
150
+ }
151
+ return { revision: createHash("sha256").update(content).digest("hex") };
152
+ }
153
+
154
+ export function resolveSequence(catalog, targets) {
155
+ if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
156
+ throw new Error("Choose one to eight agents or workflows.");
157
+ }
158
+ const sequence = targets.flatMap(target => {
159
+ if (typeof target !== "string") throw new Error("Invalid run target.");
160
+ if (!target.startsWith("workflow:")) return [{ agentId: target }];
161
+ const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
162
+ if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
163
+ return workflow.steps;
164
+ });
165
+ if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
166
+ throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
167
+ }
168
+ return sequence;
169
+ }
170
+
171
+ export async function runSelection(root, { targets, input, model }, catalog) {
172
+ if (typeof input !== "string" || !input.trim() || input.length > 4000) {
173
+ throw new Error("Enter up to 4,000 characters.");
174
+ }
175
+ const exported = Boolean(catalog);
176
+ catalog ??= await readCatalog(root);
177
+ const sequence = resolveSequence(catalog, targets);
178
+ const local = sequence.some(step => step.agentId.startsWith("local:"));
179
+ if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
180
+ throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
181
+ }
182
+ let cloud = null;
183
+ if (sequence.some(step => step.agentId.startsWith("cloud:"))) {
184
+ if (!exported) requireCloudMode(await readMode(root));
185
+ cloud = createSavedAgentClient(exported ? undefined : { key: await readSdkKey(root) });
186
+ }
187
+ const store = local ? await openStore(root) : null;
188
+ const answers = [];
189
+ const named = new Map();
190
+ try {
191
+ for (const step of sequence) {
192
+ const agent = catalog.agents.get(step.agentId);
193
+ const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
194
+ const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
195
+ let output;
196
+ if (agent.source === "cloud") {
197
+ output = await cloud.invoke(agent.id.slice("cloud:".length), text);
198
+ } else if (agent.source === "python") {
199
+ output = await runPythonAgent(root, agent, text, exported);
200
+ } else {
201
+ const request = { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] };
202
+ const event = await runAgent({
203
+ agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
204
+ request: exported ? request : await withProjectMemory(root, request),
205
+ });
206
+ if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
207
+ output = event.data.result.text;
208
+ }
209
+ if (step.output) named.set(step.output, output);
210
+ answers.push({ agent: agent.name, output });
211
+ }
212
+ return { answers };
213
+ } finally {
214
+ store?.close();
215
+ }
216
+ }
@@ -1,72 +1,72 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { readLocalAgent } from "./project.js";
5
- import { readMode, readSdkKey, requireCloudMode } from "./session.js";
6
-
7
- const hash = (name, systemPrompt) => createHash("sha256").update(JSON.stringify({ name, systemPrompt })).digest("hex");
8
- const digest = /^[a-f0-9]{64}$/;
9
-
10
- export async function pullAgentEdits(root, id, { request = fetch, key } = {}) {
11
- requireCloudMode(await readMode(root));
12
- if (!/^local:[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(id ?? "")) throw new Error("Choose a local Markdown text agent.");
13
- const base = join(root, ".lyra");
14
- const links = join(base, "agent-links");
15
- const folder = join(base, "agents");
16
- for (const directory of [base, links, folder]) {
17
- if (!(await lstat(directory).catch(() => null))?.isDirectory()) throw new Error("Push this agent to Cloud once to link it.");
18
- }
19
- const metadata = join(links, id.slice(6) + ".json");
20
- if (!(await lstat(metadata).catch(() => null))?.isFile()) throw new Error("Push this agent to Cloud once to link it.");
21
- const link = JSON.parse(await readFile(metadata, "utf8"));
22
- if (!digest.test(link?.linkId ?? "") || !digest.test(link?.revision ?? "")) throw new Error("Invalid Cloud link.");
23
-
24
- const matches = [];
25
- for (const entry of await readdir(folder, { withFileTypes: true })) {
26
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
27
- const path = join(folder, entry.name);
28
- const content = await readFile(path, "utf8");
29
- const parsed = readLocalAgent(content);
30
- if (parsed?.id === id) matches.push({ path, content, parsed });
31
- }
32
- if (matches.length !== 1) throw new Error("Use a unique local agent ID before pulling edits.");
33
- const [{ path, content, parsed }] = matches;
34
-
35
- key ??= await readSdkKey(root);
36
- if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before pulling edits.");
37
- const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/agents/" + link.linkId, {
38
- headers: { Authorization: "Bearer " + key }, redirect: "error", signal: AbortSignal.timeout(20_000),
39
- });
40
- const remote = await response.json();
41
- if (!response.ok) throw new Error(remote.error || "Could not pull agent edits.");
42
- if (remote.id !== link.cloudId || typeof remote.name !== "string" || typeof remote.prompt !== "string" ||
43
- !digest.test(remote.revision ?? "")) throw new Error("The Cloud agent link no longer matches.");
44
- const local = hash(parsed.name.trim(), parsed.prompt.trim());
45
- if (remote.revision === link.revision || local === remote.revision) {
46
- if (local !== remote.revision) return { name: parsed.name, updated: false };
47
- } else {
48
- if (local !== link.revision) throw new Error("Both copies changed. Review the Cloud agent and reconcile the edits before syncing.");
49
- const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(content)[0];
50
- const body = content.slice(front.length);
51
- const next = front.replace(/^name:[^\r\n]*/m, () => "name: " + JSON.stringify(remote.name)) +
52
- body.replace(/(^|\n)## System Prompt[^\S\r\n]*\r?\n[\s\S]*?(?=\r?\n## [^\n]+|$)/,
53
- (_whole, prefix) => prefix + "## System Prompt\n" + remote.prompt + "\n");
54
- const checked = readLocalAgent(next);
55
- if (!checked || hash(checked.name, checked.prompt) !== remote.revision) {
56
- throw new Error("The Cloud instructions cannot be represented in this Markdown agent. Copy them manually.");
57
- }
58
- if (await readFile(path, "utf8") !== content) throw new Error("The local agent changed during the pull. Try again.");
59
- await replace(path, next);
60
- }
61
- if (link.revision !== remote.revision) {
62
- await replace(metadata, JSON.stringify({ ...link, revision: remote.revision }) + "\n");
63
- }
64
- return { name: remote.name, updated: local !== remote.revision };
65
- }
66
-
67
- async function replace(path, content) {
68
- const temporary = path + "." + randomUUID() + ".tmp";
69
- await writeFile(temporary, content, { flag: "wx", mode: 0o600 });
70
- try { await rename(temporary, path); }
71
- finally { await unlink(temporary).catch(() => {}); }
72
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { readLocalAgent } from "./project.js";
5
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
6
+
7
+ const hash = (name, systemPrompt) => createHash("sha256").update(JSON.stringify({ name, systemPrompt })).digest("hex");
8
+ const digest = /^[a-f0-9]{64}$/;
9
+
10
+ export async function pullAgentEdits(root, id, { request = fetch, key } = {}) {
11
+ requireCloudMode(await readMode(root));
12
+ if (!/^local:[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/.test(id ?? "")) throw new Error("Choose a local Markdown text agent.");
13
+ const base = join(root, ".lyra");
14
+ const links = join(base, "agent-links");
15
+ const folder = join(base, "agents");
16
+ for (const directory of [base, links, folder]) {
17
+ if (!(await lstat(directory).catch(() => null))?.isDirectory()) throw new Error("Push this agent to Cloud once to link it.");
18
+ }
19
+ const metadata = join(links, id.slice(6) + ".json");
20
+ if (!(await lstat(metadata).catch(() => null))?.isFile()) throw new Error("Push this agent to Cloud once to link it.");
21
+ const link = JSON.parse(await readFile(metadata, "utf8"));
22
+ if (!digest.test(link?.linkId ?? "") || !digest.test(link?.revision ?? "")) throw new Error("Invalid Cloud link.");
23
+
24
+ const matches = [];
25
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
26
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
27
+ const path = join(folder, entry.name);
28
+ const content = await readFile(path, "utf8");
29
+ const parsed = readLocalAgent(content);
30
+ if (parsed?.id === id) matches.push({ path, content, parsed });
31
+ }
32
+ if (matches.length !== 1) throw new Error("Use a unique local agent ID before pulling edits.");
33
+ const [{ path, content, parsed }] = matches;
34
+
35
+ key ??= await readSdkKey(root);
36
+ if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before pulling edits.");
37
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/agents/" + link.linkId, {
38
+ headers: { Authorization: "Bearer " + key }, redirect: "error", signal: AbortSignal.timeout(20_000),
39
+ });
40
+ const remote = await response.json();
41
+ if (!response.ok) throw new Error(remote.error || "Could not pull agent edits.");
42
+ if (remote.id !== link.cloudId || typeof remote.name !== "string" || typeof remote.prompt !== "string" ||
43
+ !digest.test(remote.revision ?? "")) throw new Error("The Cloud agent link no longer matches.");
44
+ const local = hash(parsed.name.trim(), parsed.prompt.trim());
45
+ if (remote.revision === link.revision || local === remote.revision) {
46
+ if (local !== remote.revision) return { name: parsed.name, updated: false };
47
+ } else {
48
+ if (local !== link.revision) throw new Error("Both copies changed. Review the Cloud agent and reconcile the edits before syncing.");
49
+ const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(content)[0];
50
+ const body = content.slice(front.length);
51
+ const next = front.replace(/^name:[^\r\n]*/m, () => "name: " + JSON.stringify(remote.name)) +
52
+ body.replace(/(^|\n)## System Prompt[^\S\r\n]*\r?\n[\s\S]*?(?=\r?\n## [^\n]+|$)/,
53
+ (_whole, prefix) => prefix + "## System Prompt\n" + remote.prompt + "\n");
54
+ const checked = readLocalAgent(next);
55
+ if (!checked || hash(checked.name, checked.prompt) !== remote.revision) {
56
+ throw new Error("The Cloud instructions cannot be represented in this Markdown agent. Copy them manually.");
57
+ }
58
+ if (await readFile(path, "utf8") !== content) throw new Error("The local agent changed during the pull. Try again.");
59
+ await replace(path, next);
60
+ }
61
+ if (link.revision !== remote.revision) {
62
+ await replace(metadata, JSON.stringify({ ...link, revision: remote.revision }) + "\n");
63
+ }
64
+ return { name: remote.name, updated: local !== remote.revision };
65
+ }
66
+
67
+ async function replace(path, content) {
68
+ const temporary = path + "." + randomUUID() + ".tmp";
69
+ await writeFile(temporary, content, { flag: "wx", mode: 0o600 });
70
+ try { await rename(temporary, path); }
71
+ finally { await unlink(temporary).catch(() => {}); }
72
+ }