@akai-workflow-builder/cli-sdk 0.2.0 → 0.3.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/define-connection.d.ts.map +1 -1
  3. package/dist/define-connection.js +3 -6
  4. package/dist/runtime/execute-request.d.ts +25 -0
  5. package/dist/runtime/execute-request.d.ts.map +1 -0
  6. package/dist/runtime/execute-request.js +36 -0
  7. package/dist/runtime/executor/classify-error.d.ts +11 -0
  8. package/dist/runtime/executor/classify-error.d.ts.map +1 -0
  9. package/dist/runtime/executor/classify-error.js +162 -0
  10. package/dist/runtime/executor/image-compress.d.ts +26 -0
  11. package/dist/runtime/executor/image-compress.d.ts.map +1 -0
  12. package/dist/runtime/executor/image-compress.js +202 -0
  13. package/dist/runtime/executor/index.d.ts +44 -0
  14. package/dist/runtime/executor/index.d.ts.map +1 -0
  15. package/dist/runtime/executor/index.js +393 -0
  16. package/dist/runtime/executor/redact.d.ts +9 -0
  17. package/dist/runtime/executor/redact.d.ts.map +1 -0
  18. package/dist/runtime/executor/redact.js +23 -0
  19. package/dist/runtime/index.d.ts +15 -0
  20. package/dist/runtime/index.d.ts.map +1 -0
  21. package/dist/runtime/index.js +13 -0
  22. package/dist/runtime/registry/index.d.ts +5 -0
  23. package/dist/runtime/registry/index.d.ts.map +1 -0
  24. package/dist/runtime/registry/index.js +1 -0
  25. package/dist/runtime/registry/loader.d.ts +42 -0
  26. package/dist/runtime/registry/loader.d.ts.map +1 -0
  27. package/dist/runtime/registry/loader.js +621 -0
  28. package/dist/runtime/registry/types.d.ts +252 -0
  29. package/dist/runtime/registry/types.d.ts.map +1 -0
  30. package/dist/runtime/registry/types.js +1 -0
  31. package/dist/runtime/registry/wire.d.ts +152 -0
  32. package/dist/runtime/registry/wire.d.ts.map +1 -0
  33. package/dist/runtime/registry/wire.js +299 -0
  34. package/dist/types.d.ts +7 -9
  35. package/dist/types.d.ts.map +1 -1
  36. package/package.json +22 -2
