@solidactions/cli 3.19.0 → 3.20.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.
@@ -13,7 +13,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  return (mod && mod.__esModule) ? mod : { "default": mod };
14
14
  };
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.RESERVED_PARAM_KEYS = void 0;
16
+ exports.ROLE_FRONTMATTER_PARAMS = exports.RESERVED_PARAM_KEYS = void 0;
17
+ exports.foldedFrontmatterKeys = foldedFrontmatterKeys;
18
+ exports.noteFoldedFrontmatterKeys = noteFoldedFrontmatterKeys;
19
+ exports.shapeFrontmatterParams = shapeFrontmatterParams;
17
20
  exports.assertNoReservedFrontmatterKeys = assertNoReservedFrontmatterKeys;
18
21
  exports.parseSkillFile = parseSkillFile;
19
22
  exports.readReferences = readReferences;
@@ -31,12 +34,62 @@ const api_1 = require("../utils/api");
31
34
  const mcp_1 = require("../utils/mcp");
32
35
  const skill_snapshot_1 = require("../utils/skill-snapshot");
33
36
  const skill_pull_1 = require("./skill-pull");
37
+ const crew_1 = require("../utils/crew");
34
38
  /**
35
39
  * Protocol param names reserved by the skills/roles MCP tool actions. Frontmatter
36
40
  * keys that collide with these would silently corrupt the request once spread
37
41
  * top-level into the call arguments.
38
42
  */
