
Byted Tos File Process
- 8 installs
- 411 repo stars
- Updated August 4, 2026
- bytedance/agentkit-samples
byted-tos-file-process is a Claude skill that compresses and uncompresses file objects in Volcengine TOS through TOS file_jobs async jobs.
About
This skill compresses and uncompresses file objects stored in Volcengine TOS through TOS data-process async jobs. A developer uses it to zip or unzip archives, create tar or zstd archives, pack multiple TOS objects into one archive, or extract compressed files. It submits async jobs through the TOS gateway file_jobs API and can poll until completion.
- Compresses and uncompresses TOS objects via async file jobs
- Supports zip, tar, and zst archive formats
- Packs multiple TOS objects into a single archive
Byted Tos File Process by the numbers
- 8 all-time installs (skills.sh)
- Ranked #1,519 of 2,715 Automation & Workflows skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
byted-tos-file-process capabilities & compatibility
Requires Volcengine TOS credentials (access key, secret, endpoint, region, bucket)
- Capabilities
- file compression · archive management · media processing
- Pricing
- Bring your own API key
What byted-tos-file-process says it does
Compresses and uncompresses file objects stored in Volcengine TOS through TOS data-process async jobs.
Compress supports `zip`, `tar`, and `zst`.
npx skills add https://github.com/bytedance/agentkit-samples --skill byted-tos-file-processAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 8 |
|---|---|
| repo stars | ★ 411 |
| Last updated | August 4, 2026 |
| Repository | bytedance/agentkit-samples ↗ |
What it does
Compress or extract Volcengine TOS file objects into zip, tar, or zst archives via async jobs.
When should I use this skill?
You need to zip or unzip files in TOS, create tar or zstd archives, pack multiple TOS objects into one archive, or extract compressed files.
What you get
Submits FileCompress or FileUncompress jobs that pack or extract TOS archives, optionally waiting for completion.
By the numbers
- Bundles 3 scripts (compress, uncompress, client)
- Supports 3 archive formats: zip, tar, zst
Files
Volcengine TOS File Process
Compress and uncompress file objects stored in Volcengine TOS through the TOS gateway's file_jobs API.
Setup (once per environment)
Install dependencies on first use:
cd {baseDir}
pip install -r {baseDir}/requirements.txtThen run scripts with Python 3.7+:
python3 {baseDir}/scripts/<script>.py <args>Environment Variables
This skill relies on the TOS identity declared in the metadata block. Common runtime variables are:
| Environment Variable | Required | Description |
|---|---|---|
TOS_ACCESS_KEY | Yes | TOS access key ID |
TOS_SECRET_KEY | Yes | TOS secret access key |
TOS_ENDPOINT | Yes | TOS endpoint URL |
TOS_REGION | Yes | TOS region |
TOS_BUCKET | Yes | Source bucket that stores the file objects |
TOS_OBJECT_KEY | No | Source object key. Can be overridden with --key or --keys |
TOS_SECURITY_TOKEN | No | STS session token when using temporary credentials |
Quick start
# Compress multiple TOS objects into a zip archive and wait for completion
python3 {baseDir}/scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zip \
--output-key output/archive.zip \
--wait
# Uncompress a zip archive and wait for completion
python3 {baseDir}/scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/unzipped/ \
--waitAvailable scripts
| Script | Purpose |
|---|---|
scripts/file_compress.py | Submit an async FileCompress job via the TOS gateway's file_jobs API that compresses TOS objects into an archive (zip/tar/zst). Supports --wait to poll until completion. |
scripts/file_uncompress.py | Submit an async FileUncompress job via the TOS gateway's file_jobs API that extracts an archive in TOS. Supports --wait to poll until completion. |
scripts/tos_jobs_client.py | Shared client for TOS gateway file_jobs APIs using pre-signed URL auth. |
Rules
- TOS gateway API: This skill uses the TOS gateway's
file_jobsAPI withjob_type=FileCompressorjob_type=FileUncompress. Authentication is handled viapre_signed_urlfrom the TOS Python SDK and the TOS identity declared in themetadatablock above. - Supported archive formats: Compress supports
zip,tar, andzst. The output object key suffix must match the chosen format (.zip,.tar,.zst). - Async job model: The scripts create async jobs and optionally wait for completion with the
--waitflag. - Language: Reply in the user's preferred language.
Further reading
- Setup and environment: README.md
- Parameter reference: REFERENCE.md
- End-to-end workflows: WORKFLOWS.md
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 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.
Bytedance TOS File Process Skill
This skill provides an async file-processing toolkit for files stored in Bytedance TOS. It currently focuses on compressing TOS objects into archives and extracting archives back into TOS objects.
When To Use
Use this skill when you need to:
- Compress multiple TOS objects into a zip, tar, or zst archive
- Uncompress a zip, tar, or zst archive stored in TOS
- Archive files for distribution or storage
- Extract files from an archive in TOS
- Submit an async
FileCompressorFileUncompressjob via the TOS gateway'sfile_jobsAPI and optionally wait for completion
Do not use this skill for:
- Local-only compression workflows that do not involve TOS
- Audio or video transcoding
- Document preview or image transformation
Why This Skill Exists
The file compression and uncompression paths are exposed as async jobs via the TOS gateway's file_jobs API. This skill wraps those APIs into runnable Python scripts so agents can:
1. Submit a FileCompress job via the file_jobs API to archive TOS objects 2. Submit a FileUncompress job via the file_jobs API to extract an archive 3. Poll the job state until success or failure
Directory Layout
byted-tos-file-process/
├── SKILL.md
├── README.md
├── REFERENCE.md
├── WORKFLOWS.md
├── LICENSE
├── requirements.txt
└── scripts/
├── file_compress.py
├── file_uncompress.py
└── tos_jobs_client.pyRequirements
- Python 3.7+
- Access to Volcengine TOS
- Valid TOS AK/SK or STS credentials
- Network access to the target TOS endpoint
Install dependencies:
pip install -r requirements.txtEnvironment Variables
| Variable | Required | Description | Example |
|---|---|---|---|
TOS_ACCESS_KEY | Yes | TOS access key ID. | AK... |
TOS_SECRET_KEY | Yes | TOS secret access key. | your-secret-key |
TOS_ENDPOINT | Yes | TOS endpoint URL. | https://tos-cn-beijing.volces.com |
TOS_REGION | Yes | TOS region. | cn-beijing |
TOS_BUCKET | Yes | Source bucket that stores the file objects. | my-file-bucket |
TOS_OBJECT_KEY | No | Source object key. Can be overridden with --key or --keys. | files/archive.zip |
TOS_SECURITY_TOKEN | No | STS session token when using temporary credentials. | STS... |
Quick Start
Export the minimum required configuration:
export TOS_ACCESS_KEY="YOUR_AK"
export TOS_SECRET_KEY="YOUR_SK"
export TOS_ENDPOINT="https://tos-cn-beijing.volces.com"
export TOS_REGION="cn-beijing"
export TOS_BUCKET="your-file-bucket"Compress multiple objects into a zip archive:
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zip \
--saveas-object output/archive.zip \
--waitUncompress an archive:
python3 scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/unzipped/ \
--waitUsage Notes
file_compress.pyaccepts--keysas a comma-separated list of source object keys.file_uncompress.pyuses--prefixand optional--prefix-replaced; extraction is prefix-based, so it does not expose--saveas-object.- Async job scripts now support
--job-idto query an existing job,--validate/--dry-runto inspect the resolved payload before submission, and--jsonfor machine-readable output. - The output object key suffix must match the chosen format:
.zipfor zip,.tarfor tar,.zstfor zst. - Both scripts use the TOS gateway's
file_jobsAPI, authenticated viapre_signed_urlfrom the TOS Python SDK. No extra environment variables beyond the standard TOS credentials are needed. - Successful submission returns a
JobId;--waitthen polls the jobStateuntilSuccessorFailed.
Related Files
- Trigger-oriented usage: SKILL.md
- Parameter reference: REFERENCE.md
- Workflow guide: WORKFLOWS.md
License
This skill is licensed under the Apache License 2.0. See LICENSE.
Bytedance TOS File Process Reference
This document explains the async file compression and uncompression paths implemented by this skill.
Authentication
Authentication is handled by the TOS Python SDK. The tos_jobs_client.py shared client signs requests with the TOS identity declared in SKILL.md metadata. No additional DP-specific configuration is needed.
Core Operations
FileCompress
The script scripts/file_compress.py compresses TOS objects by:
1. Building a FileCompressConfig payload 2. Posting a JSON payload to the TOS gateway's file_jobs API with query file_jobs=&job_type=FileCompress 3. Polling the job state via the file_jobs API with job_type=FileCompress&job_id=<job_id> 4. The output is an archive file saved to TOS
FileUncompress
The script scripts/file_uncompress.py extracts an archive in TOS by:
1. Building a FileUncompressConfig payload 2. Posting a JSON payload to the TOS gateway's file_jobs API with query file_jobs=&job_type=FileUncompress 3. Polling the job state via the file_jobs API with job_type=FileUncompress&job_id=<job_id> 4. The extracted files are saved to TOS
Job Payloads
FileCompress
The submission body follows the TOS gateway's file_jobs API contract:
{
"Input": {
"Prefix": "",
"KeyConfig": [
{"Key": "file1.jpg"},
{"Key": "file2.txt"}
]
},
"FileCompressConfig": {
"Format": "zip",
"Flatten": 0
},
"Output": {
"Region": "cn-beijing",
"Bucket": "source-bucket",
"Object": "output/archive.zip"
}
}FileUncompress
{
"Input": {
"Object": "archive.zip"
},
"FileUncompressConfig": {
"Prefix": "output/dir/",
"PrefixReplaced": 0
},
"Output": {
"Region": "cn-beijing",
"Bucket": "source-bucket"
}
}CLI Mapping
file_compress.py
| CLI argument | Meaning | Notes |
|---|---|---|
--keys | Comma-separated source object keys | Required |
--bucket | Source TOS bucket | Defaults to TOS_BUCKET env |
--prefix | Input prefix filter | Optional, default empty |
--format | Archive format | zip, tar, or zst; default zip |
--flatten | Flatten directory structure | 0=keep structure, 1=flatten; default 0 |
--output-bucket | Output bucket | Defaults to source bucket |
--output-key | Output archive object key | Default archive.<ext> |
--wait | Poll until completion | Optional |
--timeout | Max wait time in seconds | Default 300 |
--poll-interval | Poll interval in seconds | Default 5 |
file_uncompress.py
| CLI argument | Meaning | Notes |
|---|---|---|
--key | Source archive object key | Required |
--bucket | Source TOS bucket | Defaults to TOS_BUCKET env |
--output-bucket | Output bucket | Defaults to source bucket |
--prefix | Target prefix for extracted files | Optional, default empty |
--prefix-replaced | Replace original directory with prefix | 0=keep original, 1=replace; default 0 |
--wait | Poll until completion | Optional |
--timeout | Max wait time in seconds | Default 300 |
--poll-interval | Poll interval in seconds | Default 5 |
Workflow States
The polling client currently treats these states as:
| State | Meaning |
|---|---|
Submitted | Job accepted by workflow service |
Running | Backend is processing |
Success | Output should be ready |
Failed | Job finished with error |
Notes
- The scripts print the raw create-job response when
--waitis not used. - When
--waitis used, the final printed object is the first job item returned byget_job. - Authentication uses the TOS identity declared in
SKILL.mdmetadata. No DP-specific configuration is needed. - For
FileCompress, the output object key suffix must match the chosen format (.zip,.tar,.zst).
tos
# 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.
#!/usr/bin/env python3
import argparse
import json
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from tos_jobs_client import create_client_from_env
JOB_TYPE = "FileCompress"
JOB_CATEGORY = "file_jobs"
FORMAT_EXTENSIONS = {
"zip": ".zip",
"tar": ".tar",
"zst": ".zst",
}
def build_file_compress_detail(
keys: list,
output_bucket: str,
output_object: str,
region: str,
prefix: str = "",
format: str = "zip",
flatten: int = 0,
) -> dict:
key_config = [{"Key": k} for k in keys]
return {
"Input": {
"Prefix": prefix,
"KeyConfig": key_config,
},
"FileCompressConfig": {
"Format": format,
"Flatten": flatten,
},
"Output": {
"Region": region,
"Bucket": output_bucket,
"Object": output_object,
},
}
def fail(message: str) -> None:
print(f"[ERROR] {message}", file=sys.stderr)
sys.exit(1)
def emit(payload: dict, json_only: bool, heading=None) -> None:
if json_only:
print(json.dumps(payload, ensure_ascii=False))
return
if heading:
print(heading)
print(json.dumps(payload, indent=2, ensure_ascii=False))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Compress TOS objects into an archive via TOS file_jobs API"
)
parser.add_argument(
"--keys", help="Comma-separated source object keys to compress"
)
parser.add_argument("--bucket", help="TOS bucket name (default: TOS_BUCKET env)")
parser.add_argument("--output-key", dest="output_key", help="Deprecated alias of --saveas-object")
parser.add_argument("--output-bucket", dest="output_bucket", help="Deprecated alias of --saveas-bucket")
parser.add_argument("--saveas-object", help="Output archive object key (default: archive.<ext>)")
parser.add_argument("--saveas-bucket", help="Output bucket (default: same as source)")
parser.add_argument(
"--prefix", default="", help="Input prefix filter (default: empty)"
)
parser.add_argument(
"--format",
default="zip",
choices=["zip", "tar", "zst"],
help="Archive format (default: zip)",
)
parser.add_argument(
"--flatten",
type=int,
default=0,
choices=[0, 1],
help="0=keep directory structure, 1=flatten (default: 0)",
)
parser.add_argument(
"--timeout",
type=int,
default=300,
help="Max wait time in seconds (default: 300)",
)
parser.add_argument(
"--poll-interval",
type=int,
default=5,
help="Poll interval in seconds (default: 5)",
)
parser.add_argument("--wait", action="store_true", help="Wait for job completion")
parser.add_argument("--job-id", help="Query an existing job instead of creating a new one")
parser.add_argument("--validate", action="store_true", help="Validate arguments and payload only")
parser.add_argument("--dry-run", action="store_true", help="Print resolved payload and exit")
parser.add_argument("--json", action="store_true", help="Print machine-readable JSON only")
return parser.parse_args()
def main():
args = parse_args()
bucket = args.bucket or os.environ.get("TOS_BUCKET", "")
if not bucket:
fail("--bucket or TOS_BUCKET env is required")
region = os.environ.get("TOS_REGION", "")
if not region:
fail("TOS_REGION env is required")
client = create_client_from_env()
client.bucket = bucket
client.region = region
if args.job_id:
result = client.get_job(JOB_TYPE, args.job_id, job_category=JOB_CATEGORY)
emit(
{
"ok": True,
"operation": "file_compress_query",
"bucket": bucket,
"job_id": args.job_id,
"job_type": JOB_TYPE,
"job_category": JOB_CATEGORY,
"result": result,
},
args.json,
"[OK] Job query result:",
)
return
if not args.keys:
fail("--keys must contain at least one object key")
keys = [k.strip() for k in args.keys.split(",") if k.strip()]
if not keys:
fail("--keys must contain at least one object key")
output_bucket = args.saveas_bucket or args.output_bucket or bucket
ext = FORMAT_EXTENSIONS.get(args.format, ".zip")
output_key = args.saveas_object or args.output_key or ("archive" + ext)
if not output_key.endswith(ext):
fail(f"Output key must end with '{ext}' for format '{args.format}'")
detail = build_file_compress_detail(
keys=keys,
output_bucket=output_bucket,
output_object=output_key,
region=region,
prefix=args.prefix,
format=args.format,
flatten=args.flatten,
)
plan = {
"ok": True,
"operation": "file_compress",
"bucket": bucket,
"keys": keys,
"saveas_bucket": output_bucket,
"saveas_object": output_key,
"job_type": JOB_TYPE,
"job_category": JOB_CATEGORY,
"detail": detail,
}
if args.validate or args.dry_run:
emit(plan, args.json, "[OK] Resolved request:")
return
if not args.json:
print(f"[INFO] Creating FileCompress job: {keys} -> {output_bucket}/{output_key}")
resp = client.create_job(JOB_CATEGORY, JOB_TYPE, detail)
job_id = resp.get("JobId", "")
if not job_id:
fail(f"No JobId in response: {resp}")
result_payload = {
**plan,
"job_id": job_id,
"create_response": resp,
}
if args.wait:
if not args.json:
print(f"[INFO] Waiting for job completion (timeout={args.timeout}s)...")
result = client.wait_for_job(
JOB_TYPE,
job_id,
timeout=args.timeout,
interval=args.poll_interval,
job_category=JOB_CATEGORY,
)
result_payload["final_result"] = result
result_payload["state"] = result.get("State", "Unknown")
emit(result_payload, args.json, "[OK] File compression result:")
if result_payload["state"] != "Success":
sys.exit(1)
return
emit(result_payload, args.json, "[OK] Job created:")
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.
#!/usr/bin/env python3
import argparse
import json
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from tos_jobs_client import create_client_from_env
JOB_TYPE = "FileUncompress"
JOB_CATEGORY = "file_jobs"
def build_file_uncompress_detail(
src_object: str,
output_bucket: str,
region: str,
prefix: str = "",
prefix_replaced: int = 0,
) -> dict:
detail = {
"Input": {
"Object": src_object,
},
"FileUncompressConfig": {
"Prefix": prefix,
"PrefixReplaced": prefix_replaced,
},
"Output": {
"Region": region,
"Bucket": output_bucket,
},
}
return detail
def fail(message: str) -> None:
print(f"[ERROR] {message}", file=sys.stderr)
sys.exit(1)
def emit(payload: dict, json_only: bool, heading=None) -> None:
if json_only:
print(json.dumps(payload, ensure_ascii=False))
return
if heading:
print(heading)
print(json.dumps(payload, indent=2, ensure_ascii=False))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Uncompress a TOS archive via TOS file_jobs API"
)
parser.add_argument("--key", help="Source archive object key in TOS")
parser.add_argument("--bucket", help="TOS bucket name (default: TOS_BUCKET env)")
parser.add_argument("--output-bucket", dest="output_bucket", help="Deprecated alias of --saveas-bucket")
parser.add_argument("--saveas-bucket", help="Output bucket (default: same as source)")
parser.add_argument(
"--prefix",
default="",
help="Target prefix for uncompressed files (default: empty)",
)
parser.add_argument(
"--prefix-replaced",
type=int,
default=0,
choices=[0, 1],
help="0=keep original directory, 1=replace with prefix (default: 0)",
)
parser.add_argument(
"--timeout",
type=int,
default=300,
help="Max wait time in seconds (default: 300)",
)
parser.add_argument(
"--poll-interval",
type=int,
default=5,
help="Poll interval in seconds (default: 5)",
)
parser.add_argument("--wait", action="store_true", help="Wait for job completion")
parser.add_argument("--job-id", help="Query an existing job instead of creating a new one")
parser.add_argument("--validate", action="store_true", help="Validate arguments and payload only")
parser.add_argument("--dry-run", action="store_true", help="Print resolved payload and exit")
parser.add_argument("--json", action="store_true", help="Print machine-readable JSON only")
return parser.parse_args()
def main():
args = parse_args()
bucket = args.bucket or os.environ.get("TOS_BUCKET", "")
if not bucket:
fail("--bucket or TOS_BUCKET env is required")
region = os.environ.get("TOS_REGION", "")
if not region:
fail("TOS_REGION env is required")
client = create_client_from_env()
client.bucket = bucket
client.region = region
if args.job_id:
result = client.get_job(JOB_TYPE, args.job_id, job_category=JOB_CATEGORY)
emit(
{
"ok": True,
"operation": "file_uncompress_query",
"bucket": bucket,
"job_id": args.job_id,
"job_type": JOB_TYPE,
"job_category": JOB_CATEGORY,
"result": result,
},
args.json,
"[OK] Job query result:",
)
return
key = args.key
if not key:
fail("--key is required")
output_bucket = args.saveas_bucket or args.output_bucket or bucket
detail = build_file_uncompress_detail(
src_object=key,
output_bucket=output_bucket,
region=region,
prefix=args.prefix,
prefix_replaced=args.prefix_replaced,
)
plan = {
"ok": True,
"operation": "file_uncompress",
"bucket": bucket,
"key": key,
"saveas_bucket": output_bucket,
"prefix": args.prefix,
"prefix_replaced": args.prefix_replaced,
"job_type": JOB_TYPE,
"job_category": JOB_CATEGORY,
"detail": detail,
}
if args.validate or args.dry_run:
emit(plan, args.json, "[OK] Resolved request:")
return
if not args.json:
print(f"[INFO] Creating FileUncompress job: {key} -> {output_bucket}/{args.prefix}")
resp = client.create_job(JOB_CATEGORY, JOB_TYPE, detail)
job_id = resp.get("JobId", "")
if not job_id:
fail(f"No JobId in response: {resp}")
result_payload = {
**plan,
"job_id": job_id,
"create_response": resp,
}
if args.wait:
if not args.json:
print(f"[INFO] Waiting for job completion (timeout={args.timeout}s)...")
result = client.wait_for_job(
JOB_TYPE,
job_id,
timeout=args.timeout,
interval=args.poll_interval,
job_category=JOB_CATEGORY,
)
result_payload["final_result"] = result
result_payload["state"] = result.get("State", "Unknown")
emit(result_payload, args.json, "[OK] File uncompression result:")
if result_payload["state"] != "Success":
sys.exit(1)
return
emit(result_payload, args.json, "[OK] Job created:")
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.
import json
import os
import time
import urllib.request
import urllib.error
from typing import Optional
import tos
class TOSJobsClient:
def __init__(self, ak: str, sk: str, endpoint: str, region: str, bucket: str):
self.bucket = bucket
self.region = region
self.client = tos.TosClientV2(ak, sk, endpoint, region)
def _signed_request(
self, method: str, query: dict, body: Optional[bytes] = None
) -> dict:
url_out = self.client.pre_signed_url(
tos.HttpMethodType.Http_Method_Post
if method == "POST"
else tos.HttpMethodType.Http_Method_Get,
self.bucket,
"",
expires=900,
query=query,
)
req = urllib.request.Request(
url_out.signed_url,
data=body,
method=method,
)
for k, v in url_out.signed_header.items():
req.add_header(k, v)
if body is not None:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as resp:
data = resp.read()
return json.loads(data)
except urllib.error.HTTPError as e:
body_text = e.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {e.code}: {body_text}") from e
def create_job(self, job_category: str, job_type: str, job_detail: dict) -> dict:
query = {job_category: "", "job_type": job_type}
body = json.dumps(job_detail).encode("utf-8")
return self._signed_request("POST", query, body)
def get_job(
self, job_type: str, job_id: str, job_category: str = "file_jobs"
) -> dict:
query = {job_category: "", "job_type": job_type, "job_id": job_id}
return self._signed_request("GET", query)
def wait_for_job(
self,
job_type: str,
job_id: str,
timeout: int = 300,
interval: int = 5,
job_category: str = "file_jobs",
) -> dict:
deadline = time.time() + timeout
while time.time() < deadline:
result = self.get_job(job_type, job_id, job_category=job_category)
items = result.get("Items", [])
if items:
item = items[0]
else:
item = result
state = item.get("State", "")
if state in ("Success", "Failed"):
return item
time.sleep(interval)
raise TimeoutError(f"Job {job_id} did not complete within {timeout}s")
def get_env(name: str) -> str:
val = os.environ.get(name, "")
if not val:
raise ValueError(f"Environment variable {name} is required")
return val
def create_client_from_env() -> TOSJobsClient:
return TOSJobsClient(
ak=get_env("TOS_ACCESS_KEY"),
sk=get_env("TOS_SECRET_KEY"),
endpoint=get_env("TOS_ENDPOINT"),
region=get_env("TOS_REGION"),
bucket=get_env("TOS_BUCKET"),
)
Bytedance TOS File Process Workflows
This document shows common end-to-end workflows for the async file compression and uncompression scripts.
Workflow 1: Compress Multiple Files into a Zip Archive
Goal: Archive multiple TOS objects into a single zip file.
Script: scripts/file_compress.py
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt,file3.pdf \
--format zip \
--saveas-object output/archive.zip \
--waitExpected Result:
- Prints job creation payload
- Polls until
Success - Writes the archive to
output/archive.zip
Workflow 2: Compress Files with Flattened Structure
Goal: Compress files without preserving their directory structure.
python3 scripts/file_compress.py \
--keys dir1/file1.jpg,dir2/file2.txt \
--format zip \
--flatten 1 \
--saveas-object output/flat_archive.zip \
--waitWorkflow 3: Create a Tar or Zst Archive
Goal: Use an alternative archive format.
# Tar archive
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format tar \
--saveas-object output/archive.tar \
--wait
# Zstd archive
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zst \
--saveas-object output/archive.zst \
--waitWorkflow 4: Uncompress an Archive with Original Directory Structure
Goal: Extract a zip archive while preserving the original directory layout.
python3 scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/extracted/ \
--prefix-replaced 0 \
--waitExpected Result:
- Prints
JobId - Polls until
Success - Extracts files to
output/extracted/with original directory structure preserved
Workflow 5: Uncompress and Replace Directory with Prefix
Goal: Extract an archive and replace the original directory structure with the specified prefix.
python3 scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/flat/ \
--prefix-replaced 1 \
--waitWorkflow 6: Submit Without Waiting
Goal: Hand off the job quickly and let another system query later.
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zip \
--saveas-object output/async_archive.zip \
--jsonExpected Result:
- Prints the create-job response
- Does not poll workflow state
- Suitable for agent orchestration that records
job_idand queries later with--job-id
Workflow 7: Compress Then Uncompress (Round Trip)
Goal: Archive files and then extract them to a different location.
# Step 1: Compress
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zip \
--output-key output/archive.zip \
--wait
# Step 2: Uncompress to a new prefix
python3 scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/restored/ \
--waitWorkflow 8: Validate or Query a Job
Goal: Let an agent inspect the resolved request before submission or resume from an existing job id.
# Preview the resolved payload without submitting
python3 scripts/file_compress.py \
--keys file1.jpg,file2.txt \
--format zip \
--saveas-object output/archive.zip \
--validate
# Query an existing compression job
python3 scripts/file_compress.py --job-id <job_id> --json
# Query an existing uncompression job
python3 scripts/file_uncompress.py --job-id <job_id> --jsonBehavior Notes:
--validateand--dry-runreturn the resolved payload without creating a job.--job-idswitches the script into query mode.--jsonis recommended when the next step is agent orchestration.
Troubleshooting
- If the script exits with missing environment-variable errors, verify that the TOS runtime configuration declared by the skill has been provided correctly.
- If submission succeeds but polling fails, confirm the TOS credentials have permission to access the
file_jobsAPI. - If the job fails after submission, check the
CodeandMessagefields in the job result for details. - If the output key suffix does not match the format, the script will exit with an error before submission.
---
Workflow 9: Compress Then Uncompress (Round Trip)
Goal: Archive multiple TOS objects into a zip, then extract them to a new directory — verifying the full async job lifecycle (submit → poll → result).
Pipeline: file_compress → file_uncompress
Step 1: Compress files into an archive
python3 scripts/file_compress.py \
--keys file1.jpg,file2.mp3 \
--format zip \
--saveas-bucket my-bucket \
--saveas-object output/archive.zip \
--wait --jsonOn success, the archive is written to output/archive.zip.
Step 2: Uncompress to a new directory
python3 scripts/file_uncompress.py \
--key output/archive.zip \
--prefix output/extracted/ \
--prefix-replaced 0 \
--wait --json--prefix-replaced 0preserves the original directory structure inside the archive.--prefix-replaced 1replaces the original directory structure with the specified prefix.
The extracted files appear under output/extracted/.
Agent orchestration notes
- Both steps are async jobs; use
--waitfor blocking or--jsonto capturejob_idand query later with--job-id. - Step 2 depends on Step 1 — the archive must exist in TOS before uncompressing.
- This workflow is the simplest end-to-end demo of the async job pattern and can serve as a smoke test for the
file_jobsAPI.