@cdot65/prisma-airs-cli 4.0.1 → 4.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.
Files changed (3) hide show
  1. package/README.md +10 -6
  2. package/dist/cli/index.js +1583 -248
  3. package/package.json +3 -2
package/dist/cli/index.js CHANGED
@@ -45,6 +45,13 @@ import { dirname as dirname4, join as join4 } from "path";
45
45
  import { fileURLToPath } from "url";
46
46
  import { Command } from "commander";
47
47
 
48
+ // src/cli/commands/aigateway.ts
49
+ import {
50
+ GatewayDefaultsInputSchema,
51
+ GatewayRateLimitInputSchema,
52
+ GatewayUsageLimitInputSchema
53
+ } from "@cdot65/prisma-airs-sdk";
54
+
48
55
  // src/airs/aigateway.ts
49
56
  import {
50
57
  AIGatewayClient
@@ -2936,29 +2943,1525 @@ function renderScanLogList(results, pageToken, format = "pretty") {
2936
2943
  console.log();
2937
2944
  }
2938
2945
 
2939
- // src/cli/confirm.ts
2940
- async function confirmOrAbort(message, force, options = {}) {
2941
- if (force) return;
2942
- const interactive = options.isTTY ?? process.stdout.isTTY === true;
2943
- if (!interactive) {
2944
- usageError(
2945
- `refusing to ${options.action ?? "proceed"} without --force in non-interactive mode`
2946
- );
2946
+ // src/cli/confirm.ts
2947
+ async function confirmOrAbort(message, force, options = {}) {
2948
+ if (force) return;
2949
+ const interactive = options.isTTY ?? process.stdout.isTTY === true;
2950
+ if (!interactive) {
2951
+ await options.onAbort?.(2);
2952
+ usageError(
2953
+ `refusing to ${options.action ?? "proceed"} without --force in non-interactive mode`
2954
+ );
2955
+ }
2956
+ const prompt = options.promptFn ?? (await import("@inquirer/prompts")).confirm;
2957
+ const confirmed = await prompt({ message, default: false });
2958
+ if (!confirmed) {
2959
+ await options.onAbort?.(0);
2960
+ ui.info("Aborted");
2961
+ process.exit(0);
2962
+ }
2963
+ }
2964
+
2965
+ // src/cli/examples.ts
2966
+ function examples(...lines) {
2967
+ return `
2968
+ Examples:
2969
+ ${lines.map((l) => ` $ ${l}`).join("\n")}
2970
+ `;
2971
+ }
2972
+
2973
+ // src/cli/commands/aigateway/inventory.ts
2974
+ import {
2975
+ AI_GATEWAY_DEPLOYMENT_STATUSES,
2976
+ AI_GATEWAY_DEPLOYMENT_TYPES,
2977
+ AI_GATEWAY_KNOWN_API_KEY_SCOPES,
2978
+ AI_GATEWAY_KNOWN_MCP_AUTH_TYPES,
2979
+ AI_GATEWAY_KNOWN_MCP_TRANSPORTS,
2980
+ AI_GATEWAY_MUTABLE_MCP_CAPABILITY_TYPES,
2981
+ GatewayApiKeyRotateRequestSchema,
2982
+ GatewayApiKeyUpdateRequestSchema,
2983
+ GatewayConfigCreateRequestSchema,
2984
+ GatewayConfigUpdateRequestSchema,
2985
+ GatewayDeploymentCreateRequestSchema,
2986
+ GatewayDeploymentUpdateRequestSchema,
2987
+ GatewayGuardrailCreateRequestSchema,
2988
+ GatewayGuardrailUpdateRequestSchema,
2989
+ GatewayIntegrationCreateRequestSchema,
2990
+ GatewayIntegrationModelsBulkUpdateRequestSchema,
2991
+ GatewayIntegrationUpdateRequestSchema,
2992
+ GatewayIntegrationWorkspacesBulkUpdateRequestSchema,
2993
+ GatewayOrganisationAuthSettingsUpdateRequestSchema,
2994
+ GatewayOrganisationUpdateRequestSchema,
2995
+ GatewayPluginCreateRequestSchema,
2996
+ GatewayProviderCreateRequestSchema,
2997
+ GatewayProviderUpdateRequestSchema,
2998
+ GatewayServiceApiKeyCreateRequestSchema,
2999
+ GatewayUserApiKeyCreateRequestSchema,
3000
+ McpIntegrationCapabilitiesBulkUpdateRequestSchema,
3001
+ McpIntegrationCreateRequestSchema,
3002
+ McpIntegrationUpdateRequestSchema,
3003
+ McpIntegrationWorkspacesBulkUpdateRequestSchema,
3004
+ redactAIGatewaySecrets
3005
+ } from "@cdot65/prisma-airs-sdk";
3006
+
3007
+ // src/cli/debug-logger.ts
3008
+ import {
3009
+ appendFileSync,
3010
+ mkdirSync,
3011
+ readdirSync,
3012
+ statSync,
3013
+ unlinkSync,
3014
+ writeFileSync
3015
+ } from "fs";
3016
+ import { dirname, join } from "path";
3017
+ var AIRS_DOMAINS = [
3018
+ "api.sase.paloaltonetworks.com",
3019
+ "service.api.aisecurity.paloaltonetworks.com",
3020
+ "auth.apps.paloaltonetworks.com",
3021
+ "api.dlp.paloaltonetworks.com"
3022
+ ];
3023
+ function isAirsUrl(url) {
3024
+ try {
3025
+ const parsed = new URL(url);
3026
+ return AIRS_DOMAINS.some((d) => parsed.hostname === d || parsed.hostname.endsWith(`.${d}`));
3027
+ } catch {
3028
+ return false;
3029
+ }
3030
+ }
3031
+ var MASK = "***";
3032
+ var SENSITIVE_KEY_PATTERN = /token|secret|password|passwd|credential|authorization|cookie|api[-_]?key|client[-_]?auth|^key$/i;
3033
+ function isSensitiveKey(key) {
3034
+ return SENSITIVE_KEY_PATTERN.test(key);
3035
+ }
3036
+ function redactHeaders(headers) {
3037
+ const out = {};
3038
+ for (const [k, v] of Object.entries(headers)) {
3039
+ out[k] = isSensitiveKey(k) ? MASK : v;
3040
+ }
3041
+ return out;
3042
+ }
3043
+ function redactDeep(value) {
3044
+ if (Array.isArray(value)) {
3045
+ return value.map(redactDeep);
3046
+ }
3047
+ if (value !== null && typeof value === "object") {
3048
+ const out = {};
3049
+ for (const [k, v] of Object.entries(value)) {
3050
+ out[k] = isSensitiveKey(k) ? MASK : redactDeep(v);
3051
+ }
3052
+ return out;
3053
+ }
3054
+ return value;
3055
+ }
3056
+ function redactUrl(url) {
3057
+ try {
3058
+ const parsed = new URL(url);
3059
+ let touched = false;
3060
+ for (const key of parsed.searchParams.keys()) {
3061
+ if (isSensitiveKey(key)) {
3062
+ parsed.searchParams.set(key, MASK);
3063
+ touched = true;
3064
+ }
3065
+ }
3066
+ return touched ? parsed.toString() : url;
3067
+ } catch {
3068
+ return url;
3069
+ }
3070
+ }
3071
+ function pruneDebugLogs(dir, keep) {
3072
+ let files;
3073
+ try {
3074
+ files = readdirSync(dir).filter((f) => f.startsWith("debug-api-") && f.endsWith(".jsonl"));
3075
+ } catch {
3076
+ return;
3077
+ }
3078
+ const byAge = files.map((f) => {
3079
+ const path3 = join(dir, f);
3080
+ try {
3081
+ return { path: path3, mtime: statSync(path3).mtimeMs };
3082
+ } catch {
3083
+ return null;
3084
+ }
3085
+ }).filter((e) => e !== null).sort((a, b) => b.mtime - a.mtime);
3086
+ for (const { path: path3 } of byAge.slice(keep)) {
3087
+ try {
3088
+ unlinkSync(path3);
3089
+ } catch {
3090
+ }
3091
+ }
3092
+ }
3093
+ function headersToRecord(headers) {
3094
+ if (!headers) return {};
3095
+ if (typeof headers === "object" && "forEach" in headers && typeof headers.forEach === "function") {
3096
+ const out = {};
3097
+ headers.forEach((v, k) => {
3098
+ out[k] = v;
3099
+ });
3100
+ return out;
3101
+ }
3102
+ if (Array.isArray(headers)) {
3103
+ return Object.fromEntries(headers);
3104
+ }
3105
+ return headers;
3106
+ }
3107
+ var KEEP_DEBUG_LOGS = 10;
3108
+ function installDebugLogger(logPath) {
3109
+ mkdirSync(dirname(logPath), { recursive: true });
3110
+ writeFileSync(logPath, "", "utf-8");
3111
+ pruneDebugLogs(dirname(logPath), KEEP_DEBUG_LOGS);
3112
+ const originalFetch = globalThis.fetch;
3113
+ globalThis.fetch = async function debugFetch(input, init2) {
3114
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
3115
+ if (!isAirsUrl(url)) {
3116
+ return originalFetch(input, init2);
3117
+ }
3118
+ const method = init2?.method ?? (input instanceof Request ? input.method : "GET");
3119
+ const reqHeaders = redactHeaders(headersToRecord(init2?.headers));
3120
+ const loggedUrl = redactUrl(url);
3121
+ let reqBody;
3122
+ if (init2?.body) {
3123
+ try {
3124
+ reqBody = redactDeep(JSON.parse(String(init2.body)));
3125
+ } catch {
3126
+ reqBody = String(init2.body);
3127
+ }
3128
+ }
3129
+ const ts2 = (/* @__PURE__ */ new Date()).toISOString();
3130
+ const startMs = Date.now();
3131
+ let response;
3132
+ let resBody;
3133
+ let error;
3134
+ try {
3135
+ response = await originalFetch(input, init2);
3136
+ } catch (err) {
3137
+ error = err instanceof Error ? err.message : String(err);
3138
+ const entry2 = JSON.stringify({
3139
+ timestamp: ts2,
3140
+ durationMs: Date.now() - startMs,
3141
+ request: { method, url: loggedUrl, headers: reqHeaders, body: reqBody },
3142
+ error
3143
+ });
3144
+ appendFileSync(logPath, `${entry2}
3145
+ `);
3146
+ throw err;
3147
+ }
3148
+ const durationMs = Date.now() - startMs;
3149
+ const resHeaders = {};
3150
+ response.headers.forEach((v, k) => {
3151
+ resHeaders[k] = v;
3152
+ });
3153
+ const clone = response.clone();
3154
+ try {
3155
+ const text = await clone.text();
3156
+ try {
3157
+ resBody = redactDeep(JSON.parse(text));
3158
+ } catch {
3159
+ resBody = text;
3160
+ }
3161
+ } catch {
3162
+ resBody = "<unreadable>";
3163
+ }
3164
+ const entry = JSON.stringify({
3165
+ timestamp: ts2,
3166
+ durationMs,
3167
+ request: { method, url: loggedUrl, headers: reqHeaders, body: reqBody },
3168
+ response: {
3169
+ status: response.status,
3170
+ statusText: response.statusText,
3171
+ headers: redactHeaders(resHeaders),
3172
+ body: resBody
3173
+ }
3174
+ });
3175
+ appendFileSync(logPath, `${entry}
3176
+ `);
3177
+ return response;
3178
+ };
3179
+ return {
3180
+ teardown() {
3181
+ globalThis.fetch = originalFetch;
3182
+ }
3183
+ };
3184
+ }
3185
+
3186
+ // src/cli/commands/aigateway/shared.ts
3187
+ import { open, readFile, unlink } from "fs/promises";
3188
+ import { AIGatewayClient as AIGatewayClient2 } from "@cdot65/prisma-airs-sdk";
3189
+ import { dump as dump3, load } from "js-yaml";
3190
+ async function defaultClientFactory() {
3191
+ const config = await loadConfig();
3192
+ return new AIGatewayClient2(aiGatewayClientOptions(config));
3193
+ }
3194
+ var clientFactory = defaultClientFactory;
3195
+ async function createAiGatewayClient() {
3196
+ return clientFactory();
3197
+ }
3198
+ function showHelpOnEmpty(command) {
3199
+ return command.action(() => command.outputHelp());
3200
+ }
3201
+ function addReadOutput(command) {
3202
+ return command.option(
3203
+ "--output <format>",
3204
+ "Output format: pretty, table, markdown, csv, json, yaml"
3205
+ );
3206
+ }
3207
+ function addWriteOutput(command) {
3208
+ return command.option("--output <format>", "Output format: pretty, json, yaml");
3209
+ }
3210
+ async function readGatewayRequest(path3) {
3211
+ let parsed;
3212
+ try {
3213
+ const text = await readFile(path3, "utf8");
3214
+ parsed = path3.endsWith(".yaml") || path3.endsWith(".yml") ? load(text) : JSON.parse(text);
3215
+ } catch (error) {
3216
+ throw new CliUsageError(
3217
+ `Unable to parse --file '${path3}' as JSON or YAML: ${error instanceof Error ? error.message : String(error)}`
3218
+ );
3219
+ }
3220
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
3221
+ throw new CliUsageError(`--file '${path3}' must contain an object`);
3222
+ }
3223
+ return parsed;
3224
+ }
3225
+ function failAiGateway(error) {
3226
+ const hint = aiGatewayGrantHint(error);
3227
+ if (hint) ui.warn(`403: ${hint}`);
3228
+ fail(error);
3229
+ }
3230
+ function responseItems(value) {
3231
+ const record = asRecord2(value);
3232
+ if (Array.isArray(value)) return value.map(asRecord2);
3233
+ if (Array.isArray(record.data)) return record.data.map(asRecord2);
3234
+ const data = asRecord2(record.data);
3235
+ if (Array.isArray(data.records)) return data.records.map(asRecord2);
3236
+ if (Array.isArray(record.records)) return record.records.map(asRecord2);
3237
+ return [];
3238
+ }
3239
+ function asRecord2(value) {
3240
+ return value !== null && typeof value === "object" ? value : { value };
3241
+ }
3242
+ function displayColumns(items) {
3243
+ const preferred = [
3244
+ "id",
3245
+ "slug",
3246
+ "name",
3247
+ "type",
3248
+ "status",
3249
+ "enabled",
3250
+ "created_at",
3251
+ "last_updated_at"
3252
+ ];
3253
+ const keys = new Set(items.flatMap((item) => Object.keys(item)));
3254
+ const scalar = (key) => items.every((item) => item[key] == null || typeof item[key] !== "object");
3255
+ const chosen = [
3256
+ ...preferred.filter((key) => keys.has(key) && scalar(key)),
3257
+ ...[...keys].filter((key) => !preferred.includes(key) && scalar(key)).sort()
3258
+ ].slice(0, 8);
3259
+ return chosen.map((key) => ({
3260
+ key,
3261
+ label: key.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase())
3262
+ }));
3263
+ }
3264
+ function renderGatewayList(items, format, label) {
3265
+ if (format === "json") {
3266
+ console.log(JSON.stringify(items, null, 2));
3267
+ return;
3268
+ }
3269
+ if (format === "yaml") {
3270
+ console.log(dump3(items, { noRefs: true, lineWidth: -1 }).trimEnd());
3271
+ return;
3272
+ }
3273
+ if (items.length === 0) {
3274
+ ui.emptyList(label);
3275
+ return;
3276
+ }
3277
+ const columns = displayColumns(items);
3278
+ const rendered = formatOutput(items, columns, format === "pretty" ? "table" : format);
3279
+ if (rendered) console.log(rendered);
3280
+ }
3281
+ function renderGatewayDetail(value, format) {
3282
+ const item = asRecord2(value);
3283
+ if (format === "json") {
3284
+ console.log(JSON.stringify(item, null, 2));
3285
+ return;
3286
+ }
3287
+ if (format === "yaml") {
3288
+ console.log(dump3(item, { noRefs: true, lineWidth: -1 }).trimEnd());
3289
+ return;
3290
+ }
3291
+ const rows = Object.entries(item).map(([key, raw]) => ({
3292
+ key,
3293
+ value: raw !== null && typeof raw === "object" ? JSON.stringify(raw) : raw
3294
+ }));
3295
+ const rendered = formatOutput(
3296
+ rows,
3297
+ [
3298
+ { key: "key", label: "Field" },
3299
+ { key: "value", label: "Value" }
3300
+ ],
3301
+ format === "pretty" ? "table" : format
3302
+ );
3303
+ if (rendered) console.log(rendered);
3304
+ }
3305
+ async function runList(command, opts, label, load2) {
3306
+ try {
3307
+ const format = await resolveOutput(command, opts);
3308
+ const client = await createAiGatewayClient();
3309
+ renderGatewayList(responseItems(await load2(client)), format, label);
3310
+ } catch (error) {
3311
+ failAiGateway(error);
3312
+ }
3313
+ }
3314
+ async function runDetail(command, opts, load2) {
3315
+ try {
3316
+ const format = await resolveOutput(command, opts);
3317
+ const client = await createAiGatewayClient();
3318
+ renderGatewayDetail(await load2(client), format);
3319
+ } catch (error) {
3320
+ failAiGateway(error);
3321
+ }
3322
+ }
3323
+ async function runWrite(command, opts, prepareOrWrite, preparedWrite) {
3324
+ try {
3325
+ const format = await resolveOutput(command, opts, { allowed: ["pretty", "json", "yaml"] });
3326
+ const prepared = preparedWrite ? await prepareOrWrite() : void 0;
3327
+ const client = await createAiGatewayClient();
3328
+ const result = preparedWrite ? await preparedWrite(client, prepared) : await prepareOrWrite(client);
3329
+ renderGatewayDetail(result, format);
3330
+ } catch (error) {
3331
+ failAiGateway(error);
3332
+ }
3333
+ }
3334
+ async function runConfirmedWrite(command, opts, prompt, prepareOrWrite, preparedWrite) {
3335
+ try {
3336
+ const format = await resolveOutput(command, opts, { allowed: ["pretty", "json", "yaml"] });
3337
+ const prepared = preparedWrite ? await prepareOrWrite() : void 0;
3338
+ const action = prompt.replace(/\?$/, "").replace(/^./, (character) => character.toLowerCase());
3339
+ await confirmOrAbort(prompt, Boolean(opts.force), { action });
3340
+ const client = await createAiGatewayClient();
3341
+ const result = preparedWrite ? await preparedWrite(client, prepared) : await prepareOrWrite(client);
3342
+ renderGatewayDetail(result ?? { success: true }, format);
3343
+ } catch (error) {
3344
+ failAiGateway(error);
3345
+ }
3346
+ }
3347
+ async function runSecretWrite(command, opts, prepare, write, prompt, settings = {}) {
3348
+ let destinationHandle;
3349
+ let destinationReserved = false;
3350
+ let secretPersisted = false;
3351
+ const cleanupReservedDestination = async () => {
3352
+ if (destinationHandle) await destinationHandle.close().catch(() => void 0);
3353
+ destinationHandle = void 0;
3354
+ if (opts.secretOutput && destinationReserved && !secretPersisted) {
3355
+ await unlink(opts.secretOutput).catch(() => void 0);
3356
+ }
3357
+ destinationReserved = false;
3358
+ };
3359
+ try {
3360
+ const prepared = await prepare();
3361
+ const requiresDestination = settings.requiresDestination?.(prepared) ?? true;
3362
+ if (requiresDestination && !opts.secretOutput && !opts.showSecret) {
3363
+ throw new CliUsageError(
3364
+ "Choose --secret-output <path> (recommended) or --show-secret before requesting a one-time credential"
3365
+ );
3366
+ }
3367
+ const format = await resolveOutput(command, opts, { allowed: ["pretty", "json", "yaml"] });
3368
+ if (requiresDestination && opts.secretOutput) {
3369
+ destinationHandle = await open(opts.secretOutput, "wx", 384);
3370
+ destinationReserved = true;
3371
+ }
3372
+ if (prompt) {
3373
+ const action = prompt.replace(/\?$/, "").replace(/^./, (character) => character.toLowerCase());
3374
+ await confirmOrAbort(prompt, Boolean(opts.force), {
3375
+ action,
3376
+ onAbort: cleanupReservedDestination
3377
+ });
3378
+ }
3379
+ const client = await createAiGatewayClient();
3380
+ const result = await write(client, prepared);
3381
+ if (requiresDestination && opts.secretOutput && destinationHandle) {
3382
+ await destinationHandle.writeFile(`${JSON.stringify(result, null, 2)}
3383
+ `, "utf8");
3384
+ secretPersisted = true;
3385
+ await destinationHandle.close();
3386
+ destinationHandle = void 0;
3387
+ renderGatewayDetail({ saved_to: opts.secretOutput }, format);
3388
+ return;
3389
+ }
3390
+ renderGatewayDetail(
3391
+ requiresDestination ? result : settings.redactResponse?.(result) ?? result,
3392
+ format
3393
+ );
3394
+ } catch (error) {
3395
+ await cleanupReservedDestination();
3396
+ failAiGateway(error);
3397
+ }
3398
+ }
3399
+
3400
+ // src/cli/commands/aigateway/structured-input.ts
3401
+ import {
3402
+ AISecSDKException,
3403
+ buildDottedObject,
3404
+ ErrorType,
3405
+ GatewayJsonObjectSchema,
3406
+ setDottedValue
3407
+ } from "@cdot65/prisma-airs-sdk";
3408
+ function collectOption(value, previous = []) {
3409
+ return [...previous, value];
3410
+ }
3411
+ function addStructuredInputOptions(command) {
3412
+ return command.option("--file <path>", "Advanced JSON/YAML request base; named flags override it").option(
3413
+ "--set <path=value>",
3414
+ "Set a typed JSON value at a request path (repeatable)",
3415
+ collectOption
3416
+ ).option(
3417
+ "--set-string <path=value>",
3418
+ "Set a literal string at a request path (repeatable)",
3419
+ collectOption
3420
+ );
3421
+ }
3422
+ function parseBooleanOption(value) {
3423
+ if (value === true || value === false) return value;
3424
+ if (value === "true") return true;
3425
+ if (value === "false") return false;
3426
+ throw new CliUsageError("Expected true or false");
3427
+ }
3428
+ function parseIntegerOption(value) {
3429
+ const text = String(value);
3430
+ if (!/^-?(0|[1-9]\d*)$/.test(text)) throw new CliUsageError("Expected an integer");
3431
+ const parsed = Number(text);
3432
+ if (!Number.isSafeInteger(parsed)) throw new CliUsageError("Expected a safe integer");
3433
+ return parsed;
3434
+ }
3435
+ function parseDateOption(value) {
3436
+ const parsed = new Date(String(value));
3437
+ if (Number.isNaN(parsed.getTime())) throw new CliUsageError("Expected an ISO-8601 timestamp");
3438
+ return parsed;
3439
+ }
3440
+ function parseCsvOption(value) {
3441
+ const values = String(value).split(",").map((item) => item.trim()).filter(Boolean);
3442
+ if (values.length === 0) throw new CliUsageError("Expected a non-empty comma-separated list");
3443
+ return values;
3444
+ }
3445
+ function parseJsonOption(value) {
3446
+ try {
3447
+ return JSON.parse(String(value));
3448
+ } catch {
3449
+ throw new CliUsageError("Expected valid JSON");
3450
+ }
3451
+ }
3452
+ function repeatableValues(value) {
3453
+ if (Array.isArray(value)) return value.map(String);
3454
+ return [String(value)];
3455
+ }
3456
+ function splitKeyValue(raw, label) {
3457
+ const separator = raw.indexOf("=");
3458
+ if (separator <= 0) throw new CliUsageError(`Expected ${label}=value`);
3459
+ return [raw.slice(0, separator), raw.slice(separator + 1)];
3460
+ }
3461
+ function parseBooleanBindingsOption(value) {
3462
+ return repeatableValues(value).map((raw) => {
3463
+ const [id, enabled] = splitKeyValue(raw, "id");
3464
+ return { id, enabled: parseBooleanOption(enabled) };
3465
+ });
3466
+ }
3467
+ function parseModelBindingsOption(value) {
3468
+ return repeatableValues(value).map((raw) => {
3469
+ const [slug, enabled] = splitKeyValue(raw, "slug");
3470
+ return { slug, enabled: parseBooleanOption(enabled) };
3471
+ });
3472
+ }
3473
+ function parseCapabilityBindingsOption(value) {
3474
+ return repeatableValues(value).map((raw) => {
3475
+ const [identity, enabled] = splitKeyValue(raw, "type:name");
3476
+ const separator = identity.indexOf(":");
3477
+ if (separator <= 0 || separator === identity.length - 1) {
3478
+ throw new CliUsageError("Expected type:name=enabled");
3479
+ }
3480
+ return {
3481
+ type: identity.slice(0, separator),
3482
+ name: identity.slice(separator + 1),
3483
+ enabled: parseBooleanOption(enabled)
3484
+ };
3485
+ });
3486
+ }
3487
+ function parseStringMapOption(value) {
3488
+ const result = {};
3489
+ for (const raw of repeatableValues(value)) {
3490
+ const [key, item] = splitKeyValue(raw, "key");
3491
+ if (["__proto__", "constructor", "prototype"].includes(key)) {
3492
+ throw new CliUsageError(`Unsafe key: ${key}`);
3493
+ }
3494
+ if (Object.hasOwn(result, key)) throw new CliUsageError(`Duplicate key: ${key}`);
3495
+ result[key] = item;
3496
+ }
3497
+ return result;
3498
+ }
3499
+ function parseAssignment(raw, forceString) {
3500
+ const separator = raw.indexOf("=");
3501
+ if (separator <= 0) throw new CliUsageError("Expected path=value");
3502
+ const path3 = raw.slice(0, separator);
3503
+ const text = raw.slice(separator + 1);
3504
+ if (forceString) return [path3, text];
3505
+ try {
3506
+ return [path3, JSON.parse(text)];
3507
+ } catch {
3508
+ return [path3, text];
3509
+ }
3510
+ }
3511
+ function schemaMessage(error) {
3512
+ const issues = error?.issues;
3513
+ if (!Array.isArray(issues) || issues.length === 0)
3514
+ return "request body does not match its schema";
3515
+ return issues.map((issue) => {
3516
+ const path3 = issue.path?.length ? issue.path.map(String).join(".") : "<root>";
3517
+ return `${path3}: ${issue.message ?? "invalid value"}`;
3518
+ }).join("; ");
3519
+ }
3520
+ function optionName(option) {
3521
+ return `--${option.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`)}`;
3522
+ }
3523
+ function asUsageError(error, prefix = "Invalid AI Gateway request") {
3524
+ if (error instanceof CliUsageError) return error;
3525
+ if (error instanceof AISecSDKException && error.errorType === ErrorType.USER_REQUEST_PAYLOAD_ERROR) {
3526
+ return new CliUsageError(`${prefix}: ${error.message}`);
3527
+ }
3528
+ return new CliUsageError(`${prefix}: ${schemaMessage(error)}`);
3529
+ }
3530
+ async function buildStructuredRequest(options, schema, fields = []) {
3531
+ try {
3532
+ let body = {};
3533
+ if (options.file) {
3534
+ body = GatewayJsonObjectSchema.parse(await readGatewayRequest(options.file));
3535
+ }
3536
+ for (const field of fields) {
3537
+ const raw = options[field.option];
3538
+ if (raw === void 0 || Array.isArray(raw) && raw.length === 0) continue;
3539
+ let value;
3540
+ try {
3541
+ value = field.parse ? field.parse(raw) : raw;
3542
+ } catch (error) {
3543
+ if (error instanceof CliUsageError) {
3544
+ throw new CliUsageError(`Invalid ${optionName(field.option)}: ${error.message}`);
3545
+ }
3546
+ throw error;
3547
+ }
3548
+ body = setDottedValue(body, field.path, value);
3549
+ }
3550
+ const assignments = [
3551
+ ...(options.set ?? []).map((raw) => {
3552
+ try {
3553
+ const [path3, value] = parseAssignment(raw, false);
3554
+ return { path: path3, value };
3555
+ } catch (error) {
3556
+ if (error instanceof CliUsageError) {
3557
+ throw new CliUsageError(`Invalid --set '${raw}': ${error.message}`);
3558
+ }
3559
+ throw error;
3560
+ }
3561
+ }),
3562
+ ...(options.setString ?? []).map((raw) => {
3563
+ try {
3564
+ const [path3, value] = parseAssignment(raw, true);
3565
+ return { path: path3, value };
3566
+ } catch (error) {
3567
+ if (error instanceof CliUsageError) {
3568
+ throw new CliUsageError(`Invalid --set-string '${raw}': ${error.message}`);
3569
+ }
3570
+ throw error;
3571
+ }
3572
+ })
3573
+ ];
3574
+ buildDottedObject(assignments);
3575
+ for (const { path: path3, value } of assignments) body = setDottedValue(body, path3, value);
3576
+ return schema.parse(body);
3577
+ } catch (error) {
3578
+ throw asUsageError(error);
3579
+ }
3580
+ }
3581
+
3582
+ // src/cli/commands/aigateway/inventory.ts
3583
+ function registerScopedReads(root, name, description, select, options = {}) {
3584
+ const group = showHelpOnEmpty(root.command(name).description(description));
3585
+ const list = addReadOutput(
3586
+ group.command("list").description(`List ${name} in a workspace (data plane)`).requiredOption("--workspace <uuid>", "Workspace UUID")
3587
+ );
3588
+ list.action(
3589
+ (opts) => runList(list, opts, name, (client) => select(client).list({ workspaceId: opts.workspace }))
3590
+ );
3591
+ let get = group.command("get <id>").description(`Get one ${name.replace(/s$/, "")} by UUID (data plane)`);
3592
+ if (options.sensitiveDetail) {
3593
+ get = get.option("--reveal-sensitive", "Show credential-bearing fields");
3594
+ }
3595
+ addReadOutput(get);
3596
+ get.action(
3597
+ (id, opts) => runDetail(get, opts, async (client) => {
3598
+ const result = await select(client).get(id);
3599
+ if (!options.sensitiveDetail || opts.revealSensitive) return result;
3600
+ const metadataRedacted = options.sensitiveOperation ? redactAIGatewaySecrets(options.sensitiveOperation, result, "response") : result;
3601
+ return redactDeep(metadataRedacted);
3602
+ })
3603
+ );
3604
+ return group;
3605
+ }
3606
+ var knownValues = (values) => values.join(", ");
3607
+ function parseNamedDate(value, flag) {
3608
+ try {
3609
+ return parseDateOption(value);
3610
+ } catch (error) {
3611
+ throw new CliUsageError(
3612
+ `Invalid ${flag}: ${error instanceof Error ? error.message : String(error)}`
3613
+ );
3614
+ }
3615
+ }
3616
+ function parsePositiveInteger(value, flag) {
3617
+ try {
3618
+ const parsed = parseIntegerOption(value);
3619
+ if (parsed <= 0) throw new CliUsageError("Expected a positive integer");
3620
+ return parsed;
3621
+ } catch (error) {
3622
+ throw new CliUsageError(
3623
+ `Invalid ${flag}: ${error instanceof Error ? error.message : String(error)}`
3624
+ );
3625
+ }
3626
+ }
3627
+ function addCrudMutationNodes(group, resource, request, operations) {
3628
+ let create = group.command("create").description(`Create a ${resource} from structured flags`);
3629
+ if (request.createOptions) create = request.createOptions(create);
3630
+ create = addWriteOutput(addStructuredInputOptions(create));
3631
+ create.action(
3632
+ (opts) => runWrite(
3633
+ create,
3634
+ opts,
3635
+ () => buildStructuredRequest(opts, request.createSchema, request.createFields),
3636
+ (client, body) => operations.create(client, body)
3637
+ )
3638
+ );
3639
+ let update = group.command("update <id>").description(`Update a ${resource} with structured flags`);
3640
+ if (request.updateOptions) update = request.updateOptions(update);
3641
+ update = addWriteOutput(addStructuredInputOptions(update));
3642
+ update.action(
3643
+ (id, opts) => runWrite(
3644
+ update,
3645
+ opts,
3646
+ () => buildStructuredRequest(opts, request.updateSchema, request.updateFields),
3647
+ (client, body) => operations.update(client, id, body)
3648
+ )
3649
+ );
3650
+ const remove = addWriteOutput(
3651
+ group.command("delete <id>").description("Permanently delete this resource").option("--force", "Skip confirmation prompt")
3652
+ );
3653
+ remove.action(
3654
+ (id, opts) => runConfirmedWrite(
3655
+ remove,
3656
+ opts,
3657
+ `Permanently delete ${resource} ${id}?`,
3658
+ (client) => operations.delete(client, id)
3659
+ )
3660
+ );
3661
+ }
3662
+ function registerApiKeys(root) {
3663
+ const apiKeys = showHelpOnEmpty(
3664
+ root.command("api-keys").description("Manage service and user gateway credentials")
3665
+ );
3666
+ for (const kind of ["service", "user"]) {
3667
+ const group = showHelpOnEmpty(apiKeys.command(kind).description(`Manage ${kind} API keys`));
3668
+ const list = addReadOutput(
3669
+ group.command("list").description(`List ${kind} API keys in a workspace (data plane)`).requiredOption("--workspace <uuid>", "Workspace UUID")
3670
+ );
3671
+ list.action(
3672
+ (opts) => runList(
3673
+ list,
3674
+ opts,
3675
+ `${kind} API keys`,
3676
+ (client) => kind === "service" ? client.apiKeys.listService({ workspaceId: opts.workspace }) : client.apiKeys.listUser({ workspaceId: opts.workspace })
3677
+ )
3678
+ );
3679
+ const get = addReadOutput(group.command("get <id>").description(`Get one ${kind} API key`));
3680
+ get.action(
3681
+ (id, opts) => runDetail(
3682
+ get,
3683
+ opts,
3684
+ (client) => kind === "service" ? client.apiKeys.getService(id) : client.apiKeys.getUser(id)
3685
+ )
3686
+ );
3687
+ const createFields = [
3688
+ { option: "alertEmails", path: "alert_emails", parse: parseCsvOption },
3689
+ { option: "description", path: "description" },
3690
+ { option: "expiresAt", path: "expires_at" },
3691
+ { option: "name", path: "name" },
3692
+ { option: "organisationId", path: "organisation_id" },
3693
+ { option: "scopes", path: "scopes", parse: parseCsvOption },
3694
+ { option: "type", path: "type" },
3695
+ { option: "workspace", path: "workspace_id" },
3696
+ ...kind === "user" ? [{ option: "userId", path: "user_id" }] : []
3697
+ ];
3698
+ let createCommand = group.command("create").description(`Create a ${kind} API key from structured flags`).option("--alert-emails <emails>", "Comma-separated alert email addresses").option("--description <text>", "Credential description").option("--expires-at <iso>", "Expiration as ISO-8601").option("--name <name>", "Credential name").option("--organisation-id <tsg>", "Numeric TSG id").option(
3699
+ "--scopes <scopes>",
3700
+ `Comma-separated scopes (known: ${knownValues(AI_GATEWAY_KNOWN_API_KEY_SCOPES)})`
3701
+ ).option("--type <type>", "Credential type").option("--workspace <uuid>", "Workspace UUID").option("--secret-output <path>", "Write the one-time credential to a new 0600 file").option("--show-secret", "Print the one-time credential to stdout");
3702
+ if (kind === "user") createCommand = createCommand.option("--user-id <uuid>", "User UUID");
3703
+ const create = addWriteOutput(addStructuredInputOptions(createCommand));
3704
+ create.action((opts) => {
3705
+ if (kind === "service") {
3706
+ return runSecretWrite(
3707
+ create,
3708
+ opts,
3709
+ () => buildStructuredRequest(opts, GatewayServiceApiKeyCreateRequestSchema, createFields),
3710
+ (client, body) => client.apiKeys.createService(body)
3711
+ );
3712
+ }
3713
+ return runSecretWrite(
3714
+ create,
3715
+ opts,
3716
+ () => buildStructuredRequest(opts, GatewayUserApiKeyCreateRequestSchema, createFields),
3717
+ (client, body) => client.apiKeys.createUser(body)
3718
+ );
3719
+ });
3720
+ const update = addWriteOutput(
3721
+ addStructuredInputOptions(
3722
+ group.command("update <id>").description(`Update a ${kind} API key with structured flags`).option("--alert-emails <emails>", "Comma-separated alert email addresses").option("--description <text>", "Credential description").option("--expires-at <iso>", "Expiration as ISO-8601").option("--name <name>", "Credential name").option("--reset-usage <boolean>", "Reset accumulated usage: true or false").option(
3723
+ "--scopes <scopes>",
3724
+ `Comma-separated scopes (known: ${knownValues(AI_GATEWAY_KNOWN_API_KEY_SCOPES)})`
3725
+ )
3726
+ )
3727
+ );
3728
+ update.action(
3729
+ (id, opts) => runWrite(
3730
+ update,
3731
+ opts,
3732
+ () => buildStructuredRequest(opts, GatewayApiKeyUpdateRequestSchema, [
3733
+ { option: "alertEmails", path: "alert_emails", parse: parseCsvOption },
3734
+ { option: "description", path: "description" },
3735
+ { option: "expiresAt", path: "expires_at" },
3736
+ { option: "name", path: "name" },
3737
+ { option: "resetUsage", path: "reset_usage", parse: parseBooleanOption },
3738
+ { option: "scopes", path: "scopes", parse: parseCsvOption }
3739
+ ]),
3740
+ (client, body) => kind === "service" ? client.apiKeys.updateService(id, body) : client.apiKeys.updateUser(id, body)
3741
+ )
3742
+ );
3743
+ const remove = addWriteOutput(
3744
+ group.command("delete <id>").description(`Revoke a ${kind} API key`).option("--force", "Skip confirmation prompt")
3745
+ );
3746
+ remove.action(
3747
+ (id, opts) => runConfirmedWrite(
3748
+ remove,
3749
+ opts,
3750
+ `Revoke ${kind} API key ${id}?`,
3751
+ (client) => kind === "service" ? client.apiKeys.deleteService(id) : client.apiKeys.deleteUser(id)
3752
+ )
3753
+ );
3754
+ const rotate = addWriteOutput(
3755
+ group.command("rotate <id>").description(`Rotate a ${kind} API key`).option("--force", "Skip confirmation prompt").option("--secret-output <path>", "Write the one-time credential to a new 0600 file").option("--show-secret", "Print the one-time credential to stdout").option("--transition-ms <ms>", "Credential overlap in milliseconds")
3756
+ );
3757
+ rotate.action(
3758
+ (id, opts) => runSecretWrite(
3759
+ rotate,
3760
+ opts,
3761
+ () => buildStructuredRequest(opts, GatewayApiKeyRotateRequestSchema, [
3762
+ {
3763
+ option: "transitionMs",
3764
+ path: "key_transition_period_ms",
3765
+ parse: parseIntegerOption
3766
+ }
3767
+ ]),
3768
+ (client, body) => kind === "service" ? client.apiKeys.rotateService(id, body) : client.apiKeys.rotateUser(id, body),
3769
+ `Rotate ${kind} API key ${id}?`
3770
+ )
3771
+ );
3772
+ }
3773
+ }
3774
+ function registerAuditLogs(root) {
3775
+ const group = showHelpOnEmpty(
3776
+ root.command("audit-logs").description("Inspect organisation audit activity")
3777
+ );
3778
+ const list = addReadOutput(
3779
+ group.command("list").description("List audit activity for a UTC time window (admin plane)").option("--days <n>", "Rolling window in days", "7").option("--end <iso>", "Window end as ISO-8601").option("--reveal-sensitive", "Show sensitive request fields").option("--start <iso>", "Window start as ISO-8601")
3780
+ );
3781
+ list.action((opts) => {
3782
+ return runList(list, opts, "audit logs", async (client) => {
3783
+ const end = opts.end ? parseNamedDate(opts.end, "--end") : /* @__PURE__ */ new Date();
3784
+ const start = opts.start ? parseNamedDate(opts.start, "--start") : new Date(end.getTime() - parsePositiveInteger(opts.days, "--days") * 864e5);
3785
+ const result = await client.auditLogs.list({ start, end });
3786
+ return opts.revealSensitive ? result : redactDeep(result);
3787
+ });
3788
+ });
3789
+ }
3790
+ function registerConfigs(root) {
3791
+ const group = registerScopedReads(
3792
+ root,
3793
+ "configs",
3794
+ "Manage routing configurations",
3795
+ (client) => client.configs
3796
+ );
3797
+ const versions = addReadOutput(
3798
+ group.command("versions <id>").description("List immutable config versions")
3799
+ );
3800
+ versions.action(
3801
+ (id, opts) => runList(versions, opts, "config versions", (client) => client.configs.listVersions(id))
3802
+ );
3803
+ const commonFields = [
3804
+ { option: "name", path: "name" },
3805
+ { option: "workspace", path: "workspace_id" },
3806
+ { option: "status", path: "status" }
3807
+ ];
3808
+ addCrudMutationNodes(
3809
+ group,
3810
+ "config",
3811
+ {
3812
+ createFields: commonFields,
3813
+ createOptions: (command) => command.option("--name <name>", "Config name").option("--workspace <uuid>", "Workspace UUID"),
3814
+ createSchema: GatewayConfigCreateRequestSchema,
3815
+ updateFields: commonFields,
3816
+ updateOptions: (command) => command.option("--name <name>", "New config name").option("--status <status>", "New config status").option("--workspace <uuid>", "New workspace UUID"),
3817
+ updateSchema: GatewayConfigUpdateRequestSchema
3818
+ },
3819
+ {
3820
+ create: (client, body) => client.configs.create(body),
3821
+ delete: (client, id) => client.configs.delete(id),
3822
+ update: (client, id, body) => client.configs.update(id, body)
3823
+ }
3824
+ );
3825
+ }
3826
+ function registerDeployments(root) {
3827
+ const group = showHelpOnEmpty(
3828
+ root.command("deployments").description("Manage self-hosted gateway registrations")
3829
+ );
3830
+ const list = addReadOutput(group.command("list").description("List deployments (admin plane)"));
3831
+ list.action((opts) => runList(list, opts, "deployments", (client) => client.deployments.list()));
3832
+ const get = addReadOutput(
3833
+ group.command("get <id>").description("Get a deployment by UUID (admin plane)")
3834
+ );
3835
+ get.action((id, opts) => runDetail(get, opts, (client) => client.deployments.get(id)));
3836
+ const ping = addReadOutput(
3837
+ group.command("ping <id>").description("Run the optional control-plane ingress diagnostic")
3838
+ );
3839
+ ping.action((id, opts) => runDetail(ping, opts, (client) => client.deployments.ping(id)));
3840
+ const archive = addWriteOutput(
3841
+ group.command("archive <id>").description("Archive a deployment registration").requiredOption("--organisation-id <tsg>", "Numeric TSG id").option("--force", "Skip confirmation prompt")
3842
+ );
3843
+ archive.action(
3844
+ (id, opts) => runConfirmedWrite(
3845
+ archive,
3846
+ opts,
3847
+ `Archive deployment ${id}?`,
3848
+ (client) => client.deployments.delete(id, opts.organisationId)
3849
+ )
3850
+ );
3851
+ const create = addWriteOutput(
3852
+ addStructuredInputOptions(
3853
+ group.command("create").description("Register a self-hosted deployment from structured flags").option("--auth-settings <json>", "Deployment authentication settings object").option("--deployment-config <json>", "Deployment configuration object").option("--is-default <boolean>", "Make this the default deployment").option("--name <name>", "Deployment name").option("--organisation-id <tsg>", "Numeric TSG id").option("--slug <slug>", "Stable deployment slug").option("--type <type>", `Deployment type: ${knownValues(AI_GATEWAY_DEPLOYMENT_TYPES)}`).option("--secret-output <path>", "Write registration credentials to a new 0600 file").option("--show-secret", "Print registration credentials to stdout")
3854
+ )
3855
+ );
3856
+ create.action(
3857
+ (opts) => runSecretWrite(
3858
+ create,
3859
+ opts,
3860
+ () => buildStructuredRequest(opts, GatewayDeploymentCreateRequestSchema, [
3861
+ { option: "authSettings", path: "auth_settings", parse: parseJsonOption },
3862
+ { option: "deploymentConfig", path: "deployment_config", parse: parseJsonOption },
3863
+ { option: "isDefault", path: "is_default", parse: parseBooleanOption },
3864
+ { option: "name", path: "name" },
3865
+ { option: "organisationId", path: "organisation_id" },
3866
+ { option: "slug", path: "slug" },
3867
+ { option: "type", path: "type" }
3868
+ ]),
3869
+ (client, body) => client.deployments.create(body)
3870
+ )
3871
+ );
3872
+ const update = addWriteOutput(
3873
+ addStructuredInputOptions(
3874
+ group.command("update <id>").description("Update a deployment registration with structured flags").option("--auth-settings <json>", "Deployment authentication settings object").option("--deployment-config <json>", "Deployment configuration object").option("--is-default <boolean>", "Make this the default deployment").option("--name <name>", "Deployment name").option("--override-existing <boolean>", "Override an existing registration").option("--rotate-auth <boolean>", "Rotate deployment authentication").option("--secret-output <path>", "Write rotated credentials to a new 0600 file").option("--show-secret", "Print rotated credentials to stdout").option(
3875
+ "--status <status>",
3876
+ `Deployment status: ${knownValues(AI_GATEWAY_DEPLOYMENT_STATUSES)}`
3877
+ ).option("--type <type>", `Deployment type: ${knownValues(AI_GATEWAY_DEPLOYMENT_TYPES)}`)
3878
+ )
3879
+ );
3880
+ update.action(
3881
+ (id, opts) => runSecretWrite(
3882
+ update,
3883
+ opts,
3884
+ () => buildStructuredRequest(opts, GatewayDeploymentUpdateRequestSchema, [
3885
+ { option: "authSettings", path: "auth_settings", parse: parseJsonOption },
3886
+ { option: "deploymentConfig", path: "deployment_config", parse: parseJsonOption },
3887
+ { option: "isDefault", path: "is_default", parse: parseBooleanOption },
3888
+ { option: "name", path: "name" },
3889
+ { option: "overrideExisting", path: "override_existing", parse: parseBooleanOption },
3890
+ { option: "rotateAuth", path: "rotate_auth", parse: parseBooleanOption },
3891
+ { option: "status", path: "status" },
3892
+ { option: "type", path: "type" }
3893
+ ]),
3894
+ (client, body) => client.deployments.update(id, body),
3895
+ void 0,
3896
+ {
3897
+ requiresDestination: (body) => body.rotate_auth === true,
3898
+ redactResponse: (result) => redactAIGatewaySecrets("deployments.update", result, "response")
3899
+ }
3900
+ )
3901
+ );
3902
+ }
3903
+ function registerIntegrations(root) {
3904
+ const group = showHelpOnEmpty(
3905
+ root.command("integrations").description("Manage organisation provider integrations")
3906
+ );
3907
+ const list = addReadOutput(
3908
+ group.command("list").description("List provider integrations (admin plane)")
3909
+ );
3910
+ list.action(
3911
+ (opts) => runList(list, opts, "integrations", (client) => client.integrations.list())
3912
+ );
3913
+ const get = addReadOutput(
3914
+ group.command("get <id>").description("Get a provider integration by UUID")
3915
+ );
3916
+ get.action((id, opts) => runDetail(get, opts, (client) => client.integrations.get(id)));
3917
+ const integrationFields = [
3918
+ { option: "aiProviderId", path: "ai_provider_id" },
3919
+ { option: "configurations", path: "configurations", parse: parseJsonOption },
3920
+ { option: "description", path: "description" },
3921
+ { option: "key", path: "key" },
3922
+ { option: "name", path: "name" },
3923
+ { option: "organisationId", path: "organisation_id" },
3924
+ { option: "secretMappings", path: "secret_mappings", parse: parseJsonOption },
3925
+ { option: "slug", path: "slug" }
3926
+ ];
3927
+ const addIntegrationFields = (command) => command.option("--ai-provider-id <uuid>", "Provider catalog UUID").option("--configurations <json>", "Provider configuration object").option("--description <text>", "Integration description").option("--key <credential>", "Inline provider credential (prefer secret mappings)").option("--name <name>", "Integration name").option("--organisation-id <tsg>", "Numeric TSG id").option("--secret-mappings <json>", "Secret reference mapping array").option("--slug <slug>", "Stable integration slug");
3928
+ const integrationUpdateFields = integrationFields.filter(
3929
+ (field) => ["configurations", "description", "key", "name", "secretMappings"].includes(field.option)
3930
+ );
3931
+ const addIntegrationUpdateFields = (command) => command.option("--configurations <json>", "Provider configuration object").option("--description <text>", "Integration description").option("--key <credential>", "Inline provider credential (prefer secret mappings)").option("--name <name>", "Integration name").option("--secret-mappings <json>", "Secret reference mapping array");
3932
+ const create = addWriteOutput(
3933
+ addStructuredInputOptions(
3934
+ addIntegrationFields(
3935
+ group.command("create").description("Create an integration from structured flags")
3936
+ )
3937
+ )
3938
+ );
3939
+ create.action(
3940
+ (opts) => runWrite(
3941
+ create,
3942
+ opts,
3943
+ () => buildStructuredRequest(opts, GatewayIntegrationCreateRequestSchema, integrationFields),
3944
+ (client, body) => client.integrations.create(body)
3945
+ )
3946
+ );
3947
+ const update = addWriteOutput(
3948
+ addStructuredInputOptions(
3949
+ addIntegrationUpdateFields(
3950
+ group.command("update <id>").description("Update an integration with structured flags")
3951
+ )
3952
+ )
3953
+ );
3954
+ update.action(
3955
+ (id, opts) => runWrite(
3956
+ update,
3957
+ opts,
3958
+ () => buildStructuredRequest(
3959
+ opts,
3960
+ GatewayIntegrationUpdateRequestSchema,
3961
+ integrationUpdateFields
3962
+ ),
3963
+ (client, body) => client.integrations.update(id, body)
3964
+ )
3965
+ );
3966
+ const remove = addWriteOutput(
3967
+ group.command("delete <id>").description("Permanently delete this integration").requiredOption("--organisation-id <tsg>", "Numeric TSG id").option("--force", "Skip confirmation prompt")
3968
+ );
3969
+ remove.action(
3970
+ (id, opts) => runConfirmedWrite(
3971
+ remove,
3972
+ opts,
3973
+ `Permanently delete integration ${id}?`,
3974
+ (client) => client.integrations.delete(id, opts.organisationId)
3975
+ )
3976
+ );
3977
+ const models = showHelpOnEmpty(
3978
+ group.command("models").description("Inspect or replace model bindings")
3979
+ );
3980
+ const modelsList = addReadOutput(
3981
+ models.command("list <id>").description("List models for an integration")
3982
+ );
3983
+ modelsList.action(
3984
+ (id, opts) => runList(modelsList, opts, "integration models", (client) => client.integrations.getModels(id))
3985
+ );
3986
+ const modelsSet = addWriteOutput(
3987
+ addStructuredInputOptions(
3988
+ models.command("set <id>").description("Replace model bindings").option("--allow-all-models <boolean>", "Allow every model: true or false").option("--model <slug=enabled>", "Model binding (repeatable)", collectOption).option("--force", "Skip confirmation prompt")
3989
+ )
3990
+ );
3991
+ modelsSet.action(
3992
+ (id, opts) => runConfirmedWrite(
3993
+ modelsSet,
3994
+ opts,
3995
+ `Replace model bindings on ${id}?`,
3996
+ () => buildStructuredRequest(opts, GatewayIntegrationModelsBulkUpdateRequestSchema, [
3997
+ { option: "allowAllModels", path: "allow_all_models", parse: parseBooleanOption },
3998
+ { option: "model", path: "models", parse: parseModelBindingsOption }
3999
+ ]),
4000
+ (client, body) => client.integrations.setModels(id, body)
4001
+ )
4002
+ );
4003
+ const workspaces = showHelpOnEmpty(
4004
+ group.command("workspaces").description("Inspect or replace workspace bindings")
4005
+ );
4006
+ const workspacesList = addReadOutput(
4007
+ workspaces.command("list <id>").description("List workspace bindings")
4008
+ );
4009
+ workspacesList.action(
4010
+ (id, opts) => runDetail(workspacesList, opts, (client) => client.integrations.getWorkspaces(id))
4011
+ );
4012
+ const workspacesSet = addWriteOutput(
4013
+ addStructuredInputOptions(
4014
+ workspaces.command("set <id>").description("Replace workspace bindings").option("--create-default-provider <boolean>", "Create defaults for new bindings").option("--default-provider-slug <slug>", "Default provider slug").option("--global-access <boolean>", "Enable or disable access to every workspace").option("--preserve-existing", "Preserve bindings not named by this command").option("--workspace-binding <id=enabled>", "Workspace binding (repeatable)", collectOption).option("--force", "Skip confirmation prompt")
4015
+ )
4016
+ );
4017
+ workspacesSet.action(
4018
+ (id, opts) => runConfirmedWrite(
4019
+ workspacesSet,
4020
+ opts,
4021
+ `Replace workspace bindings on ${id}?`,
4022
+ () => buildStructuredRequest(
4023
+ {
4024
+ ...opts,
4025
+ overrideExistingWorkspaceAccess: !opts.preserveExisting
4026
+ },
4027
+ GatewayIntegrationWorkspacesBulkUpdateRequestSchema,
4028
+ [
4029
+ {
4030
+ option: "createDefaultProvider",
4031
+ path: "create_default_provider",
4032
+ parse: parseBooleanOption
4033
+ },
4034
+ { option: "defaultProviderSlug", path: "default_provider_slug" },
4035
+ {
4036
+ option: "globalAccess",
4037
+ path: "global_workspace_access.enabled",
4038
+ parse: parseBooleanOption
4039
+ },
4040
+ {
4041
+ option: "overrideExistingWorkspaceAccess",
4042
+ path: "override_existing_workspace_access",
4043
+ parse: parseBooleanOption
4044
+ },
4045
+ { option: "workspaceBinding", path: "workspaces", parse: parseBooleanBindingsOption }
4046
+ ]
4047
+ ),
4048
+ (client, body) => client.integrations.setWorkspaces(id, body)
4049
+ )
4050
+ );
4051
+ }
4052
+ function registerMcp(root) {
4053
+ const mcp = showHelpOnEmpty(
4054
+ root.command("mcp").description("Manage MCP integrations and servers")
4055
+ );
4056
+ const group = showHelpOnEmpty(
4057
+ mcp.command("integrations").description("Manage MCP server integrations")
4058
+ );
4059
+ const list = addReadOutput(
4060
+ group.command("list").description("List MCP integrations (admin plane)")
4061
+ );
4062
+ list.action(
4063
+ (opts) => runList(list, opts, "MCP integrations", (client) => client.mcpIntegrations.list())
4064
+ );
4065
+ const get = addReadOutput(
4066
+ group.command("get <id>").description("Get an MCP integration by UUID")
4067
+ );
4068
+ get.action((id, opts) => runDetail(get, opts, (client) => client.mcpIntegrations.get(id)));
4069
+ const mcpFields = [
4070
+ { option: "authType", path: "auth_type" },
4071
+ { option: "configurations", path: "configurations", parse: parseJsonOption },
4072
+ { option: "description", path: "description" },
4073
+ { option: "name", path: "name" },
4074
+ { option: "organisationId", path: "organisation_id" },
4075
+ { option: "secretMappings", path: "secret_mappings", parse: parseJsonOption },
4076
+ { option: "slug", path: "slug" },
4077
+ { option: "transport", path: "transport" },
4078
+ { option: "url", path: "url" }
4079
+ ];
4080
+ const addMcpFields = (command) => command.option(
4081
+ "--auth-type <type>",
4082
+ `Authentication type (known: ${knownValues(AI_GATEWAY_KNOWN_MCP_AUTH_TYPES)})`
4083
+ ).option("--configurations <json>", "MCP authentication/configuration object").option("--description <text>", "Integration description").option("--name <name>", "Integration name").option("--organisation-id <tsg>", "Numeric TSG id").option("--secret-mappings <json>", "Secret reference mapping array").option("--slug <slug>", "Stable integration slug").option(
4084
+ "--transport <transport>",
4085
+ `Transport (known: ${knownValues(AI_GATEWAY_KNOWN_MCP_TRANSPORTS)})`
4086
+ ).option("--url <url>", "MCP server URL");
4087
+ const mcpUpdateFields = mcpFields.filter(
4088
+ (field) => [
4089
+ "authType",
4090
+ "configurations",
4091
+ "description",
4092
+ "name",
4093
+ "secretMappings",
4094
+ "transport",
4095
+ "url"
4096
+ ].includes(field.option)
4097
+ );
4098
+ const addMcpUpdateFields = (command) => command.option(
4099
+ "--auth-type <type>",
4100
+ `Authentication type (known: ${knownValues(AI_GATEWAY_KNOWN_MCP_AUTH_TYPES)})`
4101
+ ).option("--configurations <json>", "MCP authentication/configuration object").option("--description <text>", "Integration description").option("--name <name>", "Integration name").option("--secret-mappings <json>", "Secret reference mapping array").option(
4102
+ "--transport <transport>",
4103
+ `Transport (known: ${knownValues(AI_GATEWAY_KNOWN_MCP_TRANSPORTS)})`
4104
+ ).option("--url <url>", "MCP server URL");
4105
+ addCrudMutationNodes(
4106
+ group,
4107
+ "MCP integration",
4108
+ {
4109
+ createFields: mcpFields,
4110
+ createOptions: addMcpFields,
4111
+ createSchema: McpIntegrationCreateRequestSchema,
4112
+ updateFields: mcpUpdateFields,
4113
+ updateOptions: addMcpUpdateFields,
4114
+ updateSchema: McpIntegrationUpdateRequestSchema
4115
+ },
4116
+ {
4117
+ create: (client, body) => client.mcpIntegrations.create(body),
4118
+ delete: (client, id) => client.mcpIntegrations.delete(id),
4119
+ update: (client, id, body) => client.mcpIntegrations.update(id, body)
4120
+ }
4121
+ );
4122
+ const capabilities = showHelpOnEmpty(
4123
+ group.command("capabilities").description("Inspect or replace MCP capabilities")
4124
+ );
4125
+ const capabilitiesList = addReadOutput(
4126
+ capabilities.command("list <id>").description("List discovered MCP capabilities")
4127
+ );
4128
+ capabilitiesList.action(
4129
+ (id, opts) => runDetail(capabilitiesList, opts, (client) => client.mcpIntegrations.getCapabilities(id))
4130
+ );
4131
+ const capabilitiesSet = addWriteOutput(
4132
+ addStructuredInputOptions(
4133
+ capabilities.command("set <id>").description("Replace enabled MCP capabilities").option(
4134
+ "--capability <type:name=enabled>",
4135
+ `Capability binding (repeatable; type: ${knownValues(AI_GATEWAY_MUTABLE_MCP_CAPABILITY_TYPES)})`,
4136
+ collectOption
4137
+ ).option("--force", "Skip confirmation prompt")
4138
+ )
4139
+ );
4140
+ capabilitiesSet.action(
4141
+ (id, opts) => runConfirmedWrite(
4142
+ capabilitiesSet,
4143
+ opts,
4144
+ `Replace enabled MCP capabilities on ${id}?`,
4145
+ () => buildStructuredRequest(opts, McpIntegrationCapabilitiesBulkUpdateRequestSchema, [
4146
+ { option: "capability", path: "capabilities", parse: parseCapabilityBindingsOption }
4147
+ ]),
4148
+ (client, body) => client.mcpIntegrations.setCapabilities(id, body)
4149
+ )
4150
+ );
4151
+ const metadata = addReadOutput(
4152
+ group.command("metadata <id>").description("Get discovered MCP metadata")
4153
+ );
4154
+ metadata.action(
4155
+ (id, opts) => runDetail(metadata, opts, (client) => client.mcpIntegrations.getMetadata(id))
4156
+ );
4157
+ const workspaces = showHelpOnEmpty(
4158
+ group.command("workspaces").description("Inspect or replace MCP workspace access")
4159
+ );
4160
+ const workspacesList = addReadOutput(
4161
+ workspaces.command("list <id>").description("Read workspace access from integration detail")
4162
+ );
4163
+ workspacesList.action(
4164
+ (id, opts) => runDetail(workspacesList, opts, (client) => client.mcpIntegrations.get(id))
4165
+ );
4166
+ const workspacesSet = addWriteOutput(
4167
+ addStructuredInputOptions(
4168
+ workspaces.command("set <id>").description("Replace MCP workspace access").option("--global-access <boolean>", "Enable or disable access to every workspace").option("--preserve-existing", "Preserve bindings not named by this command").option("--workspace-binding <id=enabled>", "Workspace binding (repeatable)", collectOption).option("--force", "Skip confirmation prompt")
4169
+ )
4170
+ );
4171
+ workspacesSet.action(
4172
+ (id, opts) => runConfirmedWrite(
4173
+ workspacesSet,
4174
+ opts,
4175
+ `Replace MCP workspace access on ${id}?`,
4176
+ () => buildStructuredRequest(
4177
+ {
4178
+ ...opts,
4179
+ overrideExistingWorkspaceAccess: !opts.preserveExisting
4180
+ },
4181
+ McpIntegrationWorkspacesBulkUpdateRequestSchema,
4182
+ [
4183
+ {
4184
+ option: "globalAccess",
4185
+ path: "global_workspace_access.enabled",
4186
+ parse: parseBooleanOption
4187
+ },
4188
+ {
4189
+ option: "overrideExistingWorkspaceAccess",
4190
+ path: "override_existing_workspace_access",
4191
+ parse: parseBooleanOption
4192
+ },
4193
+ { option: "workspaceBinding", path: "workspaces", parse: parseBooleanBindingsOption }
4194
+ ]
4195
+ ),
4196
+ (client, body) => client.mcpIntegrations.setWorkspaces(id, body)
4197
+ )
4198
+ );
4199
+ }
4200
+ function registerOrganisations(root) {
4201
+ const group = showHelpOnEmpty(
4202
+ root.command("organisations").description("Manage organisation and authentication settings")
4203
+ );
4204
+ const self = showHelpOnEmpty(
4205
+ group.command("self").description("Manage the current organisation")
4206
+ );
4207
+ const selfGet = addReadOutput(self.command("get").description("Get the current organisation"));
4208
+ selfGet.action((opts) => runDetail(selfGet, opts, (client) => client.organisations.getSelf()));
4209
+ const selfUpdate = addWriteOutput(
4210
+ addStructuredInputOptions(
4211
+ self.command("update").description("Update the current organisation with structured flags").option("--name <name>", "Organisation name")
4212
+ )
4213
+ );
4214
+ selfUpdate.action(
4215
+ (opts) => runWrite(
4216
+ selfUpdate,
4217
+ opts,
4218
+ () => buildStructuredRequest(opts, GatewayOrganisationUpdateRequestSchema, [
4219
+ { option: "name", path: "name" }
4220
+ ]),
4221
+ (client, body) => client.organisations.updateSelf(body)
4222
+ )
4223
+ );
4224
+ const auth = showHelpOnEmpty(
4225
+ group.command("auth-settings").description("Manage organisation authentication settings")
4226
+ );
4227
+ const authGet = addReadOutput(
4228
+ auth.command("get").description("Get authentication settings").requiredOption("--tsg-id <tsg>", "Numeric TSG id").option("--reveal-sensitive", "Show SCIM and authentication secrets")
4229
+ );
4230
+ authGet.action(
4231
+ (opts) => runDetail(authGet, opts, async (client) => {
4232
+ const result = await client.organisations.getAuthSettings(opts.tsgId);
4233
+ return opts.revealSensitive ? result : redactAIGatewaySecrets("organisations.getAuthSettings", result, "response");
4234
+ })
4235
+ );
4236
+ const authUpdate = addWriteOutput(
4237
+ addStructuredInputOptions(
4238
+ auth.command("update").description("Update authentication settings with structured flags").requiredOption("--tsg-id <tsg>", "Numeric TSG id").option("--auth-settings <json>", "Authentication settings object").option("--domains <domains>", "Comma-separated allowed domains").option("--scim-token <token>", "SCIM token")
4239
+ )
4240
+ );
4241
+ authUpdate.action(
4242
+ (opts) => runWrite(
4243
+ authUpdate,
4244
+ opts,
4245
+ () => buildStructuredRequest(opts, GatewayOrganisationAuthSettingsUpdateRequestSchema, [
4246
+ { option: "authSettings", path: "auth_settings", parse: parseJsonOption },
4247
+ { option: "domains", path: "domains", parse: parseCsvOption },
4248
+ { option: "scimToken", path: "scim_token" }
4249
+ ]),
4250
+ (client, body) => client.organisations.updateAuthSettings(opts.tsgId, body)
4251
+ )
4252
+ );
4253
+ }
4254
+ function registerPlugins(root) {
4255
+ const group = showHelpOnEmpty(root.command("plugins").description("Manage gateway plugins"));
4256
+ const list = addReadOutput(group.command("list").description("List installed gateway plugins"));
4257
+ list.action((opts) => runList(list, opts, "plugins", (client) => client.plugins.list()));
4258
+ const create = addWriteOutput(
4259
+ addStructuredInputOptions(
4260
+ group.command("create").description("Install a gateway plugin from structured flags").option(
4261
+ "--credential <key=value>",
4262
+ "Plugin credential (repeatable; treated as sensitive)",
4263
+ collectOption
4264
+ ).option("--integration-id <uuid>", "Integration UUID").option("--organisation-id <tsg>", "Numeric TSG id")
4265
+ )
4266
+ );
4267
+ create.action(
4268
+ (opts) => runWrite(
4269
+ create,
4270
+ opts,
4271
+ () => buildStructuredRequest(opts, GatewayPluginCreateRequestSchema, [
4272
+ { option: "credential", path: "credentials", parse: parseStringMapOption },
4273
+ { option: "integrationId", path: "integration_id" },
4274
+ { option: "organisationId", path: "organisation_id" }
4275
+ ]),
4276
+ (client, body) => client.plugins.create(body)
4277
+ )
4278
+ );
4279
+ }
4280
+ function registerAiGatewayInventory(root) {
4281
+ registerApiKeys(root);
4282
+ registerAuditLogs(root);
4283
+ registerConfigs(root);
4284
+ registerDeployments(root);
4285
+ const guardrails = registerScopedReads(
4286
+ root,
4287
+ "guardrails",
4288
+ "Manage workspace guardrails",
4289
+ (client) => client.guardrails
4290
+ );
4291
+ const guardrailFields = [
4292
+ { option: "actions", path: "actions", parse: parseJsonOption },
4293
+ { option: "checks", path: "checks", parse: parseJsonOption },
4294
+ { option: "name", path: "name" },
4295
+ { option: "workspace", path: "workspace_id" }
4296
+ ];
4297
+ const addGuardrailFields = (command) => command.option("--actions <json>", "Guardrail actions object").option("--checks <json>", "Guardrail checks array").option("--name <name>", "Guardrail name").option("--workspace <uuid>", "Workspace UUID");
4298
+ const guardrailUpdateFields = guardrailFields.filter((field) => field.option !== "workspace");
4299
+ const addGuardrailUpdateFields = (command) => command.option("--actions <json>", "Guardrail actions object").option("--checks <json>", "Guardrail checks array").option("--name <name>", "Guardrail name");
4300
+ addCrudMutationNodes(
4301
+ guardrails,
4302
+ "guardrail",
4303
+ {
4304
+ createFields: guardrailFields,
4305
+ createOptions: addGuardrailFields,
4306
+ createSchema: GatewayGuardrailCreateRequestSchema,
4307
+ updateFields: guardrailUpdateFields,
4308
+ updateOptions: addGuardrailUpdateFields,
4309
+ updateSchema: GatewayGuardrailUpdateRequestSchema
4310
+ },
4311
+ {
4312
+ create: (client, body) => client.guardrails.create(body),
4313
+ delete: (client, id) => client.guardrails.delete(id),
4314
+ update: (client, id, body) => client.guardrails.update(id, body)
4315
+ }
4316
+ );
4317
+ registerIntegrations(root);
4318
+ registerMcp(root);
4319
+ registerOrganisations(root);
4320
+ registerPlugins(root);
4321
+ const providers = registerScopedReads(
4322
+ root,
4323
+ "providers",
4324
+ "Manage workspace provider bindings",
4325
+ (client) => client.providers,
4326
+ { sensitiveDetail: true, sensitiveOperation: "providers.get" }
4327
+ );
4328
+ const providerFields = [
4329
+ { option: "aiProviderId", path: "ai_provider_id" },
4330
+ { option: "expiresAt", path: "expires_at" },
4331
+ { option: "integrationId", path: "integration_id" },
4332
+ { option: "name", path: "name" },
4333
+ { option: "note", path: "note" },
4334
+ { option: "rateLimit", path: "rate_limits", parse: parseJsonOption },
4335
+ { option: "resetUsage", path: "reset_usage", parse: parseBooleanOption },
4336
+ { option: "slug", path: "slug" },
4337
+ { option: "usageLimit", path: "usage_limits", parse: parseJsonOption },
4338
+ { option: "workspace", path: "workspace_id" }
4339
+ ];
4340
+ const addProviderFields = (command) => command.option("--ai-provider-id <uuid>", "Provider catalog UUID").option("--expires-at <iso>", "Expiration as ISO-8601").option("--integration-id <uuid>", "Organisation integration UUID").option("--name <name>", "Provider binding name").option("--note <text>", "Operator note").option("--rate-limit <json>", "Rate-limit object").option("--reset-usage <boolean>", "Reset accumulated usage: true or false").option("--slug <slug>", "Provider binding slug").option("--usage-limit <json>", "Usage-limit object").option("--workspace <uuid>", "Workspace UUID");
4341
+ const providerUpdateFields = providerFields.filter(
4342
+ (field) => ["expiresAt", "name", "note", "rateLimit", "resetUsage", "usageLimit"].includes(field.option)
4343
+ );
4344
+ const addProviderUpdateFields = (command) => command.option("--expires-at <iso>", "Expiration as ISO-8601").option("--name <name>", "Provider binding name").option("--note <text>", "Operator note").option("--rate-limit <json>", "Rate-limit object").option("--reset-usage <boolean>", "Reset accumulated usage: true or false").option("--usage-limit <json>", "Usage-limit object");
4345
+ addCrudMutationNodes(
4346
+ providers,
4347
+ "provider",
4348
+ {
4349
+ createFields: providerFields,
4350
+ createOptions: addProviderFields,
4351
+ createSchema: GatewayProviderCreateRequestSchema,
4352
+ updateFields: providerUpdateFields,
4353
+ updateOptions: addProviderUpdateFields,
4354
+ updateSchema: GatewayProviderUpdateRequestSchema
4355
+ },
4356
+ {
4357
+ create: (client, body) => client.providers.create(body),
4358
+ delete: (client, id) => client.providers.delete(id),
4359
+ update: (client, id, body) => client.providers.update(id, body)
4360
+ }
4361
+ );
4362
+ }
4363
+
4364
+ // src/cli/commands/aigateway/telemetry.ts
4365
+ function addWindowOptions(command) {
4366
+ return addReadOutput(
4367
+ command.requiredOption("--workspace <slug>", "Workspace slug").option("--days <n>", "Rolling window in days", "7").option("--end <iso>", "Window end as ISO-8601").option("--start <iso>", "Window start as ISO-8601")
4368
+ );
4369
+ }
4370
+ function windowFrom(opts) {
4371
+ const window = { workspaceSlug: opts.workspace };
4372
+ if (opts.start) window.start = parseNamedDate2(opts.start, "--start");
4373
+ else window.days = parsePositiveInteger2(opts.days ?? "7", "--days");
4374
+ if (opts.end) window.end = parseNamedDate2(opts.end, "--end");
4375
+ return window;
4376
+ }
4377
+ function parsePositiveInteger2(value, flag) {
4378
+ try {
4379
+ const parsed = parseIntegerOption(value);
4380
+ if (parsed <= 0) throw new CliUsageError("Expected a positive integer");
4381
+ return parsed;
4382
+ } catch (error) {
4383
+ if (error instanceof CliUsageError)
4384
+ throw new CliUsageError(`Invalid ${flag}: ${error.message}`);
4385
+ throw error;
2947
4386
  }
2948
- const prompt = options.promptFn ?? (await import("@inquirer/prompts")).confirm;
2949
- const confirmed = await prompt({ message, default: false });
2950
- if (!confirmed) {
2951
- ui.info("Aborted");
2952
- process.exit(0);
4387
+ }
4388
+ function parseNamedDate2(value, flag) {
4389
+ try {
4390
+ return parseDateOption(value);
4391
+ } catch (error) {
4392
+ if (error instanceof CliUsageError)
4393
+ throw new CliUsageError(`Invalid ${flag}: ${error.message}`);
4394
+ throw error;
2953
4395
  }
2954
4396
  }
2955
-
2956
- // src/cli/examples.ts
2957
- function examples(...lines) {
2958
- return `
2959
- Examples:
2960
- ${lines.map((l) => ` $ ${l}`).join("\n")}
2961
- `;
4397
+ function registerMetric(telemetry, name, description, method) {
4398
+ const command = addWindowOptions(telemetry.command(name).description(description));
4399
+ command.action(
4400
+ (opts) => runDetail(command, opts, (client) => client.telemetry[method](windowFrom(opts)))
4401
+ );
4402
+ }
4403
+ function registerAiGatewayTelemetryReads(telemetry) {
4404
+ const cache = showHelpOnEmpty(telemetry.command("cache").description("Inspect cache telemetry"));
4405
+ const cacheSummary = addWindowOptions(cache.command("summary").description("Get cache totals"));
4406
+ cacheSummary.action(
4407
+ (opts) => runDetail(cacheSummary, opts, (client) => client.telemetry.cacheSummary(windowFrom(opts)))
4408
+ );
4409
+ const cacheTrend = addWindowOptions(cache.command("trend").description("Get cache-hit trend"));
4410
+ cacheTrend.action(
4411
+ (opts) => runDetail(cacheTrend, opts, (client) => client.telemetry.cacheHitTrend(windowFrom(opts)))
4412
+ );
4413
+ registerMetric(telemetry, "error-trends", "Get error trends", "errorTrends");
4414
+ registerMetric(telemetry, "errors", "Get error count", "errors");
4415
+ const feedback = showHelpOnEmpty(
4416
+ telemetry.command("feedback").description("Inspect model feedback telemetry")
4417
+ );
4418
+ const feedbackMethods = {
4419
+ distribution: "feedbackScoreDistribution",
4420
+ models: "feedbackModels",
4421
+ trend: "feedbackTrend",
4422
+ weighted: "feedbackWeighted"
4423
+ };
4424
+ for (const [name, method] of Object.entries(feedbackMethods)) {
4425
+ const command = addWindowOptions(feedback.command(name).description(`Get feedback ${name}`));
4426
+ command.action(
4427
+ (opts) => runDetail(command, opts, (client) => client.telemetry[method](windowFrom(opts)))
4428
+ );
4429
+ }
4430
+ const groupBy = addWindowOptions(
4431
+ telemetry.command("group-by <dimension>").description("Aggregate telemetry by provider, model, status, or another SDK dimension").option("--columns <names>", "Comma-separated aggregate columns")
4432
+ );
4433
+ groupBy.action(
4434
+ (dimension, opts) => runDetail(
4435
+ groupBy,
4436
+ opts,
4437
+ (client) => client.telemetry.groupBy(dimension, {
4438
+ ...windowFrom(opts),
4439
+ ...opts.columns ? { columns: opts.columns.split(",").map((value) => value.trim()) } : {}
4440
+ })
4441
+ )
4442
+ );
4443
+ registerMetric(telemetry, "latency", "Get latency telemetry", "latency");
4444
+ const logs = showHelpOnEmpty(telemetry.command("logs").description("Inspect request logs"));
4445
+ const logsList = addWindowOptions(
4446
+ logs.command("list").description("List request logs").option("--page-size <n>", "Rows per response", "50").option("--status-code <code>", "Filter by HTTP status").option("--trace-id <id>", "Return one trace id")
4447
+ );
4448
+ logsList.action(
4449
+ (opts) => runDetail(
4450
+ logsList,
4451
+ opts,
4452
+ (client) => client.telemetry.logs({
4453
+ ...windowFrom(opts),
4454
+ pageSize: parsePositiveInteger2(opts.pageSize ?? "50", "--page-size"),
4455
+ ...opts.statusCode ? { statusCode: parsePositiveInteger2(opts.statusCode, "--status-code") } : {},
4456
+ ...opts.traceId ? { traceId: opts.traceId } : {}
4457
+ })
4458
+ )
4459
+ );
4460
+ registerMetric(telemetry, "requests", "Get request count", "requests");
4461
+ registerMetric(telemetry, "rescued-retries", "Get rescued retry telemetry", "rescuedRetries");
4462
+ registerMetric(telemetry, "tokens", "Get token usage", "tokens");
4463
+ registerMetric(telemetry, "user-trends", "Get user trends", "userTrends");
4464
+ registerMetric(telemetry, "users", "Get unique-user count", "users");
2962
4465
  }
2963
4466
 
2964
4467
  // src/cli/commands/aigateway.ts
@@ -3001,18 +4504,18 @@ function buildWorkspaceWriteRequest(opts) {
3001
4504
  const defaults = parseJsonFlag(opts.defaults, "--defaults");
3002
4505
  const metadata = parseJsonFlag(opts.metadata, "--metadata");
3003
4506
  if (defaults !== void 0 || metadata !== void 0) {
3004
- out.defaults = {
4507
+ out.defaults = GatewayDefaultsInputSchema.parse({
3005
4508
  ...typeof defaults === "object" && defaults !== null ? defaults : {},
3006
4509
  ...metadata !== void 0 ? { metadata } : {}
3007
- };
4510
+ });
3008
4511
  }
3009
4512
  if (opts.users !== void 0) {
3010
4513
  out.users = opts.users.split(",").map((u) => u.trim()).filter(Boolean);
3011
4514
  }
3012
4515
  const usage = parseJsonFlag(opts.usageLimits, "--usage-limits");
3013
- if (usage !== void 0) out.usageLimits = usage;
4516
+ if (usage !== void 0) out.usageLimits = GatewayUsageLimitInputSchema.array().parse(usage);
3014
4517
  const rate = parseJsonFlag(opts.rateLimits, "--rate-limits");
3015
- if (rate !== void 0) out.rateLimits = rate;
4518
+ if (rate !== void 0) out.rateLimits = GatewayRateLimitInputSchema.array().parse(rate);
3016
4519
  return out;
3017
4520
  }
3018
4521
  function scopeNameLooksUnrelated(name, scopeName) {
@@ -3021,15 +4524,16 @@ function scopeNameLooksUnrelated(name, scopeName) {
3021
4524
  return !scopeName.toLowerCase().replace(/[^a-z0-9]/g, "").includes(nameToken);
3022
4525
  }
3023
4526
  function registerAiGatewayCommand(program) {
3024
- const aigateway = program.command("aigateway").description("AI Gateway operations");
3025
- const workspace = aigateway.command("workspace").description("Manage AI Gateway workspaces");
4527
+ const aigateway = program.command("aigateway").description("Manage and observe Prisma AIRS AI Gateway resources").action(() => aigateway.outputHelp());
4528
+ registerAiGatewayInventory(aigateway);
4529
+ const workspace = aigateway.command("workspaces").alias("workspace").description("Manage gateway workspaces").action(() => workspace.outputHelp());
3026
4530
  const workspaceList = workspace.command("list").description("List workspaces (default: active workspaces you are scoped to)").option("--plane <plane>", "Plane to read from: data (scoped) or admin (whole tenant)").option("--status <status>", "Filter by lifecycle state: active or archived").option("--all", "Merge active + archived admin-plane reads (whole tenant, both states)").option("--output <format>", "Output format: pretty, table, markdown, csv, json, yaml").addHelpText(
3027
4531
  "after",
3028
4532
  examples(
3029
- "airs aigateway workspace list",
3030
- "airs aigateway workspace list --plane admin",
3031
- "airs aigateway workspace list --plane admin --status archived",
3032
- "airs aigateway workspace list --all --output json"
4533
+ "airs aigateway workspaces list",
4534
+ "airs aigateway workspaces list --plane admin",
4535
+ "airs aigateway workspaces list --plane admin --status archived",
4536
+ "airs aigateway workspaces list --all --output json"
3033
4537
  )
3034
4538
  ).action(async (opts) => {
3035
4539
  try {
@@ -3057,8 +4561,8 @@ function registerAiGatewayCommand(program) {
3057
4561
  const workspaceGet = workspace.command("get <ref>").description("Get one workspace by UUID or slug (includes settings blocks)").option("--plane <plane>", "Plane to read from: data (scoped) or admin (whole tenant)").option("--output <format>", "Output format: pretty, table, markdown, csv, json, yaml").addHelpText(
3058
4562
  "after",
3059
4563
  examples(
3060
- "airs aigateway workspace get ws-main-a-349e0e",
3061
- "airs aigateway workspace get 16f7e90d-382a-4e78-b577-1b01eb5f8297 --plane admin --output json"
4564
+ "airs aigateway workspaces get ws-main-a-349e0e",
4565
+ "airs aigateway workspaces get 16f7e90d-382a-4e78-b577-1b01eb5f8297 --plane admin --output json"
3062
4566
  )
3063
4567
  ).action(async (ref, opts) => {
3064
4568
  try {
@@ -3081,8 +4585,8 @@ function registerAiGatewayCommand(program) {
3081
4585
  ).option("--description <text>", "Workspace description").option("--icon <icon>", "Workspace icon").option("--metadata <json>", "Sugar for defaults.metadata (flat string map)").option("--defaults <json>", "Workspace defaults object").option("--users <ids>", "Comma-separated user ids to seed the workspace with").option("--usage-limits <json>", "Usage-limit policies \u2014 a JSON ARRAY of policy objects").option("--rate-limits <json>", "Rate-limit policies \u2014 a JSON ARRAY of policy objects").option("--output <format>", "Output format: pretty, json, yaml", "pretty").addHelpText(
3082
4586
  "after",
3083
4587
  examples(
3084
- "airs aigateway workspace create --name Production --scope-name ws_production_bx7qw0",
3085
- `airs aigateway workspace create --name Production --scope-name ws_production_bx7qw0 --metadata '{"env":"production"}' --rate-limits '[{"type":"requests","unit":"rpm","value":100}]'`
4588
+ "airs aigateway workspaces create --name Production --scope-name ws_production_bx7qw0",
4589
+ `airs aigateway workspaces create --name Production --scope-name ws_production_bx7qw0 --metadata '{"env":"production"}' --rate-limits '[{"type":"requests","unit":"rpm","value":100}]'`
3086
4590
  )
3087
4591
  ).action(async (opts) => {
3088
4592
  try {
@@ -3108,7 +4612,7 @@ function registerAiGatewayCommand(program) {
3108
4612
  workspace.command("update <ref>").description("Update a workspace (admin plane, partial patch)").option("--name <name>", "New display name").option("--description <text>", "New description").option("--icon <icon>", "New icon").option("--metadata <json>", "Sugar for defaults.metadata (flat string map)").option("--defaults <json>", "Workspace defaults object").option("--usage-limits <json>", "Usage-limit policies \u2014 a JSON ARRAY of policy objects").option("--rate-limits <json>", "Rate-limit policies \u2014 a JSON ARRAY of policy objects").option("--output <format>", "Output format: pretty, json, yaml", "pretty").addHelpText(
3109
4613
  "after",
3110
4614
  examples(
3111
- `airs aigateway workspace update ws-produc-985697 --description 'Production workloads, us-east'`
4615
+ `airs aigateway workspaces update ws-produc-985697 --description 'Production workloads, us-east'`
3112
4616
  )
3113
4617
  ).action(async (ref, opts) => {
3114
4618
  try {
@@ -3128,9 +4632,14 @@ function registerAiGatewayCommand(program) {
3128
4632
  failWithGrantHint(err);
3129
4633
  }
3130
4634
  });
3131
- workspace.command("delete <ref>").description("Archive a workspace (soft delete \u2014 there is no hard delete)").option("--force", "Skip confirmation prompt").addHelpText("after", examples("airs aigateway workspace delete ws-produc-985697 --force")).action(async (ref, opts) => {
4635
+ const archiveWorkspace = async (ref, opts, deprecated) => {
3132
4636
  try {
3133
4637
  renderAiGatewayHeader();
4638
+ if (deprecated) {
4639
+ ui.warn(
4640
+ "`aigateway workspace delete` is deprecated because this operation archives; use `aigateway workspaces archive`."
4641
+ );
4642
+ }
3134
4643
  await confirmOrAbort(
3135
4644
  `Archive workspace ${ref}? (soft delete \u2014 the row remains under --status archived)`,
3136
4645
  Boolean(opts.force),
@@ -3140,13 +4649,16 @@ function registerAiGatewayCommand(program) {
3140
4649
  await service.deleteWorkspace(ref);
3141
4650
  ui.success(`Workspace archived: ${ref}`);
3142
4651
  ui.status(
3143
- "This is a soft delete \u2014 the workspace remains visible via `workspace list --plane admin --status archived`. A `get` on it now answers 404; that is expected."
4652
+ "This is a soft delete \u2014 the workspace remains visible via `workspaces list --plane admin --status archived`. A `get` on it now answers 404; that is expected."
3144
4653
  );
3145
4654
  } catch (err) {
3146
4655
  failWithGrantHint(err);
3147
4656
  }
3148
- });
3149
- const telemetry = aigateway.command("telemetry").description("AI Gateway runtime telemetry (data plane)");
4657
+ };
4658
+ workspace.command("archive <ref>").description("Archive a workspace (soft delete \u2014 there is no hard delete)").option("--force", "Skip confirmation prompt").addHelpText("after", examples("airs aigateway workspaces archive ws-produc-985697 --force")).action((ref, opts) => archiveWorkspace(ref, opts, false));
4659
+ workspace.command("delete <ref>", { hidden: true }).description("Deprecated compatibility command for archive").option("--force", "Skip confirmation prompt").action((ref, opts) => archiveWorkspace(ref, opts, true));
4660
+ const telemetry = aigateway.command("telemetry").description("AI Gateway runtime telemetry (data plane)").action(() => telemetry.outputHelp());
4661
+ registerAiGatewayTelemetryReads(telemetry);
3150
4662
  const cost = telemetry.command("cost").description(
3151
4663
  "Total and per-day spend for a workspace (API reports cents; pretty output shows dollars)"
3152
4664
  ).requiredOption("--workspace <slug>", "Workspace slug (not UUID), e.g. ws-main-a-349e0e").option("--days <n>", "Rolling window in days, counted back from now", "7").option("--output <format>", "Output format: pretty, table, markdown, csv, json, yaml").addHelpText(
@@ -3292,8 +4804,8 @@ function registerCompletionCommand(program) {
3292
4804
  }
3293
4805
 
3294
4806
  // src/cli/commands/config.ts
3295
- import { mkdir, readFile, writeFile } from "fs/promises";
3296
- import { dirname } from "path";
4807
+ import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
4808
+ import { dirname as dirname2 } from "path";
3297
4809
  var CONFIG_KEYS = Object.keys(ConfigSchema.shape);
3298
4810
  var SECRET_PATTERN = /key|secret|token|password/i;
3299
4811
  function isKnownKey(key) {
@@ -3316,7 +4828,7 @@ function buildConfigRows(inspected, reveal) {
3316
4828
  async function readConfigFileStrict(filePath) {
3317
4829
  let raw;
3318
4830
  try {
3319
- raw = await readFile(filePath, "utf-8");
4831
+ raw = await readFile2(filePath, "utf-8");
3320
4832
  } catch {
3321
4833
  return { ok: true, data: {} };
3322
4834
  }
@@ -3341,7 +4853,7 @@ async function setConfigValue(filePath, key, value) {
3341
4853
  }
3342
4854
  const coerced = result.data[key];
3343
4855
  const next = { ...read.data, [key]: coerced };
3344
- await mkdir(dirname(filePath), { recursive: true });
4856
+ await mkdir(dirname2(filePath), { recursive: true });
3345
4857
  await writeFile(filePath, `${JSON.stringify(next, null, 2)}