39
- exports.RESERVED_PARAM_KEYS = ['action', 'identifier', 'role', 'name', 'description', 'body', 'references', 'base_version_id'];
43
+ exports.RESERVED_PARAM_KEYS = ['action', 'identifier', 'role', 'name', 'description', 'body', 'references', 'base_version_id', 'in_crew', 'workspace', 'version_id'];
44
+ /**
45
+ * Frontmatter keys the current MCP catalog accepts as top-level create/edit params
46
+ * (crews_skills_manage / crews_roles_manage). The server rejects any other param
47
+ * with `unknown_params`, so everything else is folded into `metadata`.
48
+ */
49
+ const SKILL_FRONTMATTER_PARAMS = ['catalog_advertised', 'metadata', 'license', 'compatibility', 'allowed-tools', 'storage', 'version_mode'];
50
+ exports.ROLE_FRONTMATTER_PARAMS = [
51
+ 'inherits_from', 'always_load_docs', 'always_load_memory', 'always_load_skills', 'available_skills',
52
+ 'catalog_advertised', 'metadata', 'version_mode',
53
+ ];
54
+ /**
55
+ * Keys `shapeFrontmatterParams` will fold into `metadata` (not in the schema, value defined).
56
+ */
57
+ function foldedFrontmatterKeys(properties, allowed) {
58
+ return Object.entries(properties)
59
+ .filter(([key, value]) => !allowed.includes(key) && value !== undefined)
60
+ .map(([key]) => key);
61
+ }
62
+ /**
63
+ * Write the one-line stderr note about folded frontmatter keys (nothing when none were folded).
64
+ * Stderr keeps --json stdout clean.
65
+ */
66
+ function noteFoldedFrontmatterKeys(properties, allowed) {
67
+ const folded = foldedFrontmatterKeys(properties, allowed);
68
+ if (folded.length > 0) {
69
+ process.stderr.write(`note: frontmatter keys not in the schema were stored under metadata: ${folded.join(', ')}\n`);
70
+ }
71
+ }
72
+ /**
73
+ * Split frontmatter-derived properties into schema params (sent top-level) and the
74
+ * rest, which is merged under `metadata` (inert client key/value strings).
75
+ */
76
+ function shapeFrontmatterParams(properties, allowed) {
77
+ const out = {};
78
+ const extra = {};
79
+ for (const [key, value] of Object.entries(properties)) {
80
+ if (allowed.includes(key)) {
81
+ out[key] = value;
82
+ }
83
+ else if (value !== undefined) {
84
+ extra[key] = typeof value === 'string' ? value : JSON.stringify(value);
85
+ }
86
+ }
87
+ if (Object.keys(extra).length > 0) {
88
+ const existing = out.metadata && typeof out.metadata === 'object' ? out.metadata : {};
89
+ out.metadata = { ...extra, ...existing };
90
+ }
91
+ return out;
92
+ }
40
93
  /**
41
94
  * Throws if any frontmatter-derived property key collides with a reserved
42
95
  * protocol param name.
@@ -101,7 +154,8 @@ function parseSkillFile(content) {
101
154
  * their relative path (e.g. "references/member-roles.md") — matching how
102
155
  * SKILL.md cites them, so bundled reference docs land complete (#247).
103
156
  *
104
- * Also excludes `skill pull`'s provenance sidecar (SKILL_SIDECAR) and
157
+ * Also excludes `skill pull`'s provenance sidecar (SKILL_SIDECAR), `role pull`'s
158
+ * (ROLE_SIDECAR) and
105
159
  * `skill dev`'s local runtime-state dir (.sa-state/) — neither is skill
106
160
  * content, and uploading them would leak local revision bookkeeping / state
107
161
  * into the remote library and agent sandboxes.
@@ -125,6 +179,8 @@ function readReferences(dir) {
125
179
  continue; // exclude only the top-level skill file
126
180
  if (key === skill_pull_1.SKILL_SIDECAR)
127
181
  continue; // exclude the skill pull provenance sidecar
182
+ if (key === skill_pull_1.ROLE_SIDECAR)
183
+ continue; // exclude the role pull provenance sidecar
128
184
  references[key] = fs_1.default.readFileSync(abs, 'utf8');
129
185
  }
130
186
  };
@@ -217,6 +273,16 @@ async function pushParsedSkill(payload, options, config, sidecarRevision) {
217
273
  assertNoReservedFrontmatterKeys(properties);
218
274
  const isRole = !!options.role;
219
275
  const tool = isRole ? 'roles' : 'skills';
276
+ const frontmatterParams = shapeFrontmatterParams(properties, SKILL_FRONTMATTER_PARAMS);
277
+ noteFoldedFrontmatterKeys(properties, SKILL_FRONTMATTER_PARAMS);
278
+ // in_crew comes only from --in-crew (never frontmatter); sent only with --role and only when given.
279
+ const crewArgs = isRole && options.inCrew ? { in_crew: options.inCrew } : {};
280
+ // Tool error -> Error, with crew-scoping codes (ambiguous_role) mapped to an actionable --in-crew hint.
281
+ const toolError = (data) => {
282
+ const code = data?.code ?? 'unknown_error';
283
+ const hint = isRole ? (0, crew_1.crewErrorHint)(code, options.role, data?.message) : null;
284
+ return new Error(hint ?? `${code}: ${data?.message ?? 'MCP returned an error with no message'}`);
285
+ };
220
286
  // --dry-run: pre-flight a read to detect existence; make NO create/edit calls.
221
287
  if (options.dryRun) {
222
288
  // Role-scoped skills are read via the roles tool's read_skill {role, name};
@@ -224,7 +290,7 @@ async function pushParsedSkill(payload, options, config, sidecarRevision) {
224
290
  // `skill_not_found` when absent. (read does NOT accept `identifier` on the
225
291
  // roles tool, so the action/args must branch on isRole.)
226
292
  const readArgs = isRole
227
- ? { action: 'read_skill', role: options.role, name }
293
+ ? { action: 'read_skill', role: options.role, name, ...crewArgs }
228
294
  : { action: 'read', identifier: name };
229
295
  let readResult;
230
296
  try {
@@ -239,16 +305,15 @@ async function pushParsedSkill(payload, options, config, sidecarRevision) {
239
305
  return { status: 'would-create', name, data: {} };
240
306
  }
241
307
  // Any other error is unexpected — surface it
242
- const errMsg = readResult.data?.message ?? 'MCP returned an error with no message';
243
- throw new Error(`${code ?? 'unknown_error'}: ${errMsg}`);
308
+ throw toolError(readResult.data);
244
309
  }
245
310
  // Read succeeded → skill exists → would update
246
311
  return { status: 'would-update', name, data: {} };
247
312
  }
248
313
  // Spread frontmatter extras FIRST so the fixed protocol keys always win.
249
314
  const createArgs = isRole
250
- ? { ...properties, action: 'create_skill', role: options.role, name, description, body, references }
251
- : { ...properties, action: 'create', name, description, body, references };
315
+ ? { ...frontmatterParams, action: 'create_skill', role: options.role, ...crewArgs, name, description, body, references }
316
+ : { ...frontmatterParams, action: 'create', name, description, body, references };
252
317
  let result;
253
318
  try {
254
319
  result = await (0, mcp_1.callCrewsTool)(config, tool, createArgs);
@@ -260,8 +325,8 @@ async function pushParsedSkill(payload, options, config, sidecarRevision) {
260
325
  if (!result.ok && result.data?.code === 'name_collision') {
261
326
  const guardBaseVersion = sidecarRevision != null && !options.force;
262
327
  const editArgs = isRole
263
- ? { ...properties, action: 'edit_skill', role: options.role, name, description, body, references, ...(guardBaseVersion ? { base_version_id: sidecarRevision } : {}) }
264
- : { ...properties, action: 'edit', identifier: name, description, body, references, ...(guardBaseVersion ? { base_version_id: sidecarRevision } : {}) };
328
+ ? { ...frontmatterParams, action: 'edit_skill', role: options.role, ...crewArgs, name, description, body, references, ...(guardBaseVersion ? { base_version_id: sidecarRevision } : {}) }
329
+ : { ...frontmatterParams, action: 'edit', identifier: name, description, body, references, ...(guardBaseVersion ? { base_version_id: sidecarRevision } : {}) };
265
330
  try {
266
331
  result = await (0, mcp_1.callCrewsTool)(config, tool, editArgs);
267
332
  }
@@ -275,16 +340,12 @@ async function pushParsedSkill(payload, options, config, sidecarRevision) {
275
340
  const currentRevisionId = errData?.current_revision_id;
276
341
  throw new Error(`remote skill changed since your pull (their revision ${currentRevisionId}, your base ${sidecarRevision}) — re-pull to merge, or pass --force to overwrite`);
277
342
  }
278
- const errMsg = errData?.message ?? 'MCP returned an error with no message';
279
- throw new Error(`${errCode}: ${errMsg}`);
343
+ throw toolError(errData);
280
344
  }
281
345
  return { status: 'updated', name, data: result.data ?? {} };
282
346
  }
283
347
  if (!result.ok) {
284
- const errData = result.data;
285
- const errCode = errData?.code ?? 'unknown_error';
286
- const errMsg = errData?.message ?? 'MCP returned an error with no message';
287
- throw new Error(`${errCode}: ${errMsg}`);
348
+ throw toolError(result.data);
288
349
  }
289
350
  return { status: 'created', name, data: result.data ?? {} };
290
351
  }
@@ -324,7 +385,7 @@ function printPushResult(result, options) {
324
385
  * truthy snapshot_hint (null when the skill is version_mode=live).
325
386
  * Dry-run statuses never warn.
326
387
  */
