@crouter/api 0.3.377

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 (112) hide show
  1. package/README.md +67 -0
  2. package/dist/api/__tests__/error-codes.test.d.ts +1 -0
  3. package/dist/api/__tests__/error-codes.test.js +78 -0
  4. package/dist/api/__tests__/integration/client.test.d.ts +1 -0
  5. package/dist/api/__tests__/integration/client.test.js +179 -0
  6. package/dist/api/client.d.ts +467 -0
  7. package/dist/api/client.js +1179 -0
  8. package/dist/api/command-manifest/index.d.ts +3 -0
  9. package/dist/api/command-manifest/index.js +3 -0
  10. package/dist/api/command-manifest/manifest.d.ts +51 -0
  11. package/dist/api/command-manifest/manifest.js +332 -0
  12. package/dist/api/command-manifest/result.d.ts +25 -0
  13. package/dist/api/command-manifest/result.js +97 -0
  14. package/dist/api/command-manifest/schema.d.ts +28 -0
  15. package/dist/api/command-manifest/schema.js +856 -0
  16. package/dist/api/dto/analytics.d.ts +184 -0
  17. package/dist/api/dto/analytics.js +3 -0
  18. package/dist/api/dto/attach.d.ts +22 -0
  19. package/dist/api/dto/attach.js +13 -0
  20. package/dist/api/dto/bash-jobs.d.ts +24 -0
  21. package/dist/api/dto/bash-jobs.js +9 -0
  22. package/dist/api/dto/bash.d.ts +17 -0
  23. package/dist/api/dto/bash.js +1 -0
  24. package/dist/api/dto/broker-ops.d.ts +187 -0
  25. package/dist/api/dto/broker-ops.js +6 -0
  26. package/dist/api/dto/broker-signals.d.ts +25 -0
  27. package/dist/api/dto/broker-signals.js +1 -0
  28. package/dist/api/dto/broker.d.ts +86 -0
  29. package/dist/api/dto/broker.js +20 -0
  30. package/dist/api/dto/canvas.d.ts +359 -0
  31. package/dist/api/dto/canvas.js +2 -0
  32. package/dist/api/dto/chat-inventory.d.ts +56 -0
  33. package/dist/api/dto/chat-inventory.js +11 -0
  34. package/dist/api/dto/common.d.ts +29 -0
  35. package/dist/api/dto/common.js +15 -0
  36. package/dist/api/dto/config.d.ts +36 -0
  37. package/dist/api/dto/config.js +3 -0
  38. package/dist/api/dto/crons.d.ts +150 -0
  39. package/dist/api/dto/crons.js +10 -0
  40. package/dist/api/dto/custom-objects.d.ts +66 -0
  41. package/dist/api/dto/custom-objects.js +1 -0
  42. package/dist/api/dto/delivery.d.ts +71 -0
  43. package/dist/api/dto/delivery.js +7 -0
  44. package/dist/api/dto/docs.d.ts +135 -0
  45. package/dist/api/dto/docs.js +8 -0
  46. package/dist/api/dto/files.d.ts +21 -0
  47. package/dist/api/dto/files.js +1 -0
  48. package/dist/api/dto/focus.d.ts +24 -0
  49. package/dist/api/dto/focus.js +10 -0
  50. package/dist/api/dto/grants.d.ts +14 -0
  51. package/dist/api/dto/grants.js +1 -0
  52. package/dist/api/dto/health.d.ts +106 -0
  53. package/dist/api/dto/health.js +2 -0
  54. package/dist/api/dto/human-requests.d.ts +113 -0
  55. package/dist/api/dto/human-requests.js +4 -0
  56. package/dist/api/dto/human.d.ts +28 -0
  57. package/dist/api/dto/human.js +4 -0
  58. package/dist/api/dto/inbox.d.ts +273 -0
  59. package/dist/api/dto/inbox.js +4 -0
  60. package/dist/api/dto/lifecycle.d.ts +88 -0
  61. package/dist/api/dto/lifecycle.js +3 -0
  62. package/dist/api/dto/mail.d.ts +44 -0
  63. package/dist/api/dto/mail.js +1 -0
  64. package/dist/api/dto/messages.d.ts +88 -0
  65. package/dist/api/dto/messages.js +2 -0
  66. package/dist/api/dto/model-config.d.ts +25 -0
  67. package/dist/api/dto/model-config.js +1 -0
  68. package/dist/api/dto/modelauth.d.ts +132 -0
  69. package/dist/api/dto/modelauth.js +4 -0
  70. package/dist/api/dto/node-events.d.ts +65 -0
  71. package/dist/api/dto/node-events.js +4 -0
  72. package/dist/api/dto/node-outcomes.d.ts +88 -0
  73. package/dist/api/dto/node-outcomes.js +2 -0
  74. package/dist/api/dto/node-records.d.ts +35 -0
  75. package/dist/api/dto/node-records.js +5 -0
  76. package/dist/api/dto/nodes.d.ts +368 -0
  77. package/dist/api/dto/nodes.js +3 -0
  78. package/dist/api/dto/objects.d.ts +172 -0
  79. package/dist/api/dto/objects.js +5 -0
  80. package/dist/api/dto/profiles.d.ts +117 -0
  81. package/dist/api/dto/profiles.js +4 -0
  82. package/dist/api/dto/recovery.d.ts +104 -0
  83. package/dist/api/dto/recovery.js +1 -0
  84. package/dist/api/dto/reports.d.ts +93 -0
  85. package/dist/api/dto/reports.js +2 -0
  86. package/dist/api/dto/review-comments.d.ts +146 -0
  87. package/dist/api/dto/review-comments.js +5 -0
  88. package/dist/api/dto/reviews.d.ts +113 -0
  89. package/dist/api/dto/reviews.js +5 -0
  90. package/dist/api/dto/run-events.d.ts +293 -0
  91. package/dist/api/dto/run-events.js +6 -0
  92. package/dist/api/dto/subscriptions.d.ts +14 -0
  93. package/dist/api/dto/subscriptions.js +2 -0
  94. package/dist/api/dto/worktree.d.ts +55 -0
  95. package/dist/api/dto/worktree.js +6 -0
  96. package/dist/api/error-codes.d.ts +254 -0
  97. package/dist/api/error-codes.js +54 -0
  98. package/dist/api/errors.d.ts +47 -0
  99. package/dist/api/errors.js +66 -0
  100. package/dist/api/index.d.ts +42 -0
  101. package/dist/api/index.js +41 -0
  102. package/dist/api/node-transport.d.ts +18 -0
  103. package/dist/api/node-transport.js +105 -0
  104. package/dist/api/plugin-manifest-schema.d.ts +233 -0
  105. package/dist/api/plugin-manifest-schema.js +23 -0
  106. package/dist/api/routes.d.ts +160 -0
  107. package/dist/api/routes.js +193 -0
  108. package/dist/shared/generated-context.d.ts +79 -0
  109. package/dist/shared/generated-context.js +232 -0
  110. package/dist/shared/predicates.d.ts +2 -0
  111. package/dist/shared/predicates.js +4 -0
  112. package/package.json +49 -0
