agent-lyra 0.2.0 → 0.3.1

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
@@ -1,118 +1,160 @@
1
- # agent-lyra
2
-
3
- ## Local-first release 0.2.0
4
-
5
- The supported release path is local. It includes the Node CLI, SQLite run history, the draft-review team, and read-only IDE MCP. OpenAI-backed runs use your own key. The legacy gated client expects a compatible hosted `/agents/<vertical>/invoke` endpoint. The bundled hosted default has not been verified against AgentLyra production, so hosted invocation is outside this release’s supported scope.
6
-
7
- ## Run a local agent
8
-
9
- With Node.js 22.13 or newer, set `OPENAI_API_KEY` in your terminal environment, then run these commands from your project:
10
-
11
- ```bash
12
- npx agent-lyra agent run --model YOUR_MODEL --prompt "Summarize this idea"
13
- npx agent-lyra run status YOUR_RUN_ID
14
- ```
15
-
16
- The first command sends your prompt to OpenAI using your key and prints a run ID. The second reads the most recent event from `.lyra/state/runs.sqlite`, including the generated output on success. Keep that directory local if the output is sensitive. The run requires no Lyra account. The existing `init` wizard remains available for scaffolding.
17
-
18
- To run the built-in writing team with the same setup:
19
-
20
- ```bash
21
- npx agent-lyra team run draft-review --model YOUR_MODEL --prompt "Draft a project update"
22
- ```
23
-
24
- The writer produces a draft, then the reviewer receives the prompt and draft and returns revised text. Each step prints a run ID you can inspect with `agent-lyra run status`. The team makes two model calls when both steps succeed.
25
-
26
- ## Inspect saved runs from an IDE
27
-
28
- Configure a stdio MCP server in your IDE with the installed `agent-lyra` executable (use its absolute path if needed) and these arguments:
29
-
30
- ```json
31
- ["mcp", "serve", "--dir", "ABSOLUTE_PROJECT_PATH"]
32
- ```
33
-
34
- Two-layer Lyra SDK package:
35
-
36
- - Standalone layer: local orchestration primitives and RAG utilities with no API key.
37
- - Gated layer: compatibility client for deployments that provide the hosted invocation endpoint.
38
-
39
- ## Install
40
-
41
- ```bash
42
- npm install agent-lyra
43
- # or
44
- pnpm add agent-lyra
45
- ```
46
-
47
- Installation has zero side effects:
48
-
49
- - no files/folders created
50
- - no network calls by package code
51
- - no postinstall hooks
52
-
53
- Initialization is explicit and happens only when the user runs the CLI.
54
-
55
- ## Init A Repo
56
-
57
- ```bash
58
- npx agent-lyra init
59
- ```
60
-
61
- Or after install:
62
-
63
- ```bash
64
- agent-lyra init
65
- ```
66
-
67
- Flow:
68
-
69
- - optional login step with Lyra API key to sync your web-created agents
70
- - choose pack type: `Professional` or `Everyday`
71
- - choose `standalone` or `gated` (or set with `--mode`)
72
- - standalone: select onboarding domains with `Space`, confirm with `Enter`
73
- - for repository-aware engineering personas, select `engineering-bootstrap`
74
- - gated: select hosted verticals, then enter the Lyra API key from the Lyra login UI
75
- - logged-out gated selections are marked as `needs login` in generated metadata
76
- - the command creates a `.lyra/` folder in the current repo only after confirmation
77
-
78
- Generated files:
79
-
80
- - `.lyra/config.json`
81
- - `.lyra/manifest.json` (root manifest with `source` + `comparisonStatus`)
82
- - `.lyra/README.md`
83
- - `.lyra/domains/<domain>/domain.json` (domain manifest)
84
- - `.lyra/domains/<domain>/agents/*.md`
85
- - `.lyra/agents/*.md` (flattened top-level agent specs)
86
- - `.lyra/credentials.json` only for gated mode
87
- - `.lyra/.gitignore` to ignore the local credentials file
88
-
89
- Agent Markdown files are generated from the canonical onboarding catalog and include rich fields:
90
-
91
- - identity: `id`, `slug`, `name`, `domain`, `category`, `mode`
92
- - execution: `type`, `runtime` (standalone) or `hosted` (gated)
93
- - behavior: `description`, `systemPrompt`, `skills`, `integrations`
94
- - output policy: `outputs`
95
-
96
- Engineering bootstrap agents are dynamic and repo-intelligence-ready:
97
-
98
- - roles generated: `Engineering Dev Lead`, `Engineering QA Lead`, `Engineering Product Manager`, `Engineering Scrum Master`, `Engineering Architect`
99
- - prompts are stack-agnostic and rely on runtime repo scan context
100
- - each agent spec includes a `repoIntelligence` contract that aligns with:
101
- - scan endpoint: `/api/repositories/:id/scan`
102
- - PR endpoint: `/api/repositories/:id/lyra-pr`
103
-
104
- ## Usage
105
-
106
- ```js
107
- import { standalone, gated } from "agent-lyra";
108
-
109
- const workflow = standalone.createLinearWorkflow(
110
- async () => "collect",
111
- async (ctx) => `${ctx.step_1}:analyze`,
112
- );
113
-
114
- const result = await standalone.runWorkflow(workflow);
115
-
116
- const client = gated.createHostedAgentClient({ apiKey: process.env.LYRA_API_KEY });
117
- const output = await client.invoke("sales", { prompt: "Summarize latest pipeline risk." });
118
- ```
1
+ # agent-lyra
2
+
3
+ ## Local-first release
4
+
5
+ The supported release path is local. It includes the Node CLI, SQLite run history, the draft-review team, and read-only IDE MCP. OpenAI-backed runs use your own key. The legacy gated client expects a compatible hosted `/agents/<vertical>/invoke` endpoint. The bundled hosted default has not been verified against AgentLyra production, so hosted invocation is outside this release’s supported scope.
6
+
7
+ ## CLI reference
8
+
9
+ Use Node.js 22.13 or newer. Run these commands from your project after installing `agent-lyra`. Angle brackets mark required arguments. Square brackets mark optional arguments.
10
+
11
+ ### Project setup
12
+
13
+ | Command | What it does |
14
+ | --- | --- |
15
+ | `npx agent-lyra init [options]` | Scaffold a `.lyra` workspace and starter agents. Options include `--mode`, `--domains`, `--api-key`, `--api-base-url`, `--dir`, and `--force`. |
16
+ | `npx agent-lyra --help` | Show the init command and its options. The help alias does the same. Add `--help` to a specific command for its syntax. |
17
+
18
+ ### App Builder
19
+
20
+ | Command | What it does |
21
+ | --- | --- |
22
+ | `npx agent-lyra app init [manifest.json]` | Create the Support IQ starter. Defaults to `.lyra/app/manifest.json`. |
23
+ | `npx agent-lyra app validate <manifest.json>` | Check the app manifest before previewing or exporting. |
24
+ | `npx agent-lyra app preview <manifest.json>` | Run the starter preview on loopback. Set `LYRA_PREVIEW_PORT` to change its port. |
25
+ | `npx agent-lyra app export <manifest.json> <new-directory>` | Export the supported starter into a new directory. |
26
+ | `npx agent-lyra app publish <manifest.json> --dry-run` | Print the proposed Marketplace payload for review. Submit the listing in the cloud. |
27
+ | `npx agent-lyra app use <listing-id> [new-manifest.json]` | Import a published app and save its manifest. Requires `LYRA_SESSION_TOKEN`. |
28
+
29
+ ### Agent runs and IDE integration
30
+
31
+ | Command | What it does |
32
+ | --- | --- |
33
+ | `npx agent-lyra agent run --model <model> --prompt <text>` | Run a local agent with an OpenAI model. Requires `OPENAI_API_KEY`. |
34
+ | `npx agent-lyra team run draft-review --model <model> --prompt <text>` | Run the built-in writer and reviewer team. Requires `OPENAI_API_KEY`. |
35
+ | `npx agent-lyra run status <run-id>` | Read the latest event for a run from local SQLite history. |
36
+ | `npx agent-lyra mcp serve --dir <absolute-project-directory>` | Expose saved runs to an IDE over read-only stdio MCP. |
37
+
38
+ ## Build a support app
39
+
40
+ ```bash
41
+ npx agent-lyra app init
42
+ npx agent-lyra app validate .lyra/app/manifest.json
43
+ npx agent-lyra app preview .lyra/app/manifest.json
44
+ npx agent-lyra app export .lyra/app/manifest.json ./my-support-app
45
+ ```
46
+
47
+ Run each command separately. Stop the preview before exporting from the same terminal. The starter supports the local Support IQ template without cloud authentication. Use `app publish <manifest.json> --dry-run` to review a listing payload offline. `app use <listing-id>` imports a published app using an existing cloud session supplied through `LYRA_SESSION_TOKEN`. The cloud Marketplace also lets signed-in users save a private copy and download its manifest.
48
+
49
+ ## Run a local agent
50
+
51
+ With Node.js 22.13 or newer, set `OPENAI_API_KEY` in your terminal environment, then run these commands from your project:
52
+
53
+ ```bash
54
+ npx agent-lyra agent run --model YOUR_MODEL --prompt "Summarize this idea"
55
+ npx agent-lyra run status YOUR_RUN_ID
56
+ ```
57
+
58
+ The first command sends your prompt to OpenAI using your key and prints a run ID. The second reads the most recent event from `.lyra/state/runs.sqlite`, including the generated output on success. Keep that directory local if the output is sensitive. The run requires no Lyra account. The existing `init` wizard remains available for scaffolding.
59
+
60
+ To run the built-in writing team with the same setup:
61
+
62
+ ```bash
63
+ npx agent-lyra team run draft-review --model YOUR_MODEL --prompt "Draft a project update"
64
+ ```
65
+
66
+ The writer produces a draft, then the reviewer receives the prompt and draft and returns revised text. Each step prints a run ID you can inspect with `agent-lyra run status`. The team makes two model calls when both steps succeed.
67
+
68
+ ## Inspect saved runs from an IDE
69
+
70
+ Configure a stdio MCP server in your IDE with the installed `agent-lyra` executable (use its absolute path if needed) and these arguments:
71
+
72
+ ```json
73
+ ["mcp", "serve", "--dir", "ABSOLUTE_PROJECT_PATH"]
74
+ ```
75
+
76
+ Two-layer Lyra SDK package:
77
+
78
+ - Standalone layer: local orchestration primitives and RAG utilities with no API key.
79
+ - Gated layer: compatibility client for deployments that provide the hosted invocation endpoint.
80
+
81
+ ## Install
82
+
83
+ ```bash
84
+ npm install agent-lyra
85
+ # or
86
+ pnpm add agent-lyra
87
+ ```
88
+
89
+ Installation has zero side effects:
90
+
91
+ - no files/folders created
92
+ - no network calls by package code
93
+ - no postinstall hooks
94
+
95
+ Initialization is explicit and happens only when the user runs the CLI.
96
+
97
+ ## Init A Repo
98
+
99
+ ```bash
100
+ npx agent-lyra init
101
+ ```
102
+
103
+ Or after install:
104
+
105
+ ```bash
106
+ agent-lyra init
107
+ ```
108
+
109
+ Flow:
110
+
111
+ - optional login step with Lyra API key to sync your web-created agents
112
+ - choose pack type: `Professional` or `Everyday`
113
+ - choose `standalone` or `gated` (or set with `--mode`)
114
+ - standalone: select onboarding domains with `Space`, confirm with `Enter`
115
+ - for repository-aware engineering personas, select `engineering-bootstrap`
116
+ - gated: select hosted verticals, then enter the Lyra API key from the Lyra login UI
117
+ - logged-out gated selections are marked as `needs login` in generated metadata
118
+ - the command creates a `.lyra/` folder in the current repo only after confirmation
119
+
120
+ Generated files:
121
+
122
+ - `.lyra/config.json`
123
+ - `.lyra/manifest.json` (root manifest with `source` + `comparisonStatus`)
124
+ - `.lyra/README.md`
125
+ - `.lyra/domains/<domain>/domain.json` (domain manifest)
126
+ - `.lyra/domains/<domain>/agents/*.md`
127
+ - `.lyra/agents/*.md` (flattened top-level agent specs)
128
+ - `.lyra/credentials.json` only for gated mode
129
+ - `.lyra/.gitignore` to ignore the local credentials file
130
+
131
+ Agent Markdown files are generated from the canonical onboarding catalog and include rich fields:
132
+
133
+ - identity: `id`, `slug`, `name`, `domain`, `category`, `mode`
134
+ - execution: `type`, `runtime` (standalone) or `hosted` (gated)
135
+ - behavior: `description`, `systemPrompt`, `skills`, `integrations`
136
+ - output policy: `outputs`
137
+
138
+ Engineering bootstrap agents are dynamic and repo-intelligence-ready:
139
+
140
+ - roles generated: `Engineering Dev Lead`, `Engineering QA Lead`, `Engineering Product Manager`, `Engineering Scrum Master`, `Engineering Architect`
141
+ - prompts are stack-agnostic and rely on runtime repo scan context
142
+ - each agent spec includes a `repoIntelligence` contract that aligns with:
143
+ - scan endpoint: `/api/repositories/:id/scan`
144
+ - PR endpoint: `/api/repositories/:id/lyra-pr`
145
+
146
+ ## Usage
147
+
148
+ ```js
149
+ import { standalone, gated } from "agent-lyra";
150
+
151
+ const workflow = standalone.createLinearWorkflow(
152
+ async () => "collect",
153
+ async (ctx) => `${ctx.step_1}:analyze`,
154
+ );
155
+
156
+ const result = await standalone.runWorkflow(workflow);
157
+
158
+ const client = gated.createHostedAgentClient({ apiKey: process.env.LYRA_API_KEY });
159
+ const output = await client.invoke("sales", { prompt: "Summarize latest pipeline risk." });
160
+ ```
package/bin/agent-lyra.js CHANGED
@@ -3,9 +3,21 @@
3
3
  import { runCli } from "../src/init.js";
