agent-lyra 0.11.1 → 0.12.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.
- package/README.md +47 -35
- package/bin/agent-lyra.js +1 -1
- package/package.json +1 -1
- package/src/app-builder/init.js +3 -3
- package/src/app-builder/preview.js +8 -5
- package/src/framework/agent.js +19 -8
- package/src/framework/mda.js +5 -2
- package/src/framework/run.py +83 -11
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/init.js +1 -1
- package/src/intelligence/lifecycle.js +3 -2
- package/src/memory/LICENSE +1 -1
- package/src/memory/UPSTREAM.json +6 -3
- package/src/memory/external-engine.js +35 -0
- package/src/memory/index.js +19 -1
- package/src/memory/lifecycle.js +2 -1
- package/src/runtime/programmatic.d.ts +84 -0
- package/src/runtime/programmatic.js +155 -0
- package/src/runtime/run-agent.js +10 -2
- package/src/studio/browser.js +172 -30
- package/src/studio/export.js +7 -4
- package/src/studio/graphsnip-workbench.js +77 -0
- package/src/studio/history-panel.js +155 -0
- package/src/studio/ide-provider.js +65 -0
- package/src/studio/index.html +61 -9
- package/src/studio/intelligence.js +94 -0
- package/src/studio/local-provider.js +43 -0
- package/src/studio/memory-actions.js +28 -1
- package/src/studio/memory-panel.js +29 -5
- package/src/studio/mission-ui.css +52 -0
- package/src/studio/mission-ui.js +57 -0
- package/src/studio/programmatic-runner.mjs +21 -0
- package/src/studio/programmatic.js +58 -0
- package/src/studio/project.js +109 -26
- package/src/studio/python-agent.py +28 -4
- package/src/studio/run-history.js +119 -0
- package/src/studio/server.js +97 -9
- package/src/studio/session.js +1 -1
- package/src/studio/studio.css +192 -30
|
@@ -6,6 +6,7 @@ export function mountMemoryPanel(api) {
|
|
|
6
6
|
const status = byId("memory-status");
|
|
7
7
|
const query = byId("memory-query");
|
|
8
8
|
let busy = false;
|
|
9
|
+
let sourceRun;
|
|
9
10
|
|
|
10
11
|
function element(tag, text) {
|
|
11
12
|
const node = document.createElement(tag);
|
|
@@ -31,7 +32,10 @@ export function mountMemoryPanel(api) {
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
async function reload() {
|
|
34
|
-
const { records, stats } = await api("memory/list", { query: query.value });
|
|
35
|
+
const { records, stats, engine } = await api("memory/list", { query: query.value });
|
|
36
|
+
byId("memory-engine").textContent = engine?.source === "independent"
|
|
37
|
+
? "Independent Memory Engine " + engine.version
|
|
38
|
+
: "Bundled Memory Engine" + (engine?.version ? " " + engine.version : "");
|
|
35
39
|
byId("memory-summary").textContent = stats.candidate + " candidates · " + stats.verified + " verified · " + stats.archived + " archived";
|
|
36
40
|
await loadProposals();
|
|
37
41
|
lists.replaceChildren();
|
|
@@ -138,10 +142,24 @@ export function mountMemoryPanel(api) {
|
|
|
138
142
|
}));
|
|
139
143
|
}
|
|
140
144
|
|
|
141
|
-
|
|
145
|
+
function open(runId, suggestion) {
|
|
146
|
+
sourceRun = runId;
|
|
147
|
+
const form = byId("memory-create");
|
|
148
|
+
form.reset();
|
|
149
|
+
|
|
150
|
+
if (runId) {
|
|
151
|
+
form.elements.evidence.value = "run:" + runId;
|
|
152
|
+
if (suggestion) {
|
|
153
|
+
form.elements.type.value = suggestion.type;
|
|
154
|
+
form.elements.title.value = suggestion.title;
|
|
155
|
+
form.elements.learning.value = suggestion.learning;
|
|
156
|
+
}
|
|
157
|
+
form.closest("details").open = true;
|
|
158
|
+
}
|
|
142
159
|
panel.showModal();
|
|
143
160
|
return run(null, reload);
|
|
144
|
-
}
|
|
161
|
+
}
|
|
162
|
+
byId("open-memory").onclick = () => open();
|
|
145
163
|
byId("close-memory").onclick = () => panel.close();
|
|
146
164
|
byId("memory-search").onsubmit = event => {
|
|
147
165
|
event.preventDefault();
|
|
@@ -151,11 +169,16 @@ export function mountMemoryPanel(api) {
|
|
|
151
169
|
event.preventDefault();
|
|
152
170
|
const form = event.currentTarget;
|
|
153
171
|
return run(event.submitter, async () => {
|
|
154
|
-
|
|
172
|
+
const body = Object.fromEntries(new FormData(form));
|
|
173
|
+
const result = sourceRun
|
|
174
|
+
? await api("memory/record-run", { ...body, runId: sourceRun })
|
|
175
|
+
: await api("memory/record", body);
|
|
176
|
+
sourceRun = undefined;
|
|
177
|
+
|
|
155
178
|
form.reset();
|
|
156
179
|
query.value = "";
|
|
157
180
|
await reload();
|
|
158
|
-
return "Recorded a candidate.";
|
|
181
|
+
return result.reused ? "This learning already exists in this project." : "Recorded a candidate.";
|
|
159
182
|
});
|
|
160
183
|
};
|
|
161
184
|
function compareCopies(id, copies) {
|
|
@@ -197,4 +220,5 @@ export function mountMemoryPanel(api) {
|
|
|
197
220
|
return result.deleted ? "Applied Cloud deletion." : result.updated ? "Pulled a candidate for local review." : "Already up to date.";
|
|
198
221
|
});
|
|
199
222
|
};
|
|
223
|
+
return open;
|
|
200
224
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
.lyra-mission-status {
|
|
2
|
+
--mission-dot: var(--lyra-color-text-muted, var(--studio-muted, #52675e));
|
|
3
|
+
--mission-tint: var(--lyra-color-surface-2, #f1f5f2);
|
|
4
|
+
display: inline-flex;
|
|
5
|
+
align-items: center;
|
|
6
|
+
gap: .35rem;
|
|
7
|
+
width: fit-content;
|
|
8
|
+
padding: .16rem .48rem;
|
|
9
|
+
border: 1px solid var(--lyra-color-border, var(--studio-line, #dce6df));
|
|
10
|
+
border-radius: 999px;
|
|
11
|
+
background: var(--mission-tint);
|
|
12
|
+
color: var(--mission-dot);
|
|
13
|
+
font-size: .75rem;
|
|
14
|
+
font-weight: 600;
|
|
15
|
+
}
|
|
16
|
+
.lyra-mission-status[data-state="running"] {
|
|
17
|
+
--mission-dot: var(--lyra-color-primary, #286b51);
|
|
18
|
+
--mission-tint: var(--app-primary-soft, #eef5ef);
|
|
19
|
+
}
|
|
20
|
+
.lyra-mission-status[data-state="completed"] {
|
|
21
|
+
--mission-dot: var(--lyra-color-success, #226142);
|
|
22
|
+
--mission-tint: var(--lyra-color-success-bg, #eaf5ee);
|
|
23
|
+
}
|
|
24
|
+
.lyra-mission-status[data-state="failed"] {
|
|
25
|
+
--mission-dot: var(--lyra-color-danger, #a22730);
|
|
26
|
+
--mission-tint: var(--lyra-color-danger-bg, #fbeff0);
|
|
27
|
+
}
|
|
28
|
+
.lyra-mission-status-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
|
|
29
|
+
.lyra-mission-timeline { margin: .65rem 0 0; padding: 0; list-style: none; }
|
|
30
|
+
.lyra-mission-timeline-row {
|
|
31
|
+
display: grid;
|
|
32
|
+
grid-template-columns: auto minmax(0, 1fr);
|
|
33
|
+
align-items: start;
|
|
34
|
+
gap: .65rem;
|
|
35
|
+
padding: .65rem 0;
|
|
36
|
+
border-top: 1px solid var(--lyra-color-border, var(--studio-line, #dce6df));
|
|
37
|
+
}
|
|
38
|
+
.lyra-mission-timeline-marker { width: 8px; height: 8px; margin-top: .4rem; border-radius: 50%; background: var(--lyra-color-primary, #286b51); }
|
|
39
|
+
.lyra-mission-timeline-body { min-width: 0; overflow-wrap: anywhere; }
|
|
40
|
+
.lyra-mission-timeline-title { font-size: .85rem; }
|
|
41
|
+
.lyra-mission-timeline-description { margin: .18rem 0; font-size: .8rem; }
|
|
42
|
+
.lyra-mission-timeline-meta {
|
|
43
|
+
display: flex;
|
|
44
|
+
align-items: center;
|
|
45
|
+
flex-wrap: wrap;
|
|
46
|
+
gap: .3rem .55rem;
|
|
47
|
+
margin-top: .25rem;
|
|
48
|
+
color: var(--lyra-color-text-muted, var(--studio-muted, #52675e));
|
|
49
|
+
font-size: .75rem;
|
|
50
|
+
}
|
|
51
|
+
.lyra-mission-timeline-reference { display: block; margin-top: .2rem; font-size: .74rem; }
|
|
52
|
+
.lyra-mission-empty { padding: 1rem 0; text-align: center; color: var(--lyra-color-text-muted, var(--studio-muted, #52675e)); }
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const statuses = {
|
|
2
|
+
queued: ["pending", "Pending"],
|
|
3
|
+
pending: ["pending", "Pending"],
|
|
4
|
+
started: ["running", "Started"],
|
|
5
|
+
requested: ["running", "Requested"],
|
|
6
|
+
responded: ["completed", "Responded"],
|
|
7
|
+
running: ["running", "Running"],
|
|
8
|
+
in_progress: ["running", "In progress"],
|
|
9
|
+
success: ["completed", "Completed"],
|
|
10
|
+
completed: ["completed", "Completed"],
|
|
11
|
+
done: ["completed", "Completed"],
|
|
12
|
+
error: ["failed", "Failed"],
|
|
13
|
+
failed: ["failed", "Failed"],
|
|
14
|
+
cancelled: ["stopped", "Cancelled"],
|
|
15
|
+
stopped: ["stopped", "Stopped"],
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function statusDisplay(status) {
|
|
19
|
+
return Object.hasOwn(statuses, status) ? statuses[status] : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function missionStatusLabel(status) {
|
|
23
|
+
return statusDisplay(status)?.[1] ?? status;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function formatMissionDuration(ms, { showMilliseconds = false } = {}) {
|
|
27
|
+
if (!Number.isFinite(ms) || ms < 0 || (!showMilliseconds && !ms)) return "—";
|
|
28
|
+
if (showMilliseconds && ms < 1000) return Math.round(ms) + " ms";
|
|
29
|
+
const seconds = Math.floor(ms / 1000);
|
|
30
|
+
return Math.floor(seconds / 60) + "m " + seconds % 60 + "s";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function renderMissionStatus(h, status, label) {
|
|
34
|
+
const [tone, fallback] = statusDisplay(status) ?? statuses.pending;
|
|
35
|
+
return h("span", { className: "lyra-mission-status", "data-state": tone },
|
|
36
|
+
h("span", { className: "lyra-mission-status-dot", "aria-hidden": "true" }),
|
|
37
|
+
label ?? fallback);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function renderMissionTimeline(h, rows) {
|
|
41
|
+
if (!rows.length) return h("p", { className: "lyra-mission-empty" }, "No steps recorded yet");
|
|
42
|
+
return h("ol", { className: "lyra-mission-timeline" }, ...rows.map(row =>
|
|
43
|
+
h("li", { key: row.id, className: "lyra-mission-timeline-row" },
|
|
44
|
+
row.icon ?? h("span", { className: "lyra-mission-timeline-marker", "aria-hidden": "true" }),
|
|
45
|
+
h("div", { className: "lyra-mission-timeline-body" },
|
|
46
|
+
h("strong", { className: "lyra-mission-timeline-title" }, row.title),
|
|
47
|
+
row.description && h("p", { className: "lyra-mission-timeline-description" }, row.description),
|
|
48
|
+
h("div", { className: "lyra-mission-timeline-meta" },
|
|
49
|
+
row.status && renderMissionStatus(h, row.status, row.statusLabel),
|
|
50
|
+
row.duration,
|
|
51
|
+
row.timestamp && h("time", { dateTime: row.timestamp }, row.timestampLabel),
|
|
52
|
+
),
|
|
53
|
+
row.reference && h("code", { className: "lyra-mission-timeline-reference" }, row.reference),
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
));
|
|
57
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Console } from "node:console";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
|
|
4
|
+
const output = process.stdout.write.bind(process.stdout);
|
|
5
|
+
globalThis.console = new Console(process.stderr);
|
|
6
|
+
let payload = "";
|
|
7
|
+
for await (const chunk of process.stdin.setEncoding("utf8")) payload += chunk;
|
|
8
|
+
const { agent } = await import(pathToFileURL(process.argv[2]).href);
|
|
9
|
+
if (typeof agent?.run !== "function") throw new TypeError("Export an Agent named agent.");
|
|
10
|
+
const activity = [];
|
|
11
|
+
const suggestions = [];
|
|
12
|
+
const result = await agent.run(JSON.parse(payload).input, {
|
|
13
|
+
onLearning: value => { if (suggestions.length < 3) suggestions.push(value); },
|
|
14
|
+
onActivity: event => { if (activity.length < 10) activity.push(event); },
|
|
15
|
+
});
|
|
16
|
+
output(JSON.stringify({
|
|
17
|
+
status: result.status,
|
|
18
|
+
activity,
|
|
19
|
+
suggestions,
|
|
20
|
+
output: typeof result.output === "string" ? result.output : JSON.stringify(result.output),
|
|
21
|
+
}));
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
export function programmaticDescriptor(item) {
|
|
7
|
+
if (!["lyra-node", "lyra-python"].includes(item?.runtime)) return null;
|
|
8
|
+
const file = item.file;
|
|
9
|
+
const extension = item.runtime === "lyra-python" ? /\.py$/ : /\.(?:mjs|js)$/;
|
|
10
|
+
if (typeof file !== "string" || !/^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.[a-z]+$/.test(file) ||
|
|
11
|
+
!extension.test(file) || !["text", "json", undefined].includes(item.input)) return null;
|
|
12
|
+
return { runtime: item.runtime, file, input: item.input ?? "text" };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function runProgrammatic(root, agent, input, onActivity, onLearning) {
|
|
16
|
+
let directory = root;
|
|
17
|
+
for (const part of [".lyra", "agents"]) {
|
|
18
|
+
directory = join(directory, part);
|
|
19
|
+
if (!(await lstat(directory)).isDirectory()) throw new Error("Use regular .lyra/agents directories.");
|
|
20
|
+
}
|
|
21
|
+
const source = join(directory, agent.file);
|
|
22
|
+
if (!(await lstat(source)).isFile()) throw new Error("Use a regular registered agent file.");
|
|
23
|
+
const python = agent.runtime === "lyra-python";
|
|
24
|
+
const executable = python
|
|
25
|
+
? process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3")
|
|
26
|
+
: process.execPath;
|
|
27
|
+
const runner = fileURLToPath(new URL(python ? "./python-agent.py" : "./programmatic-runner.mjs", import.meta.url));
|
|
28
|
+
const args = python ? [runner, source, "--programmatic"] : [runner, source];
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
const child = execFile(executable, args, {
|
|
31
|
+
cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
|
|
32
|
+
}, (error, stdout) => {
|
|
33
|
+
if (error?.code === "ENOENT" && python) {
|
|
34
|
+
return reject(new Error("Install the Python SDK in your environment and set LYRA_PYTHON to its interpreter."));
|
|
35
|
+
}
|
|
36
|
+
if (error) return reject(new Error("The registered agent failed to load or run. Check its source and dependencies."));
|
|
37
|
+
try {
|
|
38
|
+
const result = JSON.parse(stdout);
|
|
39
|
+
if (Array.isArray(result.activity)) {
|
|
40
|
+
for (const event of result.activity.slice(0, 10)) onActivity?.(event);
|
|
41
|
+
}
|
|
42
|
+
if (result.status !== "completed") {
|
|
43
|
+
const status = ["blocked", "cancelled", "failed"].includes(result.status) ? result.status : "failed";
|
|
44
|
+
return reject(new Error("The registered agent run " + status + "."));
|
|
45
|
+
}
|
|
46
|
+
if (typeof result.output !== "string") throw new TypeError("Expected text output.");
|
|
47
|
+
if (Array.isArray(result.suggestions)) {
|
|
48
|
+
for (const suggestion of result.suggestions.slice(0, 3)) onLearning?.(suggestion);
|
|
49
|
+
}
|
|
50
|
+
resolve(result.output);
|
|
51
|
+
} catch {
|
|
52
|
+
reject(new Error("The registered agent returned an invalid response."));
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
child.stdin.on("error", () => {});
|
|
56
|
+
child.stdin.end(JSON.stringify({ input }));
|
|
57
|
+
});
|
|
58
|
+
}
|
package/src/studio/project.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createLocalModelProvider, localModelConfiguration } from "./local-provider.js";
|
|
2
|
+
import { completeIde, ideModel } from "./ide-provider.js";
|
|
1
3
|
import { availableCliProviders, completeCli } from "./cli-providers.js";
|
|
2
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
5
|
import { lstat, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
|
|
@@ -7,8 +9,12 @@ import { frameworkDescriptor, runFrameworkAgent } from "../framework/agent.js";
|
|
|
7
9
|
import { createSavedAgentClient } from "../app-builder/saved-app.js";
|
|
8
10
|
import { createOpenAIProvider, openStore, readOpenAIKey } from "../runtime/local-cli.js";
|
|
9
11
|
import { agentRevision, readAgentLink, readMode, readSdkKey, requireCloudMode } from "./session.js";
|
|
12
|
+
import { programmaticDescriptor, runProgrammatic } from "./programmatic.js";
|
|
10
13
|
import { pythonDescriptor, runPythonAgent } from "./python-agent.js";
|
|
14
|
+
import { withGraphSnipContext } from "../intelligence/lifecycle.js";
|
|
15
|
+
import { eligibleText } from "../memory/validation.js";
|
|
11
16
|
import { withProjectMemory } from "../memory/lifecycle.js";
|
|
17
|
+
import { openRunHistory, stepEventFields } from "./run-history.js";
|
|
12
18
|
import { runAgent } from "../runtime/run-agent.js";
|
|
13
19
|
|
|
14
20
|
export const kinds = ["heading", "text", "input", "textarea", "button", "agent-card", "output"];
|
|
@@ -52,7 +58,7 @@ export function readLocalAgent(source) {
|
|
|
52
58
|
return { id: "local:" + id, name, source: "local", prompt };
|
|
53
59
|
}
|
|
54
60
|
|
|
55
|
-
export async function readCatalog(root) {
|
|
61
|
+
export async function readCatalog(root, { includeSkillInstructions = false } = {}) {
|
|
56
62
|
const directory = join(root, ".lyra", "agents");
|
|
57
63
|
const agents = new Map();
|
|
58
64
|
for (const name of await resourceFiles(directory, ".md")) {
|
|
@@ -86,6 +92,13 @@ export async function readCatalog(root) {
|
|
|
86
92
|
agents.set(id, { ...external, id, source: "framework" });
|
|
87
93
|
continue;
|
|
88
94
|
}
|
|
95
|
+
const executable = programmaticDescriptor(item);
|
|
96
|
+
if (executable && typeof item.id === "string" && safeId.test(item.id) &&
|
|
97
|
+
typeof item.name === "string" && item.name.trim()) {
|
|
98
|
+
const id = "programmatic:" + item.id;
|
|
99
|
+
if (!agents.has(id)) agents.set(id, { ...executable, id, name: item.name, source: "programmatic" });
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
89
102
|
const descriptor = pythonDescriptor(item);
|
|
90
103
|
if (!descriptor || typeof item.id !== "string" || !safeId.test(item.id) ||
|
|
91
104
|
typeof item.name !== "string" || !item.name.trim()) continue;
|
|
@@ -119,7 +132,12 @@ export async function readCatalog(root) {
|
|
|
119
132
|
const source = await readFile(metadata, "utf8");
|
|
120
133
|
const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
|
|
121
134
|
const name = front && markdownValue(front[1], "name");
|
|
122
|
-
if (name) skills.push({
|
|
135
|
+
if (name) skills.push({
|
|
136
|
+
id: "markdown:" + folder.name,
|
|
137
|
+
name,
|
|
138
|
+
source: "markdown",
|
|
139
|
+
...(includeSkillInstructions ? { body: source.slice(front[0].length).trim() } : {}),
|
|
140
|
+
});
|
|
123
141
|
}
|
|
124
142
|
return { agents, workflows: await records("workflows"), teams: await records("teams"), skills };
|
|
125
143
|
}
|
|
@@ -208,6 +226,7 @@ const runtimeLabels = {
|
|
|
208
226
|
local: { location: "Local project", provider: "OpenAI · selected in Studio" },
|
|
209
227
|
cloud: { location: "Lyra Cloud", provider: "OpenAI · configured in Lyra Cloud" },
|
|
210
228
|
python: { location: "Local Python", provider: "Managed by the Python agent" },
|
|
229
|
+
programmatic: { location: "Local project", provider: "Managed by the executable agent" },
|
|
211
230
|
framework: { location: "Local framework runtime", provider: "Managed by the framework agent" },
|
|
212
231
|
};
|
|
213
232
|
|
|
@@ -224,10 +243,14 @@ export async function describeRun(root, targets, appCatalog, provider) {
|
|
|
224
243
|
const hasCloud = agents.some(agent => agent.source === 'cloud');
|
|
225
244
|
let cloudAvailable = false;
|
|
226
245
|
try { createSavedAgentClient({ key: await cloudKey(root, Boolean(appCatalog)) ?? '' }); cloudAvailable = true; } catch {}
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
const
|
|
246
|
+
const ide = !appCatalog && ideModel();
|
|
247
|
+
const localModel = !appCatalog && localModelConfiguration();
|
|
248
|
+
const providers = needsModel ? [...(ide ? ['vscode'] : []), ...(localModel ? ['local-model'] : []), ...cli, 'openai', ...(cloudAvailable || hasCloud ? ['cloud'] : [])] : [];
|
|
249
|
+
provider ??= needsModel ? (ide ? "vscode" : hasCloud && cloudAvailable ? "cloud" : "openai") : undefined;
|
|
250
|
+
const models = !needsModel ? [] : provider === "openai" ? studioModels()
|
|
251
|
+
: provider === "vscode" && ide ? [ide.id] : provider === "local-model" ? localModel?.models ?? [] : [];
|
|
230
252
|
const issues = [];
|
|
253
|
+
if (provider === "local-model" && localModel?.issue) issues.push(localModel.issue);
|
|
231
254
|
const needsOpenAIKey = needsModel && provider === "openai" &&
|
|
232
255
|
!(appCatalog ? process.env.OPENAI_API_KEY?.trim() : await readOpenAIKey());
|
|
233
256
|
if (needsOpenAIKey) issues.push(appCatalog
|
|
@@ -245,10 +268,10 @@ export async function describeRun(root, targets, appCatalog, provider) {
|
|
|
245
268
|
name: agent.name, framework: agent.framework, ...runtimeLabels[agent.source],
|
|
246
269
|
}));
|
|
247
270
|
if (needsModel && !providers.includes(provider)) issues.push('Selected provider is unavailable.');
|
|
248
|
-
return { steps: steps.map((step, i) => ['local', 'cloud'].includes(agents[i].source) ? { ...step, location: provider === 'cloud' ? 'Lyra Cloud' : 'Local project', provider } : step), providers, provider, models, needsModel: needsModel &&
|
|
271
|
+
return { frameworkOnly: agents.every(agent => agent.source === "framework"), steps: steps.map((step, i) => ['local', 'cloud'].includes(agents[i].source) ? { ...step, location: provider === 'cloud' ? 'Lyra Cloud' : provider === 'vscode' ? 'VS Code extension' : 'Local project', provider } : step), providers, provider, models, needsModel: needsModel && ['openai', 'vscode', 'local-model'].includes(provider), ideModelName: ide?.name, issues, needsOpenAIKey, inputKind: agents[0].input ?? "text" };
|
|
249
272
|
}
|
|
250
273
|
|
|
251
|
-
export async function runSelection(root, { targets, input, model, provider }, catalog) {
|
|
274
|
+
export async function runSelection(root, { targets, input, model, provider }, catalog, { signal, onDelta, onEvent } = {}) {
|
|
252
275
|
if (typeof input !== "string" || !input.trim() || input.length > 4000) {
|
|
253
276
|
throw new Error("Enter up to 4,000 characters.");
|
|
254
277
|
}
|
|
@@ -260,13 +283,18 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
260
283
|
const hasCloud = agents.some(agent => agent.source === "cloud");
|
|
261
284
|
const cli = exported ? [] : await availableCliProviders();
|
|
262
285
|
provider ??= hasCloud ? "cloud" : "openai";
|
|
263
|
-
|
|
286
|
+
const ide = !exported && ideModel();
|
|
287
|
+
const localModel = !exported && localModelConfiguration();
|
|
288
|
+
if (local && !['openai', 'cloud', ...(ide ? ['vscode'] : []), ...(localModel ? ['local-model'] : []), ...cli].includes(provider)) throw new Error('Selected provider is unavailable.');
|
|
264
289
|
const openAIKey = local && provider === "openai"
|
|
265
290
|
? exported ? process.env.OPENAI_API_KEY?.trim() : await readOpenAIKey()
|
|
266
291
|
: undefined;
|
|
267
292
|
if (local && provider === "openai" && (!openAIKey || !modelId.test(model ?? ""))) {
|
|
268
293
|
throw new Error("Configure an OpenAI API key and choose a model for this run.");
|
|
269
294
|
}
|
|
295
|
+
if (local && provider === "local-model" && !localModel?.models?.includes(model)) {
|
|
296
|
+
throw new Error(localModel?.issue ?? "Choose a configured local model.");
|
|
297
|
+
}
|
|
270
298
|
let cloud = null;
|
|
271
299
|
if (hasCloud || provider === "cloud") {
|
|
272
300
|
cloud = createSavedAgentClient({ key: await cloudKey(root, exported) ?? "" });
|
|
@@ -276,7 +304,29 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
276
304
|
const answers = [];
|
|
277
305
|
const steps = [];
|
|
278
306
|
const named = new Map();
|
|
307
|
+
let history;
|
|
308
|
+
let sequenceNumber = 0;
|
|
309
|
+
const suggestions = new Map();
|
|
310
|
+
const recordLearning = value => {
|
|
311
|
+
if (process.env.LYRA_MEMORY === "off" || exported || suggestions.size >= 8 ||
|
|
312
|
+
!["corrective", "episodic", "semantic", "procedural"].includes(value?.type) ||
|
|
313
|
+
typeof value.title !== "string" || typeof value.learning !== "string") return;
|
|
314
|
+
const { type } = value;
|
|
315
|
+
const title = value.title.trim();
|
|
316
|
+
const learning = value.learning.trim();
|
|
317
|
+
if (!title || title.length > 160 || !learning || learning.length > 4000 ||
|
|
318
|
+
!eligibleText(title + " " + learning)) return;
|
|
319
|
+
suggestions.set(JSON.stringify([type, title, learning]), { type, title, learning });
|
|
320
|
+
};
|
|
321
|
+
const record = (type, data = {}) => {
|
|
322
|
+
const event = { schemaVersion: 1, runId: traceId, sequence: sequenceNumber++,
|
|
323
|
+
type, timestamp: new Date().toISOString(), ...data };
|
|
324
|
+
history?.append(event, type === "run.completed" ? [...suggestions.values()] : undefined);
|
|
325
|
+
try { onEvent?.(event); } catch {}
|
|
326
|
+
};
|
|
279
327
|
try {
|
|
328
|
+
if (!exported) history = await openRunHistory(root);
|
|
329
|
+
record("run.started");
|
|
280
330
|
for (const step of sequence) {
|
|
281
331
|
const agent = catalog.agents.get(step.agentId);
|
|
282
332
|
const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
|
|
@@ -285,9 +335,19 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
285
335
|
steps.push(status);
|
|
286
336
|
console.info('[Lyra Studio]', JSON.stringify({ event: 'step.started', traceId: status.traceId, agent: agent.name, source: agent.source }));
|
|
287
337
|
const started = Date.now();
|
|
338
|
+
record("step.started", stepEventFields(agent.id, status));
|
|
288
339
|
let output;
|
|
289
340
|
let run;
|
|
341
|
+
let activityCount = 0;
|
|
342
|
+
const recordActivity = event => {
|
|
343
|
+
if (activityCount >= 10 || typeof event?.id !== "string" ||
|
|
344
|
+
!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,95}$/.test(event.id) ||
|
|
345
|
+
typeof event.type !== "string" || !/^(tool|model|skill|evaluation)\.(started|completed|failed)$|^tool\.(requested|responded)$/.test(event.type)) return;
|
|
346
|
+
activityCount++;
|
|
347
|
+
record(event.type, { index: status.index, stepId: status.traceId, activityId: event.id });
|
|
348
|
+
};
|
|
290
349
|
try {
|
|
350
|
+
signal?.throwIfAborted();
|
|
291
351
|
if (["local", "cloud"].includes(agent.source) && provider === "cloud") {
|
|
292
352
|
const result = agent.source === "cloud" ? await cloud.invokeWithTrace(agent.id.slice("cloud:".length), text, status.traceId) : await cloud.invokeLocal(agent, text, status.traceId);
|
|
293
353
|
output = result.output;
|
|
@@ -296,55 +356,78 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
296
356
|
status.model = result.model || null;
|
|
297
357
|
} else if (agent.source === "python") {
|
|
298
358
|
output = await runPythonAgent(root, agent, text, exported);
|
|
299
|
-
} else if (agent.source
|
|
359
|
+
} else if (["framework", "programmatic"].includes(agent.source)) {
|
|
300
360
|
let payload = text;
|
|
301
361
|
if (agent.input === "json") {
|
|
302
362
|
try { payload = JSON.parse(previous ?? input); }
|
|
303
363
|
catch { throw new Error("Provide valid JSON for " + agent.name + "."); }
|
|
304
364
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
365
|
+
if (agent.source === "programmatic") {
|
|
366
|
+
output = await runProgrammatic(root, agent, payload, recordActivity, recordLearning);
|
|
367
|
+
} else {
|
|
368
|
+
const traceId = status.traceId;
|
|
369
|
+
const revision = createHash("sha256").update(JSON.stringify(agent)).digest("hex");
|
|
370
|
+
const event = await runAgent({
|
|
371
|
+
agentId: agent.id, store, traceId, signal, framework: agent.framework, revision,
|
|
372
|
+
request: { model: "framework-managed", messages: [] },
|
|
373
|
+
provider: { complete: async (_request, options) => ({ text: await runFrameworkAgent(root, agent, payload, traceId, { ...options, onActivity: recordActivity }) }) },
|
|
374
|
+
});
|
|
375
|
+
status.runId = event.run_id;
|
|
376
|
+
if (event.type === "run.cancelled") signal.throwIfAborted();
|
|
377
|
+
if (event.type !== "run.completed") throw new Error(event.data.message + " Run " + event.run_id + " · Trace " + traceId + ".");
|
|
314
378
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
379
|
+
output = event.data.result.text;
|
|
380
|
+
run = { runId: event.run_id, traceId, framework: agent.framework };
|
|
381
|
+
}
|
|
382
|
+
} else if (!["openai", "vscode", "local-model"].includes(provider)) {
|
|
318
383
|
status.provider = provider;
|
|
319
384
|
const definition = agent.source === 'cloud' ? await cloud.definition(agent.id.slice(6)) : agent;
|
|
320
385
|
output = await completeCli(provider, root, definition.prompt + '\n\nUser input:\n' + text);
|
|
321
386
|
} else {
|
|
322
|
-
status.provider =
|
|
387
|
+
status.provider = provider;
|
|
323
388
|
status.model = model;
|
|
324
389
|
const definition = agent.source === "cloud" ? await cloud.definition(agent.id.slice(6)) : agent;
|
|
325
390
|
const request = { model, messages: [{ role: "system", content: definition.prompt }, { role: "user", content: text }] };
|
|
326
391
|
const event = await runAgent({
|
|
327
|
-
agentId: agent.id, store, traceId: status.traceId,
|
|
328
|
-
|
|
392
|
+
agentId: agent.id, store, traceId: status.traceId,
|
|
393
|
+
signal: provider === "vscode" ? signal : undefined,
|
|
394
|
+
provider: provider === "vscode"
|
|
395
|
+
? { complete: (request, options) => completeIde(request, { ...options, onDelta, onActivity: recordActivity }) }
|
|
396
|
+
: provider === "local-model" ? createLocalModelProvider(localModel) : createOpenAIProvider(openAIKey, fetch),
|
|
397
|
+
request: exported ? request : await withProjectMemory(root, await withGraphSnipContext(root, request, {
|
|
398
|
+
onContext: data => record("context.attached", { index: status.index, stepId: status.traceId, ...data }),
|
|
399
|
+
onUnavailable: () => record("context.unavailable", { index: status.index, stepId: status.traceId }),
|
|
400
|
+
}), {
|
|
401
|
+
onRetrieval: count => record("memory.retrieved", { index: status.index, stepId: status.traceId, count }),
|
|
402
|
+
onUnavailable: () => record("memory.unavailable", { index: status.index, stepId: status.traceId }),
|
|
403
|
+
}),
|
|
329
404
|
});
|
|
330
405
|
status.runId = event.run_id;
|
|
406
|
+
if (event.type === "run.cancelled") throw new Error("Run cancelled.");
|
|
331
407
|
if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
|
|
332
408
|
output = event.data.result.text;
|
|
409
|
+
status.usage = event.data.result.usage;
|
|
333
410
|
}
|
|
334
411
|
status.state = "completed";
|
|
335
412
|
} catch (error) {
|
|
336
|
-
status.state = "failed";
|
|
337
|
-
const message = error.code ? "Check the project files for " + agent.name + "." : error.message;
|
|
413
|
+
status.state = signal?.aborted ? "cancelled" : "failed";
|
|
414
|
+
const message = signal?.aborted ? "Run cancelled." : error.code ? "Check the project files for " + agent.name + "." : error.message;
|
|
338
415
|
throw Object.assign(new Error(message, { cause: error }), { progress: { traceId, steps, answers } });
|
|
339
416
|
} finally {
|
|
340
417
|
status.durationMs = Date.now() - started;
|
|
418
|
+
record("step." + status.state, stepEventFields(agent.id, status));
|
|
341
419
|
console.info('[Lyra Studio]', JSON.stringify({ event: 'step.' + status.state, ...status }));
|
|
342
420
|
}
|
|
343
421
|
if (step.output) named.set(step.output, output);
|
|
344
422
|
answers.push({ agent: agent.name, output, ...(run ? { run } : {}) });
|
|
345
423
|
}
|
|
424
|
+
record("run.completed");
|
|
346
425
|
return { answers, traceId, steps };
|
|
426
|
+
} catch (error) {
|
|
427
|
+
if (sequenceNumber > 1) record(signal?.aborted ? "run.cancelled" : "run.failed");
|
|
428
|
+
throw error;
|
|
347
429
|
} finally {
|
|
430
|
+
history?.close();
|
|
348
431
|
store?.close();
|
|
349
432
|
}
|
|
350
433
|
}
|
|
@@ -10,15 +10,39 @@ def main():
|
|
|
10
10
|
source, skill = sys.argv[1:]
|
|
11
11
|
payload = json.load(sys.stdin)
|
|
12
12
|
with redirect_stdout(sys.stderr):
|
|
13
|
-
|
|
13
|
+
if skill == "--programmatic":
|
|
14
|
+
from lyra import Agent
|
|
15
|
+
else:
|
|
16
|
+
from lyra.standalone import Agent
|
|
14
17
|
|
|
15
18
|
agent = runpy.run_path(source).get("agent")
|
|
16
19
|
if not isinstance(agent, Agent):
|
|
17
|
-
raise TypeError("Export a
|
|
18
|
-
|
|
20
|
+
raise TypeError("Export a Lyra Agent named 'agent'.")
|
|
21
|
+
if skill == "--programmatic":
|
|
22
|
+
activity = []
|
|
23
|
+
suggestions = []
|
|
24
|
+
|
|
25
|
+
def observe(event):
|
|
26
|
+
if len(activity) < 10:
|
|
27
|
+
activity.append(event)
|
|
28
|
+
|
|
29
|
+
def suggest(value):
|
|
30
|
+
if len(suggestions) < 3:
|
|
31
|
+
suggestions.append(value)
|
|
32
|
+
|
|
33
|
+
result = asyncio.run(agent.run(payload["input"], on_activity=observe, on_learning=suggest))
|
|
34
|
+
output = result.get("output")
|
|
35
|
+
else:
|
|
36
|
+
result = None
|
|
37
|
+
output = asyncio.run(agent.run(skill, payload["input"]))
|
|
19
38
|
if not isinstance(output, str):
|
|
20
39
|
output = json.dumps(output, allow_nan=False)
|
|
21
|
-
|
|
40
|
+
envelope = {"output": output}
|
|
41
|
+
if result is not None:
|
|
42
|
+
envelope["status"] = result["status"]
|
|
43
|
+
envelope["activity"] = activity
|
|
44
|
+
envelope["suggestions"] = suggestions
|
|
45
|
+
print(json.dumps(envelope))
|
|
22
46
|
|
|
23
47
|
|
|
24
48
|
if __name__ == "__main__":
|