@@ -0,0 +1,856 @@
1
+ // Unified command-manifest schema. Transport is the sole leaf-dialect discriminator.
2
+ //
3
+ // The SHAPE of a manifest is declared once, in `src/api/plugin-manifest-schema.ts`,
4
+ // and published as `@crouter/api/plugin-manifest` so a server that
5
+ // serves a plugin bundle compiles against the same types validated here. This
6
+ // module owns the validators and re-exports those types under their in-tree names.
7
+ import { isRecord } from '../../shared/predicates.js';
8
+ // Validation helpers
9
+ const TIERS = new Set(['normal', 'common', 'important']);
10
+ const FLAG_TYPES = new Set(['string', 'int', 'bool', 'path', 'enum', 'file']);
11
+ /** A capability-provider tool group id (contract 1 `<id>` grammar), so
12
+ * `<provider>:<group>` splits on its first `:`. */
13
+ const GROUP_ID = /^[A-Za-z0-9_-]{1,64}$/;
14
+ const KEBAB = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
15
+ const BRANCH_KEYS = new Set([
16
+ 'kind', 'name', 'description', 'whenToUse', 'tier', 'rootEntry', 'extensible', 'summary', 'model', 'children',
17
+ ]);
18
+ /** Only exec transport may declare `passthrough`; HTTP manifests keep
19
+ * BRANCH_KEYS, so a declared passthrough fails as an unknown key. */
20
+ const EXEC_BRANCH_KEYS = new Set([...BRANCH_KEYS, 'passthrough']);
21
+ const PASSTHROUGH_KEYS = new Set(['bin', 'installHint']);
22
+ const LEAF_KEYS_COMMON = new Set([
23
+ 'kind', 'name', 'description', 'whenToUse', 'tier', 'summary', 'params', 'output', 'effects',
24
+ ]);
25
+ const EXEC_LEAF_KEYS = new Set([...LEAF_KEYS_COMMON, 'outputKind']);
26
+ const HTTP_LEAF_KEYS = new Set([...LEAF_KEYS_COMMON, 'rest', 'group']);
27
+ const ROOT_ENTRY_KEYS = new Set(['concept', 'description', 'whenToUse']);
28
+ const FILE_ENCODINGS = new Set(['text', 'base64']);
29
+ const PARAM_KEYS_BY_KIND = {
30
+ positional: new Set(['kind', 'name', 'type', 'required', 'constraint', 'repeatable', 'encoding', 'defaultFromEnv']),
31
+ flag: new Set([
32
+ 'kind',
33
+ 'name',
34
+ 'type',
35
+ 'choices',
36
+ 'required',
37
+ 'constraint',
38
+ 'default',
39
+ 'repeatable',
40
+ 'encoding',
41
+ 'defaultFromEnv',
42
+ ]),
43
+ stdin: new Set(['kind', 'name', 'required', 'constraint']),
44
+ 'context-file': new Set(['kind', 'name', 'required', 'constraint', 'shape']),
45
+ };
46
+ const OUTPUT_KEYS = new Set(['name', 'type', 'required', 'constraint', 'children', 'items', 'values']);
47
+ /** An `items` element shape: an output field without a name or required. */
48
+ const OUTPUT_SHAPE_KEYS = new Set(['type', 'constraint', 'children', 'items', 'values']);
49
+ /** UPPER_SNAKE_CASE environment variable name — the only form an ambient default
50
+ * may name, so a typo'd lowercase key fails at authoring time rather than
51
+ * silently never resolving. */
52
+ const ENV_VAR_NAME = /^[A-Z][A-Z0-9_]*$/;
53
+ function typeName(v) {
54
+ if (v === null)
55
+ return 'null';
56
+ if (Array.isArray(v))
57
+ return 'array';
58
+ return typeof v;
59
+ }
60
+ function checkKeys(raw, allowed, path, issue) {
61
+ const unknown = Object.keys(raw).filter((k) => !allowed.has(k));
62
+ if (unknown.length > 0) {
63
+ issue('command_node_invalid', `unknown keys`, unknown.join(', '), `only: ${[...allowed].join(', ')}`, 'Remove the unknown keys.', path);
64
+ return false;
65
+ }
66
+ return true;
67
+ }
68
+ function validateRootEntry(raw, path, issue) {
69
+ if (!isRecord(raw)) {
70
+ issue('command_node_invalid', `rootEntry must be an object`, typeName(raw), 'a { concept, description, whenToUse } object', 'Fix rootEntry.', path);
71
+ return null;
72
+ }
73
+ if (!checkKeys(raw, ROOT_ENTRY_KEYS, path, issue))
74
+ return null;
75
+ for (const k of ['concept', 'description', 'whenToUse']) {
76
+ if (typeof raw[k] !== 'string' || raw[k].length === 0) {
77
+ issue('command_node_invalid', `rootEntry.${k} must be a non-empty string`, typeName(raw[k]), 'a non-empty string', `Add rootEntry.${k}.`, `${path}.${k}`);
78
+ return null;
79
+ }
80
+ }
81
+ return {
82
+ concept: raw['concept'],
83
+ description: raw['description'],
84
+ whenToUse: raw['whenToUse'],
85
+ };
86
+ }
87
+ function validateParams(raw, path, issue) {
88
+ if (raw === undefined)
89
+ return [];
90
+ if (!Array.isArray(raw)) {
91
+ issue('command_node_invalid', `params must be an array`, typeName(raw), 'an array of params (or omitted)', 'Fix params.', path);
92
+ return null;
93
+ }
94
+ const out = [];
95
+ const names = new Set();
96
+ let positionals = 0;
97
+ for (let i = 0; i < raw.length; i++) {
98
+ const p = raw[i];
99
+ const pp = `${path}[${i}]`;
100
+ if (!isRecord(p)) {
101
+ issue('command_node_invalid', `param must be an object`, typeName(p), 'a param object', 'Fix the param.', pp);
102
+ return null;
103
+ }
104
+ const kind = p['kind'];
105
+ if (typeof kind !== 'string' || !(kind in PARAM_KEYS_BY_KIND)) {
106
+ issue('command_node_invalid', `param kind must be positional|flag|stdin|context-file`, String(kind), 'positional | flag | stdin | context-file', 'Fix the param kind.', `${pp}.kind`);
107
+ return null;
108
+ }
109
+ if (!checkKeys(p, PARAM_KEYS_BY_KIND[kind], pp, issue))
110
+ return null;
111
+ const name = p['name'];
112
+ if (typeof name !== 'string' || !KEBAB.test(name)) {
113
+ issue('command_node_invalid', `param name must be a kebab-case token`, String(name), 'a kebab-case token', 'Rename the param.', `${pp}.name`);
114
+ return null;
115
+ }
116
+ if (names.has(name)) {
117
+ issue('command_node_invalid', `duplicate param name`, name, 'unique param names', 'Rename the duplicate param.', `${pp}.name`);
118
+ return null;
119
+ }
120
+ names.add(name);
121
+ if (typeof p['required'] !== 'boolean') {
122
+ issue('command_node_invalid', `param required must be a boolean`, typeName(p['required']), 'true | false', 'Set required.', `${pp}.required`);
123
+ return null;
124
+ }
125
+ if (typeof p['constraint'] !== 'string') {
126
+ issue('command_node_invalid', `param constraint must be a string`, typeName(p['constraint']), 'an inline constraint string', 'Add a constraint.', `${pp}.constraint`);
127
+ return null;
128
+ }
129
+ if (kind === 'positional') {
130
+ positionals++;
131
+ if (positionals > 1) {
132
+ issue('command_node_invalid', `a leaf may declare at most one positional`, 'multiple positionals', 'at most one positional param', 'Convert extra positionals to flags.', pp);
133
+ return null;
134
+ }
135
+ if (p['type'] !== undefined && p['type'] !== 'string' && p['type'] !== 'path' && p['type'] !== 'file') {
136
+ issue('command_node_invalid', `positional type must be string|path|file`, String(p['type']), 'string | path | file | omitted', 'Fix the positional type.', `${pp}.type`);
137
+ return null;
138
+ }
139
+ let repeatable = false;
140
+ if (p['repeatable'] !== undefined) {
141
+ if (typeof p['repeatable'] !== 'boolean') {
142
+ issue('command_node_invalid', `repeatable must be a boolean`, typeName(p['repeatable']), 'true | false | omitted', 'Fix repeatable.', `${pp}.repeatable`);
143
+ return null;
144
+ }
145
+ repeatable = p['repeatable'];
146
+ }
147
+ if (repeatable && p['type'] === 'file') {
148
+ issue('command_node_invalid', `repeatable is not valid on a file positional`, `${name}: file`, 'one file per file param', 'Remove repeatable, or declare one file param per file.', `${pp}.repeatable`);
149
+ return null;
150
+ }
151
+ const encoding = validateFileEncoding(p, pp, issue);
152
+ if (encoding === null)
153
+ return null;
154
+ const envDefault = validateDefaultFromEnv(p, pp, issue);
155
+ if (envDefault === null)
156
+ return null;
157
+ if (repeatable && envDefault !== undefined) {
158
+ issue('command_node_invalid', `repeatable positional must not declare defaultFromEnv`, name, 'no defaultFromEnv on a repeatable positional (values accumulate into an array)', 'Remove defaultFromEnv, or drop repeatable.', `${pp}.defaultFromEnv`);
159
+ return null;
160
+ }
161
+ out.push({
162
+ kind: 'positional',
163
+ name,
164
+ ...(p['type'] !== undefined ? { type: p['type'] } : {}),
165
+ required: p['required'],
166
+ constraint: p['constraint'],
167
+ ...(repeatable ? { repeatable: true } : {}),
168
+ ...(encoding !== undefined ? { encoding } : {}),
169
+ ...(envDefault !== undefined ? { defaultFromEnv: envDefault } : {}),
170
+ });
171
+ }
172
+ else if (kind === 'stdin') {
173
+ out.push({ kind: 'stdin', name, required: p['required'], constraint: p['constraint'] });
174
+ }
175
+ else if (kind === 'context-file') {
176
+ out.push({
177
+ kind: 'context-file',
178
+ name,
179
+ required: p['required'],
180
+ constraint: p['constraint'],
181
+ ...(typeof p['shape'] === 'string' ? { shape: p['shape'] } : {}),
182
+ });
183
+ }
184
+ else if (kind === 'flag') {
185
+ const type = p['type'];
186
+ if (typeof type !== 'string' || !FLAG_TYPES.has(type)) {
187
+ issue('command_node_invalid', `flag type must be string|int|bool|path|enum|file`, String(type), 'string | int | bool | path | enum | file', 'Fix the flag type.', `${pp}.type`);
188
+ return null;
189
+ }
190
+ let choices;
191
+ if (type === 'enum') {
192
+ const c = p['choices'];
193
+ if (!Array.isArray(c) || c.length === 0 || !c.every((x) => typeof x === 'string')) {
194
+ issue('command_node_invalid', `enum flag requires a non-empty string choices array`, typeName(c), 'a non-empty array of strings', 'Declare choices for the enum flag.', `${pp}.choices`);
195
+ return null;
196
+ }
197
+ choices = c;
198
+ }
199
+ else if (p['choices'] !== undefined) {
200
+ issue('command_node_invalid', `choices is only valid on an enum flag`, 'choices', 'no choices unless type is enum', 'Remove choices.', `${pp}.choices`);
201
+ return null;
202
+ }
203
+ let repeatable = false;
204
+ if (p['repeatable'] !== undefined) {
205
+ if (typeof p['repeatable'] !== 'boolean') {
206
+ issue('command_node_invalid', `repeatable must be a boolean`, typeName(p['repeatable']), 'true | false | omitted', 'Fix repeatable.', `${pp}.repeatable`);
207
+ return null;
208
+ }
209
+ repeatable = p['repeatable'];
210
+ }
211
+ if (repeatable && (type === 'bool' || type === 'path' || type === 'file')) {
212
+ issue('command_node_invalid', `repeatable is not valid on a ${type} flag`, `${name}: ${type}`, 'repeatable only on string | int | enum flags', 'Remove repeatable or change the flag type.', `${pp}.repeatable`);
213
+ return null;
214
+ }
215
+ if (repeatable && p['default'] !== undefined) {
216
+ issue('command_node_invalid', `repeatable flag must not declare a default`, name, 'no default on a repeatable flag (values accumulate into an array)', 'Remove the default.', `${pp}.default`);
217
+ return null;
218
+ }
219
+ const encoding = validateFileEncoding(p, pp, issue);
220
+ if (encoding === null)
221
+ return null;
222
+ const envDefault = validateDefaultFromEnv(p, pp, issue);
223
+ if (envDefault === null)
224
+ return null;
225
+ if (repeatable && envDefault !== undefined) {
226
+ issue('command_node_invalid', `repeatable flag must not declare defaultFromEnv`, name, 'no defaultFromEnv on a repeatable flag (values accumulate into an array)', 'Remove defaultFromEnv, or drop repeatable.', `${pp}.defaultFromEnv`);
227
+ return null;
228
+ }
229
+ out.push({
230
+ kind: 'flag',
231
+ name,
232
+ type: type,
233
+ ...(choices !== undefined ? { choices } : {}),
234
+ ...(encoding !== undefined ? { encoding } : {}),
235
+ required: p['required'],
236
+ constraint: p['constraint'],
237
+ ...(p['default'] !== undefined ? { default: p['default'] } : {}),
238
+ ...(repeatable ? { repeatable: true } : {}),
239
+ ...(envDefault !== undefined ? { defaultFromEnv: envDefault } : {}),
240
+ });
241
+ }
242
+ }
243
+ return out;
244
+ }
245
+ /** `encoding` declares the local-file materialization contract: the CLI-side
246
+ * value is a path, and the invoker sends the FILE's content under the mapped
247
+ * body key. It is meaningful only on a `path` param — anywhere else there is no
248
+ * file to read, so declaring it is an authoring error, not a silent no-op.
249
+ * Returns the encoding, undefined when absent, or null when invalid. */
250
+ function validateFileEncoding(p, pp, issue) {
251
+ const encoding = p['encoding'];
252
+ if (encoding === undefined)
253
+ return undefined;
254
+ if (typeof encoding !== 'string' || !FILE_ENCODINGS.has(encoding)) {
255
+ issue('command_node_invalid', `param encoding must be text|base64`, String(encoding), 'text | base64 | omitted', 'Fix the encoding.', `${pp}.encoding`);
256
+ return null;
257
+ }
258
+ if (p['type'] !== 'path') {
259
+ issue('command_node_invalid', `encoding is only valid on a type:"path" param`, `type ${String(p['type'])}`, 'type: "path"', 'Set the param type to "path", or remove encoding.', `${pp}.encoding`);
260
+ return null;
261
+ }
262
+ return encoding;
263
+ }
264
+ /** `defaultFromEnv` names an environment variable on the CALLING machine whose
265
+ * value fills the param when the caller omits it — and counts as supplied, so it
266
+ * satisfies `required` and ships like a typed value. It carries a textual value,
267
+ * so it is meaningful only on a string|path param, and it cannot coexist with a
268
+ * static `default` (two competing sources for one slot is an authoring error,
269
+ * not a precedence puzzle for the reader). The caller checks `repeatable`
270
+ * separately, where that param is in scope: a repeatable param accumulates an
271
+ * ARRAY, and one env string cannot honestly fill it. Returns the env var name,
272
+ * undefined when absent, or null when invalid. */
273
+ function validateDefaultFromEnv(p, pp, issue) {
274
+ const envVar = p['defaultFromEnv'];
275
+ if (envVar === undefined)
276
+ return undefined;
277
+ if (typeof envVar !== 'string' || !ENV_VAR_NAME.test(envVar)) {
278
+ issue('command_node_invalid', `defaultFromEnv must name an environment variable in UPPER_SNAKE_CASE`, String(envVar), 'e.g. "CRTR_NODE_ID"', 'Fix the environment variable name.', `${pp}.defaultFromEnv`);
279
+ return null;
280
+ }
281
+ // A positional with no declared type is a string.
282
+ const type = p['type'] === undefined && p['kind'] === 'positional' ? 'string' : p['type'];
283
+ if (type !== 'string' && type !== 'path') {
284
+ issue('command_node_invalid', `defaultFromEnv is only valid on a string|path param`, `type ${String(p['type'])}`, 'type: "string" | "path"', 'Change the param type, or remove defaultFromEnv.', `${pp}.defaultFromEnv`);
285
+ return null;
286
+ }
287
+ if (p['default'] !== undefined) {
288
+ issue('command_node_invalid', `a param must not declare both default and defaultFromEnv`, `${String(p['name'])}: default + defaultFromEnv`, 'exactly one default source', 'Remove one — defaultFromEnv counts as supplied, a static default does not.', `${pp}.defaultFromEnv`);
289
+ return null;
290
+ }
291
+ return envVar;
292
+ }
293
+ /** Base type of a declared output type: the union with every `null` part
294
+ * dropped, lower-cased. It decides which structural keys the shape may carry. */
295
+ export function outputBaseType(type) {
296
+ return type
297
+ .split('|')
298
+ .map((part) => part.trim().toLowerCase())
299
+ .filter((part) => part.length > 0 && part !== 'null')
300
+ .join(' | ');
301
+ }
302
+ /** Whether a declared output type names `file` anywhere: as a union part or
303
+ * as the element of an array type. */
304
+ export function mentionsFile(type) {
305
+ return type.split('|').some((part) => /^file(\[\])*$/i.test(part.trim()));
306
+ }
307
+ /** Validate the type/constraint/children/items/values of one output shape.
308
+ * `topLevel` is true only for a leaf's own output fields: a `file` field may
309
+ * appear nowhere else. Returns the shape, or null after raising an issue. */
310
+ function validateOutputShape(f, fp, topLevel, issue) {
311
+ if (typeof f['type'] !== 'string' || f['type'].length === 0) {
312
+ issue('command_node_invalid', `output field type must be a non-empty string`, typeName(f['type']), 'a type name', 'Add a type.', `${fp}.type`);
313
+ return null;
314
+ }
315
+ if (typeof f['constraint'] !== 'string') {
316
+ issue('command_node_invalid', `output field constraint must be a string`, typeName(f['constraint']), 'a constraint string', 'Add a constraint.', `${fp}.constraint`);
317
+ return null;
318
+ }
319
+ const type = f['type'];
320
+ const base = outputBaseType(type);
321
+ if (mentionsFile(type) && base !== 'file') {
322
+ issue('command_node_invalid', `a file output is one file, optionally nullable`, type, 'type "file" or "file | null"', 'Return one file per leaf; declare it as "file" or "file | null".', `${fp}.type`);
323
+ return null;
324
+ }
325
+ if (base === 'file' && !topLevel) {
326
+ issue('command_node_invalid', `a file output must be a top-level output field`, type, 'type "file" only on a leaf\'s own output fields, never inside children or items', 'Move the file field to the top level of the leaf output.', `${fp}.type`);
327
+ return null;
328
+ }
329
+ const structural = [
330
+ ['children', 'object'],
331
+ ['items', 'array'],
332
+ ['values', 'enum'],
333
+ ];
334
+ for (const [key, allowedOn] of structural) {
335
+ if (f[key] !== undefined && base !== allowedOn) {
336
+ issue('command_node_invalid', `output ${key} is only valid on an ${allowedOn} field`, `type ${type}`, `type "${allowedOn}" (optionally "${allowedOn} | null")`, `Remove ${key}, or change the type to ${allowedOn}.`, `${fp}.${key}`);
337
+ return null;
338
+ }
339
+ }
340
+ let children;
341
+ if (f['children'] !== undefined) {
342
+ const c = validateOutputFields(f['children'], `${fp}.children`, false, issue);
343
+ if (c === null)
344
+ return null;
345
+ children = c;
346
+ }
347
+ let items;
348
+ if (f['items'] !== undefined) {
349
+ const raw = f['items'];
350
+ const ip = `${fp}.items`;
351
+ if (!isRecord(raw)) {
352
+ issue('command_node_invalid', `output items must be an object`, typeName(raw), 'a { type, constraint, children?, items?, values? } object', 'Fix the items shape.', ip);
353
+ return null;
354
+ }
355
+ if (!checkKeys(raw, OUTPUT_SHAPE_KEYS, ip, issue))
356
+ return null;
357
+ const shape = validateOutputShape(raw, ip, false, issue);
358
+ if (shape === null)
359
+ return null;
360
+ items = shape;
361
+ }
362
+ let values;
363
+ if (f['values'] !== undefined) {
364
+ const v = f['values'];
365
+ if (!Array.isArray(v) || v.length === 0 || !v.every((x) => typeof x === 'string' && x.length > 0)) {
366
+ issue('command_node_invalid', `enum output values must be a non-empty array of strings`, typeName(v), 'a non-empty array of non-empty strings', 'Declare the values the field may take.', `${fp}.values`);
367
+ return null;
368
+ }
369
+ if (new Set(v).size !== v.length) {
370
+ issue('command_node_invalid', `enum output values must be unique`, v.join(', '), 'distinct values', 'Remove the duplicate value.', `${fp}.values`);
371
+ return null;
372
+ }
373
+ values = v;
374
+ }
375
+ return {
376
+ type,
377
+ constraint: f['constraint'],
378
+ ...(children !== undefined ? { children } : {}),
379
+ ...(items !== undefined ? { items } : {}),
380
+ ...(values !== undefined ? { values } : {}),
381
+ };
382
+ }
383
+ function validateOutput(raw, path, issue) {
384
+ return validateOutputFields(raw, path, true, issue);
385
+ }
386
+ function validateOutputFields(raw, path, topLevel, issue) {
387
+ if (!Array.isArray(raw)) {
388
+ issue('command_node_invalid', topLevel ? `output must be an array` : `output children must be an array`, typeName(raw), 'an array of output fields', topLevel ? 'Declare the leaf output fields.' : 'Declare the object\'s member fields.', path);
389
+ return null;
390
+ }
391
+ const out = [];
392
+ const names = new Set();
393
+ let fileField;
394
+ for (let i = 0; i < raw.length; i++) {
395
+ const f = raw[i];
396
+ const fp = `${path}[${i}]`;
397
+ if (!isRecord(f)) {
398
+ issue('command_node_invalid', `output field must be an object`, typeName(f), 'a { name, type, required, constraint } object', 'Fix the output field.', fp);
399
+ return null;
400
+ }
401
+ if (!checkKeys(f, OUTPUT_KEYS, fp, issue))
402
+ return null;
403
+ if (typeof f['name'] !== 'string' || f['name'].length === 0) {
404
+ issue('command_node_invalid', `output field name must be a non-empty string`, typeName(f['name']), 'a field name', 'Add a name.', `${fp}.name`);
405
+ return null;
406
+ }
407
+ if (!topLevel && names.has(f['name'])) {
408
+ issue('command_node_invalid', `duplicate output child name`, f['name'], 'unique member names within one object', 'Rename the duplicate member.', `${fp}.name`);
409
+ return null;
410
+ }
411
+ names.add(f['name']);
412
+ if (typeof f['required'] !== 'boolean') {
413
+ issue('command_node_invalid', `output field required must be a boolean`, typeName(f['required']), 'true | false', 'Set required.', `${fp}.required`);
414
+ return null;
415
+ }
416
+ const shape = validateOutputShape(f, fp, topLevel, issue);
417
+ if (shape === null)
418
+ return null;
419
+ if (outputBaseType(shape.type) === 'file') {
420
+ if (fileField !== undefined) {
421
+ issue('command_node_invalid', `a leaf declares at most one file output`, `${fileField}, ${f['name']}`, 'one top-level output field of type "file"', 'Return the extra files through a separate leaf, or drop the extra file field.', `${fp}.type`);
422
+ return null;
423
+ }
424
+ fileField = f['name'];
425
+ }
426
+ out.push({ name: f['name'], ...shape, required: f['required'] });
427
+ }
428
+ return out;
429
+ }
430
+ function checkCommon(raw, path, issue) {
431
+ const name = raw['name'];
432
+ if (typeof name !== 'string' || !KEBAB.test(name)) {
433
+ issue('command_node_invalid', `node name must be a lowercase kebab-case token`, String(name), 'a kebab-case token like "app" or "list-all"', 'Rename the node.', `${path}.name`);
434
+ return false;
435
+ }
436
+ if (typeof raw['description'] !== 'string' || raw['description'].length === 0) {
437
+ issue('command_node_invalid', `node description must be a non-empty string`, typeName(raw['description']), 'a short parent-listing description', 'Add a description.', `${path}.description`);
438
+ return false;
439
+ }
440
+ if (typeof raw['whenToUse'] !== 'string' || raw['whenToUse'].length === 0) {
441
+ issue('command_node_invalid', `node whenToUse must be a non-empty string`, typeName(raw['whenToUse']), 'a parent selection rubric', 'Add a whenToUse rubric.', `${path}.whenToUse`);
442
+ return false;
443
+ }
444
+ if (raw['tier'] !== undefined && !TIERS.has(String(raw['tier']))) {
445
+ issue('command_node_invalid', `node tier must be normal|common|important`, String(raw['tier']), 'normal | common | important', 'Fix or omit tier (external plugins cannot declare hidden commands).', `${path}.tier`);
446
+ return false;
447
+ }
448
+ return true;
449
+ }
450
+ export function validateCommandNode(raw, path, topLevel, transport, issue, options = {}) {
451
+ const pathString = path.join('.');
452
+ if (!isRecord(raw)) {
453
+ issue('command_node_invalid', 'node must be an object', typeName(raw), 'a branch or leaf node object', 'Fix the node.', pathString);
454
+ return null;
455
+ }
456
+ const kind = raw['kind'];
457
+ if (kind === 'branch')
458
+ return validateBranch(raw, pathString, topLevel, transport, issue, options);
459
+ if (kind === 'leaf') {
460
+ if (topLevel && options.topLevelRootEntry !== 'forbidden') {
461
+ issue('command_node_invalid', 'top-level node must be a branch', 'leaf', 'a branch node with a rootEntry', 'Wrap the command in a top-level branch (noun) with a rootEntry.', `${pathString}.kind`);
462
+ return null;
463
+ }
464
+ return validateLeaf(raw, pathString, transport, issue);
465
+ }
466
+ issue('command_node_invalid', 'node kind must be "branch" or "leaf"', String(kind), 'branch | leaf', 'Set kind to branch or leaf.', `${pathString}.kind`);
467
+ return null;
468
+ }
469
+ function validateBranch(raw, path, topLevel, transport, issue, options) {
470
+ const allowsPassthrough = options.allowPassthrough !== false;
471
+ const allowedKeys = transport === 'exec' && allowsPassthrough ? EXEC_BRANCH_KEYS : BRANCH_KEYS;
472
+ if (!checkKeys(raw, allowedKeys, path, issue))
473
+ return null;
474
+ if (!checkCommon(raw, path, issue))
475
+ return null;
476
+ const hasRoot = raw['rootEntry'] !== undefined;
477
+ const rootEntryPolicy = options.topLevelRootEntry ?? 'required';
478
+ if (topLevel && rootEntryPolicy === 'required' && !hasRoot) {
479
+ issue('command_node_invalid', 'top-level branch requires a rootEntry', '(missing)', 'a rootEntry { concept, description, whenToUse }', 'Add a rootEntry to the top-level branch.', `${path}.rootEntry`);
480
+ return null;
481
+ }
482
+ if ((!topLevel || rootEntryPolicy === 'forbidden') && hasRoot) {
483
+ issue('command_node_invalid', topLevel ? 'repository fragment root must not declare a rootEntry' : 'nested branch must not declare a rootEntry', 'rootEntry', topLevel ? 'no rootEntry (the owning plugin branch already has one)' : 'no rootEntry (only top-level branches carry one)', topLevel ? 'Remove rootEntry from the repository fragment root.' : 'Remove rootEntry from the nested branch.', `${path}.rootEntry`);
484
+ return null;
485
+ }
486
+ const hasExtensible = raw['extensible'] !== undefined;
487
+ if (hasExtensible && (!topLevel || options.allowExtensible === false || raw['extensible'] !== true)) {
488
+ issue('command_node_invalid', !topLevel ? 'extensible is valid only on a top-level branch mount' : 'extensible must be exactly true on a plugin top-level branch', String(raw['extensible']), !topLevel ? 'no extensible marker on nested branches' : 'extensible: true', !topLevel ? 'Move the marker to the plugin top-level branch or remove it.' : 'Set extensible to true or remove it.', `${path}.extensible`);
489
+ return null;
490
+ }
491
+ let rootEntry;
492
+ if (hasRoot) {
493
+ const validatedRootEntry = validateRootEntry(raw['rootEntry'], `${path}.rootEntry`, issue);
494
+ if (validatedRootEntry === null)
495
+ return null;
496
+ rootEntry = validatedRootEntry;
497
+ }
498
+ if (typeof raw['summary'] !== 'string' || raw['summary'].length === 0) {
499
+ issue('command_node_invalid', 'branch summary must be a non-empty string', typeName(raw['summary']), 'a one-line summary string', 'Add a summary.', `${path}.summary`);
500
+ return null;
501
+ }
502
+ if (raw['model'] !== undefined && typeof raw['model'] !== 'string') {
503
+ issue('command_node_invalid', 'branch model must be a string', typeName(raw['model']), 'a string or omitted', 'Fix or remove model.', `${path}.model`);
504
+ return null;
505
+ }
506
+ let passthrough;
507
+ if (transport === 'exec' && raw['passthrough'] !== undefined) {
508
+ const validated = validatePassthrough(raw['passthrough'], `${path}.passthrough`, issue);
509
+ if (validated === null)
510
+ return null;
511
+ passthrough = validated;
512
+ }
513
+ if (hasExtensible && passthrough !== undefined) {
514
+ issue('command_node_invalid', 'an extensible branch cannot declare passthrough', 'extensible and passthrough', 'one branch mode: extensible or passthrough', 'Remove passthrough or remove extensible.', path);
515
+ return null;
516
+ }
517
+ const children = raw['children'];
518
+ if (passthrough !== undefined) {
519
+ if (!Array.isArray(children) || children.length !== 0) {
520
+ issue('command_node_invalid', 'a passthrough branch must declare children: []', Array.isArray(children) ? `${children.length} children` : typeName(children), 'an empty children array', 'Set children to [] — a passthrough branch forwards all argv and can own no subcommands.', `${path}.children`);
521
+ return null;
522
+ }
523
+ }
524
+ else if (!Array.isArray(children)) {
525
+ issue('command_node_invalid', 'branch children must be an array', typeName(children), 'an array of branch/leaf nodes (may be empty for populated by mounts)', 'Fix children.', `${path}.children`);
526
+ return null;
527
+ }
528
+ const validated = [];
529
+ const childNames = new Set();
530
+ for (let i = 0; i < children.length; i++) {
531
+ const child = validateCommandNode(children[i], [...path.split('.'), `children[${i}]`], false, transport, issue, options);
532
+ if (child === null)
533
+ return null;
534
+ if (childNames.has(child.name)) {
535
+ issue('command_node_invalid', 'duplicate child name', child.name, 'unique child names within a branch', 'Rename the duplicate child.', `${path}.children[${i}].name`);
536
+ return null;
537
+ }
538
+ childNames.add(child.name);
539
+ validated.push(child);
540
+ }
541
+ return {
542
+ kind: 'branch', name: raw['name'], description: raw['description'], whenToUse: raw['whenToUse'],
543
+ ...(raw['tier'] !== undefined ? { tier: raw['tier'] } : {}),
544
+ ...(rootEntry !== undefined ? { rootEntry } : {}),
545
+ ...(hasExtensible ? { extensible: true } : {}), summary: raw['summary'],
546
+ ...(raw['model'] !== undefined ? { model: raw['model'] } : {}),
547
+ ...(passthrough !== undefined ? { passthrough } : {}), children: validated,
548
+ };
549
+ }
550
+ /** `passthrough: { bin, installHint }` — `bin` is a bare PATH command or a
551
+ * plugin-root-relative executable path; both fields are required non-empty strings. */
552
+ function validatePassthrough(raw, path, issue) {
553
+ if (!isRecord(raw)) {
554
+ issue('command_node_invalid', 'passthrough must be an object', typeName(raw), 'an object { bin, installHint }', 'Fix or remove passthrough.', path);
555
+ return null;
556
+ }
557
+ if (!checkKeys(raw, PASSTHROUGH_KEYS, path, issue))
558
+ return null;
559
+ for (const key of ['bin', 'installHint']) {
560
+ if (typeof raw[key] !== 'string' || raw[key].length === 0) {
561
+ issue('command_node_invalid', `passthrough ${key} must be a non-empty string`, typeName(raw[key]), key === 'bin' ? 'the external binary name' : 'a one-line install hint', `Set passthrough.${key}.`, `${path}.${key}`);
562
+ return null;
563
+ }
564
+ }
565
+ return { bin: raw['bin'], installHint: raw['installHint'] };
566
+ }
567
+ function validateLeaf(raw, path, transport, issue) {
568
+ if (!checkKeys(raw, transport === 'exec' ? EXEC_LEAF_KEYS : HTTP_LEAF_KEYS, path, issue))
569
+ return null;
570
+ if (!checkCommon(raw, path, issue))
571
+ return null;
572
+ if (typeof raw['summary'] !== 'string' || raw['summary'].length === 0) {
573
+ issue('command_node_invalid', 'leaf summary must be a non-empty string', typeName(raw['summary']), 'a one-line summary string', 'Add a summary.', `${path}.summary`);
574
+ return null;
575
+ }
576
+ if (transport === 'exec' && raw['outputKind'] !== 'object') {
577
+ issue('command_node_invalid', 'leaf outputKind must be "object" in v1', String(raw['outputKind']), 'exactly "object"', 'Set outputKind to "object".', `${path}.outputKind`);
578
+ return null;
579
+ }
580
+ if (transport === 'http' && raw['rest'] === undefined) {
581
+ issue('command_node_invalid', 'HTTP leaf requires a rest mapping', '(missing)', 'a rest object with method, path, and params', 'Add a rest mapping.', `${path}.rest`);
582
+ return null;
583
+ }
584
+ const params = validateParams(raw['params'], `${path}.params`, issue);
585
+ if (params === null)
586
+ return null;
587
+ const output = validateOutput(raw['output'], `${path}.output`, issue);
588
+ if (output === null)
589
+ return null;
590
+ const effects = raw['effects'];
591
+ if (!Array.isArray(effects) || effects.length === 0 || !effects.every((effect) => typeof effect === 'string')) {
592
+ issue('command_node_invalid', 'leaf effects must be a non-empty string array', typeName(effects), 'a non-empty array of strings (["None. Read-only."] for read-only leaves)', 'Declare every persistent effect.', `${path}.effects`);
593
+ return null;
594
+ }
595
+ const base = { kind: 'leaf', name: raw['name'], description: raw['description'], whenToUse: raw['whenToUse'],
596
+ ...(raw['tier'] !== undefined ? { tier: raw['tier'] } : {}), summary: raw['summary'], params, output, effects: effects };
597
+ if (transport === 'exec')
598
+ return { ...base, outputKind: 'object' };
599
+ const group = raw['group'];
600
+ if (group !== undefined && (typeof group !== 'string' || !GROUP_ID.test(group))) {
601
+ issue('command_node_invalid', `leaf group must match [A-Za-z0-9_-]{1,64}`, typeof group === 'string' ? group : typeName(group), 'a group id of 1-64 letters, digits, "_" or "-" (no ":" or whitespace)', `Rename the group on leaf ${path}.`, `${path}.group`);
602
+ return null;
603
+ }
604
+ const rest = validateRestMapping(raw['rest'], path, params, issue);
605
+ return rest === null ? null : { ...base, rest, ...(group !== undefined ? { group: group } : {}) };
606
+ }
607
+ // REST mapping validation (§4.4)
608
+ const REST_METHODS_SET = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
609
+ // RFC 7230 `token` grammar — the legal charset for an HTTP header field name.
610
+ const HTTP_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
611
+ const REST_PARAM_PLACEMENT_SET = new Set(['path', 'query', 'body', 'header']);
612
+ function validateRestMapping(raw, basePath, params, issue) {
613
+ const path = `${basePath}.rest`;
614
+ if (!isRecord(raw)) {
615
+ issue('command_rest_invalid', `rest must be an object`, typeName(raw), '{ method, path, streaming?, params }', 'Provide a valid rest mapping.', path);
616
+ return null;
617
+ }
618
+ // Check for unknown keys
619
+ const allowedKeys = new Set(['method', 'path', 'streaming', 'body', 'bodyRoot', 'params']);
620
+ const unknownKeys = Object.keys(raw).filter((k) => !allowedKeys.has(k));
621
+ if (unknownKeys.length > 0) {
622
+ issue('command_rest_invalid', `unknown rest keys`, unknownKeys.join(', '), 'only: method, path, streaming, body, bodyRoot, params', 'Remove the unknown keys.', path);
623
+ return null;
624
+ }
625
+ // Validate method (required)
626
+ const method = raw['method'];
627
+ if (typeof method !== 'string' || !REST_METHODS_SET.has(method)) {
628
+ issue('command_rest_invalid', `method must be GET|POST|PUT|PATCH|DELETE`, String(method), 'one of the HTTP methods', 'Set method to a valid HTTP verb.', `${path}.method`);
629
+ return null;
630
+ }
631
+ // Validate path (required, must start with /)
632
+ const restPath = raw['path'];
633
+ if (typeof restPath !== 'string' || !restPath.startsWith('/')) {
634
+ issue('command_rest_invalid', `path must be an absolute path starting with /`, String(restPath), 'an absolute path like "/v1/devices/{id}"', 'Fix the path.', `${path}.path`);
635
+ return null;
636
+ }
637
+ // Extract and validate placeholders in path
638
+ const placeholders = new Set();
639
+ const placeholderRegex = /\{([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\}/g;
640
+ let match;
641
+ while ((match = placeholderRegex.exec(restPath)) !== null) {
642
+ placeholders.add(match[1]);
643
+ }
644
+ // Validate streaming (optional, default false)
645
+ let streaming = false;
646
+ if (raw['streaming'] !== undefined) {
647
+ if (typeof raw['streaming'] !== 'boolean') {
648
+ issue('command_rest_invalid', `streaming must be a boolean`, typeName(raw['streaming']), 'true | false | omitted', 'Fix streaming.', `${path}.streaming`);
649
+ return null;
650
+ }
651
+ streaming = raw['streaming'];
652
+ }
653
+ // Validate params mapping (required object)
654
+ const restParams = raw['params'];
655
+ if (!isRecord(restParams)) {
656
+ issue('command_rest_invalid', `params must be an object`, typeName(restParams), 'a mapping of param names to placement specs', 'Provide params.', `${path}.params`);
657
+ return null;
658
+ }
659
+ // Build param name to param object map
660
+ const paramsByName = new Map();
661
+ for (const p of params) {
662
+ paramsByName.set(p.name, p);
663
+ }
664
+ // Validate each REST param mapping
665
+ const restParamMappings = {};
666
+ const bodyParams = [];
667
+ const declaredNames = new Set();
668
+ for (const [paramName, mapping] of Object.entries(restParams)) {
669
+ if (!paramsByName.has(paramName)) {
670
+ issue('command_rest_invalid', `rest params key has no matching declared param`, paramName, 'a name from the leaf params array', 'Remove this rest params entry or declare the param.', `${path}.params.${paramName}`);
671
+ return null;
672
+ }
673
+ declaredNames.add(paramName);
674
+ if (!isRecord(mapping)) {
675
+ issue('command_rest_invalid', `param mapping must be an object`, typeName(mapping), '{ in, as? }', 'Fix the param mapping.', `${path}.params.${paramName}`);
676
+ return null;
677
+ }
678
+ const allowedMappingKeys = new Set(['in', 'as']);
679
+ const unknownMappingKeys = Object.keys(mapping).filter((k) => !allowedMappingKeys.has(k));
680
+ if (unknownMappingKeys.length > 0) {
681
+ issue('command_rest_invalid', `unknown param mapping keys`, unknownMappingKeys.join(', '), 'only: in, as', 'Remove the unknown keys.', `${path}.params.${paramName}`);
682
+ return null;
683
+ }
684
+ const inValue = mapping['in'];
685
+ if (typeof inValue !== 'string' || !REST_PARAM_PLACEMENT_SET.has(inValue)) {
686
+ issue('command_rest_invalid', `param placement must be path|query|body|header`, String(inValue), 'path | query | body | header', 'Set in to a valid placement.', `${path}.params.${paramName}.in`);
687
+ return null;
688
+ }
689
+ const asValue = mapping['as'];
690
+ if (asValue !== undefined && (typeof asValue !== 'string' || asValue.length === 0)) {
691
+ issue('command_rest_invalid', `as must be a non-empty string`, String(asValue), 'a non-empty string', 'Fix the as value.', `${path}.params.${paramName}.as`);
692
+ return null;
693
+ }
694
+ // Validate 'as' placement rules
695
+ if (inValue === 'header') {
696
+ if (typeof asValue !== 'string' || asValue.length === 0) {
697
+ issue('command_rest_invalid', `header placement requires a non-empty as`, String(asValue), 'a header name', 'Provide an as value for the header name.', `${path}.params.${paramName}.as`);
698
+ return null;
699
+ }
700
+ // The header name becomes a real HTTP field name at invoke time (Node's
701
+ // req.setHeader throws ERR_INVALID_HTTP_TOKEN for an illegal one) — reject
702
+ // it here so a malformed manifest fails a structured, static check instead.
703
+ if (!HTTP_TOKEN.test(asValue)) {
704
+ issue('command_rest_invalid', `header "as" must be a legal HTTP header field name`, asValue, 'an HTTP token (letters, digits, and !#$%&\'*+-.^_`|~)', 'Fix the header name.', `${path}.params.${paramName}.as`);
705
+ return null;
706
+ }
707
+ if (asValue.toLowerCase() === 'crtr-request-id') {
708
+ issue('command_rest_invalid', `Crtr-Request-Id is assigned by crtr for each leaf call`, asValue, 'a header name other than Crtr-Request-Id', 'Remove this header mapping.', `${path}.params.${paramName}.as`);
709
+ return null;
710
+ }
711
+ }
712
+ else if (inValue === 'path') {
713
+ if (asValue !== undefined) {
714
+ issue('command_rest_invalid', `path placement must not have as`, 'as', 'no as (placeholder name governs)', 'Remove as.', `${path}.params.${paramName}.as`);
715
+ return null;
716
+ }
717
+ // §4.4: a path placeholder must always be filled, so the underlying param
718
+ // must itself be required — otherwise an omitted call renders the literal
719
+ // string "undefined" into the URL.
720
+ const pathParam = paramsByName.get(paramName);
721
+ if (pathParam.required !== true) {
722
+ issue('command_rest_invalid', `in:"path" param must be declared required`, `${paramName}: required ${String(pathParam.required)}`, 'required: true', `Set "required": true on the "${paramName}" param.`, `${path}.params.${paramName}`);
723
+ return null;
724
+ }
725
+ }
726
+ // A repeatable param's parsed value is an array; only JSON body placement
727
+ // can carry it faithfully (query/header/path would String() it into "a,b").
728
+ const mappedParam = paramsByName.get(paramName);
729
+ if ((mappedParam.kind === 'flag' || mappedParam.kind === 'positional') && mappedParam.repeatable === true && inValue !== 'body') {
730
+ issue('command_rest_invalid', `repeatable param must use body placement`, `${paramName}: in "${inValue}"`, 'in: "body" (array values ship as a JSON array)', `Map "${paramName}" to body placement.`, `${path}.params.${paramName}.in`);
731
+ return null;
732
+ }
733
+ // Collect body params for coalesced source validation
734
+ if (inValue === 'body') {
735
+ const param = paramsByName.get(paramName);
736
+ const isStdin = param.kind === 'stdin';
737
+ const asName = asValue || paramName;
738
+ bodyParams.push({ name: paramName, isStdin, as: asName });
739
+ }
740
+ restParamMappings[paramName] = {
741
+ in: inValue,
742
+ ...(asValue !== undefined ? { as: asValue } : {}),
743
+ };
744
+ }
745
+ // Check that every declared param is in rest.params
746
+ for (const param of params) {
747
+ if (!declaredNames.has(param.name)) {
748
+ issue('command_rest_invalid', `declared param not in rest mapping`, param.name, 'an entry in rest.params', 'Add a rest mapping for this param.', `${path}.params`);
749
+ return null;
750
+ }
751
+ }
752
+ // Validate path placeholders ↔ path params bijection
753
+ const pathParams = new Set();
754
+ for (const [name, mapping] of Object.entries(restParamMappings)) {
755
+ if (mapping.in === 'path') {
756
+ pathParams.add(name);
757
+ }
758
+ }
759
+ if (pathParams.size !== placeholders.size || ![...placeholders].every((p) => pathParams.has(p))) {
760
+ issue('command_rest_invalid', `mismatch between path placeholders and path params`, `placeholders: ${[...placeholders].join(', ')} | params: ${[...pathParams].join(', ')}`, 'exact bijection between {placeholders} and in:"path" params', 'Ensure every placeholder has a matching path param, and vice versa.', `${path}.path and ${path}.params`);
761
+ return null;
762
+ }
763
+ // Validate no body placement on GET
764
+ if (method === 'GET') {
765
+ if (bodyParams.length > 0) {
766
+ issue('command_rest_invalid', `GET method cannot have body params`, bodyParams.map((p) => p.name).join(', '), 'no body placement for GET', 'Move body params to query, or change the method.', `${path}.method or ${path}.params`);
767
+ return null;
768
+ }
769
+ }
770
+ // Validate rest.body (constant literal body fields, e.g. an `op` discriminator)
771
+ // and rest.bodyRoot (nests all param-sourced body values under one key, e.g.
772
+ // `args`) — both forbidden on GET, same as body params.
773
+ let bodyConstants;
774
+ if (raw['body'] !== undefined) {
775
+ if (method === 'GET') {
776
+ issue('command_rest_invalid', `GET method cannot have body constants`, 'body', 'no body for GET', 'Remove body, or change the method.', `${path}.body`);
777
+ return null;
778
+ }
779
+ const rawBody = raw['body'];
780
+ if (!isRecord(rawBody)) {
781
+ issue('command_rest_invalid', `body must be an object`, typeName(rawBody), 'a map of constant literal body fields (string | number | boolean)', 'Fix body.', `${path}.body`);
782
+ return null;
783
+ }
784
+ const constants = {};
785
+ for (const [key, value] of Object.entries(rawBody)) {
786
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
787
+ issue('command_rest_invalid', `body.${key} must be a string, number, or boolean`, typeName(value), 'string | number | boolean', `Fix body.${key}.`, `${path}.body.${key}`);
788
+ return null;
789
+ }
790
+ constants[key] = value;
791
+ }
792
+ // A constant key must not collide with any param's effective body key (its
793
+ // `as` or name) — the constant and a param-sourced value can't both claim
794
+ // the same top-level (or, with bodyRoot set, the same nested) key.
795
+ const bodyParamKeys = new Set(bodyParams.map((p) => p.as));
796
+ const colliding = Object.keys(constants).filter((k) => bodyParamKeys.has(k));
797
+ if (colliding.length > 0) {
798
+ issue('command_rest_invalid', `body constant key collides with a param's body key`, colliding.join(', '), "body constant keys distinct from every param's body key (its as or name)", 'Rename the colliding body constant or param.', `${path}.body`);
799
+ return null;
800
+ }
801
+ bodyConstants = constants;
802
+ }
803
+ let bodyRoot;
804
+ if (raw['bodyRoot'] !== undefined) {
805
+ if (method === 'GET') {
806
+ issue('command_rest_invalid', `GET method cannot have bodyRoot`, 'bodyRoot', 'no bodyRoot for GET', 'Remove bodyRoot, or change the method.', `${path}.bodyRoot`);
807
+ return null;
808
+ }
809
+ const rawBodyRoot = raw['bodyRoot'];
810
+ if (typeof rawBodyRoot !== 'string' || rawBodyRoot.length === 0) {
811
+ issue('command_rest_invalid', `bodyRoot must be a non-empty string`, typeName(rawBodyRoot), 'a non-empty string key', 'Fix bodyRoot.', `${path}.bodyRoot`);
812
+ return null;
813
+ }
814
+ bodyRoot = rawBodyRoot;
815
+ }
816
+ // Validate file params: only context-file and any type:"path" param (positional
817
+ // or flag) can be placed in body — §4.4's "path param" covers both authoring forms.
818
+ for (const [name, placement] of Object.entries(restParamMappings)) {
819
+ const param = paramsByName.get(name);
820
+ const isFileParam = param.kind === 'context-file' ||
821
+ ((param.kind === 'positional' || param.kind === 'flag') && param.type === 'path');
822
+ if (isFileParam && placement.in !== 'body') {
823
+ const paramKind = param.kind === 'context-file' ? 'context-file' : `path ${param.kind}`;
824
+ issue('command_rest_invalid', `file param (${paramKind}) must be placed in body`, `${name}: in "${placement.in}"`, 'in: "body"', 'Move the file param to body.', `${path}.params.${name}.in`);
825
+ return null;
826
+ }
827
+ }
828
+ // Validate coalesced body source rule: exactly one stdin + one non-stdin sharing same `as`
829
+ const bodyAsGroups = new Map();
830
+ for (const bp of bodyParams) {
831
+ if (!bodyAsGroups.has(bp.as)) {
832
+ bodyAsGroups.set(bp.as, []);
833
+ }
834
+ bodyAsGroups.get(bp.as).push({ name: bp.name, isStdin: bp.isStdin });
835
+ }
836
+ for (const [asName, group] of bodyAsGroups.entries()) {
837
+ if (group.length > 1) {
838
+ // Multiple params sharing the same body `as`
839
+ const stdinCount = group.filter((g) => g.isStdin).length;
840
+ const nonStdinCount = group.filter((g) => !g.isStdin).length;
841
+ // Only valid if exactly one stdin + one non-stdin
842
+ if (!(stdinCount === 1 && nonStdinCount === 1)) {
843
+ issue('command_rest_invalid', `invalid body as grouping`, group.map((g) => g.name).join(', '), 'exactly one stdin param and one non-stdin param may share a body as (for coalesced sources)', 'Fix the body grouping.', `${path}.params (as: "${asName}")`);
844
+ return null;
845
+ }
846
+ }
847
+ }
848
+ return {
849
+ method: method,
850
+ path: restPath,
851
+ ...(streaming !== false ? { streaming } : {}),
852
+ ...(bodyConstants !== undefined ? { body: bodyConstants } : {}),
853
+ ...(bodyRoot !== undefined ? { bodyRoot } : {}),
854
+ params: restParamMappings,
855
+ };
856
+ }