plugin-agent-orchestrator 1.1.0 → 1.1.2

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.
Files changed (162) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/locale/en-US.json +7 -1
  3. package/dist/locale/vi-VN.json +7 -1
  4. package/dist/locale/zh-CN.json +7 -1
  5. package/dist/node_modules/ajv/.tonic_example.js +20 -0
  6. package/dist/node_modules/ajv/LICENSE +22 -0
  7. package/dist/node_modules/ajv/dist/ajv.bundle.js +7189 -0
  8. package/dist/node_modules/ajv/dist/ajv.min.js +3 -0
  9. package/dist/node_modules/ajv/lib/ajv.d.ts +397 -0
  10. package/dist/node_modules/ajv/lib/ajv.js +3 -0
  11. package/dist/node_modules/ajv/lib/cache.js +26 -0
  12. package/dist/node_modules/ajv/lib/compile/async.js +90 -0
  13. package/dist/node_modules/ajv/lib/compile/equal.js +5 -0
  14. package/dist/node_modules/ajv/lib/compile/error_classes.js +34 -0
  15. package/dist/node_modules/ajv/lib/compile/formats.js +142 -0
  16. package/dist/node_modules/ajv/lib/compile/index.js +387 -0
  17. package/dist/node_modules/ajv/lib/compile/resolve.js +270 -0
  18. package/dist/node_modules/ajv/lib/compile/rules.js +66 -0
  19. package/dist/node_modules/ajv/lib/compile/schema_obj.js +9 -0
  20. package/dist/node_modules/ajv/lib/compile/ucs2length.js +20 -0
  21. package/dist/node_modules/ajv/lib/compile/util.js +239 -0
  22. package/dist/node_modules/ajv/lib/data.js +49 -0
  23. package/dist/node_modules/ajv/lib/definition_schema.js +37 -0
  24. package/dist/node_modules/ajv/lib/dot/_limit.jst +113 -0
  25. package/dist/node_modules/ajv/lib/dot/_limitItems.jst +12 -0
  26. package/dist/node_modules/ajv/lib/dot/_limitLength.jst +12 -0
  27. package/dist/node_modules/ajv/lib/dot/_limitProperties.jst +12 -0
  28. package/dist/node_modules/ajv/lib/dot/allOf.jst +32 -0
  29. package/dist/node_modules/ajv/lib/dot/anyOf.jst +46 -0
  30. package/dist/node_modules/ajv/lib/dot/coerce.def +51 -0
  31. package/dist/node_modules/ajv/lib/dot/comment.jst +9 -0
  32. package/dist/node_modules/ajv/lib/dot/const.jst +11 -0
  33. package/dist/node_modules/ajv/lib/dot/contains.jst +55 -0
  34. package/dist/node_modules/ajv/lib/dot/custom.jst +191 -0
  35. package/dist/node_modules/ajv/lib/dot/defaults.def +47 -0
  36. package/dist/node_modules/ajv/lib/dot/definitions.def +203 -0
  37. package/dist/node_modules/ajv/lib/dot/dependencies.jst +79 -0
  38. package/dist/node_modules/ajv/lib/dot/enum.jst +30 -0
  39. package/dist/node_modules/ajv/lib/dot/errors.def +194 -0
  40. package/dist/node_modules/ajv/lib/dot/format.jst +106 -0
  41. package/dist/node_modules/ajv/lib/dot/if.jst +73 -0
  42. package/dist/node_modules/ajv/lib/dot/items.jst +98 -0
  43. package/dist/node_modules/ajv/lib/dot/missing.def +39 -0
  44. package/dist/node_modules/ajv/lib/dot/multipleOf.jst +22 -0
  45. package/dist/node_modules/ajv/lib/dot/not.jst +43 -0
  46. package/dist/node_modules/ajv/lib/dot/oneOf.jst +54 -0
  47. package/dist/node_modules/ajv/lib/dot/pattern.jst +14 -0
  48. package/dist/node_modules/ajv/lib/dot/properties.jst +245 -0
  49. package/dist/node_modules/ajv/lib/dot/propertyNames.jst +52 -0
  50. package/dist/node_modules/ajv/lib/dot/ref.jst +85 -0
  51. package/dist/node_modules/ajv/lib/dot/required.jst +108 -0
  52. package/dist/node_modules/ajv/lib/dot/uniqueItems.jst +62 -0
  53. package/dist/node_modules/ajv/lib/dot/validate.jst +276 -0
  54. package/dist/node_modules/ajv/lib/dotjs/_limit.js +163 -0
  55. package/dist/node_modules/ajv/lib/dotjs/_limitItems.js +80 -0
  56. package/dist/node_modules/ajv/lib/dotjs/_limitLength.js +85 -0
  57. package/dist/node_modules/ajv/lib/dotjs/_limitProperties.js +80 -0
  58. package/dist/node_modules/ajv/lib/dotjs/allOf.js +42 -0
  59. package/dist/node_modules/ajv/lib/dotjs/anyOf.js +73 -0
  60. package/dist/node_modules/ajv/lib/dotjs/comment.js +14 -0
  61. package/dist/node_modules/ajv/lib/dotjs/const.js +56 -0
  62. package/dist/node_modules/ajv/lib/dotjs/contains.js +81 -0
  63. package/dist/node_modules/ajv/lib/dotjs/custom.js +228 -0
  64. package/dist/node_modules/ajv/lib/dotjs/dependencies.js +168 -0
  65. package/dist/node_modules/ajv/lib/dotjs/enum.js +66 -0
  66. package/dist/node_modules/ajv/lib/dotjs/format.js +150 -0
  67. package/dist/node_modules/ajv/lib/dotjs/if.js +103 -0
  68. package/dist/node_modules/ajv/lib/dotjs/index.js +33 -0
  69. package/dist/node_modules/ajv/lib/dotjs/items.js +140 -0
  70. package/dist/node_modules/ajv/lib/dotjs/multipleOf.js +80 -0
  71. package/dist/node_modules/ajv/lib/dotjs/not.js +84 -0
  72. package/dist/node_modules/ajv/lib/dotjs/oneOf.js +73 -0
  73. package/dist/node_modules/ajv/lib/dotjs/pattern.js +75 -0
  74. package/dist/node_modules/ajv/lib/dotjs/properties.js +335 -0
  75. package/dist/node_modules/ajv/lib/dotjs/propertyNames.js +81 -0
  76. package/dist/node_modules/ajv/lib/dotjs/ref.js +124 -0
  77. package/dist/node_modules/ajv/lib/dotjs/required.js +270 -0
  78. package/dist/node_modules/ajv/lib/dotjs/uniqueItems.js +86 -0
  79. package/dist/node_modules/ajv/lib/dotjs/validate.js +482 -0
  80. package/dist/node_modules/ajv/lib/keyword.js +146 -0
  81. package/dist/node_modules/ajv/lib/refs/data.json +17 -0
  82. package/dist/node_modules/ajv/lib/refs/json-schema-draft-04.json +149 -0
  83. package/dist/node_modules/ajv/lib/refs/json-schema-draft-06.json +154 -0
  84. package/dist/node_modules/ajv/lib/refs/json-schema-draft-07.json +168 -0
  85. package/dist/node_modules/ajv/lib/refs/json-schema-secure.json +94 -0
  86. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.eslintrc.yml +27 -0
  87. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.travis.yml +8 -0
  88. package/dist/node_modules/ajv/node_modules/json-schema-traverse/index.js +89 -0
  89. package/dist/node_modules/ajv/node_modules/json-schema-traverse/package.json +43 -0
  90. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/.eslintrc.yml +6 -0
  91. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/fixtures/schema.js +125 -0
  92. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/index.spec.js +171 -0
  93. package/dist/node_modules/ajv/package.json +1 -0
  94. package/dist/node_modules/ajv/scripts/.eslintrc.yml +3 -0
  95. package/dist/node_modules/ajv/scripts/bundle.js +61 -0
  96. package/dist/node_modules/ajv/scripts/compile-dots.js +73 -0
  97. package/dist/node_modules/ajv/scripts/info +10 -0
  98. package/dist/node_modules/ajv/scripts/prepare-tests +12 -0
  99. package/dist/node_modules/ajv/scripts/publish-built-version +32 -0
  100. package/dist/node_modules/ajv/scripts/travis-gh-pages +23 -0
  101. package/dist/server/collections/skill-definitions.js +31 -0
  102. package/dist/server/collections/skill-executions.js +19 -0
  103. package/dist/server/collections/skill-registry-installations.js +70 -0
  104. package/dist/server/migrations/20260727010000-backfill-skill-tool-names.js +66 -0
  105. package/dist/server/plugin.js +96 -1
  106. package/dist/server/services/AgentExecutionContext.js +45 -0
  107. package/dist/server/services/CodeValidator.js +1 -0
  108. package/dist/server/services/ExecutionSpanService.js +10 -2
  109. package/dist/server/services/InputSchemaValidator.js +83 -0
  110. package/dist/server/services/NativeSubAgentObserver.js +55 -8
  111. package/dist/server/services/SandboxRunner.js +6 -2
  112. package/dist/server/services/SkillAccessService.js +109 -0
  113. package/dist/server/services/SkillManager.js +2 -0
  114. package/dist/server/services/SkillRepositoryService.js +70 -0
  115. package/dist/server/skill-hub/actions/git-import.js +479 -216
  116. package/dist/server/skill-hub/mcp/McpController.js +8 -5
  117. package/dist/server/skill-hub/middlewares/git-import-request-method-policy.js +69 -0
  118. package/dist/server/skill-hub/plugin.js +68 -14
  119. package/dist/server/skill-hub/services/RegistrySkillInstallationService.js +249 -0
  120. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +228 -0
  121. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +15 -3
  122. package/dist/server/tools/skill-execute.js +23 -2
  123. package/dist/server/utils/ctx-utils.js +2 -2
  124. package/dist/server/utils/skill-tool-name.js +73 -0
  125. package/package.json +9 -3
  126. package/src/locale/en-US.json +7 -1
  127. package/src/locale/vi-VN.json +7 -1
  128. package/src/locale/zh-CN.json +7 -1
  129. package/src/server/__tests__/agent-execution-context.test.ts +18 -0
  130. package/src/server/__tests__/input-schema-validator.test.ts +26 -0
  131. package/src/server/__tests__/native-sub-agent-observer.test.ts +52 -2
  132. package/src/server/__tests__/skill-access-service.test.ts +64 -0
  133. package/src/server/__tests__/skill-execute.test.ts +37 -0
  134. package/src/server/__tests__/skill-tool-name.test.ts +23 -0
  135. package/src/server/collections/skill-definitions.ts +31 -0
  136. package/src/server/collections/skill-executions.ts +19 -0
  137. package/src/server/collections/skill-registry-installations.ts +41 -0
  138. package/src/server/migrations/20260727010000-backfill-skill-tool-names.ts +45 -0
  139. package/src/server/plugin.ts +104 -1
  140. package/src/server/services/AgentExecutionContext.ts +23 -0
  141. package/src/server/services/CodeValidator.ts +1 -0
  142. package/src/server/services/ExecutionSpanService.ts +119 -110
  143. package/src/server/services/InputSchemaValidator.ts +44 -0
  144. package/src/server/services/NativeSubAgentObserver.ts +64 -10
  145. package/src/server/services/SandboxRunner.ts +6 -0
  146. package/src/server/services/SkillAccessService.ts +100 -0
  147. package/src/server/services/SkillManager.ts +2 -0
  148. package/src/server/services/SkillRepositoryService.ts +98 -2
  149. package/src/server/services/__tests__/SkillRepositoryService.test.ts +33 -0
  150. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +501 -0
  151. package/src/server/skill-hub/actions/git-import.ts +682 -236
  152. package/src/server/skill-hub/mcp/McpController.ts +8 -14
  153. package/src/server/skill-hub/middlewares/git-import-request-method-policy.ts +51 -0
  154. package/src/server/skill-hub/plugin.ts +79 -13
  155. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +281 -0
  156. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +239 -0
  157. package/src/server/skill-hub/services/__tests__/RegistrySkillInstallationService.test.ts +295 -0
  158. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +63 -0
  159. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +14 -2
  160. package/src/server/tools/skill-execute.ts +24 -2
  161. package/src/server/utils/ctx-utils.ts +1 -1
  162. package/src/server/utils/skill-tool-name.ts +58 -0
