bpmax-cli 0.1.42 → 0.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -146,7 +146,10 @@ function resolveProfile(config, profileName) {
146
146
  workspace: profile.workspace || DEFAULT_WORKSPACE,
147
147
  language: profile.language || DEFAULT_LANGUAGE,
148
148
  user: profile.user,
149
- capabilities_cache: profile.capabilities_cache
149
+ capabilities_cache: profile.capabilities_cache,
150
+ terminal_id: profile.terminal_id,
151
+ terminal_registered_at: profile.terminal_registered_at,
152
+ terminal_status: profile.terminal_status
150
153
  }
151
154
  };
152
155
  }
@@ -169,10 +172,67 @@ async function upsertProfile(name, nextProfile) {
169
172
  // src/core/http.ts
170
173
  import axios, { AxiosHeaders } from "axios";
171
174
 
175
+ // src/core/platform-compat.ts
176
+ var CLI_GOVERNANCE_PATHS = [
177
+ "/api/cli/capabilities",
178
+ "/api/cli/terminals/register",
179
+ "/api/cli/audit/start",
180
+ "/api/cli/audit/finish"
181
+ ];
182
+ var CLI_GOVERNANCE_UNSUPPORTED_MESSAGE = "\u5F53\u524D BPMAX \u5E73\u53F0\u7248\u672C\u4E0D\u652F\u6301 CLI \u6CBB\u7406\u80FD\u529B\uFF0C\u8BF7\u5347\u7EA7 huanpingtong-server \u540E\u518D\u4F7F\u7528 bpmax-cli 0.1.42+ \u7684\u8FDC\u7AEF\u4E1A\u52A1\u547D\u4EE4\u3002";
183
+ function toCliGovernanceUnsupportedError(error, fallbackPath) {
184
+ const status = getNumber(error, ["response", "status"]);
185
+ const bodyCode = getNumber(error, ["response", "data", "code"]);
186
+ const responseUrl = getString(error, ["response", "config", "url"]) || getString(error, ["config", "url"]) || fallbackPath || "";
187
+ const normalizedPath = normalizePath(responseUrl);
188
+ const isGovernancePath = CLI_GOVERNANCE_PATHS.includes(normalizedPath);
189
+ const isMissingEndpoint = status === 404 || bodyCode === 404;
190
+ if (isGovernancePath && isMissingEndpoint) {
191
+ return new Error(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE);
192
+ }
193
+ return void 0;
194
+ }
195
+ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
196
+ const compatibilityError = toCliGovernanceUnsupportedError(error, fallbackPath);
197
+ if (compatibilityError) {
198
+ throw compatibilityError;
199
+ }
200
+ throw error;
201
+ }
202
+ function normalizePath(path6) {
203
+ let normalized = path6.split("?")[0] || "/";
204
+ if (!normalized.startsWith("/")) {
205
+ normalized = `/${normalized}`;
206
+ }
207
+ normalized = normalized.replace(/\/+/g, "/");
208
+ if (!normalized.startsWith("/api/")) {
209
+ normalized = `/api${normalized}`;
210
+ }
211
+ return normalized.replace(/\/+$/g, "") || "/api";
212
+ }
213
+ function getNumber(value, path6) {
214
+ const result = getValue(value, path6);
215
+ return typeof result === "number" ? result : void 0;
216
+ }
217
+ function getString(value, path6) {
218
+ const result = getValue(value, path6);
219
+ return typeof result === "string" ? result : void 0;
220
+ }
221
+ function getValue(value, path6) {
222
+ let current = value;
223
+ for (const key of path6) {
224
+ if (!current || typeof current !== "object" || !(key in current)) {
225
+ return void 0;
226
+ }
227
+ current = current[key];
228
+ }
229
+ return current;
230
+ }
231
+
172
232
  // src/core/capabilities.ts