4
4
  import { runLocalCli } from "../src/runtime/local-cli.js";
5
5
  import { serveSavedRuns } from "../src/runtime/mcp-stdio.js";
6
+ import { runAppValidation } from "../src/app-builder/validate.js";
7
+ import { runAppExport } from "../src/app-builder/export.js";
8
+ import { runAppInit } from "../src/app-builder/init.js";
9
+ import { runAppPreview } from "../src/app-builder/preview.js";
10
+ import { runAppPublish } from "../src/app-builder/publish.js";
11
+ import { runAppUse } from "../src/app-builder/use.js";
6
12
 
7
13
  async function main() {
8
14
  const argv = process.argv.slice(2);
15
+ if (argv[0] === "app" && argv[1] === "use") return runAppUse(argv.slice(2));
16
+ if (argv[0] === "app" && argv[1] === "init") return runAppInit(argv.slice(2));
17
+ if (argv[0] === "app" && argv[1] === "preview") return runAppPreview(argv.slice(2));
18
+ if (argv[0] === "app" && argv[1] === "publish") return runAppPublish(argv.slice(2));
19
+ if (argv[0] === "app" && argv[1] === "export") return runAppExport(argv.slice(2));
20
+ if (argv[0] === "app" && argv[1] === "validate") return runAppValidation(argv.slice(2));
9
21
  if (argv[0] === "mcp" && argv[1] === "serve") return serveSavedRuns(argv.slice(2));
10
22
  if (!(await runLocalCli(argv))) await runCli(argv);
11
23
  }
