agent-lyra 0.6.0 → 0.6.1

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 (38) hide show
  1. package/README.md +395 -173
  2. package/bin/agent-lyra.js +16 -3
  3. package/package.json +60 -56
  4. package/src/app-builder/export.js +109 -109
  5. package/src/app-builder/init.js +52 -52
  6. package/src/app-builder/preview.js +22 -22
  7. package/src/app-builder/saved-app.js +70 -70
  8. package/src/app-builder/saved-preview-browser.js +33 -33
  9. package/src/app-builder/saved-preview.html +24 -24
  10. package/src/app-builder/saved-preview.js +61 -61
  11. package/src/app-builder/validate.js +64 -64
  12. package/src/memory/cli.js +49 -0
  13. package/src/memory/contract.json +28 -0
  14. package/src/memory/index.d.ts +49 -0
  15. package/src/memory/index.js +259 -0
  16. package/src/memory/lifecycle.js +29 -0
  17. package/src/memory/proposals.js +84 -0
  18. package/src/memory/skills-cli.js +26 -0
  19. package/src/memory/sync.js +85 -0
  20. package/src/memory/validation.js +25 -0
  21. package/src/runtime/local-cli.js +2 -1
  22. package/src/studio/agent-ui.css +43 -43
  23. package/src/studio/agent-ui.js +32 -32
  24. package/src/studio/browser.js +331 -289
  25. package/src/studio/export.js +80 -79
  26. package/src/studio/index.html +37 -16
  27. package/src/studio/memory-actions.js +37 -0
  28. package/src/studio/memory-panel.js +200 -0
  29. package/src/studio/project.js +197 -190
  30. package/src/studio/pull-agent.js +72 -0
  31. package/src/studio/push.js +54 -0
  32. package/src/studio/python-agent.js +47 -47
  33. package/src/studio/python-agent.py +25 -25
  34. package/src/studio/server.js +143 -102
  35. package/src/studio/session.js +83 -0
  36. package/src/studio/studio.css +10 -7
  37. package/src/studio/sync.js +42 -39
  38. package/src/studio/workflow-sync.js +157 -0