173
233
  function capabilityForRequest(method, path6) {
174
234
  const normalizedMethod = method.toUpperCase();
175
- const normalizedPath = normalizePath(path6);
235
+ const normalizedPath = normalizePath2(path6);
176
236
  if (normalizedPath === "/cli/capabilities") {
177
237
  return void 0;
178
238
  }
@@ -199,12 +259,20 @@ function capabilityForRequest(method, path6) {
199
259
  return "api.raw";
200
260
  }
201
261
  async function refreshCapabilities(client, profile, now = /* @__PURE__ */ new Date()) {
202
- const response = await client.request({
203
- method: "GET",
204
- url: "/api/cli/capabilities"
205
- });
262
+ let response;
263
+ try {
264
+ response = await client.request({
265
+ method: "GET",
266
+ url: "/api/cli/capabilities"
267
+ });
268
+ } catch (error) {
269
+ throwCliGovernanceUnsupportedIfNeeded(error, "/api/cli/capabilities");
270
+ }
206
271
  const body = response.data;
207
272
  if (typeof body.code === "number" && body.code !== 0) {
273
+ if (body.code === 404) {
274
+ throw new Error(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE);
275
+ }
208
276
  throw new Error(body.msg || `Capabilities probe failed with code ${body.code}`);
209
277
  }
210
278
  const data = body.data ?? body;
@@ -220,12 +288,12 @@ async function refreshCapabilities(client, profile, now = /* @__PURE__ */ new Da
220
288
  await updateProfileCapabilities(profile.name, cache);
221
289
  return cache;
222
290
  }
223
- async function ensureCapability(client, profile, capabilityName) {
291
+ async function ensureCapability(client, profile, capabilityName, options = {}) {
224
292
  if (!capabilityName) {
225
293
  return;
226
294
  }
227
295
  let cache = profile.config.capabilities_cache;
228
- if (!capabilityEnabled(cache, capabilityName)) {
296
+ if (options.forceRefresh || !capabilityEnabled(cache, capabilityName)) {
229
297
  cache = await refreshCapabilities(client, profile);
230
298
  profile.config.capabilities_cache = cache;
231
299
  }
@@ -251,7 +319,7 @@ async function updateProfileCapabilities(profileName, cache) {
251
319
  };
252
320
  await saveConfig(config);
253
321
  }
254
- function normalizePath(path6) {
322
+ function normalizePath2(path6) {
255
323
  let normalized = path6.split("?")[0] || "/";
256
324
  if (!normalized.startsWith("/")) {
257
325
  normalized = `/${normalized}`;
@@ -266,8 +334,257 @@ function normalizePath(path6) {
266
334
  return normalized;
267
335
  }
268
336
 
337
+ // package.json
338
+ var package_default = {
339
+ name: "bpmax-cli",
340
+ version: "0.1.43",
341
+ description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
342
+ type: "module",
343
+ bin: {
344
+ "bpmax-cli": "dist/bin.js"
345
+ },
346
+ files: [
347
+ "dist",
348
+ "scripts/install-skills.mjs",
349
+ "skills",
350
+ "README.md"
351
+ ],
352
+ scripts: {
353
+ postinstall: "node scripts/install-skills.mjs",
354
+ build: "tsup",
355
+ dev: "tsx src/bin.ts",
356
+ "install:skills": "node scripts/install-skills.mjs",
357
+ test: "vitest run",
358
+ typecheck: "tsc --noEmit"
359
+ },
360
+ engines: {
361
+ node: ">=18"
362
+ },
363
+ dependencies: {
364
+ "@clack/prompts": "^1.2.0",
365
+ axios: "^1.9.0",
366
+ commander: "^14.0.0",
367
+ jszip: "^3.10.1",
368
+ open: "^10.1.2"
369
+ },
370
+ devDependencies: {
371
+ "@types/node": "^22.15.17",
372
+ tsup: "^8.5.0",
373
+ tsx: "^4.19.4",
374
+ typescript: "^5.8.3",
375
+ vitest: "^3.1.3"
376
+ }
377
+ };
378
+
379
+ // src/core/build.ts
380
+ var CLI_NAME = "bpmax-cli";
381
+ var VERSION = package_default.version;
382
+ var NPM_PACKAGE = "bpmax-cli";
383
+
384
+ // src/core/terminal.ts
385
+ import { randomUUID } from "crypto";
386
+ import os from "os";
387
+ function isCliControlPath(path6) {
388
+ const normalized = normalizeApiPath(path6);
389
+ return normalized === "/api/cli/capabilities" || normalized === "/api/cli/terminals/register" || normalized === "/api/cli/audit/start" || normalized === "/api/cli/audit/finish";
390
+ }
391
+ function commandSummary(argv = process.argv) {
392
+ const args = argv.slice(2);
393
+ const safeArgs = [];
394
+ const redactValueFlags = /* @__PURE__ */ new Set([
395
+ "--authorization",
396
+ "--api-key",
397
+ "--api_key",
398
+ "--body",
399
+ "--data",
400
+ "--device-code",
401
+ "--json",
402
+ "--key",
403
+ "--mobile",
404
+ "--password",
405
+ "--phone",
406
+ "--secret",
407
+ "--session",
408
+ "--token",
409
+ "--\u9A8C\u8BC1\u7801",
410
+ "--\u624B\u673A\u53F7"
411
+ ]);
412
+ for (let index = 0; index < args.length; index += 1) {
413
+ const arg = args[index];
414
+ if (arg === "--format") {
415
+ index += 1;
416
+ continue;
417
+ }
418
+ if (arg.startsWith("--format=")) {
419
+ continue;
420
+ }
421
+ const equalIndex = arg.indexOf("=");
422
+ if (equalIndex > 0) {
423
+ const key = arg.slice(0, equalIndex);
424
+ if (redactValueFlags.has(key)) {
425
+ safeArgs.push(`${key}=[REDACTED]`);
426
+ } else {
427
+ safeArgs.push(redactInlineSecrets(arg));
428
+ }
429
+ continue;
430
+ }
431
+ if (redactValueFlags.has(arg)) {
432
+ safeArgs.push(arg, "[REDACTED]");
433
+ if (index + 1 < args.length) {
434
+ index += 1;
435
+ }
436
+ continue;
437
+ }
438
+ safeArgs.push(redactInlineSecrets(arg));
439
+ }
440
+ return safeArgs.join(" ").slice(0, 300) || "bpmax-cli";
441
+ }
442
+ function commandHeaderSummary(argv = process.argv) {
443
+ const summary = commandSummary(argv);
444
+ if (/^[\x20-\x7E]*$/.test(summary)) {
445
+ return summary;
446
+ }
447
+ return `base64url:${Buffer.from(summary, "utf8").toString("base64url")}`.slice(0, 300);
448
+ }
449
+ var sensitiveObjectKeyPattern = /^(authorization|api[-_]?key|token|password|secret|phone|mobile|session|device[-_]?code|验证码|手机号)$/i;
450
+ function redactAuditValue(value, depth = 0) {
451
+ if (depth > 6) {
452
+ return "[MAX_DEPTH]";
453
+ }
454
+ if (Array.isArray(value)) {
455
+ return value.slice(0, 20).map((item) => redactAuditValue(item, depth + 1));
456
+ }
457
+ if (value && typeof value === "object") {
458
+ return Object.entries(value).reduce((acc, [key, item]) => {
459
+ acc[key] = sensitiveObjectKeyPattern.test(key) ? "[REDACTED]" : redactAuditValue(item, depth + 1);
460
+ return acc;
461
+ }, {});
462
+ }
463
+ if (typeof value === "string") {
464
+ return redactInlineSecrets(value).slice(0, 500);
465
+ }
466
+ return value;
467
+ }
468
+ function redactInlineSecrets(value) {
469
+ return value.replace(/(sk-|npm_)[A-Za-z0-9_-]{8,}/g, "$1[REDACTED]").replace(/\b1[3-9]\d{9}\b/g, "[REDACTED_PHONE]").replace(/("(?:password|token|secret|authorization|api[-_]?key|phone|mobile|手机号|验证码)"\s*:\s*")([^"]*)(")/gi, "$1[REDACTED]$3");
470
+ }
471
+ function requestId() {
472
+ return randomUUID();
473
+ }
474
+ async function ensureTerminalRegistered(client, profile) {
475
+ if (!profile.config.api_key) {
476
+ return;
477
+ }
478
+ if (profile.config.terminal_id && profile.config.terminal_status === "disabled") {
479
+ throw new Error("CLI terminal is disabled.");
480
+ }
481
+ if (profile.config.terminal_id && profile.config.terminal_status !== "disabled") {
482
+ return;
483
+ }
484
+ const terminalId = profile.config.terminal_id || randomUUID();
485
+ let response;
486
+ try {
487
+ response = await client.request({
488
+ method: "POST",
489
+ url: "/api/cli/terminals/register",
490
+ data: {
491
+ terminal_id: terminalId,
492
+ name: `${os.hostname()} ${profile.name}`,
493
+ workspace: profile.config.workspace,
494
+ cli_version: VERSION
495
+ }
496
+ });
497
+ } catch (error) {
498
+ throwCliGovernanceUnsupportedIfNeeded(error, "/api/cli/terminals/register");
499
+ }
500
+ const body = response.data;
501
+ if (typeof body.code === "number" && body.code !== 0) {
502
+ if (body.code === 404) {
503
+ throw new Error(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE);
504
+ }
505
+ throw new Error(body.msg || `CLI terminal registration failed with code ${body.code}`);
506
+ }
507
+ const data = body.data || {};
508
+ if (data.status === "disabled") {
509
+ await updateProfileTerminal(profile, data.terminal_id || terminalId, "disabled");
510
+ throw new Error("CLI terminal is disabled.");
511
+ }
512
+ await updateProfileTerminal(profile, data.terminal_id || terminalId, data.status || "enabled");
513
+ }
514
+ async function clearProfileTerminal(profile) {
515
+ const config = await loadConfig();
516
+ const stored = config.profiles[profile.name];
517
+ if (!stored) {
518
+ return;
519
+ }
520
+ const { terminal_id: _terminalId, terminal_status: _terminalStatus, terminal_registered_at: _registeredAt, ...rest } = stored;
521
+ config.profiles[profile.name] = rest;
522
+ await saveConfig(config);
523
+ delete profile.config.terminal_id;
524
+ delete profile.config.terminal_status;
525
+ delete profile.config.terminal_registered_at;
526
+ }
527
+ function isTerminalNotRegisteredError(error) {
528
+ const message = errorMessage(error).toLowerCase();
529
+ return message.includes("cli terminal is not registered") || message.includes("terminal is not registered") || message.includes("disabled or not registered");
530
+ }
531
+ function isTerminalDisabledError(error) {
532
+ const message = errorMessage(error).toLowerCase();
533
+ return message.includes("cli terminal is disabled") && !message.includes("disabled or not registered");
534
+ }
535
+ async function updateProfileTerminal(profile, terminalId, status) {
536
+ const config = await loadConfig();
537
+ const stored = config.profiles[profile.name];
538
+ if (!stored) {
539
+ return;
540
+ }
541
+ config.profiles[profile.name] = {
542
+ ...stored,
543
+ terminal_id: terminalId,
544
+ terminal_status: status,
545
+ terminal_registered_at: (/* @__PURE__ */ new Date()).toISOString()
546
+ };
547
+ await saveConfig(config);
548
+ profile.config.terminal_id = terminalId;
549
+ profile.config.terminal_status = status;
550
+ profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
551
+ }
552
+ function normalizeApiPath(path6) {
553
+ let normalized = path6.split("?")[0] || "/";
554
+ if (!normalized.startsWith("/")) {
555
+ normalized = `/${normalized}`;
556
+ }
557
+ normalized = normalized.replace(/\/+/g, "/");
558
+ if (!normalized.startsWith("/api/")) {
559
+ normalized = `/api${normalized}`;
560
+ }
561
+ return normalized.replace(/\/+$/g, "") || "/api";
562
+ }
563
+ function errorMessage(error) {
564
+ if (error instanceof Error) {
565
+ return error.message;
566
+ }
567
+ return String(error);
568
+ }
569
+
269
570
  // src/core/http.ts
270
571
  var clientProfiles = /* @__PURE__ */ new WeakMap();
572
+ var commandAuditScope;
573
+ function beginCommandAuditScope() {
574
+ commandAuditScope = { states: /* @__PURE__ */ new Set() };
575
+ }
576
+ async function finishCommandAuditScope(status = "success", error) {
577
+ const scope = commandAuditScope;
578
+ commandAuditScope = void 0;
579
+ if (!scope) {
580
+ return;
581
+ }
582
+ await Promise.all(
583
+ Array.from(scope.states).map(
584
+ (state) => finishCommandAuditState(state, status, error)
585
+ )
586
+ );
587
+ }
271
588
  var ensureApiPath = (path6) => {
272
589
  if (!path6.startsWith("/")) {
273
590
  path6 = `/${path6}`;
@@ -300,6 +617,11 @@ function createApiClient(profile) {
300
617
  if (profile.config.api_key) {
301
618
  const headers = AxiosHeaders.from(config.headers || {});
302
619
  headers.set("Authorization", `Bearer ${profile.config.api_key}`);
620
+ if (profile.config.terminal_id) {
621
+ headers.set("X-BPMAX-CLI-Terminal-Id", profile.config.terminal_id);
622
+ }
623
+ headers.set("X-BPMAX-CLI-Version", VERSION);
624
+ headers.set("X-BPMAX-CLI-Command", commandHeaderSummary());
303
625
  config.headers = headers;
304
626
  }
305
627
  return config;
@@ -308,24 +630,254 @@ function createApiClient(profile) {
308
630
  }
309
631
  async function apiRequest(client, method, path6, options = {}) {
310
632
  const profile = clientProfiles.get(client);
633
+ const apiPath2 = ensureApiPath(path6);
634
+ const capability = options.capability ?? capabilityForRequest(method, path6);
635
+ const shouldControl = profile && !isCliControlPath(apiPath2);
636
+ const reqId = requestId();
311
637
  if (profile) {
312
- await ensureCapability(client, profile, options.capability ?? capabilityForRequest(method, path6));
638
+ if (shouldControl) {
639
+ return runControlledApiRequest(client, profile, method, apiPath2, capability, reqId, options);
640
+ }
641
+ await ensureCapability(client, profile, capability, { forceRefresh: false });
642
+ }
643
+ return sendBusinessRequest(client, profile, method, apiPath2, capability, reqId, options);
644
+ }
645
+ async function runControlledApiRequest(client, profile, method, apiPath2, capability, reqId, options) {
646
+ return runWithTerminalRecovery(
647
+ client,
648
+ profile,
649
+ () => commandAuditScope ? runCommandAuditedRequest(client, profile, method, apiPath2, capability, reqId, options) : runRequestAuditedRequest(client, profile, method, apiPath2, capability, reqId, options)
650
+ );
651
+ }
652
+ async function runCommandAuditedRequest(client, profile, method, apiPath2, capability, reqId, options) {
653
+ await ensureTerminalRegistered(client, profile);
654
+ const state = await ensureCommandAuditState(client, profile, method, apiPath2, capability, options);
655
+ try {
656
+ await ensureCapability(client, profile, capability, { forceRefresh: true });
657
+ const result = await sendBusinessRequest(client, profile, method, apiPath2, capability, reqId, options);
658
+ state.requests.push({
659
+ method: method.toUpperCase(),
660
+ path: apiPath2,
661
+ capability,
662
+ status: "success"
663
+ });
664
+ return result;
665
+ } catch (error) {
666
+ if (!isTerminalNotRegisteredError(error)) {
667
+ state.requests.push({
668
+ method: method.toUpperCase(),
669
+ path: apiPath2,
670
+ capability,
671
+ status: "failed",
672
+ error_summary: error instanceof Error ? error.message : String(error)
673
+ });
674
+ }
675
+ throw error;
676
+ }
677
+ }
678
+ async function runRequestAuditedRequest(client, profile, method, apiPath2, capability, reqId, options) {
679
+ await ensureTerminalRegistered(client, profile);
680
+ const auditId = await startAudit(client, profile, {
681
+ command: commandSummary(),
682
+ capability,
683
+ workspace: String(options.params?.$workspace ?? profile.config.workspace ?? ""),
684
+ request_id: reqId,
685
+ args_summary: {
686
+ method: method.toUpperCase(),
687
+ path: apiPath2,
688
+ params: redactAuditValue(options.params),
689
+ data: redactAuditValue(options.data)
690
+ }
691
+ });
692
+ const startedAt = Date.now();
693
+ let auditFinished = false;
694
+ try {
695
+ await ensureCapability(client, profile, capability, { forceRefresh: true });
696
+ const result = await sendBusinessRequest(client, profile, method, apiPath2, capability, reqId, options);
697
+ if (auditId !== void 0) {
698
+ await finishAuditSafely(client, profile, {
699
+ id: auditId,
700
+ status: "success",
701
+ duration_ms: Date.now() - startedAt,
702
+ result_summary: { ok: true }
703
+ });
704
+ auditFinished = true;
705
+ }
706
+ return result;
707
+ } catch (error) {
708
+ if (auditId !== void 0 && !auditFinished && !isTerminalNotRegisteredError(error)) {
709
+ await finishAuditSafely(client, profile, {
710
+ id: auditId,
711
+ status: "failed",
712
+ duration_ms: Date.now() - startedAt,
713
+ error_summary: error instanceof Error ? error.message : String(error)
714
+ });
715
+ }
716
+ throw error;
717
+ }
718
+ }
719
+ async function sendBusinessRequest(client, profile, method, apiPath2, capability, reqId, options) {
720
+ const headers = AxiosHeaders.from();
721
+ if (profile?.config.terminal_id) {
722
+ headers.set("X-BPMAX-CLI-Terminal-Id", profile.config.terminal_id);
313
723
  }
724
+ headers.set("X-BPMAX-CLI-Version", VERSION);
725
+ headers.set("X-BPMAX-CLI-Command", commandHeaderSummary());
726
+ if (capability) {
727
+ headers.set("X-BPMAX-CLI-Capability", capability);
728
+ }
729
+ headers.set("X-Request-Id", reqId);
314
730
  const response = await client.request({
315
731
  method,
316
- url: ensureApiPath(path6),
732
+ url: apiPath2,
317
733
  params: options.params,
318
- data: options.data
734
+ data: options.data,
735
+ headers
319
736
  });
320
737
  const body = response.data;
321
738
  if (body.code !== 0) {
322
- if (options.preserveErrorBody) {
323
- throw new Error(JSON.stringify(body));
324
- }
325
- throw new Error(body.msg || `Request failed with code ${body.code}`);
739
+ const error = options.preserveErrorBody ? new Error(JSON.stringify(body)) : new Error(body.msg || `Request failed with code ${body.code}`);
740
+ throw error;
326
741
  }
327
742
  return body.data ?? body;
328
743
  }
744
+ async function startAudit(client, profile, data) {
745
+ let response;
746
+ try {
747
+ response = await client.request({
748
+ method: "POST",
749
+ url: "/api/cli/audit/start",
750
+ data: {
751
+ terminal_id: profile.config.terminal_id,
752
+ ...data
753
+ }
754
+ });
755
+ } catch (error) {
756
+ throwCliGovernanceUnsupportedIfNeeded(error, "/api/cli/audit/start");
757
+ }
758
+ const body = response.data;
759
+ if (typeof body.code === "number" && body.code !== 0) {
760
+ if (body.code === 404) {
761
+ throw new Error(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE);
762
+ }
763
+ throw new Error(body.msg || `CLI audit start failed with code ${body.code}`);
764
+ }
765
+ return body.data?.id ?? body.data?.audit_id;
766
+ }
767
+ async function ensureCommandAuditState(client, profile, method, apiPath2, capability, options) {
768
+ const scope = commandAuditScope;
769
+ if (!scope) {
770
+ throw new Error("Command audit scope is not active.");
771
+ }
772
+ const profileKey = commandAuditProfileKey(profile);
773
+ const existing = Array.from(scope.states).find((state2) => state2.profile_key === profileKey);
774
+ if (existing) {
775
+ if (!existing.capability && capability) {
776
+ existing.capability = capability;
777
+ }
778
+ return existing;
779
+ }
780
+ const state = {
781
+ client,
782
+ profile,
783
+ profile_key: profileKey,
784
+ request_id: requestId(),
785
+ started_at: Date.now(),
786
+ command: commandSummary(),
787
+ workspace: String(options.params?.$workspace ?? profile.config.workspace ?? ""),
788
+ capability,
789
+ requests: []
790
+ };
791
+ state.audit_id = await startAudit(client, profile, {
792
+ command: state.command,
793
+ capability,
794
+ workspace: state.workspace,
795
+ request_id: state.request_id,
796
+ args_summary: {
797
+ method: method.toUpperCase(),
798
+ path: apiPath2,
799
+ params: redactAuditValue(options.params),
800
+ data: redactAuditValue(options.data),
801
+ audit_mode: "command"
802
+ }
803
+ });
804
+ scope.states.add(state);
805
+ return state;
806
+ }
807
+ async function finishCommandAuditState(state, status, error) {
808
+ if (state.audit_id === void 0) {
809
+ return;
810
+ }
811
+ const failedRequest = state.requests.find((request) => request.status === "failed");
812
+ const finalStatus = status === "failed" || failedRequest ? "failed" : "success";
813
+ await finishAuditSafely(state.client, state.profile, {
814
+ id: state.audit_id,
815
+ status: finalStatus,
816
+ duration_ms: Date.now() - state.started_at,
817
+ ...finalStatus === "failed" ? {
818
+ error_summary: error instanceof Error ? error.message : failedRequest?.error_summary || (error ? String(error) : "Command failed")
819
+ } : {
820
+ result_summary: {
821
+ ok: true,
822
+ request_count: state.requests.length,
823
+ requests: state.requests.slice(0, 30).map((request) => ({
824
+ method: request.method,
825
+ path: request.path,
826
+ capability: request.capability,
827
+ status: request.status
828
+ }))
829
+ }
830
+ }
831
+ });
832
+ }
833
+ async function finishAuditSafely(client, profile, data) {
834
+ try {
835
+ await client.request({
836
+ method: "POST",
837
+ url: "/api/cli/audit/finish",
838
+ data: {
839
+ terminal_id: profile.config.terminal_id,
840
+ ...data
841
+ }
842
+ });
843
+ } catch {
844
+ }
845
+ }
846
+ async function runWithTerminalRecovery(client, profile, operation) {
847
+ try {
848
+ return await operation();
849
+ } catch (error) {
850
+ if (!shouldRetryTerminalRegistration(profile, error)) {
851
+ throw error;
852
+ }
853
+ clearCommandAuditStateForProfile(profile);
854
+ await clearProfileTerminal(profile);
855
+ return operation();
856
+ }
857
+ }
858
+ function clearCommandAuditStateForProfile(profile) {
859
+ if (!commandAuditScope) {
860
+ return;
861
+ }
862
+ const profileKey = commandAuditProfileKey(profile);
863
+ for (const state of Array.from(commandAuditScope.states)) {
864
+ if (state.profile_key === profileKey) {
865
+ commandAuditScope.states.delete(state);
866
+ }
867
+ }
868
+ }
869
+ function commandAuditProfileKey(profile) {
870
+ return [profile.name, profile.config.origin, profile.config.workspace, profile.config.api_key || ""].join("\n");
871
+ }
872
+ function shouldRetryTerminalRegistration(profile, error) {
873
+ if (!profile.config.terminal_id || profile.config.terminal_status === "disabled") {
874
+ return false;
875
+ }
876
+ if (isTerminalDisabledError(error)) {
877
+ return false;
878
+ }
879
+ return isTerminalNotRegisteredError(error);
880
+ }
329
881
 
330
882
  // src/core/json-input.ts
331
883
  import { readFile as readFile2 } from "fs/promises";
@@ -432,7 +984,7 @@ async function parseJsonAny(input, label = "JSON input") {
432
984
  function isMutatingMethod(method) {
433
985
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
434
986
  }
435
- function normalizeApiPath(path6) {
987
+ function normalizeApiPath2(path6) {
436
988
  let normalized = path6.trim();
437
989
  const queryIndex = normalized.indexOf("?");
438
990
  if (queryIndex >= 0) {
@@ -454,7 +1006,7 @@ function assertRawApiPathAllowed(method, path6) {
454
1006
  if (!isMutatingMethod(method)) {
455
1007
  return;
456
1008
  }
457
- const normalizedPath = normalizeApiPath(path6);
1009
+ const normalizedPath = normalizeApiPath2(path6);
458
1010
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
459
1011
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
460
1012
  if (!isProjectPath || isAllowedProjectReadPost) {
@@ -838,7 +1390,9 @@ function registerAuthCommands(program2, deps = {}) {
838
1390
  if (shouldProbeCapabilities) {
839
1391
  try {
840
1392
  const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
841
- const cache = await refreshCapabilities(createApiClient(authenticatedProfile), authenticatedProfile);
1393
+ const client = createApiClient(authenticatedProfile);
1394
+ await ensureTerminalRegistered(client, authenticatedProfile);
1395
+ const cache = await refreshCapabilities(client, authenticatedProfile);
842
1396
  capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
843
1397
  } catch (error) {
844
1398
  capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
@@ -894,7 +1448,9 @@ function registerAuthCommands(program2, deps = {}) {
894
1448
  if (shouldProbeCapabilities) {
895
1449
  try {
896
1450
  const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
897
- const cache = await refreshCapabilities(createApiClient(authenticatedProfile), authenticatedProfile);
1451
+ const client = createApiClient(authenticatedProfile);
1452
+ await ensureTerminalRegistered(client, authenticatedProfile);
1453
+ const cache = await refreshCapabilities(client, authenticatedProfile);
898
1454
  capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
899
1455
  } catch (error) {
900
1456
  capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
@@ -953,53 +1509,6 @@ function registerAuthCommands(program2, deps = {}) {
953
1509
  import { basename } from "path";
954
1510
  import { readFile as readFile5 } from "fs/promises";
955
1511
 
956
- // package.json
957
- var package_default = {
958
- name: "bpmax-cli",
959
- version: "0.1.42",
960
- description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
961
- type: "module",
962
- bin: {
963
- "bpmax-cli": "dist/bin.js"
964
- },
965
- files: [
966
- "dist",
967
- "scripts/install-skills.mjs",
968
- "skills",
969
- "README.md"
970
- ],
971
- scripts: {
972
- postinstall: "node scripts/install-skills.mjs",
973
- build: "tsup",
974
- dev: "tsx src/bin.ts",
975
- "install:skills": "node scripts/install-skills.mjs",
976
- test: "vitest run",
977
- typecheck: "tsc --noEmit"
978
- },
979
- engines: {
980
- node: ">=18"
981
- },
982
- dependencies: {
983
- "@clack/prompts": "^1.2.0",
984
- axios: "^1.9.0",
985
- commander: "^14.0.0",
986
- jszip: "^3.10.1",
987
- open: "^10.1.2"
988
- },
989
- devDependencies: {
990
- "@types/node": "^22.15.17",
991
- tsup: "^8.5.0",
992
- tsx: "^4.19.4",
993
- typescript: "^5.8.3",
994
- vitest: "^3.1.3"
995
- }
996
- };
997
-
998
- // src/core/build.ts
999
- var CLI_NAME = "bpmax-cli";
1000
- var VERSION = package_default.version;
1001
- var NPM_PACKAGE = "bpmax-cli";
1002
-
1003
1512
  // src/core/urls.ts
1004
1513
  function stripSlashes(value) {
1005
1514
  return value.trim().replace(/^\/+|\/+$/g, "");
@@ -5146,6 +5655,10 @@ program.name(CLI_NAME).description("BPMAX multi-environment CLI").version(VERSIO
5146
5655
  program.hook("preAction", (thisCommand) => {
5147
5656
  const options = thisCommand.optsWithGlobals();
5148
5657
  setConfigDir(options.configDir);
5658
+ beginCommandAuditScope();
5659
+ });
5660
+ program.hook("postAction", async () => {
5661
+ await finishCommandAuditScope("success");
5149
5662
  });
5150
5663
  registerConfigCommands(program);
5151
5664
  registerCapabilitiesCommands(program);
@@ -5166,7 +5679,9 @@ registerUpdateCommands(program);
5166
5679
  var isCompletion = process.argv.includes("completion") || process.argv.includes("__complete");
5167
5680
  setConfigDir(configDirFromArgv(process.argv));
5168
5681
  (isCompletion ? Promise.resolve() : setupNotices()).then(() => program.parseAsync(process.argv)).catch((error) => {
5169
- console.error(error instanceof Error ? error.message : String(error));
5170
- process.exitCode = 1;
5682
+ finishCommandAuditScope("failed", error).catch(() => void 0).finally(() => {
5683
+ console.error(error instanceof Error ? error.message : String(error));
5684
+ process.exitCode = 1;
5685
+ });
5171
5686
  });
5172
5687
  //# sourceMappingURL=bin.js.map