lugh-lang 0.0.0-stage → 0.7.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,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # lugh-lang
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Lugh](https://github.com/Ashutosh3142857/lugh-lang) is a programming language for
4
+ AI agents. A program declares which systems the agent may touch (`use`), its limits
5
+ (`budget`), and which actions need a person (`policy`). Every action is typed as read,
6
+ write, send, submit, spend, delete or execute, and the runtime checks it before it runs.
7
+
8
+ This package runs Lugh Core (compiled to WebAssembly) in a sandbox, with no install:
9
+ `fs`, `http`, `mcp` and `shell` act on a simulated world, but every call passes the
10
+ real policy gate and budgets. Use it to check what an agent would do before it does it.
11
+
12
+ ```bash
13
+ npx lugh-lang run program.lugh # run goals; prints a policy log of every action
14
+ npx lugh-lang run program.lugh --decline # answer every approval with no
15
+ npx lugh-lang test program.lugh # run test blocks
16
+ npx lugh-lang check program.lugh # compile only
17
+ npx lugh-lang sandbox # what the simulated world contains
18
+ ```
19
+
20
+ Commands exit with status 1 when a goal, test or compile step fails.
21
+
22
+ ## MCP server
23
+
24
+ `npx lugh-lang mcp` is a Model Context Protocol server (stdio) with five read-only
25
+ tools: `lugh_reference`, `lugh_check`, `lugh_run`, `lugh_test` and `lugh_sandbox`.
26
+ An agent can write a Lugh program for a task, check it, dry-run it, and show the
27
+ person the policy log before anything runs for real.
28
+
29
+ ```json
30
+ {
31
+ "mcpServers": {
32
+ "lugh": { "command": "npx", "args": ["-y", "lugh-lang", "mcp"] }
33
+ }
34
+ }
35
+ ```
36
+
37
+ ## Running for real
38
+
39
+ To act on real files, APIs and MCP servers, install Lugh Core (Rust) from the
40
+ [repository](https://github.com/Ashutosh3142857/lugh-lang). There, approvals are
41
+ asked in the terminal or a web inbox, and every action is written to an audit log.
42
+
43
+ Try it in the browser: https://ashutosh3142857.github.io/lugh-lang/
44
+
45
+ MIT licensed.
package/REFERENCE.md ADDED
@@ -0,0 +1,99 @@
1
+ # Lugh reference (for writing programs)
2
+
3
+ A Lugh program is indented by two spaces and starts with `agent <Name>`.
4
+
5
+ ```lugh
6
+ agent RefundDesk
7
+ use fs, mcp # adapters the agent may use; anything else is unreachable
8
+ budget time 30s, calls 12 # limits enforced by the runtime
9
+ policy
10
+ allow read # runs without asking
11
+ ask human before submit, send # pauses for a yes/no
12
+ deny delete # refused before the request is sent
13
+
14
+ goal "Refund damaged orders" # a plain-language objective, then its steps
15
+ let orders = csv.parse(fs.read "orders.csv")
16
+ let damaged = filter o in orders where o.status == "damaged"
17
+ each o in damaged
18
+ mcp.call "payments" "refund" {order_id: o.order_id, amount: o.amount}
19
+ log "Refunded {count(damaged)} orders"
20
+
21
+ test "nothing to refund in an empty list"
22
+ expect count(filter o in [] where o.status == "damaged") == 0
23
+ ```
24
+
25
+ ## Effects and the policy gate
26
+
27
+ Every adapter call has one effect: `read`, `write`, `send`, `submit`, `spend`, `delete` or `execute`.
28
+ Before each call the runtime checks the time budget, the call budget, `deny`, `allow`,
29
+ and otherwise asks a human. Effects not listed in `policy` need approval. A denial or
30
+ budget overrun cannot be caught by `attempt`.
31
+
32
+ | Adapter | Verbs → effect |
33
+ | --- | --- |
34
+ | `fs` | `read`, `list` → read; `write`, `append` → write; `delete` → delete |
35
+ | `http` | `get` → read, `post` → send, `put` → write, `delete` → delete |
36
+ | `shell` | `run` → execute |
37
+ | `db` | `query` → read, `exec` → write (SQLite) |
38
+ | `mcp` | `tools` → read; `call` → from the tool's MCP annotations: read-only → read, destructive → delete, otherwise submit |
39
+ | `llm` | `think` |
40
+
41
+ Adapter calls: `fs.read "path" as json`, `http.get "https://…" as json`,
42
+ `mcp.call "server" "tool" {arg: value}`, `mcp.tools "server"`, `shell.run "cmd"`.
43
+ Conversions: `as json`, `as text`, `as lines`, `as number`.
44
+
45
+ ## Statements
46
+
47
+ | Statement | Meaning |
48
+ | --- | --- |
49
+ | `let x = <expr>` | bind a value |
50
+ | `when <cond>` / `otherwise` | conditional (each block indented) |
51
+ | `each x in <list>` [`parallel N`] | loop |
52
+ | `let x = attempt` … `otherwise` … | fallback when the block fails |
53
+ | `let x = attempt auto` | each indented line is a route, tried best-first by learned success |
54
+ | `let x = together` | run indented lines in parallel, returns a list |
55
+ | `let x = consensus [min K]` | accept a value most indented sources agree on |
56
+ | `refine x with <expr> until <cond> [rounds N]` | re-derive until a check passes |
57
+ | `ensure <cond> else stop "msg"` / `else ask human "msg"` | verify |
58
+ | `ask human "question" -> ok` | approval, binds true/false |
59
+ | `remember "key" = <expr> [keep 7d]`, `recall "key"`, `recall like "query"` | memory |
60
+ | `send console "#channel" "message"` | deliver a message (effect: send) |
61
+ | `log <expr>`, `stop "msg"`, `expect <cond>` (in tests) | output, end, assert |
62
+
63
+ ## Expressions
64
+
65
+ Literals `42`, `"text"`, `true`, `none`, `[1, 2]`, `{a: 1}`; field access `x.a`, `xs.0`;
66
+ `+ - * / < > <= >= == != and or not` (`and`/`or` return an operand).
67
+ Collections: `filter x in xs where …`, `map x in xs to …`, `sort xs by f [desc]`,
68
+ `group xs by f`, `pick lowest price from xs`, `count xs`.
69
+ Reasoning: `attend to xs by "query" [top N]`, `point to "query" in text` (verbatim span
70
+ or `none`), `pairs a from X, b from Y where …`, `simplest of xs`,
71
+ `novelty x [against xs]`, `think "prompt" with data [samples N]`.
72
+
73
+ Strings interpolate pure expressions: `"Total {sum(xs)}"`. String literals and adapter
74
+ calls are not allowed inside `{}`; bind them with `let` first.
75
+
76
+ ## Standard library (pure, no effects)
77
+
78
+ `sum avg min max round abs upper lower trim split join replace contains unique first
79
+ last range keys values now today uuid number`, plus modules `text.*` (regex `find`,
80
+ `find_all`, `sub`, `matches`), `list.*`, `math.*`, `stats.*` (`mean median stdev
81
+ percentile`), `time.*` (`add diff weekday start_of format parse`), `json.*`,
82
+ `csv.parse`/`csv.text`, `crypto.*`, `encode.*`, `schema.check`/`schema.valid`
83
+ (`{age: "int 18..120", email: "email"}`), `template.render`.
84
+ Full list: https://github.com/Ashutosh3142857/lugh-lang/blob/main/docs/STDLIB.md
85
+
86
+ ## Web apps
87
+
88
+ Top-level `route GET "/api/x"` blocks (with `request`, `respond [status] value`) and
89
+ `page "/" title "…"` blocks (`heading`, `text`, `table from`, `stat from`, `form to`,
90
+ `button`, `approvals`). Serve with `lugh app.lugh --serve 8080`.
91
+
92
+ ## Running
93
+
94
+ - Sandbox (no install): `npx lugh-lang run program.lugh` or the MCP tools `lugh_check`,
95
+ `lugh_run`, `lugh_test`. Adapters act on a simulated world; see `lugh_sandbox`.
96
+ - For real: install Lugh Core, then `lugh program.lugh` (asks for approval in the
97
+ terminal), `lugh program.lugh --check` (what it can touch), `lugh plan "<goal>"`.
98
+
99
+ Spec: https://github.com/Ashutosh3142857/lugh-lang/blob/main/docs/SPEC.md
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // lugh-lang: check and dry-run Lugh programs, or serve them to AI agents over MCP.
3
+ import { readFileSync } from "node:fs";
4
+ import { load, failed } from "../lib/runtime.mjs";
5
+
6
+ const HELP = `lugh-lang: Lugh, the programming language for AI agents
7
+
8
+ npx lugh-lang run <file|-> [--decline] run goals in the sandbox, with a policy log
9
+ npx lugh-lang test <file|-> run test blocks
10
+ npx lugh-lang check <file|-> compile only
11
+ npx lugh-lang sandbox what the simulated world contains
12
+ npx lugh-lang mcp MCP server (stdio) for AI agents
13
+
14
+ The sandbox simulates files, an HTTP API and MCP servers, and every call
15
+ passes the real policy gate. To act on real systems, install Lugh Core:
16
+ https://github.com/Ashutosh3142857/lugh-lang`;
17
+
18
+ const [cmd, file, ...rest] = process.argv.slice(2);
19
+ if (!cmd || cmd === "-h" || cmd === "--help") { console.log(HELP); process.exit(cmd ? 0 : 2); }
20
+ if (cmd === "--version" || cmd === "-v") {
21
+ console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
22
+ process.exit(0);
23
+ }
24
+ const run = await load();
25
+ if (cmd === "mcp") {
26
+ const { serve } = await import("../lib/mcp.mjs");
27
+ serve(run);
28
+ } else if (cmd === "sandbox") {
29
+ console.log(run("", "sandbox"));
30
+ } else if (["run", "test", "check"].includes(cmd)) {
31
+ if (!file) { console.error(`usage: npx lugh-lang ${cmd} <file|->`); process.exit(2); }
32
+ const src = readFileSync(file === "-" ? 0 : file, "utf8");
33
+ const out = run(src, cmd, { decline: rest.includes("--decline") });
34
+ console.log(out.trimEnd());
35
+ process.exit(failed(out) ? 1 : 0);
36
+ } else {
37
+ console.error(`unknown command '${cmd}'\n\n${HELP}`);
38
+ process.exit(2);
39
+ }
package/lib/mcp.mjs ADDED
@@ -0,0 +1,121 @@
1
+ // A Model Context Protocol server (stdio, JSON-RPC 2.0) that lets any MCP client
2
+ // write, check and dry-run Lugh programs. Programs run in the sandbox: adapters
3
+ // act on a simulated world behind the real policy gate, so nothing real is touched.
4
+ import { readFileSync } from "node:fs";
5
+ import { createInterface } from "node:readline";
6
+ import { failed } from "./runtime.mjs";
7
+
8
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
9
+ const REFERENCE = readFileSync(new URL("../REFERENCE.md", import.meta.url), "utf8");
10
+ const PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
11
+
12
+ const code = { type: "string", description: "A complete Lugh program, starting with `agent <Name>`." };
13
+ const safe = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
14
+ export const TOOLS = [
15
+ {
16
+ name: "lugh_reference",
17
+ title: "Lugh language reference",
18
+ description: "Syntax and semantics of Lugh, a programming language for AI agents where permissions (policy), budgets and human approval are part of the code. Read this before writing a program.",
19
+ inputSchema: { type: "object", properties: {} },
20
+ annotations: safe,
21
+ },
22
+ {
23
+ name: "lugh_check",
24
+ title: "Check a Lugh program",
25
+ description: "Compile a Lugh program without running it. Reports syntax errors, unknown functions and adapters, and counts goals, tests, routes and pages.",
26
+ inputSchema: { type: "object", properties: { code }, required: ["code"] },
27
+ annotations: safe,
28
+ },
29
+ {
30
+ name: "lugh_run",
31
+ title: "Dry-run a Lugh program in the sandbox",
32
+ description: "Run a Lugh program's goals in a sandbox. fs, http, mcp and shell act on a simulated world (see lugh_sandbox), but every call passes the real policy gate and budgets. Returns the output and a policy log of every action and its decision (allowed, approved, declined, denied). Use it to show a person exactly what an agent would do before it runs for real.",
33
+ inputSchema: {
34
+ type: "object",
35
+ properties: {
36
+ code,
37
+ approvals: { type: "string", enum: ["approve", "decline"], description: "How to answer `ask human` and policy approvals. Default approve." },
38
+ },
39
+ required: ["code"],
40
+ },
41
+ annotations: safe,
42
+ },
43
+ {
44
+ name: "lugh_test",
45
+ title: "Run a Lugh program's tests",
46
+ description: "Run the `test` blocks of a Lugh program in the sandbox and report passes and failures.",
47
+ inputSchema: { type: "object", properties: { code }, required: ["code"] },
48
+ annotations: safe,
49
+ },
50
+ {
51
+ name: "lugh_sandbox",
52
+ title: "Describe the sandbox",
53
+ description: "List the simulated files, HTTP endpoints, MCP servers (with each tool's effect) and shell commands that programs run by lugh_run can use.",
54
+ inputSchema: { type: "object", properties: {} },
55
+ annotations: safe,
56
+ },
57
+ ];
58
+
59
+ function callTool(run, name, args = {}) {
60
+ const need = () => {
61
+ if (typeof args.code !== "string" || !args.code.trim()) throw new Error("`code` is required: a Lugh program starting with `agent <Name>`");
62
+ return args.code;
63
+ };
64
+ switch (name) {
65
+ case "lugh_reference": return { text: REFERENCE, isError: false };
66
+ case "lugh_sandbox": return { text: run("", "sandbox"), isError: false };
67
+ case "lugh_check": { const t = run(need(), "check"); return { text: t, isError: failed(t) }; }
68
+ case "lugh_test": { const t = run(need(), "test"); return { text: t, isError: failed(t) }; }
69
+ case "lugh_run": {
70
+ const t = run(need(), "run", { decline: args.approvals === "decline" });
71
+ // A denial or failed goal is a result to show, not a tool error.
72
+ return { text: t, isError: false };
73
+ }
74
+ default: throw Object.assign(new Error(`Unknown tool: ${name}`), { code: -32602 });
75
+ }
76
+ }
77
+
78
+ /** Handle one JSON-RPC message; returns the response object, or null for notifications. */
79
+ export function handle(run, msg) {
80
+ const reply = result => ({ jsonrpc: "2.0", id: msg.id, result });
81
+ const error = (code, message) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
82
+ if (msg?.jsonrpc !== "2.0" || typeof msg.method !== "string") return error(-32600, "Invalid Request");
83
+ const isNotification = !("id" in msg);
84
+ switch (msg.method) {
85
+ case "initialize": {
86
+ const asked = msg.params?.protocolVersion;
87
+ return reply({
88
+ protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
89
+ capabilities: { tools: { listChanged: false } },
90
+ serverInfo: { name: "lugh", title: "Lugh", version: VERSION },
91
+ instructions: "Lugh is a programming language for AI agents: a program declares what it may touch (use), its limits (budget) and which actions need a human (policy). Call lugh_reference first, write the program, check it with lugh_check, then dry-run it with lugh_run and show the person the policy log before running it for real with the Lugh CLI.",
92
+ });
93
+ }
94
+ case "ping": return isNotification ? null : reply({});
95
+ case "tools/list": return reply({ tools: TOOLS });
96
+ case "tools/call": {
97
+ try {
98
+ const { text, isError } = callTool(run, msg.params?.name, msg.params?.arguments);
99
+ return reply({ content: [{ type: "text", text }], isError });
100
+ } catch (e) {
101
+ if (e.code === -32602) return error(-32602, e.message);
102
+ return reply({ content: [{ type: "text", text: String(e.message || e) }], isError: true });
103
+ }
104
+ }
105
+ default:
106
+ return isNotification ? null : error(-32601, `Method not found: ${msg.method}`);
107
+ }
108
+ }
109
+
110
+ /** Serve over stdio: one JSON-RPC message per line. */
111
+ export function serve(run, input = process.stdin, output = process.stdout) {
112
+ const rl = createInterface({ input, crlfDelay: Infinity });
113
+ rl.on("line", line => {
114
+ if (!line.trim()) return;
115
+ let msg;
116
+ try { msg = JSON.parse(line); } catch { output.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n"); return; }
117
+ const res = Array.isArray(msg) ? msg.map(m => handle(run, m)).filter(Boolean) : handle(run, msg);
118
+ if (res && (!Array.isArray(res) || res.length)) output.write(JSON.stringify(res) + "\n");
119
+ });
120
+ return rl;
121
+ }
@@ -0,0 +1,37 @@
1
+ // Loads Lugh Core (the WebAssembly build) and runs programs in the playground
2
+ // sandbox: adapters act on a simulated world, behind the real policy gate.
3
+ import { readFileSync, existsSync } from "node:fs";
4
+
5
+ const PUBLISHED = "https://ashutosh3142857.github.io/lugh-lang/lugh.wasm";
6
+ const MODES = { run: 0, test: 1, check: 2, sandbox: 3 };
7
+
8
+ async function wasmBytes() {
9
+ const bundled = new URL("../lugh.wasm", import.meta.url);
10
+ if (existsSync(bundled)) return readFileSync(bundled);
11
+ const res = await fetch(PUBLISHED);
12
+ if (!res.ok) throw new Error(`could not download ${PUBLISHED}: HTTP ${res.status}`);
13
+ return new Uint8Array(await res.arrayBuffer());
14
+ }
15
+
16
+ /** Returns run(source, mode = "run" | "test" | "check" | "sandbox", { decline }) → output text. */
17
+ export async function load() {
18
+ const { instance } = await WebAssembly.instantiate(await wasmBytes(), {
19
+ env: { lugh_now_ms: () => Date.now() },
20
+ });
21
+ const w = instance.exports;
22
+ return function run(source, mode = "run", { decline = false } = {}) {
23
+ if (!(mode in MODES)) throw new Error(`unknown mode ${mode}`);
24
+ const input = new TextEncoder().encode(source ?? "");
25
+ const size = Math.max(1, input.length);
26
+ const ptr = w.lugh_alloc(size);
27
+ new Uint8Array(w.memory.buffer, ptr, input.length).set(input);
28
+ const n = w.lugh_run(ptr, input.length, MODES[mode] + (decline ? 4 : 0));
29
+ w.lugh_free(ptr, size);
30
+ return new TextDecoder().decode(new Uint8Array(w.memory.buffer, w.lugh_output_ptr(), n).slice());
31
+ };
32
+ }
33
+
34
+ /** True when the output reports a failed goal, test or compile error. */
35
+ export function failed(output) {
36
+ return /^❌|^\s+✗|\b[1-9]\d* failed\b/m.test(output);
37
+ }
package/lugh.wasm ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "lugh-lang",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.1",
4
+ "description": "Lugh, the programming language for AI agents: check and dry-run programs where policy, budgets and human approval are part of the code. Includes an MCP server.",
5
+ "mcpName": "io.github.Ashutosh3142857/lugh",
6
+ "type": "module",
7
+ "bin": { "lugh-lang": "bin/lugh-lang.mjs" },
8
+ "exports": { ".": "./lib/runtime.mjs", "./mcp": "./lib/mcp.mjs" },
9
+ "files": ["bin/", "lib/", "lugh.wasm", "REFERENCE.md", "README.md"],
10
+ "engines": { "node": ">=18" },
11
+ "scripts": { "test": "node test/mcp.test.mjs" },
12
+ "keywords": ["ai-agents", "agents", "mcp", "model-context-protocol", "mcp-server", "programming-language", "guardrails", "human-in-the-loop", "agent-safety", "policy", "webassembly"],
13
+ "homepage": "https://ashutosh3142857.github.io/lugh-lang/",
14
+ "repository": { "type": "git", "url": "git+https://github.com/Ashutosh3142857/lugh-lang.git", "directory": "npm" },
15
+ "bugs": "https://github.com/Ashutosh3142857/lugh-lang/issues",
16
+ "author": "Ashutosh Pandey",
17
+ "license": "MIT"
18
+ }