agent-lyra 0.8.0 → 0.11.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.
Files changed (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +320 -291
  3. package/bin/agent-lyra.js +51 -51
  4. package/bin/lyra-oss-preview.js +16 -16
  5. package/package.json +60 -60
  6. package/src/app-builder/export.js +109 -109
  7. package/src/app-builder/gateway.js +62 -62
  8. package/src/app-builder/init.js +115 -72
  9. package/src/app-builder/manifest-contract.js +46 -46
  10. package/src/app-builder/native-adapter.js +29 -29
  11. package/src/app-builder/preview.js +35 -31
  12. package/src/app-builder/publish.js +14 -14
  13. package/src/app-builder/saved-app.js +73 -70
  14. package/src/app-builder/saved-preview-browser.js +33 -33
  15. package/src/app-builder/saved-preview.html +24 -24
  16. package/src/app-builder/saved-preview.js +61 -61
  17. package/src/app-builder/support-manifest.js +50 -50
  18. package/src/app-builder/support-template/manifest.json +55 -55
  19. package/src/app-builder/support-template/support-preview.html +56 -56
  20. package/src/app-builder/support-template/support-preview.js +37 -37
  21. package/src/app-builder/support-template/support-preview.mjs +67 -67
  22. package/src/app-builder/support-template/support-workflow.mjs +36 -36
  23. package/src/app-builder/use.js +37 -37
  24. package/src/app-builder/validate.js +31 -21
  25. package/src/app-builder/value-schema.js +37 -37
  26. package/src/catalog.js +147 -147
  27. package/src/coding/catalog.js +56 -56
  28. package/src/coding/cloud-catalog.js +64 -64
  29. package/src/coding/detect-stack.mjs +110 -110
  30. package/src/coding/export.js +133 -133
  31. package/src/coding/setup.js +175 -175
  32. package/src/coding/skills/lyra-android/SKILL.md +37 -37
  33. package/src/coding/skills/lyra-angular/SKILL.md +37 -37
  34. package/src/coding/skills/lyra-cucumber/SKILL.md +37 -37
  35. package/src/coding/skills/lyra-dbt/SKILL.md +37 -37
  36. package/src/coding/skills/lyra-django/SKILL.md +37 -37
  37. package/src/coding/skills/lyra-docker/SKILL.md +37 -37
  38. package/src/coding/skills/lyra-dotnet/SKILL.md +37 -37
  39. package/src/coding/skills/lyra-express/SKILL.md +37 -37
  40. package/src/coding/skills/lyra-fastapi/SKILL.md +37 -37
  41. package/src/coding/skills/lyra-flutter/SKILL.md +37 -37
  42. package/src/coding/skills/lyra-github-actions/SKILL.md +37 -37
  43. package/src/coding/skills/lyra-gitlab-ci/SKILL.md +37 -37
  44. package/src/coding/skills/lyra-go/SKILL.md +37 -37
  45. package/src/coding/skills/lyra-ios/SKILL.md +37 -37
  46. package/src/coding/skills/lyra-kubernetes/SKILL.md +37 -37
  47. package/src/coding/skills/lyra-mongodb/SKILL.md +37 -37
  48. package/src/coding/skills/lyra-mysql/SKILL.md +37 -37
  49. package/src/coding/skills/lyra-nextjs/SKILL.md +37 -37
  50. package/src/coding/skills/lyra-node/SKILL.md +37 -37
  51. package/src/coding/skills/lyra-playwright/SKILL.md +37 -37
  52. package/src/coding/skills/lyra-postgresql/SKILL.md +37 -37
  53. package/src/coding/skills/lyra-python/SKILL.md +37 -37
  54. package/src/coding/skills/lyra-react/SKILL.md +37 -37
  55. package/src/coding/skills/lyra-react-native/SKILL.md +37 -37
  56. package/src/coding/skills/lyra-redis/SKILL.md +37 -37
  57. package/src/coding/skills/lyra-rust/SKILL.md +37 -37
  58. package/src/coding/skills/lyra-spark/SKILL.md +37 -37
  59. package/src/coding/skills/lyra-spring-boot/SKILL.md +37 -37
  60. package/src/coding/skills/lyra-svelte/SKILL.md +37 -37
  61. package/src/coding/skills/lyra-terraform/SKILL.md +37 -37
  62. package/src/coding/skills/lyra-typescript/SKILL.md +37 -37
  63. package/src/coding/skills/lyra-vue/SKILL.md +37 -37
  64. package/src/framework/agent.js +181 -181
  65. package/src/framework/mda.js +65 -65
  66. package/src/framework/run.py +111 -111
  67. package/src/gated/hostedAgents.js +56 -56
  68. package/src/gated/index.d.ts +25 -25
  69. package/src/gated/index.js +5 -5
  70. package/src/index.d.ts +2 -2
  71. package/src/index.js +2 -2
  72. package/src/init.js +963 -960
  73. package/src/intelligence/graphsnip-provider.d.ts +5 -5
  74. package/src/intelligence/graphsnip-provider.js +57 -57
  75. package/src/intelligence/lifecycle.js +25 -25
  76. package/src/memory/LICENSE +21 -21
  77. package/src/memory/README.md +5 -5
  78. package/src/memory/UPSTREAM.json +24 -24
  79. package/src/memory/bridge-cli.js +16 -16
  80. package/src/memory/bridge.js +18 -18
  81. package/src/memory/cli.js +21 -21
  82. package/src/memory/cloud-sync-actions.js +61 -61
  83. package/src/memory/contract.json +45 -45
  84. package/src/memory/index.d.ts +50 -50
  85. package/src/memory/index.js +7 -7
  86. package/src/memory/lifecycle.js +29 -29
  87. package/src/memory/local-cli.js +34 -34
  88. package/src/memory/local-store.js +209 -209
  89. package/src/memory/package.json +33 -33
  90. package/src/memory/proposals.js +90 -90
  91. package/src/memory/skills-cli.js +26 -26
  92. package/src/memory/standalone.d.ts +50 -50
  93. package/src/memory/standalone.js +1 -1
  94. package/src/memory/sync.js +89 -89
  95. package/src/memory/validation.js +25 -25
  96. package/src/onboardingAgents.js +532 -532
  97. package/src/promptTemplates.js +178 -178
  98. package/src/resource-files.js +18 -18
  99. package/src/runtime/contracts.d.ts +47 -47
  100. package/src/runtime/local-cli.js +161 -161
  101. package/src/runtime/mcp-stdio.js +111 -111
  102. package/src/runtime/orchestration.js +59 -59
  103. package/src/runtime/run-agent.js +54 -54
  104. package/src/standalone/index.d.ts +45 -45
  105. package/src/standalone/index.js +13 -13
  106. package/src/standalone/init.js +14 -12
  107. package/src/standalone/orchestration.js +6 -6
  108. package/src/standalone/rag.js +113 -113
  109. package/src/studio/agent-ui.css +43 -43
  110. package/src/studio/agent-ui.js +32 -32
  111. package/src/studio/browser.js +562 -345
  112. package/src/studio/cli-providers.js +40 -0
  113. package/src/studio/export.js +83 -86
  114. package/src/studio/index.html +74 -37
  115. package/src/studio/memory-actions.js +37 -37
  116. package/src/studio/memory-panel.js +200 -200
  117. package/src/studio/project.js +333 -240
  118. package/src/studio/pull-agent.js +72 -72
  119. package/src/studio/push.js +54 -54
  120. package/src/studio/python-agent.js +47 -47
  121. package/src/studio/python-agent.py +25 -25
  122. package/src/studio/server.js +164 -150
  123. package/src/studio/session.js +83 -83
  124. package/src/studio/studio.css +257 -10
  125. package/src/studio/sync.js +42 -42
  126. package/src/studio/workflow-editor.js +240 -0
  127. package/src/studio/workflow-sync.js +229 -157
  128. package/src/vscode/workspace.js +158 -0
@@ -1,157 +1,229 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
3
- import { join, resolve } from "node:path";
4
- import { readMode, readSdkKey, requireCloudMode } from "./session.js";
5
-
6
- const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
7
- const objectId = /^[a-f0-9]{24}$/i;
8
- const digest = /^[a-f0-9]{64}$/;
9
- const hash = value => createHash("sha256").update(value).digest("hex");
10
-
11
- async function json(path) {
12
- if (!(await lstat(path)).isFile()) throw new Error("Use a regular definition or link file.");
13
- const content = await readFile(path, "utf8");
14
- return { content, value: JSON.parse(content.replace(/^\uFEFF/, "")) };
15
- }
16
-
17
- async function replace(path, content) {
18
- const temporary = path + "." + randomUUID() + ".tmp";
19
- await writeFile(temporary, content, { flag: "wx", mode: 0o600 });
20
- try { await rename(temporary, path); }
21
- finally { await unlink(temporary).catch(() => {}); }
22
- }
23
-
24
- async function cloudAgentId(base, target) {
25
- let agentId = typeof target === "string" && target.startsWith("cloud:") ? target.slice(6) : "";
26
- if (typeof target === "string" && target.startsWith("local:") && safeId.test(target.slice(6))) {
27
- const folder = join(base, "agent-links");
28
- try {
29
- if (!(await lstat(folder)).isDirectory()) throw new Error();
30
- const linked = (await json(join(folder, target.slice(6) + ".json"))).value;
31
- agentId = linked.cloudId;
32
- } catch {
33
- throw new Error("Push agent " + target.slice(6) + " to Cloud before syncing this definition.");
34
- }
35
- }
36
- if (typeof agentId !== "string" || !objectId.test(agentId)) throw new Error("Use an agent linked to Cloud.");
37
- return agentId.toLowerCase();
38
- }
39
-
40
- async function cloudDefinition(base, workflow) {
41
- if (typeof workflow.name !== "string" || !workflow.name.trim() || (workflow.description != null && typeof workflow.description !== "string") ||
42
- !Array.isArray(workflow.steps) || workflow.steps.length < 2 || workflow.steps.length > 8) {
43
- throw new Error("Use a workflow name, optional text description, and two to eight steps.");
44
- }
45
- const steps = [];
46
- for (const item of workflow.steps) {
47
- if (typeof item?.task !== "string") throw new Error("Each workflow step needs a task.");
48
- const agentId = await cloudAgentId(base, item.agentId);
49
- steps.push({ agentId, task: item.task.trim(), input: item.input ?? null, output: item.output ?? null });
50
- }
51
- return { name: workflow.name.trim(), description: workflow.description?.trim() || "Sequential workflow from Studio.", steps };
52
- }
53
-
54
- async function cloudTeam(base, team) {
55
- if (typeof team.name !== "string" || !team.name.trim() ||
56
- (team.description != null && typeof team.description !== "string") ||
57
- !Array.isArray(team.agentIds) || team.agentIds.length > 30) {
58
- throw new Error("Use a team name, an optional description, and up to 30 agent assignments.");
59
- }
60
- const ids = await Promise.all(team.agentIds.map(agent => cloudAgentId(base, agent)));
61
- return { name: team.name.trim(), description: team.description?.trim() ?? "",
62
- agentIds: [...new Set(ids)].sort() };
63
- }
64
-
65
- function cloudSkill(skill) {
66
- if (typeof skill.name !== "string" || !skill.name.trim() || skill.name.length > 64 ||
67
- typeof skill.description !== "string" || !skill.description.trim() || skill.description.length > 1024 ||
68
- typeof skill.body !== "string" || !skill.body.trim() || skill.body.length > 16000) {
69
- throw new Error("Use a text skill with a name, description, and instructions.");
70
- }
71
- return { name: skill.name.trim(), description: skill.description.trim(), body: skill.body.trim() };
72
- }
73
-
74
- async function applyRemote(resource, base, value, local, remote) {
75
- if (resource === "skill") return { ...value, ...remote };
76
- if (resource === "team") {
77
- const byCloud = new Map(await Promise.all(value.agentIds.map(async id => [await cloudAgentId(base, id), id])));
78
- return { ...value, ...remote, agentIds: remote.agentIds.map(id => byCloud.get(id) ?? "cloud:" + id) };
79
- }
80
- const byCloud = new Map(local.steps.map((step, index) => [step.agentId, value.steps[index].agentId]));
81
- return { ...value, ...remote,
82
- steps: remote.steps.map(step => ({ ...step, agentId: byCloud.get(step.agentId) ?? "cloud:" + step.agentId })) };
83
- }
84
-
85
- export function syncWorkflow(root, id, action, options) {
86
- return syncResource("workflow", root, id, action, options);
87
- }
88
-
89
- export function syncTeam(root, id, action, options) {
90
- return syncResource("team", root, id, action, options);
91
- }
92
-
93
- export function syncSkill(root, id, action, options) {
94
- return syncResource("skill", root, id, action, options);
95
- }
96
-
97
- const cloudDefinitions = { workflow: cloudDefinition, team: cloudTeam, skill: (_base, skill) => cloudSkill(skill) };
98
-
99
- async function syncResource(resource, root, id, action, { key, request = fetch } = {}) {
100
- requireCloudMode(await readMode(root));
101
- if (typeof id !== "string" || !safeId.test(id)) throw new Error("Choose a local " + resource + " ID.");
102
- const base = join(root, ".lyra");
103
- const folder = join(base, resource + "s");
104
- for (const path of [base, folder]) {
105
- if (!(await lstat(path).catch(() => null))?.isDirectory()) throw new Error("Use a regular .lyra/" + resource + "s folder.");
106
- }
107
- const matches = [];
108
- for (const entry of await readdir(folder, { withFileTypes: true })) {
109
- if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
110
- const path = join(folder, entry.name);
111
- let file;
112
- try { file = await json(path); }
113
- catch (error) { if (error instanceof SyntaxError) continue; throw error; }
114
- if (file.value?.id === id && file.value.source !== "cloud") matches.push({ ...file, path });
115
- }
116
- if (matches.length !== 1) throw new Error("Choose a unique local " + resource + ".");
117
- const [{ path, content, value }] = matches;
118
- const local = await cloudDefinitions[resource](base, value);
119
- const localRevision = hash(JSON.stringify(local));
120
- const links = join(base, resource + "-links");
121
- await mkdir(links, { recursive: true });
122
- if (!(await lstat(links)).isDirectory()) throw new Error("Cloud links must use a regular directory.");
123
- const metadata = join(links, id + ".json");
124
- let link;
125
- try {
126
- link = (await json(metadata)).value;
127
- if (!digest.test(link?.linkId ?? "") || !digest.test(link?.revision ?? "") || !objectId.test(link?.cloudId ?? "")) {
128
- throw new Error("Invalid Cloud " + resource + " link.");
129
- }
130
- } catch (error) {
131
- if (error.code !== "ENOENT") throw error;
132
- }
133
- if (action === "pull" && !link) throw new Error("Push this " + resource + " once to link it to Cloud.");
134
- key ??= await readSdkKey(root);
135
- if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before syncing.");
136
- const linkId = link?.linkId ?? hash(resolve(root) + "\0" + resource + ":" + id);
137
- const push = action === "push";
138
- const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/" + resource + "s/" + linkId, {
139
- method: push ? "PUT" : "GET",
140
- headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
141
- body: push ? JSON.stringify({ [resource]: local, revision: link?.revision }) : undefined,
142
- redirect: "error", signal: AbortSignal.timeout(20_000),
143
- });
144
- const result = await response.json();
145
- if (!response.ok) throw new Error(result.error || "Could not sync the Cloud " + resource + ".");
146
- if (!objectId.test(result.id ?? "") || !digest.test(result.revision ?? "") ||
147
- (link && result.id !== link.cloudId)) throw new Error("The Cloud " + resource + " link no longer matches.");
148
- if (!push && result.revision !== link.revision && result.revision !== localRevision) {
149
- if (localRevision !== link.revision) throw new Error("Both copies changed. Review their edits before syncing.");
150
- if (!result[resource] || hash(JSON.stringify(result[resource])) !== result.revision) throw new Error("Invalid Cloud response.");
151
- const next = await applyRemote(resource, base, value, local, result[resource]);
152
- if ((await readFile(path, "utf8")) !== content) throw new Error("The local " + resource + " changed during sync. Try again.");
153
- await replace(path, JSON.stringify(next, null, 2) + "\n");
154
- }
155
- await replace(metadata, JSON.stringify({ linkId, cloudId: result.id, revision: result.revision }) + "\n");
156
- return { name: push ? local.name : result[resource].name, created: response.status === 201, updated: !push && result.revision !== localRevision && result.revision !== link.revision };
157
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { readMode, readSdkKey, requireCloudMode } from "./session.js";
5
+
6
+ const safeId = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,95}$/;
7
+ const objectId = /^[a-f0-9]{24}$/i;
8
+ const digest = /^[a-f0-9]{64}$/;
9
+ const hash = value => createHash("sha256").update(value).digest("hex");
10
+
11
+ async function json(path) {
12
+ if (!(await lstat(path)).isFile()) throw new Error("Use a regular definition or link file.");
13
+ const content = await readFile(path, "utf8");
14
+ return { content, value: JSON.parse(content.replace(/^\uFEFF/, "")) };
15
+ }
16
+
17
+ async function replace(path, content) {
18
+ const temporary = path + "." + randomUUID() + ".tmp";
19
+ await writeFile(temporary, content, { flag: "wx", mode: 0o600 });
20
+ try { await rename(temporary, path); }
21
+ finally { await unlink(temporary).catch(() => {}); }
22
+ }
23
+
24
+ async function cloudAgentId(base, target) {
25
+ let agentId = typeof target === "string" && target.startsWith("cloud:") ? target.slice(6) : "";
26
+ if (typeof target === "string" && target.startsWith("local:") && safeId.test(target.slice(6))) {
27
+ const folder = join(base, "agent-links");
28
+ try {
29
+ if (!(await lstat(folder)).isDirectory()) throw new Error();
30
+ const linked = (await json(join(folder, target.slice(6) + ".json"))).value;
31
+ agentId = linked.cloudId;
32
+ } catch {
33
+ throw new Error("Push agent " + target.slice(6) + " to Cloud before syncing this definition.");
34
+ }
35
+ }
36
+ if (typeof agentId !== "string" || !objectId.test(agentId)) throw new Error("Use an agent linked to Cloud.");
37
+ return agentId.toLowerCase();
38
+ }
39
+
40
+ async function cloudDefinition(base, workflow) {
41
+ if (typeof workflow.name !== "string" || !workflow.name.trim() || (workflow.description != null && typeof workflow.description !== "string") ||
42
+ !Array.isArray(workflow.steps) || workflow.steps.length < 2 || workflow.steps.length > 8) {
43
+ throw new Error("Use a workflow name, optional text description, and two to eight steps.");
44
+ }
45
+ const steps = [];
46
+ for (const item of workflow.steps) {
47
+ if (typeof item?.task !== "string") throw new Error("Each workflow step needs a task.");
48
+ const agentId = await cloudAgentId(base, item.agentId);
49
+ steps.push({ agentId, task: item.task.trim(), input: item.input ?? null, output: item.output ?? null });
50
+ }
51
+ return { name: workflow.name.trim(), description: workflow.description?.trim() || "Sequential workflow from Studio.", steps };
52
+ }
53
+
54
+ async function cloudTeam(base, team) {
55
+ if (typeof team.name !== "string" || !team.name.trim() ||
56
+ (team.description != null && typeof team.description !== "string") ||
57
+ !Array.isArray(team.agentIds) || team.agentIds.length > 30) {
58
+ throw new Error("Use a team name, an optional description, and up to 30 agent assignments.");
59
+ }
60
+ const ids = await Promise.all(team.agentIds.map(agent => cloudAgentId(base, agent)));
61
+ return { name: team.name.trim(), description: team.description?.trim() ?? "",
62
+ agentIds: [...new Set(ids)].sort() };
63
+ }
64
+
65
+ function cloudSkill(skill) {
66
+ if (typeof skill.name !== "string" || !skill.name.trim() || skill.name.length > 64 ||
67
+ typeof skill.description !== "string" || !skill.description.trim() || skill.description.length > 1024 ||
68
+ typeof skill.body !== "string" || !skill.body.trim() || skill.body.length > 16000) {
69
+ throw new Error("Use a text skill with a name, description, and instructions.");
70
+ }
71
+ return { name: skill.name.trim(), description: skill.description.trim(), body: skill.body.trim() };
72
+ }
73
+
74
+ async function applyRemote(resource, base, value, local, remote) {
75
+ if (resource === "skill") return { ...value, ...remote };
76
+ if (resource === "team") {
77
+ const byCloud = new Map(await Promise.all(value.agentIds.map(async id => [await cloudAgentId(base, id), id])));
78
+ return { ...value, ...remote, agentIds: remote.agentIds.map(id => byCloud.get(id) ?? "cloud:" + id) };
79
+ }
80
+ const byCloud = new Map(local.steps.map((step, index) => [step.agentId, value.steps[index].agentId]));
81
+ return { ...value, ...remote,
82
+ steps: remote.steps.map(step => ({ ...step, agentId: byCloud.get(step.agentId) ?? "cloud:" + step.agentId })) };
83
+ }
84
+
85
+ export function syncWorkflow(root, id, action, options) {
86
+ return syncResource("workflow", root, id, action, options);
87
+ }
88
+
89
+ export function syncTeam(root, id, action, options) {
90
+ return syncResource("team", root, id, action, options);
91
+ }
92
+
93
+ export function syncSkill(root, id, action, options) {
94
+ return syncResource("skill", root, id, action, options);
95
+ }
96
+
97
+ async function workflowFolder(root, create = false) {
98
+ const base = join(root, ".lyra");
99
+ const folder = join(base, "workflows");
100
+ for (const path of [base, folder]) {
101
+ if (create) await mkdir(path).catch(error => { if (error.code !== "EEXIST") throw error; });
102
+ if (!(await lstat(path).catch(error => {
103
+ if (error.code !== "ENOENT") throw error;
104
+ return null;
105
+ }))?.isDirectory()) throw new Error("Use a regular .lyra/workflows folder.");
106
+ }
107
+ return folder;
108
+ }
109
+
110
+ async function findWorkflow(folder, id) {
111
+ if (typeof id !== "string" || !safeId.test(id)) throw new Error("Choose a workflow from the project.");
112
+ const matches = [];
113
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
114
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
115
+ const path = join(folder, entry.name);
116
+ let file;
117
+ try { file = await json(path); }
118
+ catch (error) { if (error instanceof SyntaxError) continue; throw error; }
119
+ if (file.value?.id === id) matches.push({ ...file, path });
120
+ }
121
+ if (matches.length !== 1) throw new Error("Choose a unique workflow from .lyra/workflows.");
122
+ return matches[0];
123
+ }
124
+
125
+ export async function openStudioWorkflow(root, id) {
126
+ const file = await findWorkflow(await workflowFolder(root), id);
127
+ const { name, description, source, runnable, steps } = file.value;
128
+ return { id, name, description, source, runnable, steps: Array.isArray(steps) ? steps.map(step => ({
129
+ agentId: step?.agentId, task: step?.task, input: step?.input, output: step?.output,
130
+ })) : [], revision: hash(file.content) };
131
+ }
132
+
133
+ export async function saveStudioWorkflow(root, definition, catalog) {
134
+ const { id, name, description = "", revision, steps } = definition ?? {};
135
+ if (typeof name !== "string" || !name.trim() || name.length > 120 ||
136
+ typeof description !== "string" || description.length > 500 ||
137
+ !Array.isArray(steps) || !steps.length || steps.length > 8) {
138
+ throw new Error("Enter a workflow name and add one to eight agent steps.");
139
+ }
140
+ const outputs = new Set();
141
+ const checked = steps.map((step, index) => {
142
+ const { agentId, task, input = null, output = null } = step ?? {};
143
+ const label = "Step " + (index + 1) + " ";
144
+ if (!catalog.agents.has(agentId)) throw new Error(label + "needs an agent from this project.");
145
+ if (typeof task !== "string" || !task.trim() || task.length > 2000) throw new Error(label + "needs a task of up to 2,000 characters.");
146
+ if (input !== null && !outputs.has(input)) throw new Error(label + "must read an earlier step's named output.");
147
+ if (output !== null && (typeof output !== "string" || !safeId.test(output) || outputs.has(output))) {
148
+ throw new Error(label + "needs a unique output name using letters, numbers, hyphens, or underscores.");
149
+ }
150
+ if (output !== null) outputs.add(output);
151
+ return { agentId, task: task.trim(), input, output };
152
+ });
153
+ const folder = await workflowFolder(root, id == null);
154
+ const file = id == null ? null : await findWorkflow(folder, id);
155
+ if (file?.value.source === "cloud") throw new Error("Duplicate the Cloud workflow to edit it locally.");
156
+ if (file && hash(file.content) !== revision) throw new Error("This workflow changed on disk. Reopen it before saving.");
157
+ const workflowId = id ?? randomUUID();
158
+ const value = { ...file?.value, id: workflowId, name: name.trim(), description: description.trim(), runnable: true, steps: checked };
159
+ const content = JSON.stringify(value, null, 2) + "\n";
160
+ if (file) {
161
+ if ((await json(file.path)).content !== file.content) throw new Error("This workflow changed on disk. Reopen it before saving.");
162
+ await replace(file.path, content);
163
+ } else {
164
+ await writeFile(join(folder, workflowId + ".json"), content, { flag: "wx", mode: 0o600 });
165
+ }
166
+ return { id: workflowId, name: value.name, description: value.description, steps: checked, runnable: true, revision: hash(content) };
167
+ }
168
+
169
+ const cloudDefinitions = { workflow: cloudDefinition, team: cloudTeam, skill: (_base, skill) => cloudSkill(skill) };
170
+
171
+ async function syncResource(resource, root, id, action, { key, request = fetch } = {}) {
172
+ requireCloudMode(await readMode(root));
173
+ if (typeof id !== "string" || !safeId.test(id)) throw new Error("Choose a local " + resource + " ID.");
174
+ const base = join(root, ".lyra");
175
+ const folder = join(base, resource + "s");
176
+ for (const path of [base, folder]) {
177
+ if (!(await lstat(path).catch(() => null))?.isDirectory()) throw new Error("Use a regular .lyra/" + resource + "s folder.");
178
+ }
179
+ const matches = [];
180
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
181
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
182
+ const path = join(folder, entry.name);
183
+ let file;
184
+ try { file = await json(path); }
185
+ catch (error) { if (error instanceof SyntaxError) continue; throw error; }
186
+ if (file.value?.id === id && file.value.source !== "cloud") matches.push({ ...file, path });
187
+ }
188
+ if (matches.length !== 1) throw new Error("Choose a unique local " + resource + ".");
189
+ const [{ path, content, value }] = matches;
190
+ const local = await cloudDefinitions[resource](base, value);
191
+ const localRevision = hash(JSON.stringify(local));
192
+ const links = join(base, resource + "-links");
193
+ await mkdir(links, { recursive: true });
194
+ if (!(await lstat(links)).isDirectory()) throw new Error("Cloud links must use a regular directory.");
195
+ const metadata = join(links, id + ".json");
196
+ let link;
197
+ try {
198
+ link = (await json(metadata)).value;
199
+ if (!digest.test(link?.linkId ?? "") || !digest.test(link?.revision ?? "") || !objectId.test(link?.cloudId ?? "")) {
200
+ throw new Error("Invalid Cloud " + resource + " link.");
201
+ }
202
+ } catch (error) {
203
+ if (error.code !== "ENOENT") throw error;
204
+ }
205
+ if (action === "pull" && !link) throw new Error("Push this " + resource + " once to link it to Cloud.");
206
+ key ??= await readSdkKey(root);
207
+ if (!key) throw new Error("Use Connect to Cloud with a Cloud sync key before syncing.");
208
+ const linkId = link?.linkId ?? hash(resolve(root) + "\0" + resource + ":" + id);
209
+ const push = action === "push";
210
+ const response = await request("https://api.agentlyra.in/api/sdk/v1/studio/" + resource + "s/" + linkId, {
211
+ method: push ? "PUT" : "GET",
212
+ headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
213
+ body: push ? JSON.stringify({ [resource]: local, revision: link?.revision }) : undefined,
214
+ redirect: "error", signal: AbortSignal.timeout(20_000),
215
+ });
216
+ const result = await response.json();
217
+ if (!response.ok) throw new Error(result.error || "Could not sync the Cloud " + resource + ".");
218
+ if (!objectId.test(result.id ?? "") || !digest.test(result.revision ?? "") ||
219
+ (link && result.id !== link.cloudId)) throw new Error("The Cloud " + resource + " link no longer matches.");
220
+ if (!push && result.revision !== link.revision && result.revision !== localRevision) {
221
+ if (localRevision !== link.revision) throw new Error("Both copies changed. Review their edits before syncing.");
222
+ if (!result[resource] || hash(JSON.stringify(result[resource])) !== result.revision) throw new Error("Invalid Cloud response.");
223
+ const next = await applyRemote(resource, base, value, local, result[resource]);
224
+ if ((await readFile(path, "utf8")) !== content) throw new Error("The local " + resource + " changed during sync. Try again.");
225
+ await replace(path, JSON.stringify(next, null, 2) + "\n");
226
+ }
227
+ await replace(metadata, JSON.stringify({ linkId, cloudId: result.id, revision: result.revision }) + "\n");
228
+ return { name: push ? local.name : result[resource].name, created: response.status === 201, updated: !push && result.revision !== localRevision && result.revision !== link.revision };
229
+ }
@@ -0,0 +1,158 @@
1
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ const SETTING = "chat.agentFilesLocations";
5
+ const AGENTS = ".lyra/agents";
6
+
7
+ function tokenize(source) {
8
+ const masked = source.split("");
9
+ const tokens = [];
10
+ for (let i = 0; i < source.length;) {
11
+ const ch = source[i];
12
+ if (/\s/.test(ch)) { i += 1; continue; }
13
+ if (ch === "/" && source[i + 1] === "/") {
14
+ let j = i + 2;
15
+ while (j < source.length && source[j] !== "\n") j += 1;
16
+ for (let k = i; k < j; k += 1) masked[k] = " ";
17
+ i = j;
18
+ continue;
19
+ }
20
+ if (ch === "/" && source[i + 1] === "*") {
21
+ const end = source.indexOf("*/", i + 2);
22
+ if (end < 0) throw new Error("Unterminated comment in VS Code settings.json.");
23
+ const j = end + 2;
24
+ for (let k = i; k < j; k += 1) if (masked[k] !== "\n" && masked[k] !== "\r") masked[k] = " ";
25
+ i = j;
26
+ continue;
27
+ }
28
+ if (ch === '"') {
29
+ const start = i++;
30
+ while (i < source.length) {
31
+ if (source[i] === "\\") { i += 2; continue; }
32
+ if (source[i++] === '"') break;
33
+ }
34
+ tokens.push({ kind: "string", value: JSON.parse(source.slice(start, i)), start, end: i });
35
+ continue;
36
+ }
37
+ if ("{}[]:,".includes(ch)) {
38
+ tokens.push({ kind: ch, start: i, end: i + 1 });
39
+ i += 1;
40
+ continue;
41
+ }
42
+ const start = i++;
43
+ while (i < source.length && !/[\s{}\[\]:,\/]/.test(source[i])) i += 1;
44
+ tokens.push({ kind: "literal", start, end: i });
45
+ }
46
+ for (let i = 0; i < tokens.length - 1; i += 1) {
47
+ if (tokens[i].kind === "," && ["}", "]"].includes(tokens[i + 1].kind)) {
48
+ masked[tokens[i].start] = " ";
49
+ }
50
+ }
51
+ return { tokens, value: JSON.parse(masked.join("")) };
52
+ }
53
+
54
+ function valueEnd(tokens, index) {
55
+ const opening = tokens[index]?.kind;
56
+ if (!["{", "["].includes(opening)) return index + 1;
57
+ const stack = [];
58
+ for (let i = index; i < tokens.length; i += 1) {
59
+ const kind = tokens[i].kind;
60
+ if (kind === "{" || kind === "[") stack.push(kind);
61
+ if (kind === "}" || kind === "]") {
62
+ const expected = kind === "}" ? "{" : "[";
63
+ if (stack.pop() !== expected) throw new Error("Invalid VS Code settings.json structure.");
64
+ if (!stack.length) return i + 1;
65
+ }
66
+ }
67
+ throw new Error("Unclosed JSON container in VS Code settings.json.");
68
+ }
69
+
70
+ function objectAt(tokens, opening) {
71
+ if (tokens[opening]?.kind !== "{") throw new Error("Expected object in VS Code settings.json.");
72
+ const properties = [];
73
+ let i = opening + 1;
74
+ while (i < tokens.length && tokens[i].kind !== "}") {
75
+ const key = tokens[i];
76
+ if (key.kind !== "string" || tokens[i + 1]?.kind !== ":") {
77
+ throw new Error("Invalid VS Code settings.json property.");
78
+ }
79
+ const valueStart = i + 2;
80
+ const endIndex = valueEnd(tokens, valueStart);
81
+ properties.push({ key: key.value, valueStart, endIndex });
82
+ i = endIndex;
83
+ if (tokens[i]?.kind === ",") i += 1;
84
+ else if (tokens[i]?.kind !== "}") throw new Error("Invalid VS Code settings.json separator.");
85
+ }
86
+ if (tokens[i]?.kind !== "}") throw new Error("Unclosed VS Code settings.json object.");
87
+ return { properties, closeIndex: i, opening };
88
+ }
89
+
90
+ function insertProperty(source, tokens, object, name, value) {
91
+ const close = tokens[object.closeIndex].start;
92
+ const open = tokens[object.opening].start;
93
+ const lineStart = source.lastIndexOf("\n", open - 1) + 1;
94
+ const indent = (/^\s*/.exec(source.slice(lineStart, open)) || [""])[0];
95
+ const first = object.properties[0];
96
+ const childIndent = first
97
+ ? (/^\s*/.exec(source.slice(source.lastIndexOf("\n", tokens[first.valueStart].start - 1) + 1)) || [indent + " "])[0]
98
+ : indent + " ";
99
+ const row = "\n" + childIndent + JSON.stringify(name) + ": " + value + "\n" + indent;
100
+ let updated = source.slice(0, close) + row + source.slice(close);
101
+ const last = object.properties.at(-1);
102
+ if (last && tokens[object.closeIndex - 1]?.kind !== ",") {
103
+ const end = tokens[last.endIndex - 1].end;
104
+ updated = updated.slice(0, end) + "," + updated.slice(end);
105
+ }
106
+ return updated;
107
+ }
108
+
109
+ /**
110
+ * Register Lyra agent discovery in the current VS Code workspace.
111
+ * Preserve existing JSONC comments, other settings, and unrelated providers.
112
+ */
113
+ export async function ensureVSCodeAgentDiscovery(root) {
114
+ const directory = join(root, ".vscode");
115
+ const file = join(directory, "settings.json");
116
+ await mkdir(directory, { recursive: true });
117
+ const stat = await lstat(file).catch(error => {
118
+ if (error.code === "ENOENT") return null;
119
+ throw error;
120
+ });
121
+ if (stat && !stat.isFile()) throw new Error("Expected regular VS Code settings file: " + file);
122
+ if (!stat) {
123
+ await writeFile(file, JSON.stringify({ [SETTING]: { [AGENTS]: true } }, null, 2) + "\n", { flag: "wx" });
124
+ return true;
125
+ }
126
+
127
+ const original = await readFile(file, "utf8");
128
+ const source = original.trim() ? original : "{}";
129
+ const { tokens, value } = tokenize(source);
130
+ if (!value || Array.isArray(value) || typeof value !== "object") {
131
+ throw new Error("VS Code settings.json must contain an object.");
132
+ }
133
+ if (value[SETTING]?.[AGENTS] === true) return false;
134
+
135
+ const rootObject = objectAt(tokens, 0);
136
+ const entry = rootObject.properties.find(property => property.key === SETTING);
137
+ let updated;
138
+ if (!entry) {
139
+ updated = insertProperty(source, tokens, rootObject, SETTING, JSON.stringify({ [AGENTS]: true }));
140
+ } else {
141
+ if (!value[SETTING] || Array.isArray(value[SETTING]) || typeof value[SETTING] !== "object") {
142
+ throw new Error(SETTING + " must be an object in VS Code settings.json.");
143
+ }
144
+ const nested = objectAt(tokens, entry.valueStart);
145
+ const agentEntry = nested.properties.find(property => property.key === AGENTS);
146
+ if (agentEntry) {
147
+ const start = tokens[agentEntry.valueStart].start;
148
+ const end = tokens[agentEntry.endIndex - 1].end;
149
+ updated = source.slice(0, start) + "true" + source.slice(end);
150
+ } else {
151
+ updated = insertProperty(source, tokens, nested, AGENTS, "true");
152
+ }
153
+ }
154
+ // Validate the generated JSONC before replacing the workspace configuration.
155
+ tokenize(updated);
156
+ await writeFile(file, updated, "utf8");
157
+ return true;
158
+ }