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
package/src/init.js CHANGED
@@ -1,961 +1,964 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import process from "node:process";
4
- import readline from "node:readline/promises";
5
- import { emitKeypressEvents } from "node:readline";
6
- import { stdin as input, stdout as output } from "node:process";
7
- import { GATED_DOMAINS, STANDALONE_DOMAINS, getDomainCatalog } from "./catalog.js";
8
-
9
- import { prepareCodingStack, recommendCodingStacks, selectCodingStack } from "./coding/setup.js";
10
-
11
- const DEFAULT_API_BASE_URL = "https://www.agentlyra.in";
12
-
13
- function parseArgs(argv = process.argv.slice(2)) {
14
- const args = { _: [] };
15
-
16
- for (let index = 0; index < argv.length; index += 1) {
17
- const token = argv[index];
18
- if (!token.startsWith("--")) {
19
- args._.push(token);
20
- continue;
21
- }
22
-
23
- const [flag, inlineValue] = token.split("=", 2);
24
- const key = flag.slice(2);
25
- const next = argv[index + 1];
26
-
27
- if (inlineValue !== undefined) {
28
- args[key] = inlineValue;
29
- continue;
30
- }
31
-
32
- if (!next || next.startsWith("--")) {
33
- args[key] = true;
34
- continue;
35
- }
36
-
37
- args[key] = next;
38
- index += 1;
39
- }
40
-
41
- return args;
42
- }
43
-
44
- function printUsage() {
45
- output.write(`Usage:\n agent-lyra init\n lyra init\n\nOptions:\n --mode standalone|gated\n --domains coding,finance\n --stack mern,playwright\n --detect\n --api-key <key>\n --api-base-url <url>\n --dir <target-directory>\n --force\n`);
46
- }
47
-
48
- function printWelcomeBanner() {
49
- output.write([
50
- "",
51
- " _ _ _ ",
52
- " / \\\ __ _ ___ _ __ | |_ | | _ _ _ __ __ _ ",
53
- " / _ \\\ / _` |/ _ \\ '_ \\| __| | | | | | | '__/ _` |",
54
- " / ___ \\\ (_| | __/ | | | |_ | |__| |_| | | | (_| |",
55
- "/_/ \\\_\\__, |\\___|_| |_|\\__| |_____\\__, |_| \\__,_|",
56
- " |___/ |___/ ",
57
- "",
58
- " Local agents when you want control. Hosted agents when you want lift.",
59
- "",
60
- ].join("\n"));
61
- }
62
-
63
- async function askQuestion(rl, message, { secret = false } = {}) {
64
- if (!secret) {
65
- return (await rl.question(message)).trim();
66
- }
67
-
68
- const original = input.isTTY ? input.isTTY : false;
69
- if (input.isTTY) {
70
- input.setRawMode?.(true);
71
- }
72
-
73
- output.write(message);
74
- let buffer = "";
75
-
76
- return await new Promise((resolve) => {
77
- const onData = (chunk) => {
78
- const value = String(chunk);
79
- if (value === "\r" || value === "\n") {
80
- input.off("data", onData);
81
- output.write("\n");
82
- if (input.isTTY && original) {
83
- input.setRawMode?.(false);
84
- }
85
- resolve(buffer.trim());
86
- return;
87
- }
88
-
89
- if (value === "\u0003") {
90
- process.exitCode = 1;
91
- input.off("data", onData);
92
- if (input.isTTY && original) {
93
- input.setRawMode?.(false);
94
- }
95
- throw new Error("Cancelled.");
96
- }
97
-
98
- if (value === "\u007f") {
99
- buffer = buffer.slice(0, -1);
100
- return;
101
- }
102
-
103
- buffer += value;
104
- };
105
-
106
- input.on("data", onData);
107
- });
108
- }
109
-
110
- async function chooseMode(rl, currentMode) {
111
- if (currentMode === "standalone" || currentMode === "gated") {
112
- return currentMode;
113
- }
114
-
115
- while (true) {
116
- const answer = (await rl.question("Choose setup flow: [1] standalone [2] gated: ")).trim().toLowerCase();
117
- if (answer === "1" || answer === "standalone" || answer === "s") {
118
- return "standalone";
119
- }
120
- if (answer === "2" || answer === "gated" || answer === "g") {
121
- return "gated";
122
- }
123
- output.write("Enter 1 for standalone or 2 for gated.\n");
124
- }
125
- }
126
-
127
- async function chooseFlowGroup(rl) {
128
- while (true) {
129
- const answer = (await rl.question("Choose pack type: [1] Professional [2] Everyday: ")).trim().toLowerCase();
130
- if (answer === "1" || answer === "professional" || answer === "p") {
131
- return "professional";
132
- }
133
- if (answer === "2" || answer === "everyday" || answer === "e") {
134
- return "everyday";
135
- }
136
- output.write("Enter 1 for Professional or 2 for Everyday.\n");
137
- }
138
- }
139
-
140
- function clearScreen() {
141
- output.write("\u001Bc");
142
- }
143
-
144
- function renderMultiSelect(title, options, cursor, selected) {
145
- clearScreen();
146
- output.write(`${title}\n`);
147
- output.write("Use ↑/↓ to move, Space to toggle, Enter to confirm.\n\n");
148
-
149
- options.forEach((option, index) => {
150
- const marker = selected.has(option.id) ? "[x]" : "[ ]";
151
- const prefix = index === cursor ? ">" : " ";
152
- output.write(`${prefix} ${marker} ${option.label}\n`);
153
- });
154
- }
155
-
156
- function renderGroupedMultiSelect(title, groups, cursor, selected) {
157
- const flattened = groups.flatMap((group) => group.options);
158
- clearScreen();
159
- output.write(`${title}\n`);
160
- output.write("Use ↑/↓ to move, Space to toggle, Enter to confirm.\n\n");
161
-
162
- let running = 0;
163
- groups.forEach((group) => {
164
- output.write(`${group.label}\n`);
165
- group.options.forEach((option) => {
166
- const marker = selected.has(option.id) ? "[x]" : "[ ]";
167
- const prefix = running === cursor ? ">" : " ";
168
- output.write(`${prefix} ${marker} ${option.label}${option.hint ? ` - ${option.hint}` : ""}\n`);
169
- running += 1;
170
- });
171
- output.write("\n");
172
- });
173
-
174
- if (flattened.length === 0) {
175
- output.write("No options available.\n");
176
- }
177
- }
178
-
179
- async function selectManyGrouped(rl, title, groups, presetIds = []) {
180
- const options = groups.flatMap((group) => group.options);
181
-
182
- if (!input.isTTY || !output.isTTY) {
183
- const answer = (await rl.question(`${title} (comma-separated ids): `)).trim();
184
- const selectedIds = answer
185
- ? answer.split(",").map((value) => value.trim()).filter(Boolean)
186
- : presetIds;
187
- return options.filter((option) => selectedIds.includes(option.id));
188
- }
189
-
190
- emitKeypressEvents(input);
191
- input.setRawMode?.(true);
192
- input.resume();
193
-
194
- const selected = new Set(presetIds);
195
- let cursor = 0;
196
- renderGroupedMultiSelect(title, groups, cursor, selected);
197
-
198
- return await new Promise((resolve, reject) => {
199
- const cleanup = () => {
200
- input.setRawMode?.(false);
201
- input.removeListener("keypress", onKeypress);
202
- output.write("\n");
203
- };
204
-
205
- const onKeypress = (_, key) => {
206
- if (key?.name === "up") {
207
- cursor = cursor === 0 ? options.length - 1 : cursor - 1;
208
- renderGroupedMultiSelect(title, groups, cursor, selected);
209
- return;
210
- }
211
- if (key?.name === "down") {
212
- cursor = cursor === options.length - 1 ? 0 : cursor + 1;
213
- renderGroupedMultiSelect(title, groups, cursor, selected);
214
- return;
215
- }
216
- if (key?.name === "space") {
217
- const current = options[cursor];
218
- if (!current || current.disabled) {
219
- return;
220
- }
221
- if (selected.has(current.id)) {
222
- selected.delete(current.id);
223
- } else {
224
- selected.add(current.id);
225
- }
226
- renderGroupedMultiSelect(title, groups, cursor, selected);
227
- return;
228
- }
229
- if (key?.name === "return") {
230
- cleanup();
231
- resolve(options.filter((option) => selected.has(option.id)));
232
- return;
233
- }
234
- if (key?.ctrl && key.name === "c") {
235
- cleanup();
236
- reject(new Error("Cancelled."));
237
- }
238
- };
239
-
240
- input.on("keypress", onKeypress);
241
- });
242
- }
243
-
244
- async function askYesNo(rl, prompt, defaultValue = false) {
245
- const suffix = defaultValue ? " [Y/n]: " : " [y/N]: ";
246
- const answer = (await rl.question(`${prompt}${suffix}`)).trim().toLowerCase();
247
- if (!answer) return defaultValue;
248
- return answer === "y" || answer === "yes";
249
- }
250
-
251
- async function fetchUserAgentsByApiKey(apiBaseUrl, apiKey) {
252
- const baseUrl = String(apiBaseUrl || DEFAULT_API_BASE_URL).replace(/\/$/, "");
253
- const response = await fetch(`${baseUrl}/api/lyra-cli/agents`, {
254
- method: "GET",
255
- headers: {
256
- Authorization: `Bearer ${apiKey}`,
257
- },
258
- });
259
-
260
- if (!response.ok) {
261
- throw new Error(`Failed to sync agents: ${response.status}`);
262
- }
263
-
264
- const body = await response.json();
265
- return Array.isArray(body?.agents) ? body.agents : [];
266
- }
267
-
268
- function normalizePlatformAgents(rawAgents = []) {
269
- return rawAgents
270
- .filter((agent) => agent && agent.name && agent.id)
271
- .map((agent) => ({
272
- id: `platform-${agent.id}`,
273
- label: `${agent.name} (Your agent)`,
274
- mode: "standalone",
275
- sourceType: "platform",
276
- importPayload: {
277
- schemaVersion: 1,
278
- type: "platform-agent",
279
- id: String(agent.id),
280
- slug: String(agent.slug || agent.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
281
- name: agent.name,
282
- domain: "platform-imports",
283
- category: agent.category || "custom",
284
- mode: "standalone",
285
- description: agent.description || "",
286
- icon: null,
287
- skills: Array.isArray(agent.skills) ? agent.skills : [],
288
- integrations: Array.isArray(agent.integrations) ? agent.integrations : [],
289
- generatedFrom: "platform-sync",
290
- promptTemplateId: null,
291
- systemPrompt: agent.systemPrompt || "",
292
- runtime: {
293
- execution: "platform",
294
- source: "lyra-web",
295
- defaultModel: agent.defaultModel || null,
296
- maxTokens: agent.maxTokens ?? null,
297
- temperature: agent.temperature ?? null,
298
- },
299
- repoIntelligence: {
300
- enabled: true,
301
- requiresScan: true,
302
- scanEndpoint: "/api/repositories/:id/scan",
303
- pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
304
- contextContract: {
305
- required: [
306
- "repoContext",
307
- "findingsAtScanTime",
308
- "responsibilities",
309
- "scopedPaths",
310
- "confidence",
311
- ],
312
- },
313
- },
314
- outputs: {
315
- format: "markdown",
316
- requireCitations: false,
317
- },
318
- },
319
- }));
320
- }
321
-
322
- async function selectMany(rl, title, options, presetIds = []) {
323
- if (!input.isTTY || !output.isTTY) {
324
- const answer = (await rl.question(`${title} (comma-separated ids): `)).trim();
325
- const selectedIds = answer
326
- ? answer.split(",").map((value) => value.trim()).filter(Boolean)
327
- : presetIds;
328
- return options.filter((option) => selectedIds.includes(option.id));
329
- }
330
-
331
- emitKeypressEvents(input);
332
- input.setRawMode?.(true);
333
- input.resume();
334
-
335
- const selected = new Set(presetIds);
336
- let cursor = 0;
337
- renderMultiSelect(title, options, cursor, selected);
338
-
339
- return await new Promise((resolve, reject) => {
340
- const cleanup = () => {
341
- input.setRawMode?.(false);
342
- input.removeListener("keypress", onKeypress);
343
- output.write("\n");
344
- };
345
-
346
- const onKeypress = (_, key) => {
347
- if (key?.name === "up") {
348
- cursor = cursor === 0 ? options.length - 1 : cursor - 1;
349
- renderMultiSelect(title, options, cursor, selected);
350
- return;
351
- }
352
- if (key?.name === "down") {
353
- cursor = cursor === options.length - 1 ? 0 : cursor + 1;
354
- renderMultiSelect(title, options, cursor, selected);
355
- return;
356
- }
357
- if (key?.name === "space") {
358
- const current = options[cursor];
359
- if (selected.has(current.id)) {
360
- selected.delete(current.id);
361
- } else {
362
- selected.add(current.id);
363
- }
364
- renderMultiSelect(title, options, cursor, selected);
365
- return;
366
- }
367
- if (key?.name === "return") {
368
- cleanup();
369
- resolve(options.filter((option) => selected.has(option.id)));
370
- return;
371
- }
372
- if (key?.ctrl && key.name === "c") {
373
- cleanup();
374
- reject(new Error("Cancelled."));
375
- }
376
- };
377
-
378
- input.on("keypress", onKeypress);
379
- });
380
- }
381
-
382
- async function ensureEmptyOrApproved(rl, rootDir, force) {
383
- try {
384
- await fs.access(rootDir);
385
- if (force) {
386
- await fs.rm(rootDir, { recursive: true, force: true });
387
- return;
388
- }
389
- const answer = (await rl.question(`Directory ${rootDir} exists. Overwrite Lyra files? [y/N]: `)).trim().toLowerCase();
390
- if (answer !== "y" && answer !== "yes") {
391
- throw new Error("Aborted by user.");
392
- }
393
- await fs.rm(rootDir, { recursive: true, force: true });
394
- } catch (error) {
395
- if (error.code === "ENOENT") {
396
- return;
397
- }
398
- if (error.message === "Aborted by user.") {
399
- throw error;
400
- }
401
- }
402
- }
403
-
404
- function buildConfig(mode, selectedDomains, apiKeyProvided) {
405
- return {
406
- version: 1,
407
- mode,
408
- domains: selectedDomains.map((domain) => domain.id),
409
- createdAt: new Date().toISOString(),
410
- gated: mode === "gated"
411
- ? {
412
- apiKeySource: apiKeyProvided ? ".lyra/credentials.json" : "env:LYRA_API_KEY",
413
- verticals: selectedDomains.map((domain) => domain.id),
414
- }
415
- : undefined,
416
- domainsMetadata: selectedDomains.map((domain) => sanitizeConfigDomainEntry(domain)),
417
- };
418
- }
419
-
420
- function sanitizeConfigDomainEntry(entry) {
421
- const agentCount = Array.isArray(entry.agents) ? entry.agents.length : Number(entry.agentCount || 0);
422
- return {
423
- id: entry.id,
424
- label: entry.label,
425
- mode: entry.mode || "standalone",
426
- sourceType: entry.sourceType || "catalog",
427
- agentCount,
428
- };
429
- }
430
-
431
- function buildStandaloneAgentSpec(domain, agent) {
432
- return {
433
- schemaVersion: 1,
434
- type: "standalone-agent",
435
- id: agent.id,
436
- slug: agent.slug,
437
- name: agent.name,
438
- domain: domain.id,
439
- category: agent.category,
440
- mode: "standalone",
441
- description: agent.description,
442
- icon: agent.icon || null,
443
- skills: agent.skills || [],
444
- integrations: agent.requiresIntegration || [],
445
- generatedFrom: agent.generatedFrom || "onboarding-catalog",
446
- promptTemplateId: agent.promptTemplateId || null,
447
- systemPrompt: agent.systemPrompt || "",
448
- repoIntelligence: {
449
- enabled: true,
450
- requiresScan: Boolean(agent.runtimeHints?.requiresRepoScan),
451
- scanEndpoint: agent.runtimeHints?.suggestedScanEndpoint || "/api/repositories/:id/scan",
452
- pullRequestEndpoint: agent.runtimeHints?.suggestedPrEndpoint || "/api/repositories/:id/lyra-pr",
453
- contextContract: {
454
- required: [
455
- "repoContext",
456
- "findingsAtScanTime",
457
- "responsibilities",
458
- "scopedPaths",
459
- "confidence",
460
- ],
461
- },
462
- },
463
- runtime: {
464
- execution: "local",
465
- orchestration: "standalone",
466
- ragEnabled: true,
467
- },
468
- outputs: {
469
- format: "markdown",
470
- requireCitations: Boolean((agent.skills || []).includes("url-scraper") || (agent.skills || []).includes("web-search")),
471
- },
472
- };
473
- }
474
-
475
- function buildGatedAgentSpec(domain, agent) {
476
- return {
477
- schemaVersion: 1,
478
- type: "hosted-agent",
479
- id: agent.id,
480
- slug: agent.slug,
481
- name: agent.name,
482
- domain: domain.id,
483
- category: agent.category,
484
- mode: "gated",
485
- description: agent.description,
486
- icon: agent.icon || null,
487
- skills: agent.skills || [],
488
- integrations: agent.requiresIntegration || [],
489
- generatedFrom: agent.generatedFrom || "gated-vertical-catalog",
490
- promptTemplateId: agent.promptTemplateId || null,
491
- systemPrompt: agent.systemPrompt || "",
492
- repoIntelligence: {
493
- enabled: true,
494
- requiresScan: false,
495
- scanEndpoint: "/api/repositories/:id/scan",
496
- pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
497
- contextContract: {
498
- required: [
499
- "repoContext",
500
- "findingsAtScanTime",
501
- "responsibilities",
502
- "scopedPaths",
503
- "confidence",
504
- ],
505
- },
506
- },
507
- hosted: {
508
- provider: "lyra",
509
- vertical: agent.hosted?.vertical || domain.id,
510
- defaultModel: agent.hosted?.defaultModel || null,
511
- endpoint: `/agents/${agent.hosted?.vertical || domain.id}/invoke`,
512
- auth: {
513
- strategy: "bearer",
514
- credentialsFile: ".lyra/credentials.json",
515
- credentialsKey: "LYRA_API_KEY",
516
- },
517
- },
518
- outputs: {
519
- format: "json",
520
- includeUsage: true,
521
- },
522
- };
523
- }
524
-
525
- function buildAgentSpec(domain, mode, agent) {
526
- const effectiveMode = domain.mode || mode;
527
- return effectiveMode === "gated"
528
- ? buildGatedAgentSpec(domain, agent)
529
- : buildStandaloneAgentSpec(domain, agent);
530
- }
531
-
532
- function toYamlValue(value, indent = 0) {
533
- const pad = " ".repeat(indent);
534
- if (value === null || value === undefined) {
535
- return "null";
536
- }
537
- if (typeof value === "string") {
538
- return JSON.stringify(value);
539
- }
540
- if (typeof value === "number" || typeof value === "boolean") {
541
- return String(value);
542
- }
543
- if (Array.isArray(value)) {
544
- if (value.length === 0) {
545
- return "[]";
546
- }
547
- return value
548
- .map((item) => {
549
- const rendered = toYamlValue(item, indent + 2);
550
- if (typeof item === "object" && item !== null && !Array.isArray(item)) {
551
- const lines = rendered.split("\n");
552
- return `${pad}- ${lines[0]}${lines.length > 1 ? `\n${lines.slice(1).join("\n")}` : ""}`;
553
- }
554
- return `${pad}- ${rendered}`;
555
- })
556
- .join("\n");
557
- }
558
-
559
- const entries = Object.entries(value);
560
- if (entries.length === 0) {
561
- return "{}";
562
- }
563
- return entries
564
- .map(([key, entryValue]) => {
565
- if (typeof entryValue === "object" && entryValue !== null) {
566
- return `${pad}${key}:\n${toYamlValue(entryValue, indent + 2)}`;
567
- }
568
- return `${pad}${key}: ${toYamlValue(entryValue, indent + 2)}`;
569
- })
570
- .join("\n");
571
- }
572
-
573
- function buildAgentMarkdown(spec) {
574
- const frontMatter = {
575
- schemaVersion: spec.schemaVersion,
576
- type: spec.type,
577
- id: spec.id,
578
- slug: spec.slug,
579
- name: spec.name,
580
- domain: spec.domain,
581
- category: spec.category,
582
- mode: spec.mode,
583
- icon: spec.icon,
584
- generatedFrom: spec.generatedFrom,
585
- promptTemplateId: spec.promptTemplateId,
586
- skills: spec.skills,
587
- integrations: spec.integrations,
588
- };
589
-
590
- const sections = [
591
- "---",
592
- toYamlValue(frontMatter),
593
- "---",
594
- "",
595
- `# ${spec.name}`,
596
- "",
597
- "## Description",
598
- spec.description || "",
599
- "",
600
- "## System Prompt",
601
- spec.systemPrompt || "",
602
- "",
603
- "## Runtime Spec",
604
- "```json",
605
- JSON.stringify({
606
- repoIntelligence: spec.repoIntelligence,
607
- runtime: spec.runtime || null,
608
- hosted: spec.hosted || null,
609
- outputs: spec.outputs || null,
610
- }, null, 2),
611
- "```",
612
- "",
613
- ];
614
-
615
- return sections.join("\n");
616
- }
617
-
618
- async function writeDomainManifest(rootDir, mode, domain) {
619
- const domainRoot = path.join(rootDir, "domains", domain.id);
620
- const manifestPath = path.join(domainRoot, "domain.json");
621
- const skillSet = new Set();
622
- const integrationSet = new Set();
623
-
624
- for (const agent of domain.agents || []) {
625
- for (const skill of agent.skills || []) {
626
- skillSet.add(skill);
627
- }
628
- for (const integration of agent.requiresIntegration || []) {
629
- integrationSet.add(integration);
630
- }
631
- }
632
-
633
- const manifest = {
634
- schemaVersion: 1,
635
- id: domain.id,
636
- label: domain.label,
637
- mode,
638
- generatedFrom: domain.generatedFrom || (mode === "gated" ? "gated-vertical-catalog" : "onboarding-catalog"),
639
- agentCount: (domain.agents || []).length,
640
- agentIds: (domain.agents || []).map(agent => agent.id),
641
- skills: [...skillSet].sort(),
642
- integrations: [...integrationSet].sort(),
643
- repoIntelligence: {
644
- enabled: true,
645
- scanEndpoint: "/api/repositories/:id/scan",
646
- pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
647
- notes: "These agent specs are designed to be hydrated with repository scan output and PR generation workflows.",
648
- },
649
- generatedAt: new Date().toISOString(),
650
- };
651
-
652
- await fs.mkdir(domainRoot, { recursive: true });
653
- await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
654
- }
655
-
656
- async function writeDomainFiles(rootDir, mode, selectedDomains) {
657
- for (const domain of selectedDomains) {
658
- await writeDomainManifest(rootDir, mode, domain);
659
- }
660
- }
661
-
662
- async function writeTopLevelManifest(rootDir, mode, selectedDomains) {
663
- const agentsDir = path.join(rootDir, "agents");
664
- const manifestPath = path.join(rootDir, "manifest.json");
665
- await fs.mkdir(agentsDir, { recursive: true });
666
-
667
- const manifests = await Promise.all(selectedDomains.map(async (domain) => {
668
- const source = domain.sourceType === "platform" ? "platform-sync" : (mode === "gated" ? "gated-catalog" : "standalone-catalog");
669
- const comparisonStatus = domain.sourceType === "platform" ? "imported" : "new";
670
- const complements = selectedDomains
671
- .filter((candidate) => candidate.id !== domain.id && candidate.mode !== domain.mode)
672
- .map((candidate) => candidate.id);
673
-
674
- let overlapsWith = [];
675
- if (domain.sourceType !== "platform") {
676
- overlapsWith = selectedDomains
677
- .filter((candidate) => candidate.id !== domain.id && candidate.mode === domain.mode)
678
- .filter((candidate) => {
679
- const left = new Set((domain.agents || []).map((agent) => agent.id));
680
- const right = new Set((candidate.agents || []).map((agent) => agent.id));
681
- for (const id of left) {
682
- if (right.has(id)) return true;
683
- }
684
- return false;
685
- })
686
- .map((candidate) => candidate.id);
687
- }
688
-
689
- const agentIds = (domain.agents || []).map((agent) => agent.id);
690
- return {
691
- id: domain.id,
692
- label: domain.label,
693
- mode: domain.mode || mode,
694
- source,
695
- comparisonStatus,
696
- overlapsWith,
697
- complements,
698
- agentIds,
699
- generatedAt: new Date().toISOString(),
700
- };
701
- }));
702
-
703
- for (const domain of selectedDomains) {
704
- const domainDir = path.join(agentsDir, domain.id);
705
- await fs.mkdir(domainDir, { recursive: true });
706
- for (const agent of domain.agents || []) {
707
- const spec = buildAgentSpec(domain, mode, agent);
708
- const fileName = `${spec.slug}.md`;
709
- await fs.writeFile(path.join(domainDir, fileName), buildAgentMarkdown(spec), "utf8");
710
- }
711
- }
712
-
713
- await fs.writeFile(
714
- manifestPath,
715
- `${JSON.stringify({
716
- schemaVersion: 2,
717
- mode,
718
- generatedAt: new Date().toISOString(),
719
- domains: manifests,
720
- }, null, 2)}\n`,
721
- "utf8",
722
- );
723
- }
724
-
725
- async function writeScaffold({ targetDir, mode, selectedDomains, apiKey }) {
726
- const lyraDir = path.join(targetDir, ".lyra");
727
- await fs.mkdir(lyraDir, { recursive: true });
728
- await fs.mkdir(path.join(lyraDir, "domains"), { recursive: true });
729
- await fs.writeFile(path.join(lyraDir, ".gitignore"), "credentials.json\n", "utf8");
730
-
731
- const config = buildConfig(mode, selectedDomains, Boolean(apiKey));
732
- await fs.writeFile(path.join(lyraDir, "config.json"), `${JSON.stringify(config, null, 2)}\n`, "utf8");
733
-
734
- if (mode === "gated" && apiKey) {
735
- await fs.writeFile(
736
- path.join(lyraDir, "credentials.json"),
737
- `${JSON.stringify({ LYRA_API_KEY: apiKey }, null, 2)}\n`,
738
- "utf8",
739
- );
740
- }
741
-
742
- const readme = [
743
- "# .lyra",
744
- "",
745
- `Mode: ${mode}`,
746
- "",
747
- "Domains:",
748
- ...selectedDomains.map((domain) => `- ${domain.label} (${domain.id})`),
749
- "",
750
- mode === "gated"
751
- ? "Hosted setup stores the API key in .lyra/credentials.json, which is ignored by the local .lyra/.gitignore file."
752
- : "Standalone setup keeps all orchestration local and side-effect free until you invoke your own flows.",
753
- ].join("\n");
754
- await fs.writeFile(path.join(lyraDir, "README.md"), `${readme}\n`, "utf8");
755
-
756
- await writeDomainFiles(lyraDir, mode, selectedDomains);
757
- await writeTopLevelManifest(lyraDir, mode, selectedDomains);
758
- }
759
-
760
- function resolvePresetDomains(rawDomains, catalog) {
761
- if (!rawDomains || rawDomains === true) {
762
- return [];
763
- }
764
- const requested = String(rawDomains)
765
- .split(",")
766
- .map((value) => value.trim().toLowerCase())
767
- .filter(Boolean);
768
- return catalog.filter((domain) => requested.includes(domain.id));
769
- }
770
-
771
- function applyGatedLockIfLoggedOut(selectedDomains, hasApiKey) {
772
- if (hasApiKey) return selectedDomains;
773
-
774
- return selectedDomains.map((domain) => {
775
- if ((domain.mode || "standalone") !== "gated") {
776
- return domain;
777
- }
778
-
779
- return {
780
- ...domain,
781
- sourceType: domain.sourceType || "catalog",
782
- lockReason: "needs-login",
783
- agents: (domain.agents || []).map((agent) => ({
784
- ...agent,
785
- hosted: {
786
- ...(agent.hosted || {}),
787
- locked: true,
788
- lockReason: "needs-login",
789
- },
790
- })),
791
- };
792
- });
793
- }
794
-
795
- export async function runInitWizard(options = {}) {
796
- const rl = readline.createInterface({ input, output });
797
-
798
- try {
799
- printWelcomeBanner();
800
- const stackMode = (options.stack || options.detect) && ["standalone", "gated"].includes(options.mode);
801
- const wantsLogin = !stackMode && await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
802
- const apiBaseUrl = options["api-base-url"] || process.env.LYRA_API_BASE_URL || DEFAULT_API_BASE_URL;
803
- let apiKey = stackMode && options.mode === "standalone" ? "" : options["api-key"] || process.env.LYRA_API_KEY || "";
804
- let importedAgents = [];
805
-
806
- if (wantsLogin && !apiKey) {
807
- output.write("Paste your Lyra API key (starts with lyra_).\n");
808
- apiKey = await askQuestion(rl, "Lyra API key: ", { secret: true });
809
- }
810
-
811
- if (apiKey) {
812
- try {
813
- const agents = await fetchUserAgentsByApiKey(apiBaseUrl, apiKey);
814
- importedAgents = normalizePlatformAgents(agents);
815
- output.write(`Synced ${importedAgents.length} agent(s) from your Lyra account.\n`);
816
- } catch (error) {
817
- output.write(`Could not sync your agents: ${error.message}. Continuing with catalog selections.\n`);
818
- }
819
- }
820
-
821
- const chosenGroup = stackMode ? undefined : await chooseFlowGroup(rl);
822
- let mode = options.mode;
823
- if (mode !== "standalone" && mode !== "gated") {
824
- mode = chosenGroup === "everyday" ? "gated" : await chooseMode(rl, mode);
825
- }
826
-
827
- if (mode === "gated" && !apiKey) {
828
- output.write("Hosted packs need Lyra login. You can continue, but hosted packs will be marked as locked.\n");
829
- }
830
-
831
- const catalog = getDomainCatalog(mode);
832
- const catalogWithHints = catalog.map((item) => ({
833
- ...item,
834
- sourceType: "catalog",
835
- hint: mode === "gated" && !apiKey ? "needs login" : "",
836
- }));
837
- const presetDomains = resolvePresetDomains(options.domains, catalogWithHints);
838
-
839
- const dynamicGroups = [];
840
- if (importedAgents.length > 0) {
841
- dynamicGroups.push({ label: "Your agents", options: importedAgents });
842
- }
843
- dynamicGroups.push({
844
- label: mode === "gated" ? "Create new (hosted verticals)" : "Create new (catalog domains)",
845
- options: catalogWithHints,
846
- });
847
-
848
- if (stackMode && !presetDomains.length) throw new Error("Use --domains with a valid Coding or Engineering domain ID.");
849
- const selected = presetDomains.length > 0
850
- ? presetDomains
851
- : await selectManyGrouped(
852
- rl,
853
- "Select domains and/or your synced agents",
854
- dynamicGroups,
855
- [],
856
- );
857
-
858
- let selectedDomains = selected.map((entry) => {
859
- if (entry.sourceType === "platform") {
860
- return {
861
- id: entry.id,
862
- label: entry.label,
863
- mode: "standalone",
864
- sourceType: "platform",
865
- agents: [
866
- {
867
- id: entry.importPayload.id,
868
- slug: entry.importPayload.slug,
869
- name: entry.importPayload.name,
870
- description: entry.importPayload.description,
871
- category: entry.importPayload.category,
872
- icon: entry.importPayload.icon,
873
- skills: entry.importPayload.skills,
874
- requiresIntegration: entry.importPayload.integrations,
875
- generatedFrom: entry.importPayload.generatedFrom,
876
- systemPrompt: entry.importPayload.systemPrompt,
877
- promptTemplateId: entry.importPayload.promptTemplateId,
878
- runtimeHints: {
879
- requiresRepoScan: true,
880
- suggestedScanEndpoint: "/api/repositories/:id/scan",
881
- suggestedPrEndpoint: "/api/repositories/:id/lyra-pr",
882
- },
883
- importPayload: entry.importPayload,
884
- },
885
- ],
886
- };
887
- }
888
- return {
889
- ...entry,
890
- sourceType: entry.sourceType || "catalog",
891
- };
892
- });
893
-
894
- if (selectedDomains.length === 0) {
895
- throw new Error("Select at least one domain.");
896
- }
897
-
898
- selectedDomains = applyGatedLockIfLoggedOut(selectedDomains, Boolean(apiKey));
899
-
900
- if (mode === "gated" && !apiKey) {
901
- output.write("Enter the Lyra API key from the Lyra login UI. It will be stored in .lyra/credentials.json and ignored by .lyra/.gitignore.\n");
902
- apiKey = await askQuestion(rl, "Lyra API key: ", { secret: true });
903
- if (!apiKey) {
904
- throw new Error("A Lyra API key is required for gated setup.");
905
- }
906
- }
907
-
908
- const targetDir = path.resolve(options.dir || process.cwd());
909
- const lyraDir = path.join(targetDir, ".lyra");
910
- const coding = selectedDomains.some(domain => domain.id === "coding" || domain.id === "engineering-bootstrap");
911
- if (options.stack !== undefined && (!coding || typeof options.stack !== "string")) {
912
- throw new Error("Use --stack with a stack name and the Coding domain.");
913
- }
914
- if (options.detect && (!coding || options.stack)) throw new Error("Use --detect with the Coding domain instead of --stack.");
915
- let stack = options.stack;
916
- if (coding && !stack) {
917
- const detect = options.detect || (input.isTTY && await askYesNo(rl, "Detect technologies from this project?", false));
918
- if (detect) {
919
- const recommendations = await recommendCodingStacks(targetDir, output);
920
- if (recommendations.length && (options.detect || await askYesNo(rl, "Use these recommendations?", true))) stack = recommendations;
921
- }
922
- if (!stack && input.isTTY) stack = await selectCodingStack(rl, output);
923
- }
924
- let applyCoding;
925
- if (coding) {
926
- const existing = await fs.lstat(lyraDir).catch(error => {
927
- if (error.code !== "ENOENT") throw error;
928
- });
929
- if (existing) throw new Error("This project already has .lyra. Run agent-lyra setup coding to add packs while keeping your files.");
930
- const apply = await prepareCodingStack(targetDir, stack || [], output);
931
- if (!stack || options.stack || options.detect || /^y(?:es)?$/i.test(await askQuestion(rl, "Create these coding files? [y/N] "))) applyCoding = apply;
932
- }
933
- await ensureEmptyOrApproved(rl, lyraDir, Boolean(options.force));
934
- await writeScaffold({ targetDir, mode, selectedDomains, apiKey });
935
- if (applyCoding) await applyCoding();
936
-
937
- output.write(`Created ${lyraDir} for ${mode} mode with ${selectedDomains.length} domain(s).\n`);
938
- } finally {
939
- rl.close();
940
- }
941
- }
942
-
943
- export async function runCli(argv = process.argv.slice(2)) {
944
- const args = parseArgs(argv);
945
- const [first, second] = args._;
946
- const command = first === "lyra" ? second : first;
947
-
948
- if (!command || command === "help" || args.help) {
949
- printUsage();
950
- return;
951
- }
952
-
953
- if (command === "init") {
954
- await runInitWizard(args);
955
- return;
956
- }
957
-
958
- throw new Error(`Unknown command: ${command}`);
959
- }
960
-
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import readline from "node:readline/promises";
5
+ import { emitKeypressEvents } from "node:readline";
6
+ import { stdin as input, stdout as output } from "node:process";
7
+ import { GATED_DOMAINS, STANDALONE_DOMAINS, getDomainCatalog } from "./catalog.js";
8
+
9
+ import { prepareCodingStack, recommendCodingStacks, selectCodingStack } from "./coding/setup.js";
10
+ import { ensureVSCodeAgentDiscovery } from "./vscode/workspace.js";
11
+
12
+ const DEFAULT_API_BASE_URL = "https://www.agentlyra.in";
13
+
14
+ function parseArgs(argv = process.argv.slice(2)) {
15
+ const args = { _: [] };
16
+
17
+ for (let index = 0; index < argv.length; index += 1) {
18
+ const token = argv[index];
19
+ if (!token.startsWith("--")) {
20
+ args._.push(token);
21
+ continue;
22
+ }
23
+
24
+ const [flag, inlineValue] = token.split("=", 2);
25
+ const key = flag.slice(2);
26
+ const next = argv[index + 1];
27
+
28
+ if (inlineValue !== undefined) {
29
+ args[key] = inlineValue;
30
+ continue;
31
+ }
32
+
33
+ if (!next || next.startsWith("--")) {
34
+ args[key] = true;
35
+ continue;
36
+ }
37
+
38
+ args[key] = next;
39
+ index += 1;
40
+ }
41
+
42
+ return args;
43
+ }
44
+
45
+ function printUsage() {
46
+ output.write(`Usage:\n agent-lyra init\n lyra init\n\nOptions:\n --mode standalone|gated\n --domains coding,finance\n --stack mern,playwright\n --detect\n --api-key <key>\n --api-base-url <url>\n --dir <target-directory>\n --force\n`);
47
+ }
48
+
49
+ function printWelcomeBanner() {
50
+ output.write([
51
+ "",
52
+ " _ _ _ ",
53
+ " / \\\ __ _ ___ _ __ | |_ | | _ _ _ __ __ _ ",
54
+ " / _ \\\ / _` |/ _ \\ '_ \\| __| | | | | | | '__/ _` |",
55
+ " / ___ \\\ (_| | __/ | | | |_ | |__| |_| | | | (_| |",
56
+ "/_/ \\\_\\__, |\\___|_| |_|\\__| |_____\\__, |_| \\__,_|",
57
+ " |___/ |___/ ",
58
+ "",
59
+ " Local agents when you want control. Hosted agents when you want lift.",
60
+ "",
61
+ ].join("\n"));
62
+ }
63
+
64
+ async function askQuestion(rl, message, { secret = false } = {}) {
65
+ if (!secret) {
66
+ return (await rl.question(message)).trim();
67
+ }
68
+
69
+ const original = input.isTTY ? input.isTTY : false;
70
+ if (input.isTTY) {
71
+ input.setRawMode?.(true);
72
+ }
73
+
74
+ output.write(message);
75
+ let buffer = "";
76
+
77
+ return await new Promise((resolve) => {
78
+ const onData = (chunk) => {
79
+ const value = String(chunk);
80
+ if (value === "\r" || value === "\n") {
81
+ input.off("data", onData);
82
+ output.write("\n");
83
+ if (input.isTTY && original) {
84
+ input.setRawMode?.(false);
85
+ }
86
+ resolve(buffer.trim());
87
+ return;
88
+ }
89
+
90
+ if (value === "\u0003") {
91
+ process.exitCode = 1;
92
+ input.off("data", onData);
93
+ if (input.isTTY && original) {
94
+ input.setRawMode?.(false);
95
+ }
96
+ throw new Error("Cancelled.");
97
+ }
98
+
99
+ if (value === "\u007f") {
100
+ buffer = buffer.slice(0, -1);
101
+ return;
102
+ }
103
+
104
+ buffer += value;
105
+ };
106
+
107
+ input.on("data", onData);
108
+ });
109
+ }
110
+
111
+ async function chooseMode(rl, currentMode) {
112
+ if (currentMode === "standalone" || currentMode === "gated") {
113
+ return currentMode;
114
+ }
115
+
116
+ while (true) {
117
+ const answer = (await rl.question("Choose setup flow: [1] standalone [2] gated: ")).trim().toLowerCase();
118
+ if (answer === "1" || answer === "standalone" || answer === "s") {
119
+ return "standalone";
120
+ }
121
+ if (answer === "2" || answer === "gated" || answer === "g") {
122
+ return "gated";
123
+ }
124
+ output.write("Enter 1 for standalone or 2 for gated.\n");
125
+ }
126
+ }
127
+
128
+ async function chooseFlowGroup(rl) {
129
+ while (true) {
130
+ const answer = (await rl.question("Choose pack type: [1] Professional [2] Everyday: ")).trim().toLowerCase();
131
+ if (answer === "1" || answer === "professional" || answer === "p") {
132
+ return "professional";
133
+ }
134
+ if (answer === "2" || answer === "everyday" || answer === "e") {
135
+ return "everyday";
136
+ }
137
+ output.write("Enter 1 for Professional or 2 for Everyday.\n");
138
+ }
139
+ }
140
+
141
+ function clearScreen() {
142
+ output.write("\u001Bc");
143
+ }
144
+
145
+ function renderMultiSelect(title, options, cursor, selected) {
146
+ clearScreen();
147
+ output.write(`${title}\n`);
148
+ output.write("Use ↑/↓ to move, Space to toggle, Enter to confirm.\n\n");
149
+
150
+ options.forEach((option, index) => {
151
+ const marker = selected.has(option.id) ? "[x]" : "[ ]";
152
+ const prefix = index === cursor ? ">" : " ";
153
+ output.write(`${prefix} ${marker} ${option.label}\n`);
154
+ });
155
+ }
156
+
157
+ function renderGroupedMultiSelect(title, groups, cursor, selected) {
158
+ const flattened = groups.flatMap((group) => group.options);
159
+ clearScreen();
160
+ output.write(`${title}\n`);
161
+ output.write("Use ↑/↓ to move, Space to toggle, Enter to confirm.\n\n");
162
+
163
+ let running = 0;
164
+ groups.forEach((group) => {
165
+ output.write(`${group.label}\n`);
166
+ group.options.forEach((option) => {
167
+ const marker = selected.has(option.id) ? "[x]" : "[ ]";
168
+ const prefix = running === cursor ? ">" : " ";
169
+ output.write(`${prefix} ${marker} ${option.label}${option.hint ? ` - ${option.hint}` : ""}\n`);
170
+ running += 1;
171
+ });
172
+ output.write("\n");
173
+ });
174
+
175
+ if (flattened.length === 0) {
176
+ output.write("No options available.\n");
177
+ }
178
+ }
179
+
180
+ async function selectManyGrouped(rl, title, groups, presetIds = []) {
181
+ const options = groups.flatMap((group) => group.options);
182
+
183
+ if (!input.isTTY || !output.isTTY) {
184
+ const answer = (await rl.question(`${title} (comma-separated ids): `)).trim();
185
+ const selectedIds = answer
186
+ ? answer.split(",").map((value) => value.trim()).filter(Boolean)
187
+ : presetIds;
188
+ return options.filter((option) => selectedIds.includes(option.id));
189
+ }
190
+
191
+ emitKeypressEvents(input);
192
+ input.setRawMode?.(true);
193
+ input.resume();
194
+
195
+ const selected = new Set(presetIds);
196
+ let cursor = 0;
197
+ renderGroupedMultiSelect(title, groups, cursor, selected);
198
+
199
+ return await new Promise((resolve, reject) => {
200
+ const cleanup = () => {
201
+ input.setRawMode?.(false);
202
+ input.removeListener("keypress", onKeypress);
203
+ output.write("\n");
204
+ };
205
+
206
+ const onKeypress = (_, key) => {
207
+ if (key?.name === "up") {
208
+ cursor = cursor === 0 ? options.length - 1 : cursor - 1;
209
+ renderGroupedMultiSelect(title, groups, cursor, selected);
210
+ return;
211
+ }
212
+ if (key?.name === "down") {
213
+ cursor = cursor === options.length - 1 ? 0 : cursor + 1;
214
+ renderGroupedMultiSelect(title, groups, cursor, selected);
215
+ return;
216
+ }
217
+ if (key?.name === "space") {
218
+ const current = options[cursor];
219
+ if (!current || current.disabled) {
220
+ return;
221
+ }
222
+ if (selected.has(current.id)) {
223
+ selected.delete(current.id);
224
+ } else {
225
+ selected.add(current.id);
226
+ }
227
+ renderGroupedMultiSelect(title, groups, cursor, selected);
228
+ return;
229
+ }
230
+ if (key?.name === "return") {
231
+ cleanup();
232
+ resolve(options.filter((option) => selected.has(option.id)));
233
+ return;
234
+ }
235
+ if (key?.ctrl && key.name === "c") {
236
+ cleanup();
237
+ reject(new Error("Cancelled."));
238
+ }
239
+ };
240
+
241
+ input.on("keypress", onKeypress);
242
+ });
243
+ }
244
+
245
+ async function askYesNo(rl, prompt, defaultValue = false) {
246
+ const suffix = defaultValue ? " [Y/n]: " : " [y/N]: ";
247
+ const answer = (await rl.question(`${prompt}${suffix}`)).trim().toLowerCase();
248
+ if (!answer) return defaultValue;
249
+ return answer === "y" || answer === "yes";
250
+ }
251
+
252
+ async function fetchUserAgentsByApiKey(apiBaseUrl, apiKey) {
253
+ const baseUrl = String(apiBaseUrl || DEFAULT_API_BASE_URL).replace(/\/$/, "");
254
+ const response = await fetch(`${baseUrl}/api/lyra-cli/agents`, {
255
+ method: "GET",
256
+ headers: {
257
+ Authorization: `Bearer ${apiKey}`,
258
+ },
259
+ });
260
+
261
+ if (!response.ok) {
262
+ throw new Error(`Failed to sync agents: ${response.status}`);
263
+ }
264
+
265
+ const body = await response.json();
266
+ return Array.isArray(body?.agents) ? body.agents : [];
267
+ }
268
+
269
+ function normalizePlatformAgents(rawAgents = []) {
270
+ return rawAgents
271
+ .filter((agent) => agent && agent.name && agent.id)
272
+ .map((agent) => ({
273
+ id: `platform-${agent.id}`,
274
+ label: `${agent.name} (Your agent)`,
275
+ mode: "standalone",
276
+ sourceType: "platform",
277
+ importPayload: {
278
+ schemaVersion: 1,
279
+ type: "platform-agent",
280
+ id: String(agent.id),
281
+ slug: String(agent.slug || agent.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
282
+ name: agent.name,
283
+ domain: "platform-imports",
284
+ category: agent.category || "custom",
285
+ mode: "standalone",
286
+ description: agent.description || "",
287
+ icon: null,
288
+ skills: Array.isArray(agent.skills) ? agent.skills : [],
289
+ integrations: Array.isArray(agent.integrations) ? agent.integrations : [],
290
+ generatedFrom: "platform-sync",
291
+ promptTemplateId: null,
292
+ systemPrompt: agent.systemPrompt || "",
293
+ runtime: {
294
+ execution: "platform",
295
+ source: "lyra-web",
296
+ defaultModel: agent.defaultModel || null,
297
+ maxTokens: agent.maxTokens ?? null,
298
+ temperature: agent.temperature ?? null,
299
+ },
300
+ repoIntelligence: {
301
+ enabled: true,
302
+ requiresScan: true,
303
+ scanEndpoint: "/api/repositories/:id/scan",
304
+ pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
305
+ contextContract: {
306
+ required: [
307
+ "repoContext",
308
+ "findingsAtScanTime",
309
+ "responsibilities",
310
+ "scopedPaths",
311
+ "confidence",
312
+ ],
313
+ },
314
+ },
315
+ outputs: {
316
+ format: "markdown",
317
+ requireCitations: false,
318
+ },
319
+ },
320
+ }));
321
+ }
322
+
323
+ async function selectMany(rl, title, options, presetIds = []) {
324
+ if (!input.isTTY || !output.isTTY) {
325
+ const answer = (await rl.question(`${title} (comma-separated ids): `)).trim();
326
+ const selectedIds = answer
327
+ ? answer.split(",").map((value) => value.trim()).filter(Boolean)
328
+ : presetIds;
329
+ return options.filter((option) => selectedIds.includes(option.id));
330
+ }
331
+
332
+ emitKeypressEvents(input);
333
+ input.setRawMode?.(true);
334
+ input.resume();
335
+
336
+ const selected = new Set(presetIds);
337
+ let cursor = 0;
338
+ renderMultiSelect(title, options, cursor, selected);
339
+
340
+ return await new Promise((resolve, reject) => {
341
+ const cleanup = () => {
342
+ input.setRawMode?.(false);
343
+ input.removeListener("keypress", onKeypress);
344
+ output.write("\n");
345
+ };
346
+
347
+ const onKeypress = (_, key) => {
348
+ if (key?.name === "up") {
349
+ cursor = cursor === 0 ? options.length - 1 : cursor - 1;
350
+ renderMultiSelect(title, options, cursor, selected);
351
+ return;
352
+ }
353
+ if (key?.name === "down") {
354
+ cursor = cursor === options.length - 1 ? 0 : cursor + 1;
355
+ renderMultiSelect(title, options, cursor, selected);
356
+ return;
357
+ }
358
+ if (key?.name === "space") {
359
+ const current = options[cursor];
360
+ if (selected.has(current.id)) {
361
+ selected.delete(current.id);
362
+ } else {
363
+ selected.add(current.id);
364
+ }
365
+ renderMultiSelect(title, options, cursor, selected);
366
+ return;
367
+ }
368
+ if (key?.name === "return") {
369
+ cleanup();
370
+ resolve(options.filter((option) => selected.has(option.id)));
371
+ return;
372
+ }
373
+ if (key?.ctrl && key.name === "c") {
374
+ cleanup();
375
+ reject(new Error("Cancelled."));
376
+ }
377
+ };
378
+
379
+ input.on("keypress", onKeypress);
380
+ });
381
+ }
382
+
383
+ async function ensureEmptyOrApproved(rl, rootDir, force) {
384
+ try {
385
+ await fs.access(rootDir);
386
+ if (force) {
387
+ await fs.rm(rootDir, { recursive: true, force: true });
388
+ return;
389
+ }
390
+ const answer = (await rl.question(`Directory ${rootDir} exists. Overwrite Lyra files? [y/N]: `)).trim().toLowerCase();
391
+ if (answer !== "y" && answer !== "yes") {
392
+ throw new Error("Aborted by user.");
393
+ }
394
+ await fs.rm(rootDir, { recursive: true, force: true });
395
+ } catch (error) {
396
+ if (error.code === "ENOENT") {
397
+ return;
398
+ }
399
+ if (error.message === "Aborted by user.") {
400
+ throw error;
401
+ }
402
+ }
403
+ }
404
+
405
+ function buildConfig(mode, selectedDomains, apiKeyProvided) {
406
+ return {
407
+ version: 1,
408
+ mode,
409
+ domains: selectedDomains.map((domain) => domain.id),
410
+ createdAt: new Date().toISOString(),
411
+ gated: mode === "gated"
412
+ ? {
413
+ apiKeySource: apiKeyProvided ? ".lyra/credentials.json" : "env:LYRA_API_KEY",
414
+ verticals: selectedDomains.map((domain) => domain.id),
415
+ }
416
+ : undefined,
417
+ domainsMetadata: selectedDomains.map((domain) => sanitizeConfigDomainEntry(domain)),
418
+ };
419
+ }
420
+
421
+ function sanitizeConfigDomainEntry(entry) {
422
+ const agentCount = Array.isArray(entry.agents) ? entry.agents.length : Number(entry.agentCount || 0);
423
+ return {
424
+ id: entry.id,
425
+ label: entry.label,
426
+ mode: entry.mode || "standalone",
427
+ sourceType: entry.sourceType || "catalog",
428
+ agentCount,
429
+ };
430
+ }
431
+
432
+ function buildStandaloneAgentSpec(domain, agent) {
433
+ return {
434
+ schemaVersion: 1,
435
+ type: "standalone-agent",
436
+ id: agent.id,
437
+ slug: agent.slug,
438
+ name: agent.name,
439
+ domain: domain.id,
440
+ category: agent.category,
441
+ mode: "standalone",
442
+ description: agent.description,
443
+ icon: agent.icon || null,
444
+ skills: agent.skills || [],
445
+ integrations: agent.requiresIntegration || [],
446
+ generatedFrom: agent.generatedFrom || "onboarding-catalog",
447
+ promptTemplateId: agent.promptTemplateId || null,
448
+ systemPrompt: agent.systemPrompt || "",
449
+ repoIntelligence: {
450
+ enabled: true,
451
+ requiresScan: Boolean(agent.runtimeHints?.requiresRepoScan),
452
+ scanEndpoint: agent.runtimeHints?.suggestedScanEndpoint || "/api/repositories/:id/scan",
453
+ pullRequestEndpoint: agent.runtimeHints?.suggestedPrEndpoint || "/api/repositories/:id/lyra-pr",
454
+ contextContract: {
455
+ required: [
456
+ "repoContext",
457
+ "findingsAtScanTime",
458
+ "responsibilities",
459
+ "scopedPaths",
460
+ "confidence",
461
+ ],
462
+ },
463
+ },
464
+ runtime: {
465
+ execution: "local",
466
+ orchestration: "standalone",
467
+ ragEnabled: true,
468
+ },
469
+ outputs: {
470
+ format: "markdown",
471
+ requireCitations: Boolean((agent.skills || []).includes("url-scraper") || (agent.skills || []).includes("web-search")),
472
+ },
473
+ };
474
+ }
475
+
476
+ function buildGatedAgentSpec(domain, agent) {
477
+ return {
478
+ schemaVersion: 1,
479
+ type: "hosted-agent",
480
+ id: agent.id,
481
+ slug: agent.slug,
482
+ name: agent.name,
483
+ domain: domain.id,
484
+ category: agent.category,
485
+ mode: "gated",
486
+ description: agent.description,
487
+ icon: agent.icon || null,
488
+ skills: agent.skills || [],
489
+ integrations: agent.requiresIntegration || [],
490
+ generatedFrom: agent.generatedFrom || "gated-vertical-catalog",
491
+ promptTemplateId: agent.promptTemplateId || null,
492
+ systemPrompt: agent.systemPrompt || "",
493
+ repoIntelligence: {
494
+ enabled: true,
495
+ requiresScan: false,
496
+ scanEndpoint: "/api/repositories/:id/scan",
497
+ pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
498
+ contextContract: {
499
+ required: [
500
+ "repoContext",
501
+ "findingsAtScanTime",
502
+ "responsibilities",
503
+ "scopedPaths",
504
+ "confidence",
505
+ ],
506
+ },
507
+ },
508
+ hosted: {
509
+ provider: "lyra",
510
+ vertical: agent.hosted?.vertical || domain.id,
511
+ defaultModel: agent.hosted?.defaultModel || null,
512
+ endpoint: `/agents/${agent.hosted?.vertical || domain.id}/invoke`,
513
+ auth: {
514
+ strategy: "bearer",
515
+ credentialsFile: ".lyra/credentials.json",
516
+ credentialsKey: "LYRA_API_KEY",
517
+ },
518
+ },
519
+ outputs: {
520
+ format: "json",
521
+ includeUsage: true,
522
+ },
523
+ };
524
+ }
525
+
526
+ function buildAgentSpec(domain, mode, agent) {
527
+ const effectiveMode = domain.mode || mode;
528
+ return effectiveMode === "gated"
529
+ ? buildGatedAgentSpec(domain, agent)
530
+ : buildStandaloneAgentSpec(domain, agent);
531
+ }
532
+
533
+ function toYamlValue(value, indent = 0) {
534
+ const pad = " ".repeat(indent);
535
+ if (value === null || value === undefined) {
536
+ return "null";
537
+ }
538
+ if (typeof value === "string") {
539
+ return JSON.stringify(value);
540
+ }
541
+ if (typeof value === "number" || typeof value === "boolean") {
542
+ return String(value);
543
+ }
544
+ if (Array.isArray(value)) {
545
+ if (value.length === 0) {
546
+ return "[]";
547
+ }
548
+ return value
549
+ .map((item) => {
550
+ const rendered = toYamlValue(item, indent + 2);
551
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
552
+ const lines = rendered.split("\n");
553
+ return `${pad}- ${lines[0]}${lines.length > 1 ? `\n${lines.slice(1).join("\n")}` : ""}`;
554
+ }
555
+ return `${pad}- ${rendered}`;
556
+ })
557
+ .join("\n");
558
+ }
559
+
560
+ const entries = Object.entries(value);
561
+ if (entries.length === 0) {
562
+ return "{}";
563
+ }
564
+ return entries
565
+ .map(([key, entryValue]) => {
566
+ if (typeof entryValue === "object" && entryValue !== null) {
567
+ return `${pad}${key}:\n${toYamlValue(entryValue, indent + 2)}`;
568
+ }
569
+ return `${pad}${key}: ${toYamlValue(entryValue, indent + 2)}`;
570
+ })
571
+ .join("\n");
572
+ }
573
+
574
+ function buildAgentMarkdown(spec) {
575
+ const frontMatter = {
576
+ schemaVersion: spec.schemaVersion,
577
+ type: spec.type,
578
+ id: spec.id,
579
+ slug: spec.slug,
580
+ name: spec.name,
581
+ description: spec.description || "AgentLyra project agent",
582
+ domain: spec.domain,
583
+ category: spec.category,
584
+ mode: spec.mode,
585
+ icon: spec.icon,
586
+ generatedFrom: spec.generatedFrom,
587
+ promptTemplateId: spec.promptTemplateId,
588
+ skills: spec.skills,
589
+ integrations: spec.integrations,
590
+ };
591
+
592
+ const sections = [
593
+ "---",
594
+ toYamlValue(frontMatter),
595
+ "---",
596
+ "",
597
+ `# ${spec.name}`,
598
+ "",
599
+ "## Description",
600
+ spec.description || "",
601
+ "",
602
+ "## System Prompt",
603
+ spec.systemPrompt || "",
604
+ "",
605
+ "## Runtime Spec",
606
+ "```json",
607
+ JSON.stringify({
608
+ repoIntelligence: spec.repoIntelligence,
609
+ runtime: spec.runtime || null,
610
+ hosted: spec.hosted || null,
611
+ outputs: spec.outputs || null,
612
+ }, null, 2),
613
+ "```",
614
+ "",
615
+ ];
616
+
617
+ return sections.join("\n");
618
+ }
619
+
620
+ async function writeDomainManifest(rootDir, mode, domain) {
621
+ const domainRoot = path.join(rootDir, "domains", domain.id);
622
+ const manifestPath = path.join(domainRoot, "domain.json");
623
+ const skillSet = new Set();
624
+ const integrationSet = new Set();
625
+
626
+ for (const agent of domain.agents || []) {
627
+ for (const skill of agent.skills || []) {
628
+ skillSet.add(skill);
629
+ }
630
+ for (const integration of agent.requiresIntegration || []) {
631
+ integrationSet.add(integration);
632
+ }
633
+ }
634
+
635
+ const manifest = {
636
+ schemaVersion: 1,
637
+ id: domain.id,
638
+ label: domain.label,
639
+ mode,
640
+ generatedFrom: domain.generatedFrom || (mode === "gated" ? "gated-vertical-catalog" : "onboarding-catalog"),
641
+ agentCount: (domain.agents || []).length,
642
+ agentIds: (domain.agents || []).map(agent => agent.id),
643
+ skills: [...skillSet].sort(),
644
+ integrations: [...integrationSet].sort(),
645
+ repoIntelligence: {
646
+ enabled: true,
647
+ scanEndpoint: "/api/repositories/:id/scan",
648
+ pullRequestEndpoint: "/api/repositories/:id/lyra-pr",
649
+ notes: "These agent specs are designed to be hydrated with repository scan output and PR generation workflows.",
650
+ },
651
+ generatedAt: new Date().toISOString(),
652
+ };
653
+
654
+ await fs.mkdir(domainRoot, { recursive: true });
655
+ await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
656
+ }
657
+
658
+ async function writeDomainFiles(rootDir, mode, selectedDomains) {
659
+ for (const domain of selectedDomains) {
660
+ await writeDomainManifest(rootDir, mode, domain);
661
+ }
662
+ }
663
+
664
+ async function writeTopLevelManifest(rootDir, mode, selectedDomains) {
665
+ const agentsDir = path.join(rootDir, "agents");
666
+ const manifestPath = path.join(rootDir, "manifest.json");
667
+ await fs.mkdir(agentsDir, { recursive: true });
668
+
669
+ const manifests = await Promise.all(selectedDomains.map(async (domain) => {
670
+ const source = domain.sourceType === "platform" ? "platform-sync" : (mode === "gated" ? "gated-catalog" : "standalone-catalog");
671
+ const comparisonStatus = domain.sourceType === "platform" ? "imported" : "new";
672
+ const complements = selectedDomains
673
+ .filter((candidate) => candidate.id !== domain.id && candidate.mode !== domain.mode)
674
+ .map((candidate) => candidate.id);
675
+
676
+ let overlapsWith = [];
677
+ if (domain.sourceType !== "platform") {
678
+ overlapsWith = selectedDomains
679
+ .filter((candidate) => candidate.id !== domain.id && candidate.mode === domain.mode)
680
+ .filter((candidate) => {
681
+ const left = new Set((domain.agents || []).map((agent) => agent.id));
682
+ const right = new Set((candidate.agents || []).map((agent) => agent.id));
683
+ for (const id of left) {
684
+ if (right.has(id)) return true;
685
+ }
686
+ return false;
687
+ })
688
+ .map((candidate) => candidate.id);
689
+ }
690
+
691
+ const agentIds = (domain.agents || []).map((agent) => agent.id);
692
+ return {
693
+ id: domain.id,
694
+ label: domain.label,
695
+ mode: domain.mode || mode,
696
+ source,
697
+ comparisonStatus,
698
+ overlapsWith,
699
+ complements,
700
+ agentIds,
701
+ generatedAt: new Date().toISOString(),
702
+ };
703
+ }));
704
+
705
+ for (const domain of selectedDomains) {
706
+ const domainDir = path.join(agentsDir, domain.id);
707
+ await fs.mkdir(domainDir, { recursive: true });
708
+ for (const agent of domain.agents || []) {
709
+ const spec = buildAgentSpec(domain, mode, agent);
710
+ const fileName = `${spec.slug}.agent.md`;
711
+ await fs.writeFile(path.join(domainDir, fileName), buildAgentMarkdown(spec), "utf8");
712
+ }
713
+ }
714
+
715
+ await fs.writeFile(
716
+ manifestPath,
717
+ `${JSON.stringify({
718
+ schemaVersion: 2,
719
+ mode,
720
+ generatedAt: new Date().toISOString(),
721
+ domains: manifests,
722
+ }, null, 2)}\n`,
723
+ "utf8",
724
+ );
725
+ }
726
+
727
+ async function writeScaffold({ targetDir, mode, selectedDomains, apiKey }) {
728
+ const lyraDir = path.join(targetDir, ".lyra");
729
+ await fs.mkdir(lyraDir, { recursive: true });
730
+ await fs.mkdir(path.join(lyraDir, "domains"), { recursive: true });
731
+ await fs.writeFile(path.join(lyraDir, ".gitignore"), "credentials.json\n", "utf8");
732
+
733
+ const config = buildConfig(mode, selectedDomains, Boolean(apiKey));
734
+ await fs.writeFile(path.join(lyraDir, "config.json"), `${JSON.stringify(config, null, 2)}\n`, "utf8");
735
+
736
+ if (mode === "gated" && apiKey) {
737
+ await fs.writeFile(
738
+ path.join(lyraDir, "credentials.json"),
739
+ `${JSON.stringify({ LYRA_API_KEY: apiKey }, null, 2)}\n`,
740
+ "utf8",
741
+ );
742
+ }
743
+
744
+ const readme = [
745
+ "# .lyra",
746
+ "",
747
+ `Mode: ${mode}`,
748
+ "",
749
+ "Domains:",
750
+ ...selectedDomains.map((domain) => `- ${domain.label} (${domain.id})`),
751
+ "",
752
+ mode === "gated"
753
+ ? "Hosted setup stores the API key in .lyra/credentials.json, which is ignored by the local .lyra/.gitignore file."
754
+ : "Standalone setup keeps all orchestration local and side-effect free until you invoke your own flows.",
755
+ ].join("\n");
756
+ await fs.writeFile(path.join(lyraDir, "README.md"), `${readme}\n`, "utf8");
757
+
758
+ await writeDomainFiles(lyraDir, mode, selectedDomains);
759
+ await writeTopLevelManifest(lyraDir, mode, selectedDomains);
760
+ }
761
+
762
+ function resolvePresetDomains(rawDomains, catalog) {
763
+ if (!rawDomains || rawDomains === true) {
764
+ return [];
765
+ }
766
+ const requested = String(rawDomains)
767
+ .split(",")
768
+ .map((value) => value.trim().toLowerCase())
769
+ .filter(Boolean);
770
+ return catalog.filter((domain) => requested.includes(domain.id));
771
+ }
772
+
773
+ function applyGatedLockIfLoggedOut(selectedDomains, hasApiKey) {
774
+ if (hasApiKey) return selectedDomains;
775
+
776
+ return selectedDomains.map((domain) => {
777
+ if ((domain.mode || "standalone") !== "gated") {
778
+ return domain;
779
+ }
780
+
781
+ return {
782
+ ...domain,
783
+ sourceType: domain.sourceType || "catalog",
784
+ lockReason: "needs-login",
785
+ agents: (domain.agents || []).map((agent) => ({
786
+ ...agent,
787
+ hosted: {
788
+ ...(agent.hosted || {}),
789
+ locked: true,
790
+ lockReason: "needs-login",
791
+ },
792
+ })),
793
+ };
794
+ });
795
+ }
796
+
797
+ export async function runInitWizard(options = {}) {
798
+ const rl = readline.createInterface({ input, output });
799
+
800
+ try {
801
+ printWelcomeBanner();
802
+ const stackMode = (options.stack || options.detect) && ["standalone", "gated"].includes(options.mode);
803
+ const wantsLogin = !stackMode && await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
804
+ const apiBaseUrl = options["api-base-url"] || process.env.LYRA_API_BASE_URL || DEFAULT_API_BASE_URL;
805
+ let apiKey = stackMode && options.mode === "standalone" ? "" : options["api-key"] || process.env.LYRA_API_KEY || "";
806
+ let importedAgents = [];
807
+
808
+ if (wantsLogin && !apiKey) {
809
+ output.write("Paste your Lyra API key (starts with lyra_).\n");
810
+ apiKey = await askQuestion(rl, "Lyra API key: ", { secret: true });
811
+ }
812
+
813
+ if (apiKey) {
814
+ try {
815
+ const agents = await fetchUserAgentsByApiKey(apiBaseUrl, apiKey);
816
+ importedAgents = normalizePlatformAgents(agents);
817
+ output.write(`Synced ${importedAgents.length} agent(s) from your Lyra account.\n`);
818
+ } catch (error) {
819
+ output.write(`Could not sync your agents: ${error.message}. Continuing with catalog selections.\n`);
820
+ }
821
+ }
822
+
823
+ const chosenGroup = stackMode ? undefined : await chooseFlowGroup(rl);
824
+ let mode = options.mode;
825
+ if (mode !== "standalone" && mode !== "gated") {
826
+ mode = chosenGroup === "everyday" ? "gated" : await chooseMode(rl, mode);
827
+ }
828
+
829
+ if (mode === "gated" && !apiKey) {
830
+ output.write("Hosted packs need Lyra login. You can continue, but hosted packs will be marked as locked.\n");
831
+ }
832
+
833
+ const catalog = getDomainCatalog(mode);
834
+ const catalogWithHints = catalog.map((item) => ({
835
+ ...item,
836
+ sourceType: "catalog",
837
+ hint: mode === "gated" && !apiKey ? "needs login" : "",
838
+ }));
839
+ const presetDomains = resolvePresetDomains(options.domains, catalogWithHints);
840
+
841
+ const dynamicGroups = [];
842
+ if (importedAgents.length > 0) {
843
+ dynamicGroups.push({ label: "Your agents", options: importedAgents });
844
+ }
845
+ dynamicGroups.push({
846
+ label: mode === "gated" ? "Create new (hosted verticals)" : "Create new (catalog domains)",
847
+ options: catalogWithHints,
848
+ });
849
+
850
+ if (stackMode && !presetDomains.length) throw new Error("Use --domains with a valid Coding or Engineering domain ID.");
851
+ const selected = presetDomains.length > 0
852
+ ? presetDomains
853
+ : await selectManyGrouped(
854
+ rl,
855
+ "Select domains and/or your synced agents",
856
+ dynamicGroups,
857
+ [],
858
+ );
859
+
860
+ let selectedDomains = selected.map((entry) => {
861
+ if (entry.sourceType === "platform") {
862
+ return {
863
+ id: entry.id,
864
+ label: entry.label,
865
+ mode: "standalone",
866
+ sourceType: "platform",
867
+ agents: [
868
+ {
869
+ id: entry.importPayload.id,
870
+ slug: entry.importPayload.slug,
871
+ name: entry.importPayload.name,
872
+ description: entry.importPayload.description,
873
+ category: entry.importPayload.category,
874
+ icon: entry.importPayload.icon,
875
+ skills: entry.importPayload.skills,
876
+ requiresIntegration: entry.importPayload.integrations,
877
+ generatedFrom: entry.importPayload.generatedFrom,
878
+ systemPrompt: entry.importPayload.systemPrompt,
879
+ promptTemplateId: entry.importPayload.promptTemplateId,
880
+ runtimeHints: {
881
+ requiresRepoScan: true,
882
+ suggestedScanEndpoint: "/api/repositories/:id/scan",
883
+ suggestedPrEndpoint: "/api/repositories/:id/lyra-pr",
884
+ },
885
+ importPayload: entry.importPayload,
886
+ },
887
+ ],
888
+ };
889
+ }
890
+ return {
891
+ ...entry,
892
+ sourceType: entry.sourceType || "catalog",
893
+ };
894
+ });
895
+
896
+ if (selectedDomains.length === 0) {
897
+ throw new Error("Select at least one domain.");
898
+ }
899
+
900
+ selectedDomains = applyGatedLockIfLoggedOut(selectedDomains, Boolean(apiKey));
901
+
902
+ if (mode === "gated" && !apiKey) {
903
+ output.write("Enter the Lyra API key from the Lyra login UI. It will be stored in .lyra/credentials.json and ignored by .lyra/.gitignore.\n");
904
+ apiKey = await askQuestion(rl, "Lyra API key: ", { secret: true });
905
+ if (!apiKey) {
906
+ throw new Error("A Lyra API key is required for gated setup.");
907
+ }
908
+ }
909
+
910
+ const targetDir = path.resolve(options.dir || process.cwd());
911
+ const lyraDir = path.join(targetDir, ".lyra");
912
+ const coding = selectedDomains.some(domain => domain.id === "coding" || domain.id === "engineering-bootstrap");
913
+ if (options.stack !== undefined && (!coding || typeof options.stack !== "string")) {
914
+ throw new Error("Use --stack with a stack name and the Coding domain.");
915
+ }
916
+ if (options.detect && (!coding || options.stack)) throw new Error("Use --detect with the Coding domain instead of --stack.");
917
+ let stack = options.stack;
918
+ if (coding && !stack) {
919
+ const detect = options.detect || (input.isTTY && await askYesNo(rl, "Detect technologies from this project?", false));
920
+ if (detect) {
921
+ const recommendations = await recommendCodingStacks(targetDir, output);
922
+ if (recommendations.length && (options.detect || await askYesNo(rl, "Use these recommendations?", true))) stack = recommendations;
923
+ }
924
+ if (!stack && input.isTTY) stack = await selectCodingStack(rl, output);
925
+ }
926
+ let applyCoding;
927
+ if (coding) {
928
+ const existing = await fs.lstat(lyraDir).catch(error => {
929
+ if (error.code !== "ENOENT") throw error;
930
+ });
931
+ if (existing) throw new Error("This project already has .lyra. Run agent-lyra setup coding to add packs while keeping your files.");
932
+ const apply = await prepareCodingStack(targetDir, stack || [], output);
933
+ if (!stack || options.stack || options.detect || /^y(?:es)?$/i.test(await askQuestion(rl, "Create these coding files? [y/N] "))) applyCoding = apply;
934
+ }
935
+ await ensureEmptyOrApproved(rl, lyraDir, Boolean(options.force));
936
+ await writeScaffold({ targetDir, mode, selectedDomains, apiKey });
937
+ if (applyCoding) await applyCoding();
938
+ await ensureVSCodeAgentDiscovery(targetDir);
939
+
940
+ output.write(`Created ${lyraDir} for ${mode} mode with ${selectedDomains.length} domain(s).\n`);
941
+ } finally {
942
+ rl.close();
943
+ }
944
+ }
945
+
946
+ export async function runCli(argv = process.argv.slice(2)) {
947
+ const args = parseArgs(argv);
948
+ const [first, second] = args._;
949
+ const command = first === "lyra" ? second : first;
950
+
951
+ if (!command || command === "help" || args.help) {
952
+ printUsage();
953
+ return;
954
+ }
955
+
956
+ if (command === "init") {
957
+ await runInitWizard(args);
958
+ return;
959
+ }
960
+
961
+ throw new Error(`Unknown command: ${command}`);
962
+ }
963
+
961
964
  export { GATED_DOMAINS, STANDALONE_DOMAINS };