@solidactions/cli 1.29.0 → 1.31.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.
@@ -16,28 +16,13 @@ exports.docsPushWithConfig = docsPushWithConfig;
16
16
  exports.docsPush = docsPush;
17
17
  const fs_1 = __importDefault(require("fs"));
18
18
  const path_1 = __importDefault(require("path"));
19
+ const axios_1 = __importDefault(require("axios"));
20
+ const form_data_1 = __importDefault(require("form-data"));
19
21
  const chalk_1 = __importDefault(require("chalk"));
20
22
  const api_1 = require("../utils/api");
21
23
  const mcp_1 = require("../utils/mcp");
22
- const docs_pull_1 = require("./docs-pull");
24
+ const docs_manifest_1 = require("../utils/docs-manifest");
23
25
  const CHUNK_SIZE = 50;
24
- /**
25
- * Read `<absDir>/.solidactions-docs.json`. Absent or unparseable → null,
26
- * meaning nothing under `absDir` is guarded (sidecar convention from D1/D2).
27
- */
28
- function readManifest(absDir) {
29
- const manifestPath = path_1.default.join(absDir, docs_pull_1.DOCS_MANIFEST);
30
- if (!fs_1.default.existsSync(manifestPath)) {
31
- return null;
32
- }
33
- try {
34
- return JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
35
- }
36
- catch {
37
- process.stderr.write(chalk_1.default.yellow(`warn: ${docs_pull_1.DOCS_MANIFEST} exists but could not be parsed — all files will be treated as untracked\n`));
38
- return null;
39
- }
40
- }
41
26
  /**
42
27
  * Recursively walk `dir` and collect all *.md files.
43
28
  * Returns a list of absolute paths.
@@ -58,6 +43,35 @@ function walkMarkdownFiles(dir) {
58
43
  walk(dir);
59
44
  return results;
60
45
  }
46
+ const SKIP_DIRS = new Set(['node_modules']);
47
+ /**
48
+ * Recursively walk `dir` and collect relative paths of non-.md files that
49
+ * are not present in the manifest — never uploaded by `docs push`; `docs
50
+ * upload` is the way to create media docs from these. Dotfiles and
51
+ * dot-directories are excluded (`entry.name.startsWith('.')` also covers the
52
+ * `.solidactions-docs.json` sidecar itself).
53
+ */
54
+ function walkUntrackedBinaries(dir, manifest) {
55
+ const results = [];
56
+ const walk = (current) => {
57
+ for (const entry of fs_1.default.readdirSync(current, { withFileTypes: true })) {
58
+ if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name))
59
+ continue;
60
+ const abs = path_1.default.join(current, entry.name);
61
+ if (entry.isDirectory()) {
62
+ walk(abs);
63
+ }
64
+ else if (entry.isFile() && !entry.name.endsWith('.md')) {
65
+ const relPath = path_1.default.relative(dir, abs).split(path_1.default.sep).join('/');
66
+ if (!manifest?.docs[relPath]) {
67
+ results.push(relPath);
68
+ }
69
+ }
70
+ }
71
+ };
72
+ walk(dir);
73
+ return results;
74
+ }
61
75
  /**
62
76
  * Convert an absolute file path to a bulk_create item, relative to `rootDir`.
63
77
  */
@@ -132,19 +146,29 @@ async function docsPushWithConfig(dir, options, config) {
132
146
  process.exit(1);
133
147
  }
134
148
  const allFiles = walkMarkdownFiles(absDir);
