@codemieai/cdk 0.1.665 → 0.1.667

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/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import ora from 'ora';
2
2
  import * as crypto from 'crypto';
3
+ import * as fs14 from 'fs';
4
+ import * as path14 from 'path';
3
5
  import { CodeMieClient, DataSourceType, SkillVisibility } from 'codemie-sdk';
4
- import * as fs12 from 'fs';
5
- import * as path from 'path';
6
- import * as yaml7 from 'yaml';
6
+ import * as yaml8 from 'yaml';
7
7
  import 'dotenv/config';
8
8
  import pLimit from 'p-limit';
9
9
  import * as readline from 'readline';
@@ -344,13 +344,116 @@ function calculateSkillConfigChecksum(skill) {
344
344
  const filtered = buildChecksumObject(skill, SKILL_EXCLUDED_FIELDS);
345
345
  return calculateChecksum(JSON.stringify(filtered));
346
346
  }
347
+ function calculateCompanionFilesChecksum(files) {
348
+ const sortedFiles = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
349
+ const companionFileHashes = {};
350
+ for (const file of sortedFiles) {
351
+ companionFileHashes[file.path] = calculateChecksum(file.content);
352
+ }
353
+ const aggregateEntries = sortedFiles.map((file) => ({
354
+ path: file.path,
355
+ mime_type: file.mime_type,
356
+ encoding: file.encoding,
357
+ size_bytes: file.size_bytes,
358
+ contentHash: companionFileHashes[file.path]
359
+ }));
360
+ const companionFilesChecksum = calculateChecksum(JSON.stringify(aggregateEntries));
361
+ return { companionFilesChecksum, companionFileHashes };
362
+ }
347
363
  var DATASOURCE_EXCLUDED_FIELDS, WORKFLOW_EXCLUDED_FIELDS, SKILL_EXCLUDED_FIELDS;
348
364
  var init_codemieConfigChecksums = __esm({
349
365
  "src/lib/codemieConfigChecksums.ts"() {
350
366
  init_checksumUtils();
351
367
  DATASOURCE_EXCLUDED_FIELDS = createExcludeSet(["force_reindex"]);
352
368
  WORKFLOW_EXCLUDED_FIELDS = createExcludeSet(["definition"]);
353
- SKILL_EXCLUDED_FIELDS = createExcludeSet(["file"]);
369
+ SKILL_EXCLUDED_FIELDS = createExcludeSet([
370
+ "file",
371
+ "source_dir",
372
+ "ignore_file",
373
+ "content",
374
+ "group"
375
+ ]);
376
+ }
377
+ });
378
+ function sanitizeFileName(name, maxLength = 255) {
379
+ const nameWithHyphens = name.replaceAll(/[/\\]/g, "-");
380
+ const sanitized = nameWithHyphens.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "").slice(0, maxLength);
381
+ if (!sanitized) {
382
+ throw new Error(`Sanitized filename is empty for input: "${name}"`);
383
+ }
384
+ return sanitized;
385
+ }
386
+ function skillFileBaseName(name) {
387
+ return sanitizeFileName(name);
388
+ }
389
+ function skillDirRelativePath(name) {
390
+ return `skills/${skillFileBaseName(name)}`;
391
+ }
392
+ function skillFlatFileRelativePath(name) {
393
+ return `skills/${skillFileBaseName(name)}.skill.md`;
394
+ }
395
+ function skillMarkdownRelativePath(name) {
396
+ return `${skillDirRelativePath(name)}/${SKILL_MD_FILENAME2}`;
397
+ }
398
+ function resolvePathWithinDirectory(baseDir, candidatePath) {
399
+ const resolvedBase = path14.resolve(baseDir);
400
+ const resolved = path14.resolve(resolvedBase, candidatePath);
401
+ if (!resolved.startsWith(resolvedBase + path14.sep)) {
402
+ throw new Error(`Refusing to write "${candidatePath}": it resolves to "${resolved}", outside "${resolvedBase}"`);
403
+ }
404
+ return resolved;
405
+ }
406
+ function validateBackupDirectory(backupDir, minSpaceGB = 1) {
407
+ try {
408
+ const parentDir = path14.dirname(backupDir);
409
+ if (!fs14.existsSync(parentDir)) {
410
+ fs14.mkdirSync(parentDir, { recursive: true });
411
+ }
412
+ const testFile = path14.join(parentDir, ".write-test");
413
+ fs14.writeFileSync(testFile, "test");
414
+ fs14.unlinkSync(testFile);
415
+ try {
416
+ const stats = fs14.statfsSync(parentDir);
417
+ const availableGB = stats.bavail * stats.bsize / BYTES_IN_GB;
418
+ if (availableGB < minSpaceGB) {
419
+ throw new Error(`Insufficient disk space: ${availableGB.toFixed(2)}GB available, need ${minSpaceGB}GB`);
420
+ }
421
+ } catch (error) {
422
+ if (error.code !== "ERR_METHOD_NOT_SUPPORTED") {
423
+ throw error;
424
+ }
425
+ }
426
+ } catch (error) {
427
+ throw new Error(`Cannot write to backup directory: ${error instanceof Error ? error.message : String(error)}`);
428
+ }
429
+ }
430
+ function moveAtomically(tempPath, finalPath) {
431
+ try {
432
+ fs14.renameSync(tempPath, finalPath);
433
+ } catch (error) {
434
+ const err = error;
435
+ if (err.code === "EEXIST") {
436
+ throw new Error(`Destination already exists: ${finalPath}`);
437
+ }
438
+ throw error;
439
+ }
440
+ }
441
+ function cleanupDirectory(dirPath) {
442
+ if (fs14.existsSync(dirPath)) {
443
+ fs14.rmSync(dirPath, { recursive: true, force: true });
444
+ }
445
+ }
446
+ function ensureDirectoryExists(filePath) {
447
+ const dir = path14.dirname(filePath);
448
+ if (!fs14.existsSync(dir)) {
449
+ fs14.mkdirSync(dir, { recursive: true });
450
+ }
451
+ }
452
+ var BYTES_IN_GB, SKILL_MD_FILENAME2;
453
+ var init_fileUtils = __esm({
454
+ "src/lib/fileUtils.ts"() {
455
+ BYTES_IN_GB = 1024 ** 3;
456
+ SKILL_MD_FILENAME2 = "SKILL.md";
354
457
  }
355
458
  });
356
459
 
@@ -573,11 +676,12 @@ function workflowResponseToResource(workflow) {
573
676
  };
574
677
  }