3346
4858
  `, "utf-8");
3347
4859
  return { ok: true, value: coerced };
@@ -3452,7 +4964,7 @@ function registerConfigCommand(program) {
3452
4964
 
3453
4965
  // src/cli/commands/doctor.ts
3454
4966
  import { randomUUID } from "crypto";
3455
- import { readFile as readFile2 } from "fs/promises";
4967
+ import { readFile as readFile3 } from "fs/promises";
3456
4968
  import { init, Scanner } from "@cdot65/prisma-airs-sdk";
3457
4969
  var DOCTOR_TIMEOUT_MS = 5e3;
3458
4970
  var MIN_NODE_MAJOR = 20;
@@ -3472,7 +4984,7 @@ async function checkConfigFile(filePath) {
3472
4984
  const name = "Config file";
3473
4985
  let raw;
3474
4986
  try {
3475
- raw = await readFile2(filePath, "utf-8");
4987
+ raw = await readFile3(filePath, "utf-8");
3476
4988
  } catch {
3477
4989
  return {
3478
4990
  name,
@@ -5634,8 +7146,8 @@ function registerRedteamCommand(program) {
5634
7146
  // src/cli/commands/runtime.ts
5635
7147
  import { randomUUID as randomUUID4 } from "crypto";
5636
7148
  import * as fs5 from "fs";
5637
- import { readFile as readFile8 } from "fs/promises";
5638
- import { basename as basename3, dirname as dirname2, join as join2, resolve as resolvePath } from "path";
7149
+ import { readFile as readFile9 } from "fs/promises";
7150
+ import { basename as basename3, dirname as dirname3, join as join3, resolve as resolvePath } from "path";
5639
7151
  import chalk11 from "chalk";
5640
7152
 
5641
7153
  // src/cli/builders/profile-builder.ts
@@ -6313,7 +7825,7 @@ var topicsView = {
6313
7825
  };
6314
7826
 
6315
7827
  // src/cli/commands/dlp/dictionaries.ts
6316
- import { readFile as readFile6 } from "fs/promises";
7828
+ import { readFile as readFile7 } from "fs/promises";
6317
7829
  import { basename as basename2 } from "path";
6318
7830
 
6319
7831
  // src/airs/dlp/dictionaries.ts
@@ -6352,7 +7864,7 @@ var SdkDictionariesService = class {
6352
7864
  };
6353
7865
 
6354
7866
  // src/cli/commands/dlp/patch.ts
6355
- import { readFile as readFile5 } from "fs/promises";
7867
+ import { readFile as readFile6 } from "fs/promises";
6356
7868
  function buildMergePatch(opts) {
6357
7869
  const out = {};
6358
7870
  for (const entry of opts.set ?? []) {
@@ -6394,7 +7906,7 @@ function coerceValue(raw) {
6394
7906
  async function parseBody(opts) {
6395
7907
  let raw;
6396
7908
  if (opts.bodyFile) {
6397
- raw = await readFile5(opts.bodyFile, "utf-8");
7909
+ raw = await readFile6(opts.bodyFile, "utf-8");
6398
7910
  } else if (opts.body === "-") {
6399
7911
  const chunks = [];
6400
7912
  for await (const chunk of opts.stdin ?? process.stdin) {
@@ -6415,7 +7927,7 @@ async function parseBody(opts) {
6415
7927
  // src/cli/commands/dlp/dictionaries.ts
6416
7928
  async function buildMetadata(opts) {
6417
7929
  if (opts.metadataFile) {
6418
- return JSON.parse(await readFile6(opts.metadataFile, "utf-8"));
7930
+ return JSON.parse(await readFile7(opts.metadataFile, "utf-8"));
6419
7931
  }
6420
7932
  if (!opts.name || !opts.category || !opts.region || !opts.file) {
6421
7933
  throw new Error("--name, --category, --region, and --file are required");
@@ -6460,7 +7972,7 @@ function register(dlp) {
6460
7972
  try {
6461
7973
  const metadata = await buildMetadata(opts);
6462
7974
  if (!opts.file) throw new Error("--file is required (multipart upload)");
6463
- const file = await readFile6(opts.file);
7975
+ const file = await readFile7(opts.file);
6464
7976
  const r = await new SdkDictionariesService().create({
6465
7977
  metadata,
6466
7978
  file,
@@ -6488,7 +8000,7 @@ function register(dlp) {
6488
8000
  try {
6489
8001
  const metadata = await buildMetadata(opts);
6490
8002
  if (!opts.file) throw new Error("--file is required (multipart upload)");
6491
- const file = await readFile6(opts.file);
8003
+ const file = await readFile7(opts.file);
6492
8004
  const r = await new SdkDictionariesService().replace(id, {
6493
8005
  metadata,
6494
8006
  file,
@@ -7308,7 +8820,7 @@ function registerCreateCommand(parent) {
7308
8820
  }
7309
8821
 
7310
8822
  // src/cli/commands/topics-eval.ts
7311
- import { readFile as readFile7 } from "fs/promises";
8823
+ import { readFile as readFile8 } from "fs/promises";
7312
8824
 
7313
8825
  // src/core/prompt-loader.ts
7314
8826
  function parseCsvLine(line) {
@@ -7451,7 +8963,7 @@ function registerEvalCommand(parent) {
7451
8963
  resolveDeprecatedAliases(cmd, opts);
7452
8964
  try {
7453
8965
  const config = await loadConfig();
7454
- const csvContent = await readFile7(opts.prompts, "utf-8");
8966
+ const csvContent = await readFile8(opts.prompts, "utf-8");
7455
8967
  const { cases, intent } = loadPrompts(csvContent, (msg) => ui.status(`Warning: ${msg}`));
7456
8968
  if (!config.airsApiKey && !config.airsApiToken) {
7457
8969
  fail(new Error("PANW_AI_SEC_API_KEY or PANW_AI_SEC_API_TOKEN is required"));
@@ -7622,7 +9134,7 @@ function completedBulkResults(state) {
7622
9134
  return state.items.flatMap((item) => item.result ? [item.result] : []).sort((left, right) => left.index - right.index);
7623
9135
  }
7624
9136
  async function writeBulkResults(outputPath, results) {
7625
- await fs5.promises.mkdir(dirname2(outputPath), { recursive: true });
9137
+ await fs5.promises.mkdir(dirname3(outputPath), { recursive: true });
7626
9138
  const temporary = `${outputPath}.tmp-${process.pid}-${randomUUID4()}`;
7627
9139
  try {
7628
9140
  await fs5.promises.writeFile(temporary, SdkRuntimeService.formatResultsCsv(results), {
@@ -7640,10 +9152,10 @@ function isDefiniteSubmissionRejection(error) {
7640
9152
  const metadata = error;
7641
9153
  return metadata?.failureKind === "http" && typeof metadata.statusCode === "number" && metadata.statusCode >= 400 && metadata.statusCode < 500;
7642
9154
  }
7643
- function parsePositiveInteger(value, optionName) {
9155
+ function parsePositiveInteger3(value, optionName2) {
7644
9156
  const parsed = Number(value);
7645
9157
  if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(parsed)) {
7646
- usageError(`${optionName} must be a positive integer`);
9158
+ usageError(`${optionName2} must be a positive integer`);
7647
9159
  }
7648
9160
  return parsed;
7649
9161
  }
@@ -7746,14 +9258,14 @@ function registerRuntimeCommand(program) {
7746
9258
  if (!opts.file) {
7747
9259
  usageError("--file <file> is required");
7748
9260
  }
7749
- const batchSize = parsePositiveInteger(opts.batchSize, "--batch-size");
9261
+ const batchSize = parsePositiveInteger3(opts.batchSize, "--batch-size");
7750
9262
  let releaseJobLock;
7751
9263
  try {
7752
9264
  const config = await loadConfig({});
7753
9265
  if (!config.airsApiKey && !config.airsApiToken) {
7754
9266
  fail(new Error("PANW_AI_SEC_API_KEY or PANW_AI_SEC_API_TOKEN is required"));
7755
9267
  }
7756
- const raw = await readFile8(opts.file, "utf-8");
9268
+ const raw = await readFile9(opts.file, "utf-8");
7757
9269
  const prompts = parseInputFile(raw, opts.file);
7758
9270
  if (prompts.length === 0) {
7759
9271
  usageError("No prompts found in input file");
@@ -7763,7 +9275,7 @@ function registerRuntimeCommand(program) {
7763
9275
  opts.outputFile ?? `${opts.profile.replace(/\s+/g, "-")}-bulk-scan.csv`
7764
9276
  );
7765
9277
  const stateDir = resolvePath(
7766
- basename3(config.dataDir) === "runs" ? join2(dirname2(config.dataDir), "bulk-scans") : join2(config.dataDir, "bulk-scans")
9278
+ basename3(config.dataDir) === "runs" ? join3(dirname3(config.dataDir), "bulk-scans") : join3(config.dataDir, "bulk-scans")
7767
9279
  );
7768
9280
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
7769
9281
  const state = {
@@ -8202,7 +9714,7 @@ function registerRuntimeCommand(program) {
8202
9714
  );
8203
9715
  const outputPath = resolvePath(opts.outputFile ?? state.outputFile);
8204
9716
  state.outputFile = outputPath;
8205
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9717
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8206
9718
  const pollSubmitted = async (items) => {
8207
9719
  for (const batch of submittedBatches(items)) {
8208
9720
  const results2 = await service.pollBatch(batch, void 0, {
@@ -8211,12 +9723,12 @@ function registerRuntimeCommand(program) {
8211
9723
  },
8212
9724
  onProgress: async (progress) => {
8213
9725
  recordBulkResults(state, progress);
8214
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9726
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8215
9727
  await writeBulkResults(outputPath, completedBulkResults(state));
8216
9728
  }
8217
9729
  });
8218
9730
  recordBulkResults(state, results2);
8219
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9731
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8220
9732
  await writeBulkResults(outputPath, completedBulkResults(state));
8221
9733
  }
8222
9734
  };
@@ -8240,7 +9752,7 @@ function registerRuntimeCommand(program) {
8240
9752
  for (let start = 0; start < pendingItems.length; start += SDK_ASYNC_BATCH_SIZE) {
8241
9753
  const chunk = pendingItems.slice(start, start + SDK_ASYNC_BATCH_SIZE);
8242
9754
  for (const item of chunk) item.status = "submitting";
8243
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9755
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8244
9756
  try {
8245
9757
  const batch = await service.submitBatch(state.profile, chunk, state.sessionId, {
8246
9758
  onRetry: (attempt, delayMs) => {
@@ -8256,19 +9768,19 @@ function registerRuntimeCommand(program) {
8256
9768
  item.receiptReportId = batch.reportId;
8257
9769
  item.error = void 0;
8258
9770
  }
8259
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9771
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8260
9772
  } catch (error) {
8261
9773
  for (const item of chunk) {
8262
9774
  item.status = isDefiniteSubmissionRejection(error) ? "pending" : "ambiguous";
8263
9775
  item.error = error instanceof Error ? error.message : String(error);
8264
9776
  }
8265
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9777
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8266
9778
  throw error;
8267
9779
  }
8268
9780
  }
8269
9781
  await pollSubmitted(logicalBatch);
8270
9782
  }
8271
- await saveBulkScanState(state, dirname2(stateFile), stateFile);
9783
+ await saveBulkScanState(state, dirname3(stateFile), stateFile);
8272
9784
  const results = completedBulkResults(state);
8273
9785
  await writeBulkResults(outputPath, results);
8274
9786
  const blocked = results.filter((r) => r.action === "block").length;
@@ -8421,185 +9933,6 @@ function registerRuntimeCommand(program) {
8421
9933
  registerDlpCommands(runtime);
8422
9934
  }
8423
9935
 
8424
- // src/cli/debug-logger.ts
8425
- import {
8426
- appendFileSync,
8427
- mkdirSync,
8428
- readdirSync,
8429
- statSync,
8430
- unlinkSync,
8431
- writeFileSync as writeFileSync2
8432
- } from "fs";
8433
- import { dirname as dirname3, join as join3 } from "path";
8434
- var AIRS_DOMAINS = [
8435
- "api.sase.paloaltonetworks.com",
8436
- "service.api.aisecurity.paloaltonetworks.com",
8437
- "auth.apps.paloaltonetworks.com",
8438
- "api.dlp.paloaltonetworks.com"
8439
- ];
8440
- function isAirsUrl(url) {
8441
- try {
8442
- const parsed = new URL(url);
8443
- return AIRS_DOMAINS.some((d) => parsed.hostname === d || parsed.hostname.endsWith(`.${d}`));
8444
- } catch {
8445
- return false;
8446
- }
8447
- }
8448
- var MASK = "***";
8449
- var SENSITIVE_KEY_PATTERN = /token|secret|password|passwd|credential|authorization|cookie|api[-_]?key/i;
8450
- function isSensitiveKey(key) {
8451
- return SENSITIVE_KEY_PATTERN.test(key);
8452
- }
8453
- function redactHeaders(headers) {
8454
- const out = {};
8455
- for (const [k, v] of Object.entries(headers)) {
8456
- out[k] = isSensitiveKey(k) ? MASK : v;
8457
- }
8458
- return out;
8459
- }
8460
- function redactDeep(value) {
8461
- if (Array.isArray(value)) {
8462
- return value.map(redactDeep);
8463
- }
8464
- if (value !== null && typeof value === "object") {
8465
- const out = {};
8466
- for (const [k, v] of Object.entries(value)) {
8467
- out[k] = isSensitiveKey(k) ? MASK : redactDeep(v);
8468
- }
8469
- return out;
8470
- }
8471
- return value;
8472
- }
8473
- function redactUrl(url) {
8474
- try {
8475
- const parsed = new URL(url);
8476
- let touched = false;
8477
- for (const key of parsed.searchParams.keys()) {
8478
- if (isSensitiveKey(key)) {
8479
- parsed.searchParams.set(key, MASK);
8480
- touched = true;
8481
- }
8482
- }
8483
- return touched ? parsed.toString() : url;
8484
- } catch {
8485
- return url;
8486
- }
8487
- }
8488
- function pruneDebugLogs(dir, keep) {
8489
- let files;
8490
- try {
8491
- files = readdirSync(dir).filter((f) => f.startsWith("debug-api-") && f.endsWith(".jsonl"));
8492
- } catch {
8493
- return;
8494
- }
8495
- const byAge = files.map((f) => {
8496
- const path3 = join3(dir, f);
8497
- try {
8498
- return { path: path3, mtime: statSync(path3).mtimeMs };
8499
- } catch {
8500
- return null;
8501
- }
8502
- }).filter((e) => e !== null).sort((a, b) => b.mtime - a.mtime);
8503
- for (const { path: path3 } of byAge.slice(keep)) {
8504
- try {
8505
- unlinkSync(path3);
8506
- } catch {
8507
- }
8508
- }
8509
- }
8510
- function headersToRecord(headers) {
8511
- if (!headers) return {};
8512
- if (typeof headers === "object" && "forEach" in headers && typeof headers.forEach === "function") {
8513
- const out = {};
8514
- headers.forEach((v, k) => {
8515
- out[k] = v;
8516
- });
8517
- return out;
8518
- }
8519
- if (Array.isArray(headers)) {
8520
- return Object.fromEntries(headers);
8521
- }
8522
- return headers;
8523
- }
8524
- var KEEP_DEBUG_LOGS = 10;
8525
- function installDebugLogger(logPath) {
8526
- mkdirSync(dirname3(logPath), { recursive: true });
8527
- writeFileSync2(logPath, "", "utf-8");
8528
- pruneDebugLogs(dirname3(logPath), KEEP_DEBUG_LOGS);
8529
- const originalFetch = globalThis.fetch;
8530
- globalThis.fetch = async function debugFetch(input, init2) {
8531
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
8532
- if (!isAirsUrl(url)) {
8533
- return originalFetch(input, init2);
8534
- }
8535
- const method = init2?.method ?? (input instanceof Request ? input.method : "GET");
8536
- const reqHeaders = redactHeaders(headersToRecord(init2?.headers));
8537
- const loggedUrl = redactUrl(url);
8538
- let reqBody;
8539
- if (init2?.body) {
8540
- try {
8541
- reqBody = redactDeep(JSON.parse(String(init2.body)));
8542
- } catch {
8543
- reqBody = String(init2.body);
8544
- }
8545
- }
8546
- const ts2 = (/* @__PURE__ */ new Date()).toISOString();
8547
- const startMs = Date.now();
8548
- let response;
8549
- let resBody;
8550
- let error;
8551
- try {
8552
- response = await originalFetch(input, init2);
8553
- } catch (err) {
8554
- error = err instanceof Error ? err.message : String(err);
8555
- const entry2 = JSON.stringify({
8556
- timestamp: ts2,
8557
- durationMs: Date.now() - startMs,
8558
- request: { method, url: loggedUrl, headers: reqHeaders, body: reqBody },
8559
- error
8560
- });
8561
- appendFileSync(logPath, `${entry2}
8562
- `);
8563
- throw err;
8564
- }
8565
- const durationMs = Date.now() - startMs;
8566
- const resHeaders = {};
8567
- response.headers.forEach((v, k) => {
8568
- resHeaders[k] = v;
8569
- });
8570
- const clone = response.clone();
8571
- try {
8572
- const text = await clone.text();
8573
- try {
8574
- resBody = redactDeep(JSON.parse(text));
8575
- } catch {
8576
- resBody = text;
8577
- }
8578
- } catch {
8579
- resBody = "<unreadable>";
8580
- }
8581
- const entry = JSON.stringify({
8582
- timestamp: ts2,
8583
- durationMs,
8584
- request: { method, url: loggedUrl, headers: reqHeaders, body: reqBody },
8585
- response: {
8586
- status: response.status,
8587
- statusText: response.statusText,
8588
- headers: redactHeaders(resHeaders),
8589
- body: resBody
8590
- }
8591
- });
8592
- appendFileSync(logPath, `${entry}
8593
- `);
8594
- return response;
8595
- };
8596
- return {
8597
- teardown() {
8598
- globalThis.fetch = originalFetch;
8599
- }
8600
- };
8601
- }
8602
-
8603
9936
  // src/cli/program.ts
8604
9937
  var READ_COMMAND_NAMES = /* @__PURE__ */ new Set([
8605
9938
  "categories",
@@ -8625,7 +9958,9 @@ var READ_COMMAND_NAMES = /* @__PURE__ */ new Set([
8625
9958
  function applyListDeleteAliases(cmd) {
8626
9959
  for (const sub of cmd.commands) {
8627
9960
  if (sub.name() === "list" && !sub.aliases().includes("ls")) sub.alias("ls");
8628
- if (sub.name() === "delete" && !sub.aliases().includes("rm")) sub.alias("rm");
9961
+ const isHiddenCompatibilityCommand = sub.name() === "delete" && Boolean(sub._hidden);
9962
+ if (sub.name() === "delete" && !isHiddenCompatibilityCommand && !sub.aliases().includes("rm"))
9963
+ sub.alias("rm");
8629
9964
  applyListDeleteAliases(sub);
8630
9965
  }
8631
9966
  }