Hermes Bot commited on
Commit
b1b7ff5
·
unverified ·
2 Parent(s): 9f5136362071c9

Merge branch 'develop'

Browse files

# Conflicts:
# projects/tinybard/app.py

.agents/skills/hf-cli/.hf-skill-manifest.json ADDED
File without changes
.agents/skills/hf-cli/SKILL.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: hf-cli
3
+ description: "Hugging Face Hub CLI (`hf`) for downloading, uploading, and managing models, datasets, spaces, buckets, repos, papers, jobs, and more on the Hugging Face Hub. Use when: handling authentication; managing local cache; managing Hugging Face Buckets; running or scheduling jobs on Hugging Face infrastructure; managing Hugging Face repos; discussions and pull requests; browsing models, datasets and spaces; reading, searching, or browsing academic papers; managing collections; querying datasets; configuring spaces; setting up webhooks; or deploying and managing HF Inference Endpoints. Make sure to use this skill whenever the user mentions 'hf', 'huggingface', 'Hugging Face', 'huggingface-cli', or 'hugging face cli', or wants to do anything related to the Hugging Face ecosystem and to AI and ML in general. Also use for cloud storage needs like training checkpoints, data pipelines, or agent traces. Use even if the user doesn't explicitly ask for a CLI command. Replaces the deprecated `huggingface-cli`."
4
+ ---
5
+
6
+ Install: `curl -LsSf https://hf.co/cli/install.sh | bash -s`.
7
+
8
+ The Hugging Face Hub CLI tool `hf` is available. IMPORTANT: The `hf` command replaces the deprecated `huggingface-cli` command.
9
+
10
+ Use `hf --help` to view available functions. Note that auth commands are now all under `hf auth` e.g. `hf auth whoami`.
11
+
12
+ Generated with `huggingface_hub v1.18.0`. Run `hf skills add --force` to regenerate.
13
+
14
+ ## Commands
15
+
16
+ - `hf cp SRC` — Copy files between local paths, repositories, and buckets. `[--format [auto|human|agent|json|quiet]]`
17
+ - `hf download REPO_ID` — Download files from the Hub. `[--type [model|dataset|space] --revision TEXT --include TEXT --exclude TEXT --cache-dir TEXT --local-dir TEXT --force-download --dry-run --max-workers INTEGER --format [auto|human|agent|json|quiet]]`
18
+ - `hf env` — Print information about the environment. `[--format [auto|human|agent|json|quiet]]`
19
+ - `hf sync` — Sync files between local directory and a bucket. `[--delete --ignore-times --ignore-sizes --plan TEXT --apply TEXT --dry-run --include TEXT --exclude TEXT --filter-from TEXT --existing --ignore-existing --verbose --format [auto|human|agent|json|quiet]]`
20
+ - `hf update` — Update the `hf` CLI to the latest version. `[--format [auto|human|agent|json|quiet]]`
21
+ - `hf upload REPO_ID` — Upload a file or a folder to the Hub. Recommended for single-commit uploads. `[--type [model|dataset|space] --revision TEXT --private --include TEXT --exclude TEXT --delete TEXT --commit-message TEXT --commit-description TEXT --create-pr --every FLOAT --format [auto|human|agent|json|quiet]]`
22
+ - `hf upload-large-folder REPO_ID LOCAL_PATH` — Upload a large folder to the Hub. Recommended for resumable uploads. `[--type [model|dataset|space] --revision TEXT --private --include TEXT --exclude TEXT --num-workers INTEGER --no-report --no-bars --format [auto|human|agent|json|quiet]]`
23
+ - `hf version` — Print information about the hf version. `[--format [auto|human|agent|json|quiet]]`
24
+
25
+ ### `hf auth` — Manage authentication (login, logout, etc.).
26
+
27
+ - `hf auth list` — List all stored access tokens. `[--format [auto|human|agent|json|quiet]]`
28
+ - `hf auth login` — Login using a token from huggingface.co/settings/tokens. `[--add-to-git-credential --force --format [auto|human|agent|json|quiet]]`
29
+ - `hf auth logout` — Logout from a specific token. `[--token-name TEXT --format [auto|human|agent|json|quiet]]`
30
+ - `hf auth switch` — Switch between access tokens. `[--token-name TEXT --add-to-git-credential --format [auto|human|agent|json|quiet]]`
31
+ - `hf auth token` — Print the current access token to stdout. `[--format [auto|human|agent|json|quiet]]`
32
+ - `hf auth whoami` — Find out which huggingface.co account you are logged in as. `[--format [auto|human|agent|json|quiet]]`
33
+
34
+ ### `hf buckets` — Commands to interact with buckets.
35
+
36
+ - `hf buckets cp SRC` — Copy files between local paths, repositories, and buckets. `[--format [auto|human|agent|json|quiet]]`
37
+ - `hf buckets create BUCKET_ID` — Create a new bucket. `[--private --region [us|eu] --exist-ok --format [auto|human|agent|json|quiet]]`
38
+ - `hf buckets delete BUCKET_ID` — Delete a bucket. `[--yes --missing-ok --format [auto|human|agent|json|quiet]]`
39
+ - `hf buckets info BUCKET_ID` — Get info about a bucket. `[--format [auto|human|agent|json|quiet]]`
40
+ - `hf buckets list` — List buckets or files in a bucket. `[--human-readable --tree --recursive --search TEXT --format [auto|human|agent|json|quiet]]`
41
+ - `hf buckets move FROM_ID TO_ID` — Move (rename) a bucket to a new name or namespace. `[--format [auto|human|agent|json|quiet]]`
42
+ - `hf buckets remove ARGUMENT` — Remove files from a bucket. `[--recursive --yes --dry-run --include TEXT --exclude TEXT --format [auto|human|agent|json|quiet]]`
43
+ - `hf buckets sync` — Sync files between local directory and a bucket. `[--delete --ignore-times --ignore-sizes --plan TEXT --apply TEXT --dry-run --include TEXT --exclude TEXT --filter-from TEXT --existing --ignore-existing --verbose --format [auto|human|agent|json|quiet]]`
44
+
45
+ ### `hf cache` — Manage local cache directory.
46
+
47
+ - `hf cache list` — List cached repositories or revisions. `[--cache-dir TEXT --revisions --filter TEXT --sort [accessed|accessed:asc|accessed:desc|modified|modified:asc|modified:desc|name|name:asc|name:desc|size|size:asc|size:desc] --limit INTEGER --format [auto|human|agent|json|quiet]]`
48
+ - `hf cache prune` — Remove detached revisions from the cache. `[--cache-dir TEXT --yes --dry-run --format [auto|human|agent|json|quiet]]`
49
+ - `hf cache rm TARGETS` — Remove cached repositories or revisions. `[--cache-dir TEXT --yes --dry-run --format [auto|human|agent|json|quiet]]`
50
+ - `hf cache verify REPO_ID` — Verify checksums for a single repo revision from cache or a local directory. `[--type [model|dataset|space] --revision TEXT --cache-dir TEXT --local-dir TEXT --fail-on-missing-files --fail-on-extra-files --format [auto|human|agent|json|quiet]]`
51
+
52
+ ### `hf collections` — Interact with collections on the Hub.
53
+
54
+ - `hf collections add-item COLLECTION_SLUG ITEM_ID ITEM_TYPE` — Add an item to a collection. `[--note TEXT --exists-ok --format [auto|human|agent|json|quiet]]`
55
+ - `hf collections create TITLE` — Create a new collection on the Hub. `[--namespace TEXT --description TEXT --private --exists-ok --format [auto|human|agent|json|quiet]]`
56
+ - `hf collections delete COLLECTION_SLUG` — Delete a collection from the Hub. `[--missing-ok --format [auto|human|agent|json|quiet]]`
57
+ - `hf collections delete-item COLLECTION_SLUG ITEM_OBJECT_ID` — Delete an item from a collection. `[--missing-ok --format [auto|human|agent|json|quiet]]`
58
+ - `hf collections info COLLECTION_SLUG` — Get info about a collection on the Hub. `[--format [auto|human|agent|json|quiet]]`
59
+ - `hf collections list` — List collections on the Hub. `[--owner TEXT --item TEXT --sort [lastModified|trending|upvotes] --limit INTEGER --format [auto|human|agent|json|quiet]]`
60
+ - `hf collections update COLLECTION_SLUG` — Update a collection's metadata on the Hub. `[--title TEXT --description TEXT --position INTEGER --private --theme TEXT --format [auto|human|agent|json|quiet]]`
61
+ - `hf collections update-item COLLECTION_SLUG ITEM_OBJECT_ID` — Update an item in a collection. `[--note TEXT --position INTEGER --format [auto|human|agent|json|quiet]]`
62
+
63
+ ### `hf datasets` — Interact with datasets on the Hub.
64
+
65
+ - `hf datasets card DATASET_ID` — Get the dataset card (README) for a dataset on the Hub. `[--metadata --text --format [auto|human|agent|json|quiet]]`
66
+ - `hf datasets info DATASET_ID` — Get info about a dataset on the Hub. `[--revision TEXT --expand TEXT --format [auto|human|agent|json|quiet]]`
67
+ - `hf datasets leaderboard DATASET_ID` — List model scores from a dataset leaderboard. This command helps find the best models for a task or compare models by benchmark scores. Use 'hf datasets ls --filter benchmark:official' to list available leaderboards. `[--limit INTEGER --format [auto|human|agent|json|quiet]]`
68
+ - `hf datasets list` — List datasets on the Hub, or files in a dataset repo. `[--search TEXT --author TEXT --filter TEXT --sort [created_at|downloads|last_modified|likes|trending_score] --limit INTEGER --expand TEXT --human-readable --tree --recursive --revision TEXT --format [auto|human|agent|json|quiet]]`
69
+ - `hf datasets parquet DATASET_ID` — List parquet file URLs available for a dataset. `[--subset TEXT --split TEXT --format [auto|human|agent|json|quiet]]`
70
+ - `hf datasets sql SQL` — Execute a raw SQL query with DuckDB against dataset parquet URLs. `[--format [auto|human|agent|json|quiet]]`
71
+
72
+ ### `hf discussions` — Manage discussions and pull requests on the Hub.
73
+
74
+ - `hf discussions close REPO_ID NUM` — Close a discussion or pull request. `[--comment TEXT --yes --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
75
+ - `hf discussions comment REPO_ID NUM` — Comment on a discussion or pull request. `[--body TEXT --body-file PATH --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
76
+ - `hf discussions create REPO_ID --title TEXT` — Create a new discussion or pull request on a repo. `[--body TEXT --body-file PATH --pull-request --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
77
+ - `hf discussions diff REPO_ID NUM` — Show the diff of a pull request. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
78
+ - `hf discussions info REPO_ID NUM` — Get info about a discussion or pull request. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
79
+ - `hf discussions list REPO_ID` — List discussions and pull requests on a repo. `[--status [open|closed|merged|draft|all] --kind [all|discussion|pull_request] --author TEXT --limit INTEGER --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
80
+ - `hf discussions merge REPO_ID NUM` — Merge a pull request. `[--comment TEXT --yes --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
81
+ - `hf discussions rename REPO_ID NUM NEW_TITLE` — Rename a discussion or pull request. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
82
+ - `hf discussions reopen REPO_ID NUM` — Reopen a closed discussion or pull request. `[--comment TEXT --yes --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
83
+
84
+ ### `hf endpoints` — Manage Hugging Face Inference Endpoints.
85
+
86
+ - `hf endpoints catalog deploy --repo TEXT` — Deploy an Inference Endpoint from the Model Catalog. `[--name TEXT --accelerator TEXT --namespace TEXT --format [auto|human|agent|json|quiet]]`
87
+ - `hf endpoints catalog list` — List available Catalog models. `[--format [auto|human|agent|json|quiet]]`
88
+ - `hf endpoints delete NAME` — Delete an Inference Endpoint permanently. `[--namespace TEXT --yes --format [auto|human|agent|json|quiet]]`
89
+ - `hf endpoints deploy NAME --repo TEXT --framework TEXT --accelerator TEXT --instance-size TEXT --instance-type TEXT --region TEXT --vendor TEXT` — Deploy an Inference Endpoint from a Hub repository. `[--namespace TEXT --task TEXT --min-replica INTEGER --max-replica INTEGER --scale-to-zero-timeout INTEGER --scaling-metric [pendingRequests|hardwareUsage] --scaling-threshold FLOAT --format [auto|human|agent|json|quiet]]`
90
+ - `hf endpoints describe NAME` — Get information about an existing endpoint. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
91
+ - `hf endpoints list` — Lists all Inference Endpoints for the given namespace. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
92
+ - `hf endpoints pause NAME` — Pause an Inference Endpoint. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
93
+ - `hf endpoints resume NAME` — Resume an Inference Endpoint. `[--namespace TEXT --fail-if-already-running --format [auto|human|agent|json|quiet]]`
94
+ - `hf endpoints scale-to-zero NAME` — Scale an Inference Endpoint to zero. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
95
+ - `hf endpoints update NAME` — Update an existing endpoint. `[--namespace TEXT --repo TEXT --accelerator TEXT --instance-size TEXT --instance-type TEXT --framework TEXT --revision TEXT --task TEXT --min-replica INTEGER --max-replica INTEGER --scale-to-zero-timeout INTEGER --scaling-metric [pendingRequests|hardwareUsage] --scaling-threshold FLOAT --format [auto|human|agent|json|quiet]]`
96
+
97
+ ### `hf extensions` — Manage hf CLI extensions.
98
+
99
+ - `hf extensions exec NAME` — Execute an installed extension.
100
+ - `hf extensions install REPO_ID` — Install an extension from a public GitHub repository. `[--force --format [auto|human|agent|json|quiet]]`
101
+ - `hf extensions list` — List installed extension commands. `[--format [auto|human|agent|json|quiet]]`
102
+ - `hf extensions remove NAME` — Remove an installed extension. `[--format [auto|human|agent|json|quiet]]`
103
+ - `hf extensions search` — Search extensions available on GitHub (tagged with 'hf-extension' topic). `[--format [auto|human|agent|json|quiet]]`
104
+
105
+ ### `hf jobs` — Run and manage Jobs on the Hub.
106
+
107
+ - `hf jobs cancel JOB_ID` — Cancel a Job `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
108
+ - `hf jobs hardware` — List available hardware options for Jobs `[--format [auto|human|agent|json|quiet]]`
109
+ - `hf jobs inspect JOB_IDS` — Display detailed information on one or more Jobs `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
110
+ - `hf jobs labels JOB_ID` — Update labels on a Job. Replaces all existing labels. `[--label TEXT --clear --namespace TEXT --format [auto|human|agent|json|quiet]]`
111
+ - `hf jobs logs JOB_ID` — Fetch the logs of a Job. `[--follow --tail INTEGER --namespace TEXT --format [auto|human|agent|json|quiet]]`
112
+ - `hf jobs ps` — List Jobs. `[--all --namespace TEXT --filter TEXT --format [auto|human|agent|json|quiet]]`
113
+ - `hf jobs run IMAGE COMMAND` — Run a Job. `[--env TEXT --secrets TEXT --label TEXT --volume TEXT --env-file TEXT --secrets-file TEXT --flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|rtx-pro-6000|rtx-pro-6000x2|rtx-pro-6000x4|rtx-pro-6000x8] --timeout TEXT --detach --namespace TEXT]`
114
+ - `hf jobs scheduled delete SCHEDULED_JOB_ID` — Delete a scheduled Job. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
115
+ - `hf jobs scheduled inspect SCHEDULED_JOB_IDS` — Display detailed information on one or more scheduled Jobs `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
116
+ - `hf jobs scheduled labels SCHEDULED_JOB_ID` — Update labels on a scheduled Job. Replaces all existing labels. `[--label TEXT --clear --namespace TEXT --format [auto|human|agent|json|quiet]]`
117
+ - `hf jobs scheduled ps` — List scheduled Jobs `[--all --namespace TEXT --filter TEXT --format [auto|human|agent|json|quiet]]`
118
+ - `hf jobs scheduled resume SCHEDULED_JOB_ID` — Resume (unpause) a scheduled Job. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
119
+ - `hf jobs scheduled run SCHEDULE IMAGE COMMAND` — Schedule a Job. `[--suspend --concurrency --env TEXT --secrets TEXT --label TEXT --volume TEXT --env-file TEXT --secrets-file TEXT --flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|rtx-pro-6000|rtx-pro-6000x2|rtx-pro-6000x4|rtx-pro-6000x8] --timeout TEXT --namespace TEXT]`
120
+ - `hf jobs scheduled suspend SCHEDULED_JOB_ID` — Suspend (pause) a scheduled Job. `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
121
+ - `hf jobs scheduled uv run SCHEDULE SCRIPT` — Run a UV script (local file or URL) on HF infrastructure `[--suspend --concurrency --image TEXT --flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|rtx-pro-6000|rtx-pro-6000x2|rtx-pro-6000x4|rtx-pro-6000x8] --env TEXT --secrets TEXT --label TEXT --volume TEXT --env-file TEXT --secrets-file TEXT --timeout TEXT --namespace TEXT --with TEXT --python TEXT]`
122
+ - `hf jobs stats` — Fetch the resource usage statistics and metrics of Jobs `[--namespace TEXT --format [auto|human|agent|json|quiet]]`
123
+ - `hf jobs uv run SCRIPT` — Run a UV script (local file or URL) on HF infrastructure `[--image TEXT --flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|rtx-pro-6000|rtx-pro-6000x2|rtx-pro-6000x4|rtx-pro-6000x8] --env TEXT --secrets TEXT --label TEXT --volume TEXT --env-file TEXT --secrets-file TEXT --timeout TEXT --detach --namespace TEXT --with TEXT --python TEXT]`
124
+
125
+ ### `hf models` — Interact with models on the Hub.
126
+
127
+ - `hf models card MODEL_ID` — Get the model card (README) for a model on the Hub. `[--metadata --text --format [auto|human|agent|json|quiet]]`
128
+ - `hf models info MODEL_ID` — Get info about a model on the Hub. `[--revision TEXT --expand TEXT --format [auto|human|agent|json|quiet]]`
129
+ - `hf models list` — List models on the Hub, or files in a model repo. `[--search TEXT --author TEXT --filter TEXT --num-parameters TEXT --sort [created_at|downloads|last_modified|likes|trending_score] --limit INTEGER --expand TEXT --human-readable --tree --recursive --revision TEXT --format [auto|human|agent|json|quiet]]`
130
+
131
+ ### `hf papers` — Interact with papers on the Hub.
132
+
133
+ - `hf papers info PAPER_ID` — Get info about a paper on the Hub. `[--format [auto|human|agent|json|quiet]]`
134
+ - `hf papers list` — List daily papers on the Hub. `[--date TEXT --week TEXT --month TEXT --submitter TEXT --sort [publishedAt|trending] --limit INTEGER --format [auto|human|agent|json|quiet]]`
135
+ - `hf papers read PAPER_ID` — Read a paper as markdown. `[--format [auto|human|agent|json|quiet]]`
136
+ - `hf papers search QUERY` — Search papers on the Hub. `[--limit INTEGER --format [auto|human|agent|json|quiet]]`
137
+
138
+ ### `hf repos` — Manage repos on the Hub.
139
+
140
+ - `hf repos branch create REPO_ID BRANCH` — Create a new branch for a repo on the Hub. `[--revision TEXT --type [model|dataset|space] --exist-ok --format [auto|human|agent|json|quiet]]`
141
+ - `hf repos branch delete REPO_ID BRANCH` — Delete a branch from a repo on the Hub. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
142
+ - `hf repos cp SRC` — Copy files between local paths, repositories, and buckets. `[--format [auto|human|agent|json|quiet]]`
143
+ - `hf repos create REPO_ID` — Create a new repo on the Hub. `[--type [model|dataset|space] --space-sdk TEXT --private --public --protected --exist-ok --resource-group-id TEXT --region [us|eu] --flavor [cpu-basic|cpu-upgrade|zero-a10g|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8] --storage [small|medium|large] --sleep-time INTEGER --secrets TEXT --secrets-file TEXT --env TEXT --env-file TEXT --volume TEXT --format [auto|human|agent|json|quiet]]`
144
+ - `hf repos delete REPO_ID` — Delete a repo from the Hub. This is an irreversible operation. `[--type [model|dataset|space] --missing-ok --yes --format [auto|human|agent|json|quiet]]`
145
+ - `hf repos delete-files REPO_ID PATTERNS` — Delete files from a repo on the Hub. `[--type [model|dataset|space] --revision TEXT --commit-message TEXT --commit-description TEXT --create-pr --format [auto|human|agent|json|quiet]]`
146
+ - `hf repos duplicate FROM_ID` — Duplicate a repo on the Hub (model, dataset, or Space). `[--type [model|dataset|space] --private --public --protected --exist-ok --flavor [cpu-basic|cpu-upgrade|zero-a10g|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8] --storage [small|medium|large] --sleep-time INTEGER --secrets TEXT --secrets-file TEXT --env TEXT --env-file TEXT --volume TEXT --format [auto|human|agent|json|quiet]]`
147
+ - `hf repos list` — List all repos (models, datasets, spaces, buckets) with storage info. `[--namespace TEXT --type [model|dataset|space|bucket] --search TEXT --limit INTEGER --explore --format [auto|human|agent|json|quiet]]`
148
+ - `hf repos move FROM_ID TO_ID` — Move a repository from a namespace to another namespace. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
149
+ - `hf repos settings REPO_ID` — Update the settings of a repository. `[--gated [auto|manual|false] --private --public --protected --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
150
+ - `hf repos tag create REPO_ID TAG` — Create a tag for a repo. `[--message TEXT --revision TEXT --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
151
+ - `hf repos tag delete REPO_ID TAG` — Delete a tag for a repo. `[--yes --type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
152
+ - `hf repos tag list REPO_ID` — List tags for a repo. `[--type [model|dataset|space] --format [auto|human|agent|json|quiet]]`
153
+
154
+ ### `hf skills` — Manage skills for AI assistants.
155
+
156
+ - `hf skills add` — Download a Hugging Face skill and install it for an AI assistant. `[--claude --global --dest PATH --force --format [auto|human|agent|json|quiet]]`
157
+ - `hf skills list` — List available skills from the Hugging Face marketplace. `[--format [auto|human|agent|json|quiet]]`
158
+ - `hf skills preview` — Print the generated `hf-cli` SKILL.md to stdout. `[--format [auto|human|agent|json|quiet]]`
159
+ - `hf skills update` — Update installed Hugging Face marketplace skills. `[--claude --global --dest PATH --format [auto|human|agent|json|quiet]]`
160
+
161
+ ### `hf spaces` — Interact with spaces on the Hub.
162
+
163
+ - `hf spaces card SPACE_ID` — Get the Space card (README) for a Space on the Hub. `[--metadata --text --format [auto|human|agent|json|quiet]]`
164
+ - `hf spaces dev-mode SPACE_ID` — Enable or disable dev mode on a Space. `[--stop --format [auto|human|agent|json|quiet]]`
165
+ - `hf spaces hardware` — List available hardware options for Spaces. `[--format [auto|human|agent|json|quiet]]`
166
+ - `hf spaces hot-reload SPACE_ID` — Hot-reload any Python file of a Space without a full rebuild + restart. `[--local-file PATH --skip-checks --skip-summary --format [auto|human|agent|json|quiet]]`
167
+ - `hf spaces info SPACE_ID` — Get info about a space on the Hub. `[--revision TEXT --expand TEXT --format [auto|human|agent|json|quiet]]`
168
+ - `hf spaces list` — List spaces on the Hub, or files in a space repo. `[--search TEXT --author TEXT --filter TEXT --sort [created_at|last_modified|likes|trending_score] --limit INTEGER --expand TEXT --human-readable --tree --recursive --revision TEXT --format [auto|human|agent|json|quiet]]`
169
+ - `hf spaces logs SPACE_ID` — Fetch the run or build logs of a Space. `[--build --follow --tail INTEGER --format [auto|human|agent|json|quiet]]`
170
+ - `hf spaces pause SPACE_ID` — Pause a Space. `[--format [auto|human|agent|json|quiet]]`
171
+ - `hf spaces restart SPACE_ID` — Restart a Space. `[--factory-reboot --format [auto|human|agent|json|quiet]]`
172
+ - `hf spaces search QUERY` — Search spaces on the Hub using semantic search. `[--filter TEXT --sdk TEXT --include-non-running --description --limit INTEGER --format [auto|human|agent|json|quiet]]`
173
+ - `hf spaces secrets add SPACE_ID` — Add or update secrets for a Space. `[--secrets TEXT --secrets-file TEXT --format [auto|human|agent|json|quiet]]`
174
+ - `hf spaces secrets delete SPACE_ID KEY` — Remove a secret from a Space. `[--yes --format [auto|human|agent|json|quiet]]`
175
+ - `hf spaces secrets list SPACE_ID` — List secrets for a Space. Secret values are write-only and not returned. `[--format [auto|human|agent|json|quiet]]`
176
+ - `hf spaces settings SPACE_ID` — Update the settings of a Space. `[--sleep-time INTEGER --hardware [cpu-basic|cpu-upgrade|zero-a10g|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8] --format [auto|human|agent|json|quiet]]`
177
+ - `hf spaces ssh SPACE_ID` — SSH into a Space's Dev Mode container. `[--identity-file PATH --dry-run --auto --format [auto|human|agent|json|quiet]]`
178
+ - `hf spaces variables add SPACE_ID` — Add or update environment variables for a Space. `[--env TEXT --env-file TEXT --format [auto|human|agent|json|quiet]]`
179
+ - `hf spaces variables delete SPACE_ID KEY` — Remove an environment variable from a Space. `[--yes --format [auto|human|agent|json|quiet]]`
180
+ - `hf spaces variables list SPACE_ID` — List environment variables for a Space. `[--format [auto|human|agent|json|quiet]]`
181
+ - `hf spaces volumes delete SPACE_ID` — Remove all volumes from a Space. `[--yes --format [auto|human|agent|json|quiet]]`
182
+ - `hf spaces volumes list SPACE_ID` — List volumes mounted in a Space. `[--format [auto|human|agent|json|quiet]]`
183
+ - `hf spaces volumes set SPACE_ID` — Set (replace) volumes for a Space. `[--volume TEXT --format [auto|human|agent|json|quiet]]`
184
+
185
+ ### `hf webhooks` — Manage webhooks on the Hub.
186
+
187
+ - `hf webhooks create --watch TEXT` — Create a new webhook. `[--url TEXT --job-id TEXT --domain [repo|discussions] --secret TEXT --format [auto|human|agent|json|quiet]]`
188
+ - `hf webhooks delete WEBHOOK_ID` — Delete a webhook permanently. `[--yes --format [auto|human|agent|json|quiet]]`
189
+ - `hf webhooks disable WEBHOOK_ID` — Disable an active webhook. `[--format [auto|human|agent|json|quiet]]`
190
+ - `hf webhooks enable WEBHOOK_ID` — Enable a disabled webhook. `[--format [auto|human|agent|json|quiet]]`
191
+ - `hf webhooks info WEBHOOK_ID` — Show full details for a single webhook. `[--format [auto|human|agent|json|quiet]]`
192
+ - `hf webhooks list` — List all webhooks for the current user. `[--format [auto|human|agent|json|quiet]]`
193
+ - `hf webhooks update WEBHOOK_ID` — Update an existing webhook. Only provided options are changed. `[--url TEXT --watch TEXT --domain [repo|discussions] --secret TEXT --format [auto|human|agent|json|quiet]]`
194
+
195
+ ## Common options
196
+
197
+ - `--format` — Output format: `--format json` (or `--json`) or `--format table` (default).
198
+ - `-q / --quiet` — Quiet output (one ID per line).
199
+ - `--revision` — Git revision id which can be a branch name, a tag, or a commit hash.
200
+ - `--token` — Use a User Access Token. Prefer setting `HF_TOKEN` env var instead of passing `--token`.
201
+ - `--type` — The type of repository (model, dataset, or space).
202
+
203
+ ## Mounting repos as local filesystems
204
+
205
+ To mount Hub repositories or buckets as local filesystems — no download, no copy, no waiting — use `hf-mount`. Files are fetched on demand. GitHub: https://github.com/huggingface/hf-mount
206
+
207
+ Install: `curl -fsSL https://raw.githubusercontent.com/huggingface/hf-mount/main/install.sh | sh`
208
+
209
+ Some command examples:
210
+ - `hf-mount start repo openai-community/gpt2 /tmp/gpt2` — mount a repo (read-only)
211
+ - `hf-mount start --hf-token $HF_TOKEN bucket myuser/my-bucket /tmp/data` — mount a bucket (read-write)
212
+ - `hf-mount status` / `hf-mount stop /tmp/data` — list or unmount
213
+
214
+ ## Tips
215
+
216
+ - Use `hf <command> --help` for full options, descriptions, usage, and real-world examples
217
+ - Authenticate with `HF_TOKEN` env var (recommended) or with `--token`
218
+ - Update the CLI with `hf update` (uses the correct command for the detected install method)
.agents/skills/ml-intern/SKILL.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: ml-intern
3
+ description: "Hugging Face ML Intern CLI (`ml-intern`) — an agent that turns natural-language goals into end-to-end ML workflows using the HF ecosystem. Use when: the user wants to research papers/datasets, fine-tune models, run ML experiments, publish artifacts to HF Hub, or perform any multi-step ML engineering task. Combines research, code generation, sandbox execution, and Hub publishing. Use with `hf` CLI for deterministic repo/space/job operations."
4
+ ---
5
+
6
+ # ML Intern Skill
7
+
8
+ ## What is ml-intern?
9
+
10
+ `ml-intern` is a CLI-first agent from Hugging Face that orchestrates end-to-end ML workflows:
11
+ - Research papers and docs via HF Hub
12
+ - Inspect and query datasets
13
+ - Write training/evaluation code
14
+ - Run experiments locally or in HF sandbox (GPU-backed)
15
+ - Publish models, datasets, and Spaces to HF Hub
16
+
17
+ **Source**: https://github.com/huggingface/ml-intern
18
+
19
+ ## When to Use
20
+
21
+ | Use `ml-intern` | Use `hf` CLI | Use both |
22
+ |---|---|---|
23
+ | Broad ML engineering task | Precise Hub/Space/Jobs commands | Agent-driven workflow + deterministic ops |
24
+ | Research → plan → train → eval → publish | Upload/download files | Train locally, publish via `hf upload` |
25
+ | Multi-step experimentation | Check model/dataset info | Research via ml-intern, deploy via `hf` |
26
+ | "Fine-tune X on my dataset" | "List my models" | "Train then push to Hub" |
27
+
28
+ ## Prerequisites
29
+
30
+ ### Install
31
+
32
+ ```bash
33
+ git clone https://github.com/huggingface/ml-intern.git
34
+ cd ml-intern
35
+ uv sync
36
+ uv tool install -e .
37
+ ```
38
+
39
+ ### Required Environment Variables
40
+
41
+ ```bash
42
+ HF_TOKEN=<your-hugging-face-token>
43
+ GITHUB_TOKEN=<github-personal-access-token>
44
+ ```
45
+
46
+ Optional (only for closed providers):
47
+ ```bash
48
+ ANTHROPIC_API_KEY=...
49
+ OPENAI_API_KEY=...
50
+ ```
51
+
52
+ **Secrets management**: Use PQC secrets bundle (`~/.config/pqc-secrets/`) or `secrets-load` shell function. Never commit tokens to repo files.
53
+
54
+ ## Basic Usage
55
+
56
+ ```bash
57
+ # Interactive mode
58
+ ml-intern
59
+
60
+ # Goal-directed mode
61
+ ml-intern "fine-tune llama on my dataset"
62
+
63
+ # With sandbox (GPU-backed remote execution)
64
+ ml-intern --sandbox-tools "test this training script in a GPU sandbox"
65
+
66
+ # Limit iterations
67
+ ml-intern --max-iterations 100 "your prompt"
68
+
69
+ # Non-streaming output
70
+ ml-intern --no-stream "your prompt"
71
+ ```
72
+
73
+ ## Model Selection
74
+
75
+ ```bash
76
+ # Default (HF Inference)
77
+ ml-intern "your prompt"
78
+
79
+ # Specific HF model
80
+ ml-intern --model moonshotai/Kimi-K2.6 "your prompt"
81
+
82
+ # Closed provider
83
+ ml-intern --model openai/gpt-5.5:fal-ai "your prompt"
84
+
85
+ # Local models
86
+ ml-intern --model ollama/llama3.1:8b "your prompt"
87
+ ml-intern --model vllm/meta-llama/Llama-3.1-8B-Instruct "your prompt"
88
+ ml-intern --model lm_studio/google/gemma-3-4b "your prompt"
89
+ ml-intern --model llamacpp/llama-3.1-8b-instruct "your prompt"
90
+ ```
91
+
92
+ Interactive model switch during session:
93
+ ```
94
+ /model ollama/llama3.1:8b
95
+ ```
96
+
97
+ ## Built-in Tools
98
+
99
+ ml-intern routes to these tool groups:
100
+
101
+ | Tool | Purpose |
102
+ |---|---|
103
+ | Research sub-agent | Deep topic investigation |
104
+ | HF docs search/fetch | Official documentation lookup |
105
+ | HF papers | Academic paper search and reading |
106
+ | Web search | General web research |
107
+ | Dataset inspection | `hf datasets info`, parquet queries |
108
+ | Planning + notifications | Workflow orchestration |
109
+ | HF Jobs | Run compute on HF infrastructure |
110
+ | HF repo files/git | Repo file management |
111
+ | GitHub code search | Find implementation examples |
112
+ | Sandbox tools | Remote GPU execution |
113
+ | Local tools | Filesystem read/write/edit |
114
+
115
+ ## Workflows
116
+
117
+ ### Standard ML Workflow
118
+
119
+ ```
120
+ Research → Plan → Inspect Data → Write Code → Train → Evaluate → Publish
121
+ ```
122
+
123
+ ### Local Mode vs Sandbox Mode
124
+
125
+ **Local mode** (`bash`, `read`, `write`, `edit`):
126
+ - Direct filesystem inspection
127
+ - Local repo checkout iteration
128
+ - No remote compute costs
129
+
130
+ **Sandbox mode** (HF Space sandbox + GPU):
131
+ - Remote isolation
132
+ - GPU-backed training
133
+ - Disposable execution environments
134
+ - Requires HF Jobs access
135
+
136
+ ### Approval Gates
137
+
138
+ ml-intern has built-in approval for sensitive operations:
139
+ - `approval_required` events pause the loop
140
+ - Human must confirm before: destructive file ops, Hub publishes, compute job launches
141
+ - This is a safety feature, not a bug
142
+
143
+ ## Integration with HF CLI
144
+
145
+ Pair ml-intern with `hf` for deterministic operations:
146
+
147
+ ```bash
148
+ # ml-intern handles research + code generation
149
+ ml-intern "write a training script for sentiment analysis"
150
+
151
+ # hf handles precise Hub operations
152
+ hf upload myorg/sentiment-model ./output
153
+
154
+ # hf handles Space deployment
155
+ hf repos create myorg/sentiment-demo --type space --space-sdk gradio
156
+ hf upload myorg/sentiment-demo ./app.py
157
+
158
+ # hf handles Jobs
159
+ hf jobs run pytorch/pytorch:latest "python train.py" --flavor t4-small
160
+ ```
161
+
162
+ ## Troubleshooting
163
+
164
+ | Issue | Cause | Fix |
165
+ |---|---|---|
166
+ | Stalled on approval | Approval gate waiting | Check terminal for `approval_required` event |
167
+ | Token scope error | HF_TOKEN lacks permissions | `hf auth login` with write token |
168
+ | Sandbox timeout | GPU queue busy | Retry or use `--flavor` for different hardware |
169
+ | MCP tool error | External MCP server down | Check MCP server status, restart ml-intern |
170
+ | Stale tools | Tool cache issue | Restart ml-intern session |
171
+
172
+ ## Security Notes
173
+
174
+ - Token scoping: use fine-grained tokens with minimal permissions
175
+ - Sandbox mode is safer for untrusted code (isolated execution)
176
+ - Local mode has full filesystem access — trust the code before running
177
+ - Never commit `.env` files with tokens
178
+ - Use PQC secrets bundle for production token management
179
+
180
+ ## Quick Reference
181
+
182
+ ```bash
183
+ ml-intern # Interactive mode
184
+ ml-intern "goal" # Goal-directed
185
+ ml-intern --sandbox-tools "goal" # With GPU sandbox
186
+ ml-intern --max-iterations N "goal" # Limit iterations
187
+ ml-intern --model MODEL "goal" # Specific model
188
+ ml-intern --no-stream "goal" # Non-streaming
189
+ ```
projects/tinybard/app.py CHANGED
@@ -25,8 +25,8 @@ import gradio as gr
25
  from fastapi import FastAPI
26
  from fastapi.responses import HTMLResponse
27
  from fastapi.staticfiles import StaticFiles
28
- from pydantic import BaseModel
29
  from gradio import mount_gradio_app
 
30
 
31
  # Inference client with cooldown (no local GGUF, no llama-cpp-python build!)
32
  # Path layout: monorepo/shared/inference_client.py — go up two parents from this file.
@@ -258,35 +258,471 @@ def generate_llm_choices(genre: str, story_context: str) -> List[str]:
258
  # Gradio Blocks — API endpoints (exposed as MCP tools)
259
  # ---------------------------------------------------------------------------
260
  def create_gradio_app() -> gr.Blocks:
261
- """Build the Gradio Blocks app with API endpoints for MCP integration."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
- with gr.Blocks(title="TinyBard API") as blocks:
264
- # Hidden state — not rendered in UI, used by API
265
- genre_input = gr.Textbox(label="Genre", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  step_input = gr.Number(label="Step", value=0, visible=False)
267
  health_input = gr.Number(label="Health", value=100, visible=False)
268
- choice_input = gr.Textbox(label="Choice", visible=False)
269
  history_input = gr.Textbox(label="History JSON", value="[]", visible=False)
270
 
271
- # Output fields
272
- story_output = gr.Textbox(label="Story")
273
- choices_output = gr.JSON(label="Choices")
274
- health_output = gr.Number(label="Health")
275
- step_output = gr.Number(label="Step")
276
- game_over_output = gr.Checkbox(label="Game Over")
277
- history_output = gr.Textbox(label="History JSON")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
 
279
  def api_start_game(genre: str):
280
  """Start a new interactive text adventure. Exposed as MCP tool."""
281
- genre = genre.lower()
282
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
283
  genre = "fantasy"
284
 
285
- # Try LLM first (will skip if cooldown is active)
286
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
287
  story = generate_llm_story(genre, [], instruction)
288
  if not story:
289
- # Procedural fallback
290
  result = generate_procedural_step(genre, 0, 100)
291
  return (
292
  result["story"], result["choices"], result["health"],
@@ -297,7 +733,6 @@ def create_gradio_app() -> gr.Blocks:
297
  history = [{"role": "narrator", "text": story}]
298
  choices = generate_llm_choices(genre, story)
299
  if len(choices) < 2:
300
- # Use the procedural choices
301
  fallback = generate_procedural_step(genre, 0, 100)
302
  choices = fallback["choices"]
303
 
@@ -305,15 +740,15 @@ def create_gradio_app() -> gr.Blocks:
305
 
306
  def api_make_choice(choice: str, genre: str, step: int, health: int, history_json: str):
307
  """Submit a player choice to advance the story. Exposed as MCP tool."""
 
308
  try:
309
  history = json.loads(history_json)
310
  except Exception:
311
  history = []
312
 
313
- step = int(step)
314
- health = int(health)
315
 
316
- # First try LLM narration
317
  history.append({"role": "player", "text": choice})
318
 
319
  health_delta = random.choice([-15, 0, 10])
@@ -327,7 +762,6 @@ def create_gradio_app() -> gr.Blocks:
327
  [], 0, step + 1, True, json.dumps(history)
328
  )
329
 
330
- # No step cap — adventure continues infinitely until health reaches 0
331
  instruction = "Narrate what happens next as a result of the player's choice."
332
  story = generate_llm_story(genre, history, instruction)
333
  if not story:
@@ -346,19 +780,140 @@ def create_gradio_app() -> gr.Blocks:
346
 
347
  return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
348
 
349
- # Register API endpoints
350
- gr.Button("Start Game").click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  fn=api_start_game,
352
  inputs=[genre_input],
353
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
354
- api_name="start_game"
 
 
 
 
 
 
 
355
  )
356
 
357
- gr.Button("Make Choice").click(
 
358
  fn=api_make_choice,
359
- inputs=[choice_input, genre_input, step_input, health_input, history_input],
360
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
361
- api_name="make_choice"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  )
363
 
364
  return blocks
@@ -620,16 +1175,17 @@ async def get_config():
620
  fastapi_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
621
 
622
  # Mount Gradio app at /gradio — this creates the API + MCP endpoints
623
- demo = create_gradio_app()
624
- app = mount_gradio_app(fastapi_app, demo, path="/gradio")
625
 
626
  # ---------------------------------------------------------------------------
627
  # Entrypoint
628
  # ---------------------------------------------------------------------------
629
  if __name__ == "__main__":
 
630
  if os.environ.get("SPACE_ID"):
631
- log.info("Running on HF Spaces — launching Gradio on default port.")
632
- demo.launch(server_name="0.0.0.0")
633
  else:
634
  import uvicorn
635
  port = int(os.environ.get("PORT", "7860"))
 
25
  from fastapi import FastAPI
26
  from fastapi.responses import HTMLResponse
27
  from fastapi.staticfiles import StaticFiles
 
28
  from gradio import mount_gradio_app
29
+ from pydantic import BaseModel
30
 
31
  # Inference client with cooldown (no local GGUF, no llama-cpp-python build!)
32
  # Path layout: monorepo/shared/inference_client.py — go up two parents from this file.
 
258
  # Gradio Blocks — API endpoints (exposed as MCP tools)
259
  # ---------------------------------------------------------------------------
260
  def create_gradio_app() -> gr.Blocks:
261
+ """Build the Gradio Blocks app with Anishinaabe Solarpunk CRT aesthetic.
262
+
263
+ API endpoints (start_game, make_choice) are preserved for MCP integration.
264
+ On HF Spaces, this Gradio UI IS the only interface.
265
+ """
266
+
267
+ # Anishinaabe Solarpunk CRT custom CSS
268
+ ASP_CSS = """
269
+ :root {
270
+ --asp-sky: #5BA4D9;
271
+ --asp-water: #1B4965;
272
+ --asp-frost: #CAF0F8;
273
+ --asp-sun: #F2A93B;
274
+ --asp-sunlight: #FFB347;
275
+ --asp-ember: #E76F51;
276
+ --asp-birch: #F5F1E8;
277
+ --asp-moss: #588157;
278
+ --asp-spruce: #1B4332;
279
+ --asp-night: #0F1A2C;
280
+ --asp-earth: #8B3A1F;
281
+ --asp-stone: #A89F91;
282
+ }
283
+
284
+ /* Page background */
285
+ .gradio-container, .app, body {
286
+ background:
287
+ radial-gradient(ellipse at top, #1B4965 0%, transparent 60%),
288
+ radial-gradient(ellipse at bottom right, #1B4332 0%, transparent 70%),
289
+ #0F1A2C !important;
290
+ color: #F5F1E8 !important;
291
+ font-family: Georgia, 'Iowan Old Style', serif !important;
292
+ }
293
+
294
+ /* CRT scanline overlay */
295
+ .gradio-container::after {
296
+ content: "";
297
+ position: fixed;
298
+ top: 0; left: 0; right: 0; bottom: 0;
299
+ background: repeating-linear-gradient(
300
+ 0deg,
301
+ transparent,
302
+ transparent 2px,
303
+ rgba(91, 164, 217, 0.04) 2px,
304
+ rgba(91, 164, 217, 0.04) 4px
305
+ );
306
+ pointer-events: none;
307
+ z-index: 9999;
308
+ }
309
+
310
+ /* Banner */
311
+ .asp-banner {
312
+ background: linear-gradient(95deg, #5BA4D9 0%, #1B4965 100%);
313
+ color: #F5F1E8;
314
+ border: 1px solid rgba(255, 179, 71, 0.3);
315
+ border-radius: 10px;
316
+ padding: 14px 20px;
317
+ margin-bottom: 16px;
318
+ font-family: Georgia, serif;
319
+ text-align: center;
320
+ text-shadow: 0 1px 2px rgba(15, 26, 44, 0.45);
321
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
322
+ letter-spacing: 0.5px;
323
+ }
324
+ .asp-banner .syll { font-size: 1.6em; opacity: 0.9; }
325
+ .asp-banner .glyph { color: #FFB347; font-size: 1.15em; }
326
+ .asp-banner .title {
327
+ font-size: 1.1em; font-weight: 700;
328
+ letter-spacing: 2px; text-transform: uppercase;
329
+ }
330
+ .asp-banner .subtitle {
331
+ color: #CAF0F8; font-size: 0.85em;
332
+ font-style: italic; opacity: 0.85;
333
+ }
334
+
335
+ /* Section containers */
336
+ .asp-section {
337
+ background: linear-gradient(160deg, rgba(139, 58, 31, 0.25) 0%, rgba(15, 26, 44, 0.6) 100%);
338
+ border: 1px solid rgba(91, 164, 217, 0.2);
339
+ border-radius: 10px;
340
+ padding: 16px 20px;
341
+ margin-bottom: 12px;
342
+ box-shadow:
343
+ inset 0 0 40px rgba(0, 0, 0, 0.3),
344
+ 0 8px 32px rgba(0, 0, 0, 0.4);
345
+ }
346
+ .asp-section::before {
347
+ content: "\\25C8";
348
+ display: block;
349
+ color: #F2A93B;
350
+ font-size: 0.7rem;
351
+ letter-spacing: 6px;
352
+ margin-bottom: 6px;
353
+ opacity: 0.5;
354
+ text-align: center;
355
+ }
356
+
357
+ /* Section labels */
358
+ .asp-label {
359
+ color: #CAF0F8 !important;
360
+ font-family: Georgia, serif !important;
361
+ font-size: 0.72rem !important;
362
+ text-transform: uppercase !important;
363
+ letter-spacing: 2px !important;
364
+ margin-bottom: 8px !important;
365
+ text-shadow: 0 0 6px rgba(91, 164, 217, 0.3);
366
+ }
367
+
368
+ /* Genre radio buttons */
369
+ .asp-genre label {
370
+ background: rgba(15, 26, 44, 0.4) !important;
371
+ border: 1px solid rgba(91, 164, 217, 0.3) !important;
372
+ border-radius: 4px !important;
373
+ color: #CAF0F8 !important;
374
+ padding: 10px 18px !important;
375
+ font-family: Georgia, serif !important;
376
+ font-size: 0.82rem !important;
377
+ letter-spacing: 1.5px !important;
378
+ text-transform: uppercase !important;
379
+ cursor: pointer !important;
380
+ transition: all 0.2s !important;
381
+ }
382
+ .asp-genre label:hover {
383
+ background: rgba(242, 169, 59, 0.15) !important;
384
+ border-color: #F2A93B !important;
385
+ color: #FFB347 !important;
386
+ text-shadow: 0 0 12px rgba(242, 169, 59, 0.5);
387
+ }
388
+ .asp-genre input[type="radio"]:checked + span {
389
+ color: #FFB347 !important;
390
+ text-shadow: 0 0 8px rgba(242, 169, 59, 0.5);
391
+ }
392
+
393
+ /* Choice radio buttons */
394
+ .asp-choices label {
395
+ display: block !important;
396
+ background: rgba(15, 26, 44, 0.3) !important;
397
+ border: 1px solid rgba(91, 164, 217, 0.25) !important;
398
+ border-radius: 3px !important;
399
+ color: #CAF0F8 !important;
400
+ padding: 10px 16px !important;
401
+ margin-bottom: 4px !important;
402
+ font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', Menlo, monospace !important;
403
+ font-size: 0.82rem !important;
404
+ cursor: pointer !important;
405
+ transition: all 0.15s !important;
406
+ text-shadow: 0 0 3px rgba(91, 164, 217, 0.2);
407
+ }
408
+ .asp-choices label:hover {
409
+ background: rgba(91, 164, 217, 0.1) !important;
410
+ border-color: #F2A93B !important;
411
+ color: #FFB347 !important;
412
+ padding-left: 26px !important;
413
+ box-shadow: 0 0 12px rgba(242, 169, 59, 0.15);
414
+ }
415
 
416
+ /* Buttons */
417
+ .asp-btn {
418
+ background: linear-gradient(95deg, rgba(139, 58, 31, 0.4) 0%, rgba(27, 67, 50, 0.4) 100%) !important;
419
+ border: 1px solid rgba(91, 164, 217, 0.35) !important;
420
+ border-radius: 4px !important;
421
+ color: #CAF0F8 !important;
422
+ font-family: Georgia, serif !important;
423
+ font-size: 0.82rem !important;
424
+ letter-spacing: 1.5px !important;
425
+ text-transform: uppercase !important;
426
+ padding: 10px 22px !important;
427
+ cursor: pointer !important;
428
+ transition: all 0.2s !important;
429
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
430
+ }
431
+ .asp-btn:hover {
432
+ background: linear-gradient(95deg, rgba(242, 169, 59, 0.25) 0%, rgba(91, 164, 217, 0.25) 100%) !important;
433
+ border-color: #F2A93B !important;
434
+ color: #FFB347 !important;
435
+ box-shadow: 0 0 18px rgba(242, 169, 59, 0.3);
436
+ text-shadow: 0 0 8px rgba(242, 169, 59, 0.4);
437
+ }
438
+ .asp-btn-primary {
439
+ background: linear-gradient(95deg, #8B3A1F 0%, #1B4332 100%) !important;
440
+ border-color: rgba(242, 169, 59, 0.5) !important;
441
+ box-shadow: 0 0 16px rgba(242, 169, 59, 0.15);
442
+ }
443
+ .asp-btn-primary:hover {
444
+ box-shadow: 0 0 24px rgba(242, 169, 59, 0.4) !important;
445
+ }
446
+
447
+ /* Story output */
448
+ .asp-story textarea {
449
+ background: rgba(15, 26, 44, 0.5) !important;
450
+ border: none !important;
451
+ border-left: 3px solid #F2A93B !important;
452
+ border-radius: 0 6px 6px 0 !important;
453
+ color: #F5F1E8 !important;
454
+ font-family: Georgia, 'Iowan Old Style', serif !important;
455
+ font-size: 0.92rem !important;
456
+ line-height: 1.7 !important;
457
+ padding: 14px 18px !important;
458
+ text-shadow: 0 0 6px rgba(242, 169, 59, 0.12);
459
+ box-shadow: inset 0 0 30px rgba(15, 26, 44, 0.4);
460
+ animation: fadeSlideIn 0.5s ease-out;
461
+ }
462
+
463
+ /* Textbox inputs */
464
+ .asp-input textarea, .asp-input input {
465
+ background: rgba(15, 26, 44, 0.5) !important;
466
+ border: 1px solid rgba(91, 164, 217, 0.3) !important;
467
+ border-radius: 4px !important;
468
+ color: #F5F1E8 !important;
469
+ font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', Menlo, monospace !important;
470
+ font-size: 0.88rem !important;
471
+ caret-color: #F2A93B !important;
472
+ }
473
+ .asp-input textarea:focus, .asp-input input:focus {
474
+ border-color: #F2A93B !important;
475
+ box-shadow: 0 0 12px rgba(242, 169, 59, 0.2);
476
+ outline: none !important;
477
+ }
478
+
479
+ /* Status row */
480
+ .asp-status {
481
+ background: rgba(15, 26, 44, 0.4) !important;
482
+ border: 1px solid rgba(91, 164, 217, 0.15) !important;
483
+ border-radius: 6px !important;
484
+ padding: 10px 16px !important;
485
+ }
486
+ .asp-status label {
487
+ color: #CAF0F8 !important;
488
+ font-family: Georgia, serif !important;
489
+ font-size: 0.7rem !important;
490
+ text-transform: uppercase !important;
491
+ letter-spacing: 1.5px !important;
492
+ }
493
+
494
+ /* Footer */
495
+ .asp-footer {
496
+ text-align: center;
497
+ padding: 10px 0 4px;
498
+ border-top: 1px solid rgba(91, 164, 217, 0.15);
499
+ margin-top: 8px;
500
+ font-size: 0.65rem;
501
+ color: #A89F91;
502
+ letter-spacing: 1.5px;
503
+ font-family: Georgia, serif;
504
+ }
505
+
506
+ @keyframes fadeSlideIn {
507
+ from { opacity: 0; transform: translateX(-10px); }
508
+ to { opacity: 1; transform: translateX(0); }
509
+ }
510
+
511
+ label, .wrap > label {
512
+ color: #CAF0F8 !important;
513
+ font-family: Georgia, serif !important;
514
+ }
515
+
516
+ ::-webkit-scrollbar { width: 6px; }
517
+ ::-webkit-scrollbar-track { background: transparent; }
518
+ ::-webkit-scrollbar-thumb {
519
+ background: rgba(91, 164, 217, 0.25);
520
+ border-radius: 3px;
521
+ }
522
+
523
+ @media (max-width: 600px) {
524
+ .asp-banner { padding: 10px 14px; font-size: 0.85em; }
525
+ .asp-section { padding: 12px; }
526
+ }
527
+ """
528
+
529
+ with gr.Blocks(title="TinyBard") as blocks:
530
+
531
+ blocks.theme = gr.themes.Base(
532
+ primary_hue="amber",
533
+ neutral_hue="slate",
534
+ ).set(
535
+ body_background_fill="#0F1A2C",
536
+ body_text_color="#F5F1E8",
537
+ block_background_fill="rgba(15, 26, 44, 0.3)",
538
+ block_border_color="rgba(91, 164, 217, 0.2)",
539
+ block_label_text_color="#CAF0F8",
540
+ input_background_fill="rgba(15, 26, 44, 0.5)",
541
+ input_border_color="rgba(91, 164, 217, 0.3)",
542
+ button_primary_background_fill="linear-gradient(95deg, #8B3A1F, #1B4332)",
543
+ button_primary_border_color="rgba(242, 169, 59, 0.5)",
544
+ button_primary_text_color="#CAF0F8",
545
+ button_secondary_background_fill="rgba(139, 58, 31, 0.3)",
546
+ button_secondary_border_color="rgba(91, 164, 217, 0.35)",
547
+ button_secondary_text_color="#CAF0F8",
548
+ )
549
+
550
+ # Inject CSS via HTML since Gradio 6.0 has no css= param on Blocks
551
+ gr.HTML(f"<style>{ASP_CSS}</style>")
552
+
553
+ # Banner
554
+ gr.HTML(
555
+ '<div class="asp-banner">'
556
+ '<span class="syll">\u1434</span> '
557
+ '<span class="glyph">\u263C</span> '
558
+ '<span class="title">TINYBARD</span> '
559
+ '<span class="glyph">\u2618</span> '
560
+ '<span class="subtitle">\u2014 a fire-fly storyteller in cedar and copper \u2014</span> '
561
+ '<span class="syll">\u1514</span>'
562
+ '</div>'
563
+ )
564
+
565
+ # Hidden state fields (for internal tracking + MCP API)
566
+ genre_input = gr.Textbox(label="Genre", value="fantasy", visible=False)
567
  step_input = gr.Number(label="Step", value=0, visible=False)
568
  health_input = gr.Number(label="Health", value=100, visible=False)
 
569
  history_input = gr.Textbox(label="History JSON", value="[]", visible=False)
570
 
571
+ # Genre selector
572
+ with gr.Group(elem_classes=["asp-section"]):
573
+ gr.HTML('<div class="asp-label">\u1434 INAABANDA\u0027IWIN / SELECT GENRE \u1514</div>')
574
+ genre_radio = gr.Radio(
575
+ choices=[
576
+ ("\u263C Aadizookaan / Fantasy", "fantasy"),
577
+ ("\u25C8 Ishpiming / Sci-Fi", "scifi"),
578
+ ("\u25C6 Mashkodewaazibi / Cyberpunk", "cyberpunk"),
579
+ ],
580
+ value="fantasy",
581
+ label=None,
582
+ show_label=False,
583
+ elem_classes=["asp-genre"],
584
+ )
585
+
586
+ # Story output
587
+ with gr.Group(elem_classes=["asp-section"]):
588
+ gr.HTML('<div class="asp-label">\u1434 AADIZOOKAAN / STORY \u1514</div>')
589
+ story_output = gr.Textbox(
590
+ label="Story",
591
+ show_label=False,
592
+ lines=8,
593
+ max_lines=20,
594
+ interactive=False,
595
+ elem_classes=["asp-story"],
596
+ )
597
+
598
+ # Choices radio (populated after game start)
599
+ with gr.Group(elem_classes=["asp-section"]):
600
+ gr.HTML('<div class="asp-label">\u1434 INAABANDA\u0027IWIN / CHOOSE \u1514</div>')
601
+ choice_radio = gr.Radio(
602
+ choices=[],
603
+ label=None,
604
+ show_label=False,
605
+ interactive=True,
606
+ elem_classes=["asp-choices"],
607
+ )
608
+
609
+ # Choice text input (fallback / custom choice)
610
+ with gr.Group(elem_classes=["asp-section"]):
611
+ gr.HTML('<div class="asp-label">\u1434 NINDANOKIMAA / TYPE YOUR ACTION \u1514</div>')
612
+ choice_text_input = gr.Textbox(
613
+ label="Type your choice",
614
+ show_label=False,
615
+ placeholder="Type your action or select above...",
616
+ lines=1,
617
+ max_lines=3,
618
+ elem_classes=["asp-input"],
619
+ )
620
+
621
+ # Action buttons
622
+ with gr.Row():
623
+ start_btn = gr.Button(
624
+ "\u263C START GAME",
625
+ variant="primary",
626
+ elem_classes=["asp-btn", "asp-btn-primary"],
627
+ scale=2,
628
+ )
629
+ choice_btn = gr.Button(
630
+ "\u25C8 MAKE CHOICE",
631
+ variant="secondary",
632
+ elem_classes=["asp-btn"],
633
+ scale=2,
634
+ )
635
+ save_btn = gr.Button(
636
+ "\u25C6 SAVE",
637
+ variant="secondary",
638
+ elem_classes=["asp-btn"],
639
+ scale=1,
640
+ )
641
+ load_btn = gr.Button(
642
+ "\u2618 LOAD",
643
+ variant="secondary",
644
+ elem_classes=["asp-btn"],
645
+ scale=1,
646
+ )
647
+
648
+ # Save slot input
649
+ with gr.Group(elem_classes=["asp-section"]):
650
+ gr.HTML('<div class="asp-label">\u1434 OZHIIMAAGAN / SAVE SLOT \u1514</div>')
651
+ save_slot_input = gr.Textbox(
652
+ label="Slot Name",
653
+ show_label=False,
654
+ placeholder="my-adventure",
655
+ lines=1,
656
+ elem_classes=["asp-input"],
657
+ )
658
+ save_status = gr.Textbox(
659
+ label="Save Status",
660
+ show_label=False,
661
+ interactive=False,
662
+ lines=1,
663
+ elem_classes=["asp-input"],
664
+ )
665
+
666
+ # Status bar
667
+ with gr.Row(elem_classes=["asp-status"]):
668
+ health_output = gr.Number(label="NOOSISKAAZOWIN / Health", value=100, interactive=False)
669
+ step_output = gr.Number(label="DIBIK / Step", value=0, interactive=False)
670
+ game_over_output = gr.Checkbox(label="GIIZHIG / Game Over", value=False, interactive=False)
671
+
672
+ # Choices JSON (hidden for MCP/debug)
673
+ choices_output = gr.JSON(label="Choices JSON", visible=False, elem_classes=["asp-json"])
674
+ history_output = gr.Textbox(label="History JSON", visible=False)
675
+
676
+ # Footer
677
+ gr.HTML(
678
+ '<div class="asp-footer">'
679
+ '\u1434 TinyBard \u00b7 FastAPI + Gradio + MCP \u00b7 Anishinaabe Solarpunk \u1514'
680
+ '</div>'
681
+ )
682
+
683
+ # ================================================================
684
+ # Event Handlers
685
+ # ================================================================
686
+
687
+ # Sync genre radio to hidden genre_input
688
+ def sync_genre(genre_val):
689
+ return genre_val or "fantasy"
690
+
691
+ genre_radio.change(
692
+ fn=sync_genre,
693
+ inputs=[genre_radio],
694
+ outputs=[genre_input],
695
+ )
696
+
697
+ # Sync choice radio selection to text input
698
+ def sync_choice_to_text(radio_val, current_text):
699
+ if radio_val:
700
+ return radio_val
701
+ return current_text
702
+
703
+ choice_radio.change(
704
+ fn=sync_choice_to_text,
705
+ inputs=[choice_radio, choice_text_input],
706
+ outputs=[choice_text_input],
707
+ )
708
+
709
+ # Update choice radio from choices JSON
710
+ def update_choices_radio(choices_json):
711
+ if not choices_json:
712
+ return gr.update(choices=[], value=None)
713
+ if isinstance(choices_json, list):
714
+ return gr.update(choices=choices_json, value=None)
715
+ return gr.update(choices=[], value=None)
716
 
717
  def api_start_game(genre: str):
718
  """Start a new interactive text adventure. Exposed as MCP tool."""
719
+ genre = (genre or "fantasy").lower()
720
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
721
  genre = "fantasy"
722
 
 
723
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
724
  story = generate_llm_story(genre, [], instruction)
725
  if not story:
 
726
  result = generate_procedural_step(genre, 0, 100)
727
  return (
728
  result["story"], result["choices"], result["health"],
 
733
  history = [{"role": "narrator", "text": story}]
734
  choices = generate_llm_choices(genre, story)
735
  if len(choices) < 2:
 
736
  fallback = generate_procedural_step(genre, 0, 100)
737
  choices = fallback["choices"]
738
 
 
740
 
741
  def api_make_choice(choice: str, genre: str, step: int, health: int, history_json: str):
742
  """Submit a player choice to advance the story. Exposed as MCP tool."""
743
+ genre = (genre or "fantasy").lower()
744
  try:
745
  history = json.loads(history_json)
746
  except Exception:
747
  history = []
748
 
749
+ step = int(step or 0)
750
+ health = int(health or 100)
751
 
 
752
  history.append({"role": "player", "text": choice})
753
 
754
  health_delta = random.choice([-15, 0, 10])
 
762
  [], 0, step + 1, True, json.dumps(history)
763
  )
764
 
 
765
  instruction = "Narrate what happens next as a result of the player's choice."
766
  story = generate_llm_story(genre, history, instruction)
767
  if not story:
 
780
 
781
  return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
782
 
783
+ # Helper: resolve choice from radio or text input
784
+ def resolve_choice(choice_text, choice_radio_val):
785
+ """Use text input if filled, otherwise use radio selection."""
786
+ if choice_text and choice_text.strip():
787
+ return choice_text.strip()
788
+ if choice_radio_val:
789
+ return choice_radio_val
790
+ return ""
791
+
792
+ # Make Choice: resolve choice, then call api_make_choice
793
+ def handle_make_choice(choice_text, choice_radio_val, genre, step, health, history_json):
794
+ resolved = resolve_choice(choice_text, choice_radio_val)
795
+ if not resolved:
796
+ return (
797
+ "Please type or select a choice before making your move.",
798
+ gr.update(), 100, 0, False, "[]",
799
+ "", gr.update()
800
+ )
801
+ story, choices, h, s, go, hist = api_make_choice(resolved, genre, step, health, history_json)
802
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
803
+
804
+ # Start Game: call api_start_game, clear choice input, update radio
805
+ def handle_start_game(genre):
806
+ story, choices, h, s, go, hist = api_start_game(genre)
807
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
808
+
809
+ # API endpoints (preserved for MCP)
810
+ start_btn.click(
811
  fn=api_start_game,
812
  inputs=[genre_input],
813
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
814
+ api_name="start_game",
815
+ )
816
+
817
+ # UI start game button: also updates choices radio and clears text
818
+ start_btn.click(
819
+ fn=handle_start_game,
820
+ inputs=[genre_input],
821
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
822
  )
823
 
824
+ # API make_choice endpoint (preserved for MCP)
825
+ choice_btn.click(
826
  fn=api_make_choice,
827
+ inputs=[choice_text_input, genre_input, step_input, health_input, history_input],
828
  outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output],
829
+ api_name="make_choice",
830
+ )
831
+
832
+ # UI make choice button: resolves radio/text, updates choices radio
833
+ choice_btn.click(
834
+ fn=handle_make_choice,
835
+ inputs=[choice_text_input, choice_radio, genre_input, step_input, health_input, history_input],
836
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
837
+ )
838
+
839
+ # Save game handler
840
+ def handle_save(slot_name, genre, step, health, history_json, game_over):
841
+ import urllib.request
842
+ import urllib.error
843
+ if not slot_name or not slot_name.strip():
844
+ return "Please enter a save slot name."
845
+ try:
846
+ history = json.loads(history_json) if history_json else []
847
+ except Exception:
848
+ history = []
849
+ payload = json.dumps({
850
+ "slot_name": slot_name.strip(),
851
+ "genre": genre or "fantasy",
852
+ "step": int(step or 0),
853
+ "health": int(health or 100),
854
+ "history": history,
855
+ "game_over": bool(game_over),
856
+ }).encode()
857
+ try:
858
+ req = urllib.request.Request(
859
+ "/api/game/save",
860
+ data=payload,
861
+ headers={"Content-Type": "application/json"},
862
+ method="POST",
863
+ )
864
+ with urllib.request.urlopen(req) as resp:
865
+ result = json.loads(resp.read())
866
+ return f"Saved to '{result.get('slot_name', slot_name)}'"
867
+ except Exception as e:
868
+ return f"Save failed: {e}"
869
+
870
+ save_btn.click(
871
+ fn=handle_save,
872
+ inputs=[save_slot_input, genre_input, step_input, health_input, history_input, game_over_output],
873
+ outputs=[save_status],
874
+ )
875
+
876
+ # Load game handler
877
+ def handle_load(slot_name):
878
+ import urllib.request
879
+ if not slot_name or not slot_name.strip():
880
+ return "Enter a slot name to load.", gr.update(), 100, 0, False, "[]", ""
881
+ try:
882
+ payload = json.dumps({"slot_name": slot_name.strip()}).encode()
883
+ req = urllib.request.Request(
884
+ "/api/game/load",
885
+ data=payload,
886
+ headers={"Content-Type": "application/json"},
887
+ method="POST",
888
+ )
889
+ with urllib.request.urlopen(req) as resp:
890
+ result = json.loads(resp.read())
891
+ if result.get("status") != "ok":
892
+ return f"Load failed: {result.get('message', 'Unknown error')}", gr.update(), 100, 0, False, "[]", ""
893
+ choices = result.get("choices", [])
894
+ history = result.get("history", [])
895
+ story = ""
896
+ if history:
897
+ for h in reversed(history):
898
+ if h.get("role") == "narrator":
899
+ story = h.get("text", "")
900
+ break
901
+ return (
902
+ story or "Game loaded.",
903
+ gr.update(choices=choices, value=None),
904
+ result.get("health", 100),
905
+ result.get("step", 0),
906
+ result.get("game_over", False),
907
+ json.dumps(history),
908
+ f"Loaded '{result.get('slot_name', slot_name)}'",
909
+ )
910
+ except Exception as e:
911
+ return f"Load failed: {e}", gr.update(), 100, 0, False, "[]", ""
912
+
913
+ load_btn.click(
914
+ fn=handle_load,
915
+ inputs=[save_slot_input],
916
+ outputs=[story_output, choice_radio, health_output, step_output, game_over_output, history_input, save_status],
917
  )
918
 
919
  return blocks
 
1175
  fastapi_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
1176
 
1177
  # Mount Gradio app at /gradio — this creates the API + MCP endpoints
1178
+ gradio_blocks = create_gradio_app()
1179
+ mount_gradio_app(fastapi_app, gradio_blocks, path="/gradio")
1180
 
1181
  # ---------------------------------------------------------------------------
1182
  # Entrypoint
1183
  # ---------------------------------------------------------------------------
1184
  if __name__ == "__main__":
1185
+ # On HF Spaces, the platform handles the server — just launch Gradio
1186
  if os.environ.get("SPACE_ID"):
1187
+ log.info("Running on HF Spaces — launching Gradio directly")
1188
+ gradio_blocks.launch(server_name="0.0.0.0", server_port=7860)
1189
  else:
1190
  import uvicorn
1191
  port = int(os.environ.get("PORT", "7860"))