@@ -0,0 +1,621 @@
1
+ /**
2
+ * Tool registry loader.
3
+ *
4
+ * At boot the service scans one or two filesystem paths — baseline (always)
5
+ * and customer (optional) — for SDK-authored CLI packages. Each package
6
+ * directory has a `package.json` whose `main` (or default `dist/index.js`)
7
+ * points at a module that default-exports a `defineCLI()` result, a
8
+ * `defineConnection()` result, or an array mixing both. The loader
9
+ * dynamic-imports each entry, normalizes the export to an array, and buckets
10
+ * each element by brand (`__akaiCLI` → registry entry, `__akaiConnection` →
11
+ * connection entry). Both brands are mutually exclusive on a real def.
12
+ *
13
+ * Both baseline and customer entries are first-class — `lookupTool` doesn't
14
+ * distinguish; the `source` is preserved on each entry for logging/audit
15
+ * but isn't consulted during dispatch.
16
+ *
17
+ * The brand markers are the contract for what a package IS; specific shape
18
+ * validation happens at the call site (the execute route's input-schema
19
+ * check, etc.). The one contract the loader shares with the SDK is the set of
20
+ * dynamic-egress prefixes (`property:` | `secret:`), imported from the SDK so
21
+ * the two never drift.
22
+ */
23
+ import { promises as fs } from 'node:fs';
24
+ import path from 'node:path';
25
+ import { pathToFileURL } from 'node:url';
26
+ import { DYNAMIC_EGRESS_PREFIXES } from '../../tool.js';
27
+ export class Registry {
28
+ // Map keyed by `cli.id`. Stable iteration order matches insertion which
29
+ // matches directory-listing order from `fs.readdir` (sorted).
30
+ byCliId;
31
+ // Map keyed by `connection.slug`. CLIs join to a connection by
32
+ // `connectionSlug` at the wire layer; the connection itself is identity-only.
33
+ byConnectionSlug;
34
+ // Packages skipped at load (recorded, not thrown): a customer package that
35
+ // failed the brand/shape check, OR either side of a duplicate id/slug whose
36
+ // later definition was dropped (see `resolveCollision`). A *malformed* baseline
37
+ // package still fails the boot hard; a *duplicate* never does (non-strict).
38
+ loadFailures;
39
+ constructor(entries, connections, loadFailures) {
40
+ this.byCliId = new Map();
41
+ for (const e of entries)
42
+ this.byCliId.set(e.cli.id, e);
43
+ this.byConnectionSlug = new Map();
44
+ for (const c of connections)
45
+ this.byConnectionSlug.set(c.connection.slug, c);
46
+ this.loadFailures = loadFailures;
47
+ }
48
+ static async load(opts) {
49
+ const failures = [];
50
+ // Keyed by cli.id / connection.slug so a collision can either drop the
51
+ // newcomer or REPLACE the incumbent (explicit override) — the map keeps the
52
+ // original insertion position on replace, so load order stays stable.
53
+ const cliById = new Map();
54
+ const connBySlug = new Map();
55
+ const strict = opts.strict ?? false;
56
+ const logger = opts.logger;
57
+ /**
58
+ * Resolve a collision between an already-loaded entry and an `incoming` one
59
+ * sharing its id/slug. Returns `true` iff `incoming` should REPLACE the
60
+ * incumbent. Precedence:
61
+ * 1. A CUSTOMER package that declares `override: true` replaces a BASELINE
62
+ * incumbent — the opt-in escape hatch for a tenant intentionally
63
+ * customising a first-party tool. This is the ONLY case an override is
64
+ * honored: override on a baseline package, or a customer overriding
65
+ * another customer, is NOT honored (a customer must never be able to
66
+ * grant itself precedence over anything but baseline, and baseline
67
+ * never needs it — our own CI gates baseline dups).
68
+ * 2. Otherwise FIRST definition wins. Baseline is scanned before customer,
69
+ * so baseline beats an accidental customer collision and a customer can
70
+ * never silently shadow a first-party tool.
71
+ * The loser is recorded as a `LoadFailure`; boot never fails on a duplicate.
72
+ * In strict mode (CI/authoring) an ACCIDENTAL collision throws so a PR fails
73
+ * pre-merge — but an honored customer override is intentional, so it is
74
+ * recorded (`kind: 'overridden'`) and never throws, even in strict mode.
75
+ */
76
+ const resolveCollision = (kind, key, existing, incoming) => {
77
+ // Honor override ONLY for a customer package replacing a baseline incumbent.
78
+ // `intentional` tracks exactly that honored case, so a non-override newcomer
79
+ // colliding with an incumbent that merely happens to carry `override` is
80
+ // still an accidental duplicate (throws under strict, recorded otherwise).
81
+ const intentional = incoming.override === true && incoming.source === 'customer' && existing.source === 'baseline';
82
+ const replace = intentional;
83
+ const winner = replace ? incoming : existing;
84
+ const loser = replace ? existing : incoming;
85
+ const detail = `duplicate ${kind} '${key}' — kept ${winner.packagePath} (${winner.source}), ` +
86
+ `dropped ${loser.packagePath} (${loser.source})${intentional ? ' [explicit customer override]' : ''}`;
87
+ if (strict && !intentional)
88
+ throw new Error(`registry: ${detail}`);
89
+ if (intentional) {
90
+ logger?.warn({ key, kind, kept: winner.packagePath, dropped: loser.packagePath }, `registry: ${detail}`);
91
+ }
92
+ else {
93
+ logger?.error({ key, kind, kept: winner.packagePath, dropped: loser.packagePath }, `registry: ${detail} — first definition wins, dropped package is unavailable`);
94
+ }
95
+ failures.push({
96
+ packagePath: loser.packagePath,
97
+ source: loser.source,
98
+ error: `registry: ${detail}`,
99
+ kind: intentional ? 'overridden' : 'duplicate',
100
+ keptSource: winner.source,
101
+ });
102
+ return replace;
103
+ };
104
+ const ingest = (loaded) => {
105
+ for (const item of loaded) {
106
+ if (item.kind === 'cli') {
107
+ const e = item.entry;
108
+ const existing = cliById.get(e.cli.id);
109
+ if (existing) {
110
+ const replace = resolveCollision('CLI id', e.cli.id, { packagePath: existing.packagePath, source: existing.source, override: existing.cli.override === true }, { packagePath: e.packagePath, source: e.source, override: e.cli.override === true });
111
+ if (replace)
112
+ cliById.set(e.cli.id, e);
113
+ continue;
114
+ }
115
+ cliById.set(e.cli.id, e);
116
+ }
117
+ else {
118
+ const c = item.entry;
119
+ const existing = connBySlug.get(c.connection.slug);
120
+ if (existing) {
121
+ const replace = resolveCollision('connection slug', c.connection.slug, { packagePath: existing.packagePath, source: existing.source, override: existing.connection.override === true }, { packagePath: c.packagePath, source: c.source, override: c.connection.override === true });
122
+ if (replace)
123
+ connBySlug.set(c.connection.slug, c);
124
+ continue;
125
+ }
126
+ connBySlug.set(c.connection.slug, c);
127
+ }
128
+ }
129
+ };
130
+ // INVARIANT: baseline is ingested BEFORE customer. The whole "first
131
+ // definition wins ⇒ baseline wins" guarantee — and the safety property that
132
+ // a customer can only ever displace baseline via an explicit override, never
133
+ // silently — rests on this ordering. Do not reorder these two blocks, and do
134
+ // not route baseline packages through `customerPath` (source is assigned by
135
+ // which path a package came from): either would let a customer shadow a
136
+ // first-party tool, the exact outage class this loader defends against.
137
+ if (opts.baselinePath) {
138
+ const scan = await scanPath(opts.baselinePath, 'baseline', opts.logger);
139
+ ingest(scan.loaded);
140
+ failures.push(...scan.failures);
141
+ }
142
+ if (opts.customerPath) {
143
+ const scan = await scanPath(opts.customerPath, 'customer', opts.logger);
144
+ ingest(scan.loaded);
145
+ failures.push(...scan.failures);
146
+ }
147
+ return new Registry(Array.from(cliById.values()), Array.from(connBySlug.values()), failures);
148
+ }
149
+ lookupTool(cliId, toolKey) {
150
+ const entry = this.byCliId.get(cliId);
151
+ if (!entry)
152
+ return undefined;
153
+ const tool = entry.cli.tools[toolKey];
154
+ if (!tool)
155
+ return undefined;
156
+ return { cli: entry.cli, toolKey, tool, source: entry.source };
157
+ }
158
+ entries() {
159
+ return Array.from(this.byCliId.values());
160
+ }
161
+ connections() {
162
+ return Array.from(this.byConnectionSlug.values());
163
+ }
164
+ /** Packages skipped at load: failed brand/shape check, or the dropped side of
165
+ * a duplicate id/slug collision. */
166
+ failures() {
167
+ return this.loadFailures;
168
+ }
169
+ stats() {
170
+ let baselineCount = 0;
171
+ let customerCount = 0;
172
+ let toolCount = 0;
173
+ for (const e of this.byCliId.values()) {
174
+ if (e.source === 'baseline')
175
+ baselineCount++;
176
+ else
177
+ customerCount++;
178
+ toolCount += Object.keys(e.cli.tools).length;
179
+ }
180
+ for (const c of this.byConnectionSlug.values()) {
181
+ if (c.source === 'baseline')
182
+ baselineCount++;
183
+ else
184
+ customerCount++;
185
+ }
186
+ // An intentional override is not a load failure — split it out so
187
+ // `failedCount` means "something actually went wrong" (safe to alert on).
188
+ let overriddenCount = 0;
189
+ for (const f of this.loadFailures)
190
+ if (f.kind === 'overridden')
191
+ overriddenCount++;
192
+ return {
193
+ cliCount: this.byCliId.size,
194
+ toolCount,
195
+ connectionCount: this.byConnectionSlug.size,
196
+ baselineCount,
197
+ customerCount,
198
+ failedCount: this.loadFailures.length - overriddenCount,
199
+ overriddenCount,
200
+ };
201
+ }
202
+ }
203
+ /**
204
+ * Scan one root directory for SDK-authored CLI packages. Each immediate
205
+ * subdirectory is treated as a candidate package; non-directory entries are
206
+ * skipped silently. Per package we read `package.json` to find the entry
207
+ * point (`main`, defaulting to `dist/index.js`), dynamic-import it, and
208
+ * brand-check the default export.
209
+ *
210
+ * A package with no `package.json` or no resolvable entry file is logged
211
+ * and skipped (`resolveEntryPoint` returns undefined) — a directory that
212
+ * isn't a package shouldn't block startup.
213
+ *
214
+ * A package that IS a loadable module but fails the brand/shape check is
215
+ * handled by `source`:
216
+ * - `baseline` (first-party, gated by our own CI): throws immediately. A
217
+ * broken baseline is a bad deploy we want to halt.
218
+ * - `customer` (third-party): logged loudly, recorded as a `LoadFailure`, and
219
+ * skipped — one customer's broken package must not take every tenant's
220
+ * tools down. This is NOT a silent half-load: each skip is recorded
221
+ * explicitly, so the catalog view stays deterministic ("these loaded,
222
+ * these are unavailable: <reason>").
223
+ */
224
+ async function scanPath(root, source, logger) {
225
+ let dirents;
226
+ try {
227
+ dirents = await fs.readdir(root, { withFileTypes: true });
228
+ }
229
+ catch (err) {
230
+ const code = err.code;
231
+ if (code === 'ENOENT') {
232
+ // Configured path doesn't exist — treat as empty rather than failing.
233
+ // This is the local-dev case where AKAI_CUSTOMER_PACKAGES isn't set.
234
+ logger?.warn({ root, source }, 'registry: package root does not exist; treating as empty');
235
+ return { loaded: [], failures: [] };
236
+ }
237
+ throw err;
238
+ }
239
+ const loaded = [];
240
+ const failures = [];
241
+ // Sort for stable load order — useful for deterministic startup logs and
242
+ // for "which package's tools shadow which" debugging if duplicates land.
243
+ const subdirs = dirents
244
+ .filter((d) => d.isDirectory())
245
+ .map((d) => d.name)
246
+ .sort();
247
+ for (const name of subdirs) {
248
+ const packagePath = path.join(root, name);
249
+ const entryPoint = await resolveEntryPoint(packagePath);
250
+ if (!entryPoint) {
251
+ logger?.warn({ packagePath }, 'registry: skipping — no package.json or resolvable entry point');
252
+ continue;
253
+ }
254
+ try {
255
+ for (const item of await loadPackageEntry(entryPoint, packagePath, source)) {
256
+ loaded.push(item);
257
+ }
258
+ }
259
+ catch (err) {
260
+ // Baseline failures fail the boot hard (first-party, gated by our CI).
261
+ // A broken customer package is skipped + recorded so it can't take every
262
+ // tenant's tools down with it.
263
+ if (source === 'baseline')
264
+ throw err;
265
+ const message = err instanceof Error ? err.message : String(err);
266
+ logger?.error({ packagePath, source, error: message }, 'registry: customer package failed to load — skipping');
267
+ failures.push({ packagePath, source, error: message });
268
+ }
269
+ }
270
+ return { loaded, failures };
271
+ }
272
+ async function resolveEntryPoint(packagePath) {
273
+ const manifestPath = path.join(packagePath, 'package.json');
274
+ let manifest;
275
+ try {
276
+ const raw = await fs.readFile(manifestPath, 'utf8');
277
+ manifest = JSON.parse(raw);
278
+ }
279
+ catch (err) {
280
+ if (err.code === 'ENOENT')
281
+ return undefined;
282
+ throw new Error(`registry: failed to read ${manifestPath}: ${err.message}`);
283
+ }
284
+ const mainRel = typeof manifest.main === 'string' ? manifest.main : 'dist/index.js';
285
+ const entry = path.resolve(packagePath, mainRel);
286
+ try {
287
+ await fs.access(entry);
288
+ }
289
+ catch {
290
+ return undefined;
291
+ }
292
+ return entry;
293
+ }
294
+ /**
295
+ * Load one package's default export and bucket it. The default export is
296
+ * normalized to an array — a lone `defineCLI()`/`defineConnection()` result OR
297
+ * an array of them (the `connections/` package default-exports a Connection[],
298
+ * a customer package may export a mixed `[cli, connection]`). Each item is
299
+ * brand-checked as a CLI xor a Connection; anything else fails fast so a
300
+ * malformed package can't half-load the registry.
301
+ */
302
+ async function loadPackageEntry(entryPoint, packagePath, source) {
303
+ // Dynamic import via file:// URL so absolute paths outside node_modules
304
+ // resolve correctly on Node ESM.
305
+ const url = pathToFileURL(entryPoint).href;
306
+ let mod;
307
+ try {
308
+ mod = (await import(url));
309
+ }
310
+ catch (err) {
311
+ throw new Error(`registry: failed to import ${entryPoint}: ${err.message}`);
312
+ }
313
+ const items = Array.isArray(mod.default) ? mod.default : [mod.default];
314
+ if (items.length === 0) {
315
+ throw new Error(`registry: ${packagePath} default export is an empty array (expected at least one defineCLI()/defineConnection() result)`);
316
+ }
317
+ const loaded = [];
318
+ for (const candidate of items) {
319
+ if (isBrandedCLI(candidate)) {
320
+ validateTools(candidate, packagePath);
321
+ loaded.push({ kind: 'cli', entry: { cli: candidate, source, packagePath } });
322
+ continue;
323
+ }
324
+ if (isBrandedConnection(candidate)) {
325
+ loaded.push({
326
+ kind: 'connection',
327
+ entry: { connection: candidate, source, packagePath },
328
+ });
329
+ continue;
330
+ }
331
+ throw new Error(`registry: ${packagePath} default export is neither a defineCLI() nor a defineConnection() result (missing __akaiCLI/__akaiConnection brand or required fields)`);
332
+ }
333
+ return loaded;
334
+ }
335
+ function isBrandedCLI(x) {
336
+ if (x === null || typeof x !== 'object')
337
+ return false;
338
+ const o = x;
339
+ if (o.__akaiCLI !== true)
340
+ return false;
341
+ if (typeof o.id !== 'string' || o.id.length === 0)
342
+ return false;
343
+ if (typeof o.name !== 'string' || o.name.length === 0)
344
+ return false;
345
+ // Wire serialization (/tools/list) reads these unconditionally — spreading
346
+ // `instructions`, mapping `secrets`, emitting `vendor`/`summary`. Validate
347
+ // them here so a malformed package fails with a registry error at load time
348
+ // instead of a TypeError when the list payload is precomputed.
349
+ if (typeof o.vendor !== 'string')
350
+ return false;
351
+ if (typeof o.summary !== 'string')
352
+ return false;
353
+ // `/tools/list` spreads `instructions` onto the wire verbatim, so a
354
+ // non-string element (e.g. `[null]`) would pass a bare Array.isArray check
355
+ // and leak onto the wire — validate each element is a string at load time.
356
+ if (!Array.isArray(o.instructions) || !o.instructions.every((i) => typeof i === 'string')) {
357
+ return false;
358
+ }
359
+ // `/tools/list` maps each secret to `{ name, description, required, key }`.
360
+ // An array of non-conformant elements (e.g. `[null]`) would pass a bare
361
+ // Array.isArray check and then throw when the wire payload is precomputed —
362
+ // validate each element's shape here so the failure is a load-time registry
363
+ // error instead.
364
+ if (!Array.isArray(o.secrets) || !o.secrets.every(isBrandedSecretDecl))
365
+ return false;
366
+ // `properties` is optional + additive (older packages omit it). When present
367
+ // the wire serializer maps each element, so reject a malformed array at load
368
+ // time rather than throwing when the list payload is precomputed.
369
+ if (o.properties !== undefined && (!Array.isArray(o.properties) || !o.properties.every(isBrandedPropertyDecl))) {
370
+ return false;
371
+ }
372
+ // Optional + additive: the cross-repo override opt-in. Reject a non-boolean so
373
+ // a malformed value can't be mistaken for intent at collision time.
374
+ if (o.override !== undefined && typeof o.override !== 'boolean')
375
+ return false;
376
+ if (typeof o.tools !== 'object' || o.tools === null)
377
+ return false;
378
+ return true;
379
+ }
380
+ /**
381
+ * Brand + shape check for a `defineConnection()` result. Same rigor as
382
+ * `isBrandedCLI`: the wire serializer reads every field unconditionally, so a
383
+ * malformed connection must fail at load time, not when the list payload is
384
+ * precomputed. A customer package exporting a mixed `[cli, connection]` default
385
+ * relies on this to disambiguate from `isBrandedCLI` — the `__akaiConnection`
386
+ * brand and `__akaiCLI` brand are mutually exclusive on a real def.
387
+ */
388
+ function isBrandedConnection(x) {
389
+ if (x === null || typeof x !== 'object')
390
+ return false;
391
+ const o = x;
392
+ if (o.__akaiConnection !== true)
393
+ return false;
394
+ if (o.__akaiCLI === true)
395
+ return false; // brands are mutually exclusive
396
+ if (typeof o.slug !== 'string' || o.slug.length === 0)
397
+ return false;
398
+ if (typeof o.name !== 'string' || o.name.length === 0)
399
+ return false;
400
+ if (typeof o.vendor !== 'string' || o.vendor.length === 0)
401
+ return false;
402
+ if (typeof o.blurb !== 'string')
403
+ return false;
404
+ if (typeof o.longDesc !== 'string')
405
+ return false;
406
+ if (!Array.isArray(o.instructions) || !o.instructions.every((i) => typeof i === 'string')) {
407
+ return false;
408
+ }
409
+ if (!isConnectionAuthKind(o.authKind))
410
+ return false;
411
+ // oauth is required for oauth2 and forbidden for all other authKinds.
412
+ if (o.authKind === 'oauth2' && o.oauth === undefined)
413
+ return false;
414
+ if (o.authKind !== 'oauth2' && o.oauth !== undefined)
415
+ return false;
416
+ if (o.oauth !== undefined && !isBrandedConnectionOAuth(o.oauth))
417
+ return false;
418
+ // Optional wire-relevant fields — the /tools/list serializer reads each
419
+ // unconditionally, so a present-but-malformed value must fail at load, not
420
+ // when the list payload is precomputed.
421
+ if (o.secrets !== undefined && (!Array.isArray(o.secrets) || !o.secrets.every(isBrandedSecretDecl))) {
422
+ return false;
423
+ }
424
+ if (o.apiKeyHeader !== undefined && typeof o.apiKeyHeader !== 'string')
425
+ return false;
426
+ if (o.hosts !== undefined && !isConnectionHosts(o.hosts))
427
+ return false;
428
+ if (o.nativeBuiltin !== undefined && typeof o.nativeBuiltin !== 'boolean')
429
+ return false;
430
+ // Optional + additive: the cross-repo override opt-in (see BrandedCLI).
431
+ if (o.override !== undefined && typeof o.override !== 'boolean')
432
+ return false;
433
+ return true;
434
+ }
435
+ function isConnectionAuthKind(x) {
436
+ return x === 'apiKey' || x === 'oauth2' || x === 'none';
437
+ }
438
+ /** Validate the optional per-env host map — known keys must be strings when present. */
439
+ function isConnectionHosts(x) {
440
+ if (x === null || typeof x !== 'object')
441
+ return false;
442
+ const o = x;
443
+ for (const k of ['production', 'demo', 'dev']) {
444
+ if (o[k] !== undefined && typeof o[k] !== 'string')
445
+ return false;
446
+ }
447
+ return true;
448
+ }
449
+ function isBrandedConnectionOAuth(x) {
450
+ if (x === null || typeof x !== 'object')
451
+ return false;
452
+ const o = x;
453
+ if (typeof o.authorizeUrl !== 'string' || o.authorizeUrl.length === 0)
454
+ return false;
455
+ if (typeof o.tokenUrl !== 'string' || o.tokenUrl.length === 0)
456
+ return false;
457
+ // `scopes` is optional — the wire serializer defaults a missing list to [].
458
+ // Only a present-but-malformed value is a load-time error.
459
+ if (o.scopes !== undefined && (!Array.isArray(o.scopes) || !o.scopes.every((s) => typeof s === 'string'))) {
460
+ return false;
461
+ }
462
+ if (o.pkce !== undefined && typeof o.pkce !== 'boolean')
463
+ return false;
464
+ if (o.tokenEndpointAuthMethod !== undefined &&
465
+ o.tokenEndpointAuthMethod !== 'client_secret_post' &&
466
+ o.tokenEndpointAuthMethod !== 'client_secret_basic') {
467
+ return false;
468
+ }
469
+ if (o.refreshStrategy !== undefined && o.refreshStrategy !== 'cron' && o.refreshStrategy !== 'jit') {
470
+ return false;
471
+ }
472
+ if (o.extraAuthorizeParams !== undefined && !isStringRecord(o.extraAuthorizeParams))
473
+ return false;
474
+ if (!Array.isArray(o.adminFields) || !o.adminFields.every(isBrandedOAuthAdminField))
475
+ return false;
476
+ if (o.hasCustomConnectFlow !== undefined && typeof o.hasCustomConnectFlow !== 'boolean')
477
+ return false;
478
+ // Optional wire-relevant fields the serializer (toWireConnection) reads — validate
479
+ // when present so the `is BrandedConnectionOAuth` assertion is honest at load time.
480
+ if (o.tokenResponsePath !== undefined && typeof o.tokenResponsePath !== 'string')
481
+ return false;
482
+ if (o.appToken !== undefined && !isBrandedAppToken(o.appToken))
483
+ return false;
484
+ return true;
485
+ }
486
+ /** Validate the optional client-credentials app-token mint spec on an OAuth connection. */
487
+ function isBrandedAppToken(x) {
488
+ if (x === null || typeof x !== 'object')
489
+ return false;
490
+ const o = x;
491
+ if (typeof o.tokenUrl !== 'string' || o.tokenUrl.length === 0)
492
+ return false;
493
+ if (o.requestStyle !== undefined && o.requestStyle !== 'oauth2_client_credentials' && o.requestStyle !== 'json') {
494
+ return false;
495
+ }
496
+ if (o.credentialParams !== undefined) {
497
+ const c = o.credentialParams;
498
+ if (c === null || typeof c !== 'object')
499
+ return false;
500
+ const cp = c;
501
+ if (typeof cp.id !== 'string' || typeof cp.secret !== 'string')
502
+ return false;
503
+ }
504
+ if (o.tokenField !== undefined && typeof o.tokenField !== 'string')
505
+ return false;
506
+ if (o.expiresField !== undefined && typeof o.expiresField !== 'string')
507
+ return false;
508
+ return true;
509
+ }
510
+ function isStringRecord(x) {
511
+ if (x === null || typeof x !== 'object' || Array.isArray(x))
512
+ return false;
513
+ return Object.values(x).every((v) => typeof v === 'string');
514
+ }
515
+ function isBrandedOAuthAdminField(x) {
516
+ if (x === null || typeof x !== 'object')
517
+ return false;
518
+ const o = x;
519
+ if (typeof o.key !== 'string' || o.key.length === 0)
520
+ return false;
521
+ if (typeof o.label !== 'string' || o.label.length === 0)
522
+ return false;
523
+ if (o.secret !== undefined && typeof o.secret !== 'boolean')
524
+ return false;
525
+ return true;
526
+ }
527
+ function isBrandedSecretDecl(x) {
528
+ if (x === null || typeof x !== 'object')
529
+ return false;
530
+ const o = x;
531
+ return (typeof o.name === 'string' &&
532
+ typeof o.description === 'string' &&
533
+ typeof o.required === 'boolean' &&
534
+ typeof o.key === 'string' &&
535
+ o.key.length > 0);
536
+ }
537
+ function isBrandedPropertyDecl(x) {
538
+ if (x === null || typeof x !== 'object')
539
+ return false;
540
+ const o = x;
541
+ if (typeof o.name !== 'string' ||
542
+ typeof o.description !== 'string' ||
543
+ typeof o.required !== 'boolean' ||
544
+ typeof o.key !== 'string') {
545
+ return false;
546
+ }
547
+ if (o.options !== undefined && (!Array.isArray(o.options) || !o.options.every((v) => typeof v === 'string'))) {
548
+ return false;
549
+ }
550
+ if (o.adminManaged !== undefined && typeof o.adminManaged !== 'boolean')
551
+ return false;
552
+ return true;
553
+ }
554
+ function validateTools(cli, packagePath) {
555
+ const tools = cli.tools;
556
+ const toolKeys = Object.keys(tools);
557
+ if (toolKeys.length === 0) {
558
+ throw new Error(`registry: CLI '${cli.id}' (${packagePath}) declares no tools`);
559
+ }
560
+ for (const key of toolKeys) {
561
+ const tool = tools[key];
562
+ if (!isBrandedTool(tool)) {
563
+ throw new Error(`registry: CLI '${cli.id}' tool '${key}' (${packagePath}) is not a tool() result (missing __akaiTool brand or required fields)`);
564
+ }
565
+ }
566
+ }
567
+ function isBrandedTool(x) {
568
+ if (x === null || typeof x !== 'object')
569
+ return false;
570
+ const o = x;
571
+ if (o.__akaiTool !== true)
572
+ return false;
573
+ if (typeof o.handler !== 'function')
574
+ return false;
575
+ const opts = o.options;
576
+ if (!opts || typeof opts !== 'object')
577
+ return false;
578
+ if (typeof opts.isReadonly !== 'boolean')
579
+ return false;
580
+ if (!Array.isArray(opts.secretKeys))
581
+ return false;
582
+ // Optional + additive: older packages have no propertyKeys. When present it
583
+ // must be a string array — the executor scopes ctx.properties to these keys.
584
+ if (opts.propertyKeys !== undefined &&
585
+ (!Array.isArray(opts.propertyKeys) || !opts.propertyKeys.every((k) => typeof k === 'string'))) {
586
+ return false;
587
+ }
588
+ // Optional + additive (mirrors the SDK contract): when present it gates the
589
+ // file-output channel, so a non-boolean is a malformed package — reject it
590
+ // rather than silently treating a truthy non-boolean as "produces files".
591
+ if (opts.producesFiles !== undefined && typeof opts.producesFiles !== 'boolean')
592
+ return false;
593
+ // Mirror the SDK contract exactly:
594
+ // transport: 'native' → `options.network` MUST be absent (in-process,
595
+ // no socket access).
596
+ // transport: 'http' → `options.network.egress` MUST be EITHER a
597
+ // string[] (static allowlist) OR a dynamic-egress
598
+ // ref `{ from: 'property:<KEY>' }` | `{ from:
599
+ // 'secret:<KEY>' }` resolved per-invocation from a
600
+ // tenant property/secret (SDK DynamicEgress). `http`
601
+ // is the implicit default when `transport` is unset.
602
+ if (o.transport === 'native') {
603
+ if (opts.network !== undefined)
604
+ return false;
605
+ }
606
+ else {
607
+ const network = opts.network;
608
+ if (!network)
609
+ return false;
610
+ const egress = network.egress;
611
+ const isHostArray = Array.isArray(egress) && egress.every((h) => typeof h === 'string');
612
+ const from = !!egress && typeof egress === 'object' && !Array.isArray(egress)
613
+ ? egress.from
614
+ : undefined;
615
+ const isDynamic = typeof from === 'string' &&
616
+ DYNAMIC_EGRESS_PREFIXES.some((p) => from.startsWith(p) && from.length > p.length);
617
+ if (!isHostArray && !isDynamic)
618
+ return false;
619
+ }
620
+ return true;
621
+ }