rungent 0.0.0-stage → 0.5.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.
Files changed (59) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +183 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +4 -0
  5. package/dist/catalog-Ck2mzpGZ.js +432 -0
  6. package/dist/catalog-DoiuK6y8.d.ts +189 -0
  7. package/dist/catalog.d.ts +6 -0
  8. package/dist/catalog.js +1 -0
  9. package/dist/cli-U5MMs2jE.js +1198 -0
  10. package/dist/cli.d.ts +34 -0
  11. package/dist/cli.js +1 -0
  12. package/dist/client-D8_e0C0N.js +712 -0
  13. package/dist/client.d.ts +2 -0
  14. package/dist/client.js +1 -0
  15. package/dist/delegation-BQmPu1RM.js +180 -0
  16. package/dist/delegation-C3EZxfFY.d.ts +104 -0
  17. package/dist/delegation.d.ts +6 -0
  18. package/dist/delegation.js +1 -0
  19. package/dist/documents-HwF64PZc.js +191 -0
  20. package/dist/documents.d.ts +81 -0
  21. package/dist/documents.js +1 -0
  22. package/dist/driver-DYREymK1.d.ts +17 -0
  23. package/dist/index-CH8FofM1.d.ts +324 -0
  24. package/dist/index-CYJG9ld3.d.ts +416 -0
  25. package/dist/index-Cp8KJF66.d.ts +19 -0
  26. package/dist/index-DtB_N2hi.d.ts +54 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +1 -0
  29. package/dist/knowledge-D7Qa1qEL.js +497 -0
  30. package/dist/knowledge.d.ts +2 -0
  31. package/dist/knowledge.js +1 -0
  32. package/dist/node.d.ts +41 -0
  33. package/dist/node.js +226 -0
  34. package/dist/placeholders-vTBC14bL.js +51 -0
  35. package/dist/postgres-CijIPqDh.js +55 -0
  36. package/dist/protocol-BofydQsK.js +398 -0
  37. package/dist/protocol-C6rJdYiK.d.ts +482 -0
  38. package/dist/protocol.d.ts +6 -0
  39. package/dist/protocol.js +1 -0
  40. package/dist/react.d.ts +377 -0
  41. package/dist/react.js +3644 -0
  42. package/dist/runtime-CJ4hND2v.js +4595 -0
  43. package/dist/search-BYP5MdEb.js +72 -0
  44. package/dist/search-CpF3yp_j.d.ts +86 -0
  45. package/dist/search.d.ts +5 -0
  46. package/dist/search.js +1 -0
  47. package/dist/sql/d1.d.ts +23 -0
  48. package/dist/sql/d1.js +26 -0
  49. package/dist/sql/postgres.d.ts +33 -0
  50. package/dist/sql/postgres.js +1 -0
  51. package/dist/sql/sqlite.d.ts +14 -0
  52. package/dist/sql/sqlite.js +1 -0
  53. package/dist/sql-BeHlZwCm.js +102 -0
  54. package/dist/sql.d.ts +3 -0
  55. package/dist/sql.js +1 -0
  56. package/dist/sqlite-CkmPc5aB.js +51 -0
  57. package/dist/styles.css +1833 -0
  58. package/dist/version-ChyqhO7x.js +4 -0
  59. package/package.json +155 -3
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Rungent Contributors
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
package/README.md CHANGED
@@ -1,3 +1,184 @@
1
- # Temporary Holding Version
1
+ # rungent
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
+ Make your product agent-native from the API you already have. Annotate your OpenAPI 3.1
4
+ operations with `x-rungent`; rungent turns that catalog into an in-app agent that acts as the signed-in
5
+ user, an MCP server, a CLI, `skill.md` and `llms.txt`, federated search with cited answers from
6
+ your docs, and the React UI for all of it.
7
+
8
+ ```bash
9
+ npm install rungent
10
+ ```
11
+
12
+ One package, one subpath per part. Import only what your stack needs; the browser subpaths never
13
+ load Node-only code.
14
+
15
+ | Import | What it is | Runs on |
16
+ | --- | --- | --- |
17
+ | `rungent` | The runtime: `createRungent`, the agent, approvals, forms, MCP, search, the HTTP API, `MemoryStore`, `SqlStore` | Node, Bun, Deno, Workers |
18
+ | `rungent/node` | `serve()`, `nodeHandler(rungent)` for Express and `node:http`, `readSettings(env)` | Node |
19
+ | `rungent/sql` | The `SqlDriver` contract and `migrate` | anywhere |
20
+ | `rungent/sql/postgres`, `/sql/sqlite`, `/sql/d1` | Drivers for Postgres, Node's SQLite and Cloudflare D1 | Node / Workers |
21
+ | `rungent/knowledge` | Your Markdown docs as a cited search source (BM25 + vectors) | anywhere |
22
+ | `rungent/documents` | `renderSkill`, `renderLlmsTxt`, `renderReference`, `toolMeta` | anywhere |
23
+ | `rungent/client` | Typed client of the HTTP API and the AG-UI thread reducer | browser, Node |
24
+ | `rungent/react` | `RungentProvider`, `RungentDock`, `RungentThread`, `ApprovalCard`, `RungentForm`, `SearchPalette`, `HelpViewer`, `ModelSettings` | browser (React 19) |
25
+ | `rungent/react/styles.css` | The components' styles | browser |
26
+ | `rungent/catalog` | `readCatalog`, `findOperation`, the `XRungent` and `Identity` schemas | anywhere |
27
+ | `rungent/delegation` | `signAssertion`, `verifyAssertion`, `checkCall`, `argsHash`, key helpers | anywhere |
28
+ | `rungent/protocol` | The AG-UI profile: interrupts, forms, custom events, host jobs | anywhere |
29
+ | `rungent/search` | `SearchHit`, `PublicHit`, `fuse` | anywhere |
30
+ | `rungent/cli` | `run(argv, options)`: the CLI as a library, for a branded CLI | Node |
31
+
32
+ `react` and `react-dom` are optional peer dependencies, needed only for `./react`. The guides are
33
+ at [rungent.dev](https://rungent.dev); the contract is in
34
+ [`spec/`](https://github.com/rungent/rungent/tree/main/spec).
35
+
36
+ ## Embed it in a JavaScript API
37
+
38
+ ```ts
39
+ import { createRungent, SqlStore } from 'rungent';
40
+ import { importSigningKey } from 'rungent/delegation';
41
+ import { postgresDriver } from 'rungent/sql/postgres';
42
+ import { app } from './api'; // your Hono app, serving /api/openapi.json
43
+
44
+ const rungent = createRungent({
45
+ url: 'https://console.example.com',
46
+ host: { origin: 'https://console.example.com', openapi: '/api/openapi.json', fetch: app.fetch },
47
+ signingKey: await importSigningKey(JSON.parse(process.env.RUNGENT_SIGNING_KEY!)),
48
+ secret: process.env.RUNGENT_SECRET!, // 32+ bytes; seals model API keys at rest
49
+ store: new SqlStore(postgresDriver(process.env.DATABASE_URL!)),
50
+ models: { chain: [{ id: 'main', provider: 'openai', model: 'gpt-5.1', apiKey: process.env.OPENAI_API_KEY }] },
51
+ });
52
+
53
+ for (const path of ['/rungent/v0/*', '/mcp', '/skill.md', '/llms.txt', '/.well-known/rungent-keys.json']) {
54
+ app.all(path, (c) => rungent.fetch(c.req.raw));
55
+ }
56
+ ```
57
+
58
+ `host.fetch` takes any handler from `Request` to `Response | Promise<Response>`, so Hono's
59
+ `app.fetch` fits as it is; without it rungent calls the host over the network. On Cloudflare Workers,
60
+ use `d1Driver(env.DB)` from `rungent/sql/d1` and pass the execution context:
61
+ `rungent.fetch(request, ctx)`. Under Express, mount `nodeHandler(rungent)` from `rungent/node`.
62
+
63
+ Every call rungent makes to your API carries the user's own `Authorization` and `Cookie` and an
64
+ `Rungent-Assertion`, which your API verifies with `verifyAssertion` and `checkCall` from
65
+ `rungent/delegation` ([delegation](https://github.com/rungent/rungent/blob/main/spec/delegation.md)).
66
+
67
+ ## Add the UI
68
+
69
+ ```tsx
70
+ import { createClient } from 'rungent/client';
71
+ import { RungentDock, RungentProvider, SearchPalette } from 'rungent/react';
72
+ import 'rungent/react/styles.css';
73
+
74
+ const client = createClient(); // same origin; the client adds /rungent/v0
75
+
76
+ export function Shell({ children }: { children: React.ReactNode }) {
77
+ return (
78
+ <RungentProvider client={client} onOpen={(path) => router.push(path)}>
79
+ <RungentDock>{children}</RungentDock>
80
+ <SearchPalette />
81
+ </RungentProvider>
82
+ );
83
+ }
84
+ ```
85
+
86
+ ⌘/Ctrl+J toggles the dock and ⌘/Ctrl+K opens search. Theme with the `--rungent-*` CSS variables.
87
+
88
+ ## Run it beside any other stack: `rungent serve`
89
+
90
+ Python, Go or Java hosts run rungent as a server next to their API, configured from the
91
+ environment, with `npx rungent serve` or the image `ghcr.io/rungent/rungent-server`.
92
+
93
+ ```bash
94
+ npx rungent keys generate --kid rungent-1 # prints the public JWK; writes rungent-1.private.jwk (0600)
95
+
96
+ RUNGENT_URL=https://console.example.com \
97
+ RUNGENT_HOST_ORIGIN=https://console.example.com \
98
+ RUNGENT_HOST_BASE_URL=http://api.internal:8000 \
99
+ RUNGENT_SIGNING_KEY="$(cat rungent-1.private.jwk)" \
100
+ RUNGENT_SECRET="$(openssl rand -base64 48)" \
101
+ RUNGENT_DATABASE_URL=postgres://rungent:…@db/rungent \
102
+ RUNGENT_MODELS='[{"id":"main","provider":"openai","model":"gpt-5.1","apiKey":"…"}]' \
103
+ npx rungent serve
104
+ ```
105
+
106
+ Then route `/rungent/`, `/mcp`, `/skill.md`, `/llms.txt` and `/.well-known/rungent-keys.json` on your
107
+ public origin to the server, and pin the public key in your host kit.
108
+
109
+ | Variable | Required | Meaning |
110
+ | --- | --- | --- |
111
+ | `RUNGENT_URL` | yes | Public URL of rungent; the assertion `iss`. |
112
+ | `RUNGENT_HOST_ORIGIN` | yes | Your product's public origin; the assertion `aud`. |
113
+ | `RUNGENT_HOST_BASE_URL` | | Where rungent reaches your API, when that differs from the origin (an internal service URL). |
114
+ | `RUNGENT_HOST_OPENAPI` | | Path or URL of your OpenAPI 3.1 document. Default `/api/openapi.json`. |
115
+ | `RUNGENT_SIGNING_KEY` | yes | Private Ed25519 JWK with `kid` (`rungent keys generate`). |
116
+ | `RUNGENT_HOST_KEYS` | | JSON array of public JWKs your host signs `Rungent-Host-Assertion`s with (deferred-task completions and `POST /rungent/v0/generate`). |
117
+ | `RUNGENT_SECRET` | yes | 32+ bytes; seals stored model API keys. |
118
+ | `RUNGENT_PREVIOUS_SECRET` | | The secret before a rotation: it still unseals saved settings, which are sealed again with `RUNGENT_SECRET` on first read. Remove it afterwards. |
119
+ | `RUNGENT_DATABASE_URL` | yes | `postgres://…` or `sqlite:<path>`. rungent creates its own `rungent_*` tables; give it its own database or schema. |
120
+ | `RUNGENT_MODELS` | | JSON model chain (`id`, `provider` = `openai-compatible`/`openai`/`anthropic`, `model`, `baseURL`, `apiKey`, `vision`, `temperature`, `maxOutputTokens`, `cooldownSeconds` = `{quota, rateLimit, error}`, `providerOptions`). Admins can change it in the app. |
121
+ | `RUNGENT_PRODUCT_NAME`, `RUNGENT_PRODUCT_SUMMARY` | | The product's name and summary in `/skill.md` and `/llms.txt` for signed-out callers, when your OpenAPI needs a sign-in. |
122
+ | `RUNGENT_NAME` | | The assistant's name. Default `Assistant`. |
123
+ | `RUNGENT_INSTRUCTIONS` | | System instructions, or `@path` to a file. |
124
+ | `RUNGENT_SKILL_GUIDE` | | Hand-written guide placed first in `/skill.md`, or `@path`. |
125
+ | `RUNGENT_SKILL_NAME` | | The `/skill.md` frontmatter `name` (a slug). Default: the product's slug, else the first label of the host's hostname. |
126
+ | `RUNGENT_CLI_COMMAND`, `RUNGENT_CLI_PACKAGE`, `RUNGENT_CLI_INSTALL` | | The CLI `/skill.md` and `/llms.txt` name, and how to install it: its npm package, or a free-form install line (which wins). Default `rungent` from `rungent`. |
127
+ | `RUNGENT_KNOWLEDGE_DIR`, `RUNGENT_KNOWLEDGE_BASE_URL` | | A directory of Markdown docs indexed for search and answers, and the URL their pages live under. |
128
+ | `RUNGENT_MCP_INSTRUCTIONS` | | Instructions MCP clients receive on `initialize`, or `@path`. Default: the skill guide. |
129
+ | `RUNGENT_MCP_AUTHORIZATION_SERVERS` | | Comma-separated OAuth issuers for MCP clients. |
130
+ | `RUNGENT_BASE_PATH` | | Prefix of every route when rungent is served below a path. |
131
+ | `RUNGENT_MAX_STEPS` | | Model steps per run. Default 16. |
132
+ | `PORT` | | Default 8080. `GET /healthz` answers `ok`. |
133
+
134
+ The image is built from this package's `Dockerfile`; to build it on your own base image, pass
135
+ `--build-arg BASE_IMAGE=… --build-arg RUNGENT_VERSION=0.4.0`.
136
+
137
+ ## The `rungent` command
138
+
139
+ `rungent` is the command line of every rungent host. Its host commands come from the host's MCP
140
+ tools at run time; the rest are built in.
141
+
142
+ ```bash
143
+ rungent login https://console.example.com # asks for the token; or --token-stdin < token.txt
144
+ rungent tools # every command the host offers you
145
+ rungent tools gpu # the commands matching the words
146
+ rungent search "gpu box" # search everything you can see in the product
147
+ rungent vm stop vm-42 --forced # a host command; writes ask for confirmation (--yes)
148
+ rungent status | logout | --version
149
+ ```
150
+
151
+ | Built-in | |
152
+ | --- | --- |
153
+ | `login`, `logout`, `status`, `tools` | Host access. A host command of the same name wins; `rungent:<name>` always runs the built-in. |
154
+ | `check`, `skill`, `llms`, `reference`, `docs` | Check a catalog and write its documents from `--openapi <file|url>`. |
155
+ | `keys generate --kid <id>` | A new Ed25519 key pair: the public JWK on stdout, the private one in a 0600 file. |
156
+ | `brand --name <cmd>` | An npm package whose bin runs this CLI as your product's command. |
157
+ | `serve` | rungent over HTTP, configured from the environment (above). |
158
+
159
+ The host is `--host`, else `$RUNGENT_HOST`, else the last host logged in to; the token is
160
+ `$RUNGENT_TOKEN`, else the one `login` saved (`~/.config/rungent/hosts.json`, 0600). No command prints
161
+ a token. Output is JSON on stdout; exit codes: 0 ok, 1 tool error, 2 usage, 3 auth, 4 network.
162
+ Every command takes `--help`.
163
+
164
+ A branded CLI is a few lines over `rungent/cli` (`rungent brand` writes them):
165
+
166
+ ```ts
167
+ import { run } from 'rungent/cli';
168
+
169
+ process.exitCode = await run(process.argv.slice(2), {
170
+ program: 'acme',
171
+ host: 'https://console.example.com', // optional preset
172
+ env: { host: 'ACME_HOST', token: 'ACME_TOKEN' },
173
+ });
174
+ ```
175
+
176
+ ## Development
177
+
178
+ ```bash
179
+ pnpm --filter rungent test # unit tests and every conformance case (memory, SQLite)
180
+ RUNGENT_TEST_POSTGRES_URL=postgres://… pnpm --filter rungent test # and on Postgres
181
+ pnpm --filter rungent example # the React components against a fake server
182
+ ```
183
+
184
+ License: Apache-2.0.
package/dist/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { t as run } from "./cli-U5MMs2jE.js";
3
+ // src/cli/bin.ts
4
+ process.exitCode = await run(process.argv.slice(2));
@@ -0,0 +1,432 @@
1
+ import * as z from "zod";
2
+ // src/spec/catalog.ts
3
+ /**
4
+ * The rungent catalog: the `x-rungent` OpenAPI extension and the operations derived from it.
5
+ * See spec/catalog.md.
6
+ */
7
+ const OPERATION_NAME = /^[a-z][a-z0-9_]{0,63}$/;
8
+ const operationName = z.string().regex(OPERATION_NAME);
9
+ const productPath = z.string().regex(/^\/(?!\/)/, "must start with a single /");
10
+ const Effect = z.enum([
11
+ "read",
12
+ "create",
13
+ "update",
14
+ "delete",
15
+ "external"
16
+ ]);
17
+ const Approval = z.enum(["never", "always"]);
18
+ const Surface = z.enum([
19
+ "agent",
20
+ "mcp",
21
+ "cli"
22
+ ]);
23
+ const Role = z.enum([
24
+ "identity",
25
+ "search",
26
+ "form"
27
+ ]);
28
+ const Confirmation = z.strictObject({
29
+ title: z.string().min(1).max(200),
30
+ target: z.string().min(1).max(200).optional(),
31
+ fields: z.array(z.strictObject({
32
+ key: z.string().min(1),
33
+ label: z.string().min(1),
34
+ values: z.record(z.string(), z.string()).optional()
35
+ })).optional(),
36
+ lookup: z.strictObject({
37
+ path: productPath,
38
+ labelPath: z.string().min(1)
39
+ }).optional(),
40
+ risk: z.enum([
41
+ "low",
42
+ "medium",
43
+ "high"
44
+ ]).optional(),
45
+ costHint: z.string().min(1).max(200).optional()
46
+ });
47
+ const Next = z.strictObject({
48
+ op: operationName,
49
+ arguments: z.record(z.string(), z.string().min(1)).optional(),
50
+ argumentsFrom: z.string().min(1).optional(),
51
+ when: z.record(z.string(), z.unknown()).optional()
52
+ });
53
+ const XRungent = z.strictObject({
54
+ name: operationName,
55
+ title: z.string().min(1).max(80).optional(),
56
+ description: z.string().min(1).max(500).optional(),
57
+ effect: Effect.optional(),
58
+ approval: Approval.optional(),
59
+ role: Role.optional(),
60
+ surfaces: z.array(Surface).optional(),
61
+ confirmation: Confirmation.optional(),
62
+ form: operationName.optional(),
63
+ resolve: z.record(z.string(), z.strictObject({
64
+ op: operationName,
65
+ key: z.string().min(1).optional()
66
+ })).optional(),
67
+ next: Next.optional(),
68
+ open: productPath.optional(),
69
+ redact: z.array(z.string().min(1)).optional(),
70
+ repeatable: z.boolean().optional(),
71
+ timeoutSeconds: z.number().positive().max(3600).optional(),
72
+ cli: z.strictObject({
73
+ command: z.string().regex(/^[a-z][a-z0-9-]*( [a-z][a-z0-9-]*)*$/),
74
+ args: z.array(z.string().min(1)).optional()
75
+ }).optional()
76
+ }).meta({
77
+ id: "x-rungent",
78
+ title: "x-rungent",
79
+ description: "rungent operation metadata on an OpenAPI 3.1 operation."
80
+ });
81
+ const Identity = z.object({
82
+ subject: z.string().min(1),
83
+ tenant: z.string().min(1).optional(),
84
+ name: z.string().min(1).optional(),
85
+ locale: z.string().min(2).optional(),
86
+ scopes: z.array(z.string().min(1)).optional()
87
+ }).meta({
88
+ id: "identity",
89
+ title: "Identity",
90
+ description: "Answer of the role: identity operation."
91
+ });
92
+ const ADMIN_SCOPE = "rungent:admin";
93
+ var CatalogError = class extends Error {
94
+ issues;
95
+ constructor(issues) {
96
+ super(`Invalid rungent catalog:\n${issues.map((issue) => ` ${issue.at}: ${issue.message}`).join("\n")}`);
97
+ this.name = "CatalogError";
98
+ this.issues = issues;
99
+ }
100
+ };
101
+ const METHODS = [
102
+ "GET",
103
+ "HEAD",
104
+ "POST",
105
+ "PUT",
106
+ "PATCH",
107
+ "DELETE"
108
+ ];
109
+ const DEFAULT_TIMEOUT_SECONDS = 120;
110
+ /** A search source's timeout: the default, and the most it may ask for. */
111
+ const SEARCH_TIMEOUT_SECONDS = {
112
+ default: 2,
113
+ max: 10
114
+ };
115
+ function isObject(value) {
116
+ return typeof value === "object" && value !== null && !Array.isArray(value);
117
+ }
118
+ function defaultEffect(method) {
119
+ switch (method) {
120
+ case "GET":
121
+ case "HEAD": return "read";
122
+ case "POST": return "create";
123
+ case "PUT":
124
+ case "PATCH": return "update";
125
+ case "DELETE": return "delete";
126
+ }
127
+ }
128
+ function defaultSurfaces(effect, role) {
129
+ if (role) return [];
130
+ return effect === "read" ? [
131
+ "agent",
132
+ "mcp",
133
+ "cli"
134
+ ] : ["agent", "cli"];
135
+ }
136
+ /** Placeholders `{name}` in a template. */
137
+ function placeholders(template) {
138
+ return [...template.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]);
139
+ }
140
+ /**
141
+ * Rewrites `#/components/schemas/X` references to `#/$defs/X` and collects the
142
+ * referenced component schemas, transitively, into `defs`.
143
+ */
144
+ var SchemaRefs = class {
145
+ defs = {};
146
+ components;
147
+ report;
148
+ constructor(doc, report) {
149
+ const components = isObject(doc.components) ? doc.components : {};
150
+ this.components = isObject(components.schemas) ? components.schemas : {};
151
+ this.report = report;
152
+ }
153
+ rewrite(schema) {
154
+ if (Array.isArray(schema)) return schema.map((item) => this.rewrite(item));
155
+ if (!isObject(schema)) return schema;
156
+ const out = {};
157
+ for (const [key, value] of Object.entries(schema)) out[key] = key === "$ref" && typeof value === "string" ? this.ref(value) : this.rewrite(value);
158
+ return out;
159
+ }
160
+ /** The component a top-level `$ref` points at, for inspecting a body's shape. */
161
+ target(schema) {
162
+ if (isObject(schema) && typeof schema.$ref === "string") {
163
+ const name = schema.$ref.replace("#/components/schemas/", "");
164
+ return this.components[name];
165
+ }
166
+ return schema;
167
+ }
168
+ ref(ref) {
169
+ if (!ref.startsWith("#/components/schemas/")) {
170
+ this.report(`unsupported $ref ${ref}`);
171
+ return ref;
172
+ }
173
+ const name = ref.slice(21);
174
+ if (!(name in this.defs)) {
175
+ const component = this.components[name];
176
+ if (component === void 0) this.report(`$ref ${ref} names no component schema`);
177
+ else {
178
+ this.defs[name] = true;
179
+ this.defs[name] = this.rewrite(component);
180
+ }
181
+ }
182
+ return `#/$defs/${name}`;
183
+ }
184
+ };
185
+ function resolveComponent(doc, value, kind) {
186
+ if (!isObject(value) || typeof value.$ref !== "string") return value;
187
+ const prefix = `#/components/${kind}/`;
188
+ if (!value.$ref.startsWith(prefix)) return void 0;
189
+ const components = isObject(doc.components) ? doc.components : {};
190
+ return (isObject(components[kind]) ? components[kind] : {})[value.$ref.slice(prefix.length)];
191
+ }
192
+ function buildInput(doc, pathItem, operation, report) {
193
+ const refs = new SchemaRefs(doc, report);
194
+ const properties = {};
195
+ const required = [];
196
+ const bindings = {};
197
+ const add = (name, schema, binding, isRequired) => {
198
+ if (name in bindings) {
199
+ report(`input "${name}" is bound twice (${bindings[name]} and ${binding})`);
200
+ return;
201
+ }
202
+ bindings[name] = binding;
203
+ properties[name] = refs.rewrite(schema ?? {});
204
+ if (isRequired) required.push(name);
205
+ };
206
+ const parameters = /* @__PURE__ */ new Map();
207
+ for (const raw of [...Array.isArray(pathItem.parameters) ? pathItem.parameters : [], ...Array.isArray(operation.parameters) ? operation.parameters : []]) {
208
+ const parameter = resolveComponent(doc, raw, "parameters");
209
+ if (!isObject(parameter) || typeof parameter.name !== "string") {
210
+ report("unresolvable parameter");
211
+ continue;
212
+ }
213
+ parameters.set(`${parameter.in}:${parameter.name}`, parameter);
214
+ }
215
+ for (const parameter of parameters.values()) {
216
+ const name = parameter.name;
217
+ if (parameter.in === "path" || parameter.in === "query") {
218
+ const schema = isObject(parameter.schema) ? { ...parameter.schema } : {};
219
+ if (typeof parameter.description === "string" && schema.description === void 0) schema.description = parameter.description;
220
+ add(name, schema, parameter.in, parameter.in === "path" || parameter.required === true);
221
+ } else if (parameter.required === true) report(`required ${String(parameter.in)} parameter "${name}" is not supported`);
222
+ }
223
+ let body = "none";
224
+ const requestBody = resolveComponent(doc, operation.requestBody, "requestBodies");
225
+ if (operation.requestBody !== void 0) {
226
+ const json = (isObject(requestBody) && isObject(requestBody.content) ? requestBody.content : {})["application/json"];
227
+ if (!isObject(json)) report("request body must be application/json");
228
+ else {
229
+ const bodyRequired = isObject(requestBody) && requestBody.required === true;
230
+ const shape = refs.target(json.schema);
231
+ if (isObject(shape) && shape.type === "object" && isObject(shape.properties) && shape.oneOf === void 0 && shape.anyOf === void 0 && shape.allOf === void 0) {
232
+ body = "fields";
233
+ const fieldsRequired = Array.isArray(shape.required) ? shape.required : [];
234
+ for (const [name, schema] of Object.entries(shape.properties)) add(name, schema, "body", bodyRequired && fieldsRequired.includes(name));
235
+ } else {
236
+ body = "value";
237
+ add("body", json.schema, "body", bodyRequired);
238
+ }
239
+ }
240
+ }
241
+ const input = {
242
+ type: "object",
243
+ properties,
244
+ required
245
+ };
246
+ if (Object.keys(refs.defs).length > 0) input.$defs = refs.defs;
247
+ return {
248
+ input,
249
+ bindings,
250
+ body
251
+ };
252
+ }
253
+ function zodIssues(error) {
254
+ return error.issues.map((issue) => {
255
+ return `${issue.path.length > 0 ? `x-rungent.${issue.path.join(".")}: ` : "x-rungent: "}${issue.message}`;
256
+ });
257
+ }
258
+ function checkRole(op, report) {
259
+ const properties = op.input.properties;
260
+ switch (op.role) {
261
+ case "identity":
262
+ if (op.method !== "GET") report("identity operations must be GET");
263
+ if (Object.keys(properties).length > 0) report("identity operations take no input");
264
+ break;
265
+ case "search":
266
+ if (op.method !== "GET") report("search operations must be GET");
267
+ if (op.bindings.q !== "query" || !op.input.required.includes("q")) report("search operations need a required query parameter \"q\"");
268
+ if (op.timeoutSeconds > SEARCH_TIMEOUT_SECONDS.max) report(`search operations take timeoutSeconds ≤ ${SEARCH_TIMEOUT_SECONDS.max}`);
269
+ break;
270
+ case "form":
271
+ if (op.method !== "POST") report("form operations must be POST");
272
+ if (op.approval !== "never") report("form operations must have approval: never");
273
+ break;
274
+ case void 0:
275
+ }
276
+ if (op.role && op.effect !== "read") report(`${op.role} operations must have effect: read`);
277
+ }
278
+ function readOperation(doc, pathItem, path, method, operation, report) {
279
+ const parsed = XRungent.safeParse(operation["x-rungent"]);
280
+ if (!parsed.success) {
281
+ for (const message of zodIssues(parsed.error)) report(message);
282
+ return;
283
+ }
284
+ const meta = parsed.data;
285
+ const summary = typeof operation.summary === "string" ? operation.summary.trim() : "";
286
+ const effect = meta.effect ?? (meta.role ? "read" : defaultEffect(method));
287
+ if ((method === "GET" || method === "HEAD") && effect !== "read") report(`${method} operations must have effect: read`);
288
+ if (meta.role && meta.surfaces && meta.surfaces.length > 0) report("role operations have no surfaces");
289
+ const { input, bindings, body } = buildInput(doc, pathItem, operation, report);
290
+ const title = meta.title ?? (summary || meta.name);
291
+ const op = {
292
+ name: meta.name,
293
+ title,
294
+ description: (meta.description ?? summary) || title,
295
+ method,
296
+ path,
297
+ effect,
298
+ approval: meta.approval ?? (effect === "read" ? "never" : "always"),
299
+ ...meta.role ? { role: meta.role } : {},
300
+ surfaces: meta.surfaces ?? defaultSurfaces(effect, meta.role),
301
+ input,
302
+ bindings,
303
+ body,
304
+ ...meta.confirmation ? { confirmation: meta.confirmation } : {},
305
+ ...meta.form ? { form: meta.form } : {},
306
+ ...meta.resolve ? { resolve: Object.fromEntries(Object.entries(meta.resolve).map(([arg, ref]) => [arg, {
307
+ op: ref.op,
308
+ key: ref.key ?? "id"
309
+ }])) } : {},
310
+ ...meta.next ? { next: meta.next } : {},
311
+ ...meta.open ? { open: meta.open } : {},
312
+ redact: meta.redact ?? [],
313
+ repeatable: meta.repeatable ?? false,
314
+ timeoutSeconds: meta.timeoutSeconds ?? (meta.role === "search" ? SEARCH_TIMEOUT_SECONDS.default : DEFAULT_TIMEOUT_SECONDS),
315
+ cli: {
316
+ command: meta.cli?.command ?? meta.name.replaceAll("_", "-"),
317
+ args: meta.cli?.args ?? []
318
+ }
319
+ };
320
+ checkRole(op, report);
321
+ for (const arg of op.cli.args) if (!(arg in bindings)) report(`cli argument "${arg}" is not an input`);
322
+ for (const arg of Object.keys(op.resolve ?? {})) if (!(arg in bindings)) report(`resolve argument "${arg}" is not an input`);
323
+ if (op.confirmation) {
324
+ const templates = [
325
+ op.confirmation.title,
326
+ op.confirmation.target,
327
+ op.confirmation.lookup?.path
328
+ ];
329
+ for (const template of templates) for (const name of placeholders(template ?? "")) if (name !== "resource_name" && !(name in bindings)) report(`confirmation placeholder {${name}} is not an input`);
330
+ if (op.confirmation.lookup && !op.confirmation.title.includes("{resource_name}")) report("a confirmation lookup needs {resource_name} in the title");
331
+ }
332
+ return op;
333
+ }
334
+ function templateKey(path) {
335
+ return path.replace(/\{[^{}]+\}/g, "{}");
336
+ }
337
+ /**
338
+ * The operation serving a method and a path. The path may be a template
339
+ * (`/api/vm/{id}`) or concrete (`/api/vm/vm-42`); a query string is ignored.
340
+ * Literal segments win over parameters, so `/api/vm/search` beats `/api/vm/{id}`.
341
+ */
342
+ function findOperation(ops, method, path) {
343
+ const bare = path.split("?")[0];
344
+ const key = templateKey(bare);
345
+ const segments = bare.split("/");
346
+ let best;
347
+ for (const op of ops) {
348
+ if (op.method !== method.toUpperCase()) continue;
349
+ if (templateKey(op.path) === key) return op;
350
+ const pattern = op.path.split("/");
351
+ if (pattern.length !== segments.length) continue;
352
+ let literals = 0;
353
+ if (pattern.every((part, i) => {
354
+ if (/^\{[^{}]+\}$/.test(part)) return true;
355
+ literals += 1;
356
+ return part === segments[i];
357
+ }) && (!best || literals > best.literals)) best = {
358
+ op,
359
+ literals
360
+ };
361
+ }
362
+ return best?.op;
363
+ }
364
+ function checkReferences(ops, issues) {
365
+ const byName = /* @__PURE__ */ new Map();
366
+ for (const op of ops) {
367
+ if (byName.has(op.name)) issues.push({
368
+ at: op.name,
369
+ message: "duplicate operation name"
370
+ });
371
+ byName.set(op.name, op);
372
+ }
373
+ for (const op of ops) {
374
+ const report = (message) => issues.push({
375
+ at: op.name,
376
+ message
377
+ });
378
+ if (op.form) {
379
+ if (byName.get(op.form)?.role !== "form") report(`form "${op.form}" is not a role: form operation`);
380
+ }
381
+ for (const [arg, ref] of Object.entries(op.resolve ?? {})) {
382
+ const list = byName.get(ref.op);
383
+ if (!list || list.role || list.effect !== "read") report(`resolve "${arg}" needs a read operation, got "${ref.op}"`);
384
+ }
385
+ if (op.next) {
386
+ const next = byName.get(op.next.op);
387
+ if (!next || next.role) report(`next "${op.next.op}" is not a catalog operation`);
388
+ }
389
+ const lookup = op.confirmation?.lookup;
390
+ if (lookup && !findOperation(ops, "GET", lookup.path)) report(`confirmation lookup ${lookup.path} is not served by a GET operation`);
391
+ }
392
+ const identities = ops.filter((op) => op.role === "identity");
393
+ if (identities.length !== 1) issues.push({
394
+ at: "catalog",
395
+ message: `exactly one role: identity operation is required, found ${identities.length}`
396
+ });
397
+ }
398
+ /**
399
+ * Reads the rungent catalog from an OpenAPI 3.1 document. Only operations with an
400
+ * `x-rungent` object are included. Throws a CatalogError listing every problem.
401
+ */
402
+ function readCatalog(document) {
403
+ const issues = [];
404
+ if (!isObject(document) || typeof document.openapi !== "string") throw new CatalogError([{
405
+ at: "document",
406
+ message: "not an OpenAPI document"
407
+ }]);
408
+ if (!document.openapi.startsWith("3.1.")) throw new CatalogError([{
409
+ at: "document",
410
+ message: `OpenAPI 3.1 is required, got ${document.openapi}`
411
+ }]);
412
+ const ops = [];
413
+ const paths = isObject(document.paths) ? document.paths : {};
414
+ for (const [path, pathItem] of Object.entries(paths)) {
415
+ if (!isObject(pathItem)) continue;
416
+ for (const method of METHODS) {
417
+ const operation = pathItem[method.toLowerCase()];
418
+ if (!isObject(operation) || operation["x-rungent"] === void 0) continue;
419
+ const at = `${method} ${path}`;
420
+ const report = (message) => issues.push({
421
+ at,
422
+ message
423
+ });
424
+ const op = readOperation(document, pathItem, path, method, operation, report);
425
+ if (op) ops.push(op);
426
+ }
427
+ }
428
+ checkReferences(ops, issues);
429
+ if (issues.length > 0) throw new CatalogError(issues);
430
+ return ops;
431
+ }
432
+ export { Effect as a, OPERATION_NAME as c, Surface as d, XRungent as f, Confirmation as i, Role as l, readCatalog as m, Approval as n, Identity as o, findOperation as p, CatalogError as r, Next as s, ADMIN_SCOPE as t, SEARCH_TIMEOUT_SECONDS as u };