bpmax-cli 0.1.12 → 0.1.14

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,135 @@ 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 next_command.",
489
+ next_command: `bpmax-cli auth device complete --profile ${input.profile} --session ${input.device_code} --format json`
490
+ };
491
+ }
352
492
  function updateProfileAuth(profile, result) {
353
493
  return {
354
494
  ...profile,
@@ -358,23 +498,103 @@ function updateProfileAuth(profile, result) {
358
498
  }
359
499
 
360
500
  // src/commands/auth.ts
361
- function registerAuthCommands(program2) {
501
+ function deviceStartBody(result) {
502
+ return {
503
+ ok: true,
504
+ ...result,
505
+ session: result.device_code,
506
+ message_card: buildAuthorizationMessageCard(result)
507
+ };
508
+ }
509
+ function registerAuthCommands(program2, deps = {}) {
510
+ const load = deps.loadConfig || loadConfig;
511
+ const save = deps.saveConfig || saveConfig;
512
+ const browserLogin = deps.browserLogin || runBrowserLogin;
513
+ const startDevice = deps.startDeviceLogin || startDeviceLogin;
514
+ const completeDevice = deps.completeDeviceLogin || completeDeviceLogin;
362
515
  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();
516
+ 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) => {
517
+ const config = await load();
518
+ const profile = resolveProfile(config, options.profile);
519
+ let result;
520
+ let authorization;
521
+ if (options.mode === "device") {
522
+ authorization = await startDevice({
523
+ origin: profile.config.origin,
524
+ workspace: profile.config.workspace,
525
+ profileName: profile.name,
526
+ apiKeyName: options.keyName,
527
+ agent: options.agent,
528
+ channel: options.channel
529
+ });
530
+ if (options.format !== "json") {
531
+ console.log(`Open ${authorization.authorization_url}`);
532
+ console.log(`Confirm code: ${authorization.user_code}`);
533
+ }
534
+ result = await pollDeviceLogin({
535
+ origin: profile.config.origin,
536
+ deviceCode: authorization.device_code,
537
+ interval: authorization.interval,
538
+ expiresIn: authorization.expires_in
539
+ });
540
+ } else {
541
+ result = await browserLogin({
542
+ origin: profile.config.origin,
543
+ workspace: profile.config.workspace,
544
+ profileName: profile.name,
545
+ apiKeyName: options.keyName
546
+ });
547
+ }
548
+ config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
549
+ await save(config);
550
+ if (options.format === "json") {
551
+ printResult("json", {
552
+ ok: true,
553
+ profile: profile.name,
554
+ login: "authenticated",
555
+ user: result.user,
556
+ ...authorization ? { authorization, message_card: buildAuthorizationMessageCard(authorization) } : {}
557
+ });
558
+ } else {
559
+ console.log(`Saved API key for profile "${profile.name}".`);
560
+ }
561
+ });
562
+ const device = auth.command("device").description("Device authorization for browserless agent environments");
563
+ 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) => {
564
+ const config = await load();
365
565
  const profile = resolveProfile(config, options.profile);
366
- const result = await runBrowserLogin({
566
+ const result = await startDevice({
367
567
  origin: profile.config.origin,
368
568
  workspace: profile.config.workspace,
369
569
  profileName: profile.name,
370
- apiKeyName: options.keyName
570
+ apiKeyName: options.keyName,
571
+ agent: options.agent,
572
+ channel: options.channel
573
+ });
574
+ printResult(options.format, deviceStartBody(result));
575
+ });
576
+ 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) => {
577
+ const deviceCode = options.deviceCode || options.session;
578
+ if (!deviceCode) {
579
+ throw new Error("--device-code or --session is required.");
580
+ }
581
+ const config = await load();
582
+ const profile = resolveProfile(config, options.profile);
583
+ const result = await completeDevice({
584
+ origin: profile.config.origin,
585
+ deviceCode
371
586
  });
372
587
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
373
- await saveConfig(config);
374
- console.log(`Saved API key for profile "${profile.name}".`);
588
+ await save(config);
589
+ printResult(options.format, {
590
+ ok: true,
591
+ profile: profile.name,
592
+ login: "authenticated",
593
+ user: result.user
594
+ });
375
595
  });