@@ -7,11 +7,9 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- var __create = Object.create;
11
10
  var __defProp = Object.defineProperty;
12
11
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
13
  var __hasOwnProp = Object.prototype.hasOwnProperty;
16
14
  var __export = (target, all) => {
17
15
  for (var name in all)
@@ -25,77 +23,84 @@ var __copyProps = (to, from, except, desc) => {
25
23
  }
26
24
  return to;
27
25
  };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
27
  var git_import_exports = {};
38
28
  __export(git_import_exports, {
29
+ GIT_SKILL_MARKDOWN_LIMITS: () => GIT_SKILL_MARKDOWN_LIMITS,
39
30
  gitListSkills: () => gitListSkills,
40
31
  gitSyncSkills: () => gitSyncSkills
41
32
  });
42
33
  module.exports = __toCommonJS(git_import_exports);
43
- var import_fs = require("fs");
44
- var path = __toESM(require("path"));
45
34
  var import_json_fields = require("../utils/json-fields");
35
+ var import_skill_tool_name = require("../../utils/skill-tool-name");
36
+ class GitImportError extends Error {
37
+ constructor(code, status, message, translation) {
38
+ super(message);
39
+ this.code = code;
40
+ this.status = status;
41
+ this.translation = translation;
42
+ this.name = "GitImportError";
43
+ }
44
+ }
45
+ const GIT_MANAGER_CONTENT_CAPABILITY = "skill-hub-content-with-actor";
46
+ const GIT_MANAGER_CONTENT_CONTRACT_VERSION = 2;
47
+ const MISSING_GIT_FILE_CODE = "REGISTRY_GIT_FILE_NOT_FOUND";
48
+ const ACCESS_DENIED_CODE = "SKILL_HUB_REPOSITORY_ACCESS_DENIED";
49
+ const CONTENT_LIMIT_CODE = "REGISTRY_CONTENT_LIMIT_EXCEEDED";
50
+ const GIT_IMPORT_NAMESPACE = "plugin-agent-orchestrator";
46
51
  const CODE_FILES = [
47
52
  ["index.py", "python"],
48
53
  ["index.js", "node"],
49
54
  ["main.py", "python"]
50
55
  ];
