@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.
@@ -8,16 +8,28 @@
8
8
  * The role def is a SKILL.md-shaped file (frontmatter name+description, body).
9
9
  * Roles carry NO references.
10
10
  *
11
- * Supports --dry-run: pre-flight a read to detect existence; prints
12
- * "[dry-run] would create/update '<name>'" without making any create/edit call.
11
+ * Supports --dry-run: prints "[dry-run] would create/update '<name>'" without making any
12
+ * create/edit call, and reports the same outcome (or the same error) the real push would.
13
13
  *
14
- * Upsert: create → on name_collision → edit.
14
+ * Which crew: --in-crew is required to CREATE a role (the server rejects a create without it
15
+ * before it even checks for a collision). So without --in-crew the role is resolved first via
16
+ * roles `list`: exactly one match -> edit it (in that match's crew); none -> it would be a
17
+ * create, so ask for --in-crew; several -> ambiguous, ask for --in-crew.
18
+ * With --in-crew: create -> on name_collision -> edit (dry-run pre-flights a read).
15
19
  * Roles use 'name' (NOT 'identifier') for read and edit.
20
+ *
21
+ * Skill links: `role pull` records the always_load_skills / available_skills it exported in the
22
+ * .solidactions-role.json sidecar. Editing the role the folder was pulled from omits a link list
23
+ * that still equals that baseline (the server keeps all links, including ones the caller cannot
24
+ * see) and refuses a changed list unless --replace-links. Creates and sidecar-less folders send
25
+ * the lists as written.
16
26
  */
17
27
  var __importDefault = (this && this.__importDefault) || function (mod) {
18
28
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
29
  };
20
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.readRoleSidecar = readRoleSidecar;
32
+ exports.planLinkBaseline = planLinkBaseline;
21
33
  exports.rolePushWithConfig = rolePushWithConfig;
22
34
  exports.rolePush = rolePush;
23
35
  const fs_1 = __importDefault(require("fs"));
@@ -25,7 +37,149 @@ const path_1 = __importDefault(require("path"));
25
37
  const chalk_1 = __importDefault(require("chalk"));
26
38
  const api_1 = require("../utils/api");
27
39
  const mcp_1 = require("../utils/mcp");
40
+ const crew_1 = require("../utils/crew");
41
+ const skill_pull_1 = require("./skill-pull");
28
42
  const skill_push_1 = require("./skill-push");
43
+ const LINK_FIELDS = ['always_load_skills', 'available_skills'];
44
+ /** A doc id from JSON (number or numeric string); anything else => null. */
45
+ function asDocId(v) {
46
+ const n = typeof v === 'string' && /^\d+$/.test(v) ? parseInt(v, 10) : v;
47
+ return typeof n === 'number' && Number.isInteger(n) ? n : null;
48
+ }
49
+ /**
50
+ * Read the role pull sidecar. Absent, unreadable or nameless => null (treated as a hand-authored
51
+ * folder). A sidecar without `links` (written before links were recorded) has an empty baseline,
52
+ * which errs on the safe side: an unchanged (absent) list is omitted, a present list needs
53
+ * --replace-links.
54
+ */
55
+ function readRoleSidecar(absDir) {
56
+ const file = path_1.default.join(absDir, skill_pull_1.ROLE_SIDECAR);
57
+ if (!fs_1.default.existsSync(file))
58
+ return null;
59
+ let raw;
60
+ try {
61
+ raw = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || raw.name === '')
67
+ return null;
68
+ const asList = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
69
+ return {
70
+ name: raw.name,
71
+ inCrew: (0, crew_1.normalizeCrewPath)(raw.in_crew),
72
+ docId: asDocId(raw.doc_id),
73
+ links: {
74
+ always_load_skills: asList(raw.links?.always_load_skills),
75
+ available_skills: asList(raw.links?.available_skills),
76
+ },
77
+ };
78
+ }
79
+ /**
80
+ * When editing the role this folder was pulled from, leave unchanged link lists out of the edit
81
+ * (the server then preserves every link, hidden ones included) and refuse a changed list unless
82
+ * --replace-links. Not the pulled role => params as-is. "Pulled role" means the sidecar name equals
83
+ * the frontmatter name and, when both sides know the role's doc id, the doc ids are equal;
84
+ * otherwise (either id unknown) the sidecar's crew, if it recorded one, must equal the target crew
85
+ * after normalisation (trimmed segments, empty ones dropped).
86
+ * Equality is exact and ordered; absent equals []. Returns the params to send and the fields
87
+ * that were kept as-is (present in the frontmatter, left out of the call).
88
+ */
89
+ function planLinkBaseline(params, sidecar, name, target, replaceLinks) {
90
+ if (!sidecar || sidecar.name !== name)
91
+ return { params, kept: [], refused: null };
92
+ if (sidecar.docId !== null && target.docId != null) {
93
+ if (sidecar.docId !== target.docId)
94
+ return { params, kept: [], refused: null };
95
+ }
96
+ else if (sidecar.inCrew !== null && sidecar.inCrew !== (0, crew_1.normalizeCrewPath)(target.crew)) {
97
+ return { params, kept: [], refused: null };
98
+ }
99
+ const out = { ...params };
100
+ const kept = [];
101
+ for (const field of LINK_FIELDS) {
102
+ const base = sidecar.links[field];
103
+ // Absent equals []; a blank value (`always_load_skills:` => null) is not a list, so it counts as changed.
104
+ const value = out[field] === undefined ? [] : out[field];
105
+ const same = Array.isArray(value) && value.length === base.length && value.every((v, i) => v === base[i]);
106
+ if (same) {
107
+ if (out[field] !== undefined)
108
+ kept.push(field);
109
+ delete out[field];
110
+ }
111
+ else if (!replaceLinks) {
112
+ return {
113
+ params, kept: [],
114
+ refused: `${field} differs from what was pulled. The server may hold skill links you can't see, ` +
115
+ `and replacing the list deletes them. Re-run with --replace-links to replace it anyway.`,
116
+ };
117
+ }
118
+ else if (out[field] === undefined || out[field] === null) {
119
+ out[field] = []; // list removed or left blank in the frontmatter + --replace-links: clear it
120
+ }
121
+ }
122
+ return { params: out, kept, refused: null };
123
+ }
124
+ /** planLinkBaseline, exiting 1 with the refusal on stderr. */
125
+ function applyLinkBaseline(params, sidecar, name, target, replaceLinks) {
126
+ const plan = planLinkBaseline(params, sidecar, name, target, replaceLinks);
127
+ if (plan.refused !== null) {
128
+ process.stderr.write(chalk_1.default.red(`error: ${plan.refused}\n`));
129
+ process.exit(1);
130
+ }
131
+ return plan;
132
+ }
133
+ /** Print a role-push tool error (mapping crew-scoping codes to a hint) and exit 1. */
134
+ function failWithToolError(data, roleName) {
135
+ const code = data?.code ?? 'unknown_error';
136
+ const hint = (0, crew_1.crewErrorHint)(code, roleName, data?.message);
137
+ if (hint) {
138
+ process.stderr.write(chalk_1.default.red(`error: ${hint}\n`));
139
+ }
140
+ else {
141
+ const errMsg = data?.message ?? 'MCP returned an error with no message';
142
+ process.stderr.write(chalk_1.default.red(`error: ${code}: ${errMsg}\n`));
143
+ }
144
+ process.exit(1);
145
+ }
146
+ /**
147
+ * Find the role by name via roles `list` (each entry carries `identifier`/`name` and
148
+ * `in_crew`). `list` takes no paging parameters and returns every role, so no role can be
149
+ * missed. Exits 1 if the list call itself fails.
150
+ */
151
+ async function resolveExistingRole(config, name) {
152
+ let list;
153
+ try {
154
+ list = await (0, mcp_1.callCrewsTool)(config, 'roles', { action: 'list' });
155
+ }
156
+ catch (e) {
157
+ process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
158
+ process.exit(1);
159
+ }
160
+ if (!list.ok) {
161
+ process.stderr.write(chalk_1.default.red(`error: could not list roles to find '${name}': ${list.data?.code ?? 'unknown_error'}: ${list.data?.message ?? 'MCP returned an error with no message'}\n`));
162
+ process.exit(1);
163
+ }
164
+ const roles = Array.isArray(list.data?.roles) ? list.data.roles : [];
165
+ const matches = roles.filter((r) => (r.identifier ?? r.name) === name);
166
+ if (matches.length === 0)
167
+ return { kind: 'missing' };
168
+ if (matches.length === 1)
169
+ return { kind: 'edit', inCrew: matches[0].in_crew ?? null, docId: asDocId(matches[0].doc_id) };
170
+ return { kind: 'ambiguous', crews: matches.map((m) => m.in_crew ?? null) };
171
+ }
172
+ /** Exit 1 for a role that cannot be pushed without --in-crew (would be a create, or is ambiguous). */
173
+ function failUnresolved(resolved, name) {
174
+ if (resolved.kind === 'missing') {
175
+ process.stderr.write(chalk_1.default.red(`error: role '${name}' does not exist yet; ${(0, crew_1.crewErrorHint)('crew_required')}\n`));
176
+ }
177
+ else {
178
+ const crews = resolved.crews.map((c) => c ?? '(legacy flat role)').join(', ');
179
+ process.stderr.write(chalk_1.default.red(`error: ${(0, crew_1.crewErrorHint)('ambiguous_role', name)} (found in: ${crews})\n`));
180
+ }
181
+ process.exit(1);
182
+ }
29
183
  /**
30
184
  * Core implementation — accepts an injected config so tests can point at a
31
185
  * stub server without touching the filesystem config.
@@ -62,12 +216,40 @@ async function rolePushWithConfig(dir, options, config) {
62
216
  process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
63
217
  process.exit(1);
64
218
  }
65
- // --dry-run: pre-flight a read to detect existence; NO create or edit.
66
- // Roles use {action:'read', name} (NOT identifier).
219
+ const frontmatterParams = (0, skill_push_1.shapeFrontmatterParams)(properties, skill_push_1.ROLE_FRONTMATTER_PARAMS);
220
+ (0, skill_push_1.noteFoldedFrontmatterKeys)(properties, skill_push_1.ROLE_FRONTMATTER_PARAMS);
221
+ // in_crew comes only from --in-crew (never frontmatter); sent only when given.
222
+ const crewArgs = options.inCrew ? { in_crew: options.inCrew } : {};
223
+ // Without --in-crew, find the role first: the outcome (edit / error) is decided here, for
224
+ // the real push and --dry-run alike.
225
+ let resolved = null;
226
+ if (!options.inCrew) {
227
+ resolved = await resolveExistingRole(config, name);
228
+ if (resolved.kind !== 'edit')
229
+ failUnresolved(resolved, name);
230
+ }
231
+ // --dry-run: NO create or edit. Resolved above (no --in-crew) => would update.
232
+ // With --in-crew, pre-flight a read to detect existence. Roles use {action:'read', name} (NOT identifier).
233
+ const sidecar = readRoleSidecar(absDir);
234
+ const replaceLinks = options.replaceLinks === true;
235
+ /** The would-update line, after the same link check the real edit runs (may exit 1). */
236
+ const reportWouldUpdate = (target) => {
237
+ const { kept } = applyLinkBaseline(frontmatterParams, sidecar, name, target, replaceLinks);
238
+ if (options.json) {
239
+ console.log(JSON.stringify({}));
240
+ }
241
+ else {
242
+ const note = kept.length > 0 ? ` (keeping ${kept.join(', ')} as-is on the server)` : '';
243
+ console.log(chalk_1.default.cyan(`[dry-run] would update '${name}'${note}`));
244
+ }
245
+ process.exit(0);
246
+ };
67
247
  if (options.dryRun) {
248
+ if (resolved?.kind === 'edit')
249
+ reportWouldUpdate({ crew: resolved.inCrew, docId: resolved.docId });
68
250
  let readResult;
69
251
  try {
70
- readResult = await (0, mcp_1.callCrewsTool)(config, 'roles', { action: 'read', name });
252
+ readResult = await (0, mcp_1.callCrewsTool)(config, 'roles', { action: 'read', name, ...crewArgs });
71
253
  }
72
254
  catch (e) {
73
255
  process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
@@ -84,43 +266,49 @@ async function rolePushWithConfig(dir, options, config) {
84
266
  }
85
267
  process.exit(0);
86
268
  }
269
+ // A versioned role with no published snapshot answers read with no_snapshot:
270
+ // the role exists (there is a doc), it just has nothing live yet -> would update.
271
+ if (code === 'no_snapshot')
272
+ reportWouldUpdate({ crew: options.inCrew ?? null });
87
273
  // Any other error is unexpected — surface it
88
- const errMsg = readResult.data?.message ?? 'MCP returned an error with no message';
89
- process.stderr.write(chalk_1.default.red(`error: ${code ?? 'unknown_error'}: ${errMsg}\n`));
90
- process.exit(1);
274
+ failWithToolError(readResult.data, name);
91
275
  }
92
276
  // Read succeeded → role exists → would update
93
- if (options.json) {
94
- console.log(JSON.stringify({}));
95
- }
96
- else {
97
- console.log(chalk_1.default.cyan(`[dry-run] would update '${name}'`));
98
- }
99
- process.exit(0);
277
+ reportWouldUpdate({ crew: options.inCrew ?? null });
100
278
  }
