@cuylabs/agent-capability-pack 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # @cuylabs/agent-capability-pack
2
+
3
+ Distributable capability packs for `@cuylabs/agent-core`.
4
+
5
+ A capability pack is a single unit that can contribute:
6
+
7
+ - skills
8
+ - MCP server configurations
9
+ - plugin contributions
10
+
11
+ This package gives you:
12
+
13
+ - `defineCapabilityPack()` for inline or package-authored packs
14
+ - `PackRef` + source resolvers for inline, local, npm, URL, and git sources
15
+ - `PackLoader` to register pack content into `agent-core`
16
+ - `MCPSkillBridge` to surface MCP prompts as skills
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pnpm add @cuylabs/agent-capability-pack @cuylabs/agent-core
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ```ts
27
+ import { emptySkillRegistry } from "@cuylabs/agent-core/skill";
28
+ import { PluginRegistry } from "@cuylabs/agent-core/plugin";
29
+ import { createMCPManager } from "@cuylabs/agent-core/mcp";
30
+ import {
31
+ PackLoader,
32
+ defineCapabilityPack,
33
+ inlinePack,
34
+ MCPSkillBridge,
35
+ } from "@cuylabs/agent-capability-pack";
36
+
37
+ const skillRegistry = emptySkillRegistry();
38
+ const pluginRegistry = new PluginRegistry();
39
+
40
+ const localPack = defineCapabilityPack({
41
+ id: "demo-pack",
42
+ name: "Demo Pack",
43
+ skills: [
44
+ {
45
+ name: "demo-skill",
46
+ description: "Use when the task needs the demo workflow.",
47
+ body: "# Demo Skill\n\nFollow the demo workflow carefully.",
48
+ },
49
+ ],
50
+ });
51
+
52
+ const loader = new PackLoader({ skillRegistry, pluginRegistry });
53
+ const result = await loader.loadAll([inlinePack(localPack)]);
54
+
55
+ const mcp = createMCPManager(result.mcpServers);
56
+ await mcp.connect();
57
+
58
+ const bridge = new MCPSkillBridge(mcp, skillRegistry);
59
+ await bridge.bridge();
60
+ ```
61
+
62
+ ## Docs
63
+
64
+ - [docs/README.md](./docs/README.md)
65
+ - [docs/authoring.md](./docs/authoring.md)
66
+ - [docs/sources.md](./docs/sources.md)
67
+ - [docs/mcp-bridge.md](./docs/mcp-bridge.md)
@@ -0,0 +1,77 @@
1
+ import { MCPManager } from '@cuylabs/agent-core/mcp';
2
+ import { SkillRegistry } from '@cuylabs/agent-core/skill';
3
+
4
+ /**
5
+ * MCPSkillBridge — surfaces MCP server prompts as skills in the SkillRegistry.
6
+ *
7
+ * This is the fix for the missing connection between the MCP and skill
8
+ * subsystems. When an MCP server declares prompts (via `prompts/list`),
9
+ * those prompts are activated the same way as file-based skills — the agent
10
+ * calls the `skill` tool, the bridge fetches the prompt from the server and
11
+ * returns its content as L2 skill content.
12
+ *
13
+ * ## How it works
14
+ *
15
+ * 1. `bridge()` calls `mcpManager.listPrompts()` to get all prompts from
16
+ * connected servers.
17
+ * 2. Each prompt becomes a `SkillMetadata` entry registered in the
18
+ * `SkillRegistry` (L1 — always visible to the agent).
19
+ * 3. Static prompts (no arguments) are rendered immediately via
20
+ * `mcpManager.getPrompt()` and cached as L2 skill content.
21
+ * 4. Parameterized prompts are converted into metadata-backed skill content
22
+ * that lists prompt arguments and usage.
23
+ *
24
+ * ## Naming
25
+ *
26
+ * Bridged skill names are scoped to their server to avoid collisions:
27
+ * `<serverName>:<promptName>`
28
+ *
29
+ * If a project or user skill with the same name exists, it wins
30
+ * (the registry's `register()` respects scope priority).
31
+ *
32
+ * ## Usage
33
+ *
34
+ * Call `bridge()` AFTER `mcpManager.connect()` and before the agent loop:
35
+ *
36
+ * ```ts
37
+ * await mcpManager.connect()
38
+ * const bridge = new MCPSkillBridge(mcpManager, skillRegistry)
39
+ * const result = await bridge.bridge()
40
+ * // result.bridgedCount — skills registered from MCP prompts
41
+ * // result.errors — servers that failed to list prompts
42
+ * ```
43
+ */
44
+
45
+ interface BridgeResult {
46
+ /** Number of MCP prompts successfully registered or updated as skills. */
47
+ bridgedCount: number;
48
+ /**
49
+ * Non-fatal bridge warnings or errors.
50
+ * Static prompts may still bridge successfully while returning a fallback warning.
51
+ */
52
+ errors: Array<{
53
+ server: string;
54
+ error: string;
55
+ }>;
56
+ }
57
+ /**
58
+ * Bridges MCP server prompts into the skill registry as first-class skills.
59
+ *
60
+ * The bridge is designed to be called once per agent session, after
61
+ * `mcpManager.connect()` resolves. It is idempotent — calling `bridge()`
62
+ * multiple times updates previously bridged skills in place.
63
+ */
64
+ declare class MCPSkillBridge {
65
+ private readonly mcpManager;
66
+ private readonly skillRegistry;
67
+ constructor(mcpManager: MCPManager, skillRegistry: SkillRegistry);
68
+ /**
69
+ * Discover all prompts from connected MCP servers and register them as skills.
70
+ *
71
+ * @returns Summary of what was bridged and any errors encountered.
72
+ */
73
+ bridge(): Promise<BridgeResult>;
74
+ private buildPromptSkill;
75
+ }
76
+
77
+ export { type BridgeResult, MCPSkillBridge };
@@ -0,0 +1,7 @@
1
+ import {
2
+ MCPSkillBridge
3
+ } from "../chunk-LDYHPSNE.js";
4
+ export {
5
+ MCPSkillBridge
6
+ };
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,25 @@
1
+ // src/sources/types.ts
2
+ function inlinePack(pack) {
3
+ return { source: "inline", pack };
4
+ }
5
+ function localPack(path) {
6
+ return { source: "local", path };
7
+ }
8
+ function npmPack(pkg, options) {
9
+ return { source: "npm", package: pkg, export: options?.export };
10
+ }
11
+ function urlPack(url) {
12
+ return { source: "url", url };
13
+ }
14
+ function gitPack(url, ref) {
15
+ return { source: "git", url, ...ref ? { ref } : {} };
16
+ }
17
+
18
+ export {
19
+ inlinePack,
20
+ localPack,
21
+ npmPack,
22
+ urlPack,
23
+ gitPack
24
+ };
25
+ //# sourceMappingURL=chunk-2TICMDUA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sources/types.ts"],"sourcesContent":["/**\n * PackRef — typed references to capability packs from external sources.\n *\n * A `PackRef` tells the resolver WHERE to get a pack.\n * Every ref resolves to the same `CapabilityPack` shape, regardless of origin.\n *\n * Use the helper constructors below rather than building refs by hand:\n *\n * inlinePack(pack) — already-constructed CapabilityPack\n * localPack(\"./path\") — directory on disk with a pack.json\n * npmPack(\"@org/my-pack\") — npm package exporting a CapabilityPack\n * urlPack(\"https://...\") — URL serving a pack JSON manifest\n * gitPack(\"https://...\") — Git repository containing a pack\n */\n\nimport type { CapabilityPack } from \"../pack/types.js\";\n\n// ============================================================================\n// PackRef discriminated union\n// ============================================================================\n\n/** A pack that is already constructed — no resolution needed. */\nexport interface InlinePackRef {\n source: \"inline\";\n pack: CapabilityPack;\n}\n\n/**\n * A pack stored in a local directory.\n *\n * The directory must contain a `pack.json` manifest. Skills are discovered\n * from a `skills/` subdirectory using the SKILL.md convention. MCP server\n * configs and plugin entry paths are read from `pack.json`.\n */\nexport interface LocalPackRef {\n source: \"local\";\n /** Absolute or cwd-relative path to the pack directory. */\n path: string;\n}\n\n/**\n * A pack published as an npm package.\n *\n * The package must have a default export or a named export that is a\n * `CapabilityPack`. The resolver uses a dynamic `import()`.\n *\n * @example\n * ```ts\n * npmPack(\"@mycompany/agent-pack\")\n * npmPack(\"@mycompany/agent-pack\", { export: \"dataPack\" })\n * ```\n */\nexport interface NpmPackRef {\n source: \"npm\";\n /** npm package specifier (e.g. \"@mycompany/agent-pack\" or \"agent-pack@1.2.0\"). */\n package: string;\n /**\n * Named export to use as the pack.\n *\n * When omitted, the default export is used.\n */\n export?: string;\n}\n\n/**\n * A pack served as JSON at a URL.\n *\n * The URL must return a JSON object matching `CapabilityPack`.\n * Only the pack metadata, skills, and MCP server configs are supported\n * via URL packs — plugin code cannot be loaded from a URL for security.\n */\nexport interface UrlPackRef {\n source: \"url\";\n /** HTTPS URL serving the pack JSON. */\n url: string;\n}\n\n/**\n * A pack stored in a Git repository.\n *\n * The repository root must contain a `pack.json` manifest.\n * The resolver clones (or fetches) the repository to a local cache\n * before reading the pack.\n *\n * Requires `git` to be available on PATH.\n */\nexport interface GitPackRef {\n source: \"git\";\n /** Git-cloneable URL (HTTPS or SSH). */\n url: string;\n /** Branch, tag, or commit SHA to check out. Defaults to the default branch. */\n ref?: string;\n}\n\n/** Union of all pack reference types. */\nexport type PackRef =\n | InlinePackRef\n | LocalPackRef\n | NpmPackRef\n | UrlPackRef\n | GitPackRef;\n\n// ============================================================================\n// Helper constructors\n// ============================================================================\n\n/** Reference to an already-constructed CapabilityPack. */\nexport function inlinePack(pack: CapabilityPack): InlinePackRef {\n return { source: \"inline\", pack };\n}\n\n/** Reference to a pack stored in a local directory. */\nexport function localPack(path: string): LocalPackRef {\n return { source: \"local\", path };\n}\n\n/**\n * Reference to a pack published as an npm package.\n *\n * @param pkg Package specifier (e.g. `\"@mycompany/agent-pack\"`).\n * @param options.export Named export to use instead of the default export.\n */\nexport function npmPack(\n pkg: string,\n options?: { export?: string },\n): NpmPackRef {\n return { source: \"npm\", package: pkg, export: options?.export };\n}\n\n/** Reference to a pack served as JSON at a URL. */\nexport function urlPack(url: string): UrlPackRef {\n return { source: \"url\", url };\n}\n\n/**\n * Reference to a pack in a Git repository.\n *\n * @param url Git URL (HTTPS or SSH).\n * @param ref Branch, tag, or commit. Defaults to the default branch.\n */\nexport function gitPack(url: string, ref?: string): GitPackRef {\n return { source: \"git\", url, ...(ref ? { ref } : {}) };\n}\n"],"mappings":";AA2GO,SAAS,WAAW,MAAqC;AAC9D,SAAO,EAAE,QAAQ,UAAU,KAAK;AAClC;AAGO,SAAS,UAAU,MAA4B;AACpD,SAAO,EAAE,QAAQ,SAAS,KAAK;AACjC;AAQO,SAAS,QACd,KACA,SACY;AACZ,SAAO,EAAE,QAAQ,OAAO,SAAS,KAAK,QAAQ,SAAS,OAAO;AAChE;AAGO,SAAS,QAAQ,KAAyB;AAC/C,SAAO,EAAE,QAAQ,OAAO,IAAI;AAC9B;AAQO,SAAS,QAAQ,KAAa,KAA0B;AAC7D,SAAO,EAAE,QAAQ,OAAO,KAAK,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC,EAAG;AACvD;","names":[]}
@@ -0,0 +1,290 @@
1
+ // src/pack/types.ts
2
+ var CAPABILITY_PACK_KIND = "agent-capability-pack";
3
+ var CAPABILITY_PACK_SCHEMA_VERSION = 1;
4
+
5
+ // src/sources/validate.ts
6
+ function validatePackManifest(manifest, source) {
7
+ if (typeof manifest.id !== "string" || manifest.id.trim() === "") {
8
+ throw new Error(
9
+ `Pack manifest at "${source}" is missing a required string "id" field.`
10
+ );
11
+ }
12
+ if (manifest.id.includes(" ")) {
13
+ throw new Error(
14
+ `Pack manifest at "${source}" has an invalid "id" \u2014 must not contain spaces (use kebab-case).`
15
+ );
16
+ }
17
+ if (manifest.kind !== void 0 && manifest.kind !== CAPABILITY_PACK_KIND) {
18
+ throw new Error(
19
+ `Pack manifest at "${source}" has unsupported "kind" "${String(manifest.kind)}". Expected "${CAPABILITY_PACK_KIND}".`
20
+ );
21
+ }
22
+ if (manifest.schemaVersion !== void 0 && manifest.schemaVersion !== CAPABILITY_PACK_SCHEMA_VERSION) {
23
+ throw new Error(
24
+ `Pack manifest at "${source}" has unsupported schemaVersion "${String(manifest.schemaVersion)}". Expected ${CAPABILITY_PACK_SCHEMA_VERSION}.`
25
+ );
26
+ }
27
+ }
28
+ function assertNoPluginInUrlPack(manifest, url) {
29
+ if (manifest.plugin !== void 0) {
30
+ throw new Error(
31
+ `Pack from URL "${url}" declares a plugin, which is not allowed. Plugin code can only be loaded from local files or npm packages.`
32
+ );
33
+ }
34
+ }
35
+ function normalizePackManifest(pack) {
36
+ return {
37
+ kind: pack.kind ?? CAPABILITY_PACK_KIND,
38
+ schemaVersion: pack.schemaVersion ?? CAPABILITY_PACK_SCHEMA_VERSION,
39
+ ...pack
40
+ };
41
+ }
42
+
43
+ // src/sources/inline-source.ts
44
+ function resolveInlinePack(ref) {
45
+ return normalizePackManifest(ref.pack);
46
+ }
47
+
48
+ // src/sources/local-source.ts
49
+ import { readFile } from "fs/promises";
50
+ import { join, resolve } from "path";
51
+ import { loadPluginModule } from "@cuylabs/agent-core/plugin";
52
+ import { discoverSkills, loadSkillContent } from "@cuylabs/agent-core/skill";
53
+ async function resolveLocalPack(ref) {
54
+ const absPath = resolve(ref.path);
55
+ const manifest = await readPackJson(absPath);
56
+ validatePackManifest(manifest, absPath);
57
+ const skills = await discoverAndInlineSkills(absPath);
58
+ const plugin = await resolveLocalPlugin(absPath, manifest.plugin);
59
+ return normalizePackManifest({
60
+ id: manifest.id,
61
+ name: manifest.name,
62
+ description: manifest.description,
63
+ version: manifest.version,
64
+ skills,
65
+ mcpServers: manifest.mcpServers,
66
+ plugin
67
+ });
68
+ }
69
+ async function readPackJson(packDir) {
70
+ const packJsonPath = join(packDir, "pack.json");
71
+ let raw;
72
+ try {
73
+ raw = await readFile(packJsonPath, "utf-8");
74
+ } catch {
75
+ throw new Error(
76
+ `Cannot read pack.json at ${packJsonPath}. Ensure the directory is a valid capability pack.`
77
+ );
78
+ }
79
+ try {
80
+ return JSON.parse(raw);
81
+ } catch {
82
+ throw new Error(`pack.json at ${packJsonPath} contains invalid JSON.`);
83
+ }
84
+ }
85
+ async function discoverAndInlineSkills(packDir) {
86
+ const skillsDir = join(packDir, "skills");
87
+ const discovery = await discoverSkills(packDir, {
88
+ roots: [skillsDir],
89
+ // One extra level to handle skills/my-skill/SKILL.md.
90
+ maxScanDepth: 3,
91
+ // Disable external directory scanning — we only want this pack's skills.
92
+ externalDirs: []
93
+ });
94
+ const packSkills = [];
95
+ for (const metadata of discovery.skills) {
96
+ const content = await loadSkillContent(metadata);
97
+ const resources = content.resources.map((r) => ({
98
+ relativePath: r.relativePath,
99
+ type: r.type,
100
+ // Keep absolutePath — the resource file is on disk and will be
101
+ // loaded lazily when the agent calls skill_resource.
102
+ absolutePath: r.absolutePath
103
+ }));
104
+ packSkills.push({
105
+ name: metadata.name,
106
+ description: metadata.description,
107
+ body: content.body,
108
+ version: metadata.version,
109
+ tags: metadata.tags,
110
+ dependencies: metadata.dependencies,
111
+ resources: resources.length > 0 ? resources : void 0
112
+ });
113
+ }
114
+ return packSkills;
115
+ }
116
+ async function resolveLocalPlugin(packDir, pluginEntry) {
117
+ if (!pluginEntry) {
118
+ return void 0;
119
+ }
120
+ if (typeof pluginEntry !== "string" || pluginEntry.trim() === "") {
121
+ throw new Error(
122
+ `Invalid "plugin" entry in pack.json at ${packDir}. Expected a non-empty relative module path.`
123
+ );
124
+ }
125
+ return loadPluginModule(resolve(packDir, pluginEntry));
126
+ }
127
+
128
+ // src/sources/npm-source.ts
129
+ async function resolveNpmPack(ref) {
130
+ let mod;
131
+ try {
132
+ mod = await import(ref.package);
133
+ } catch (err) {
134
+ throw new Error(
135
+ `Failed to import pack package "${ref.package}": ${err instanceof Error ? err.message : String(err)}. Ensure the package is installed in your workspace.`
136
+ );
137
+ }
138
+ const exportName = ref.export ?? "default";
139
+ const value = mod[exportName];
140
+ if (value === void 0) {
141
+ const available = Object.keys(mod).join(", ") || "(none)";
142
+ throw new Error(
143
+ `Package "${ref.package}" does not have a "${exportName}" export. Available exports: ${available}.`
144
+ );
145
+ }
146
+ const pack = value;
147
+ validatePackManifest(pack, `${ref.package}#${exportName}`);
148
+ return normalizePackManifest(pack);
149
+ }
150
+
151
+ // src/sources/url-source.ts
152
+ var FETCH_TIMEOUT_MS = 15e3;
153
+ async function resolveUrlPack(ref) {
154
+ if (!ref.url.startsWith("https://")) {
155
+ throw new Error(
156
+ `URL pack source must use HTTPS. Got: "${ref.url}". Plain HTTP is not allowed \u2014 capability packs must be served over a secure connection.`
157
+ );
158
+ }
159
+ const controller = new AbortController();
160
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
161
+ let response;
162
+ try {
163
+ response = await fetch(ref.url, {
164
+ signal: controller.signal,
165
+ headers: { Accept: "application/json" }
166
+ });
167
+ } catch (err) {
168
+ throw new Error(
169
+ `Failed to fetch pack from "${ref.url}": ${err instanceof Error ? err.message : String(err)}.`
170
+ );
171
+ } finally {
172
+ clearTimeout(timeout);
173
+ }
174
+ if (!response.ok) {
175
+ throw new Error(
176
+ `Pack fetch from "${ref.url}" returned HTTP ${response.status} ${response.statusText}.`
177
+ );
178
+ }
179
+ let manifest;
180
+ try {
181
+ manifest = await response.json();
182
+ } catch {
183
+ throw new Error(`Pack from "${ref.url}" did not return valid JSON.`);
184
+ }
185
+ validatePackManifest(manifest, ref.url);
186
+ const pack = manifest;
187
+ assertNoPluginInUrlPack(pack, ref.url);
188
+ return normalizePackManifest(pack);
189
+ }
190
+
191
+ // src/sources/git-source.ts
192
+ import { execFile } from "child_process";
193
+ import { createHash } from "crypto";
194
+ import { mkdir, rm, stat } from "fs/promises";
195
+ import { homedir } from "os";
196
+ import { join as join2 } from "path";
197
+ import { promisify } from "util";
198
+ var execFileAsync = promisify(execFile);
199
+ function gitCacheRoot() {
200
+ return join2(homedir(), ".cache", "cuylabs", "packs", "git");
201
+ }
202
+ function slugify(url, ref) {
203
+ const readable = url.replace(/^https?:\/\//, "").replace(/^git@/, "").replace(/[/:. ]/g, "-").replace(/-+/g, "-").replace(/\.git$/, "");
204
+ const hash = createHash("sha256").update(`${url}#${ref ?? ""}`).digest("hex").slice(0, 12);
205
+ return `${readable}--${hash}`;
206
+ }
207
+ async function resolveGitPack(ref) {
208
+ const cacheRoot = gitCacheRoot();
209
+ const repoDir = join2(cacheRoot, slugify(ref.url, ref.ref));
210
+ await ensureCloned(repoDir, ref);
211
+ return resolveLocalPack({ source: "local", path: repoDir });
212
+ }
213
+ async function ensureCloned(repoDir, ref) {
214
+ const alreadyCloned = await directoryExists(repoDir);
215
+ if (!alreadyCloned) {
216
+ await mkdir(gitCacheRoot(), { recursive: true });
217
+ await gitClone(ref.url, ref.ref, repoDir);
218
+ } else if (!isFixedRef(ref.ref)) {
219
+ await gitPull(repoDir);
220
+ }
221
+ }
222
+ function isFixedRef(ref) {
223
+ if (!ref) return false;
224
+ if (/^[0-9a-f]{40}$/i.test(ref)) return true;
225
+ if (/^[0-9a-f]{7,}$/i.test(ref)) return true;
226
+ return false;
227
+ }
228
+ async function gitClone(url, ref, target) {
229
+ const args = ["clone", "--depth=1"];
230
+ if (ref && !isFixedRef(ref)) args.push("--branch", ref);
231
+ args.push(url, target);
232
+ try {
233
+ await git(args, ".");
234
+ if (ref && isFixedRef(ref)) {
235
+ await git(["fetch", "--depth=1", "origin", ref], target);
236
+ await git(["checkout", "FETCH_HEAD"], target);
237
+ }
238
+ } catch (err) {
239
+ await rm(target, { recursive: true, force: true });
240
+ throw err;
241
+ }
242
+ }
243
+ async function gitPull(repoDir) {
244
+ await git(["pull", "--ff-only"], repoDir);
245
+ }
246
+ async function git(args, cwd) {
247
+ try {
248
+ await execFileAsync("git", args, { cwd });
249
+ } catch (err) {
250
+ const msg = err instanceof Error ? err.message : String(err);
251
+ throw new Error(`git ${args[0]} failed: ${msg}`);
252
+ }
253
+ }
254
+ async function directoryExists(path) {
255
+ try {
256
+ const info = await stat(path);
257
+ return info.isDirectory();
258
+ } catch {
259
+ return false;
260
+ }
261
+ }
262
+
263
+ // src/sources/resolve.ts
264
+ async function resolvePackRef(ref) {
265
+ switch (ref.source) {
266
+ case "inline":
267
+ return resolveInlinePack(ref);
268
+ case "local":
269
+ return resolveLocalPack(ref);
270
+ case "npm":
271
+ return resolveNpmPack(ref);
272
+ case "url":
273
+ return resolveUrlPack(ref);
274
+ case "git":
275
+ return resolveGitPack(ref);
276
+ default: {
277
+ const _exhaustive = ref;
278
+ throw new Error(
279
+ `Unknown pack source: "${_exhaustive.source}"`
280
+ );
281
+ }
282
+ }
283
+ }
284
+
285
+ export {
286
+ CAPABILITY_PACK_KIND,
287
+ CAPABILITY_PACK_SCHEMA_VERSION,
288
+ resolvePackRef
289
+ };
290
+ //# sourceMappingURL=chunk-5E66GFAI.js.map