From b4a5e5dffdd5f77277277d055eafbc0d44b5b827 Mon Sep 17 00:00:00 2001 From: Liuzhaoliang Date: Fri, 13 Mar 2026 15:43:29 +0800 Subject: [PATCH] chore: add volcengine skills --- skills/volcengine-api/LICENSE.txt | 202 ++++++ skills/volcengine-api/SKILL.md | 321 ++++++++++ skills/volcengine-cli/LICENSE.txt | 202 ++++++ skills/volcengine-cli/SKILL.md | 246 ++++++++ skills/volcengine-cli/notes/ecs.md | 131 ++++ skills/volcengine-cli/notes/iam.md | 13 + skills/volcengine-cli/notes/redis.md | 14 + .../volcengine-cli/scripts/fetch_swagger.py | 420 +++++++++++++ skills/volcengine-cli/scripts/find_api.py | 99 +++ skills/volcengine-sdk-generator/LICENSE.txt | 202 ++++++ skills/volcengine-sdk-generator/SKILL.md | 577 ++++++++++++++++++ .../references/sdk-integration-go.md | 142 +++++ .../references/sdk-integration-java.md | 120 ++++ .../references/sdk-integration-nodejs.md | 226 +++++++ .../references/sdk-integration-php.md | 87 +++ .../references/sdk-integration-python.md | 141 +++++ 16 files changed, 3143 insertions(+) create mode 100644 skills/volcengine-api/LICENSE.txt create mode 100644 skills/volcengine-api/SKILL.md create mode 100644 skills/volcengine-cli/LICENSE.txt create mode 100644 skills/volcengine-cli/SKILL.md create mode 100644 skills/volcengine-cli/notes/ecs.md create mode 100644 skills/volcengine-cli/notes/iam.md create mode 100644 skills/volcengine-cli/notes/redis.md create mode 100644 skills/volcengine-cli/scripts/fetch_swagger.py create mode 100644 skills/volcengine-cli/scripts/find_api.py create mode 100644 skills/volcengine-sdk-generator/LICENSE.txt create mode 100644 skills/volcengine-sdk-generator/SKILL.md create mode 100644 skills/volcengine-sdk-generator/references/sdk-integration-go.md create mode 100644 skills/volcengine-sdk-generator/references/sdk-integration-java.md create mode 100644 skills/volcengine-sdk-generator/references/sdk-integration-nodejs.md create mode 100644 skills/volcengine-sdk-generator/references/sdk-integration-php.md create mode 100644 skills/volcengine-sdk-generator/references/sdk-integration-python.md diff --git a/skills/volcengine-api/LICENSE.txt b/skills/volcengine-api/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/skills/volcengine-api/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/skills/volcengine-api/SKILL.md b/skills/volcengine-api/SKILL.md new file mode 100644 index 00000000..98788345 --- /dev/null +++ b/skills/volcengine-api/SKILL.md @@ -0,0 +1,321 @@ +--- +name: volcengine-api +description: > + Query and answer questions about Volcengine API specifications. Trigger this skill whenever a user + asks about Volcengine API parameters, error codes, request methods, enum values, required fields, + response structures, pagination, parameter dependencies, or API comparisons — even if they don't + explicitly say "API". Typical triggers include questions like "What parameters does DescribeInstances + have?", "What values does Status support?", "What does InvalidInstanceId.NotFound mean?", + "Does Volcengine have a batch tag deletion API?", "Which APIs does ECS support?", + "How do I pass parameters to CreateDatabase?", "Is ChargeType required?", + "What fields does DescribeInstances return?", "How do I paginate instance lists?", + "What's the difference between these two APIs?", "RunInstances returns InvalidParameterValue". + When the user needs runnable SDK code, hand off to the volcengine-sdk-generator skill. + When the user needs CLI-based operations, hand off to the volcengine-cli skill. + Supports both Chinese and English prompts. +--- + +# Volcengine API Query Assistant + +Answer user questions about Volcengine APIs by querying the API Explorer for authoritative, up-to-date information. + +## Applicable Scenarios + +| Scenario | Example Questions | +|----------|-------------------| +| Find an API | "How do I list ECS instances?", "Is there a batch tag creation API?" | +| Query parameters | "What are the required params for RunInstances?", "What values does ChargeType accept?" | +| Response structure | "What fields does DescribeInstances return?", "What statuses can Status have?" | +| Parameter dependencies | "If I set Ipv6Isp, how should I fill Ipv6MaskLen?", "When is SpotPriceLimit required?" | +| Pagination | "How do I paginate instance queries?", "How does NextToken work?" | +| Error codes | "What does InvalidInstanceId.NotFound mean?", "CreateVpc returns QuotaExceeded" | +| Browse services | "Which APIs does ECS have?", "What operations does VPC support?" | +| API comparison | "What's the difference between DescribeInstances and DescribeInstancesByIds?" | + +## Workflow + +### Step 1: Understand User Intent + +Determine what the user is looking for: + +| Intent | Signal | Query Path | +|--------|--------|------------| +| **Find an API** | Describes an operation but doesn't know the API name | Search (2e) or Services (2a) -> API list (2c) -> Details (2d) | +| **Query parameters** | Knows the API name, asks about params/enums/required fields | Go directly to Details (2d) | +| **Query response** | Asks about return fields or status values | Go directly to Details (2d), focus on response schema | +| **Query parameter dependencies** | Asks "when is X required?" or "how does X relate to Y?" | Go directly to Details (2d), focus on conditional rules in descriptions | +| **Query error codes** | Provides an error code or error message | Error code handling (Step 3) | +| **Browse a service** | Asks what capabilities a service offers | Services (2a) -> API list (2c) | +| **Compare APIs** | Asks about differences between two APIs | Query Details (2d) for each, compare params and functionality | + +### Step 2: Query API Information Progressively + +Start from the appropriate sub-step based on what is already known. When the user describes a requirement in natural language, Search (2e) is often faster than browsing level by level. + +#### 2a. Query service list (when the service is unknown) + +``` +GET https://api.volcengine.com/api/common/explorer/services +``` + +Each service in the response contains: +- `ServiceCode`: service identifier (e.g., `ecs`, `vpc`) +- `ServiceCn`: Chinese name (e.g., "cloud server", "virtual private cloud") +- `Product`: product identifier (e.g., `ECS`, `VPC`) +- `RegionType`: `regional` or `global` + +Match the most appropriate `ServiceCode` based on the user's description. + +#### 2b. Query version list (when the version is unknown) + +``` +GET https://api.volcengine.com/api/common/explorer/versions?ServiceCode={ServiceCode} +``` + +Each version contains: +- `Version`: version string (e.g., `2020-04-01`) +- `IsDefault`: `1` indicates the default version + +Prefer the version with `IsDefault=1`. If none is marked default, use the latest version. + +#### 2c. Query API list (when the specific API is unknown) + +``` +GET https://api.volcengine.com/api/common/explorer/apis?ServiceCode={ServiceCode}&Version={Version}&APIVersion={Version} +``` + +The response groups APIs by category. Each API contains: +- `Action`: API name (e.g., `DescribeInstances`) +- `NameCn`: Chinese name (e.g., "Query instance list") +- `ApiGroup`: group name (e.g., "Instance", "Image") +- `Description`: functional description +- `UsageScenario`: usage scenarios +- `Attentions`: constraints and caveats + +Match user intent using `Action`, `NameCn`, and `Description`. + +#### 2d. Query API details (core step) + +``` +GET https://api.volcengine.com/api/common/explorer/api-swagger?ServiceCode={ServiceCode}&Version={Version}&APIVersion={Version}&ActionName={ActionName} +``` + +Returns the full Swagger/OpenAPI specification for the API. Extract key information as follows. + +##### HTTP Method + +The key under `paths["/{ActionName}"]` (`get` or `post`) indicates the HTTP method. + +##### Request Parameters + +Parameter location depends on the HTTP method: + +**GET requests:** parameters are in `paths["/{ActionName}"].get.parameters`. Each parameter includes: +- `name`: parameter name +- `required`: whether it is required +- `schema.type`: data type +- `schema.description`: parameter description (often contains enum values, conditional rules, and value ranges) +- `schema.enum`: allowed values (if any) +- `schema.default`: default value (if any) +- `schema.example`: example value (if any) + +Arrays and nested objects in GET parameters use naming conventions: +- Arrays: `ParamName.N` (N starts from 1), e.g., `InstanceIds.1`, `InstanceIds.2` +- Nested objects: `Parent.Child`, e.g., `TagFilters.N.Key`, `TagFilters.N.Values.N` + +**POST requests:** parameters are in `paths["/{ActionName}"].post.requestBody.content["application/json"].schema`, using JSON Schema: +- `properties`: parameter definitions, keyed by name +- `required`: array of required parameter names + +POST parameters often have nested structures that require recursive parsing: +- `type: object` -> inspect `properties` for child parameters +- `type: array` -> inspect `items` for element structure +- `$ref: "#/components/schemas/XxxObject"` -> look up the definition in `components.schemas` and expand recursively + +Present nested parameters in a tree structure: +``` +- InstanceId (string, required): instance ID +- DatabasePrivileges (array, optional): database privilege list + - AccountName (string, required): account name + - AccountPrivilege (string, required): privilege type — enum: ReadWrite, ReadOnly, ... + - AccountPrivilegeDetail (string, optional): privilege detail, comma-separated +``` + +##### Parameter Dependencies + +Many parameters have conditional dependencies, typically described in the `description` field. Watch for: + +- **Conditionally required**: e.g., "required when `EnableIpv6` is true" +- **Mutually exclusive**: e.g., "when `Ipv6CidrBlock` is specified, `Ipv6MaskLen` is ignored" +- **Value constraints**: e.g., "when `Ipv6Isp` is BGP, only 56 is supported" +- **Prerequisites**: e.g., "`TagFilters.N.Values.N` requires `TagFilters.N.Key` to be set first" + +Highlight these dependencies in the answer to help users avoid misconfiguration. + +##### Pagination Parameters + +Volcengine APIs use two common pagination patterns, identifiable from the Swagger parameters: + +- **Token-based**: uses `MaxResults` (page size) + `NextToken` (continuation token). The response includes `NextToken`; an empty value means the last page. +- **Offset-based**: uses `PageSize` + `PageNumber` (or `Offset`/`Limit`). The response includes `TotalCount`. + +Specify which pagination pattern the API uses, along with default values and upper limits. + +##### Response Structure + +The response schema is defined at `paths["/{ActionName}"].{method}.responses["200"].content["application/json"].schema`, and may reference `components.schemas` via `$ref`. + +Key response information: +- Field names, types, and descriptions +- Enum fields and their possible values (e.g., `Status`: RUNNING / STOPPED / CREATING) +- Nested object structures (e.g., fields within each item in an `Instances` array) + +The `info.x-demo` section also provides useful reference — `responseDemo[0].Code` shows the complete response structure with example values. + +##### Request/Response Examples + +In the `info.x-demo` array: +- `requestDemo[0].Code`: request example (shows how parameters are filled) +- `responseDemo[0].Code`: response example (shows the full return structure with sample values) + +These are official examples and highly valuable. Proactively include them in the answer. + +##### Associated Error Codes + +In `paths["/{ActionName}"].{method}.responses["x-error-code"].content["application/json"].schema.oneOf`, each error code contains: +- `code`: error code identifier (e.g., `InvalidInstanceId.NotFound`) +- `http_code`: HTTP status code (e.g., 400, 404, 409, 429, 500) +- `message`: English description +- `description`: Chinese description + +#### 2e. Search APIs (quick lookup) + +When the user describes a requirement in natural language, searching is often the fastest approach. This can be used alongside steps 2a–2c. + +``` +GET https://api.volcengine.com/api/common/search/all?Query={keyword}&Channel=api +``` + +Search terms can be in Chinese or English. If one keyword yields poor results, try synonyms, different granularity, or English Action-name style (e.g., "DescribeXxx"). + +Each result contains: +- `BizInfo.Action`: API name +- `BizInfo.ServiceCode`: service identifier +- `BizInfo.ServiceCn`: service Chinese name +- `BizInfo.Version`: version +- `Highlight`: matched highlight text + +After finding the target API, use step 2d to get full details. + +### Step 3: Handle Error Code Queries + +Error code queries need special handling because the same error code (e.g., `InvalidParameter`) may appear across dozens of APIs with different meanings. + +#### Common Error Code Categories + +| Category | Common Patterns | Typical Cause | +|----------|----------------|---------------| +| Parameter error | `InvalidParameter`, `InvalidParameterValue`, `MissingParameter` | Typo in parameter name, value outside enum range, missing required parameter | +| Resource not found | `InvalidXxx.NotFound`, `ResourceNotFound` | Wrong resource ID, resource in a different region, already deleted | +| Resource status | `InvalidXxx.InvalidStatus`, `IncorrectInstanceStatus` | Current resource state does not allow this operation (e.g., modifying config without stopping the instance) | +| Quota/limit | `QuotaExceeded`, `LimitExceeded` | Account quota or API rate limit exceeded | +| Permission denied | `UnauthorizedOperation`, `Forbidden` | IAM policy not authorized, sub-account lacks permissions | +| Throttling | `Throttling`, `RequestLimitExceeded` | API call rate too high — reduce request rate or use exponential backoff | +| Server error | `InternalError`, `ServiceUnavailable` | Temporary server-side issue, usually retryable | +| Resource conflict | `ResourceInUse`, `DuplicateXxx`, `OperationConflict` | Resource is in use or name already exists | + +#### When the user provides a specific API name + +Query the API Swagger via step 2d and locate the error code in `x-error-code`. This is the most accurate approach because the same error code can have different meanings across APIs. + +Combine the `description` (Chinese) and `message` (English) fields to provide: +1. Error meaning +2. Specific trigger conditions in the context of this API +3. Troubleshooting steps and resolution suggestions + +#### When the user provides only the error code + +1. **Ask for context first**: ask which API triggered the error — this enables precise diagnosis. The same `InvalidParameter` means entirely different things in `RunInstances` vs. `CreateVpc`. +2. **If the user provides a service name but no API name**: infer the most likely API from the error pattern and context, then query its Swagger to confirm. +3. **Fallback search**: if the user cannot provide more context, use the error code search endpoint: + +``` +GET https://api.volcengine.com/api/common/search/all?Query={error_code}&Channel=error_code +``` + +Each result contains: +- `Type`: `error_code` +- `BizInfo.ServiceCode`: service identifier +- `BizInfo.ServiceCn`: service Chinese name +- `BizInfo.Version`: version +- `URL`: error code documentation link +- `Highlight`: matched highlight text + +Since the same error code appears across multiple services, results may be numerous. Filter by any context the user has provided (service name, operation type, scenario). + +### Step 4: Compose the Answer + +Organize a clear, professional answer based on the question type. Core principle: **center on the user's question** — extract the information the user needs rather than dumping the entire Swagger. + +#### Finding an API + +1. Recommend the API and explain why +2. Briefly describe its functionality and use case +3. List core required parameters +4. If multiple candidates exist, compare their use cases and let the user choose + +#### Querying Parameters + +1. State the HTTP method (GET/POST) +2. **Required parameters first**: list with type, description, and enum values +3. Use tree structure for nested parameters, marking required/optional at each level +4. **Parameter dependencies**: highlight conditional requirements, mutual exclusions, and value constraints +5. Describe the pagination pattern and default values separately +6. Show the request example (from x-demo) +7. Group optional parameters by function (filters, sorting, advanced config) and list briefly + +#### Querying Response Structure + +1. List key return fields with type and description +2. Show all possible values for enum fields +3. Use tree structure for nested objects +4. Show the response example (from x-demo responseDemo) + +#### Querying Error Codes + +1. Error meaning (Chinese and English descriptions) +2. Error category (parameter error / resource not found / permission denied, etc.) +3. Common causes +4. Specific troubleshooting steps and resolution suggestions +5. For throttling errors, recommend a retry strategy + +#### Browsing Service Capabilities + +1. Organize the API list by `ApiGroup` +2. Show Action name + Chinese name + one-line description for each API +3. If there are many APIs, prioritize core/commonly-used ones + +#### Comparing APIs + +1. Describe the functional purpose of each API +2. Compare applicable scenarios +3. Compare parameter differences (which is simpler, which is more flexible) +4. Provide a usage recommendation + +### Query Efficiency Tips + +- **API name known**: go directly to 2d — one step +- **Service name known**: 2b -> 2c -> 2d, or search in parallel via 2e +- **Only a natural-language description**: prefer 2e search — faster than browsing level by level +- **Completely uncertain**: combine 2a (service list) + 2e (keyword search) +- **Error code lookup**: if an API name is available, go to 2d; otherwise, ask the user for context first + +### Important Notes + +- Always fetch the latest data from the API Explorer endpoints — Volcengine APIs are updated frequently, so do not rely on memory +- Match the answer language to the user's language (Chinese question -> Chinese answer, English -> English) +- If the user's description is ambiguous, list possible options and ask for confirmation rather than guessing +- If the user needs runnable SDK code, direct them to the `volcengine-sdk-generator` skill +- If the user needs CLI-based operations, direct them to the `volcengine-cli` skill +- When presenting parameter information, enum values, conditional rules, and value ranges in the description field are the most valuable content — do not omit them +- If a network error occurs during queries, inform the user and suggest retrying later diff --git a/skills/volcengine-cli/LICENSE.txt b/skills/volcengine-cli/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/skills/volcengine-cli/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/skills/volcengine-cli/SKILL.md b/skills/volcengine-cli/SKILL.md new file mode 100644 index 00000000..e39e4a7c --- /dev/null +++ b/skills/volcengine-cli/SKILL.md @@ -0,0 +1,246 @@ +--- +name: volcengine-cli +description: >- + Create and manage Volcengine cloud resources using the Volcengine CLI (`ve` command). Supports all + Volcengine services including ECS, VPC, CLB, RDS, Redis, and more. Trigger this skill whenever the + user asks to create, query, modify, or delete cloud resources on Volcengine, mentions the `ve` command, + says "volcengine CLI", or describes infrastructure tasks such as "create an ECS instance", + "set up a VPC", "list security groups", "allocate an EIP". Also trigger when the user encounters + errors from `ve` commands and needs troubleshooting help. +argument-hint: +user-invocable: true +allowed-tools: Bash, Read, Write +--- + +# Volcengine CLI Skill + +Create and manage Volcengine cloud resources by calling Volcengine OpenAPIs through the `ve` command. + +--- + +## 0. Install the ve CLI + +If the `ve` command is not available on the system: + +**Option 1: npm (recommended)** +```bash +npm i -g @volcengine/cli +``` + +**Option 2: GitHub Releases** +Download: https://github.com/volcengine/volcengine-cli/releases + +Verify the installation: `ve --version` + +--- + +## 1. Initialization (run at the start of every session) + +Run the identity verification command to confirm that credentials are usable: + +```bash +ve sts GetCallerIdentity +``` + +**Success** -> inform the user of the current account identity and region, then proceed with the task. + +> **Switching regions**: the `--region` flag and the `VOLCENGINE_REGION` environment variable do not override the region in the config file. Switch regions via `ve configure profile --profile `. Use `ve configure list` to view available profiles. + +**Failure** -> credentials are not configured or invalid. Guide the user through one of the following: + +**Option 1: Environment variables** (recommended for temporary use) +```bash +export VOLCENGINE_ACCESS_KEY_ID="" +export VOLCENGINE_SECRET_ACCESS_KEY="" +export VOLCENGINE_REGION="cn-beijing" +``` + +**Option 2: Config file** (persistent) + +If `~/.volcengine/config.json` does not exist, create an empty template for the user to fill in: + +```bash +mkdir -p ~/.volcengine +cat > ~/.volcengine/config.json << 'EOF' +{ + "current": "default", + "profiles": { + "default": { + "name": "default", + "mode": "ak", + "access-key": "", + "secret-key": "", + "region": "cn-beijing", + "endpoint": "", + "session-token": "", + "disable-ssl": false + } + }, + "enableColor": false +} +EOF +``` + +> **Never read `~/.volcengine/config.json`** — the file contains sensitive credentials. Only create an empty template; never read an existing config. + +--- + +## 2. Safety Rules (mandatory) + +### Read/Write Classification + +| Level | Operation Types | Behavior | +|-------|----------------|----------| +| **Read-only** | Describe\* / List\* / Get\* / Query\* | Execute directly, no confirmation needed | +| **Write** | Create\* / Run\* / Allocate\* / Attach\* / Associate\* / Authorize\* | Show the full command and wait for user confirmation | +| **Destructive** | Delete\* / Terminate\* / Release\* / Revoke\* / Modify\* / Stop\* / Detach\* | Show command + impact summary; **require** user confirmation | + +### Core Principles + +1. **Default to read-only** — unless the user explicitly requests a change, execute in read-only mode +2. **DryRun first** — if a write/destructive operation supports `--DryRun true`, run a DryRun to preview the plan, then confirm before executing +3. **Confirm before executing** — show the full command for write operations and wait for approval +4. **Protect credentials** — never read `~/.volcengine/config.json`; never expose access-key, secret-key, or session-token in output + +### DryRun Notes + +A successful DryRun validation returns **exit code 1** (non-zero) with `DryRunOperation` in stderr. This is expected behavior: + +```bash +output=$(ve --DryRun true ... 2>&1) +if echo "$output" | grep -q "DryRunOperation"; then + echo "Parameter validation passed" +fi +``` + +--- + +## 3. Locate APIs and Retrieve Parameters + +### Locate the API (find the service name + Action name) + +``` +Step 1: Service name + Action known? -> Use them directly; skip to "Retrieve parameters" +Step 2: Service name known, Action unknown? + -> ve 2>&1 | grep -i +Step 3: Service name also unknown? + -> ve 2>&1 | grep -i +Step 4: None of the above work? + -> python3 scripts/find_api.py +``` + +### Retrieve parameters (once the Action is known) + +Choose a strategy based on operation type: + +| Operation Type | Strategy | Rationale | +|---------------|----------|-----------| +| **Read-only** (Describe/List/Get) | `ve --help` | Few, simple parameters — names alone are sufficient | +| **Write/destructive** (Create/Run/Delete, etc.) | `scripts/fetch_swagger.py` for full docs | Many parameters, nested structures — need required fields, examples, and descriptions | +| **Still unclear after `--help`** | Supplement with `scripts/fetch_swagger.py` | Use whenever parameter meaning is uncertain | +| **Errors like `Invalid*` / `Missing*`** | Recheck with `scripts/fetch_swagger.py` | On `InvalidParameter`, `InvalidXxx.NotFound`, or `MissingParameter`, verify parameter names, required fields, and value ranges | + +```bash +# Read-only — --help is sufficient +ve ecs DescribeInstances --help + +# Write — retrieve full documentation +python3 scripts/fetch_swagger.py --service ecs --action RunInstances +``` + +### ve command name and API version relationship + +- Default version -> ve command = base service name (e.g., `iam`) +- Non-default version -> ve command = `service name + version without hyphens` (e.g., `iam` v2021-08-01 -> `iam20210801`) +- When in doubt: `ve 2>&1 | grep ` to confirm + +### Python helper usage + +```bash +# Search for an API (when the service name is unknown) +python3 scripts/find_api.py [--limit N] + +# Get full API parameter documentation (when descriptions/examples are needed) +python3 scripts/fetch_swagger.py --service --action + +# List all APIs for a service +python3 scripts/fetch_swagger.py --service --list +``` + +> Always pass the **base service name** to scripts/fetch_swagger.py (e.g., `--service iam`, not `iam20210801`) — the script auto-detects the version. + +--- + +## 4. Execute API Calls + +### Basic Format + +```bash +ve --ParamName "value" +``` + +### Parameter Passing Rules + +Determine the format from `--help` output: +- **Flat parameter format**: `--help` lists individual `--Key type` entries (e.g., ECS, VPC, IAM) -> pass with `--Key "value"` +- **JSON format**: `--help` only shows `--body '{...}'` (e.g., Redis, CR, and other POST APIs) -> pass with `--body '{...}'` + +```bash +# Flat parameters — nested fields use dot notation; arrays use .N index (starting from 1) +ve ecs RunInstances --Placement.ZoneId "cn-beijing-a" +ve ecs RunInstances --NetworkInterfaces.1.SubnetId "subnet-xxxx" +ve ecs RunInstances --Tags.1.Key "env" --Tags.2.Key "app" + +# JSON format (when --help only shows --body) +ve redis CreateDBInstance --body '{"InstanceName":"demo", "RegionId":"cn-beijing", ...}' +``` + +### Response Format + +```json +// Success +{ "ResponseMetadata": { "RequestId": "..." }, "Result": { ... } } + +// Failure +{ "ResponseMetadata": { "Error": { "Code": "...", "Message": "..." } } } +``` + +### Async Resource Creation Requires Polling + +Some resources (VKE clusters, RDS instances, ECS instances, etc.) take several minutes to create. After creation, poll the Describe endpoint until the resource reaches the desired status before proceeding. + +> Creating sub-resources (e.g., security groups) immediately after VPC creation may fail with `InvalidVpc.InvalidStatus`. Create sub-resources sequentially (subnet first, then security group), or wait a few seconds and retry. + +```bash +# General polling pattern: check every 30 seconds until the target status is reached +while true; do + cur_status=$(ve Describe -- "xxx" 2>&1 | grep -o '"Status":"[^"]*"') + echo "$(date +%H:%M:%S) $cur_status" + echo "$cur_status" | grep -q '"Status":"Running"' && break + sleep 30 +done +``` + +--- + +## 5. End-to-End Execution Flow (Summary) + +``` +1. Initialize: verify credentials -> GetCallerIdentity -> confirm region +2. Understand the task: is the user querying or making changes? +3. Locate the API: ve --help first -> Python helpers as fallback +4. Query dependent resources: use Describe*/List* to obtain required IDs +5. Read operation -> execute directly and display results + Write operation -> show command -> DryRun (if supported) -> user confirmation -> execute +6. Parse the response and report results to the user +``` + +--- + +## 6. Service-Specific Notes + +Consult or update the corresponding notes file when encountering service-specific issues: + +- ECS: [notes/ecs.md](notes/ecs.md) +- IAM: [notes/iam.md](notes/iam.md) +- Redis: [notes/redis.md](notes/redis.md) diff --git a/skills/volcengine-cli/notes/ecs.md b/skills/volcengine-cli/notes/ecs.md new file mode 100644 index 00000000..c04aa883 --- /dev/null +++ b/skills/volcengine-cli/notes/ecs.md @@ -0,0 +1,131 @@ +# ECS Service Notes + +## DescribeInstanceTypes returns only 10 results by default + +Calling `DescribeInstanceTypes` without filters returns at most 10 entries, making it impossible to find the smallest available instance type. + +**Correct approach (two steps):** + +```bash +# 1. Query available instance types in a specific zone +ve ecs DescribeAvailableResource \ + --ZoneId "cn-beijing-a" \ + --DestinationResource "InstanceType" + +# 2. Filter by type name and query CPU/memory details +# Naming convention: .large < .xlarge < .2xlarge (higher = larger) +# The smallest general-purpose type typically ends with .large +ve ecs DescribeInstanceTypes --InstanceTypes.1 "ecs.c3i.large" +``` + +--- + +## veLinux image search requires an exact name + +A fuzzy keyword like `"velinux"` matches GPU, Docker, ARM, and other variant images, producing too many results. + +**Correct approach:** use an exact name prefix. + +```bash +# Search for veLinux 2.0 64-bit +ve ecs DescribeImages \ + --ImageName "veLinux 2.0 64" \ + --ImageOwnerAlias "system" +``` + +Common image names: +- `veLinux 2.0 64` — standard x86_64 +- `veLinux 2.0 ARM 64` — ARM + +--- + +## Full ECS instance creation workflow + +```bash +# 1. List availability zones +ve ecs DescribeZones --Region cn-beijing + +# 2. Query available instance types (do NOT use DescribeInstanceTypes directly) +ve ecs DescribeAvailableResource \ + --ZoneId "cn-beijing-a" \ + --DestinationResource InstanceType + +# 3. Get the veLinux image ID +ve ecs DescribeImages \ + --ImageName "veLinux 2.0 64" \ + --ImageOwnerAlias "system" + +# 4. Get VPC and subnet IDs +ve vpc DescribeVpcs +ve vpc DescribeSubnets --VpcId "vpc-xxxx" + +# 5. Get or create a security group and open port 22 +ve ecs DescribeSecurityGroups --VpcId "vpc-xxxx" +ve ecs AuthorizeSecurityGroupIngress \ + --SecurityGroupId "sg-xxxx" \ + --Protocol "tcp" \ + --PortStart 22 \ + --PortEnd 22 \ + --CidrIp "0.0.0.0/0" + +# 6. DryRun validation +output=$(ve ecs RunInstances \ + --Placement.ZoneId "cn-beijing-a" \ + --InstanceTypeId "ecs.c3i.large" \ + --ImageId "image-xxxx" \ + --NetworkInterfaces.1.SubnetId "subnet-xxxx" \ + --NetworkInterfaces.1.SecurityGroupIds.1 "sg-xxxx" \ + --SystemVolume.Size 40 \ + --SystemVolume.VolumeType "ESSD_PL0" \ + --InstanceName "my-instance" \ + --DryRun true 2>&1) +echo "$output" | grep -q "DryRunOperation" && echo "DryRun passed" + +# 7. Create the instance +ve ecs RunInstances \ + --Placement.ZoneId "cn-beijing-a" \ + --InstanceTypeId "ecs.c3i.large" \ + --ImageId "image-xxxx" \ + --NetworkInterfaces.1.SubnetId "subnet-xxxx" \ + --NetworkInterfaces.1.SecurityGroupIds.1 "sg-xxxx" \ + --SystemVolume.Size 40 \ + --SystemVolume.VolumeType "ESSD_PL0" \ + --InstanceName "my-instance" \ + --Count 1 +``` + +--- + +## ZoneId notes + +- Beijing zones: `cn-beijing-a` / `cn-beijing-b` / `cn-beijing-c`, etc. +- `--Placement.ZoneId` is a nested parameter (dot-separated), not `--ZoneId`. +- ZoneId is required when creating instances. + +--- + +## Instance type existence does not guarantee zone availability + +`DescribeInstanceTypes` returns a global list of instance types regardless of actual zone inventory. Creating an instance may fail with `InvalidInstanceType.NotFound`. + +**Correct approach:** use `DescribeAvailableResource` to query available types in the target zone. If creation fails, try an alternative type within the same family (e.g., `ecs.hfc4i.large` -> `ecs.hfc3il.large`). + +--- + +## Cloud Assistant Agent requires a reboot after installation + +After calling `InstallCloudAssistant`, the agent status is `ReadyReboot` and `RunCommand` will keep timing out. + +**Correct approach:** +1. Call `InstallCloudAssistant`. +2. Call `RebootInstance` to restart the instance. +3. Poll `DescribeCloudAssistantStatus` until status becomes `Running`. +4. Then execute `RunCommand`. + +> Tip: pass `--InstallRunCommandAgent true` during instance creation to avoid manual installation later. + +--- + +## RunCommand Timeout minimum is 60 + +Setting `--Timeout` below 60 seconds triggers `LimitExceeded.MaximumTimeout`. Valid range: 60–86400 seconds. diff --git a/skills/volcengine-cli/notes/iam.md b/skills/volcengine-cli/notes/iam.md new file mode 100644 index 00000000..b48b8391 --- /dev/null +++ b/skills/volcengine-cli/notes/iam.md @@ -0,0 +1,13 @@ +# IAM Service Notes + +## UpdateUser does not support Tags + +`UpdateUser` can only modify basic attributes such as Description and DisplayName. It cannot manage tags. + +**Correct approach:** use `TagResources` to tag users separately: + +```bash +ve iam TagResources --ResourceType "User" --ResourceNames.1 "" --Tags.1.Key "key" --Tags.1.Value "value" +``` + +The same applies to roles — use `TagResources` with `ResourceType` set to `Role`. diff --git a/skills/volcengine-cli/notes/redis.md b/skills/volcengine-cli/notes/redis.md new file mode 100644 index 00000000..6dcf0f0f --- /dev/null +++ b/skills/volcengine-cli/notes/redis.md @@ -0,0 +1,14 @@ +# Redis Service Notes + +## Allow-list deletion requires the instance to be fully released + +Calling `DeleteAllowList` immediately after `DeleteDBInstance` fails with `AllowListBindInstanceCannotDelete` because the instance has not been fully removed yet. + +**Correct approach:** wait for the Redis instance to be fully deleted (~30 seconds) before deleting the associated allow list. + +```bash +# Poll until the instance no longer exists +ve redis DescribeDBInstanceDetail --body '{"InstanceId":"redis-xxx"}' +# Once the instance is gone, delete the allow list +ve redis DeleteAllowList --body '{"AllowListId":"acl-xxx"}' +``` diff --git a/skills/volcengine-cli/scripts/fetch_swagger.py b/skills/volcengine-cli/scripts/fetch_swagger.py new file mode 100644 index 00000000..e7ae3128 --- /dev/null +++ b/skills/volcengine-cli/scripts/fetch_swagger.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +""" +Fetch Volcengine API Swagger and convert to Markdown documentation. +Usage: python3 fetch_swagger.py --service ecs --action RunInstances [--version 2020-04-01] +""" + +import argparse +import json +import sys +import urllib.request +import urllib.error + +BASE_URL = "https://api.volcengine.com/api/common/explorer" + + +def fetch_json(url, allow_404=False): + try: + with urllib.request.urlopen(url, timeout=10) as resp: + return json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + if allow_404 and e.code == 404: + return None + print(f"Error fetching {url}: {e}", file=sys.stderr) + sys.exit(1) + except urllib.error.URLError as e: + print(f"Error fetching {url}: {e}", file=sys.stderr) + sys.exit(1) + + +def get_all_versions(service_code): + """Return all versions for a service, IsDefault=1 first.""" + url = f"{BASE_URL}/versions?ServiceCode={service_code}" + data = fetch_json(url) + assert data is not None + versions = data.get("Result", {}).get("Versions", []) + if not versions: + print(f"No version found for service: {service_code}", file=sys.stderr) + sys.exit(1) + versions.sort(key=lambda v: 0 if v.get("IsDefault") == 1 else 1) + return [v["Version"] for v in versions] + + +def get_default_version(service_code): + return get_all_versions(service_code)[0] + + +def get_swagger(service_code, version, action_name, all_versions=None): + """Fetch swagger for an action. If not found in given version, try all other versions.""" + def _try(ver): + url = ( + f"{BASE_URL}/api-swagger" + f"?ServiceCode={service_code}" + f"&Version={ver}" + f"&APIVersion={ver}" + f"&ActionName={action_name}" + ) + data = fetch_json(url, allow_404=True) + if data is None: + return None, None + api = data.get("Result", {}).get("Api") + return api, ver + + api, matched_ver = _try(version) + if api: + return api, matched_ver + + # Fallback: try remaining versions + if all_versions is None: + all_versions = get_all_versions(service_code) + for ver in all_versions: + if ver == version: + continue + api, matched_ver = _try(ver) + if api: + print(f"Note: action '{action_name}' not found in v{version}, using v{matched_ver}", file=sys.stderr) + return api, matched_ver + + print(f"No swagger found for {service_code}.{action_name} in any version: {all_versions}", file=sys.stderr) + sys.exit(1) + + +def resolve_ref(ref_str, schemas): + """Resolve a $ref like '#/components/schemas/Foo' to its schema dict.""" + if ref_str.startswith("#/components/schemas/"): + name = ref_str[len("#/components/schemas/"):] + return name, schemas.get(name, {}) + return ref_str, {} + + +def get_type_str(schema, schemas): + """Get a human-readable type string from a schema object.""" + if "$ref" in schema: + name, _ = resolve_ref(schema["$ref"], schemas) + return f"object({name})" + t = schema.get("type", "string") + if t == "array": + items = schema.get("items", {}) + if "$ref" in items: + name, _ = resolve_ref(items["$ref"], schemas) + return f"array[object({name})]" + return f"array[{items.get('type', 'string')}]" + if t == "integer": + fmt = schema.get("format", "") + return "integer" if not fmt else f"integer({fmt})" + if t == "number": + return "number" + return t + + +def escape_md(text): + """Escape pipe characters and newlines for markdown table cells.""" + if not text: + return "" + text = str(text) + # Collapse multi-line descriptions to single line, keep it readable + text = text.replace("\n", " ").replace("|", "|") + # Trim markdown tip/note blocks + import re + text = re.sub(r":::.*?:::", "", text, flags=re.DOTALL).strip() + # Limit length + if len(text) > 200: + text = text[:197] + "..." + return text + + +def format_example(example): + if example is None: + return "" + if isinstance(example, list): + return ", ".join(str(e) for e in example[:2]) + return str(example) + + +def build_params_table(params_list): + """Build a markdown table from a list of param dicts.""" + lines = [ + "| 参数名 | 类型 | 必填 | 说明 | 示例值 |", + "|--------|------|:----:|------|--------|", + ] + for p in params_list: + required = "✓" if p.get("required") else "" + lines.append( + f"| `{p['name']}` | {p['type']} | {required} | {escape_md(p.get('description', ''))} | {escape_md(format_example(p.get('example', '')))} |" + ) + return "\n".join(lines) + + +def parse_get_params(parameters, schemas): + """Parse GET query parameters, separating flat and nested ($ref) params.""" + flat = [] + nested = [] # list of (param_name, is_array, schema_name, schema_dict) + + for p in parameters: + schema = p.get("schema", {}) + name = p.get("name", "") + required = p.get("required", False) + description = p.get("description", "") + example = p.get("example") + + if "$ref" in schema: + ref_name, ref_schema = resolve_ref(schema["$ref"], schemas) + nested.append((name, False, ref_name, ref_schema, required, description)) + elif schema.get("type") == "array" and "$ref" in schema.get("items", {}): + ref_name, ref_schema = resolve_ref(schema["items"]["$ref"], schemas) + nested.append((name, True, ref_name, ref_schema, required, description)) + else: + flat.append({ + "name": name, + "type": get_type_str(schema, schemas), + "required": required, + "description": description, + "example": example or schema.get("example"), + }) + + return flat, nested + + +def parse_nested_schema(schema_name, schema_dict, parent_prefix, is_array, schemas, visited=None): + """Recursively parse a schema into a flat list of param dicts with full paths.""" + if visited is None: + visited = set() + if schema_name in visited: + return [] + visited = visited | {schema_name} + + params = [] + properties = schema_dict.get("properties", {}) + sort_order = schema_dict.get("x-sort-params", []) + + # Use sort order if provided, otherwise alphabetical + sorted_keys = sort_order if sort_order else sorted(properties.keys()) + # Make sure all keys are included (sort_order might be incomplete) + sorted_keys = sorted_keys + [k for k in properties if k not in sorted_keys] + + for prop_name in sorted_keys: + if prop_name not in properties: + continue + prop = properties[prop_name] + full_name = f"{parent_prefix}.N.{prop_name}" if is_array else f"{parent_prefix}.{prop_name}" + + if "$ref" in prop: + sub_name, sub_schema = resolve_ref(prop["$ref"], schemas) + params.append({ + "name": full_name, + "type": f"object", + "required": False, + "description": prop.get("description", ""), + "example": prop.get("example"), + }) + params.extend(parse_nested_schema(sub_name, sub_schema, full_name, False, schemas, visited)) + elif prop.get("type") == "array" and "$ref" in prop.get("items", {}): + sub_name, sub_schema = resolve_ref(prop["items"]["$ref"], schemas) + params.append({ + "name": full_name, + "type": "array[object]", + "required": False, + "description": prop.get("description", ""), + "example": prop.get("example"), + }) + params.extend(parse_nested_schema(sub_name, sub_schema, full_name, True, schemas, visited)) + else: + params.append({ + "name": full_name, + "type": get_type_str(prop, schemas), + "required": False, + "description": prop.get("description", ""), + "example": prop.get("example"), + }) + + return params + + +def parse_post_body(request_body, schemas): + """Parse a POST requestBody schema into flat + nested params.""" + content = request_body.get("content", {}) + schema = content.get("application/json", {}).get("schema", {}) + + # Handle top-level $ref + if "$ref" in schema: + _, schema = resolve_ref(schema["$ref"], schemas) + + flat = [] + nested_sections = [] + properties = schema.get("properties", {}) + required_list = schema.get("required", []) + sort_order = schema.get("x-sort-params", []) + sorted_keys = sort_order + [k for k in properties if k not in sort_order] + + for key in sorted_keys: + if key not in properties: + continue + prop = properties[key] + required = key in required_list + description = prop.get("description", "") + example = prop.get("example") + + if "$ref" in prop: + ref_name, ref_schema = resolve_ref(prop["$ref"], schemas) + flat.append({ + "name": key, + "type": "object", + "required": required, + "description": description, + "example": example, + }) + nested_sections.append((key, False, ref_name, ref_schema)) + elif prop.get("type") == "array" and "$ref" in prop.get("items", {}): + ref_name, ref_schema = resolve_ref(prop["items"]["$ref"], schemas) + flat.append({ + "name": key, + "type": "array[object]", + "required": required, + "description": description, + "example": example, + }) + nested_sections.append((key, True, ref_name, ref_schema)) + else: + flat.append({ + "name": key, + "type": get_type_str(prop, schemas), + "required": required, + "description": description, + "example": example or prop.get("example"), + }) + + return flat, nested_sections + + +def swagger_to_markdown(service_code, action_name, version, api_swagger): + schemas = api_swagger.get("components", {}).get("schemas", {}) + paths = api_swagger.get("paths", {}) + + # Find the operation + method = "GET" + operation = {} + for _, methods in paths.items(): + for m, op in methods.items(): + method = m.upper() + operation = op + break + break + + # API description (from operation summary or first param description) + summary = operation.get("summary", operation.get("description", "")) + + lines = [] + lines.append(f"# `ve {service_code} {action_name}`") + if summary: + lines.append(f"\n{summary.strip()}") + lines.append(f"\n**服务**: `{service_code}` | **版本**: `{version}` | **方法**: `{method}`") + lines.append(f"\n**CLI 格式**: `ve {service_code} {action_name} [参数...]`") + lines.append("") + + if method == "GET": + parameters = operation.get("parameters", []) + flat_params, nested_list = parse_get_params(parameters, schemas) + + lines.append("## 请求参数\n") + if flat_params: + lines.append(build_params_table(flat_params)) + else: + lines.append("_无独立参数_") + + for (param_name, is_array, schema_name, schema_dict, _, description) in nested_list: + type_label = "array[object]" if is_array else "object" + lines.append(f"\n### 嵌套参数:`{param_name}` ({type_label})\n") + if description and description != param_name: + lines.append(f"{description}\n") + nested_params = parse_nested_schema( + schema_name, schema_dict, param_name, is_array, schemas + ) + if nested_params: + lines.append(build_params_table(nested_params)) + + else: # POST + request_body = operation.get("requestBody", {}) + if request_body: + flat_params, nested_sections = parse_post_body(request_body, schemas) + lines.append("## 请求参数 (Request Body JSON)\n") + if flat_params: + lines.append(build_params_table(flat_params)) + for (key, is_array, ref_name, ref_schema) in nested_sections: + type_label = "array[object]" if is_array else "object" + lines.append(f"\n### 嵌套参数:`{key}` ({type_label})\n") + nested_params = parse_nested_schema( + ref_name, ref_schema, key, is_array, schemas + ) + if nested_params: + lines.append(build_params_table(nested_params)) + else: + params = operation.get("parameters", []) + flat_params, nested_list = parse_get_params(params, schemas) + lines.append("## 请求参数\n") + if flat_params: + lines.append(build_params_table(flat_params)) + for (param_name, is_array, schema_name, schema_dict, _req, _desc) in nested_list: + type_label = "array[object]" if is_array else "object" + lines.append(f"\n### 嵌套参数:`{param_name}` ({type_label})\n") + nested_params = parse_nested_schema( + schema_name, schema_dict, param_name, is_array, schemas + ) + if nested_params: + lines.append(build_params_table(nested_params)) + + lines.append("\n---") + lines.append(f"_生成自 Volcengine OpenAPI Explorer: {service_code} {action_name} v{version}_") + return "\n".join(lines) + + +def list_apis(service_code, version): + """List all available APIs for a service/version.""" + url = ( + f"{BASE_URL}/apis" + f"?ServiceCode={service_code}" + f"&Version={version}" + f"&APIVersion={version}" + ) + data = fetch_json(url) + assert data is not None + groups = data.get("Result", {}).get("Groups", []) + lines = [f"# {service_code} v{version} API 列表\n"] + for group in groups: + group_name = group.get("Name", "") + apis = group.get("Apis", []) + if apis: + lines.append(f"## {group_name}\n") + for api in apis: + action = api.get("Action", "") + name_cn = api.get("NameCn", "") + desc = api.get("Description", "") + lines.append(f"- **{action}** - {name_cn}: {desc[:80]}") + lines.append("") + return "\n".join(lines) + + +def main(): + parser = argparse.ArgumentParser( + description="Fetch Volcengine API Swagger and output as Markdown" + ) + parser.add_argument("--service", "-s", required=True, help="Service code, e.g. ecs") + parser.add_argument("--action", "-a", help="API action name, e.g. RunInstances") + parser.add_argument("--version", "-v", help="API version, e.g. 2020-04-01 (auto-detected if omitted)") + parser.add_argument("--list", "-l", action="store_true", help="List all APIs for the service") + args = parser.parse_args() + + service_code = args.service + all_versions = get_all_versions(service_code) + version = args.version or all_versions[0] + + if args.list or not args.action: + print(list_apis(service_code, version)) + return + + api_swagger, matched_version = get_swagger(service_code, version, args.action, all_versions) + md = swagger_to_markdown(service_code, args.action, matched_version, api_swagger) + print(md) + + +if __name__ == "__main__": + main() diff --git a/skills/volcengine-cli/scripts/find_api.py b/skills/volcengine-cli/scripts/find_api.py new file mode 100644 index 00000000..93f53ca7 --- /dev/null +++ b/skills/volcengine-cli/scripts/find_api.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +""" +火山引擎 API 搜索工具 +用法:python3 find_api.py <搜索关键词> [--limit N] +示例:python3 find_api.py 获取项目列表 + python3 find_api.py ListProjects --limit 5 +""" + +import sys +import re +import json +import argparse +import urllib.request +import urllib.parse + + +def strip_em(text): + return re.sub(r"", "", text or "") + + +def search(query, limit=10): + params = urllib.parse.urlencode({"Query": query, "Channel": "api", "Limit": limit}) + url = f"https://api.volcengine.com/api/common/search/all?{params}" + req = urllib.request.Request(url, headers={"User-Agent": "volcengine-cli-skill/1.0"}) + with urllib.request.urlopen(req, timeout=10) as resp: + data = json.loads(resp.read()) + return data.get("Result", {}).get("List", []) + + +def main(): + parser = argparse.ArgumentParser(description="Search Volcengine APIs") + parser.add_argument("query", nargs="+", help="搜索关键词") + parser.add_argument("--limit", type=int, default=10, help="返回条数(默认10)") + parser.add_argument("--json", action="store_true", help="输出原始 JSON") + args = parser.parse_args() + + query = " ".join(args.query) + results = search(query, args.limit) + + if not results: + print("No results found.") + sys.exit(0) + + if args.json: + print(json.dumps(results, ensure_ascii=False, indent=2)) + return + + # 找出 content 字段的描述 + def get_desc(item): + for h in item.get("Highlight", []): + if h.get("Field") == "content": + return strip_em(h.get("Summary", "")) + return "" + + # 表格宽度 + rows = [] + for item in results: + biz = item.get("BizInfo", {}) + rows.append({ + "action": biz.get("Action", ""), + "service": biz.get("ServiceCode", ""), + "service_cn": biz.get("ServiceCn", ""), + "version": biz.get("Version", ""), + "desc": get_desc(item), + }) + + col_w = {k: len(k) for k in ("action", "service", "service_cn", "version", "desc")} + for r in rows: + for k in col_w: + col_w[k] = max(col_w[k], len(r[k])) + + def fmt(r): + return ( + f" {r['action']:<{col_w['action']}} " + f"{r['service']:<{col_w['service']}} " + f"{r['service_cn']:<{col_w['service_cn']}} " + f"{r['version']:<{col_w['version']}} " + f"{r['desc']}" + ) + + header = ( + f" {'Action':<{col_w['action']}} " + f"{'Service':<{col_w['service']}} " + f"{'服务名':<{col_w['service_cn']}} " + f"{'Version':<{col_w['version']}} " + f"{'描述'}" + ) + sep = " " + "-" * (sum(col_w.values()) + 8) + + print(f"\nSearch: {query!r} ({len(rows)} results)\n") + print(header) + print(sep) + for r in rows: + print(fmt(r)) + print() + + +if __name__ == "__main__": + main() diff --git a/skills/volcengine-sdk-generator/LICENSE.txt b/skills/volcengine-sdk-generator/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/skills/volcengine-sdk-generator/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/skills/volcengine-sdk-generator/SKILL.md b/skills/volcengine-sdk-generator/SKILL.md new file mode 100644 index 00000000..ee74770f --- /dev/null +++ b/skills/volcengine-sdk-generator/SKILL.md @@ -0,0 +1,577 @@ +--- +name: volcengine-sdk-generator +description: > + Generate complete, runnable Volcengine SDK code and provide SDK configuration guidance. + Supports Go, Python, PHP, Java, and Node.js. Trigger this skill whenever the user wants to call + a Volcengine API, generate Volcengine SDK code, or describes a cloud operation on Volcengine + (e.g., "list ECS instances", "create a VPC on Volcengine", "query Volcengine billing with Python"). + Also trigger when the user asks about Volcengine SDK configuration and best practices — including + retry, timeout, authentication (AK/SK, STS, AssumeRole), proxy, connection pooling, SSL, debug mode, + and error handling (e.g., "how to configure retry for Volcengine Go SDK", "volcengine python sdk + proxy setup"). Trigger when the user mentions Volcengine service names such as ECS, VPC, CDN, CLB, + RDS, Redis, Kafka, billing, IAM, DNS with code generation or SDK usage intent. + When the user only needs API specification queries (parameters, error codes, response structures), + hand off to the volcengine-api skill. When the user needs CLI-based operations, hand off to + the volcengine-cli skill. Supports both Chinese and English prompts. +--- + +# Volcengine SDK Code Generator + +Generate complete, runnable Volcengine SDK code from natural-language descriptions, and answer SDK configuration questions. + +## Workflow + +When a user describes a Volcengine API operation, follow these steps: + +### Step 1: Identify Target Service, Operation, and Advanced Configuration Needs + +Parse the user's description to determine: +- **Target service**: which Volcengine service (e.g., ECS, VPC, TOS, billing) +- **Target operation**: what operation to perform (e.g., list instances, create a VPC, query billing) +- **Target language**: which programming language (Go, Python, PHP, Java, Node.js). If not specified, ask the user. +- **Advanced configuration needs**: whether the user mentions or the scenario implies any of the following: + - **Retry**: user mentions "retry", "fault tolerance", or the operation is a write/create type (prone to throttling) + - **Timeout**: user mentions "timeout", or the operation involves large data volumes (batch queries, file uploads) + - **Credentials**: user mentions "STS", "AssumeRole", "temporary credentials", "OIDC", or explicitly wants to avoid hardcoding AK/SK + - **Proxy/network**: user mentions "proxy" or "internal network" + - **Debug mode**: user mentions "debug" or "logging" + - **Connection pooling**: user mentions "connection pool", "high concurrency", or "pool" + + If the user explicitly requests these, include the corresponding configuration in the generated code. If not explicitly requested but implied by the scenario (e.g., resource creation naturally warrants retry), include suggested configuration as comments. + +### Step 2: Query Service Metadata via Volcengine API Explorer + +Use the following APIs to find the correct service code, version, and action name. This step is critical because guessing often produces incorrect code — the API Explorer is the authoritative source. + +**2a. Find the ServiceCode** + +Fetch the service catalog: +``` +GET https://api.volcengine.com/api/common/explorer/services +``` +Response structure: +```json +{ + "Result": { + "Categories": [ + { + "CategoryName": "...", + "Services": [ + { + "ServiceCn": "Cloud Server", + "ServiceCode": "ecs", + "Product": "ECS", + "IsSdkAvailable": true, + "RegionType": "regional" + } + ] + } + ] + } +} +``` +Match the user's intent to the correct `ServiceCode` based on `ServiceCn`, `Product`, and category name. + +**2b. Find the API version** + +``` +GET https://api.volcengine.com/api/common/explorer/versions?ServiceCode={ServiceCode} +``` +Response: +```json +{ + "Result": { + "Versions": [ + { + "ServiceCode": "billing", + "Version": "2022-01-01", + "IsDefault": 0 + } + ] + } +} +``` +Use the version with `IsDefault == 1`. If no default version exists, use the latest available. + +**2c. Find the Action name** + +``` +GET https://api.volcengine.com/api/common/explorer/apis?ServiceCode={ServiceCode}&Version={Version}&APIVersion={Version} +``` +Response: +```json +{ + "Result": { + "Groups": [ + { + "Name": "Instance", + "Apis": [ + { + "Action": "DescribeInstances", + "NameCn": "Query instance list", + "Description": "..." + } + ] + } + ] + } +} +``` +Match user intent using the `Action` name and `NameCn` (Chinese name). + +**2c-alt: Search API (when direct lookup fails)** + +If the service catalog or API list cannot clearly match the user's description — for example, the user uses vague terms, Chinese names that don't map directly to a ServiceCode, or the API list doesn't seem to contain what the user wants — use the search API as a fallback: + +``` +GET https://api.volcengine.com/api/common/search/all?Query={URL-encoded search term}&Channel=api&Limit=10 +``` + +Search terms can be Chinese or English — use whichever best matches the user's description. + +Response structure: +```json +{ + "Result": { + "List": [ + { + "BizInfo": { + "Action": "ListProjects", + "ServiceCn": "Access Control", + "ServiceCode": "iam", + "Version": "2021-08-01" + }, + "Highlight": [ + {"Field": "title", "Summary": "Get project list"} + ] + } + ], + "Total": 200 + } +} +``` + +Select the best match based on `ServiceCn`, `Action`, and highlight text, then continue to step 2d. + +The search API is particularly useful when: +- The user describes the operation in natural language but doesn't know which service owns it +- A service has too many APIs to browse manually +- The description spans multiple services (search returns results across all services) + +**2d. Get full API parameter details** + +``` +GET https://api.volcengine.com/api/common/explorer/api-swagger?ServiceCode={ServiceCode}&Version={Version}&APIVersion={Version}&ActionName={Action} +``` +Returns the full Swagger/OpenAPI specification, including: +- HTTP method (GET/POST) +- All request parameters with types, required flags, and descriptions +- Response structure +- Constraints and validation rules +- **`x-demo` field**: contains `requestDemo` and `responseDemo` with official examples + +Read this specification carefully — it is essential for generating accurate code. + +**2e. Extract parameter example values (from x-demo requestDemo)** + +The `info.x-demo` array in the Swagger response contains `requestDemo` — official request examples. Extract realistic parameter values from these to populate generated code. + +Extraction process: +1. Locate `info.x-demo[0].requestDemo` and parse the request body JSON +2. Use requestDemo values as example values in generated code — they are more accurate and realistic than invented values +3. For masked values (e.g., `cc5silum********`), keep the masked format and add a comment prompting the user to replace with real values +4. If a parameter value is a JSON string (e.g., a `Config` field), format it clearly and comment each sub-field + +Example: for VKE CreateAddon, requestDemo contains: +```json +{ + "ClusterId": "cc5silum********", + "Name": "ingress-nginx", + "DeployMode": "Unmanaged", + "DeployNodeType": ["VirtualNode"], + "Config": "{\"Replica\":1,\"Resource\":{\"Request\":{\"Cpu\":\"0.25\",\"Memory\":\"512Mi\"},\"Limit\":{\"Cpu\":\"0.5\",\"Memory\":\"1024Mi\"}},\"PrivateNetwork\":{\"SubnetId\":\"subnet-2d61qn69iji****\",\"IpVersion\":\"IPV4\"}}" +} +``` +Use these example values directly instead of empty placeholders. + +**2f. Retrieve detailed configuration for complex parameters** + +Some parameter `description` fields contain documentation links (e.g., `https://www.volcengine.com/docs/...`) pointing to detailed configuration guides. For complex parameters, fetch these links for more information: + +When to consult documentation: +- The parameter value is a JSON string with a "see detailed configuration" reference in the description (e.g., VKE `Config`) +- The parameter is a nested structure whose sub-field format is documented externally +- The `enum` values have unclear meanings that are explained in the documentation + +Processing flow: +1. Check whether the parameter `description` contains a `volcengine.com/docs` link +2. If so, use WebFetch to retrieve the linked page and extract configuration details relevant to the parameter +3. Incorporate documentation examples into the generated code as comments or structured parameters +4. If the documentation is inaccessible, fall back to requestDemo example values + +**2g. Determine required and recommended parameters** + +Required-field detection relies on multiple sources, not just the `required` array: + +1. **Explicitly required**: listed in the Swagger `required` array +2. **Implied by description**: the description contains phrases like "must specify", "required", or equivalent +3. **Logically required**: semantically essential even if not formally marked (e.g., instance type and network config when creating resources) +4. **Conditionally required**: the description states "required when X=Y" — if the user's scenario matches, include it + +Parameter value priority: +1. **requestDemo example values** (highest priority): use the official examples directly +2. **`example` field**: individual parameter `example` values from the Swagger spec +3. **enum values**: pick the most common or general-purpose option +4. **Documentation recommendations**: values extracted from linked docs +5. **Industry conventions**: reasonable defaults following cloud-computing norms (e.g., `172.16.0.0/16` for CIDR, descriptive names for instances) + +### Step 3: Consult SDK Configuration References (as needed) + +If Step 1 identified advanced configuration needs, read the corresponding reference file for the target language to get accurate configuration code: + +| Language | Reference File | +|----------|---------------| +| Go | `references/sdk-integration-go.md` | +| Python | `references/sdk-integration-python.md` | +| Java | `references/sdk-integration-java.md` | +| Node.js | `references/sdk-integration-nodejs.md` | +| PHP | `references/sdk-integration-php.md` | + +These files contain verified code snippets for retry, timeout, credentials, proxy, connection pooling, and debug configuration. Use these patterns directly rather than writing from memory — SDK configuration varies significantly across languages, and the reference files ensure accuracy. + +### Step 4: Generate Complete SDK Code + +Generate a complete, runnable code example following these rules: + +#### General Rules (all languages) + +1. **Authentication**: read AK/SK from environment variables `VOLCENGINE_ACCESS_KEY` and `VOLCENGINE_SECRET_KEY` by default. If the user needs a different auth method (STS, AssumeRole, OIDC), use the corresponding pattern from the reference files. The exact reading mechanism varies by language — see each language section and the reference files. +2. **Region**: default to `cn-beijing` for regional services. Add a comment noting that users can change this. +3. **Required parameters**: include all required parameters (sources per step 2g), using realistic example values from requestDemo or example fields. Add a comment next to each value explaining its meaning and source. +4. **Parameter value quality**: values must follow realistic formats and business semantics, not simple placeholders: + - Instance IDs: use masked format like `i-abc123******` (from requestDemo) + - CIDRs: use reasonable ranges like `172.16.0.0/16` + - Enums: use the most common option + - Nested JSON configs: expand into readable multi-line format with per-field comments +5. **Complex parameter handling**: for parameters whose value is a JSON string (e.g., VKE Config), build a struct/dict first and then serialize to JSON, rather than hardcoding a long string. This makes the code more readable and easier to modify. +6. **Optional parameters**: include commonly-used optional parameters (e.g., pagination) as commented-out lines with explanations. +7. **Error handling**: include standard error handling for the target language. +8. **Output**: print the response in a readable format (e.g., formatted JSON). +9. **Comments**: add a header comment describing the code's purpose. Add inline comments for non-obvious parameters. Match comment language to the user's prompt language. +10. **Advanced configuration integration**: when the user has advanced config needs, weave the configuration naturally into the main code (not as a separate block), producing a single runnable file: + - **Retry**: add retry settings during client/config initialization, with comments explaining defaults and tunable parameters + - **Timeout**: set global timeout during client initialization; show per-request timeout usage if needed + - **Credentials**: replace the default AK/SK auth code with the user-specified method (STS, AssumeRole, etc.) + - **Proxy**: add proxy settings in client configuration + - **Debug**: enable debug mode in client configuration + - **Connection pooling**: set pool parameters in client configuration + +#### Go + +The Go SDK uses `{Action}Input` structs (not `Request`). Services are instantiated via `{service}.New(sess)`. + +```go +package main + +import ( + "fmt" + "os" + "github.com/volcengine/volcengine-go-sdk/service/{service}" + "github.com/volcengine/volcengine-go-sdk/volcengine" + "github.com/volcengine/volcengine-go-sdk/volcengine/credentials" + "github.com/volcengine/volcengine-go-sdk/volcengine/session" +) + +func main() { + ak := os.Getenv("VOLCENGINE_ACCESS_KEY") + sk := os.Getenv("VOLCENGINE_SECRET_KEY") + region := "cn-beijing" + + config := volcengine.NewConfig(). + WithRegion(region). + WithCredentials(credentials.NewStaticCredentials(ak, sk, "")) + + // [Advanced config — add as needed, see references/sdk-integration-go.md] + // Retry: config.WithMaxRetries(5) + // Timeout: config.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}) + // Proxy: config.WithHTTPProxy("http://proxy:8080") + // Debug: config.WithDebug(true) + + sess, err := session.NewSession(config) + if err != nil { + panic(err) + } + svc := {service}.New(sess) + + input := &{service}.{Action}Input{ + // Set required parameters here + } + resp, err := svc.{Action}(input) + if err != nil { + panic(err) + } + fmt.Println(resp) +} +``` + +Key points: +- Package path: `github.com/volcengine/volcengine-go-sdk/service/{service}` (lowercase, e.g., `billing`, `ecs`, `vpc`) +- Config chain: `volcengine.NewConfig().WithRegion(region).WithCredentials(credentials.NewStaticCredentials(ak, sk, ""))` +- Session: `session.NewSession(config)` (returns session and error) +- Service client: `{service}.New(sess)` (e.g., `billing.New(sess)`, `ecs.New(sess)`) +- Request struct: `{Action}Input` (e.g., `ListAvailableInstancesInput`, `DescribeInstancesInput`) +- Method: `svc.{Action}(input)`, PascalCase action name + +#### Python + +The Python SDK uses `{SERVICE}Api` (uppercase service name) and `{Action}Request` models. + +```python +from __future__ import print_function +import os +import volcenginesdkcore +import volcenginesdk{service} +from volcenginesdkcore.rest import ApiException + +if __name__ == '__main__': + configuration = volcenginesdkcore.Configuration() + configuration.ak = os.environ.get("VOLCENGINE_ACCESS_KEY") + configuration.sk = os.environ.get("VOLCENGINE_SECRET_KEY") + configuration.region = "cn-beijing" + + # [Advanced config — add as needed, see references/sdk-integration-python.md] + # Retry: configuration.max_retry_attempts = 5 + # Timeout: configuration.connection_timeout = 10; configuration.read_timeout = 60 + # Proxy: configuration.proxy = "http://proxy:8080" + # Debug: configuration.debug = True + + volcenginesdkcore.Configuration.set_default(configuration) + + api_instance = volcenginesdk{service}.{SERVICE}Api() + request = volcenginesdk{service}.{Action}Request( + # Set required parameters here + ) + + try: + resp = api_instance.{action_snake_case}(request) + print(resp) + except ApiException as e: + print("API exception: %s\n" % e) +``` + +Key points: +- Package: `volcenginesdkcore` + `volcenginesdk{service}` (all lowercase, no separators, e.g., `volcenginesdkbilling`, `volcenginesdkecs`) +- Config: `volcenginesdkcore.Configuration()`, set `.ak`, `.sk`, `.region`, then `set_default()` +- API class: `volcenginesdk{service}.{SERVICE}Api()` — service name ALL CAPS (e.g., `BILLINGApi`, `ECSApi`, `VPCApi`) +- Request class: `volcenginesdk{service}.{Action}Request(...)` (PascalCase, e.g., `ListAvailableInstancesRequest`) +- Method: `api_instance.{action_snake_case}(request)` — snake_case (e.g., `list_available_instances`, `describe_instances`) +- Exception: `from volcenginesdkcore.rest import ApiException` + +#### Java + +The Java SDK uses `{ServiceName}Api` and `{Action}Request` models under `com.volcengine.{service}`. + +```java +package com.volcengine.sample; + +import com.volcengine.ApiClient; +import com.volcengine.ApiException; +import com.volcengine.sign.Credentials; +import com.volcengine.{service}.{ServiceName}Api; +import com.volcengine.{service}.model.*; + +public class Example { + public static void main(String[] args) throws Exception { + String ak = System.getenv("VOLCENGINE_ACCESS_KEY"); + String sk = System.getenv("VOLCENGINE_SECRET_KEY"); + String region = "cn-beijing"; + + ApiClient apiClient = new ApiClient() + .setCredentials(Credentials.getCredentials(ak, sk)) + .setRegion(region); + + // [Advanced config — add as needed, see references/sdk-integration-java.md] + // Retry: apiClient.setRetrySettings(new RetrySettings().setMaxAttempts(5)); + // Timeout: apiClient.setConnectionTimeout(5000); apiClient.setReadTimeout(30000); + // Proxy: apiClient.setHttpProxy("http://proxy:8080"); + // Debug: apiClient.setDebugging(true); + + {ServiceName}Api api = new {ServiceName}Api(apiClient); + + {Action}Request request = new {Action}Request(); + // request.setParamName(value); + + try { + {Action}Response resp = api.{actionCamelCase}(request); + System.out.println(resp); + } catch (ApiException e) { + System.out.println(e.getResponseBody()); + } + } +} +``` + +Key points: +- Package: `com.volcengine.{service}` (lowercase, e.g., `com.volcengine.billing`, `com.volcengine.ecs`) +- ApiClient: `new ApiClient().setCredentials(Credentials.getCredentials(ak, sk)).setRegion(region)` +- API class: `{ServiceName}Api` (PascalCase, e.g., `BillingApi`, `EcsApi`) — constructor takes `apiClient` +- Request class: `{Action}Request` (e.g., `ListAvailableInstancesRequest`) — set params via setters +- Method: `api.{actionCamelCase}(request)` — camelCase (e.g., `listAvailableInstances`, `describeInstances`) +- Exception: `ApiException`, use `e.getResponseBody()` for details + +#### Node.js + +The Node.js SDK uses a command pattern: `{SERVICE}Client` + `{Action}Command`. + +```javascript +import { {SERVICE}Client, {Action}Command } from "@volcengine/{service}"; + +// Automatically reads VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY from env +const client = new {SERVICE}Client({ + region: "cn-beijing", + // [Advanced config — add as needed, see references/sdk-integration-nodejs.md] + // maxRetries: 5, // retry count + // autoRetry: false, // disable auto-retry + // httpOptions: { timeout: 30000 }, // timeout (ms) + // httpOptions: { proxy: { protocol: "http", host: "127.0.0.1", port: 8888 } }, // proxy +}); + +async function main() { + try { + const command = new {Action}Command({ + // Set required parameters here + }); + const response = await client.send(command); + console.log(JSON.stringify(response, null, 2)); + } catch (error) { + console.error("Error:", error); + } +} + +main(); +``` + +Key points: +- Package: `@volcengine/{service}` (lowercase, e.g., `@volcengine/ecs`, `@volcengine/vpc`) +- Client: `{SERVICE}Client` (ALL CAPS service name, e.g., `ECSClient`, `VPCClient`) +- Command: `{Action}Command` (PascalCase, e.g., `DescribeInstancesCommand`, `CreateVpcCommand`) +- Invocation: `client.send(command)` — async, returns a Promise +- Auth: automatically reads `VOLCENGINE_ACCESS_KEY` and `VOLCENGINE_SECRET_KEY` from env; can also pass `accessKeyId`/`secretAccessKey` in the client constructor + +#### PHP + +The PHP SDK uses classes under the `\Volcengine\{Service}\` namespace. + +```php +setAk(getenv("VOLCENGINE_ACCESS_KEY")) + ->setSk(getenv("VOLCENGINE_SECRET_KEY")) + ->setRegion("cn-beijing"); + +// [Advanced config — add as needed, see references/sdk-integration-php.md] +// Proxy and timeout are configured via GuzzleHttp\Client options +$httpClient = new GuzzleHttp\Client([ + // 'proxy' => 'http://proxy:8080', // proxy + // 'timeout' => 60, // request timeout (seconds) + // 'connect_timeout' => 10, // connection timeout (seconds) +]); + +$apiInstance = new \Volcengine\{Service}\Api\{SERVICE}Api( + $httpClient, + $config +); + +$request = new \Volcengine\{Service}\Model\{Action}Request(); +// $request->setParamName("value"); + +try { + $resp = $apiInstance->{actionCamelCase}($request); + print_r($resp); +} catch (Exception $e) { + echo 'API exception: ', $e->getMessage(), PHP_EOL; +} +``` + +Key points: +- Config: `\Volcengine\Common\Configuration::getDefaultConfiguration()->setAk()->setSk()->setRegion()` +- API class: `\Volcengine\{Service}\Api\{SERVICE}Api` — namespace uses PascalCase `Service` (e.g., `Billing`), class name uses ALL CAPS (e.g., `BILLINGApi`) +- Constructor: takes `GuzzleHttp\Client()` and `$config` +- Request class: `\Volcengine\{Service}\Model\{Action}Request` (e.g., `\Volcengine\Billing\Model\ListAvailableInstancesRequest`) +- Set params via setters: `$request->setProduct("value")` +- Method: `$apiInstance->{actionCamelCase}($request)` (e.g., `listAvailableInstances`) + +### Step 5: Present Results + +After generating code: + +1. Display the complete code in a code block with the correct language tag +2. List the dependencies the user needs to install (`go get`, `pip install`, `npm install`, `composer require`, Maven/Gradle coordinates) +3. Remind the user to set environment variables: + ``` + export VOLCENGINE_ACCESS_KEY="your-access-key" + export VOLCENGINE_SECRET_KEY="your-secret-key" + ``` +4. Note important constraints from the API spec (rate limits, required permissions, data range limits, etc.) +5. If the code includes advanced configuration, briefly explain each setting's purpose, defaults, and tuning advice. For example: + - "Retry defaults to 3 attempts, covers network errors and throttling — adjust via `WithMaxRetries`" + - "Connection timeout defaults to 30s; consider increasing for large batch queries" + +## Answering SDK Configuration Questions + +When the user asks how to configure or use the Volcengine SDK (rather than generate API call code), follow this approach: + +### Step 1: Identify the User's Need + +Common configuration topics: +- **Authentication**: AK/SK, STS Token, AssumeRole, OIDC, SAML +- **Retry**: enable/disable, max attempts, backoff strategy, custom retry conditions +- **Timeout**: connection timeout, read timeout, per-request timeout +- **Proxy**: HTTP/HTTPS proxy configuration +- **Endpoint**: custom endpoint, region-based resolution, dual-stack (IPv6) +- **SSL/HTTPS**: disable SSL verification, TLS version, HTTP vs. HTTPS +- **Connection pooling**: pool size, keep-alive, idle connections +- **Debug**: debug mode, logging, middleware +- **Error handling**: exception types, retryable vs. non-retryable errors +- **Environment variables**: supported env vars per SDK + +### Step 2: Consult the Reference Documentation + +Read the reference file for the user's target language: + +| Language | Reference File | +|----------|---------------| +| Go | `references/sdk-integration-go.md` | +| Python | `references/sdk-integration-python.md` | +| Java | `references/sdk-integration-java.md` | +| Node.js | `references/sdk-integration-nodejs.md` | +| PHP | `references/sdk-integration-php.md` | + +These files contain concise code examples for each major configuration topic. Read the relevant file and answer with accurate, copy-paste-ready code. + +If the user's question is not covered in the reference file or requires more detail, fetch the full upstream documentation from GitHub: + +| Language | Upstream Documentation URL | +|----------|---------------------------| +| Go | `https://raw.githubusercontent.com/volcengine/volcengine-go-sdk/master/SDK_Integration.md` | +| Python | `https://raw.githubusercontent.com/volcengine/volcengine-python-sdk/master/SDK_Integration.md` | +| Java | `https://raw.githubusercontent.com/volcengine/volcengine-java-sdk/master/SDK_Integration.md` | +| Node.js | `https://raw.githubusercontent.com/volcengine/volcengine-nodejs-sdk/master/SDK_Integration.md` | +| PHP | `https://raw.githubusercontent.com/volcengine/volcengine-php-sdk/main/SDK_Integration.md` | + +### Step 3: Provide a Clear Answer + +- Show complete, runnable code snippets demonstrating the configuration +- Explain each setting's purpose and default value +- Mention caveats (e.g., "disabling SSL verification is only appropriate in test environments") +- If the user has not specified a language, ask which one they are using +- Match the answer language to the user's prompt language + +## Important Notes + +- Always fetch data from the API Explorer — Volcengine APIs are updated frequently, so the Explorer is the authoritative source. Do not rely on memory. +- If the user's description is ambiguous (could map to multiple services or operations), list the options and ask for confirmation. +- If a service has `IsSdkAvailable: false`, inform the user that the official SDK may not yet support this service, and provide a raw HTTP request example as an alternative. +- For regional services, remind the user to change the region setting if their resources are not in `cn-beijing`. diff --git a/skills/volcengine-sdk-generator/references/sdk-integration-go.md b/skills/volcengine-sdk-generator/references/sdk-integration-go.md new file mode 100644 index 00000000..c96b2166 --- /dev/null +++ b/skills/volcengine-sdk-generator/references/sdk-integration-go.md @@ -0,0 +1,142 @@ +# Go SDK Integration Reference + +Source: https://github.com/volcengine/volcengine-go-sdk/blob/master/SDK_Integration.md + +## Requirements + +Go 1.14+ (1.18+ for Ark service). Use `go mod` for dependency management. + +## Authentication + +### AK/SK + +```go +ak := os.Getenv("VOLCENGINE_ACCESS_KEY") +sk := os.Getenv("VOLCENGINE_SECRET_KEY") +config := volcengine.NewConfig(). + WithRegion("cn-beijing"). + WithCredentials(credentials.NewStaticCredentials(ak, sk, "")) +sess, _ := session.NewSession(config) +``` + +Env vars: `VOLCSTACK_ACCESS_KEY_ID`, `VOLCSTACK_SECRET_ACCESS_KEY` + +### STS Token + +```go +config := volcengine.NewConfig(). + WithRegion("cn-beijing"). + WithCredentials(credentials.NewStaticCredentials(ak, sk, sessionToken)) +``` + +### STS AssumeRole + +```go +config := volcengine.NewConfig(). + WithRegion("cn-beijing"). + WithCredentials(credentials.NewAssumeRoleCredentials( + ak, sk, + "trn:iam::accountId:role/roleName", + "sessionName", + 3600, // durationSeconds + )) +``` + +### STS AssumeRoleWithOIDC (file-based) + +```go +config := volcengine.NewConfig(). + WithRegion("cn-beijing"). + WithCredentials(credentials.NewOIDCRoleCredentials( + ak, sk, + "trn:iam::accountId:role/roleName", + "trn:iam::accountId:oidc-provider/providerName", + "/path/to/oidc-token-file", + "sessionName", + 3600, + )) +``` + +## Endpoint Configuration + +```go +// Custom endpoint +config.WithEndpoint("custom-endpoint.volcengineapi.com") + +// Custom region +config.WithRegion("cn-shanghai") + +// DualStack (IPv6) +config.WithUseDualStack(true) +``` + +## HTTP Connection Pool + +```go +// Default: 100 max idle connections, 90s timeout +// Customize via custom http.Client +httpClient := &http.Client{ + Transport: &http.Transport{ + MaxIdleConns: 200, + IdleConnTimeout: 120 * time.Second, + }, +} +config.WithHTTPClient(httpClient) +``` + +## SSL / HTTPS + +```go +// Disable SSL (use HTTP) +config.WithDisableSSL(true) + +// Custom TLS config +tlsConfig := &tls.Config{ + MinVersion: tls.VersionTLS12, + MaxVersion: tls.VersionTLS13, +} +``` + +## Proxy + +```go +config.WithHTTPProxy("http://proxy:8080") +config.WithHTTPSProxy("https://proxy:8080") +// Also reads env vars: http_proxy, https_proxy +``` + +## Timeouts + +```go +// Global client-level (default: 30s connection) +config.WithHTTPClient(&http.Client{ + Timeout: 60 * time.Second, +}) + +// Per-API timeout via context (use {Action}WithContext methods) +ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) +defer cancel() +resp, err := svc.DescribeInstancesWithContext(ctx, input) +``` + +## Retry + +```go +// Default: 3 retries for network errors +// Disable retry +config.WithMaxRetries(0) + +// Custom max retries +config.WithMaxRetries(5) + +// Custom retry error codes (per-request) +input.SetRetryableErrorCodes([]string{"Throttling", "ResourceIsBusy"}) +``` + +## Debugging + +```go +config.WithDebug(true) +// Custom log writer +config.WithLogWriter(os.Stderr) +``` diff --git a/skills/volcengine-sdk-generator/references/sdk-integration-java.md b/skills/volcengine-sdk-generator/references/sdk-integration-java.md new file mode 100644 index 00000000..8861de4d --- /dev/null +++ b/skills/volcengine-sdk-generator/references/sdk-integration-java.md @@ -0,0 +1,120 @@ +# Java SDK Integration Reference + +Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md + +## Requirements + +Java 1.8.0_131+. For Java 9+, add `javax.annotation-api` dependency. + +## Authentication + +### AK/SK + +```java +String ak = System.getenv("VOLCENGINE_ACCESS_KEY"); +String sk = System.getenv("VOLCENGINE_SECRET_KEY"); +ApiClient apiClient = new ApiClient() + .setCredentials(Credentials.getCredentials(ak, sk)) + .setRegion("cn-beijing"); +``` + +### STS Token + +```java +String ak = System.getenv("VOLCENGINE_ACCESS_KEY"); +String sk = System.getenv("VOLCENGINE_SECRET_KEY"); +String token = System.getenv("VOLCENGINE_SESSION_TOKEN"); +ApiClient apiClient = new ApiClient() + .setCredentials(Credentials.getCredentials(ak, sk, token)) + .setRegion("cn-beijing"); +``` + +### STS AssumeRole + +```java +ApiClient apiClient = new ApiClient(); +apiClient.setCredentials(Credentials.getAssumeRoleCredentials( + ak, sk, + "trn:iam::accountId:role/roleName", + "sessionName", + 3600, // durationSeconds + null // policy (optional) +)); +apiClient.setRegion("cn-beijing"); +``` + +## Endpoint Configuration + +```java +// Custom endpoint +apiClient.setEndPoint("custom-endpoint.volcengineapi.com"); + +// Custom region (auto-resolves endpoint) +apiClient.setRegion("cn-shanghai"); + +// DualStack (IPv6) +apiClient.setUseDualStack(true); +``` + +## HTTP Connection Pool + +```java +// Default: 5 idle connections, 5 min keep-alive +apiClient.setMaxIdleConns(10); +apiClient.setKeepAliveDurationMs(300000); +``` + +## SSL / HTTPS + +```java +// Disable SSL verification (testing only) +apiClient.setVerifyingSsl(false); + +// Use HTTP instead of HTTPS +apiClient.setDisableSSL(true); +``` + +## Proxy + +```java +apiClient.setHttpProxy("http://proxy:8080"); +apiClient.setHttpsProxy("https://proxy:8080"); +// Also supports env vars: http_proxy, https_proxy +``` + +## Timeouts + +```java +// All in milliseconds, default 10000 (10s) +apiClient.setConnectionTimeout(5000); +apiClient.setReadTimeout(30000); +apiClient.setWriteTimeout(30000); +``` + +## Retry + +```java +// Retry is enabled by default with exponential backoff +// Configure retry attempts +apiClient.setRetrySettings(new RetrySettings() + .setMaxAttempts(5) + .setMinDelay(300) // ms + .setMaxDelay(300000) // ms +); + +// Disable retry +apiClient.setRetrySettings(new RetrySettings().setMaxAttempts(0)); + +// Custom retry error codes +apiClient.setRetrySettings(new RetrySettings() + .setRetryableErrorCodes(Arrays.asList("Throttling", "ResourceIsBusy")) +); +``` + +## Debugging + +```java +// Enable debug logging (uses SLF4J) +apiClient.setDebugging(true); +// Configure logger: com.volcengine.sdkcore +``` diff --git a/skills/volcengine-sdk-generator/references/sdk-integration-nodejs.md b/skills/volcengine-sdk-generator/references/sdk-integration-nodejs.md new file mode 100644 index 00000000..438c0024 --- /dev/null +++ b/skills/volcengine-sdk-generator/references/sdk-integration-nodejs.md @@ -0,0 +1,226 @@ +# Node.js SDK Integration Reference + +Source: https://github.com/volcengine/volcengine-nodejs-sdk/blob/master/SDK_Integration.md + +## Requirements + +Node.js >= 18. Install via pnpm/npm/yarn. + +```bash +pnpm add @volcengine/sdk-core +pnpm add @volcengine/ecs # service-specific package +``` + +## Authentication + +Credential priority: Code config > Environment variables > Config file (`~/.volc/config`) + +### AK/SK + +```typescript +// Method 1: Code (not recommended for plain text) +const client = new EcsClient({ + accessKeyId: "YOUR_AK", + secretAccessKey: "YOUR_SK", + region: "cn-beijing", +}); + +// Method 2: Environment variables (recommended) +// export VOLCSTACK_ACCESS_KEY_ID="YOUR_AK" +// export VOLCSTACK_SECRET_ACCESS_KEY="YOUR_SK" +const client = new EcsClient({ region: "cn-beijing" }); + +// Method 3: Config file (~/.volc/config) +// { "VOLC_ACCESSKEY": "AK", "VOLC_SECRETKEY": "SK" } +``` + +### STS Token + +```typescript +const client = new EcsClient({ + accessKeyId: "TEMP_AK", + secretAccessKey: "TEMP_SK", + sessionToken: "SESSION_TOKEN", + region: "cn-beijing", +}); +// Or via env: VOLCSTACK_SESSION_TOKEN +``` + +### STS AssumeRole + +```typescript +const client = new EcsClient({ + region: "cn-beijing", + assumeRoleParams: { + accessKeyId: "SUB_ACCOUNT_AK", + secretAccessKey: "SUB_ACCOUNT_SK", + roleName: "role123", + accountId: "2110400000", + region: "cn-beijing", + host: "sts.volcengineapi.com", + durationSeconds: 3600, + policy: '{"Statement":[...]}', // optional + tags: [{ Key: "project", Value: "test" }], // optional + }, +}); +``` + +## Endpoint Configuration + +```typescript +// Custom endpoint (highest priority) +const client = new EcsClient({ host: "open.volcengineapi.com" }); + +// Custom region (auto-resolves endpoint) +const client = new EcsClient({ region: "cn-shanghai" }); + +// DualStack (IPv6) - suffix changes to volcengine-api.com +const client = new EcsClient({ region: "cn-beijing", useDualStack: true }); + +// Custom bootstrap region list +const client = new EcsClient({ + region: "my-private-region", + customBootstrapRegion: { "my-private-region": {} }, +}); +// Or via env: VOLC_BOOTSTRAP_REGION_LIST_CONF=/path/to/regions.conf +``` + +### Endpoint Resolution Rules + +| Global Service | DualStack | Format | +|---|---|---| +| Yes | No | `{Service}.volcengineapi.com` | +| Yes | Yes | `{Service}.volcengine-api.com` | +| No | No | `{Service}.{region}.volcengineapi.com` | +| No | Yes | `{Service}.{region}.volcengine-api.com` | + +## Network Configuration + +```typescript +// Protocol (default: https) +const client = new EcsClient({ protocol: "http" }); + +// Proxy +const client = new EcsClient({ + httpOptions: { + proxy: { protocol: "http", host: "127.0.0.1", port: 8888 }, + }, +}); +// Or via env: VOLC_PROXY_PROTOCOL, VOLC_PROXY_HOST, VOLC_PROXY_PORT + +// Ignore SSL verification (testing only) +const client = new EcsClient({ httpOptions: { ignoreSSL: true } }); + +// Connection pool +const client = new EcsClient({ + httpOptions: { + pool: { + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 50, + maxFreeSockets: 10, + }, + }, +}); +``` + +## Timeouts + +```typescript +// Client-level (default: 30000ms) +const client = new EcsClient({ httpOptions: { timeout: 5000 } }); + +// Request-level (overrides client) +await client.send(command, { timeout: 30000 }); +``` + +## Retry + +```typescript +// Default: 4 attempts (1 initial + 3 retries) +// Retries on: network errors, HTTP 429/500/502/503/504 + +// Custom max retries +const client = new EcsClient({ maxRetries: 5 }); + +// Disable retry +const client = new EcsClient({ autoRetry: false }); + +// Backoff strategies +import { StrategyName } from "@volcengine/sdk-core"; +const client = new EcsClient({ + strategyName: StrategyName.ExponentialWithRandomJitterBackoffStrategy, // default +}); +// Options: NoBackoffStrategy, ExponentialBackoffStrategy, ExponentialWithRandomJitterBackoffStrategy + +// Custom retry strategy +const client = new EcsClient({ + retryStrategy: { + minRetryDelay: 500, + maxRetryDelay: 20000, + retryIf: (error) => { + if (error.data?.ResponseMetadata?.Error?.Code === "ResourceIsBusy") return true; + return false; + }, + delay: (attemptNumber) => 1000, + }, +}); +``` + +## Exception Handling + +```typescript +import { HttpRequestError } from "@volcengine/sdk-core"; + +try { + await client.send(command); +} catch (error) { + if (error instanceof HttpRequestError) { + if (error.status !== undefined) { + if (error.status === 0) { + // SSL error + } else if (error.data?.ResponseMetadata?.Error) { + const { Code, Message } = error.data.ResponseMetadata.Error; + const { RequestId } = error.data.ResponseMetadata; + // API error + } + } else if (error.name === "NetworkError") { + // Network error (timeout, DNS, connection refused) + } + } +} +``` + +## Resource Cleanup + +```typescript +client.destroy(); // Release network connections before app exit +``` + +## Debugging + +```typescript +// Add logging middleware +client.middlewareStack.add( + (next, context) => async (args) => { + console.log("Request:", args.request.method, args.request.host); + const result = await next(args); + console.log("Response:", result.response?.status); + return result; + }, + { step: "finalizeRequest", name: "LogMiddleware", priority: 10 } +); +``` + +## Environment Variables + +| Variable | Description | +|---|---| +| `VOLCSTACK_ACCESS_KEY_ID` / `VOLCSTACK_ACCESS_KEY` | Access Key ID | +| `VOLCSTACK_SECRET_ACCESS_KEY` / `VOLCSTACK_SECRET_KEY` | Secret Access Key | +| `VOLCSTACK_SESSION_TOKEN` | Session Token | +| `VOLC_ENABLE_DUALSTACK` | Enable DualStack (IPv6) | +| `VOLC_BOOTSTRAP_REGION_LIST_CONF` | Custom bootstrap region list file | +| `VOLC_PROXY_PROTOCOL` | Proxy protocol | +| `VOLC_PROXY_HOST` | Proxy host | +| `VOLC_PROXY_PORT` | Proxy port | diff --git a/skills/volcengine-sdk-generator/references/sdk-integration-php.md b/skills/volcengine-sdk-generator/references/sdk-integration-php.md new file mode 100644 index 00000000..378dfbd1 --- /dev/null +++ b/skills/volcengine-sdk-generator/references/sdk-integration-php.md @@ -0,0 +1,87 @@ +# PHP SDK Integration Reference + +Source: https://github.com/volcengine/volcengine-php-sdk/blob/main/SDK_Integration.md + +## Requirements + +PHP >= 5.5. Install via Composer. + +## Authentication + +### AK/SK + +```php +$config = \Volcengine\Common\Configuration::getDefaultConfiguration() + ->setAk(getenv("VOLCENGINE_ACCESS_KEY")) + ->setSk(getenv("VOLCENGINE_SECRET_KEY")) + ->setRegion("cn-beijing"); +``` + +### STS Token + +```php +$config = \Volcengine\Common\Configuration::getDefaultConfiguration() + ->setAk("TEMP_AK") + ->setSk("TEMP_SK") + ->setSessionToken("SESSION_TOKEN") + ->setRegion("cn-beijing"); +``` + +### STS AssumeRole + +```php +$config = \Volcengine\Common\Configuration::getDefaultConfiguration() + ->setAk("SUB_ACCOUNT_AK") + ->setSk("SUB_ACCOUNT_SK") + ->setRegion("cn-beijing") + ->setAssumeRoleTrn("trn:iam::accountId:role/roleName") + ->setAssumeRoleSessionName("session-name") + ->setAssumeRoleDurationSeconds(3600); +``` + +## Endpoint Configuration + +```php +// Custom endpoint +$config->setHost("custom-endpoint.volcengineapi.com"); + +// Custom region (auto-resolves endpoint) +$config->setRegion("cn-shanghai"); + +// DualStack (IPv6) +$config->setUseDualStack(true); +``` + +## SSL / HTTPS + +```php +// Use HTTP instead of HTTPS +$config->setScheme("http"); + +// Disable SSL verification (testing only) +$config->setVerifySsl(false); + +// Custom TLS version +$apiInstance = new \Volcengine\Ecs\Api\ECSApi( + new GuzzleHttp\Client([ + 'curl' => [CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2], + ]), + $config +); +``` + +## Proxy + +```php +$apiInstance = new \Volcengine\Ecs\Api\ECSApi( + new GuzzleHttp\Client([ + 'proxy' => 'http://proxy:8080', + ]), + $config +); +``` + +## Notes + +The PHP SDK documentation does not currently cover retry, timeout, or logging configuration. +For the latest details, see: https://github.com/volcengine/volcengine-php-sdk/blob/main/SDK_Integration.md diff --git a/skills/volcengine-sdk-generator/references/sdk-integration-python.md b/skills/volcengine-sdk-generator/references/sdk-integration-python.md new file mode 100644 index 00000000..aaa75aed --- /dev/null +++ b/skills/volcengine-sdk-generator/references/sdk-integration-python.md @@ -0,0 +1,141 @@ +# Python SDK Integration Reference + +Source: https://github.com/volcengine/volcengine-python-sdk/blob/master/SDK_Integration.md + +## Requirements + +Python >= 2.7 (Python 3.6+ for Ark runtime). + +## Authentication + +### AK/SK + +```python +import volcenginesdkcore + +configuration = volcenginesdkcore.Configuration() +configuration.ak = os.environ.get("VOLCENGINE_ACCESS_KEY") +configuration.sk = os.environ.get("VOLCENGINE_SECRET_KEY") +configuration.region = "cn-beijing" +volcenginesdkcore.Configuration.set_default(configuration) +``` + +### STS Token + +```python +configuration = volcenginesdkcore.Configuration() +configuration.ak = "TEMP_AK" +configuration.sk = "TEMP_SK" +configuration.session_token = "SESSION_TOKEN" +configuration.region = "cn-beijing" +volcenginesdkcore.Configuration.set_default(configuration) +``` + +### STS AssumeRole + +```python +configuration = volcenginesdkcore.Configuration() +configuration.ak = "SUB_ACCOUNT_AK" +configuration.sk = "SUB_ACCOUNT_SK" +configuration.region = "cn-beijing" +configuration.assume_role_trn = "trn:iam::accountId:role/roleName" +configuration.assume_role_session_name = "session-name" +configuration.assume_role_duration_seconds = 3600 +volcenginesdkcore.Configuration.set_default(configuration) +``` + +### STS AssumeRoleWithOIDC / SAML + +```python +# OIDC +configuration.assume_role_with_oidc_trn = "trn:iam::accountId:role/roleName" +configuration.assume_role_with_oidc_provider = "trn:iam::accountId:oidc-provider/providerName" +configuration.assume_role_with_oidc_token = "oidc-token" + +# SAML +configuration.assume_role_with_saml_trn = "trn:iam::accountId:role/roleName" +configuration.assume_role_with_saml_principal = "trn:iam::accountId:saml-provider/providerName" +configuration.assume_role_with_saml_assertion = "saml-assertion" +``` + +## Endpoint Configuration + +```python +# Custom endpoint +configuration.host = "custom-endpoint.volcengineapi.com" + +# Custom region (auto-resolves endpoint) +configuration.region = "cn-shanghai" + +# DualStack (IPv6) +configuration.use_dual_stack = True +``` + +## Connection Pool + +```python +# Default: 4 pools, maxsize = cpu_count * 5 +configuration.connection_pool_maxsize = 20 +configuration.connection_pools_count = 8 +``` + +## SSL / HTTPS + +```python +# Use HTTP instead of HTTPS +configuration.scheme = "http" + +# Disable SSL verification (testing only) +configuration.verify_ssl = False + +# Custom SSL CA cert +configuration.ssl_ca_cert = "/path/to/ca-bundle.crt" +``` + +## Proxy + +```python +configuration.proxy = "http://proxy:8080" +configuration.proxy_https = "https://proxy:8080" +# Also reads env vars: http_proxy, https_proxy (code takes precedence) +``` + +## Timeouts + +```python +# Default: 30s each +configuration.connection_timeout = 10 # seconds +configuration.read_timeout = 60 # seconds + +# Per-request timeout via RuntimeOption +runtime_option = volcenginesdkcore.RuntimeOption() +runtime_option.connection_timeout = 5 +runtime_option.read_timeout = 30 +resp = api_instance.some_action(request, _runtime_option=runtime_option) +``` + +## Retry + +```python +# Retry is enabled by default for network errors and throttling +configuration.max_retry_attempts = 5 +configuration.min_retry_delay = 300 # ms +configuration.max_retry_delay = 300000 # ms + +# Disable retry +configuration.max_retry_attempts = 0 + +# Custom retry error codes +configuration.retry_error_codes = ["Throttling", "ResourceIsBusy"] + +# Backoff strategies: ExponentialBackoff, ExponentialBackoffWithJitter (default) +configuration.retry_backoff_strategy = "ExponentialBackoffWithJitter" +``` + +## Debugging + +```python +configuration.debug = True +# Log level: configuration.log_level = "DEBUG" +# Log file: configuration.log_file = "/path/to/sdk.log" +```