@bike4mind/cli 3.4.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +223 -39
  2. package/bin/bike4mind-cli.mjs +301 -38
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/bin/hearth-hook.mjs +53 -7
  6. package/dist/{AgentHistoryStore-ClO2zOn6.mjs → AgentHistoryStore--J3sgO_-.mjs} +9011 -6699
  7. package/dist/ApiClient-CdO4Gamg.mjs +152 -0
  8. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  9. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  10. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  11. package/dist/{ConfigStore-CbVFLXMH.mjs → Logger-C1Wj6xla.mjs} +32880 -20779
  12. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  13. package/dist/RemoteSkillSource-qTvRkaNA.mjs +455 -0
  14. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  15. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  16. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  17. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  18. package/dist/{WorkItemsClient-SeNbzvEw.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  19. package/dist/agents/defaults/review.md +8 -1
  20. package/dist/agents/defaults/test.md +8 -1
  21. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  22. package/dist/commands/acpCommand.mjs +33 -27
  23. package/dist/commands/apiCommand.mjs +3 -5
  24. package/dist/commands/doctorCommand.mjs +2 -2
  25. package/dist/commands/envCommand.mjs +1 -1
  26. package/dist/commands/headlessCommand.mjs +118 -36
  27. package/dist/commands/hostCommand.mjs +2344 -0
  28. package/dist/commands/mcpCommand.mjs +46 -30
  29. package/dist/commands/mirrorCommand.mjs +279 -0
  30. package/dist/commands/modelsCommand.mjs +1117 -0
  31. package/dist/commands/pluginCommand.mjs +9 -9
  32. package/dist/commands/skillsCommand.mjs +404 -0
  33. package/dist/commands/updateCommand.mjs +2 -2
  34. package/dist/curated-build.json +1 -0
  35. package/dist/dist-CbViwiS9.mjs +4739 -0
  36. package/dist/dist-Citbv0y0.mjs +7864 -0
  37. package/dist/fit-CVWDiavv.mjs +200 -0
  38. package/dist/index.mjs +1001 -442
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-BaegigV-.mjs +2465 -0
  41. package/dist/{package-MoDZ9cGj.mjs → package-C9pfAdGF.mjs} +1 -1
  42. package/dist/{serve-zi-B2iUT.mjs → serve-8wyGb8of.mjs} +1243 -44
  43. package/dist/store-BYeE0shc.mjs +2 -0
  44. package/dist/{store-BxmPEI3v.mjs → store-BbvSi3KK.mjs} +26 -2
  45. package/dist/types-BFIvwByC.mjs +2 -0
  46. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  47. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  48. package/package.json +17 -13
  49. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  50. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  51. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  52. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  53. package/dist/buildAgent-BeaVbpzH.mjs +0 -1992
  54. package/dist/dist-DlBq3wHu.mjs +0 -739
  55. package/dist/store-BkMur6uk.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as ConfigStore } from "../ConfigStore-CbVFLXMH.mjs";
2
+ import { D as sanitizeTerminalText, t as ConfigStore } from "../ConfigStore-Dusy6glb.mjs";
3
3
  import { n as getDefaultPluginsDir, r as isFeatureEnabled, t as PluginStore } from "../PluginStore-DwvOJ-G3.mjs";
4
4
  import { promises } from "fs";
5
5
  import path from "path";
@@ -53,9 +53,9 @@ function formatPluginList(descriptors, config) {
53
53
  const lines = [];
54
54
  for (const descriptor of descriptors) if (descriptor.valid) {
55
55
  const enabled = isFeatureEnabled(config.features, descriptor.configKey);
56
- lines.push(`• ${descriptor.name}@${descriptor.version} - ${enabled ? "✅ Enabled" : "⏸️ Disabled"} (key: ${descriptor.configKey})`);
57
- if (descriptor.description) lines.push(` ${descriptor.description}`);
58
- } else lines.push(`• ${descriptor.name} - ⚠️ ${descriptor.reason}`);
56
+ lines.push(`• ${sanitizeTerminalText(descriptor.name)}@${sanitizeTerminalText(descriptor.version)} - ${enabled ? "✅ Enabled" : "⏸️ Disabled"} (key: ${sanitizeTerminalText(descriptor.configKey)})`);
57
+ if (descriptor.description) lines.push(` ${sanitizeTerminalText(descriptor.description)}`);
58
+ } else lines.push(`• ${sanitizeTerminalText(descriptor.name)} - ⚠️ ${sanitizeTerminalText(descriptor.reason)}`);
59
59
  return lines.join("\n");
