@solidactions/cli 1.30.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.
package/README.md CHANGED
@@ -150,10 +150,19 @@ Manage agent skills on the crews SOP surface. `push` is an idempotent upsert (cr
150
150
  | `skill view <name>` | `--json` | Show one skill |
151
151
  | `skill pull <name> [dest]` | `--json` | Fetch a skill to a local folder for editing (inverse of push); writes a `.solidactions-skill.json` provenance sidecar used by `push`'s drift guard |
152
152
  | `skill delete <name>` | `--json` | Delete a skill (Admin only) |
153
- | `skill run <dir> -- <command...>` | `--crew <nameOrId>`, `--environment <env>` (default `dev`), `--env-file <path>` | Run a skill script LOCALLY with crew variables fetched from the platform (dev loop). Secret values need a token with `env:reveal`; see `skill exec` for the remote/deployed counterpart |
154
- | `skill exec <name> -- <command...>` | `--role <name>`, `--in-crew <crew>`, `--environment <env>` (default `production`) | Run a command against the DEPLOYED skill in its real sandbox runtime (post-push smoke); see `skill run` for the local dev-loop counterpart |
155
-
156
- For `skill run` / `skill exec`, pass the command as separate words after `--` (e.g. `-- python script.py --flag`); to run a single preformed shell string, wrap it explicitly with `sh -c '...'`.
153
+ | `skill exec <name> --target sandbox -- <cmd>` (`--target` required) | `--role <name>`, `--in-crew <crew>`, `--environment <env>` (default `production`) | Execute the server-stored skill in its server sandbox (post-push smoke; default env production) |
154
+ | `skill exec <name> --target host -- <cmd>` (`--target` required) | `--role <name>`, `--in-crew <crew>`, `--crew <nameOrId>`, `--environment <env>` (default `production`), `--env-file <path>` | Execute the server-stored skill on THIS machine via a transparent revision-checked cache — no pull step; crew vars fetched from the platform (default env production; secrets need `env:reveal`) |
155
+ | `skill dev <dir> -- <cmd>` | `--crew <nameOrId>`, `--environment <env>` (default `dev`), `--env-file <path>` | Run your local working copy (the folder you're editing) with platform crew vars (default env dev). Replaces `skill run` (deprecated) |
156
+
157
+ `skill exec` always executes the **server-stored** skill — `--target` only picks
158
+ where it runs (`sandbox` = server, `host` = your machine, cached under
159
+ `~/.solidactions/cache/skills/`, refreshed automatically when the skill's
160
+ published revision changes). `skill dev` always runs the **folder you're
161
+ editing**. Passing a directory to `exec` or a bare name to `dev` is an error
162
+ that points at the right command. Both `exec` targets default to `production`
163
+ variables; `dev` defaults to `dev`.
164
+
165
+ For `skill dev` / `skill exec`, pass the command as separate words after `--` (e.g. `-- python script.py --flag`); to run a single preformed shell string, wrap it explicitly with `sh -c '...'`.
157
166
 
158
167
  ### role
159
168
 
@@ -3,23 +3,25 @@ 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.formatValue = formatValue;
6
7
  exports.crewEnvList = crewEnvList;
7
8
  const axios_1 = __importDefault(require("axios"));
8
9
  const chalk_1 = __importDefault(require("chalk"));
9
10
  const api_1 = require("../utils/api");
10
11
  const crew_1 = require("../utils/crew");
11
12
  /**
12
- * Format a value for display. Secrets are ALWAYS masked with a fixed
13
- * placeholder — regardless of what the server sent — so a server-side
14
- * masking bug can never leak a raw secret into stdout.
13
+ * Format a value for display. A null/undefined value means the env is
14
+ * unset and always renders as '-'. Otherwise, a secret's value is ALWAYS
15
+ * masked with a fixed placeholder — regardless of what the server sent —
16
+ * so a server-side masking bug can never leak a raw secret into stdout.
15
17
  */
16
18
  function formatValue(value, isSecret) {
17
- if (isSecret) {
18
- return chalk_1.default.yellow('••••••');
19
- }
20
19
  if (value === null || value === undefined) {
21
20
  return chalk_1.default.gray('-');
22
21
  }
22
+ if (isSecret) {
23
+ return chalk_1.default.yellow('••••••');
24
+ }
23
25
  return value.substring(0, 18);
24
26
  }
25
27
  async function crewEnvList(crewArg, options = {}) {
@@ -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);
@@ -20,9 +20,9 @@ exports.skillPull = skillPull;
20
20
  const fs_1 = __importDefault(require("fs"));
21
21
  const path_1 = __importDefault(require("path"));
22
22
  const chalk_1 = __importDefault(require("chalk"));
23
- const js_yaml_1 = __importDefault(require("js-yaml"));
24
23
  const api_1 = require("../utils/api");
25
24
  const mcp_1 = require("../utils/mcp");
25
+ const skill_bundle_1 = require("../utils/skill-bundle");
26
26
  /** Filename of the provenance sidecar written alongside a pulled skill. */
27
27
  exports.SKILL_SIDECAR = '.solidactions-skill.json';
28
28
  /**
@@ -69,19 +69,7 @@ async function skillPullWithConfig(name, dest, options, config) {
69
69
  // The server stores a `type` field but it is stripped on push (parseSkillFile
70
70
  // does `const { type: _type, ...properties } = rest`). We mirror that here
71
71
  // so that pull → push is idempotent.
72
- const { type: _type, name: propName, description: propDescription, ...extraProps } = data.properties;
73
- // Reconstruct the full frontmatter: name + description (from properties)
74
- // followed by all remaining extra props (minus type).
75
- const frontmatterObj = {
76
- name: propName,
77
- description: propDescription,
78
- ...extraProps,
79
- };
80
- // yaml.dump produces "key: value\n" lines; we wrap in ---\n...\n---\n
81
- const yamlBlock = js_yaml_1.default.dump(frontmatterObj, { lineWidth: -1 });
82
- const body = data.body ?? '';
83
- // Ensure the body starts on its own line after the closing ---
84
- const skillMdContent = `---\n${yamlBlock}---\n${body.startsWith('\n') ? body : '\n' + body}`;
72
+ const skillMdContent = (0, skill_bundle_1.reconstructSkillMd)(data.properties, data.body);
85
73
  // Create the output directory (and parents) if needed
86
74
  fs_1.default.mkdirSync(absOut, { recursive: true });
87
75
  // Write SKILL.md
@@ -102,7 +102,7 @@ function parseSkillFile(content) {
102
102
  * SKILL.md cites them, so bundled reference docs land complete (#247).
103
103
  *
104
104
  * Also excludes `skill pull`'s provenance sidecar (SKILL_SIDECAR) and
105
- * `skill run`'s local runtime-state dir (.sa-state/) — neither is skill
105
+ * `skill dev`'s local runtime-state dir (.sa-state/) — neither is skill
106
106
  * content, and uploading them would leak local revision bookkeeping / state
107
107
  * into the remote library and agent sandboxes.
108
108
  */
@@ -113,7 +113,7 @@ function readReferences(dir) {
113
113
  const abs = path_1.default.join(current, entry.name);
114
114
  if (entry.isDirectory()) {
115
115
  if (entry.name === '.sa-state')
116
- continue; // skill run's local runtime-state dir
116
+ continue; // skill dev's local runtime-state dir
117
117
  walk(abs);
118
118
  continue;
119
119
  }
@@ -6,10 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.shellQuoteArg = shellQuoteArg;
7
7
  exports.parseEnvFile = parseEnvFile;
8
8
  exports.assembleEnv = assembleEnv;
9
+ exports.execLocally = execLocally;
9
10
  exports.skillRunWithConfig = skillRunWithConfig;
10
11
  exports.skillRun = skillRun;
11
12
  /**
12
- * solidactions skill run <dir> [--crew <c>] [--environment <env>] [--env-file <f>] -- <command...>
13
+ * solidactions skill dev <dir> [--crew <c>] [--environment <env>] [--env-file <f>] -- <command...>
13
14
  *
14
15
  * Local analogue of the crews MCP exec_skill: runs <command> with cwd=<dir>
15
16
  * (matching the sandbox's cwd=/work/skills/<slug>), with crew variables
@@ -106,14 +107,47 @@ function readStorageScope(dir) {
106
107
  const scope = fm?.storage?.scope ?? fm?.['storage.scope'] ?? null;
107
108
  return scope === 'crew' || scope === 'workspace' ? scope : null;
108
109
  }
110
+ /**
111
+ * Shared local runner: env assembly + provenance banner + spawn. Used by both
112
+ * `skill dev` (working copy) and `skill exec --target host` (cached artifact).
113
+ */
114
+ function execLocally(args) {
115
+ const fileVars = args.envFile ? parseEnvFile(fs_1.default.readFileSync(path_1.default.resolve(args.envFile), 'utf8')) : {};
116
+ const storageScope = readStorageScope(args.dir);
117
+ const { env, warnings } = assembleEnv({
118
+ resolved: args.resolved, fileVars, storageScope, dir: args.dir, config: args.config,
119
+ });
120
+ for (const w of warnings)
121
+ process.stderr.write(chalk_1.default.yellow(`warn: ${w}\n`));
122
+ if (env.SOLIDACTIONS_STATE_DIR)
123
+ fs_1.default.mkdirSync(env.SOLIDACTIONS_STATE_DIR, { recursive: true });
124
+ if (env.SOLIDACTIONS_SHARED_DIR)
125
+ fs_1.default.mkdirSync(env.SOLIDACTIONS_SHARED_DIR, { recursive: true });
126
+ process.stderr.write(chalk_1.default.blue(`${args.banner}\n`));
127
+ if (args.skippedSecrets.length > 0) {
128
+ process.stderr.write(chalk_1.default.yellow(`${args.skippedSecrets.length} secret ${args.skippedSecrets.length === 1 ? 'var' : 'vars'} unavailable (${args.skippedSecrets.join(', ')}): ` +
129
+ `your API key lacks the 'env:reveal' ability. Mint a key with env:reveal, set a dev value with \`solidactions crew env set\`, or use --env-file.\n`));
130
+ }
131
+ const result = (0, child_process_1.spawnSync)(args.commandParts.map(shellQuoteArg).join(' '), {
132
+ shell: true,
133
+ cwd: args.dir,
134
+ stdio: 'inherit',
135
+ env: { ...process.env, ...env },
136
+ });
137
+ process.exit(result.status ?? 1);
138
+ }
109
139
  async function skillRunWithConfig(dir, commandParts, options, config) {
110
140
  const absDir = path_1.default.resolve(dir);
141
+ if (!fs_1.default.existsSync(absDir) || !fs_1.default.statSync(absDir).isDirectory()) {
142
+ process.stderr.write(chalk_1.default.red(`error: '${dir}' is not a directory — skill dev runs a local working folder. To execute the stored skill locally: skill exec ${dir} --target host\n`));
143
+ process.exit(1);
144
+ }
111
145
  if (!fs_1.default.existsSync(path_1.default.join(absDir, 'SKILL.md'))) {
112
146
  process.stderr.write(chalk_1.default.red(`error: ${dir} does not contain a SKILL.md\n`));
113
147
  process.exit(1);
114
148
  }
115
149
  if (commandParts.length === 0) {
116
- process.stderr.write(chalk_1.default.red('error: no command given — usage: skill run <dir> -- <command...>\n'));
150
+ process.stderr.write(chalk_1.default.red('error: no command given — usage: skill dev <dir> -- <command...>\n'));
117
151
  process.exit(1);
118
152
  }
119
153
  const environment = options.environment ?? 'dev';
@@ -135,28 +169,17 @@ async function skillRunWithConfig(dir, commandParts, options, config) {
135
169
  else {
136
170
  process.stderr.write(chalk_1.default.gray('no --crew given — running without crew variables (shared-skill parity)\n'));
137
171
  }
138
- const fileVars = options.envFile ? parseEnvFile(fs_1.default.readFileSync(path_1.default.resolve(options.envFile), 'utf8')) : {};
139
- const storageScope = readStorageScope(absDir);
140
- const { env, warnings } = assembleEnv({ resolved, fileVars, storageScope, dir: absDir, config });
141
- for (const w of warnings)
142
- process.stderr.write(chalk_1.default.yellow(`warn: ${w}\n`));
143
- if (env.SOLIDACTIONS_STATE_DIR)
144
- fs_1.default.mkdirSync(env.SOLIDACTIONS_STATE_DIR, { recursive: true });
145
- if (env.SOLIDACTIONS_SHARED_DIR)
146
- fs_1.default.mkdirSync(env.SOLIDACTIONS_SHARED_DIR, { recursive: true });
147
172
  const plainCount = Object.keys(resolved).length;
148
- process.stderr.write(chalk_1.default.blue(`running locally in ${dir} — env '${environment}', ${plainCount} crew vars loaded\n`));
149
- if (skippedSecrets.length > 0) {
150
- process.stderr.write(chalk_1.default.yellow(`${skippedSecrets.length} secret ${skippedSecrets.length === 1 ? 'var' : 'vars'} unavailable (${skippedSecrets.join(', ')}): ` +
151
- `your API key lacks the 'env:reveal' ability. Mint a key with env:reveal, set a dev value with \`solidactions crew env set\`, or use --env-file.\n`));
152
- }
153
- const result = (0, child_process_1.spawnSync)(commandParts.map(shellQuoteArg).join(' '), {
154
- shell: true,
155
- cwd: absDir,
156
- stdio: 'inherit',
157
- env: { ...process.env, ...env },
173
+ execLocally({
174
+ dir: absDir,
175
+ commandParts,
176
+ environment,
177
+ resolved,
178
+ skippedSecrets,
179
+ envFile: options.envFile,
180
+ config,
181
+ banner: `▶ working copy ${dir} → local (${environment}) — ${plainCount} crew vars`,
158
182
  });
159
- process.exit(result.status ?? 1);
160
183
  }
161
184
  async function skillRun(dir, commandParts, options) {
162
185
  const config = await (0, api_1.requireConfigWithWorkspace)();
package/dist/index.js CHANGED
@@ -41,7 +41,7 @@ const skill_pull_1 = require("./commands/skill-pull");
41
41
  const skill_list_1 = require("./commands/skill-list");
42
42
  const skill_view_1 = require("./commands/skill-view");
43
43
  const skill_delete_1 = require("./commands/skill-delete");
44
- const skill_run_1 = require("./commands/skill-run");
44
+ const skill_dev_1 = require("./commands/skill-dev");
45
45
  const skill_exec_1 = require("./commands/skill-exec");
46
46
  const role_push_1 = require("./commands/role-push");
47
47
  const docs_push_1 = require("./commands/docs-push");
@@ -557,24 +557,39 @@ skill
557
557
  await (0, skill_delete_1.skillDelete)(name, options);
558
558
  });
559
559
  skill
560
- .command('run')
561
- .description('Run a skill script LOCALLY with crew variables fetched from the platform (dev loop; default env dev; secrets need env:reveal; see `skill exec` for the remote/deployed counterpart, default env production)')
560
+ .command('dev')
561
+ .description('Run YOUR WORKING COPY of a skill locally with crew variables fetched from the platform (dev loop; default env dev; secrets need env:reveal). To execute the server-stored skill instead: skill exec <name> --target sandbox|host')
562
562
  .argument('<dir>', 'Local skill directory (must contain SKILL.md)')
563
563
  .argument('<command...>', 'Command to run (after --), e.g. -- node scripts/q.js')
564
564
  .option('--crew <nameOrId>', 'Crew whose variables to fetch (omit for shared skills)')
565
565
  .option('--environment <env>', 'Variable environment: production|staging|dev', 'dev')
566
566
  .option('--env-file <path>', 'Local KEY=VALUE overrides (reserved names ignored)')
567
567
  .action(async (dir, commandParts, options) => {
568
- await (0, skill_run_1.skillRun)(dir, commandParts, options);
568
+ await (0, skill_dev_1.skillDev)(dir, commandParts, options);
569
+ });
570
+ skill
571
+ .command('run', { hidden: true })
572
+ .description('[deprecated] alias of `skill dev` — removed in v2.0.0')
573
+ .argument('<dir>', 'Local skill directory (must contain SKILL.md)')
574
+ .argument('<command...>', 'Command to run (after --)')
575
+ .option('--crew <nameOrId>', 'Crew whose variables to fetch (omit for shared skills)')
576
+ .option('--environment <env>', 'Variable environment: production|staging|dev', 'dev')
577
+ .option('--env-file <path>', 'Local KEY=VALUE overrides (reserved names ignored)')
578
+ .action(async (dir, commandParts, options) => {
579
+ process.stderr.write(chalk_1.default.yellow("warn: 'skill run' is deprecated — use 'skill dev' (alias removed in v2.0.0)\n"));
580
+ await (0, skill_dev_1.skillDev)(dir, commandParts, options);
569
581
  });
570
582
  skill
571
583
  .command('exec')
572
- .description('Run a command against the DEPLOYED skill in its real sandbox runtime (post-push smoke; default env production; see `skill run` for the local dev-loop counterpart, default env dev)')
573
- .argument('<name>', 'Skill name or identifier')
574
- .argument('<command...>', 'Command to run remotely (after --), e.g. -- node scripts/q.js')
575
- .option('--role <name>', 'Role-scoped skill (uses roles.exec_skill)')
584
+ .description('Execute the SERVER-STORED skill (never local edits — see `skill dev`). --target picks where: sandbox (server) or host (this machine, transparent cache). Default env production for both targets; secrets on host need env:reveal')
585
+ .argument('<name>', 'Skill name or identifier (names only — directories are rejected)')
586
+ .argument('<command...>', 'Command to run (after --), e.g. -- node scripts/q.js')
587
+ .requiredOption('--target <target>', "Where to execute: 'sandbox' or 'host'")
588
+ .option('--role <name>', 'Role-scoped skill (crew inferred from the role)')
576
589
  .option('--in-crew <crew>', 'Disambiguate when the role name exists in multiple crews')
577
- .option('--environment <env>', 'Sandbox environment: production|staging|dev (default production)')
590
+ .option('--crew <nameOrId>', 'host+shared only: crew whose variables to fetch')
591
+ .option('--environment <env>', 'Variable environment: production|staging|dev (default production)')
592
+ .option('--env-file <path>', 'host only: local KEY=VALUE overrides (reserved names ignored)')
578
593
  .action(async (name, commandParts, options) => {
579
594
  await (0, skill_exec_1.skillExec)(name, commandParts, options);
580
595
  });
@@ -10,9 +10,12 @@ exports.isNumericCrewArg = isNumericCrewArg;
10
10
  exports.matchCrewByName = matchCrewByName;
11
11
  exports.fetchCrews = fetchCrews;
12
12
  exports.resolveCrewId = resolveCrewId;
13
+ exports.resolveRoleCrewPath = resolveRoleCrewPath;
14
+ exports.crewIdForPath = crewIdForPath;
13
15
  const axios_1 = __importDefault(require("axios"));
14
16
  const chalk_1 = __importDefault(require("chalk"));
15
17
  const api_1 = require("./api");
18
+ const mcp_1 = require("./mcp");
16
19
  exports.CREW_ENV_VALUES = ['production', 'staging', 'dev', 'all'];
17
20
  function isValidCrewEnv(value) {
18
21
  return exports.CREW_ENV_VALUES.includes(value);
@@ -70,3 +73,48 @@ async function resolveCrewId(config, input) {
70
73
  }
71
74
  return result.crew;
72
75
  }
76
+ /**
77
+ * Resolve the containment crew path for a role-scoped skill. --in-crew names it
78
+ * directly; otherwise roles.list is consulted (each entry carries in_crew).
79
+ * roles.read_skill does NOT return the crew, so this lookup is load-bearing for
80
+ * both variable resolution and cache scoping.
81
+ */
82
+ async function resolveRoleCrewPath(config, role, inCrew) {
83
+ if (inCrew)
84
+ return inCrew;
85
+ const result = await (0, mcp_1.callCrewsTool)(config, 'roles', { action: 'list' });
86
+ if (!result.ok) {
87
+ console.error(chalk_1.default.red(`Failed to list roles: ${result.data?.message ?? 'unknown error'}`));
88
+ process.exit(1);
89
+ }
90
+ const roles = result.data?.roles ?? [];
91
+ const matches = roles.filter((r) => r.identifier === role);
92
+ if (matches.length === 0) {
93
+ console.error(chalk_1.default.red(`Role "${role}" not found.`));
94
+ process.exit(1);
95
+ }
96
+ if (matches.length > 1) {
97
+ console.error(chalk_1.default.red(`Role "${role}" exists in multiple crews — pass --in-crew <crew>:`));
98
+ for (const m of matches)
99
+ console.error(chalk_1.default.gray(` --in-crew ${m.in_crew ?? '(legacy flat role)'}`));
100
+ process.exit(1);
101
+ }
102
+ if (!matches[0].in_crew) {
103
+ console.error(chalk_1.default.red(`Role "${role}" is a legacy flat role with no crew — crew variables cannot be resolved.`));
104
+ process.exit(1);
105
+ }
106
+ return matches[0].in_crew;
107
+ }
108
+ /** Map a containment crew path (e.g. "acme/marketing") to the crew doc id used by /variables/resolve. */
109
+ async function crewIdForPath(config, crewPath) {
110
+ const crews = await fetchCrews(config);
111
+ const byPath = crews.filter((c) => c.path === crewPath);
112
+ if (byPath.length === 1)
113
+ return byPath[0].id;
114
+ const lastSegment = crewPath.split('/').pop() ?? crewPath;
115
+ const byName = crews.filter((c) => c.name.toLowerCase() === lastSegment.toLowerCase());
116
+ if (byName.length === 1)
117
+ return byName[0].id;
118
+ 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
+ process.exit(1);
120
+ }
package/dist/utils/mcp.js CHANGED
@@ -42,6 +42,7 @@ var __importStar = (this && this.__importStar) || (function () {
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
43
  exports.callCrewsTool = callCrewsTool;
44
44
  exports.callDocsTool = callDocsTool;
45
+ exports.callCrewsToolContent = callCrewsToolContent;
45
46
  const http = __importStar(require("http"));
46
47
  const https = __importStar(require("https"));
47
48
  const url_1 = require("url");
@@ -49,14 +50,9 @@ const api_1 = require("./api");
49
50
  // eslint-disable-next-line @typescript-eslint/no-var-requires
50
51
  const pkg = require('../../package.json');
51
52
  const CLI_VERSION = pkg.version;
52
- /**
53
- * Internal: call a single MCP tool on the given endpoint path.
54
- *
55
- * Returns { ok: true, data: <success shape> } or { ok: false, data: { code, message } }.
56
- */
57
- async function callMcpTool(config, endpointPath, toolName, args) {
53
+ /** Internal: POST one tools/call and return the raw result envelope (isError + content blocks). */
54
+ async function postMcpTool(config, endpointPath, toolName, args) {
58
55
  const baseHeaders = (0, api_1.getApiHeaders)(config, 'application/json');
59
- // Override Accept to include text/event-stream for streamable-HTTP transport
60
56
  const headers = {
61
57
  ...baseHeaders,
62
58
  'Accept': 'application/json, text/event-stream',
@@ -65,10 +61,7 @@ async function callMcpTool(config, endpointPath, toolName, args) {
65
61
  jsonrpc: '2.0',
66
62
  id: 1,
67
63
  method: 'tools/call',
68
- params: {
69
- name: toolName,
70
- arguments: args,
71
- },
64
+ params: { name: toolName, arguments: args },
72
65
  });
73
66
  const parsed = new url_1.URL(`${config.host}${endpointPath}`);
74
67
  const isHttps = parsed.protocol === 'https:';
@@ -79,10 +72,7 @@ async function callMcpTool(config, endpointPath, toolName, args) {
79
72
  port: parsed.port || (isHttps ? 443 : 80),
80
73
  path: parsed.pathname + (parsed.search || ''),
81
74
  method: 'POST',
82
- headers: {
83
- ...headers,
84
- 'Content-Length': Buffer.byteLength(body),
85
- },
75
+ headers: { ...headers, 'Content-Length': Buffer.byteLength(body) },
86
76
  };
87
77
  const req = transport.request(options, (res) => {
88
78
  let raw = '';
@@ -111,8 +101,16 @@ async function callMcpTool(config, endpointPath, toolName, args) {
111
101
  throw new Error(`MCP server returned non-JSON response: ${responseData}`);
112
102
  }
113
103
  const result = parsed2?.result;
114
- const isError = result?.isError === true;
115
- const textContent = result?.content?.[0]?.text ?? '{}';
104
+ return { isError: result?.isError === true, content: result?.content ?? [] };
105
+ }
106
+ /**
107
+ * Internal: call a single MCP tool and JSON-parse its first text content block.
108
+ *
109
+ * Returns { ok: true, data: <success shape> } or { ok: false, data: { code, message } }.
110
+ */
111
+ async function callMcpTool(config, endpointPath, toolName, args) {
112
+ const raw = await postMcpTool(config, endpointPath, toolName, args);
113
+ const textContent = raw.content?.[0]?.text ?? '{}';
116
114
  let toolData;
117
115
  try {
118
116
  toolData = JSON.parse(textContent);
@@ -120,7 +118,7 @@ async function callMcpTool(config, endpointPath, toolName, args) {
120
118
  catch {
121
119
  throw new Error(`MCP tool result content is not valid JSON: ${textContent}`);
122
120
  }
123
- return { ok: !isError, data: toolData };
121
+ return { ok: !raw.isError, data: toolData };
124
122
  }
125
123
  const UNIFIED_MCP_PATH = '/mcp';
126
124
  // Server consolidated per-domain MCP servers into one endpoint with namespaced tools.
@@ -138,3 +136,13 @@ async function callCrewsTool(config, toolName, args) {
138
136
  async function callDocsTool(config, toolName, args) {
139
137
  return callMcpTool(config, UNIFIED_MCP_PATH, toolName, args);
140
138
  }
139
+ /**
140
+ * Call a crews MCP tool and return the RAW content blocks. Needed for
141
+ * read_reference_file, whose success responses can be an MCP image block
142
+ * (base64 bytes) rather than a JSON text block — JSON-parsing content[0].text
143
+ * (callCrewsTool) would throw on those.
144
+ */
145
+ async function callCrewsToolContent(config, toolName, args) {
146
+ const raw = await postMcpTool(config, UNIFIED_MCP_PATH, CREWS_TOOL_NAMES[toolName] ?? toolName, args);
147
+ return { ok: !raw.isError, content: raw.content };
148
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.reconstructSkillMd = reconstructSkillMd;
7
+ exports.normalizeBundle = normalizeBundle;
8
+ exports.fetchBinaryReference = fetchBinaryReference;
9
+ /**
10
+ * Normalization of a skills.read / roles.read_skill bundle into the pieces the
11
+ * host-cache needs, plus binary reference fetching.
12
+ *
13
+ * Binary reference values arrive as {binary, mime, size, blob_sha} metadata —
14
+ * bytes come from a separate read_reference_file call which returns EITHER a
15
+ * JSON text block {signed_url,...} (non-image or large) OR an MCP image block
16
+ * (base64) for small images. fetchBinaryReference handles both.
17
+ */
18
+ const axios_1 = __importDefault(require("axios"));
19
+ const path_1 = __importDefault(require("path"));
20
+ const js_yaml_1 = __importDefault(require("js-yaml"));
21
+ const mcp_1 = require("./mcp");
22
+ const skill_cache_1 = require("./skill-cache");
23
+ const skill_cache_fs_1 = require("./skill-cache-fs");
24
+ function reconstructSkillMd(properties, body) {
25
+ const { type: _type, name: propName, description: propDescription, ...extraProps } = properties;
26
+ const frontmatterObj = {
27
+ name: propName,
28
+ description: propDescription,
29
+ ...extraProps,
30
+ };
31
+ const yamlBlock = js_yaml_1.default.dump(frontmatterObj, { lineWidth: -1 });
32
+ const bodyText = body ?? '';
33
+ return `---\n${yamlBlock}---\n${bodyText.startsWith('\n') ? bodyText : '\n' + bodyText}`;
34
+ }
35
+ function readStorageScopeProp(properties) {
36
+ const nested = properties.storage?.scope;
37
+ const flat = properties['storage.scope'];
38
+ const scope = nested ?? flat ?? null;
39
+ return scope === 'crew' || scope === 'workspace' ? scope : null;
40
+ }
41
+ /** True when a reference key would escape the cache dir (same guards as skill pull). */
42
+ function isUnsafeReferenceKey(key) {
43
+ if (path_1.default.isAbsolute(key))
44
+ return true;
45
+ const root = path_1.default.resolve('/probe-root');
46
+ return !path_1.default.resolve(root, key).startsWith(root + path_1.default.sep);
47
+ }
48
+ function normalizeBundle(data) {
49
+ const properties = (data.properties ?? {});
50
+ const textFiles = {};
51
+ const binaryFiles = {};
52
+ const skippedUnsafe = [];
53
+ for (const [key, value] of Object.entries((data.reference ?? {}))) {
54
+ if (isUnsafeReferenceKey(key)) {
55
+ skippedUnsafe.push(key);
56
+ continue;
57
+ }
58
+ if (typeof value === 'string') {
59
+ textFiles[key] = value;
60
+ }
61
+ else if (value && typeof value === 'object' && value.binary === true) {
62
+ const v = value;
63
+ binaryFiles[key] = { blobSha: v.blob_sha, mime: v.mime, size: v.size };
64
+ }
65
+ // else: unreachable — the server wire contract has exactly two reference
66
+ // shapes, string | {binary:true,...} (see ResolvedReference::toWireValue).
67
+ }
68
+ return {
69
+ identifier: data.identifier,
70
+ properties,
71
+ skillMd: reconstructSkillMd(properties, data.body),
72
+ textFiles,
73
+ binaryFiles,
74
+ identity: (0, skill_cache_1.artifactIdentity)(data),
75
+ storageScope: readStorageScopeProp(properties),
76
+ skippedUnsafe,
77
+ };
78
+ }
79
+ async function fetchBinaryReference(config, tool, locator, refPath, expected) {
80
+ const result = await (0, mcp_1.callCrewsToolContent)(config, tool, {
81
+ action: 'read_reference_file',
82
+ ...locator,
83
+ path: refPath,
84
+ });
85
+ if (!result.ok) {
86
+ const text = result.content?.[0]?.text ?? '';
87
+ throw new Error(`failed to fetch binary reference '${refPath}': ${text}`);
88
+ }
89
+ let bytes = null;
90
+ for (const block of result.content) {
91
+ if (block?.type === 'image' && typeof block.data === 'string') {
92
+ bytes = Buffer.from(block.data, 'base64');
93
+ break;
94
+ }
95
+ if (block?.type === 'text' && typeof block.text === 'string') {
96
+ let parsed;
97
+ try {
98
+ parsed = JSON.parse(block.text);
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ if (parsed?.signed_url) {
104
+ const response = await axios_1.default.get(parsed.signed_url, { responseType: 'arraybuffer' });
105
+ bytes = Buffer.from(response.data);
106
+ break;
107
+ }
108
+ }
109
+ }
110
+ if (bytes === null) {
111
+ throw new Error(`failed to fetch binary reference '${refPath}': unrecognized response shape`);
112
+ }
113
+ if (bytes.length !== expected.size) {
114
+ throw new Error(`binary reference '${refPath}' failed validation (got ${bytes.length} bytes, expected ${expected.size}) — refusing to cache a corrupt download`);
115
+ }
116
+ if (/^[0-9a-f]{64}$/.test(expected.blobSha)) {
117
+ const actualHash = (0, skill_cache_fs_1.sha256Hex)(bytes);
118
+ if (actualHash !== expected.blobSha) {
119
+ throw new Error(`binary reference '${refPath}' failed validation (sha256 mismatch: got ${actualHash}, expected ${expected.blobSha}) — refusing to cache a corrupt download`);
120
+ }
121
+ }
122
+ return bytes;
123
+ }
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.sha256Hex = sha256Hex;
7
+ exports.hashFileOrNull = hashFileOrNull;
8
+ exports.readManifest = readManifest;
9
+ exports.onDiskHashes = onDiskHashes;
10
+ exports.writeFileAtomic = writeFileAtomic;
11
+ exports.applyCachePlan = applyCachePlan;
12
+ exports.withCacheLock = withCacheLock;
13
+ /**
14
+ * Filesystem side of the host skill cache: hashing, atomic writes, the
15
+ * per-cache-key lock, and plan application. Kept separate from the pure
16
+ * planner (skill-cache.ts) so planning stays unit-testable without fs.
17
+ *
18
+ * Write protocol: every managed file is written via temp-file + rename in the
19
+ * same directory (atomic on POSIX); the manifest is written LAST, so a crash
20
+ * mid-refresh leaves a manifest that simply mismatches on the next run and
21
+ * triggers a clean re-refresh. Per-file renames also mean a concurrently
22
+ * RUNNING exec keeps its already-open scripts.
23
+ *
24
+ * Lock ownership: the lock dir carries an `owner` token file written right
25
+ * after `mkdirSync` succeeds. A stale-lock takeover removes the whole dir
26
+ * (token included) before re-acquiring, and release only removes the lock
27
+ * dir when its `owner` file still matches our token — so a holder that ran
28
+ * past the staleness window and had its lock stolen can't rm the new
29
+ * holder's lock out from under it. If a concurrent stale-takeover `rmSync`
30
+ * lands between our `mkdirSync` and the `owner` write, that write sees
31
+ * ENOENT — treated as having lost the race, so acquisition retries.
32
+ */
33
+ const crypto_1 = __importDefault(require("crypto"));
34
+ const fs_1 = __importDefault(require("fs"));
35
+ const path_1 = __importDefault(require("path"));
36
+ const skill_cache_1 = require("./skill-cache");
37
+ function sha256Hex(data) {
38
+ return crypto_1.default.createHash('sha256').update(data).digest('hex');
39
+ }
40
+ function hashFileOrNull(filePath) {
41
+ try {
42
+ return sha256Hex(fs_1.default.readFileSync(filePath));
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ function readManifest(cacheDir) {
49
+ try {
50
+ const parsed = JSON.parse(fs_1.default.readFileSync(path_1.default.join(cacheDir, skill_cache_1.CACHE_MANIFEST), 'utf8'));
51
+ if (parsed?.schema_version !== 1 || typeof parsed?.files !== 'object' || parsed.files === null || Array.isArray(parsed.files))
52
+ return null;
53
+ return parsed;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ function onDiskHashes(cacheDir, paths) {
60
+ const out = {};
61
+ for (const p of paths) {
62
+ out[p] = hashFileOrNull(path_1.default.join(cacheDir, p));
63
+ }
64
+ return out;
65
+ }
66
+ function writeFileAtomic(target, data) {
67
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
68
+ const tmp = path_1.default.join(path_1.default.dirname(target), `.tmp-${process.pid}-${crypto_1.default.randomBytes(4).toString('hex')}`);
69
+ fs_1.default.writeFileSync(tmp, data);
70
+ fs_1.default.renameSync(tmp, target);
71
+ }
72
+ function applyCachePlan(cacheDir, plan, contents, manifest) {
73
+ fs_1.default.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
74
+ for (const rel of plan.writes) {
75
+ if (!(rel in contents)) {
76
+ throw new Error(`applyCachePlan: no content provided for planned write '${rel}'`);
77
+ }
78
+ writeFileAtomic(path_1.default.join(cacheDir, rel), contents[rel]);
79
+ }
80
+ for (const rel of plan.deletes) {
81
+ fs_1.default.rmSync(path_1.default.join(cacheDir, rel), { force: true });
82
+ }
83
+ writeFileAtomic(path_1.default.join(cacheDir, skill_cache_1.CACHE_MANIFEST), JSON.stringify(manifest, null, 2) + '\n');
84
+ }
85
+ const LOCK_STALE_MS = 120_000;
86
+ const LOCK_TIMEOUT_MS = 20_000;
87
+ const LOCK_POLL_MS = 100;
88
+ async function withCacheLock(cacheDir, fn) {
89
+ const lockDir = cacheDir + '.lock';
90
+ fs_1.default.mkdirSync(path_1.default.dirname(lockDir), { recursive: true });
91
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
92
+ const token = `${process.pid}-${crypto_1.default.randomBytes(8).toString('hex')}`;
93
+ for (;;) {
94
+ if (Date.now() > deadline) {
95
+ throw new Error(`timed out waiting for skill cache lock: ${lockDir} (another exec running? delete it if stale)`);
96
+ }
97
+ try {
98
+ fs_1.default.mkdirSync(lockDir);
99
+ fs_1.default.writeFileSync(path_1.default.join(lockDir, 'owner'), token);
100
+ break;
101
+ }
102
+ catch (e) {
103
+ if (e?.code !== 'EEXIST' && e?.code !== 'ENOENT')
104
+ throw e;
105
+ let stale = false;
106
+ try {
107
+ stale = Date.now() - fs_1.default.statSync(lockDir).mtimeMs > LOCK_STALE_MS;
108
+ }
109
+ catch {
110
+ continue; // holder just released — retry immediately
111
+ }
112
+ if (stale) {
113
+ try {
114
+ fs_1.default.rmSync(lockDir, { recursive: true, force: true });
115
+ }
116
+ catch { /* raced another taker */ }
117
+ continue;
118
+ }
119
+ await new Promise((r) => setTimeout(r, LOCK_POLL_MS));
120
+ }
121
+ }
122
+ try {
123
+ return await fn();
124
+ }
125
+ finally {
126
+ try {
127
+ if (fs_1.default.readFileSync(path_1.default.join(lockDir, 'owner'), 'utf8') === token) {
128
+ fs_1.default.rmSync(lockDir, { recursive: true, force: true });
129
+ }
130
+ }
131
+ catch { /* lock missing or owned by someone else — best-effort, do nothing */ }
132
+ }
133
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CACHE_MANIFEST = void 0;
7
+ exports.artifactIdentity = artifactIdentity;
8
+ exports.sanitizeSegment = sanitizeSegment;
9
+ exports.cacheOrigin = cacheOrigin;
10
+ exports.cacheDirFor = cacheDirFor;
11
+ exports.planCacheRefresh = planCacheRefresh;
12
+ /**
13
+ * Pure cache-planning core for `skill exec --target host`.
14
+ *
15
+ * The executed artifact is identified by {doc_id, published, execution_revision_id}:
16
+ * reads serve ACTIVE-SNAPSHOT content when published (head may be newer), so the
17
+ * execution revision is active_snapshot_revision_id when published and
18
+ * head_revision_id only for unpublished drafts. Comparing head alone would run
19
+ * stale cached content after a publish that promotes without moving head.
20
+ *
21
+ * planCacheRefresh() is deliberately pure (no fs, no network) so cache
22
+ * correctness — noop detection, per-file skip, upstream deletions, local
23
+ * drift — is unit-testable. The fs side lives in skill-cache-fs.ts.
24
+ */
25
+ const os_1 = __importDefault(require("os"));
26
+ const path_1 = __importDefault(require("path"));
27
+ const url_1 = require("url");
28
+ exports.CACHE_MANIFEST = '.sa-cache-manifest.json';
29
+ function toNum(v) {
30
+ if (v === null || v === undefined)
31
+ return null;
32
+ const n = typeof v === 'string' ? parseInt(v, 10) : v;
33
+ return Number.isNaN(n) ? null : n;
34
+ }
35
+ function artifactIdentity(bundle) {
36
+ const published = bundle.published !== false;
37
+ const executionRevisionId = published
38
+ // The `?? toNum(bundle.head_revision_id)` fallback guards a domain-unreachable
39
+ // state: a published doc without an active snapshot revision.
40
+ ? (toNum(bundle.active_snapshot_revision_id) ?? toNum(bundle.head_revision_id))
41
+ : toNum(bundle.head_revision_id);
42
+ return { docId: toNum(bundle.doc_id), published, executionRevisionId };
43
+ }
44
+ function sanitizeSegment(s) {
45
+ return s.replace(/[^a-zA-Z0-9._-]/g, '_');
46
+ }
47
+ /**
48
+ * Cache identity for "which server + which workspace": host authority (host:port)
49
+ * plus the canonical workspace id. NOT the workspace slug — Config distinguishes
50
+ * cosmetic `workspace` from canonical `workspaceId`, and custom hosts may collide
51
+ * on ids alone.
52
+ */
53
+ function cacheOrigin(config) {
54
+ const authority = new url_1.URL(config.host).host; // host[:port]
55
+ return `${sanitizeSegment(authority)}__${sanitizeSegment(config.workspaceId ?? 'default')}`;
56
+ }
57
+ function cacheDirFor(config, scope, skillName) {
58
+ const base = path_1.default.join(os_1.default.homedir(), '.solidactions', 'cache', 'skills', cacheOrigin(config));
59
+ const scopeSegs = scope.kind === 'shared'
60
+ ? ['shared']
61
+ : [sanitizeSegment(scope.crewPath), sanitizeSegment(scope.role)];
62
+ return path_1.default.join(base, ...scopeSegs, sanitizeSegment(skillName));
63
+ }
64
+ function planCacheRefresh(args) {
65
+ const { manifest, origin, identity, desired, onDisk } = args;
66
+ const mfiles = manifest?.files ?? {};
67
+ const identityOk = !!manifest
68
+ && manifest.schema_version === 1
69
+ && manifest.origin === origin
70
+ && manifest.doc_id === identity.docId
71
+ && manifest.published === identity.published
72
+ && manifest.execution_revision_id === identity.executionRevisionId;
73
+ const writes = [];
74
+ for (const [p, spec] of Object.entries(desired)) {
75
+ const m = mfiles[p];
76
+ const upstreamSame = !!m && (spec.kind === 'text' ? m.sha256 === spec.sha256 : m.blob_sha === spec.blobSha);
77
+ const diskSame = !!m && onDisk[p] !== null && onDisk[p] !== undefined && onDisk[p] === m.sha256;
78
+ if (!upstreamSame || !diskSame)
79
+ writes.push(p);
80
+ }
81
+ const deletes = Object.keys(mfiles).filter((p) => !(p in desired));
82
+ const action = !identityOk || writes.length > 0 || deletes.length > 0 ? 'refresh' : 'noop';
83
+ return { action, writes: action === 'noop' ? [] : writes, deletes: action === 'noop' ? [] : deletes };
84
+ }
@@ -16,6 +16,7 @@ const SKILL_NAMES = [
16
16
  'solidactions-workflow-coding',
17
17
  'solidactions-deploy-and-config',
18
18
  'solidactions-oauth-actions',
19
+ 'solidactions-crew-skills',
19
20
  ];
20
21
  const EXAMPLES_OWNER = 'SolidActions';
21
22
  const EXAMPLES_REPO = 'solidactions-examples';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "1.30.0",
3
+ "version": "1.31.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {