bpmax-cli 0.1.12 → 0.1.13

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
@@ -270,7 +270,18 @@ function registerApiCommands(program2) {
270
270
  // src/core/auth.ts
271
271
  import { createServer } from "http";
272
272
  import { randomBytes } from "crypto";
273
+ import axios2 from "axios";
273
274
  import open from "open";
275
+ var DeviceAuthorizationError = class extends Error {
276
+ code;
277
+ interval;
278
+ constructor(code, message, interval) {
279
+ super(message || code);
280
+ this.name = "DeviceAuthorizationError";
281
+ this.code = code;
282
+ this.interval = interval;
283
+ }
284
+ };
274
285
  function buildBridgeUrl(origin, workspace, params) {
275
286
  const query = new URLSearchParams(params);
276
287
  return `${origin}/${encodeURIComponent(workspace)}/cli-login?${query.toString()}`;
@@ -349,6 +360,134 @@ async function runBrowserLogin(options) {
349
360
  }, timeoutMs);
350
361
  });
351
362
  }
363
+ function apiPath(path5) {
364
+ if (path5.startsWith("/api/")) {
365
+ return path5;
366
+ }
367
+ return `/api${path5.startsWith("/") ? path5 : `/${path5}`}`;
368
+ }
369
+ function createDeviceRequest(origin) {
370
+ const client = axios2.create({ baseURL: origin, withCredentials: false });
371
+ return async (method, path5, options) => {
372
+ const response = await client.request({
373
+ method,
374
+ url: apiPath(path5),
375
+ data: options.data
376
+ });
377
+ const body = response.data;
378
+ if (typeof body.code === "number" && body.code !== 0) {
379
+ throw new Error(body.msg || `Request failed with code ${body.code}`);
380
+ }
381
+ return body.data ?? body;
382
+ };
383
+ }
384
+ function stringField(value, name) {
385
+ if (typeof value !== "string" || !value.trim()) {
386
+ throw new Error(`Device authorization response missing ${name}.`);
387
+ }
388
+ return value;
389
+ }
390
+ function numberField(value, name, fallback) {
391
+ if (typeof value === "number" && Number.isFinite(value)) {
392
+ return value;
393
+ }
394
+ if (fallback !== void 0) {
395
+ return fallback;
396
+ }
397
+ throw new Error(`Device authorization response missing ${name}.`);
398
+ }
399
+ async function startDeviceLogin(options) {
400
+ const agent = options.agent || "generic";
401
+ const channel = options.channel || "json";
402
+ const request = options.request || createDeviceRequest(options.origin);
403
+ const response = await request("POST", "/cli/device_authorizations", {
404
+ data: {
405
+ workspace: options.workspace,
406
+ profile: options.profileName,
407
+ key_name: options.apiKeyName,
408
+ agent,
409
+ channel,
410
+ origin: options.origin
411
+ }
412
+ });
413
+ const expiresIn = numberField(response.expires_in, "expires_in");
414
+ const now = options.now?.() || /* @__PURE__ */ new Date();
415
+ const verificationUri = stringField(response.verification_uri, "verification_uri");
416
+ const verificationUriComplete = typeof response.verification_uri_complete === "string" && response.verification_uri_complete.trim() ? response.verification_uri_complete : void 0;
417
+ return {
418
+ profile: options.profileName,
419
+ agent,
420
+ channel,
421
+ device_code: stringField(response.device_code, "device_code"),
422
+ user_code: stringField(response.user_code, "user_code"),
423
+ verification_uri: verificationUri,
424
+ verification_uri_complete: verificationUriComplete,
425
+ authorization_url: verificationUriComplete || verificationUri,
426
+ expires_in: expiresIn,
427
+ interval: numberField(response.interval, "interval", 5),
428
+ expires_at: new Date(now.getTime() + expiresIn * 1e3).toISOString()
429
+ };
430
+ }
431
+ async function completeDeviceLogin(options) {
432
+ const request = options.request || createDeviceRequest(options.origin || "");
433
+ const response = await request("POST", "/cli/device_token", {
434
+ data: { device_code: options.deviceCode }
435
+ });
436
+ if (typeof response.error === "string" && response.error) {
437
+ throw new DeviceAuthorizationError(
438
+ response.error,
439
+ typeof response.error_description === "string" ? response.error_description : response.error,
440
+ typeof response.interval === "number" ? response.interval : void 0
441
+ );
442
+ }
443
+ const apiKey = response.api_key;
444
+ if (typeof apiKey !== "string" || !apiKey) {
445
+ throw new Error("Device token response missing api_key.");
446
+ }
447
+ return {
448
+ apiKey,
449
+ user: response.user
450
+ };
451
+ }
452
+ async function pollDeviceLogin(options) {
453
+ const startedAt = Date.now();
454
+ let interval = Math.max(1, options.interval) * 1e3;
455
+ const sleep = options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
456
+ while (Date.now() - startedAt < options.expiresIn * 1e3) {
457
+ try {
458
+ return await completeDeviceLogin({
459
+ origin: options.origin,
460
+ deviceCode: options.deviceCode,
461
+ request: options.request
462
+ });
463
+ } catch (error) {
464
+ if (!(error instanceof DeviceAuthorizationError)) {
465
+ throw error;
466
+ }
467
+ if (error.code !== "authorization_pending" && error.code !== "slow_down") {
468
+ throw error;
469
+ }
470
+ if (error.code === "slow_down") {
471
+ interval += 5e3;
472
+ }
473
+ if (error.interval) {
474
+ interval = Math.max(1, error.interval) * 1e3;
475
+ }
476
+ await sleep(interval);
477
+ }
478
+ }
479
+ throw new DeviceAuthorizationError("expired_token", "Device authorization expired.");
480
+ }
481
+ function buildAuthorizationMessageCard(input) {
482
+ return {
483
+ title: "Authorize BPMAX CLI",
484
+ summary: `Open the authorization link and confirm code ${input.user_code} for profile "${input.profile}".`,
485
+ authorization_url: input.authorization_url,
486
+ user_code: input.user_code,
487
+ expires_at: input.expires_at,
488
+ next_action: "Open the authorization URL, confirm the code, then run device completion."
489
+ };
490
+ }
352
491
  function updateProfileAuth(profile, result) {
353
492
  return {
354
493
  ...profile,
@@ -358,23 +497,103 @@ function updateProfileAuth(profile, result) {
358
497
  }
359
498
 
360
499
  // src/commands/auth.ts
361
- function registerAuthCommands(program2) {
500
+ function deviceStartBody(result) {
501
+ return {
502
+ ok: true,
503
+ ...result,
504
+ session: result.device_code,
505
+ message_card: buildAuthorizationMessageCard(result)
506
+ };
507
+ }
508
+ function registerAuthCommands(program2, deps = {}) {
509
+ const load = deps.loadConfig || loadConfig;
510
+ const save = deps.saveConfig || saveConfig;
511
+ const browserLogin = deps.browserLogin || runBrowserLogin;
512
+ const startDevice = deps.startDeviceLogin || startDeviceLogin;
513
+ const completeDevice = deps.completeDeviceLogin || completeDeviceLogin;
362
514
  const auth = program2.command("auth").description("Authenticate and manage API key state");
363
- auth.command("login").description("Open the hpt-frontend bridge page and persist the returned API key").option("--profile <profile>", "Profile name").option("--key-name <keyName>", "Target API key name", "bpmax-cli").action(async (options) => {
364
- const config = await loadConfig();
515
+ auth.command("login").description("Authorize and persist the returned API key").option("--profile <profile>", "Profile name").option("--key-name <keyName>", "Target API key name", "bpmax-cli").option("--mode <mode>", "Login mode: browser | device", "browser").option("--agent <agent>", "Agent adapter for device mode", "generic").option("--channel <channel>", "Interaction channel for device mode", "terminal").option("--format <format>", "Output format", "pretty").action(async (options) => {
516
+ const config = await load();
517
+ const profile = resolveProfile(config, options.profile);
518
+ let result;
519
+ let authorization;
520
+ if (options.mode === "device") {
521
+ authorization = await startDevice({
522
+ origin: profile.config.origin,
523
+ workspace: profile.config.workspace,
524
+ profileName: profile.name,
525
+ apiKeyName: options.keyName,
526
+ agent: options.agent,
527
+ channel: options.channel
528
+ });
529
+ if (options.format !== "json") {
530
+ console.log(`Open ${authorization.authorization_url}`);
531
+ console.log(`Confirm code: ${authorization.user_code}`);
532
+ }
533
+ result = await pollDeviceLogin({
534
+ origin: profile.config.origin,
535
+ deviceCode: authorization.device_code,
536
+ interval: authorization.interval,
537
+ expiresIn: authorization.expires_in
538
+ });
539
+ } else {
540
+ result = await browserLogin({
541
+ origin: profile.config.origin,
542
+ workspace: profile.config.workspace,
543
+ profileName: profile.name,
544
+ apiKeyName: options.keyName
545
+ });
546
+ }
547
+ config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
548
+ await save(config);
549
+ if (options.format === "json") {
550
+ printResult("json", {
551
+ ok: true,
552
+ profile: profile.name,
553
+ login: "authenticated",
554
+ user: result.user,
555
+ ...authorization ? { authorization, message_card: buildAuthorizationMessageCard(authorization) } : {}
556
+ });
557
+ } else {
558
+ console.log(`Saved API key for profile "${profile.name}".`);
559
+ }
560
+ });
561
+ const device = auth.command("device").description("Device authorization for browserless agent environments");
562
+ device.command("start").description("Start BPMAX device authorization and print a code/link for the user").option("--profile <profile>", "Profile name").option("--key-name <keyName>", "Target API key name", "bpmax-cli").option("--agent <agent>", "Agent adapter name", "generic").option("--channel <channel>", "Interaction channel", "json").option("--format <format>", "Output format", "pretty").action(async (options) => {
563
+ const config = await load();
365
564
  const profile = resolveProfile(config, options.profile);
366
- const result = await runBrowserLogin({
565
+ const result = await startDevice({
367
566
  origin: profile.config.origin,
368
567
  workspace: profile.config.workspace,
369
568
  profileName: profile.name,
370
- apiKeyName: options.keyName
569
+ apiKeyName: options.keyName,
570
+ agent: options.agent,
571
+ channel: options.channel
572
+ });
573
+ printResult(options.format, deviceStartBody(result));
574
+ });
575
+ device.command("complete").description("Complete BPMAX device authorization after the user confirms the code").option("--profile <profile>", "Profile name").option("--device-code <deviceCode>", "Device code returned by auth device start").option("--session <session>", "Alias for --device-code").option("--format <format>", "Output format", "pretty").action(async (options) => {
576
+ const deviceCode = options.deviceCode || options.session;
577
+ if (!deviceCode) {
578
+ throw new Error("--device-code or --session is required.");
579
+ }
580
+ const config = await load();
581
+ const profile = resolveProfile(config, options.profile);
582
+ const result = await completeDevice({
583
+ origin: profile.config.origin,
584
+ deviceCode
371
585
  });
372
586
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
373
- await saveConfig(config);
374
- console.log(`Saved API key for profile "${profile.name}".`);
587
+ await save(config);
588
+ printResult(options.format, {
589
+ ok: true,
590
+ profile: profile.name,
591
+ login: "authenticated",
592
+ user: result.user
593
+ });
375
594
  });
376
595
  auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
377
- const config = await loadConfig();
596
+ const config = await load();
378
597
  const profile = resolveProfile(config, options.profile);
379
598
  const output = {
380
599
  profile: profile.name,
@@ -402,14 +621,14 @@ function registerAuthCommands(program2) {
402
621
  printResult(options.format, output);
403
622
  });
404
623
  auth.command("logout").description("Clear the stored API key for the selected profile").option("--profile <profile>", "Profile name").action(async (options) => {
405
- const config = await loadConfig();
624
+ const config = await load();
406
625
  const profile = resolveProfile(config, options.profile);
407
626
  config.profiles[profile.name] = {
408
627
  ...config.profiles[profile.name],
409
628
  api_key: "",
410
629
  user: void 0
411
630
  };
412
- await saveConfig(config);
631
+ await save(config);
413
632
  console.log(`Cleared API key for profile "${profile.name}".`);
414
633
  });
415
634
  }
@@ -545,6 +764,296 @@ function registerFlowCommands(program2) {
545
764
  });
546
765
  }
547
766
 
767
+ // package.json
768
+ var package_default = {
769
+ name: "bpmax-cli",
770
+ version: "0.1.13",
771
+ description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
772
+ type: "module",
773
+ bin: {
774
+ "bpmax-cli": "dist/bin.js"
775
+ },
776
+ files: [
777
+ "dist",
778
+ "scripts/install-skills.mjs",
779
+ "skills",
780
+ "README.md"
781
+ ],
782
+ scripts: {
783
+ postinstall: "node scripts/install-skills.mjs",
784
+ build: "tsup",
785
+ dev: "tsx src/bin.ts",
786
+ "install:skills": "node scripts/install-skills.mjs",
787
+ test: "vitest run",
788
+ typecheck: "tsc --noEmit"
789
+ },
790
+ engines: {
791
+ node: ">=18"
792
+ },
793
+ dependencies: {
794
+ "@clack/prompts": "^1.2.0",
795
+ axios: "^1.9.0",
796
+ commander: "^14.0.0",
797
+ open: "^10.1.2"
798
+ },
799
+ devDependencies: {
800
+ "@types/node": "^22.15.17",
801
+ tsup: "^8.5.0",
802
+ tsx: "^4.19.4",
803
+ typescript: "^5.8.3",
804
+ vitest: "^3.1.3"
805
+ }
806
+ };
807
+
808
+ // src/core/build.ts
809
+ var CLI_NAME = "bpmax-cli";
810
+ var VERSION = package_default.version;
811
+ var NPM_PACKAGE = "bpmax-cli";
812
+
813
+ // src/core/setup.ts
814
+ function parseBpmUrl(input) {
815
+ const trimmed = input.trim();
816
+ if (!trimmed) {
817
+ throw new Error("BPMAX URL is required.");
818
+ }
819
+ let url;
820
+ try {
821
+ url = new URL(trimmed);
822
+ } catch {
823
+ throw new Error(`Invalid BPMAX URL: ${input}`);
824
+ }
825
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
826
+ throw new Error(`BPMAX URL must start with http:// or https://: ${input}`);
827
+ }
828
+ const workspace = url.pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment))[0];
829
+ if (!workspace) {
830
+ throw new Error(`BPMAX URL must include a workspace path, for example ${url.origin}/w:store_mgr`);
831
+ }
832
+ return {
833
+ origin: url.origin,
834
+ workspace
835
+ };
836
+ }
837
+ function configuredProfiles(config) {
838
+ return Object.entries(config.profiles).filter(([, profile]) => Boolean(profile.origin?.trim())).map(([name, profile]) => ({
839
+ name,
840
+ current: config.current_profile === name,
841
+ origin: profile.origin,
842
+ workspace: profile.workspace || DEFAULT_WORKSPACE,
843
+ language: profile.language || DEFAULT_LANGUAGE,
844
+ authenticated: Boolean(profile.api_key)
845
+ }));
846
+ }
847
+ function defaultSetupProfileName(config) {
848
+ if (configuredProfiles(config).length > 0) {
849
+ let index2 = 2;
850
+ while (config.profiles[`local-${index2}`]) {
851
+ index2 += 1;
852
+ }
853
+ return `local-${index2}`;
854
+ }
855
+ const defaultProfile = config.profiles.default;
856
+ if (!defaultProfile || !defaultProfile.origin?.trim()) {
857
+ return "default";
858
+ }
859
+ let index = 2;
860
+ while (config.profiles[`local-${index}`]) {
861
+ index += 1;
862
+ }
863
+ return `local-${index}`;
864
+ }
865
+ function applySetupProfile(config, name, profile) {
866
+ return {
867
+ ...config,
868
+ current_profile: name,
869
+ profiles: {
870
+ ...config.profiles,
871
+ [name]: {
872
+ ...config.profiles[name],
873
+ ...profile
874
+ }
875
+ }
876
+ };
877
+ }
878
+ function setupSummary(input) {
879
+ return {
880
+ profile: input.profile,
881
+ origin: input.origin,
882
+ workspace: input.workspace,
883
+ login: input.login,
884
+ ...input.user ? { user: input.user } : {},
885
+ ...input.login === "skipped" ? { next: `Run \`bpmax-cli auth login --profile ${input.profile}\` to authorize this profile.` } : {}
886
+ };
887
+ }
888
+
889
+ // src/core/skills.ts
890
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
891
+ import path2 from "path";
892
+ import { fileURLToPath } from "url";
893
+
894
+ // src/core/process.ts
895
+ import { spawn } from "child_process";
896
+ var runCommand = (command, args, options = {}) => new Promise((resolve) => {
897
+ const child = spawn(command, args, {
898
+ cwd: options.cwd,
899
+ env: options.env,
900
+ stdio: ["ignore", "pipe", "pipe"]
901
+ });
902
+ let stdout = "";
903
+ let stderr = "";
904
+ let settled = false;
905
+ const timer = options.timeoutMs && options.timeoutMs > 0 ? setTimeout(() => {
906
+ if (settled) {
907
+ return;
908
+ }
909
+ settled = true;
910
+ child.kill("SIGTERM");
911
+ resolve({
912
+ stdout,
913
+ stderr: `${stderr}${stderr ? "\n" : ""}Timed out after ${options.timeoutMs}ms`,
914
+ exitCode: 124
915
+ });
916
+ }, options.timeoutMs) : void 0;
917
+ child.stdout?.on("data", (chunk) => {
918
+ stdout += String(chunk);
919
+ });
920
+ child.stderr?.on("data", (chunk) => {
921
+ stderr += String(chunk);
922
+ });
923
+ child.on("error", (error) => {
924
+ if (settled) {
925
+ return;
926
+ }
927
+ settled = true;
928
+ if (timer) {
929
+ clearTimeout(timer);
930
+ }
931
+ resolve({ stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}`, exitCode: 1 });
932
+ });
933
+ child.on("close", (code) => {
934
+ if (settled) {
935
+ return;
936
+ }
937
+ settled = true;
938
+ if (timer) {
939
+ clearTimeout(timer);
940
+ }
941
+ resolve({ stdout, stderr, exitCode: code ?? 1 });
942
+ });
943
+ });
944
+
945
+ // src/core/skills.ts
946
+ var SKILLS_STAMP_FILE = "skills.stamp";
947
+ var SKILLS_INSTALL_TIMEOUT_MS = 2 * 60 * 1e3;
948
+ function skillsStampValue(version, agent) {
949
+ return agent ? `${version}:${agent}` : version;
950
+ }
951
+ function stampPath(configDir = getConfigDir()) {
952
+ return path2.join(configDir, SKILLS_STAMP_FILE);
953
+ }
954
+ async function readSkillsStamp(configDir = getConfigDir()) {
955
+ try {
956
+ return (await readFile2(stampPath(configDir), "utf8")).trim();
957
+ } catch {
958
+ return "";
959
+ }
960
+ }
961
+ async function writeSkillsStamp(version, configDir = getConfigDir(), agent) {
962
+ await mkdir2(configDir, { recursive: true });
963
+ await writeFile2(stampPath(configDir), skillsStampValue(version, agent), "utf8");
964
+ }
965
+ async function checkSkillsSync(currentVersion, configDir = getConfigDir(), agent) {
966
+ const target = skillsStampValue(currentVersion, agent);
967
+ if (process.env.BPMAX_CLI_NO_SKILLS_NOTIFIER) {
968
+ return { current: target, target, inSync: true };
969
+ }
970
+ const current = await readSkillsStamp(configDir);
971
+ return { current, target, inSync: current === target };
972
+ }
973
+ function defaultPackageRoot() {
974
+ return path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "..", "..");
975
+ }
976
+ async function runSkillsInstall(options = {}) {
977
+ const runner = options.runner || runCommand;
978
+ const args = [path2.join(options.packageRoot || defaultPackageRoot(), "scripts", "install-skills.mjs")];
979
+ if (options.agent) {
980
+ args.push("--json", "--agent", options.agent);
981
+ }
982
+ return runner(process.execPath, args, {
983
+ timeoutMs: SKILLS_INSTALL_TIMEOUT_MS
984
+ });
985
+ }
986
+ async function syncSkills(version, options = {}) {
987
+ if (!options.force) {
988
+ const status = await checkSkillsSync(version, options.configDir, options.agent);
989
+ if (status.inSync) {
990
+ return { action: "in_sync" };
991
+ }
992
+ }
993
+ const result = await runSkillsInstall({ packageRoot: options.packageRoot, runner: options.runner, agent: options.agent });
994
+ if (result.exitCode === 0) {
995
+ await writeSkillsStamp(version, options.configDir, options.agent);
996
+ return { action: "synced", result };
997
+ }
998
+ return { action: "failed", result };
999
+ }
1000
+
1001
+ // src/commands/init.ts
1002
+ function parseSkillsDetail(stdout) {
1003
+ if (!stdout?.trim()) {
1004
+ return void 0;
1005
+ }
1006
+ try {
1007
+ return JSON.parse(stdout);
1008
+ } catch {
1009
+ return void 0;
1010
+ }
1011
+ }
1012
+ function registerInitCommand(program2, deps = {}) {
1013
+ const loadConfig2 = deps.loadConfig || loadConfig;
1014
+ const saveConfig2 = deps.saveConfig || saveConfig;
1015
+ const syncSkills2 = deps.syncSkills || syncSkills;
1016
+ const startDeviceLogin2 = deps.startDeviceLogin || startDeviceLogin;
1017
+ program2.command("init").description("Initialize bpmax-cli for browserless agent environments").requiredOption("--url <url>", "Full BPMAX workspace URL, for example https://example.com/w:store_mgr").option("--name <name>", "Profile name", "default").option("--agent <agent>", "Agent adapter: openclaw | aily | codex | claude | gemini | generic", "generic").option("--channel <channel>", "Interaction channel: feishu | terminal | json", "json").option("--key-name <keyName>", "Target API key name", "bpmax-cli").option("--language <language>", "Default language", DEFAULT_LANGUAGE).option("--force-skills", "Force skills reinstall").option("--format <format>", "Output format", "pretty").action(async (options) => {
1018
+ const parsed = parseBpmUrl(options.url);
1019
+ const profileName = options.name || "default";
1020
+ const config = await loadConfig2();
1021
+ const nextConfig = applySetupProfile(config, profileName, {
1022
+ origin: parsed.origin,
1023
+ workspace: parsed.workspace,
1024
+ language: options.language || DEFAULT_LANGUAGE
1025
+ });
1026
+ await saveConfig2(nextConfig);
1027
+ const skills = await syncSkills2(VERSION, {
1028
+ force: Boolean(options.forceSkills),
1029
+ agent: options.agent
1030
+ });
1031
+ const authorization = await startDeviceLogin2({
1032
+ origin: parsed.origin,
1033
+ workspace: parsed.workspace,
1034
+ profileName,
1035
+ apiKeyName: options.keyName,
1036
+ agent: options.agent,
1037
+ channel: options.channel
1038
+ });
1039
+ printResult(options.format, {
1040
+ ok: true,
1041
+ profile: profileName,
1042
+ origin: parsed.origin,
1043
+ workspace: parsed.workspace,
1044
+ agent: options.agent,
1045
+ channel: options.channel,
1046
+ skills: {
1047
+ action: skills.action,
1048
+ detail: parseSkillsDetail(skills.result?.stdout),
1049
+ ...skills.action === "failed" ? { error: skills.result?.stderr || skills.result?.stdout } : {}
1050
+ },
1051
+ authorization,
1052
+ message_card: buildAuthorizationMessageCard(authorization)
1053
+ });
1054
+ });
1055
+ }
1056
+
548
1057
  // src/core/form-schema.ts
549
1058
  var FIELD_KEY_NAMES = [
550
1059
  "key",
@@ -971,12 +1480,12 @@ function registerProjectCommands(program2) {
971
1480
  }
972
1481
 
973
1482
  // src/commands/recipe.ts
974
- import { spawn } from "child_process";
975
- import { fileURLToPath } from "url";
1483
+ import { spawn as spawn2 } from "child_process";
1484
+ import { fileURLToPath as fileURLToPath2 } from "url";
976
1485
 
977
1486
  // src/core/recipes.ts
978
- import { access, mkdir as mkdir2, readdir, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
979
- import path2 from "path";
1487
+ import { access, mkdir as mkdir3, readdir, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
1488
+ import path3 from "path";
980
1489
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
981
1490
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
982
1491
  function assertSafeName(kind, value) {
@@ -1000,12 +1509,12 @@ function resolveRecipeLocation(options) {
1000
1509
  workspace,
1001
1510
  workspaceDirName,
1002
1511
  recipeName: options.recipeName,
1003
- recipeDir: path2.join(profileDir, "recipes", workspaceDirName, options.recipeName)
1512
+ recipeDir: path3.join(profileDir, "recipes", workspaceDirName, options.recipeName)
1004
1513
  };
1005
1514
  }
1006
1515
  function getRecipesDir(options) {
1007
1516
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
1008
- return path2.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
1517
+ return path3.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
1009
1518
  }
1010
1519
  function isRecord4(value) {
1011
1520
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1057,7 +1566,7 @@ function parseRecipeDefinition(input) {
1057
1566
  };
1058
1567
  }
1059
1568
  async function loadRecipe(recipeDir) {
1060
- const raw = await readFile2(path2.join(recipeDir, "recipe.json"), "utf8");
1569
+ const raw = await readFile3(path3.join(recipeDir, "recipe.json"), "utf8");
1061
1570
  return parseRecipeDefinition(JSON.parse(raw));
1062
1571
  }
1063
1572
  async function listRecipes(recipesDir) {
@@ -1075,7 +1584,7 @@ async function listRecipes(recipesDir) {
1075
1584
  if (!RECIPE_NAME_PATTERN.test(entry)) {
1076
1585
  continue;
1077
1586
  }
1078
- const recipeDir = path2.join(recipesDir, entry);
1587
+ const recipeDir = path3.join(recipesDir, entry);
1079
1588
  try {
1080
1589
  const recipe = await loadRecipe(recipeDir);
1081
1590
  summaries.push({
@@ -1141,12 +1650,12 @@ function renderTemplate(template, variables) {
1141
1650
  }
1142
1651
  function resolveRecipeFile(recipeDir, token) {
1143
1652
  const relative = token.slice(1);
1144
- if (!relative || relative.includes("..") || path2.isAbsolute(relative)) {
1653
+ if (!relative || relative.includes("..") || path3.isAbsolute(relative)) {
1145
1654
  throw new Error(`Unsafe recipe file reference: ${token}`);
1146
1655
  }
1147
- const resolved = path2.resolve(recipeDir, relative);
1148
- const root = path2.resolve(recipeDir);
1149
- if (resolved !== root && !resolved.startsWith(`${root}${path2.sep}`)) {
1656
+ const resolved = path3.resolve(recipeDir, relative);
1657
+ const root = path3.resolve(recipeDir);
1658
+ if (resolved !== root && !resolved.startsWith(`${root}${path3.sep}`)) {
1150
1659
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
1151
1660
  }
1152
1661
  return resolved;
@@ -1156,7 +1665,7 @@ async function renderArgv(options) {
1156
1665
  const rendered = [];
1157
1666
  for (const token of options.recipe.command.argv) {
1158
1667
  if (token.startsWith("@")) {
1159
- const raw = await readFile2(resolveRecipeFile(options.recipeDir, token), "utf8");
1668
+ const raw = await readFile3(resolveRecipeFile(options.recipeDir, token), "utf8");
1160
1669
  rendered.push(renderTemplate(raw, options.variables));
1161
1670
  } else {
1162
1671
  rendered.push(renderTemplate(token, options.variables));
@@ -1182,7 +1691,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
1182
1691
  }
1183
1692
  async function writeRecipeScaffold(options) {
1184
1693
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
1185
- await mkdir2(options.location.recipeDir, { recursive: true });
1694
+ await mkdir3(options.location.recipeDir, { recursive: true });
1186
1695
  const title = options.title || options.location.recipeName;
1187
1696
  const recipe = {
1188
1697
  version: 1,
@@ -1196,16 +1705,16 @@ async function writeRecipeScaffold(options) {
1196
1705
  mutating: true
1197
1706
  }
1198
1707
  };
1199
- await writeFile2(path2.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
1708
+ await writeFile3(path3.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
1200
1709
  `, "utf8");
1201
- await writeFile2(
1202
- path2.join(options.location.recipeDir, "payload.json"),
1710
+ await writeFile3(
1711
+ path3.join(options.location.recipeDir, "payload.json"),
1203
1712
  `${JSON.stringify({ name: "{{name}}" }, null, 2)}
1204
1713
  `,
1205
1714
  "utf8"
1206
1715
  );
1207
- await writeFile2(
1208
- path2.join(options.location.recipeDir, "README.md"),
1716
+ await writeFile3(
1717
+ path3.join(options.location.recipeDir, "README.md"),
1209
1718
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
1210
1719
  "utf8"
1211
1720
  );
@@ -1213,7 +1722,7 @@ async function writeRecipeScaffold(options) {
1213
1722
 
1214
1723
  // src/commands/recipe.ts
1215
1724
  function currentCliInvocation() {
1216
- const entry = process.argv[1] || fileURLToPath(import.meta.url);
1725
+ const entry = process.argv[1] || fileURLToPath2(import.meta.url);
1217
1726
  return {
1218
1727
  command: process.execPath,
1219
1728
  argsPrefix: [entry]
@@ -1222,7 +1731,7 @@ function currentCliInvocation() {
1222
1731
  function defaultRunRecipe(argv) {
1223
1732
  const invocation = currentCliInvocation();
1224
1733
  return new Promise((resolve, reject) => {
1225
- const child = spawn(invocation.command, [...invocation.argsPrefix, ...argv], {
1734
+ const child = spawn2(invocation.command, [...invocation.argsPrefix, ...argv], {
1226
1735
  stdio: "inherit",
1227
1736
  shell: false
1228
1737
  });
@@ -1362,84 +1871,6 @@ function registerSchemaCommands(program2) {
1362
1871
 
1363
1872
  // src/commands/setup.ts
1364
1873
  import { confirm, text as text2 } from "@clack/prompts";
1365
-
1366
- // src/core/setup.ts
1367
- function parseBpmUrl(input) {
1368
- const trimmed = input.trim();
1369
- if (!trimmed) {
1370
- throw new Error("BPMAX URL is required.");
1371
- }
1372
- let url;
1373
- try {
1374
- url = new URL(trimmed);
1375
- } catch {
1376
- throw new Error(`Invalid BPMAX URL: ${input}`);
1377
- }
1378
- if (url.protocol !== "http:" && url.protocol !== "https:") {
1379
- throw new Error(`BPMAX URL must start with http:// or https://: ${input}`);
1380
- }
1381
- const workspace = url.pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment))[0];
1382
- if (!workspace) {
1383
- throw new Error(`BPMAX URL must include a workspace path, for example ${url.origin}/w:store_mgr`);
1384
- }
1385
- return {
1386
- origin: url.origin,
1387
- workspace
1388
- };
1389
- }
1390
- function configuredProfiles(config) {
1391
- return Object.entries(config.profiles).filter(([, profile]) => Boolean(profile.origin?.trim())).map(([name, profile]) => ({
1392
- name,
1393
- current: config.current_profile === name,
1394
- origin: profile.origin,
1395
- workspace: profile.workspace || DEFAULT_WORKSPACE,
1396
- language: profile.language || DEFAULT_LANGUAGE,
1397
- authenticated: Boolean(profile.api_key)
1398
- }));
1399
- }
1400
- function defaultSetupProfileName(config) {
1401
- if (configuredProfiles(config).length > 0) {
1402
- let index2 = 2;
1403
- while (config.profiles[`local-${index2}`]) {
1404
- index2 += 1;
1405
- }
1406
- return `local-${index2}`;
1407
- }
1408
- const defaultProfile = config.profiles.default;
1409
- if (!defaultProfile || !defaultProfile.origin?.trim()) {
1410
- return "default";
1411
- }
1412
- let index = 2;
1413
- while (config.profiles[`local-${index}`]) {
1414
- index += 1;
1415
- }
1416
- return `local-${index}`;
1417
- }
1418
- function applySetupProfile(config, name, profile) {
1419
- return {
1420
- ...config,
1421
- current_profile: name,
1422
- profiles: {
1423
- ...config.profiles,
1424
- [name]: {
1425
- ...config.profiles[name],
1426
- ...profile
1427
- }
1428
- }
1429
- };
1430
- }
1431
- function setupSummary(input) {
1432
- return {
1433
- profile: input.profile,
1434
- origin: input.origin,
1435
- workspace: input.workspace,
1436
- login: input.login,
1437
- ...input.user ? { user: input.user } : {},
1438
- ...input.login === "skipped" ? { next: `Run \`bpmax-cli auth login --profile ${input.profile}\` to authorize this profile.` } : {}
1439
- };
1440
- }
1441
-
1442
- // src/commands/setup.ts
1443
1874
  async function promptText(current, message, placeholder) {
1444
1875
  if (current?.trim()) {
1445
1876
  return current.trim();
@@ -1535,156 +1966,6 @@ function registerStepCommands(program2) {
1535
1966
  });
1536
1967
  }
1537
1968
 
1538
- // package.json
1539
- var package_default = {
1540
- name: "bpmax-cli",
1541
- version: "0.1.12",
1542
- description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
1543
- type: "module",
1544
- bin: {
1545
- "bpmax-cli": "dist/bin.js"
1546
- },
1547
- files: [
1548
- "dist",
1549
- "scripts/install-skills.mjs",
1550
- "skills",
1551
- "README.md"
1552
- ],
1553
- scripts: {
1554
- postinstall: "node scripts/install-skills.mjs",
1555
- build: "tsup",
1556
- dev: "tsx src/bin.ts",
1557
- "install:skills": "node scripts/install-skills.mjs",
1558
- test: "vitest run",
1559
- typecheck: "tsc --noEmit"
1560
- },
1561
- engines: {
1562
- node: ">=18"
1563
- },
1564
- dependencies: {
1565
- "@clack/prompts": "^1.2.0",
1566
- axios: "^1.9.0",
1567
- commander: "^14.0.0",
1568
- open: "^10.1.2"
1569
- },
1570
- devDependencies: {
1571
- "@types/node": "^22.15.17",
1572
- tsup: "^8.5.0",
1573
- tsx: "^4.19.4",
1574
- typescript: "^5.8.3",
1575
- vitest: "^3.1.3"
1576
- }
1577
- };
1578
-
1579
- // src/core/build.ts
1580
- var CLI_NAME = "bpmax-cli";
1581
- var VERSION = package_default.version;
1582
- var NPM_PACKAGE = "bpmax-cli";
1583
-
1584
- // src/core/skills.ts
1585
- import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
1586
- import path3 from "path";
1587
- import { fileURLToPath as fileURLToPath2 } from "url";
1588
-
1589
- // src/core/process.ts
1590
- import { spawn as spawn2 } from "child_process";
1591
- var runCommand = (command, args, options = {}) => new Promise((resolve) => {
1592
- const child = spawn2(command, args, {
1593
- cwd: options.cwd,
1594
- env: options.env,
1595
- stdio: ["ignore", "pipe", "pipe"]
1596
- });
1597
- let stdout = "";
1598
- let stderr = "";
1599
- let settled = false;
1600
- const timer = options.timeoutMs && options.timeoutMs > 0 ? setTimeout(() => {
1601
- if (settled) {
1602
- return;
1603
- }
1604
- settled = true;
1605
- child.kill("SIGTERM");
1606
- resolve({
1607
- stdout,
1608
- stderr: `${stderr}${stderr ? "\n" : ""}Timed out after ${options.timeoutMs}ms`,
1609
- exitCode: 124
1610
- });
1611
- }, options.timeoutMs) : void 0;
1612
- child.stdout?.on("data", (chunk) => {
1613
- stdout += String(chunk);
1614
- });
1615
- child.stderr?.on("data", (chunk) => {
1616
- stderr += String(chunk);
1617
- });
1618
- child.on("error", (error) => {
1619
- if (settled) {
1620
- return;
1621
- }
1622
- settled = true;
1623
- if (timer) {
1624
- clearTimeout(timer);
1625
- }
1626
- resolve({ stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}`, exitCode: 1 });
1627
- });
1628
- child.on("close", (code) => {
1629
- if (settled) {
1630
- return;
1631
- }
1632
- settled = true;
1633
- if (timer) {
1634
- clearTimeout(timer);
1635
- }
1636
- resolve({ stdout, stderr, exitCode: code ?? 1 });
1637
- });
1638
- });
1639
-
1640
- // src/core/skills.ts
1641
- var SKILLS_STAMP_FILE = "skills.stamp";
1642
- var SKILLS_INSTALL_TIMEOUT_MS = 2 * 60 * 1e3;
1643
- function stampPath(configDir = getConfigDir()) {
1644
- return path3.join(configDir, SKILLS_STAMP_FILE);
1645
- }
1646
- async function readSkillsStamp(configDir = getConfigDir()) {
1647
- try {
1648
- return (await readFile3(stampPath(configDir), "utf8")).trim();
1649
- } catch {
1650
- return "";
1651
- }
1652
- }
1653
- async function writeSkillsStamp(version, configDir = getConfigDir()) {
1654
- await mkdir3(configDir, { recursive: true });
1655
- await writeFile3(stampPath(configDir), version, "utf8");
1656
- }
1657
- async function checkSkillsSync(currentVersion, configDir = getConfigDir()) {
1658
- if (process.env.BPMAX_CLI_NO_SKILLS_NOTIFIER) {
1659
- return { current: currentVersion, target: currentVersion, inSync: true };
1660
- }
1661
- const current = await readSkillsStamp(configDir);
1662
- return { current, target: currentVersion, inSync: current === currentVersion };
1663
- }
1664
- function defaultPackageRoot() {
1665
- return path3.resolve(path3.dirname(fileURLToPath2(import.meta.url)), "..", "..");
1666
- }
1667
- async function runSkillsInstall(options = {}) {
1668
- const runner = options.runner || runCommand;
1669
- return runner(process.execPath, [path3.join(options.packageRoot || defaultPackageRoot(), "scripts", "install-skills.mjs")], {
1670
- timeoutMs: SKILLS_INSTALL_TIMEOUT_MS
1671
- });
1672
- }
1673
- async function syncSkills(version, options = {}) {
1674
- if (!options.force) {
1675
- const status = await checkSkillsSync(version, options.configDir);
1676
- if (status.inSync) {
1677
- return { action: "in_sync" };
1678
- }
1679
- }
1680
- const result = await runSkillsInstall({ packageRoot: options.packageRoot, runner: options.runner });
1681
- if (result.exitCode === 0) {
1682
- await writeSkillsStamp(version, options.configDir);
1683
- return { action: "synced", result };
1684
- }
1685
- return { action: "failed", result };
1686
- }
1687
-
1688
1969
  // src/core/update.ts
1689
1970
  import { access as access2, mkdir as mkdir4, readFile as readFile4, realpath, writeFile as writeFile4 } from "fs/promises";
1690
1971
  import path4 from "path";
@@ -2185,6 +2466,7 @@ registerStepCommands(program);
2185
2466
  registerRecipeCommands(program);
2186
2467
  registerUrlCommands(program);
2187
2468
  registerSetupCommand(program);
2469
+ registerInitCommand(program);
2188
2470
  registerUpdateCommands(program);
2189
2471
  var isCompletion = process.argv.includes("completion") || process.argv.includes("__complete");
2190
2472
  (isCompletion ? Promise.resolve() : setupNotices()).then(() => program.parseAsync(process.argv)).catch((error) => {