@@ -13,4 +25,4 @@ async function main() {
13
25
  main().catch((error) => {
14
26
  process.stderr.write(`${error.message}\n`);
15
27
  process.exitCode = 1;
16
- });
28
+ });
package/package.json CHANGED
@@ -1,56 +1,56 @@
1
- {
2
- "name": "agent-lyra",
3
- "version": "0.2.0",
4
- "description": "Two-layer Lyra SDK with standalone local primitives and gated hosted agents.",
5
- "type": "module",
6
- "main": "./src/index.js",
7
- "types": "./src/index.d.ts",
8
- "engines": {
9
- "node": ">=22.13.0"
10
- },
11
- "repository": {
12
- "type": "git",
13
- "url": "git+https://gitlab.com/vibified/agent-lyra.git",
14
- "directory": "packages/lyra"
15
- },
16
- "homepage": "https://agentlyra.in",
17
- "bin": {
18
- "agent-lyra": "./bin/agent-lyra.js"
19
- },
20
- "exports": {
21
- ".": {
22
- "types": "./src/index.d.ts",
23
- "default": "./src/index.js"
24
- },
25
- "./standalone": {
26
- "types": "./src/standalone/index.d.ts",
27
- "default": "./src/standalone/index.js"
28
- },
29
- "./gated": {
30
- "types": "./src/gated/index.d.ts",
31
- "default": "./src/gated/index.js"
32
- }
33
- },
34
- "files": [
35
- "bin",
36
- "src",
37
- "README.md",
38
- "LICENSE"
39
- ],
40
- "sideEffects": false,
41
- "scripts": {
42
- "test": "node --test"
43
- },
44
- "keywords": [
45
- "lyra",
46
- "orchestration",
47
- "rag",
48
- "agents",
49
- "sdk"
50
- ],
51
- "author": "",
52
- "license": "MIT",
53
- "publishConfig": {
54
- "access": "public"
55
- }
56
- }
1
+ {
2
+ "name": "agent-lyra",
3
+ "version": "0.3.1",
4
+ "description": "Two-layer Lyra SDK with standalone local primitives and gated hosted agents.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "engines": {
9
+ "node": ">=22.13.0"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://gitlab.com/vibified/agent-lyra.git",
14
+ "directory": "packages/lyra"
15
+ },
16
+ "homepage": "https://agentlyra.in",
17
+ "bin": {
18
+ "agent-lyra": "./bin/agent-lyra.js"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./src/index.d.ts",
23
+ "default": "./src/index.js"
24
+ },
25
+ "./standalone": {
26
+ "types": "./src/standalone/index.d.ts",
27
+ "default": "./src/standalone/index.js"
28
+ },
29
+ "./gated": {
30
+ "types": "./src/gated/index.d.ts",
31
+ "default": "./src/gated/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "bin",
36
+ "src",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "sideEffects": false,
41
+ "scripts": {
42
+ "test": "node --test"
43
+ },
44
+ "keywords": [
45
+ "lyra",
46
+ "orchestration",
47
+ "rag",
48
+ "agents",
49
+ "sdk"
50
+ ],
51
+ "author": "",
52
+ "license": "MIT",
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }
@@ -0,0 +1,59 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { readSupportManifest } from "./support-manifest.js";
4
+
5
+ const assets = {
6
+ "runtime/app-builder/support-template/support-preview.mjs": "./support-template/support-preview.mjs",
7
+ "runtime/app-builder/support-template/support-preview.html": "./support-template/support-preview.html",
8
+ "runtime/app-builder/support-template/support-preview.js": "./support-template/support-preview.js",
9
+ "runtime/app-builder/support-template/support-workflow.mjs": "./support-template/support-workflow.mjs",
10
+ "runtime/app-builder/gateway.js": "./gateway.js",
11
+ "runtime/app-builder/validate.js": "./validate.js",
12
+ "runtime/app-builder/value-schema.js": "./value-schema.js",
13
+ "runtime/app-builder/native-adapter.js": "./native-adapter.js",
14
+ "runtime/runtime/run-agent.js": "../runtime/run-agent.js",
15
+ LICENSE: "../../LICENSE",
16
+ };
17
+
18
+ export async function runAppExport(args, output = process.stdout) {
19
+ if (args.length === 1 && args[0] === "--help") {
20
+ output.write("Usage: agent-lyra app export <manifest.json> <new-directory>\n");
21
+ return;
22
+ }
23
+ if (args.length !== 2 || args.some((arg) => arg.startsWith("-"))) {
24
+ throw new Error("Provide a manifest and new output directory. See agent-lyra app export --help.");
25
+ }
26
+ const manifest = await readSupportManifest(args[0]);
27
+ const directory = resolve(args[1]);
28
+ const files = await Promise.all(Object.entries(assets).map(async ([name, sourcePath]) =>
29
+ [name, await readFile(new URL(sourcePath, import.meta.url))]));
30
+ const manifestReader = 'const manifest = JSON.parse(await readFile(new URL("./example-manifest.json", import.meta.url), "utf8"));\n';
31
+ files.push(["example-manifest.json", JSON.stringify(manifest, null, 2) + "\n"]);
32
+ files.push(["support-preview.mjs",
33
+ 'import { readFile } from "node:fs/promises";\n' +
34
+ 'import { startSupportPreview } from "./runtime/app-builder/support-template/support-preview.mjs";\n' +
35
+ manifestReader + "await startSupportPreview(manifest);\n"]);
36
+ files.push(["support-example.mjs",
37
+ 'import { readFile } from "node:fs/promises";\n' +
38
+ 'import { createSupportWorkflow } from "./runtime/app-builder/support-template/support-workflow.mjs";\n' +
39
+ manifestReader +
40
+ 'console.log(JSON.stringify(await createSupportWorkflow(manifest)(process.argv[2] ?? "Invoice question"), null, 2));\n']);
41
+ files.push(["package.json", JSON.stringify({
42
+ name: manifest.application.id, version: "1.0.0", private: true, type: "module",
43
+ engines: { node: ">=22.13.0" },
44
+ scripts: { start: "node support-preview.mjs", demo: "node support-example.mjs" },
45
+ }, null, 2) + "\n"]);
46
+ files.push(["README.md", "# Support app\n\nRun `npm start` and open http://127.0.0.1:4173/. Run `npm run demo` for the terminal workflow.\n\nThe bundled classifier and provider are deterministic. The app binds to loopback and does not persist or send tickets.\n"]);
47
+ try {
48
+ await mkdir(directory);
49
+ } catch (error) {
50
+ if (error.code === "EEXIST") throw new Error("Choose a new directory. Existing files were preserved.");
51
+ throw error;
52
+ }
53
+ for (const [name, contents] of files) {
54
+ const target = join(directory, name);
55
+ await mkdir(dirname(target), { recursive: true });
56
+ await writeFile(target, contents, { flag: "wx" });
57
+ }
58
+ output.write(`Exported ${manifest.application.id} to ${directory}\n`);
59
+ }
@@ -0,0 +1,62 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { validateAppManifest } from "./validate.js";
3
+ import { matchesValueSchema } from "./value-schema.js";
4
+
5
+ export const capabilityContractVersion = "1.0";
6
+
7
+ export function createCapabilityGateway(manifest, adapters = []) {
8
+ validateAppManifest(manifest);
9
+ const registry = new Map();
10
+ for (const adapter of adapters) {
11
+ if (!adapter || typeof adapter.id !== "string" || !adapter.id ||
12
+ adapter.contractVersion !== capabilityContractVersion || typeof adapter.invoke !== "function") {
13
+ throw new Error("Adapter requires an id, contract version 1.0, and invoke function.");
14
+ }
15
+ if (registry.has(adapter.id)) throw new Error(`Duplicate adapter: ${adapter.id}.`);
16
+ registry.set(adapter.id, adapter.invoke.bind(adapter));
17
+ }
18
+ const capabilities = new Map(manifest.capabilities.map(({ id, adapterId, executionMode, inputSchema, outputSchema }) =>
19
+ [id, structuredClone({ id, adapterId, executionMode, inputSchema, outputSchema })]));
20
+ const actions = new Map(manifest.actions.map(({ id, capabilityId }) => [id, capabilityId]));
21
+
22
+ return {
23
+ async invokeAction(actionId, input, { correlationId = randomUUID() } = {}) {
24
+ const capability = capabilities.get(actions.get(actionId));
25
+ const base = { executionId: randomUUID(), correlationId };
26
+ const fail = (status, code, message) => ({
27
+ ...base, status, error: { code, message, retryable: false },
28
+ });
29
+ if (!capability) return fail("failed", "UNKNOWN_ACTION", "Action is not declared in the manifest.");
30
+ if (capability.executionMode !== "in-process") {
31
+ return fail("unsupported", "UNSUPPORTED_MODE", "Only in-process execution is supported by this gateway.");
32
+ }
33
+ const invoke = registry.get(capability.adapterId);
34
+ if (!invoke) return fail("unsupported", "ADAPTER_NOT_REGISTERED", "Capability adapter is not registered.");
35
+ if (capability.inputSchema && !matchesValueSchema(input, capability.inputSchema)) {
36
+ return fail("failed", "INVALID_INPUT", "Input does not satisfy the capability schema.");
37
+ }
38
+ try {
39
+ const result = await invoke({ ...base, capabilityId: capability.id, input });
40
+ if (result?.status === "completed") {
41
+ if (capability.outputSchema && !matchesValueSchema(result.output, capability.outputSchema)) {
42
+ return fail("failed", "INVALID_OUTPUT", "Adapter output does not satisfy the capability schema.");
43
+ }
44
+ return {
45
+ ...base, status: "completed", output: result.output,
46
+ ...(result.nativeExecutionId && { nativeExecutionId: result.nativeExecutionId }),
47
+ ...(result.usage && { usage: result.usage }),
48
+ };
49
+ }
50
+ if (result?.status === "failed") {
51
+ return {
52
+ ...fail("failed", "ADAPTER_FAILED", "Capability execution failed."),
53
+ ...(result.nativeExecutionId && { nativeExecutionId: result.nativeExecutionId }),
54
+ };
55
+ }
56
+ return fail("failed", "INVALID_ADAPTER_RESULT", "Adapter returned an invalid result.");
57
+ } catch {
58
+ return fail("failed", "ADAPTER_FAILED", "Capability execution failed.");
59
+ }
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,23 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+
4
+ export async function runAppInit(args, output = process.stdout) {
5
+ if (args.length === 1 && args[0] === "--help") {
6
+ output.write("Usage: agent-lyra app init [manifest.json]\nDefault: .lyra/app/manifest.json\n");
7
+ return;
8
+ }
9
+ if (args.length > 1 || args[0]?.startsWith("-")) {
10
+ throw new Error("Provide at most one manifest path. See agent-lyra app init --help.");
11
+ }
12
+
13
+ const target = resolve(args[0] ?? ".lyra/app/manifest.json");
14
+ const template = await readFile(new URL("./support-template/manifest.json", import.meta.url));
15
+ await mkdir(dirname(target), { recursive: true });
16
+ try {
17
+ await writeFile(target, template, { flag: "wx" });
18
+ } catch (error) {
19
+ if (error.code === "EEXIST") throw new Error(`Manifest already exists at ${target}. It was preserved.`);
20
+ throw error;
21
+ }
22
+ output.write(`Created ${target}\n`);
23
+ }
@@ -0,0 +1,29 @@
1
+ import { runAgent } from "../runtime/run-agent.js";
2
+ import { capabilityContractVersion } from "./gateway.js";
3
+
4
+ export function createNativeAdapter({ agents, provider, store }) {
5
+ const configured = new Map(agents);
6
+ return {
7
+ id: "native",
8
+ contractVersion: capabilityContractVersion,
9
+ async invoke({ capabilityId, input }) {
10
+ const agent = configured.get(capabilityId);
11
+ if (!agent || typeof input !== "string" || !input.trim()) return { status: "failed" };
12
+ const event = await runAgent({
13
+ agentId: capabilityId,
14
+ request: {
15
+ model: agent.model,
16
+ messages: [
17
+ ...(agent.system ? [{ role: "system", content: agent.system }] : []),
18
+ { role: "user", content: input },
19
+ ],
20
+ },
21
+ provider,
22
+ store,
23
+ });
24
+ if (event.type === "run.failed") return { status: "failed", nativeExecutionId: event.run_id };
25
+ const { text, usage } = event.data.result;
26
+ return { status: "completed", nativeExecutionId: event.run_id, output: text, ...(usage && { usage }) };
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,14 @@
1
+ import { readSupportManifest } from "./support-manifest.js";
2
+ import { startSupportPreview } from "./support-template/support-preview.mjs";
3
+
4
+ export async function runAppPreview(args, output = process.stdout) {
5
+ if (args.length === 1 && args[0] === "--help") {
6
+ output.write("Usage: agent-lyra app preview <manifest.json>\nSet LYRA_PREVIEW_PORT to override the loopback port.\n");
7
+ return;
8
+ }
9
+ if (args.length !== 1 || args[0].startsWith("-")) {
10
+ throw new Error("Provide a manifest path. See agent-lyra app preview --help.");
11
+ }
12
+ const manifest = await readSupportManifest(args[0]);
13
+ await startSupportPreview(manifest);
14
+ }
@@ -0,0 +1,14 @@
1
+ import { readSupportManifest } from "./support-manifest.js";
2
+
3
+ export async function runAppPublish(args, output = process.stdout) {
4
+ if (args.length === 1 && args[0] === "--help") {
5
+ output.write("Usage: agent-lyra app publish <manifest.json> --dry-run\n");
6
+ return;
7
+ }
8
+ if (args.length !== 2 || args[0].startsWith("-") || args[1] !== "--dry-run") {
9
+ throw new Error("Only offline listing previews are supported. Pass <manifest.json> --dry-run.");
10
+ }
11
+ const manifest = await readSupportManifest(args[0]);
12
+ const listing = { listingSchemaVersion: "1.0", manifest };
13
+ output.write(`${JSON.stringify(listing, null, 2)}\n`);
14
+ }
@@ -0,0 +1,50 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { validateAppManifest } from "./validate.js";
3
+ import { matchesValueSchema } from "./value-schema.js";
4
+
5
+ export function projectSupportManifest(manifest) {
6
+ validateAppManifest(manifest);
7
+ const { preview } = manifest;
8
+ if (preview?.template !== "support" || preview.classifyAction === preview.draftAction) {
9
+ throw new Error("Choose the support preview template with two distinct actions.");
10
+ }
11
+ const bind = (id, adapterId) => {
12
+ const action = manifest.actions.find((entry) => entry.id === id);
13
+ const capability = manifest.capabilities.find((entry) => entry.id === action?.capabilityId);
14
+ if (capability?.adapterId !== adapterId || capability.executionMode !== "in-process") {
15
+ throw new Error(`The support template requires an in-process ${adapterId} action.`);
16
+ }
17
+ const { id: capabilityId, executionMode, inputSchema, outputSchema } = capability;
18
+ return { action: { id, capabilityId }, capability: { id: capabilityId, adapterId, executionMode, inputSchema, outputSchema } };
19
+ };
20
+ const classify = bind(preview.classifyAction, "mock");
21
+ const draft = bind(preview.draftAction, "native");
22
+ for (const [binding, sampleInput, sampleOutput] of [
23
+ [classify, "Invoice question", { category: "billing" }],
24
+ [draft, "billing", "Draft reply"],
25
+ ]) {
26
+ const { inputSchema, outputSchema } = binding.capability;
27
+ if ((inputSchema && !matchesValueSchema(sampleInput, inputSchema)) ||
28
+ (outputSchema && !matchesValueSchema(sampleOutput, outputSchema))) {
29
+ throw new Error(`Action ${binding.action.id} has an incompatible schema for the support template.`);
30
+ }
31
+ }
32
+ return {
33
+ version: manifest.version,
34
+ application: { id: manifest.application.id, name: manifest.application.name },
35
+ preview: { template: "support", classifyAction: classify.action.id, draftAction: draft.action.id },
36
+ capabilities: [classify.capability, draft.capability],
37
+ actions: [classify.action, draft.action],
38
+ };
39
+ }
40
+
41
+ export async function readSupportManifest(path) {
42
+ const source = await readFile(path, "utf8");
43
+ let raw;
44
+ try {
45
+ raw = JSON.parse(source.replace(/^\uFEFF/, ""));
46
+ } catch {
47
+ throw new Error("Application manifest is not valid JSON.");
48
+ }
49
+ return projectSupportManifest(raw);
50
+ }
@@ -0,0 +1,55 @@
1
+ {
2
+ "version": "1.0",
3
+ "application": {
4
+ "id": "support-iq",
5
+ "name": "Support IQ"
6
+ },
7
+ "capabilities": [
8
+ {
9
+ "id": "classify-ticket",
10
+ "adapterId": "mock",
11
+ "executionMode": "in-process",
12
+ "inputSchema": {
13
+ "type": "string"
14
+ },
15
+ "outputSchema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "category": {
19
+ "type": "string"
20
+ }
21
+ },
22
+ "required": [
23
+ "category"
24
+ ],
25
+ "additionalProperties": false
26
+ }
27
+ },
28
+ {
29
+ "id": "draft-reply",
30
+ "adapterId": "native",
31
+ "executionMode": "in-process",
32
+ "inputSchema": {
33
+ "type": "string"
34
+ },
35
+ "outputSchema": {
36
+ "type": "string"
37
+ }
38
+ }
39
+ ],
40
+ "actions": [
41
+ {
42
+ "id": "classify",
43
+ "capabilityId": "classify-ticket"
44
+ },
45
+ {
46
+ "id": "draft",
47
+ "capabilityId": "draft-reply"
48
+ }
49
+ ],
50
+ "preview": {
51
+ "template": "support",
52
+ "classifyAction": "classify",
53
+ "draftAction": "draft"
54
+ }
55
+ }
@@ -0,0 +1,56 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>__LYRA_APP_TITLE__ | AgentLyra</title>
7
+ <style>
8
+ :root { color-scheme: light; font-family: system-ui, sans-serif; color: #16302a; background: #f3f6f4; }
9
+ body { margin: 0; }
10
+ main { width: min(100% - 2rem, 64rem); margin: 3rem auto; }
11
+ h1 { margin: .25rem 0 1.5rem; font-size: clamp(2rem, 6vw, 3.5rem); letter-spacing: -.055em; }
12
+ h2 { margin: 0 0 1rem; font-size: 1.15rem; }
13
+ .label { color: #436459; font-weight: 650; }
14
+ .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
15
+ section { padding: 1.25rem; background: #fff; border: 1px solid #cedcd4; border-radius: .8rem; min-width: 0; }
16
+ textarea { box-sizing: border-box; display: block; margin: .5rem 0 1rem; padding: .8rem; width: 100%; min-height: 11rem; resize: vertical; border: 1px solid #859d91; border-radius: .4rem; font: inherit; color: inherit; }
17
+ button { background: #245745; color: white; font: inherit; font-weight: 650; padding: .65rem 1rem; border: 0; border-radius: .4rem; cursor: pointer; }
18
+ button:disabled { opacity: .65; cursor: wait; }
19
+ dd { margin: .3rem 0 1rem; overflow-wrap: anywhere; }
20
+ dt { font-weight: 650; }
21
+ #draft { white-space: pre-wrap; }
22
+ #status { min-height: 1.5em; margin-bottom: 0; }
23
+ #status[data-error] { color: #a52430; }
24
+ @media (max-width: 650px) { .grid { grid-template-columns: 1fr; } }
25
+ </style>
26
+ <script type="module" src="/preview.js"></script>
27
+ </head>
28
+ <body>
29
+ <main>
30
+ <div class="label">AgentLyra · Local preview</div>
31
+ <h1>__LYRA_APP_TITLE__</h1>
32
+ <div class="grid">
33
+ <section aria-labelledby="ticket-heading">
34
+ <h2 id="ticket-heading">Support ticket</h2>
35
+ <form id="ticket-form">
36
+ <label for="ticket">Customer message</label>
37
+ <textarea id="ticket" required maxlength="2000">I was charged twice for an invoice.</textarea>
38
+ <button type="submit">Draft reply</button>
39
+ </form>
40
+ <p id="status" role="status">Demo logic runs locally. Drafts stay on this screen.</p>
41
+ </section>
42
+ <section aria-labelledby="result-heading">
43
+ <h2 id="result-heading">Draft and trace</h2>
44
+ <p id="empty">Submit a ticket to see its category, draft reply, and run trace.</p>
45
+ <dl id="result" hidden>
46
+ <dt>Category</dt><dd id="category"></dd>
47
+ <dt>Draft reply</dt><dd id="draft"></dd>
48
+ <dt>Correlation ID</dt><dd id="correlation"></dd>
49
+ <dt>Native run ID</dt><dd id="run"></dd>
50
+ <dt>Events</dt><dd id="events"></dd>
51
+ </dl>
52
+ </section>
53
+ </div>
54
+ </main>
55
+ </body>
56
+ </html>
@@ -0,0 +1,37 @@
1
+ const form = document.getElementById("ticket-form");
2
+ const button = form.querySelector("button");
3
+ const status = document.getElementById("status");
4
+ const result = document.getElementById("result");
5
+ const empty = document.getElementById("empty");
6
+
7
+ form.addEventListener("submit", async (event) => {
8
+ event.preventDefault();
9
+ button.disabled = true;
10
+ result.hidden = true;
11
+ empty.hidden = true;
12
+ delete status.dataset.error;
13
+ status.textContent = "Running the support workflow…";
14
+ try {
15
+ const response = await fetch("/api/ticket", {
16
+ method: "POST",
17
+ headers: { "Content-Type": "application/json" },
18
+ body: JSON.stringify({ ticket: document.getElementById("ticket").value }),
19
+ });
20
+ const data = await response.json();
21
+ if (!response.ok) throw new Error(data.error);
22
+ for (const [id, value] of Object.entries({
23
+ category: data.category, draft: data.draft, correlation: data.correlationId,
24
+ run: data.nativeExecutionId, events: data.events.join(" → "),
25
+ })) {
26
+ document.getElementById(id).textContent = value;
27
+ }
28
+ result.hidden = false;
29
+ status.textContent = "Draft ready for review.";
30
+ } catch (error) {
31
+ status.dataset.error = "";
32
+ status.textContent = error.message || "Could not run the workflow.";
33
+ empty.hidden = false;
34
+ } finally {
35
+ button.disabled = false;
36
+ }
37
+ });
@@ -0,0 +1,67 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { createServer } from "node:http";
3
+ import { createSupportWorkflow } from "./support-workflow.mjs";
4
+
5
+ export async function startSupportPreview(manifest, { port = Number(process.env.LYRA_PREVIEW_PORT ?? "4173") } = {}) {
6
+ const runSupportTicket = createSupportWorkflow(manifest);
7
+
8
+ const host = "127.0.0.1";
9
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid preview port.");
10
+
11
+ const title = manifest.application.name.replace(/[&<>"']/g, (character) =>
12
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]);
13
+ const html = (await readFile(new URL("./support-preview.html", import.meta.url), "utf8"))
14
+ .replaceAll("__LYRA_APP_TITLE__", () => title);
15
+ const script = await readFile(new URL("./support-preview.js", import.meta.url));
16
+ const server = createServer(async (req, res) => {
17
+ const send = (status, type, body) => {
18
+ res.writeHead(status, {
19
+ "Content-Type": type,
20
+ "Cache-Control": "no-store",
21
+ "X-Content-Type-Options": "nosniff",
22
+ "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'",
23
+ });
24
+ res.end(body);
25
+ };
26
+ const json = (status, data) => send(status, "application/json; charset=utf-8", JSON.stringify(data));
27
+ const authority = `${host}:${server.address().port}`;
28
+ if (req.headers.host !== authority) return json(403, { error: "Use the loopback preview address." });
29
+ if (req.method === "GET" && req.url === "/") return send(200, "text/html; charset=utf-8", html);
30
+ if (req.method === "GET" && req.url === "/preview.js") return send(200, "text/javascript; charset=utf-8", script);
31
+ if (req.method !== "POST" || req.url !== "/api/ticket") return json(404, { error: "Route not found." });
32
+ if (req.headers.origin !== `http://${authority}`) return json(403, { error: "Request must come from the preview." });
33
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") {
34
+ return json(415, { error: "Expected a JSON ticket." });
35
+ }
36
+ let size = 0;
37
+ const chunks = [];
38
+ try {
39
+ for await (const chunk of req) {
40
+ size += chunk.length;
41
+ if (size > 16384) {
42
+ json(413, { error: "Ticket request is too large." });
43
+ return;
44
+ }
45
+ chunks.push(chunk);
46
+ }
47
+ } catch {
48
+ return;
49
+ }
50
+ let ticket;
51
+ try {
52
+ ({ ticket } = JSON.parse(Buffer.concat(chunks).toString("utf8")));
53
+ } catch {
54
+ return json(400, { error: "Invalid JSON ticket." });
55
+ }
56
+ if (typeof ticket !== "string" || !ticket.trim() || ticket.length > 2000) {
57
+ return json(400, { error: "Enter a ticket between 1 and 2,000 characters." });
58
+ }
59
+ try {
60
+ return json(200, await runSupportTicket(ticket));
61
+ } catch {
62
+ return json(500, { error: "The support workflow could not produce a draft." });
63
+ }
64
+ });
65
+ server.requestTimeout = 10000;
66
+ server.listen(port, host, () => console.log(`Support preview: http://${host}:${server.address().port}/`));
67
+ }
@@ -0,0 +1,36 @@
1
+ import { createCapabilityGateway } from "../gateway.js";
2
+ import { createNativeAdapter } from "../native-adapter.js";
3
+
4
+ export function createSupportWorkflow(manifest) {
5
+ const { classifyAction, draftAction } = manifest.preview;
6
+ const draftCapabilityId = manifest.actions.find(({ id }) => id === draftAction).capabilityId;
7
+ return async function runSupportTicket(ticket) {
8
+ const events = [];
9
+ const gateway = createCapabilityGateway(manifest, [
10
+ {
11
+ id: "mock",
12
+ contractVersion: "1.0",
13
+ async invoke({ input }) {
14
+ return { status: "completed", output: { category: /invoice|refund|charge/i.test(input) ? "billing" : "general" } };
15
+ },
16
+ },
17
+ createNativeAdapter({
18
+ agents: [[draftCapabilityId, { model: "demo-fixture" }]],
19
+ provider: {
20
+ async complete({ messages }) {
21
+ return { text: `Thanks for contacting support. Your ticket is categorized as ${messages.at(-1).content} and is ready for review.` };
22
+ },
23
+ },
24
+ store: { append: async (event) => events.push(event) },
25
+ }),
26
+ ]);
27
+
28
+ const classified = await gateway.invokeAction(classifyAction, ticket);
29
+ if (classified.status !== "completed") throw new Error(classified.error.message);
30
+ const reply = await gateway.invokeAction(draftAction, classified.output.category, { correlationId: classified.correlationId });
31
+ if (reply.status !== "completed") throw new Error(reply.error.message);
32
+ return { category: classified.output.category, draft: reply.output,
33
+ correlationId: reply.correlationId, nativeExecutionId: reply.nativeExecutionId,
34
+ events: events.map(({ type }) => type) };
35
+ }
36
+ }
@@ -0,0 +1,37 @@
1
+ import { lstat, mkdir, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { projectSupportManifest } from "./support-manifest.js";
4
+
5
+ export async function runAppUse(args, {
6
+ output = process.stdout, token = process.env.LYRA_SESSION_TOKEN, fetchRequest = globalThis.fetch,
7
+ } = {}) {
8
+ if (args.length === 1 && args[0] === "--help") {
9
+ output.write("Usage: agent-lyra app use <listing-id> [new-manifest.json]\n");
10
+ return;
11
+ }
12
+ if (!/^[a-f0-9]{24}$/i.test(args[0] ?? "") || args.length > 2 || args[1]?.startsWith("-")) {
13
+ throw new Error("Provide a Marketplace listing ID and an optional new manifest path.");
14
+ }
15
+ if (!token) throw new Error("Sign in to use an app. Set LYRA_SESSION_TOKEN to a valid cloud session token.");
16
+ const target = resolve(args[1] ?? ".lyra/app/manifest.json");
17
+ try {
18
+ await lstat(target);
19
+ throw new Error("Manifest already exists. Choose a new path.");
20
+ } catch (error) {
21
+ if (error.code !== "ENOENT") throw error;
22
+ }
23
+ const response = await fetchRequest(`https://api.agentlyra.in/api/app-marketplace/apps/${args[0]}/use`, {
24
+ method: "POST",
25
+ headers: { Authorization: `Bearer ${token}` },
26
+ redirect: "error",
27
+ signal: AbortSignal.timeout(15000),
28
+ });
29
+ if (response.status === 401 || response.status === 403) throw new Error("Cloud session expired or is invalid.");
30
+ if (!response.ok) throw new Error(`Marketplace import failed (HTTP ${response.status}).`);
31
+ const { listing } = await response.json();
32
+ if (listing?.listingSchemaVersion !== "1.0") throw new Error("Unsupported Marketplace listing.");
33
+ const manifest = projectSupportManifest(listing.manifest);
34
+ await mkdir(dirname(target), { recursive: true });
35
+ await writeFile(target, JSON.stringify(manifest, null, 2) + "\n", { flag: "wx" });
36
+ output.write(`Imported ${manifest.application.name} to ${target}\n`);
37
+ }
@@ -0,0 +1,65 @@
1
+ import { readFile } from "node:fs/promises";
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
+ }
47
+
48
+ export async function runAppValidation(args, output = process.stdout) {
49
+ if (args.length === 1 && args[0] === "--help") {
50
+ output.write("Usage: agent-lyra app validate <manifest.json>\n");
51
+ return;
52
+ }
53
+ if (args.length !== 1 || args[0].startsWith("-")) {
54
+ throw new Error("Provide a manifest path. See agent-lyra app validate --help.");
55
+ }
56
+ const source = await readFile(args[0], "utf8");
57
+ let manifest;
58
+ try {
59
+ manifest = JSON.parse(source.replace(/^\uFEFF/, ""));
60
+ } catch {
61
+ throw new Error("Application manifest is not valid JSON.");
62
+ }
63
+ const { id, capabilityCount, actionCount } = validateAppManifest(manifest);
64
+ output.write(`Valid app ${id} (${capabilityCount} capabilities, ${actionCount} actions).\n`);
65
+ }
@@ -0,0 +1,37 @@
1
+ const scalarTypes = new Set(["string", "boolean", "number", "integer", "null"]);
2
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3
+
4
+ function isScalarSchema(schema) {
5
+ return isObject(schema) && scalarTypes.has(schema.type) && Object.keys(schema).length === 1;
6
+ }
7
+
8
+ export function assertValueSchema(schema, label) {
9
+ if (isScalarSchema(schema)) return;
10
+ if (!isObject(schema) || schema.type !== "object" || !isObject(schema.properties) ||
11
+ Object.keys(schema).some((key) => !["type", "properties", "required", "additionalProperties"].includes(key)) ||
12
+ (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== "boolean") ||
13
+ !Object.values(schema.properties).every(isScalarSchema)) {
14
+ throw new Error(`${label} must be a scalar schema or a flat object schema with scalar properties.`);
15
+ }
16
+ if (schema.required !== undefined &&
17
+ (!Array.isArray(schema.required) || new Set(schema.required).size !== schema.required.length ||
18
+ schema.required.some((key) => typeof key !== "string" || !Object.hasOwn(schema.properties, key)))) {
19
+ throw new Error(`${label} required entries must be unique declared properties.`);
20
+ }
21
+ }
22
+
23
+ function matchesScalar(value, type) {
24
+ if (type === "null") return value === null;
25
+ if (type === "integer") return Number.isInteger(value);
26
+ if (type === "number") return Number.isFinite(value);
27
+ return typeof value === type;
28
+ }
29
+
30
+ export function matchesValueSchema(value, schema) {
31
+ if (schema.type !== "object") return matchesScalar(value, schema.type);
32
+ if (!isObject(value) || (schema.required ?? []).some((key) => !Object.hasOwn(value, key))) return false;
33
+ return Object.entries(value).every(([key, entry]) =>
34
+ Object.hasOwn(schema.properties, key)
35
+ ? matchesScalar(entry, schema.properties[key].type)
36
+ : schema.additionalProperties !== false);
37
+ }