327
- function stagedPushWarning(result, isRole) {
388
+ function stagedPushWarning(result, isRole, role, inCrew) {
328
389
  const { status, name, data } = result;
329
390
  if (status === 'created') {
330
391
  if (!data.snapshot_hint) {
@@ -340,7 +401,7 @@ function stagedPushWarning(result, isRole) {
340
401
  return null;
341
402
  }
342
403
  const publishLine = isRole
343
- ? ` Publish this role-scoped skill via the MCP crews_versions take_snapshot tool.\n`
404
+ ? ` Run: solidactions skill publish ${name} --role ${role ?? '<role>'}${inCrew ? ` --in-crew ${inCrew}` : ''}\n`
344
405
  : ` Run: solidactions skill publish ${name}\n`;
345
406
  const headline = status === 'updated'
346
407
  ? `⚠ Staged, not published. This revision won't run for agents until you publish it.\n`
@@ -386,7 +447,7 @@ async function refreshSidecarRevision(dir, sidecar, pushResult, options, config)
386
447
  if (headRevisionId === null) {
387
448
  const isRole = !!options.role;
388
449
  const readArgs = isRole
389
- ? { action: 'read_skill', role: options.role, name: pushResult.name }
450
+ ? { action: 'read_skill', role: options.role, name: pushResult.name, ...(options.inCrew ? { in_crew: options.inCrew } : {}) }
390
451
  : { action: 'read', identifier: pushResult.name };
391
452
  try {
392
453
  const readResult = await (0, mcp_1.callCrewsTool)(config, isRole ? 'roles' : 'skills', readArgs);
@@ -412,13 +473,17 @@ async function refreshSidecarRevision(dir, sidecar, pushResult, options, config)
412
473
  * (skills/ + commands/ subdirectories) based on directory structure.
413
474
  */
414
475
  async function skillPushWithConfig(dir, options, config) {
476
+ if (options.inCrew && !options.role) {
477
+ process.stderr.write(chalk_1.default.red('error: --in-crew requires --role.\n'));
478
+ process.exit(1);
479
+ }
415
480
  const absDir = path_1.default.resolve(dir);
416
481
  if (!fs_1.default.existsSync(absDir) || !fs_1.default.statSync(absDir).isDirectory()) {
417
482
  process.stderr.write(chalk_1.default.red(`error: "${dir}" is not a directory.\n`));
418
483
  process.exit(1);
419
484
  }
420
- if (options.publish && options.role) {
421
- process.stderr.write(chalk_1.default.red('error: --publish is not supported with --role yet; publish the role-scoped skill via the MCP take_snapshot tool.\n'));
485
+ if (fs_1.default.existsSync(path_1.default.join(absDir, skill_pull_1.ROLE_SIDECAR))) {
486
+ process.stderr.write(chalk_1.default.red(`error: ${dir} is a pulled role folder; use \`solidactions role push\`\n`));
422
487
  process.exit(1);
423
488
  }
424
489
  const topLevelSkillMd = path_1.default.join(absDir, 'SKILL.md');
@@ -461,7 +526,7 @@ async function skillPushWithConfig(dir, options, config) {
461
526
  }
462
527
  }
463
528
  else {
464
- publishOutcome = await (0, skill_snapshot_1.publishSkillByName)(config, pushResult.name);
529
+ publishOutcome = await (0, skill_snapshot_1.publishSkillByName)(config, pushResult.name, { role: options.role, inCrew: options.inCrew });
465
530
  }
466
531
  }
467
532
  if (options.json) {
@@ -471,9 +536,9 @@ async function skillPushWithConfig(dir, options, config) {
471
536
  }
472
537
  printPushResult(pushResult, options);
473
538
  if (publishOutcome) {
474
- (0, skill_snapshot_1.emitPublishOutcome)(pushResult.name, publishOutcome, { pushed: true });
539
+ (0, skill_snapshot_1.emitPublishOutcome)(pushResult.name, publishOutcome, { pushed: true, role: options.role, inCrew: options.inCrew });
475
540
  }
476
- const warning = stagedPushWarning(pushResult, !!options.role);
541
+ const warning = stagedPushWarning(pushResult, !!options.role, options.role, options.inCrew);
477
542
  if (warning) {
478
543
  process.stderr.write(chalk_1.default.yellow(warning));
479
544
  }
package/dist/index.js CHANGED
@@ -82,6 +82,7 @@ const skill_delete_1 = require("./commands/skill-delete");
82
82
  const skill_dev_1 = require("./commands/skill-dev");
83
83
  const skill_exec_1 = require("./commands/skill-exec");
84
84
  const role_push_1 = require("./commands/role-push");
85
+ const role_pull_1 = require("./commands/role-pull");
85
86
  const doc_push_1 = require("./commands/doc-push");
86
87
  const doc_pull_1 = require("./commands/doc-pull");
87
88
  const doc_upload_1 = require("./commands/doc-upload");
@@ -922,6 +923,7 @@ skill
922
923
  .description('Push a local skill folder into the library (create, or update if it already exists)')
923
924
  .argument('<dir>', 'Path to the skill directory (must contain SKILL.md)')
924
925
  .option('--role <name>', 'Scope the skill to a role instead of the shared library')
926
+ .option('--in-crew <crew>', 'Crew containing the role (with --role; disambiguates roles in multiple crews)')
925
927
  .option('--json', 'Output result as JSON')
926
928
  .option('--dry-run', 'Preview create vs update without writing')
927
929
  .option('--publish', 'Publish (snapshot) the skill after pushing, making it live for agents')
@@ -933,6 +935,8 @@ skill
933
935
  .command('publish')
934
936
  .description('Publish (snapshot) a skill so its latest pushed revision goes live for agents')
935
937
  .argument('<name>', 'Skill name/identifier (e.g. "my-skill" or "shared/my-skill")')
938
+ .option('--role <name>', 'Publish a role-scoped skill of this role instead of a shared-library skill')
939
+ .option('--in-crew <crew>', 'Crew containing the role (with --role; disambiguates roles in multiple crews)')
936
940
  .option('--json', 'Output result as JSON')
937
941
  .action(async (name, options) => {
938
942
  await (0, skill_publish_1.skillPublish)(name, options);
@@ -942,6 +946,8 @@ skill
942
946
  .description('Fetch a skill from the library to a local folder for editing (inverse of push)')
943
947
  .argument('<name>', 'Skill name or identifier')
944
948
  .argument('[dest]', 'Destination directory (defaults to ./<name>/)')
949
+ .option('--role <role>', 'Pull a role-scoped skill of this role instead of a shared-library skill')
950
+ .option('--in-crew <crew>', 'Crew containing the role (with --role; disambiguates roles in multiple crews)')
945
951
  .option('--json', 'Output raw read result as JSON (no file writes)')
946
952
  .action(async (name, dest, options) => {
947
953
  await (0, skill_pull_1.skillPull)(name, dest, options);
@@ -1012,11 +1018,27 @@ const role = exports.program.command('role').description('Manage roles (crews SO
1012
1018
  role
1013
1019
  .command('push <dir>')
1014
1020
  .description('Push a role definition (create or update)')
1021
+ .option('--in-crew <crew>', 'Crew that contains the role (required to create a role; disambiguates when the name exists in several crews)')
1022
+ .option('--replace-links', 'Replace always_load_skills / available_skills even when they differ from what role pull recorded (the server may hold links you cannot see)')
1015
1023
  .option('--dry-run', 'Preview create vs update without writing')
1016
1024
  .option('--json', 'Output result as JSON')
1017
1025
  .action(async (dir, options) => {
1018
1026
  await (0, role_push_1.rolePush)(dir, options);
1019
1027
  });
1028
+ role
1029
+ .command('pull')
1030
+ .description('Fetch a role and its role-scoped skills to a local folder (inverse of push)\n\n' +
1031
+ 'Pulls the role\'s PUBLISHED version: a versioned role must have a snapshot (or use version_mode: live).\n' +
1032
+ 'Inherited properties are merged by the server (RoleActivator) and are pulled as the effective value.\n' +
1033
+ 'For a role with inherits_from, pushing the pulled folder back would store the inherited values on the child (a warning is printed).\n' +
1034
+ 'Writes SKILL.md, .solidactions-role.json and skills/<skill>/ in one atomic replace of the folder.')
1035
+ .argument('<name>', 'Role name')
1036
+ .argument('[dir]', 'Destination directory (defaults to ./<name>/)')
1037
+ .option('--in-crew <crew>', 'Crew that contains the role (disambiguates when the name exists in several crews)')
1038
+ .option('--no-skills', 'Pull the role only, without its role-scoped skills')
1039
+ .action(async (name, dir, options) => {
1040
+ await (0, role_pull_1.rolePull)(name, dir, options);
1041
+ });
1020
1042
  // =============================================================================
1021
1043
  // doc <subcommand> (SA-Docs surface)
1022
1044
  // =============================================================================
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.writeDirAtomic = writeDirAtomic;
37
+ exports.assertReplaceableDir = assertReplaceableDir;
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ /**
41
+ * Replace `dest` with a folder holding exactly `files` (relative path -> content),
42
+ * as a unit: the result is either the old complete folder or the new complete one,
43
+ * never a mix, and no stale files survive. Files go into a sibling temp dir first,
44
+ * then the temp dir is swapped in by rename. If any step fails the temp dir is removed and
45
+ * the old folder (if any) is left in place. `opts.stamp` fixes the temp/old name suffix
46
+ * (default pid-time); it exists so tests can force a rename failure.
47
+ */
48
+ function writeDirAtomic(dest, files, opts = {}) {
49
+ dest = path.resolve(dest); // a trailing slash would otherwise put the temp dir inside dest
50
+ for (const rel of Object.keys(files)) {
51
+ if (path.isAbsolute(rel) || rel.split(/[\\/]/).includes('..'))
52
+ throw new Error(`unsafe path: ${rel}`);
53
+ }
54
+ const stamp = opts.stamp ?? `${process.pid}-${Date.now()}`;
55
+ const tmp = `${dest}.tmp-${stamp}`;
56
+ fs.mkdirSync(tmp, { recursive: true });
57
+ try {
58
+ for (const [rel, content] of Object.entries(files)) {
59
+ const target = path.join(tmp, rel);
60
+ fs.mkdirSync(path.dirname(target), { recursive: true });
61
+ fs.writeFileSync(target, content);
62
+ }
63
+ }
64
+ catch (e) {
65
+ fs.rmSync(tmp, { recursive: true, force: true });
66
+ throw e;
67
+ }
68
+ const old = `${dest}.old-${stamp}`;
69
+ const hadOld = fs.existsSync(dest);
70
+ let movedAside = false;
71
+ try {
72
+ if (hadOld) {
73
+ fs.renameSync(dest, old);
74
+ movedAside = true;
75
+ }
76
+ fs.renameSync(tmp, dest);
77
+ }
78
+ catch (e) {
79
+ // Put the old folder back if it was already moved aside, and never leave the staged dir behind.
80
+ if (movedAside)
81
+ fs.renameSync(old, dest);
82
+ fs.rmSync(tmp, { recursive: true, force: true });
83
+ throw e;
84
+ }
85
+ if (hadOld)
86
+ fs.rmSync(old, { recursive: true, force: true });
87
+ }
88
+ /**
89
+ * Guard for callers that replace a whole folder with writeDirAtomic. Throws unless
90
+ * `dest` is safe to swap out: it must not be the current directory or one of its
91
+ * parents, must not be a file, and if it already holds anything it must contain
92
+ * `marker` directly (proof that a previous pull created it). A missing or empty
93
+ * dest is fine. `cwd` exists so tests can avoid process.chdir; `kind` names the noun in the refusal.
94
+ */
95
+ function assertReplaceableDir(dest, marker, cwd = process.cwd(), kind = 'skill') {
96
+ const resolved = path.resolve(dest);
97
+ const exists = fs.existsSync(resolved);
98
+ const real = exists ? fs.realpathSync(resolved) : resolved;
99
+ const rel = path.relative(real, fs.realpathSync(cwd));
100
+ if (rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel))) {
101
+ throw new Error(`refusing to replace ${dest}: it is the current directory or one of its parents`);
102
+ }
103
+ if (!exists)
104
+ return;
105
+ if (!fs.statSync(resolved).isDirectory()) {
106
+ throw new Error(`refusing to replace ${dest}: it exists and is not a directory`);
107
+ }
108
+ if (fs.readdirSync(resolved).length > 0 && !fs.existsSync(path.join(resolved, marker))) {
109
+ throw new Error(`refusing to replace ${dest}: it exists and is not a pulled ${kind} (no ${marker}); remove it or choose another destination`);
110
+ }
111
+ }
@@ -12,6 +12,8 @@ exports.fetchCrews = fetchCrews;
12
12
  exports.resolveCrewId = resolveCrewId;
13
13
  exports.resolveRoleCrewPath = resolveRoleCrewPath;
14
14
  exports.crewIdForPath = crewIdForPath;
15
+ exports.crewErrorHint = crewErrorHint;
16
+ exports.normalizeCrewPath = normalizeCrewPath;
15
17
  const axios_1 = __importDefault(require("axios"));
16
18
  const chalk_1 = __importDefault(require("chalk"));
17
19
  const api_1 = require("./api");
@@ -118,3 +120,32 @@ async function crewIdForPath(config, crewPath) {
118
120
  console.error(chalk_1.default.red(`Could not resolve crew "${crewPath}" to a crew id (matched ${byPath.length} by path, ${byName.length} by name).`));
119
121
  process.exit(1);
120
122
  }
123
+ /**
124
+ * Map crew-scoping server error codes to an actionable CLI message, or null when
125
+ * the code is not crew-related. `crew_required`: a role create with no crew.
126
+ * `ambiguous_role`: the role name exists in several crews. The live server answers a
127
+ * create that omits in_crew entirely with `invalid_parameter` ("Required for create:
128
+ * in_crew") and reserves `crew_required` for an empty/null in_crew, so both map to
129
+ * the same hint.
130
+ */
131
+ function crewErrorHint(code, roleName, message) {
132
+ const missingInCrew = code === 'invalid_parameter' && typeof message === 'string' && /required for create:\s*in_crew/i.test(message);
133
+ if (code === 'crew_required' || missingInCrew) {
134
+ return 'this role must live in a crew: pass --in-crew CREW';
135
+ }
136
+ if (code === 'ambiguous_role') {
137
+ return `role${roleName ? ` '${roleName}'` : ''} exists in multiple crews: pass --in-crew CREW to choose one`;
138
+ }
139
+ return null;
140
+ }
141
+ /**
142
+ * Canonical spelling of a crew path for comparison: split on '/', trim each segment, drop empty
143
+ * segments, rejoin. Mirrors how the server resolves crew paths (it trims segments and ignores
144
+ * empty ones), so 'acme/', ' acme ' and 'acme' are the same crew. Blank or non-string => null.
145
+ */
146
+ function normalizeCrewPath(value) {
147
+ if (typeof value !== 'string')
148
+ return null;
149
+ const path = value.split('/').map((seg) => seg.trim()).filter((seg) => seg !== '').join('/');
150
+ return path === '' ? null : path;
151
+ }
package/dist/utils/mcp.js CHANGED
@@ -40,6 +40,9 @@ var __importStar = (this && this.__importStar) || (function () {
40
40
  };
41
41
  })();
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.McpRpcError = void 0;
44
+ exports.retryAfterSeconds = retryAfterSeconds;
45
+ exports.resolveCrewsCall = resolveCrewsCall;
43
46
  exports.callCrewsTool = callCrewsTool;
44
47
  exports.callDocsTool = callDocsTool;
45
48
  exports.callCrewsToolContent = callCrewsToolContent;
@@ -50,6 +53,42 @@ const api_1 = require("./api");
50
53
  // eslint-disable-next-line @typescript-eslint/no-var-requires
51
54
  const pkg = require('../../package.json');
52
55
  const CLI_VERSION = pkg.version;
56
+ /** A JSON-RPC `error` member in the server's response (protocol-level failure, not a tool isError). */
57
+ class McpRpcError extends Error {
58
+ code;
59
+ constructor(code, message) {
60
+ super(message);
61
+ this.code = code;
62
+ this.name = 'McpRpcError';
63
+ }
64
+ }
65
+ exports.McpRpcError = McpRpcError;
66
+ /** Total HTTP attempts for one call when the server answers 429 (the first try plus 2 retries). */
67
+ const RATE_LIMIT_MAX_ATTEMPTS = 3;
68
+ /** Wait used when a 429 carries no usable Retry-After. */
69
+ const RATE_LIMIT_DEFAULT_WAIT_SEC = 5;
70
+ /** No single wait exceeds this, whatever the server asks for. */
71
+ const RATE_LIMIT_MAX_WAIT_SEC = 60;
72
+ /** Seconds to wait for a Retry-After value (integer seconds or HTTP-date, RFC 9110); default when missing/invalid; capped. */
73
+ function retryAfterSeconds(header) {
74
+ const value = (Array.isArray(header) ? header[0] : header)?.trim();
75
+ let sec = RATE_LIMIT_DEFAULT_WAIT_SEC;
76
+ if (value) {
77
+ if (/^\d+$/.test(value)) {
78
+ sec = parseInt(value, 10);
79
+ }
80
+ else if (/^[+-]?\d+(\.\d+)?$/.test(value)) {
81
+ // Signed or fractional numbers are not valid Retry-After; wait at least 1s (only a literal "0" waits 0).
82
+ sec = Math.max(1, Math.ceil(Number(value)));
83
+ }
84
+ else {
85
+ const at = Date.parse(value);
86
+ if (!Number.isNaN(at))
87
+ sec = Math.max(1, Math.ceil((at - Date.now()) / 1000));
88
+ }
89
+ }
90
+ return Math.min(sec, RATE_LIMIT_MAX_WAIT_SEC);
91
+ }
53
92
  /** Internal: POST one tools/call and return the raw result envelope (isError + content blocks). */
54
93
  async function postMcpTool(config, endpointPath, toolName, args) {
55
94
  const baseHeaders = (0, api_1.getApiHeaders)(config, 'application/json');
@@ -66,7 +105,7 @@ async function postMcpTool(config, endpointPath, toolName, args) {
66
105
  const parsed = new url_1.URL(`${config.host}${endpointPath}`);
67
106
  const isHttps = parsed.protocol === 'https:';
68
107
  const transport = isHttps ? https : http;
69
- const responseData = await new Promise((resolve, reject) => {
108
+ const attempt = () => new Promise((resolve, reject) => {
70
109
  const options = {
71
110
  hostname: parsed.hostname,
72
111
  port: parsed.port || (isHttps ? 443 : 80),
@@ -75,24 +114,38 @@ async function postMcpTool(config, endpointPath, toolName, args) {
75
114
  headers: { ...headers, 'Content-Length': Buffer.byteLength(body) },
76
115
  };
77
116
  const req = transport.request(options, (res) => {
78
- let raw = '';
79
- res.on('data', (chunk) => { raw += chunk; });
117
+ // Collect bytes and decode once: appending Buffer chunks to a string decodes
118
+ // each chunk separately and corrupts multibyte UTF-8 split across chunks.
119
+ const chunks = [];
120
+ res.on('data', (chunk) => { chunks.push(chunk); });
80
121
  res.on('end', () => {
81
- if (res.statusCode === 404) {
82
- reject(new Error(`MCP request failed: ${parsed.host} has no ${endpointPath} endpoint — the server may be older or newer than this CLI (${CLI_VERSION}). Raw: HTTP 404 ${raw}`));
83
- }
84
- else if (res.statusCode && res.statusCode >= 400) {
85
- reject(new Error(`MCP request failed with HTTP ${res.statusCode}: ${raw}`));
86
- }
87
- else {
88
- resolve(raw);
89
- }
122
+ resolve({
123
+ status: res.statusCode ?? 0,
124
+ retryAfter: res.headers['retry-after'],
125
+ raw: Buffer.concat(chunks).toString('utf8'),
126
+ });
90
127
  });
91
128
  });
92
129
  req.on('error', reject);
93
130
  req.write(body);
94
131
  req.end();
95
132
  });
133
+ let last;
134
+ for (let n = 1;; n++) {
135
+ last = await attempt();
136
+ if (last.status !== 429 || n >= RATE_LIMIT_MAX_ATTEMPTS)
137
+ break;
138
+ const waitSec = retryAfterSeconds(last.retryAfter);
139
+ process.stderr.write(`solidactions: rate limited by server (429); retrying in ${waitSec}s (attempt ${n + 1}/${RATE_LIMIT_MAX_ATTEMPTS})\n`);
140
+ await new Promise((resolve) => setTimeout(resolve, waitSec * 1000));
141
+ }
142
+ if (last.status === 404) {
143
+ throw new Error(`MCP request failed: ${parsed.host} has no ${endpointPath} endpoint — the server may be older or newer than this CLI (${CLI_VERSION}). Raw: HTTP 404 ${last.raw}`);
144
+ }
145
+ if (last.status >= 400) {
146
+ throw new Error(`MCP request failed with HTTP ${last.status}: ${last.raw}`);
147
+ }
148
+ const responseData = last.raw;
96
149
  let parsed2;
97
150
  try {
98
151
  parsed2 = JSON.parse(responseData);
@@ -100,6 +153,9 @@ async function postMcpTool(config, endpointPath, toolName, args) {
100
153
  catch {
101
154
  throw new Error(`MCP server returned non-JSON response: ${responseData}`);
102
155
  }
156
+ if (parsed2?.error) {
157
+ throw new McpRpcError(parsed2.error.code ?? -1, `MCP ${toolName}: ${parsed2.error.message ?? JSON.stringify(parsed2.error)}`);
158
+ }
103
159
  const result = parsed2?.result;
104
160
  return { isError: result?.isError === true, content: result?.content ?? [] };
105
161
  }
@@ -110,7 +166,10 @@ async function postMcpTool(config, endpointPath, toolName, args) {
110
166
  */
111
167
  async function callMcpTool(config, endpointPath, toolName, args) {
112
168
  const raw = await postMcpTool(config, endpointPath, toolName, args);
113
- const textContent = raw.content?.[0]?.text ?? '{}';
169
+ if (!raw.content || raw.content.length === 0) {
170
+ return { ok: false, data: { code: 'empty_result', message: `MCP ${toolName} returned no content` } };
171
+ }
172
+ const textContent = raw.content[0]?.text ?? '{}';
114
173
  let toolData;
115
174
  try {
116
175
  toolData = JSON.parse(textContent);
@@ -121,14 +180,64 @@ async function callMcpTool(config, endpointPath, toolName, args) {
121
180
  return { ok: !raw.isError, data: toolData };
122
181
  }
123
182
  const UNIFIED_MCP_PATH = '/mcp';
124
- // Server consolidated per-domain MCP servers into one endpoint with namespaced tools.
125
- const CREWS_TOOL_NAMES = { skills: 'crews_skills', roles: 'crews_roles' };
183
+ // Current catalog (solidactions-app ToolCatalog.php): the public tool depends on the action.
184
+ // Only actions the CLI actually sends are routed; anything else throws in resolveCrewsCall.
185
+ const CREWS_ROUTES = {
186
+ skills: {
187
+ list: { tool: 'crews_skills_read' },
188
+ read: { tool: 'crews_skills_read' },
189
+ read_reference_file: { tool: 'crews_skills_read' },
190
+ create: { tool: 'crews_skills_manage' },
191
+ edit: { tool: 'crews_skills_manage' },
192
+ delete: { tool: 'crews_delete', action: 'delete_skill' },
193
+ sandbox_exec: { tool: 'crews_sandbox', action: 'skill_exec', rename: { environment: 'skill_exec_environment' } },
194
+ },
195
+ roles: {
196
+ list: { tool: 'crews_roles_read' },
197
+ read: { tool: 'crews_roles_read' },
198
+ list_skills: { tool: 'crews_roles_read' },
199
+ read_skill: { tool: 'crews_roles_read' },
200
+ read_reference_file: { tool: 'crews_roles_read' },
201
+ create: { tool: 'crews_roles_manage' },
202
+ edit: { tool: 'crews_roles_manage' },
203
+ create_skill: { tool: 'crews_roles_manage' },
204
+ edit_skill: { tool: 'crews_roles_manage' },
205
+ sandbox_exec: { tool: 'crews_sandbox', action: 'role_exec', rename: { environment: 'role_exec_environment' } },
206
+ },
207
+ };
208
+ /**
209
+ * Map a CLI-level crews call (group + action) to the public MCP tool, action and
210
+ * param names of the current catalog. Throws for an action the CLI has no route for.
211
+ */
212
+ function resolveCrewsCall(group, args) {
213
+ const action = String(args.action ?? '');
214
+ const route = CREWS_ROUTES[group][action];
215
+ if (!route)
216
+ throw new Error(`unsupported crews action: ${group}.${action}`);
217
+ const out = {};
218
+ for (const [k, v] of Object.entries(args)) {
219
+ if (v === undefined)
220
+ continue;
221
+ out[route.rename?.[k] ?? k] = v;
222
+ }
223
+ if (route.action)
224
+ out.action = route.action;
225
+ return { tool: route.tool, args: out };
226
+ }
227
+ function isCrewsGroup(name) {
228
+ return name === 'skills' || name === 'roles';
229
+ }
126
230
  /**
127
- * Call a single MCP tool on the unified /mcp endpoint, mapping legacy crews
128
- * tool names ('skills'/'roles') to their namespaced equivalents.
231
+ * Call a crews MCP tool on the unified /mcp endpoint. 'skills' / 'roles' are CLI
232
+ * groups resolved per action via resolveCrewsCall; any other name (e.g.
233
+ * 'crews_history_manage') is passed through unchanged.
129
234
  */
130
235
  async function callCrewsTool(config, toolName, args) {
131
- return callMcpTool(config, UNIFIED_MCP_PATH, CREWS_TOOL_NAMES[toolName] ?? toolName, args);
236
+ if (isCrewsGroup(toolName)) {
237
+ const r = resolveCrewsCall(toolName, args);
238
+ return callMcpTool(config, UNIFIED_MCP_PATH, r.tool, r.args);
239
+ }
240
+ return callMcpTool(config, UNIFIED_MCP_PATH, toolName, args);
132
241
  }
133
242
  /**
134
243
  * Call a single MCP tool on the unified /mcp endpoint.
@@ -143,6 +252,7 @@ async function callDocsTool(config, toolName, args) {
143
252
  * (callCrewsTool) would throw on those.
144
253
  */
145
254
  async function callCrewsToolContent(config, toolName, args) {
146
- const raw = await postMcpTool(config, UNIFIED_MCP_PATH, CREWS_TOOL_NAMES[toolName] ?? toolName, args);
255
+ const r = isCrewsGroup(toolName) ? resolveCrewsCall(toolName, args) : { tool: toolName, args };
256
+ const raw = await postMcpTool(config, UNIFIED_MCP_PATH, r.tool, r.args);
147
257
  return { ok: !raw.isError, content: raw.content };
148
258
  }