agent-lyra 0.11.2 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -35
- package/bin/agent-lyra.js +4 -1
- package/bin/lyra-oss-preview.js +3 -1
- package/package.json +1 -1
- package/src/app-builder/init.js +3 -3
- 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 +13 -1
- package/src/intelligence/graph-setup.js +125 -0
- package/src/intelligence/lifecycle.js +4 -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/standalone/init.js +4 -2
- package/src/studio/browser.js +219 -23
- package/src/studio/code-discovery.js +81 -0
- package/src/studio/export.js +8 -5
- package/src/studio/graphsnip-workbench.js +72 -0
- package/src/studio/history-panel.js +193 -0
- package/src/studio/ide-provider.js +65 -0
- package/src/studio/index.html +69 -10
- package/src/studio/intelligence.js +110 -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 +54 -0
- package/src/studio/project.js +103 -25
- package/src/studio/python-agent.py +31 -4
- package/src/studio/run-history.js +128 -0
- package/src/studio/server.js +90 -10
- package/src/studio/session.js +1 -1
- package/src/studio/studio.css +128 -0
|
@@ -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,54 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { resolveAgentSource } from "./code-discovery.js";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
export function programmaticDescriptor(item) {
|
|
6
|
+
if (!["lyra-node", "lyra-python"].includes(item?.runtime)) return null;
|
|
7
|
+
const file = item.file;
|
|
8
|
+
const extension = item.runtime === "lyra-python" ? /\.py$/ : /\.(?:mjs|js|mts|ts)$/;
|
|
9
|
+
const projectRelative = item.projectRelative === true;
|
|
10
|
+
const validPath = projectRelative ? /^(?:[a-zA-Z0-9_.-]+\/)*[a-zA-Z0-9_-]+\.[a-z]+$/ : /^[A-Za-z0-9_][A-Za-z0-9_-]{0,95}\.[a-z]+$/;
|
|
11
|
+
if (typeof file !== "string" || !validPath.test(file) || file.split("/").some(part => part === "." || part === "..") ||
|
|
12
|
+
!extension.test(file) || !["text", "json", undefined].includes(item.input)) return null;
|
|
13
|
+
return { runtime: item.runtime, file, input: item.input ?? "text", ...(projectRelative ? { projectRelative } : {}) };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function runProgrammatic(root, agent, input, onActivity, onLearning) {
|
|
17
|
+
const source = await resolveAgentSource(root, agent.file, agent.projectRelative);
|
|
18
|
+
const python = agent.runtime === "lyra-python";
|
|
19
|
+
const executable = python
|
|
20
|
+
? process.env.LYRA_PYTHON || (process.platform === "win32" ? "py.exe" : "python3")
|
|
21
|
+
: process.execPath;
|
|
22
|
+
const runner = fileURLToPath(new URL(python ? "./python-agent.py" : "./programmatic-runner.mjs", import.meta.url));
|
|
23
|
+
const args = python ? [runner, source, "--programmatic"]
|
|
24
|
+
: [...(/\.m?ts$/.test(source) ? ["--experimental-strip-types"] : []), runner, source];
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const child = execFile(executable, args, {
|
|
27
|
+
cwd: root, timeout: 60_000, maxBuffer: 1024 * 1024, windowsHide: true,
|
|
28
|
+
}, (error, stdout) => {
|
|
29
|
+
if (error?.code === "ENOENT" && python) {
|
|
30
|
+
return reject(new Error("Install the Python SDK in your environment and set LYRA_PYTHON to its interpreter."));
|
|
31
|
+
}
|
|
32
|
+
if (error) return reject(new Error("The registered agent failed to load or run. Check its source and dependencies."));
|
|
33
|
+
try {
|
|
34
|
+
const result = JSON.parse(stdout);
|
|
35
|
+
if (Array.isArray(result.activity)) {
|
|
36
|
+
for (const event of result.activity.slice(0, 10)) onActivity?.(event);
|
|
37
|
+
}
|
|
38
|
+
if (result.status !== "completed") {
|
|
39
|
+
const status = ["blocked", "cancelled", "failed"].includes(result.status) ? result.status : "failed";
|
|
40
|
+
return reject(new Error("The registered agent run " + status + "."));
|
|
41
|
+
}
|
|
42
|
+
if (typeof result.output !== "string") throw new TypeError("Expected text output.");
|
|
43
|
+
if (Array.isArray(result.suggestions)) {
|
|
44
|
+
for (const suggestion of result.suggestions.slice(0, 3)) onLearning?.(suggestion);
|
|
45
|
+
}
|
|
46
|
+
resolve(result.output);
|
|
47
|
+
} catch {
|
|
48
|
+
reject(new Error("The registered agent returned an invalid response."));
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
child.stdin.on("error", () => {});
|
|
52
|
+
child.stdin.end(JSON.stringify({ input }));
|
|
53
|
+
});
|
|
54
|
+
}
|
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"];
|
|
@@ -49,7 +55,7 @@ export function readLocalAgent(source) {
|
|
|
49
55
|
if (mode === "cloud" && cloudId.test(id)) return { id: "cloud:" + id, name, source: "cloud" };
|
|
50
56
|
if (mode && mode !== "standalone") return null;
|
|
51
57
|
if (!prompt || prompt.length > 16_000) return null;
|
|
52
|
-
return { id: "local:" + id, name, source: "local", prompt };
|
|
58
|
+
return { id: "local:" + id, name, source: "local", description: markdownValue(front[1], "description"), prompt };
|
|
53
59
|
}
|
|
54
60
|
|
|
55
61
|
export async function readCatalog(root, { includeSkillInstructions = false } = {}) {
|
|
@@ -86,6 +92,13 @@ export async function readCatalog(root, { includeSkillInstructions = false } = {
|
|
|
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;
|
|
@@ -213,6 +226,7 @@ const runtimeLabels = {
|
|
|
213
226
|
local: { location: "Local project", provider: "OpenAI · selected in Studio" },
|
|
214
227
|
cloud: { location: "Lyra Cloud", provider: "OpenAI · configured in Lyra Cloud" },
|
|
215
228
|
python: { location: "Local Python", provider: "Managed by the Python agent" },
|
|
229
|
+
programmatic: { location: "Local project", provider: "Managed by the executable agent" },
|
|
216
230
|
framework: { location: "Local framework runtime", provider: "Managed by the framework agent" },
|
|
217
231
|
};
|
|
218
232
|
|
|
@@ -229,10 +243,14 @@ export async function describeRun(root, targets, appCatalog, provider) {
|
|
|
229
243
|
const hasCloud = agents.some(agent => agent.source === 'cloud');
|
|
230
244
|
let cloudAvailable = false;
|
|
231
245
|
try { createSavedAgentClient({ key: await cloudKey(root, Boolean(appCatalog)) ?? '' }); cloudAvailable = true; } catch {}
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
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 ?? [] : [];
|
|
235
252
|
const issues = [];
|
|
253
|
+
if (provider === "local-model" && localModel?.issue) issues.push(localModel.issue);
|
|
236
254
|
const needsOpenAIKey = needsModel && provider === "openai" &&
|
|
237
255
|
!(appCatalog ? process.env.OPENAI_API_KEY?.trim() : await readOpenAIKey());
|
|
238
256
|
if (needsOpenAIKey) issues.push(appCatalog
|
|
@@ -250,10 +268,10 @@ export async function describeRun(root, targets, appCatalog, provider) {
|
|
|
250
268
|
name: agent.name, framework: agent.framework, ...runtimeLabels[agent.source],
|
|
251
269
|
}));
|
|
252
270
|
if (needsModel && !providers.includes(provider)) issues.push('Selected provider is unavailable.');
|
|
253
|
-
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" };
|
|
254
272
|
}
|
|
255
273
|
|
|
256
|
-
export async function runSelection(root, { targets, input, model, provider }, catalog) {
|
|
274
|
+
export async function runSelection(root, { targets, input, model, provider }, catalog, { signal, onDelta, onEvent } = {}) {
|
|
257
275
|
if (typeof input !== "string" || !input.trim() || input.length > 4000) {
|
|
258
276
|
throw new Error("Enter up to 4,000 characters.");
|
|
259
277
|
}
|
|
@@ -265,13 +283,18 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
265
283
|
const hasCloud = agents.some(agent => agent.source === "cloud");
|
|
266
284
|
const cli = exported ? [] : await availableCliProviders();
|
|
267
285
|
provider ??= hasCloud ? "cloud" : "openai";
|
|
268
|
-
|
|
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.');
|
|
269
289
|
const openAIKey = local && provider === "openai"
|
|
270
290
|
? exported ? process.env.OPENAI_API_KEY?.trim() : await readOpenAIKey()
|
|
271
291
|
: undefined;
|
|
272
292
|
if (local && provider === "openai" && (!openAIKey || !modelId.test(model ?? ""))) {
|
|
273
293
|
throw new Error("Configure an OpenAI API key and choose a model for this run.");
|
|
274
294
|
}
|
|
295
|
+
if (local && provider === "local-model" && !localModel?.models?.includes(model)) {
|
|
296
|
+
throw new Error(localModel?.issue ?? "Choose a configured local model.");
|
|
297
|
+
}
|
|
275
298
|
let cloud = null;
|
|
276
299
|
if (hasCloud || provider === "cloud") {
|
|
277
300
|
cloud = createSavedAgentClient({ key: await cloudKey(root, exported) ?? "" });
|
|
@@ -281,7 +304,29 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
281
304
|
const answers = [];
|
|
282
305
|
const steps = [];
|
|
283
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
|
+
};
|
|
284
327
|
try {
|
|
328
|
+
if (!exported) history = await openRunHistory(root);
|
|
329
|
+
record("run.started");
|
|
285
330
|
for (const step of sequence) {
|
|
286
331
|
const agent = catalog.agents.get(step.agentId);
|
|
287
332
|
const previous = step.input ? named.get(step.input) : answers.at(-1)?.output;
|
|
@@ -290,9 +335,19 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
290
335
|
steps.push(status);
|
|
291
336
|
console.info('[Lyra Studio]', JSON.stringify({ event: 'step.started', traceId: status.traceId, agent: agent.name, source: agent.source }));
|
|
292
337
|
const started = Date.now();
|
|
338
|
+
record("step.started", { ...stepEventFields(agent.id, status), agentName: agent.name.slice(0, 160) });
|
|
293
339
|
let output;
|
|
294
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
|
+
};
|
|
295
349
|
try {
|
|
350
|
+
signal?.throwIfAborted();
|
|
296
351
|
if (["local", "cloud"].includes(agent.source) && provider === "cloud") {
|
|
297
352
|
const result = agent.source === "cloud" ? await cloud.invokeWithTrace(agent.id.slice("cloud:".length), text, status.traceId) : await cloud.invokeLocal(agent, text, status.traceId);
|
|
298
353
|
output = result.output;
|
|
@@ -301,55 +356,78 @@ export async function runSelection(root, { targets, input, model, provider }, ca
|
|
|
301
356
|
status.model = result.model || null;
|
|
302
357
|
} else if (agent.source === "python") {
|
|
303
358
|
output = await runPythonAgent(root, agent, text, exported);
|
|
304
|
-
} else if (agent.source
|
|
359
|
+
} else if (["framework", "programmatic"].includes(agent.source)) {
|
|
305
360
|
let payload = text;
|
|
306
361
|
if (agent.input === "json") {
|
|
307
362
|
try { payload = JSON.parse(previous ?? input); }
|
|
308
363
|
catch { throw new Error("Provide valid JSON for " + agent.name + "."); }
|
|
309
364
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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 + ".");
|
|
319
378
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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)) {
|
|
323
383
|
status.provider = provider;
|
|
324
384
|
const definition = agent.source === 'cloud' ? await cloud.definition(agent.id.slice(6)) : agent;
|
|
325
385
|
output = await completeCli(provider, root, definition.prompt + '\n\nUser input:\n' + text);
|
|
326
386
|
} else {
|
|
327
|
-
status.provider =
|
|
387
|
+
status.provider = provider;
|
|
328
388
|
status.model = model;
|
|
329
389
|
const definition = agent.source === "cloud" ? await cloud.definition(agent.id.slice(6)) : agent;
|
|
330
390
|
const request = { model, messages: [{ role: "system", content: definition.prompt }, { role: "user", content: text }] };
|
|
331
391
|
const event = await runAgent({
|
|
332
|
-
agentId: agent.id, store, traceId: status.traceId,
|
|
333
|
-
|
|
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
|
+
}),
|
|
334
404
|
});
|
|
335
405
|
status.runId = event.run_id;
|
|
406
|
+
if (event.type === "run.cancelled") throw new Error("Run cancelled.");
|
|
336
407
|
if (event.type !== "run.completed") throw new Error("The model could not complete " + agent.name + ".");
|
|
337
408
|
output = event.data.result.text;
|
|
409
|
+
status.usage = event.data.result.usage;
|
|
338
410
|
}
|
|
339
411
|
status.state = "completed";
|
|
340
412
|
} catch (error) {
|
|
341
|
-
status.state = "failed";
|
|
342
|
-
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;
|
|
343
415
|
throw Object.assign(new Error(message, { cause: error }), { progress: { traceId, steps, answers } });
|
|
344
416
|
} finally {
|
|
345
417
|
status.durationMs = Date.now() - started;
|
|
418
|
+
record("step." + status.state, stepEventFields(agent.id, status));
|
|
346
419
|
console.info('[Lyra Studio]', JSON.stringify({ event: 'step.' + status.state, ...status }));
|
|
347
420
|
}
|
|
348
421
|
if (step.output) named.set(step.output, output);
|
|
349
422
|
answers.push({ agent: agent.name, output, ...(run ? { run } : {}) });
|
|
350
423
|
}
|
|
424
|
+
record("run.completed");
|
|
351
425
|
return { answers, traceId, steps };
|
|
426
|
+
} catch (error) {
|
|
427
|
+
if (sequenceNumber > 1) record(signal?.aborted ? "run.cancelled" : "run.failed");
|
|
428
|
+
throw error;
|
|
352
429
|
} finally {
|
|
430
|
+
history?.close();
|
|
353
431
|
store?.close();
|
|
354
432
|
}
|
|
355
433
|
}
|
|
@@ -3,6 +3,7 @@ import asyncio
|
|
|
3
3
|
import json
|
|
4
4
|
import runpy
|
|
5
5
|
import sys
|
|
6
|
+
from pathlib import Path
|
|
6
7
|
from contextlib import redirect_stdout
|
|
7
8
|
|
|
8
9
|
|
|
@@ -10,15 +11,41 @@ def main():
|
|
|
10
11
|
source, skill = sys.argv[1:]
|
|
11
12
|
payload = json.load(sys.stdin)
|
|
12
13
|
with redirect_stdout(sys.stderr):
|
|
13
|
-
|
|
14
|
+
if skill == "--programmatic":
|
|
15
|
+
sys.path.insert(0, str(Path.cwd()))
|
|
16
|
+
sys.path.insert(0, str(Path(source).parent))
|
|
17
|
+
from lyra import Agent
|
|
18
|
+
else:
|
|
19
|
+
from lyra.standalone import Agent
|
|
14
20
|
|
|
15
21
|
agent = runpy.run_path(source).get("agent")
|
|
16
22
|
if not isinstance(agent, Agent):
|
|
17
|
-
raise TypeError("Export a
|
|
18
|
-
|
|
23
|
+
raise TypeError("Export a Lyra Agent named 'agent'.")
|
|
24
|
+
if skill == "--programmatic":
|
|
25
|
+
activity = []
|
|
26
|
+
suggestions = []
|
|
27
|
+
|
|
28
|
+
def observe(event):
|
|
29
|
+
if len(activity) < 10:
|
|
30
|
+
activity.append(event)
|
|
31
|
+
|
|
32
|
+
def suggest(value):
|
|
33
|
+
if len(suggestions) < 3:
|
|
34
|
+
suggestions.append(value)
|
|
35
|
+
|
|
36
|
+
result = asyncio.run(agent.run(payload["input"], on_activity=observe, on_learning=suggest))
|
|
37
|
+
output = result.get("output")
|
|
38
|
+
else:
|
|
39
|
+
result = None
|
|
40
|
+
output = asyncio.run(agent.run(skill, payload["input"]))
|
|
19
41
|
if not isinstance(output, str):
|
|
20
42
|
output = json.dumps(output, allow_nan=False)
|
|
21
|
-
|
|
43
|
+
envelope = {"output": output}
|
|
44
|
+
if result is not None:
|
|
45
|
+
envelope["status"] = result["status"]
|
|
46
|
+
envelope["activity"] = activity
|
|
47
|
+
envelope["suggestions"] = suggestions
|
|
48
|
+
print(json.dumps(envelope))
|
|
22
49
|
|
|
23
50
|
|
|
24
51
|
if __name__ == "__main__":
|