60
60
  }
61
61
  /**
@@ -142,13 +142,13 @@ async function handleAdd(spec, pluginsDir, configStore) {
142
142
  }
143
143
  for (const descriptor of added) {
144
144
  if (!descriptor.valid) {
145
- console.warn(`⚠️ ${descriptor.name} installed, but its manifest is invalid: ${descriptor.reason}`);
145
+ console.warn(`\u26A0\uFE0F ${sanitizeTerminalText(descriptor.name)} installed, but its manifest is invalid: ${sanitizeTerminalText(descriptor.reason)}`);
146
146
  console.warn("It will not load until the manifest is fixed.");
147
147
  continue;
148
148
  }
149
149
  if (!newTopLevel.has(descriptor.name)) {
150
- console.warn(`ℹ️ ${descriptor.name} is a dependency and carries a plugin manifest; not enabling it.`);
151
- console.warn(` Enable it explicitly with: b4m plugin add ${descriptor.name}`);
150
+ console.warn(`ℹ️ ${sanitizeTerminalText(descriptor.name)} is a dependency and carries a plugin manifest; not enabling it.`);
151
+ console.warn(` Enable it explicitly with: b4m plugin add ${sanitizeTerminalText(descriptor.name)}`);
152
152
  continue;
153
153
  }
154
154
  const config = await configStore.load();
@@ -156,8 +156,8 @@ async function handleAdd(spec, pluginsDir, configStore) {
156
156
  ...config.features,
157
157
  [descriptor.configKey]: true
158
158
  } });
159
- console.log(`✅ Installed ${descriptor.name}@${descriptor.version} (plugin key: ${descriptor.configKey})`);
160
- console.log(`Enabled feature "${descriptor.configKey}". It will load next time you start b4m.`);
159
+ console.log(`✅ Installed ${sanitizeTerminalText(descriptor.name)}@${sanitizeTerminalText(descriptor.version)} (plugin key: ${sanitizeTerminalText(descriptor.configKey)})`);
160
+ console.log(`Enabled feature "${sanitizeTerminalText(descriptor.configKey)}". It will load next time you start b4m.`);
161
161
  }
162
162
  }
163
163
  async function handleRemove(name, pluginsDir, configStore) {
@@ -0,0 +1,404 @@
1
+ #!/usr/bin/env node
2
+ import { t as ConfigStore, v as requireApiUrl } from "../ConfigStore-Dusy6glb.mjs";
3
+ import { nn as splitSkillMdFrontmatter, tn as readSkillMdSourceUrl } from "../Logger-C1Wj6xla.mjs";
4
+ import { r as isReservedCommandName, t as RemoteSkillSource } from "../RemoteSkillSource-qTvRkaNA.mjs";
5
+ import { t as ApiClient } from "../ApiClient-CdO4Gamg.mjs";
6
+ import { promises } from "fs";
7
+ import os from "os";
8
+ import path from "path";
9
+ import YAML from "yaml";
10
+ import { createInterface } from "readline";
11
+ const THIRD_PARTY_LINE = new RegExp(`^\\s*#\\s*Third-party skill from the Bike4Mind Skill Market - review before use`, "m");
12
+ const CLAUDE_CODE_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9.:_-]*$/;
13
+ /** Trimmed `model` value when it is a plausible Claude Code alias or model id; no closed alias list. */
14
+ function normalizeClaudeCodeModel(value) {
15
+ const model = typeof value === "string" ? value.trim() : "";
16
+ return model.length > 0 && model.length <= 64 && CLAUDE_CODE_MODEL_PATTERN.test(model) ? model : void 0;
17
+ }
18
+ const ARGUMENT_HINT_LINE = /^(argument-hint:[ \t]*)([^\r\n]+?)[ \t]*$/gm;
19
+ function quoteRawArgumentHint(frontmatter) {
20
+ return frontmatter.replace(ARGUMENT_HINT_LINE, (line, key, raw) => {
21
+ if (/^["'|>]/.test(raw)) return line;
22
+ const hint = (raw.startsWith("[") || raw.startsWith("<") ? raw.replace(/([\]>])[ \t]+#.*$/, "$1") : raw.replace(/[ \t]+#.*$/, "")).trimEnd();
23
+ return hint.startsWith("[") || hint.startsWith("<") || hint.includes(": ") ? `${key}${JSON.stringify(hint)}` : line;
24
+ });
25
+ }
26
+ const toText = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
27
+ /**
28
+ * Claude Code's `allowed-tools`: a YAML list, or one string separated by commas or spaces. Every list
29
+ * entry is split too, because the export joins them and Claude Code re-splits on commas and spaces. A space
30
+ * inside parentheses (`Bash(git add:*)`) belongs to the entry; an unclosed `(` keeps the rest whole.
31
+ */
32
+ function splitAllowedTools(value) {
33
+ if (Array.isArray(value)) return value.flatMap((v) => splitAllowedTools(toText(v)));
34
+ const text = toText(value);
35
+ if (!text) return [];
36
+ const tools = [];
37
+ let current = "";
38
+ let depth = 0;
39
+ for (const ch of text) {
40
+ if (ch === "(") depth++;
41
+ else if (ch === ")") depth = Math.max(0, depth - 1);
42
+ if (depth === 0 && (ch === "," || /\s/.test(ch))) {
43
+ if (current.trim()) tools.push(current.trim());
44
+ current = "";
45
+ } else current += ch;
46
+ }
47
+ if (current.trim()) tools.push(current.trim());
48
+ return tools;
49
+ }
50
+ const UNQUOTED_TOP_LEVEL_VALUE = /^([^\s#:][^:]*?):[ \t]+(\S.*)$/;
51
+ /** Line of the first top-level `key: "value` whose opening quote never closes on its own line. */
52
+ function findUnclosedQuoteLine(lines) {
53
+ const index = lines.findIndex((line) => {
54
+ const match = line.match(/^[^\s#][^:]*:[ \t]+(["'])(.*)$/);
55
+ if (!match) return false;
56
+ return !match[2].replace(match[1] === "\"" ? /\\./g : /''/g, "").includes(match[1]);
57
+ });
58
+ return index === -1 ? void 0 : index + 1;
59
+ }
60
+ /**
61
+ * Turns a YAML failure into a message with a fix. The frontmatter starts on file line 2 (line 1 is
62
+ * the opening ---), so every reported line is the frontmatter line plus one.
63
+ */
64
+ function describeYamlError(frontmatter, error) {
65
+ const details = error instanceof Error ? error.message : String(error);
66
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
67
+ const linePos = typeof error === "object" && error !== null && "linePos" in error ? error.linePos : void 0;
68
+ const lines = frontmatter.split("\n");
69
+ const errorLine = linePos?.[0]?.line;
70
+ const fail = (message) => ({
71
+ ok: false,
72
+ error: message,
73
+ details
74
+ });
75
+ if (code === "TAB_AS_INDENT" && errorLine) return fail(`Line ${errorLine + 1} uses a tab for indentation; YAML needs spaces.`);
76
+ if (code === "MISSING_CHAR" && /quote/i.test(details)) {
77
+ const line = findUnclosedQuoteLine(lines) ?? errorLine;
78
+ if (line) return fail(`Line ${line + 1} has a quote that is never closed.`);
79
+ }
80
+ if (errorLine) {
81
+ const match = lines[errorLine - 1]?.match(UNQUOTED_TOP_LEVEL_VALUE);
82
+ if (match && !/^["'[{|>&*!]/.test(match[2]) && match[2].includes(": ")) return fail(`Line ${errorLine + 1} (\`${match[1]}\`) has a colon followed by a space, which YAML reads as a new key. Wrap the value in double quotes.`);
83
+ return fail(`The frontmatter is not valid YAML (line ${errorLine + 1}).`);
84
+ }
85
+ return fail("The frontmatter is not valid YAML.");
86
+ }
87
+ /** Parses a SKILL.md into skill form fields. Never throws; a malformed file yields `ok: false`. */
88
+ function parseSkillMd(input) {
89
+ const text = input.replace(/\r\n?/g, "\n");
90
+ const split = splitSkillMdFrontmatter(text);
91
+ if (!split) {
92
+ if (/^\uFEFF?---/.test(text)) return {
93
+ ok: false,
94
+ error: "The frontmatter block has no closing --- line."
95
+ };
96
+ return {
97
+ ok: true,
98
+ fields: { body: stripBodyNewlines(text.replace(/^\uFEFF/, "")) },
99
+ dropped: []
100
+ };
101
+ }
102
+ if (split.lang && split.lang !== "yaml" && split.lang !== "yml") return {
103
+ ok: false,
104
+ error: `Unsupported frontmatter language "${split.lang}"; only YAML is supported.`
105
+ };
106
+ let data;
107
+ try {
108
+ const frontmatter = quoteRawArgumentHint(split.frontmatter);
109
+ data = YAML.parse(frontmatter) ?? {};
110
+ } catch (error) {
111
+ return describeYamlError(split.frontmatter, error);
112
+ }
113
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return {
114
+ ok: false,
115
+ error: "The frontmatter must be a set of key: value pairs."
116
+ };
117
+ const fields = { body: stripBodyNewlines(split.rest) };
118
+ const dropped = [];
119
+ for (const [key, value] of Object.entries(data)) switch (key) {
120
+ case "name":
121
+ fields.name = toText(value);
122
+ break;
123
+ case "description":
124
+ fields.description = toText(value);
125
+ break;
126
+ case "argument-hint":
127
+ fields.argumentHint = toText(value);
128
+ break;
129
+ case "disable-model-invocation":
130
+ fields.disableModelInvocation = fields.disableModelInvocation || value === true || value === "true";
131
+ break;
132
+ case "autoinvoke":
133
+ fields.disableModelInvocation = fields.disableModelInvocation || value === false || value === "false";
134
+ break;
135
+ case "allowed-tools": {
136
+ const tools = splitAllowedTools(value);
137
+ if (tools.length) fields.claudeCodeAllowedTools = tools;
138
+ else if (value != null && value !== "" && !(Array.isArray(value) && value.length === 0)) dropped.push(key);
139
+ break;
140
+ }
141
+ case "model": {
142
+ const model = normalizeClaudeCodeModel(value);
143
+ if (model) fields.claudeCodeModel = model;
144
+ else if (value != null && value !== "") dropped.push(key);
145
+ break;
146
+ }
147
+ default: dropped.push(key);
148
+ }
149
+ const url = readSkillMdSourceUrl(split.frontmatter);
150
+ return {
151
+ ok: true,
152
+ fields: Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== void 0)),
153
+ dropped,
154
+ ...url !== void 0 && { source: {
155
+ url,
156
+ thirdParty: THIRD_PARTY_LINE.test(split.frontmatter)
157
+ } }
158
+ };
159
+ }
160
+ /** Drops the blank line after the closing fence and the single trailing newline toSkillMd adds. */
161
+ function stripBodyNewlines(rest) {
162
+ return rest.replace(/^\r?\n/, "").replace(/\r?\n$/, "");
163
+ }
164
+ //#endregion
165
+ //#region src/commands/skillsCommand.ts
166
+ /**
167
+ * External skills command (b4m skills push <path> [--publish]).
168
+ * Imports a Claude Code SKILL.md (or commands/*.md) as the user's own
169
+ * Bike4Mind skill, and with --publish lists it on the Skill Market. Runs
170
+ * outside the interactive CLI session. Validation is left to the server
171
+ * (apps/client/server/utils/skillValidation.ts).
172
+ */
173
+ const MAX_LISTED_FILES = 10;
174
+ const DESCRIPTION_MAX = 500;
175
+ /** The server requires a description, but many Claude Code commands/*.md files have none. */
176
+ function descriptionFor(fields) {
177
+ if (fields.description?.trim()) return fields.description;
178
+ return ((fields.body ?? "").split("\n").map((line) => line.replace(/^#+\s*/, "").trim()).find(Boolean) ?? "").slice(0, DESCRIPTION_MAX);
179
+ }
180
+ /**
181
+ * Built from an explicit field list (never a spread of parsed data). The file's
182
+ * allowed-tools goes to claudeCodeAllowedTools, never allowedTools: Claude Code
183
+ * tool names don't map to B4M. claudeCodeAllowedTools, disableModelInvocation
184
+ * and claudeCodeModel ('' clears) are always sent so an update mirrors the file.
185
+ */
186
+ function buildSkillPayload(fields, fallbackName) {
187
+ return {
188
+ name: (fields.name?.trim() || fallbackName).trim().toLowerCase(),
189
+ description: descriptionFor(fields),
190
+ body: fields.body ?? "",
191
+ ...fields.argumentHint !== void 0 && { argumentHint: fields.argumentHint },
192
+ claudeCodeAllowedTools: fields.claudeCodeAllowedTools ?? [],
193
+ claudeCodeModel: fields.claudeCodeModel ?? "",
194
+ disableModelInvocation: fields.disableModelInvocation ?? false
195
+ };
196
+ }
197
+ /** Resolves <dir>, <dir>/SKILL.md or any .md file and parses it. */
198
+ async function readSkillFile(input) {
199
+ const expanded = input === "~" || input.startsWith("~/") ? path.join(os.homedir(), input.slice(1)) : input;
200
+ const resolved = path.resolve(expanded);
201
+ let stat;
202
+ try {
203
+ stat = await promises.stat(resolved);
204
+ } catch {
205
+ throw new Error(`No such file or folder: ${input}`);
206
+ }
207
+ let filePath;
208
+ let fallbackName;
209
+ if (stat.isDirectory()) {
210
+ filePath = path.join(resolved, "SKILL.md");
211
+ fallbackName = path.basename(resolved);
212
+ } else if (stat.isFile() && resolved.toLowerCase().endsWith(".md")) {
213
+ filePath = resolved;
214
+ fallbackName = path.basename(resolved).toLowerCase() === "skill.md" ? path.basename(path.dirname(resolved)) : path.basename(resolved, path.extname(resolved));
215
+ } else throw new Error(`Not a skill: ${input} - pass a skill folder, its SKILL.md, or a .md file.`);
216
+ let text;
217
+ try {
218
+ text = await promises.readFile(filePath, "utf8");
219
+ } catch {
220
+ throw new Error(stat.isDirectory() ? "No SKILL.md in that folder." : `Cannot read ${input}`);
221
+ }
222
+ const parsed = parseSkillMd(text);
223
+ if (!parsed.ok) throw new Error(parsed.error);
224
+ const name = path.basename(filePath);
225
+ const extraFiles = name.toLowerCase() === "skill.md" ? (await promises.readdir(path.dirname(filePath))).filter((f) => f !== name && !f.startsWith(".")).sort() : [];
226
+ return {
227
+ payload: buildSkillPayload(parsed.fields, fallbackName),
228
+ dropped: parsed.dropped,
229
+ ...parsed.source && { source: parsed.source },
230
+ extraFiles
231
+ };
232
+ }
233
+ function serverMessage(error) {
234
+ const err = error;
235
+ return err?.response?.data?.error ?? err?.response?.data?.message ?? err?.message ?? String(error);
236
+ }
237
+ /** Names the scope a 403 from an API-key gate asks for, so the user knows what to re-mint the key with. */
238
+ function scopeHint(error) {
239
+ const required = error.response?.data?.required_scopes;
240
+ return required?.length ? ` (the API key needs ${required.join(" or ")})` : "";
241
+ }
242
+ /** The stamp is plain comment text, so only a same-origin URL is presented as provenance. */
243
+ function isSameOrigin(url, apiOrigin) {
244
+ try {
245
+ return apiOrigin !== void 0 && new URL(url).origin === new URL(apiOrigin).origin;
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+ /**
251
+ * Prints the notices, applies the third-party and name-conflict gates, then
252
+ * creates or updates the skill. Nothing is sent to the server before the
253
+ * third-party gate passes. Throws on any exit-1 condition.
254
+ */
255
+ async function pushSkill(file, deps) {
256
+ const { payload, dropped, source, extraFiles } = file;
257
+ const { api, log } = deps;
258
+ if (dropped.length > 0) log(`Ignored (not supported in Bike4Mind skills): ${dropped.join(", ")}`);
259
+ if (extraFiles.length > 0) log(`Not uploaded: supporting files (${extraFiles.slice(0, MAX_LISTED_FILES).join(", ")}${extraFiles.length > MAX_LISTED_FILES ? ` and ${extraFiles.length - MAX_LISTED_FILES} more` : ""}) - only SKILL.md is pushed.`);
260
+ if (isReservedCommandName(payload.name)) log(`Note: /${payload.name} is a built-in B4M CLI command, so the CLI won't list this skill (the web still will).`);
261
+ if (source) {
262
+ log(isSameOrigin(source.url, deps.apiOrigin) ? `This skill came from Bike4Mind: ${source.url}` : `This file has a Bike4Mind source stamp from another site: ${source.url}`);
263
+ if (source.thirdParty) {
264
+ log("This is another author's Skill Market skill - import it from the market instead to keep updates and attribution.");
265
+ if (!deps.yes) {
266
+ if (!deps.isTTY) throw new Error("Re-run with --yes to push another author's skill as your own.");
267
+ if (!await deps.confirm("Push it as your own skill anyway? [y/N] ")) return { outcome: "aborted" };
268
+ }
269
+ }
270
+ }
271
+ try {
272
+ const me = await (deps.whoAmI ?? (() => api.getCurrentUser()))();
273
+ if (!me) throw new Error("Not authenticated. Run `b4m /login` to authenticate.");
274
+ let existing;
275
+ for (let page = 1; !existing; page++) {
276
+ const { data, hasMore } = await api.get("/api/skills", { params: {
277
+ query: payload.name,
278
+ limit: 100,
279
+ page
280
+ } });
281
+ existing = data.find((s) => s.name === payload.name && s.userId === me.id);
282
+ if (!hasMore) break;
283
+ }
284
+ if (!existing) return {
285
+ outcome: "created",
286
+ skillId: (await api.post("/api/skills", payload)).id
287
+ };
288
+ if (existing.importedFrom) throw new Error(`"${payload.name}" is the name of a Skill Market skill you imported - rename the local skill or delete the import first.`);
289
+ if (!deps.update) {
290
+ if (!deps.isTTY) throw new Error(`A skill named "${payload.name}" already exists - re-run with --update to overwrite it.`);
291
+ if (!await deps.confirm(`A skill named "${payload.name}" already exists. Update it? [y/N] `)) return { outcome: "aborted" };
292
+ }
293
+ await api.put(`/api/skills/${existing.id}`, {
294
+ ...payload,
295
+ argumentHint: payload.argumentHint ?? ""
296
+ });
297
+ return {
298
+ outcome: "updated",
299
+ skillId: existing.id
300
+ };
301
+ } catch (error) {
302
+ throw new Error(`${serverMessage(error)}${scopeHint(error)}`);
303
+ }
304
+ }
305
+ function describeVersion(version) {
306
+ const verdict = `scan ${version.scan_status}, review ${version.review_status}, risk ${version.risk_tier ?? "n/a"}`;
307
+ return version.review_status === "pending" ? `${verdict} - it goes live once a reviewer approves it` : verdict;
308
+ }
309
+ /**
310
+ * Lists a pushed skill on the Skill Market: a new version of its live listing when there is one,
311
+ * else a new listing. Uses the /api/v1 routes, so an API key needs `skills:write`.
312
+ */
313
+ async function publishToMarket(skillId, opts, api, log) {
314
+ try {
315
+ const { data } = await api.get("/api/v1/skills/market/listings/mine", { params: { source_skill_id: skillId } });
316
+ const live = data.find((l) => l.status !== "withdrawn" && l.status !== "delisted");
317
+ const tags = opts.tags ? { tags: opts.tags } : {};
318
+ if (live) {
319
+ let version;
320
+ try {
321
+ ({version} = await api.post(`/api/v1/skills/market/listings/${live.id}/versions`, tags));
322
+ } catch (error) {
323
+ if (error.response?.status === 400 && serverMessage(error).includes("already live or waiting for review")) {
324
+ log(`Listing "${live.name}" is already up to date`);
325
+ return;
326
+ }
327
+ throw error;
328
+ }
329
+ log(`Submitted version ${version.version} of listing "${live.name}": ${describeVersion(version)}`);
330
+ return;
331
+ }
332
+ const { listing, version } = await api.post("/api/v1/skills/market/listings", {
333
+ skill_id: skillId,
334
+ visibility: opts.visibility,
335
+ ...opts.org && { organization_id: opts.org },
336
+ ...tags
337
+ });
338
+ log(`Published listing "${listing.name}" (${listing.visibility}): ${describeVersion(version)}`);
339
+ } catch (error) {
340
+ throw new Error(`Publishing to the Skill Market failed: ${serverMessage(error)}${scopeHint(error)}`);
341
+ }
342
+ }
343
+ /** The key's owner, for a push made with an API key (the stored-login lookup does not apply). */
344
+ async function whoAmIWithKey(api) {
345
+ try {
346
+ return await api.get("/api/v1/me");
347
+ } catch (error) {
348
+ if (error.response?.status === 403) throw new Error("This API key needs the me:read and skills:write scopes.");
349
+ throw error;
350
+ }
351
+ }
352
+ async function confirm(question) {
353
+ const rl = createInterface({
354
+ input: process.stdin,
355
+ output: process.stdout
356
+ });
357
+ try {
358
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
359
+ return /^y(es)?$/i.test(answer.trim());
360
+ } finally {
361
+ rl.close();
362
+ }
363
+ }
364
+ async function handleSkillsCommand(subcommand, argv) {
365
+ if (subcommand !== "push") throw new Error(`Unknown skills subcommand: ${subcommand ?? "(none)"}`);
366
+ if (!argv.path) throw new Error("Usage: b4m skills push <path> [--publish]");
367
+ const file = await readSkillFile(argv.path);
368
+ const configStore = new ConfigStore();
369
+ const config = await configStore.load();
370
+ const apiKey = argv["api-key"] ?? process.env.B4M_API_KEY;
371
+ if (!apiKey && !await configStore.getAuthTokens()) throw new Error("Not authenticated. Run `b4m /login` to authenticate, or set B4M_API_KEY.");
372
+ const apiUrl = requireApiUrl(config.apiConfig);
373
+ const apiClient = new ApiClient(apiUrl, configStore, apiKey);
374
+ const result = await pushSkill(file, {
375
+ api: apiClient,
376
+ confirm,
377
+ isTTY: Boolean(process.stdin.isTTY),
378
+ update: Boolean(argv.update),
379
+ yes: Boolean(argv.yes),
380
+ apiOrigin: apiUrl,
381
+ log: (line) => console.log(line),
382
+ ...apiKey && { whoAmI: () => whoAmIWithKey(apiClient) }
383
+ });
384
+ if (result.outcome === "aborted") {
385
+ console.log("Aborted");
386
+ return;
387
+ }
388
+ try {
389
+ await new RemoteSkillSource(apiClient).clearCache();
390
+ } catch (error) {
391
+ console.warn(`Skill saved, but the local skills cache could not be cleared: ${serverMessage(error)}`);
392
+ }
393
+ console.log(`${result.outcome === "created" ? "Created" : "Updated"} skill /${file.payload.name}`);
394
+ if (argv.publish) {
395
+ const tags = argv.tags?.split(",").map((t) => t.trim()).filter(Boolean);
396
+ await publishToMarket(result.skillId, {
397
+ visibility: argv.visibility ?? "organization",
398
+ org: argv.org,
399
+ tags
400
+ }, apiClient, (line) => console.log(line));
401
+ }
402
+ }
403
+ //#endregion
404
+ export { buildSkillPayload, handleSkillsCommand, publishToMarket, pushSkill, readSkillFile };
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "../package-MoDZ9cGj.mjs";
3
- import { a as forceCheckForUpdate, c as isNpmPrefixWritable, d as shouldAttemptAutoUpdate, l as readCachedUpdate, n as REEXEC_GUARD_ENV, o as getAutoUpdatePreference, t as INSTALL_CMD, u as setAutoUpdatePreference } from "../updateChecker-CCLVVdH0.mjs";
2
+ import { t as version } from "../package-C9pfAdGF.mjs";
3
+ import { a as forceCheckForUpdate, c as isNpmPrefixWritable, d as shouldAttemptAutoUpdate, l as readCachedUpdate, n as REEXEC_GUARD_ENV, o as getAutoUpdatePreference, t as INSTALL_CMD, u as setAutoUpdatePreference } from "../updateChecker-BAKb8KWP.mjs";
4
4
  import { t as checkRipgrep } from "../ripgrepCheck-BmkyTK2i.mjs";
5
5
  import { execSync, spawnSync } from "child_process";
6
6
  import { createInterface } from "readline";
@@ -0,0 +1 @@
1
+ {"devKeys":false,"manifestUrl":""}