376
596
  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();
597
+ const config = await load();
378
598
  const profile = resolveProfile(config, options.profile);
379
599
  const output = {
380
600
  profile: profile.name,
@@ -402,14 +622,14 @@ function registerAuthCommands(program2) {
402
622
  printResult(options.format, output);
403
623
  });
404
624
  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();
625
+ const config = await load();
406
626
  const profile = resolveProfile(config, options.profile);
407
627
  config.profiles[profile.name] = {
408
628
  ...config.profiles[profile.name],
409
629
  api_key: "",
410
630
  user: void 0
411
631
  };
412
- await saveConfig(config);
632
+ await save(config);
413
633
  console.log(`Cleared API key for profile "${profile.name}".`);
414
634
  });
415
635
  }
@@ -545,6 +765,296 @@ function registerFlowCommands(program2) {
545
765
  });
546
766
  }
547
767
 
768
+ // package.json
769
+ var package_default = {
770
+ name: "bpmax-cli",
771
+ version: "0.1.14",
772
+ description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
773
+ type: "module",
774
+ bin: {
775
+ "bpmax-cli": "dist/bin.js"
776
+ },
777
+ files: [
778
+ "dist",
779
+ "scripts/install-skills.mjs",
780
+ "skills",
781
+ "README.md"
782
+ ],
783
+ scripts: {
784
+ postinstall: "node scripts/install-skills.mjs",
785
+ build: "tsup",
786
+ dev: "tsx src/bin.ts",
787
+ "install:skills": "node scripts/install-skills.mjs",
788
+ test: "vitest run",
789
+ typecheck: "tsc --noEmit"
790
+ },
791
+ engines: {
792
+ node: ">=18"
793
+ },
794
+ dependencies: {
795
+ "@clack/prompts": "^1.2.0",
796
+ axios: "^1.9.0",
797
+ commander: "^14.0.0",
798
+ open: "^10.1.2"
799
+ },
800
+ devDependencies: {
801
+ "@types/node": "^22.15.17",
802
+ tsup: "^8.5.0",
803
+ tsx: "^4.19.4",
804
+ typescript: "^5.8.3",
805
+ vitest: "^3.1.3"
806
+ }
807
+ };
808
+
809
+ // src/core/build.ts
810
+ var CLI_NAME = "bpmax-cli";
811
+ var VERSION = package_default.version;
812
+ var NPM_PACKAGE = "bpmax-cli";
813
+
814
+ // src/core/setup.ts
815
+ function parseBpmUrl(input) {
816
+ const trimmed = input.trim();
817
+ if (!trimmed) {
818
+ throw new Error("BPMAX URL is required.");
819
+ }
820
+ let url;
821
+ try {
822
+ url = new URL(trimmed);
823
+ } catch {
824
+ throw new Error(`Invalid BPMAX URL: ${input}`);
825
+ }
826
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
827
+ throw new Error(`BPMAX URL must start with http:// or https://: ${input}`);
828
+ }
829
+ const workspace = url.pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment))[0];
830
+ if (!workspace) {
831
+ throw new Error(`BPMAX URL must include a workspace path, for example ${url.origin}/w:store_mgr`);
832
+ }
833
+ return {
834
+ origin: url.origin,
835
+ workspace
836
+ };
837
+ }
838
+ function configuredProfiles(config) {
839
+ return Object.entries(config.profiles).filter(([, profile]) => Boolean(profile.origin?.trim())).map(([name, profile]) => ({
840
+ name,
841
+ current: config.current_profile === name,
842
+ origin: profile.origin,
843
+ workspace: profile.workspace || DEFAULT_WORKSPACE,
844
+ language: profile.language || DEFAULT_LANGUAGE,
845
+ authenticated: Boolean(profile.api_key)
846
+ }));
847
+ }
848
+ function defaultSetupProfileName(config) {
849
+ if (configuredProfiles(config).length > 0) {
850
+ let index2 = 2;
851
+ while (config.profiles[`local-${index2}`]) {
852
+ index2 += 1;
853
+ }
854
+ return `local-${index2}`;
855
+ }
856
+ const defaultProfile = config.profiles.default;
857
+ if (!defaultProfile || !defaultProfile.origin?.trim()) {
858
+ return "default";
859
+ }
860
+ let index = 2;
861
+ while (config.profiles[`local-${index}`]) {
862
+ index += 1;
863
+ }
864
+ return `local-${index}`;
865
+ }
866
+ function applySetupProfile(config, name, profile) {
867
+ return {
868
+ ...config,
869
+ current_profile: name,
870
+ profiles: {
871
+ ...config.profiles,
872
+ [name]: {
873
+ ...config.profiles[name],
874
+ ...profile
875
+ }
876
+ }
877
+ };
878
+ }
879
+ function setupSummary(input) {
880
+ return {
881
+ profile: input.profile,
882
+ origin: input.origin,
883
+ workspace: input.workspace,
884
+ login: input.login,
885
+ ...input.user ? { user: input.user } : {},
886
+ ...input.login === "skipped" ? { next: `Run \`bpmax-cli auth login --profile ${input.profile}\` to authorize this profile.` } : {}
887
+ };
888
+ }
889
+
890
+ // src/core/skills.ts
891
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
892
+ import path2 from "path";
893
+ import { fileURLToPath } from "url";
894
+
895
+ // src/core/process.ts
896
+ import { spawn } from "child_process";
897
+ var runCommand = (command, args, options = {}) => new Promise((resolve) => {
898
+ const child = spawn(command, args, {
899
+ cwd: options.cwd,
900
+ env: options.env,
901
+ stdio: ["ignore", "pipe", "pipe"]
902
+ });
903
+ let stdout = "";
904
+ let stderr = "";
905
+ let settled = false;
906
+ const timer = options.timeoutMs && options.timeoutMs > 0 ? setTimeout(() => {
907
+ if (settled) {
908
+ return;
909
+ }
910
+ settled = true;
911
+ child.kill("SIGTERM");
912
+ resolve({
913
+ stdout,
914
+ stderr: `${stderr}${stderr ? "\n" : ""}Timed out after ${options.timeoutMs}ms`,
915
+ exitCode: 124
916
+ });
917
+ }, options.timeoutMs) : void 0;
918
+ child.stdout?.on("data", (chunk) => {
919
+ stdout += String(chunk);
920
+ });
921
+ child.stderr?.on("data", (chunk) => {
922
+ stderr += String(chunk);
923
+ });
924
+ child.on("error", (error) => {
925
+ if (settled) {
926
+ return;
927
+ }
928
+ settled = true;
929
+ if (timer) {
930
+ clearTimeout(timer);
931
+ }
932
+ resolve({ stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}`, exitCode: 1 });
933
+ });
934
+ child.on("close", (code) => {
935
+ if (settled) {
936
+ return;
937
+ }
938
+ settled = true;
939
+ if (timer) {
940
+ clearTimeout(timer);
941
+ }
942
+ resolve({ stdout, stderr, exitCode: code ?? 1 });
943
+ });
944
+ });
945
+
946
+ // src/core/skills.ts
947
+ var SKILLS_STAMP_FILE = "skills.stamp";
948
+ var SKILLS_INSTALL_TIMEOUT_MS = 2 * 60 * 1e3;
949
+ function skillsStampValue(version, agent) {
950
+ return agent ? `${version}:${agent}` : version;
951
+ }
952
+ function stampPath(configDir = getConfigDir()) {
953
+ return path2.join(configDir, SKILLS_STAMP_FILE);
954
+ }
955
+ async function readSkillsStamp(configDir = getConfigDir()) {
956
+ try {
957
+ return (await readFile2(stampPath(configDir), "utf8")).trim();
958
+ } catch {
959
+ return "";
960
+ }
961
+ }
962
+ async function writeSkillsStamp(version, configDir = getConfigDir(), agent) {
963
+ await mkdir2(configDir, { recursive: true });
964
+ await writeFile2(stampPath(configDir), skillsStampValue(version, agent), "utf8");
965
+ }
966
+ async function checkSkillsSync(currentVersion, configDir = getConfigDir(), agent) {
967
+ const target = skillsStampValue(currentVersion, agent);
968
+ if (process.env.BPMAX_CLI_NO_SKILLS_NOTIFIER) {
969
+ return { current: target, target, inSync: true };
970
+ }
971
+ const current = await readSkillsStamp(configDir);
972
+ return { current, target, inSync: current === target };
973
+ }
974
+ function defaultPackageRoot() {
975
+ return path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "..", "..");
976
+ }
977
+ async function runSkillsInstall(options = {}) {
978
+ const runner = options.runner || runCommand;
979
+ const args = [path2.join(options.packageRoot || defaultPackageRoot(), "scripts", "install-skills.mjs")];
980
+ if (options.agent) {
981
+ args.push("--json", "--agent", options.agent);
982
+ }
983
+ return runner(process.execPath, args, {
984
+ timeoutMs: SKILLS_INSTALL_TIMEOUT_MS
985
+ });
986
+ }
987
+ async function syncSkills(version, options = {}) {
988
+ if (!options.force) {
989
+ const status = await checkSkillsSync(version, options.configDir, options.agent);
990
+ if (status.inSync) {
991
+ return { action: "in_sync" };
992
+ }
993
+ }
994
+ const result = await runSkillsInstall({ packageRoot: options.packageRoot, runner: options.runner, agent: options.agent });
995
+ if (result.exitCode === 0) {
996
+ await writeSkillsStamp(version, options.configDir, options.agent);
997
+ return { action: "synced", result };
998
+ }
999
+ return { action: "failed", result };
1000
+ }
1001
+
1002
+ // src/commands/init.ts
1003
+ function parseSkillsDetail(stdout) {
1004
+ if (!stdout?.trim()) {
1005
+ return void 0;
1006
+ }
1007
+ try {
1008
+ return JSON.parse(stdout);
1009
+ } catch {
1010
+ return void 0;
1011
+ }
1012
+ }
1013
+ function registerInitCommand(program2, deps = {}) {
1014
+ const loadConfig2 = deps.loadConfig || loadConfig;
1015
+ const saveConfig2 = deps.saveConfig || saveConfig;
1016
+ const syncSkills2 = deps.syncSkills || syncSkills;
1017
+ const startDeviceLogin2 = deps.startDeviceLogin || startDeviceLogin;
1018
+ 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) => {
1019
+ const parsed = parseBpmUrl(options.url);
1020
+ const profileName = options.name || "default";
1021
+ const config = await loadConfig2();
1022
+ const nextConfig = applySetupProfile(config, profileName, {
1023
+ origin: parsed.origin,
1024
+ workspace: parsed.workspace,
1025
+ language: options.language || DEFAULT_LANGUAGE
1026
+ });
1027
+ await saveConfig2(nextConfig);
1028
+ const skills = await syncSkills2(VERSION, {
1029
+ force: Boolean(options.forceSkills),
1030
+ agent: options.agent
1031
+ });
1032
+ const authorization = await startDeviceLogin2({
1033
+ origin: parsed.origin,
1034
+ workspace: parsed.workspace,
1035
+ profileName,
1036
+ apiKeyName: options.keyName,
1037
+ agent: options.agent,
1038
+ channel: options.channel
1039
+ });
1040
+ printResult(options.format, {
1041
+ ok: true,
1042
+ profile: profileName,
1043
+ origin: parsed.origin,
1044
+ workspace: parsed.workspace,
1045
+ agent: options.agent,
1046
+ channel: options.channel,
1047
+ skills: {
1048
+ action: skills.action,
1049
+ detail: parseSkillsDetail(skills.result?.stdout),
1050
+ ...skills.action === "failed" ? { error: skills.result?.stderr || skills.result?.stdout } : {}
1051
+ },
1052
+ authorization,
1053
+ message_card: buildAuthorizationMessageCard(authorization)
1054
+ });
1055
+ });
1056
+ }
1057
+
548
1058
  // src/core/form-schema.ts
549
1059
  var FIELD_KEY_NAMES = [
550
1060
  "key",
@@ -971,12 +1481,12 @@ function registerProjectCommands(program2) {
971
1481
  }
972
1482
 
973
1483
  // src/commands/recipe.ts
974
- import { spawn } from "child_process";
975
- import { fileURLToPath } from "url";
1484
+ import { spawn as spawn2 } from "child_process";
1485
+ import { fileURLToPath as fileURLToPath2 } from "url";
976
1486
 
977
1487
  // 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";
1488
+ import { access, mkdir as mkdir3, readdir, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
1489
+ import path3 from "path";
980
1490
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
981
1491
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
982
1492
  function assertSafeName(kind, value) {
@@ -1000,12 +1510,12 @@ function resolveRecipeLocation(options) {
1000
1510
  workspace,
1001
1511
  workspaceDirName,
1002
1512
  recipeName: options.recipeName,
1003
- recipeDir: path2.join(profileDir, "recipes", workspaceDirName, options.recipeName)
1513
+ recipeDir: path3.join(profileDir, "recipes", workspaceDirName, options.recipeName)
1004
1514
  };
1005
1515
  }
1006
1516
  function getRecipesDir(options) {
1007
1517
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
1008
- return path2.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
1518
+ return path3.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
1009
1519
  }
1010
1520
  function isRecord4(value) {
1011
1521
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1057,7 +1567,7 @@ function parseRecipeDefinition(input) {
1057
1567
  };
1058
1568
  }
1059
1569
  async function loadRecipe(recipeDir) {
1060
- const raw = await readFile2(path2.join(recipeDir, "recipe.json"), "utf8");
1570
+ const raw = await readFile3(path3.join(recipeDir, "recipe.json"), "utf8");
1061
1571
  return parseRecipeDefinition(JSON.parse(raw));
1062
1572
  }
1063
1573
  async function listRecipes(recipesDir) {
@@ -1075,7 +1585,7 @@ async function listRecipes(recipesDir) {
1075
1585
  if (!RECIPE_NAME_PATTERN.test(entry)) {
1076
1586
  continue;
1077
1587
  }
1078
- const recipeDir = path2.join(recipesDir, entry);
1588
+ const recipeDir = path3.join(recipesDir, entry);
1079
1589
  try {
1080
1590
  const recipe = await loadRecipe(recipeDir);
1081
1591
  summaries.push({
@@ -1141,12 +1651,12 @@ function renderTemplate(template, variables) {
1141
1651
  }
1142
1652
  function resolveRecipeFile(recipeDir, token) {
1143
1653
  const relative = token.slice(1);
1144
- if (!relative || relative.includes("..") || path2.isAbsolute(relative)) {
1654
+ if (!relative || relative.includes("..") || path3.isAbsolute(relative)) {
1145
1655
  throw new Error(`Unsafe recipe file reference: ${token}`);
1146
1656
  }
1147
- const resolved = path2.resolve(recipeDir, relative);
1148
- const root = path2.resolve(recipeDir);
1149
- if (resolved !== root && !resolved.startsWith(`${root}${path2.sep}`)) {
1657
+ const resolved = path3.resolve(recipeDir, relative);
1658
+ const root = path3.resolve(recipeDir);
1659
+ if (resolved !== root && !resolved.startsWith(`${root}${path3.sep}`)) {
1150
1660
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
1151
1661
  }
1152
1662
  return resolved;
@@ -1156,7 +1666,7 @@ async function renderArgv(options) {
1156
1666
  const rendered = [];
1157
1667
  for (const token of options.recipe.command.argv) {
1158
1668
  if (token.startsWith("@")) {
1159
- const raw = await readFile2(resolveRecipeFile(options.recipeDir, token), "utf8");
1669
+ const raw = await readFile3(resolveRecipeFile(options.recipeDir, token), "utf8");
1160
1670
  rendered.push(renderTemplate(raw, options.variables));
1161
1671
  } else {
1162
1672
  rendered.push(renderTemplate(token, options.variables));
@@ -1182,7 +1692,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
1182
1692
  }
1183
1693
  async function writeRecipeScaffold(options) {
1184
1694
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
1185
- await mkdir2(options.location.recipeDir, { recursive: true });
1695
+ await mkdir3(options.location.recipeDir, { recursive: true });
1186
1696
  const title = options.title || options.location.recipeName;
1187
1697
  const recipe = {
1188
1698
  version: 1,
@@ -1196,16 +1706,16 @@ async function writeRecipeScaffold(options) {
1196
1706
  mutating: true
1197
1707
  }
1198
1708
  };
1199
- await writeFile2(path2.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
1709
+ await writeFile3(path3.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
1200
1710
  `, "utf8");
1201
- await writeFile2(
1202
- path2.join(options.location.recipeDir, "payload.json"),
1711
+ await writeFile3(
1712
+ path3.join(options.location.recipeDir, "payload.json"),
1203
1713
  `${JSON.stringify({ name: "{{name}}" }, null, 2)}
1204
1714
  `,
1205
1715
  "utf8"
1206
1716
  );
1207
- await writeFile2(
1208
- path2.join(options.location.recipeDir, "README.md"),
1717
+ await writeFile3(
1718
+ path3.join(options.location.recipeDir, "README.md"),
1209
1719
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
1210
1720
  "utf8"
1211
1721
  );
@@ -1213,7 +1723,7 @@ async function writeRecipeScaffold(options) {
1213
1723
 
1214
1724
  // src/commands/recipe.ts
1215
1725
  function currentCliInvocation() {
1216
- const entry = process.argv[1] || fileURLToPath(import.meta.url);
1726
+ const entry = process.argv[1] || fileURLToPath2(import.meta.url);
1217
1727
  return {
1218
1728
  command: process.execPath,
1219
1729
  argsPrefix: [entry]
@@ -1222,7 +1732,7 @@ function currentCliInvocation() {
1222
1732
  function defaultRunRecipe(argv) {
1223
1733
  const invocation = currentCliInvocation();
1224
1734
  return new Promise((resolve, reject) => {
1225
- const child = spawn(invocation.command, [...invocation.argsPrefix, ...argv], {
1735
+ const child = spawn2(invocation.command, [...invocation.argsPrefix, ...argv], {
1226
1736
  stdio: "inherit",
1227
1737
  shell: false
1228
1738
  });
@@ -1362,84 +1872,6 @@ function registerSchemaCommands(program2) {
1362
1872
 
1363
1873
  // src/commands/setup.ts
1364
1874
  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
1875
  async function promptText(current, message, placeholder) {
1444
1876
  if (current?.trim()) {
1445
1877
  return current.trim();
@@ -1535,156 +1967,6 @@ function registerStepCommands(program2) {
1535
1967
  });
1536
1968
  }
1537
1969
 
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
1970
  // src/core/update.ts
1689
1971
  import { access as access2, mkdir as mkdir4, readFile as readFile4, realpath, writeFile as writeFile4 } from "fs/promises";
1690
1972
  import path4 from "path";
@@ -2185,6 +2467,7 @@ registerStepCommands(program);
2185
2467
  registerRecipeCommands(program);
2186
2468
  registerUrlCommands(program);
2187
2469
  registerSetupCommand(program);
2470
+ registerInitCommand(program);
2188
2471
  registerUpdateCommands(program);
2189
2472
  var isCompletion = process.argv.includes("completion") || process.argv.includes("__complete");
2190
2473
  (isCompletion ? Promise.resolve() : setupNotices()).then(() => program.parseAsync(process.argv)).catch((error) => {