@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.
@@ -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
  });
@@ -623,8 +638,9 @@ docs
623
638
  .description('Upload one or more media files to SA-Docs (requires a token with the "docs" ability)')
624
639
  .option('--folder <path>', 'Folder path to upload into (auto-created if missing)')
625
640
  .option('--title <title>', 'Title for the uploaded doc (only valid with a single file)')
641
+ .option('--replace <doc-id-or-path>', 'replace the bytes of an existing media doc (by id, or by docs path)')
626
642
  .action(async (files, options) => {
627
- await (0, docs_upload_1.docsUpload)(files, { folder: options.folder, title: options.title });
643
+ await (0, docs_upload_1.docsUpload)(files, { folder: options.folder, title: options.title, replace: options.replace });
628
644
  });
629
645
  program.parseAsync().catch((err) => {
630
646
  console.error(chalk_1.default.red(err.message ?? String(err)));
@@ -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
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ /**
3
+ * Sidecar manifest (`.solidactions-docs.json`) shared by `docs pull` and
4
+ * `docs push` to track which local files correspond to which SA-Docs docs,
5
+ * and to detect local/server drift via a body sha256.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.DOCS_MANIFEST = void 0;
12
+ exports.sha256Hex = sha256Hex;
13
+ exports.readManifest = readManifest;
14
+ exports.writeManifest = writeManifest;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const crypto_1 = __importDefault(require("crypto"));
18
+ const chalk_1 = __importDefault(require("chalk"));
19
+ exports.DOCS_MANIFEST = '.solidactions-docs.json';
20
+ /** sha256 hex digest of the given bytes/string, as written to disk. */
21
+ function sha256Hex(data) {
22
+ return crypto_1.default.createHash('sha256').update(data).digest('hex');
23
+ }
24
+ /**
25
+ * Read `<dir>/.solidactions-docs.json`. Absent or unparseable → null,
26
+ * meaning nothing under `dir` is guarded (sidecar convention).
27
+ *
28
+ * `docs push` warns on unparseable JSON (files silently becoming untracked would
29
+ * re-create every doc); `docs pull` stays silent (it is about to rewrite it anyway).
30
+ */
31
+ function readManifest(dir, opts = {}) {
32
+ const manifestPath = path_1.default.join(dir, exports.DOCS_MANIFEST);
33
+ if (!fs_1.default.existsSync(manifestPath)) {
34
+ return null;
35
+ }
36
+ try {
37
+ return JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
38
+ }
39
+ catch {
40
+ if (opts.warnOnParseError) {
41
+ process.stderr.write(chalk_1.default.yellow(`warn: ${exports.DOCS_MANIFEST} exists but could not be parsed — all files will be treated as untracked\n`));
42
+ }
43
+ return null;
44
+ }
45
+ }
46
+ function writeManifest(dir, manifest) {
47
+ fs_1.default.writeFileSync(path_1.default.join(dir, exports.DOCS_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
48
+ }
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
+ }