agent-lyra 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,9 +9,9 @@ Build apps from your saved Lyra agents, run agents with your own OpenAI key, and
9
9
  | Mode | Where work runs | What you need |
10
10
  | --- | --- | --- |
11
11
  | **Work locally** | In your own Node.js process. Use `agent-lyra/standalone` for local workflows and retrieval, or run your own local workflows. | No AgentLyra account or key. Model-backed CLI runs use your own OpenAI key. |
12
- | **Connect to Cloud** | On a compatible hosted backend. `agent-lyra/gated` calls the backend's `/agents/<vertical>/invoke` endpoint. | A Lyra API key for that backend and its base URL. For AgentLyra Cloud, use a dedicated SDK key and the base URL https://api.agentlyra.in/api/sdk/v1. Cloud SDK calls also require an OpenAI key in Models settings. |
12
+ | **Connect to Cloud** | On a compatible hosted backend. `agent-lyra/gated` calls the backend's `/agents/<vertical>/invoke` endpoint. | A Lyra API key for that backend and its base URL. For AgentLyra Cloud, use an AgentLyra API key with hosted agent access and the base URL https://api.agentlyra.in/api/sdk/v1. Cloud SDK calls also require an OpenAI key in Models settings. |
13
13
 
14
- The App Builder below uses a dedicated SDK key to run saved agents in AgentLyra Cloud. Standalone workflows remain available through the SDK and CLI.
14
+ The App Builder below uses an AgentLyra API key with hosted agent access to run saved agents in AgentLyra Cloud. Standalone workflows remain available through the SDK and CLI.
15
15
 
16
16
  ## Install
17
17
 
@@ -34,16 +34,16 @@ npx.cmd agent-lyra connect-cloud
34
34
  npx.cmd agent-lyra work-locally
35
35
  ```
36
36
 
37
- The first connection to Cloud prompts for an SDK key if none is available. Paste the key at the hidden prompt. The CLI saves a prompted key under `~/.agent-lyra/` for reuse by your OS account. Later switches reuse it. Run `npx.cmd agent-lyra connect-cloud --replace-key` to replace it. Working locally pauses Studio Cloud pulls and runs. Switching preserves your canvas and local agents. When connected to Cloud, you can use local and Cloud agents. If Studio is already open, click **Reload agents** to refresh the mode shown in its header.
37
+ The first connection to Cloud prompts for an AgentLyra API key if none is available. Paste the key at the hidden prompt. The CLI saves a prompted key under `~/.agent-lyra/` for reuse by your OS account. Later switches reuse it. Run `npx.cmd agent-lyra connect-cloud --replace-key` to replace it. Working locally pauses Studio Cloud pulls and runs. Switching preserves your canvas and local agents. When connected to Cloud, you can use local and Cloud agents. If Studio is already open, click **Reload agents** to refresh the mode shown in its header.
38
38
 
39
39
 
40
40
  ### Push a local text agent to Cloud
41
41
 
42
- Generate a **Cloud sync key** on the API Keys page and set it with `npx.cmd agent-lyra connect-cloud --replace-key`. In Studio, click **Push to Cloud** on a local Markdown agent. From the terminal, use `npx.cmd agent-lyra studio push <local-agent-id>`. This sends the name and instructions and creates a private Cloud agent. Later pushes update the same agent. If the Cloud instructions or name changed, Studio stops before overwriting them. Use **Pull agent edits** on the linked card or `npx.cmd agent-lyra studio pull-agent <local-agent-id>` to bring the Cloud version back. If both copies changed, review them before updating either one. If your terminal already sets `LYRA_API_KEY`, that value takes priority over the saved key.
42
+ Generate an **AgentLyra API key** with Cloud resource sync permission on the API Keys page and set it with `npx.cmd agent-lyra connect-cloud --replace-key`. In Studio, click **Push to Cloud** on a local Markdown agent. From the terminal, use `npx.cmd agent-lyra studio push <local-agent-id>`. This sends the name and instructions and creates a private Cloud agent. Later pushes update the same agent. If the Cloud instructions or name changed, Studio stops before overwriting them. Use **Pull agent edits** on the linked card or `npx.cmd agent-lyra studio pull-agent <local-agent-id>` to bring the Cloud version back. If both copies changed, review them before updating either one. If your terminal already sets `LYRA_API_KEY`, that value takes priority over the saved key.
43
43
 
44
44
  ### Sync a sequential workflow
45
45
 
46
- Use a **Cloud sync key**. Push any local Markdown agents referenced by the workflow first. Save a workflow such as this one in `.lyra/workflows/review.json`:
46
+ Use an **AgentLyra API key** with Cloud resource sync permission. Push any local Markdown agents referenced by the workflow first. Save a workflow such as this one in `.lyra/workflows/review.json`:
47
47
 
48
48
  ```json
