From 78deea2b15469d45d64be11fabd9dccb2742ef10 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 5 Aug 2026 14:52:44 +0200 Subject: [PATCH] feat(agents): zero-dependency CLI and agent skill over the same API pip install openshorts / uvx openshorts: process, status --watch, clips, quota and publish, all against the REST surface the dashboard and MCP already use, so nothing can drift. Auth and target via env vars; the self-hosted case is the same binary pointed at localhost with no key. skills/openshorts/SKILL.md teaches skill-capable agents the async loop (quota, submit, signed webhook, publish) including the self-host 401/404 convention and the rights acknowledgement. The skills/ ignore narrows to third-party installs so the published skill is versioned. README wires up CLI, skill and the n8n example under the automation section. --- .gitignore | 4 +- README.md | 30 +++++ cli/README.md | 32 +++++ cli/openshorts_cli.py | 234 +++++++++++++++++++++++++++++++++++++ cli/pyproject.toml | 30 +++++ skills/openshorts/SKILL.md | 62 ++++++++++ 6 files changed, 391 insertions(+), 1 deletion(-) create mode 100644 cli/README.md create mode 100644 cli/openshorts_cli.py create mode 100644 cli/pyproject.toml create mode 100644 skills/openshorts/SKILL.md diff --git a/.gitignore b/.gitignore index 7a52e00..e66e2b4 100644 --- a/.gitignore +++ b/.gitignore @@ -37,7 +37,9 @@ output/ .agents/ .agent/ .claude/ -skills/ +# skills/ holds third-party installs (symlinks); our own published skill is versioned +skills/* +!skills/openshorts/ skills-lock.json diff --git a/README.md b/README.md index 8c91523..101a62e 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,36 @@ Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and With a secret, the body is signed: `X-OpenShorts-Signature: sha256=`. +### CLI + +The same API from the terminal, zero dependencies (`cli/`): + +```bash +pip install openshorts # or: uvx openshorts + +export OPENSHORTS_API_KEY=osk_... # hosted +# export OPENSHORTS_API_URL=http://localhost:8000 # self-hosted, no key + +openshorts process "https://youtube.com/watch?v=..." --wait +openshorts clips +openshorts publish 0 --platforms tiktok,youtube +``` + +### Agent skill + +`skills/openshorts/SKILL.md` teaches any skill-capable agent (Claude Code and +friends) the whole flow: quota check, submit, signed webhook, publish. Install +it by copying the folder into your agent's skills directory: + +```bash +cp -r skills/openshorts ~/.claude/skills/ +``` + +### n8n + +An importable workflow (video URL in, published-ready clips out, no polling) +lives in [`examples/n8n/`](examples/n8n/). + --- ## Tech Stack diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 0000000..ac0b4db --- /dev/null +++ b/cli/README.md @@ -0,0 +1,32 @@ +# OpenShorts CLI + +Clip long videos into vertical 9:16 shorts from the terminal. Zero +dependencies; talks to the same API the dashboard, the MCP server and the +webhooks use. + +```bash +pip install openshorts # or: uvx openshorts / pipx run openshorts + +export OPENSHORTS_API_KEY=osk_... # from your account page at openshorts.app + +openshorts process "https://youtube.com/watch?v=..." --wait +openshorts clips +openshorts publish 0 --platforms tiktok,youtube +openshorts quota +``` + +Self-hosted instance? Point it at your own machine and skip the key: + +```bash +export OPENSHORTS_API_URL=http://localhost:8000 +openshorts process "https://youtube.com/watch?v=..." --wait +``` + +For pipelines, prefer the webhook to `--wait`: pass `--webhook` and +`--webhook-secret` and OpenShorts POSTs once (HMAC-signed, +`X-OpenShorts-Signature: sha256=`) when the job ends, with clip titles +and durable download links. + +The hosted free tier is 20 minutes/month with a watermark; paid plans from +$12/month. The self-hosted edition is MIT and has no meter. Agent-native +version of the same surface: [openshorts.app/mcp](https://www.openshorts.app/mcp). diff --git a/cli/openshorts_cli.py b/cli/openshorts_cli.py new file mode 100644 index 0000000..0e70fcb --- /dev/null +++ b/cli/openshorts_cli.py @@ -0,0 +1,234 @@ +"""OpenShorts CLI: clip long videos into vertical shorts from the terminal. + +Zero dependencies by design so `uvx openshorts` and `pipx run openshorts` +start instantly. Talks to the same REST API the dashboard and the MCP server +use; nothing here can drift from what the app actually does. + +Auth and target come from the environment: + OPENSHORTS_API_KEY osk_... key from the account page (cloud only) + OPENSHORTS_API_URL defaults to https://api.openshorts.app; set to + http://localhost:8000 for a self-hosted instance, + where no key is needed. +""" + +import argparse +import json +import os +import sys +import time +import urllib.error +import urllib.request + +DEFAULT_API = "https://api.openshorts.app" +POLL_SECONDS = 10 + + +def _base(): + return os.environ.get("OPENSHORTS_API_URL", DEFAULT_API).rstrip("/") + + +def _request(method, path, body=None): + headers = {"Accept": "application/json"} + key = os.environ.get("OPENSHORTS_API_KEY") + if key: + headers["Authorization"] = f"Bearer {key}" + data = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(_base() + path, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=120) as resp: + return resp.status, json.loads(resp.read().decode() or "{}") + except urllib.error.HTTPError as e: + try: + payload = json.loads(e.read().decode() or "{}") + except Exception: + payload = {"detail": str(e.reason)} + return e.code, payload + except urllib.error.URLError as e: + print(f"error: cannot reach {_base()} ({e.reason})", file=sys.stderr) + sys.exit(2) + + +def _die(status, payload): + detail = payload.get("detail", payload) if isinstance(payload, dict) else payload + if not isinstance(detail, str): + detail = json.dumps(detail) + print(f"error ({status}): {detail}", file=sys.stderr) + sys.exit(1) + + +def _absolutize(url): + if url and url.startswith("/"): + return _base() + url + return url + + +def _print_clips(result): + clips = (result or {}).get("clips") or [] + if not clips: + print("no clips in result") + return + for i, clip in enumerate(clips): + title = clip.get("title") or clip.get("video_title_for_youtube_short") or f"clip {i}" + print(f"[{i}] {title}") + print(f" {_absolutize(clip.get('video_url') or '')}") + + +def cmd_process(args): + body = {"url": args.url, "acknowledged": True} + if args.layouts: + body["layouts"] = args.layouts + if args.format: + body["output_format"] = args.format + if args.webhook: + body["webhook_url"] = args.webhook + if args.webhook_secret: + body["webhook_secret"] = args.webhook_secret + status, payload = _request("POST", "/api/process", body) + if status >= 400: + _die(status, payload) + job_id = payload.get("job_id") + if args.json and not args.wait: + print(json.dumps(payload)) + return + print(f"job queued: {job_id}") + if args.wait: + _watch(job_id, as_json=args.json) + else: + print(f"follow it with: openshorts status {job_id} --watch") + + +def _watch(job_id, as_json=False): + seen_logs = 0 + while True: + status, payload = _request("GET", f"/api/status/{job_id}") + if status >= 400: + _die(status, payload) + logs = payload.get("logs") or [] + for line in logs[seen_logs:]: + print(f" {line}") + seen_logs = len(logs) + state = payload.get("status") + if state == "completed": + if as_json: + print(json.dumps(payload.get("result") or {})) + else: + print("completed:") + _print_clips(payload.get("result")) + return + if state == "failed": + print("job failed; last log lines above", file=sys.stderr) + sys.exit(1) + time.sleep(POLL_SECONDS) + + +def cmd_status(args): + if args.watch: + _watch(args.job_id, as_json=args.json) + return + status, payload = _request("GET", f"/api/status/{args.job_id}") + if status >= 400: + _die(status, payload) + if args.json: + print(json.dumps(payload)) + return + print(f"status: {payload.get('status')}") + logs = payload.get("logs") or [] + if logs: + print(f"last log: {logs[-1]}") + + +def cmd_clips(args): + status, payload = _request("GET", f"/api/status/{args.job_id}") + if status >= 400: + _die(status, payload) + if payload.get("status") != "completed": + print(f"job is {payload.get('status')}, no clips yet", file=sys.stderr) + sys.exit(1) + if args.json: + print(json.dumps((payload.get("result") or {}).get("clips") or [])) + return + _print_clips(payload.get("result")) + + +def cmd_quota(args): + status, payload = _request("GET", "/api/me") + # 401 anonymous, 404 self-host (the cloud router is not mounted): neither + # is an error, there is simply no minute quota to report. + if status in (401, 404): + print("no cloud account in play: self-hosted or anonymous, no minute quota") + return + if status >= 400: + _die(status, payload) + if args.json: + print(json.dumps(payload)) + return + print(f"plan: {payload.get('plan')}") + print(f"minutes: {payload.get('minutes')}") + print(f"entitled: {payload.get('entitled')}") + + +def cmd_publish(args): + body = { + "job_id": args.job_id, + "clip_index": args.clip_index, + "platforms": [p.strip() for p in args.platforms.split(",") if p.strip()], + } + if args.title: + body["title"] = args.title + if args.schedule: + body["scheduled_date"] = args.schedule + if args.timezone: + body["timezone"] = args.timezone + status, payload = _request("POST", "/api/social/post", body) + if status >= 400: + _die(status, payload) + print(json.dumps(payload) if args.json else f"publishing: {payload}") + + +def main(argv=None): + parser = argparse.ArgumentParser( + prog="openshorts", + description="Clip long videos into vertical shorts via the OpenShorts API.", + ) + parser.add_argument("--json", action="store_true", help="raw JSON output") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("process", help="submit a video URL for clipping") + p.add_argument("url", help="YouTube or direct video URL") + p.add_argument("--layouts", help="comma list: auto,split,screencast,speaker_cut,punch_in") + p.add_argument("--format", help="output format, e.g. 1080p") + p.add_argument("--webhook", help="webhook URL fired once when the job ends") + p.add_argument("--webhook-secret", help="HMAC secret for X-OpenShorts-Signature") + p.add_argument("--wait", action="store_true", help="stream logs until the job ends") + p.set_defaults(func=cmd_process) + + p = sub.add_parser("status", help="job status and last log line") + p.add_argument("job_id") + p.add_argument("--watch", action="store_true", help="stream logs until the job ends") + p.set_defaults(func=cmd_status) + + p = sub.add_parser("clips", help="list finished clips with links") + p.add_argument("job_id") + p.set_defaults(func=cmd_clips) + + p = sub.add_parser("quota", help="plan and remaining minutes") + p.set_defaults(func=cmd_quota) + + p = sub.add_parser("publish", help="post or schedule one clip to social platforms") + p.add_argument("job_id") + p.add_argument("clip_index", type=int) + p.add_argument("--platforms", required=True, help="comma list: tiktok,instagram,youtube") + p.add_argument("--title") + p.add_argument("--schedule", help="ISO datetime for scheduled posting") + p.add_argument("--timezone", help="IANA timezone for --schedule") + p.set_defaults(func=cmd_publish) + + args = parser.parse_args(argv) + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/cli/pyproject.toml b/cli/pyproject.toml new file mode 100644 index 0000000..1bb8867 --- /dev/null +++ b/cli/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "openshorts" +version = "0.1.0" +description = "CLI for OpenShorts: clip long videos into vertical shorts and publish them, from the terminal" +readme = "README.md" +requires-python = ">=3.9" +license = { text = "MIT" } +authors = [{ name = "OpenShorts" }] +keywords = ["video", "clips", "shorts", "ai", "tiktok", "youtube-shorts", "cli"] +classifiers = [ + "Environment :: Console", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Topic :: Multimedia :: Video", +] + +[project.urls] +Homepage = "https://www.openshorts.app" +Source = "https://github.com/mutonby/openshorts" +Documentation = "https://www.openshorts.app/mcp" + +[project.scripts] +openshorts = "openshorts_cli:main" + +[tool.setuptools] +py-modules = ["openshorts_cli"] diff --git a/skills/openshorts/SKILL.md b/skills/openshorts/SKILL.md new file mode 100644 index 0000000..943aa26 --- /dev/null +++ b/skills/openshorts/SKILL.md @@ -0,0 +1,62 @@ +--- +name: openshorts +description: Turn long videos (podcasts, webinars, streams) into vertical 9:16 clips with subtitles and publish them to TikTok, Instagram Reels and YouTube Shorts via the OpenShorts API or MCP server. Use when the user wants to clip a video into shorts, restyle captions on a clip, schedule or post clips to social platforms, or automate a clipping pipeline. +--- + +# OpenShorts: clip and publish video + +OpenShorts turns a long video into 3-15 vertical clips (15-60s each) with +word-level subtitles burned in, then optionally publishes them. One job takes +minutes, not seconds: always work async (submit, then webhook or poll). + +## Connect + +Two equivalent surfaces; prefer MCP when the client supports it: + +- **MCP** (streamable HTTP): `https://mcp.openshorts.app/mcp` with header + `Authorization: Bearer osk_...`. Six tools: `process_video`, + `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `publish_clip`. +- **REST**: same key against `https://api.openshorts.app` (OpenAPI at + `/openapi.json`, docs at `/docs`). + +Keys are created in the account page at openshorts.app and start with `osk_`. +**Self-hosted instances expose the same endpoints on `http://localhost:8000` +with no key.** If a call returns 401/404 on `/api/me`, assume self-host or +anonymous: there is no minute quota to enforce. + +## The core loop + +1. `get_quota` first when the job is large: `process_video` fails with + `quota_exceeded` if minutes run out; on the hosted service API calls draw + from the same minute balance as the dashboard (no separate meter). +2. Submit: `POST /api/process` with JSON + `{"url": "...", "acknowledged": true}`. Optional: `layouts` + (`"auto,split,screencast"`), `output_format` (`"1080p"`), `webhook_url` + + `webhook_secret`. Returns `{"job_id": ...}` immediately. +3. Finish: **webhooks beat polling.** With `webhook_url` set, OpenShorts POSTs + exactly once when the job ends (completed OR failed, so pipelines never + hang): `{"event": "job.completed", "job_id", "status", "clips": [{"index", + "title", "video_url", "download_url"}]}`. If a secret was set, verify + `X-OpenShorts-Signature: sha256=` = HMAC-SHA256 of the raw body. + Without a webhook, poll `GET /api/status/{job_id}` every ~10s; response is + `{"status", "logs", "result"}` and `result.clips` appears on completion. +4. Publish: `POST /api/social/post` with `{"job_id", "clip_index", + "platforms": ["tiktok", "instagram", "youtube"]}`, optional `title`, + `scheduled_date` (ISO) + `timezone`. Restyle captions first if asked: + `POST /api/subtitle` with `{"job_id", "clip_index", "style"}` (`classic` + or karaoke word highlighting). + +## Rules + +- Only submit videos the user has rights to; `process_video` requires the + `confirm_rights` acknowledgement and that is deliberate. +- `download_url` links are presigned for 24h: fetch or forward them promptly. +- Never describe OpenShorts as simply "free": the self-hosted edition is free + and MIT-licensed; the hosted service has 20 free minutes/month (watermarked) + and paid plans from $12/month without watermark. + +## CLI shortcut + +When shell access is easier than HTTP: `uvx openshorts process --wait`, +`openshorts clips `, `openshorts publish 0 --platforms +tiktok`. Auth via `OPENSHORTS_API_KEY` / `OPENSHORTS_API_URL` env vars.