agent-lyra 0.11.2 → 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 +45 -35
- package/bin/agent-lyra.js +1 -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 +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 +125 -19
- 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 +102 -24
- package/src/studio/python-agent.py +28 -4
- package/src/studio/run-history.js +119 -0
- package/src/studio/server.js +77 -8
- package/src/studio/session.js +1 -1
- package/src/studio/studio.css +76 -0
|
@@ -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"];
|
|
@@ -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));
|
|
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
|
}
|
|
@@ -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__":
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { lstat, mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
const defaultRetentionDays = 30;
|
|
6
|
+
const maxEvents = 128;
|
|
7
|
+
|
|
8
|
+
function retentionDays() {
|
|
9
|
+
const value = Number(process.env.LYRA_RUN_HISTORY_DAYS ?? defaultRetentionDays);
|
|
10
|
+
return Number.isInteger(value) && value >= 1 && value <= 365 ? value : defaultRetentionDays;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function openRunHistory(root) {
|
|
14
|
+
const state = join(root, ".lyra", "state");
|
|
15
|
+
await mkdir(state, { recursive: true, mode: 0o700 });
|
|
16
|
+
for (const path of [join(root, ".lyra"), state]) {
|
|
17
|
+
if (!(await lstat(path)).isDirectory()) throw new Error("Run history requires regular project directories.");
|
|
18
|
+
}
|
|
19
|
+
await writeFile(join(state, ".gitignore"), "*\n", { flag: "wx" }).catch(error => {
|
|
20
|
+
if (error.code !== "EEXIST") throw error;
|
|
21
|
+
});
|
|
22
|
+
const path = join(state, "runs.sqlite");
|
|
23
|
+
const stat = await lstat(path).catch(error => {
|
|
24
|
+
if (error.code === "ENOENT") return undefined;
|
|
25
|
+
throw error;
|
|
26
|
+
});
|
|
27
|
+
if (stat && !stat.isFile()) throw new Error("Run history requires a regular SQLite file.");
|
|
28
|
+
const db = new DatabaseSync(path);
|
|
29
|
+
try {
|
|
30
|
+
db.exec(`
|
|
31
|
+
PRAGMA busy_timeout = 5000;
|
|
32
|
+
PRAGMA foreign_keys = ON;
|
|
33
|
+
CREATE TABLE IF NOT EXISTS studio_runs (
|
|
34
|
+
id TEXT PRIMARY KEY, started_at TEXT NOT NULL, status TEXT NOT NULL, ended_at TEXT
|
|
35
|
+
);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS studio_runs_started ON studio_runs(started_at DESC);
|
|
37
|
+
CREATE TABLE IF NOT EXISTS studio_run_learnings (
|
|
38
|
+
run_id TEXT NOT NULL REFERENCES studio_runs(id) ON DELETE CASCADE,
|
|
39
|
+
position INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(run_id, position)
|
|
40
|
+
);
|
|
41
|
+
CREATE TABLE IF NOT EXISTS studio_run_events (
|
|
42
|
+
run_id TEXT NOT NULL REFERENCES studio_runs(id) ON DELETE CASCADE,
|
|
43
|
+
sequence INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(run_id, sequence)
|
|
44
|
+
);
|
|
45
|
+
`);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
db.close();
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
const insertRun = db.prepare("INSERT INTO studio_runs (id, started_at, status) VALUES (?, ?, 'running')");
|
|
51
|
+
const insertEvent = db.prepare("INSERT INTO studio_run_events (run_id, sequence, body) VALUES (?, ?, ?)");
|
|
52
|
+
const finishRun = db.prepare("UPDATE studio_runs SET status = ?, ended_at = ? WHERE id = ? AND status = 'running'");
|
|
53
|
+
const prune = db.prepare("DELETE FROM studio_runs WHERE started_at < ?");
|
|
54
|
+
const list = db.prepare("SELECT id, started_at AS startedAt, status, ended_at AS endedAt FROM studio_runs ORDER BY started_at DESC, id LIMIT 100");
|
|
55
|
+
const detail = db.prepare("SELECT id, started_at AS startedAt, status, ended_at AS endedAt FROM studio_runs WHERE id = ?");
|
|
56
|
+
const insertLearning = db.prepare("INSERT INTO studio_run_learnings (run_id, position, body) VALUES (?, ?, ?)");
|
|
57
|
+
const readLearnings = db.prepare("SELECT body FROM studio_run_learnings WHERE run_id = ? ORDER BY position");
|
|
58
|
+
const events = db.prepare("SELECT body FROM studio_run_events WHERE run_id = ? ORDER BY sequence LIMIT ?");
|
|
59
|
+
function transaction(work) {
|
|
60
|
+
db.exec("BEGIN IMMEDIATE");
|
|
61
|
+
try {
|
|
62
|
+
const result = work();
|
|
63
|
+
db.exec("COMMIT");
|
|
64
|
+
return result;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
db.exec("ROLLBACK");
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
append(event, suggestions = []) {
|
|
72
|
+
transaction(() => {
|
|
73
|
+
if (event.type === "run.started") {
|
|
74
|
+
const cutoff = new Date(Date.now() - retentionDays() * 86_400_000).toISOString();
|
|
75
|
+
prune.run(cutoff);
|
|
76
|
+
insertRun.run(event.runId, event.timestamp);
|
|
77
|
+
} else if (event.type.startsWith("run.")) {
|
|
78
|
+
finishRun.run(event.type.slice(4), event.timestamp, event.runId);
|
|
79
|
+
}
|
|
80
|
+
if (event.sequence >= maxEvents) throw new Error("Studio run event limit exceeded.");
|
|
81
|
+
insertEvent.run(event.runId, event.sequence, JSON.stringify(event));
|
|
82
|
+
if (event.type === "run.completed") {
|
|
83
|
+
for (const [index, suggestion] of suggestions.entries()) {
|
|
84
|
+
insertLearning.run(event.runId, index, JSON.stringify(suggestion));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
list: () => list.all(),
|
|
90
|
+
suggestions(id) {
|
|
91
|
+
if (detail.get(id)?.status !== "completed") return [];
|
|
92
|
+
return readLearnings.all(id).map(row => JSON.parse(row.body));
|
|
93
|
+
},
|
|
94
|
+
withCompletedRun(id, action) {
|
|
95
|
+
return transaction(() => {
|
|
96
|
+
if (detail.get(id)?.status !== "completed") throw new Error("Choose a completed run in this project.");
|
|
97
|
+
return action();
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
get(id) {
|
|
101
|
+
const run = detail.get(id);
|
|
102
|
+
return run && { schemaVersion: 1, run, events: events.all(id, maxEvents).map(row => JSON.parse(row.body)) };
|
|
103
|
+
},
|
|
104
|
+
close: () => db.close(),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const short = value => typeof value === "string" ? value.slice(0, 160) : undefined;
|
|
109
|
+
export function stepEventFields(agentId, step) {
|
|
110
|
+
const usage = Object.fromEntries(Object.entries(step.usage ?? {}).filter(([key, value]) =>
|
|
111
|
+
["inputTokens", "outputTokens"].includes(key) && Number.isSafeInteger(value) && value >= 0));
|
|
112
|
+
return {
|
|
113
|
+
agentId: short(agentId), source: short(step.source), stepId: short(step.traceId),
|
|
114
|
+
runtimeRunId: short(step.runId), index: step.index,
|
|
115
|
+
provider: short(step.provider), model: short(step.model),
|
|
116
|
+
durationMs: step.durationMs,
|
|
117
|
+
...(Object.keys(usage).length ? { usage } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|