135
- if (allFiles.length === 0) {
136
- process.stderr.write(chalk_1.default.red(`error: no .md files found under "${dir}" — nothing to push.\n`));
149
+ // A missing/unparseable manifest means nothing is tracked — everything is untracked,
150
+ // matching the existing (pre-drift-guard) bulk_create behavior byte-for-byte.
151
+ const manifest = (0, docs_manifest_1.readManifest)(absDir, { warnOnParseError: true });
152
+ const trackedMediaEntries = Object.entries(manifest?.docs ?? {}).filter(([, e]) => e.media);
153
+ // A pulled folder of images alone (no .md files) must still be pushable — the early
154
+ // exit only fires when there's truly nothing to push.
155
+ if (allFiles.length === 0 && trackedMediaEntries.length === 0) {
156
+ process.stderr.write(chalk_1.default.red(`error: no .md files or tracked media found under "${dir}" — nothing to push.\n`));
137
157
  process.exit(1);
138
158
  }
139
159
  // Partition into tracked (relative path present in the pull manifest) vs. untracked.
140
- // A missing/unparseable manifest means nothing is tracked — everything is untracked,
141
- // matching the existing (pre-drift-guard) bulk_create behavior byte-for-byte.
142
- const manifest = readManifest(absDir);
160
+ // A media doc titled *.md (e.g. `notes.md`) is bytes, not markdown — it's owned by
161
+ // the media pass below, not this markdown pass, or its bytes would be sent through
162
+ // docs_edit as a text body and corrupt the doc.
143
163
  const trackedFiles = [];
144
164
  const untrackedFiles = [];
145
165
  for (const f of allFiles) {
146
166
  const relPath = path_1.default.relative(absDir, f).split(path_1.default.sep).join('/');
147
- if (manifest?.docs[relPath]) {
167
+ const entry = manifest?.docs[relPath];
168
+ if (entry?.media) {
169
+ continue;
170
+ }
171
+ if (entry) {
148
172
  trackedFiles.push({ absPath: f, relPath });
149
173
  }
150
174
  else {
@@ -155,10 +179,11 @@ async function docsPushWithConfig(dir, options, config) {
155
179
  const trackedDrifted = [];
156
180
  const trackedPlanned = [];
157
181
  const trackedUnchanged = [];
182
+ const trackedMissing = [];
158
183
  for (const { absPath, relPath } of trackedFiles) {
159
184
  const entry = manifest.docs[relPath];
160
185
  const body = fs_1.default.readFileSync(absPath, 'utf8');
161
- const bodyHash = (0, docs_pull_1.sha256Hex)(body);
186
+ const bodyHash = (0, docs_manifest_1.sha256Hex)(body);
162
187
  // Skip-unchanged applies regardless of --force or --dry-run: force answers
163
188
  // drift, not staleness, and an old manifest lacking body_sha256 (undefined)
164
189
  // never matches, so it always falls through to a write (graceful degradation).
@@ -185,6 +210,12 @@ async function docsPushWithConfig(dir, options, config) {
185
210
  }
186
211
  if (!mcpResult.ok) {
187
212
  const code = mcpResult.data?.code ?? 'unknown_error';
213
+ if (code === 'doc_not_found') {
214
+ // The tracked doc was deleted remotely since the last pull. Not a genuine
215
+ // drift/error: report it and move on rather than aborting the whole push.
216
+ trackedMissing.push({ file: relPath, id: entry.id });
217
+ continue;
218
+ }
188
219
  const message = mcpResult.data?.message ?? 'MCP returned an error with no message';
189
220
  process.stderr.write(chalk_1.default.red(`error: ${code}: ${message}\n`));
190
221
  process.exit(1);
@@ -199,14 +230,87 @@ async function docsPushWithConfig(dir, options, config) {
199
230
  trackedWritten.push({ file: relPath, id: entry.id, current_revision_id: entry.current_revision_id });
200
231
  // Persist immediately so a later failure (another tracked write, or an
201
232
  // untracked bulk_create error) never loses this file's refreshed revision.
202
- fs_1.default.writeFileSync(path_1.default.join(absDir, docs_pull_1.DOCS_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
233
+ (0, docs_manifest_1.writeManifest)(absDir, manifest);
203
234
  }
235
+ // Media pass: tracked binaries (media: true) replace via POST /api/v1/docs/{id}/media,
236
+ // sharing the report arrays above.
237
+ for (const [relPath, entry] of trackedMediaEntries) {
238
+ const absPath = path_1.default.join(absDir, ...relPath.split('/'));
239
+ // Existence before hash: a pull whose media download failed records
240
+ // `media: true, body_sha256: null` and writes no file. push never deletes.
241
+ if (!fs_1.default.existsSync(absPath)) {
242
+ continue;
243
+ }
244
+ // A directory sitting where a media file is tracked (e.g. `hero.png/`) would
245
+ // otherwise make readFileSync throw EISDIR uncaught mid-push. push never deletes,
246
+ // so skip it rather than crash.
247
+ if (!fs_1.default.statSync(absPath).isFile()) {
248
+ continue;
249
+ }
250
+ const bytes = fs_1.default.readFileSync(absPath);
251
+ const bodyHash = (0, docs_manifest_1.sha256Hex)(bytes);
252
+ if (entry.body_sha256 != null && entry.body_sha256 === bodyHash) {
253
+ trackedUnchanged.push({ file: relPath, id: entry.id });
254
+ continue;
255
+ }
256
+ if (options.dryRun) {
257
+ trackedPlanned.push({ file: relPath, id: entry.id });
258
+ continue;
259
+ }
260
+ const form = new form_data_1.default();
261
+ form.append('file', bytes, { filename: path_1.default.basename(relPath) });
262
+ if (!options.force && entry.current_revision_id !== null) {
263
+ form.append('base_revision', String(entry.current_revision_id));
264
+ }
265
+ let doc;
266
+ try {
267
+ const response = await axios_1.default.post(`${config.host}/api/v1/docs/${entry.id}/media`, form, {
268
+ headers: { ...form.getHeaders(), ...(0, api_1.getApiHeaders)(config) },
269
+ maxContentLength: Infinity,
270
+ maxBodyLength: Infinity,
271
+ });
272
+ doc = response.data?.doc;
273
+ }
274
+ catch (error) {
275
+ const status = error.response?.status;
276
+ const data = error.response?.data;
277
+ if (status === 409 && data?.code === 'stale_revision') {
278
+ trackedDrifted.push({ file: relPath, their: data.current_revision_id ?? null, base: entry.current_revision_id });
279
+ continue;
280
+ }
281
+ if (status === 404 && data?.code === 'doc_not_found') {
282
+ // The tracked doc was deleted remotely since the last pull — same
283
+ // treatment as the markdown pass. `media_not_found` is a different case
284
+ // (doc exists but isn't a media doc) and is not handled here.
285
+ trackedMissing.push({ file: relPath, id: entry.id });
286
+ continue;
287
+ }
288
+ process.stderr.write(chalk_1.default.red(`error: ${relPath}: ${data?.message ?? error.message}\n`));
289
+ process.exit(1);
290
+ }
291
+ // The REST presenter names the revision `current_version_id`; MCP docs_edit
292
+ // names it `current_revision_id`. Reading the wrong one nulls the entry and
293
+ // silently disarms the drift guard on every later push.
294
+ entry.current_revision_id = doc?.current_version_id ?? entry.current_revision_id;
295
+ entry.body_sha256 = bodyHash;
296
+ trackedWritten.push({ file: relPath, id: entry.id, current_revision_id: entry.current_revision_id });
297
+ (0, docs_manifest_1.writeManifest)(absDir, manifest);
298
+ }
299
+ const untrackedMedia = walkUntrackedBinaries(absDir, manifest);
204
300
  const items = untrackedFiles.map((f) => fileToItem(f, absDir));
301
+ // Untracked docs (new files, or files re-orphaned by a deleted-remotely re-pull)
302
+ // must land back under the folder this directory was pulled into, not the docs
303
+ // root — an explicit --folder always overrides the manifest's recorded folder.
304
+ const effectiveFolder = options.folder ?? manifest?.folder_path;
305
+ const folderInferredFromManifest = !options.folder && !!manifest?.folder_path;
205
306
  // Chunk into groups of CHUNK_SIZE
206
307
  const chunks = [];
207
308
  for (let i = 0; i < items.length; i += CHUNK_SIZE) {
208
309
  chunks.push(items.slice(i, i + CHUNK_SIZE));
209
310
  }
311
+ if (folderInferredFromManifest && items.length > 0 && !options.json) {
312
+ console.log(chalk_1.default.gray(`creating untracked docs under "${effectiveFolder}" (from ${docs_manifest_1.DOCS_MANIFEST})`));
313
+ }
210
314
  const onConflict = options.onConflict ?? 'skip';
211
315
  const allResultRows = [];
212
316
  let mergedSummary = {};
@@ -225,9 +329,11 @@ async function docsPushWithConfig(dir, options, config) {
225
329
  if (options.type) {
226
330
  callArgs.type = options.type;
227
331
  }
228
- if (options.folder) {
332
+ if (effectiveFolder) {
229
333
  // Top-level base for every item; each item's relative_folder_path nests under it.
230
- callArgs.folder_path = options.folder;
334
+ // Explicit --folder wins; otherwise defaults to the manifest's folder_path so
335
+ // untracked docs in a pulled directory land back in the folder they came from.
336
+ callArgs.folder_path = effectiveFolder;
231
337
  }
232
338
  if (options.dryRun) {
233
339
  callArgs.dry_run = true;
@@ -267,14 +373,17 @@ async function docsPushWithConfig(dir, options, config) {
267
373
  missing: r.property_validation.missing ?? [],
268
374
  invalid: r.property_validation.invalid ?? [],
269
375
  }));
270
- const exitCode = trackedDrifted.length > 0 ? 1 : 0;
376
+ // `done: N errors` on its own says nothing. Name the file and the server's reason.
377
+ const erroredRows = allResultRows.filter((r) => r.status === 'error');
378
+ const exitCode = trackedDrifted.length > 0 || erroredRows.length > 0 ? 1 : 0;
271
379
  // --json: output single JSON object
272
380
  if (options.json) {
273
381
  console.log(JSON.stringify({
274
382
  summary: mergedSummary,
275
383
  pending: pendingItems,
276
384
  results: allResultRows,
277
- tracked: { written: trackedWritten, drifted: trackedDrifted, planned: trackedPlanned, unchanged: trackedUnchanged },
385
+ tracked: { written: trackedWritten, drifted: trackedDrifted, planned: trackedPlanned, unchanged: trackedUnchanged, missing: trackedMissing },
386
+ untracked_media: untrackedMedia,
278
387
  }));
279
388
  process.exit(exitCode);
280
389
  }
@@ -299,13 +408,31 @@ async function docsPushWithConfig(dir, options, config) {
299
408
  console.log(chalk_1.default.gray(` ${w.file}`));
300
409
  }
301
410
  }
411
+ if (untrackedMedia.length > 0) {
412
+ for (const file of untrackedMedia.slice(0, 10)) {
413
+ process.stderr.write(chalk_1.default.yellow(`${file}: not pushed — use \`solidactions docs upload\`\n`));
414
+ }
415
+ if (untrackedMedia.length > 10) {
416
+ process.stderr.write(chalk_1.default.yellow(`… and ${untrackedMedia.length - 10} more\n`));
417
+ }
418
+ }
419
+ for (const m of trackedMissing) {
420
+ process.stderr.write(chalk_1.default.yellow(`${m.file}: doc ${m.id} no longer exists (deleted remotely) — re-pull to untrack it, then push to re-create (restore or empty it from the trash first, or the title stays taken)\n`));
421
+ }
302
422
  const summaryLine = formatSummaryLine(mergedSummary, !!options.dryRun);
303
423
  if (options.dryRun) {
304
424
  console.log(chalk_1.default.cyan(`[dry-run preview] ${summaryLine}`));
305
425
  }
306
- else {
426
+ else if (items.length > 0) {
427
+ // Suppress "done: 0 docs" when there was nothing to bulk_create — printing it
428
+ // alongside a successful tracked/media write reads as a contradiction.
307
429
  console.log(chalk_1.default.green(`done: ${summaryLine}`));
308
430
  }
431
+ if (erroredRows.length > 0 && !options.json) {
432
+ for (const row of erroredRows) {
433
+ process.stderr.write(chalk_1.default.red(`${row.file}: ${row.error ?? row.code ?? 'unknown error'}\n`));
434
+ }
435
+ }
309
436
  if (pendingItems.length > 0) {
310
437
  console.log(chalk_1.default.yellow(`\nProperties pending (${pendingItems.length} doc${pendingItems.length === 1 ? '' : 's'}):`));
311
438
  for (const item of pendingItems) {
@@ -43,6 +43,53 @@ const axios_1 = __importDefault(require("axios"));
43
43
  const form_data_1 = __importDefault(require("form-data"));
44
44
  const chalk_1 = __importDefault(require("chalk"));
45
45
  const api_1 = require("../utils/api");
46
+ /**
47
+ * Resolve `--replace` to a doc id. A purely numeric value is an id; anything else
48
+ * is a docs path, resolved against the doc's *title* via GET /docs/by-path.
49
+ *
50
+ * Note the title is not always the local filename: `docs pull` sanitizes
51
+ * filesystem-illegal characters and may suffix collisions. For path-based work
52
+ * on a pulled folder, `docs push` is the right verb.
53
+ */
54
+ async function resolveReplaceTarget(config, replace) {
55
+ if (/^\d+$/.test(replace)) {
56
+ return Number(replace);
57
+ }
58
+ const slash = replace.lastIndexOf('/');
59
+ const folderPath = slash === -1 ? undefined : replace.slice(0, slash);
60
+ const title = slash === -1 ? replace : replace.slice(slash + 1);
61
+ // A trailing slash ("marketing/") leaves no title to look up. Fail here rather
62
+ // than asking the server to resolve an empty title and reporting its 404.
63
+ if (title === '') {
64
+ console.error(chalk_1.default.red(`✗ --replace "${replace}" names a folder, not a doc`));
65
+ return process.exit(1);
66
+ }
67
+ try {
68
+ const params = {};
69
+ if (folderPath)
70
+ params.folder_path = folderPath;
71
+ params.title = title;
72
+ const response = await axios_1.default.get(`${config.host}/api/v1/docs/by-path`, {
73
+ params,
74
+ headers: (0, api_1.getApiHeaders)(config),
75
+ });
76
+ return response.data.doc.id;
77
+ }
78
+ catch (error) {
79
+ const status = error.response?.status;
80
+ const code = error.response?.data?.code;
81
+ if (status === 422 && code === 'folder_path_not_found') {
82
+ console.error(chalk_1.default.red(`✗ no folder "${folderPath}" in this workspace`));
83
+ }
84
+ else if (status === 404) {
85
+ console.error(chalk_1.default.red(`✗ no doc titled "${title}"${folderPath ? ` in "${folderPath}"` : ' at the docs root'}`));
86
+ }
87
+ else {
88
+ console.error(chalk_1.default.red(`✗ could not resolve "${replace}" — ${error.response?.data?.message ?? error.message}`));
89
+ }
90
+ return process.exit(1);
91
+ }
92
+ }
46
93
  /**
47
94
  * Uploads one or more local files to SA-Docs media (`POST /api/v1/docs/media`),
48
95
  * sequentially. `--title` is only valid for a single file — with multiple
@@ -53,6 +100,14 @@ async function docsUpload(files, options = {}) {
53
100
  console.error(chalk_1.default.red('--title can only be used when uploading a single file.'));
54
101
  process.exit(1);
55
102
  }
103
+ if (options.replace && files.length > 1) {
104
+ console.error(chalk_1.default.red('--replace can only be used when uploading a single file.'));
105
+ process.exit(1);
106
+ }
107
+ if (options.replace && (options.title || options.folder)) {
108
+ console.error(chalk_1.default.red('--replace cannot be combined with --title or --folder — replace never renames or moves a doc.'));
109
+ process.exit(1);
110
+ }
56
111
  const config = await (0, api_1.requireConfigWithWorkspace)();
57
112
  let hadError = false;
58
113
  for (const file of files) {
@@ -65,12 +120,20 @@ async function docsUpload(files, options = {}) {
65
120
  }
66
121
  const form = new form_data_1.default();
67
122
  form.append('file', fs.createReadStream(absPath));
68
- if (options.folder)
69
- form.append('folder_path', options.folder);
70
- if (options.title)
71
- form.append('title', options.title);
123
+ if (!options.replace) {
124
+ if (options.folder)
125
+ form.append('folder_path', options.folder);
126
+ if (options.title)
127
+ form.append('title', options.title);
128
+ }
129
+ // Resolved once (--replace forbids multiple files), and kept so error messages
130
+ // can name the numeric doc id rather than echoing back a path.
131
+ const replaceDocId = options.replace ? await resolveReplaceTarget(config, options.replace) : null;
132
+ const url = replaceDocId !== null
133
+ ? `${config.host}/api/v1/docs/${replaceDocId}/media`
134
+ : `${config.host}/api/v1/docs/media`;
72
135
  try {
73
- const response = await axios_1.default.post(`${config.host}/api/v1/docs/media`, form, {
136
+ const response = await axios_1.default.post(url, form, {
74
137
  headers: {
75
138
  ...form.getHeaders(),
76
139
  ...(0, api_1.getApiHeaders)(config),
@@ -78,10 +141,15 @@ async function docsUpload(files, options = {}) {
78
141
  maxContentLength: Infinity,
79
142
  maxBodyLength: Infinity,
80
143
  });
81
- // The 201 body nests the created doc under a `doc` key.
144
+ // The 201/200 body nests the created/updated doc under a `doc` key.
82
145
  const doc = response.data?.doc;
83
- const location = doc?.folder_path || '/';
84
- console.log(chalk_1.default.green(`✓ ${displayName} → ${location} (doc ${doc?.id})`));
146
+ if (options.replace) {
147
+ console.log(chalk_1.default.green(`✓ ${displayName} → doc ${doc?.id} (replaced, rev ${doc?.current_version_id})`));
148
+ }
149
+ else {
150
+ const location = doc?.folder_path || '/';
151
+ console.log(chalk_1.default.green(`✓ ${displayName} → ${location} (doc ${doc?.id})`));
152
+ }
85
153
  }
86
154
  catch (error) {
87
155
  hadError = true;
@@ -93,6 +161,9 @@ async function docsUpload(files, options = {}) {
93
161
  else if (status === 401) {
94
162
  console.error(chalk_1.default.red(`✗ ${displayName} — Authentication failed. Run "solidactions login <api-key>" to re-configure.`));
95
163
  }
164
+ else if (status === 404 && data?.code === 'media_not_found') {
165
+ console.error(chalk_1.default.red(`✗ ${displayName} — doc ${replaceDocId} is not a media doc`));
166
+ }
96
167
  else if (status === 422) {
97
168
  console.error(chalk_1.default.red(`✗ ${displayName} — ${(0, api_1.formatValidationError)(data)}`));
98
169
  }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.skillDev = void 0;
4
+ /**
5
+ * solidactions skill dev <dir> -- <command...>
6
+ *
7
+ * Runs YOUR WORKING COPY (the folder you're editing) locally, with crew
8
+ * variables fetched at runtime. Counterpart of `skill exec`, which always
9
+ * executes the SERVER-STORED skill (--target sandbox|host). Renamed from
10
+ * `skill run` (deprecated alias kept until v2.0.0): "run" collides with the
11
+ * workflow-runs noun (`solidactions run …`), and run-vs-exec didn't encode
12
+ * the source-of-truth split agents need.
13
+ */
14
+ var skill_run_1 = require("./skill-run");
15
+ Object.defineProperty(exports, "skillDev", { enumerable: true, get: function () { return skill_run_1.skillRun; } });
@@ -3,26 +3,77 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateExecInvocation = validateExecInvocation;
6
7
  exports.skillExecWithConfig = skillExecWithConfig;
7
8
  exports.skillExec = skillExec;
8
9
  /**
9
- * solidactions skill exec <name> [--role <r>] [--environment <env>] -- <command...>
10
+ * solidactions skill exec <name> --target sandbox|host [...] -- <command...>
10
11
  *
11
- * Runs a command against the DEPLOYED skill in its real sandbox runtime via
12
- * the crews MCP exec_skill action — the post-push smoke step. Counterpart to
13
- * `skill run` (local). DELIBERATE DIVERGENCE from `skill run`: default
14
- * environment here is `production` (matches the server default — this is the
15
- * "verify deployed" step); `skill run` defaults to `dev` (a local dev loop).
12
+ * ALWAYS executes the server-stored skill (the artifact) — never local edits;
13
+ * that's `skill dev <dir>`. --target picks WHERE the stored skill executes:
14
+ * sandbox — the server-managed sandbox via crews MCP exec_skill (v1.30 behavior)
15
+ * host — this machine, from a transparent revision-checked cache under
16
+ * ~/.solidactions/cache/skills/ (no visible pull step)
17
+ * --target is REQUIRED (no default): a half-remembered command errors instead
18
+ * of guessing where to execute. Both targets default --environment production —
19
+ * moving execution between sandbox and host never silently changes the env.
16
20
  */
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const axios_1 = __importDefault(require("axios"));
17
23
  const chalk_1 = __importDefault(require("chalk"));
24
+ const path_1 = __importDefault(require("path"));
18
25
  const api_1 = require("../utils/api");
19
26
  const mcp_1 = require("../utils/mcp");
20
27
  const skill_run_1 = require("./skill-run");
28
+ const crew_1 = require("../utils/crew");
29
+ const skill_cache_1 = require("../utils/skill-cache");
30
+ const skill_cache_fs_1 = require("../utils/skill-cache-fs");
31
+ const skill_bundle_1 = require("../utils/skill-bundle");
32
+ /** Pure invocation checks (option matrix + name shape). Returns error text or null. */
33
+ function validateExecInvocation(name, options) {
34
+ if (options.target !== 'sandbox' && options.target !== 'host') {
35
+ return "--target is required: 'sandbox' (run in the server sandbox) or 'host' (run on this machine from the stored skill)";
36
+ }
37
+ if (name.startsWith('./') || name.startsWith('../') || path_1.default.isAbsolute(name)) {
38
+ return `'${name}' looks like a directory — skill exec executes the server-stored skill by name. To run a working copy: skill dev ${name}`;
39
+ }
40
+ if (options.target === 'sandbox' && options.crew) {
41
+ return '--crew only applies to --target host (sandbox variable composition is server-side)';
42
+ }
43
+ if (options.target === 'sandbox' && options.envFile) {
44
+ return '--env-file only applies to --target host (the sandbox env is composed server-side)';
45
+ }
46
+ if (options.role && options.crew) {
47
+ return '--crew conflicts with --role: a role-scoped skill takes its variables from the crew the role lives in';
48
+ }
49
+ if (options.inCrew && !options.role) {
50
+ return '--in-crew requires --role';
51
+ }
52
+ return null;
53
+ }
21
54
  async function skillExecWithConfig(name, commandParts, options, config) {
55
+ const invalid = validateExecInvocation(name, options);
56
+ if (invalid) {
57
+ process.stderr.write(chalk_1.default.red(`error: ${invalid}\n`));
58
+ process.exit(1);
59
+ }
60
+ if (fs_1.default.existsSync(name) && fs_1.default.statSync(name).isDirectory()) {
61
+ process.stderr.write(chalk_1.default.red(`error: '${name}' looks like a directory — skill exec executes the server-stored skill by name. To run a working copy: skill dev ${name}\n`));
62
+ process.exit(1);
63
+ }
22
64
  if (commandParts.length === 0) {
23
- process.stderr.write(chalk_1.default.red('error: no command given — usage: skill exec <name> -- <command...>\n'));
65
+ process.stderr.write(chalk_1.default.red('error: no command given — usage: skill exec <name> --target sandbox|host -- <command...>\n'));
24
66
  process.exit(1);
25
67
  }
68
+ const environment = options.environment ?? 'production';
69
+ if (options.target === 'sandbox') {
70
+ await execInSandbox(name, commandParts, options, environment, config);
71
+ }
72
+ else {
73
+ await execOnHost(name, commandParts, options, environment, config);
74
+ }
75
+ }
76
+ async function execInSandbox(name, commandParts, options, environment, config) {
26
77
  const command = commandParts.map(skill_run_1.shellQuoteArg).join(' ');
27
78
  const isRole = Boolean(options.role);
28
79
  const tool = isRole ? 'roles' : 'skills';
@@ -33,6 +84,7 @@ async function skillExecWithConfig(name, commandParts, options, config) {
33
84
  args.environment = options.environment;
34
85
  if (isRole && options.inCrew)
35
86
  args.in_crew = options.inCrew;
87
+ process.stderr.write(chalk_1.default.blue(`▶ stored skill ${name} → sandbox (${environment})\n`));
36
88
  let result;
37
89
  try {
38
90
  result = await (0, mcp_1.callCrewsTool)(config, tool, args);
@@ -55,6 +107,126 @@ async function skillExecWithConfig(name, commandParts, options, config) {
55
107
  process.stderr.write(chalk_1.default.blue(`remote exec: status=${data.status ?? 'unknown'} exit_code=${data.exit_code ?? 'unknown'}\n`));
56
108
  process.exit(data.exit_code ?? 1);
57
109
  }
110
+ async function execOnHost(name, commandParts, options, environment, config) {
111
+ const isRole = Boolean(options.role);
112
+ const tool = isRole ? 'roles' : 'skills';
113
+ const locator = isRole
114
+ ? { role: options.role, name, ...(options.inCrew ? { in_crew: options.inCrew } : {}) }
115
+ : { identifier: name };
116
+ // 1. Fetch the bundle.
117
+ let result;
118
+ try {
119
+ result = await (0, mcp_1.callCrewsTool)(config, tool, isRole
120
+ ? { action: 'read_skill', ...locator }
121
+ : { action: 'read', ...locator });
122
+ }
123
+ catch (e) {
124
+ process.stderr.write(chalk_1.default.red(`error: ${e.message}\n`));
125
+ process.exit(1);
126
+ }
127
+ if (!result.ok) {
128
+ const code = result.data?.code ?? 'unknown_error';
129
+ const message = result.data?.message ?? 'MCP returned an error with no message';
130
+ process.stderr.write(chalk_1.default.red(`error: ${code}: ${message}\n`));
131
+ process.exit(1);
132
+ }
133
+ const bundle = (0, skill_bundle_1.normalizeBundle)(result.data);
134
+ for (const unsafe of bundle.skippedUnsafe) {
135
+ process.stderr.write(chalk_1.default.yellow(`warn: skipping unsafe reference key: ${unsafe}\n`));
136
+ }
137
+ // 2. Resolve crew identity (vars + cache scope).
138
+ let crewId = null;
139
+ let scope = { kind: 'shared' };
140
+ if (isRole) {
141
+ const crewPath = await (0, crew_1.resolveRoleCrewPath)(config, options.role, options.inCrew);
142
+ crewId = await (0, crew_1.crewIdForPath)(config, crewPath);
143
+ scope = { kind: 'role', crewPath, role: options.role };
144
+ }
145
+ else if (options.crew) {
146
+ crewId = (await (0, crew_1.resolveCrewId)(config, options.crew)).id;
147
+ }
148
+ else {
149
+ process.stderr.write(chalk_1.default.gray('no --crew given — running without crew variables (shared-skill parity)\n'));
150
+ }
151
+ // 3. Plan + refresh the cache under the lock.
152
+ const cacheDir = (0, skill_cache_1.cacheDirFor)(config, scope, name);
153
+ const origin = (0, skill_cache_1.cacheOrigin)(config);
154
+ const desired = { 'SKILL.md': { kind: 'text', sha256: (0, skill_cache_fs_1.sha256Hex)(bundle.skillMd) } };
155
+ for (const [p, content] of Object.entries(bundle.textFiles)) {
156
+ desired[p] = { kind: 'text', sha256: (0, skill_cache_fs_1.sha256Hex)(content) };
157
+ }
158
+ for (const [p, ref] of Object.entries(bundle.binaryFiles)) {
159
+ desired[p] = { kind: 'binary', blobSha: ref.blobSha };
160
+ }
161
+ await (0, skill_cache_fs_1.withCacheLock)(cacheDir, async () => {
162
+ const manifest = (0, skill_cache_fs_1.readManifest)(cacheDir);
163
+ const onDisk = (0, skill_cache_fs_1.onDiskHashes)(cacheDir, [...new Set([...Object.keys(desired), ...Object.keys(manifest?.files ?? {})])]);
164
+ const plan = (0, skill_cache_1.planCacheRefresh)({ manifest, origin, identity: bundle.identity, desired, onDisk });
165
+ if (plan.action === 'refresh') {
166
+ const contents = {};
167
+ const newFiles = {};
168
+ for (const p of Object.keys(desired)) {
169
+ const spec = desired[p];
170
+ if (spec.kind === 'text') {
171
+ const content = p === 'SKILL.md' ? bundle.skillMd : bundle.textFiles[p];
172
+ if (plan.writes.includes(p))
173
+ contents[p] = content;
174
+ newFiles[p] = { sha256: spec.sha256 };
175
+ }
176
+ else {
177
+ if (plan.writes.includes(p)) {
178
+ const ref = bundle.binaryFiles[p];
179
+ const bytes = await (0, skill_bundle_1.fetchBinaryReference)(config, tool, locator, p, { size: ref.size, blobSha: ref.blobSha });
180
+ contents[p] = bytes;
181
+ newFiles[p] = { sha256: (0, skill_cache_fs_1.sha256Hex)(bytes), blob_sha: spec.blobSha };
182
+ }
183
+ else {
184
+ // Invariant: the planner only omits a binary from writes when the
185
+ // manifest entry exists and matches (upstreamSame && diskSame), so
186
+ // this carry-over cannot be undefined.
187
+ newFiles[p] = manifest?.files[p];
188
+ }
189
+ }
190
+ }
191
+ (0, skill_cache_fs_1.applyCachePlan)(cacheDir, plan, contents, {
192
+ schema_version: 1,
193
+ origin,
194
+ doc_id: bundle.identity.docId,
195
+ published: bundle.identity.published,
196
+ execution_revision_id: bundle.identity.executionRevisionId,
197
+ files: newFiles,
198
+ });
199
+ }
200
+ });
201
+ // 4. Resolve crew variables.
202
+ let resolved = {};
203
+ let skippedSecrets = [];
204
+ if (crewId !== null) {
205
+ try {
206
+ const response = await axios_1.default.get(`${config.host}/api/v1/crews/${crewId}/variables/resolve?environment=${encodeURIComponent(environment)}`, { headers: (0, api_1.getApiHeaders)(config) });
207
+ resolved = response.data?.variables ?? {};
208
+ skippedSecrets = response.data?.skipped_secrets ?? [];
209
+ }
210
+ catch (e) {
211
+ process.stderr.write(chalk_1.default.red(`error: failed to resolve crew variables: ${e?.response?.data?.message ?? e.message}\n`));
212
+ process.exit(1);
213
+ }
214
+ }
215
+ // 5. Run.
216
+ if (!bundle.identity.published) {
217
+ process.stderr.write(chalk_1.default.yellow('running unpublished draft revision\n'));
218
+ }
219
+ (0, skill_run_1.execLocally)({
220
+ dir: cacheDir,
221
+ commandParts,
222
+ environment,
223
+ resolved,
224
+ skippedSecrets,
225
+ envFile: options.envFile,
226
+ config,
227
+ banner: `▶ stored skill ${name} @ rev ${bundle.identity.executionRevisionId ?? '?'} → local cache (${environment})`,
228
+ });
229
+ }
58
230
  async function skillExec(name, commandParts, options) {
59
231
  const config = await (0, api_1.requireConfigWithWorkspace)();
60
232
  await skillExecWithConfig(name, commandParts, options, config);