@@ -1,190 +1,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 { pythonDescriptor, runPythonAgent } from "./python-agent.js";
7
- import { runAgent } from "../runtime/run-agent.js";
8
-
9
- export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
10
- const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
11
- const cloudId = /^[a-f0-9]{24}$/i;
12
-
13
- async function files(directory, extension) {
14
- const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
15
- if (error.code === "ENOENT") return [];
16
- throw error;
17
- });
18
- return entries.filter(entry => entry.isFile() && entry.name.endsWith(extension)).map(entry => entry.name);
19
- }
20
-
21
- function markdownValue(source, name) {
22
- const raw = new RegExp("^" + name + ":\\s*(.+)$", "m").exec(source)?.[1]?.trim();
23
- if (!raw) return "";
24
- if (raw.startsWith('"')) {
25
- try { return JSON.parse(raw); } catch { return ""; }
26
- }
27
- return raw.replace(/^'|'$/g, "");
28
- }
29
-
30
- export function readLocalAgent(source) {
31
- const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
32
- if (!front) return null;
33
- const id = markdownValue(front[1], "id");
34
- const name = markdownValue(front[1], "name");
35
- const mode = markdownValue(front[1], "mode");
36
- const prompt = /(?:^|\n)## System Prompt\s*\r?\n([\s\S]*?)(?=\r?\n## [^\n]+|$)/.exec(source.slice(front[0].length))?.[1]?.trim();
37
- if (typeof name !== "string" || !name || !safeId.test(id)) return null;
38
- if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
39
- if (mode && mode !== "standalone") return null;
40
- if (!prompt || prompt.length > 16_000) return null;
41
- return { id: "local:" + id, name, source: "local", prompt };
42
- }
43
-
44
- export async function readCatalog(root) {
45
- const directory = join(root, ".lyra", "agents");
46
- const agents = new Map();
47
- for (const name of await files(directory, ".md")) {
48
- const parsed = readLocalAgent(await readFile(join(directory, name), "utf8"));
49
- if (parsed && !agents.has(parsed.id)) agents.set(parsed.id, parsed);
50
- }
51
- async function records(kind) {
52
- const folder = join(root, ".lyra", kind);
53
- const rows = [];
54
- for (const name of await files(folder, ".json")) {
55
- try {
56
- const item = JSON.parse(await readFile(join(folder, name), "utf8"));
57
- if (safeId.test(item.id) && typeof item.name === "string") rows.push(item);
58
- } catch (error) {
59
- if (!(error instanceof SyntaxError)) throw error;
60
- }
61
- }
62
- return rows;
63
- }
64
- for (const name of await files(directory, ".json")) {
65
- let item;
66
- try {
67
- item = JSON.parse((await readFile(join(directory, name), "utf8")).replace(/^\uFEFF/, ""));
68
- } catch (error) {
69
- if (error instanceof SyntaxError) continue;
70
- throw error;
71
- }
72
- const descriptor = pythonDescriptor(item);
73
- if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
74
- typeof item.name !== "string" || !item.name.trim()) continue;
75
- const id = "python:" + item.id;
76
- if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
77
- }
78
- return { agents, workflows: await records("workflows"), teams: await records("teams") };
79
- }
80
-
81
- export function validateLayout(layout) {
82
- if (!Array.isArray(layout) || layout.length > 60) throw new Error("The layout must contain at most 60 components.");
83
- const ids = new Set();
84
- const checked = layout.map(node => {
85
- if (!node || !safeId.test(node.id) || ids.has(node.id) || !kinds.includes(node.kind) ||
86
- typeof node.label !== "string" || node.label.length > 160) throw new Error("Invalid layout component.");
87
- ids.add(node.id);
88
- return { id: node.id, kind: node.kind, label: node.label, ...["button", "agent-card"].includes(node.kind) && {
89
- sourceId: String(node.sourceId ?? "").slice(0, 96),
90
- outputId: String(node.outputId ?? "").slice(0, 96),
91
- targets: Array.isArray(node.targets) ? node.targets.slice(0, node.kind === "agent-card" ? 1 : 8).map(target => String(target).slice(0, 120)) : [],
92
- } };
93
- });
94
- return checked;
95
- }
96
-
97
- async function manifestFile(root) {
98
- const path = join(root, "manifest.json");
99
- try {
100
- if (!(await lstat(path)).isFile()) throw new Error("manifest.json must be a regular file.");
101
- const raw = await readFile(path, "utf8");
102
- return { path, manifest: JSON.parse(raw.replace(/^\uFEFF/, "")), revision: createHash("sha256").update(raw).digest("hex") };
103
- } catch (error) {
104
- if (error.code !== "ENOENT") throw error;
105
- return { path, manifest: { version: "3.0", application: { id: "lyra-app", name: "Lyra app" } }, revision: null };
106
- }
107
- }
108
-
109
- export async function readLayout(root) {
110
- const { manifest, revision } = await manifestFile(root);
111
- return { revision, name: manifest.application?.name ?? "Lyra app", layout: validateLayout(manifest.studio?.layout ?? []) };
112
- }
113
-
114
- export async function saveLayout(root, layout, revision) {
115
- const current = await manifestFile(root);
116
- if (revision !== current.revision) throw new Error("manifest.json changed. Reload Studio before saving.");
117
- if (!current.manifest.application || !["1.0", "2.0", "3.0"].includes(current.manifest.version)) {
118
- throw new Error("The existing manifest is not an App Builder manifest.");
119
- }
120
- const content = JSON.stringify({ ...current.manifest, studio: { layout: validateLayout(layout) } }, null, 2) + "\n";
121
- const temp = current.path + "." + randomUUID() + ".tmp";
122
- await writeFile(temp, content, { flag: "wx" });
123
- try {
124
- if ((await manifestFile(root)).revision !== revision) throw new Error("manifest.json changed. Reload Studio before saving.");
125
- await rename(temp, current.path);
126
- } catch (error) {
127
- await import("node:fs/promises").then(({ unlink }) => unlink(temp)).catch(() => {});
128
- throw error;
129
- }
130
- return { revision: createHash("sha256").update(content).digest("hex") };
131
- }
132
-
133
- export function resolveSequence(catalog, targets) {
134
- if (!Array.isArray(targets) || targets.length === 0 || targets.length > 8) {
135
- throw new Error("Choose one to eight agents or workflows.");
136
- }
137
- const sequence = targets.flatMap(target => {
138
- if (typeof target !== "string") throw new Error("Invalid run target.");
139
- if (!target.startsWith("workflow:")) return [{ agentId: target }];
140
- const workflow = catalog.workflows.find(item => "workflow:" + item.id === target);
141
- if (!workflow?.runnable || !Array.isArray(workflow.steps)) throw new Error("This Cloud workflow cannot run in local Studio.");
142
- return workflow.steps;
143
- });
144
- if (!sequence.length || sequence.length > 8 || sequence.some(step => !catalog.agents.has(step.agentId))) {
145
- throw new Error("Select up to eight available text agents. Pull missing Cloud agents first.");
146
- }
147
- return sequence;
148
- }
149
-
150
- export async function runSelection(root, { targets, input, model }, catalog) {
151
- if (typeof input !== "string" || !input.trim() || input.length > 4000) {
152
- throw new Error("Enter up to 4,000 characters.");
153
- }
154
- const exported = Boolean(catalog);
155
- catalog ??= await readCatalog(root);
156
- const sequence = resolveSequence(catalog, targets);
157
- const local = sequence.some(step => step.agentId.startsWith("local:"));
158
- if (local && (!process.env.OPENAI_API_KEY || !/^[\w.:-]{1,120}$/.test(model ?? ""))) {
159
- throw new Error("Set OPENAI_API_KEY and select an OpenAI model for local agents.");
160
- }
161
- const cloud = sequence.some(step => step.agentId.startsWith("cloud:")) ? createSavedAgentClient() : null;
162
- const store = local ? await openStore(root) : null;
163
- const answers = [];
164
- const named = new Map();
165
- try {
166
- for (const step of sequence) {
167
- const agent = catalog.agents.get(step.agentId);
168
- const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
169
- const text = [step.task, input.trim(), previous && "Previous result: " + previous].filter(Boolean).join("\n\n").slice(0, 12_000);
170
- let output;
171
- if (agent.source === "cloud") {
172
- output = await cloud.invoke(agent.id.slice("cloud:".length), text);
173
- } else if (agent.source === "python") {
174
- output = await runPythonAgent(root, agent, text, exported);
175
- } else {
176
- const event = await runAgent({
177
- agentId: agent.id, store, provider: createOpenAIProvider(process.env.OPENAI_API_KEY, fetch),
178
- request: { model, messages: [{ role: "system", content: agent.prompt }, { role: "user", content: text }] },
179
- });
180
- if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
181
- output = event.data.result.text;
182
- }
183
- if (step.output) named.set(step.output, output);
184
- answers.push({ agent: agent.name, output });
185
- }
186
- return { answers };
187
- } finally {
188
- store?.close();
189
- }
190
- }
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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +1,54 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { readCatalog } from "./project.js";
5
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
6
+
7
+ export async function pushStudioAgent(root, id, { key, request = fetch } = {}) {
8
+ requireCloudMode(await readMode(root));
9
+ const base = join(root, ".lyra");
10
+ for (const directory of [base, join(base, "agents")]) {
11
+ if (!(await lstat(directory).catch(() => null))?.isDirectory()) throw new Error("Use a regular .lyra/agents folder.");
12
+ }
13
+ const agent = (await readCatalog(root)).agents.get(id);
14
+ if (agent?.source !== "local") throw new Error("Choose a local Markdown text agent to push.");
15
+ key ??= await readSdkKey(root);
16
+ if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before pushing.");
17
+
18
+ const links = join(base, "agent-links");
19
+ await mkdir(links, { recursive: true });
20
+ if (!(await lstat(links)).isDirectory()) throw new Error("Agent links must use a regular directory.");
21
+ const metadata = join(links, agent.id.slice("local:".length) + ".json");
22
+ let link;
23
+ try {
24
+ if (!(await lstat(metadata)).isFile()) throw new Error("An agent link must be a regular file.");
25
+ link = JSON.parse(await readFile(metadata, "utf8"));
26
+ if (!/^[a-f0-9]{64}$/.test(link?.linkId ?? "") || !/^[a-f0-9]{64}$/.test(link?.revision ?? "")) {
27
+ throw new Error("This agent has invalid Cloud link metadata.");
28
+ }
29
+ } catch (error) {
30
+ if (error.code !== "ENOENT") throw error;
31
+ }
32
+ const linkId = link?.linkId ?? createHash("sha256").update(resolve(root) + "\0" + id).digest("hex");
33
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/agents/" + linkId, {
34
+ method: "PUT", headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
35
+ body: JSON.stringify({ name: agent.name, prompt: agent.prompt, revision: link?.revision }),
36
+ redirect: "error", signal: AbortSignal.timeout(20_000),
37
+ });
38
+ const result = await response.json();
39
+ if (!response.ok) {
40
+ if (response.status === 401) throw new Error("The Cloud key was rejected. Run connect-cloud --replace-key.");
41
+ throw new Error(result.error || "Cloud push failed (HTTP " + response.status + ").");
42
+ }
43
+ if (!/^[a-f0-9]{24}$/i.test(result.id ?? "") || !/^[a-f0-9]{64}$/.test(result.revision ?? "")) {
44
+ throw new Error("Unexpected Cloud agent response.");
45
+ }
46
+ const temporary = metadata + "." + process.pid + ".tmp";
47
+ await writeFile(temporary, JSON.stringify({ linkId, cloudId: result.id, revision: result.revision }) + "\n", { flag: "wx", mode: 0o600 });
48
+ try {
49
+ await rename(temporary, metadata);
50
+ } finally {
51
+ await unlink(temporary).catch(() => {});
52
+ }
53
+ return { name: agent.name, created: response.status === 201 };
54
+ }
@@ -1,47 +1,47 @@
1
- import { execFile } from "node:child_process";
2
- import { lstat } from "node:fs/promises";
3
- import { join } from "node:path";
4
-
5
- const filename = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.py$/;
6
- const skillId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/;
7
-
8
- export function pythonDescriptor(item) {
9
- if (item?.runtime !== "python" || !filename.test(item.file ?? "") || !skillId.test(item.skill ?? "")) return null;
10
- return { file: item.file, skill: item.skill };
11
- }
12
-
13
- export async function pythonSource(root, agent, exported) {
14
- if (!pythonDescriptor({ ...agent, runtime: "python" })) throw new Error("Invalid Python agent descriptor.");
15
- let directory = root;
16
- for (const part of exported ? ["python-agents"] : [".lyra", "agents"]) {
17
- directory = join(directory, part);
18
- if (!(await lstat(directory)).isDirectory()) throw new Error("Python agent folders must be regular directories.");
19
- }
20
- const source = join(directory, agent.file);
21
- if (!(await lstat(source)).isFile()) throw new Error("Python agent source must be a regular file.");
22
- return source;
23
- }
24
-
25
- export async function runPythonAgent(root, agent, input, exported) {
26
- const file = await pythonSource(root, agent, exported);
27
- const python = process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3");
28
- const runner = new URL("./python-agent.py", import.meta.url);
29
- const { fileURLToPath } = await import("node:url");
30
- return new Promise((resolve, reject) => {
31
- const child = execFile(python, [fileURLToPath(runner), file, agent.skill], {
32
- cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
33
- }, (error, stdout) => {
34
- if (error?.code === "ENOENT") return reject(new Error("Install Python 3.9+ and agent-lyra, or set LYRA_PYTHON to your virtual environment's interpreter."));
35
- if (error) return reject(new Error("Python agent " + agent.name + " failed. Check its dependencies and skill registration."));
36
- try {
37
- const result = JSON.parse(stdout);
38
- if (typeof result.output !== "string") throw new Error();
39
- resolve(result.output);
40
- } catch {
41
- reject(new Error("Python agent " + agent.name + " returned an invalid response."));
42
- }
43
- });
44
- child.stdin.on("error", () => {});
45
- child.stdin.end(JSON.stringify({ input }));
46
- });
47
- }
1
+ import { execFile } from "node:child_process";
2
+ import { lstat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+
5
+ const filename = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.py$/;
6
+ const skillId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/;
7
+
8
+ export function pythonDescriptor(item) {
9
+ if (item?.runtime !== "python" || !filename.test(item.file ?? "") || !skillId.test(item.skill ?? "")) return null;
10
+ return { file: item.file, skill: item.skill };
11
+ }
12
+
13
+ export async function pythonSource(root, agent, exported) {
14
+ if (!pythonDescriptor({ ...agent, runtime: "python" })) throw new Error("Invalid Python agent descriptor.");
15
+ let directory = root;
16
+ for (const part of exported ? ["python-agents"] : [".lyra", "agents"]) {
17
+ directory = join(directory, part);
18
+ if (!(await lstat(directory)).isDirectory()) throw new Error("Python agent folders must be regular directories.");
19
+ }
20
+ const source = join(directory, agent.file);
21
+ if (!(await lstat(source)).isFile()) throw new Error("Python agent source must be a regular file.");
22
+ return source;
23
+ }
24
+
25
+ export async function runPythonAgent(root, agent, input, exported) {
26
+ const file = await pythonSource(root, agent, exported);
27
+ const python = process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3");
28
+ const runner = new URL("./python-agent.py", import.meta.url);
29
+ const { fileURLToPath } = await import("node:url");
30
+ return new Promise((resolve, reject) => {
31
+ const child = execFile(python, [fileURLToPath(runner), file, agent.skill], {
32
+ cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
33
+ }, (error, stdout) => {
34
+ if (error?.code === "ENOENT") return reject(new Error("Install Python 3.9+ and agent-lyra, or set LYRA_PYTHON to your virtual environment's interpreter."));
35
+ if (error) return reject(new Error("Python agent " + agent.name + " failed. Check its dependencies and skill registration."));
36
+ try {
37
+ const result = JSON.parse(stdout);
38
+ if (typeof result.output !== "string") throw new Error();
39
+ resolve(result.output);
40
+ } catch {
41
+ reject(new Error("Python agent " + agent.name + " returned an invalid response."));
42
+ }
43
+ });
44
+ child.stdin.on("error", () => {});
45
+ child.stdin.end(JSON.stringify({ input }));
46
+ });
47
+ }