bpmax-cli 0.2.1-beta.26 → 0.2.1-beta.27

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
@@ -50,7 +50,8 @@ var toV2Config = (input) => {
50
50
  api_key_capabilities: profile.api_key_capabilities || {},
51
51
  capabilities_cache: profile.capabilities_cache,
52
52
  capabilities_probe: profile.capabilities_probe,
53
- config_environments: profile.config_environments || {}
53
+ config_environments: profile.config_environments || {},
54
+ plugin_skill_update_policy: profile.plugin_skill_update_policy || "check"
54
55
  }
55
56
  ])
56
57
  )
@@ -176,7 +177,8 @@ function resolveProfile(config, profileName) {
176
177
  terminal_status: profile.terminal_status,
177
178
  api_key_capabilities: profile.api_key_capabilities || {},
178
179
  capabilities_probe: profile.capabilities_probe,
179
- config_environments: profile.config_environments || {}
180
+ config_environments: profile.config_environments || {},
181
+ plugin_skill_update_policy: profile.plugin_skill_update_policy || "check"
180
182
  }
181
183
  };
182
184
  }
@@ -469,7 +471,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
469
471
  // package.json
470
472
  var package_default = {
471
473
  name: "bpmax-cli",
472
- version: "0.2.1-beta.26",
474
+ version: "0.2.1-beta.27",
473
475
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
474
476
  type: "module",
475
477
  bin: {
@@ -1270,7 +1272,7 @@ function registerApiCommands(program2) {
1270
1272
  }
1271
1273
 
1272
1274
  // src/commands/auth.ts
1273
- import axios3, { AxiosHeaders as AxiosHeaders2 } from "axios";
1275
+ import axios5, { AxiosHeaders as AxiosHeaders2 } from "axios";
1274
1276
 
1275
1277
  // src/core/auth.ts
1276
1278
  import { createServer } from "http";
@@ -1510,721 +1512,375 @@ function updateProfileAuth(profile, result) {
1510
1512
  };
1511
1513
  }
1512
1514
 
1513
- // src/commands/auth.ts
1514
- function deviceStartBody(result) {
1515
- const configDir = isConfigDirOverridden() ? getConfigDir() : void 0;
1516
- return {
1517
- ok: true,
1518
- ...result,
1519
- session: result.device_code,
1520
- ...configDir ? { config_dir: configDir } : {},
1521
- message_card: buildAuthorizationMessageCard({
1522
- ...result,
1523
- ...configDir ? { config_dir: configDir } : {}
1524
- })
1525
- };
1515
+ // src/core/plugin-skills.ts
1516
+ import { createHash as createHash3 } from "crypto";
1517
+ import { cp as cp2, mkdir as mkdir4, readdir, readFile as readFile6, rm as rm2, stat as stat3, writeFile as writeFile4 } from "fs/promises";
1518
+ import path4 from "path";
1519
+ import { fileURLToPath as fileURLToPath2 } from "url";
1520
+ import axios4 from "axios";
1521
+ import JSZip2 from "jszip";
1522
+
1523
+ // src/core/business-skills.ts
1524
+ import { cp, mkdir as mkdir2, readFile as readFile4, rm, stat as stat2, writeFile as writeFile2 } from "fs/promises";
1525
+ import { createHash as createHash2 } from "crypto";
1526
+ import { homedir as homedir2, tmpdir } from "os";
1527
+ import path2 from "path";
1528
+ import { setTimeout as delay } from "timers/promises";
1529
+ import axios3 from "axios";
1530
+ import JSZip from "jszip";
1531
+
1532
+ // src/core/process.ts
1533
+ import { spawn } from "child_process";
1534
+ var runCommand = (command, args, options = {}) => new Promise((resolve) => {
1535
+ const child = spawn(command, args, {
1536
+ cwd: options.cwd,
1537
+ env: options.env,
1538
+ stdio: ["ignore", "pipe", "pipe"]
1539
+ });
1540
+ let stdout = "";
1541
+ let stderr = "";
1542
+ let settled = false;
1543
+ const timer = options.timeoutMs && options.timeoutMs > 0 ? setTimeout(() => {
1544
+ if (settled) {
1545
+ return;
1546
+ }
1547
+ settled = true;
1548
+ child.kill("SIGTERM");
1549
+ resolve({
1550
+ stdout,
1551
+ stderr: `${stderr}${stderr ? "\n" : ""}Timed out after ${options.timeoutMs}ms`,
1552
+ exitCode: 124
1553
+ });
1554
+ }, options.timeoutMs) : void 0;
1555
+ child.stdout?.on("data", (chunk) => {
1556
+ stdout += String(chunk);
1557
+ });
1558
+ child.stderr?.on("data", (chunk) => {
1559
+ stderr += String(chunk);
1560
+ });
1561
+ child.on("error", (error) => {
1562
+ if (settled) {
1563
+ return;
1564
+ }
1565
+ settled = true;
1566
+ if (timer) {
1567
+ clearTimeout(timer);
1568
+ }
1569
+ resolve({ stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}`, exitCode: 1 });
1570
+ });
1571
+ child.on("close", (code) => {
1572
+ if (settled) {
1573
+ return;
1574
+ }
1575
+ settled = true;
1576
+ if (timer) {
1577
+ clearTimeout(timer);
1578
+ }
1579
+ resolve({ stdout, stderr, exitCode: code ?? 1 });
1580
+ });
1581
+ });
1582
+
1583
+ // src/core/business-skills.ts
1584
+ var directoryTargets = {
1585
+ codex: path2.join(homedir2(), ".codex", "skills"),
1586
+ claude: path2.join(homedir2(), ".claude", "skills"),
1587
+ "cc-switch": path2.join(homedir2(), ".cc-switch", "skills"),
1588
+ agents: path2.join(homedir2(), ".agents", "skills"),
1589
+ gemini: path2.join(homedir2(), ".gemini", "skills"),
1590
+ generic: path2.join(homedir2(), ".agents", "skills")
1591
+ };
1592
+ var semverPattern = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
1593
+ var knownBpmCommands = {
1594
+ api: null,
1595
+ auth: /* @__PURE__ */ new Set(["login", "status", "logout", "device"]),
1596
+ bbs: /* @__PURE__ */ new Set(["list", "show", "create", "upgrade", "sync", "ensure", "install", "update", "uninstall", "lint", "gate"]),
1597
+ capabilities: /* @__PURE__ */ new Set(["status", "refresh"]),
1598
+ config: null,
1599
+ es: /* @__PURE__ */ new Set(["project-search"]),
1600
+ flow: /* @__PURE__ */ new Set(["list", "options", "get"]),
1601
+ init: null,
1602
+ plugin: /* @__PURE__ */ new Set(["skills"]),
1603
+ project: /* @__PURE__ */ new Set(["list", "search", "get", "my-step", "approval-context", "create"]),
1604
+ recipe: /* @__PURE__ */ new Set(["list", "show", "run", "scaffold"]),
1605
+ schema: /* @__PURE__ */ new Set(["list", "show"]),
1606
+ setup: null,
1607
+ step: /* @__PURE__ */ new Set(["get", "context", "actions", "requirements", "submit"]),
1608
+ update: null,
1609
+ url: /* @__PURE__ */ new Set(["workspace", "project-create", "project-list", "project-detail", "project-step"]),
1610
+ user: /* @__PURE__ */ new Set(["current"])
1611
+ };
1612
+ function issue(severity, code, message) {
1613
+ return { severity, code, message };
1526
1614
  }
1527
- function shellQuote2(value) {
1528
- if (/^[A-Za-z0-9_./:@=-]+$/.test(value)) {
1529
- return value;
1615
+ function parseFrontmatter(markdown) {
1616
+ const match = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---/);
1617
+ if (!match) {
1618
+ return {};
1530
1619
  }
1531
- return `'${value.replace(/'/g, `'\\''`)}'`;
1620
+ const result = {};
1621
+ match[1].split(/\r?\n/).forEach((line) => {
1622
+ const item = line.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
1623
+ if (!item) {
1624
+ return;
1625
+ }
1626
+ result[item[1]] = item[2].trim().replace(/^['"]|['"]$/g, "");
1627
+ });
1628
+ return result;
1532
1629
  }
1533
- function configWorkspaceNextCommands(profileName, cache) {
1534
- if (!capabilityEnabled(cache, "config.repository.view") || !capabilityEnabled(cache, "config.latest.pull")) {
1535
- return void 0;
1630
+ function normalizeBusinessSkillKey(input) {
1631
+ return input.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
1632
+ }
1633
+ function parseBbsJson(raw) {
1634
+ const parsed = JSON.parse(raw);
1635
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1636
+ throw new Error("bbs.json must be a JSON object.");
1536
1637
  }
1537
- const configDirPrefix = isConfigDirOverridden() ? ` --config-dir ${shellQuote2(getConfigDir())}` : "";
1638
+ return parsed;
1639
+ }
1640
+ async function readBbsJson(skillDir) {
1641
+ try {
1642
+ return parseBbsJson(await readFile4(path2.join(skillDir, "bbs.json"), "utf8"));
1643
+ } catch (error) {
1644
+ if (error.code === "ENOENT") {
1645
+ return void 0;
1646
+ }
1647
+ throw error;
1648
+ }
1649
+ }
1650
+ function compareSemver(a, b) {
1651
+ const left = a.split(/[+-]/)[0].split(".").map((part) => Number(part));
1652
+ const right = b.split(/[+-]/)[0].split(".").map((part) => Number(part));
1653
+ for (let index = 0; index < 3; index += 1) {
1654
+ const diff = (left[index] || 0) - (right[index] || 0);
1655
+ if (diff !== 0) {
1656
+ return diff;
1657
+ }
1658
+ }
1659
+ return a.localeCompare(b);
1660
+ }
1661
+ function extractBpmaxCommands(markdown) {
1662
+ const commands = [];
1663
+ const regex = /bpmax-cli\s+([^\n`]+)/g;
1664
+ let match;
1665
+ while (match = regex.exec(markdown)) {
1666
+ commands.push(`bpmax-cli ${match[1].trim()}`);
1667
+ }
1668
+ return commands;
1669
+ }
1670
+ function commandPrefix(command) {
1671
+ return command.replace(/^bpmax-cli\s+/, "").split(/\s+/).filter(Boolean).slice(0, 2).join(" ");
1672
+ }
1673
+ function commandExists(command) {
1674
+ const parts = command.replace(/^bpmax-cli\s+/, "").split(/\s+/).filter(Boolean);
1675
+ const group = parts[0];
1676
+ if (!group || !Object.prototype.hasOwnProperty.call(knownBpmCommands, group)) {
1677
+ return false;
1678
+ }
1679
+ const subcommands = knownBpmCommands[group];
1680
+ if (!subcommands) {
1681
+ return true;
1682
+ }
1683
+ return Boolean(parts[1] && subcommands.has(parts[1]));
1684
+ }
1685
+ function isApprovalSkill(markdown, manifest) {
1686
+ const text5 = `${manifest.name || ""}
1687
+ ${manifest.description || ""}
1688
+ ${markdown}`.toLowerCase();
1689
+ return /审批|同意|拒绝|approve|reject|approval/.test(text5);
1690
+ }
1691
+ function hasAny(text5, patterns) {
1692
+ return patterns.some((pattern) => pattern.test(text5));
1693
+ }
1694
+ function truncateOutput(value) {
1695
+ return value.length > 4e3 ? `${value.slice(0, 4e3)}...<truncated>` : value;
1696
+ }
1697
+ async function runShellCommand(command, cwd) {
1698
+ const shell = process.platform === "win32" ? "cmd" : "sh";
1699
+ const args = process.platform === "win32" ? ["/c", command] : ["-c", command];
1700
+ return runCommand(shell, args, { cwd, timeoutMs: 6e4 });
1701
+ }
1702
+ function completeReport(report) {
1703
+ const errors = report.issues.filter((item) => item.severity === "error");
1704
+ const warnings = report.issues.filter((item) => item.severity === "warning");
1538
1705
  return {
1539
- config_workspace_init: `bpmax-cli${configDirPrefix} config workspace init <env> --profile ${profileName} --workspace-dir <dir> --format json`
1706
+ ok: errors.length === 0,
1707
+ errors,
1708
+ warnings,
1709
+ manifest: report.manifest,
1710
+ checks: report.checks,
1711
+ skill_dir: report.skill_dir
1540
1712
  };
1541
1713
  }
1542
- async function fetchCurrentUserForStatus(profile) {
1543
- const headers = AxiosHeaders2.from();
1544
- headers.set("Authorization", `Bearer ${profile.config.api_key}`);
1545
- const response = await axios3.request({
1546
- method: "GET",
1547
- baseURL: profile.config.origin,
1548
- url: "/api/user/current",
1549
- params: {
1550
- $workspace: normalizeWorkspaceForApi(profile.config.workspace),
1551
- $language: profile.config.language
1552
- },
1553
- headers
1554
- });
1555
- const body = response.data;
1556
- if (typeof body.code === "number" && body.code !== 0) {
1557
- throw new Error(body.msg || `Request failed with code ${body.code}`);
1714
+ async function exists(targetPath) {
1715
+ try {
1716
+ await stat2(targetPath);
1717
+ return true;
1718
+ } catch {
1719
+ return false;
1558
1720
  }
1559
- return body.data ?? body;
1560
1721
  }
1561
- function minimalStatusUser(user) {
1562
- const safe = {};
1563
- for (const key of ["id", "user_id", "uid", "name", "nickname", "realname"]) {
1564
- if (user[key] !== void 0 && user[key] !== null && user[key] !== "") {
1565
- safe[key] = user[key];
1566
- }
1722
+ function businessSkillStatePath(profileName, agent) {
1723
+ return path2.join(getConfigDir(), "business-skills", profileName, agent, "state.json");
1724
+ }
1725
+ async function readBusinessSkillState(profileName, agent) {
1726
+ try {
1727
+ return JSON.parse(await readFile4(businessSkillStatePath(profileName, agent), "utf8"));
1728
+ } catch {
1729
+ return { skills: {} };
1567
1730
  }
1568
- return safe;
1569
1731
  }
1570
- function registerAuthCommands(program2, deps = {}) {
1571
- const load = deps.loadConfig || loadConfig;
1572
- const save = deps.saveConfig || saveConfig;
1573
- const startDevice = deps.startDeviceLogin || startDeviceLogin;
1574
- const completeDevice = deps.completeDeviceLogin || completeDeviceLogin;
1575
- const pollDevice = deps.pollDeviceLogin || pollDeviceLogin;
1576
- const shouldProbeCapabilities = !deps.loadConfig && !deps.saveConfig;
1577
- const auth = program2.command("auth").description("Authenticate and manage API key state");
1578
- 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: device", "device").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) => {
1579
- const config = await load();
1580
- const profile = resolveProfile(config, options.profile);
1581
- let result;
1582
- let authorization;
1583
- if (options.mode && options.mode !== "device") {
1584
- throw new Error("Browser callback authorization is no longer supported. Use `bpmax-cli auth login --mode device`.");
1585
- }
1586
- authorization = await startDevice({
1587
- origin: profile.config.origin,
1588
- workspace: profile.config.workspace,
1589
- profileName: profile.name,
1590
- apiKeyName: options.keyName,
1591
- agent: options.agent,
1592
- channel: options.channel,
1593
- requestConfigurationCapability: true
1594
- });
1595
- const codeOutput = options.format === "json" ? console.error : console.log;
1596
- codeOutput(`Open ${authorization.authorization_url}`);
1597
- codeOutput(`Confirm code: ${authorization.user_code}`);
1598
- result = await pollDevice({
1599
- origin: profile.config.origin,
1600
- deviceCode: authorization.device_code,
1601
- interval: authorization.interval,
1602
- expiresIn: authorization.expires_in
1603
- });
1604
- config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1605
- result = { ...result, user: config.profiles[profile.name].user };
1606
- await save(config);
1607
- let capabilitiesProbe;
1608
- let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
1609
- if (shouldProbeCapabilities) {
1610
- try {
1611
- const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
1612
- const client = createApiClient(authenticatedProfile);
1613
- await ensureTerminalRegistered(client, authenticatedProfile);
1614
- const cache = await refreshCapabilities(client, authenticatedProfile);
1615
- config.profiles[profile.name].capabilities_cache = cache;
1616
- capabilitiesCache = cache;
1617
- capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
1618
- } catch (error) {
1619
- capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
1620
- }
1621
- }
1622
- const nextCommands = configWorkspaceNextCommands(profile.name, capabilitiesCache);
1623
- if (options.format === "json") {
1624
- printResult("json", {
1625
- ok: true,
1626
- profile: profile.name,
1627
- login: "authenticated",
1628
- user: result.user,
1629
- ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
1630
- ...nextCommands ? { next_commands: nextCommands } : {},
1631
- ...authorization ? {
1632
- authorization,
1633
- message_card: buildAuthorizationMessageCard({
1634
- ...authorization,
1635
- ...isConfigDirOverridden() ? { config_dir: getConfigDir() } : {}
1636
- })
1637
- } : {}
1638
- });
1639
- } else {
1640
- console.log(`Saved API key for profile "${profile.name}".`);
1641
- }
1642
- });
1643
- const device = auth.command("device").description("Device authorization for browserless agent environments");
1644
- 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) => {
1645
- const config = await load();
1646
- const profile = resolveProfile(config, options.profile);
1647
- const result = await startDevice({
1648
- origin: profile.config.origin,
1649
- workspace: profile.config.workspace,
1650
- profileName: profile.name,
1651
- apiKeyName: options.keyName,
1652
- agent: options.agent,
1653
- channel: options.channel,
1654
- requestConfigurationCapability: true
1655
- });
1656
- printResult(options.format, deviceStartBody(result));
1657
- });
1658
- 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) => {
1659
- const deviceCode = options.deviceCode || options.session;
1660
- if (!deviceCode) {
1661
- throw new Error("--device-code or --session is required.");
1662
- }
1663
- const config = await load();
1664
- const profile = resolveProfile(config, options.profile);
1665
- const result = await completeDevice({
1666
- origin: profile.config.origin,
1667
- deviceCode
1668
- });
1669
- config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1670
- const safeUser = config.profiles[profile.name].user;
1671
- await save(config);
1672
- let capabilitiesProbe;
1673
- let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
1674
- if (shouldProbeCapabilities) {
1675
- try {
1676
- const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
1677
- const client = createApiClient(authenticatedProfile);
1678
- await ensureTerminalRegistered(client, authenticatedProfile);
1679
- const cache = await refreshCapabilities(client, authenticatedProfile);
1680
- config.profiles[profile.name].capabilities_cache = cache;
1681
- capabilitiesCache = cache;
1682
- capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
1683
- } catch (error) {
1684
- capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
1685
- }
1686
- }
1687
- const nextCommands = configWorkspaceNextCommands(profile.name, capabilitiesCache);
1688
- printResult(options.format, {
1689
- ok: true,
1690
- profile: profile.name,
1691
- login: "authenticated",
1692
- user: safeUser,
1693
- ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
1694
- ...nextCommands ? { next_commands: nextCommands } : {}
1695
- });
1696
- });
1697
- auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--verbose", "Include the full /api/user/current response. Default output is minimized and redacted for logs.").option("--format <format>", "Output format", "pretty").action(async (options) => {
1698
- const config = await load();
1699
- const profile = resolveProfile(config, options.profile);
1700
- const output = {
1701
- profile: profile.name,
1702
- origin: profile.config.origin,
1703
- workspace: profile.config.workspace,
1704
- language: profile.config.language,
1705
- api_key: maskApiKey(profile.config.api_key)
1706
- };
1707
- if (profile.config.api_key) {
1708
- try {
1709
- const currentUser = await fetchCurrentUserForStatus(profile);
1710
- output.user = options.verbose ? currentUser : minimalStatusUser(currentUser);
1711
- output.user_detail = options.verbose ? "full" : "minimal";
1712
- output.authenticated = true;
1713
- } catch (error) {
1714
- const message = error instanceof Error ? error.message : String(error);
1715
- if (message.includes(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE)) {
1716
- output.authenticated = "unknown";
1717
- output.platform_cli_governance = "unsupported";
1718
- output.error = message;
1719
- output.next = "Upgrade huanpingtong-server to enable CLI governance, or validate this API key with a CLI version that matches the old platform.";
1720
- } else {
1721
- output.authenticated = false;
1722
- output.error = message;
1723
- }
1732
+ async function writeBusinessSkillState(profileName, agent, state) {
1733
+ const target = businessSkillStatePath(profileName, agent);
1734
+ await mkdir2(path2.dirname(target), { recursive: true });
1735
+ await writeFile2(target, JSON.stringify(state, null, 2), "utf8");
1736
+ }
1737
+ async function acquireStateLock(profileName, agent) {
1738
+ const target = businessSkillStatePath(profileName, agent);
1739
+ const lockPath = `${target}.lock`;
1740
+ await mkdir2(path2.dirname(target), { recursive: true });
1741
+ for (let attempt = 0; attempt < 100; attempt += 1) {
1742
+ try {
1743
+ await mkdir2(lockPath);
1744
+ return lockPath;
1745
+ } catch (error) {
1746
+ const code = error.code;
1747
+ if (code !== "EEXIST") {
1748
+ throw error;
1724
1749
  }
1725
- } else {
1726
- output.authenticated = false;
1750
+ await delay(50);
1727
1751
  }
1728
- printResult(options.format, output);
1729
- });
1730
- auth.command("logout").description("Clear the stored API key for the selected profile").option("--profile <profile>", "Profile name").action(async (options) => {
1731
- const config = await load();
1732
- const profile = resolveProfile(config, options.profile);
1733
- config.profiles[profile.name] = {
1734
- ...config.profiles[profile.name],
1735
- api_key: "",
1736
- user: void 0,
1737
- terminal_id: void 0,
1738
- terminal_status: void 0,
1739
- terminal_registered_at: void 0
1740
- };
1741
- await save(config);
1742
- console.log(`Cleared API key for profile "${profile.name}".`);
1743
- });
1744
- }
1745
-
1746
- // src/commands/bbs.ts
1747
- import { basename } from "path";
1748
- import { randomUUID as randomUUID2 } from "crypto";
1749
- import { readFile as readFile5 } from "fs/promises";
1750
-
1751
- // src/core/urls.ts
1752
- function stripSlashes(value) {
1753
- return value.trim().replace(/^\/+|\/+$/g, "");
1754
- }
1755
- function isRecord2(value) {
1756
- return typeof value === "object" && value !== null && !Array.isArray(value);
1757
- }
1758
- function normalizeWorkspaceForUrl(workspace) {
1759
- const nextWorkspace = stripSlashes(workspace);
1760
- if (!nextWorkspace) {
1761
- throw new Error("Workspace is required to build a BPMAX URL.");
1762
- }
1763
- if (nextWorkspace === "default" || nextWorkspace.startsWith("w:")) {
1764
- return nextWorkspace;
1765
- }
1766
- return `w:${nextWorkspace}`;
1767
- }
1768
- function normalizeOrigin2(origin) {
1769
- const nextOrigin = origin.trim().replace(/\/+$/, "");
1770
- if (!nextOrigin) {
1771
- throw new Error("Origin is required to build a BPMAX URL.");
1772
1752
  }
1773
- return nextOrigin;
1753
+ throw new Error(`Timed out waiting for BBS state lock: ${lockPath}`);
1774
1754
  }
1775
- function requireNumericId(value, name) {
1776
- const nextValue = String(value || "").trim();
1777
- if (!/^\d+$/.test(nextValue)) {
1778
- throw new Error(`${name} must be a non-empty numeric string.`);
1755
+ async function updateBusinessSkillState(profileName, agent, updater) {
1756
+ const lockPath = await acquireStateLock(profileName, agent);
1757
+ try {
1758
+ const state = await readBusinessSkillState(profileName, agent);
1759
+ const next = await updater(state) ?? state;
1760
+ await writeBusinessSkillState(profileName, agent, next);
1761
+ return next;
1762
+ } finally {
1763
+ await rm(lockPath, { recursive: true, force: true });
1779
1764
  }
1780
- return nextValue;
1781
1765
  }
1782
- function withQuery(path16, query) {
1783
- const params = new URLSearchParams();
1784
- for (const [key, value] of Object.entries(query)) {
1785
- if (value !== void 0) {
1786
- params.set(key, value);
1787
- }
1766
+ async function zipDirectoryToTemp(zipBuffer, prefix) {
1767
+ const zip = await JSZip.loadAsync(zipBuffer);
1768
+ const root = path2.join(tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
1769
+ await mkdir2(root, { recursive: true });
1770
+ await Promise.all(
1771
+ Object.keys(zip.files).map(async (filename) => {
1772
+ const normalized = filename.replace(/\\/g, "/");
1773
+ if (normalized.startsWith("/") || normalized.includes("../") || normalized === "..") {
1774
+ throw new Error(`Unsafe path in BBS zip: ${filename}`);
1775
+ }
1776
+ const file = zip.files[filename];
1777
+ const target = path2.join(root, normalized);
1778
+ if (file.dir) {
1779
+ await mkdir2(target, { recursive: true });
1780
+ return;
1781
+ }
1782
+ await mkdir2(path2.dirname(target), { recursive: true });
1783
+ await writeFile2(target, await file.async("nodebuffer"));
1784
+ })
1785
+ );
1786
+ if (!await exists(path2.join(root, "SKILL.md"))) {
1787
+ throw new Error("BBS zip must contain top-level SKILL.md.");
1788
1788
  }
1789
- return `${path16}?${params.toString()}`;
1789
+ return root;
1790
1790
  }
1791
- function buildBpmaxUrl(profile, kind, params = {}) {
1792
- const origin = normalizeOrigin2(profile.config.origin);
1793
- const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
1794
- const basePath = `/${workspace}`;
1795
- let path16 = basePath;
1796
- const result = {
1797
- kind,
1798
- profile: profile.name,
1799
- origin,
1800
- workspace
1801
- };
1802
- if (kind === "project-list") {
1803
- path16 = `${basePath}/project`;
1804
- } else if (kind === "project-detail") {
1805
- const projectId = requireNumericId(params.projectId, "projectId");
1806
- path16 = `${basePath}/project_detail/0/${projectId}`;
1807
- result.project_id = projectId;
1808
- } else if (kind === "project-step") {
1809
- const projectId = requireNumericId(params.projectId, "projectId");
1810
- const stepId = requireNumericId(params.stepId, "stepId");
1811
- path16 = withQuery(`${basePath}/projectContinue`, {
1812
- id: projectId,
1813
- step_id: stepId
1814
- });
1815
- result.project_id = projectId;
1816
- result.step_id = stepId;
1817
- } else if (kind === "project-create") {
1818
- const flowType = params.flowType || "default";
1819
- const flowKey = params.flowKey || "";
1820
- const initValue = params.initValue ? JSON.stringify(params.initValue) : void 0;
1821
- const prefillToken = params.prefillToken;
1822
- const query = {
1823
- flow_type: flowType,
1824
- flow_key: flowKey,
1825
- ...flowKey ? { key: flowKey } : {},
1826
- ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
1827
- };
1828
- path16 = withQuery(`${basePath}/project/create`, query);
1829
- result.flow_type = flowType;
1830
- result.flow_key = flowKey;
1831
- result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
1791
+ async function lintBusinessSkillDirectory(skillDir, options = {}) {
1792
+ const issues = [];
1793
+ const checks = [];
1794
+ let skillMarkdown = "";
1795
+ let manifest = {};
1796
+ let config;
1797
+ try {
1798
+ skillMarkdown = await readFile4(path2.join(skillDir, "SKILL.md"), "utf8");
1799
+ manifest = parseFrontmatter(skillMarkdown);
1800
+ } catch {
1801
+ issues.push(issue("error", "missing_skill_md", "BBS package must contain top-level SKILL.md."));
1832
1802
  }
1833
- const url = `${origin}${path16}`;
1834
- return {
1835
- ...result,
1836
- path: path16,
1837
- url,
1838
- ...kind === "project-create" ? { pc_url: url } : {}
1839
- };
1840
- }
1841
- function extractProjectId(value) {
1842
- if (!isRecord2(value)) {
1843
- return void 0;
1803
+ try {
1804
+ config = await readBbsJson(skillDir);
1805
+ } catch (error) {
1806
+ issues.push(issue("error", "invalid_bbs_json", error instanceof Error ? error.message : String(error)));
1844
1807
  }
1845
- const candidates = [value.id, value.project_id, value.projectId];
1846
- const candidate = candidates.find((item) => item !== void 0 && item !== null);
1847
- if (candidate === void 0) {
1848
- return void 0;
1808
+ const name = manifest.name;
1809
+ const version = manifest.version;
1810
+ const description = manifest.description;
1811
+ if (!name || typeof name !== "string") {
1812
+ issues.push(issue("error", "missing_name", "SKILL.md frontmatter must contain name."));
1813
+ } else if (!normalizeBusinessSkillKey(name)) {
1814
+ issues.push(issue("error", "invalid_name", "SKILL.md frontmatter name must produce a valid BBS key."));
1849
1815
  }
1850
- const projectId = String(candidate).trim();
1851
- return /^\d+$/.test(projectId) ? projectId : void 0;
1852
- }
1853
- function attachProjectDetailUrl(profile, value) {
1854
- if (!isRecord2(value) || typeof value.url === "string") {
1855
- return value;
1816
+ if (!version || typeof version !== "string") {
1817
+ issues.push(issue("error", "missing_version", "SKILL.md frontmatter must contain version."));
1818
+ } else if (!semverPattern.test(version)) {
1819
+ issues.push(issue("error", "invalid_version", "SKILL.md frontmatter version must be semver, for example 1.0.0."));
1820
+ } else if (options.latestVersion && compareSemver(version, options.latestVersion) <= 0) {
1821
+ issues.push(
1822
+ issue(
1823
+ "error",
1824
+ "version_not_incremented",
1825
+ `BBS package version ${version} must be greater than latest version ${options.latestVersion}.`
1826
+ )
1827
+ );
1856
1828
  }
1857
- const projectId = extractProjectId(value);
1858
- if (!projectId) {
1859
- return value;
1829
+ if (!description || typeof description !== "string") {
1830
+ issues.push(issue("error", "missing_description", "SKILL.md frontmatter must contain description."));
1860
1831
  }
1861
- return {
1862
- ...value,
1863
- url: buildBpmaxUrl(profile, "project-detail", { projectId }).url
1864
- };
1865
- }
1866
-
1867
- // src/core/business-skills.ts
1868
- import { cp, mkdir as mkdir2, readFile as readFile4, rm, stat as stat2, writeFile as writeFile2 } from "fs/promises";
1869
- import { createHash as createHash2 } from "crypto";
1870
- import { homedir as homedir2, tmpdir } from "os";
1871
- import path2 from "path";
1872
- import { setTimeout as delay } from "timers/promises";
1873
- import axios4 from "axios";
1874
- import JSZip from "jszip";
1875
-
1876
- // src/core/process.ts
1877
- import { spawn } from "child_process";
1878
- var runCommand = (command, args, options = {}) => new Promise((resolve) => {
1879
- const child = spawn(command, args, {
1880
- cwd: options.cwd,
1881
- env: options.env,
1882
- stdio: ["ignore", "pipe", "pipe"]
1832
+ const commands = extractBpmaxCommands(skillMarkdown);
1833
+ const unknownCommands = commands.filter((command) => !commandExists(command));
1834
+ unknownCommands.forEach((command) => {
1835
+ issues.push(issue("error", "unknown_bpmax_command", `Unknown bpmax-cli command in SKILL.md: ${commandPrefix(command)}`));
1883
1836
  });
1884
- let stdout = "";
1885
- let stderr = "";
1886
- let settled = false;
1887
- const timer = options.timeoutMs && options.timeoutMs > 0 ? setTimeout(() => {
1888
- if (settled) {
1889
- return;
1837
+ checks.push({ name: "bpmax_commands", commands, unknown: unknownCommands });
1838
+ [
1839
+ { pattern: /\brm\s+-rf\b/, code: "dangerous_rm_rf", message: "Dangerous rm -rf command found." },
1840
+ { pattern: /\bgit\s+reset\s+--hard\b/, code: "dangerous_git_reset", message: "Dangerous git reset --hard command found." },
1841
+ { pattern: /\bgit\s+checkout\s+--\b/, code: "dangerous_git_checkout", message: "Dangerous git checkout -- command found." },
1842
+ { pattern: /authorization\s*:\s*bearer|api[_-]?key\s*[:=]\s*['"][^'"]+/i, code: "secret_literal", message: "Possible literal credential found." },
1843
+ { pattern: /\bcurl\b[\s\S]{0,160}\b-X\s*(POST|PUT|PATCH|DELETE)\b/i, code: "raw_mutating_curl", message: "Raw mutating curl command found; use bpmax-cli wrappers." },
1844
+ { pattern: /bpmax-cli\s+project\s+create\b[^\n`]*\s--body\b/i, code: "unsafe_project_create_body", message: "BBS must not use bpmax-cli project create --body; use project create --json so the CLI can enforce form handoff safety." },
1845
+ { pattern: /bpmax-cli\s+api\s+POST\s+\/(?:api\/)?project\b/i, code: "unsafe_raw_project_create_api", message: "BBS must not call raw api POST /project; use bpmax-cli project create --json." }
1846
+ ].forEach((rule) => {
1847
+ if (rule.pattern.test(skillMarkdown)) {
1848
+ issues.push(issue("error", rule.code, rule.message));
1890
1849
  }
1891
- settled = true;
1892
- child.kill("SIGTERM");
1893
- resolve({
1894
- stdout,
1895
- stderr: `${stderr}${stderr ? "\n" : ""}Timed out after ${options.timeoutMs}ms`,
1896
- exitCode: 124
1897
- });
1898
- }, options.timeoutMs) : void 0;
1899
- child.stdout?.on("data", (chunk) => {
1900
- stdout += String(chunk);
1901
- });
1902
- child.stderr?.on("data", (chunk) => {
1903
- stderr += String(chunk);
1904
1850
  });
1905
- child.on("error", (error) => {
1906
- if (settled) {
1907
- return;
1851
+ if (/\bcurl\b/i.test(skillMarkdown)) {
1852
+ issues.push(issue("warning", "curl_usage", "curl usage found; prefer bpmax-cli commands for BPMAX APIs."));
1853
+ }
1854
+ if (isApprovalSkill(skillMarkdown, manifest)) {
1855
+ const lower = skillMarkdown.toLowerCase();
1856
+ if (!hasAny(lower, [/confirm|confirmation|explicit|明确|确认/])) {
1857
+ issues.push(issue("error", "approval_missing_confirmation", "Approval BBS must require explicit user confirmation."));
1908
1858
  }
1909
- settled = true;
1910
- if (timer) {
1911
- clearTimeout(timer);
1859
+ if (!hasAny(lower, [/batch|multiple|批量|多个|exact task list/])) {
1860
+ issues.push(issue("error", "approval_missing_batch_guardrail", "Approval BBS must define batch approval guardrails."));
1912
1861
  }
1913
- resolve({ stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}`, exitCode: 1 });
1914
- });
1915
- child.on("close", (code) => {
1916
- if (settled) {
1917
- return;
1862
+ if (!/bpmax-cli\s+project\s+approval-context/.test(skillMarkdown)) {
1863
+ issues.push(issue("error", "approval_missing_context", "Approval BBS must use bpmax-cli project approval-context before approving."));
1918
1864
  }
1919
- settled = true;
1920
- if (timer) {
1921
- clearTimeout(timer);
1865
+ if (!hasAny(lower, [/stop|failed|failure|error|失败|不要|不得|do not/])) {
1866
+ issues.push(issue("error", "approval_missing_failure_stop", "Approval BBS must stop on failed context or API errors."));
1922
1867
  }
1923
- resolve({ stdout, stderr, exitCode: code ?? 1 });
1924
- });
1925
- });
1926
-
1927
- // src/core/business-skills.ts
1928
- var directoryTargets = {
1929
- codex: path2.join(homedir2(), ".codex", "skills"),
1930
- claude: path2.join(homedir2(), ".claude", "skills"),
1931
- "cc-switch": path2.join(homedir2(), ".cc-switch", "skills"),
1932
- agents: path2.join(homedir2(), ".agents", "skills"),
1933
- gemini: path2.join(homedir2(), ".gemini", "skills"),
1934
- generic: path2.join(homedir2(), ".agents", "skills")
1935
- };
1936
- var semverPattern = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
1937
- var knownBpmCommands = {
1938
- api: null,
1939
- auth: /* @__PURE__ */ new Set(["login", "status", "logout", "device"]),
1940
- bbs: /* @__PURE__ */ new Set(["list", "show", "create", "upgrade", "sync", "ensure", "install", "update", "uninstall", "lint", "gate"]),
1941
- capabilities: /* @__PURE__ */ new Set(["status", "refresh"]),
1942
- config: null,
1943
- es: /* @__PURE__ */ new Set(["project-search"]),
1944
- flow: /* @__PURE__ */ new Set(["list", "options", "get"]),
1945
- init: null,
1946
- plugin: /* @__PURE__ */ new Set(["skills"]),
1947
- project: /* @__PURE__ */ new Set(["list", "search", "get", "my-step", "approval-context", "create"]),
1948
- recipe: /* @__PURE__ */ new Set(["list", "show", "run", "scaffold"]),
1949
- schema: /* @__PURE__ */ new Set(["list", "show"]),
1950
- setup: null,
1951
- step: /* @__PURE__ */ new Set(["get", "context", "actions", "requirements", "submit"]),
1952
- update: null,
1953
- url: /* @__PURE__ */ new Set(["workspace", "project-create", "project-list", "project-detail", "project-step"]),
1954
- user: /* @__PURE__ */ new Set(["current"])
1955
- };
1956
- function issue(severity, code, message) {
1957
- return { severity, code, message };
1958
- }
1959
- function parseFrontmatter(markdown) {
1960
- const match = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---/);
1961
- if (!match) {
1962
- return {};
1963
1868
  }
1964
- const result = {};
1965
- match[1].split(/\r?\n/).forEach((line) => {
1966
- const item = line.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
1967
- if (!item) {
1968
- return;
1869
+ const lintCommands = config?.lint?.commands || [];
1870
+ for (const command of lintCommands) {
1871
+ const result = await runShellCommand(command, skillDir);
1872
+ checks.push({
1873
+ name: "custom_lint_command",
1874
+ command,
1875
+ exit_code: result.exitCode,
1876
+ stdout: truncateOutput(result.stdout),
1877
+ stderr: truncateOutput(result.stderr)
1878
+ });
1879
+ if (result.exitCode !== 0) {
1880
+ issues.push(issue("error", "custom_lint_failed", `Custom lint command failed: ${command}`));
1969
1881
  }
1970
- result[item[1]] = item[2].trim().replace(/^['"]|['"]$/g, "");
1971
- });
1972
- return result;
1973
- }
1974
- function normalizeBusinessSkillKey(input) {
1975
- return input.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
1976
- }
1977
- function parseBbsJson(raw) {
1978
- const parsed = JSON.parse(raw);
1979
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1980
- throw new Error("bbs.json must be a JSON object.");
1981
1882
  }
1982
- return parsed;
1983
- }
1984
- async function readBbsJson(skillDir) {
1985
- try {
1986
- return parseBbsJson(await readFile4(path2.join(skillDir, "bbs.json"), "utf8"));
1987
- } catch (error) {
1988
- if (error.code === "ENOENT") {
1989
- return void 0;
1990
- }
1991
- throw error;
1992
- }
1993
- }
1994
- function compareSemver(a, b) {
1995
- const left = a.split(/[+-]/)[0].split(".").map((part) => Number(part));
1996
- const right = b.split(/[+-]/)[0].split(".").map((part) => Number(part));
1997
- for (let index = 0; index < 3; index += 1) {
1998
- const diff = (left[index] || 0) - (right[index] || 0);
1999
- if (diff !== 0) {
2000
- return diff;
2001
- }
2002
- }
2003
- return a.localeCompare(b);
2004
- }
2005
- function extractBpmaxCommands(markdown) {
2006
- const commands = [];
2007
- const regex = /bpmax-cli\s+([^\n`]+)/g;
2008
- let match;
2009
- while (match = regex.exec(markdown)) {
2010
- commands.push(`bpmax-cli ${match[1].trim()}`);
2011
- }
2012
- return commands;
2013
- }
2014
- function commandPrefix(command) {
2015
- return command.replace(/^bpmax-cli\s+/, "").split(/\s+/).filter(Boolean).slice(0, 2).join(" ");
2016
- }
2017
- function commandExists(command) {
2018
- const parts = command.replace(/^bpmax-cli\s+/, "").split(/\s+/).filter(Boolean);
2019
- const group = parts[0];
2020
- if (!group || !Object.prototype.hasOwnProperty.call(knownBpmCommands, group)) {
2021
- return false;
2022
- }
2023
- const subcommands = knownBpmCommands[group];
2024
- if (!subcommands) {
2025
- return true;
2026
- }
2027
- return Boolean(parts[1] && subcommands.has(parts[1]));
2028
- }
2029
- function isApprovalSkill(markdown, manifest) {
2030
- const text5 = `${manifest.name || ""}
2031
- ${manifest.description || ""}
2032
- ${markdown}`.toLowerCase();
2033
- return /审批|同意|拒绝|approve|reject|approval/.test(text5);
2034
- }
2035
- function hasAny(text5, patterns) {
2036
- return patterns.some((pattern) => pattern.test(text5));
2037
- }
2038
- function truncateOutput(value) {
2039
- return value.length > 4e3 ? `${value.slice(0, 4e3)}...<truncated>` : value;
2040
- }
2041
- async function runShellCommand(command, cwd) {
2042
- const shell = process.platform === "win32" ? "cmd" : "sh";
2043
- const args = process.platform === "win32" ? ["/c", command] : ["-c", command];
2044
- return runCommand(shell, args, { cwd, timeoutMs: 6e4 });
2045
- }
2046
- function completeReport(report) {
2047
- const errors = report.issues.filter((item) => item.severity === "error");
2048
- const warnings = report.issues.filter((item) => item.severity === "warning");
2049
- return {
2050
- ok: errors.length === 0,
2051
- errors,
2052
- warnings,
2053
- manifest: report.manifest,
2054
- checks: report.checks,
2055
- skill_dir: report.skill_dir
2056
- };
2057
- }
2058
- async function exists(targetPath) {
2059
- try {
2060
- await stat2(targetPath);
2061
- return true;
2062
- } catch {
2063
- return false;
2064
- }
2065
- }
2066
- function businessSkillStatePath(profileName, agent) {
2067
- return path2.join(getConfigDir(), "business-skills", profileName, agent, "state.json");
2068
- }
2069
- async function readBusinessSkillState(profileName, agent) {
2070
- try {
2071
- return JSON.parse(await readFile4(businessSkillStatePath(profileName, agent), "utf8"));
2072
- } catch {
2073
- return { skills: {} };
2074
- }
2075
- }
2076
- async function writeBusinessSkillState(profileName, agent, state) {
2077
- const target = businessSkillStatePath(profileName, agent);
2078
- await mkdir2(path2.dirname(target), { recursive: true });
2079
- await writeFile2(target, JSON.stringify(state, null, 2), "utf8");
2080
- }
2081
- async function acquireStateLock(profileName, agent) {
2082
- const target = businessSkillStatePath(profileName, agent);
2083
- const lockPath = `${target}.lock`;
2084
- await mkdir2(path2.dirname(target), { recursive: true });
2085
- for (let attempt = 0; attempt < 100; attempt += 1) {
2086
- try {
2087
- await mkdir2(lockPath);
2088
- return lockPath;
2089
- } catch (error) {
2090
- const code = error.code;
2091
- if (code !== "EEXIST") {
2092
- throw error;
2093
- }
2094
- await delay(50);
2095
- }
2096
- }
2097
- throw new Error(`Timed out waiting for BBS state lock: ${lockPath}`);
2098
- }
2099
- async function updateBusinessSkillState(profileName, agent, updater) {
2100
- const lockPath = await acquireStateLock(profileName, agent);
2101
- try {
2102
- const state = await readBusinessSkillState(profileName, agent);
2103
- const next = await updater(state) ?? state;
2104
- await writeBusinessSkillState(profileName, agent, next);
2105
- return next;
2106
- } finally {
2107
- await rm(lockPath, { recursive: true, force: true });
2108
- }
2109
- }
2110
- async function zipDirectoryToTemp(zipBuffer, prefix) {
2111
- const zip = await JSZip.loadAsync(zipBuffer);
2112
- const root = path2.join(tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
2113
- await mkdir2(root, { recursive: true });
2114
- await Promise.all(
2115
- Object.keys(zip.files).map(async (filename) => {
2116
- const normalized = filename.replace(/\\/g, "/");
2117
- if (normalized.startsWith("/") || normalized.includes("../") || normalized === "..") {
2118
- throw new Error(`Unsafe path in BBS zip: ${filename}`);
2119
- }
2120
- const file = zip.files[filename];
2121
- const target = path2.join(root, normalized);
2122
- if (file.dir) {
2123
- await mkdir2(target, { recursive: true });
2124
- return;
2125
- }
2126
- await mkdir2(path2.dirname(target), { recursive: true });
2127
- await writeFile2(target, await file.async("nodebuffer"));
2128
- })
2129
- );
2130
- if (!await exists(path2.join(root, "SKILL.md"))) {
2131
- throw new Error("BBS zip must contain top-level SKILL.md.");
2132
- }
2133
- return root;
2134
- }
2135
- async function lintBusinessSkillDirectory(skillDir, options = {}) {
2136
- const issues = [];
2137
- const checks = [];
2138
- let skillMarkdown = "";
2139
- let manifest = {};
2140
- let config;
2141
- try {
2142
- skillMarkdown = await readFile4(path2.join(skillDir, "SKILL.md"), "utf8");
2143
- manifest = parseFrontmatter(skillMarkdown);
2144
- } catch {
2145
- issues.push(issue("error", "missing_skill_md", "BBS package must contain top-level SKILL.md."));
2146
- }
2147
- try {
2148
- config = await readBbsJson(skillDir);
2149
- } catch (error) {
2150
- issues.push(issue("error", "invalid_bbs_json", error instanceof Error ? error.message : String(error)));
2151
- }
2152
- const name = manifest.name;
2153
- const version = manifest.version;
2154
- const description = manifest.description;
2155
- if (!name || typeof name !== "string") {
2156
- issues.push(issue("error", "missing_name", "SKILL.md frontmatter must contain name."));
2157
- } else if (!normalizeBusinessSkillKey(name)) {
2158
- issues.push(issue("error", "invalid_name", "SKILL.md frontmatter name must produce a valid BBS key."));
2159
- }
2160
- if (!version || typeof version !== "string") {
2161
- issues.push(issue("error", "missing_version", "SKILL.md frontmatter must contain version."));
2162
- } else if (!semverPattern.test(version)) {
2163
- issues.push(issue("error", "invalid_version", "SKILL.md frontmatter version must be semver, for example 1.0.0."));
2164
- } else if (options.latestVersion && compareSemver(version, options.latestVersion) <= 0) {
2165
- issues.push(
2166
- issue(
2167
- "error",
2168
- "version_not_incremented",
2169
- `BBS package version ${version} must be greater than latest version ${options.latestVersion}.`
2170
- )
2171
- );
2172
- }
2173
- if (!description || typeof description !== "string") {
2174
- issues.push(issue("error", "missing_description", "SKILL.md frontmatter must contain description."));
2175
- }
2176
- const commands = extractBpmaxCommands(skillMarkdown);
2177
- const unknownCommands = commands.filter((command) => !commandExists(command));
2178
- unknownCommands.forEach((command) => {
2179
- issues.push(issue("error", "unknown_bpmax_command", `Unknown bpmax-cli command in SKILL.md: ${commandPrefix(command)}`));
2180
- });
2181
- checks.push({ name: "bpmax_commands", commands, unknown: unknownCommands });
2182
- [
2183
- { pattern: /\brm\s+-rf\b/, code: "dangerous_rm_rf", message: "Dangerous rm -rf command found." },
2184
- { pattern: /\bgit\s+reset\s+--hard\b/, code: "dangerous_git_reset", message: "Dangerous git reset --hard command found." },
2185
- { pattern: /\bgit\s+checkout\s+--\b/, code: "dangerous_git_checkout", message: "Dangerous git checkout -- command found." },
2186
- { pattern: /authorization\s*:\s*bearer|api[_-]?key\s*[:=]\s*['"][^'"]+/i, code: "secret_literal", message: "Possible literal credential found." },
2187
- { pattern: /\bcurl\b[\s\S]{0,160}\b-X\s*(POST|PUT|PATCH|DELETE)\b/i, code: "raw_mutating_curl", message: "Raw mutating curl command found; use bpmax-cli wrappers." },
2188
- { pattern: /bpmax-cli\s+project\s+create\b[^\n`]*\s--body\b/i, code: "unsafe_project_create_body", message: "BBS must not use bpmax-cli project create --body; use project create --json so the CLI can enforce form handoff safety." },
2189
- { pattern: /bpmax-cli\s+api\s+POST\s+\/(?:api\/)?project\b/i, code: "unsafe_raw_project_create_api", message: "BBS must not call raw api POST /project; use bpmax-cli project create --json." }
2190
- ].forEach((rule) => {
2191
- if (rule.pattern.test(skillMarkdown)) {
2192
- issues.push(issue("error", rule.code, rule.message));
2193
- }
2194
- });
2195
- if (/\bcurl\b/i.test(skillMarkdown)) {
2196
- issues.push(issue("warning", "curl_usage", "curl usage found; prefer bpmax-cli commands for BPMAX APIs."));
2197
- }
2198
- if (isApprovalSkill(skillMarkdown, manifest)) {
2199
- const lower = skillMarkdown.toLowerCase();
2200
- if (!hasAny(lower, [/confirm|confirmation|explicit|明确|确认/])) {
2201
- issues.push(issue("error", "approval_missing_confirmation", "Approval BBS must require explicit user confirmation."));
2202
- }
2203
- if (!hasAny(lower, [/batch|multiple|批量|多个|exact task list/])) {
2204
- issues.push(issue("error", "approval_missing_batch_guardrail", "Approval BBS must define batch approval guardrails."));
2205
- }
2206
- if (!/bpmax-cli\s+project\s+approval-context/.test(skillMarkdown)) {
2207
- issues.push(issue("error", "approval_missing_context", "Approval BBS must use bpmax-cli project approval-context before approving."));
2208
- }
2209
- if (!hasAny(lower, [/stop|failed|failure|error|失败|不要|不得|do not/])) {
2210
- issues.push(issue("error", "approval_missing_failure_stop", "Approval BBS must stop on failed context or API errors."));
2211
- }
2212
- }
2213
- const lintCommands = config?.lint?.commands || [];
2214
- for (const command of lintCommands) {
2215
- const result = await runShellCommand(command, skillDir);
2216
- checks.push({
2217
- name: "custom_lint_command",
2218
- command,
2219
- exit_code: result.exitCode,
2220
- stdout: truncateOutput(result.stdout),
2221
- stderr: truncateOutput(result.stderr)
2222
- });
2223
- if (result.exitCode !== 0) {
2224
- issues.push(issue("error", "custom_lint_failed", `Custom lint command failed: ${command}`));
2225
- }
2226
- }
2227
- return completeReport({ manifest, checks, issues, skill_dir: skillDir });
1883
+ return completeReport({ manifest, checks, issues, skill_dir: skillDir });
2228
1884
  }
2229
1885
  async function lintBusinessSkillZip(zipPath, options = {}) {
2230
1886
  try {
@@ -2310,13 +1966,21 @@ async function findOpenClawCli() {
2310
1966
  }
2311
1967
  return result.stdout.split(/\r?\n/).find((line) => line.trim())?.trim() || "openclaw";
2312
1968
  }
1969
+ function resolveAgentSkillInstallPath(skillName, agent) {
1970
+ const root = agent === "openclaw" ? path2.join(homedir2(), ".openclaw", "skills") : directoryTargets[agent] || directoryTargets.generic;
1971
+ return path2.join(root, skillName);
1972
+ }
2313
1973
  async function readSkillInstallOwner(destination) {
2314
- try {
2315
- const parsed = JSON.parse(await readFile4(path2.join(destination, ".bpmax-skill-install.json"), "utf8"));
2316
- return parsed?.kind === "plugin" ? parsed : void 0;
2317
- } catch {
2318
- return void 0;
1974
+ for (const fileName of [".bpmax-plugin-skill.json", ".bpmax-skill-install.json"]) {
1975
+ try {
1976
+ const parsed = JSON.parse(await readFile4(path2.join(destination, fileName), "utf8"));
1977
+ if (parsed?.kind === "plugin") {
1978
+ return parsed;
1979
+ }
1980
+ } catch {
1981
+ }
2319
1982
  }
1983
+ return void 0;
2320
1984
  }
2321
1985
  async function assertPluginSkillOwnerCompatible(destination, owner, options = {}) {
2322
1986
  if (!owner) {
@@ -2334,7 +1998,7 @@ async function assertPluginSkillOwnerCompatible(destination, owner, options = {}
2334
1998
  `Plugin skill ${owner.skill} already exists at ${destination} but has no BPMAX ownership metadata. Refusing to overwrite it; uninstall or move the existing skill first.`
2335
1999
  );
2336
2000
  }
2337
- if (existing.profile === owner.profile && existing.plugin === owner.plugin && existing.skill === owner.skill) {
2001
+ if (existing.profile === owner.profile && existing.plugin === owner.plugin && existing.skill === owner.skill && (!existing.origin || !owner.origin || existing.origin === owner.origin)) {
2338
2002
  return;
2339
2003
  }
2340
2004
  throw new Error(
@@ -2346,6 +2010,7 @@ async function writeSkillInstallOwner(destination, owner) {
2346
2010
  return;
2347
2011
  }
2348
2012
  await writeFile2(path2.join(destination, ".bpmax-skill-install.json"), JSON.stringify(owner, null, 2), "utf8");
2013
+ await writeFile2(path2.join(destination, ".bpmax-plugin-skill.json"), JSON.stringify(owner, null, 2), "utf8");
2349
2014
  }
2350
2015
  async function installSkillDirectory(skillDir, skillName, agent, options = {}) {
2351
2016
  if (agent === "openclaw") {
@@ -2353,17 +2018,24 @@ async function installSkillDirectory(skillDir, skillName, agent, options = {}) {
2353
2018
  const destination2 = path2.join(fallbackRoot, skillName);
2354
2019
  const executable = await findOpenClawCli();
2355
2020
  if (executable) {
2356
- await assertPluginSkillOwnerCompatible(destination2, options.owner, { allowUnownedExisting: true });
2021
+ await assertPluginSkillOwnerCompatible(destination2, options.owner, {
2022
+ allowUnownedExisting: options.allowUnownedExisting
2023
+ });
2357
2024
  await writeSkillInstallOwner(skillDir, options.owner);
2358
2025
  const result = await runCommand(executable, ["skills", "install", "--file-path", skillDir], {
2359
2026
  timeoutMs: 2 * 60 * 1e3
2360
2027
  });
2361
2028
  if (result.exitCode === 0) {
2362
- return skillDir;
2029
+ const installedOwner = await readSkillInstallOwner(destination2);
2030
+ if (!options.owner || installedOwner?.profile === options.owner.profile && installedOwner.plugin === options.owner.plugin && installedOwner.skill === options.owner.skill && installedOwner.origin === options.owner.origin) {
2031
+ return destination2;
2032
+ }
2363
2033
  }
2364
2034
  }
2365
2035
  await mkdir2(fallbackRoot, { recursive: true });
2366
- await assertPluginSkillOwnerCompatible(destination2, options.owner);
2036
+ await assertPluginSkillOwnerCompatible(destination2, options.owner, {
2037
+ allowUnownedExisting: options.allowUnownedExisting
2038
+ });
2367
2039
  await rm(destination2, { recursive: true, force: true });
2368
2040
  await cp(skillDir, destination2, { recursive: true });
2369
2041
  await writeSkillInstallOwner(destination2, options.owner);
@@ -2372,7 +2044,9 @@ async function installSkillDirectory(skillDir, skillName, agent, options = {}) {
2372
2044
  const root = directoryTargets[agent] || directoryTargets.generic;
2373
2045
  const destination = path2.join(root, skillName);
2374
2046
  await mkdir2(root, { recursive: true });
2375
- await assertPluginSkillOwnerCompatible(destination, options.owner);
2047
+ await assertPluginSkillOwnerCompatible(destination, options.owner, {
2048
+ allowUnownedExisting: options.allowUnownedExisting
2049
+ });
2376
2050
  await rm(destination, { recursive: true, force: true });
2377
2051
  await cp(skillDir, destination, { recursive: true });
2378
2052
  await writeSkillInstallOwner(destination, options.owner);
@@ -2386,7 +2060,7 @@ function resolveDownloadUrl(profile, url) {
2386
2060
  }
2387
2061
  async function downloadBusinessSkillPackage(profile, download) {
2388
2062
  const buffer = download.content_base64 ? Buffer.from(download.content_base64, "base64") : Buffer.from(
2389
- (await axios4.get(resolveDownloadUrl(profile, download.url), {
2063
+ (await axios3.get(resolveDownloadUrl(profile, download.url), {
2390
2064
  responseType: "arraybuffer"
2391
2065
  })).data
2392
2066
  );
@@ -2453,1316 +2127,2094 @@ async function buildCatalogSkill(skills) {
2453
2127
  };
2454
2128
  }
2455
2129
 
2456
- // src/commands/bbs.ts
2457
- async function zipPayload(zipPath) {
2458
- const buffer = await readFile5(zipPath);
2459
- return {
2460
- zip_base64: buffer.toString("base64"),
2461
- file_name: basename(zipPath)
2462
- };
2130
+ // src/core/skills.ts
2131
+ import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
2132
+ import path3 from "path";
2133
+ import { fileURLToPath } from "url";
2134
+ var SKILLS_STAMP_FILE = "skills.stamp";
2135
+ var SKILLS_INSTALL_TIMEOUT_MS = 2 * 60 * 1e3;
2136
+ function skillsStampValue(version, agent) {
2137
+ return agent ? `${version}:${agent}` : version;
2463
2138
  }
2464
- function defaultAgent(options) {
2465
- return options.agent || process.env.BPMAX_CLI_AGENT || "openclaw";
2139
+ function stampPath(configDir = getConfigDir()) {
2140
+ return path3.join(configDir, SKILLS_STAMP_FILE);
2466
2141
  }
2467
- function assertLintPassed(report, allowLintErrors) {
2468
- if (!report.ok && !allowLintErrors) {
2469
- throw new Error(`BBS lint failed:
2470
- - ${report.errors.map((item) => item.message).join("\n- ")}`);
2142
+ async function readSkillsStamp(configDir = getConfigDir()) {
2143
+ try {
2144
+ return (await readFile5(stampPath(configDir), "utf8")).trim();
2145
+ } catch {
2146
+ return "";
2471
2147
  }
2472
2148
  }
2473
- async function readJsonSummary(input) {
2474
- if (!input) {
2475
- return void 0;
2149
+ async function writeSkillsStamp(version, configDir = getConfigDir(), agent) {
2150
+ await mkdir3(configDir, { recursive: true });
2151
+ await writeFile3(stampPath(configDir), skillsStampValue(version, agent), "utf8");
2152
+ }
2153
+ async function checkSkillsSync(currentVersion, configDir = getConfigDir(), agent) {
2154
+ const target = skillsStampValue(currentVersion, agent);
2155
+ if (process.env.BPMAX_CLI_NO_SKILLS_NOTIFIER) {
2156
+ return { current: target, target, inSync: true };
2476
2157
  }
2477
- return redactAuditValue(await parseJsonInput(input, "BBS invocation JSON"));
2158
+ const current = await readSkillsStamp(configDir);
2159
+ return { current, target, inSync: current === target };
2478
2160
  }
2479
- function registerBbsCommands(program2) {
2480
- const bbs = program2.command("bbs").description("Manage BPMAX Business Skills");
2481
- const invocation = bbs.command("invocation").description("Record BBS business invocation audit logs");
2482
- invocation.command("start").description("Start a BBS business invocation audit log").requiredOption("--skill-key <key>", "BBS key").requiredOption("--action <action>", "BBS business action").option("--skill-name <name>", "BBS display name").option("--skill-version <version>", "BBS version").option("--source <source>", "Invocation source", "manual").option("--args <jsonOrFile>", "Invocation args JSON or @file.json").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
2483
- const profile = resolveProfile(await loadConfig(), options.profile);
2484
- const client = createApiClient(profile);
2485
- await ensureTerminalRegistered(client, profile);
2486
- const result = await apiRequest(
2487
- client,
2488
- "POST",
2489
- "/cli/bbs_invocations/start",
2490
- {
2491
- data: {
2492
- bbs_key: options.skillKey,
2493
- bbs_name: options.skillName || "",
2494
- bbs_version: options.skillVersion || "",
2495
- action: options.action,
2496
- source: options.source || "manual",
2497
- workspace: profile.config.workspace,
2498
- request_id: randomUUID2(),
2499
- args_summary: await readJsonSummary(options.args)
2500
- }
2501
- }
2502
- );
2503
- printResult(options.format, result);
2161
+ async function resolvePackageRootFrom(entrypointPath) {
2162
+ const entryDir = path3.dirname(entrypointPath);
2163
+ if (path3.basename(entryDir) === "dist") {
2164
+ return path3.dirname(entryDir);
2165
+ }
2166
+ if (path3.basename(entryDir) === "core" && path3.basename(path3.dirname(entryDir)) === "src") {
2167
+ return path3.dirname(path3.dirname(entryDir));
2168
+ }
2169
+ return path3.resolve(entryDir, "..", "..");
2170
+ }
2171
+ async function defaultPackageRoot() {
2172
+ return resolvePackageRootFrom(fileURLToPath(import.meta.url));
2173
+ }
2174
+ async function runSkillsInstall(options = {}) {
2175
+ const runner = options.runner || runCommand;
2176
+ const packageRoot = options.packageRoot || await defaultPackageRoot();
2177
+ const args = [path3.join(packageRoot, "scripts", "install-skills.mjs")];
2178
+ if (options.agent) {
2179
+ args.push("--json", "--agent", options.agent);
2180
+ }
2181
+ return runner(process.execPath, args, {
2182
+ timeoutMs: SKILLS_INSTALL_TIMEOUT_MS
2504
2183
  });
2505
- invocation.command("finish").description("Finish a BBS business invocation audit log").requiredOption("--audit-id <id>", "BBS invocation audit id").requiredOption("--status <status>", "Invocation status: success, failed, or blocked").option("--result <jsonOrFile>", "Invocation result JSON or @file.json").option("--error <text>", "Invocation error summary").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
2506
- if (!["success", "failed", "blocked"].includes(options.status)) {
2507
- throw new Error("status must be success, failed, or blocked.");
2184
+ }
2185
+ async function syncSkills(version, options = {}) {
2186
+ if (!options.force) {
2187
+ const status = await checkSkillsSync(version, options.configDir, options.agent);
2188
+ if (status.inSync) {
2189
+ return { action: "in_sync" };
2508
2190
  }
2509
- const profile = resolveProfile(await loadConfig(), options.profile);
2510
- const client = createApiClient(profile);
2511
- await ensureTerminalRegistered(client, profile);
2512
- const result = await apiRequest(
2513
- client,
2514
- "POST",
2515
- "/cli/bbs_invocations/finish",
2516
- {
2517
- data: {
2518
- audit_id: options.auditId,
2519
- status: options.status,
2520
- result_summary: await readJsonSummary(options.result),
2521
- error_summary: redactAuditValue(options.error || "")
2522
- }
2523
- }
2524
- );
2525
- printResult(options.format, result);
2526
- });
2527
- bbs.command("list").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2528
- const profile = resolveProfile(await loadConfig(), options.profile);
2529
- const result = await apiRequest(createApiClient(profile), "GET", "/business_skill");
2530
- printResult(options.format, result);
2531
- });
2532
- bbs.command("show <keyOrId>").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
2533
- const profile = resolveProfile(await loadConfig(), options.profile);
2534
- const result = await fetchBusinessSkillByKeyOrId(createApiClient(profile), keyOrId);
2535
- printResult(options.format, result);
2536
- });
2537
- bbs.command("lint").requiredOption("--zip <path>", "Skill zip path").option("--format <format>", "Output format", "json").action(async (options) => {
2538
- const report = await lintBusinessSkillZip(options.zip);
2539
- printResult(options.format, report);
2540
- });
2541
- bbs.command("create").requiredOption("--zip <path>", "Skill zip path").option("--name <name>", "BBS display name").option("--key <key>", "BBS key").option("--scene <scene>", "BBS scene").option("--description <description>", "BBS description").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2542
- const lintReport2 = await lintBusinessSkillZip(options.zip);
2543
- assertLintPassed(lintReport2, options.allowLintErrors);
2544
- const profile = resolveProfile(await loadConfig(), options.profile);
2545
- const data = {
2546
- ...await zipPayload(options.zip),
2547
- name: options.name,
2548
- key: options.key,
2549
- scene: options.scene,
2550
- description: options.description
2551
- };
2552
- const result = await apiRequest(createApiClient(profile), "POST", "/business_skill", { data });
2553
- printResult(options.format, {
2554
- ...typeof result === "object" && result !== null ? result : { result },
2555
- lint_report: lintReport2,
2556
- ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
2557
- });
2558
- });
2559
- bbs.command("upgrade <keyOrId>").requiredOption("--zip <path>", "Skill zip path").option("--release-note <text>", "Release note").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
2560
- const profile = resolveProfile(await loadConfig(), options.profile);
2561
- const client = createApiClient(profile);
2562
- const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
2563
- const lintReport2 = await lintBusinessSkillZip(options.zip, { latestVersion: skill.latest_version });
2564
- assertLintPassed(lintReport2, options.allowLintErrors);
2565
- const data = {
2566
- ...await zipPayload(options.zip),
2567
- release_note: options.releaseNote
2568
- };
2569
- const result = await apiRequest(client, "POST", `/business_skill/${skill.id}/versions`, { data });
2570
- printResult(options.format, {
2571
- ...typeof result === "object" && result !== null ? result : { result },
2572
- lint_report: lintReport2,
2573
- ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
2574
- });
2191
+ }
2192
+ const result = await runSkillsInstall({ packageRoot: options.packageRoot, runner: options.runner, agent: options.agent });
2193
+ if (result.exitCode === 0) {
2194
+ await writeSkillsStamp(version, options.configDir, options.agent);
2195
+ return { action: "synced", result };
2196
+ }
2197
+ return { action: "failed", result };
2198
+ }
2199
+
2200
+ // src/core/plugin-skills.ts
2201
+ var allowedTopLevelFiles = /* @__PURE__ */ new Set(["SKILL.md"]);
2202
+ var allowedTopLevelDirs = /* @__PURE__ */ new Set(["references", "scripts", "assets", "agents", "lint", "config"]);
2203
+ var allowedAgentsFiles = /* @__PURE__ */ new Set(["openai.yaml"]);
2204
+ var semverPattern2 = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
2205
+ var safeSkillNamePattern = /^bpmax-[A-Za-z0-9][A-Za-z0-9_-]*$/;
2206
+ var safePathSegmentPattern = /^[A-Za-z0-9_.:-]+$/;
2207
+ var pluginSkillCheckMaxAgeMs = 6 * 60 * 60 * 1e3;
2208
+ var pluginSkillMetadataFiles = /* @__PURE__ */ new Set([".bpmax-plugin-skill.json", ".bpmax-skill-install.json"]);
2209
+ function issue2(severity, code, message) {
2210
+ return { severity, code, message };
2211
+ }
2212
+ async function exists2(targetPath) {
2213
+ try {
2214
+ await stat3(targetPath);
2215
+ return true;
2216
+ } catch {
2217
+ return false;
2218
+ }
2219
+ }
2220
+ function parseFrontmatter2(markdown) {
2221
+ const match = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---/);
2222
+ if (!match) {
2223
+ return {};
2224
+ }
2225
+ const result = {};
2226
+ match[1].split(/\r?\n/).forEach((line) => {
2227
+ const item = line.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
2228
+ if (!item) {
2229
+ return;
2230
+ }
2231
+ result[item[1]] = item[2].trim().replace(/^['"]|['"]$/g, "");
2575
2232
  });
2576
- bbs.command("gate <keyOrId>").requiredOption("--stage <stage>", "Gate stage, for example preflight or verify").requiredOption("--input <json>", "Gate input JSON or @file").option("--skill-dir <path>", "Installed skill directory override").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
2577
- const profile = resolveProfile(await loadConfig(), options.profile);
2578
- const agent = defaultAgent(options);
2579
- const input = await parseJsonInput(options.input, "Gate input");
2580
- let skillDir = options.skillDir;
2581
- if (!skillDir) {
2582
- const state = await readBusinessSkillState(profile.name, agent);
2583
- const installed = state.skills[keyOrId];
2584
- if (!installed) {
2585
- throw new Error(`BBS ${keyOrId} is not installed for agent ${agent}. Run: bpmax-cli bbs ensure ${keyOrId} --agent ${agent}`);
2233
+ return result;
2234
+ }
2235
+ function completeReport2(report) {
2236
+ const errors = report.issues.filter((item) => item.severity === "error");
2237
+ const warnings = report.issues.filter((item) => item.severity === "warning");
2238
+ return {
2239
+ ok: errors.length === 0,
2240
+ errors,
2241
+ warnings,
2242
+ checks: report.checks,
2243
+ manifest: report.manifest,
2244
+ skill_dir: report.skill_dir
2245
+ };
2246
+ }
2247
+ async function listCoreSkillNames() {
2248
+ const packageRoot = await resolvePackageRootFrom(fileURLToPath2(import.meta.url));
2249
+ const roots = [path4.join(packageRoot, "skills")];
2250
+ const names = /* @__PURE__ */ new Set();
2251
+ for (const root of roots) {
2252
+ let entries;
2253
+ try {
2254
+ entries = await readdir(root, { withFileTypes: true });
2255
+ } catch {
2256
+ continue;
2257
+ }
2258
+ for (const entry of entries) {
2259
+ if (!entry.isDirectory()) {
2260
+ continue;
2261
+ }
2262
+ if (await exists2(path4.join(root, entry.name, "SKILL.md"))) {
2263
+ names.add(entry.name);
2586
2264
  }
2587
- skillDir = installed.install_path;
2588
2265
  }
2589
- const projectId = input.project_id;
2590
- const projectUrl = typeof projectId === "number" || typeof projectId === "string" ? buildBpmaxUrl(profile, "project-detail", { projectId: String(projectId) }).url : void 0;
2591
- const report = await runBusinessSkillGate({
2592
- skill: keyOrId,
2593
- stage: options.stage,
2594
- skillDir,
2595
- input,
2596
- projectUrl
2597
- });
2598
- if (!report.ok) {
2599
- throw new Error(`BBS gate failed:
2600
- - ${report.errors.map((item) => item.message).join("\n- ")}`);
2266
+ }
2267
+ return names;
2268
+ }
2269
+ async function collectRelativeFiles(root, dir = "") {
2270
+ const absolute = path4.join(root, dir);
2271
+ const entries = await readdir(absolute, { withFileTypes: true });
2272
+ const files = [];
2273
+ for (const entry of entries) {
2274
+ const relative = path4.posix.join(dir.replace(/\\/g, "/"), entry.name);
2275
+ if (entry.isDirectory()) {
2276
+ files.push(...await collectRelativeFiles(root, relative));
2277
+ } else {
2278
+ files.push(relative);
2601
2279
  }
2602
- printResult(options.format, report);
2603
- });
2604
- bbs.command("sync").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2605
- const profile = resolveProfile(await loadConfig(), options.profile);
2606
- const agent = defaultAgent(options);
2607
- const result = await apiRequest(
2608
- createApiClient(profile),
2609
- "GET",
2610
- "/business_skill",
2611
- { params: { page_size: 1e3 } }
2612
- );
2613
- const skills = Array.isArray(result) ? result : result.data || [];
2614
- const catalog = await buildCatalogSkill(skills);
2615
- const installPath = await installSkillDirectory(catalog.dir, "bpmax-business-skill-catalog", agent);
2616
- await updateBusinessSkillState(profile.name, agent, (state) => {
2617
- state.catalog = {
2618
- checksum: catalog.checksum,
2619
- install_path: installPath,
2620
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
2621
- };
2622
- });
2623
- printResult(options.format, {
2624
- action: "synced",
2625
- agent,
2626
- installed: "bpmax-business-skill-catalog",
2627
- install_path: installPath,
2628
- skills_count: skills.length
2629
- });
2280
+ }
2281
+ return files;
2282
+ }
2283
+ async function hashSkillDirectory(root) {
2284
+ if (!await exists2(root)) {
2285
+ return void 0;
2286
+ }
2287
+ const files = (await collectRelativeFiles(root)).filter((file) => !pluginSkillMetadataFiles.has(file)).sort();
2288
+ const hash = createHash3("sha256");
2289
+ for (const file of files) {
2290
+ hash.update(file);
2291
+ hash.update("\0");
2292
+ hash.update(await readFile6(path4.join(root, file)));
2293
+ hash.update("\0");
2294
+ }
2295
+ return hash.digest("hex");
2296
+ }
2297
+ function validateAllowedPath(relative) {
2298
+ const normalized = relative.replace(/\\/g, "/");
2299
+ const parts = normalized.split("/");
2300
+ if (normalized.startsWith("/") || path4.isAbsolute(normalized) || parts.some((part) => part === "" || part === "." || part === "..")) {
2301
+ return issue2("error", "unsafe_path", `Plugin skill contains unsafe path: ${relative}`);
2302
+ }
2303
+ if (parts.length === 1) {
2304
+ if (!allowedTopLevelFiles.has(parts[0])) {
2305
+ return issue2("error", "disallowed_top_level_file", `Plugin skill top-level file is not allowed: ${relative}`);
2306
+ }
2307
+ return void 0;
2308
+ }
2309
+ const top = parts[0];
2310
+ if (!allowedTopLevelDirs.has(top)) {
2311
+ return issue2("error", "disallowed_top_level_dir", `Plugin skill top-level directory is not allowed: ${top}`);
2312
+ }
2313
+ if (top === "agents" && (parts.length !== 2 || !allowedAgentsFiles.has(parts[1]))) {
2314
+ return issue2("error", "disallowed_agents_file", `Plugin skill agents/ may only contain openai.yaml: ${relative}`);
2315
+ }
2316
+ if (top === "lint" && (parts.length !== 2 || !parts[1].endsWith(".json"))) {
2317
+ return issue2("error", "disallowed_lint_file", `Plugin skill lint/ may only contain JSON files: ${relative}`);
2318
+ }
2319
+ if (top === "config" && (parts.length !== 2 || !parts[1].endsWith(".json"))) {
2320
+ return issue2("error", "disallowed_config_file", `Plugin skill config/ may only contain JSON files: ${relative}`);
2321
+ }
2322
+ return void 0;
2323
+ }
2324
+ function validateSafeSkillName(name, issues, context = "Plugin skill") {
2325
+ if (!safeSkillNamePattern.test(name)) {
2326
+ issues.push(issue2("error", "invalid_name", `${context} name must match ${safeSkillNamePattern.source}: ${name}`));
2327
+ }
2328
+ }
2329
+ function assertSafeStateSegment(value, label) {
2330
+ if (!value || value.includes("/") || value.includes("\\") || value === "." || value === ".." || !safePathSegmentPattern.test(value)) {
2331
+ throw new Error(`Unsafe plugin skill state ${label}: ${value}`);
2332
+ }
2333
+ }
2334
+ async function assertInstallablePluginSkillName(name) {
2335
+ if (!safeSkillNamePattern.test(name)) {
2336
+ throw new Error(`Plugin skill name must match ${safeSkillNamePattern.source}: ${name}`);
2337
+ }
2338
+ const coreSkillNames = await listCoreSkillNames();
2339
+ if (coreSkillNames.has(name)) {
2340
+ throw new Error(`Plugin skill must not overwrite built-in/core skill: ${name}`);
2341
+ }
2342
+ }
2343
+ async function installProfilePluginSkillDirectory(skillDir, profileName, agent, skillName) {
2344
+ assertSafeStateSegment(profileName, "profile");
2345
+ assertSafeStateSegment(agent, "agent");
2346
+ if (!safeSkillNamePattern.test(skillName)) {
2347
+ throw new Error(`Plugin skill name must match ${safeSkillNamePattern.source}: ${skillName}`);
2348
+ }
2349
+ const destination = path4.join(getConfigDir(), "plugin-skills", profileName, agent, "installed", skillName);
2350
+ await copySkillDirectory(skillDir, destination);
2351
+ return destination;
2352
+ }
2353
+ function normalizePluginLintManifests(value) {
2354
+ if (!Array.isArray(value)) {
2355
+ return [];
2356
+ }
2357
+ return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item)).map((item) => ({
2358
+ domain: typeof item.domain === "string" ? item.domain : "",
2359
+ plugin_key: typeof item.plugin_key === "string" ? item.plugin_key : "",
2360
+ path: typeof item.path === "string" ? item.path.replace(/\\/g, "/") : "",
2361
+ version: typeof item.version === "string" || typeof item.version === "number" ? item.version : void 0,
2362
+ paths: Array.isArray(item.paths) ? item.paths.filter((pathItem) => typeof pathItem === "string" && Boolean(pathItem.trim())).map((pathItem) => pathItem.replace(/\\/g, "/")) : void 0
2363
+ })).filter((item) => item.domain && item.plugin_key && item.path);
2364
+ }
2365
+ function normalizePluginConfigAdapterManifests(value) {
2366
+ if (!Array.isArray(value)) {
2367
+ return [];
2368
+ }
2369
+ return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item)).map((item) => ({
2370
+ domain: typeof item.domain === "string" ? item.domain : "",
2371
+ plugin_key: typeof item.plugin_key === "string" ? item.plugin_key : "",
2372
+ capability_prefix: typeof item.capability_prefix === "string" ? item.capability_prefix : "",
2373
+ adapter: typeof item.adapter === "string" ? item.adapter.replace(/\\/g, "/") : "",
2374
+ version: typeof item.version === "string" || typeof item.version === "number" ? item.version : void 0
2375
+ })).filter((item) => item.domain && item.plugin_key && item.capability_prefix && item.adapter);
2376
+ }
2377
+ function validatePluginConfigAdapterManifest(item, issues, context) {
2378
+ if (!/^[a-z][a-z0-9-]*$/.test(item.domain)) {
2379
+ issues.push(issue2("error", "invalid_config_adapter_domain", `${context} config adapter domain must be kebab-case.`));
2380
+ }
2381
+ if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
2382
+ issues.push(issue2("error", "invalid_config_adapter_plugin_key", `${context} config adapter plugin_key must look like plugin_xxx.`));
2383
+ }
2384
+ if (!item.capability_prefix.startsWith(`config.plugin.${item.plugin_key}.`)) {
2385
+ issues.push(issue2("error", "invalid_config_adapter_capability", `${context} config adapter capability_prefix must start with config.plugin.${item.plugin_key}.`));
2386
+ }
2387
+ const normalized = item.adapter.replace(/\\/g, "/");
2388
+ const parts = normalized.split("/");
2389
+ if (!normalized.startsWith("config/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
2390
+ issues.push(issue2("error", "invalid_config_adapter_path", `${context} config adapter path must be a config/*.json file.`));
2391
+ }
2392
+ }
2393
+ function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, allowedMethods, issues, context) {
2394
+ const endpoint = endpoints[operation];
2395
+ if (endpoint === void 0) return;
2396
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint)) {
2397
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must be an object.`));
2398
+ return;
2399
+ }
2400
+ const value = endpoint;
2401
+ const method = typeof value.method === "string" ? value.method : allowedMethods[0];
2402
+ if (!allowedMethods.includes(method)) {
2403
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} method must be ${allowedMethods.join(" or ")}.`));
2404
+ }
2405
+ const endpointPath2 = typeof value.path === "string" ? value.path : "";
2406
+ const variants = [endpointPath2];
2407
+ let current = endpointPath2;
2408
+ for (let i = 0; i < 3; i += 1) {
2409
+ try {
2410
+ const decoded = decodeURIComponent(current);
2411
+ if (decoded === current) break;
2412
+ variants.push(decoded);
2413
+ current = decoded;
2414
+ } catch {
2415
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains malformed URL encoding.`));
2416
+ return;
2417
+ }
2418
+ }
2419
+ const hasUnsafePath = variants.some((variant) => {
2420
+ const endpointParts = variant.split("/");
2421
+ return !variant.startsWith("/") || variant.includes("\\") || /%(?:2e|2f|5c)/i.test(variant) || endpointParts.some((part) => part === "." || part === "..");
2630
2422
  });
2631
- async function ensureSkill(keyOrId, options) {
2632
- const profile = resolveProfile(await loadConfig(), options.profile);
2633
- const agent = defaultAgent(options);
2634
- const client = createApiClient(profile);
2635
- const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
2636
- const state = await readBusinessSkillState(profile.name, agent);
2637
- const installed = state.skills[skill.key];
2638
- if (!options.force && installed?.version === skill.latest_version) {
2639
- printResult(options.format, { action: "in_sync", agent, skill: skill.key, version: installed.version });
2423
+ if (hasUnsafePath) {
2424
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains an unsafe path.`));
2425
+ return;
2426
+ }
2427
+ const expectedPrefix = `/${pluginKey}`;
2428
+ if (!endpointPath2 || variants.some((variant) => !variant.startsWith(`${expectedPrefix}/`) && variant !== expectedPrefix)) {
2429
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must stay under ${expectedPrefix}.`));
2430
+ }
2431
+ }
2432
+ function validatePluginConfigAdapterEndpoints(endpoints, pluginKey, issues, context) {
2433
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "list", ["GET"], issues, context);
2434
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "get", ["GET"], issues, context);
2435
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "create", ["POST"], issues, context);
2436
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "update", ["PUT"], issues, context);
2437
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "test", ["POST"], issues, context);
2438
+ }
2439
+ async function validatePluginConfigAdapterFile(skillDir, item, issues, context) {
2440
+ const adapterFile = path4.join(skillDir, item.adapter);
2441
+ if (!await exists2(adapterFile)) {
2442
+ issues.push(issue2("error", "missing_config_adapter_file", `${context} config adapter file not found: ${item.adapter}`));
2443
+ return;
2444
+ }
2445
+ try {
2446
+ const parsed = JSON.parse(await readFile6(adapterFile, "utf8"));
2447
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || parsed.version !== 1 || parsed.domain !== item.domain || parsed.plugin_key !== item.plugin_key || parsed.capability_prefix !== item.capability_prefix || !parsed.endpoints || typeof parsed.endpoints !== "object" || Array.isArray(parsed.endpoints)) {
2448
+ issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must match manifest and declare endpoints: ${item.adapter}`));
2640
2449
  return;
2641
2450
  }
2642
- const download = await apiRequest(
2643
- client,
2644
- "GET",
2645
- `/business_skill/${skill.id}/download`,
2646
- { params: skill.latest_version ? { version: skill.latest_version } : void 0 }
2647
- );
2648
- const buffer = await downloadBusinessSkillPackage(profile, download);
2649
- const skillDir = await zipDirectoryToTemp(buffer, `bbs-${skill.key}`);
2650
- const installPath = await installSkillDirectory(skillDir, skill.key, agent);
2651
- await updateBusinessSkillState(profile.name, agent, (current) => {
2652
- current.skills[skill.key] = {
2653
- id: skill.id,
2654
- key: skill.key,
2655
- name: skill.name,
2656
- version: download.version,
2657
- checksum: download.checksum,
2658
- install_path: installPath,
2659
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
2660
- };
2661
- });
2662
- await apiRequest(client, "POST", "/business_skill/install_record", {
2663
- data: {
2664
- skill_id: skill.id,
2665
- version_id: download.version_id,
2666
- version: download.version,
2667
- agent,
2668
- action: installed ? "update" : options.action || "install",
2669
- status: "success",
2670
- cli_version: VERSION,
2671
- install_path: installPath
2451
+ validatePluginConfigAdapterEndpoints(parsed.endpoints, item.plugin_key, issues, context);
2452
+ const capabilities = parsed.capabilities;
2453
+ if (capabilities !== void 0) {
2454
+ if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
2455
+ issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must be an object: ${item.adapter}`));
2456
+ return;
2457
+ }
2458
+ for (const value of Object.values(capabilities)) {
2459
+ if (typeof value !== "string" || !value.startsWith(`config.plugin.${item.plugin_key}.`)) {
2460
+ issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must stay under config.plugin.${item.plugin_key}.`));
2461
+ return;
2462
+ }
2463
+ }
2464
+ }
2465
+ const work = parsed.work;
2466
+ if (work !== void 0) {
2467
+ if (!work || typeof work !== "object" || Array.isArray(work)) {
2468
+ issues.push(issue2("error", "invalid_config_adapter_work", `${context} config adapter work must be an object: ${item.adapter}`));
2469
+ return;
2470
+ }
2471
+ const lintPath = work.lint;
2472
+ if (lintPath !== void 0) {
2473
+ if (typeof lintPath !== "string") {
2474
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2475
+ return;
2476
+ }
2477
+ const normalizedLintPath = lintPath.replace(/\\/g, "/");
2478
+ const lintParts = normalizedLintPath.split("/");
2479
+ if (!normalizedLintPath.startsWith("lint/") || lintParts.some((part) => part === "" || part === "." || part === "..") || normalizedLintPath.startsWith("/") || path4.isAbsolute(normalizedLintPath) || !normalizedLintPath.endsWith(".json")) {
2480
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2481
+ return;
2482
+ }
2483
+ const lintFile = path4.join(skillDir, normalizedLintPath);
2484
+ if (!await exists2(lintFile)) {
2485
+ issues.push(issue2("error", "missing_config_adapter_lint", `${context} config adapter lint file not found: ${normalizedLintPath}`));
2486
+ return;
2487
+ }
2488
+ const lint = JSON.parse(await readFile6(lintFile, "utf8"));
2489
+ if (!lint || typeof lint !== "object" || Array.isArray(lint) || lint.version !== 1 || lint.domain !== item.domain || lint.plugin_key !== item.plugin_key || !Array.isArray(lint.rules) || !lint.rules.length) {
2490
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter lint file must match adapter manifest and declare rules: ${normalizedLintPath}`));
2491
+ return;
2492
+ }
2493
+ }
2494
+ }
2495
+ } catch (error) {
2496
+ issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must be valid JSON: ${item.adapter}`));
2497
+ }
2498
+ }
2499
+ function validatePluginLintManifest(item, issues, context) {
2500
+ if (item.domain !== "flow-template-node") {
2501
+ issues.push(issue2("error", "unsupported_lint_domain", `${context} lint domain is not supported: ${item.domain}`));
2502
+ }
2503
+ if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
2504
+ issues.push(issue2("error", "invalid_lint_plugin_key", `${context} lint plugin_key must look like plugin_xxx.`));
2505
+ }
2506
+ const normalized = item.path.replace(/\\/g, "/");
2507
+ const parts = normalized.split("/");
2508
+ if (!normalized.startsWith("lint/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
2509
+ issues.push(issue2("error", "invalid_lint_path", `${context} lint path must be a lint/*.json file.`));
2510
+ }
2511
+ if (item.paths) {
2512
+ item.paths.forEach((scanPath) => {
2513
+ if (!isAllowedPluginConfigScanPath(scanPath)) {
2514
+ issues.push(issue2("error", "invalid_lint_scan_path", `${context} lint scan path is not supported: ${scanPath}`));
2672
2515
  }
2673
- });
2674
- printResult(options.format, {
2675
- action: installed ? "updated" : "installed",
2676
- agent,
2677
- skill: skill.key,
2678
- version: download.version,
2679
- install_path: installPath
2680
2516
  });
2681
2517
  }
2682
- bbs.command("ensure <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
2683
- (keyOrId, options) => ensureSkill(keyOrId, options)
2684
- );
2685
- bbs.command("install <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
2686
- (keyOrId, options) => ensureSkill(keyOrId, { ...options, force: true, action: "install" })
2687
- );
2688
- bbs.command("update <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
2689
- (keyOrId, options) => ensureSkill(keyOrId, { ...options, force: true, action: "update" })
2690
- );
2691
- bbs.command("uninstall <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
2692
- const profile = resolveProfile(await loadConfig(), options.profile);
2693
- const agent = defaultAgent(options);
2694
- const client = createApiClient(profile);
2695
- const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
2696
- const state = await readBusinessSkillState(profile.name, agent);
2697
- const installed = state.skills[skill.key];
2698
- if (installed) {
2699
- const { rm: rm5 } = await import("fs/promises");
2700
- await rm5(installed.install_path, { recursive: true, force: true });
2701
- await updateBusinessSkillState(profile.name, agent, (current) => {
2702
- delete current.skills[skill.key];
2703
- });
2518
+ }
2519
+ function isAllowedPluginConfigScanPath(scanPath) {
2520
+ return scanPath === "data.meta.<plugin_key>" || scanPath === "data.nodes[].<plugin_key>" || /^data\.nodes\[\]\.<plugin_key>\.[A-Za-z0-9_]+\[\]$/.test(scanPath) || /^data\.nodes\[\]\.[A-Za-z0-9_]+_(?:triggers|configs|plugins)\[\]$/.test(scanPath);
2521
+ }
2522
+ async function validatePluginLintRuleFiles(skillDir, files, issues) {
2523
+ for (const file of files) {
2524
+ if (!file.startsWith("lint/") && !file.startsWith("config/") || !file.endsWith(".json")) {
2525
+ continue;
2704
2526
  }
2705
- await apiRequest(client, "POST", "/business_skill/install_record", {
2706
- data: {
2707
- skill_id: skill.id,
2708
- version: installed?.version || "",
2709
- agent,
2710
- action: "uninstall",
2711
- status: "success",
2712
- cli_version: VERSION,
2713
- install_path: installed?.install_path || ""
2527
+ try {
2528
+ const parsed = JSON.parse(await readFile6(path4.join(skillDir, file), "utf8"));
2529
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2530
+ issues.push(issue2("error", "invalid_plugin_json_file", `${file} must contain a declarative JSON object.`));
2531
+ continue;
2714
2532
  }
2715
- });
2716
- printResult(options.format, { action: "uninstalled", agent, skill: skill.key });
2717
- });
2533
+ if (file.startsWith("lint/") && (!Array.isArray(parsed.rules) || !parsed.rules.length)) {
2534
+ issues.push(issue2("error", "empty_lint_rules", `${file} must contain a non-empty rules array.`));
2535
+ }
2536
+ } catch (error) {
2537
+ issues.push(issue2("error", "invalid_plugin_json_file", `${file} must be valid JSON.`));
2538
+ }
2539
+ }
2718
2540
  }
2719
-
2720
- // src/commands/capabilities.ts
2721
- function registerCapabilitiesCommands(program2) {
2722
- const capabilities = program2.command("capabilities").description("Inspect bpmax-cli server capability whitelist");
2723
- capabilities.command("status").description("Show cached server capabilities for a profile").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2724
- const profile = resolveProfile(await loadConfig(), options.profile);
2725
- printResult(options.format, {
2726
- profile: profile.name,
2727
- origin: profile.config.origin,
2728
- workspace: profile.config.workspace,
2729
- capabilities_cache: profile.config.capabilities_cache || null
2730
- });
2731
- });
2732
- capabilities.command("refresh").description("Refresh server capabilities for a profile").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2733
- const profile = resolveProfile(await loadConfig(), options.profile);
2734
- const cache = await refreshCapabilities(createApiClient(profile), profile);
2735
- printResult(options.format, {
2736
- profile: profile.name,
2737
- origin: profile.config.origin,
2738
- workspace: profile.config.workspace,
2739
- capabilities_cache: cache
2740
- });
2541
+ async function lintPluginSkillDirectory(skillDir, options = {}) {
2542
+ const issues = [];
2543
+ const checks = [];
2544
+ let skillMarkdown = "";
2545
+ let manifest = {};
2546
+ try {
2547
+ skillMarkdown = await readFile6(path4.join(skillDir, "SKILL.md"), "utf8");
2548
+ manifest = parseFrontmatter2(skillMarkdown);
2549
+ } catch {
2550
+ issues.push(issue2("error", "missing_skill_md", "Plugin skill package must contain top-level SKILL.md."));
2551
+ }
2552
+ const name = manifest.name;
2553
+ const version = manifest.version;
2554
+ if (!name || typeof name !== "string") {
2555
+ issues.push(issue2("error", "missing_name", "SKILL.md frontmatter must contain name."));
2556
+ } else {
2557
+ if (!name.startsWith("bpmax-")) {
2558
+ issues.push(issue2("error", "invalid_name_prefix", "Plugin skill name must start with bpmax-."));
2559
+ }
2560
+ validateSafeSkillName(name, issues);
2561
+ if (options.expectedName && name !== options.expectedName) {
2562
+ issues.push(issue2("error", "name_mismatch", `Plugin skill name ${name} does not match expected ${options.expectedName}.`));
2563
+ }
2564
+ if (!options.allowCoreOverwrite) {
2565
+ const coreSkillNames = await listCoreSkillNames();
2566
+ if (coreSkillNames.has(name)) {
2567
+ issues.push(issue2("error", "core_skill_overwrite", `Plugin skill must not overwrite built-in/core skill: ${name}`));
2568
+ }
2569
+ }
2570
+ }
2571
+ if (!version || typeof version !== "string") {
2572
+ issues.push(issue2("error", "missing_version", "SKILL.md frontmatter must contain version."));
2573
+ } else if (!semverPattern2.test(version)) {
2574
+ issues.push(issue2("error", "invalid_version", "Plugin skill version must be semver, for example 1.0.0."));
2575
+ }
2576
+ try {
2577
+ const files = await collectRelativeFiles(skillDir);
2578
+ const invalid = files.map(validateAllowedPath).filter(Boolean);
2579
+ issues.push(...invalid);
2580
+ await validatePluginLintRuleFiles(skillDir, files, issues);
2581
+ checks.push({ name: "allowed_files", files, invalid: invalid.map((item) => item.message) });
2582
+ } catch (error) {
2583
+ issues.push(issue2("error", "read_failed", error instanceof Error ? error.message : String(error)));
2584
+ }
2585
+ [
2586
+ { pattern: /\brm\s+-rf\b/, code: "dangerous_rm_rf", message: "Dangerous rm -rf command found." },
2587
+ { pattern: /\bgit\s+reset\s+--hard\b/, code: "dangerous_git_reset", message: "Dangerous git reset --hard command found." },
2588
+ { pattern: /\bgit\s+checkout\s+--\b/, code: "dangerous_git_checkout", message: "Dangerous git checkout -- command found." },
2589
+ { pattern: /authorization\s*:\s*bearer|api[_-]?key\s*[:=]\s*['"][^'"]+/i, code: "secret_literal", message: "Possible literal credential found." },
2590
+ { pattern: /\bcurl\b[\s\S]{0,160}\b-X\s*(POST|PUT|PATCH|DELETE)\b/i, code: "raw_mutating_curl", message: "Raw mutating curl command found; use bpmax-cli wrappers." }
2591
+ ].forEach((rule) => {
2592
+ if (rule.pattern.test(skillMarkdown)) {
2593
+ issues.push(issue2("error", rule.code, rule.message));
2594
+ }
2741
2595
  });
2596
+ return completeReport2({ checks, issues, manifest, skill_dir: skillDir });
2742
2597
  }
2743
-
2744
- // src/commands/config.ts
2745
- import { text as text2 } from "@clack/prompts";
2746
- import { mkdir as mkdir8, writeFile as writeFile8 } from "fs/promises";
2747
- import path9 from "path";
2748
-
2749
- // src/core/config-workflow.ts
2750
- import { createHash as createHash4 } from "crypto";
2751
- import { mkdir as mkdir5, readdir as readdir2, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
2752
- import path5 from "path";
2753
-
2754
- // src/core/plugin-skills.ts
2755
- import { createHash as createHash3 } from "crypto";
2756
- import { cp as cp2, mkdir as mkdir4, readdir, readFile as readFile7, rm as rm2, stat as stat3, writeFile as writeFile4 } from "fs/promises";
2757
- import path4 from "path";
2758
- import { fileURLToPath as fileURLToPath2 } from "url";
2759
- import axios5 from "axios";
2760
- import JSZip2 from "jszip";
2761
-
2762
- // src/core/skills.ts
2763
- import { mkdir as mkdir3, readFile as readFile6, writeFile as writeFile3 } from "fs/promises";
2764
- import path3 from "path";
2765
- import { fileURLToPath } from "url";
2766
- var SKILLS_STAMP_FILE = "skills.stamp";
2767
- var SKILLS_INSTALL_TIMEOUT_MS = 2 * 60 * 1e3;
2768
- function skillsStampValue(version, agent) {
2769
- return agent ? `${version}:${agent}` : version;
2598
+ async function lintPluginSkillZip(zipPath, options = {}) {
2599
+ try {
2600
+ const buffer = await readFile6(zipPath);
2601
+ const dir = await zipDirectoryToTemp(buffer, "plugin-skill-lint");
2602
+ return lintPluginSkillDirectory(dir, options);
2603
+ } catch (error) {
2604
+ return completeReport2({
2605
+ checks: [],
2606
+ manifest: {},
2607
+ issues: [issue2("error", "invalid_package", error instanceof Error ? error.message : String(error))]
2608
+ });
2609
+ }
2770
2610
  }
2771
- function stampPath(configDir = getConfigDir()) {
2772
- return path3.join(configDir, SKILLS_STAMP_FILE);
2611
+ function pluginSkillStatePath(profileName, agent) {
2612
+ assertSafeStateSegment(profileName, "profile");
2613
+ assertSafeStateSegment(agent, "agent");
2614
+ return path4.join(getConfigDir(), "plugin-skills", profileName, agent, "state.json");
2773
2615
  }
2774
- async function readSkillsStamp(configDir = getConfigDir()) {
2616
+ async function readPluginSkillState(profileName, agent) {
2775
2617
  try {
2776
- return (await readFile6(stampPath(configDir), "utf8")).trim();
2618
+ return JSON.parse(await readFile6(pluginSkillStatePath(profileName, agent), "utf8"));
2777
2619
  } catch {
2778
- return "";
2620
+ return { plugins: {} };
2779
2621
  }
2780
2622
  }
2781
- async function writeSkillsStamp(version, configDir = getConfigDir(), agent) {
2782
- await mkdir3(configDir, { recursive: true });
2783
- await writeFile3(stampPath(configDir), skillsStampValue(version, agent), "utf8");
2623
+ async function writePluginSkillState(profileName, agent, state) {
2624
+ const target = pluginSkillStatePath(profileName, agent);
2625
+ await mkdir4(path4.dirname(target), { recursive: true });
2626
+ await writeFile4(target, JSON.stringify(state, null, 2), "utf8");
2784
2627
  }
2785
- async function checkSkillsSync(currentVersion, configDir = getConfigDir(), agent) {
2786
- const target = skillsStampValue(currentVersion, agent);
2787
- if (process.env.BPMAX_CLI_NO_SKILLS_NOTIFIER) {
2788
- return { current: target, target, inSync: true };
2628
+ async function acquireStateLock2(profileName, agent) {
2629
+ const target = pluginSkillStatePath(profileName, agent);
2630
+ const lockPath = `${target}.lock`;
2631
+ await mkdir4(path4.dirname(target), { recursive: true });
2632
+ for (let attempt = 0; attempt < 100; attempt += 1) {
2633
+ try {
2634
+ await mkdir4(lockPath);
2635
+ return lockPath;
2636
+ } catch (error) {
2637
+ if (error.code !== "EEXIST") {
2638
+ throw error;
2639
+ }
2640
+ await new Promise((resolve) => setTimeout(resolve, 50));
2641
+ }
2789
2642
  }
2790
- const current = await readSkillsStamp(configDir);
2791
- return { current, target, inSync: current === target };
2643
+ throw new Error(`Timed out waiting for plugin skill state lock: ${lockPath}`);
2792
2644
  }
2793
- async function resolvePackageRootFrom(entrypointPath) {
2794
- const entryDir = path3.dirname(entrypointPath);
2795
- if (path3.basename(entryDir) === "dist") {
2796
- return path3.dirname(entryDir);
2797
- }
2798
- if (path3.basename(entryDir) === "core" && path3.basename(path3.dirname(entryDir)) === "src") {
2799
- return path3.dirname(path3.dirname(entryDir));
2645
+ async function updatePluginSkillState(profileName, agent, updater) {
2646
+ const lockPath = await acquireStateLock2(profileName, agent);
2647
+ try {
2648
+ const state = await readPluginSkillState(profileName, agent);
2649
+ const next = await updater(state) ?? state;
2650
+ await writePluginSkillState(profileName, agent, next);
2651
+ return next;
2652
+ } finally {
2653
+ await rm2(lockPath, { recursive: true, force: true });
2800
2654
  }
2801
- return path3.resolve(entryDir, "..", "..");
2802
- }
2803
- async function defaultPackageRoot() {
2804
- return resolvePackageRootFrom(fileURLToPath(import.meta.url));
2805
2655
  }
2806
- async function runSkillsInstall(options = {}) {
2807
- const runner = options.runner || runCommand;
2808
- const packageRoot = options.packageRoot || await defaultPackageRoot();
2809
- const args = [path3.join(packageRoot, "scripts", "install-skills.mjs")];
2810
- if (options.agent) {
2811
- args.push("--json", "--agent", options.agent);
2656
+ function resolveDownloadUrl2(profile, url) {
2657
+ if (/^https?:\/\//i.test(url)) {
2658
+ return url;
2812
2659
  }
2813
- return runner(process.execPath, args, {
2814
- timeoutMs: SKILLS_INSTALL_TIMEOUT_MS
2815
- });
2660
+ return `${profile.config.origin.replace(/\/$/, "")}${url.startsWith("/") ? url : `/${url}`}`;
2816
2661
  }
2817
- async function syncSkills(version, options = {}) {
2818
- if (!options.force) {
2819
- const status = await checkSkillsSync(version, options.configDir, options.agent);
2820
- if (status.inSync) {
2821
- return { action: "in_sync" };
2662
+ async function downloadPluginSkillPackage(profile, download, options = {}) {
2663
+ const resolvedUrl = resolveDownloadUrl2(profile, download.url);
2664
+ if (options.requireSameOrigin && !download.content_base64) {
2665
+ const sourceOrigin = new URL(resolvedUrl).origin;
2666
+ const profileOrigin = new URL(profile.config.origin).origin;
2667
+ if (sourceOrigin !== profileOrigin) {
2668
+ throw new Error(`Plugin skill automatic update must use the profile origin. expected ${profileOrigin}, got ${sourceOrigin}`);
2822
2669
  }
2823
2670
  }
2824
- const result = await runSkillsInstall({ packageRoot: options.packageRoot, runner: options.runner, agent: options.agent });
2825
- if (result.exitCode === 0) {
2826
- await writeSkillsStamp(version, options.configDir, options.agent);
2827
- return { action: "synced", result };
2671
+ const buffer = download.content_base64 ? Buffer.from(download.content_base64, "base64") : Buffer.from(
2672
+ (await axios4.get(resolvedUrl, {
2673
+ responseType: "arraybuffer"
2674
+ })).data
2675
+ );
2676
+ const sha2562 = createHash3("sha256").update(buffer).digest("hex");
2677
+ if (download.sha256 && sha2562 !== download.sha256) {
2678
+ throw new Error(`Plugin skill checksum mismatch. expected ${download.sha256}, got ${sha2562}`);
2828
2679
  }
2829
- return { action: "failed", result };
2830
- }
2831
-
2832
- // src/core/plugin-skills.ts
2833
- var allowedTopLevelFiles = /* @__PURE__ */ new Set(["SKILL.md"]);
2834
- var allowedTopLevelDirs = /* @__PURE__ */ new Set(["references", "scripts", "assets", "agents", "lint", "config"]);
2835
- var allowedAgentsFiles = /* @__PURE__ */ new Set(["openai.yaml"]);
2836
- var semverPattern2 = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
2837
- var safeSkillNamePattern = /^bpmax-[A-Za-z0-9][A-Za-z0-9_-]*$/;
2838
- var safePathSegmentPattern = /^[A-Za-z0-9_.:-]+$/;
2839
- function issue2(severity, code, message) {
2840
- return { severity, code, message };
2680
+ return buffer;
2841
2681
  }
2842
- async function exists2(targetPath) {
2843
- try {
2844
- await stat3(targetPath);
2845
- return true;
2846
- } catch {
2847
- return false;
2682
+ async function listPluginSkills(client, plugin) {
2683
+ if (plugin) {
2684
+ const result2 = await apiRequest(
2685
+ client,
2686
+ "GET",
2687
+ `/cli/plugins/${plugin}/skills`
2688
+ );
2689
+ return Array.isArray(result2) ? result2 : result2.skills || [];
2690
+ }
2691
+ const result = await apiRequest(
2692
+ client,
2693
+ "GET",
2694
+ "/cli/plugins",
2695
+ { params: { include_skills: 1 } }
2696
+ );
2697
+ if (Array.isArray(result)) {
2698
+ return result;
2848
2699
  }
2700
+ return (result.plugins || []).flatMap(
2701
+ (item) => (item.skills || []).map((skill) => ({
2702
+ ...skill,
2703
+ plugin: skill.plugin || item.en_name || item.plugin || item.name
2704
+ }))
2705
+ );
2849
2706
  }
2850
- function parseFrontmatter2(markdown) {
2851
- const match = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---/);
2852
- if (!match) {
2853
- return {};
2707
+ async function ensurePluginSkill(options) {
2708
+ await assertInstallablePluginSkillName(options.skill.name);
2709
+ const state = await readPluginSkillState(options.profile.name, options.agent);
2710
+ const installed = state.origin === options.profile.config.origin ? state.plugins[options.plugin]?.skills[options.skill.name] : void 0;
2711
+ if (!options.force && installed?.version === options.skill.version && installed.sha256 === options.skill.sha256) {
2712
+ if (installed.content_sha256) {
2713
+ const managedPath = installed.agent_install_path || installed.install_path;
2714
+ const currentContentSha256 = await hashSkillDirectory(managedPath);
2715
+ if (currentContentSha256 !== installed.content_sha256) {
2716
+ throw new Error(
2717
+ `\u63D2\u4EF6 Skill ${options.skill.name} \u7684\u672C\u5730\u5185\u5BB9\u5DF2\u88AB\u4FEE\u6539\uFF0C\u62D2\u7EDD\u81EA\u52A8\u8986\u76D6\u3002\u5982\u9700\u4EE5\u5E73\u53F0\u7248\u672C\u66FF\u6362\u672C\u5730\u526F\u672C\uFF0C\u8BF7\u663E\u5F0F\u6267\u884C ${pluginSkillUpdateCommand(options.plugin, options.skill.name, options.profile.name, options.agent)}\u3002`
2718
+ );
2719
+ }
2720
+ }
2721
+ if (!installed.profile_content_sha256) {
2722
+ throw new Error(
2723
+ `\u63D2\u4EF6 Skill ${options.skill.name} \u7684 profile-scoped \u5185\u5BB9\u7F3A\u5C11\u54C8\u5E0C\u57FA\u7EBF\u3002\u8BF7\u663E\u5F0F\u6267\u884C ${pluginSkillUpdateCommand(options.plugin, options.skill.name, options.profile.name, options.agent)} \u91CD\u65B0\u540C\u6B65\u3002`
2724
+ );
2725
+ }
2726
+ const currentProfileContentSha256 = await hashSkillDirectory(installed.install_path);
2727
+ if (currentProfileContentSha256 !== installed.profile_content_sha256) {
2728
+ throw new Error(
2729
+ `\u63D2\u4EF6 Skill ${options.skill.name} \u7684 profile-scoped lint/config adapter \u5185\u5BB9\u5DF2\u88AB\u4FEE\u6539\uFF0C\u62D2\u7EDD\u7EE7\u7EED\u590D\u7528\u3002\u8BF7\u663E\u5F0F\u6267\u884C ${pluginSkillUpdateCommand(options.plugin, options.skill.name, options.profile.name, options.agent)} \u91CD\u65B0\u540C\u6B65\u3002`
2730
+ );
2731
+ }
2732
+ return {
2733
+ action: "in_sync",
2734
+ skill: options.skill.name,
2735
+ plugin: options.plugin,
2736
+ version: installed.version,
2737
+ install_path: installed.install_path
2738
+ };
2854
2739
  }
2855
- const result = {};
2856
- match[1].split(/\r?\n/).forEach((line) => {
2857
- const item = line.match(/^([A-Za-z0-9_.-]+):\s*(.*)$/);
2858
- if (!item) {
2859
- return;
2740
+ const download = await apiRequest(
2741
+ options.client,
2742
+ "GET",
2743
+ `/cli/plugins/${options.plugin}/skills/${options.skill.name}/download`
2744
+ );
2745
+ const buffer = await downloadPluginSkillPackage(options.profile, download, {
2746
+ requireSameOrigin: options.requireSameOrigin
2747
+ });
2748
+ const skillDir = await zipDirectoryToTemp(buffer, `plugin-skill-${options.plugin}-${options.skill.name}`);
2749
+ const lint = await lintPluginSkillDirectory(skillDir, { expectedName: options.skill.name });
2750
+ if (!lint.ok) {
2751
+ throw new Error(`Plugin skill lint failed:
2752
+ - ${lint.errors.map((item) => item.message).join("\n- ")}`);
2753
+ }
2754
+ const lintManifests = normalizePluginLintManifests(download.manifest?.lint || options.skill.lint);
2755
+ const configAdapters = normalizePluginConfigAdapterManifests(download.manifest?.config_adapters || options.skill.config_adapters);
2756
+ const lintManifestIssues = [];
2757
+ lintManifests.forEach((item) => validatePluginLintManifest(item, lintManifestIssues, `Plugin skill ${options.skill.name}`));
2758
+ configAdapters.forEach((item) => validatePluginConfigAdapterManifest(item, lintManifestIssues, `Plugin skill ${options.skill.name}`));
2759
+ for (const item of lintManifests) {
2760
+ if (!await exists2(path4.join(skillDir, item.path))) {
2761
+ lintManifestIssues.push(issue2("error", "missing_lint_file", `Plugin skill ${options.skill.name} lint file not found: ${item.path}`));
2860
2762
  }
2861
- result[item[1]] = item[2].trim().replace(/^['"]|['"]$/g, "");
2763
+ }
2764
+ await Promise.all(
2765
+ configAdapters.map(
2766
+ (item) => validatePluginConfigAdapterFile(skillDir, item, lintManifestIssues, `Plugin skill ${options.skill.name}`)
2767
+ )
2768
+ );
2769
+ if (lintManifestIssues.length) {
2770
+ throw new Error(`Plugin skill lint manifest failed:
2771
+ - ${lintManifestIssues.map((item) => item.message).join("\n- ")}`);
2772
+ }
2773
+ const agentInstallPath = await installSkillDirectory(skillDir, options.skill.name, options.agent, {
2774
+ owner: {
2775
+ kind: "plugin",
2776
+ profile: options.profile.name,
2777
+ plugin: options.plugin,
2778
+ skill: options.skill.name,
2779
+ version: download.version || options.skill.version,
2780
+ sha256: download.sha256,
2781
+ origin: options.profile.config.origin
2782
+ },
2783
+ allowUnownedExisting: Boolean(options.adoptUnownedExisting)
2784
+ });
2785
+ const installPath = await installProfilePluginSkillDirectory(
2786
+ skillDir,
2787
+ options.profile.name,
2788
+ options.agent,
2789
+ options.skill.name
2790
+ );
2791
+ const contentSha256 = await hashSkillDirectory(agentInstallPath);
2792
+ const profileContentSha256 = await hashSkillDirectory(installPath);
2793
+ await updatePluginSkillState(options.profile.name, options.agent, (current) => {
2794
+ current.origin = options.profile.config.origin;
2795
+ delete current.last_check;
2796
+ current.plugins[options.plugin] ||= { skills: {} };
2797
+ current.plugins[options.plugin].skills[options.skill.name] = {
2798
+ name: options.skill.name,
2799
+ plugin: options.plugin,
2800
+ version: download.version || options.skill.version,
2801
+ sha256: download.sha256,
2802
+ install_path: installPath,
2803
+ agent_install_path: agentInstallPath,
2804
+ content_sha256: contentSha256,
2805
+ profile_content_sha256: profileContentSha256,
2806
+ domains: options.skill.domains || [],
2807
+ capabilities: options.skill.capabilities || [],
2808
+ lint: lintManifests,
2809
+ config_adapters: configAdapters,
2810
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
2811
+ };
2862
2812
  });
2863
- return result;
2864
- }
2865
- function completeReport2(report) {
2866
- const errors = report.issues.filter((item) => item.severity === "error");
2867
- const warnings = report.issues.filter((item) => item.severity === "warning");
2868
2813
  return {
2869
- ok: errors.length === 0,
2870
- errors,
2871
- warnings,
2872
- checks: report.checks,
2873
- manifest: report.manifest,
2874
- skill_dir: report.skill_dir
2814
+ action: installed ? "updated" : "installed",
2815
+ skill: options.skill.name,
2816
+ plugin: options.plugin,
2817
+ version: download.version || options.skill.version,
2818
+ install_path: installPath
2875
2819
  };
2876
2820
  }
2877
- async function listCoreSkillNames() {
2878
- const packageRoot = await resolvePackageRootFrom(fileURLToPath2(import.meta.url));
2879
- const roots = [path4.join(packageRoot, "skills")];
2880
- const names = /* @__PURE__ */ new Set();
2881
- for (const root of roots) {
2882
- let entries;
2883
- try {
2884
- entries = await readdir(root, { withFileTypes: true });
2885
- } catch {
2821
+ function pluginSkillDomains(skill) {
2822
+ return [...new Set([
2823
+ ...skill.domains || [],
2824
+ ...normalizePluginLintManifests(skill.lint).map((item) => item.domain),
2825
+ ...normalizePluginConfigAdapterManifests(skill.config_adapters).map((item) => item.domain)
2826
+ ].filter(Boolean))];
2827
+ }
2828
+ function pluginSkillUpdateCommand(plugin, skill, profile, agent) {
2829
+ return `bpmax-cli plugin skills update ${plugin} --skill ${skill} --profile ${profile} --agent ${agent} --format json`;
2830
+ }
2831
+ function isFreshPluginSkillCheck(checkedAt, now) {
2832
+ if (!checkedAt) return false;
2833
+ const timestamp = Date.parse(checkedAt);
2834
+ return Number.isFinite(timestamp) && now - timestamp < pluginSkillCheckMaxAgeMs;
2835
+ }
2836
+ function updateMatchesDomain(update, domain) {
2837
+ return !domain || update.domain.includes(domain);
2838
+ }
2839
+ function updateMatchesSelection(update, domain, plugins) {
2840
+ return updateMatchesDomain(update, domain) && (!plugins?.length || plugins.includes(update.plugin));
2841
+ }
2842
+ async function validateCachedPluginSkillUpdates(state, updates, profile, agent) {
2843
+ const validated = [];
2844
+ for (const update of updates) {
2845
+ if (update.status !== "in_sync") {
2846
+ validated.push(update);
2886
2847
  continue;
2887
2848
  }
2888
- for (const entry of entries) {
2889
- if (!entry.isDirectory()) {
2849
+ const installed = state.plugins[update.plugin]?.skills[update.skill];
2850
+ if (!installed) {
2851
+ validated.push({
2852
+ ...update,
2853
+ status: "state_missing",
2854
+ reason: "\u672C\u5730\u5B89\u88C5\u72B6\u6001\u7F3A\u5931\uFF0C\u65E0\u6CD5\u52A0\u8F7D\u63D2\u4EF6 lint/config adapter \u58F0\u660E\u3002",
2855
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2856
+ });
2857
+ continue;
2858
+ }
2859
+ const installPath = installed.agent_install_path || installed.install_path;
2860
+ if (!await exists2(installPath)) {
2861
+ validated.push({
2862
+ ...update,
2863
+ status: "not_installed",
2864
+ reason: "\u672C\u5730 Agent Skill \u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728\u3002",
2865
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2866
+ });
2867
+ continue;
2868
+ }
2869
+ const owner = await readSkillInstallOwner(installPath);
2870
+ if (!owner || owner.profile !== profile.name || owner.plugin !== update.plugin || owner.skill !== update.skill || owner.origin !== profile.config.origin) {
2871
+ validated.push({
2872
+ ...update,
2873
+ status: "conflicted",
2874
+ reason: "\u672C\u5730 Skill \u6765\u6E90\u5143\u6570\u636E\u5728\u7F13\u5B58\u671F\u5185\u53D1\u751F\u53D8\u5316\u3002",
2875
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2876
+ });
2877
+ continue;
2878
+ }
2879
+ if (installed.content_sha256 && installed.profile_content_sha256) {
2880
+ const contentSha256 = await hashSkillDirectory(installPath);
2881
+ if (contentSha256 !== installed.content_sha256) {
2882
+ validated.push({
2883
+ ...update,
2884
+ status: "conflicted",
2885
+ reason: "\u672C\u5730 Skill \u5185\u5BB9\u5728\u7F13\u5B58\u671F\u5185\u88AB\u4FEE\u6539\uFF0C\u81EA\u52A8\u66F4\u65B0\u4E0D\u4F1A\u8986\u76D6\u4EBA\u5DE5\u6539\u52A8\u3002",
2886
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2887
+ });
2890
2888
  continue;
2891
2889
  }
2892
- if (await exists2(path4.join(root, entry.name, "SKILL.md"))) {
2893
- names.add(entry.name);
2890
+ const profileContentSha256 = await hashSkillDirectory(installed.install_path);
2891
+ if (profileContentSha256 !== installed.profile_content_sha256) {
2892
+ validated.push({
2893
+ ...update,
2894
+ status: "conflicted",
2895
+ reason: "profile-scoped lint/config adapter \u5185\u5BB9\u5728\u7F13\u5B58\u671F\u5185\u88AB\u4FEE\u6539\u3002",
2896
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2897
+ });
2898
+ continue;
2899
+ }
2900
+ } else {
2901
+ validated.push({
2902
+ ...update,
2903
+ status: "conflicted",
2904
+ reason: "\u672C\u5730\u5B89\u88C5\u72B6\u6001\u7F3A\u5C11 Agent \u6216 profile-scoped \u5185\u5BB9\u54C8\u5E0C\u57FA\u7EBF\u3002",
2905
+ next_command: pluginSkillUpdateCommand(update.plugin, update.skill, profile.name, agent)
2906
+ });
2907
+ continue;
2908
+ }
2909
+ validated.push(update);
2910
+ }
2911
+ return validated;
2912
+ }
2913
+ async function checkPluginSkillUpdates(options) {
2914
+ const policy = options.policy || options.profile.config.plugin_skill_update_policy || "check";
2915
+ const now = Date.now();
2916
+ if (policy === "off") {
2917
+ return {
2918
+ ok: true,
2919
+ policy,
2920
+ profile: options.profile.name,
2921
+ origin: options.profile.config.origin,
2922
+ agent: options.agent,
2923
+ checked_at: new Date(now).toISOString(),
2924
+ cached: false,
2925
+ plugin_skill_updates: [],
2926
+ actions: []
2927
+ };
2928
+ }
2929
+ const currentState = await readPluginSkillState(options.profile.name, options.agent);
2930
+ const state = currentState.origin === options.profile.config.origin ? currentState : { plugins: {} };
2931
+ if (!options.force && state.last_check?.origin === options.profile.config.origin && isFreshPluginSkillCheck(state.last_check.checked_at, now)) {
2932
+ const updates2 = (await validateCachedPluginSkillUpdates(
2933
+ state,
2934
+ state.last_check.updates,
2935
+ options.profile,
2936
+ options.agent
2937
+ )).filter((item) => updateMatchesSelection(item, options.domain, options.plugins));
2938
+ return {
2939
+ ok: updates2.every((item) => item.status === "in_sync"),
2940
+ policy,
2941
+ profile: options.profile.name,
2942
+ origin: options.profile.config.origin,
2943
+ agent: options.agent,
2944
+ checked_at: state.last_check.checked_at,
2945
+ cached: true,
2946
+ plugin_skill_updates: updates2,
2947
+ actions: []
2948
+ };
2949
+ }
2950
+ const remoteSkills = options.remoteSkills || await listPluginSkills(options.client);
2951
+ const updates = [];
2952
+ for (const skill of remoteSkills) {
2953
+ const plugin = skill.plugin || "";
2954
+ const domains = pluginSkillDomains(skill);
2955
+ if (!plugin) {
2956
+ continue;
2957
+ }
2958
+ const installed = state.plugins[plugin]?.skills[skill.name];
2959
+ const installPath = installed?.agent_install_path || installed?.install_path || resolveAgentSkillInstallPath(skill.name, options.agent);
2960
+ const owner = await readSkillInstallOwner(installPath);
2961
+ const installedSha256 = installed?.sha256 || (owner?.profile === options.profile.name && owner.plugin === plugin && owner.skill === skill.name && owner.origin === options.profile.config.origin ? owner.sha256 : void 0);
2962
+ let status;
2963
+ let reason;
2964
+ if (await exists2(installPath)) {
2965
+ if (!owner || owner.profile !== options.profile.name || owner.plugin !== plugin || owner.skill !== skill.name || owner.origin !== options.profile.config.origin) {
2966
+ status = "conflicted";
2967
+ reason = "\u672C\u5730 Skill \u76EE\u5F55\u7F3A\u5C11\u5339\u914D\u7684 BPMAX \u63D2\u4EF6\u6765\u6E90\u5143\u6570\u636E\uFF0C\u53EF\u80FD\u88AB\u4EBA\u5DE5\u521B\u5EFA\u6216\u5C5E\u4E8E\u5176\u4ED6 profile/origin\u3002";
2968
+ } else if (!installed) {
2969
+ status = "state_missing";
2970
+ reason = "\u672C\u5730\u5B89\u88C5\u72B6\u6001\u7F3A\u5931\uFF0C\u65E0\u6CD5\u52A0\u8F7D\u63D2\u4EF6 lint/config adapter \u58F0\u660E\u3002";
2971
+ } else if (installed.content_sha256 && installed.profile_content_sha256) {
2972
+ const contentSha256 = await hashSkillDirectory(installPath);
2973
+ if (contentSha256 !== installed.content_sha256) {
2974
+ status = "conflicted";
2975
+ reason = "\u672C\u5730 Skill \u5185\u5BB9\u5DF2\u88AB\u4FEE\u6539\uFF0C\u81EA\u52A8\u66F4\u65B0\u4E0D\u4F1A\u8986\u76D6\u4EBA\u5DE5\u6539\u52A8\u3002";
2976
+ } else if (await hashSkillDirectory(installed.install_path) !== installed.profile_content_sha256) {
2977
+ status = "conflicted";
2978
+ reason = "profile-scoped lint/config adapter \u5185\u5BB9\u5DF2\u88AB\u4FEE\u6539\uFF0C\u81EA\u52A8\u66F4\u65B0\u4E0D\u4F1A\u8986\u76D6\u4EBA\u5DE5\u6539\u52A8\u3002";
2979
+ } else if (!skill.sha256) {
2980
+ status = "checksum_unavailable";
2981
+ reason = "\u5E73\u53F0\u672A\u8FD4\u56DE Skill sha256\uFF0C\u65E0\u6CD5\u5B89\u5168\u5224\u65AD\u662F\u5426\u9700\u8981\u66F4\u65B0\u3002";
2982
+ } else {
2983
+ status = installedSha256 === skill.sha256 ? "in_sync" : "update_available";
2984
+ }
2985
+ } else {
2986
+ status = "conflicted";
2987
+ reason = "\u672C\u5730\u5B89\u88C5\u72B6\u6001\u7F3A\u5C11\u5185\u5BB9\u54C8\u5E0C\u57FA\u7EBF\uFF0C\u65E0\u6CD5\u786E\u8BA4\u76EE\u5F55\u662F\u5426\u88AB\u4EBA\u5DE5\u4FEE\u6539\u3002";
2988
+ }
2989
+ } else {
2990
+ status = skill.sha256 ? "not_installed" : "checksum_unavailable";
2991
+ if (!skill.sha256) {
2992
+ reason = "\u5E73\u53F0\u672A\u8FD4\u56DE Skill sha256\uFF0C\u65E0\u6CD5\u5B89\u5168\u5B89\u88C5\u3002";
2993
+ }
2994
+ }
2995
+ updates.push({
2996
+ plugin,
2997
+ skill: skill.name,
2998
+ domain: domains,
2999
+ status,
3000
+ installed_version: installed?.version || owner?.version,
3001
+ latest_version: skill.version,
3002
+ installed_sha256: installedSha256,
3003
+ latest_sha256: skill.sha256,
3004
+ install_path: installPath,
3005
+ ...reason ? { reason } : {},
3006
+ ...status === "in_sync" ? {} : {
3007
+ next_command: pluginSkillUpdateCommand(plugin, skill.name, options.profile.name, options.agent)
2894
3008
  }
3009
+ });
3010
+ }
3011
+ const checkedAt = new Date(now).toISOString();
3012
+ await updatePluginSkillState(options.profile.name, options.agent, (next) => {
3013
+ if (next.origin && next.origin !== options.profile.config.origin) {
3014
+ next.plugins = {};
3015
+ }
3016
+ next.origin = options.profile.config.origin;
3017
+ next.last_check = {
3018
+ checked_at: checkedAt,
3019
+ origin: options.profile.config.origin,
3020
+ updates
3021
+ };
3022
+ });
3023
+ const filtered = updates.filter((item) => updateMatchesSelection(item, options.domain, options.plugins));
3024
+ return {
3025
+ ok: filtered.every((item) => item.status === "in_sync"),
3026
+ policy,
3027
+ profile: options.profile.name,
3028
+ origin: options.profile.config.origin,
3029
+ agent: options.agent,
3030
+ checked_at: checkedAt,
3031
+ cached: false,
3032
+ plugin_skill_updates: filtered,
3033
+ actions: []
3034
+ };
3035
+ }
3036
+ async function ensurePluginSkillsForDomain(options) {
3037
+ const policy = options.policy || options.profile.config.plugin_skill_update_policy || "check";
3038
+ if (policy === "off") {
3039
+ return {
3040
+ ok: true,
3041
+ policy,
3042
+ profile: options.profile.name,
3043
+ origin: options.profile.config.origin,
3044
+ agent: options.agent,
3045
+ checked_at: (/* @__PURE__ */ new Date()).toISOString(),
3046
+ cached: false,
3047
+ plugin_skill_updates: [],
3048
+ actions: []
3049
+ };
3050
+ }
3051
+ let report = await checkPluginSkillUpdates({ ...options, policy, force: options.forceCheck });
3052
+ if (policy !== "auto") {
3053
+ return report;
3054
+ }
3055
+ const actionable = report.plugin_skill_updates.filter(
3056
+ (item) => item.status === "not_installed" || item.status === "update_available"
3057
+ );
3058
+ if (!actionable.length) {
3059
+ return report;
3060
+ }
3061
+ const remoteSkills = options.remoteSkills || await listPluginSkills(options.client);
3062
+ const actions = [];
3063
+ const failures = /* @__PURE__ */ new Map();
3064
+ for (const update of actionable) {
3065
+ const skill = remoteSkills.find((item) => item.plugin === update.plugin && item.name === update.skill);
3066
+ if (!skill) {
3067
+ failures.set(`${update.plugin}\0${update.skill}`, {
3068
+ ...update,
3069
+ status: "update_failed",
3070
+ reason: `\u63D2\u4EF6 ${update.plugin} \u58F0\u660E\u7684 Skill ${update.skill} \u5728\u66F4\u65B0\u68C0\u67E5\u540E\u5DF2\u4E0D\u53EF\u7528\u3002`
3071
+ });
3072
+ continue;
3073
+ }
3074
+ try {
3075
+ const result = await ensurePluginSkill({
3076
+ client: options.client,
3077
+ profile: options.profile,
3078
+ plugin: update.plugin,
3079
+ skill,
3080
+ agent: options.agent,
3081
+ requireSameOrigin: true
3082
+ });
3083
+ actions.push({ plugin: result.plugin, skill: result.skill, action: result.action });
3084
+ } catch (error) {
3085
+ failures.set(`${update.plugin}\0${update.skill}`, {
3086
+ ...update,
3087
+ status: "update_failed",
3088
+ reason: error instanceof Error ? error.message : String(error)
3089
+ });
2895
3090
  }
2896
3091
  }
2897
- return names;
3092
+ report = await checkPluginSkillUpdates({ ...options, policy, force: true });
3093
+ const pluginSkillUpdates = report.plugin_skill_updates.map(
3094
+ (item) => failures.get(`${item.plugin}\0${item.skill}`) || item
3095
+ );
3096
+ return {
3097
+ ...report,
3098
+ ok: pluginSkillUpdates.every((item) => item.status === "in_sync"),
3099
+ plugin_skill_updates: pluginSkillUpdates,
3100
+ actions
3101
+ };
2898
3102
  }
2899
- async function collectRelativeFiles(root, dir = "") {
2900
- const absolute = path4.join(root, dir);
2901
- const entries = await readdir(absolute, { withFileTypes: true });
2902
- const files = [];
2903
- for (const entry of entries) {
2904
- const relative = path4.posix.join(dir.replace(/\\/g, "/"), entry.name);
2905
- if (entry.isDirectory()) {
2906
- files.push(...await collectRelativeFiles(root, relative));
2907
- } else {
2908
- files.push(relative);
3103
+ function getPathValue(source, pathExpression) {
3104
+ if (!pathExpression || pathExpression === "$" || pathExpression === ".") {
3105
+ return source;
3106
+ }
3107
+ const parts = pathExpression.replace(/^\$\.?/, "").split(".").filter(Boolean);
3108
+ let current = source;
3109
+ for (const part of parts) {
3110
+ if (current === null || typeof current !== "object" || Array.isArray(current)) {
3111
+ return void 0;
2909
3112
  }
3113
+ current = current[part];
2910
3114
  }
2911
- return files;
3115
+ return current;
2912
3116
  }
2913
- function validateAllowedPath(relative) {
2914
- const normalized = relative.replace(/\\/g, "/");
2915
- const parts = normalized.split("/");
2916
- if (normalized.startsWith("/") || path4.isAbsolute(normalized) || parts.some((part) => part === "" || part === "." || part === "..")) {
2917
- return issue2("error", "unsafe_path", `Plugin skill contains unsafe path: ${relative}`);
3117
+ function isNonEmptyValue(value) {
3118
+ if (typeof value === "string") {
3119
+ return value.trim().length > 0;
2918
3120
  }
2919
- if (parts.length === 1) {
2920
- if (!allowedTopLevelFiles.has(parts[0])) {
2921
- return issue2("error", "disallowed_top_level_file", `Plugin skill top-level file is not allowed: ${relative}`);
2922
- }
2923
- return void 0;
3121
+ if (Array.isArray(value)) {
3122
+ return value.length > 0;
2924
3123
  }
2925
- const top = parts[0];
2926
- if (!allowedTopLevelDirs.has(top)) {
2927
- return issue2("error", "disallowed_top_level_dir", `Plugin skill top-level directory is not allowed: ${top}`);
3124
+ return value !== void 0 && value !== null && value !== "";
3125
+ }
3126
+ function shouldSkipPluginLint(config, skipRules) {
3127
+ if (!Array.isArray(skipRules) || !skipRules.length) {
3128
+ return false;
2928
3129
  }
2929
- if (top === "agents" && (parts.length !== 2 || !allowedAgentsFiles.has(parts[1]))) {
2930
- return issue2("error", "disallowed_agents_file", `Plugin skill agents/ may only contain openai.yaml: ${relative}`);
3130
+ return skipRules.some((rule) => getPathValue(config, rule.path) === rule.equals);
3131
+ }
3132
+ function evaluatePluginRule(config, rule, location) {
3133
+ const type = String(rule.type || "");
3134
+ const value = getPathValue(config, rule.path);
3135
+ const label = rule.path ? `${location}.${rule.path}` : location;
3136
+ if (rule.optional && (value === void 0 || value === null || value === "")) {
3137
+ return void 0;
2931
3138
  }
2932
- if (top === "lint" && (parts.length !== 2 || !parts[1].endsWith(".json"))) {
2933
- return issue2("error", "disallowed_lint_file", `Plugin skill lint/ may only contain JSON files: ${relative}`);
3139
+ if (type === "object") {
3140
+ const target = rule.path ? value : config;
3141
+ if (target === null || typeof target !== "object" || Array.isArray(target)) {
3142
+ return rule.message || `${label} must be an object.`;
3143
+ }
3144
+ return void 0;
2934
3145
  }
2935
- if (top === "config" && (parts.length !== 2 || !parts[1].endsWith(".json"))) {
2936
- return issue2("error", "disallowed_config_file", `Plugin skill config/ may only contain JSON files: ${relative}`);
3146
+ if (type === "requiredAny") {
3147
+ const paths = Array.isArray(rule.paths) ? rule.paths : [];
3148
+ if (!paths.some((item) => isNonEmptyValue(getPathValue(config, item)))) {
3149
+ return rule.message || `${location} requires at least one of: ${paths.join(", ")}.`;
3150
+ }
3151
+ return void 0;
2937
3152
  }
2938
- return void 0;
2939
- }
2940
- function validateSafeSkillName(name, issues, context = "Plugin skill") {
2941
- if (!safeSkillNamePattern.test(name)) {
2942
- issues.push(issue2("error", "invalid_name", `${context} name must match ${safeSkillNamePattern.source}: ${name}`));
3153
+ if (type === "nonEmptyString") {
3154
+ if (typeof value !== "string" || !value.trim()) {
3155
+ return rule.message || `${label} must be a non-empty string.`;
3156
+ }
3157
+ return void 0;
2943
3158
  }
2944
- }
2945
- function assertSafeStateSegment(value, label) {
2946
- if (!value || value.includes("/") || value.includes("\\") || value === "." || value === ".." || !safePathSegmentPattern.test(value)) {
2947
- throw new Error(`Unsafe plugin skill state ${label}: ${value}`);
3159
+ if (type === "nonEmptyArray") {
3160
+ if (!Array.isArray(value) || !value.length) {
3161
+ return rule.message || `${label} must be a non-empty array.`;
3162
+ }
3163
+ return void 0;
2948
3164
  }
2949
- }
2950
- async function assertInstallablePluginSkillName(name) {
2951
- if (!safeSkillNamePattern.test(name)) {
2952
- throw new Error(`Plugin skill name must match ${safeSkillNamePattern.source}: ${name}`);
3165
+ if (type === "positiveNumber") {
3166
+ const numericValue = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
3167
+ if (!Number.isFinite(numericValue) || numericValue <= 0) {
3168
+ return rule.message || `${label} must be a positive number.`;
3169
+ }
3170
+ return void 0;
2953
3171
  }
2954
- const coreSkillNames = await listCoreSkillNames();
2955
- if (coreSkillNames.has(name)) {
2956
- throw new Error(`Plugin skill must not overwrite built-in/core skill: ${name}`);
3172
+ if (type === "enum") {
3173
+ const values = Array.isArray(rule.values) ? rule.values : [];
3174
+ if (!values.includes(value)) {
3175
+ return rule.message || `${label} must be one of ${values.map((item) => String(item)).join(", ")}.`;
3176
+ }
3177
+ return void 0;
2957
3178
  }
3179
+ return `${location} has unsupported plugin lint rule type: ${type || "(missing)"}.`;
2958
3180
  }
2959
- async function installProfilePluginSkillDirectory(skillDir, profileName, agent, skillName) {
2960
- assertSafeStateSegment(profileName, "profile");
2961
- assertSafeStateSegment(agent, "agent");
2962
- if (!safeSkillNamePattern.test(skillName)) {
2963
- throw new Error(`Plugin skill name must match ${safeSkillNamePattern.source}: ${skillName}`);
3181
+ function collectFlowTemplatePluginConfigs(flowWork, pluginKey, lintManifests = []) {
3182
+ const scanPaths = new Set(lintManifests.flatMap((item) => item.paths || []));
3183
+ if (scanPaths.size) {
3184
+ const occurrences = [];
3185
+ scanPaths.forEach((scanPath) => {
3186
+ occurrences.push(...collectFlowTemplatePluginConfigsByPath(flowWork, scanPath, pluginKey));
3187
+ });
3188
+ return occurrences;
2964
3189
  }
2965
- const destination = path4.join(getConfigDir(), "plugin-skills", profileName, agent, "installed", skillName);
2966
- await copySkillDirectory(skillDir, destination);
2967
- return destination;
3190
+ return collectDefaultFlowTemplatePluginConfigs(flowWork, pluginKey);
2968
3191
  }
2969
- function normalizePluginLintManifests(value) {
2970
- if (!Array.isArray(value)) {
2971
- return [];
2972
- }
2973
- return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item)).map((item) => ({
2974
- domain: typeof item.domain === "string" ? item.domain : "",
2975
- plugin_key: typeof item.plugin_key === "string" ? item.plugin_key : "",
2976
- path: typeof item.path === "string" ? item.path.replace(/\\/g, "/") : "",
2977
- version: typeof item.version === "string" || typeof item.version === "number" ? item.version : void 0,
2978
- paths: Array.isArray(item.paths) ? item.paths.filter((pathItem) => typeof pathItem === "string" && Boolean(pathItem.trim())).map((pathItem) => pathItem.replace(/\\/g, "/")) : void 0
2979
- })).filter((item) => item.domain && item.plugin_key && item.path);
3192
+ function flowTemplateUsesPluginSkill(flowWork, skill) {
3193
+ const declarations = normalizePluginLintManifests(skill.lint).filter((item) => item.domain === "flow-template-node");
3194
+ return declarations.some(
3195
+ (declaration) => collectFlowTemplatePluginConfigs(
3196
+ flowWork,
3197
+ declaration.plugin_key,
3198
+ declarations.filter((item) => item.plugin_key === declaration.plugin_key)
3199
+ ).length > 0
3200
+ );
2980
3201
  }
2981
- function normalizePluginConfigAdapterManifests(value) {
2982
- if (!Array.isArray(value)) {
2983
- return [];
3202
+ function collectDefaultFlowTemplatePluginConfigs(flowWork, pluginKey) {
3203
+ const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3204
+ const meta = typeof data.meta === "object" && data.meta !== null && !Array.isArray(data.meta) ? data.meta : {};
3205
+ const occurrences = [];
3206
+ if (Object.prototype.hasOwnProperty.call(meta, pluginKey)) {
3207
+ occurrences.push({ location: `data.meta.${pluginKey}`, config: meta[pluginKey] });
2984
3208
  }
2985
- return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item)).map((item) => ({
2986
- domain: typeof item.domain === "string" ? item.domain : "",
2987
- plugin_key: typeof item.plugin_key === "string" ? item.plugin_key : "",
2988
- capability_prefix: typeof item.capability_prefix === "string" ? item.capability_prefix : "",
2989
- adapter: typeof item.adapter === "string" ? item.adapter.replace(/\\/g, "/") : "",
2990
- version: typeof item.version === "string" || typeof item.version === "number" ? item.version : void 0
2991
- })).filter((item) => item.domain && item.plugin_key && item.capability_prefix && item.adapter);
3209
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3210
+ nodes.forEach((node, index) => {
3211
+ if (node && typeof node === "object" && !Array.isArray(node) && Object.prototype.hasOwnProperty.call(node, pluginKey)) {
3212
+ const nodeRecord = node;
3213
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${index}]`;
3214
+ occurrences.push({ location: `${nodeName}.${pluginKey}`, config: nodeRecord[pluginKey] });
3215
+ }
3216
+ });
3217
+ return occurrences;
2992
3218
  }
2993
- function validatePluginConfigAdapterManifest(item, issues, context) {
2994
- if (!/^[a-z][a-z0-9-]*$/.test(item.domain)) {
2995
- issues.push(issue2("error", "invalid_config_adapter_domain", `${context} config adapter domain must be kebab-case.`));
3219
+ function collectFlowTemplatePluginConfigsByPath(flowWork, scanPath, pluginKey) {
3220
+ if (scanPath === "data.meta.<plugin_key>") {
3221
+ const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3222
+ const meta = typeof data2.meta === "object" && data2.meta !== null && !Array.isArray(data2.meta) ? data2.meta : {};
3223
+ return Object.prototype.hasOwnProperty.call(meta, pluginKey) ? [{ location: `data.meta.${pluginKey}`, config: meta[pluginKey] }] : [];
2996
3224
  }
2997
- if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
2998
- issues.push(issue2("error", "invalid_config_adapter_plugin_key", `${context} config adapter plugin_key must look like plugin_xxx.`));
3225
+ if (scanPath === "data.nodes[].<plugin_key>") {
3226
+ const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3227
+ const nodes2 = Array.isArray(data2.nodes) ? data2.nodes : [];
3228
+ const occurrences2 = [];
3229
+ nodes2.forEach((node, nodeIndex) => {
3230
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
3231
+ return;
3232
+ }
3233
+ const nodeRecord = node;
3234
+ if (!Object.prototype.hasOwnProperty.call(nodeRecord, pluginKey)) {
3235
+ return;
3236
+ }
3237
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3238
+ occurrences2.push({ location: `${nodeName}.${pluginKey}`, config: nodeRecord[pluginKey] });
3239
+ });
3240
+ return occurrences2;
2999
3241
  }
3000
- if (!item.capability_prefix.startsWith(`config.plugin.${item.plugin_key}.`)) {
3001
- issues.push(issue2("error", "invalid_config_adapter_capability", `${context} config adapter capability_prefix must start with config.plugin.${item.plugin_key}.`));
3242
+ const pluginArrayMatch = scanPath.match(/^data\.nodes\[\]\.<plugin_key>\.([A-Za-z0-9_]+)\[\]$/);
3243
+ if (pluginArrayMatch) {
3244
+ const field2 = pluginArrayMatch[1];
3245
+ const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3246
+ const nodes2 = Array.isArray(data2.nodes) ? data2.nodes : [];
3247
+ const occurrences2 = [];
3248
+ nodes2.forEach((node, nodeIndex) => {
3249
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
3250
+ return;
3251
+ }
3252
+ const nodeRecord = node;
3253
+ const pluginConfig = nodeRecord[pluginKey];
3254
+ if (!pluginConfig || typeof pluginConfig !== "object" || Array.isArray(pluginConfig)) {
3255
+ return;
3256
+ }
3257
+ const values = pluginConfig[field2];
3258
+ if (!Array.isArray(values)) {
3259
+ return;
3260
+ }
3261
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3262
+ values.forEach((value, valueIndex) => {
3263
+ occurrences2.push({
3264
+ location: `${nodeName}.${pluginKey}.${field2}[${valueIndex}]`,
3265
+ config: value
3266
+ });
3267
+ });
3268
+ });
3269
+ return occurrences2;
3002
3270
  }
3003
- const normalized = item.adapter.replace(/\\/g, "/");
3004
- const parts = normalized.split("/");
3005
- if (!normalized.startsWith("config/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
3006
- issues.push(issue2("error", "invalid_config_adapter_path", `${context} config adapter path must be a config/*.json file.`));
3271
+ const match = scanPath.match(/^data\.nodes\[\]\.([A-Za-z0-9_]+)\[\]$/);
3272
+ if (!match) {
3273
+ return [];
3007
3274
  }
3275
+ const field = match[1];
3276
+ const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3277
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3278
+ const occurrences = [];
3279
+ nodes.forEach((node, nodeIndex) => {
3280
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
3281
+ return;
3282
+ }
3283
+ const nodeRecord = node;
3284
+ const values = nodeRecord[field];
3285
+ if (!Array.isArray(values)) {
3286
+ return;
3287
+ }
3288
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3289
+ values.forEach((value, valueIndex) => {
3290
+ occurrences.push({
3291
+ location: `${nodeName}.${field}[${valueIndex}]`,
3292
+ config: value
3293
+ });
3294
+ });
3295
+ });
3296
+ return occurrences;
3008
3297
  }
3009
- function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, allowedMethods, issues, context) {
3010
- const endpoint = endpoints[operation];
3011
- if (endpoint === void 0) return;
3012
- if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint)) {
3013
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must be an object.`));
3014
- return;
3015
- }
3016
- const value = endpoint;
3017
- const method = typeof value.method === "string" ? value.method : allowedMethods[0];
3018
- if (!allowedMethods.includes(method)) {
3019
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} method must be ${allowedMethods.join(" or ")}.`));
3020
- }
3021
- const endpointPath2 = typeof value.path === "string" ? value.path : "";
3022
- const variants = [endpointPath2];
3023
- let current = endpointPath2;
3024
- for (let i = 0; i < 3; i += 1) {
3025
- try {
3026
- const decoded = decodeURIComponent(current);
3027
- if (decoded === current) break;
3028
- variants.push(decoded);
3029
- current = decoded;
3030
- } catch {
3031
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains malformed URL encoding.`));
3298
+ function collectFlowTemplatePluginKeys(flowWork) {
3299
+ const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3300
+ const meta = typeof data.meta === "object" && data.meta !== null && !Array.isArray(data.meta) ? data.meta : {};
3301
+ const keys = /* @__PURE__ */ new Set();
3302
+ Object.keys(meta).forEach((key) => {
3303
+ if (/^plugin_[A-Za-z0-9_]+$/.test(key)) {
3304
+ keys.add(key);
3305
+ }
3306
+ });
3307
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3308
+ nodes.forEach((node) => {
3309
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
3032
3310
  return;
3033
3311
  }
3034
- }
3035
- const hasUnsafePath = variants.some((variant) => {
3036
- const endpointParts = variant.split("/");
3037
- return !variant.startsWith("/") || variant.includes("\\") || /%(?:2e|2f|5c)/i.test(variant) || endpointParts.some((part) => part === "." || part === "..");
3312
+ Object.keys(node).forEach((key) => {
3313
+ if (/^plugin_[A-Za-z0-9_]+$/.test(key)) {
3314
+ keys.add(key);
3315
+ }
3316
+ });
3038
3317
  });
3039
- if (hasUnsafePath) {
3040
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains an unsafe path.`));
3041
- return;
3318
+ return [...keys];
3319
+ }
3320
+ function collectUndeclaredPluginArrayLocations(flowWork) {
3321
+ const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3322
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3323
+ const locations = [];
3324
+ nodes.forEach((node, nodeIndex) => {
3325
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
3326
+ const nodeRecord = node;
3327
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3328
+ Object.entries(nodeRecord).forEach(([key, value]) => {
3329
+ if (/_(?:triggers|configs|plugins)$/.test(key) && Array.isArray(value) && value.some((item) => item && typeof item === "object" && !Array.isArray(item))) {
3330
+ locations.push(`${nodeName}.${key}`);
3331
+ }
3332
+ });
3333
+ });
3334
+ return locations;
3335
+ }
3336
+ function isExplicitlyDisabledPluginConfig(config) {
3337
+ return Boolean(
3338
+ config && typeof config === "object" && !Array.isArray(config) && config.enabled === false
3339
+ );
3340
+ }
3341
+ async function readPluginLintRuleFile(skillInstallPath, lintManifest) {
3342
+ const fullPath = path4.join(skillInstallPath, lintManifest.path);
3343
+ const value = JSON.parse(await readFile6(fullPath, "utf8"));
3344
+ if (value.domain && value.domain !== lintManifest.domain) {
3345
+ throw new Error(`Plugin lint rule domain mismatch for ${lintManifest.path}.`);
3042
3346
  }
3043
- const expectedPrefix = `/${pluginKey}`;
3044
- if (!endpointPath2 || variants.some((variant) => !variant.startsWith(`${expectedPrefix}/`) && variant !== expectedPrefix)) {
3045
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must stay under ${expectedPrefix}.`));
3347
+ if (value.plugin_key && value.plugin_key !== lintManifest.plugin_key) {
3348
+ throw new Error(`Plugin lint rule plugin_key mismatch for ${lintManifest.path}.`);
3046
3349
  }
3350
+ return value;
3047
3351
  }
3048
- function validatePluginConfigAdapterEndpoints(endpoints, pluginKey, issues, context) {
3049
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "list", ["GET"], issues, context);
3050
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "get", ["GET"], issues, context);
3051
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "create", ["POST"], issues, context);
3052
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "update", ["PUT"], issues, context);
3053
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "test", ["POST"], issues, context);
3054
- }
3055
- async function validatePluginConfigAdapterFile(skillDir, item, issues, context) {
3056
- const adapterFile = path4.join(skillDir, item.adapter);
3057
- if (!await exists2(adapterFile)) {
3058
- issues.push(issue2("error", "missing_config_adapter_file", `${context} config adapter file not found: ${item.adapter}`));
3059
- return;
3352
+ async function lintFlowTemplatePluginExtensions(options) {
3353
+ const errors = [];
3354
+ const warnings = [];
3355
+ const pluginLints = [];
3356
+ const platformSkills = options.platformSkills || [];
3357
+ const state = await readPluginSkillState(options.profile.name, options.agent);
3358
+ const platformLintDeclarations = platformSkills.flatMap(
3359
+ (skill) => normalizePluginLintManifests(skill.lint).map((lint) => ({
3360
+ plugin: skill.plugin || "",
3361
+ skill: skill.name,
3362
+ lint
3363
+ }))
3364
+ ).filter((item) => item.plugin && item.lint.domain === "flow-template-node");
3365
+ const installedLintDeclarations = Object.values(state.plugins).flatMap(
3366
+ (pluginState) => Object.values(pluginState.skills).flatMap(
3367
+ (skill) => normalizePluginLintManifests(skill.lint).map((lint) => ({
3368
+ plugin: skill.plugin,
3369
+ skill: skill.name,
3370
+ installPath: skill.install_path,
3371
+ lint
3372
+ }))
3373
+ )
3374
+ ).filter((item) => item.lint.domain === "flow-template-node");
3375
+ const usedPluginKeys = new Set(collectFlowTemplatePluginKeys(options.flowWork));
3376
+ const hasRemoteFlowIdentity = typeof options.flowWork.flow_type === "string" && options.flowWork.flow_type.trim().length > 0;
3377
+ if (!usedPluginKeys.size && !platformLintDeclarations.length && !installedLintDeclarations.length) {
3378
+ const undeclaredLocations = collectUndeclaredPluginArrayLocations(options.flowWork);
3379
+ if (undeclaredLocations.length) {
3380
+ const message = `\u6D41\u7A0B\u6A21\u677F\u5305\u542B\u63D2\u4EF6\u5F0F\u914D\u7F6E\u4F46\u6CA1\u6709\u4EFB\u4F55\u53EF\u7528\u7684 flow-template-node lint \u58F0\u660E\uFF1A${undeclaredLocations.join(", ")}\u3002\u8BF7\u5148\u540C\u6B65\u5BF9\u5E94\u63D2\u4EF6 Skill\u3002`;
3381
+ return {
3382
+ ok: !options.requireInstalled,
3383
+ errors: options.requireInstalled ? [message] : [],
3384
+ warnings: options.requireInstalled ? [] : [message],
3385
+ plugin_lints: [{
3386
+ plugin: "unknown",
3387
+ plugin_key: "unknown",
3388
+ domain: "flow-template-node",
3389
+ checked_locations: undeclaredLocations,
3390
+ errors: options.requireInstalled ? [message] : [],
3391
+ warnings: options.requireInstalled ? [] : [message]
3392
+ }]
3393
+ };
3394
+ }
3395
+ return {
3396
+ ok: true,
3397
+ errors: [],
3398
+ warnings: [],
3399
+ plugin_lints: []
3400
+ };
3060
3401
  }
3061
- try {
3062
- const parsed = JSON.parse(await readFile7(adapterFile, "utf8"));
3063
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || parsed.version !== 1 || parsed.domain !== item.domain || parsed.plugin_key !== item.plugin_key || parsed.capability_prefix !== item.capability_prefix || !parsed.endpoints || typeof parsed.endpoints !== "object" || Array.isArray(parsed.endpoints)) {
3064
- issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must match manifest and declare endpoints: ${item.adapter}`));
3065
- return;
3402
+ const allPluginKeys = /* @__PURE__ */ new Set([
3403
+ ...platformLintDeclarations.map((item) => item.lint.plugin_key),
3404
+ ...installedLintDeclarations.map((item) => item.lint.plugin_key)
3405
+ ]);
3406
+ for (const pluginKey of usedPluginKeys) {
3407
+ if (allPluginKeys.has(pluginKey)) {
3408
+ continue;
3066
3409
  }
3067
- validatePluginConfigAdapterEndpoints(parsed.endpoints, item.plugin_key, issues, context);
3068
- const capabilities = parsed.capabilities;
3069
- if (capabilities !== void 0) {
3070
- if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
3071
- issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must be an object: ${item.adapter}`));
3072
- return;
3073
- }
3074
- for (const value of Object.values(capabilities)) {
3075
- if (typeof value !== "string" || !value.startsWith(`config.plugin.${item.plugin_key}.`)) {
3076
- issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must stay under config.plugin.${item.plugin_key}.`));
3077
- return;
3078
- }
3410
+ const occurrences = collectFlowTemplatePluginConfigs(options.flowWork, pluginKey);
3411
+ const preservesExistingExtension = hasRemoteFlowIdentity && occurrences.length > 0;
3412
+ const preservesExistingDisabledExtension = preservesExistingExtension && occurrences.every((occurrence) => isExplicitlyDisabledPluginConfig(occurrence.config));
3413
+ const message = preservesExistingDisabledExtension ? `Flow template preserves disabled plugin extension ${pluginKey} without a platform or installed flow-template lint declaration; skipped plugin-specific lint because every occurrence explicitly sets enabled=false.` : preservesExistingExtension ? `Flow template preserves existing plugin extension ${pluginKey} without a platform or installed flow-template lint declaration; skipped plugin-specific lint for compatibility with the existing remote flow.` : `Flow template uses unknown plugin extension ${pluginKey}; no platform or installed flow-template lint declaration was found.`;
3414
+ if (options.requireInstalled && !preservesExistingExtension) {
3415
+ errors.push(message);
3416
+ } else {
3417
+ warnings.push(message);
3418
+ }
3419
+ pluginLints.push({
3420
+ plugin: pluginKey,
3421
+ plugin_key: pluginKey,
3422
+ domain: "flow-template-node",
3423
+ checked_locations: occurrences.map((occurrence) => occurrence.location),
3424
+ errors: options.requireInstalled && !preservesExistingExtension ? [message] : [],
3425
+ warnings: options.requireInstalled && !preservesExistingExtension ? [] : [message]
3426
+ });
3427
+ }
3428
+ for (const pluginKey of allPluginKeys) {
3429
+ const declarations = [
3430
+ ...platformLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey).map((item) => item.lint),
3431
+ ...installedLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey).map((item) => item.lint)
3432
+ ];
3433
+ if (!usedPluginKeys.has(pluginKey) && !declarations.some((item) => item.paths?.length)) {
3434
+ continue;
3435
+ }
3436
+ const occurrences = collectFlowTemplatePluginConfigs(options.flowWork, pluginKey, declarations);
3437
+ if (!occurrences.length) {
3438
+ continue;
3439
+ }
3440
+ const installed = installedLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey);
3441
+ if (!installed.length) {
3442
+ const platform = platformLintDeclarations.find((item) => item.lint.plugin_key === pluginKey);
3443
+ const plugin = platform?.plugin || pluginKey;
3444
+ const message = `Plugin lint for ${pluginKey} is declared but not installed. Run: bpmax-cli plugin skills ensure ${plugin} --profile ${options.profile.name} --agent ${options.agent} --format json`;
3445
+ if (options.requireInstalled) {
3446
+ errors.push(message);
3447
+ } else {
3448
+ warnings.push(message);
3079
3449
  }
3450
+ pluginLints.push({
3451
+ plugin,
3452
+ skill: platform?.skill,
3453
+ plugin_key: pluginKey,
3454
+ domain: "flow-template-node",
3455
+ checked_locations: occurrences.map((item) => item.location),
3456
+ errors: options.requireInstalled ? [message] : [],
3457
+ warnings: options.requireInstalled ? [] : [message]
3458
+ });
3459
+ continue;
3080
3460
  }
3081
- const work = parsed.work;
3082
- if (work !== void 0) {
3083
- if (!work || typeof work !== "object" || Array.isArray(work)) {
3084
- issues.push(issue2("error", "invalid_config_adapter_work", `${context} config adapter work must be an object: ${item.adapter}`));
3085
- return;
3461
+ for (const declaration of installed) {
3462
+ const lintErrors = [];
3463
+ const lintWarnings = [];
3464
+ let ruleFile;
3465
+ try {
3466
+ ruleFile = await readPluginLintRuleFile(declaration.installPath, declaration.lint);
3467
+ } catch (error) {
3468
+ lintErrors.push(error instanceof Error ? error.message : String(error));
3469
+ ruleFile = {};
3086
3470
  }
3087
- const lintPath = work.lint;
3088
- if (lintPath !== void 0) {
3089
- if (typeof lintPath !== "string") {
3090
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
3091
- return;
3092
- }
3093
- const normalizedLintPath = lintPath.replace(/\\/g, "/");
3094
- const lintParts = normalizedLintPath.split("/");
3095
- if (!normalizedLintPath.startsWith("lint/") || lintParts.some((part) => part === "" || part === "." || part === "..") || normalizedLintPath.startsWith("/") || path4.isAbsolute(normalizedLintPath) || !normalizedLintPath.endsWith(".json")) {
3096
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
3097
- return;
3471
+ for (const occurrence of occurrences) {
3472
+ if (shouldSkipPluginLint(occurrence.config, ruleFile.skipWhen)) {
3473
+ continue;
3098
3474
  }
3099
- const lintFile = path4.join(skillDir, normalizedLintPath);
3100
- if (!await exists2(lintFile)) {
3101
- issues.push(issue2("error", "missing_config_adapter_lint", `${context} config adapter lint file not found: ${normalizedLintPath}`));
3102
- return;
3475
+ const rules = Array.isArray(ruleFile.rules) ? ruleFile.rules : [];
3476
+ if (!rules.length) {
3477
+ const message = `${occurrence.location} has no plugin lint rules.`;
3478
+ if (options.requireInstalled) {
3479
+ lintErrors.push(message);
3480
+ } else {
3481
+ lintWarnings.push(message);
3482
+ }
3103
3483
  }
3104
- const lint = JSON.parse(await readFile7(lintFile, "utf8"));
3105
- if (!lint || typeof lint !== "object" || Array.isArray(lint) || lint.version !== 1 || lint.domain !== item.domain || lint.plugin_key !== item.plugin_key || !Array.isArray(lint.rules) || !lint.rules.length) {
3106
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter lint file must match adapter manifest and declare rules: ${normalizedLintPath}`));
3107
- return;
3484
+ for (const rule of rules) {
3485
+ const error = evaluatePluginRule(occurrence.config, rule, occurrence.location);
3486
+ if (error) {
3487
+ lintErrors.push(error);
3488
+ }
3108
3489
  }
3109
3490
  }
3491
+ errors.push(...lintErrors);
3492
+ warnings.push(...lintWarnings);
3493
+ pluginLints.push({
3494
+ plugin: declaration.plugin,
3495
+ skill: declaration.skill,
3496
+ plugin_key: pluginKey,
3497
+ domain: declaration.lint.domain,
3498
+ rule_path: declaration.lint.path,
3499
+ checked_locations: occurrences.map((item) => item.location),
3500
+ errors: lintErrors,
3501
+ warnings: lintWarnings
3502
+ });
3110
3503
  }
3111
- } catch (error) {
3112
- issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must be valid JSON: ${item.adapter}`));
3113
3504
  }
3505
+ return {
3506
+ ok: errors.length === 0,
3507
+ errors,
3508
+ warnings,
3509
+ plugin_lints: pluginLints
3510
+ };
3114
3511
  }
3115
- function validatePluginLintManifest(item, issues, context) {
3116
- if (item.domain !== "flow-template-node") {
3117
- issues.push(issue2("error", "unsupported_lint_domain", `${context} lint domain is not supported: ${item.domain}`));
3118
- }
3119
- if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
3120
- issues.push(issue2("error", "invalid_lint_plugin_key", `${context} lint plugin_key must look like plugin_xxx.`));
3512
+ async function copySkillDirectory(sourceDir, destinationDir) {
3513
+ await rm2(destinationDir, { recursive: true, force: true });
3514
+ await mkdir4(path4.dirname(destinationDir), { recursive: true });
3515
+ await cp2(sourceDir, destinationDir, { recursive: true });
3516
+ }
3517
+
3518
+ // src/commands/auth.ts
3519
+ function deviceStartBody(result) {
3520
+ const configDir = isConfigDirOverridden() ? getConfigDir() : void 0;
3521
+ return {
3522
+ ok: true,
3523
+ ...result,
3524
+ session: result.device_code,
3525
+ ...configDir ? { config_dir: configDir } : {},
3526
+ message_card: buildAuthorizationMessageCard({
3527
+ ...result,
3528
+ ...configDir ? { config_dir: configDir } : {}
3529
+ })
3530
+ };
3531
+ }
3532
+ function shellQuote2(value) {
3533
+ if (/^[A-Za-z0-9_./:@=-]+$/.test(value)) {
3534
+ return value;
3121
3535
  }
3122
- const normalized = item.path.replace(/\\/g, "/");
3123
- const parts = normalized.split("/");
3124
- if (!normalized.startsWith("lint/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
3125
- issues.push(issue2("error", "invalid_lint_path", `${context} lint path must be a lint/*.json file.`));
3536
+ return `'${value.replace(/'/g, `'\\''`)}'`;
3537
+ }
3538
+ function configWorkspaceNextCommands(profileName, cache) {
3539
+ if (!capabilityEnabled(cache, "config.repository.view") || !capabilityEnabled(cache, "config.latest.pull")) {
3540
+ return void 0;
3126
3541
  }
3127
- if (item.paths) {
3128
- item.paths.forEach((scanPath) => {
3129
- if (!isAllowedPluginConfigScanPath(scanPath)) {
3130
- issues.push(issue2("error", "invalid_lint_scan_path", `${context} lint scan path is not supported: ${scanPath}`));
3131
- }
3542
+ const configDirPrefix = isConfigDirOverridden() ? ` --config-dir ${shellQuote2(getConfigDir())}` : "";
3543
+ return {
3544
+ config_workspace_init: `bpmax-cli${configDirPrefix} config workspace init <env> --profile ${profileName} --workspace-dir <dir> --format json`
3545
+ };
3546
+ }
3547
+ async function discoverPluginSkillUpdates(profile, agent) {
3548
+ try {
3549
+ return await ensurePluginSkillsForDomain({
3550
+ client: createApiClient(profile),
3551
+ profile,
3552
+ agent,
3553
+ forceCheck: true
3132
3554
  });
3555
+ } catch (error) {
3556
+ return {
3557
+ ok: false,
3558
+ error: error instanceof Error ? error.message : String(error)
3559
+ };
3133
3560
  }
3134
3561
  }
3135
- function isAllowedPluginConfigScanPath(scanPath) {
3136
- return scanPath === "data.meta.<plugin_key>" || scanPath === "data.nodes[].<plugin_key>" || /^data\.nodes\[\]\.<plugin_key>\.[A-Za-z0-9_]+\[\]$/.test(scanPath) || /^data\.nodes\[\]\.[A-Za-z0-9_]+_(?:triggers|configs|plugins)\[\]$/.test(scanPath);
3562
+ async function fetchCurrentUserForStatus(profile) {
3563
+ const headers = AxiosHeaders2.from();
3564
+ headers.set("Authorization", `Bearer ${profile.config.api_key}`);
3565
+ const response = await axios5.request({
3566
+ method: "GET",
3567
+ baseURL: profile.config.origin,
3568
+ url: "/api/user/current",
3569
+ params: {
3570
+ $workspace: normalizeWorkspaceForApi(profile.config.workspace),
3571
+ $language: profile.config.language
3572
+ },
3573
+ headers
3574
+ });
3575
+ const body = response.data;
3576
+ if (typeof body.code === "number" && body.code !== 0) {
3577
+ throw new Error(body.msg || `Request failed with code ${body.code}`);
3578
+ }
3579
+ return body.data ?? body;
3137
3580
  }
3138
- async function validatePluginLintRuleFiles(skillDir, files, issues) {
3139
- for (const file of files) {
3140
- if (!file.startsWith("lint/") && !file.startsWith("config/") || !file.endsWith(".json")) {
3141
- continue;
3142
- }
3143
- try {
3144
- const parsed = JSON.parse(await readFile7(path4.join(skillDir, file), "utf8"));
3145
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3146
- issues.push(issue2("error", "invalid_plugin_json_file", `${file} must contain a declarative JSON object.`));
3147
- continue;
3148
- }
3149
- if (file.startsWith("lint/") && (!Array.isArray(parsed.rules) || !parsed.rules.length)) {
3150
- issues.push(issue2("error", "empty_lint_rules", `${file} must contain a non-empty rules array.`));
3151
- }
3152
- } catch (error) {
3153
- issues.push(issue2("error", "invalid_plugin_json_file", `${file} must be valid JSON.`));
3581
+ function minimalStatusUser(user) {
3582
+ const safe = {};
3583
+ for (const key of ["id", "user_id", "uid", "name", "nickname", "realname"]) {
3584
+ if (user[key] !== void 0 && user[key] !== null && user[key] !== "") {
3585
+ safe[key] = user[key];
3154
3586
  }
3155
3587
  }
3588
+ return safe;
3156
3589
  }
3157
- async function lintPluginSkillDirectory(skillDir, options = {}) {
3158
- const issues = [];
3159
- const checks = [];
3160
- let skillMarkdown = "";
3161
- let manifest = {};
3162
- try {
3163
- skillMarkdown = await readFile7(path4.join(skillDir, "SKILL.md"), "utf8");
3164
- manifest = parseFrontmatter2(skillMarkdown);
3165
- } catch {
3166
- issues.push(issue2("error", "missing_skill_md", "Plugin skill package must contain top-level SKILL.md."));
3167
- }
3168
- const name = manifest.name;
3169
- const version = manifest.version;
3170
- if (!name || typeof name !== "string") {
3171
- issues.push(issue2("error", "missing_name", "SKILL.md frontmatter must contain name."));
3172
- } else {
3173
- if (!name.startsWith("bpmax-")) {
3174
- issues.push(issue2("error", "invalid_name_prefix", "Plugin skill name must start with bpmax-."));
3175
- }
3176
- validateSafeSkillName(name, issues);
3177
- if (options.expectedName && name !== options.expectedName) {
3178
- issues.push(issue2("error", "name_mismatch", `Plugin skill name ${name} does not match expected ${options.expectedName}.`));
3590
+ function registerAuthCommands(program2, deps = {}) {
3591
+ const load = deps.loadConfig || loadConfig;
3592
+ const save = deps.saveConfig || saveConfig;
3593
+ const startDevice = deps.startDeviceLogin || startDeviceLogin;
3594
+ const completeDevice = deps.completeDeviceLogin || completeDeviceLogin;
3595
+ const pollDevice = deps.pollDeviceLogin || pollDeviceLogin;
3596
+ const shouldProbeCapabilities = !deps.loadConfig && !deps.saveConfig;
3597
+ const auth = program2.command("auth").description("Authenticate and manage API key state");
3598
+ 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: device", "device").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) => {
3599
+ const config = await load();
3600
+ const profile = resolveProfile(config, options.profile);
3601
+ let result;
3602
+ let authorization;
3603
+ if (options.mode && options.mode !== "device") {
3604
+ throw new Error("Browser callback authorization is no longer supported. Use `bpmax-cli auth login --mode device`.");
3179
3605
  }
3180
- if (!options.allowCoreOverwrite) {
3181
- const coreSkillNames = await listCoreSkillNames();
3182
- if (coreSkillNames.has(name)) {
3183
- issues.push(issue2("error", "core_skill_overwrite", `Plugin skill must not overwrite built-in/core skill: ${name}`));
3606
+ authorization = await startDevice({
3607
+ origin: profile.config.origin,
3608
+ workspace: profile.config.workspace,
3609
+ profileName: profile.name,
3610
+ apiKeyName: options.keyName,
3611
+ agent: options.agent,
3612
+ channel: options.channel,
3613
+ requestConfigurationCapability: true
3614
+ });
3615
+ const codeOutput = options.format === "json" ? console.error : console.log;
3616
+ codeOutput(`Open ${authorization.authorization_url}`);
3617
+ codeOutput(`Confirm code: ${authorization.user_code}`);
3618
+ result = await pollDevice({
3619
+ origin: profile.config.origin,
3620
+ deviceCode: authorization.device_code,
3621
+ interval: authorization.interval,
3622
+ expiresIn: authorization.expires_in
3623
+ });
3624
+ config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
3625
+ result = { ...result, user: config.profiles[profile.name].user };
3626
+ await save(config);
3627
+ let capabilitiesProbe;
3628
+ let pluginSkillUpdates;
3629
+ let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
3630
+ if (shouldProbeCapabilities) {
3631
+ try {
3632
+ const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
3633
+ const client = createApiClient(authenticatedProfile);
3634
+ await ensureTerminalRegistered(client, authenticatedProfile);
3635
+ const cache = await refreshCapabilities(client, authenticatedProfile);
3636
+ config.profiles[profile.name].capabilities_cache = cache;
3637
+ capabilitiesCache = cache;
3638
+ capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
3639
+ } catch (error) {
3640
+ capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
3184
3641
  }
3185
3642
  }
3186
- }
3187
- if (!version || typeof version !== "string") {
3188
- issues.push(issue2("error", "missing_version", "SKILL.md frontmatter must contain version."));
3189
- } else if (!semverPattern2.test(version)) {
3190
- issues.push(issue2("error", "invalid_version", "Plugin skill version must be semver, for example 1.0.0."));
3191
- }
3192
- try {
3193
- const files = await collectRelativeFiles(skillDir);
3194
- const invalid = files.map(validateAllowedPath).filter(Boolean);
3195
- issues.push(...invalid);
3196
- await validatePluginLintRuleFiles(skillDir, files, issues);
3197
- checks.push({ name: "allowed_files", files, invalid: invalid.map((item) => item.message) });
3198
- } catch (error) {
3199
- issues.push(issue2("error", "read_failed", error instanceof Error ? error.message : String(error)));
3200
- }
3201
- [
3202
- { pattern: /\brm\s+-rf\b/, code: "dangerous_rm_rf", message: "Dangerous rm -rf command found." },
3203
- { pattern: /\bgit\s+reset\s+--hard\b/, code: "dangerous_git_reset", message: "Dangerous git reset --hard command found." },
3204
- { pattern: /\bgit\s+checkout\s+--\b/, code: "dangerous_git_checkout", message: "Dangerous git checkout -- command found." },
3205
- { pattern: /authorization\s*:\s*bearer|api[_-]?key\s*[:=]\s*['"][^'"]+/i, code: "secret_literal", message: "Possible literal credential found." },
3206
- { pattern: /\bcurl\b[\s\S]{0,160}\b-X\s*(POST|PUT|PATCH|DELETE)\b/i, code: "raw_mutating_curl", message: "Raw mutating curl command found; use bpmax-cli wrappers." }
3207
- ].forEach((rule) => {
3208
- if (rule.pattern.test(skillMarkdown)) {
3209
- issues.push(issue2("error", rule.code, rule.message));
3643
+ if (shouldProbeCapabilities) {
3644
+ const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
3645
+ pluginSkillUpdates = await discoverPluginSkillUpdates(
3646
+ authenticatedProfile,
3647
+ options.agent || process.env.BPMAX_CLI_AGENT || "codex"
3648
+ );
3649
+ }
3650
+ const nextCommands = configWorkspaceNextCommands(profile.name, capabilitiesCache);
3651
+ if (options.format === "json") {
3652
+ printResult("json", {
3653
+ ok: true,
3654
+ profile: profile.name,
3655
+ login: "authenticated",
3656
+ user: result.user,
3657
+ ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
3658
+ ...pluginSkillUpdates ? { plugin_skill_updates: pluginSkillUpdates } : {},
3659
+ ...nextCommands ? { next_commands: nextCommands } : {},
3660
+ ...authorization ? {
3661
+ authorization,
3662
+ message_card: buildAuthorizationMessageCard({
3663
+ ...authorization,
3664
+ ...isConfigDirOverridden() ? { config_dir: getConfigDir() } : {}
3665
+ })
3666
+ } : {}
3667
+ });
3668
+ } else {
3669
+ console.log(`Saved API key for profile "${profile.name}".`);
3210
3670
  }
3211
3671
  });
3212
- return completeReport2({ checks, issues, manifest, skill_dir: skillDir });
3213
- }
3214
- async function lintPluginSkillZip(zipPath, options = {}) {
3215
- try {
3216
- const buffer = await readFile7(zipPath);
3217
- const dir = await zipDirectoryToTemp(buffer, "plugin-skill-lint");
3218
- return lintPluginSkillDirectory(dir, options);
3219
- } catch (error) {
3220
- return completeReport2({
3221
- checks: [],
3222
- manifest: {},
3223
- issues: [issue2("error", "invalid_package", error instanceof Error ? error.message : String(error))]
3672
+ const device = auth.command("device").description("Device authorization for browserless agent environments");
3673
+ 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) => {
3674
+ const config = await load();
3675
+ const profile = resolveProfile(config, options.profile);
3676
+ const result = await startDevice({
3677
+ origin: profile.config.origin,
3678
+ workspace: profile.config.workspace,
3679
+ profileName: profile.name,
3680
+ apiKeyName: options.keyName,
3681
+ agent: options.agent,
3682
+ channel: options.channel,
3683
+ requestConfigurationCapability: true
3684
+ });
3685
+ printResult(options.format, deviceStartBody(result));
3686
+ });
3687
+ 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) => {
3688
+ const deviceCode = options.deviceCode || options.session;
3689
+ if (!deviceCode) {
3690
+ throw new Error("--device-code or --session is required.");
3691
+ }
3692
+ const config = await load();
3693
+ const profile = resolveProfile(config, options.profile);
3694
+ const result = await completeDevice({
3695
+ origin: profile.config.origin,
3696
+ deviceCode
3224
3697
  });
3225
- }
3226
- }
3227
- function pluginSkillStatePath(profileName, agent) {
3228
- assertSafeStateSegment(profileName, "profile");
3229
- assertSafeStateSegment(agent, "agent");
3230
- return path4.join(getConfigDir(), "plugin-skills", profileName, agent, "state.json");
3231
- }
3232
- async function readPluginSkillState(profileName, agent) {
3233
- try {
3234
- return JSON.parse(await readFile7(pluginSkillStatePath(profileName, agent), "utf8"));
3235
- } catch {
3236
- return { plugins: {} };
3237
- }
3238
- }
3239
- async function writePluginSkillState(profileName, agent, state) {
3240
- const target = pluginSkillStatePath(profileName, agent);
3241
- await mkdir4(path4.dirname(target), { recursive: true });
3242
- await writeFile4(target, JSON.stringify(state, null, 2), "utf8");
3243
- }
3244
- async function acquireStateLock2(profileName, agent) {
3245
- const target = pluginSkillStatePath(profileName, agent);
3246
- const lockPath = `${target}.lock`;
3247
- await mkdir4(path4.dirname(target), { recursive: true });
3248
- for (let attempt = 0; attempt < 100; attempt += 1) {
3249
- try {
3250
- await mkdir4(lockPath);
3251
- return lockPath;
3252
- } catch (error) {
3253
- if (error.code !== "EEXIST") {
3254
- throw error;
3698
+ config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
3699
+ const safeUser = config.profiles[profile.name].user;
3700
+ await save(config);
3701
+ let capabilitiesProbe;
3702
+ let pluginSkillUpdates;
3703
+ let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
3704
+ if (shouldProbeCapabilities) {
3705
+ try {
3706
+ const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
3707
+ const client = createApiClient(authenticatedProfile);
3708
+ await ensureTerminalRegistered(client, authenticatedProfile);
3709
+ const cache = await refreshCapabilities(client, authenticatedProfile);
3710
+ config.profiles[profile.name].capabilities_cache = cache;
3711
+ capabilitiesCache = cache;
3712
+ capabilitiesProbe = { status: "ok", count: cache.capabilities.filter((item) => item.enabled).length };
3713
+ } catch (error) {
3714
+ capabilitiesProbe = { status: "failed", error: error instanceof Error ? error.message : String(error) };
3255
3715
  }
3256
- await new Promise((resolve) => setTimeout(resolve, 50));
3257
3716
  }
3258
- }
3259
- throw new Error(`Timed out waiting for plugin skill state lock: ${lockPath}`);
3260
- }
3261
- async function updatePluginSkillState(profileName, agent, updater) {
3262
- const lockPath = await acquireStateLock2(profileName, agent);
3263
- try {
3264
- const state = await readPluginSkillState(profileName, agent);
3265
- const next = await updater(state) ?? state;
3266
- await writePluginSkillState(profileName, agent, next);
3267
- return next;
3268
- } finally {
3269
- await rm2(lockPath, { recursive: true, force: true });
3270
- }
3271
- }
3272
- function resolveDownloadUrl2(profile, url) {
3273
- if (/^https?:\/\//i.test(url)) {
3274
- return url;
3275
- }
3276
- return `${profile.config.origin.replace(/\/$/, "")}${url.startsWith("/") ? url : `/${url}`}`;
3277
- }
3278
- async function downloadPluginSkillPackage(profile, download) {
3279
- const buffer = download.content_base64 ? Buffer.from(download.content_base64, "base64") : Buffer.from(
3280
- (await axios5.get(resolveDownloadUrl2(profile, download.url), {
3281
- responseType: "arraybuffer"
3282
- })).data
3283
- );
3284
- const sha2562 = createHash3("sha256").update(buffer).digest("hex");
3285
- if (download.sha256 && sha2562 !== download.sha256) {
3286
- throw new Error(`Plugin skill checksum mismatch. expected ${download.sha256}, got ${sha2562}`);
3287
- }
3288
- return buffer;
3289
- }
3290
- async function listPluginSkills(client, plugin) {
3291
- if (plugin) {
3292
- const result2 = await apiRequest(
3293
- client,
3294
- "GET",
3295
- `/cli/plugins/${plugin}/skills`
3296
- );
3297
- return Array.isArray(result2) ? result2 : result2.skills || [];
3298
- }
3299
- const result = await apiRequest(
3300
- client,
3301
- "GET",
3302
- "/cli/plugins",
3303
- { params: { include_skills: 1 } }
3304
- );
3305
- if (Array.isArray(result)) {
3306
- return result;
3307
- }
3308
- return (result.plugins || []).flatMap((item) => item.skills || []);
3309
- }
3310
- async function ensurePluginSkill(options) {
3311
- await assertInstallablePluginSkillName(options.skill.name);
3312
- const state = await readPluginSkillState(options.profile.name, options.agent);
3313
- const installed = state.plugins[options.plugin]?.skills[options.skill.name];
3314
- if (!options.force && installed?.version === options.skill.version && installed.sha256 === options.skill.sha256) {
3315
- return {
3316
- action: "in_sync",
3317
- skill: options.skill.name,
3318
- plugin: options.plugin,
3319
- version: installed.version,
3320
- install_path: installed.install_path
3321
- };
3322
- }
3323
- const download = await apiRequest(
3324
- options.client,
3325
- "GET",
3326
- `/cli/plugins/${options.plugin}/skills/${options.skill.name}/download`
3327
- );
3328
- const buffer = await downloadPluginSkillPackage(options.profile, download);
3329
- const skillDir = await zipDirectoryToTemp(buffer, `plugin-skill-${options.plugin}-${options.skill.name}`);
3330
- const lint = await lintPluginSkillDirectory(skillDir, { expectedName: options.skill.name });
3331
- if (!lint.ok) {
3332
- throw new Error(`Plugin skill lint failed:
3333
- - ${lint.errors.map((item) => item.message).join("\n- ")}`);
3334
- }
3335
- const lintManifests = normalizePluginLintManifests(download.manifest?.lint || options.skill.lint);
3336
- const configAdapters = normalizePluginConfigAdapterManifests(download.manifest?.config_adapters || options.skill.config_adapters);
3337
- const lintManifestIssues = [];
3338
- lintManifests.forEach((item) => validatePluginLintManifest(item, lintManifestIssues, `Plugin skill ${options.skill.name}`));
3339
- configAdapters.forEach((item) => validatePluginConfigAdapterManifest(item, lintManifestIssues, `Plugin skill ${options.skill.name}`));
3340
- for (const item of lintManifests) {
3341
- if (!await exists2(path4.join(skillDir, item.path))) {
3342
- lintManifestIssues.push(issue2("error", "missing_lint_file", `Plugin skill ${options.skill.name} lint file not found: ${item.path}`));
3717
+ if (shouldProbeCapabilities) {
3718
+ const authenticatedProfile = resolveProfile(await loadConfig(), profile.name);
3719
+ pluginSkillUpdates = await discoverPluginSkillUpdates(
3720
+ authenticatedProfile,
3721
+ process.env.BPMAX_CLI_AGENT || "codex"
3722
+ );
3343
3723
  }
3344
- }
3345
- await Promise.all(
3346
- configAdapters.map(
3347
- (item) => validatePluginConfigAdapterFile(skillDir, item, lintManifestIssues, `Plugin skill ${options.skill.name}`)
3348
- )
3349
- );
3350
- if (lintManifestIssues.length) {
3351
- throw new Error(`Plugin skill lint manifest failed:
3352
- - ${lintManifestIssues.map((item) => item.message).join("\n- ")}`);
3353
- }
3354
- await installSkillDirectory(skillDir, options.skill.name, options.agent, {
3355
- owner: {
3356
- kind: "plugin",
3357
- profile: options.profile.name,
3358
- plugin: options.plugin,
3359
- skill: options.skill.name,
3360
- version: download.version || options.skill.version,
3361
- sha256: download.sha256
3724
+ const nextCommands = configWorkspaceNextCommands(profile.name, capabilitiesCache);
3725
+ printResult(options.format, {
3726
+ ok: true,
3727
+ profile: profile.name,
3728
+ login: "authenticated",
3729
+ user: safeUser,
3730
+ ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
3731
+ ...pluginSkillUpdates ? { plugin_skill_updates: pluginSkillUpdates } : {},
3732
+ ...nextCommands ? { next_commands: nextCommands } : {}
3733
+ });
3734
+ });
3735
+ auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--verbose", "Include the full /api/user/current response. Default output is minimized and redacted for logs.").option("--format <format>", "Output format", "pretty").action(async (options) => {
3736
+ const config = await load();
3737
+ const profile = resolveProfile(config, options.profile);
3738
+ const output = {
3739
+ profile: profile.name,
3740
+ origin: profile.config.origin,
3741
+ workspace: profile.config.workspace,
3742
+ language: profile.config.language,
3743
+ api_key: maskApiKey(profile.config.api_key)
3744
+ };
3745
+ if (profile.config.api_key) {
3746
+ try {
3747
+ const currentUser = await fetchCurrentUserForStatus(profile);
3748
+ output.user = options.verbose ? currentUser : minimalStatusUser(currentUser);
3749
+ output.user_detail = options.verbose ? "full" : "minimal";
3750
+ output.authenticated = true;
3751
+ } catch (error) {
3752
+ const message = error instanceof Error ? error.message : String(error);
3753
+ if (message.includes(CLI_GOVERNANCE_UNSUPPORTED_MESSAGE)) {
3754
+ output.authenticated = "unknown";
3755
+ output.platform_cli_governance = "unsupported";
3756
+ output.error = message;
3757
+ output.next = "Upgrade huanpingtong-server to enable CLI governance, or validate this API key with a CLI version that matches the old platform.";
3758
+ } else {
3759
+ output.authenticated = false;
3760
+ output.error = message;
3761
+ }
3762
+ }
3763
+ } else {
3764
+ output.authenticated = false;
3362
3765
  }
3766
+ printResult(options.format, output);
3363
3767
  });
3364
- const installPath = await installProfilePluginSkillDirectory(
3365
- skillDir,
3366
- options.profile.name,
3367
- options.agent,
3368
- options.skill.name
3369
- );
3370
- await updatePluginSkillState(options.profile.name, options.agent, (current) => {
3371
- current.plugins[options.plugin] ||= { skills: {} };
3372
- current.plugins[options.plugin].skills[options.skill.name] = {
3373
- name: options.skill.name,
3374
- plugin: options.plugin,
3375
- version: download.version || options.skill.version,
3376
- sha256: download.sha256,
3377
- install_path: installPath,
3378
- domains: options.skill.domains || [],
3379
- capabilities: options.skill.capabilities || [],
3380
- lint: lintManifests,
3381
- config_adapters: configAdapters,
3382
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
3768
+ auth.command("logout").description("Clear the stored API key for the selected profile").option("--profile <profile>", "Profile name").action(async (options) => {
3769
+ const config = await load();
3770
+ const profile = resolveProfile(config, options.profile);
3771
+ config.profiles[profile.name] = {
3772
+ ...config.profiles[profile.name],
3773
+ api_key: "",
3774
+ user: void 0,
3775
+ terminal_id: void 0,
3776
+ terminal_status: void 0,
3777
+ terminal_registered_at: void 0
3383
3778
  };
3779
+ await save(config);
3780
+ console.log(`Cleared API key for profile "${profile.name}".`);
3384
3781
  });
3385
- return {
3386
- action: installed ? "updated" : "installed",
3387
- skill: options.skill.name,
3388
- plugin: options.plugin,
3389
- version: download.version || options.skill.version,
3390
- install_path: installPath
3391
- };
3392
3782
  }
3393
- function getPathValue(source, pathExpression) {
3394
- if (!pathExpression || pathExpression === "$" || pathExpression === ".") {
3395
- return source;
3396
- }
3397
- const parts = pathExpression.replace(/^\$\.?/, "").split(".").filter(Boolean);
3398
- let current = source;
3399
- for (const part of parts) {
3400
- if (current === null || typeof current !== "object" || Array.isArray(current)) {
3401
- return void 0;
3402
- }
3403
- current = current[part];
3404
- }
3405
- return current;
3783
+
3784
+ // src/commands/bbs.ts
3785
+ import { basename } from "path";
3786
+ import { randomUUID as randomUUID2 } from "crypto";
3787
+ import { readFile as readFile7 } from "fs/promises";
3788
+
3789
+ // src/core/urls.ts
3790
+ function stripSlashes(value) {
3791
+ return value.trim().replace(/^\/+|\/+$/g, "");
3406
3792
  }
3407
- function isNonEmptyValue(value) {
3408
- if (typeof value === "string") {
3409
- return value.trim().length > 0;
3793
+ function isRecord2(value) {
3794
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3795
+ }
3796
+ function normalizeWorkspaceForUrl(workspace) {
3797
+ const nextWorkspace = stripSlashes(workspace);
3798
+ if (!nextWorkspace) {
3799
+ throw new Error("Workspace is required to build a BPMAX URL.");
3410
3800
  }
3411
- if (Array.isArray(value)) {
3412
- return value.length > 0;
3801
+ if (nextWorkspace === "default" || nextWorkspace.startsWith("w:")) {
3802
+ return nextWorkspace;
3413
3803
  }
3414
- return value !== void 0 && value !== null && value !== "";
3804
+ return `w:${nextWorkspace}`;
3415
3805
  }
3416
- function shouldSkipPluginLint(config, skipRules) {
3417
- if (!Array.isArray(skipRules) || !skipRules.length) {
3418
- return false;
3806
+ function normalizeOrigin2(origin) {
3807
+ const nextOrigin = origin.trim().replace(/\/+$/, "");
3808
+ if (!nextOrigin) {
3809
+ throw new Error("Origin is required to build a BPMAX URL.");
3419
3810
  }
3420
- return skipRules.some((rule) => getPathValue(config, rule.path) === rule.equals);
3811
+ return nextOrigin;
3421
3812
  }
3422
- function evaluatePluginRule(config, rule, location) {
3423
- const type = String(rule.type || "");
3424
- const value = getPathValue(config, rule.path);
3425
- const label = rule.path ? `${location}.${rule.path}` : location;
3426
- if (rule.optional && (value === void 0 || value === null || value === "")) {
3427
- return void 0;
3813
+ function requireNumericId(value, name) {
3814
+ const nextValue = String(value || "").trim();
3815
+ if (!/^\d+$/.test(nextValue)) {
3816
+ throw new Error(`${name} must be a non-empty numeric string.`);
3428
3817
  }
3429
- if (type === "object") {
3430
- const target = rule.path ? value : config;
3431
- if (target === null || typeof target !== "object" || Array.isArray(target)) {
3432
- return rule.message || `${label} must be an object.`;
3818
+ return nextValue;
3819
+ }
3820
+ function withQuery(path16, query) {
3821
+ const params = new URLSearchParams();
3822
+ for (const [key, value] of Object.entries(query)) {
3823
+ if (value !== void 0) {
3824
+ params.set(key, value);
3433
3825
  }
3434
- return void 0;
3435
3826
  }
3436
- if (type === "requiredAny") {
3437
- const paths = Array.isArray(rule.paths) ? rule.paths : [];
3438
- if (!paths.some((item) => isNonEmptyValue(getPathValue(config, item)))) {
3439
- return rule.message || `${location} requires at least one of: ${paths.join(", ")}.`;
3440
- }
3441
- return void 0;
3827
+ return `${path16}?${params.toString()}`;
3828
+ }
3829
+ function buildBpmaxUrl(profile, kind, params = {}) {
3830
+ const origin = normalizeOrigin2(profile.config.origin);
3831
+ const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
3832
+ const basePath = `/${workspace}`;
3833
+ let path16 = basePath;
3834
+ const result = {
3835
+ kind,
3836
+ profile: profile.name,
3837
+ origin,
3838
+ workspace
3839
+ };
3840
+ if (kind === "project-list") {
3841
+ path16 = `${basePath}/project`;
3842
+ } else if (kind === "project-detail") {
3843
+ const projectId = requireNumericId(params.projectId, "projectId");
3844
+ path16 = `${basePath}/project_detail/0/${projectId}`;
3845
+ result.project_id = projectId;
3846
+ } else if (kind === "project-step") {
3847
+ const projectId = requireNumericId(params.projectId, "projectId");
3848
+ const stepId = requireNumericId(params.stepId, "stepId");
3849
+ path16 = withQuery(`${basePath}/projectContinue`, {
3850
+ id: projectId,
3851
+ step_id: stepId
3852
+ });
3853
+ result.project_id = projectId;
3854
+ result.step_id = stepId;
3855
+ } else if (kind === "project-create") {
3856
+ const flowType = params.flowType || "default";
3857
+ const flowKey = params.flowKey || "";
3858
+ const initValue = params.initValue ? JSON.stringify(params.initValue) : void 0;
3859
+ const prefillToken = params.prefillToken;
3860
+ const query = {
3861
+ flow_type: flowType,
3862
+ flow_key: flowKey,
3863
+ ...flowKey ? { key: flowKey } : {},
3864
+ ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
3865
+ };
3866
+ path16 = withQuery(`${basePath}/project/create`, query);
3867
+ result.flow_type = flowType;
3868
+ result.flow_key = flowKey;
3869
+ result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
3442
3870
  }
3443
- if (type === "nonEmptyString") {
3444
- if (typeof value !== "string" || !value.trim()) {
3445
- return rule.message || `${label} must be a non-empty string.`;
3446
- }
3871
+ const url = `${origin}${path16}`;
3872
+ return {
3873
+ ...result,
3874
+ path: path16,
3875
+ url,
3876
+ ...kind === "project-create" ? { pc_url: url } : {}
3877
+ };
3878
+ }
3879
+ function extractProjectId(value) {
3880
+ if (!isRecord2(value)) {
3447
3881
  return void 0;
3448
3882
  }
3449
- if (type === "nonEmptyArray") {
3450
- if (!Array.isArray(value) || !value.length) {
3451
- return rule.message || `${label} must be a non-empty array.`;
3452
- }
3883
+ const candidates = [value.id, value.project_id, value.projectId];
3884
+ const candidate = candidates.find((item) => item !== void 0 && item !== null);
3885
+ if (candidate === void 0) {
3453
3886
  return void 0;
3454
3887
  }
3455
- if (type === "positiveNumber") {
3456
- const numericValue = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
3457
- if (!Number.isFinite(numericValue) || numericValue <= 0) {
3458
- return rule.message || `${label} must be a positive number.`;
3459
- }
3460
- return void 0;
3888
+ const projectId = String(candidate).trim();
3889
+ return /^\d+$/.test(projectId) ? projectId : void 0;
3890
+ }
3891
+ function attachProjectDetailUrl(profile, value) {
3892
+ if (!isRecord2(value) || typeof value.url === "string") {
3893
+ return value;
3461
3894
  }
3462
- if (type === "enum") {
3463
- const values = Array.isArray(rule.values) ? rule.values : [];
3464
- if (!values.includes(value)) {
3465
- return rule.message || `${label} must be one of ${values.map((item) => String(item)).join(", ")}.`;
3466
- }
3467
- return void 0;
3895
+ const projectId = extractProjectId(value);
3896
+ if (!projectId) {
3897
+ return value;
3468
3898
  }
3469
- return `${location} has unsupported plugin lint rule type: ${type || "(missing)"}.`;
3899
+ return {
3900
+ ...value,
3901
+ url: buildBpmaxUrl(profile, "project-detail", { projectId }).url
3902
+ };
3470
3903
  }
3471
- function collectFlowTemplatePluginConfigs(flowWork, pluginKey, lintManifests = []) {
3472
- const scanPaths = new Set(lintManifests.flatMap((item) => item.paths || []));
3473
- if (scanPaths.size) {
3474
- const occurrences = [];
3475
- scanPaths.forEach((scanPath) => {
3476
- occurrences.push(...collectFlowTemplatePluginConfigsByPath(flowWork, scanPath, pluginKey));
3477
- });
3478
- return occurrences;
3904
+
3905
+ // src/commands/bbs.ts
3906
+ async function zipPayload(zipPath) {
3907
+ const buffer = await readFile7(zipPath);
3908
+ return {
3909
+ zip_base64: buffer.toString("base64"),
3910
+ file_name: basename(zipPath)
3911
+ };
3912
+ }
3913
+ function defaultAgent(options) {
3914
+ return options.agent || process.env.BPMAX_CLI_AGENT || "openclaw";
3915
+ }
3916
+ function assertLintPassed(report, allowLintErrors) {
3917
+ if (!report.ok && !allowLintErrors) {
3918
+ throw new Error(`BBS lint failed:
3919
+ - ${report.errors.map((item) => item.message).join("\n- ")}`);
3479
3920
  }
3480
- return collectDefaultFlowTemplatePluginConfigs(flowWork, pluginKey);
3481
3921
  }
3482
- function collectDefaultFlowTemplatePluginConfigs(flowWork, pluginKey) {
3483
- const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3484
- const meta = typeof data.meta === "object" && data.meta !== null && !Array.isArray(data.meta) ? data.meta : {};
3485
- const occurrences = [];
3486
- if (Object.prototype.hasOwnProperty.call(meta, pluginKey)) {
3487
- occurrences.push({ location: `data.meta.${pluginKey}`, config: meta[pluginKey] });
3922
+ async function readJsonSummary(input) {
3923
+ if (!input) {
3924
+ return void 0;
3488
3925
  }
3489
- const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3490
- nodes.forEach((node, index) => {
3491
- if (node && typeof node === "object" && !Array.isArray(node) && Object.prototype.hasOwnProperty.call(node, pluginKey)) {
3492
- const nodeRecord = node;
3493
- const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${index}]`;
3494
- occurrences.push({ location: `${nodeName}.${pluginKey}`, config: nodeRecord[pluginKey] });
3926
+ return redactAuditValue(await parseJsonInput(input, "BBS invocation JSON"));
3927
+ }
3928
+ function registerBbsCommands(program2) {
3929
+ const bbs = program2.command("bbs").description("Manage BPMAX Business Skills");
3930
+ const invocation = bbs.command("invocation").description("Record BBS business invocation audit logs");
3931
+ invocation.command("start").description("Start a BBS business invocation audit log").requiredOption("--skill-key <key>", "BBS key").requiredOption("--action <action>", "BBS business action").option("--skill-name <name>", "BBS display name").option("--skill-version <version>", "BBS version").option("--source <source>", "Invocation source", "manual").option("--args <jsonOrFile>", "Invocation args JSON or @file.json").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
3932
+ const profile = resolveProfile(await loadConfig(), options.profile);
3933
+ const client = createApiClient(profile);
3934
+ await ensureTerminalRegistered(client, profile);
3935
+ const result = await apiRequest(
3936
+ client,
3937
+ "POST",
3938
+ "/cli/bbs_invocations/start",
3939
+ {
3940
+ data: {
3941
+ bbs_key: options.skillKey,
3942
+ bbs_name: options.skillName || "",
3943
+ bbs_version: options.skillVersion || "",
3944
+ action: options.action,
3945
+ source: options.source || "manual",
3946
+ workspace: profile.config.workspace,
3947
+ request_id: randomUUID2(),
3948
+ args_summary: await readJsonSummary(options.args)
3949
+ }
3950
+ }
3951
+ );
3952
+ printResult(options.format, result);
3953
+ });
3954
+ invocation.command("finish").description("Finish a BBS business invocation audit log").requiredOption("--audit-id <id>", "BBS invocation audit id").requiredOption("--status <status>", "Invocation status: success, failed, or blocked").option("--result <jsonOrFile>", "Invocation result JSON or @file.json").option("--error <text>", "Invocation error summary").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
3955
+ if (!["success", "failed", "blocked"].includes(options.status)) {
3956
+ throw new Error("status must be success, failed, or blocked.");
3495
3957
  }
3958
+ const profile = resolveProfile(await loadConfig(), options.profile);
3959
+ const client = createApiClient(profile);
3960
+ await ensureTerminalRegistered(client, profile);
3961
+ const result = await apiRequest(
3962
+ client,
3963
+ "POST",
3964
+ "/cli/bbs_invocations/finish",
3965
+ {
3966
+ data: {
3967
+ audit_id: options.auditId,
3968
+ status: options.status,
3969
+ result_summary: await readJsonSummary(options.result),
3970
+ error_summary: redactAuditValue(options.error || "")
3971
+ }
3972
+ }
3973
+ );
3974
+ printResult(options.format, result);
3975
+ });
3976
+ bbs.command("list").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
3977
+ const profile = resolveProfile(await loadConfig(), options.profile);
3978
+ const result = await apiRequest(createApiClient(profile), "GET", "/business_skill");
3979
+ printResult(options.format, result);
3980
+ });
3981
+ bbs.command("show <keyOrId>").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
3982
+ const profile = resolveProfile(await loadConfig(), options.profile);
3983
+ const result = await fetchBusinessSkillByKeyOrId(createApiClient(profile), keyOrId);
3984
+ printResult(options.format, result);
3985
+ });
3986
+ bbs.command("lint").requiredOption("--zip <path>", "Skill zip path").option("--format <format>", "Output format", "json").action(async (options) => {
3987
+ const report = await lintBusinessSkillZip(options.zip);
3988
+ printResult(options.format, report);
3989
+ });
3990
+ bbs.command("create").requiredOption("--zip <path>", "Skill zip path").option("--name <name>", "BBS display name").option("--key <key>", "BBS key").option("--scene <scene>", "BBS scene").option("--description <description>", "BBS description").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
3991
+ const lintReport2 = await lintBusinessSkillZip(options.zip);
3992
+ assertLintPassed(lintReport2, options.allowLintErrors);
3993
+ const profile = resolveProfile(await loadConfig(), options.profile);
3994
+ const data = {
3995
+ ...await zipPayload(options.zip),
3996
+ name: options.name,
3997
+ key: options.key,
3998
+ scene: options.scene,
3999
+ description: options.description
4000
+ };
4001
+ const result = await apiRequest(createApiClient(profile), "POST", "/business_skill", { data });
4002
+ printResult(options.format, {
4003
+ ...typeof result === "object" && result !== null ? result : { result },
4004
+ lint_report: lintReport2,
4005
+ ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
4006
+ });
3496
4007
  });
3497
- return occurrences;
3498
- }
3499
- function collectFlowTemplatePluginConfigsByPath(flowWork, scanPath, pluginKey) {
3500
- if (scanPath === "data.meta.<plugin_key>") {
3501
- const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3502
- const meta = typeof data2.meta === "object" && data2.meta !== null && !Array.isArray(data2.meta) ? data2.meta : {};
3503
- return Object.prototype.hasOwnProperty.call(meta, pluginKey) ? [{ location: `data.meta.${pluginKey}`, config: meta[pluginKey] }] : [];
3504
- }
3505
- if (scanPath === "data.nodes[].<plugin_key>") {
3506
- const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3507
- const nodes2 = Array.isArray(data2.nodes) ? data2.nodes : [];
3508
- const occurrences2 = [];
3509
- nodes2.forEach((node, nodeIndex) => {
3510
- if (!node || typeof node !== "object" || Array.isArray(node)) {
3511
- return;
3512
- }
3513
- const nodeRecord = node;
3514
- if (!Object.prototype.hasOwnProperty.call(nodeRecord, pluginKey)) {
3515
- return;
3516
- }
3517
- const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3518
- occurrences2.push({ location: `${nodeName}.${pluginKey}`, config: nodeRecord[pluginKey] });
4008
+ bbs.command("upgrade <keyOrId>").requiredOption("--zip <path>", "Skill zip path").option("--release-note <text>", "Release note").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
4009
+ const profile = resolveProfile(await loadConfig(), options.profile);
4010
+ const client = createApiClient(profile);
4011
+ const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
4012
+ const lintReport2 = await lintBusinessSkillZip(options.zip, { latestVersion: skill.latest_version });
4013
+ assertLintPassed(lintReport2, options.allowLintErrors);
4014
+ const data = {
4015
+ ...await zipPayload(options.zip),
4016
+ release_note: options.releaseNote
4017
+ };
4018
+ const result = await apiRequest(client, "POST", `/business_skill/${skill.id}/versions`, { data });
4019
+ printResult(options.format, {
4020
+ ...typeof result === "object" && result !== null ? result : { result },
4021
+ lint_report: lintReport2,
4022
+ ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
3519
4023
  });
3520
- return occurrences2;
3521
- }
3522
- const pluginArrayMatch = scanPath.match(/^data\.nodes\[\]\.<plugin_key>\.([A-Za-z0-9_]+)\[\]$/);
3523
- if (pluginArrayMatch) {
3524
- const field2 = pluginArrayMatch[1];
3525
- const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3526
- const nodes2 = Array.isArray(data2.nodes) ? data2.nodes : [];
3527
- const occurrences2 = [];
3528
- nodes2.forEach((node, nodeIndex) => {
3529
- if (!node || typeof node !== "object" || Array.isArray(node)) {
3530
- return;
3531
- }
3532
- const nodeRecord = node;
3533
- const pluginConfig = nodeRecord[pluginKey];
3534
- if (!pluginConfig || typeof pluginConfig !== "object" || Array.isArray(pluginConfig)) {
3535
- return;
3536
- }
3537
- const values = pluginConfig[field2];
3538
- if (!Array.isArray(values)) {
3539
- return;
4024
+ });
4025
+ bbs.command("gate <keyOrId>").requiredOption("--stage <stage>", "Gate stage, for example preflight or verify").requiredOption("--input <json>", "Gate input JSON or @file").option("--skill-dir <path>", "Installed skill directory override").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
4026
+ const profile = resolveProfile(await loadConfig(), options.profile);
4027
+ const agent = defaultAgent(options);
4028
+ const input = await parseJsonInput(options.input, "Gate input");
4029
+ let skillDir = options.skillDir;
4030
+ if (!skillDir) {
4031
+ const state = await readBusinessSkillState(profile.name, agent);
4032
+ const installed = state.skills[keyOrId];
4033
+ if (!installed) {
4034
+ throw new Error(`BBS ${keyOrId} is not installed for agent ${agent}. Run: bpmax-cli bbs ensure ${keyOrId} --agent ${agent}`);
3540
4035
  }
3541
- const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3542
- values.forEach((value, valueIndex) => {
3543
- occurrences2.push({
3544
- location: `${nodeName}.${pluginKey}.${field2}[${valueIndex}]`,
3545
- config: value
3546
- });
3547
- });
3548
- });
3549
- return occurrences2;
3550
- }
3551
- const match = scanPath.match(/^data\.nodes\[\]\.([A-Za-z0-9_]+)\[\]$/);
3552
- if (!match) {
3553
- return [];
3554
- }
3555
- const field = match[1];
3556
- const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3557
- const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3558
- const occurrences = [];
3559
- nodes.forEach((node, nodeIndex) => {
3560
- if (!node || typeof node !== "object" || Array.isArray(node)) {
3561
- return;
3562
- }
3563
- const nodeRecord = node;
3564
- const values = nodeRecord[field];
3565
- if (!Array.isArray(values)) {
3566
- return;
4036
+ skillDir = installed.install_path;
3567
4037
  }
3568
- const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3569
- values.forEach((value, valueIndex) => {
3570
- occurrences.push({
3571
- location: `${nodeName}.${field}[${valueIndex}]`,
3572
- config: value
3573
- });
4038
+ const projectId = input.project_id;
4039
+ const projectUrl = typeof projectId === "number" || typeof projectId === "string" ? buildBpmaxUrl(profile, "project-detail", { projectId: String(projectId) }).url : void 0;
4040
+ const report = await runBusinessSkillGate({
4041
+ skill: keyOrId,
4042
+ stage: options.stage,
4043
+ skillDir,
4044
+ input,
4045
+ projectUrl
3574
4046
  });
3575
- });
3576
- return occurrences;
3577
- }
3578
- function collectFlowTemplatePluginKeys(flowWork) {
3579
- const data = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3580
- const meta = typeof data.meta === "object" && data.meta !== null && !Array.isArray(data.meta) ? data.meta : {};
3581
- const keys = /* @__PURE__ */ new Set();
3582
- Object.keys(meta).forEach((key) => {
3583
- if (/^plugin_[A-Za-z0-9_]+$/.test(key)) {
3584
- keys.add(key);
4047
+ if (!report.ok) {
4048
+ throw new Error(`BBS gate failed:
4049
+ - ${report.errors.map((item) => item.message).join("\n- ")}`);
3585
4050
  }
4051
+ printResult(options.format, report);
3586
4052
  });
3587
- const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3588
- nodes.forEach((node) => {
3589
- if (!node || typeof node !== "object" || Array.isArray(node)) {
3590
- return;
3591
- }
3592
- Object.keys(node).forEach((key) => {
3593
- if (/^plugin_[A-Za-z0-9_]+$/.test(key)) {
3594
- keys.add(key);
3595
- }
4053
+ bbs.command("sync").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
4054
+ const profile = resolveProfile(await loadConfig(), options.profile);
4055
+ const agent = defaultAgent(options);
4056
+ const result = await apiRequest(
4057
+ createApiClient(profile),
4058
+ "GET",
4059
+ "/business_skill",
4060
+ { params: { page_size: 1e3 } }
4061
+ );
4062
+ const skills = Array.isArray(result) ? result : result.data || [];
4063
+ const catalog = await buildCatalogSkill(skills);
4064
+ const installPath = await installSkillDirectory(catalog.dir, "bpmax-business-skill-catalog", agent);
4065
+ await updateBusinessSkillState(profile.name, agent, (state) => {
4066
+ state.catalog = {
4067
+ checksum: catalog.checksum,
4068
+ install_path: installPath,
4069
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
4070
+ };
4071
+ });
4072
+ printResult(options.format, {
4073
+ action: "synced",
4074
+ agent,
4075
+ installed: "bpmax-business-skill-catalog",
4076
+ install_path: installPath,
4077
+ skills_count: skills.length
3596
4078
  });
3597
4079
  });
3598
- return [...keys];
3599
- }
3600
- function isExplicitlyDisabledPluginConfig(config) {
3601
- return Boolean(
3602
- config && typeof config === "object" && !Array.isArray(config) && config.enabled === false
3603
- );
3604
- }
3605
- async function readPluginLintRuleFile(skillInstallPath, lintManifest) {
3606
- const fullPath = path4.join(skillInstallPath, lintManifest.path);
3607
- const value = JSON.parse(await readFile7(fullPath, "utf8"));
3608
- if (value.domain && value.domain !== lintManifest.domain) {
3609
- throw new Error(`Plugin lint rule domain mismatch for ${lintManifest.path}.`);
3610
- }
3611
- if (value.plugin_key && value.plugin_key !== lintManifest.plugin_key) {
3612
- throw new Error(`Plugin lint rule plugin_key mismatch for ${lintManifest.path}.`);
3613
- }
3614
- return value;
3615
- }
3616
- async function lintFlowTemplatePluginExtensions(options) {
3617
- const errors = [];
3618
- const warnings = [];
3619
- const pluginLints = [];
3620
- const platformSkills = options.platformSkills || [];
3621
- const state = await readPluginSkillState(options.profile.name, options.agent);
3622
- const platformLintDeclarations = platformSkills.flatMap(
3623
- (skill) => normalizePluginLintManifests(skill.lint).map((lint) => ({
3624
- plugin: skill.plugin || "",
3625
- skill: skill.name,
3626
- lint
3627
- }))
3628
- ).filter((item) => item.plugin && item.lint.domain === "flow-template-node");
3629
- const installedLintDeclarations = Object.values(state.plugins).flatMap(
3630
- (pluginState) => Object.values(pluginState.skills).flatMap(
3631
- (skill) => normalizePluginLintManifests(skill.lint).map((lint) => ({
3632
- plugin: skill.plugin,
3633
- skill: skill.name,
3634
- installPath: skill.install_path,
3635
- lint
3636
- }))
3637
- )
3638
- ).filter((item) => item.lint.domain === "flow-template-node");
3639
- const usedPluginKeys = new Set(collectFlowTemplatePluginKeys(options.flowWork));
3640
- const hasRemoteFlowIdentity = typeof options.flowWork.flow_type === "string" && options.flowWork.flow_type.trim().length > 0;
3641
- if (!usedPluginKeys.size && !platformLintDeclarations.length && !installedLintDeclarations.length) {
3642
- return {
3643
- ok: true,
3644
- errors: [],
3645
- warnings: [],
3646
- plugin_lints: []
3647
- };
3648
- }
3649
- const allPluginKeys = /* @__PURE__ */ new Set([
3650
- ...platformLintDeclarations.map((item) => item.lint.plugin_key),
3651
- ...installedLintDeclarations.map((item) => item.lint.plugin_key)
3652
- ]);
3653
- for (const pluginKey of usedPluginKeys) {
3654
- if (allPluginKeys.has(pluginKey)) {
3655
- continue;
3656
- }
3657
- const occurrences = collectFlowTemplatePluginConfigs(options.flowWork, pluginKey);
3658
- const preservesExistingExtension = hasRemoteFlowIdentity && occurrences.length > 0;
3659
- const preservesExistingDisabledExtension = preservesExistingExtension && occurrences.every((occurrence) => isExplicitlyDisabledPluginConfig(occurrence.config));
3660
- const message = preservesExistingDisabledExtension ? `Flow template preserves disabled plugin extension ${pluginKey} without a platform or installed flow-template lint declaration; skipped plugin-specific lint because every occurrence explicitly sets enabled=false.` : preservesExistingExtension ? `Flow template preserves existing plugin extension ${pluginKey} without a platform or installed flow-template lint declaration; skipped plugin-specific lint for compatibility with the existing remote flow.` : `Flow template uses unknown plugin extension ${pluginKey}; no platform or installed flow-template lint declaration was found.`;
3661
- if (options.requireInstalled && !preservesExistingExtension) {
3662
- errors.push(message);
3663
- } else {
3664
- warnings.push(message);
4080
+ async function ensureSkill(keyOrId, options) {
4081
+ const profile = resolveProfile(await loadConfig(), options.profile);
4082
+ const agent = defaultAgent(options);
4083
+ const client = createApiClient(profile);
4084
+ const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
4085
+ const state = await readBusinessSkillState(profile.name, agent);
4086
+ const installed = state.skills[skill.key];
4087
+ if (!options.force && installed?.version === skill.latest_version) {
4088
+ printResult(options.format, { action: "in_sync", agent, skill: skill.key, version: installed.version });
4089
+ return;
3665
4090
  }
3666
- pluginLints.push({
3667
- plugin: pluginKey,
3668
- plugin_key: pluginKey,
3669
- domain: "flow-template-node",
3670
- checked_locations: occurrences.map((occurrence) => occurrence.location),
3671
- errors: options.requireInstalled && !preservesExistingExtension ? [message] : [],
3672
- warnings: options.requireInstalled && !preservesExistingExtension ? [] : [message]
4091
+ const download = await apiRequest(
4092
+ client,
4093
+ "GET",
4094
+ `/business_skill/${skill.id}/download`,
4095
+ { params: skill.latest_version ? { version: skill.latest_version } : void 0 }
4096
+ );
4097
+ const buffer = await downloadBusinessSkillPackage(profile, download);
4098
+ const skillDir = await zipDirectoryToTemp(buffer, `bbs-${skill.key}`);
4099
+ const installPath = await installSkillDirectory(skillDir, skill.key, agent);
4100
+ await updateBusinessSkillState(profile.name, agent, (current) => {
4101
+ current.skills[skill.key] = {
4102
+ id: skill.id,
4103
+ key: skill.key,
4104
+ name: skill.name,
4105
+ version: download.version,
4106
+ checksum: download.checksum,
4107
+ install_path: installPath,
4108
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
4109
+ };
3673
4110
  });
3674
- }
3675
- for (const pluginKey of allPluginKeys) {
3676
- const declarations = [
3677
- ...platformLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey).map((item) => item.lint),
3678
- ...installedLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey).map((item) => item.lint)
3679
- ];
3680
- if (!usedPluginKeys.has(pluginKey) && !declarations.some((item) => item.paths?.length)) {
3681
- continue;
3682
- }
3683
- const occurrences = collectFlowTemplatePluginConfigs(options.flowWork, pluginKey, declarations);
3684
- if (!occurrences.length) {
3685
- continue;
3686
- }
3687
- const installed = installedLintDeclarations.filter((item) => item.lint.plugin_key === pluginKey);
3688
- if (!installed.length) {
3689
- const platform = platformLintDeclarations.find((item) => item.lint.plugin_key === pluginKey);
3690
- const plugin = platform?.plugin || pluginKey;
3691
- const message = `Plugin lint for ${pluginKey} is declared but not installed. Run: bpmax-cli plugin skills ensure ${plugin} --profile ${options.profile.name} --agent ${options.agent} --format json`;
3692
- if (options.requireInstalled) {
3693
- errors.push(message);
3694
- } else {
3695
- warnings.push(message);
4111
+ await apiRequest(client, "POST", "/business_skill/install_record", {
4112
+ data: {
4113
+ skill_id: skill.id,
4114
+ version_id: download.version_id,
4115
+ version: download.version,
4116
+ agent,
4117
+ action: installed ? "update" : options.action || "install",
4118
+ status: "success",
4119
+ cli_version: VERSION,
4120
+ install_path: installPath
3696
4121
  }
3697
- pluginLints.push({
3698
- plugin,
3699
- skill: platform?.skill,
3700
- plugin_key: pluginKey,
3701
- domain: "flow-template-node",
3702
- checked_locations: occurrences.map((item) => item.location),
3703
- errors: options.requireInstalled ? [message] : [],
3704
- warnings: options.requireInstalled ? [] : [message]
4122
+ });
4123
+ printResult(options.format, {
4124
+ action: installed ? "updated" : "installed",
4125
+ agent,
4126
+ skill: skill.key,
4127
+ version: download.version,
4128
+ install_path: installPath
4129
+ });
4130
+ }
4131
+ bbs.command("ensure <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
4132
+ (keyOrId, options) => ensureSkill(keyOrId, options)
4133
+ );
4134
+ bbs.command("install <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
4135
+ (keyOrId, options) => ensureSkill(keyOrId, { ...options, force: true, action: "install" })
4136
+ );
4137
+ bbs.command("update <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(
4138
+ (keyOrId, options) => ensureSkill(keyOrId, { ...options, force: true, action: "update" })
4139
+ );
4140
+ bbs.command("uninstall <keyOrId>").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
4141
+ const profile = resolveProfile(await loadConfig(), options.profile);
4142
+ const agent = defaultAgent(options);
4143
+ const client = createApiClient(profile);
4144
+ const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
4145
+ const state = await readBusinessSkillState(profile.name, agent);
4146
+ const installed = state.skills[skill.key];
4147
+ if (installed) {
4148
+ const { rm: rm5 } = await import("fs/promises");
4149
+ await rm5(installed.install_path, { recursive: true, force: true });
4150
+ await updateBusinessSkillState(profile.name, agent, (current) => {
4151
+ delete current.skills[skill.key];
3705
4152
  });
3706
- continue;
3707
4153
  }
3708
- for (const declaration of installed) {
3709
- const lintErrors = [];
3710
- const lintWarnings = [];
3711
- let ruleFile;
3712
- try {
3713
- ruleFile = await readPluginLintRuleFile(declaration.installPath, declaration.lint);
3714
- } catch (error) {
3715
- lintErrors.push(error instanceof Error ? error.message : String(error));
3716
- ruleFile = {};
3717
- }
3718
- for (const occurrence of occurrences) {
3719
- if (shouldSkipPluginLint(occurrence.config, ruleFile.skipWhen)) {
3720
- continue;
3721
- }
3722
- const rules = Array.isArray(ruleFile.rules) ? ruleFile.rules : [];
3723
- if (!rules.length) {
3724
- const message = `${occurrence.location} has no plugin lint rules.`;
3725
- if (options.requireInstalled) {
3726
- lintErrors.push(message);
3727
- } else {
3728
- lintWarnings.push(message);
3729
- }
3730
- }
3731
- for (const rule of rules) {
3732
- const error = evaluatePluginRule(occurrence.config, rule, occurrence.location);
3733
- if (error) {
3734
- lintErrors.push(error);
3735
- }
3736
- }
4154
+ await apiRequest(client, "POST", "/business_skill/install_record", {
4155
+ data: {
4156
+ skill_id: skill.id,
4157
+ version: installed?.version || "",
4158
+ agent,
4159
+ action: "uninstall",
4160
+ status: "success",
4161
+ cli_version: VERSION,
4162
+ install_path: installed?.install_path || ""
3737
4163
  }
3738
- errors.push(...lintErrors);
3739
- warnings.push(...lintWarnings);
3740
- pluginLints.push({
3741
- plugin: declaration.plugin,
3742
- skill: declaration.skill,
3743
- plugin_key: pluginKey,
3744
- domain: declaration.lint.domain,
3745
- rule_path: declaration.lint.path,
3746
- checked_locations: occurrences.map((item) => item.location),
3747
- errors: lintErrors,
3748
- warnings: lintWarnings
4164
+ });
4165
+ printResult(options.format, { action: "uninstalled", agent, skill: skill.key });
4166
+ });
4167
+ }
4168
+
4169
+ // src/commands/capabilities.ts
4170
+ function registerCapabilitiesCommands(program2) {
4171
+ const capabilities = program2.command("capabilities").description("Inspect bpmax-cli server capability whitelist");
4172
+ capabilities.command("status").description("Show cached server capabilities for a profile").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
4173
+ const profile = resolveProfile(await loadConfig(), options.profile);
4174
+ printResult(options.format, {
4175
+ profile: profile.name,
4176
+ origin: profile.config.origin,
4177
+ workspace: profile.config.workspace,
4178
+ capabilities_cache: profile.config.capabilities_cache || null
4179
+ });
4180
+ });
4181
+ capabilities.command("refresh").description("Refresh server capabilities for a profile").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
4182
+ const profile = resolveProfile(await loadConfig(), options.profile);
4183
+ const client = createApiClient(profile);
4184
+ const cache = await refreshCapabilities(client, profile);
4185
+ let pluginSkillUpdates;
4186
+ try {
4187
+ pluginSkillUpdates = await ensurePluginSkillsForDomain({
4188
+ client,
4189
+ profile,
4190
+ agent: process.env.BPMAX_CLI_AGENT || "codex",
4191
+ forceCheck: true
3749
4192
  });
4193
+ } catch (error) {
4194
+ pluginSkillUpdates = {
4195
+ ok: false,
4196
+ error: error instanceof Error ? error.message : String(error)
4197
+ };
3750
4198
  }
3751
- }
3752
- return {
3753
- ok: errors.length === 0,
3754
- errors,
3755
- warnings,
3756
- plugin_lints: pluginLints
3757
- };
3758
- }
3759
- async function copySkillDirectory(sourceDir, destinationDir) {
3760
- await rm2(destinationDir, { recursive: true, force: true });
3761
- await mkdir4(path4.dirname(destinationDir), { recursive: true });
3762
- await cp2(sourceDir, destinationDir, { recursive: true });
4199
+ printResult(options.format, {
4200
+ profile: profile.name,
4201
+ origin: profile.config.origin,
4202
+ workspace: profile.config.workspace,
4203
+ capabilities_cache: cache,
4204
+ plugin_skill_updates: pluginSkillUpdates
4205
+ });
4206
+ });
3763
4207
  }
3764
4208
 
4209
+ // src/commands/config.ts
4210
+ import { text as text2 } from "@clack/prompts";
4211
+ import { mkdir as mkdir8, writeFile as writeFile8 } from "fs/promises";
4212
+ import path9 from "path";
4213
+
3765
4214
  // src/core/config-workflow.ts
4215
+ import { createHash as createHash4 } from "crypto";
4216
+ import { mkdir as mkdir5, readdir as readdir2, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
4217
+ import path5 from "path";
3766
4218
  var NAV_CONFIG_TYPES = ["navmenu", "shortcut", "navmenu_mobile", "shortcut_mobile"];
3767
4219
  var NAV_CONTENT_KEY_BY_TYPE = {
3768
4220
  navmenu: "navConfig",
@@ -5853,6 +6305,117 @@ function isListTemplateOperationColumn(column) {
5853
6305
  }
5854
6306
  return collectListTemplateActionNodes(column.createElement).length >= 2;
5855
6307
  }
6308
+ function isListTemplateUtilityColumn(column) {
6309
+ if (isListTemplateOperationColumn(column)) {
6310
+ return true;
6311
+ }
6312
+ const props = isRecord3(column.props) ? column.props : {};
6313
+ const type = typeof props.type === "string" ? props.type.trim().toLowerCase() : "";
6314
+ return ["selection", "index", "expand"].includes(type);
6315
+ }
6316
+ function parseListTemplateColumnWidth(value) {
6317
+ if (typeof value === "number") {
6318
+ return Number.isFinite(value) && value > 0 ? value : void 0;
6319
+ }
6320
+ if (typeof value !== "string") {
6321
+ return void 0;
6322
+ }
6323
+ const match = value.trim().match(/^(\d+(?:\.\d+)?)(?:px)?$/i);
6324
+ if (!match) {
6325
+ return void 0;
6326
+ }
6327
+ const width = Number(match[1]);
6328
+ return Number.isFinite(width) && width > 0 ? width : void 0;
6329
+ }
6330
+ function listTemplateColumnLabel(column, index) {
6331
+ const title = typeof column.title === "string" ? column.title.trim() : "";
6332
+ const key = typeof column.key === "string" ? column.key.trim() : typeof column.prop === "string" ? column.prop.trim() : "";
6333
+ return title || key || `\u7B2C ${index + 1} \u5217`;
6334
+ }
6335
+ function estimatedListTemplateTitleWidth(title) {
6336
+ let textWidth = 0;
6337
+ for (const character of title) {
6338
+ textWidth += /[\u1100-\u11ff\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff\uff01-\uff60\uffe0-\uffe6]/u.test(character) ? 16 : 8;
6339
+ }
6340
+ return Math.max(64, textWidth + 40);
6341
+ }
6342
+ function isListTemplateLongTextColumn(column) {
6343
+ const title = typeof column.title === "string" ? column.title : "";
6344
+ const key = typeof column.key === "string" ? column.key : typeof column.prop === "string" ? column.prop : "";
6345
+ return /(备注|描述|说明|内容|原因|意见|地址|标题|主题|岗位jd|remark|description|content|reason|comment|address|title|subject|memo|note|\bjd\b)/i.test(`${title} ${key}`);
6346
+ }
6347
+ function hasListTemplateOverflowDisclosure(column) {
6348
+ const props = isRecord3(column.props) ? column.props : {};
6349
+ if (props.showOverflowTooltip === true || column.showOverflowTooltip === true) {
6350
+ return true;
6351
+ }
6352
+ let disclosed = false;
6353
+ const visit = (value) => {
6354
+ if (disclosed || !value) return;
6355
+ if (Array.isArray(value)) {
6356
+ value.forEach(visit);
6357
+ return;
6358
+ }
6359
+ if (!isRecord3(value)) return;
6360
+ const component = typeof value.is === "string" ? value.is.toLowerCase() : "";
6361
+ if (component.includes("tooltip") || component.includes("popover")) {
6362
+ disclosed = true;
6363
+ return;
6364
+ }
6365
+ const attribute = isRecord3(value.attribute) ? value.attribute : {};
6366
+ if (attribute.title !== void 0 && attribute.title !== null && attribute.title !== "") {
6367
+ disclosed = true;
6368
+ return;
6369
+ }
6370
+ Object.values(value).forEach(visit);
6371
+ };
6372
+ visit(column.createElement);
6373
+ return disclosed;
6374
+ }
6375
+ function validateListTemplateColumnWidths(columns, errors) {
6376
+ const recordColumns = columns.filter(isRecord3);
6377
+ const dataColumns = recordColumns.filter((column) => !isListTemplateUtilityColumn(column));
6378
+ if (dataColumns.length === 0) {
6379
+ errors.push("\u5217\u8868\u6A21\u677F\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u975E\u64CD\u4F5C\u6570\u636E\u5217\uFF0C\u4E0D\u80FD\u53EA\u6709\u64CD\u4F5C/\u9009\u62E9/\u5E8F\u53F7/\u5C55\u5F00\u5217\u3002");
6380
+ return;
6381
+ }
6382
+ let adaptiveColumnCount = 0;
6383
+ recordColumns.forEach((column, index) => {
6384
+ const props = isRecord3(column.props) ? column.props : {};
6385
+ const label = listTemplateColumnLabel(column, index);
6386
+ const isDataColumn = !isListTemplateUtilityColumn(column);
6387
+ const hasWidth = props.width !== void 0 && props.width !== null && props.width !== "";
6388
+ const hasMinWidth = props.minWidth !== void 0 && props.minWidth !== null && props.minWidth !== "";
6389
+ const width = parseListTemplateColumnWidth(props.width);
6390
+ const minWidth = parseListTemplateColumnWidth(props.minWidth);
6391
+ if (isDataColumn && !hasWidth) {
6392
+ adaptiveColumnCount += 1;
6393
+ }
6394
+ if (hasWidth && width === void 0) {
6395
+ errors.push(`\u5217\u8868\u6A21\u677F\u5217\u201C${label}\u201D\u7684 props.width \u5FC5\u987B\u662F\u6B63\u6570\u6216 px \u6570\u503C\uFF1B\u81EA\u9002\u5E94\u5217\u8BF7\u5220\u9664 width\u3002`);
6396
+ }
6397
+ if (hasMinWidth && minWidth === void 0) {
6398
+ errors.push(`\u5217\u8868\u6A21\u677F\u5217\u201C${label}\u201D\u7684 props.minWidth \u5FC5\u987B\u662F\u6B63\u6570\u6216 px \u6570\u503C\u3002`);
6399
+ }
6400
+ if (width !== void 0 && minWidth !== void 0 && minWidth > width) {
6401
+ errors.push(`\u5217\u8868\u6A21\u677F\u5217\u201C${label}\u201D\u7684 props.minWidth \u4E0D\u80FD\u5927\u4E8E props.width\u3002`);
6402
+ }
6403
+ const title = typeof column.title === "string" ? column.title.trim() : "";
6404
+ const effectiveReadableWidth = width ?? minWidth;
6405
+ if (title && effectiveReadableWidth !== void 0) {
6406
+ const requiredWidth = estimatedListTemplateTitleWidth(title);
6407
+ if (effectiveReadableWidth < requiredWidth) {
6408
+ errors.push(`\u5217\u8868\u6A21\u677F\u5217\u201C${label}\u201D\u5BBD\u5EA6\u8FC7\u5C0F\uFF0C\u6807\u9898\u5B8C\u6574\u5C55\u793A\u81F3\u5C11\u9700\u8981\u7EA6 ${requiredWidth}px\u3002`);
6409
+ }
6410
+ }
6411
+ if (isDataColumn && hasWidth && isListTemplateLongTextColumn(column) && !hasListTemplateOverflowDisclosure(column)) {
6412
+ errors.push(`\u5217\u8868\u6A21\u677F\u957F\u6587\u672C\u5217\u201C${label}\u201D\u4F7F\u7528\u56FA\u5B9A\u5BBD\u5EA6\u65F6\u5FC5\u987B\u63D0\u4F9B\u5B8C\u6574\u5185\u5BB9\u63D0\u793A\uFF0C\u4F8B\u5982 props.showOverflowTooltip: true\u3001attribute.title \u6216 tooltip\u3002`);
6413
+ }
6414
+ });
6415
+ if (adaptiveColumnCount === 0) {
6416
+ errors.push("\u5217\u8868\u6A21\u677F\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u81EA\u9002\u5E94\u6570\u636E\u5217\uFF1B\u8BF7\u5728\u4E00\u4E2A\u975E\u64CD\u4F5C\u5217\u4E0A\u5220\u9664 props.width\uFF0C\u53EF\u4FDD\u7559 props.minWidth\u3002");
6417
+ }
6418
+ }
5856
6419
  function classifyListTemplateAction(label) {
5857
6420
  if (/(删除|移除|作废|delete|remove|discard)/i.test(label)) {
5858
6421
  return "delete";
@@ -6244,6 +6807,7 @@ function validateListTemplateActionGate(value, errors) {
6244
6807
  return;
6245
6808
  }
6246
6809
  lintListTemplateQuerySafety(content, nextErrors);
6810
+ validateListTemplateColumnWidths(columns, nextErrors);
6247
6811
  const operationColumn = columns.filter(isRecord3).find(isListTemplateOperationColumn);
6248
6812
  if (!operationColumn) {
6249
6813
  nextErrors.push("list-template action gate requires an operation column when content.config has columns.");
@@ -7178,7 +7742,7 @@ function validateFormTemplateControlContracts(payload, errors) {
7178
7742
  if (type === "radio") {
7179
7743
  validateRadioFormTemplateControl(field, rule, value, errors);
7180
7744
  }
7181
- if (rule?.lambda === "ctx.$PROJECT?.owner?.name || ''") {
7745
+ if (rule?.lambda === "ctx.userInfo?.name || ''") {
7182
7746
  const props = isRecord3(rule.props) ? rule.props : {};
7183
7747
  if (type !== "i_input" || props.disabled !== true) {
7184
7748
  errors.push(`form-template applicant-name lambda field ${field} must use disabled i_input.`);
@@ -7187,7 +7751,7 @@ function validateFormTemplateControlContracts(payload, errors) {
7187
7751
  errors.push(`form-template applicant-name lambda field ${field} must use lambda_version=1.0 and lambdaInit=true.`);
7188
7752
  }
7189
7753
  }
7190
- if (rule?.lambda === "ctx.$PROJECT?.owner?.id || null") {
7754
+ if (rule?.lambda === "ctx.userInfo?.id || null") {
7191
7755
  const props = isRecord3(rule.props) ? rule.props : {};
7192
7756
  if (type !== "i_input" || props.disabled !== true || rule.hidden !== true) {
7193
7757
  errors.push(`form-template applicant-id lambda field ${field} must use hidden disabled i_input.`);
@@ -9647,11 +10211,33 @@ async function runFlowTemplatePluginLint(flowWork, options = {}) {
9647
10211
  const client = createApiClient(options.profile);
9648
10212
  let platformSkills = [];
9649
10213
  let discoveryWarning = "";
10214
+ let updateFailure = "";
10215
+ let updateReport;
9650
10216
  try {
9651
10217
  platformSkills = await listPluginSkills(client);
9652
10218
  } catch (error) {
9653
10219
  discoveryWarning = `Remote plugin lint discovery unavailable; used installed local lint declarations only: ${error instanceof Error ? error.message : String(error)}`;
9654
10220
  }
10221
+ if (!discoveryWarning) {
10222
+ const relevantPlugins = [...new Set(
10223
+ platformSkills.filter((skill) => flowTemplateUsesPluginSkill(flowWork, skill)).map((skill) => skill.plugin).filter((plugin) => Boolean(plugin))
10224
+ )];
10225
+ if (relevantPlugins.length) {
10226
+ try {
10227
+ updateReport = await ensurePluginSkillsForDomain({
10228
+ client,
10229
+ profile: options.profile,
10230
+ agent,
10231
+ domain: "flow-template-node",
10232
+ plugins: relevantPlugins,
10233
+ remoteSkills: platformSkills,
10234
+ forceCheck: true
10235
+ });
10236
+ } catch (error) {
10237
+ updateFailure = error instanceof Error ? error.message : String(error);
10238
+ }
10239
+ }
10240
+ }
9655
10241
  const result = await lintFlowTemplatePluginExtensions({
9656
10242
  profile: options.profile,
9657
10243
  agent,
@@ -9659,9 +10245,31 @@ async function runFlowTemplatePluginLint(flowWork, options = {}) {
9659
10245
  platformSkills,
9660
10246
  requireInstalled: Boolean(options.requireInstalled)
9661
10247
  });
10248
+ const relevantUpdates = updateReport?.plugin_skill_updates.filter(
10249
+ (item) => item.status !== "in_sync" && result.plugin_lints.some((lint) => lint.plugin === item.plugin || lint.skill === item.skill)
10250
+ ) || [];
10251
+ const updateErrors = relevantUpdates.map((item) => {
10252
+ const prefix = item.status === "conflicted" ? `\u63D2\u4EF6 Skill ${item.skill} \u7684\u672C\u5730\u526F\u672C\u5B58\u5728\u51B2\u7A81` : item.status === "checksum_unavailable" ? `\u63D2\u4EF6 Skill ${item.skill} \u7F3A\u5C11\u53EF\u9A8C\u8BC1\u7684 sha256` : item.status === "update_failed" ? `\u63D2\u4EF6 Skill ${item.skill} \u81EA\u52A8\u66F4\u65B0\u5931\u8D25` : `\u63D2\u4EF6 Skill ${item.skill} \u9700\u8981\u540C\u6B65\uFF08${item.status}\uFF09`;
10253
+ return `${prefix}\u3002${item.reason || ""}${item.next_command ? ` \u6267\u884C\uFF1A${item.next_command}` : ""}`.trim();
10254
+ });
9662
10255
  if (discoveryWarning) {
9663
10256
  result.warnings.push(discoveryWarning);
9664
10257
  }
10258
+ if (updateFailure) {
10259
+ const message = `\u63D2\u4EF6 Skill \u81EA\u52A8\u53D1\u73B0\u6216\u66F4\u65B0\u5931\u8D25\uFF1A${updateFailure}`;
10260
+ if (options.profile.config.plugin_skill_update_policy === "auto" && options.requireInstalled) {
10261
+ result.errors.unshift(message);
10262
+ result.ok = false;
10263
+ } else {
10264
+ result.warnings.unshift(message);
10265
+ }
10266
+ }
10267
+ if (options.requireInstalled && updateErrors.length) {
10268
+ result.errors.unshift(...updateErrors);
10269
+ result.ok = false;
10270
+ } else if (updateErrors.length) {
10271
+ result.warnings.unshift(...updateErrors);
10272
+ }
9665
10273
  return result;
9666
10274
  }
9667
10275
  function hasPotentialFlowTemplatePluginExtension(flowWork) {
@@ -12234,6 +12842,9 @@ function configCommandGate(actionCommand) {
12234
12842
  if (group === "profile") {
12235
12843
  return { required: false };
12236
12844
  }
12845
+ if (group === "set") {
12846
+ return { required: false };
12847
+ }
12237
12848
  if (group === "adapters" && !operation) {
12238
12849
  return { required: false };
12239
12850
  }
@@ -12275,6 +12886,24 @@ function registerConfigCommands(program2) {
12275
12886
  });
12276
12887
  });
12277
12888
  const profile = config.command("profile").description("Manage named environment profiles");
12889
+ config.command("set <key> <value>").description("Set a profile-scoped bpmax-cli behavior option").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (key, value, options) => {
12890
+ if (key !== "plugin_skill_update_policy") {
12891
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u9879\uFF1A${key}\u3002\u5F53\u524D\u4EC5\u652F\u6301 plugin_skill_update_policy\u3002`);
12892
+ }
12893
+ if (!["off", "check", "prompt", "auto"].includes(value)) {
12894
+ throw new Error("plugin_skill_update_policy \u5FC5\u987B\u662F off\u3001check\u3001prompt \u6216 auto\u3002");
12895
+ }
12896
+ const configData = await loadConfig();
12897
+ const resolved = resolveProfile(configData, options.profile);
12898
+ configData.profiles[resolved.name].plugin_skill_update_policy = value;
12899
+ await saveConfig(configData);
12900
+ printResult(options.format, {
12901
+ ok: true,
12902
+ profile: resolved.name,
12903
+ key,
12904
+ value
12905
+ });
12906
+ });
12278
12907
  profile.command("add").description("Add or update a profile").option("--name <name>", "Profile name").option("--origin <origin>", "Profile origin").option("--api-key <apiKey>", "API key").option("--workspace <workspace>", "Default workspace", DEFAULT_WORKSPACE).option("--language <language>", "Default language", DEFAULT_LANGUAGE).action(async (options) => {
12279
12908
  const name = await ensureValue(options.name, "Profile name", "default");
12280
12909
  const origin = await ensureValue(options.origin, "Origin", "https://example.com");
@@ -12337,6 +12966,7 @@ function registerConfigCommands(program2) {
12337
12966
  configuration_capability: Boolean(target.api_key_capabilities?.["configuration.manage"]),
12338
12967
  config_environments: Object.keys(target.config_environments || {}),
12339
12968
  capabilities_probe: target.capabilities_probe || null,
12969
+ plugin_skill_update_policy: target.plugin_skill_update_policy || "check",
12340
12970
  user: target.user || null
12341
12971
  });
12342
12972
  });
@@ -17692,6 +18322,30 @@ function registerPluginCommands(program2) {
17692
18322
  state: await readPluginSkillState(profile.name, agent)
17693
18323
  });
17694
18324
  });
18325
+ skills.command("check [plugin]").description("Discover plugin Skill installs and updates by sha256 without changing local files").option("--domain <domain>", "Filter by lint/config domain, e.g. flow-template-node").option("--agent <agent>", "Agent adapter", "codex").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (pluginName, options) => {
18326
+ const profile = resolveProfile(await loadConfig(), options.profile);
18327
+ const report = await checkPluginSkillUpdates({
18328
+ client: createApiClient(profile),
18329
+ profile,
18330
+ agent: defaultAgent2(options),
18331
+ domain: options.domain,
18332
+ force: true,
18333
+ policy: "check"
18334
+ });
18335
+ if (pluginName) {
18336
+ const updates = report.plugin_skill_updates.filter((item) => item.plugin === pluginName);
18337
+ if (!updates.length) {
18338
+ throw new Error(`\u63D2\u4EF6 ${pluginName} \u672A\u58F0\u660E\u53EF\u7528\u7684 Agent Skill\u3002`);
18339
+ }
18340
+ printResult(options.format, {
18341
+ ...report,
18342
+ ok: updates.every((item) => item.status === "in_sync"),
18343
+ plugin_skill_updates: updates
18344
+ });
18345
+ return;
18346
+ }
18347
+ printResult(options.format, report);
18348
+ });
17695
18349
  skills.command("lint").requiredOption("--zip <path>", "Plugin skill zip path").option("--skill <skill>", "Expected skill name").option("--format <format>", "Output format", "json").action(async (options) => {
17696
18350
  printResult(options.format, await lintPluginSkillZip(options.zip, { expectedName: options.skill }));
17697
18351
  });
@@ -17712,14 +18366,22 @@ function registerPluginCommands(program2) {
17712
18366
  plugin: pluginName,
17713
18367
  skill,
17714
18368
  agent,
17715
- force: options.force
18369
+ force: options.force,
18370
+ adoptUnownedExisting: Boolean(options.force)
17716
18371
  }));
17717
18372
  }
18373
+ const updateState = await checkPluginSkillUpdates({
18374
+ client,
18375
+ profile,
18376
+ agent,
18377
+ force: true
18378
+ });
17718
18379
  printResult(options.format, {
17719
18380
  action: options.force ? "updated" : installed.every((item) => item.action === "in_sync") ? "in_sync" : "ensured",
17720
18381
  agent,
17721
18382
  plugin: pluginName,
17722
18383
  skills: installed,
18384
+ plugin_skill_updates: updateState.plugin_skill_updates.filter((item) => item.plugin === pluginName),
17723
18385
  next_commands: installed.map((item) => `Use skill ${item.skill} for plugin ${pluginName}.`)
17724
18386
  });
17725
18387
  }