56
+ const GIT_SKILL_MARKDOWN_LIMITS = Object.freeze({
57
+ maxFiles: 64,
58
+ maxBytes: 2 * 1024 * 1024
59
+ });
51
60
  async function gitListSkills(ctx, next) {
52
61
  const { repositoryId, ref = "HEAD", prefix = "" } = ctx.action.params;
53
62
  const rootFolder = normalizeRootFolder(ctx.action.params.rootFolder);
54
63
  if (!repositoryId) {
55
64
  ctx.throw(400, "repositoryId and rootFolder are required");
56
65
  }
57
- const gitPlugin = ctx.app.pm.get("plugin-git-manager");
58
- if (!gitPlugin) {
59
- ctx.throw(400, "plugin-git-manager is not installed");
60
- }
61
66
  try {
62
- const repo = await ctx.db.getRepository("gitRepositories").findOne({ filterByTk: repositoryId });
63
- if (!repo) ctx.throw(404, "Repository not found");
64
- const simpleGit = require("simple-git").default;
65
- const localPath = getLocalPath(repo.get("localPath"));
66
- const git = simpleGit(localPath);
67
+ const service = getGitManagerContentService(ctx);
68
+ const access = accessFromContext(ctx);
69
+ const commitSha = await service.resolveCommit(repositoryId, ref, access);
67
70
  const configPath = joinGitPath(rootFolder, "skills.json");
68
- const loaded = await loadSkillsManifest(git, ref, localPath, configPath);
69
- let config = loaded.config;
70
- let initialized = false;
71
- if (!loaded.exists) {
72
- const discovered = await discoverSkills(git, ref, rootFolder);
73
- config = createSkillsManifest(rootFolder, discovered);
74
- initialized = initSkillsManifestFile(localPath, configPath, config);
75
- }
71
+ const skillsRoot = await resolveSkillsRoot(service, repositoryId, commitSha, access, rootFolder);
72
+ const loaded = await loadSkillsManifest(service, repositoryId, commitSha, access, configPath);
73
+ const config = loaded.exists ? loaded.config : createSkillsManifest(
74
+ rootFolder,
75
+ await discoverSkills(service, repositoryId, commitSha, access, rootFolder, skillsRoot)
76
+ );
76
77
  const manifestSkills = Array.isArray(config.skills) ? config.skills.filter((skill) => getSkillKey(skill)) : [];
77
78
  const enriched = manifestSkills.map((skill) => enrichListedSkill(skill, prefix));
78
79
  const existingSkills = enriched.length ? await ctx.db.getRepository("skillDefinitions").find({
79
- filter: { name: { $in: enriched.map((s) => s.name) } },
80
+ filter: { name: { $in: enriched.map((skill) => skill.name) } },
80
81
  fields: ["name"]
81
82
  }) : [];
82
- const existingNames = new Set(existingSkills.map((s) => s.get("name")));
83
+ const existingNames = new Set(
84
+ existingSkills.map((skill) => skill.get("name"))
85
+ );
83
86
  ctx.body = {
84
- data: enriched.map((s) => ({
85
- ...s,
86
- existsInDb: existingNames.has(s.name)
87
+ data: enriched.map((skill) => ({
88
+ ...skill,
89
+ existsInDb: existingNames.has(skill.name)
87
90
  })),
88
91
  config: {
89
92
  name: config.name || rootFolder || "skills",
90
93
  description: config.description || "",
91
94
  rootFolder,
92
95
  path: configPath,
93
- initializedSkillsJson: initialized
96
+ // An absent manifest is intentionally virtual. Writing a new file to
97
+ // Git Manager's checkout would reintroduce a cross-plugin disk bypass.
98
+ initializedSkillsJson: false
94
99
  }
95
100
  };
96
101
  await next();
97
- } catch (err) {
98
- ctx.throw(400, err.message);
102
+ } catch (error) {
103
+ throwGitImportError(ctx, error);
99
104
  }
100
105
  }
101
106
  async function gitSyncSkills(ctx, next) {
@@ -105,176 +110,376 @@ async function gitSyncSkills(ctx, next) {
105
110
  if (!repositoryId || !Array.isArray(selectedKeys) || selectedKeys.length === 0) {
106
111
  ctx.throw(400, "repositoryId, rootFolder and skills[] are required");
107
112
  }
108
- const repo = await ctx.db.getRepository("gitRepositories").findOne({ filterByTk: repositoryId });
109
- if (!repo) ctx.throw(404, "Repository not found");
110
- const simpleGit = require("simple-git").default;
111
- const localPath = getLocalPath(repo.get("localPath"));
112
- const git = simpleGit(localPath);
113
- const configPath = joinGitPath(rootFolder, "skills.json");
114
- const loaded = await loadSkillsManifest(git, ref, localPath, configPath);
115
- let config = loaded.config;
116
- if (!loaded.exists) {
117
- const discovered = await discoverSkills(git, ref, rootFolder);
118
- config = createSkillsManifest(rootFolder, discovered);
119
- initSkillsManifestFile(localPath, configPath, config);
113
+ const selectedSkillKeys = selectedKeys.filter(
114
+ (key) => typeof key === "string" && key.trim().length > 0
115
+ );
116
+ if (selectedSkillKeys.length !== selectedKeys.length) {
117
+ ctx.throw(400, translateGitImportMessage(ctx, "skills[] must contain non-empty string keys"));
120
118
  }
121
- const manifest = /* @__PURE__ */ new Map();
122
- for (const entry of config.skills || []) {
123
- const key = getSkillKey(entry);
124
- if (key) {
125
- manifest.set(key, entry);
126
- }
127
- }
128
- const results = [];
129
- const skillRepo = ctx.db.getRepository("skillDefinitions");
130
- for (const key of selectedKeys) {
131
- const meta = manifest.get(key) || { folder: key, name: key };
132
- const isPluginSkill = isPluginStorage(meta);
133
- const rawName = meta.name || meta.pluginSource || meta.folder || key;
134
- const skillName = `${prefix}${rawName}`;
135
- const skillsSubDir = meta.folder ? joinGitPath(rootFolder, "skills", meta.folder) : "";
136
- const skillBaseDir = skillsSubDir || rootFolder;
137
- try {
138
- let frontmatter = {};
139
- let instructions = "";
140
- if (skillBaseDir || !meta.folder) {
141
- try {
142
- const skillMd = await git.show([`${ref}:${joinGitPath(skillBaseDir, "SKILL.md")}`]);
143
- const parsed = (0, import_json_fields.parseSkillMarkdown)(skillMd);
144
- frontmatter = parsed.metadata;
145
- instructions = parsed.body;
146
- const otherMds = await fetchAllMarkdownInFolder(git, ref, skillBaseDir);
147
- if (otherMds) instructions += otherMds;
148
- } catch {
149
- }
119
+ try {
120
+ const service = getGitManagerContentService(ctx);
121
+ const access = accessFromContext(ctx);
122
+ const commitSha = await service.resolveCommit(repositoryId, ref, access);
123
+ const configPath = joinGitPath(rootFolder, "skills.json");
124
+ const skillsRoot = await resolveSkillsRoot(service, repositoryId, commitSha, access, rootFolder);
125
+ const loaded = await loadSkillsManifest(service, repositoryId, commitSha, access, configPath);
126
+ const config = loaded.exists ? loaded.config : createSkillsManifest(
127
+ rootFolder,
128
+ await discoverSkills(service, repositoryId, commitSha, access, rootFolder, skillsRoot)
129
+ );
130
+ const manifest = /* @__PURE__ */ new Map();
131
+ for (const entry of config.skills || []) {
132
+ const key = getSkillKey(entry);
133
+ if (key) {
134
+ manifest.set(key, entry);
150
135
  }
151
- const storageType = normalizeStorageType(
152
- frontmatter.storageType || meta.storageType || (isPluginSkill ? "plugin" : "git")
153
- );
154
- const pluginSource = frontmatter.pluginSource || meta.pluginSource || (storageType === "plugin" ? rawName : void 0);
155
- let detectedLanguage = frontmatter.language || meta.language || "python";
156
- let codeTemplate = frontmatter.codeTemplate || meta.codeTemplate || "";
157
- if (!codeTemplate && meta.codeFile) {
158
- codeTemplate = await readOptionalGitFile(git, ref, joinGitPath(skillBaseDir, meta.codeFile));
136
+ }
137
+ if (loaded.exists) {
138
+ const unlistedKeys = selectedSkillKeys.filter((key) => !manifest.has(key));
139
+ if (unlistedKeys.length > 0) {
140
+ const skills = unlistedKeys.join(", ");
141
+ throw new GitImportError(
142
+ "SKILL_HUB_SKILL_NOT_LISTED",
143
+ 400,
144
+ `Selected skills are not listed in the explicit skills.json manifest: ${skills}`,
145
+ {
146
+ key: "Selected skills are not listed in the explicit skills.json manifest: {{skills}}",
147
+ values: { skills }
148
+ }
149
+ );
159
150
  }
160
- if (!codeTemplate && storageType !== "plugin") {
161
- const codeFile = await readConventionalCodeFile(git, ref, skillBaseDir);
162
- if (codeFile) {
163
- codeTemplate = codeFile.content;
164
- detectedLanguage = codeFile.language;
151
+ }
152
+ const results = [];
153
+ const skillRepo = ctx.db.getRepository("skillDefinitions");
154
+ for (const key of selectedSkillKeys) {
155
+ const meta = manifest.get(key) || { folder: key, name: key };
156
+ const isPluginSkill = isPluginStorage(meta);
157
+ const rawName = meta.name || meta.pluginSource || meta.folder || key;
158
+ const skillName = `${prefix}${rawName}`;
159
+ const skillsSubDir = meta.folder ? joinGitPath(skillsRoot.path, meta.folder) : "";
160
+ const skillBaseDir = skillsSubDir || rootFolder;
161
+ try {
162
+ let frontmatter = {};
163
+ let instructions = "";
164
+ if (skillBaseDir || !meta.folder) {
165
+ const skillMarkdown = await readOptionalGitFile(
166
+ service,
167
+ repositoryId,
168
+ commitSha,
169
+ access,
170
+ joinGitPath(skillBaseDir, "SKILL.md")
171
+ );
172
+ if (skillMarkdown) {
173
+ try {
174
+ const parsed = (0, import_json_fields.parseSkillMarkdown)(skillMarkdown);
175
+ frontmatter = parsed.metadata;
176
+ instructions = parsed.body;
177
+ const otherMarkdown = await fetchAllMarkdownInFolder(
178
+ service,
179
+ repositoryId,
180
+ commitSha,
181
+ access,
182
+ skillBaseDir
183
+ );
184
+ if (otherMarkdown) instructions += otherMarkdown;
185
+ } catch (error) {
186
+ if (isFatalGitContentError(error)) {
187
+ throw error;
188
+ }
189
+ }
190
+ }
165
191
  }
192
+ const storageType = normalizeStorageType(
193
+ frontmatter.storageType || meta.storageType || (isPluginSkill ? "plugin" : "git")
194
+ );
195
+ const pluginSource = frontmatter.pluginSource || meta.pluginSource || (storageType === "plugin" ? rawName : void 0);
196
+ let detectedLanguage = frontmatter.language || meta.language || "python";
197
+ let codeTemplate = frontmatter.codeTemplate || meta.codeTemplate || "";
198
+ if (!codeTemplate && meta.codeFile) {
199
+ codeTemplate = await readOptionalGitFile(
200
+ service,
201
+ repositoryId,
202
+ commitSha,
203
+ access,
204
+ joinGitPath(skillBaseDir, meta.codeFile)
205
+ );
206
+ }
207
+ if (!codeTemplate && storageType !== "plugin") {
208
+ const codeFile = await readConventionalCodeFile(service, repositoryId, commitSha, access, skillBaseDir);
209
+ if (codeFile) {
210
+ codeTemplate = codeFile.content;
211
+ detectedLanguage = codeFile.language;
212
+ }
213
+ }
214
+ const toolName = (0, import_skill_tool_name.buildSkillToolName)(skillName);
215
+ const merged = {
216
+ name: skillName,
217
+ toolName,
218
+ title: frontmatter.title || meta.title || rawName,
219
+ description: frontmatter.description || meta.description || "",
220
+ language: detectedLanguage,
221
+ storageType,
222
+ storageUrl: storageType === "plugin" ? `git://${repositoryId}/${rootFolder || ""}@${commitSha}#${pluginSource || rawName}` : `git://${repositoryId}/${skillsSubDir || rootFolder || ""}@${commitSha}`,
223
+ timeoutSeconds: parseInteger(frontmatter.timeoutSeconds ?? meta.timeoutSeconds, 60),
224
+ maxOutputSizeMb: parseInteger(frontmatter.maxOutputSizeMb ?? meta.maxOutputSizeMb, 50),
225
+ toolScope: frontmatter.toolScope || meta.toolScope || "CUSTOM",
226
+ enabled: parseBoolean(frontmatter.enabled ?? meta.enabled, true),
227
+ autoCall: parseBoolean(frontmatter.autoCall ?? meta.autoCall, false),
228
+ packages: (0, import_json_fields.stringifyJsonText)((0, import_json_fields.parseJsonLike)(meta.packages ?? frontmatter.packages, []), [])
229
+ };
230
+ if (codeTemplate) {
231
+ merged.codeTemplate = codeTemplate;
232
+ }
233
+ if (pluginSource) {
234
+ merged.pluginSource = pluginSource;
235
+ }
236
+ if (instructions) {
237
+ merged.instructions = instructions.trim();
238
+ }
239
+ const inputSchema = (0, import_json_fields.parseJsonLike)(frontmatter.inputSchema ?? meta.inputSchema, null);
240
+ if (inputSchema) {
241
+ merged.inputSchema = (0, import_json_fields.stringifyJsonText)(inputSchema);
242
+ }
243
+ const interactionSchema = (0, import_json_fields.parseJsonLike)(frontmatter.interactionSchema ?? meta.interactionSchema, null);
244
+ if (interactionSchema) {
245
+ merged.interactionSchema = (0, import_json_fields.stringifyJsonText)(interactionSchema);
246
+ }
247
+ const existing = await skillRepo.findOne({ filter: { name: skillName } });
248
+ if (existing && !overwrite) {
249
+ results.push({ folder: key, name: skillName, status: "skipped", reason: "Already exists" });
250
+ continue;
251
+ }
252
+ if (existing) {
253
+ delete merged.toolName;
254
+ await skillRepo.update({ filterByTk: existing.get("id"), values: merged });
255
+ results.push({ folder: key, name: skillName, status: "updated" });
256
+ } else {
257
+ await (0, import_skill_tool_name.assertSkillToolNameAvailable)(ctx.db, toolName);
258
+ await skillRepo.create({ values: merged });
259
+ results.push({ folder: key, name: skillName, status: "created" });
260
+ }
261
+ } catch (error) {
262
+ if (isFatalGitContentError(error)) {
263
+ throw error;
264
+ }
265
+ results.push({ folder: key, name: skillName, status: "error", reason: errorMessage(error) });
166
266
  }
167
- const merged = {
168
- name: skillName,
169
- title: frontmatter.title || meta.title || rawName,
170
- description: frontmatter.description || meta.description || "",
171
- language: detectedLanguage,
172
- storageType,
173
- storageUrl: storageType === "plugin" ? `git://${repositoryId}/${rootFolder || ""}@${ref}#${pluginSource || rawName}` : `git://${repositoryId}/${skillsSubDir || rootFolder || ""}@${ref}`,
174
- timeoutSeconds: parseInteger(frontmatter.timeoutSeconds ?? meta.timeoutSeconds, 60),
175
- maxOutputSizeMb: parseInteger(frontmatter.maxOutputSizeMb ?? meta.maxOutputSizeMb, 50),
176
- toolScope: frontmatter.toolScope || meta.toolScope || "CUSTOM",
177
- enabled: parseBoolean(frontmatter.enabled ?? meta.enabled, true),
178
- autoCall: parseBoolean(frontmatter.autoCall ?? meta.autoCall, false),
179
- packages: (0, import_json_fields.stringifyJsonText)((0, import_json_fields.parseJsonLike)(meta.packages ?? frontmatter.packages, []), [])
180
- };
181
- if (codeTemplate) {
182
- merged.codeTemplate = codeTemplate;
183
- }
184
- if (pluginSource) {
185
- merged.pluginSource = pluginSource;
186
- }
187
- if (instructions) {
188
- merged.instructions = instructions.trim();
189
- }
190
- const inputSchema = (0, import_json_fields.parseJsonLike)(frontmatter.inputSchema ?? meta.inputSchema, null);
191
- if (inputSchema) {
192
- merged.inputSchema = (0, import_json_fields.stringifyJsonText)(inputSchema);
193
- }
194
- const interactionSchema = (0, import_json_fields.parseJsonLike)(frontmatter.interactionSchema ?? meta.interactionSchema, null);
195
- if (interactionSchema) {
196
- merged.interactionSchema = (0, import_json_fields.stringifyJsonText)(interactionSchema);
197
- }
198
- const existing = await skillRepo.findOne({ filter: { name: skillName } });
199
- if (existing && !overwrite) {
200
- results.push({ folder: key, name: skillName, status: "skipped", reason: "Already exists" });
201
- continue;
202
- }
203
- if (existing) {
204
- await skillRepo.update({ filterByTk: existing.get("id"), values: merged });
205
- results.push({ folder: key, name: skillName, status: "updated" });
206
- } else {
207
- await skillRepo.create({ values: merged });
208
- results.push({ folder: key, name: skillName, status: "created" });
209
- }
210
- } catch (err) {
211
- results.push({ folder: key, name: skillName, status: "error", reason: err.message });
212
267
  }
268
+ ctx.body = { data: results };
269
+ await next();
270
+ } catch (error) {
271
+ throwGitImportError(ctx, error);
272
+ }
273
+ }
274
+ function getGitManagerContentService(ctx) {
275
+ const pluginManager = ctx.app.pm;
276
+ const plugin = pluginManager == null ? void 0 : pluginManager.get("plugin-git-manager");
277
+ if (!plugin || typeof plugin !== "object") {
278
+ throw new GitImportError(
279
+ "GIT_MANAGER_CONTENT_UNAVAILABLE",
280
+ 424,
281
+ "Git Manager is not enabled for Skill Hub imports."
282
+ );
283
+ }
284
+ const service = plugin.skillHubContentService;
285
+ if (!service || typeof service !== "object") {
286
+ throw new GitImportError(
287
+ "GIT_MANAGER_CONTENT_UNAVAILABLE",
288
+ 424,
289
+ "Git Manager must support actor-aware content reads for Skill Hub imports."
290
+ );
291
+ }
292
+ const candidate = service;
293
+ const contractVersion = candidate.contractVersion;
294
+ const capabilities = candidate.capabilities;
295
+ const hasCompatibleContract = typeof contractVersion === "number" && Number.isSafeInteger(contractVersion) && contractVersion >= GIT_MANAGER_CONTENT_CONTRACT_VERSION;
296
+ if (!hasCompatibleContract || !Array.isArray(capabilities) || !capabilities.includes(GIT_MANAGER_CONTENT_CAPABILITY) || typeof candidate.resolveCommit !== "function" || typeof candidate.listTree !== "function" || typeof candidate.readFile !== "function") {
297
+ throw new GitImportError(
298
+ "GIT_MANAGER_CONTENT_UNAVAILABLE",
299
+ 424,
300
+ "Git Manager must support actor-aware content reads for Skill Hub imports."
301
+ );
302
+ }
303
+ return service;
304
+ }
305
+ function accessFromContext(ctx) {
306
+ var _a;
307
+ const currentRoles = (_a = ctx.state) == null ? void 0 : _a.currentRoles;
308
+ if (!Array.isArray(currentRoles) || !currentRoles.every((role) => typeof role === "string")) {
309
+ throw new GitImportError(
310
+ "SKILL_HUB_REPOSITORY_ACCESS_DENIED",
311
+ 403,
312
+ "A valid user role context is required to import skills from Git Manager."
313
+ );
314
+ }
315
+ return { kind: "user", roles: currentRoles };
316
+ }
317
+ function errorCode(error) {
318
+ if (!error || typeof error !== "object") return void 0;
319
+ const code = error.code;
320
+ return typeof code === "string" ? code : void 0;
321
+ }
322
+ function errorMessage(error) {
323
+ return error instanceof Error ? error.message : String(error);
324
+ }
325
+ function isMissingGitFile(error) {
326
+ return errorCode(error) === MISSING_GIT_FILE_CODE;
327
+ }
328
+ function isFatalGitContentError(error) {
329
+ if (error instanceof GitImportError) return true;
330
+ const code = errorCode(error);
331
+ return code === ACCESS_DENIED_CODE || code === CONTENT_LIMIT_CODE;
332
+ }
333
+ function throwGitImportError(ctx, error) {
334
+ if (error instanceof GitImportError) {
335
+ return throwHttpError(ctx, error.status, error.message, error.translation);
336
+ }
337
+ switch (errorCode(error)) {
338
+ case ACCESS_DENIED_CODE:
339
+ return throwHttpError(ctx, 403, errorMessage(error));
340
+ case CONTENT_LIMIT_CODE:
341
+ return throwHttpError(ctx, 422, errorMessage(error));
342
+ case MISSING_GIT_FILE_CODE:
343
+ return throwHttpError(ctx, 404, errorMessage(error));
344
+ default:
345
+ return throwHttpError(ctx, 502, "Git Manager could not read the requested repository content.");
213
346
  }
214
- ctx.body = { data: results };
215
- await next();
216
347
  }
217
- async function loadSkillsManifest(git, ref, localPath, configPath) {
218
- let raw = null;
348
+ function translateGitImportMessage(ctx, key, values, fallback = key) {
349
+ const translate = ctx.t;
350
+ if (typeof translate !== "function") {
351
+ return fallback;
352
+ }
353
+ const translated = translate(key, { ns: GIT_IMPORT_NAMESPACE, ...values });
354
+ return typeof translated === "string" ? translated : fallback;
355
+ }
356
+ function throwHttpError(ctx, status, message, translation) {
357
+ const localizedMessage = translation ? translateGitImportMessage(ctx, translation.key, translation.values, message) : message;
358
+ return ctx.throw(status, localizedMessage);
359
+ }
360
+ async function loadSkillsManifest(service, repositoryId, commitSha, access, configPath) {
361
+ let raw;
219
362
  try {
220
- raw = await git.show([`${ref}:${configPath}`]);
221
- } catch {
222
- const filePath = resolveRepoFile(localPath, configPath);
223
- if ((0, import_fs.existsSync)(filePath)) {
224
- raw = (0, import_fs.readFileSync)(filePath, "utf8");
363
+ raw = (await service.readFile({ repositoryId, commitSha, filePath: configPath }, access)).toString("utf8");
364
+ } catch (error) {
365
+ if (isMissingGitFile(error)) {
366
+ return { exists: false, config: {} };
225
367
  }
226
- }
227
- if (!raw) {
228
- return { exists: false, config: {} };
368
+ throw error;
229
369
  }
230
370
  try {
231
371
  return { exists: true, config: JSON.parse(raw) };
232
- } catch (err) {
233
- throw new Error(`Invalid ${configPath}: ${err.message}`);
372
+ } catch (error) {
373
+ throw new Error(`Invalid ${configPath}: ${errorMessage(error)}`);
234
374
  }
235
375
  }
236
- async function discoverSkills(git, ref, rootFolder) {
237
- const folderSkills = await discoverSkillFolders(git, ref, rootFolder);
238
- if (folderSkills.length > 0) {
239
- return folderSkills;
376
+ async function discoverSkills(service, repositoryId, commitSha, access, rootFolder, skillsRoot) {
377
+ if (skillsRoot.folders.length > 0) {
378
+ return skillsRoot.folders;
240
379
  }
241
- const pluginSkill = await discoverPluginSkill(git, ref, rootFolder);
380
+ const pluginSkill = await discoverPluginSkill(service, repositoryId, commitSha, access, rootFolder);
242
381
  return pluginSkill ? [pluginSkill] : [];
243
382
  }
244
- async function discoverSkillFolders(git, ref, rootFolder) {
245
- const baseDir = joinGitPath(rootFolder, "skills");
383
+ async function resolveSkillsRoot(service, repositoryId, commitSha, access, rootFolder) {
384
+ const configuredRoot = normalizeRootFolder(rootFolder);
385
+ const rootEntries = await service.listTree(
386
+ { repositoryId, commitSha, rootPath: configuredRoot, recursive: false },
387
+ access
388
+ );
389
+ const configuredRootIsSkillsDirectory = configuredRoot === "skills" || configuredRoot.endsWith("/skills");
390
+ const directFolders = await discoverSkillFoldersAtRoot(
391
+ service,
392
+ repositoryId,
393
+ commitSha,
394
+ access,
395
+ configuredRoot,
396
+ rootEntries
397
+ );
398
+ if (directFolders.length > 0 || configuredRootIsSkillsDirectory) {
399
+ return { path: configuredRoot, folders: directFolders };
400
+ }
401
+ const hasSkillsSubfolder = rootEntries.some((entry) => entry.type === "tree" && entry.path === "skills");
402
+ if (!hasSkillsSubfolder) {
403
+ return { path: configuredRoot, folders: directFolders };
404
+ }
405
+ const fallbackRoot = joinGitPath(configuredRoot, "skills");
406
+ return {
407
+ path: fallbackRoot,
408
+ folders: await discoverSkillFoldersAtRoot(service, repositoryId, commitSha, access, fallbackRoot)
409
+ };
410
+ }
411
+ async function discoverSkillFoldersAtRoot(service, repositoryId, commitSha, access, baseDir, rootEntries) {
246
412
  try {
247
- const dirs = await git.raw(["ls-tree", "-d", "--name-only", `${ref}:${baseDir}/`]);
248
- return dirs.trim().split("\n").filter(Boolean).map((folder) => ({
249
- folder,
250
- name: folder,
251
- title: folder,
252
- storageType: "git"
253
- }));
254
- } catch {
255
- return [];
413
+ const entries = rootEntries || await service.listTree({ repositoryId, commitSha, rootPath: baseDir, recursive: false }, access);
414
+ const folders = entries.filter((entry) => entry.type === "tree").map((entry) => entry.path);
415
+ const discovered = [];
416
+ const batchSize = 16;
417
+ for (let offset = 0; offset < folders.length; offset += batchSize) {
418
+ const batch = folders.slice(offset, offset + batchSize);
419
+ const results = await Promise.all(
420
+ batch.map(async (folder) => {
421
+ const folderEntries = await service.listTree(
422
+ { repositoryId, commitSha, rootPath: joinGitPath(baseDir, folder), recursive: false },
423
+ access
424
+ );
425
+ return folderEntries.some((entry) => entry.type === "blob" && entry.path === "SKILL.md") ? folder : null;
426
+ })
427
+ );
428
+ for (const folder of results) {
429
+ if (folder) {
430
+ discovered.push({ folder, name: folder, title: folder, storageType: "git" });
431
+ }
432
+ }
433
+ }
434
+ return discovered;
435
+ } catch (error) {
436
+ if (isMissingGitFile(error)) {
437
+ return [];
438
+ }
439
+ throw error;
256
440
  }
257
441
  }
258
- async function discoverPluginSkill(git, ref, rootFolder) {
442
+ async function discoverPluginSkill(service, repositoryId, commitSha, access, rootFolder) {
259
443
  const packageJsonPath = joinGitPath(rootFolder, "package.json");
444
+ const rawPackageJson = await readOptionalGitFile(service, repositoryId, commitSha, access, packageJsonPath);
445
+ if (!rawPackageJson) {
446
+ return null;
447
+ }
260
448
  let packageJson;
261
449
  try {
262
- packageJson = JSON.parse(await git.show([`${ref}:${packageJsonPath}`]));
450
+ const parsed = JSON.parse(rawPackageJson);
451
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
452
+ return null;
453
+ }
454
+ packageJson = parsed;
263
455
  } catch {
264
456
  return null;
265
457
  }
266
- const definition = await readOptionalGitFile(git, ref, joinGitPath(rootFolder, "src/server/skill-definition.ts")) || await readOptionalGitFile(git, ref, joinGitPath(rootFolder, "src/server/skill-definition.js"));
458
+ const definition = await readOptionalGitFile(
459
+ service,
460
+ repositoryId,
461
+ commitSha,
462
+ access,
463
+ joinGitPath(rootFolder, "src/server/skill-definition.ts")
464
+ ) || await readOptionalGitFile(
465
+ service,
466
+ repositoryId,
467
+ commitSha,
468
+ access,
469
+ joinGitPath(rootFolder, "src/server/skill-definition.js")
470
+ );
267
471
  const templateName = definition ? extractStringProperty(definition, "name") : null;
268
472
  const title = definition ? extractStringProperty(definition, "title") : null;
269
473
  const language = definition ? extractStringProperty(definition, "language") : null;
270
- const pluginSource = templateName || packageJson.name;
474
+ const packageName = stringValue(packageJson.name);
475
+ const pluginSource = templateName || packageName;
271
476
  if (!pluginSource) {
272
477
  return null;
273
478
  }
274
479
  return {
275
480
  name: pluginSource,
276
- title: title || packageJson.displayName || packageJson.name || pluginSource,
277
- description: packageJson.description || "",
481
+ title: title || stringValue(packageJson.displayName) || packageName || pluginSource,
482
+ description: stringValue(packageJson.description) || "",
278
483
  language: language || "python",
279
484
  storageType: "plugin",
280
485
  pluginSource
@@ -288,30 +493,30 @@ function createSkillsManifest(rootFolder, skills) {
288
493
  skills
289
494
  };
290
495
  }
291
- function initSkillsManifestFile(localPath, configPath, config) {
292
- const filePath = resolveRepoFile(localPath, configPath);
293
- if ((0, import_fs.existsSync)(filePath)) {
294
- return false;
295
- }
296
- (0, import_fs.mkdirSync)(path.dirname(filePath), { recursive: true });
297
- (0, import_fs.writeFileSync)(filePath, `${JSON.stringify(config, null, 2)}
298
- `, "utf8");
299
- return true;
300
- }
301
- async function readConventionalCodeFile(git, ref, skillsSubDir) {
496
+ async function readConventionalCodeFile(service, repositoryId, commitSha, access, skillsSubDir) {
302
497
  for (const [file, language] of CODE_FILES) {
303
- const content = await readOptionalGitFile(git, ref, joinGitPath(skillsSubDir, file));
498
+ const content = await readOptionalGitFile(
499
+ service,
500
+ repositoryId,
501
+ commitSha,
502
+ access,
503
+ joinGitPath(skillsSubDir, file)
504
+ );
304
505
  if (content) {
305
506
  return { content, language };
306
507
  }
307
508
  }
308
509
  return null;
309
510
  }
310
- async function readOptionalGitFile(git, ref, filePath) {
511
+ async function readOptionalGitFile(service, repositoryId, commitSha, access, filePath, maxBytes) {
311
512
  try {
312
- return await git.show([`${ref}:${filePath}`]);
313
- } catch {
314
- return "";
513
+ const input = maxBytes === void 0 ? { repositoryId, commitSha, filePath } : { repositoryId, commitSha, filePath, maxBytes };
514
+ return (await service.readFile(input, access)).toString("utf8");
515
+ } catch (error) {
516
+ if (isMissingGitFile(error)) {
517
+ return "";
518
+ }
519
+ throw error;
315
520
  }
316
521
  }
317
522
  function enrichListedSkill(skill, prefix) {
@@ -346,7 +551,7 @@ function normalizeStorageType(storageType) {
346
551
  return "git";
347
552
  }
348
553
  function parseInteger(value, fallback) {
349
- const parsed = parseInt(value, 10);
554
+ const parsed = Number.parseInt(String(value), 10);
350
555
  return Number.isFinite(parsed) ? parsed : fallback;
351
556
  }
352
557
  function parseBoolean(value, fallback) {
@@ -356,7 +561,7 @@ function parseBoolean(value, fallback) {
356
561
  return Boolean(value);
357
562
  }
358
563
  function extractStringProperty(source, property) {
359
- const match = source.match(new RegExp(`${property}\\s*:\\s*(['"\`])([\\s\\S]*?)\\1`));
564
+ const match = source.match(new RegExp(property + `\\s*:\\s*(['"\\x60])([\\s\\S]*?)\\1`));
360
565
  return match ? match[2] : null;
361
566
  }
362
567
  function normalizeRootFolder(rootFolder) {
@@ -369,45 +574,103 @@ function normalizeRootFolder(rootFolder) {
369
574
  }
370
575
  return normalized;
371
576
  }
577
+ function stringValue(value) {
578
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
579
+ }
372
580
  function joinGitPath(...parts) {
373
581
  return parts.filter((part) => part !== void 0 && part !== "").join("/").replace(/\/+/g, "/");
374
582
  }
375
- function resolveRepoFile(localPath, gitPath) {
376
- const basePath = path.resolve(localPath);
377
- const resolved = path.resolve(basePath, ...gitPath.split("/").filter(Boolean));
378
- if (resolved !== basePath && !resolved.startsWith(basePath + path.sep)) {
379
- throw new Error("Invalid file path");
380
- }
381
- return resolved;
583
+ function markdownContentHeader(path) {
584
+ return `
585
+
586
+ --- Content from ${path} ---
587
+
588
+ `;
382
589
  }
383
- function getLocalPath(localPath) {
384
- const basePath = process.env.GIT_REPOS_BASE_PATH || path.join(process.cwd(), "storage", "git-repos");
385
- if (path.isAbsolute(localPath)) return localPath;
386
- return path.resolve(basePath, localPath);
590
+ function markdownContentLimitError(message, translation) {
591
+ return new GitImportError("REGISTRY_CONTENT_LIMIT_EXCEEDED", 422, message, translation);
387
592
  }
388
- async function fetchAllMarkdownInFolder(git, ref, folderPath) {
389
- let combined = "";
593
+ async function fetchAllMarkdownInFolder(service, repositoryId, commitSha, access, folderPath) {
390
594
  try {
391
- const filesOut = await git.raw(["ls-tree", "-r", "--name-only", `${ref}:${folderPath}/`]);
392
- const files = filesOut.trim().split("\n").filter(Boolean);
393
- for (const file of files) {
394
- if (file.toLowerCase().endsWith(".md") && file.toUpperCase() !== "SKILL.md") {
395
- const content = await readOptionalGitFile(git, ref, joinGitPath(folderPath, file));
396
- if (content) {
397
- combined += `
398
-
399
- --- Content from ${file} ---
400
-
401
- ${content}`;
595
+ const entries = await service.listTree({ repositoryId, commitSha, rootPath: folderPath, recursive: true }, access);
596
+ const markdownEntries = entries.filter(
597
+ (entry) => entry.type === "blob" && entry.path.toLowerCase().endsWith(".md") && entry.path.toUpperCase() !== "SKILL.MD"
598
+ ).sort((left, right) => left.path.localeCompare(right.path));
599
+ if (markdownEntries.length > GIT_SKILL_MARKDOWN_LIMITS.maxFiles) {
600
+ throw markdownContentLimitError(
601
+ `Git skill contains more than ${GIT_SKILL_MARKDOWN_LIMITS.maxFiles} supplemental Markdown files.`,
602
+ {
603
+ key: "Git skill contains more than {{count}} supplemental Markdown files.",
604
+ values: { count: GIT_SKILL_MARKDOWN_LIMITS.maxFiles }
605
+ }
606
+ );
607
+ }
608
+ let declaredBytes = 0;
609
+ for (const entry of markdownEntries) {
610
+ if (!Number.isSafeInteger(entry.size) || entry.size < 0) {
611
+ throw markdownContentLimitError("Git skill contains a supplemental Markdown file with an invalid size.", {
612
+ key: "Git skill contains a supplemental Markdown file with an invalid size."
613
+ });
614
+ }
615
+ declaredBytes += Buffer.byteLength(markdownContentHeader(entry.path), "utf8") + entry.size;
616
+ if (declaredBytes > GIT_SKILL_MARKDOWN_LIMITS.maxBytes) {
617
+ throw markdownContentLimitError(
618
+ `Git skill supplemental Markdown exceeds ${GIT_SKILL_MARKDOWN_LIMITS.maxBytes} bytes.`,
619
+ {
620
+ key: "Git skill supplemental Markdown exceeds {{maxBytes}} bytes.",
621
+ values: { maxBytes: GIT_SKILL_MARKDOWN_LIMITS.maxBytes }
622
+ }
623
+ );
624
+ }
625
+ }
626
+ let combined = "";
627
+ let combinedBytes = 0;
628
+ for (const entry of markdownEntries) {
629
+ const header = markdownContentHeader(entry.path);
630
+ const remainingContentBytes = GIT_SKILL_MARKDOWN_LIMITS.maxBytes - combinedBytes - Buffer.byteLength(header, "utf8");
631
+ if (remainingContentBytes <= 0) {
632
+ throw markdownContentLimitError(
633
+ `Git skill supplemental Markdown exceeds ${GIT_SKILL_MARKDOWN_LIMITS.maxBytes} bytes.`,
634
+ {
635
+ key: "Git skill supplemental Markdown exceeds {{maxBytes}} bytes.",
636
+ values: { maxBytes: GIT_SKILL_MARKDOWN_LIMITS.maxBytes }
637
+ }
638
+ );
639
+ }
640
+ const content = await readOptionalGitFile(
641
+ service,
642
+ repositoryId,
643
+ commitSha,
644
+ access,
645
+ joinGitPath(folderPath, entry.path),
646
+ remainingContentBytes
647
+ );
648
+ if (content) {
649
+ const contentBytes = Buffer.byteLength(content, "utf8");
650
+ if (contentBytes > remainingContentBytes) {
651
+ throw markdownContentLimitError(
652
+ `Git skill supplemental Markdown exceeds ${GIT_SKILL_MARKDOWN_LIMITS.maxBytes} bytes.`,
653
+ {
654
+ key: "Git skill supplemental Markdown exceeds {{maxBytes}} bytes.",
655
+ values: { maxBytes: GIT_SKILL_MARKDOWN_LIMITS.maxBytes }
656
+ }
657
+ );
402
658
  }
659
+ combined += header + content;
660
+ combinedBytes += Buffer.byteLength(header, "utf8") + contentBytes;
403
661
  }
404
662
  }
405
- } catch (err) {
663
+ return combined;
664
+ } catch (error) {
665
+ if (isMissingGitFile(error)) {
666
+ return "";
667
+ }
668
+ throw error;
406
669
  }
407
- return combined;
408
670
  }
409
671
  // Annotate the CommonJS export names for ESM import in node:
410
672
  0 && (module.exports = {
673
+ GIT_SKILL_MARKDOWN_LIMITS,
411
674
  gitListSkills,
412
675
  gitSyncSkills
413
676
  });