49
49
  {
@@ -70,7 +70,7 @@ npx.cmd agent-lyra studio pull-workflow review
70
70
 
71
71
  ### Sync a personal team
72
72
 
73
- Use a **Cloud sync key**. Push local agents first, then save a definition such as this one in `.lyra/teams/research.json`:
73
+ Use an **AgentLyra API key** with Cloud resource sync permission. Push local agents first, then save a definition such as this one in `.lyra/teams/research.json`:
74
74
 
75
75
  ```json
76
76
  {"id":"research","name":"Research","description":"Draft and review research notes.","agentIds":["local:writer"]}
@@ -86,7 +86,7 @@ npx.cmd agent-lyra studio pull-team research
86
86
 
87
87
  ### Sync a text skill
88
88
 
89
- Use a **Cloud sync key**. Save a text definition such as this one in `.lyra/skills/notes.json`:
89
+ Use an **AgentLyra API key** with Cloud resource sync permission. Save a text definition such as this one in `.lyra/skills/notes.json`:
90
90
 
91
91
  ```json
92
92
  {"id":"notes","name":"Meeting notes","description":"Turn notes into a short recap.","body":"Summarize decisions and list next steps."}
@@ -104,11 +104,11 @@ npx.cmd agent-lyra studio pull-skill notes
104
104
 
105
105
  Standalone agents run in your project. Cloud agents run in AgentLyra Cloud. Studio can use both in one canvas. You can keep your existing `.lyra` files and `manifest.json`. Rerunning `init` or changing the manifest mode is unnecessary.
106
106
 
107
- 1. Open [AgentLyra Console → API Keys](https://console.agentlyra.in/mcp-servers). Select **Generate SDK key** and copy the key beginning with `lyra_sdk_`.
107
+ 1. Open [AgentLyra Console → API Keys](https://console.agentlyra.in/mcp-servers). Select **Generate AgentLyra API key** and copy the key beginning with `lyra_sdk_`.
108
108
  2. In VS Code, open a **PowerShell** terminal in your project. Run the line below, paste the key at the masked prompt, and press Enter. The key is available to this terminal and the programs it starts.
109
109
 
110
110
  ```powershell
111
- $env:LYRA_API_KEY = Read-Host "Paste your AgentLyra SDK key" -MaskInput
111
+ $env:LYRA_API_KEY = Read-Host "Paste your AgentLyra API key" -MaskInput
112
112
  ```
113
113
 
114
114
  3. Start Studio from that same terminal. If it is already running, stop it first with **Ctrl+C** so it picks up the key.
@@ -118,14 +118,14 @@ Standalone agents run in your project. Cloud agents run in AgentLyra Cloud. Stud
118
118
  ```
119
119
 
120
120
  4. Open the URL Studio prints and click **Pull from Cloud**. You can also pull from the terminal with `npx agent-lyra studio pull`. The pull adds agent references, workflows, team metadata, and skill references under `.lyra/` and preserves existing files.
121
- 5. In the Inspector, choose the Cloud agent for an **Agent card**, or add it to a **Run button** sequence. Existing bindings keep using their current agents until you change them. To execute a Cloud agent, also configure your OpenAI key in **Console → Models**. The SDK key authorizes the pull and Cloud requests.
121
+ 5. In the Inspector, choose the Cloud agent for an **Agent card**, or add it to a **Run button** sequence. Existing bindings keep using their current agents until you change them. To execute a Cloud agent, also configure your OpenAI key in **Console → Models**. The AgentLyra API key authorizes the pull and Cloud requests.
122
122
 
123
- For exported apps with Cloud agents, set `LYRA_API_KEY` in the terminal that starts the exported app. Keep keys out of manifests and Git. If Studio asks for the SDK key after you set it, check that you launched Studio in the same terminal. If Cloud execution asks for a provider key, check **Console → Models**.
123
+ For exported apps with Cloud agents, set `LYRA_API_KEY` in the terminal that starts the exported app. Keep keys out of manifests and Git. If Studio asks for the AgentLyra API key after you set it, check that you launched Studio in the same terminal. If Cloud execution asks for a provider key, check **Console → Models**.
124
124
 
125
125
 
126
126
  ## Build an app from your Lyra agents
127
127
 
128
- Create two enabled text agents in AgentLyra Console. In [API key settings](https://console.agentlyra.in/mcp-servers), choose **Generate SDK key** and set it as `LYRA_API_KEY` in your terminal environment. Add your own OpenAI key in Console → Models. Keep both keys out of source control.
128
+ Create two enabled text agents in AgentLyra Console. In [API key settings](https://console.agentlyra.in/mcp-servers), choose **Generate AgentLyra API key** and set it as `LYRA_API_KEY` in your terminal environment. Add your own OpenAI key in Console → Models. Keep both keys out of source control.
129
129
 
130
130
  ```bash
131
131
  npx agent-lyra app init
@@ -313,12 +313,14 @@ The approval records your review. It does not install the proposal or edit any s
313
313
 
314
314
  ### Sync selected memories to Cloud
315
315
 
316
- Local memory stays on your machine by default. To sync a record, generate a **Memory sync key** in [Console → API Keys](https://console.agentlyra.in/mcp-servers). This key is separate from the keys for running agents and syncing other resources. In PowerShell, enter the key at the masked prompt:
316
+ Local memory stays on your machine by default. In [Console → API Keys](https://console.agentlyra.in/mcp-servers), select **Generate AgentLyra API key** with **Sync verified memories** enabled. Leave all permissions selected to reuse the same key for hosted agents, Cloud resources, and memories.
317
317
 
318
- ```powershell
319
- $env:LYRA_MEMORY_KEY = (Read-Host 'Paste your Memory sync key' -MaskInput).Trim()
318
+ ```sh
319
+ npx agent-lyra connect-cloud
320
320
  ```
321
321
 
322
+ If you previously saved a key, add `--replace-key` to enter the new one. Existing dedicated Memory keys still work through `LYRA_MEMORY_KEY`, which takes priority for Memory sync.
323
+
322
324
  From the same terminal, preview a verified record and then explicitly confirm the upload:
323
325
 
324
326
  ```sh
@@ -393,3 +395,41 @@ The standalone entry point also includes retrieval utilities. The gated entry po
393
395
  The App Builder supports two saved text agents in sequence. Publishing saved-agent app manifests to Marketplace is outside the current release. OpenAI-backed agent runs use your own provider key. Cloud accounts and AgentLyra API keys are managed in the [AgentLyra console](https://console.agentlyra.in/).
394
396
 
395
397
  MIT licensed.
398
+
399
+ ## Set up coding agents and skills
400
+
401
+ Choose **Coding** or **Engineering** during interactive `init`, or run `npx agent-lyra setup coding` from an existing project. The Python command uses the bundled CLI and requires Node.js 22.13 or newer.
402
+
403
+ ```sh
404
+ npx agent-lyra setup coding --stack mern,typescript,playwright --preview
405
+ npx agent-lyra setup coding --stack playwright-cucumber --yes
406
+ ```
407
+
408
+ Choose frontend, backend, database, DevOps, or QA packs individually. Presets include `mern`, `python-fastapi`, and `playwright-cucumber`. Setup works locally and creates editable agents in `.lyra/agents` and skills in `.lyra/skills`. It preserves existing files on rerun. A new combination creates a separate profile for the affected area. Studio lists the generated agents and Markdown skills.
409
+
410
+ For an existing repository, preview automatic stack recommendations:
411
+
412
+ ```sh
413
+ npx agent-lyra setup coding --detect --preview
414
+ ```
415
+
416
+ The scan prints the evidence for each folder and flags technologies that have no bundled pack. Run interactive setup to confirm the recommendations or choose manually. Use `--detect --yes` to apply recommendations unattended. After setup, run `node .lyra/scripts/detect-stack.mjs` to get a read-only JSON report. The scanner reads local project metadata and skips hidden directories, dependency trees, and symbolic links.
417
+
418
+ ### Export to a coding assistant
419
+
420
+ ```sh
421
+ npx agent-lyra setup coding export --to claude,codex,copilot --preview
422
+ npx agent-lyra setup coding export --to claude,codex,copilot --yes
423
+ ```
424
+
425
+ The command reads the editable Markdown in `.lyra/agents` and `.lyra/skills`. An interactive run suggests targets from project folders and asks which ones to configure. Each target gets its own agent format and `SKILL.md` files. Preview reports existing files and the exporter preserves them. Export carries instructions only. Check referenced scripts and resources separately. Review any changed export against your customized copy before replacing an existing file.
426
+
427
+ ### Choose a catalog version
428
+
429
+ Setup uses the bundled catalog offline. It includes frontend, backend, databases, DevOps, QA, mobile, and data engineering packs. To preview a specific published version from AgentLyra Cloud, run:
430
+
431
+ ```sh
432
+ npx agent-lyra setup coding --detect --catalog-version 2 --preview
433
+ ```
434
+
435
+ Use `--stack` with a named preset or comma-separated technologies for manual setup. Existing agent and skill files are preserved. Review differences yourself before replacing a personalized file. The setup receipt records which catalog version was selected.
package/bin/agent-lyra.js CHANGED
@@ -3,6 +3,8 @@
3
3
  import { runSkillProposals } from "../src/memory/skills-cli.js";
4
4
  import { runMemory } from "../src/memory/cli.js";
5
5
  import { runCli } from "../src/init.js";
6
+ import { runCodingExport } from "../src/coding/export.js";
7
+ import { runCodingSetup } from "../src/coding/setup.js";
6
8
  import { runLocalCli } from "../src/runtime/local-cli.js";
7
9
  import { serveSavedRuns } from "../src/runtime/mcp-stdio.js";
8
10
  import { runAppValidation } from "../src/app-builder/validate.js";
@@ -17,6 +19,9 @@ import { runStudio } from "../src/studio/server.js";
17
19
 
18
20
  async function main() {
19
21
  const argv = process.argv.slice(2);
22
+ if (argv[0] === "setup" && argv[1] === "coding") {
23
+ return argv[2] === "export" ? runCodingExport(argv.slice(3)) : runCodingSetup(argv.slice(2));
24
+ }
20
25
  if (argv[0] === "skills") return runSkillProposals(argv.slice(1));
21
26
  if (argv[0] === "memory") return runMemory(argv.slice(1));
22
27
  if (argv[0] === "connect-cloud") return switchMode(process.cwd(), "gated", argv.slice(1));
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { runLocalMemory } from '../src/memory/local-cli.js';
3
+ import { runSkillProposals } from '../src/memory/skills-cli.js';
4
+ import { runLocalCli } from '../src/runtime/local-cli.js';
5
+ import { serveSavedRuns } from '../src/runtime/mcp-stdio.js';
6
+ const [command,...args]=process.argv.slice(2);
7
+ try {
8
+ if (command==='memory') await runLocalMemory(args);
9
+ else if (command==='skills') await runSkillProposals(args);
10
+ else if (command==='mcp' && args[0]==='serve') await serveSavedRuns(args.slice(1));
11
+ else if (await runLocalCli([command,...args])) {}
12
+ else if (!command || command==='--help') console.log('Usage: agent-lyra-oss-preview memory | skills | agent run | team run | run status | mcp serve');
13
+ else throw new Error('Unsupported standalone command');
14
+ } catch(error) { console.error(error.message); process.exitCode=1; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyra",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Two-layer Lyra SDK with standalone local primitives and gated hosted agents.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -0,0 +1,46 @@
1
+ import { assertValueSchema } from "./value-schema.js";
2
+
3
+ const modes = new Set(["in-process", "local-process", "remote"]);
4
+ const identifier = /^[a-z][a-z0-9-]*$/;
5
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
6
+ const isIdentifier = (value) => typeof value === "string" && identifier.test(value);
7
+
8
+ export function validateAppManifest(manifest) {
9
+ if (!isRecord(manifest) || manifest.version !== "1.0") {
10
+ throw new Error('Application manifest requires version "1.0".');
11
+ }
12
+ const { application, capabilities, actions } = manifest;
13
+ if (!isRecord(application) || !isIdentifier(application.id) ||
14
+ typeof application.name !== "string" || !application.name.trim()) {
15
+ throw new Error("Application requires a valid id and a name.");
16
+ }
17
+ if (!Array.isArray(capabilities) || !Array.isArray(actions)) {
18
+ throw new Error("Capabilities and actions must be arrays.");
19
+ }
20
+
21
+ const capabilityIds = new Set();
22
+ for (const capability of capabilities) {
23
+ if (!isRecord(capability) || !isIdentifier(capability.id) || !isIdentifier(capability.adapterId) ||
24
+ !modes.has(capability.executionMode)) {
25
+ throw new Error("Each capability requires an id, adapterId, and supported executionMode.");
26
+ }
27
+ if (capabilityIds.has(capability.id)) throw new Error(`Duplicate capability: ${capability.id}.`);
28
+ for (const key of ["inputSchema", "outputSchema"]) {
29
+ if (Object.hasOwn(capability, key)) assertValueSchema(capability[key], `${capability.id} ${key}`);
30
+ }
31
+ capabilityIds.add(capability.id);
32
+ }
33
+ const actionIds = new Set();
34
+ for (const action of actions) {
35
+ if (!isRecord(action) || !isIdentifier(action.id) || !isIdentifier(action.capabilityId)) {
36
+ throw new Error("Each action requires an id and capabilityId.");
37
+ }
38
+ if (actionIds.has(action.id)) throw new Error(`Duplicate action: ${action.id}.`);
39
+ if (!capabilityIds.has(action.capabilityId)) {
40
+ throw new Error(`Action ${action.id} refers to unknown capability ${action.capabilityId}.`);
41
+ }
42
+ actionIds.add(action.id);
43
+ }
44
+ return { id: application.id, capabilityCount: capabilityIds.size, actionCount: actionIds.size };
45
+ }
46
+
@@ -1,49 +1,6 @@
1
1
  import { readAppManifest, SAVED_VERSION, validateSavedApp } from "./saved-app.js";
2
- import { assertValueSchema } from "./value-schema.js";
3
-
4
- const modes = new Set(["in-process", "local-process", "remote"]);
5
- const identifier = /^[a-z][a-z0-9-]*$/;
6
- const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
- const isIdentifier = (value) => typeof value === "string" && identifier.test(value);
8
-
9
- export function validateAppManifest(manifest) {
10
- if (!isRecord(manifest) || manifest.version !== "1.0") {
11
- throw new Error('Application manifest requires version "1.0".');
12
- }
13
- const { application, capabilities, actions } = manifest;
14
- if (!isRecord(application) || !isIdentifier(application.id) ||
15
- typeof application.name !== "string" || !application.name.trim()) {
16
- throw new Error("Application requires a valid id and a name.");
17
- }
18
- if (!Array.isArray(capabilities) || !Array.isArray(actions)) {
19
- throw new Error("Capabilities and actions must be arrays.");
20
- }
21
-
22
- const capabilityIds = new Set();
23
- for (const capability of capabilities) {
24
- if (!isRecord(capability) || !isIdentifier(capability.id) || !isIdentifier(capability.adapterId) ||
25
- !modes.has(capability.executionMode)) {
26
- throw new Error("Each capability requires an id, adapterId, and supported executionMode.");
27
- }
28
- if (capabilityIds.has(capability.id)) throw new Error(`Duplicate capability: ${capability.id}.`);
29
- for (const key of ["inputSchema", "outputSchema"]) {
30
- if (Object.hasOwn(capability, key)) assertValueSchema(capability[key], `${capability.id} ${key}`);
31
- }
32
- capabilityIds.add(capability.id);
33
- }
34
- const actionIds = new Set();
35
- for (const action of actions) {
36
- if (!isRecord(action) || !isIdentifier(action.id) || !isIdentifier(action.capabilityId)) {
37
- throw new Error("Each action requires an id and capabilityId.");
38
- }
39
- if (actionIds.has(action.id)) throw new Error(`Duplicate action: ${action.id}.`);
40
- if (!capabilityIds.has(action.capabilityId)) {
41
- throw new Error(`Action ${action.id} refers to unknown capability ${action.capabilityId}.`);
42
- }
43
- actionIds.add(action.id);
44
- }
45
- return { id: application.id, capabilityCount: capabilityIds.size, actionCount: actionIds.size };
46
- }
2
+ import { validateAppManifest } from "./manifest-contract.js";
3
+ export { validateAppManifest } from "./manifest-contract.js";
47
4
 
48
5
  export async function runAppValidation(args, output = process.stdout) {
49
6
  if (args.length === 1 && args[0] === "--help") {
@@ -0,0 +1,56 @@
1
+ export const catalogVersion = 2;
2
+
3
+ // Each technology contributes an actionable skill. Roles are reused across packs.
4
+ export const areas = {
5
+ frontend: "Frontend developer",
6
+ backend: "Backend developer",
7
+ database: "Database developer",
8
+ devops: "DevOps engineer",
9
+ qa: "QA automation engineer",
10
+ mobile: "Mobile developer",
11
+ data: "Data engineer",
12
+ };
13
+
14
+ export const technologies = {
15
+ react: ["frontend", "React", "Component behavior", "Check loading, error, and success states. Test the visible behavior with accessible queries and keep state close to the components that own it."],
16
+ nextjs: ["frontend", "Next.js", "Rendering and routing", "Identify the router and rendering boundary first. Keep server-only data on the server and test navigation, loading, and error states."],
17
+ typescript: ["frontend", "TypeScript", "Type-safe changes", "Read tsconfig for the project. Narrow unknown input at boundaries, preserve public types, and run the repository type check."],
18
+ node: ["backend", "Node.js", "Runtime compatibility", "Check the supported Node versions and module format. Handle async errors, close resources, and run the applicable package scripts."],
19
+ express: ["backend", "Express", "Request validation", "Validate request data at the route boundary, reuse existing middleware, and test status codes for missing, invalid, and valid input."],
20
+ python: ["backend", "Python", "Package and test changes", "Read pyproject.toml and supported Python versions. Use existing project tooling and test behavior through its public entry points."],
21
+ fastapi: ["backend", "FastAPI", "API contracts", "Use request and response models consistent with the project. Test validation, dependency overrides, and error responses with the app test client."],
22
+ mongodb: ["database", "MongoDB", "Document modeling", "Model against actual query patterns. Review indexes, existing document shapes, and migration compatibility with synthetic data."],
23
+ postgresql: ["database", "PostgreSQL", "Schema migrations", "Review data volume and lock implications. Test forward migrations against realistic fixtures and document application compatibility."],
24
+ docker: ["devops", "Docker", "Container builds", "Check build context and ignore rules. Keep secrets outside image layers and verify the start command and health endpoint locally."],
25
+ "github-actions": ["devops", "GitHub Actions", "CI workflows", "Review job triggers, permissions, and test artifacts. Reuse repository scripts and keep credentials in repository or environment secrets."],
26
+ "gitlab-ci": ["devops", "GitLab CI", "CI pipelines", "Review job rules, needs, and artifacts. Reuse project test commands and validate changes on a test branch."],
27
+ playwright: ["qa", "Playwright", "Browser automation", "Use role-based locators and web-first assertions. Isolate test data with fixtures, retain traces on failures, and diagnose flaky tests without adding fixed sleeps."],
28
+ vue: ["frontend", "Vue", "Reactive UI", "Check the Vue version and routing conventions. Test emitted events, user-visible states, and composable cleanup."],
29
+ angular: ["frontend", "Angular", "Component and service integration", "Follow the project's standalone or module pattern. Verify DI boundaries, form validation, and loading and error states."],
30
+ svelte: ["frontend", "Svelte", "Component state", "Use the project's Svelte version and reactive primitives. Cover interaction, SSR boundaries where relevant, and state reset."],
31
+ django: ["backend", "Django", "Model and view changes", "Review model validation, permissions, and migration dependencies. Exercise the relevant views through the test client."],
32
+ "spring-boot": ["backend", "Spring Boot", "Service and controller changes", "Follow existing configuration and dependency injection conventions. Test validation and error mapping using the project's test slices."],
33
+ dotnet: ["backend", ".NET", "Application and API changes", "Check target frameworks and hosting conventions. Test middleware, dependency injection, and public endpoint behavior."],
34
+ go: ["backend", "Go", "Service changes", "Use the module version and existing package boundaries. Propagate context and errors, and use table-driven tests for edge cases."],
35
+ rust: ["backend", "Rust", "Crate changes", "Check workspace features and the minimum supported Rust version. Preserve API error contracts and test meaningful feature combinations."],
36
+ mysql: ["database", "MySQL", "Schema and query changes", "Check server version and SQL mode. Validate migration locks, indexes, and query plans against synthetic data."],
37
+ redis: ["database", "Redis", "Cache behavior", "Define key scope and expiration. Cover cache misses, stale values, and recovery when Redis is unavailable."],
38
+ kubernetes: ["devops", "Kubernetes", "Deployment configuration", "Validate manifests against supported versions. Review probes, resource requests, and rollout behavior in a test namespace."],
39
+ terraform: ["devops", "Terraform", "Infrastructure review", "Inspect configuration and state boundaries. Review a plan in the intended environment before any apply."],
40
+ "react-native": ["mobile", "React Native", "Cross-platform screens", "Verify behavior on both supported platforms. Check accessibility, permission handling, and loading or offline states."],
41
+ flutter: ["mobile", "Flutter", "Widgets and navigation", "Follow project state and navigation conventions. Cover key behavior with widget tests and verify platform integrations separately."],
42
+ android: ["mobile", "Android", "Platform behavior", "Check lifecycle and target SDK constraints. Use local and instrumented tests as appropriate for storage, permissions, and navigation."],
43
+ ios: ["mobile", "iOS", "Platform behavior", "Check supported OS versions and project structure. Verify main-thread UI behavior, accessibility, and permission states."],
44
+ dbt: ["data", "dbt", "Data model tests", "Trace model dependencies, review incremental behavior, and test uniqueness, nullability, and source freshness with suitable data."],
45
+ spark: ["data", "Apache Spark", "Pipeline changes", "Review schema evolution, joins, partitioning, and null semantics. Test with a small deterministic dataset before larger workloads."],
46
+ cucumber: ["qa", "Cucumber", "Acceptance scenarios", "Write Gherkin scenarios around observable behavior. Reuse parameterized steps, keep state scoped to each scenario, and review undefined or ambiguous steps."],
47
+ };
48
+
49
+ export const presets = {
50
+ mern: ["mongodb", "express", "react", "node"],
51
+ "python-fastapi": ["python", "fastapi"],
52
+ "playwright-cucumber": ["playwright", "cucumber"],
53
+ "spring-postgres": ["spring-boot", "postgresql"],
54
+ "react-native-mobile": ["react-native", "typescript"],
55
+ "spark-dbt": ["spark", "dbt"],
56
+ };
@@ -0,0 +1,44 @@
1
+ import { areas, catalogVersion, presets, technologies } from "./catalog.js";
2
+
3
+ export const bundledCatalog = { version: catalogVersion, technologies, presets };
4
+
5
+ export async function fetchCodingCatalog(version, fetchRequest = fetch) {
6
+ if (!/^[1-9][0-9]{0,5}$/.test(version)) throw new Error("Use a numeric Cloud catalog version.");
7
+ const response = await fetchRequest("https://api.agentlyra.in/api/coding-catalog/" + version, {
8
+ redirect: "error", signal: AbortSignal.timeout(5000),
9
+ });
10
+ if (!response.ok) throw new Error("Cloud coding catalog version " + version + " is unavailable. Omit --catalog-version to use bundled packs.");
11
+ const reader = response.body.getReader();
12
+ const chunks = [];
13
+ let total = 0;
14
+ while (true) {
15
+ const { done, value } = await reader.read();
16
+ if (done) break;
17
+ total += value.byteLength;
18
+ if (total > 262_144) {
19
+ await reader.cancel();
20
+ throw new Error("Cloud coding catalog exceeds the size limit.");
21
+ }
22
+ chunks.push(Buffer.from(value));
23
+ }
24
+ return validateCodingCatalog(JSON.parse(Buffer.concat(chunks).toString("utf8")), Number(version));
25
+ }
26
+
27
+ export function validateCodingCatalog(catalog, version = catalog?.version) {
28
+ if (!Number.isSafeInteger(version) || version < 1 || version > 999_999) throw new Error("Invalid Cloud catalog version.");
29
+ const slug = /^[a-z0-9][a-z0-9-]{0,31}$/;
30
+ const plain = object => object !== null && typeof object === "object" && !Array.isArray(object);
31
+ const validText = (value, max) => typeof value === "string" && value.trim() && value.length <= max &&
32
+ !/[\u0000-\u001f\u007f]/.test(value);
33
+ if (catalog?.version !== version || !plain(catalog.technologies) || !plain(catalog.presets)) throw new Error("Invalid Cloud catalog.");
34
+ const items = Object.entries(catalog.technologies);
35
+ const bundles = Object.entries(catalog.presets);
36
+ if (!items.length || items.length > 150 || bundles.length > 100 ||
37
+ items.some(([id, pack]) => !slug.test(id) || !Array.isArray(pack) || pack.length !== 4 ||
38
+ !Object.hasOwn(areas, pack[0]) || !validText(pack[1], 80) || !validText(pack[2], 120) || !validText(pack[3], 2000)) ||
39
+ bundles.some(([id, ids]) => !slug.test(id) || !Array.isArray(ids) || !ids.length || ids.length > 30 ||
40
+ ids.some(item => typeof item !== "string" || !Object.hasOwn(catalog.technologies, item)))) {
41
+ throw new Error("Invalid Cloud catalog.");
42
+ }
43
+ return { version: catalog.version, technologies: catalog.technologies, presets: catalog.presets };
44
+ }
@@ -0,0 +1,110 @@
1
+ import { lstat, readdir, readFile } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+
5
+ const ignored = new Set(["node_modules", "dist", "build", "vendor", "coverage", "__pycache__", "target", "venv"]);
6
+ const signals = {
7
+ react: ["react"], nextjs: ["next"], typescript: ["typescript"], express: ["express"],
8
+ mongodb: ["mongodb", "mongoose"], postgresql: ["pg", "psycopg", "psycopg2", "asyncpg"],
9
+ fastapi: ["fastapi"], playwright: ["playwright", "@playwright/test", "playwright-core"],
10
+ cucumber: ["@cucumber/cucumber", "cucumber", "behave", "pytest-bdd"],
11
+ mysql: ["mysql", "mysql2", "mysqlclient", "pymysql"], redis: ["redis", "ioredis"],
12
+ "react-native": ["react-native"], dbt: ["dbt-core"], spark: ["pyspark"],
13
+ vue: ["vue"], angular: ["@angular/core"], svelte: ["svelte"], django: ["django"],
14
+ };
15
+
16
+ export async function detectStack(root) {
17
+ const projects = new Map();
18
+ let visited = 0;
19
+ let truncated = false;
20
+ async function scan(folder, scope, depth) {
21
+ if (visited >= 400) { truncated = true; return; }
22
+ visited++;
23
+ if (!(await lstat(folder)).isDirectory()) return;
24
+ const entries = await readdir(folder, { withFileTypes: true });
25
+ entries.sort((a, b) => a.name.localeCompare(b.name, "en"));
26
+ const files = new Set(entries.filter(item => item.isFile()).map(item => item.name));
27
+ const add = (technology, file) => {
28
+ const evidence = scope === "." ? file : scope + "/" + file;
29
+ if (!projects.has(scope)) projects.set(scope, new Map());
30
+ const hits = projects.get(scope);
31
+ if (!hits.has(technology)) hits.set(technology, new Set());
32
+ hits.get(technology).add(evidence);
33
+ };
34
+ async function text(name) {
35
+ const path = join(folder, name);
36
+ const stat = await lstat(path);
37
+ if (!stat.isFile() || stat.size > 256_000) return "";
38
+ return (await readFile(path, "utf8")).replace(/^\uFEFF/, "");
39
+ }
40
+ for (const name of files) {
41
+ if (name === "package.json") {
42
+ let pkg;
43
+ try { pkg = JSON.parse(await text(name)); }
44
+ catch (error) { if (error instanceof SyntaxError) continue; throw error; }
45
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) continue;
46
+ const deps = [pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies];
47
+ if (!pkg.workspaces || pkg.engines?.node) add("node", name);
48
+ for (const [id, names] of Object.entries(signals)) {
49
+ if (names.some(dep => deps.some(section => section && Object.hasOwn(section, dep)))) add(id, name);
50
+ }
51
+ } else if (name === "pyproject.toml" || /^requirements(?:[-.][\w-]+)?\.txt$/.test(name)) {
52
+ add("python", name);
53
+ const content = await text(name);
54
+ for (const [id, names] of Object.entries(signals)) {
55
+ if (names.some(dep => /^[a-z][a-z0-9-]*$/.test(dep) && new RegExp("[\\s'\"]" + dep + "(?=[\\s'\"[=<>!,;~]|$)", "i").test(" " + content))) add(id, name);
56
+ }
57
+ } else if (/^playwright\.config\.[cm]?[jt]s$/.test(name)) add("playwright", name);
58
+ else if (/^cucumber\.(?:[cm]?js|json|ya?ml)$/.test(name)) add("cucumber", name);
59
+ else if (/^(?:Dockerfile(?:\..+)?|(?:docker-)?compose\.ya?ml)$/.test(name)) add("docker", name);
60
+ else if (name === ".gitlab-ci.yml") add("gitlab-ci", name);
61
+ else if (name === "go.mod") add("go", name);
62
+ else if (name === "Cargo.toml") add("rust", name);
63
+ else if (name === "pom.xml" || /^build\.gradle(?:\.kts)?$/.test(name)) {
64
+ const content = await text(name);
65
+ if (/org\.springframework\.boot/.test(content)) add("spring-boot", name);
66
+ if (/com\.android\.(?:application|library)/.test(content)) add("android", name);
67
+ }
68
+ else if (name === "pubspec.yaml" && /^\s*flutter:/m.test(await text(name))) add("flutter", name);
69
+ else if (name === "dbt_project.yml") add("dbt", name);
70
+ else if (name.endsWith(".tf")) add("terraform", name);
71
+ else if (/^kustomization\.ya?ml$/.test(name)) add("kubernetes", name);
72
+ else if (name.endsWith(".csproj")) add("dotnet", name);
73
+ }
74
+ if (entries.some(item => item.name === ".github" && item.isDirectory())) {
75
+ const workflows = join(folder, ".github", "workflows");
76
+ const stat = await lstat(workflows).catch(error => { if (error.code !== "ENOENT") throw error; });
77
+ if (stat?.isDirectory()) {
78
+ const workflow = (await readdir(workflows, { withFileTypes: true })).find(item => item.isFile() && /\.ya?ml$/.test(item.name));
79
+ if (workflow) add("github-actions", ".github/workflows/" + workflow.name);
80
+ }
81
+ }
82
+ const xcode = entries.find(item => item.isDirectory() && item.name.endsWith(".xcodeproj"));
83
+ if (xcode) add("ios", xcode.name);
84
+ // Gherkin is a hint by itself. A project dependency or config identifies Cucumber.
85
+ const feature = [...files].find(name => name.endsWith(".feature"));
86
+ if (feature) add("gherkin", feature);
87
+ for (const child of entries) {
88
+ if (!child.isDirectory() || child.name.startsWith(".") || ignored.has(child.name)) continue;
89
+ if (depth >= 4 || visited >= 400) { truncated = true; continue; }
90
+ await scan(join(folder, child.name), scope === "." ? child.name : scope + "/" + child.name, depth + 1);
91
+ }
92
+ }
93
+ await scan(root, ".", 0);
94
+ return {
95
+ truncated,
96
+ projects: [...projects].map(([scope, hits]) => ({
97
+ scope, technologies: [...hits].map(([id, evidence]) => ({ id, evidence: [...evidence] })),
98
+ })),
99
+ };
100
+ }
101
+
102
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
103
+ const root = resolve(process.argv[2] ?? fileURLToPath(new URL("../../", import.meta.url)));
104
+ try {
105
+ console.log(JSON.stringify(await detectStack(root), null, 2));
106
+ } catch (error) {
107
+ console.error(error.message);
108
+ process.exitCode = 1;
109
+ }
110
+ }
@@ -0,0 +1,130 @@
1
+ import { lstat, readFile, readdir } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { readLocalAgent } from "../studio/project.js";
6
+ import { prepareProjectFiles } from "./setup.js";
7
+
8
+ const formats = {
9
+ claude: { marker: ".claude", skills: ".claude/skills", agents: ".claude/agents", extension: ".md" },
10
+ codex: { marker: ".codex", skills: ".agents/skills", agents: ".codex/agents", extension: ".toml" },
11
+ copilot: { marker: ".github", skills: ".github/skills", agents: ".github/agents", extension: ".agent.md" },
12
+ };
13
+ const safeName = /^[a-z0-9][a-z0-9-]{0,95}$/;
14
+ const missing = error => {
15
+ if (error.code !== "ENOENT") throw error;
16
+ return null;
17
+ };
18
+
19
+ async function entries(path) {
20
+ const stat = await lstat(path).catch(missing);
21
+ if (!stat) return [];
22
+ if (!stat.isDirectory()) throw new Error("Expected a regular project directory: " + path);
23
+ return readdir(path, { withFileTypes: true });
24
+ }
25
+
26
+ async function text(path) {
27
+ const stat = await lstat(path).catch(missing);
28
+ if (!stat?.isFile() || stat.size > 64_000) return "";
29
+ return (await readFile(path, "utf8")).replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
30
+ }
31
+
32
+ function scalar(header, key) {
33
+ const value = new RegExp("^" + key + ":[ \t]*(.+)$", "m").exec(header)?.[1]?.trim();
34
+ if (!value) return "";
35
+ if (!value.startsWith('"')) return value.replace(/^'|'$/g, "");
36
+ try {
37
+ const parsed = JSON.parse(value);
38
+ return typeof parsed === "string" ? parsed : "";
39
+ } catch { return ""; }
40
+ }
41
+
42
+ async function sources(root, output) {
43
+ await entries(join(root, ".lyra"));
44
+ const agents = new Map();
45
+ const skills = new Map();
46
+ const agentDir = join(root, ".lyra", "agents");
47
+ for (const entry of await entries(agentDir)) {
48
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
49
+ const source = await text(join(agentDir, entry.name));
50
+ const item = readLocalAgent(source);
51
+ if (!item || item.source !== "local" || !safeName.test(item.id.slice(6))) {
52
+ output.write("Skip unsupported agent " + JSON.stringify(entry.name) + "\n");
53
+ continue;
54
+ }
55
+ const id = item.id.slice(6);
56
+ if (agents.has(id)) throw new Error("Duplicate Lyra agent ID: " + id);
57
+ agents.set(id, item);
58
+ }
59
+ const skillDir = join(root, ".lyra", "skills");
60
+ for (const entry of await entries(skillDir)) {
61
+ if (!entry.isDirectory() || !safeName.test(entry.name)) continue;
62
+ const source = await text(join(skillDir, entry.name, "SKILL.md"));
63
+ const front = /^---\n([\s\S]*?)\n---\n/.exec(source);
64
+ const name = front && scalar(front[1], "name");
65
+ const description = front && scalar(front[1], "description");
66
+ if (!name || name !== entry.name || !description) {
67
+ output.write("Skip skill without matching name and description " + JSON.stringify(entry.name) + "\n");
68
+ continue;
69
+ }
70
+ skills.set(name, ["---", "name: " + name, "description: " + JSON.stringify(description), "---", source.slice(front[0].length)].join("\n"));
71
+ }
72
+ return { agents, skills };
73
+ }
74
+
75
+ function renderAgent(target, id, agent) {
76
+ const description = "AgentLyra project profile for " + agent.name + ".";
77
+ if (target === "codex") {
78
+ const quoted = value => JSON.stringify(value).replace(/\u007f/g, "\\u007F");
79
+ return "name = " + quoted(id) + "\ndescription = " + quoted(description) +
80
+ "\ndeveloper_instructions = " + quoted(agent.prompt) + "\n";
81
+ }
82
+ return ["---", "name: " + id, "description: " + JSON.stringify(description), "---", "", agent.prompt, ""].join("\n");
83
+ }
84
+
85
+ export async function runCodingExport(args, { input = process.stdin, output = process.stdout, root = process.cwd() } = {}) {
86
+ const { values } = parseArgs({ args, options: {
87
+ to: { type: "string" }, dir: { type: "string" }, preview: { type: "boolean" },
88
+ yes: { type: "boolean", short: "y" }, help: { type: "boolean", short: "h" },
89
+ } });
90
+ if (values.help) {
91
+ output.write("Usage: agent-lyra setup coding export [--to claude,codex,copilot] [--preview | --yes] [--dir <folder>]\n");
92
+ return;
93
+ }
94
+ if (!input.isTTY && (!values.to || (!values.preview && !values.yes))) {
95
+ throw new Error("Provide --to with --preview or --yes when running without an interactive terminal.");
96
+ }
97
+ const project = resolve(root, values.dir ?? ".");
98
+ const rl = input.isTTY ? createInterface({ input, output }) : null;
99
+ try {
100
+ let choice = values.to;
101
+ if (!choice) {
102
+ const existing = new Set((await entries(project)).filter(item => item.isDirectory() || item.isFile()).map(item => item.name));
103
+ const hints = Object.entries(formats).filter(([id, { marker }]) => existing.has(marker) ||
104
+ (id === "codex" && existing.has(".agents")) || (id === "claude" && existing.has("CLAUDE.md")));
105
+ if (hints.length) output.write("Project files suggest: " + hints.map(([id]) => id).join(", ") + "\n");
106
+ choice = (await rl.question("Export to claude, codex, or copilot (comma separated, Enter to cancel): ")).trim();
107
+ if (!choice) return;
108
+ }
109
+ const targets = [...new Set(choice.split(",").map(name => name.trim().toLowerCase()))];
110
+ if (targets.some(target => !Object.hasOwn(formats, target))) throw new Error("Choose claude, codex, or copilot.");
111
+ const { agents, skills } = await sources(project, output);
112
+ const files = new Map();
113
+ for (const target of targets) {
114
+ const format = formats[target];
115
+ for (const [id, agent] of agents) files.set(format.agents + "/" + id + format.extension, renderAgent(target, id, agent));
116
+ for (const [name, skill] of skills) files.set(format.skills + "/" + name + "/SKILL.md", skill);
117
+ }
118
+ if (!files.size) {
119
+ output.write("No exportable Markdown agents or skills found in .lyra. Run setup coding first.\n");
120
+ return;
121
+ }
122
+ output.write("Export includes instructions only. Tool permissions, hooks, scripts, and other skill resources stay in their original project files.\n");
123
+ const apply = await prepareProjectFiles(project, files, output);
124
+ if (values.preview || (!values.yes && !/^y(?:es)?$/i.test((await rl.question("Write these exports? [y/N] ")).trim()))) return;
125
+ await apply();
126
+ output.write("Assistant export complete. Existing files were preserved.\n");
127
+ } finally {
128
+ rl?.close();
129
+ }
130
+ }
@@ -0,0 +1,174 @@
1
+ import { createHash } from "node:crypto";
2
+ import { detectStack } from "./detect-stack.mjs";
3
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { parseArgs } from "node:util";
7
+ import { areas } from "./catalog.js";
8
+ import { bundledCatalog, fetchCodingCatalog } from "./cloud-catalog.js";
9
+ const areaLabels = { frontend: "Frontend", backend: "Backend and APIs", database: "Databases", devops: "DevOps", qa: "QA and test automation", mobile: "Mobile", data: "Data engineering" };
10
+
11
+ function showChoices(output, { presets, technologies }) {
12
+ output.write("Presets: " + Object.keys(presets).join(", ") + "\n");
13
+ for (const [area, label] of Object.entries(areaLabels)) {
14
+ output.write(label + ": " + Object.entries(technologies).filter(([, pack]) => pack[0] === area)
15
+ .map(([id, [, name]]) => name + " (" + id + ")").join(", ") + "\n");
16
+ }
17
+ }
18
+
19
+ export async function selectCodingStack(rl, output, catalog = bundledCatalog) {
20
+ showChoices(output, catalog);
21
+ return (await rl.question("Choose presets or technologies (comma separated, Enter to skip): ")).trim();
22
+ }
23
+
24
+ function plan(selection, scope, { version, technologies, presets }) {
25
+ const chosen = selection.toLowerCase().split(",").map(part => part.trim()).filter(Boolean);
26
+ if (!chosen.length) throw new Error("Choose at least one preset or technology.");
27
+ const ids = [...new Set(chosen.flatMap(id => {
28
+ if (Object.hasOwn(presets, id)) return presets[id];
29
+ if (Object.hasOwn(technologies, id)) return [id];
30
+ throw new Error("Unknown technology or preset: " + id);
31
+ }))].sort();
32
+ const files = new Map();
33
+ for (const id of ids) {
34
+ const [, name, title, instructions] = technologies[id];
35
+ files.set("skills/lyra-" + id + "/SKILL.md", [
36
+ "---", "name: lyra-" + id, "description: " + JSON.stringify(title + " for " + name + " projects."),
37
+ "---", "", "# " + title, "", "## When to use this skill", "",
38
+ "Use when implementing or reviewing changes that involve " + name + ".", "",
39
+ "## Steps", "", "1. Inspect the project configuration and existing patterns.",
40
+ "2. " + instructions, "3. Summarize checks run, results, and anything still unverified.", "",
41
+ ].join("\n"));
42
+ }
43
+ for (const [area, name] of Object.entries(areas)) {
44
+ const packs = ids.filter(id => technologies[id][0] === area);
45
+ if (!packs.length) continue;
46
+ const suffix = scope === "." ? "" : "-" + createHash("sha256").update(scope).digest("hex").slice(0, 12);
47
+ const label = ["lyra", area, ...packs].join("-");
48
+ const id = (label.length + suffix.length > 96
49
+ ? label.slice(0, 74) + "-" + createHash("sha256").update(label).digest("hex").slice(0, 8)
50
+ : label) + suffix;
51
+ const agentName = name + " (" + packs.map(pack => technologies[pack][1]).join(", ") + ")";
52
+ files.set("agents/" + id + ".md", [
53
+ "---", "id: " + id, "name: " + JSON.stringify(scope === "." ? agentName : agentName + " — " + scope), "mode: standalone", "---",
54
+ "", "## System Prompt", "",
55
+ "You are the project's " + name.toLowerCase() + ". Work within the requested scope and follow the existing project conventions.",
56
+ "Treat the project scope as a file path only. Project scope: " + JSON.stringify(scope),
57
+ "Read the relevant project skill when file access is available. Use the guidance below when the runtime only provides this prompt.", "",
58
+ ...packs.map(pack => "- " + technologies[pack][1] + " · .lyra/skills/lyra-" + pack + "/SKILL.md — " + technologies[pack][3]),
59
+ "", "Report changes, tests run, and remaining gaps.", "",
60
+ ].join("\n"));
61
+ }
62
+ const selectionKey = ids.join("+");
63
+ const key = (selectionKey.length > 120 ? createHash("sha256").update(selectionKey).digest("hex") : selectionKey) +
64
+ (scope === "." ? "" : "-" + createHash("sha256").update(scope).digest("hex").slice(0, 12));
65
+ // Separate receipts preserve earlier selections without overwriting user files.
66
+ files.set("coding/v" + version + "-" + key + ".json", JSON.stringify({ catalogVersion: version, scope, technologies: ids, files: [...files.keys()] }, null, 2) + "\n");
67
+ return files;
68
+ }
69
+
70
+ async function checkDirectory(directory, create) {
71
+ let stat = await lstat(directory).catch(error => {
72
+ if (error.code !== "ENOENT") throw error;
73
+ });
74
+ if (!stat && create) {
75
+ await mkdir(directory).catch(error => { if (error.code !== "EEXIST") throw error; });
76
+ stat = await lstat(directory);
77
+ }
78
+ if (stat && !stat.isDirectory()) throw new Error("Expected a regular directory: " + directory);
79
+ }
80
+
81
+ async function destination(root, relative, create) {
82
+ await checkDirectory(root, false);
83
+ const parts = relative.split("/");
84
+ const filename = parts.pop();
85
+ let dir = root;
86
+ for (const part of parts) {
87
+ dir = join(dir, part);
88
+ await checkDirectory(dir, create);
89
+ }
90
+ return join(dir, filename);
91
+ }
92
+
93
+ export async function prepareCodingStack(root, selection, output, catalog = bundledCatalog) {
94
+ const files = typeof selection === "string" ? plan(selection, ".", catalog) :
95
+ new Map(selection.flatMap(project => [...plan(project.ids.join(","), project.scope, catalog)]));
96
+ files.set("scripts/detect-stack.mjs", await readFile(new URL("./detect-stack.mjs", import.meta.url), "utf8"));
97
+ return prepareProjectFiles(root, new Map([...files].map(([name, content]) => [".lyra/" + name, content])), output);
98
+ }
99
+
100
+ export async function prepareProjectFiles(root, files, output) {
101
+ for (const [relative, content] of files) {
102
+ const path = await destination(root, relative, false);
103
+ const stat = await lstat(path).catch(error => {
104
+ if (error.code !== "ENOENT") throw error;
105
+ });
106
+ const unchanged = stat?.isFile() && (await readFile(path, "utf8")).replace(/\r\n/g, "\n") === content;
107
+ output.write((!stat ? "Create" : unchanged ? "Already installed" : "Keep existing") + " " + relative + "\n");
108
+ }
109
+ return async () => {
110
+ for (const [relative, content] of files) {
111
+ const path = await destination(root, relative, true);
112
+ await writeFile(path, content, { flag: "wx" }).catch(error => {
113
+ if (error.code !== "EEXIST" && error.code !== "EISDIR") throw error;
114
+ });
115
+ }
116
+ };
117
+ }
118
+
119
+ export async function recommendCodingStacks(root, output, { technologies } = bundledCatalog) {
120
+ const detected = await detectStack(root);
121
+ if (detected.truncated) output.write("Scan limit reached. Some folders were skipped.\n");
122
+ const selected = [];
123
+ for (const { scope, technologies: hits } of detected.projects) {
124
+ const supported = hits.filter(({ id }) => Object.hasOwn(technologies, id));
125
+ output.write("Project " + JSON.stringify(scope) + "\n");
126
+ for (const { id, evidence } of hits) {
127
+ output.write(" " + id + (Object.hasOwn(technologies, id) ? "" : " (no pack)") +
128
+ " · " + evidence.map(file => JSON.stringify(file)).join(", ") + "\n");
129
+ }
130
+ if (supported.length) selected.push({ scope, ids: supported.map(hit => hit.id) });
131
+ }
132
+ if (!selected.length) output.write("No supported stack detected. Choose your technologies manually.\n");
133
+ return selected;
134
+ }
135
+
136
+ export async function runCodingSetup(args, { input = process.stdin, output = process.stdout, root = process.cwd() } = {}) {
137
+ const { values } = parseArgs({ args, options: {
138
+ "catalog-version": { type: "string" }, detect: { type: "boolean" }, stack: { type: "string" }, dir: { type: "string" }, preview: { type: "boolean" },
139
+ yes: { type: "boolean", short: "y" }, help: { type: "boolean", short: "h" },
140
+ } });
141
+ if (values.help) {
142
+ output.write("Usage: agent-lyra setup coding [--stack <names> | --detect] [--catalog-version <number>] [--preview | --yes] [--dir <folder>]\n");
143
+ return;
144
+ }
145
+ if (values.detect && values.stack) throw new Error("Choose --detect or --stack.");
146
+ if (!input.isTTY && ((!values.stack && !values.detect) || (!values.preview && !values.yes))) {
147
+ throw new Error("Provide --stack or --detect with --preview or --yes when running without an interactive terminal.");
148
+ }
149
+ const rl = input.isTTY ? createInterface({ input, output }) : null;
150
+ try {
151
+ const target = resolve(root, values.dir ?? ".");
152
+ const catalog = values["catalog-version"] ? await fetchCodingCatalog(values["catalog-version"]) : bundledCatalog;
153
+ output.write("Coding catalog " + catalog.version + (values["catalog-version"] ? " (Cloud)" : " (bundled)") + "\n");
154
+ const useDetection = values.detect || (!values.stack && /^y(?:es)?$/i.test((await rl.question("Detect technologies from this project? [y/N] ")).trim()));
155
+ let selected = values.stack;
156
+ if (useDetection) {
157
+ selected = await recommendCodingStacks(target, output, catalog);
158
+ if (!selected.length) {
159
+ selected = undefined;
160
+ } else if (rl && !values.yes && !values.preview) {
161
+ const answer = (await rl.question("Use these recommendations? [Y/n] ")).trim();
162
+ if (/^n(?:o)?$/i.test(answer)) selected = undefined;
163
+ }
164
+ }
165
+ if (selected === undefined && rl && !values.preview) selected = await selectCodingStack(rl, output, catalog);
166
+ if (!selected) return;
167
+ const apply = await prepareCodingStack(target, selected, output, catalog);
168
+ if (values.preview || (!values.yes && !/^y(?:es)?$/i.test((await rl.question("Create these files? [y/N] ")).trim()))) return;
169
+ await apply();
170
+ output.write("Coding setup complete. Edit your agent and skill guidance in .lyra.\n");
171
+ } finally {
172
+ rl?.close();
173
+ }
174
+ }
package/src/init.js CHANGED
@@ -6,6 +6,8 @@ import { emitKeypressEvents } from "node:readline";
6
6
  import { stdin as input, stdout as output } from "node:process";
7
7
  import { GATED_DOMAINS, STANDALONE_DOMAINS, getDomainCatalog } from "./catalog.js";
8
8
 
9
+ import { prepareCodingStack, recommendCodingStacks, selectCodingStack } from "./coding/setup.js";
10
+
9
11
  const DEFAULT_API_BASE_URL = "https://www.agentlyra.in";
10
12
 
11
13
  function parseArgs(argv = process.argv.slice(2)) {
@@ -40,7 +42,7 @@ function parseArgs(argv = process.argv.slice(2)) {
40
42
  }
41
43
 
42
44
  function printUsage() {
43
- output.write(`Usage:\n agent-lyra init\n lyra init\n\nOptions:\n --mode standalone|gated\n --domains coding,finance\n --api-key <key>\n --api-base-url <url>\n --dir <target-directory>\n --force\n`);
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`);
44
46
  }
45
47
 
46
48
  function printWelcomeBanner() {
@@ -800,9 +802,10 @@ export async function runInitWizard(options = {}) {
800
802
 
801
803
  try {
802
804
  printWelcomeBanner();
803
- const wantsLogin = await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
805
+ const stackMode = (options.stack || options.detect) && ["standalone", "gated"].includes(options.mode);
806
+ const wantsLogin = !stackMode && await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
804
807
  const apiBaseUrl = options["api-base-url"] || process.env.LYRA_API_BASE_URL || DEFAULT_API_BASE_URL;
805
- let apiKey = options["api-key"] || process.env.LYRA_API_KEY || "";
808
+ let apiKey = stackMode && options.mode === "standalone" ? "" : options["api-key"] || process.env.LYRA_API_KEY || "";
806
809
  let importedAgents = [];
807
810
 
808
811
  if (wantsLogin && !apiKey) {
@@ -820,7 +823,7 @@ export async function runInitWizard(options = {}) {
820
823
  }
821
824
  }
822
825
 
823
- const chosenGroup = await chooseFlowGroup(rl);
826
+ const chosenGroup = stackMode ? undefined : await chooseFlowGroup(rl);
824
827
  let mode = options.mode;
825
828
  if (mode !== "standalone" && mode !== "gated") {
826
829
  mode = chosenGroup === "everyday" ? "gated" : await chooseMode(rl, mode);
@@ -847,6 +850,7 @@ export async function runInitWizard(options = {}) {
847
850
  options: catalogWithHints,
848
851
  });
849
852
 
853
+ if (stackMode && !presetDomains.length) throw new Error("Use --domains with a valid Coding or Engineering domain ID.");
850
854
  const selected = presetDomains.length > 0
851
855
  ? presetDomains
852
856
  : await selectManyGrouped(
@@ -908,8 +912,32 @@ export async function runInitWizard(options = {}) {
908
912
 
909
913
  const targetDir = path.resolve(options.dir || process.cwd());
910
914
  const lyraDir = path.join(targetDir, ".lyra");
915
+ const coding = selectedDomains.some(domain => domain.id === "coding" || domain.id === "engineering-bootstrap");
916
+ if (options.stack !== undefined && (!coding || typeof options.stack !== "string")) {
917
+ throw new Error("Use --stack with a stack name and the Coding domain.");
918
+ }
919
+ if (options.detect && (!coding || options.stack)) throw new Error("Use --detect with the Coding domain instead of --stack.");
920
+ let stack = options.stack;
921
+ if (coding && !stack) {
922
+ const detect = options.detect || (input.isTTY && await askYesNo(rl, "Detect technologies from this project?", false));
923
+ if (detect) {
924
+ const recommendations = await recommendCodingStacks(targetDir, output);
925
+ if (recommendations.length && (options.detect || await askYesNo(rl, "Use these recommendations?", true))) stack = recommendations;
926
+ }
927
+ if (!stack && input.isTTY) stack = await selectCodingStack(rl, output);
928
+ }
929
+ let applyCoding;
930
+ if (coding) {
931
+ const existing = await fs.lstat(lyraDir).catch(error => {
932
+ if (error.code !== "ENOENT") throw error;
933
+ });
934
+ if (existing) throw new Error("This project already has .lyra. Run agent-lyra setup coding to add packs while keeping your files.");
935
+ const apply = await prepareCodingStack(targetDir, stack || [], output);
936
+ if (!stack || options.stack || options.detect || /^y(?:es)?$/i.test(await askQuestion(rl, "Create these coding files? [y/N] "))) applyCoding = apply;
937
+ }
911
938
  await ensureEmptyOrApproved(rl, lyraDir, Boolean(options.force));
912
939
  await writeScaffold({ targetDir, mode, selectedDomains, apiKey });
940
+ if (applyCoding) await applyCoding();
913
941
 
914
942
  output.write(`Created ${lyraDir} for ${mode} mode with ${selectedDomains.length} domain(s).\n`);
915
943
  } finally {
package/src/memory/cli.js CHANGED
@@ -1,37 +1,9 @@
1
1
  import { syncMemory } from "./sync.js";
2
- import { readFile } from "node:fs/promises";
3
- import { openMemoryStore } from "./index.js";
4
-
2
+ import { runLocalMemory } from "./local-cli.js";
5
3
  export async function runMemory(args, output = process.stdout) {
6
- const [action, value, flag] = args;
7
- if (action === "cloud") return runCloudMemory(args.slice(1), output);
8
- if (!action || action === "--help") {
9
- output.write("Usage: agent-lyra memory init | record <json-file> | list | search <query> | inspect <id> | verify <id> <evidence.json> | archive <id> | consolidate <context> | stats | forget <id> --yes | cloud --help\n");
10
- return;
11
- }
12
- const bare = ["init", "list", "stats"].includes(action) && args.length === 1;
13
- const withValue = ["record", "search", "inspect", "archive", "consolidate"].includes(action) && args.length === 2 && value;
14
- if (!bare && !withValue && !(action === "verify" && args.length === 3 && value && flag) && !(action === "forget" && args.length === 3 && flag === "--yes" && value)) {
15
- throw new Error("See agent-lyra memory --help. Forget requires --yes.");
16
- }
17
- const store = await openMemoryStore();
18
- try {
19
- let result;
20
- switch (action) {
21
- case "init": result = { database: store.file, ...store.stats() }; break;
22
- case "record": result = store.record(JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
23
- case "list": result = store.list(); break;
24
- case "search": result = store.search(value); break;
25
- case "inspect": result = store.get(value); break;
26
- case "verify": result = store.verify(value, JSON.parse((await readFile(flag, "utf8")).replace(/^\uFEFF/, ""))); break;
27
- case "consolidate": result = store.consolidate(value); break;
28
- case "archive": result = store.archive(value); break;
29
- case "stats": result = store.stats(); break;
30
- case "forget": result = store.forget(value) ? { deleted: value } : null; break;
31
- }
32
- if (result === null) throw new Error("Memory record was not found.");
33
- output.write(JSON.stringify(result, null, 2) + "\n");
34
- } finally { store.close(); }
4
+ if (args[0] === "cloud") return runCloudMemory(args.slice(1), output);
5
+ if (!args[0] || args[0] === "--help") { await runLocalMemory(args, output); output.write("Cloud: agent-lyra memory cloud --help\n"); return; }
6
+ return runLocalMemory(args, output);
35
7
  }
36
8
 
37
9
  async function runCloudMemory(args, output) {
@@ -0,0 +1,34 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { openMemoryStore } from "./index.js";
3
+
4
+ export async function runLocalMemory(args, output = process.stdout) {
5
+ const [action, value, flag] = args;
6
+ if (action === "cloud") throw new Error("Cloud memory is not available in the standalone CLI.");
7
+ if (!action || action === "--help") {
8
+ output.write("Usage: agent-lyra memory init | record <json-file> | list | search <query> | inspect <id> | verify <id> <evidence.json> | archive <id> | consolidate <context> | stats | forget <id> --yes\n");
9
+ return;
10
+ }
11
+ const bare = ["init", "list", "stats"].includes(action) && args.length === 1;
12
+ const withValue = ["record", "search", "inspect", "archive", "consolidate"].includes(action) && args.length === 2 && value;
13
+ if (!bare && !withValue && !(action === "verify" && args.length === 3 && value && flag) && !(action === "forget" && args.length === 3 && flag === "--yes" && value)) {
14
+ throw new Error("See agent-lyra memory --help. Forget requires --yes.");
15
+ }
16
+ const store = await openMemoryStore();
17
+ try {
18
+ let result;
19
+ switch (action) {
20
+ case "init": result = { database: store.file, ...store.stats() }; break;
21
+ case "record": result = store.record(JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
22
+ case "list": result = store.list(); break;
23
+ case "search": result = store.search(value); break;
24
+ case "inspect": result = store.get(value); break;
25
+ case "verify": result = store.verify(value, JSON.parse((await readFile(flag, "utf8")).replace(/^\uFEFF/, ""))); break;
26
+ case "consolidate": result = store.consolidate(value); break;
27
+ case "archive": result = store.archive(value); break;
28
+ case "stats": result = store.stats(); break;
29
+ case "forget": result = store.forget(value) ? { deleted: value } : null; break;
30
+ }
31
+ if (result === null) throw new Error("Memory record was not found.");
32
+ output.write(JSON.stringify(result, null, 2) + "\n");
33
+ } finally { store.close(); }
34
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readMode, requireCloudMode } from "../studio/session.js";
2
+ import { readMode, readSdkKey, requireCloudMode } from "../studio/session.js";
3
3
  import { openMemoryStore } from "./index.js";
4
4
  import { eligibleText } from "./validation.js";
5
5
 
@@ -15,7 +15,10 @@ export async function syncMemory(root, action, id, {
15
15
  if (action === "push" && !confirmed) throw new Error("Review memory cloud preview first, then pass --yes to push.");
16
16
  if (action !== "preview") {
17
17
  requireCloudMode(await readMode(root));
18
- if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) throw new Error("Set LYRA_MEMORY_KEY to a dedicated Memory sync key.");
18
+ key ??= await readSdkKey(root);
19
+ if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) {
20
+ throw new Error("Run connect-cloud with an AgentLyra API key that has Memory sync permission.");
21
+ }
19
22
  }
20
23
  const send = async (url, method = "GET", data) => {
21
24
  const response = await fetchRequest(url, {
@@ -23,6 +26,7 @@ export async function syncMemory(root, action, id, {
23
26
  body: data ? JSON.stringify(data) : undefined, redirect: "error", signal: AbortSignal.timeout(15_000),
24
27
  });
25
28
  const result = await response.json();
29
+ if (response.status === 401) throw new Error("Cloud rejected this key. Check its Memory sync permission or run connect-cloud --replace-key.");
26
30
  if (!response.ok) throw new Error(result.error || "Cloud memory request failed.");
27
31
  return result;
28
32
  };
@@ -215,7 +215,7 @@ function renderCatalog() {
215
215
  if (id === "workflows") card.append(row.runnable
216
216
  ? button("Run now", () => openRun(["workflow:" + row.id]))
217
217
  : element("span", "Cloud workflow requires the console"));
218
- const syncType = id === "skills" ? "skill" : id === "teams" ? "team" : id === "workflows" && row.runnable ? "workflow" : undefined;
218
+ const syncType = id === "skills" && row.source !== "markdown" ? "skill" : id === "teams" ? "team" : id === "workflows" && row.runnable ? "workflow" : undefined;
219
219
  if (syncType && row.source !== "cloud" && project.mode !== "standalone") {
220
220
  for (const [action, label] of [["push", "Push to Cloud"], ["pull", "Pull " + syncType + " edits"]]) {
221
221
  const control = button(label, async () => {
@@ -232,7 +232,7 @@ function renderCatalog() {
232
232
  card.append(control);
233
233
  }
234
234
  }
235
- if (id === "skills") card.append(element("span", row.source === "cloud" ? "Cloud skill" : "Local text skill"));
235
+ if (id === "skills") card.append(element("span", row.source === "cloud" ? "Cloud skill" : row.source === "markdown" ? "Local Markdown skill" : "Local text skill"));
236
236
  if (id === "teams") card.append(element("span", row.source === "cloud" ? "Cloud team" : "Local team"));
237
237
  section.append(card);
238
238
  }
@@ -77,7 +77,26 @@ export async function readCatalog(root) {
77
77
  const id = "python:" + item.id;
78
78
  if (!agents.has(id)) agents.set(id, { id, name: item.name, source: "python", ...descriptor });
79
79
  }
80
- return { agents, workflows: await records("workflows"), teams: await records("teams"), skills: await records("skills") };
80
+ const skills = await records("skills");
81
+ const skillRoot = join(root, ".lyra", "skills");
82
+ const folders = await readdir(skillRoot, { withFileTypes: true }).catch(error => {
83
+ if (error.code === "ENOENT") return [];
84
+ throw error;
85
+ });
86
+ for (const folder of folders) {
87
+ if (!folder.isDirectory() || !safeId.test(folder.name)) continue;
88
+ const metadata = join(skillRoot, folder.name, "SKILL.md");
89
+ const stat = await lstat(metadata).catch(error => {
90
+ if (error.code === "ENOENT") return null;
91
+ throw error;
92
+ });
93
+ if (!stat?.isFile() || stat.size > 64_000) continue;
94
+ const source = await readFile(metadata, "utf8");
95
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/.exec(source);
96
+ const name = front && markdownValue(front[1], "name");
97
+ if (name) skills.push({ id: "markdown:" + folder.name, name, source: "markdown" });
98
+ }
99
+ return { agents, workflows: await records("workflows"), teams: await records("teams"), skills };
81
100
  }
82
101
 
83
102
  export function validateLayout(layout) {
@@ -48,13 +48,13 @@ export async function readSdkKey(root, { home = account() } = {}) {
48
48
 
49
49
  async function promptKey() {
50
50
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
51
- throw new Error("Run this command in your IDE terminal to enter an SDK key, or supply LYRA_API_KEY in the environment.");
51
+ throw new Error("Run this command in your IDE terminal to enter an AgentLyra API key, or supply LYRA_API_KEY in the environment.");
52
52
  }
53
53
  const silent = new Writable({ write(_chunk, _encoding, done) { done(); } });
54
54
  const prompt = createInterface({ input: process.stdin, output: silent, terminal: true, historySize: 0 });
55
55
  const cancel = new AbortController();
56
56
  prompt.once("SIGINT", () => cancel.abort());
57
- process.stdout.write("Paste your AgentLyra SDK key and press Enter (input hidden): ");
57
+ process.stdout.write("Paste your AgentLyra API key and press Enter (input hidden): ");
58
58
  try {
59
59
  return (await prompt.question("", { signal: cancel.signal })).trim();
60
60
  } finally {
@@ -67,9 +67,9 @@ export async function switchMode(root, mode, args, { output = process.stdout, pr
67
67
  const replace = mode === "gated" && args.length === 1 && args[0] === "--replace-key";
68
68
  if (args.length && !replace) throw new Error("Usage: agent-lyra work-locally | agent-lyra connect-cloud [--replace-key]");
69
69
  if (mode === "gated" && (replace || !(await readSdkKey(root, { home })))) {
70
- output.write("Generate an SDK key at https://console.agentlyra.in/mcp-servers\n");
70
+ output.write("Generate an AgentLyra API key at https://console.agentlyra.in/mcp-servers\n");
71
71
  const key = await prompt();
72
- if (!validKey(key)) throw new Error("Enter a dedicated Lyra SDK key beginning with lyra_sdk_.");
72
+ if (!validKey(key)) throw new Error("Enter an AgentLyra API key beginning with lyra_sdk_.");
73
73
  await saveJson(home, "credentials.json", { LYRA_API_KEY: key });
74
74
  }
75
75
  await saveJson(workspace(root), "session.json", { mode });