101
- // Upsert: try create first; on name_collision switch to edit.
279
+ // Upsert. Resolved to an existing role (no --in-crew): edit it in the crew the list gave.
280
+ // With --in-crew: try create first; on name_collision switch to edit.
102
281
  // Roles carry NO references — do not send references key.
103
282
  // Frontmatter extras are spread FIRST so the fixed protocol keys always win.
104
- let result;
105
- try {
106
- result = await (0, mcp_1.callCrewsTool)(config, 'roles', {
107
- ...properties,
108
- action: 'create',
109
- name,
110
- description,
111
- body,
112
- });
113
- }
114
- catch (e) {
115
- process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
116
- process.exit(1);
283
+ let result = null;
284
+ if (resolved?.kind !== 'edit') {
285
+ try {
286
+ result = await (0, mcp_1.callCrewsTool)(config, 'roles', {
287
+ ...frontmatterParams,
288
+ ...crewArgs,
289
+ action: 'create',
290
+ name,
291
+ description,
292
+ body,
293
+ });
294
+ }
295
+ catch (e) {
296
+ process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
297
+ process.exit(1);
298
+ }
117
299
  }
118
- // On name collision, switch to the edit path.
300
+ // Edit path: the role was resolved as existing, or the create collided.
119
301
  // Roles edit uses 'name' (NOT 'identifier').
120
- if (!result.ok && result.data?.code === 'name_collision') {
302
+ if (result === null || (!result.ok && result.data?.code === 'name_collision')) {
303
+ const editCrewArgs = resolved?.kind === 'edit'
304
+ ? (resolved.inCrew ? { in_crew: resolved.inCrew } : {})
305
+ : crewArgs;
306
+ const { params: editParams } = applyLinkBaseline(frontmatterParams, sidecar, name, resolved?.kind === 'edit' ? { crew: resolved.inCrew, docId: resolved.docId } : { crew: options.inCrew ?? null }, replaceLinks);
307
+ let edited;
121
308
  try {
122
- result = await (0, mcp_1.callCrewsTool)(config, 'roles', {
123
- ...properties,
309
+ edited = await (0, mcp_1.callCrewsTool)(config, 'roles', {
310
+ ...editParams,
311
+ ...editCrewArgs,
124
312
  action: 'edit',
125
313
  name,
126
314
  description,
@@ -131,14 +319,11 @@ async function rolePushWithConfig(dir, options, config) {
131
319
  process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
132
320
  process.exit(1);
133
321
  }
134
- if (!result.ok) {
135
- const errCode = result.data?.code ?? 'unknown_error';
136
- const errMsg = result.data?.message ?? 'MCP returned an error with no message';
137
- process.stderr.write(chalk_1.default.red(`error: ${errCode}: ${errMsg}\n`));
138
- process.exit(1);
322
+ if (!edited.ok) {
323
+ failWithToolError(edited.data, name);
139
324
  }
140
325
  if (options.json) {
141
- console.log(JSON.stringify(result.data ?? {}));
326
+ console.log(JSON.stringify(edited.data ?? {}));
142
327
  }
143
328
  else {
144
329
  console.log(chalk_1.default.green(`updated role '${name}'`));
@@ -146,10 +331,7 @@ async function rolePushWithConfig(dir, options, config) {
146
331
  process.exit(0);
147
332
  }
148
333
  if (!result.ok) {
149
- const errCode = result.data?.code ?? 'unknown_error';
150
- const errMsg = result.data?.message ?? 'MCP returned an error with no message';
151
- process.stderr.write(chalk_1.default.red(`error: ${errCode}: ${errMsg}\n`));
152
- process.exit(1);
334
+ failWithToolError(result.data, name);
153
335
  }
154
336
  if (options.json) {
155
337
  console.log(JSON.stringify(result.data ?? {}));
@@ -2,18 +2,26 @@
2
2
  /**
3
3
  * solidactions skill publish <name>
4
4
  *
5
- * Publishes (snapshots) a shared skill so its latest pushed revision goes live
6
- * for agents.
5
+ * Publishes (snapshots) a skill so its latest pushed revision goes live for
6
+ * agents. Shared-library by default; --role [--in-crew] targets a role-scoped skill.
7
7
  */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
9
12
  exports.skillPublishWithConfig = skillPublishWithConfig;
10
13
  exports.skillPublish = skillPublish;
14
+ const chalk_1 = __importDefault(require("chalk"));
11
15
  const api_1 = require("../utils/api");
12
16
  const skill_snapshot_1 = require("../utils/skill-snapshot");
13
17
  /** Core implementation — accepts an injected config for tests. */
14
18
  async function skillPublishWithConfig(name, options, config) {
15
- const outcome = await (0, skill_snapshot_1.publishSkillByName)(config, name);
16
- (0, skill_snapshot_1.emitPublishOutcome)(name, outcome, { json: options.json });
19
+ if (options.inCrew && !options.role) {
20
+ process.stderr.write(chalk_1.default.red('error: --in-crew requires --role.\n'));
21
+ process.exit(1);
22
+ }
23
+ const outcome = await (0, skill_snapshot_1.publishSkillByName)(config, name, { role: options.role, inCrew: options.inCrew });
24
+ (0, skill_snapshot_1.emitPublishOutcome)(name, outcome, { json: options.json, role: options.role });
17
25
  }
18
26
  /** Entry point called from index.ts. */
19
27
  async function skillPublish(name, options) {
@@ -4,7 +4,12 @@
4
4
  *
5
5
  * Fetches a skill from the crews library and reconstructs a local skill folder
6
6
  * (the inverse of `skill push`): writes <dest>/SKILL.md + any bundled reference
7
- * files under <dest>/. Default dest = ./<name>/.
7
+ * files under <dest>/. Default dest = ./<name>/. Shared-library skills by
8
+ * default; --role [--in-crew] pulls a role-scoped skill.
9
+ *
10
+ * The destination is replaced as a unit (writeDirAtomic): after a pull it holds
11
+ * exactly the fetched files — old complete copy or new complete copy, never a
12
+ * mix, and no stale files.
8
13
  *
9
14
  * --json mode: prints the raw read result from the server and exits WITHOUT
10
15
  * writing any files. This is useful for scripting/inspection. The default
@@ -14,99 +19,172 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
19
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
20
  };
16
21
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.SKILL_SIDECAR = void 0;
22
+ exports.ROLE_SIDECAR = exports.SKILL_SIDECAR = void 0;
23
+ exports.fetchSkillFiles = fetchSkillFiles;
24
+ exports.pullSkillWithConfig = pullSkillWithConfig;
18
25
  exports.skillPullWithConfig = skillPullWithConfig;
19
26
  exports.skillPull = skillPull;
20
- const fs_1 = __importDefault(require("fs"));
21
27
  const path_1 = __importDefault(require("path"));
22
28
  const chalk_1 = __importDefault(require("chalk"));
23
29
  const api_1 = require("../utils/api");
24
30
  const mcp_1 = require("../utils/mcp");
25
31
  const skill_bundle_1 = require("../utils/skill-bundle");
32
+ const atomic_dir_1 = require("../utils/atomic-dir");
26
33
  /** Filename of the provenance sidecar written alongside a pulled skill. */
27
34
  exports.SKILL_SIDECAR = '.solidactions-skill.json';
28
- /**
29
- * Core implementation — accepts an injected config so tests can point at a
30
- * stub server without touching the filesystem config.
31
- *
32
- * Steps:
33
- * 1. Call skills.read to fetch the skill from the library.
34
- * 2. If --json: print the raw result, exit 0 (no file writes).
35
- * 3. Otherwise: reconstruct SKILL.md from the returned `properties` (which
36
- * contains name, description, and any extra props), OMITTING `type` (the
37
- * server sets it; stripping mirrors what parseSkillFile does on push so a
38
- * push→pull→push round-trip is idempotent). Write <dest>/SKILL.md, then
39
- * write each reference file under <dest>/ with a path-traversal guard.
40
- */
41
- async function skillPullWithConfig(name, dest, options, config) {
42
- // Call the crews MCP server for a skills.read
35
+ /** Filename of the provenance sidecar written into a pulled role folder (and the replace marker). Lives here so skill push can recognise a pulled role folder without importing role-pull (which imports skill-push). */
36
+ exports.ROLE_SIDECAR = '.solidactions-role.json';
37
+ /** A user-facing pull failure (message is printed as-is after `error: `). */
38
+ class SkillPullError extends Error {
39
+ }
40
+ function isPlainObject(v) {
41
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
42
+ }
43
+ /** Same rule as writeDirAtomic, so unsafe reference keys can be skipped with a warning instead of aborting the pull. */
44
+ function isUnsafeKey(key) {
45
+ return path_1.default.isAbsolute(key) || key.split(/[\\/]/).includes('..');
46
+ }
47
+ /** Call skills.read (shared) or roles.read_skill (--role) and return the raw payload. */
48
+ async function readSkillData(config, name, opts) {
49
+ const isRole = Boolean(opts.role);
43
50
  let result;
44
51
  try {
45
- result = await (0, mcp_1.callCrewsTool)(config, 'skills', { action: 'read', identifier: name });
52
+ result = isRole
53
+ ? await (0, mcp_1.callCrewsTool)(config, 'roles', {
54
+ action: 'read_skill',
55
+ role: opts.role,
56
+ name,
57
+ in_crew: opts.inCrew,
58
+ })
59
+ : await (0, mcp_1.callCrewsTool)(config, 'skills', { action: 'read', identifier: name });
46
60
  }
47
61
  catch (e) {
48
- process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
49
- process.exit(1);
62
+ throw new SkillPullError(e.message);
50
63
  }
51
64
  if (!result.ok) {
52
65
  const code = result.data?.code ?? 'unknown_error';
53
66
  const message = result.data?.message ?? 'MCP returned an error with no message';
54
- process.stderr.write(chalk_1.default.red(`error: ${code}: ${message}\n`));
55
- process.exit(1);
67
+ if (!isRole && code === 'skill_not_found') {
68
+ throw new SkillPullError(`${code}: ${message}\n` +
69
+ `'${name}' is not in the shared library; if it belongs to a role, pass --role ROLE [--in-crew CREW]`);
70
+ }
71
+ throw new SkillPullError(`${code}: ${message}`);
56
72
  }
57
- const data = result.data;
58
- // --json mode: print raw result and exit WITHOUT writing files.
59
- // This is intentionally non-destructive: inspect the raw server payload
60
- // without side-effects. File reconstruction is the default (no --json) mode.
61
- if (options.json) {
62
- console.log(JSON.stringify(data));
63
- process.exit(0);
73
+ return result.data;
74
+ }
75
+ /**
76
+ * Read, validate and return the full file map for a skill (SKILL.md, references,
77
+ * provenance sidecar) WITHOUT writing anything. Keys are relative paths.
78
+ * Throws SkillPullError-style Errors on server errors or a malformed response.
79
+ */
80
+ async function fetchSkillFiles(config, name, opts = {}) {
81
+ const data = await readSkillData(config, name, opts);
82
+ return buildSkillFiles(config, name, opts, data);
83
+ }
84
+ async function buildSkillFiles(config, name, opts, data) {
85
+ // Shape guard — before anything is written or fetched further.
86
+ if (!isPlainObject(data) || typeof data.body !== 'string' || !isPlainObject(data.properties)) {
87
+ const keys = isPlainObject(data) ? Object.keys(data) : [];
88
+ throw new SkillPullError(`unexpected response shape from server (keys received: ${keys.length ? keys.join(', ') : '(none)'})`);
64
89
  }
65
- // Resolve the output directory (default: ./<name>/)
66
- const out = dest ?? './' + name;
67
- const absOut = path_1.default.resolve(out);
68
- // Build the frontmatter object from `properties`, OMITTING `type`.
69
- // The server stores a `type` field but it is stripped on push (parseSkillFile
70
- // does `const { type: _type, ...properties } = rest`). We mirror that here
71
- // so that pull → push is idempotent.
72
- const skillMdContent = (0, skill_bundle_1.reconstructSkillMd)(data.properties, data.body);
73
- // Create the output directory (and parents) if needed
74
- fs_1.default.mkdirSync(absOut, { recursive: true });
75
- // Write SKILL.md
76
- fs_1.default.writeFileSync(path_1.default.join(absOut, 'SKILL.md'), skillMdContent, 'utf8');
77
- // Write reference files, guarding against path traversal
78
- const reference = data.reference ?? {};
79
- const absOutNorm = path_1.default.resolve(absOut) + path_1.default.sep;
80
- let writtenCount = 0;
81
- let skippedCount = 0;
82
- for (const [key, content] of Object.entries(reference)) {
83
- // Guard 1: reject absolute paths
84
- if (path_1.default.isAbsolute(key)) {
85
- process.stderr.write(chalk_1.default.yellow(`warn: skipping unsafe reference key (absolute path): ${key}\n`));
86
- skippedCount++;
90
+ if (data.reference !== undefined && data.reference !== null && !isPlainObject(data.reference)) {
91
+ throw new SkillPullError(`unexpected response shape from server: 'reference' is not an object (keys received: ${Object.keys(data).join(', ')})`);
92
+ }
93
+ const isRole = Boolean(opts.role);
94
+ const group = isRole ? 'roles' : 'skills';
95
+ const locator = isRole
96
+ ? { role: opts.role, name, in_crew: opts.inCrew }
97
+ : { identifier: name };
98
+ const files = {};
99
+ for (const [key, value] of Object.entries((data.reference ?? {}))) {
100
+ if (isUnsafeKey(key)) {
101
+ process.stderr.write(chalk_1.default.yellow(`warn: skipping unsafe reference key: ${key}\n`));
87
102
  continue;
88
103
  }
89
- // Guard 2: reject path traversal (any key that resolves outside absOut)
90
- const target = path_1.default.resolve(absOut, key);
91
- if (!target.startsWith(absOutNorm)) {
92
- process.stderr.write(chalk_1.default.yellow(`warn: skipping unsafe reference key (traversal): ${key}\n`));
93
- skippedCount++;
94
- continue;
104
+ if (typeof value === 'string') {
105
+ files[key] = value;
106
+ }
107
+ else if (isPlainObject(value) && value.binary === true) {
108
+ files[key] = await (0, skill_bundle_1.fetchBinaryReference)(config, group, locator, key, {
109
+ size: value.size,
110
+ blobSha: value.blob_sha,
111
+ });
112
+ }
113
+ else {
114
+ throw new SkillPullError(`unexpected response shape from server: reference '${key}' is neither text nor a binary descriptor`);
95
115
  }
96
- // Safe: create parent dirs and write the file
97
- fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
98
- fs_1.default.writeFileSync(target, content, 'utf8');
99
- writtenCount++;
100
116
  }
101
- // Write the provenance sidecar so downstream commands (e.g. `skill push`)
102
- // can detect drift against the revision this pull was taken from.
117
+ // Build the frontmatter from `properties`, OMITTING `type` (the server sets it;
118
+ // stripping mirrors parseSkillFile on push so push -> pull -> push is idempotent).
119
+ files['SKILL.md'] = (0, skill_bundle_1.reconstructSkillMd)(data.properties, data.body);
120
+ // Provenance sidecar so downstream commands (e.g. `skill push`) can detect drift.
103
121
  const sidecar = {
104
122
  identifier: data.identifier,
105
123
  doc_id: typeof data.doc_id === 'string' ? parseInt(data.doc_id, 10) : data.doc_id,
106
124
  head_revision_id: typeof data.head_revision_id === 'string' ? parseInt(data.head_revision_id, 10) : (data.head_revision_id ?? null),
107
- role: null,
125
+ role: opts.role ?? null,
108
126
  };
109
- fs_1.default.writeFileSync(path_1.default.join(absOut, exports.SKILL_SIDECAR), JSON.stringify(sidecar, null, 2) + '\n', 'utf8');
127
+ if (isRole)
128
+ sidecar.in_crew = opts.inCrew ?? null;
129
+ files[exports.SKILL_SIDECAR] = JSON.stringify(sidecar, null, 2) + '\n';
130
+ return files;
131
+ }
132
+ /** Fetch a skill and replace `dest` with it as a unit. Throws on failure; nothing is written on error. */
133
+ async function pullSkillWithConfig(name, dest, config, opts = {}) {
134
+ (0, atomic_dir_1.assertReplaceableDir)(dest, exports.SKILL_SIDECAR);
135
+ (0, atomic_dir_1.writeDirAtomic)(path_1.default.resolve(dest), await fetchSkillFiles(config, name, opts));
136
+ }
137
+ function fail(message) {
138
+ process.stderr.write(chalk_1.default.red(`error: ${message}\n`));
139
+ process.exit(1);
140
+ }
141
+ /**
142
+ * Core CLI implementation — accepts an injected config so tests can point at a
143
+ * stub server without touching the filesystem config.
144
+ */
145
+ async function skillPullWithConfig(name, dest, options, config) {
146
+ if (options.inCrew && !options.role)
147
+ fail('--in-crew requires --role.');
148
+ if (dest === undefined && (name === '.' || name === '..' || name.includes('/') || name.includes('\\'))) {
149
+ fail(`'${name}' cannot be used as a default destination folder; pass an explicit [dest] directory`);
150
+ }
151
+ const readOpts = { role: options.role, inCrew: options.inCrew };
152
+ const out = dest ?? './' + name;
153
+ // Replacing a folder is destructive: refuse before any network call or write.
154
+ if (!options.json) {
155
+ try {
156
+ (0, atomic_dir_1.assertReplaceableDir)(out, exports.SKILL_SIDECAR);
157
+ }
158
+ catch (e) {
159
+ fail(e.message);
160
+ }
161
+ }
162
+ let data;
163
+ try {
164
+ data = await readSkillData(config, name, readOpts);
165
+ }
166
+ catch (e) {
167
+ fail(e.message);
168
+ }
169
+ // --json mode: print raw result and exit WITHOUT writing files.
170
+ if (options.json) {
171
+ console.log(JSON.stringify(data));
172
+ process.exit(0);
173
+ }
174
+ let files;
175
+ try {
176
+ files = await buildSkillFiles(config, name, readOpts, data);
177
+ }
178
+ catch (e) {
179
+ fail(e.message);
180
+ }
181
+ try {
182
+ (0, atomic_dir_1.writeDirAtomic)(path_1.default.resolve(out), files);
183
+ }
184
+ catch (e) {
185
+ fail(`failed to write ${out}: ${e.message}`);
186
+ }
187
+ const writtenCount = Object.keys(files).filter((k) => k !== 'SKILL.md' && k !== exports.SKILL_SIDECAR).length;
110
188
  const refSummary = writtenCount === 1 ? '1 reference' : `${writtenCount} references`;
111
189
  console.log(chalk_1.default.green(`pulled skill '${name}' → ${out} (${refSummary})`));
112
190
  process.exit(0);