575
678
  function skillResponseToResource(skill) {
576
- const fileName = skill.name.toLowerCase().replaceAll(/\s+/g, "-");
577
679
  return {
578
680
  name: skill.name,
579
681
  description: skill.description || "",
580
- file: `skills/${fileName}.skill.md`,
682
+ // Derived from the one shared helper the backup and import writers use, so the path in the
683
+ // generated YAML is always the path that was actually written to disk.
684
+ file: skillFlatFileRelativePath(skill.name),
581
685
  ...skill.categories && skill.categories.length > 0 && { categories: skill.categories },
582
686
  ...skill.visibility && skill.visibility !== "project" && { visibility: skill.visibility }
583
687
  };
@@ -672,6 +776,7 @@ var CHUNK_SUMMARY_ALIASES, FILE_SUMMARY_ALIASES;
672
776
  var init_converters = __esm({
673
777
  "src/lib/converters.ts"() {
674
778
  init_checksumUtils();
779
+ init_fileUtils();
675
780
  init_logger();
676
781
  init_mcpSanitizer();
677
782
  init_typeGuards();
@@ -679,64 +784,232 @@ var init_converters = __esm({
679
784
  FILE_SUMMARY_ALIASES = /* @__PURE__ */ new Set(["file_summary", "file-summary", "file-summay"]);
680
785
  }
681
786
  });
682
- function sanitizeFileName(name, maxLength = 255) {
683
- const nameWithHyphens = name.replaceAll(/[/\\]/g, "-");
684
- const sanitized = nameWithHyphens.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "").slice(0, maxLength);
685
- if (!sanitized) {
686
- throw new Error(`Sanitized filename is empty for input: "${name}"`);
787
+ function hasCompanionFileLayout(skill) {
788
+ if (!skill.file) {
789
+ return false;
687
790
  }
688
- return sanitized;
791
+ return path14.basename(skill.file) === SKILL_MD_FILENAME3;
689
792
  }
690
- function validateBackupDirectory(backupDir, minSpaceGB = 1) {
691
- try {
692
- const parentDir = path.dirname(backupDir);
693
- if (!fs12.existsSync(parentDir)) {
694
- fs12.mkdirSync(parentDir, { recursive: true });
793
+ function findBalancedBraceIndices(pattern) {
794
+ const openIndices = [];
795
+ const balanced = /* @__PURE__ */ new Set();
796
+ for (let i = 0; i < pattern.length; i++) {
797
+ if (pattern[i] === "{") {
798
+ openIndices.push(i);
799
+ continue;
695
800
  }
696
- const testFile = path.join(parentDir, ".write-test");
697
- fs12.writeFileSync(testFile, "test");
698
- fs12.unlinkSync(testFile);
699
- try {
700
- const stats = fs12.statfsSync(parentDir);
701
- const availableGB = stats.bavail * stats.bsize / BYTES_IN_GB;
702
- if (availableGB < minSpaceGB) {
703
- throw new Error(`Insufficient disk space: ${availableGB.toFixed(2)}GB available, need ${minSpaceGB}GB`);
801
+ if (pattern[i] === "}") {
802
+ const openIndex = openIndices.pop();
803
+ if (openIndex !== void 0) {
804
+ balanced.add(openIndex);
805
+ balanced.add(i);
704
806
  }
705
- } catch (error) {
706
- if (error.code !== "ERR_METHOD_NOT_SUPPORTED") {
707
- throw error;
807
+ }
808
+ }
809
+ return balanced;
810
+ }
811
+ function hasUnbalancedBraces(pattern) {
812
+ const balanced = findBalancedBraceIndices(pattern);
813
+ for (let i = 0; i < pattern.length; i++) {
814
+ if ((pattern[i] === "{" || pattern[i] === "}") && !balanced.has(i)) {
815
+ return true;
816
+ }
817
+ }
818
+ return false;
819
+ }
820
+ function translatePatternToRegexSource(pattern) {
821
+ const balancedBraces = findBalancedBraceIndices(pattern);
822
+ let source = "";
823
+ let braceDepth = 0;
824
+ for (let i = 0; i < pattern.length; i++) {
825
+ const char = pattern[i];
826
+ if (char === "*" && pattern[i + 1] === "*") {
827
+ source += ".*";
828
+ i++;
829
+ continue;
830
+ }
831
+ if (char === "*") {
832
+ source += "[^/]*";
833
+ continue;
834
+ }
835
+ if (char === "?") {
836
+ source += "[^/]";
837
+ continue;
838
+ }
839
+ if (char === "{") {
840
+ if (!balancedBraces.has(i)) {
841
+ source += "\\{";
842
+ continue;
708
843
  }
844
+ braceDepth++;
845
+ source += "(?:";
846
+ continue;
709
847
  }
710
- } catch (error) {
711
- throw new Error(`Cannot write to backup directory: ${error instanceof Error ? error.message : String(error)}`);
848
+ if (char === "}") {
849
+ if (!balancedBraces.has(i)) {
850
+ source += "\\}";
851
+ continue;
852
+ }
853
+ braceDepth = Math.max(0, braceDepth - 1);
854
+ source += ")";
855
+ continue;
856
+ }
857
+ if (char === "," && braceDepth > 0) {
858
+ source += "|";
859
+ continue;
860
+ }
861
+ if (/[.+^$()|[\]\\]/.test(char)) {
862
+ source += `\\${char}`;
863
+ continue;
864
+ }
865
+ source += char;
712
866
  }
867
+ return source;
713
868
  }
714
- function moveAtomically(tempPath, finalPath) {
715
- try {
716
- fs12.renameSync(tempPath, finalPath);
717
- } catch (error) {
718
- const err = error;
719
- if (err.code === "EEXIST") {
720
- throw new Error(`Destination already exists: ${finalPath}`);
869
+ function matchesExcludePattern(relPath, pattern) {
870
+ const isDirectoryPrefix = pattern.endsWith("/");
871
+ const normalizedPattern = isDirectoryPrefix ? pattern.slice(0, -1) : pattern;
872
+ const source = translatePatternToRegexSource(normalizedPattern);
873
+ if (isDirectoryPrefix) {
874
+ const regex2 = new RegExp(`^${source}/.*$`);
875
+ return regex2.test(relPath);
876
+ }
877
+ if (normalizedPattern.includes("/")) {
878
+ const regex2 = new RegExp(`^${source}(?:/.*)?$`);
879
+ return regex2.test(relPath);
880
+ }
881
+ const regex = new RegExp(`^${source}$`);
882
+ const segments = relPath.split("/");
883
+ const basename2 = segments[segments.length - 1];
884
+ return regex.test(basename2);
885
+ }
886
+ function readExcludePatterns(skillDir) {
887
+ const excludePath = path14.join(skillDir, EXCLUDE_FILE_NAME);
888
+ if (!fs14.existsSync(excludePath)) {
889
+ return [];
890
+ }
891
+ const raw = fs14.readFileSync(excludePath, "utf8");
892
+ const patterns = raw.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
893
+ for (const pattern of patterns) {
894
+ if (hasUnbalancedBraces(pattern)) {
895
+ logger.warn(
896
+ ` \u26A0\uFE0F Unbalanced brace in exclude pattern "${pattern}" (${excludePath}) \u2014 the brace is matched as a literal character. Use {a,b} for alternation.`
897
+ );
721
898
  }
722
- throw error;
723
899
  }
900
+ return patterns;
724
901
  }
725
- function cleanupDirectory(dirPath) {
726
- if (fs12.existsSync(dirPath)) {
727
- fs12.rmSync(dirPath, { recursive: true, force: true });
902
+ function isBinaryBuffer(buffer) {
903
+ if (buffer.includes(0)) {
904
+ return true;
728
905
  }
906
+ return !Buffer.from(buffer.toString("utf8"), "utf8").equals(buffer);
729
907
  }
730
- function ensureDirectoryExists(filePath) {
731
- const dir = path.dirname(filePath);
732
- if (!fs12.existsSync(dir)) {
733
- fs12.mkdirSync(dir, { recursive: true });
908
+ function toPosixPath(relPath) {
909
+ return relPath.split(path14.sep).join("/");
910
+ }
911
+ function buildCompanionFile(absPath, relPath) {
912
+ const buffer = fs14.readFileSync(absPath);
913
+ const binary = isBinaryBuffer(buffer);
914
+ const ext = path14.extname(relPath).toLowerCase();
915
+ const mimeType = MIME_TYPES[ext] ?? DEFAULT_MIME_TYPE;
916
+ return {
917
+ path: relPath,
918
+ content: binary ? buffer.toString("base64") : buffer.toString("utf8"),
919
+ mime_type: mimeType,
920
+ encoding: binary ? "base64" : "text",
921
+ size_bytes: buffer.length
922
+ };
923
+ }
924
+ function walk(currentDir, skillDir, excludePatterns, results) {
925
+ const entries = fs14.readdirSync(currentDir, { withFileTypes: true });
926
+ for (const entry of entries) {
927
+ const absPath = path14.join(currentDir, entry.name);
928
+ const relPath = toPosixPath(path14.relative(skillDir, absPath));
929
+ if (entry.isSymbolicLink()) {
930
+ continue;
931
+ }
932
+ if (entry.isDirectory()) {
933
+ if (ALWAYS_SKIPPED_DIRS.has(entry.name)) {
934
+ continue;
935
+ }
936
+ const directoryCandidates = [relPath, `${relPath}/`];
937
+ if (excludePatterns.some((pattern) => directoryCandidates.some((cand) => matchesExcludePattern(cand, pattern)))) {
938
+ continue;
939
+ }
940
+ walk(absPath, skillDir, excludePatterns, results);
941
+ continue;
942
+ }
943
+ if (!entry.isFile()) {
944
+ continue;
945
+ }
946
+ if (entry.name === SKILL_MD_FILENAME3 || entry.name === EXCLUDE_FILE_NAME) {
947
+ continue;
948
+ }
949
+ if (ALWAYS_SKIPPED_LOCKFILES.has(entry.name)) {
950
+ continue;
951
+ }
952
+ if (excludePatterns.some((pattern) => matchesExcludePattern(relPath, pattern))) {
953
+ continue;
954
+ }
955
+ results.push(buildCompanionFile(absPath, relPath));
734
956
  }
735
957
  }
736
- var BYTES_IN_GB;
737
- var init_fileUtils = __esm({
738
- "src/lib/fileUtils.ts"() {
739
- BYTES_IN_GB = 1024 ** 3;
958
+ function collectCompanionFiles(skillDir) {
959
+ const excludePatterns = readExcludePatterns(skillDir);
960
+ const results = [];
961
+ walk(skillDir, skillDir, excludePatterns, results);
962
+ results.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
963
+ return results;
964
+ }
965
+ function stateHasCompanionFiles(existingState) {
966
+ return Object.keys(existingState?.companionFileHashes ?? {}).length > 0;
967
+ }
968
+ var SKILL_MD_FILENAME3, EXCLUDE_FILE_NAME, ALWAYS_SKIPPED_DIRS, ALWAYS_SKIPPED_LOCKFILES, DEFAULT_MIME_TYPE, MIME_TYPES;
969
+ var init_skillCompanionFiles = __esm({
970
+ "src/lib/skillCompanionFiles.ts"() {
971
+ init_logger();
972
+ SKILL_MD_FILENAME3 = "SKILL.md";
973
+ EXCLUDE_FILE_NAME = ".codemie-exclude";
974
+ ALWAYS_SKIPPED_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "evals"]);
975
+ ALWAYS_SKIPPED_LOCKFILES = /* @__PURE__ */ new Set([
976
+ "package-lock.json",
977
+ "npm-shrinkwrap.json",
978
+ "yarn.lock",
979
+ "pnpm-lock.yaml",
980
+ "bun.lockb",
981
+ "composer.lock",
982
+ "Gemfile.lock",
983
+ "Cargo.lock",
984
+ "poetry.lock"
985
+ ]);
986
+ DEFAULT_MIME_TYPE = "application/octet-stream";
987
+ MIME_TYPES = {
988
+ ".md": "text/markdown",
989
+ ".txt": "text/plain",
990
+ ".json": "application/json",
991
+ ".yaml": "application/yaml",
992
+ ".yml": "application/yaml",
993
+ ".js": "text/javascript",
994
+ ".mjs": "text/javascript",
995
+ ".ts": "text/plain",
996
+ ".py": "text/x-python",
997
+ ".html": "text/html",
998
+ ".htm": "text/html",
999
+ ".css": "text/css",
1000
+ ".csv": "text/csv",
1001
+ ".xml": "application/xml",
1002
+ ".sh": "text/x-sh",
1003
+ ".png": "image/png",
1004
+ ".jpg": "image/jpeg",
1005
+ ".jpeg": "image/jpeg",
1006
+ ".gif": "image/gif",
1007
+ ".svg": "image/svg+xml",
1008
+ ".webp": "image/webp",
1009
+ ".ico": "image/x-icon",
1010
+ ".pdf": "application/pdf",
1011
+ ".zip": "application/zip"
1012
+ };
740
1013
  }
741
1014
  });
742
1015
 
@@ -869,7 +1142,7 @@ function prepareWorkflowForYaml(workflow, state, assistants, backupDir) {
869
1142
  let finalYamlContent = yamlConfig || "";
870
1143
  if (yamlConfig) {
871
1144
  try {
872
- const workflowYaml = yaml7.parse(yamlConfig);
1145
+ const workflowYaml = yaml8.parse(yamlConfig);
873
1146
  const transformedAssistants = workflowYaml.assistants?.map((assistant) => {
874
1147
  if (assistant.assistant_id && typeof assistant.assistant_id === "string") {
875
1148
  const assistantId = assistant.assistant_id;
@@ -884,10 +1157,10 @@ function prepareWorkflowForYaml(workflow, state, assistants, backupDir) {
884
1157
  if (transformedAssistants) {
885
1158
  const transformedYaml = { ...workflowYaml, assistants: transformedAssistants };
886
1159
  const fileName = `${sanitizeFileName(workflow.name)}.yaml`;
887
- const filePath = path.join(backupDir, "workflows", fileName);
1160
+ const filePath = path14.join(backupDir, "workflows", fileName);
888
1161
  ensureDirectoryExists(filePath);
889
- finalYamlContent = yaml7.stringify(transformedYaml);
890
- fs12.writeFileSync(filePath, finalYamlContent, "utf8");
1162
+ finalYamlContent = yaml8.stringify(transformedYaml);
1163
+ fs14.writeFileSync(filePath, finalYamlContent, "utf8");
891
1164
  }
892
1165
  } catch (error) {
893
1166
  logger.warn(
@@ -933,8 +1206,18 @@ function prepareImportedSkillForYaml(skill) {
933
1206
  id: skill.id
934
1207
  };
935
1208
  }
936
- function prepareSkillForYaml(skill, state) {
1209
+ function prepareSkillForYaml(skill, state, backupDir) {
937
1210
  const resource = skillResponseToResource(skill);
1211
+ let companionFiles = [];
1212
+ if (resource.file && (skill.companion_files?.length ?? 0) > 0) {
1213
+ resource.file = skillMarkdownRelativePath(skill.name);
1214
+ if (backupDir) {
1215
+ const skillDir = path14.join(backupDir, path14.dirname(resource.file));
1216
+ if (fs14.existsSync(skillDir)) {
1217
+ companionFiles = collectCompanionFiles(skillDir);
1218
+ }
1219
+ }
1220
+ }
938
1221
  if (!state.resources.skills) {
939
1222
  state.resources.skills = {};
940
1223
  }
@@ -942,7 +1225,9 @@ function prepareSkillForYaml(skill, state) {
942
1225
  id: skill.id,
943
1226
  lastDeployed: (/* @__PURE__ */ new Date()).toISOString(),
944
1227
  contentChecksum: calculateChecksum(skill.content || ""),
945
- configChecksum: calculateSkillConfigChecksum(resource)
1228
+ configChecksum: calculateSkillConfigChecksum(resource),
1229
+ // Omitted entirely for a companion-less skill, so its state entry stays exactly as before.
1230
+ ...companionFiles.length > 0 ? calculateCompanionFilesChecksum(companionFiles) : {}
946
1231
  };
947
1232
  return resource;
948
1233
  }
@@ -954,6 +1239,7 @@ var init_backupTransformers = __esm({
954
1239
  init_fileUtils();
955
1240
  init_logger();
956
1241
  init_mcpSanitizer();
1242
+ init_skillCompanionFiles();
957
1243
  init_skillUtils();
958
1244
  init_typeGuards();
959
1245
  }
@@ -976,8 +1262,8 @@ function resolveImports(obj, baseDir, visitedFiles = /* @__PURE__ */ new Set())
976
1262
  const value = obj[key];
977
1263
  if (isPlainObject(value) && "$import" in value) {
978
1264
  const importDirective = value;
979
- const importPath = path.join(baseDir, importDirective.$import);
980
- const normalizedPath = path.resolve(importPath);
1265
+ const importPath = path14.join(baseDir, importDirective.$import);
1266
+ const normalizedPath = path14.resolve(importPath);
981
1267
  if (visitedFiles.has(normalizedPath)) {
982
1268
  throw new Error(
983
1269
  `Circular import detected: ${normalizedPath}
@@ -987,7 +1273,7 @@ Import chain: ${[...visitedFiles].join(" \u2192 ")} \u2192 ${normalizedPath}`
987
1273
  visitedFiles.add(normalizedPath);
988
1274
  const imported = loadYamlFile(importPath);
989
1275
  obj[key] = imported;
990
- resolveImports(obj[key], path.dirname(importPath), visitedFiles);
1276
+ resolveImports(obj[key], path14.dirname(importPath), visitedFiles);
991
1277
  visitedFiles.delete(normalizedPath);
992
1278
  } else if (Array.isArray(value)) {
993
1279
  obj[key] = resolveArrayImports(value, baseDir, visitedFiles);
@@ -1001,8 +1287,8 @@ function resolveArrayImports(arr, baseDir, visitedFiles = /* @__PURE__ */ new Se
1001
1287
  for (const item of arr) {
1002
1288
  if (isPlainObject(item) && "$import" in item) {
1003
1289
  const importDirective = item;
1004
- const importPath = path.join(baseDir, importDirective.$import);
1005
- const normalizedPath = path.resolve(importPath);
1290
+ const importPath = path14.join(baseDir, importDirective.$import);
1291
+ const normalizedPath = path14.resolve(importPath);
1006
1292
  if (visitedFiles.has(normalizedPath)) {
1007
1293
  throw new Error(
1008
1294
  `Circular import detected: ${normalizedPath}
@@ -1012,13 +1298,13 @@ Import chain: ${[...visitedFiles].join(" \u2192 ")} \u2192 ${normalizedPath}`
1012
1298
  visitedFiles.add(normalizedPath);
1013
1299
  const imported = loadYamlFile(importPath);
1014
1300
  if (Array.isArray(imported)) {
1015
- const resolvedArray = resolveArrayImports(imported, path.dirname(importPath), visitedFiles);
1301
+ const resolvedArray = resolveArrayImports(imported, path14.dirname(importPath), visitedFiles);
1016
1302
  for (const resolvedItem of resolvedArray) {
1017
1303
  result.push(resolvedItem);
1018
1304
  }
1019
1305
  } else if (isPlainObject(imported)) {
1020
1306
  result.push(imported);
1021
- resolveImports(imported, path.dirname(importPath), visitedFiles);
1307
+ resolveImports(imported, path14.dirname(importPath), visitedFiles);
1022
1308
  } else {
1023
1309
  throw new TypeError(
1024
1310
  `Import file ${importPath} must contain either an object or an array. Got: ${typeof imported}`
@@ -1035,12 +1321,12 @@ Import chain: ${[...visitedFiles].join(" \u2192 ")} \u2192 ${normalizedPath}`
1035
1321
  return result;
1036
1322
  }
1037
1323
  function loadYamlFile(filePath) {
1038
- if (!fs12.existsSync(filePath)) {
1324
+ if (!fs14.existsSync(filePath)) {
1039
1325
  throw new Error(`Import file not found: ${filePath}`);
1040
1326
  }
1041
1327
  try {
1042
- const content = fs12.readFileSync(filePath, "utf8");
1043
- const parsed = yaml7.parse(content);
1328
+ const content = fs14.readFileSync(filePath, "utf8");
1329
+ const parsed = yaml8.parse(content);
1044
1330
  if (parsed === null || parsed === void 0) {
1045
1331
  throw new TypeError(`Import file ${filePath} is empty`);
1046
1332
  }
@@ -1053,7 +1339,7 @@ function loadYamlFile(filePath) {
1053
1339
  }
1054
1340
  }
1055
1341
  function findResourceDefinition(rootDir, codemieConfigPath, plural, name) {
1056
- const configPath = path.join(rootDir, codemieConfigPath);
1342
+ const configPath = path14.join(rootDir, codemieConfigPath);
1057
1343
  const config = loadYamlFile(configPath);
1058
1344
  if (!isPlainObject(config) || !isPlainObject(config.resources)) {
1059
1345
  return void 0;
@@ -1070,8 +1356,8 @@ function findResourceInList(items, baseDir, currentFile, name, visitedFiles) {
1070
1356
  continue;
1071
1357
  }
1072
1358
  if (typeof item.$import === "string") {
1073
- const importPath = path.join(baseDir, item.$import);
1074
- const normalizedPath = path.resolve(importPath);
1359
+ const importPath = path14.join(baseDir, item.$import);
1360
+ const normalizedPath = path14.resolve(importPath);
1075
1361
  if (visitedFiles.has(normalizedPath)) {
1076
1362
  throw new Error(
1077
1363
  `Circular import detected: ${normalizedPath}
@@ -1082,7 +1368,7 @@ Import chain: ${[...visitedFiles].join(" \u2192 ")} \u2192 ${normalizedPath}`
1082
1368
  const loaded = loadYamlFile(importPath);
1083
1369
  let found;
1084
1370
  if (Array.isArray(loaded)) {
1085
- found = findResourceInList(loaded, path.dirname(importPath), normalizedPath, name, visitedFiles);
1371
+ found = findResourceInList(loaded, path14.dirname(importPath), normalizedPath, name, visitedFiles);
1086
1372
  } else if (isPlainObject(loaded) && typeof loaded.name === "string" && namesEqual(loaded.name, name)) {
1087
1373
  found = { file: normalizedPath, resource: loaded, inList: false };
1088
1374
  }
@@ -1099,6 +1385,214 @@ Import chain: ${[...visitedFiles].join(" \u2192 ")} \u2192 ${normalizedPath}`
1099
1385
  return void 0;
1100
1386
  }
1101
1387
 
1388
+ // src/lib/validationUtils.ts
1389
+ var MIN_SKILL_DESCRIPTION_LENGTH = 10;
1390
+ var MAX_SKILL_DESCRIPTION_LENGTH = 1e3;
1391
+ function isAssistantWithSlug(obj) {
1392
+ return typeof obj === "object" && obj !== null && "slug" in obj && "name" in obj && typeof obj.slug === "string" && typeof obj.name === "string";
1393
+ }
1394
+ function isAssistant(obj) {
1395
+ return typeof obj === "object" && obj !== null && "id" in obj && "slug" in obj;
1396
+ }
1397
+ function validateSlugUniqueness(config) {
1398
+ const slugErrors = [];
1399
+ const slugMap = /* @__PURE__ */ new Map();
1400
+ if (config.resources.assistants) {
1401
+ for (const assistant of config.resources.assistants) {
1402
+ if (assistant.slug) {
1403
+ if (!slugMap.has(assistant.slug)) {
1404
+ slugMap.set(assistant.slug, []);
1405
+ }
1406
+ slugMap.get(assistant.slug).push(assistant.name);
1407
+ }
1408
+ }
1409
+ }
1410
+ for (const [slug, names] of slugMap.entries()) {
1411
+ if (names.length > 1) {
1412
+ slugErrors.push(`Duplicate slug "${slug}" for assistants: ${names.join(", ")}`);
1413
+ }
1414
+ }
1415
+ return slugErrors;
1416
+ }
1417
+ async function checkApiSlugConflicts({
1418
+ config,
1419
+ client,
1420
+ assistantState
1421
+ }) {
1422
+ const existingAssistants = await client.assistants.list({
1423
+ minimal_response: false,
1424
+ per_page: 100
1425
+ });
1426
+ const existingSlugs = /* @__PURE__ */ new Map();
1427
+ for (const assistant of existingAssistants) {
1428
+ if (isAssistantWithSlug(assistant) && assistant.slug) {
1429
+ existingSlugs.set(assistant.slug, assistant.name);
1430
+ }
1431
+ }
1432
+ const conflictErrors = [];
1433
+ const iacAssistantNames = new Set(Object.keys(assistantState));
1434
+ if (config.resources.assistants) {
1435
+ for (const assistant of config.resources.assistants) {
1436
+ if (!assistant.slug || iacAssistantNames.has(assistant.name)) {
1437
+ continue;
1438
+ }
1439
+ if (existingSlugs.has(assistant.slug)) {
1440
+ const existingName = existingSlugs.get(assistant.slug);
1441
+ const existingAssistant = existingAssistants.find((a) => isAssistant(a) && a.slug === assistant.slug);
1442
+ conflictErrors.push(
1443
+ `\u274C Slug "${assistant.slug}" for assistant "${assistant.name}" already exists in Codemie
1444
+ Existing assistant: "${existingName}" (ID: ${isAssistant(existingAssistant) ? existingAssistant.id : "unknown"})
1445
+ \u{1F4A1} Change slug to a unique value or omit slug (platform will generate)`
1446
+ );
1447
+ }
1448
+ }
1449
+ }
1450
+ return conflictErrors;
1451
+ }
1452
+ function validateSkillDescriptions(skills) {
1453
+ const errors = [];
1454
+ for (const skill of skills) {
1455
+ const length = skill.description?.length ?? 0;
1456
+ if (length < MIN_SKILL_DESCRIPTION_LENGTH || length > MAX_SKILL_DESCRIPTION_LENGTH) {
1457
+ errors.push(
1458
+ `\u274C Skill "${skill.name}" description length is ${length} characters
1459
+ \u{1F4A1} Allowed range: ${MIN_SKILL_DESCRIPTION_LENGTH}-${MAX_SKILL_DESCRIPTION_LENGTH} characters`
1460
+ );
1461
+ }
1462
+ }
1463
+ return errors;
1464
+ }
1465
+ function validateSkillContentLengths(entries, limits) {
1466
+ const errors = [];
1467
+ for (const entry of entries) {
1468
+ const length = entry.content?.length ?? 0;
1469
+ if (length < limits.min_content_length || length > limits.max_content_length) {
1470
+ errors.push(
1471
+ `\u274C Skill "${entry.name}" content length is ${length} characters
1472
+ \u{1F4A1} Allowed range: ${limits.min_content_length}-${limits.max_content_length} characters`
1473
+ );
1474
+ }
1475
+ }
1476
+ return errors;
1477
+ }
1478
+
1479
+ // src/lib/skillSourceLoader.ts
1480
+ var SKILL_MD_FILENAME = "SKILL.md";
1481
+ var SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/;
1482
+ var BOM = "\uFEFF";
1483
+ var FRONT_MATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
1484
+ function stripBom(raw) {
1485
+ return raw.charCodeAt(0) === BOM.charCodeAt(0) ? raw.slice(1) : raw;
1486
+ }
1487
+ function parseSkillFrontMatter(raw, sourcePath = SKILL_MD_FILENAME) {
1488
+ const content = stripBom(raw);
1489
+ const match = content.match(FRONT_MATTER_PATTERN);
1490
+ if (!match) {
1491
+ return { frontMatter: {}, body: content };
1492
+ }
1493
+ const [, yamlBlock, body] = match;
1494
+ let parsed;
1495
+ try {
1496
+ parsed = yaml8.parse(yamlBlock);
1497
+ } catch (error) {
1498
+ throw new Error(
1499
+ `Invalid YAML front matter in ${sourcePath}: ${error instanceof Error ? error.message : String(error)}`
1500
+ );
1501
+ }
1502
+ const frontMatter = parsed !== null && typeof parsed === "object" ? parsed : {};
1503
+ return { frontMatter, body };
1504
+ }
1505
+ function readIgnoreSet(rootDir, ignoreFile, sourceDir) {
1506
+ if (!ignoreFile) {
1507
+ return /* @__PURE__ */ new Set();
1508
+ }
1509
+ const resolvedIgnorePath = path14.join(rootDir, ignoreFile);
1510
+ if (!fs14.existsSync(resolvedIgnorePath)) {
1511
+ throw new Error(
1512
+ `Skill ignore file not found: ${resolvedIgnorePath} (from ignore_file "${ignoreFile}" in source_dir "${sourceDir}")`
1513
+ );
1514
+ }
1515
+ let parsed;
1516
+ try {
1517
+ const content = fs14.readFileSync(resolvedIgnorePath, "utf8");
1518
+ parsed = yaml8.parse(content);
1519
+ } catch (error) {
1520
+ throw new Error(
1521
+ `Invalid YAML in skill ignore file ${resolvedIgnorePath} (from source_dir "${sourceDir}"): ${error instanceof Error ? error.message : String(error)}`
1522
+ );
1523
+ }
1524
+ return new Set(parsed?.skills ?? []);
1525
+ }
1526
+ function stringOrUndefined(value) {
1527
+ return typeof value === "string" ? value : void 0;
1528
+ }
1529
+ function expandOneSourceDir(entry, rootDir) {
1530
+ const sourceDir = entry.source_dir;
1531
+ const resolvedSourceDir = path14.join(rootDir, sourceDir);
1532
+ if (!fs14.existsSync(resolvedSourceDir) || !fs14.statSync(resolvedSourceDir).isDirectory()) {
1533
+ throw new Error(`Skill source directory not found: ${resolvedSourceDir} (from source_dir "${sourceDir}")`);
1534
+ }
1535
+ const ignoreSet = readIgnoreSet(rootDir, entry.ignore_file, sourceDir);
1536
+ const dirNames = fs14.readdirSync(resolvedSourceDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name).filter((dirName) => !ignoreSet.has(dirName)).sort();
1537
+ const expanded = [];
1538
+ for (const dirName of dirNames) {
1539
+ const skillMdPath = path14.join(resolvedSourceDir, dirName, SKILL_MD_FILENAME);
1540
+ if (!fs14.existsSync(skillMdPath)) {
1541
+ continue;
1542
+ }
1543
+ const raw = fs14.readFileSync(skillMdPath, "utf8");
1544
+ const { frontMatter, body } = parseSkillFrontMatter(raw, skillMdPath);
1545
+ const name = stringOrUndefined(frontMatter.name) ?? dirName;
1546
+ const description = stringOrUndefined(frontMatter.description);
1547
+ if (!SKILL_NAME_PATTERN.test(name)) {
1548
+ throw new Error(
1549
+ `\u274C Skill "${name}" (from directory "${dirName}" in source_dir "${sourceDir}") has an invalid name
1550
+ \u{1F4A1} Names must be kebab-case, 3-64 characters, and start and end with a letter or digit`
1551
+ );
1552
+ }
1553
+ const resource = {
1554
+ name,
1555
+ description: description ?? "",
1556
+ file: path14.join(sourceDir, dirName, SKILL_MD_FILENAME),
1557
+ content: body,
1558
+ ...entry.categories !== void 0 ? { categories: entry.categories } : {},
1559
+ ...entry.visibility !== void 0 ? { visibility: entry.visibility } : {},
1560
+ ...entry.group !== void 0 ? { group: entry.group } : {}
1561
+ };
1562
+ expanded.push({ resource, origin: `directory "${dirName}" in source_dir "${sourceDir}"` });
1563
+ }
1564
+ return expanded;
1565
+ }
1566
+ function expandSkillSourceDirs(skills, rootDir) {
1567
+ const collected = [];
1568
+ const descriptionErrors = [];
1569
+ for (const skill of skills) {
1570
+ if (!skill.source_dir) {
1571
+ collected.push({ resource: skill, origin: `hand-written entry "${skill.name}"` });
1572
+ continue;
1573
+ }
1574
+ const expanded = expandOneSourceDir(skill, rootDir);
1575
+ descriptionErrors.push(...validateSkillDescriptions(expanded.map((item) => item.resource)));
1576
+ collected.push(...expanded);
1577
+ }
1578
+ if (descriptionErrors.length > 0) {
1579
+ throw new Error(descriptionErrors.join("\n\n"));
1580
+ }
1581
+ const originByName = /* @__PURE__ */ new Map();
1582
+ for (const { resource, origin } of collected) {
1583
+ const key = resource.name.toLowerCase();
1584
+ const previousOrigin = originByName.get(key);
1585
+ if (previousOrigin !== void 0) {
1586
+ throw new Error(
1587
+ `\u274C Duplicate skill name "${resource.name}": defined by ${previousOrigin} and ${origin}
1588
+ \u{1F4A1} Skill names must be unique across every source_dir and hand-written entry`
1589
+ );
1590
+ }
1591
+ originByName.set(key, origin);
1592
+ }
1593
+ return collected.map((item) => item.resource);
1594
+ }
1595
+
1102
1596
  // src/lib/codemieConfigLoader.ts
1103
1597
  var CodemieConfigLoader = class {
1104
1598
  appConfig;
@@ -1110,14 +1604,17 @@ var CodemieConfigLoader = class {
1110
1604
  */
1111
1605
  loadConfig() {
1112
1606
  const { rootDir, codemieConfig } = this.appConfig;
1113
- const configPath = path.join(rootDir, codemieConfig);
1114
- if (!fs12.existsSync(configPath)) {
1607
+ const configPath = path14.join(rootDir, codemieConfig);
1608
+ if (!fs14.existsSync(configPath)) {
1115
1609
  throw new Error(`Configuration file not found: ${configPath}`);
1116
1610
  }
1117
- const content = fs12.readFileSync(configPath, "utf8");
1118
- const config = yaml7.parse(content);
1611
+ const content = fs14.readFileSync(configPath, "utf8");
1612
+ const config = yaml8.parse(content);
1119
1613
  resolveImports(config, rootDir);
1120
1614
  this.substituteEnvVars(config);
1615
+ if (config.resources.skills) {
1616
+ config.resources.skills = expandSkillSourceDirs(config.resources.skills, rootDir);
1617
+ }
1121
1618
  this.applyDatasourceDefaults(config);
1122
1619
  this.resolveReferencesRecursive(config, config);
1123
1620
  this.validateDatasourceIntegrationReferences(config);
@@ -1128,34 +1625,48 @@ var CodemieConfigLoader = class {
1128
1625
  */
1129
1626
  loadPrompt(promptPath) {
1130
1627
  const { rootDir } = this.appConfig;
1131
- const fullPath = path.join(rootDir, promptPath);
1132
- if (!fs12.existsSync(fullPath)) {
1628
+ const fullPath = path14.join(rootDir, promptPath);
1629
+ if (!fs14.existsSync(fullPath)) {
1133
1630
  throw new Error(`Prompt file not found: ${fullPath}`);
1134
1631
  }
1135
- return fs12.readFileSync(fullPath, "utf8");
1632
+ return fs14.readFileSync(fullPath, "utf8");
1136
1633
  }
1137
1634
  /**
1138
1635
  * Load skill content file (.skill.md)
1139
1636
  */
1140
1637
  loadSkillContent(contentPath) {
1141
1638
  const { rootDir } = this.appConfig;
1142
- const fullPath = path.join(rootDir, contentPath);
1143
- if (!fs12.existsSync(fullPath)) {
1639
+ const fullPath = path14.join(rootDir, contentPath);
1640
+ if (!fs14.existsSync(fullPath)) {
1144
1641
  throw new Error(`Skill content file not found: ${fullPath}`);
1145
1642
  }
1146
- return fs12.readFileSync(fullPath, "utf8");
1643
+ return fs14.readFileSync(fullPath, "utf8");
1644
+ }
1645
+ /**
1646
+ * Resolve a skill's content: prefers an already-loaded `content` (e.g. from an expanded
1647
+ * `source_dir` entry) and otherwise falls back to reading `file`. This is the single
1648
+ * content accessor for skills — every consumer routes through it.
1649
+ */
1650
+ resolveSkillContent(skill) {
1651
+ if (skill.content !== void 0) {
1652
+ return skill.content;
1653
+ }
1654
+ if (skill.file) {
1655
+ return this.loadSkillContent(skill.file);
1656
+ }
1657
+ throw new Error(`Skill "${skill.name}" has neither 'content' nor 'file' to load content from`);
1147
1658
  }
1148
1659
  /**
1149
1660
  * Load assistant configuration file
1150
1661
  */
1151
1662
  loadAssistantConfig(configPath) {
1152
1663
  const { rootDir } = this.appConfig;
1153
- const fullPath = path.join(rootDir, configPath);
1154
- if (!fs12.existsSync(fullPath)) {
1664
+ const fullPath = path14.join(rootDir, configPath);
1665
+ if (!fs14.existsSync(fullPath)) {
1155
1666
  throw new Error(`Config file not found: ${fullPath}`);
1156
1667
  }
1157
- const content = fs12.readFileSync(fullPath, "utf8");
1158
- return yaml7.parse(content);
1668
+ const content = fs14.readFileSync(fullPath, "utf8");
1669
+ return yaml8.parse(content);
1159
1670
  }
1160
1671
  /**
1161
1672
  * Validate that all referenced files exist
@@ -1167,12 +1678,12 @@ var CodemieConfigLoader = class {
1167
1678
  for (const assistant of config.resources.assistants) {
1168
1679
  if (!assistant.prompt) {
1169
1680
  errors.push(`Missing 'prompt' for assistant: ${assistant.name}`);
1170
- } else if (!fs12.existsSync(path.join(rootDir, assistant.prompt))) {
1681
+ } else if (!fs14.existsSync(path14.join(rootDir, assistant.prompt))) {
1171
1682
  errors.push(`Prompt file not found for ${assistant.name}: ${assistant.prompt}`);
1172
1683
  }
1173
1684
  if (assistant.config) {
1174
- const configPath = path.join(rootDir, assistant.config);
1175
- if (!fs12.existsSync(configPath)) {
1685
+ const configPath = path14.join(rootDir, assistant.config);
1686
+ if (!fs14.existsSync(configPath)) {
1176
1687
  errors.push(`Config file not found for ${assistant.name}: ${assistant.config}`);
1177
1688
  }
1178
1689
  }
@@ -1186,15 +1697,16 @@ var CodemieConfigLoader = class {
1186
1697
  }
1187
1698
  if (config.resources.skills) {
1188
1699
  for (const skill of config.resources.skills) {
1189
- if (!skill.file) {
1190
- errors.push(`Missing 'file' for skill: ${skill.name}`);
1191
- } else if (!fs12.existsSync(path.join(rootDir, skill.file))) {
1192
- errors.push(`Content file not found for skill ${skill.name}: ${skill.file}`);
1700
+ const hasFile = !!skill.file;
1701
+ const hasContent = skill.content !== void 0;
1702
+ if (!hasFile && !hasContent) {
1703
+ errors.push(`Skill '${skill.name}' must specify at least one of 'file' or 'content'`);
1193
1704
  }
1194
- if (!skill.description) {
1195
- errors.push(`Missing 'description' for skill: ${skill.name}`);
1705
+ if (hasFile && !fs14.existsSync(path14.join(rootDir, skill.file))) {
1706
+ errors.push(`Content file not found for skill ${skill.name}: ${skill.file}`);
1196
1707
  }
1197
1708
  }
1709
+ errors.push(...validateSkillDescriptions(config.resources.skills));
1198
1710
  }
1199
1711
  for (const skill of config.imported?.skills || []) {
1200
1712
  if (!skill.name) {
@@ -1217,28 +1729,28 @@ var CodemieConfigLoader = class {
1217
1729
  * @param rootConfig - Root config object (constant reference for resolving paths like "imported.integrations.xxx")
1218
1730
  * @param path - Current path in config tree (for error messages, e.g., "resources.assistants[0].toolkits")
1219
1731
  */
1220
- resolveReferencesRecursive(current, rootConfig, path13 = "") {
1732
+ resolveReferencesRecursive(current, rootConfig, path15 = "") {
1221
1733
  if (!current || typeof current !== "object") {
1222
1734
  return;
1223
1735
  }
1224
1736
  if (Array.isArray(current)) {
1225
- this.resolveArrayReferences(current, rootConfig, path13);
1737
+ this.resolveArrayReferences(current, rootConfig, path15);
1226
1738
  return;
1227
1739
  }
1228
1740
  if ("$ref" in current && typeof current.$ref === "string") {
1229
- this.resolveObjectReference(current, rootConfig, path13);
1741
+ this.resolveObjectReference(current, rootConfig, path15);
1230
1742
  return;
1231
1743
  }
1232
- this.resolveObjectProperties(current, rootConfig, path13);
1744
+ this.resolveObjectProperties(current, rootConfig, path15);
1233
1745
  }
1234
1746
  /**
1235
1747
  * Resolve $ref items in arrays and flatten if they point to arrays
1236
1748
  * Example: [{ $ref: "context_definitions.repos" }] where repos is [item1, item2]
1237
1749
  * becomes [item1, item2]
1238
1750
  */
1239
- resolveArrayReferences(arr, rootConfig, path13) {
1751
+ resolveArrayReferences(arr, rootConfig, path15) {
1240
1752
  const result = arr.flatMap((item, i) => {
1241
- const contextPath = `${path13}[${i}]`;
1753
+ const contextPath = `${path15}[${i}]`;
1242
1754
  if (!this.isRefObject(item) || item.$ref.startsWith("#")) {
1243
1755
  this.resolveReferencesRecursive(item, rootConfig, contextPath);
1244
1756
  return [item];
@@ -1256,9 +1768,9 @@ var CodemieConfigLoader = class {
1256
1768
  * Resolve object reference: { $ref: "path" }
1257
1769
  * Replaces object with resolved data (in-place mutation)
1258
1770
  */
1259
- resolveObjectReference(current, rootConfig, path13) {
1771
+ resolveObjectReference(current, rootConfig, path15) {
1260
1772
  const refPath = current.$ref;
1261
- const contextPath = path13 || "root";
1773
+ const contextPath = path15 || "root";
1262
1774
  if (refPath.startsWith("#")) {
1263
1775
  return;
1264
1776
  }
@@ -1268,24 +1780,24 @@ var CodemieConfigLoader = class {
1268
1780
  delete current[key];
1269
1781
  }
1270
1782
  Object.assign(current, filteredResolved);
1271
- this.resolveReferencesRecursive(current, rootConfig, path13);
1783
+ this.resolveReferencesRecursive(current, rootConfig, path15);
1272
1784
  }
1273
1785
  /**
1274
1786
  * Resolve object properties recursively
1275
1787
  * Handles both nested objects and "$ref:path" string references
1276
1788
  */
1277
- resolveObjectProperties(current, rootConfig, path13) {
1789
+ resolveObjectProperties(current, rootConfig, path15) {
1278
1790
  for (const [key, value] of Object.entries(current)) {
1279
1791
  if (typeof value === "string" && value.startsWith("$ref:")) {
1280
1792
  const refPath = value.slice(5);
1281
1793
  if (refPath.startsWith("#")) {
1282
1794
  continue;
1283
1795
  }
1284
- const contextPath = path13 ? `${path13}.${key}` : key;
1796
+ const contextPath = path15 ? `${path15}.${key}` : key;
1285
1797
  const resolved = this.resolveReference(rootConfig, refPath, contextPath);
1286
1798
  current[key] = resolved;
1287
1799
  } else {
1288
- this.resolveReferencesRecursive(value, rootConfig, path13 ? `${path13}.${key}` : key);
1800
+ this.resolveReferencesRecursive(value, rootConfig, path15 ? `${path15}.${key}` : key);
1289
1801
  }
1290
1802
  }
1291
1803
  }
@@ -1409,8 +1921,10 @@ var CodemieConfigLoader = class {
1409
1921
  * - ${VAR_NAME:default} - optional with default value (simplified)
1410
1922
  * - ${VAR_NAME:-} or ${VAR_NAME:} - optional with empty string default
1411
1923
  */
1412
- substituteEnvVars(obj) {
1924
+ substituteEnvVars(obj, configPath = "") {
1925
+ const isArray = Array.isArray(obj);
1413
1926
  for (const key in obj) {
1927
+ const childPath = isArray ? `${configPath}[${key}]` : configPath ? `${configPath}.${key}` : key;
1414
1928
  if (typeof obj[key] === "string") {
1415
1929
  obj[key] = obj[key].replaceAll(
1416
1930
  /\$\{([^:}]+)(?::-?([^}]*))?\}/g,
@@ -1420,13 +1934,13 @@ var CodemieConfigLoader = class {
1420
1934
  if (defaultValue !== void 0) {
1421
1935
  return defaultValue;
1422
1936
  }
1423
- throw new Error(`Environment variable ${varName} is not set`);
1937
+ throw new Error(`Environment variable ${varName} is not set (referenced in ${childPath})`);
1424
1938
  }
1425
1939
  return value;
1426
1940
  }
1427
1941
  );
1428
- } else if (this.isPlainObject(obj[key])) {
1429
- this.substituteEnvVars(obj[key]);
1942
+ } else if (this.isPlainObject(obj[key]) || Array.isArray(obj[key])) {
1943
+ this.substituteEnvVars(obj[key], childPath);
1430
1944
  }
1431
1945
  }
1432
1946
  }
@@ -1439,16 +1953,16 @@ var StateManager = class {
1439
1953
  statePath;
1440
1954
  constructor(appConfig) {
1441
1955
  const { rootDir, codemieState } = appConfig;
1442
- this.statePath = path.join(rootDir, codemieState);
1956
+ this.statePath = path14.join(rootDir, codemieState);
1443
1957
  }
1444
1958
  /**
1445
1959
  * Load state file
1446
1960
  */
1447
1961
  loadState() {
1448
- if (!fs12.existsSync(this.statePath)) {
1962
+ if (!fs14.existsSync(this.statePath)) {
1449
1963
  return this.createEmptyState();
1450
1964
  }
1451
- const content = fs12.readFileSync(this.statePath, "utf8");
1965
+ const content = fs14.readFileSync(this.statePath, "utf8");
1452
1966
  const state = JSON.parse(content);
1453
1967
  if (!state.resources) {
1454
1968
  state.resources = {
@@ -1476,12 +1990,12 @@ var StateManager = class {
1476
1990
  * Save state file
1477
1991
  */
1478
1992
  saveState(state) {
1479
- const dir = path.dirname(this.statePath);
1480
- if (!fs12.existsSync(dir)) {
1481
- fs12.mkdirSync(dir, { recursive: true });
1993
+ const dir = path14.dirname(this.statePath);
1994
+ if (!fs14.existsSync(dir)) {
1995
+ fs14.mkdirSync(dir, { recursive: true });
1482
1996
  }
1483
1997
  state.lastSync = (/* @__PURE__ */ new Date()).toISOString();
1484
- fs12.writeFileSync(this.statePath, JSON.stringify(state, null, 2));
1998
+ fs14.writeFileSync(this.statePath, JSON.stringify(state, null, 2));
1485
1999
  }
1486
2000
  /**
1487
2001
  * Create empty state structure
@@ -1652,7 +2166,7 @@ var StateManager = class {
1652
2166
  /**
1653
2167
  * Update skill state (keyed by NAME)
1654
2168
  */
1655
- updateSkillState(name, id, content, skillResource) {
2169
+ updateSkillState(name, id, content, skillResource, companionFiles) {
1656
2170
  const state = this.loadState();
1657
2171
  if (!state.resources.skills) {
1658
2172
  state.resources.skills = {};
@@ -1661,7 +2175,13 @@ var StateManager = class {
1661
2175
  id,
1662
2176
  lastDeployed: (/* @__PURE__ */ new Date()).toISOString(),
1663
2177
  contentChecksum: calculateChecksum(content),
1664
- configChecksum: calculateSkillConfigChecksum(skillResource)
2178
+ configChecksum: calculateSkillConfigChecksum(skillResource),
2179
+ // Persisted for group selection (`deploy --replace-skill-group`) only. The group label stays out
2180
+ // of configChecksum on purpose, so relabelling a skill never marks it as changed.
2181
+ ...skillResource.group !== void 0 ? { group: skillResource.group } : {},
2182
+ // Only written when companionFiles is passed, so an older/companion-less entry has
2183
+ // neither key at all — the absence itself is what Tasks 10/11 read as "no companion files".
2184
+ ...companionFiles ? calculateCompanionFilesChecksum(companionFiles) : {}
1665
2185
  };
1666
2186
  this.saveState(state);
1667
2187
  }
@@ -2094,6 +2614,28 @@ async function createAssistantAndGetId(client, params, slug) {
2094
2614
  init_checksumUtils();
2095
2615
  init_codemieConfigChecksums();
2096
2616
  init_converters();
2617
+
2618
+ // src/lib/constants.ts
2619
+ var PAGINATION = {
2620
+ DEFAULT_PAGE_SIZE: 100};
2621
+ var TIMEOUTS_MS = {
2622
+ ASSISTANT_FETCH: 3e4,
2623
+ DATASOURCE_FETCH: 3e4,
2624
+ WORKFLOW_FETCH: 3e4,
2625
+ INTEGRATION_FETCH: 3e4,
2626
+ SKILL_FETCH: 3e4
2627
+ };
2628
+ var RATE_LIMITING = {
2629
+ MAX_CONCURRENT_REQUESTS: 5,
2630
+ RETRY_ATTEMPTS: 3,
2631
+ RETRY_DELAY_MS: 1e3
2632
+ };
2633
+ var BACKUP = {
2634
+ TEMP_DIR_PREFIX: ".temp-",
2635
+ TRANSACTION_SAVE_TIMEOUT_MS: 5e3
2636
+ };
2637
+
2638
+ // src/deploy.ts
2097
2639
  init_logger();
2098
2640
 
2099
2641
  // src/lib/resourceExistenceChecker.ts
@@ -2173,21 +2715,127 @@ function resolveSkillId(skillName, stateManager, config) {
2173
2715
  const importedSkill = findImportedSkill(config, skillName);
2174
2716
  if (configuredSkill && importedSkill) {
2175
2717
  throw new Error(
2176
- `Skill "${skillName}" is defined in both resources.skills and imported.skills. Keep project-owned skills in resources.skills or external skills in imported.skills, not both.`
2718
+ `Skill "${skillName}" is defined in both resources.skills and imported.skills. Keep project-owned skills in resources.skills or external skills in imported.skills, not both.`
2719
+ );
2720
+ }
2721
+ const skillId = lookupSkillId(skillName, stateManager, config);
2722
+ if (skillId) {
2723
+ const source = importedSkill ? "imported" : "state";
2724
+ logger.info(` \u2713 Resolved${source === "imported" ? " (imported)" : ""} "${skillName}" \u2192 ${skillId}`);
2725
+ return skillId;
2726
+ }
2727
+ throw new Error(
2728
+ `Skill "${skillName}" cannot be resolved. For project-owned skills, define it in resources.skills and deploy it so state.json contains its ID. For external skills, add name and id to imported.skills.`
2729
+ );
2730
+ }
2731
+ function resolveSkillIds(skillNames, stateManager, config) {
2732
+ return skillNames.map((name) => resolveSkillId(name, stateManager, config));
2733
+ }
2734
+
2735
+ // src/deploy.ts
2736
+ init_skillCompanionFiles();
2737
+
2738
+ // src/lib/skillReplacement.ts
2739
+ function getSkillNamesInGroup(skills, group) {
2740
+ return new Set((skills || []).filter((skill) => skill.group === group).map((skill) => skill.name));
2741
+ }
2742
+ function getSkillsInGroup(skills, group) {
2743
+ return (skills || []).filter((skill) => skill.group === group);
2744
+ }
2745
+ function collectSkillNamesForReplacement(skills, stateManager, group) {
2746
+ const groupSkillNames = getSkillNamesInGroup(skills, group);
2747
+ const namesToDelete = /* @__PURE__ */ new Set();
2748
+ for (const name of stateManager.getAllManagedResources().skills) {
2749
+ const state = stateManager.getSkillState(name);
2750
+ if (state?.group === group || groupSkillNames.has(name)) {
2751
+ namesToDelete.add(name);
2752
+ }
2753
+ }
2754
+ return [...namesToDelete].sort((left, right) => left.localeCompare(right));
2755
+ }
2756
+ function filterAssistantsReferencingSkillGroup(assistants, skills, group) {
2757
+ const skillNames = getSkillNamesInGroup(skills, group);
2758
+ if (skillNames.size === 0) {
2759
+ return [];
2760
+ }
2761
+ const groupNames = [...skillNames];
2762
+ return (assistants || []).filter(
2763
+ (assistant) => assistant.skills?.some((skillName) => groupNames.some((groupName) => namesEqual(groupName, skillName)))
2764
+ );
2765
+ }
2766
+ function expandAssistantsWithDependencies(selected, allAssistants) {
2767
+ const byName = new Map((allAssistants || []).map((assistant) => [assistant.name, assistant]));
2768
+ const result = [];
2769
+ const seen = /* @__PURE__ */ new Set();
2770
+ const visit = (assistant) => {
2771
+ if (seen.has(assistant.name)) {
2772
+ return;
2773
+ }
2774
+ seen.add(assistant.name);
2775
+ result.push(assistant);
2776
+ for (const subName of assistant.sub_assistants || []) {
2777
+ const subAssistant = byName.get(subName);
2778
+ if (subAssistant) {
2779
+ visit(subAssistant);
2780
+ }
2781
+ }
2782
+ };
2783
+ for (const assistant of selected) {
2784
+ visit(assistant);
2785
+ }
2786
+ return result;
2787
+ }
2788
+ function collectAssistantIdsForDetach(stateManager, config) {
2789
+ const ids = [];
2790
+ const seen = /* @__PURE__ */ new Set();
2791
+ const add = (id) => {
2792
+ if (id && !seen.has(id)) {
2793
+ seen.add(id);
2794
+ ids.push(id);
2795
+ }
2796
+ };
2797
+ for (const name of stateManager.getAllManagedResources().assistants) {
2798
+ add(stateManager.getIdByName("assistant", name));
2799
+ }
2800
+ for (const imported of config.imported?.assistants || []) {
2801
+ add(imported.id);
2802
+ }
2803
+ return ids;
2804
+ }
2805
+ function selectSkillGroupForReplacement(config, stateManager, group) {
2806
+ assertSkillGroupNotImported(config.imported?.skills, group);
2807
+ const namesToDelete = collectSkillNamesForReplacement(config.resources.skills, stateManager, group);
2808
+ const groupSkills = getSkillsInGroup(config.resources.skills, group);
2809
+ if (namesToDelete.length === 0 && groupSkills.length === 0) {
2810
+ throw new Error(
2811
+ `Skill group "${group}" matched no skills in state or in resources.skills. Group membership comes from the "group" field of a skill entry, never from its name.`
2177
2812
  );
2178
2813
  }
2179
- const skillId = lookupSkillId(skillName, stateManager, config);
2180
- if (skillId) {
2181
- const source = importedSkill ? "imported" : "state";
2182
- logger.info(` \u2713 Resolved${source === "imported" ? " (imported)" : ""} "${skillName}" \u2192 ${skillId}`);
2183
- return skillId;
2814
+ return { namesToDelete, groupSkills };
2815
+ }
2816
+ function assertSkillGroupNotImported(importedSkills, group) {
2817
+ const conflict = (importedSkills || []).find((skill) => namesEqual(skill.name, group));
2818
+ if (conflict) {
2819
+ throw new Error(
2820
+ `Skill group "${group}" matches an entry in imported.skills ("${conflict.name}"). Imported skills are platform-managed and are never deleted or recreated by IaC. Rename the group or remove the imported.skills entry.`
2821
+ );
2184
2822
  }
2185
- throw new Error(
2186
- `Skill "${skillName}" cannot be resolved. For project-owned skills, define it in resources.skills and deploy it so state.json contains its ID. For external skills, add name and id to imported.skills.`
2187
- );
2188
2823
  }
2189
- function resolveSkillIds(skillNames, stateManager, config) {
2190
- return skillNames.map((name) => resolveSkillId(name, stateManager, config));
2824
+
2825
+ // src/lib/timeoutUtils.ts
2826
+ async function withTimeout(promise, timeoutMs, operation) {
2827
+ let timeoutId;
2828
+ const timeoutPromise = new Promise((_, reject) => {
2829
+ timeoutId = setTimeout(() => reject(new Error(`Operation timeout: ${operation} (${timeoutMs}ms)`)), timeoutMs);
2830
+ timeoutId.unref();
2831
+ });
2832
+ try {
2833
+ return await Promise.race([promise, timeoutPromise]);
2834
+ } finally {
2835
+ if (timeoutId !== void 0) {
2836
+ clearTimeout(timeoutId);
2837
+ }
2838
+ }
2191
2839
  }
2192
2840
 
2193
2841
  // src/deploy.ts
@@ -2456,7 +3104,35 @@ async function deployAssistants(config, client, loader, stateManager) {
2456
3104
  }
2457
3105
  return stats;
2458
3106
  }
2459
- async function deploySkills(config, client, loader, stateManager) {
3107
+ function companionFilesForCreate(companionFiles) {
3108
+ return companionFiles.length > 0 ? { companion_files: companionFiles } : {};
3109
+ }
3110
+ function stateKnowsCompanionFiles(existingState) {
3111
+ return existingState?.companionFileHashes !== void 0;
3112
+ }
3113
+ async function companionFilesForUpdate(client, skillId, skillName, companionFiles, existingState) {
3114
+ if (companionFiles.length > 0) {
3115
+ return { companion_files: companionFiles };
3116
+ }
3117
+ if (stateKnowsCompanionFiles(existingState)) {
3118
+ return stateHasCompanionFiles(existingState) ? { companion_files: [] } : {};
3119
+ }
3120
+ let platformCompanionFiles;
3121
+ try {
3122
+ platformCompanionFiles = await withTimeout(
3123
+ client.skills.listCompanionFiles(skillId),
3124
+ TIMEOUTS_MS.SKILL_FETCH,
3125
+ `Timeout listing companion files for skill "${skillId}"`
3126
+ );
3127
+ } catch (error) {
3128
+ logger.warn(
3129
+ ` \u26A0\uFE0F Could not list companion files for skill "${skillName}": ${error instanceof Error ? error.message : String(error)}. Leaving any companion files on the platform untouched.`
3130
+ );
3131
+ return {};
3132
+ }
3133
+ return platformCompanionFiles.length > 0 ? { companion_files: [] } : {};
3134
+ }
3135
+ async function deploySkills(config, client, loader, stateManager, rootDir = process.cwd()) {
2460
3136
  const stats = { created: 0, updated: 0, unchanged: 0, failed: 0 };
2461
3137
  logger.info("\u{1F3AF} Processing skills...\n");
2462
3138
  if (!config.resources.skills) {
@@ -2466,15 +3142,18 @@ async function deploySkills(config, client, loader, stateManager) {
2466
3142
  for (const skill of config.resources.skills) {
2467
3143
  try {
2468
3144
  logger.info(`Processing: ${skill.name}`);
2469
- const content = loader.loadSkillContent(skill.file);
3145
+ const content = loader.resolveSkillContent(skill);
2470
3146
  const contentChecksum = calculateChecksum(content);
2471
3147
  const configChecksum = calculateSkillConfigChecksum(skill);
2472
3148
  const visibility = skill.visibility ?? "project";
3149
+ const companionFiles = hasCompanionFileLayout(skill) ? collectCompanionFiles(path14.dirname(path14.join(rootDir, skill.file))) : [];
3150
+ const { companionFilesChecksum } = calculateCompanionFilesChecksum(companionFiles);
2473
3151
  const existingState = stateManager.getSkillState(skill.name);
2474
3152
  if (existingState) {
2475
3153
  const existsOnPlatform = await checkSkillExists(client, skill.name, stateManager);
2476
3154
  if (existsOnPlatform) {
2477
- const hasChanged = existingState.contentChecksum !== contentChecksum || existingState.configChecksum !== configChecksum;
3155
+ const companionFilesChanged = companionFiles.length > 0 || stateHasCompanionFiles(existingState) ? existingState.companionFilesChecksum !== companionFilesChecksum : false;
3156
+ const hasChanged = existingState.contentChecksum !== contentChecksum || existingState.configChecksum !== configChecksum || companionFilesChanged;
2478
3157
  if (hasChanged) {
2479
3158
  logger.info(` Updating skill (ID: ${existingState.id})...`);
2480
3159
  if (process.env.DEBUG_API) {
@@ -2492,10 +3171,12 @@ async function deploySkills(config, client, loader, stateManager) {
2492
3171
  name: skill.name,
2493
3172
  description: skill.description,
2494
3173
  content,
2495
- categories: skill.categories
3174
+ visibility,
3175
+ categories: skill.categories,
3176
+ ...await companionFilesForUpdate(client, existingState.id, skill.name, companionFiles, existingState)
2496
3177
  });
2497
3178
  logger.info(`\u2713 Updated skill: ${skill.name} (${existingState.id})`);
2498
- stateManager.updateSkillState(skill.name, existingState.id, content, skill);
3179
+ stateManager.updateSkillState(skill.name, existingState.id, content, skill, companionFiles);
2499
3180
  stats.updated++;
2500
3181
  } else {
2501
3182
  logger.info(` \u2713 No changes detected (ID: ${existingState.id})`);
@@ -2510,11 +3191,12 @@ async function deploySkills(config, client, loader, stateManager) {
2510
3191
  content,
2511
3192
  project: config.project.name,
2512
3193
  visibility,
2513
- categories: skill.categories
3194
+ categories: skill.categories,
3195
+ ...companionFilesForCreate(companionFiles)
2514
3196
  });
2515
3197
  logger.info(`\u2713 Created skill: ${skill.name} (${result.id})`);
2516
3198
  skillIndex.record(skill.name, result.id);
2517
- stateManager.updateSkillState(skill.name, result.id, content, skill);
3199
+ stateManager.updateSkillState(skill.name, result.id, content, skill, companionFiles);
2518
3200
  stats.created++;
2519
3201
  }
2520
3202
  } else {
@@ -2538,7 +3220,8 @@ async function deploySkills(config, client, loader, stateManager) {
2538
3220
  content,
2539
3221
  project: config.project.name,
2540
3222
  visibility,
2541
- categories: skill.categories
3223
+ categories: skill.categories,
3224
+ ...companionFilesForCreate(companionFiles)
2542
3225
  });
2543
3226
  skillId = result.id;
2544
3227
  logger.info(`\u2713 Created skill: ${skill.name} (${skillId})`);
@@ -2559,13 +3242,15 @@ async function deploySkills(config, client, loader, stateManager) {
2559
3242
  name: skill.name,
2560
3243
  description: skill.description,
2561
3244
  content,
2562
- categories: skill.categories
3245
+ visibility,
3246
+ categories: skill.categories,
3247
+ ...await companionFilesForUpdate(client, existingId, skill.name, companionFiles, void 0)
2563
3248
  });
2564
3249
  skillId = existingId;
2565
3250
  logger.info(`\u2713 Recovered and updated skill: ${skill.name} (${skillId})`);
2566
3251
  stats.updated++;
2567
3252
  }
2568
- stateManager.updateSkillState(skill.name, skillId, content, skill);
3253
+ stateManager.updateSkillState(skill.name, skillId, content, skill, companionFiles);
2569
3254
  }
2570
3255
  logger.info("");
2571
3256
  } catch (error) {
@@ -2686,12 +3371,12 @@ async function deployWorkflows(config, client, stateManager, rootDir = process.c
2686
3371
  for (const workflow of config.resources.workflows) {
2687
3372
  try {
2688
3373
  logger.info(`Processing: ${workflow.name}`);
2689
- const yamlPath = path.join(rootDir, workflow.definition);
2690
- if (!fs12.existsSync(yamlPath)) {
3374
+ const yamlPath = path14.join(rootDir, workflow.definition);
3375
+ if (!fs14.existsSync(yamlPath)) {
2691
3376
  throw new Error(`Workflow definition file not found: ${workflow.definition}`);
2692
3377
  }
2693
- const yamlConfigContent = fs12.readFileSync(yamlPath, "utf8");
2694
- const workflowYaml = yaml7.parse(yamlConfigContent);
3378
+ const yamlConfigContent = fs14.readFileSync(yamlPath, "utf8");
3379
+ const workflowYaml = yaml8.parse(yamlConfigContent);
2695
3380
  const referencesToResolve = [];
2696
3381
  for (const assistant of workflowYaml.assistants ?? []) {
2697
3382
  const isInline = !assistant.assistant_name && assistant.model && assistant.system_prompt;
@@ -2732,7 +3417,7 @@ async function deployWorkflows(config, client, stateManager, rootDir = process.c
2732
3417
  });
2733
3418
  }
2734
3419
  }
2735
- const yamlConfig = yaml7.stringify(workflowYaml);
3420
+ const yamlConfig = yaml8.stringify(workflowYaml);
2736
3421
  const workflowYamlChecksum = calculateChecksum(yamlConfigContent);
2737
3422
  const configChecksum = calculateWorkflowConfigChecksum(workflow);
2738
3423
  const existingState = stateManager.getWorkflowState(workflow.name);
@@ -2809,19 +3494,168 @@ async function deployWorkflows(config, client, stateManager, rootDir = process.c
2809
3494
  }
2810
3495
  return stats;
2811
3496
  }
3497
+ function isAlreadyGoneError(error) {
3498
+ const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
3499
+ return message.includes("404") || message.includes("not found") || message.includes("not attached");
3500
+ }
3501
+ async function detachSkillsBeforeDelete(client, assistantIds, skills, group) {
3502
+ if (skills.length === 0 || assistantIds.length === 0) {
3503
+ return;
3504
+ }
3505
+ const targetIds = new Set(skills.map((skill) => skill.id));
3506
+ logger.info(`\u{1F517} Detaching ${skills.length} skill(s) from ${assistantIds.length} assistant(s)...`);
3507
+ for (const assistantId of assistantIds) {
3508
+ let attachedTargetIds;
3509
+ try {
3510
+ const currentSkills = await client.skills.getAssistantSkills(assistantId);
3511
+ attachedTargetIds = currentSkills.map((skill) => skill.id).filter((id) => targetIds.has(id));
3512
+ } catch (fetchError) {
3513
+ logger.warn(` \u26A0\uFE0F Could not list skills of assistant ${assistantId}, attempting every detach instead`);
3514
+ logger.debug(` ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`);
3515
+ attachedTargetIds = [...targetIds];
3516
+ }
3517
+ for (const skillId of attachedTargetIds) {
3518
+ try {
3519
+ await client.skills.detachFromAssistant(assistantId, skillId);
3520
+ logger.info(` \u2713 Detached skill ${skillId} from assistant ${assistantId}`);
3521
+ } catch (detachError) {
3522
+ if (isAlreadyGoneError(detachError)) {
3523
+ logger.info(` \u2713 Skill ${skillId} already detached from assistant ${assistantId}`);
3524
+ continue;
3525
+ }
3526
+ const message = detachError instanceof Error ? detachError.message : String(detachError);
3527
+ throw new Error(
3528
+ `Failed to detach skill ${skillId} from assistant ${assistantId} while replacing skill group "${group}": ${message}. Nothing was deleted.`
3529
+ );
3530
+ }
3531
+ }
3532
+ }
3533
+ logger.info("");
3534
+ }
3535
+ async function deleteSkillsForReplacement(client, stateManager, skills, group) {
3536
+ let deleted = 0;
3537
+ for (const { name, id } of skills) {
3538
+ try {
3539
+ await client.skills.delete(id);
3540
+ logger.info(` \u{1F5D1}\uFE0F Deleted skill: ${name} (${id})`);
3541
+ deleted++;
3542
+ } catch (deleteError) {
3543
+ if (isAlreadyGoneError(deleteError)) {
3544
+ logger.warn(` \u26A0\uFE0F Skill ${name} (${id}) not found on platform (already deleted) - removing from state`);
3545
+ } else {
3546
+ const message = deleteError instanceof Error ? deleteError.message : String(deleteError);
3547
+ throw new Error(
3548
+ `Failed to delete skill "${name}" (${id}) while replacing skill group "${group}": ${message}. No skills were recreated; rerun the command once the platform error is resolved.`
3549
+ );
3550
+ }
3551
+ }
3552
+ stateManager.deleteSkillState(name);
3553
+ }
3554
+ logger.info("");
3555
+ return deleted;
3556
+ }
3557
+ async function replaceSkillGroupResources(config, client, loader, stateManager, group, rootDir = process.cwd()) {
3558
+ const { namesToDelete, groupSkills } = selectSkillGroupForReplacement(config, stateManager, group);
3559
+ logger.info(`\u267B\uFE0F Replacing skill group "${group}"...
3560
+ `);
3561
+ logger.info(` ${namesToDelete.length} skill(s) to delete, ${groupSkills.length} skill(s) to recreate
3562
+ `);
3563
+ const skillsToDelete = namesToDelete.map((name) => ({ name, id: stateManager.getIdByName("skill", name) })).filter((entry) => Boolean(entry.id));
3564
+ await detachSkillsBeforeDelete(client, collectAssistantIdsForDetach(stateManager, config), skillsToDelete, group);
3565
+ const deleted = await deleteSkillsForReplacement(client, stateManager, skillsToDelete, group);
3566
+ const skillStats = await deploySkills(
3567
+ {
3568
+ ...config,
3569
+ resources: { ...config.resources, skills: groupSkills, assistants: [], workflows: [] }
3570
+ },
3571
+ client,
3572
+ loader,
3573
+ stateManager,
3574
+ rootDir
3575
+ );
3576
+ const referencingAssistants = expandAssistantsWithDependencies(
3577
+ filterAssistantsReferencingSkillGroup(config.resources.assistants, config.resources.skills, group),
3578
+ config.resources.assistants
3579
+ );
3580
+ logger.info(` ${referencingAssistants.length} assistant(s) reference the replaced skill group
3581
+ `);
3582
+ const assistantStats = await deployAssistants(
3583
+ {
3584
+ ...config,
3585
+ resources: { ...config.resources, assistants: referencingAssistants, workflows: [] }
3586
+ },
3587
+ client,
3588
+ loader,
3589
+ stateManager
3590
+ );
3591
+ return {
3592
+ deleted,
3593
+ stats: {
3594
+ created: skillStats.created + assistantStats.created,
3595
+ updated: skillStats.updated + assistantStats.updated,
3596
+ unchanged: skillStats.unchanged + assistantStats.unchanged,
3597
+ failed: skillStats.failed + assistantStats.failed
3598
+ }
3599
+ };
3600
+ }
3601
+ function logDeploymentSummary(stats, deleted) {
3602
+ logger.info("=".repeat(50));
3603
+ logger.info("\u{1F4CA} Deployment Summary:\n");
3604
+ logger.info(` \u2705 Created: ${stats.created}`);
3605
+ logger.info(` \u{1F504} Updated: ${stats.updated}`);
3606
+ logger.info(` \u{1F4CB} Unchanged: ${stats.unchanged}`);
3607
+ if (deleted > 0) {
3608
+ logger.info(` \u{1F5D1}\uFE0F Deleted: ${deleted}`);
3609
+ }
3610
+ if (stats.failed > 0) {
3611
+ logger.info(` \u274C Failed: ${stats.failed}`);
3612
+ }
3613
+ logger.info("");
3614
+ }
2812
3615
  async function deployResources(options) {
2813
3616
  logger.info("\u{1F680} Deploying resources to Codemie...\n");
2814
3617
  try {
2815
- const { appConfig, prune = false, skipDatasources = false } = options;
3618
+ const { appConfig, prune = false, skipDatasources = false, replaceSkillGroup, yesReplaceSkills = false } = options;
3619
+ if (replaceSkillGroup && !yesReplaceSkills) {
3620
+ throw new Error(
3621
+ `Refusing to replace skill group "${replaceSkillGroup}" without --yes-replace-skills. Replacing a group deletes its skills and recreates them with new ids; nothing was touched.`
3622
+ );
3623
+ }
2816
3624
  const loader = new CodemieConfigLoader(appConfig);
2817
3625
  const stateManager = new StateManager(appConfig);
2818
3626
  logger.info("\u{1F4C4} Loading configuration...");
2819
3627
  const config = loader.loadConfig();
2820
3628
  logger.info(`\u2713 Loaded config for project: ${config.project.name}
2821
3629
  `);
3630
+ const skillDescriptionErrors = validateSkillDescriptions(config.resources.skills ?? []);
3631
+ if (skillDescriptionErrors.length > 0) {
3632
+ throw new Error(skillDescriptionErrors.join("\n"));
3633
+ }
2822
3634
  logger.info("\u{1F50C} Connecting to Codemie API...");
2823
3635
  const client = await createClient(config);
2824
3636
  logger.info("\u2713 Connected to Codemie API\n");
3637
+ if (replaceSkillGroup) {
3638
+ if (prune) {
3639
+ logger.info("\u26A0\uFE0F --prune is ignored with --replace-skill-group\n");
3640
+ }
3641
+ if (skipDatasources) {
3642
+ logger.info("\u2139\uFE0F Datasources are skipped by --replace-skill-group anyway\n");
3643
+ }
3644
+ const replacement = await replaceSkillGroupResources(
3645
+ config,
3646
+ client,
3647
+ loader,
3648
+ stateManager,
3649
+ replaceSkillGroup,
3650
+ appConfig.rootDir
3651
+ );
3652
+ logDeploymentSummary(replacement.stats, replacement.deleted);
3653
+ if (replacement.stats.failed > 0) {
3654
+ throw new Error("Deployment completed with errors");
3655
+ }
3656
+ logger.info("\u2705 Deployment successful!");
3657
+ return;
3658
+ }
2825
3659
  logger.info("\u{1F9F9} Checking for orphaned resources...");
2826
3660
  const cleanupManager = new CleanupManager(client, stateManager);
2827
3661
  const foundOrphaned = cleanupManager.findOrphanedResources(config);
@@ -2880,7 +3714,7 @@ async function deployResources(options) {
2880
3714
  unchanged += datasourceStats.unchanged;
2881
3715
  failed += datasourceStats.failed;
2882
3716
  }
2883
- const skillStats = await deploySkills(config, client, loader, stateManager);
3717
+ const skillStats = await deploySkills(config, client, loader, stateManager, appConfig.rootDir);
2884
3718
  created += skillStats.created;
2885
3719
  updated += skillStats.updated;
2886
3720
  unchanged += skillStats.unchanged;
@@ -2910,18 +3744,7 @@ async function deployResources(options) {
2910
3744
  `);
2911
3745
  }
2912
3746
  }
2913
- logger.info("=".repeat(50));
2914
- logger.info("\u{1F4CA} Deployment Summary:\n");
2915
- logger.info(` \u2705 Created: ${created}`);
2916
- logger.info(` \u{1F504} Updated: ${updated}`);
2917
- logger.info(` \u{1F4CB} Unchanged: ${unchanged}`);
2918
- if (deleted > 0) {
2919
- logger.info(` \u{1F5D1}\uFE0F Deleted: ${deleted}`);
2920
- }
2921
- if (failed > 0) {
2922
- logger.info(` \u274C Failed: ${failed}`);
2923
- }
2924
- logger.info("");
3747
+ logDeploymentSummary({ created, updated, unchanged, failed }, deleted);
2925
3748
  if (failed > 0) {
2926
3749
  throw new Error("Deployment completed with errors");
2927
3750
  } else {
@@ -2956,10 +3779,10 @@ var DependencyValidator = class {
2956
3779
  const errors = [];
2957
3780
  const visited = /* @__PURE__ */ new Set();
2958
3781
  const recursionStack = /* @__PURE__ */ new Set();
2959
- const dfs = (name, path13) => {
3782
+ const dfs = (name, path15) => {
2960
3783
  if (recursionStack.has(name)) {
2961
- const cycleStart = path13.indexOf(name);
2962
- const cycle = [...path13.slice(cycleStart), name];
3784
+ const cycleStart = path15.indexOf(name);
3785
+ const cycle = [...path15.slice(cycleStart), name];
2963
3786
  errors.push(`Cyclic dependency detected: ${cycle.join(" \u2192 ")}`);
2964
3787
  return true;
2965
3788
  }
@@ -2968,14 +3791,14 @@ var DependencyValidator = class {
2968
3791
  }
2969
3792
  visited.add(name);
2970
3793
  recursionStack.add(name);
2971
- path13.push(name);
3794
+ path15.push(name);
2972
3795
  const assistant = assistantMap.get(name);
2973
3796
  const subAssistantRefs = assistant?.sub_assistants || [];
2974
3797
  for (const subRef of subAssistantRefs) {
2975
3798
  if (!assistantMap.has(subRef)) {
2976
3799
  continue;
2977
3800
  }
2978
- if (dfs(subRef, [...path13])) {
3801
+ if (dfs(subRef, [...path15])) {
2979
3802
  return true;
2980
3803
  }
2981
3804
  }
@@ -3034,7 +3857,7 @@ var DependencyValidator = class {
3034
3857
  }
3035
3858
  for (const workflow of workflows) {
3036
3859
  try {
3037
- const workflowYaml = yaml7.parse(workflow.definition);
3860
+ const workflowYaml = yaml8.parse(workflow.definition);
3038
3861
  if (!workflowYaml.assistants) {
3039
3862
  continue;
3040
3863
  }
@@ -3086,71 +3909,6 @@ var DependencyValidator = class {
3086
3909
 
3087
3910
  // src/validate.ts
3088
3911
  init_logger();
3089
-
3090
- // src/lib/validationUtils.ts
3091
- function isAssistantWithSlug(obj) {
3092
- return typeof obj === "object" && obj !== null && "slug" in obj && "name" in obj && typeof obj.slug === "string" && typeof obj.name === "string";
3093
- }
3094
- function isAssistant(obj) {
3095
- return typeof obj === "object" && obj !== null && "id" in obj && "slug" in obj;
3096
- }
3097
- function validateSlugUniqueness(config) {
3098
- const slugErrors = [];
3099
- const slugMap = /* @__PURE__ */ new Map();
3100
- if (config.resources.assistants) {
3101
- for (const assistant of config.resources.assistants) {
3102
- if (assistant.slug) {
3103
- if (!slugMap.has(assistant.slug)) {
3104
- slugMap.set(assistant.slug, []);
3105
- }
3106
- slugMap.get(assistant.slug).push(assistant.name);
3107
- }
3108
- }
3109
- }
3110
- for (const [slug, names] of slugMap.entries()) {
3111
- if (names.length > 1) {
3112
- slugErrors.push(`Duplicate slug "${slug}" for assistants: ${names.join(", ")}`);
3113
- }
3114
- }
3115
- return slugErrors;
3116
- }
3117
- async function checkApiSlugConflicts({
3118
- config,
3119
- client,
3120
- assistantState
3121
- }) {
3122
- const existingAssistants = await client.assistants.list({
3123
- minimal_response: false,
3124
- per_page: 100
3125
- });
3126
- const existingSlugs = /* @__PURE__ */ new Map();
3127
- for (const assistant of existingAssistants) {
3128
- if (isAssistantWithSlug(assistant) && assistant.slug) {
3129
- existingSlugs.set(assistant.slug, assistant.name);
3130
- }
3131
- }
3132
- const conflictErrors = [];
3133
- const iacAssistantNames = new Set(Object.keys(assistantState));
3134
- if (config.resources.assistants) {
3135
- for (const assistant of config.resources.assistants) {
3136
- if (!assistant.slug || iacAssistantNames.has(assistant.name)) {
3137
- continue;
3138
- }
3139
- if (existingSlugs.has(assistant.slug)) {
3140
- const existingName = existingSlugs.get(assistant.slug);
3141
- const existingAssistant = existingAssistants.find((a) => isAssistant(a) && a.slug === assistant.slug);
3142
- conflictErrors.push(
3143
- `\u274C Slug "${assistant.slug}" for assistant "${assistant.name}" already exists in Codemie
3144
- Existing assistant: "${existingName}" (ID: ${isAssistant(existingAssistant) ? existingAssistant.id : "unknown"})
3145
- \u{1F4A1} Change slug to a unique value or omit slug (platform will generate)`
3146
- );
3147
- }
3148
- }
3149
- }
3150
- return conflictErrors;
3151
- }
3152
-
3153
- // src/validate.ts
3154
3912
  async function validateConfig(options) {
3155
3913
  const errors = [];
3156
3914
  const { checkApi = false, appConfig } = options;
@@ -3174,12 +3932,12 @@ async function validateConfig(options) {
3174
3932
  }
3175
3933
  if (config.resources.workflows && config.resources.workflows.length > 0) {
3176
3934
  const workflowsWithContent = config.resources.workflows.map((workflow) => {
3177
- const workflowPath = path.resolve(workflow.definition);
3178
- if (!fs12.existsSync(workflowPath)) {
3935
+ const workflowPath = path14.resolve(workflow.definition);
3936
+ if (!fs14.existsSync(workflowPath)) {
3179
3937
  errors.push(`Workflow definition file not found: ${workflow.definition}`);
3180
3938
  return { ...workflow, definition: "" };
3181
3939
  }
3182
- const definition = fs12.readFileSync(workflowPath, "utf8");
3940
+ const definition = fs14.readFileSync(workflowPath, "utf8");
3183
3941
  return { ...workflow, definition };
3184
3942
  });
3185
3943
  const workflowErrors = DependencyValidator.validateWorkflowAssistantReferences(
@@ -3195,6 +3953,16 @@ async function validateConfig(options) {
3195
3953
  const state = stateManager.loadState();
3196
3954
  const conflictErrors = await checkApiSlugConflicts({ config, client, assistantState: state.resources.assistants });
3197
3955
  errors.push(...conflictErrors);
3956
+ const skills = config.resources.skills ?? [];
3957
+ if (skills.length > 0) {
3958
+ const limits = await client.skills.getConfig();
3959
+ const entries = skills.map((skill) => ({
3960
+ name: skill.name,
3961
+ content: loader.resolveSkillContent(skill)
3962
+ }));
3963
+ const contentLengthErrors = validateSkillContentLengths(entries, limits);
3964
+ errors.push(...contentLengthErrors);
3965
+ }
3198
3966
  }
3199
3967
  return { success: errors.length === 0, errors };
3200
3968
  }
@@ -3204,6 +3972,7 @@ init_logger();
3204
3972
  init_checksumUtils();
3205
3973
  init_codemieConfigChecksums();
3206
3974
  init_converters();
3975
+ init_skillCompanionFiles();
3207
3976
  async function previewResource(resource, resourceType, getState, checkExists, calculateChecksums, staleDetails) {
3208
3977
  const existingState = getState(resource.name);
3209
3978
  if (existingState) {
@@ -3278,12 +4047,67 @@ function previewOrphanedResources(orphaned, stateManager) {
3278
4047
  }
3279
4048
  return changes;
3280
4049
  }
3281
- async function previewSkills(skills, loader, stateManager, client) {
4050
+ function previewSkillGroupReplacement(config, stateManager, group) {
4051
+ const { namesToDelete, groupSkills } = selectSkillGroupForReplacement(config, stateManager, group);
4052
+ const changes = [];
4053
+ for (const name of namesToDelete) {
4054
+ const skillState = stateManager.getSkillState(name);
4055
+ changes.push({
4056
+ type: "delete",
4057
+ resourceType: "skill",
4058
+ name,
4059
+ details: skillState ? `Replacing skill group "${group}" (ID: ${skillState.id})` : `Replacing skill group "${group}"`
4060
+ });
4061
+ }
4062
+ for (const skill of groupSkills) {
4063
+ changes.push({
4064
+ type: "create",
4065
+ resourceType: "skill",
4066
+ name: skill.name,
4067
+ details: `Recreated by --replace-skill-group "${group}" with a new platform id`
4068
+ });
4069
+ }
4070
+ return changes;
4071
+ }
4072
+ function describeCompanionFileChanges(currentHashes, previousHashes) {
4073
+ const added = [];
4074
+ const removed = [];
4075
+ const modified = [];
4076
+ const allPaths = /* @__PURE__ */ new Set([...Object.keys(currentHashes), ...Object.keys(previousHashes)]);
4077
+ for (const filePath of allPaths) {
4078
+ const inCurrent = Object.hasOwn(currentHashes, filePath);
4079
+ const inPrevious = Object.hasOwn(previousHashes, filePath);
4080
+ if (inCurrent && !inPrevious) {
4081
+ added.push(filePath);
4082
+ } else if (!inCurrent && inPrevious) {
4083
+ removed.push(filePath);
4084
+ } else if (currentHashes[filePath] !== previousHashes[filePath]) {
4085
+ modified.push(filePath);
4086
+ }
4087
+ }
4088
+ added.sort();
4089
+ removed.sort();
4090
+ modified.sort();
4091
+ const segments = [];
4092
+ if (added.length > 0) {
4093
+ segments.push(`added ${added.join(", ")}`);
4094
+ }
4095
+ if (removed.length > 0) {
4096
+ segments.push(`removed ${removed.join(", ")}`);
4097
+ }
4098
+ if (modified.length > 0) {
4099
+ segments.push(`modified ${modified.join(", ")}`);
4100
+ }
4101
+ return `Companion files changed: ${segments.join("; ")}`;
4102
+ }
4103
+ async function previewSkills(skills, loader, stateManager, client, rootDir = process.cwd()) {
3282
4104
  const changes = [];
3283
4105
  for (const skill of skills) {
3284
- const content = loader.loadSkillContent(skill.file);
4106
+ const content = loader.resolveSkillContent(skill);
3285
4107
  const contentChecksum = calculateChecksum(content);
3286
4108
  const configChecksum = calculateSkillConfigChecksum(skill);
4109
+ const companionFiles = hasCompanionFileLayout(skill) ? collectCompanionFiles(path14.dirname(path14.join(rootDir, skill.file))) : [];
4110
+ const { companionFilesChecksum, companionFileHashes } = calculateCompanionFilesChecksum(companionFiles);
3287
4111
  const change = await previewResource(
3288
4112
  skill,
3289
4113
  "skill",
@@ -3291,10 +4115,22 @@ async function previewSkills(skills, loader, stateManager, client) {
3291
4115
  () => checkSkillExists(client, skill.name, stateManager),
3292
4116
  () => {
3293
4117
  const existingState = stateManager.getSkillState(skill.name);
3294
- const hasChanged = existingState ? existingState.contentChecksum !== contentChecksum || existingState.configChecksum !== configChecksum : false;
4118
+ if (!existingState) {
4119
+ return { hasChanged: false };
4120
+ }
4121
+ const contentOrConfigChanged = existingState.contentChecksum !== contentChecksum || existingState.configChecksum !== configChecksum;
4122
+ const companionFilesChanged = companionFiles.length > 0 || stateHasCompanionFiles(existingState) ? existingState.companionFilesChecksum !== companionFilesChecksum : false;
4123
+ const hasChanged = contentOrConfigChanged || companionFilesChanged;
4124
+ const detailParts = [];
4125
+ if (contentOrConfigChanged) {
4126
+ detailParts.push("Content or configuration changed");
4127
+ }
4128
+ if (companionFilesChanged) {
4129
+ detailParts.push(describeCompanionFileChanges(companionFileHashes, existingState.companionFileHashes ?? {}));
4130
+ }
3295
4131
  return {
3296
4132
  hasChanged,
3297
- updateDetails: "Content or configuration changed"
4133
+ updateDetails: detailParts.length > 0 ? detailParts.join("; ") : void 0
3298
4134
  };
3299
4135
  }
3300
4136
  );
@@ -3429,11 +4265,11 @@ async function previewWorkflows(workflows, stateManager, client, rootDir = proce
3429
4265
  const projectClause = project ? ` in project ${project}` : "";
3430
4266
  const staleDetails = `ID from state not found; will adopt a same-name workflow${projectClause} if one exists, otherwise create`;
3431
4267
  for (const workflow of workflows) {
3432
- const yamlPath = path.join(rootDir, workflow.definition);
3433
- if (!fs12.existsSync(yamlPath)) {
4268
+ const yamlPath = path14.join(rootDir, workflow.definition);
4269
+ if (!fs14.existsSync(yamlPath)) {
3434
4270
  throw new Error(`Workflow definition file not found: ${workflow.definition}`);
3435
4271
  }
3436
- const yamlConfig = fs12.readFileSync(yamlPath, "utf8");
4272
+ const yamlConfig = fs14.readFileSync(yamlPath, "utf8");
3437
4273
  const change = await previewResource(
3438
4274
  workflow,
3439
4275
  "workflow",
@@ -3464,15 +4300,31 @@ async function previewChanges(appConfig, existingClient, options) {
3464
4300
  const loader = new CodemieConfigLoader(appConfig);
3465
4301
  const stateManager = new StateManager(appConfig);
3466
4302
  const config = loader.loadConfig();
4303
+ const skillDescriptionErrors = validateSkillDescriptions(config.resources.skills ?? []);
4304
+ if (skillDescriptionErrors.length > 0) {
4305
+ throw new Error(skillDescriptionErrors.join("\n"));
4306
+ }
3467
4307
  const client = existingClient || await createClient(config);
3468
4308
  const changes = [];
4309
+ if (options?.replaceSkillGroup) {
4310
+ const group = options.replaceSkillGroup;
4311
+ changes.push(...previewSkillGroupReplacement(config, stateManager, group));
4312
+ const referencingAssistants = expandAssistantsWithDependencies(
4313
+ filterAssistantsReferencingSkillGroup(config.resources.assistants, config.resources.skills, group),
4314
+ config.resources.assistants
4315
+ );
4316
+ if (referencingAssistants.length > 0) {
4317
+ changes.push(...await previewAssistants(referencingAssistants, loader, stateManager, client, config));
4318
+ }
4319
+ return summarizeChanges(changes);
4320
+ }
3469
4321
  const cleanupManager = new CleanupManager(client, stateManager);
3470
4322
  const skipDatasources = options?.skipDatasources === true;
3471
4323
  const foundOrphaned = cleanupManager.findOrphanedResources(config);
3472
4324
  const orphaned = skipDatasources ? { ...foundOrphaned, datasources: [] } : foundOrphaned;
3473
4325
  changes.push(...previewOrphanedResources(orphaned, stateManager));
3474
4326
  if (config.resources.skills) {
3475
- const skillChanges = await previewSkills(config.resources.skills, loader, stateManager, client);
4327
+ const skillChanges = await previewSkills(config.resources.skills, loader, stateManager, client, appConfig.rootDir);
3476
4328
  changes.push(...skillChanges);
3477
4329
  }
3478
4330
  if (config.resources.assistants) {
@@ -3493,17 +4345,16 @@ async function previewChanges(appConfig, existingClient, options) {
3493
4345
  );
3494
4346
  changes.push(...workflowChanges);
3495
4347
  }
3496
- const toDelete = changes.filter((c) => c.type === "delete");
3497
- const toCreate = changes.filter((c) => c.type === "create");
3498
- const toUpdate = changes.filter((c) => c.type === "update");
3499
- const unchanged = changes.filter((c) => c.type === "no-change");
4348
+ return summarizeChanges(changes);
4349
+ }
4350
+ function summarizeChanges(changes) {
3500
4351
  return {
3501
4352
  changes,
3502
4353
  summary: {
3503
- deleted: toDelete.length,
3504
- created: toCreate.length,
3505
- updated: toUpdate.length,
3506
- unchanged: unchanged.length,
4354
+ deleted: changes.filter((c) => c.type === "delete").length,
4355
+ created: changes.filter((c) => c.type === "create").length,
4356
+ updated: changes.filter((c) => c.type === "update").length,
4357
+ unchanged: changes.filter((c) => c.type === "no-change").length,
3507
4358
  total: changes.length
3508
4359
  }
3509
4360
  };
@@ -3512,28 +4363,6 @@ async function previewChanges(appConfig, existingClient, options) {
3512
4363
  // src/backup.ts
3513
4364
  init_backupTransformers();
3514
4365
  init_skillUtils();
3515
-
3516
- // src/lib/constants.ts
3517
- var PAGINATION = {
3518
- DEFAULT_PAGE_SIZE: 100};
3519
- var TIMEOUTS_MS = {
3520
- ASSISTANT_FETCH: 3e4,
3521
- DATASOURCE_FETCH: 3e4,
3522
- WORKFLOW_FETCH: 3e4,
3523
- INTEGRATION_FETCH: 3e4,
3524
- SKILL_FETCH: 3e4
3525
- };
3526
- var RATE_LIMITING = {
3527
- MAX_CONCURRENT_REQUESTS: 5,
3528
- RETRY_ATTEMPTS: 3,
3529
- RETRY_DELAY_MS: 1e3
3530
- };
3531
- var BACKUP = {
3532
- TEMP_DIR_PREFIX: ".temp-",
3533
- TRANSACTION_SAVE_TIMEOUT_MS: 5e3
3534
- };
3535
-
3536
- // src/lib/backupTransaction.ts
3537
4366
  init_fileUtils();
3538
4367
  init_logger();
3539
4368
  function busyWaitDelay(ms) {
@@ -3544,9 +4373,9 @@ var BackupTransaction = class {
3544
4373
  isDirty = false;
3545
4374
  saveTimer;
3546
4375
  constructor(backupDir, transactionId) {
3547
- this.transactionPath = path.join(backupDir, "transaction.json");
4376
+ this.transactionPath = path14.join(backupDir, "transaction.json");
3548
4377
  try {
3549
- const content = fs12.readFileSync(this.transactionPath, "utf8");
4378
+ const content = fs14.readFileSync(this.transactionPath, "utf8");
3550
4379
  this.data = JSON.parse(content);
3551
4380
  logger.info(`\u{1F4C2} Resuming backup transaction ${this.data.id}`);
3552
4381
  } catch (error) {
@@ -3578,9 +4407,9 @@ var BackupTransaction = class {
3578
4407
  }
3579
4408
  writeTransactionExclusively(data) {
3580
4409
  try {
3581
- const fd = fs12.openSync(this.transactionPath, "wx");
3582
- fs12.writeSync(fd, JSON.stringify(data, null, 2));
3583
- fs12.closeSync(fd);
4410
+ const fd = fs14.openSync(this.transactionPath, "wx");
4411
+ fs14.writeSync(fd, JSON.stringify(data, null, 2));
4412
+ fs14.closeSync(fd);
3584
4413
  } catch (writeError) {
3585
4414
  const writeErr = writeError;
3586
4415
  if (writeErr.code === "EEXIST") {
@@ -3599,7 +4428,7 @@ var BackupTransaction = class {
3599
4428
  if (delayMs > 0) {
3600
4429
  busyWaitDelay(delayMs);
3601
4430
  }
3602
- const content = fs12.readFileSync(this.transactionPath, "utf8");
4431
+ const content = fs14.readFileSync(this.transactionPath, "utf8");
3603
4432
  this.data = JSON.parse(content);
3604
4433
  logger.info(`\u{1F4C2} Resuming backup transaction ${this.data.id} (created by concurrent process)`);
3605
4434
  break;
@@ -3622,7 +4451,7 @@ var BackupTransaction = class {
3622
4451
  */
3623
4452
  async save() {
3624
4453
  ensureDirectoryExists(this.transactionPath);
3625
- const savePromise = fs12.promises.writeFile(this.transactionPath, JSON.stringify(this.data, null, 2), "utf8");
4454
+ const savePromise = fs14.promises.writeFile(this.transactionPath, JSON.stringify(this.data, null, 2), "utf8");
3626
4455
  let timeoutId;
3627
4456
  const timeoutPromise = new Promise((_, reject) => {
3628
4457
  timeoutId = setTimeout(
@@ -3648,7 +4477,7 @@ var BackupTransaction = class {
3648
4477
  */
3649
4478
  saveSyncInternal() {
3650
4479
  ensureDirectoryExists(this.transactionPath);
3651
- fs12.writeFileSync(this.transactionPath, JSON.stringify(this.data, null, 2), "utf8");
4480
+ fs14.writeFileSync(this.transactionPath, JSON.stringify(this.data, null, 2), "utf8");
3652
4481
  this.isDirty = false;
3653
4482
  }
3654
4483
  /**
@@ -3759,8 +4588,8 @@ var BackupTransaction = class {
3759
4588
  * Clean up transaction file after successful completion
3760
4589
  */
3761
4590
  cleanup() {
3762
- if (fs12.existsSync(this.transactionPath)) {
3763
- fs12.unlinkSync(this.transactionPath);
4591
+ if (fs14.existsSync(this.transactionPath)) {
4592
+ fs14.unlinkSync(this.transactionPath);
3764
4593
  }
3765
4594
  }
3766
4595
  };
@@ -3846,14 +4675,14 @@ function generateCodemieYaml(backup, projectName, backupDir, integrationSpecPath
3846
4675
  (workflow) => prepareWorkflowForYaml(workflow, backup.state, backup.resources.assistants, backupDir)
3847
4676
  ),
3848
4677
  ...ownedSkills.length > 0 && {
3849
- skills: ownedSkills.map((skill) => prepareSkillForYaml(skill, backup.state))
4678
+ skills: ownedSkills.map((skill) => prepareSkillForYaml(skill, backup.state, backupDir))
3850
4679
  }
3851
4680
  }
3852
4681
  };
3853
- return yaml7.stringify(config);
4682
+ return yaml8.stringify(config);
3854
4683
  }
3855
4684
  function saveIntegrationOpenApiSpecs(backupData, backupDir) {
3856
- const specsDir = path.join(backupDir, "openapi_specs");
4685
+ const specsDir = path14.join(backupDir, "openapi_specs");
3857
4686
  let specsCount = 0;
3858
4687
  const integrationSpecPaths = /* @__PURE__ */ new Map();
3859
4688
  for (const integration of backupData.resources.integrations) {
@@ -3866,8 +4695,8 @@ function saveIntegrationOpenApiSpecs(backupData, backupDir) {
3866
4695
  if (specEntry && typeof specEntry.value === "string" && specEntry.value) {
3867
4696
  const alias = integration.alias || integration.id;
3868
4697
  const fileName = String(alias).toLowerCase().replaceAll(/[^a-z0-9]+/g, "-");
3869
- if (!fs12.existsSync(specsDir)) {
3870
- fs12.mkdirSync(specsDir, { recursive: true });
4698
+ if (!fs14.existsSync(specsDir)) {
4699
+ fs14.mkdirSync(specsDir, { recursive: true });
3871
4700
  }
3872
4701
  const specContent = specEntry.value;
3873
4702
  let fileExtension = ".yaml";
@@ -3880,8 +4709,8 @@ function saveIntegrationOpenApiSpecs(backupData, backupDir) {
3880
4709
  fileExtension = ".yaml";
3881
4710
  }
3882
4711
  const specFileName = `${fileName}${fileExtension}`;
3883
- const specPath = path.join(specsDir, specFileName);
3884
- fs12.writeFileSync(specPath, contentToSave, "utf8");
4712
+ const specPath = path14.join(specsDir, specFileName);
4713
+ fs14.writeFileSync(specPath, contentToSave, "utf8");
3885
4714
  integrationSpecPaths.set(integration.id, `openapi_specs/${specFileName}`);
3886
4715
  specsCount++;
3887
4716
  }
@@ -3894,15 +4723,15 @@ function saveIntegrationOpenApiSpecs(backupData, backupDir) {
3894
4723
  function saveBackupFiles(backupData, backupDir, projectName) {
3895
4724
  logger.info("\u{1F4BE} Writing backup files...\n");
3896
4725
  const integrationSpecPaths = saveIntegrationOpenApiSpecs(backupData, backupDir);
3897
- const codemieYamlPath = path.join(backupDir, "codemie.yaml");
4726
+ const codemieYamlPath = path14.join(backupDir, "codemie.yaml");
3898
4727
  const codemieYaml = generateCodemieYaml(backupData, projectName, backupDir, integrationSpecPaths);
3899
- fs12.writeFileSync(codemieYamlPath, codemieYaml, "utf8");
4728
+ fs14.writeFileSync(codemieYamlPath, codemieYaml, "utf8");
3900
4729
  logger.info(` \u2713 Saved config file: codemie.yaml`);
3901
- const backupJsonPath = path.join(backupDir, "backup.json");
3902
- fs12.writeFileSync(backupJsonPath, JSON.stringify(backupData, null, 2), "utf8");
4730
+ const backupJsonPath = path14.join(backupDir, "backup.json");
4731
+ fs14.writeFileSync(backupJsonPath, JSON.stringify(backupData, null, 2), "utf8");
3903
4732
  logger.info(` \u2713 Saved full backup: backup.json`);
3904
- const statePath = path.join(backupDir, "state.json");
3905
- fs12.writeFileSync(statePath, JSON.stringify(backupData.state, null, 2), "utf8");
4733
+ const statePath = path14.join(backupDir, "state.json");
4734
+ fs14.writeFileSync(statePath, JSON.stringify(backupData.state, null, 2), "utf8");
3906
4735
  logger.info(` \u2713 Saved state file: state.json`);
3907
4736
  }
3908
4737
 
@@ -3928,30 +4757,14 @@ async function withRetry(fn, operation, maxAttempts = RATE_LIMITING.RETRY_ATTEMP
3928
4757
  }
3929
4758
  const delayMs = RATE_LIMITING.RETRY_DELAY_MS * 2 ** (attempt - 1);
3930
4759
  logger.warn(` \u26A0\uFE0F Retry ${attempt}/${maxAttempts} for ${operation} after ${delayMs}ms...`);
3931
- await new Promise((resolve3) => {
3932
- setTimeout(resolve3, delayMs);
4760
+ await new Promise((resolve4) => {
4761
+ setTimeout(resolve4, delayMs);
3933
4762
  });
3934
4763
  }
3935
4764
  }
3936
4765
  throw lastError || new Error(`Failed after ${maxAttempts} attempts: ${operation}`);
3937
4766
  }
3938
4767
 
3939
- // src/lib/timeoutUtils.ts
3940
- async function withTimeout(promise, timeoutMs, operation) {
3941
- let timeoutId;
3942
- const timeoutPromise = new Promise((_, reject) => {
3943
- timeoutId = setTimeout(() => reject(new Error(`Operation timeout: ${operation} (${timeoutMs}ms)`)), timeoutMs);
3944
- timeoutId.unref();
3945
- });
3946
- try {
3947
- return await Promise.race([promise, timeoutPromise]);
3948
- } finally {
3949
- if (timeoutId !== void 0) {
3950
- clearTimeout(timeoutId);
3951
- }
3952
- }
3953
- }
3954
-
3955
4768
  // src/backup.ts
3956
4769
  init_backupTransformers();
3957
4770
  async function* streamResources(fetchPage, resourceType) {
@@ -4010,9 +4823,9 @@ async function saveAssistantToBackup(assistant, client, backupData, backupDir) {
4010
4823
  backupData.resources.assistants.push(full);
4011
4824
  if (full.system_prompt) {
4012
4825
  const fileName = `${full.slug || sanitizeFileName(full.name)}.prompt.md`;
4013
- const filePath = path.join(backupDir, "system_prompts", fileName);
4826
+ const filePath = path14.join(backupDir, "system_prompts", fileName);
4014
4827
  ensureDirectoryExists(filePath);
4015
- fs12.writeFileSync(filePath, full.system_prompt, "utf8");
4828
+ fs14.writeFileSync(filePath, full.system_prompt, "utf8");
4016
4829
  }
4017
4830
  }
4018
4831
  async function backupAssistants(client, backupData, backupDir, transaction) {
@@ -4138,9 +4951,9 @@ async function backupWorkflows(client, backupData, backupDir, transaction) {
4138
4951
  backupData.resources.workflows.push(full);
4139
4952
  if (full.yaml_config) {
4140
4953
  const fileName = `${sanitizeFileName(full.name)}.yaml`;
4141
- const filePath = path.join(backupDir, "workflows", fileName);
4954
+ const filePath = path14.join(backupDir, "workflows", fileName);
4142
4955
  ensureDirectoryExists(filePath);
4143
- fs12.writeFileSync(filePath, full.yaml_config, "utf8");
4956
+ fs14.writeFileSync(filePath, full.yaml_config, "utf8");
4144
4957
  }
4145
4958
  transaction.markCompleted("workflows", workflow.id);
4146
4959
  } catch (error) {
@@ -4240,15 +5053,33 @@ async function backupSkills(client, backupData, backupDir, transaction, projectN
4240
5053
  logger.info(` \u21B7 Skipping unreferenced external skill ${skill.name} (owner: ${full.project})`);
4241
5054
  return;
4242
5055
  }
4243
- backupData.resources.skills.push(full);
4244
5056
  if (fullIsProjectOwned) {
4245
- const fileName = `${sanitizeFileName(skill.name)}.skill.md`;
4246
- const filePath = path.join(backupDir, "skills", fileName);
4247
- ensureDirectoryExists(filePath);
4248
- fs12.writeFileSync(filePath, full.content || "", "utf8");
5057
+ const companionFiles = await client.skills.listCompanionFiles(skill.id);
5058
+ full.companion_files = companionFiles;
5059
+ if (companionFiles.length > 0) {
5060
+ const skillDir = path14.join(backupDir, skillDirRelativePath(skill.name));
5061
+ const skillMdPath = path14.join(backupDir, skillMarkdownRelativePath(skill.name));
5062
+ ensureDirectoryExists(skillMdPath);
5063
+ fs14.writeFileSync(skillMdPath, full.content || "", "utf8");
5064
+ for (const companionMeta of companionFiles) {
5065
+ const companionPath = resolvePathWithinDirectory(skillDir, companionMeta.path);
5066
+ const companionFile = await client.skills.getCompanionFile(skill.id, companionMeta.path);
5067
+ ensureDirectoryExists(companionPath);
5068
+ if (companionFile.encoding === "base64") {
5069
+ fs14.writeFileSync(companionPath, Buffer.from(companionFile.content, "base64"));
5070
+ } else {
5071
+ fs14.writeFileSync(companionPath, companionFile.content, "utf8");
5072
+ }
5073
+ }
5074
+ } else {
5075
+ const filePath = path14.join(backupDir, skillFlatFileRelativePath(skill.name));
5076
+ ensureDirectoryExists(filePath);
5077
+ fs14.writeFileSync(filePath, full.content || "", "utf8");
5078
+ }
4249
5079
  } else {
4250
5080
  logger.info(` \u21B7 Skipping content file for imported skill ${skill.name} (owner: ${full.project})`);
4251
5081
  }
5082
+ backupData.resources.skills.push(full);
4252
5083
  }, `Backup skill ${skill.name}`)
4253
5084
  );
4254
5085
  transaction.markCompleted("skills", skill.id);
@@ -4267,17 +5098,17 @@ async function backupSkills(client, backupData, backupDir, transaction, projectN
4267
5098
  }
4268
5099
  function getUniqueBackupDir(baseDir, timestamp) {
4269
5100
  let counter = 0;
4270
- let finalBackupDir = path.join(baseDir, timestamp);
4271
- while (fs12.existsSync(finalBackupDir)) {
5101
+ let finalBackupDir = path14.join(baseDir, timestamp);
5102
+ while (fs14.existsSync(finalBackupDir)) {
4272
5103
  counter++;
4273
- finalBackupDir = path.join(baseDir, `${timestamp}-${counter}`);
5104
+ finalBackupDir = path14.join(baseDir, `${timestamp}-${counter}`);
4274
5105
  }
4275
5106
  const dirSuffix = counter > 0 ? `${timestamp}-${counter}` : timestamp;
4276
- const tempBackupDir = path.join(baseDir, `${BACKUP.TEMP_DIR_PREFIX}${dirSuffix}`);
5107
+ const tempBackupDir = path14.join(baseDir, `${BACKUP.TEMP_DIR_PREFIX}${dirSuffix}`);
4277
5108
  return { finalDir: finalBackupDir, tempDir: tempBackupDir };
4278
5109
  }
4279
5110
  function performCleanup(tempBackupDir, transaction) {
4280
- if (fs12.existsSync(tempBackupDir)) {
5111
+ if (fs14.existsSync(tempBackupDir)) {
4281
5112
  try {
4282
5113
  logger.info(`\u{1F9F9} Rolling back: cleaning up ${tempBackupDir}...`);
4283
5114
  cleanupDirectory(tempBackupDir);
@@ -4306,7 +5137,7 @@ async function backupResources(options) {
4306
5137
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "").replaceAll(":", "-");
4307
5138
  const { appConfig } = options;
4308
5139
  const { rootDir, backupsDirectory } = appConfig;
4309
- const backupBaseDir = path.join(rootDir, backupsDirectory);
5140
+ const backupBaseDir = path14.join(rootDir, backupsDirectory);
4310
5141
  const { finalDir: finalBackupDir, tempDir: tempBackupDir } = getUniqueBackupDir(backupBaseDir, timestamp);
4311
5142
  let transaction = null;
4312
5143
  try {
@@ -4316,8 +5147,8 @@ async function backupResources(options) {
4316
5147
  logger.info("\u{1F50C} Connecting to Codemie API...");
4317
5148
  const client = await createClient(config);
4318
5149
  logger.info("\u2713 Connected to Codemie API\n");
4319
- if (!fs12.existsSync(tempBackupDir)) {
4320
- fs12.mkdirSync(tempBackupDir, { recursive: true });
5150
+ if (!fs14.existsSync(tempBackupDir)) {
5151
+ fs14.mkdirSync(tempBackupDir, { recursive: true });
4321
5152
  }
4322
5153
  logger.info(`\u{1F4C1} Temporary backup directory: ${tempBackupDir}
4323
5154
  `);
@@ -4417,6 +5248,7 @@ function pluralTypeOf(resourceType) {
4417
5248
  }
4418
5249
 
4419
5250
  // src/import.ts
5251
+ init_skillCompanionFiles();
4420
5252
  init_skillUtils();
4421
5253
  async function findAssistant(client, slug) {
4422
5254
  if (UUID_RE.test(slug)) {
@@ -4477,6 +5309,38 @@ async function findSkill(client, name) {
4477
5309
  const match = await findResourceByName2((params) => client.skills.list(params), name, "skill");
4478
5310
  return withTimeout(client.skills.get(match.id), TIMEOUTS_MS.SKILL_FETCH, `Timeout fetching skill "${match.id}"`);
4479
5311
  }
5312
+ async function fetchSkillCompanionFiles(client, skill) {
5313
+ const metadata = await withTimeout(
5314
+ client.skills.listCompanionFiles(skill.id),
5315
+ TIMEOUTS_MS.SKILL_FETCH,
5316
+ `Timeout listing companion files for skill "${skill.id}"`
5317
+ );
5318
+ skill.companion_files = metadata;
5319
+ const limit = createConcurrentLimiter();
5320
+ return Promise.all(
5321
+ metadata.map(
5322
+ (entry) => limit(
5323
+ () => withTimeout(
5324
+ client.skills.getCompanionFile(skill.id, entry.path),
5325
+ TIMEOUTS_MS.SKILL_FETCH,
5326
+ `Timeout fetching companion file "${entry.path}" of skill "${skill.id}"`
5327
+ )
5328
+ )
5329
+ )
5330
+ );
5331
+ }
5332
+ function writeCompanionFiles(skillDir, companionFiles) {
5333
+ for (const file of companionFiles) {
5334
+ const absPath = resolvePathWithinDirectory(skillDir, file.path);
5335
+ ensureDirectoryExists(absPath);
5336
+ if (file.encoding === "base64") {
5337
+ fs14.writeFileSync(absPath, Buffer.from(file.content, "base64"));
5338
+ } else {
5339
+ fs14.writeFileSync(absPath, file.content, "utf8");
5340
+ }
5341
+ logger.info(` \u{1F4CE} Saved companion file: ${file.path}`);
5342
+ }
5343
+ }
4480
5344
  async function findResourceByName2(fetchPage, name, resourceType) {
4481
5345
  const allResources = [];
4482
5346
  let page = 0;
@@ -4549,7 +5413,7 @@ function assertResolvedNameIsFree(config, stateManager, resourceType, slug, reso
4549
5413
  }
4550
5414
  return managedName;
4551
5415
  }
4552
- function writeResourceFiles(rootDir, resourceType, resource, apiResponse) {
5416
+ function writeResourceFiles(rootDir, resourceType, resource, apiResponse, companionFiles = []) {
4553
5417
  const safeName = sanitizeFileName(resource.name);
4554
5418
  const target = resource;
4555
5419
  if (resourceType === "workflow") {
@@ -4557,34 +5421,34 @@ function writeResourceFiles(rootDir, resourceType, resource, apiResponse) {
4557
5421
  const workflowResource = resource;
4558
5422
  if (workflow.yaml_config) {
4559
5423
  const defFileName = `${safeName}.yaml`;
4560
- const defPath = path.join(rootDir, "workflows", defFileName);
5424
+ const defPath = path14.join(rootDir, "workflows", defFileName);
4561
5425
  ensureDirectoryExists(defPath);
4562
- fs12.writeFileSync(defPath, workflow.yaml_config, "utf8");
5426
+ fs14.writeFileSync(defPath, workflow.yaml_config, "utf8");
4563
5427
  logger.info(` \u{1F4CB} Saved workflow definition: workflows/${defFileName}`);
4564
5428
  workflowResource.definition = `workflows/${defFileName}`;
4565
5429
  } else {
4566
5430
  delete target.definition;
4567
5431
  }
4568
- const configPath = path.join(rootDir, "configs", "workflows", `${safeName}.yaml`);
5432
+ const configPath = path14.join(rootDir, "configs", "workflows", `${safeName}.yaml`);
4569
5433
  const relativeConfigPath = `configs/workflows/${safeName}.yaml`;
4570
5434
  ensureDirectoryExists(configPath);
4571
- const yamlContent2 = yaml7.stringify(workflowResource, { lineWidth: 120 });
4572
- fs12.writeFileSync(configPath, yamlContent2, "utf8");
5435
+ const yamlContent2 = yaml8.stringify(workflowResource, { lineWidth: 120 });
5436
+ fs14.writeFileSync(configPath, yamlContent2, "utf8");
4573
5437
  logger.info(` \u{1F4C4} Saved workflow config: ${relativeConfigPath}`);
4574
5438
  return relativeConfigPath;
4575
5439
  }
4576
5440
  const pluralType = pluralTypeOf(resourceType);
4577
- const resourceDir = path.join(rootDir, "configs", "imported-resources", pluralType);
4578
- const resourceFilePath = path.join(resourceDir, `${safeName}.yaml`);
5441
+ const resourceDir = path14.join(rootDir, "configs", "imported-resources", pluralType);
5442
+ const resourceFilePath = path14.join(resourceDir, `${safeName}.yaml`);
4579
5443
  const relativeResourcePath = `configs/imported-resources/${pluralType}/${safeName}.yaml`;
4580
5444
  if (resourceType === "assistant") {
4581
5445
  const assistant = apiResponse;
4582
5446
  const assistantResource = resource;
4583
5447
  if (assistant.system_prompt) {
4584
5448
  const promptFileName = assistant.slug || safeName;
4585
- const promptPath = path.join(rootDir, "system_prompts", `${promptFileName}.prompt.md`);
5449
+ const promptPath = path14.join(rootDir, "system_prompts", `${promptFileName}.prompt.md`);
4586
5450
  ensureDirectoryExists(promptPath);
4587
- fs12.writeFileSync(promptPath, assistant.system_prompt, "utf8");
5451
+ fs14.writeFileSync(promptPath, assistant.system_prompt, "utf8");
4588
5452
  logger.info(` \u{1F4DD} Saved prompt: system_prompts/${promptFileName}.prompt.md`);
4589
5453
  assistantResource.prompt = `system_prompts/${promptFileName}.prompt.md`;
4590
5454
  } else {
@@ -4594,19 +5458,23 @@ function writeResourceFiles(rootDir, resourceType, resource, apiResponse) {
4594
5458
  const skill = apiResponse;
4595
5459
  const skillResource = resource;
4596
5460
  if (skill.content) {
4597
- const skillFileName = `${safeName}.skill.md`;
4598
- const skillPath = path.join(rootDir, "skills", skillFileName);
5461
+ const hasCompanionFiles = companionFiles.length > 0;
5462
+ const relativeSkillPath = hasCompanionFiles ? skillMarkdownRelativePath(resource.name) : skillFlatFileRelativePath(resource.name);
5463
+ const skillPath = path14.join(rootDir, relativeSkillPath);
4599
5464
  ensureDirectoryExists(skillPath);
4600
- fs12.writeFileSync(skillPath, skill.content, "utf8");
4601
- logger.info(` \u{1F9E0} Saved skill content: skills/${skillFileName}`);
4602
- skillResource.file = `skills/${skillFileName}`;
5465
+ fs14.writeFileSync(skillPath, skill.content, "utf8");
5466
+ logger.info(` \u{1F9E0} Saved skill content: ${relativeSkillPath}`);
5467
+ if (hasCompanionFiles) {
5468
+ writeCompanionFiles(path14.dirname(skillPath), companionFiles);
5469
+ }
5470
+ skillResource.file = relativeSkillPath;
4603
5471
  } else {
4604
5472
  delete target.file;
4605
5473
  }
4606
5474
  }
4607
5475
  ensureDirectoryExists(resourceFilePath);
4608
- const yamlContent = yaml7.stringify(resource, { lineWidth: 120 });
4609
- fs12.writeFileSync(resourceFilePath, yamlContent, "utf8");
5476
+ const yamlContent = yaml8.stringify(resource, { lineWidth: 120 });
5477
+ fs14.writeFileSync(resourceFilePath, yamlContent, "utf8");
4610
5478
  logger.info(` \u{1F4C4} Saved resource config: ${relativeResourcePath}`);
4611
5479
  return relativeResourcePath;
4612
5480
  }
@@ -4622,7 +5490,7 @@ function planCompanionWrite(rootDir, target, key, configuredValue, content, defa
4622
5490
  }
4623
5491
  const relPath = configuredPath ?? defaultPath;
4624
5492
  target[key] = relPath;
4625
- return { absPath: path.join(rootDir, relPath), content, log: ` ${label}: ${relPath}` };
5493
+ return { absPath: path14.join(rootDir, relPath), content, log: ` ${label}: ${relPath}` };
4626
5494
  }
4627
5495
  var IN_LIST_ITEM_INDENT = 2;
4628
5496
  function itemCarriesAnchorAliasOrMergeKey(node) {
@@ -4631,28 +5499,28 @@ function itemCarriesAnchorAliasOrMergeKey(node) {
4631
5499
  }
4632
5500
  return node.items.some((pair) => {
4633
5501
  const key = pair.key;
4634
- const keyValue = yaml7.isScalar(key) ? key.value : key;
5502
+ const keyValue = yaml8.isScalar(key) ? key.value : key;
4635
5503
  if (keyValue === "<<") {
4636
5504
  return true;
4637
5505
  }
4638
5506
  const value = pair.value;
4639
- if (yaml7.isAlias(value)) {
5507
+ if (yaml8.isAlias(value)) {
4640
5508
  return true;
4641
5509
  }
4642
- return yaml7.isNode(value) && value.anchor !== void 0;
5510
+ return yaml8.isNode(value) && value.anchor !== void 0;
4643
5511
  });
4644
5512
  }
4645
5513
  function spliceResourceIntoList(filePath, relativeResourcePath, resource, existingName) {
4646
- const source = fs12.readFileSync(filePath, "utf8");
4647
- const doc = yaml7.parseDocument(source);
5514
+ const source = fs14.readFileSync(filePath, "utf8");
5515
+ const doc = yaml8.parseDocument(source);
4648
5516
  const refusal = (reason) => new Error(
4649
5517
  `Cannot safely update "${existingName}" inside ${relativeResourcePath}: ${reason}. Update ${relativeResourcePath} manually.`
4650
5518
  );
4651
- if (!yaml7.isSeq(doc.contents) || doc.contents.flow) {
5519
+ if (!yaml8.isSeq(doc.contents) || doc.contents.flow) {
4652
5520
  throw refusal("the file is not a block-style YAML sequence");
4653
5521
  }
4654
5522
  const node = doc.contents.items.find((item) => {
4655
- if (!yaml7.isMap(item)) {
5523
+ if (!yaml8.isMap(item)) {
4656
5524
  return false;
4657
5525
  }
4658
5526
  const itemName = item.get("name");
@@ -4672,13 +5540,13 @@ function spliceResourceIntoList(filePath, relativeResourcePath, resource, existi
4672
5540
  if (indent !== IN_LIST_ITEM_INDENT) {
4673
5541
  throw refusal(`its entry is indented by ${indent} spaces instead of ${IN_LIST_ITEM_INDENT}`);
4674
5542
  }
4675
- const rendered = yaml7.stringify(resource, { lineWidth: 120 }).trimEnd();
5543
+ const rendered = yaml8.stringify(resource, { lineWidth: 120 }).trimEnd();
4676
5544
  const replacement = rendered.split("\n").map((line, index) => index === 0 || !line ? line : `${" ".repeat(IN_LIST_ITEM_INDENT)}${line}`).join("\n");
4677
5545
  const tail = source.slice(valueEnd);
4678
5546
  const separator = tail.startsWith("\n") ? "" : "\n";
4679
5547
  return source.slice(0, start) + replacement + separator + tail;
4680
5548
  }
4681
- function updateResourceFiles(rootDir, resourceType, resource, apiResponse, existing) {
5549
+ function updateResourceFiles(rootDir, resourceType, resource, apiResponse, existing, companionFiles = []) {
4682
5550
  const filePath = existing.file;
4683
5551
  if (!filePath) {
4684
5552
  throw new Error("updateResourceFiles requires an existing resource backed by a file");
@@ -4706,13 +5574,15 @@ function updateResourceFiles(rootDir, resourceType, resource, apiResponse, exist
4706
5574
  );
4707
5575
  } else if (resourceType === "skill") {
4708
5576
  const skill = apiResponse;
5577
+ const hasCompanionFiles = companionFiles.length > 0;
5578
+ const defaultSkillPath = hasCompanionFiles ? skillMarkdownRelativePath(resource.name) : skillFlatFileRelativePath(resource.name);
4709
5579
  companion = planCompanionWrite(
4710
5580
  rootDir,
4711
5581
  target,
4712
5582
  "file",
4713
5583
  existingResource.file,
4714
5584
  skill.content,
4715
- `skills/${safeName}.skill.md`,
5585
+ defaultSkillPath,
4716
5586
  "\u{1F9E0} Updated skill content"
4717
5587
  );
4718
5588
  } else if (resourceType === "workflow") {
@@ -4727,16 +5597,25 @@ function updateResourceFiles(rootDir, resourceType, resource, apiResponse, exist
4727
5597
  "\u{1F4CB} Updated workflow definition"
4728
5598
  );
4729
5599
  }
4730
- const relativeResourcePath = path.relative(rootDir, filePath);
4731
- const newResourceFileContent = existing.inList ? spliceResourceIntoList(filePath, relativeResourcePath, resource, String(existingResource.name)) : yaml7.stringify(resource, { lineWidth: 120 });
5600
+ const relativeResourcePath = path14.relative(rootDir, filePath);
5601
+ const newResourceFileContent = existing.inList ? spliceResourceIntoList(filePath, relativeResourcePath, resource, String(existingResource.name)) : yaml8.stringify(resource, { lineWidth: 120 });
5602
+ const companionFilesWritten = resourceType === "skill" && companionFiles.length > 0 && companion !== void 0 && hasCompanionFileLayout(resource);
4732
5603
  if (companion) {
4733
5604
  ensureDirectoryExists(companion.absPath);
4734
- fs12.writeFileSync(companion.absPath, companion.content, "utf8");
5605
+ fs14.writeFileSync(companion.absPath, companion.content, "utf8");
4735
5606
  logger.info(companion.log);
5607
+ if (companionFilesWritten) {
5608
+ writeCompanionFiles(path14.dirname(companion.absPath), companionFiles);
5609
+ }
5610
+ }
5611
+ if (resourceType === "skill" && companionFiles.length > 0 && !companionFilesWritten) {
5612
+ logger.warn(
5613
+ ` \u26A0\uFE0F Skill "${resource.name}" has ${companionFiles.length} companion file(s) on the platform, but none were written locally (configured file: "${resource.file ?? "(none)"}"): they stay on the platform and are not managed locally. Point the entry at a skills/<name>/SKILL.md layout to manage them.`
5614
+ );
4736
5615
  }
4737
- fs12.writeFileSync(filePath, newResourceFileContent, "utf8");
5616
+ fs14.writeFileSync(filePath, newResourceFileContent, "utf8");
4738
5617
  logger.info(` \u{1F4C4} Updated resource config: ${relativeResourcePath}`);
4739
- return relativeResourcePath;
5618
+ return { relativeResourcePath, companionFilesWritten };
4740
5619
  }
4741
5620
  function deleteStateEntry(stateManager, resourceType, name) {
4742
5621
  switch (resourceType) {
@@ -4759,12 +5638,12 @@ function deleteStateEntry(stateManager, resourceType, name) {
4759
5638
  }
4760
5639
  }
4761
5640
  function addImportToCodemieYaml(rootDir, codemieConfigPath, resourceType, relativeResourcePath) {
4762
- const configPath = path.join(rootDir, codemieConfigPath);
4763
- if (!fs12.existsSync(configPath)) {
5641
+ const configPath = path14.join(rootDir, codemieConfigPath);
5642
+ if (!fs14.existsSync(configPath)) {
4764
5643
  throw new Error(`Configuration file not found: ${configPath}`);
4765
5644
  }
4766
- const content = fs12.readFileSync(configPath, "utf8");
4767
- const doc = yaml7.parseDocument(content);
5645
+ const content = fs14.readFileSync(configPath, "utf8");
5646
+ const doc = yaml8.parseDocument(content);
4768
5647
  const pluralType = pluralTypeOf(resourceType);
4769
5648
  let resourcesNode = doc.get("resources");
4770
5649
  if (!resourcesNode) {
@@ -4778,7 +5657,7 @@ function addImportToCodemieYaml(rootDir, codemieConfigPath, resourceType, relati
4778
5657
  }
4779
5658
  const importDirective = { $import: relativeResourcePath };
4780
5659
  const existingImports = typeArray.items.filter((item) => {
4781
- if (yaml7.isMap(item)) {
5660
+ if (yaml8.isMap(item)) {
4782
5661
  const importValue = item.get("$import");
4783
5662
  return importValue === relativeResourcePath;
4784
5663
  }
@@ -4790,16 +5669,16 @@ function addImportToCodemieYaml(rootDir, codemieConfigPath, resourceType, relati
4790
5669
  }
4791
5670
  const newNode = doc.createNode(importDirective);
4792
5671
  typeArray.add(newNode);
4793
- fs12.writeFileSync(configPath, doc.toString(), "utf8");
5672
+ fs14.writeFileSync(configPath, doc.toString(), "utf8");
4794
5673
  logger.info(` \u2705 Added $import to ${codemieConfigPath} \u2192 resources.${pluralType}`);
4795
5674
  }
4796
5675
  function addImportedSkillToCodemieYaml(rootDir, codemieConfigPath, skill) {
4797
- const configPath = path.join(rootDir, codemieConfigPath);
4798
- if (!fs12.existsSync(configPath)) {
5676
+ const configPath = path14.join(rootDir, codemieConfigPath);
5677
+ if (!fs14.existsSync(configPath)) {
4799
5678
  throw new Error(`Configuration file not found: ${configPath}`);
4800
5679
  }
4801
- const content = fs12.readFileSync(configPath, "utf8");
4802
- const doc = yaml7.parseDocument(content);
5680
+ const content = fs14.readFileSync(configPath, "utf8");
5681
+ const doc = yaml8.parseDocument(content);
4803
5682
  let importedNode = doc.get("imported");
4804
5683
  if (!importedNode) {
4805
5684
  importedNode = doc.createNode({ assistants: [], datasources: [], skills: [], integrations: [] });
@@ -4811,7 +5690,7 @@ function addImportedSkillToCodemieYaml(rootDir, codemieConfigPath, skill) {
4811
5690
  doc.setIn(["imported", "skills"], skillsArray);
4812
5691
  }
4813
5692
  const existingSkill = skillsArray.items.find((item) => {
4814
- if (!yaml7.isMap(item)) {
5693
+ if (!yaml8.isMap(item)) {
4815
5694
  return false;
4816
5695
  }
4817
5696
  const existingName = item.get("name");
@@ -4828,21 +5707,21 @@ function addImportedSkillToCodemieYaml(rootDir, codemieConfigPath, skill) {
4828
5707
  return;
4829
5708
  }
4830
5709
  skillsArray.add(doc.createNode({ name: skill.name, id: skill.id }));
4831
- fs12.writeFileSync(configPath, doc.toString(), "utf8");
5710
+ fs14.writeFileSync(configPath, doc.toString(), "utf8");
4832
5711
  logger.info(` \u2705 Added skill to ${codemieConfigPath} \u2192 imported.skills`);
4833
5712
  }
4834
5713
  function updateImportedSkillInCodemieYaml(rootDir, codemieConfigPath, skill) {
4835
- const configPath = path.join(rootDir, codemieConfigPath);
4836
- if (!fs12.existsSync(configPath)) {
5714
+ const configPath = path14.join(rootDir, codemieConfigPath);
5715
+ if (!fs14.existsSync(configPath)) {
4837
5716
  throw new Error(`Configuration file not found: ${configPath}`);
4838
5717
  }
4839
- const content = fs12.readFileSync(configPath, "utf8");
4840
- const doc = yaml7.parseDocument(content);
5718
+ const content = fs14.readFileSync(configPath, "utf8");
5719
+ const doc = yaml8.parseDocument(content);
4841
5720
  const skillsArray = doc.getIn(["imported", "skills"]);
4842
5721
  if (!skillsArray) {
4843
5722
  return false;
4844
5723
  }
4845
- const items = skillsArray.items.filter((item) => yaml7.isMap(item));
5724
+ const items = skillsArray.items.filter((item) => yaml8.isMap(item));
4846
5725
  const entryById = items.find((item) => {
4847
5726
  const existingId = item.get("id");
4848
5727
  return typeof existingId === "string" && existingId === skill.id;
@@ -4856,7 +5735,7 @@ function updateImportedSkillInCodemieYaml(rootDir, codemieConfigPath, skill) {
4856
5735
  }
4857
5736
  entry.set("name", skill.name);
4858
5737
  entry.set("id", skill.id);
4859
- fs12.writeFileSync(configPath, doc.toString(), "utf8");
5738
+ fs14.writeFileSync(configPath, doc.toString(), "utf8");
4860
5739
  return true;
4861
5740
  }
4862
5741
  function upsertImportedSkill(rootDir, codemieConfigPath, skill, update) {
@@ -4878,7 +5757,15 @@ function ensureExternalSkillDoesNotConflictWithManagedSkill(config, skillName) {
4878
5757
  `External skill "${skillName}" is already defined in resources.skills. Keep project-owned skills in resources.skills or external skills in imported.skills, not both.`
4879
5758
  );
4880
5759
  }
4881
- function updateState(stateManager, resourceType, resource, apiResponse) {
5760
+ async function importReferencedProjectSkill(client, rootDir, codemieConfigPath, stateManager, skill) {
5761
+ const companionFiles = await fetchSkillCompanionFiles(client, skill);
5762
+ const skillResource = skillResponseToResource(skill);
5763
+ const relativeSkillPath = writeResourceFiles(rootDir, "skill", skillResource, skill, companionFiles);
5764
+ addImportToCodemieYaml(rootDir, codemieConfigPath, "skill", relativeSkillPath);
5765
+ updateState(stateManager, "skill", skillResource, skill, companionFiles);
5766
+ logger.info(` \u2713 Imported project-owned skill "${skill.name}" into resources.skills`);
5767
+ }
5768
+ function updateState(stateManager, resourceType, resource, apiResponse, companionFiles = []) {
4882
5769
  switch (resourceType) {
4883
5770
  case "assistant": {
4884
5771
  const assistant = apiResponse;
@@ -4906,7 +5793,13 @@ function updateState(stateManager, resourceType, resource, apiResponse) {
4906
5793
  case "skill": {
4907
5794
  const skill = apiResponse;
4908
5795
  const skillResource = resource;
4909
- stateManager.updateSkillState(resource.name, skill.id, skill.content || "", skillResource);
5796
+ stateManager.updateSkillState(
5797
+ resource.name,
5798
+ skill.id,
5799
+ skill.content || "",
5800
+ skillResource,
5801
+ companionFiles.length > 0 ? companionFiles : void 0
5802
+ );
4910
5803
  break;
4911
5804
  }
4912
5805
  }
@@ -4921,10 +5814,13 @@ function buildIntegrationAliasMap(config) {
4921
5814
  return map;
4922
5815
  }
4923
5816
  async function importResource(options) {
4924
- const { appConfig, resourceType, slug, update = false } = options;
5817
+ const { appConfig, resourceType, slug, update = false, withSkills = false } = options;
4925
5818
  if (!VALID_RESOURCE_TYPES.includes(resourceType)) {
4926
5819
  throw new Error(`Invalid resource type: "${resourceType}". Must be one of: ${VALID_RESOURCE_TYPES.join(", ")}`);
4927
5820
  }
5821
+ if (withSkills && resourceType !== "assistant") {
5822
+ logger.warn(` \u26A0\uFE0F --with-skills only applies to assistants \u2014 ignoring it for ${resourceType}.`);
5823
+ }
4928
5824
  const configLoader = new CodemieConfigLoader(appConfig);
4929
5825
  const config = configLoader.loadConfig();
4930
5826
  const rootDir = appConfig.rootDir;
@@ -4941,6 +5837,7 @@ async function importResource(options) {
4941
5837
  let resource;
4942
5838
  let apiResponse;
4943
5839
  let managedName;
5840
+ let skillCompanionFiles = [];
4944
5841
  switch (resourceType) {
4945
5842
  case "assistant": {
4946
5843
  logger.info(` Searching for assistant "${slug}"...`);
@@ -4972,6 +5869,7 @@ async function importResource(options) {
4972
5869
  if (assistantData.skill_ids && assistantData.skill_ids.length > 0) {
4973
5870
  logger.info(` Resolving ${assistantData.skill_ids.length} skill ID(s)...`);
4974
5871
  const skillNames = [];
5872
+ const importedProjectSkills = /* @__PURE__ */ new Set();
4975
5873
  for (const skillId of assistantData.skill_ids) {
4976
5874
  let skill;
4977
5875
  try {
@@ -4989,6 +5887,18 @@ async function importResource(options) {
4989
5887
  if (!isProjectOwnedSkill(skill, config.project.name)) {
4990
5888
  ensureExternalSkillDoesNotConflictWithManagedSkill(config, skill.name);
4991
5889
  upsertImportedSkill(rootDir, appConfig.codemieConfig, { name: skill.name, id: skill.id }, update);
5890
+ continue;
5891
+ }
5892
+ if (withSkills && !checkResourceExists2(config, "skill", skill.name) && !importedProjectSkills.has(skill.name.toLowerCase())) {
5893
+ const managedSkillName = findManagedNameById(stateManager, "skill", skill.id);
5894
+ if (managedSkillName !== void 0) {
5895
+ logger.warn(
5896
+ ` \u26A0\uFE0F Skill "${skill.name}" is already managed under the name "${managedSkillName}" \u2014 not imported. Run \`codemie import skill ${skill.id} --update\` to refresh it.`
5897
+ );
5898
+ continue;
5899
+ }
5900
+ await importReferencedProjectSkill(client, rootDir, appConfig.codemieConfig, stateManager, skill);
5901
+ importedProjectSkills.add(skill.name.toLowerCase());
4992
5902
  }
4993
5903
  }
4994
5904
  if (skillNames.length > 0) {
@@ -5041,6 +5951,7 @@ async function importResource(options) {
5041
5951
  if (isProjectOwnedSkill(skill, config.project.name)) {
5042
5952
  logger.info(` Project-owned skill \u2014 importing into resources.skills`);
5043
5953
  apiResponse = skill;
5954
+ skillCompanionFiles = await fetchSkillCompanionFiles(client, skill);
5044
5955
  resource = skillResponseToResource(skill);
5045
5956
  break;
5046
5957
  }
@@ -5062,12 +5973,25 @@ async function importResource(options) {
5062
5973
  );
5063
5974
  }
5064
5975
  logger.info(` \u267B\uFE0F Updating existing ${resourceType} config in place...`);
5065
- updateResourceFiles(rootDir, resourceType, resource, apiResponse, existing);
5976
+ const { companionFilesWritten } = updateResourceFiles(
5977
+ rootDir,
5978
+ resourceType,
5979
+ resource,
5980
+ apiResponse,
5981
+ existing,
5982
+ skillCompanionFiles
5983
+ );
5066
5984
  if (managedName !== void 0 && !namesEqual(managedName, resource.name)) {
5067
5985
  logger.info(` \u{1F3F7}\uFE0F Renamed from "${managedName}" to "${resource.name}" \u2014 updating state.json`);
5068
5986
  deleteStateEntry(stateManager, resourceType, managedName);
5069
5987
  }
5070
- updateState(stateManager, resourceType, resource, apiResponse);
5988
+ updateState(
5989
+ stateManager,
5990
+ resourceType,
5991
+ resource,
5992
+ apiResponse,
5993
+ companionFilesWritten ? skillCompanionFiles : void 0
5994
+ );
5071
5995
  logger.info(`
5072
5996
  \u2705 Successfully imported ${resourceType} "${resource.name}"
5073
5997
  `);
@@ -5075,9 +5999,9 @@ async function importResource(options) {
5075
5999
  }
5076
6000
  logger.info(` No existing ${resourceType} found in the configuration \u2014 importing as new`);
5077
6001
  }
5078
- const relativeResourcePath = writeResourceFiles(rootDir, resourceType, resource, apiResponse);
6002
+ const relativeResourcePath = writeResourceFiles(rootDir, resourceType, resource, apiResponse, skillCompanionFiles);
5079
6003
  addImportToCodemieYaml(rootDir, appConfig.codemieConfig, resourceType, relativeResourcePath);
5080
- updateState(stateManager, resourceType, resource, apiResponse);
6004
+ updateState(stateManager, resourceType, resource, apiResponse, skillCompanionFiles);
5081
6005
  logger.info(`
5082
6006
  \u2705 Successfully imported ${resourceType} "${resource.name}"
5083
6007
  `);
@@ -5093,8 +6017,8 @@ async function promptUser(question, defaultValue) {
5093
6017
  });
5094
6018
  const displayQuestion = `${question}: `;
5095
6019
  const answer = await pauseSpinnerWhile(
5096
- () => new Promise((resolve3) => {
5097
- rl.question(displayQuestion, resolve3);
6020
+ () => new Promise((resolve4) => {
6021
+ rl.question(displayQuestion, resolve4);
5098
6022
  })
5099
6023
  );
5100
6024
  rl.close();