agent-lyra 0.7.0 → 0.10.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 (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +301 -276
  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 +70 -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 -173
  65. package/src/framework/mda.js +65 -0
  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 +960 -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 -0
  76. package/src/memory/LICENSE +21 -21
  77. package/src/memory/README.md +5 -5
  78. package/src/memory/UPSTREAM.json +24 -14
  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 -49
  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 -160
  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 -53
  104. package/src/standalone/index.d.ts +45 -45
  105. package/src/standalone/index.js +13 -13
  106. package/src/standalone/init.js +12 -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 +542 -345
  112. package/src/studio/export.js +83 -85
  113. package/src/studio/index.html +74 -37
  114. package/src/studio/memory-actions.js +37 -37
  115. package/src/studio/memory-panel.js +200 -200
  116. package/src/studio/project.js +308 -240
  117. package/src/studio/pull-agent.js +72 -72
  118. package/src/studio/push.js +54 -54
  119. package/src/studio/python-agent.js +47 -47
  120. package/src/studio/python-agent.py +25 -25
  121. package/src/studio/server.js +164 -150
  122. package/src/studio/session.js +83 -83
  123. package/src/studio/studio.css +257 -10
  124. package/src/studio/sync.js +42 -42
  125. package/src/studio/workflow-editor.js +240 -0
  126. package/src/studio/workflow-sync.js +229 -157
@@ -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
+ }