@aidy-dev/spec 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 Aidy 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,26 @@
1
- # Temporary Holding Version
1
+ # @aidy-dev/spec
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
+ aidy's language-neutral contract, in TypeScript. The prose spec is in
4
+ [`spec/`](https://github.com/aidy-dev/aidy/tree/main/spec).
5
+
6
+ | Import | What it gives you |
7
+ | --- | --- |
8
+ | `@aidy-dev/spec/catalog` | `readCatalog(openapi)`, which turns an OpenAPI 3.1 document into aidy operations or a `CatalogError` listing every problem. Also `findOperation`, and the zod schemas `XAidy` and `Identity`. |
9
+ | `@aidy-dev/spec/delegation` | `signAssertion`, `verifyAssertion`, `checkCall`, `argsHash`, `canonicalJson`, `generateKeyPair`, `importPublicKeys`. |
10
+ | `@aidy-dev/spec/search` | `SearchHit`, `SearchResponse`, `fuse` (reciprocal rank fusion). |
11
+ | `@aidy-dev/spec/protocol` | The AG-UI profile: interrupt metadata, `Form`, `checkAnswers`, `formResponseSchema`, custom events. |
12
+
13
+ A TypeScript host verifies aidy's calls like this:
14
+
15
+ ```ts
16
+ import { checkCall, importPublicKeys, verifyAssertion } from '@aidy-dev/spec/delegation';
17
+
18
+ const keys = await importPublicKeys([AIDY_PUBLIC_JWK]);
19
+ const claims = await verifyAssertion(request.headers.get('aidy-assertion')!, {
20
+ keys,
21
+ audience: 'https://console.example.com',
22
+ request: { method: request.method, url: publicUrl, body: rawBody },
23
+ remember: (jti, exp) => replayCache.add(jti, exp),
24
+ });
25
+ checkCall(claims, { subject: user.id, op: operation.name, approval: operation.approval });
26
+ ```
@@ -0,0 +1,187 @@
1
+ /**
2
+ * The aidy catalog: the `x-aidy` OpenAPI extension and the operations derived from it.
3
+ * See spec/catalog.md.
4
+ */
5
+ import * as z from "zod";
6
+ export declare const OPERATION_NAME: RegExp;
7
+ export declare const Effect: z.ZodEnum<{
8
+ create: "create";
9
+ delete: "delete";
10
+ external: "external";
11
+ read: "read";
12
+ update: "update";
13
+ }>;
14
+ export type Effect = z.infer<typeof Effect>;
15
+ export declare const Approval: z.ZodEnum<{
16
+ always: "always";
17
+ never: "never";
18
+ }>;
19
+ export type Approval = z.infer<typeof Approval>;
20
+ export declare const Surface: z.ZodEnum<{
21
+ agent: "agent";
22
+ cli: "cli";
23
+ mcp: "mcp";
24
+ }>;
25
+ export type Surface = z.infer<typeof Surface>;
26
+ export declare const Role: z.ZodEnum<{
27
+ form: "form";
28
+ identity: "identity";
29
+ search: "search";
30
+ }>;
31
+ export type Role = z.infer<typeof Role>;
32
+ export declare const Confirmation: z.ZodObject<{
33
+ title: z.ZodString;
34
+ target: z.ZodOptional<z.ZodString>;
35
+ fields: z.ZodOptional<z.ZodArray<z.ZodObject<{
36
+ key: z.ZodString;
37
+ label: z.ZodString;
38
+ values: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
39
+ }, z.core.$strict>>>;
40
+ lookup: z.ZodOptional<z.ZodObject<{
41
+ path: z.ZodString;
42
+ labelPath: z.ZodString;
43
+ }, z.core.$strict>>;
44
+ risk: z.ZodOptional<z.ZodEnum<{
45
+ high: "high";
46
+ low: "low";
47
+ medium: "medium";
48
+ }>>;
49
+ costHint: z.ZodOptional<z.ZodString>;
50
+ }, z.core.$strict>;
51
+ export type Confirmation = z.infer<typeof Confirmation>;
52
+ export declare const Next: z.ZodObject<{
53
+ op: z.ZodString;
54
+ arguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
55
+ argumentsFrom: z.ZodOptional<z.ZodString>;
56
+ when: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
57
+ }, z.core.$strict>;
58
+ export type Next = z.infer<typeof Next>;
59
+ export declare const XAidy: z.ZodObject<{
60
+ name: z.ZodString;
61
+ title: z.ZodOptional<z.ZodString>;
62
+ description: z.ZodOptional<z.ZodString>;
63
+ effect: z.ZodOptional<z.ZodEnum<{
64
+ create: "create";
65
+ delete: "delete";
66
+ external: "external";
67
+ read: "read";
68
+ update: "update";
69
+ }>>;
70
+ approval: z.ZodOptional<z.ZodEnum<{
71
+ always: "always";
72
+ never: "never";
73
+ }>>;
74
+ role: z.ZodOptional<z.ZodEnum<{
75
+ form: "form";
76
+ identity: "identity";
77
+ search: "search";
78
+ }>>;
79
+ surfaces: z.ZodOptional<z.ZodArray<z.ZodEnum<{
80
+ agent: "agent";
81
+ cli: "cli";
82
+ mcp: "mcp";
83
+ }>>>;
84
+ confirmation: z.ZodOptional<z.ZodObject<{
85
+ title: z.ZodString;
86
+ target: z.ZodOptional<z.ZodString>;
87
+ fields: z.ZodOptional<z.ZodArray<z.ZodObject<{
88
+ key: z.ZodString;
89
+ label: z.ZodString;
90
+ values: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
91
+ }, z.core.$strict>>>;
92
+ lookup: z.ZodOptional<z.ZodObject<{
93
+ path: z.ZodString;
94
+ labelPath: z.ZodString;
95
+ }, z.core.$strict>>;
96
+ risk: z.ZodOptional<z.ZodEnum<{
97
+ high: "high";
98
+ low: "low";
99
+ medium: "medium";
100
+ }>>;
101
+ costHint: z.ZodOptional<z.ZodString>;
102
+ }, z.core.$strict>>;
103
+ form: z.ZodOptional<z.ZodString>;
104
+ resolve: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
105
+ op: z.ZodString;
106
+ key: z.ZodOptional<z.ZodString>;
107
+ }, z.core.$strict>>>;
108
+ next: z.ZodOptional<z.ZodObject<{
109
+ op: z.ZodString;
110
+ arguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
111
+ argumentsFrom: z.ZodOptional<z.ZodString>;
112
+ when: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
113
+ }, z.core.$strict>>;
114
+ open: z.ZodOptional<z.ZodString>;
115
+ redact: z.ZodOptional<z.ZodArray<z.ZodString>>;
116
+ repeatable: z.ZodOptional<z.ZodBoolean>;
117
+ timeoutSeconds: z.ZodOptional<z.ZodNumber>;
118
+ cli: z.ZodOptional<z.ZodObject<{
119
+ command: z.ZodString;
120
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
121
+ }, z.core.$strict>>;
122
+ }, z.core.$strict>;
123
+ export type XAidy = z.infer<typeof XAidy>;
124
+ export declare const Identity: z.ZodObject<{
125
+ subject: z.ZodString;
126
+ tenant: z.ZodOptional<z.ZodString>;
127
+ name: z.ZodOptional<z.ZodString>;
128
+ locale: z.ZodOptional<z.ZodString>;
129
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
130
+ }, z.core.$strip>;
131
+ export type Identity = z.infer<typeof Identity>;
132
+ export declare const ADMIN_SCOPE = "aidy:admin";
133
+ export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
134
+ export type JsonSchema = Record<string, unknown>;
135
+ /** Where an input property goes in the HTTP request. */
136
+ export type Binding = 'path' | 'query' | 'body';
137
+ export interface Operation {
138
+ readonly name: string;
139
+ readonly title: string;
140
+ readonly description: string;
141
+ readonly method: HttpMethod;
142
+ readonly path: string;
143
+ readonly effect: Effect;
144
+ readonly approval: Approval;
145
+ readonly role?: Role;
146
+ readonly surfaces: readonly Surface[];
147
+ /** JSON Schema of the flattened input: path, query and body fields as top-level properties. */
148
+ readonly input: JsonSchema;
149
+ readonly bindings: Readonly<Record<string, Binding>>;
150
+ /** `fields`: the body is the object of all body-bound properties; `value`: the `body` property. */
151
+ readonly body: 'fields' | 'value' | 'none';
152
+ readonly confirmation?: Confirmation;
153
+ readonly form?: string;
154
+ readonly resolve?: Readonly<Record<string, {
155
+ readonly op: string;
156
+ readonly key: string;
157
+ }>>;
158
+ readonly next?: Next;
159
+ readonly open?: string;
160
+ readonly redact: readonly string[];
161
+ readonly repeatable: boolean;
162
+ readonly timeoutSeconds: number;
163
+ readonly cli: {
164
+ readonly command: string;
165
+ readonly args: readonly string[];
166
+ };
167
+ }
168
+ export interface CatalogIssue {
169
+ /** `METHOD /path` or the operation name. */
170
+ readonly at: string;
171
+ readonly message: string;
172
+ }
173
+ export declare class CatalogError extends Error {
174
+ readonly issues: readonly CatalogIssue[];
175
+ constructor(issues: readonly CatalogIssue[]);
176
+ }
177
+ /**
178
+ * The operation serving a method and a path. The path may be a template
179
+ * (`/api/vm/{id}`) or concrete (`/api/vm/vm-42`); a query string is ignored.
180
+ * Literal segments win over parameters, so `/api/vm/search` beats `/api/vm/{id}`.
181
+ */
182
+ export declare function findOperation(ops: readonly Operation[], method: string, path: string): Operation | undefined;
183
+ /**
184
+ * Reads the aidy catalog from an OpenAPI 3.1 document. Only operations with an
185
+ * `x-aidy` object are included. Throws a CatalogError listing every problem.
186
+ */
187
+ export declare function readCatalog(document: unknown): Operation[];
@@ -0,0 +1,426 @@
1
+ import * as z from "zod";
2
+ // src/catalog.ts
3
+ /**
4
+ * The aidy catalog: the `x-aidy` 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 XAidy = 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-aidy",
78
+ title: "x-aidy",
79
+ description: "aidy 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 = "aidy:admin";
93
+ var CatalogError = class extends Error {
94
+ issues;
95
+ constructor(issues) {
96
+ super(`Invalid aidy 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
+ function isObject(value) {
111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
112
+ }
113
+ function defaultEffect(method) {
114
+ switch (method) {
115
+ case "GET":
116
+ case "HEAD": return "read";
117
+ case "POST": return "create";
118
+ case "PUT":
119
+ case "PATCH": return "update";
120
+ case "DELETE": return "delete";
121
+ }
122
+ }
123
+ function defaultSurfaces(effect, role) {
124
+ if (role) return [];
125
+ return effect === "read" ? [
126
+ "agent",
127
+ "mcp",
128
+ "cli"
129
+ ] : ["agent", "cli"];
130
+ }
131
+ /** Placeholders `{name}` in a template. */
132
+ function placeholders(template) {
133
+ return [...template.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]);
134
+ }
135
+ /**
136
+ * Rewrites `#/components/schemas/X` references to `#/$defs/X` and collects the
137
+ * referenced component schemas, transitively, into `defs`.
138
+ */
139
+ var SchemaRefs = class {
140
+ defs = {};
141
+ components;
142
+ report;
143
+ constructor(doc, report) {
144
+ const components = isObject(doc.components) ? doc.components : {};
145
+ this.components = isObject(components.schemas) ? components.schemas : {};
146
+ this.report = report;
147
+ }
148
+ rewrite(schema) {
149
+ if (Array.isArray(schema)) return schema.map((item) => this.rewrite(item));
150
+ if (!isObject(schema)) return schema;
151
+ const out = {};
152
+ for (const [key, value] of Object.entries(schema)) out[key] = key === "$ref" && typeof value === "string" ? this.ref(value) : this.rewrite(value);
153
+ return out;
154
+ }
155
+ /** The component a top-level `$ref` points at, for inspecting a body's shape. */
156
+ target(schema) {
157
+ if (isObject(schema) && typeof schema.$ref === "string") {
158
+ const name = schema.$ref.replace("#/components/schemas/", "");
159
+ return this.components[name];
160
+ }
161
+ return schema;
162
+ }
163
+ ref(ref) {
164
+ if (!ref.startsWith("#/components/schemas/")) {
165
+ this.report(`unsupported $ref ${ref}`);
166
+ return ref;
167
+ }
168
+ const name = ref.slice(21);
169
+ if (!(name in this.defs)) {
170
+ const component = this.components[name];
171
+ if (component === void 0) this.report(`$ref ${ref} names no component schema`);
172
+ else {
173
+ this.defs[name] = true;
174
+ this.defs[name] = this.rewrite(component);
175
+ }
176
+ }
177
+ return `#/$defs/${name}`;
178
+ }
179
+ };
180
+ function resolveComponent(doc, value, kind) {
181
+ if (!isObject(value) || typeof value.$ref !== "string") return value;
182
+ const prefix = `#/components/${kind}/`;
183
+ if (!value.$ref.startsWith(prefix)) return void 0;
184
+ const components = isObject(doc.components) ? doc.components : {};
185
+ return (isObject(components[kind]) ? components[kind] : {})[value.$ref.slice(prefix.length)];
186
+ }
187
+ function buildInput(doc, pathItem, operation, report) {
188
+ const refs = new SchemaRefs(doc, report);
189
+ const properties = {};
190
+ const required = [];
191
+ const bindings = {};
192
+ const add = (name, schema, binding, isRequired) => {
193
+ if (name in bindings) {
194
+ report(`input "${name}" is bound twice (${bindings[name]} and ${binding})`);
195
+ return;
196
+ }
197
+ bindings[name] = binding;
198
+ properties[name] = refs.rewrite(schema ?? {});
199
+ if (isRequired) required.push(name);
200
+ };
201
+ const parameters = /* @__PURE__ */ new Map();
202
+ for (const raw of [...Array.isArray(pathItem.parameters) ? pathItem.parameters : [], ...Array.isArray(operation.parameters) ? operation.parameters : []]) {
203
+ const parameter = resolveComponent(doc, raw, "parameters");
204
+ if (!isObject(parameter) || typeof parameter.name !== "string") {
205
+ report("unresolvable parameter");
206
+ continue;
207
+ }
208
+ parameters.set(`${parameter.in}:${parameter.name}`, parameter);
209
+ }
210
+ for (const parameter of parameters.values()) {
211
+ const name = parameter.name;
212
+ if (parameter.in === "path" || parameter.in === "query") {
213
+ const schema = isObject(parameter.schema) ? { ...parameter.schema } : {};
214
+ if (typeof parameter.description === "string" && schema.description === void 0) schema.description = parameter.description;
215
+ add(name, schema, parameter.in, parameter.in === "path" || parameter.required === true);
216
+ } else if (parameter.required === true) report(`required ${String(parameter.in)} parameter "${name}" is not supported`);
217
+ }
218
+ let body = "none";
219
+ const requestBody = resolveComponent(doc, operation.requestBody, "requestBodies");
220
+ if (operation.requestBody !== void 0) {
221
+ const json = (isObject(requestBody) && isObject(requestBody.content) ? requestBody.content : {})["application/json"];
222
+ if (!isObject(json)) report("request body must be application/json");
223
+ else {
224
+ const bodyRequired = isObject(requestBody) && requestBody.required === true;
225
+ const shape = refs.target(json.schema);
226
+ if (isObject(shape) && shape.type === "object" && isObject(shape.properties) && shape.oneOf === void 0 && shape.anyOf === void 0 && shape.allOf === void 0) {
227
+ body = "fields";
228
+ const fieldsRequired = Array.isArray(shape.required) ? shape.required : [];
229
+ for (const [name, schema] of Object.entries(shape.properties)) add(name, schema, "body", bodyRequired && fieldsRequired.includes(name));
230
+ } else {
231
+ body = "value";
232
+ add("body", json.schema, "body", bodyRequired);
233
+ }
234
+ }
235
+ }
236
+ const input = {
237
+ type: "object",
238
+ properties,
239
+ required
240
+ };
241
+ if (Object.keys(refs.defs).length > 0) input.$defs = refs.defs;
242
+ return {
243
+ input,
244
+ bindings,
245
+ body
246
+ };
247
+ }
248
+ function zodIssues(error) {
249
+ return error.issues.map((issue) => {
250
+ return `${issue.path.length > 0 ? `x-aidy.${issue.path.join(".")}: ` : "x-aidy: "}${issue.message}`;
251
+ });
252
+ }
253
+ function checkRole(op, report) {
254
+ const properties = op.input.properties;
255
+ switch (op.role) {
256
+ case "identity":
257
+ if (op.method !== "GET") report("identity operations must be GET");
258
+ if (Object.keys(properties).length > 0) report("identity operations take no input");
259
+ break;
260
+ case "search":
261
+ if (op.method !== "GET") report("search operations must be GET");
262
+ if (op.bindings.q !== "query" || !op.input.required.includes("q")) report("search operations need a required query parameter \"q\"");
263
+ break;
264
+ case "form":
265
+ if (op.method !== "POST") report("form operations must be POST");
266
+ if (op.approval !== "never") report("form operations must have approval: never");
267
+ break;
268
+ case void 0:
269
+ }
270
+ if (op.role && op.effect !== "read") report(`${op.role} operations must have effect: read`);
271
+ }
272
+ function readOperation(doc, pathItem, path, method, operation, report) {
273
+ const parsed = XAidy.safeParse(operation["x-aidy"]);
274
+ if (!parsed.success) {
275
+ for (const message of zodIssues(parsed.error)) report(message);
276
+ return;
277
+ }
278
+ const meta = parsed.data;
279
+ const summary = typeof operation.summary === "string" ? operation.summary.trim() : "";
280
+ const effect = meta.effect ?? defaultEffect(method);
281
+ if ((method === "GET" || method === "HEAD") && effect !== "read") report(`${method} operations must have effect: read`);
282
+ if (meta.role && meta.surfaces && meta.surfaces.length > 0) report("role operations have no surfaces");
283
+ const { input, bindings, body } = buildInput(doc, pathItem, operation, report);
284
+ const title = meta.title ?? (summary || meta.name);
285
+ const op = {
286
+ name: meta.name,
287
+ title,
288
+ description: (meta.description ?? summary) || title,
289
+ method,
290
+ path,
291
+ effect,
292
+ approval: meta.approval ?? (effect === "read" ? "never" : "always"),
293
+ ...meta.role ? { role: meta.role } : {},
294
+ surfaces: meta.surfaces ?? defaultSurfaces(effect, meta.role),
295
+ input,
296
+ bindings,
297
+ body,
298
+ ...meta.confirmation ? { confirmation: meta.confirmation } : {},
299
+ ...meta.form ? { form: meta.form } : {},
300
+ ...meta.resolve ? { resolve: Object.fromEntries(Object.entries(meta.resolve).map(([arg, ref]) => [arg, {
301
+ op: ref.op,
302
+ key: ref.key ?? "id"
303
+ }])) } : {},
304
+ ...meta.next ? { next: meta.next } : {},
305
+ ...meta.open ? { open: meta.open } : {},
306
+ redact: meta.redact ?? [],
307
+ repeatable: meta.repeatable ?? false,
308
+ timeoutSeconds: meta.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,
309
+ cli: {
310
+ command: meta.cli?.command ?? meta.name.replaceAll("_", "-"),
311
+ args: meta.cli?.args ?? []
312
+ }
313
+ };
314
+ checkRole(op, report);
315
+ for (const arg of op.cli.args) if (!(arg in bindings)) report(`cli argument "${arg}" is not an input`);
316
+ for (const arg of Object.keys(op.resolve ?? {})) if (!(arg in bindings)) report(`resolve argument "${arg}" is not an input`);
317
+ if (op.confirmation) {
318
+ const templates = [
319
+ op.confirmation.title,
320
+ op.confirmation.target,
321
+ op.confirmation.lookup?.path
322
+ ];
323
+ 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`);
324
+ if (op.confirmation.lookup && !op.confirmation.title.includes("{resource_name}")) report("a confirmation lookup needs {resource_name} in the title");
325
+ }
326
+ return op;
327
+ }
328
+ function templateKey(path) {
329
+ return path.replace(/\{[^{}]+\}/g, "{}");
330
+ }
331
+ /**
332
+ * The operation serving a method and a path. The path may be a template
333
+ * (`/api/vm/{id}`) or concrete (`/api/vm/vm-42`); a query string is ignored.
334
+ * Literal segments win over parameters, so `/api/vm/search` beats `/api/vm/{id}`.
335
+ */
336
+ function findOperation(ops, method, path) {
337
+ const bare = path.split("?")[0];
338
+ const key = templateKey(bare);
339
+ const segments = bare.split("/");
340
+ let best;
341
+ for (const op of ops) {
342
+ if (op.method !== method.toUpperCase()) continue;
343
+ if (templateKey(op.path) === key) return op;
344
+ const pattern = op.path.split("/");
345
+ if (pattern.length !== segments.length) continue;
346
+ let literals = 0;
347
+ if (pattern.every((part, i) => {
348
+ if (/^\{[^{}]+\}$/.test(part)) return true;
349
+ literals += 1;
350
+ return part === segments[i];
351
+ }) && (!best || literals > best.literals)) best = {
352
+ op,
353
+ literals
354
+ };
355
+ }
356
+ return best?.op;
357
+ }
358
+ function checkReferences(ops, issues) {
359
+ const byName = /* @__PURE__ */ new Map();
360
+ for (const op of ops) {
361
+ if (byName.has(op.name)) issues.push({
362
+ at: op.name,
363
+ message: "duplicate operation name"
364
+ });
365
+ byName.set(op.name, op);
366
+ }
367
+ for (const op of ops) {
368
+ const report = (message) => issues.push({
369
+ at: op.name,
370
+ message
371
+ });
372
+ if (op.form) {
373
+ if (byName.get(op.form)?.role !== "form") report(`form "${op.form}" is not a role: form operation`);
374
+ }
375
+ for (const [arg, ref] of Object.entries(op.resolve ?? {})) {
376
+ const list = byName.get(ref.op);
377
+ if (!list || list.role || list.effect !== "read") report(`resolve "${arg}" needs a read operation, got "${ref.op}"`);
378
+ }
379
+ if (op.next) {
380
+ const next = byName.get(op.next.op);
381
+ if (!next || next.role) report(`next "${op.next.op}" is not a catalog operation`);
382
+ }
383
+ const lookup = op.confirmation?.lookup;
384
+ if (lookup && !findOperation(ops, "GET", lookup.path)) report(`confirmation lookup ${lookup.path} is not served by a GET operation`);
385
+ }
386
+ const identities = ops.filter((op) => op.role === "identity");
387
+ if (identities.length !== 1) issues.push({
388
+ at: "catalog",
389
+ message: `exactly one role: identity operation is required, found ${identities.length}`
390
+ });
391
+ }
392
+ /**
393
+ * Reads the aidy catalog from an OpenAPI 3.1 document. Only operations with an
394
+ * `x-aidy` object are included. Throws a CatalogError listing every problem.
395
+ */
396
+ function readCatalog(document) {
397
+ const issues = [];
398
+ if (!isObject(document) || typeof document.openapi !== "string") throw new CatalogError([{
399
+ at: "document",
400
+ message: "not an OpenAPI document"
401
+ }]);
402
+ if (!document.openapi.startsWith("3.1.")) throw new CatalogError([{
403
+ at: "document",
404
+ message: `OpenAPI 3.1 is required, got ${document.openapi}`
405
+ }]);
406
+ const ops = [];
407
+ const paths = isObject(document.paths) ? document.paths : {};
408
+ for (const [path, pathItem] of Object.entries(paths)) {
409
+ if (!isObject(pathItem)) continue;
410
+ for (const method of METHODS) {
411
+ const operation = pathItem[method.toLowerCase()];
412
+ if (!isObject(operation) || operation["x-aidy"] === void 0) continue;
413
+ const at = `${method} ${path}`;
414
+ const report = (message) => issues.push({
415
+ at,
416
+ message
417
+ });
418
+ const op = readOperation(document, pathItem, path, method, operation, report);
419
+ if (op) ops.push(op);
420
+ }
421
+ }
422
+ checkReferences(ops, issues);
423
+ if (issues.length > 0) throw new CatalogError(issues);
424
+ return ops;
425
+ }
426
+ export { ADMIN_SCOPE, Approval, CatalogError, Confirmation, Effect, Identity, Next, OPERATION_NAME, Role, Surface, XAidy, findOperation, readCatalog };