
Tos File Access
- 58 installs
- 411 repo stars
- Updated August 4, 2026
- bytedance/agentkit-samples
TOS File Access is a Claude skill (ByteDance AgentKit sample) that uploads files and directories to Volcengine TOS object storage and downloads files from URLs for agent processing.
About
TOS File Access is a ByteDance AgentKit skill that uploads agent-generated files or directories to Volcengine TOS object storage and downloads files from URLs. Uploads return a signed shareable URL for files or a tos:// path for directories, while downloads pull remote files locally before processing. It auto-detects file versus directory and uses Volcengine access/secret keys or a VeFaaS IAM role. Developers use it to move files in and out of TOS around agent runs.
- Uploads files or directories to Volcengine TOS object storage
- Downloads files from URLs for agent processing
- Returns signed URLs for files and tos:// paths for directories
Tos File Access by the numbers
- 58 all-time installs (skills.sh)
- Ranked #692 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
tos-file-access capabilities & compatibility
Requires Volcengine access/secret keys or a VeFaaS IAM role, plus a TOS bucket.
- Capabilities
- file upload · file download · object storage
- Pricing
- Bring your own API key
What tos-file-access says it does
This skill provides utilities for uploading files and directories to Volcano Engine TOS (Torch Object Storage) and downloading files from URLs.
**TOS (Torch Object Storage)** is Volcano Engine's object storage service, similar to AWS S3.
**For files**: Prints a signed URL that can be shared with users (valid for specified duration)
npx skills add https://github.com/bytedance/agentkit-samples --skill tos-file-accessAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 58 |
|---|---|
| repo stars | ★ 411 |
| Last updated | August 4, 2026 |
| Repository | bytedance/agentkit-samples ↗ |
What it does
Upload agent files or directories to Volcengine TOS and download files from URLs.
Who is it for?
Uploading agent outputs to Volcengine TOS and downloading source files from URLs.
Skip if: Non-Volcengine object storage; it targets TOS and needs Volcengine credentials or a VeFaaS IAM role.
When should I use this skill?
You need to upload agent-generated files to TOS or download files from URLs before processing.
What you get
Files/directories uploaded to TOS with signed URLs or tos:// paths, and remote URLs downloaded locally.
- signed TOS URL for files
- tos:// path for directories
- downloaded files locally
By the numbers
- signed URLs valid 7 days (604800s) by default
- default region cn-beijing
Files
TOS File Access
This skill provides utilities for uploading files and directories to Volcano Engine TOS (Torch Object Storage) and downloading files from URLs.
Overview
TOS (Torch Object Storage) is Volcano Engine's object storage service, similar to AWS S3. This skill enables:
- Upload: Upload Agent-generated files or entire directories to TOS and get shareable signed URLs (for files) or TOS paths (for directories)
- Download: Download files from URLs to local storage for Agent processing
Typical Workflows
Pre-Agent Execution: Download User Files
When users provide file URLs (TOS or external), download them before processing:
# Download single file
python scripts/file_download.py https://example.com/data.csv
# Download multiple files
python scripts/file_download.py https://example.com/data.csv https://example.com/config.json
# Specify save directory and filenames
python scripts/file_download.py https://example.com/data.csv --save-dir /workspace --filenames dataset.csvPost-Agent Execution: Upload Output Files or Directories
After generating files or directories (videos, charts, reports, output folders, etc.), upload them to TOS for user access:
# Upload single file (auto-detected)
python scripts/tos_upload.py /path/to/output.mp4 --bucket my-bucket
# Upload entire directory (auto-detected)
python scripts/tos_upload.py /path/to/output_folder --bucket my-bucket
# Upload with custom region and expiration
python scripts/tos_upload.py /path/to/report.pdf --bucket my-bucket --region cn-beijing --expires 86400Scripts
scripts/file_download.py
Download files from URLs to local storage.
Usage:
python scripts/file_download.py <url1> [url2 ...] [--save-dir DIR] [--filenames NAME1 NAME2 ...]Arguments:
urls: One or more URLs to download (positional, required)--save-dir: Save directory (optional, defaults to/tmp)--filenames: Custom filenames for downloaded files (optional, must match number of URLs)
Examples:
# Download single file to /tmp
python scripts/file_download.py https://tos-cn-beijing.volces.com/bucket/file.pdf
# Download to specific directory
python scripts/file_download.py https://example.com/data.json --save-dir /workspace/data
# Download multiple files with custom names
python scripts/file_download.py \
https://example.com/file1.pdf \
https://example.com/file2.jpg \
--save-dir /workspace \
--filenames document.pdf image.jpgReturns: Prints absolute paths of downloaded files (one per line)
scripts/tos_upload.py
Upload files or directories to TOS and generate signed access URLs (for files) or TOS paths (for directories).
Key Features:
- Auto-detection: Automatically detects whether the path is a file or directory
- Session-based paths: Uses
TOOL_USER_SESSION_IDenvironment variable to organize uploads - Preserves structure: For directories, maintains the full directory structure in TOS
- Automatic bucket creation: Creates bucket if it doesn't exist (with private ACL)
Usage:
python scripts/tos_upload.py <path> --bucket BUCKET [--region REGION] [--expires SECONDS]Arguments:
path: Local file or directory path to upload (positional, required)--bucket: TOS bucket name (required)--region: TOS region (optional, defaults tocn-beijing)--expires: Signed URL expiration in seconds (optional, defaults to 604800 = 7 days, only applies to file uploads)
Upload Structure:
- File:
upload/{session_prefix}/{filename} - Example:
upload/skill_agent_veadk_default_user_tmp-session-20251210150057/video.mp4 - Directory:
upload/{session_prefix}/{directory_name}/{relative_path} - Example:
upload/skill_agent_veadk_default_user_tmp-session-20251210150057/output_folder/file1.txt
Session Prefix:
- If
TOOL_USER_SESSION_IDis set, uses that value as prefix - Otherwise, falls back to timestamp format
YYYYMMDD_HHMMSS
Authentication: Requires one of:
- Environment variables:
VOLCENGINE_ACCESS_KEYandVOLCENGINE_SECRET_KEY - VeFaaS IAM Role (automatic credential retrieval)
Examples:
# Upload single file (auto-detected)
python scripts/tos_upload.py /workspace/output.mp4 --bucket my-bucket
# Upload entire directory (auto-detected)
python scripts/tos_upload.py /workspace/results_folder --bucket my-bucket
# Upload to different region with 1-day expiration
python scripts/tos_upload.py /workspace/report.pdf \
--bucket my-reports \
--region cn-beijing \
--expires 86400
# Upload directory with all options
python scripts/tos_upload.py /workspace/output_dir \
--bucket data-storage \
--region cn-beijingReturns:
- For files: Prints a signed URL that can be shared with users (valid for specified duration)
- For directories: Prints a TOS path in format
tos://bucket-name/path/to/directory
Output Examples:
# File upload output
============================================================
✅ Upload Successful!
============================================================
Signed URL:
https://my-bucket.tos-cn-beijing.volces.com/upload/skill_agent_xxx/video.mp4?X-Tos-Signature=...
============================================================
# Directory upload output
============================================================
✅ Upload Successful!
============================================================
TOS Path:
tos://my-bucket/upload/skill_agent_xxx/output_folder
============================================================Environment Variables
VOLCENGINE_ACCESS_KEY: Volcano Engine access key for TOS authenticationVOLCENGINE_SECRET_KEY: Volcano Engine secret key for TOS authenticationTOOL_USER_SESSION_ID: Session ID used to generate organized upload paths (optional, falls back to timestamp)
Common Use Cases
1. Video Processing: Download source video → process → upload result
# Download
python scripts/file_download.py https://example.com/input.mp4 --save-dir /workspace
# Process video (your code here)
# Upload result
python scripts/tos_upload.py /workspace/output.mp4 --bucket video-storage2. Data Analysis: Download datasets → analyze → upload charts/reports folder
# Download data
python scripts/file_download.py https://example.com/data.csv --save-dir /workspace
# Analyze and generate charts (your code here)
# Upload entire results folder
python scripts/tos_upload.py /workspace/analysis_results --bucket analysis-bucket3. Batch Processing: Process multiple files and upload output directory
# Process files (your code here, generates /workspace/batch_output/)
# Upload entire output directory
python scripts/tos_upload.py /workspace/batch_output --bucket batch-results4. Project Export: Upload a complete project directory structure
# Upload project directory with subdirectories
python scripts/tos_upload.py /workspace/my_project --bucket project-storage
# Result: tos://project-storage/upload/{session_id}/my_project/...Error Handling
- IF the script raises the error
VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY are not provided or IAM Role is not configured., inform the user that they need to provide theVOLCENGINE_ACCESS_KEYandVOLCENGINE_SECRET_KEYenvironment variable. Write it to the environment variable file in the workspace. If the file already exists, append it to the end. Ensure the environment variable format is correct, make the environment variable effective, and retry the task that just failed.
Notes
- Auto-detection: No need to specify whether uploading a file or directory - the script detects automatically
- Session organization: Files and directories are automatically organized by session ID for easy tracking
- Signed URLs (files only): Valid for 7 days by default (adjustable via
--expires) - TOS Paths (directories): Returned as
tos://bucket/pathformat for reference - Structure preservation: Directory uploads maintain the complete folder structure in TOS
- No timestamp in filenames: Original filenames are preserved (session prefix provides uniqueness)
- Auto-bucket creation: Bucket is automatically created with private ACL if it doesn't exist
- Auto-deduplication: Downloads automatically rename files if they already exist
- IAM Role support: Scripts automatically retrieve credentials from VeFaaS IAM when available
- Error handling: Scripts print clear error messages for network, permission, or file issues
- Bucket requirement: Bucket name must be specified via
--bucketparameter (required)
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.# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# 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.
import argparse
import logging
import os
import sys
from pathlib import Path
from typing import List, Optional
from urllib.parse import unquote, urlparse
import requests
# Configure logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.handlers:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
def file_download(
url: List[str], save_dir: Optional[str] = None, filename: Optional[List[str]] = None
) -> List[str]:
"""
Batch download files from the internet to local storage, supporting simultaneous download of multiple URLs to avoid agent loop calls
Args:
url: List of file URLs (can be a single-URL list or multiple URLs)
save_dir: Save directory, defaults to /tmp
filename: List of filenames to save; if None, filenames will be extracted from URLs
Returns:
List[str]: List of absolute paths to downloaded files
Raises:
requests.exceptions.RequestException: Network request failure
IOError: File write failure
ValueError: Parameter error
Examples:
# Download single file
paths = file_download(["https://example.com/file.pdf"])
# Batch download multiple files
paths = file_download([
"https://example.com/file1.pdf",
"https://example.com/file2.jpg",
"https://example.com/file3.json"
])
"""
# Ensure url is a list
if not isinstance(url, list):
raise ValueError("url parameter must be a list")
urls = url
if save_dir is None:
# Prefer environment variable
save_dir = "/tmp"
# Handle filename parameter
if filename is None:
filenames = [None] * len(urls)
elif isinstance(filename, list):
if len(filename) != len(urls):
raise ValueError(
f"filename list length ({len(filename)}) must match url list length ({len(urls)})"
)
filenames = filename
else:
raise ValueError("filename must be a list or None")
# Download all files
downloaded_paths = []
for url_item, filename_item in zip(urls, filenames):
path = _download_single_file(url_item, save_dir, filename_item)
downloaded_paths.append(path)
return downloaded_paths
def _download_single_file(
url: str, save_dir: Optional[str] = None, filename: Optional[str] = None
) -> str:
"""
Download a single file (internal helper function)
Args:
url: File URL
save_dir: Save directory, defaults to /tmp
filename: Filename to save
Returns:
str: Absolute path to downloaded file
Raises:
requests.exceptions.RequestException: Network request failure
IOError: File write failure
"""
# Determine save directory
if save_dir is None:
# Prefer environment variable
save_dir = "/tmp"
# Ensure save directory exists
save_path = Path(save_dir)
save_path.mkdir(parents=True, exist_ok=True)
# Determine filename
if filename is None:
# Extract filename from URL
parsed_url = urlparse(url)
filename = unquote(os.path.basename(parsed_url.path))
# If no filename in URL, use default name
if not filename or filename == "/":
filename = "downloaded_file"
# Full file path
full_path = save_path / filename
# If file exists, add counter to avoid overwriting
counter = 1
original_stem = full_path.stem
original_suffix = full_path.suffix
while full_path.exists():
filename = f"{original_stem}_{counter}{original_suffix}"
full_path = save_path / filename
counter += 1
# Download file
try:
logger.info(f"Downloading: {url}")
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
# Write file
with open(full_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
logger.info(f"Downloaded: {full_path}")
return str(full_path.absolute())
except requests.exceptions.RequestException as e:
raise requests.exceptions.RequestException(f"Download failed: {str(e)}")
except IOError as e:
raise IOError(f"Write file failed: {str(e)}")
def main():
"""Command-line interface for file_download"""
parser = argparse.ArgumentParser(
description="Download files from URLs to local storage",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Download single file
python file_download.py https://example.com/file.pdf
# Download multiple files
python file_download.py https://example.com/file1.pdf https://example.com/file2.jpg
# Download to specific directory
python file_download.py https://example.com/file.pdf --save-dir /workspace
# Download with custom filenames
python file_download.py https://example.com/f1.pdf https://example.com/f2.jpg --filenames doc.pdf img.jpg
""",
)
parser.add_argument("urls", nargs="+", help="One or more URLs to download")
parser.add_argument(
"--save-dir",
type=str,
default="/tmp",
help="Directory to save downloaded files (default: /tmp)",
)
parser.add_argument(
"--filenames",
nargs="+",
default=None,
help="Custom filenames for downloaded files (must match number of URLs)",
)
args = parser.parse_args()
try:
# Call download function
downloaded_paths = file_download(
url=args.urls, save_dir=args.save_dir, filename=args.filenames
)
# Print results (one path per line for easy parsing)
print("\n=== Downloaded Files ===")
for path in downloaded_paths:
print(path)
sys.exit(0)
except Exception as e:
logger.error(f"Error: {e}")
sys.exit(1)
# Example usage
if __name__ == "__main__":
main()
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# 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.
"""
TOS file/directory upload utility
Provides functionality to upload files or directories to Volcano Engine TOS object storage and returns signed access URLs
"""
import argparse
import logging
import os
import requests
import sys
from datetime import datetime
from pathlib import Path
from pydantic import BaseModel
from typing import Optional, Union
from dotenv import load_dotenv
import tos
from tos import HttpMethodType
# Current directory
sys.path.append(str(Path(__file__).resolve().parent))
# Parent directory
sys.path.append(str(Path(__file__).resolve().parent.parent))
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.handlers:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
def success_loaded_openclaw_dotenv() -> bool:
openclaw_env = Path("/root/.openclaw/.env")
# openclaw_env = Path(
# "/Users/bytedance/workspace/agentkit/agentkit-samples/skills/.venv/.openclaw/.env"
# )
if openclaw_env.exists():
success = load_dotenv(openclaw_env)
logger.info(f"Successfully loaded environment variables from {openclaw_env}")
return success
LOAD_OPENCLAW_DOTENV_SUCCESS = success_loaded_openclaw_dotenv()
class VeIAMCredential(BaseModel):
access_key_id: str
secret_access_key: str
session_token: str
def get_credential_from_service() -> VeIAMCredential:
"""Get credential from credential service"""
endpoint = os.getenv("CREDENTIAL_SERVICE_ENDPOINT")
api_key = os.getenv("CREDENTIAL_SERVICE_API_KEY")
if not endpoint or not api_key:
logger.error(
"CREDENTIAL_SERVICE_ENDPOINT and CREDENTIAL_SERVICE_API_KEY environment variables must be set to fetch credentials from service."
)
return None
try:
response = requests.get(
url=f"{endpoint}/credential",
headers={"Authorization": f"Bearer {api_key}"},
timeout=5,
)
response.raise_for_status()
credential_data = response.json()["data"]
logger.info(f"Successfully fetched credentials from service {endpoint}.")
print(f"Credential data from service: {credential_data}") # Debug output
return VeIAMCredential(
access_key_id=credential_data["access_key_id"],
secret_access_key=credential_data["secret_access_key"],
session_token=credential_data["session_token"],
)
except Exception as e:
logger.error(f"Failed to fetch credentials from service: {e}")
return None
def identify_volc_env() -> str:
"""
Identify the Volcano Engine environment (vefaas or ecs).
"""
VEFAAS_IAM_CRIDENTIAL_PATH = "/var/run/secrets/iam/credential"
ECS_CLOUD_LINUX_ENV_PATH = "/etc/cloud/cloud.cfg"
ECS_CLOUD_WINDOWS_ENV_PATH = r"C:\Program Files\Cloudbase Solutions\Cloudbase-Init"
if os.path.exists(VEFAAS_IAM_CRIDENTIAL_PATH):
return "vefaas"
elif os.path.exists(ECS_CLOUD_LINUX_ENV_PATH):
return "ecs"
elif os.path.exists(ECS_CLOUD_WINDOWS_ENV_PATH):
return "ecs"
else:
return "unknown"
VOLC_ENV = identify_volc_env()
if VOLC_ENV == "vefaas":
try:
from veadk.auth.veauth.utils import get_credential_from_vefaas_iam
except ImportError:
logger.error("vefaas environment detected but veadk import failed.")
def _get_session_prefix() -> str:
"""Extract session prefix from TOOL_USER_SESSION_ID environment variable
Returns:
str: Session prefix (e.g., "skill_agent_veadk_default_user_tmp-session-20251210150057")
or timestamp if not set
"""
session_id = os.getenv("TOOL_USER_SESSION_ID", "")
if session_id:
return session_id
else:
# Fallback to timestamp if no session ID
return datetime.now().strftime("%Y%m%d_%H%M%S")
def upload_file_to_tos(
file_path: str,
bucket_name: str,
region: str = "cn-beijing",
ak: Optional[str] = None,
sk: Optional[str] = None,
session_token: Optional[str] = None,
expires: int = 604800, # 7-day validity
) -> Optional[str]:
"""
Upload a file to TOS object storage and return a signed accessible URL
Args:
file_path: Local file path
bucket_name: TOS bucket name
region: TOS region, defaults to cn-beijing
ak: Access Key; if empty, reads from environment variables
sk: Secret Key; if empty, reads from environment variables
session_token: Session token
expires: Signed URL validity period (seconds), defaults to 7 days
Returns:
str: Signed TOS URL that can be accessed directly
None: Returns None if upload fails
Environment variables:
VOLCENGINE_ACCESS_KEY: Volcano Engine access key
VOLCENGINE_SECRET_KEY: Volcano Engine secret key
TOOL_USER_SESSION_ID: Session ID for generating object key prefix
"""
if bucket_name is None:
logger.error("Error: bucket name The bucket has not been specified.")
return None
# Check if file exists
if not os.path.exists(file_path):
logger.error(f"Error: File does not exist: {file_path}")
return None
if not os.path.isfile(file_path):
logger.error(f"Error: Path is not a file: {file_path}")
return None
# Retrieve credentials
access_key = ak or os.getenv("VOLCENGINE_ACCESS_KEY")
secret_key = sk or os.getenv("VOLCENGINE_SECRET_KEY")
session_token = session_token or ""
if not (access_key and secret_key):
# First try to get credentials from Credential Service if environment variables are set
if os.getenv("CREDENTIAL_SERVICE_ENDPOINT") and os.getenv(
"CREDENTIAL_SERVICE_API_KEY"
):
logger.info("Trying to fetch credentials from Credential Service...")
try:
cred = get_credential_from_service()
access_key = cred.access_key_id
secret_key = cred.secret_access_key
session_token = cred.session_token
except Exception as e:
logger.warning(f"Failed to get credential from Credential Service: {e}")
if VOLC_ENV == "vefaas":
if get_credential_from_vefaas_iam:
logger.info("Trying to fetch credentials from VeFaaS IAM...")
try:
cred = get_credential_from_vefaas_iam()
access_key = cred.access_key_id
secret_key = cred.secret_access_key
session_token = cred.session_token
except Exception as e:
logger.warning(f"Failed to get credential from vefaas iam: {e}")
else:
logger.warning(
"vefaas environment detected but get_credential_from_vefaas_iam is None."
)
if not access_key or not secret_key:
raise PermissionError(
"VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY are not provided or IAM Role or Credential Service is not configured."
)
# Auto-generate object_key: upload/{session_prefix}/{filename}
session_prefix = _get_session_prefix()
filename = os.path.basename(file_path)
object_key = f"upload/{session_prefix}/{filename}"
# Create TOS client
client = None
try:
# Initialize TOS client
endpoint = f"tos-{region}.volces.com"
client = tos.TosClientV2(
ak=access_key,
sk=secret_key,
security_token=session_token,
endpoint=endpoint,
region=region,
)
logger.info(f"Starting file upload: {file_path}")
logger.info(f"Target Bucket: {bucket_name}")
logger.info(f"Object Key: {object_key}")
# Ensure bucket exists (create if not)
try:
client.head_bucket(bucket_name)
logger.info(f"Bucket {bucket_name} already exists")
except tos.exceptions.TosServerError as e:
if e.status_code == 404:
logger.info(f"Bucket {bucket_name} does not exist, creating...")
client.create_bucket(
bucket=bucket_name,
acl=tos.ACLType.ACL_Private,
storage_class=tos.StorageClassType.Storage_Class_Standard,
)
logger.info(f"Bucket {bucket_name} created successfully")
else:
raise e
# Upload file
result = client.put_object_from_file(
bucket=bucket_name, key=object_key, file_path=file_path
)
logger.info("File uploaded successfully!")
logger.info(f"ETag: {result.etag}")
# Generate signed URL
signed_url_output = client.pre_signed_url(
http_method=HttpMethodType.Http_Method_Get,
bucket=bucket_name,
key=object_key,
expires=expires,
)
signed_url = signed_url_output.signed_url
logger.info(
f"Signed URL generated (valid for {expires} seconds / {expires // 86400} days)"
)
return signed_url
except tos.exceptions.TosClientError as e:
logger.error(f"TOS client error: {e}")
return None
except tos.exceptions.TosServerError as e:
logger.error(f"TOS server error: {e}")
logger.error(f"Status code: {e.status_code}")
logger.error(f"Error code: {e.code}")
logger.error(f"Error message: {e.message}")
return None
except Exception as e:
logger.error(f"File upload failed: {e}")
import traceback
traceback.print_exc()
return None
finally:
# Close client
if client:
client.close()
def upload_directory_to_tos(
directory_path: str,
bucket_name: str,
region: str = "cn-beijing",
ak: Optional[str] = None,
sk: Optional[str] = None,
session_token: Optional[str] = None,
expires: int = 604800,
) -> Optional[str]:
"""
Upload entire directory to TOS object storage and return signed URLs for all files
Args:
directory_path: Local directory path
bucket_name: TOS bucket name
region: TOS region, defaults to cn-beijing
ak: Access Key; if empty, reads from environment variables
sk: Secret Key; if empty, reads from environment variables
session_token: Session token
expires: Signed URL validity period (seconds), defaults to 7 days
Returns:
str: TOS path for uploaded directory
None: Returns None if upload fails
Environment variables:
VOLCENGINE_ACCESS_KEY: Volcano Engine access key
VOLCENGINE_SECRET_KEY: Volcano Engine secret key
"""
if bucket_name is None:
logger.error("Error: bucket name The bucket has not been specified.")
return None
# Check if directory exists
if not os.path.exists(directory_path):
logger.error(f"Error: Directory does not exist: {directory_path}")
return None
if not os.path.isdir(directory_path):
logger.error(f"Error: Path is not a directory: {directory_path}")
return None
# Retrieve credentials
access_key = ak or os.getenv("VOLCENGINE_ACCESS_KEY")
secret_key = sk or os.getenv("VOLCENGINE_SECRET_KEY")
session_token = session_token or ""
if not (access_key and secret_key):
# First try to get credentials from Credential Service if environment variables are set
if os.getenv("CREDENTIAL_SERVICE_ENDPOINT") and os.getenv(
"CREDENTIAL_SERVICE_API_KEY"
):
logger.info("Trying to fetch credentials from Credential Service...")
try:
cred = get_credential_from_service()
access_key = cred.access_key_id
secret_key = cred.secret_access_key
session_token = cred.session_token
except Exception as e:
logger.warning(f"Failed to get credential from Credential Service: {e}")
if VOLC_ENV == "vefaas":
if get_credential_from_vefaas_iam:
try:
cred = get_credential_from_vefaas_iam()
access_key = cred.access_key_id
secret_key = cred.secret_access_key
session_token = cred.session_token
except Exception as e:
logger.error(f"Failed to get credential from vefaas iam: {e}")
else:
logger.warning(
"vefaas environment detected but get_credential_from_vefaas_iam is None."
)
if not access_key or not secret_key:
logger.error(
"Error: VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY are not provided or IAM Role or Credential Service is not configured."
)
return None
# Auto-generate object_key_prefix: upload/{session_prefix}/{directory_name}
session_prefix = _get_session_prefix()
directory_name = os.path.basename(os.path.abspath(directory_path))
object_key_prefix = f"upload/{session_prefix}/{directory_name}"
# Create TOS client
client = None
try:
# Initialize TOS client
endpoint = f"tos-{region}.volces.com"
client = tos.TosClientV2(
ak=access_key,
sk=secret_key,
security_token=session_token,
endpoint=endpoint,
region=region,
)
logger.info(f"Starting directory upload: {directory_path}")
logger.info(f"Target Bucket: {bucket_name}")
logger.info(f"Object Key Prefix: {object_key_prefix}")
# Ensure bucket exists (create if not)
try:
client.head_bucket(bucket_name)
logger.info(f"Bucket {bucket_name} already exists")
except tos.exceptions.TosServerError as e:
if e.status_code == 404:
logger.info(f"Bucket {bucket_name} does not exist, creating...")
client.create_bucket(
bucket=bucket_name,
acl=tos.ACLType.ACL_Private,
storage_class=tos.StorageClassType.Storage_Class_Standard,
)
logger.info(f"Bucket {bucket_name} created successfully")
else:
raise e
# Upload all files in directory recursively
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
# Calculate relative path from directory_path
relative_path = os.path.relpath(file_path, directory_path)
# Construct object key: upload/{session_prefix}/{directory_name}/{relative_path}
object_key = f"{object_key_prefix}/{relative_path}"
# Upload file
try:
result = client.put_object_from_file(
bucket=bucket_name, key=object_key, file_path=file_path
)
logger.info(
f"Uploaded: {file_path} -> {object_key}, result: {result}"
)
except Exception as e:
logger.error(f"Failed to upload {file_path}: {e}")
tos_path = f"tos://{bucket_name}/{object_key_prefix} "
logger.info(f"Directory upload completed! TOS Path: {tos_path}")
return tos_path
except tos.exceptions.TosClientError as e:
logger.error(f"TOS client error: {e}")
return None
except tos.exceptions.TosServerError as e:
logger.error(f"TOS server error: {e}")
logger.error(f"Status code: {e.status_code}")
logger.error(f"Error code: {e.code}")
logger.error(f"Error message: {e.message}")
return None
except Exception as e:
logger.error(f"Directory upload failed: {e}")
import traceback
traceback.print_exc()
return None
finally:
# Close client
if client:
client.close()
def upload_to_tos(
path: str,
bucket_name: str,
region: str = "cn-beijing",
ak: Optional[str] = None,
sk: Optional[str] = None,
session_token: Optional[str] = None,
expires: int = 604800,
) -> Optional[Union[str, list[str]]]:
"""
Upload a file or directory to TOS object storage
This function automatically detects whether the path is a file or directory
and calls the appropriate upload function.
Args:
path: Local file or directory path
bucket_name: TOS bucket name
region: TOS region
ak: Access Key
sk: Secret Key
session_token: Session token
expires: Signed URL validity period (seconds)
Returns:
str: Signed URL if uploading a file
list[str]: List of signed URLs if uploading a directory
None: Returns None if upload fails
"""
if not os.path.exists(path):
logger.error(f"Error: Path does not exist: {path}")
return None
if os.path.isfile(path):
# Upload single file
return upload_file_to_tos(
file_path=path,
bucket_name=bucket_name,
region=region,
ak=ak,
sk=sk,
session_token=session_token,
expires=expires,
)
elif os.path.isdir(path):
# Upload directory
return upload_directory_to_tos(
directory_path=path,
bucket_name=bucket_name,
region=region,
ak=ak,
sk=sk,
session_token=session_token,
expires=expires,
)
else:
logger.error(f"Error: Path is neither a file nor a directory: {path}")
return None
def main():
"""Command-line interface for tos_upload"""
parser = argparse.ArgumentParser(
description="Upload files or directories to Volcano Engine TOS and generate signed URLs",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Upload a file (auto-detect)
python tos_upload.py /path/to/file.mp4 --bucket my-bucket
# Upload a directory (auto-detect)
python tos_upload.py /path/to/directory --bucket my-bucket
# Upload to different region with custom expiration
python tos_upload.py /path/to/file.json --bucket my-bucket --region cn-beijing --expires 86400
File Upload Structure:
File: upload/{session_prefix}/{filename}
Directory: upload/{session_prefix}/{directory_name}/{relative_path}
Environment Variables:
VOLCENGINE_ACCESS_KEY Volcano Engine access key
VOLCENGINE_SECRET_KEY Volcano Engine secret key
TOOL_USER_SESSION_ID Session ID for generating object key prefix
""",
)
parser.add_argument("path", type=str, help="Local file or directory path to upload")
parser.add_argument("--bucket", type=str, required=True, help="TOS bucket name")
parser.add_argument(
"--region",
type=str,
default="cn-beijing",
help="TOS region (default: cn-beijing)",
)
parser.add_argument(
"--expires",
type=int,
default=604800,
help="Signed URL expiration in seconds (default: 604800 = 7 days)",
)
args = parser.parse_args()
try:
# Auto-detect and upload
result = upload_to_tos(
path=args.path,
bucket_name=args.bucket,
region=args.region,
expires=args.expires,
)
if result:
print("\n" + "=" * 60)
print("✅ Upload Successful!")
print("=" * 60)
if os.path.isfile(args.path):
print(f"Signed URL:\n{result}")
elif os.path.isdir(args.path):
print(f"TOS Path:\n{result}")
print("=" * 60)
sys.exit(0)
else:
logger.error("\n❌ Upload failed")
sys.exit(1)
except Exception as e:
logger.error(f"Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()
Related skills
FAQ
What does an upload return?
A signed URL for a single file (valid 7 days by default) or a tos:// path for a directory.
How does it authenticate?
With VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY, or automatically via a VeFaaS IAM role.