AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(hugging-face): let agents read datasets, write to the Hub and manage webhooks and notifications (#16074)
Odai Ahmadb20b547f37b1
diff --git a/bun.lock b/bun.lockindex c7d459d4712..fe270ce8f06 100644--- a/bun.lock+++ b/bun.lock@@ -4407,7 +4407,7 @@},"packages/pieces/community/hugging-face": {"name": "@activepieces/piece-hugging-face",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/hugging-face/package.json b/packages/pieces/community/hugging-face/package.jsonindex 0b709e6b7a2..ecaa22dbc0e 100644--- a/packages/pieces/community/hugging-face/package.json+++ b/packages/pieces/community/hugging-face/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-hugging-face",- "version": "0.2.0",+ "version": "0.3.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/hugging-face/src/i18n/translation.json b/packages/pieces/community/hugging-face/src/i18n/translation.jsonindex b616da725ae..7b27812096a 100644--- a/packages/pieces/community/hugging-face/src/i18n/translation.json+++ b/packages/pieces/community/hugging-face/src/i18n/translation.json@@ -38,6 +38,53 @@"Get Collection": "Get Collection","Generate Chat Completion": "Generate Chat Completion","Generate Text Embeddings": "Generate Text Embeddings",+ "Check Dataset Viewer Support": "Check Dataset Viewer Support",+ "List Dataset Subsets & Splits": "List Dataset Subsets & Splits",+ "Preview Dataset Rows": "Preview Dataset Rows",+ "Get Dataset Rows": "Get Dataset Rows",+ "Search Dataset Rows": "Search Dataset Rows",+ "Filter Dataset Rows": "Filter Dataset Rows",+ "Get Dataset Schema & Info": "Get Dataset Schema & Info",+ "Get Dataset Size": "Get Dataset Size",+ "Get Column Statistics": "Get Column Statistics",+ "List Parquet Files": "List Parquet Files",+ "Get Dataset Leaderboard": "Get Dataset Leaderboard",+ "Create Repository": "Create Repository",+ "Update Repo Settings": "Update Repo Settings",+ "Create Branch": "Create Branch",+ "Delete Branch": "Delete Branch",+ "Create Tag": "Create Tag",+ "Delete Tag": "Delete Tag",+ "Commit Files": "Commit Files",+ "Create Discussion": "Create Discussion",+ "Comment on Discussion": "Comment on Discussion",+ "Open or Close Discussion": "Open or Close Discussion",+ "Rename Discussion": "Rename Discussion",+ "Pin or Unpin Discussion": "Pin or Unpin Discussion",+ "Delete Discussion": "Delete Discussion",+ "Comment on Paper": "Comment on Paper",+ "Reply to Paper Comment": "Reply to Paper Comment",+ "Create Collection": "Create Collection",+ "Add Item to Collection": "Add Item to Collection",+ "List Gated Access Requests": "List Gated Access Requests",+ "Accept or Reject Access Request": "Accept or Reject Access Request",+ "Set Space Secret": "Set Space Secret",+ "Delete Space Secret": "Delete Space Secret",+ "Set Space Variable": "Set Space Variable",+ "Delete Space Variable": "Delete Space Variable",+ "List Notifications": "List Notifications",+ "Delete Notifications": "Delete Notifications",+ "Watch or Unwatch": "Watch or Unwatch",+ "List Webhooks": "List Webhooks",+ "Get Webhook": "Get Webhook",+ "Create Webhook": "Create Webhook",+ "Update Webhook": "Update Webhook",+ "Delete Webhook": "Delete Webhook",+ "Enable or Disable Webhook": "Enable or Disable Webhook",+ "List Inference Endpoints": "List Inference Endpoints",+ "Get User Social Handles": "Get User Social Handles",+ "Get Organization Social Handles": "Get Organization Social Handles",+ "Search Hugging Face Docs": "Search Hugging Face Docs","Answer questions from document images using Hugging Face models": "Answer questions from document images using Hugging Face models","Translate text between languages using specialized Hugging Face translation models": "Translate text between languages using specialized Hugging Face translation models","Classify text into categories using Hugging Face models - includes zero-shot classification for custom categories": "Classify text into categories using Hugging Face models - includes zero-shot classification for custom categories",@@ -75,6 +122,53 @@"Get one Hugging Face collection with all of its items.": "Get one Hugging Face collection with all of its items.","Generate an assistant reply from a list of chat messages with a model served by Inference Providers.": "Generate an assistant reply from a list of chat messages with a model served by Inference Providers.","Turn text into embedding vectors with a feature-extraction model served by Inference Providers.": "Turn text into embedding vectors with a feature-extraction model served by Inference Providers.",+ "Check which dataset viewer features (preview, rows, search, filter, statistics) a dataset supports.": "Check which dataset viewer features (preview, rows, search, filter, statistics) a dataset supports.",+ "List the subsets (configs) and splits of a dataset in the dataset viewer.": "List the subsets (configs) and splits of a dataset in the dataset viewer.",+ "Get the first rows (up to 100) of a dataset split, with its column types.": "Get the first rows (up to 100) of a dataset split, with its column types.",+ "Get a page of rows (up to 100) from a dataset split, by offset.": "Get a page of rows (up to 100) from a dataset split, by offset.",+ "Full-text search over the text columns of a dataset split.": "Full-text search over the text columns of a dataset split.",+ "Get the rows of a dataset split that match a SQL-like condition, optionally sorted.": "Get the rows of a dataset split that match a SQL-like condition, optionally sorted.",+ "Get the column schema (features), description, license, citation and split sizes of a dataset.": "Get the column schema (features), description, license, citation and split sizes of a dataset.",+ "Get the number of rows and bytes of a dataset, per subset and per split.": "Get the number of rows and bytes of a dataset, per subset and per split.",+ "Get per-column statistics (counts, nulls, min/max/mean, histograms, label frequencies) of a dataset split.": "Get per-column statistics (counts, nulls, min/max/mean, histograms, label frequencies) of a dataset split.",+ "List the auto-converted Parquet files of a dataset, with their download URLs and sizes.": "List the auto-converted Parquet files of a dataset, with their download URLs and sizes.",+ "Get the models ranked by their evaluation score on a benchmark dataset.": "Get the models ranked by their evaluation score on a benchmark dataset.",+ "Create a model, dataset or Space repository on the Hugging Face Hub, or return it if it already exists.": "Create a model, dataset or Space repository on the Hugging Face Hub, or return it if it already exists.",+ "Change the visibility, discussions or gated-access settings of a Hub repository.": "Change the visibility, discussions or gated-access settings of a Hub repository.",+ "Create a new branch in a Hub repository.": "Create a new branch in a Hub repository.",+ "Delete a branch from a Hub repository.": "Delete a branch from a Hub repository.",+ "Create a git tag on a revision of a Hub repository.": "Create a git tag on a revision of a Hub repository.",+ "Delete a git tag from a Hub repository.": "Delete a git tag from a Hub repository.",+ "Create, update or delete text files in a Hub repository in a single commit, optionally as a pull request.": "Create, update or delete text files in a Hub repository in a single commit, optionally as a pull request.",+ "Open a new discussion or draft pull request on a Hub repository.": "Open a new discussion or draft pull request on a Hub repository.",+ "Post a comment on a discussion or pull request of a Hub repository.": "Post a comment on a discussion or pull request of a Hub repository.",+ "Close or reopen a discussion or pull request of a Hub repository.": "Close or reopen a discussion or pull request of a Hub repository.",+ "Change the title of a discussion or pull request of a Hub repository.": "Change the title of a discussion or pull request of a Hub repository.",+ "Pin a discussion to the top of a repository Community tab, or unpin it.": "Pin a discussion to the top of a repository Community tab, or unpin it.",+ "Permanently delete a discussion or pull request from a Hub repository.": "Permanently delete a discussion or pull request from a Hub repository.",+ "Post a public comment on a research paper page on Hugging Face.": "Post a public comment on a research paper page on Hugging Face.",+ "Post a public reply to a comment on a research paper page on Hugging Face.": "Post a public reply to a comment on a research paper page on Hugging Face.",+ "Create a Hugging Face collection, or return it if one with the same title already exists.": "Create a Hugging Face collection, or return it if one with the same title already exists.",+ "Add a model, dataset, Space, paper or collection to a Hugging Face collection.": "Add a model, dataset, Space, paper or collection to a Hugging Face collection.",+ "List the access requests of a gated model or dataset by status.": "List the access requests of a gated model or dataset by status.",+ "Accept, reject, reset or re-queue a user's access request to a gated model or dataset.": "Accept, reject, reset or re-queue a user's access request to a gated model or dataset.",+ "Create or update a secret environment variable of a Hugging Face Space.": "Create or update a secret environment variable of a Hugging Face Space.",+ "Delete a secret from a Hugging Face Space.": "Delete a secret from a Hugging Face Space.",+ "Create or update a public environment variable of a Hugging Face Space.": "Create or update a public environment variable of a Hugging Face Space.",+ "Delete an environment variable from a Hugging Face Space.": "Delete an environment variable from a Hugging Face Space.",+ "List the Hugging Face notifications of the connected account.": "List the Hugging Face notifications of the connected account.",+ "Delete specific notifications from the Hugging Face inbox of the connected account.": "Delete specific notifications from the Hugging Face inbox of the connected account.",+ "Start or stop watching Hugging Face users, organizations or repositories.": "Start or stop watching Hugging Face users, organizations or repositories.",+ "List the webhooks configured on the connected Hugging Face account.": "List the webhooks configured on the connected Hugging Face account.",+ "Get one webhook of the connected Hugging Face account.": "Get one webhook of the connected Hugging Face account.",+ "Create a Hugging Face webhook that calls an https URL when watched items change.": "Create a Hugging Face webhook that calls an https URL when watched items change.",+ "Change the target URL, watched items, domains or secret of a Hugging Face webhook.": "Change the target URL, watched items, domains or secret of a Hugging Face webhook.",+ "Permanently delete a webhook from the connected Hugging Face account.": "Permanently delete a webhook from the connected Hugging Face account.",+ "Turn a Hugging Face webhook on or off without deleting it.": "Turn a Hugging Face webhook on or off without deleting it.",+ "List the dedicated Inference Endpoints of a Hugging Face user or organization.": "List the dedicated Inference Endpoints of a Hugging Face user or organization.",+ "Get the social media handles a Hugging Face user lists on their profile.": "Get the social media handles a Hugging Face user lists on their profile.",+ "Get the social media handles a Hugging Face organization lists on its profile.": "Get the social media handles a Hugging Face organization lists on its profile.",+ "Search the official Hugging Face documentation.": "Search the official Hugging Face documentation.","Model": "Model","Document Image": "Document Image","Question": "Question",@@ -197,6 +291,68 @@"Truncate": "Truncate","Truncation Direction": "Truncation Direction","Prompt Name": "Prompt Name",+ "Dataset ID": "Dataset ID",+ "Subset (Config)": "Subset (Config)",+ "Split": "Split",+ "Max Rows": "Max Rows",+ "Offset": "Offset",+ "Length": "Length",+ "Where": "Where",+ "Order By": "Order By",+ "Task ID": "Task ID",+ "Max Parameters": "Max Parameters",+ "Model Scope": "Model Scope",+ "Repository Name": "Repository Name",+ "Visibility": "Visibility",+ "Space SDK": "Space SDK",+ "Discussions": "Discussions",+ "Gated Access": "Gated Access",+ "Access Request Notifications": "Access Request Notifications",+ "Notification Email": "Notification Email",+ "Branch Name": "Branch Name",+ "Starting Point": "Starting Point",+ "Empty Branch": "Empty Branch",+ "Tag Name": "Tag Name",+ "Message": "Message",+ "Branch": "Branch",+ "Commit Title": "Commit Title",+ "Commit Description": "Commit Description",+ "Files to Write": "Files to Write",+ "Paths to Delete": "Paths to Delete",+ "Parent Commit": "Parent Commit",+ "Open as Pull Request": "Open as Pull Request",+ "Title": "Title",+ "Description": "Description",+ "Comment": "Comment",+ "New Title": "New Title",+ "Action": "Action",+ "Comment ID": "Comment ID",+ "Reply": "Reply",+ "Namespace": "Namespace",+ "Private": "Private",+ "First Item Type": "First Item Type",+ "First Item ID": "First Item ID",+ "Item Type": "Item Type",+ "Item ID": "Item ID",+ "Note": "Note",+ "Requested After": "Requested After",+ "Requested Before": "Requested Before",+ "New Status": "New Status",+ "Reason": "Reason",+ "Space ID": "Space ID",+ "Key": "Key",+ "Value": "Value",+ "Read Status": "Read Status",+ "Involvement": "Involvement",+ "Discussion IDs": "Discussion IDs",+ "Watched Items": "Watched Items",+ "Webhook ID": "Webhook ID",+ "Target URL": "Target URL",+ "Domains": "Domains",+ "Secret": "Secret",+ "New Secret": "New Secret",+ "Enabled": "Enabled",+ "Product": "Product","Hugging Face document question answering model": "Hugging Face document question answering model","Image of the document to analyze (invoice, contract, etc.)": "Image of the document to analyze (invoice, contract, etc.)","Question to ask about the document (e.g., 'What is the invoice total?')": "Question to ask about the document (e.g., 'What is the invoice total?')",@@ -358,6 +514,106 @@"Cut texts longer than the model's maximum input length instead of failing. Leave empty for the model default.": "Cut texts longer than the model's maximum input length instead of failing. Leave empty for the model default.","Which end of an over-long text to cut when truncating. Leave empty for the model default (right).": "Which end of an over-long text to cut when truncating. Leave empty for the model default (right).","Name of a prompt template defined in the model's Sentence Transformers config, for example 'query' or 'passage' for retrieval models. Leave empty when the model has none.": "Name of a prompt template defined in the model's Sentence Transformers config, for example 'query' or 'passage' for retrieval models. Leave empty when the model has none.",+ "The dataset ID in 'namespace/name' form, for example 'stanfordnlp/imdb'. Find it with Search Datasets.": "The dataset ID in 'namespace/name' form, for example 'stanfordnlp/imdb'. Find it with Search Datasets.",+ "Optional subset (config) name, for example 'plain_text'. Leave empty to cover every subset. List valid names with List Dataset Subsets & Splits.": "Optional subset (config) name, for example 'plain_text'. Leave empty to cover every subset. List valid names with List Dataset Subsets & Splits.",+ "Optional split name, for example 'train'. Only used together with a subset (config).": "Optional split name, for example 'train'. Only used together with a subset (config).",+ "The subset (config) name, for example 'plain_text' or 'default'. List valid names with List Dataset Subsets & Splits.": "The subset (config) name, for example 'plain_text' or 'default'. List valid names with List Dataset Subsets & Splits.",+ "The split name, for example 'train', 'test' or 'validation'. List valid names with List Dataset Subsets & Splits.": "The split name, for example 'train', 'test' or 'validation'. List valid names with List Dataset Subsets & Splits.",+ "How many of the first rows to return (1 to 100). Defaults to 20.": "How many of the first rows to return (1 to 100). Defaults to 20.",+ "Zero-based index of the first row to return. Use 0 for the first page, then the returned next_offset value.": "Zero-based index of the first row to return. Use 0 for the first page, then the returned next_offset value.",+ "Number of rows to return in this page (1 to 100).": "Number of rows to return in this page (1 to 100).",+ "Words to look for in the text columns, for example 'wonderful acting'.": "Words to look for in the text columns, for example 'wonderful acting'.",+ "SQL-like condition with double-quoted column names, for example \"label\"=1 or \"score\">0.5 AND \"lang\"='en'. String values use single quotes.": "SQL-like condition with double-quoted column names, for example \"label\"=1 or \"score\">0.5 AND \"lang\"='en'. String values use single quotes.",+ "Optional sort with double-quoted column names, for example \"idx\" DESC or \"score\" ASC.": "Optional sort with double-quoted column names, for example \"idx\" DESC or \"score\" ASC.",+ "Optional benchmark task for datasets with several tasks, for example 'gsm8k'. It matches the eval result file name (.eval_results/<task>.yaml). Leave empty for the default task.": "Optional benchmark task for datasets with several tasks, for example 'gsm8k'. It matches the eval result file name (.eval_results/<task>.yaml). Leave empty for the default task.",+ "Only models up to this size, for example '10B', '500M' or a raw count such as '7000000000'.": "Only models up to this size, for example '10B', '500M' or a raw count such as '7000000000'.",+ "Leave empty for the Hub default (base models only), or include fine-tuned and derived models as well.": "Leave empty for the Hub default (base models only), or include fine-tuned and derived models as well.",+ "The repository name, for example 'my-model'. You may also pass 'namespace/name' to create it under an organization.": "The repository name, for example 'my-model'. You may also pass 'namespace/name' to create it under an organization.",+ "Optional organization to create the repository in. Leave empty to create it under the connected user.": "Optional organization to create the repository in. Leave empty to create it under the connected user.",+ "Private (default) or Public. Public repositories are visible to everyone, so choose Public only when explicitly asked.": "Private (default) or Public. Public repositories are visible to everyone, so choose Public only when explicitly asked.",+ "Required when Repository Type is 'space': the framework the Space runs. 'static' is free for everyone; 'gradio' and 'docker' need a PRO/Team subscription or billing. Ignored for models and datasets.": "Required when Repository Type is 'space': the framework the Space runs. 'static' is free for everyone; 'gradio' and 'docker' need a PRO/Team subscription or billing. Ignored for models and datasets.",+ "Leave empty to keep the current visibility. Public makes the repository and all its files visible to everyone.": "Leave empty to keep the current visibility. Public makes the repository and all its files visible to everyone.",+ "Leave empty to keep the current setting. Disabled hides the Community tab and blocks new discussions.": "Leave empty to keep the current setting. Disabled hides the Community tab and blocks new discussions.",+ "Leave empty to keep the current gate. 'Automatic approval' and 'Manual approval' require users to request access; 'Not gated' removes the gate. Not available for Spaces.": "Leave empty to keep the current gate. 'Automatic approval' and 'Manual approval' require users to request access; 'Not gated' removes the gate. Not available for Spaces.",+ "Leave empty to keep the current mode. How the owner is notified of new gated-access requests.": "Leave empty to keep the current mode. How the owner is notified of new gated-access requests.",+ "Leave empty to keep the current address. The email address that receives gated-access request notifications.": "Leave empty to keep the current address. The email address that receives gated-access request notifications.",+ "The name of the new branch, for example 'dev' or 'experiment-1'.": "The name of the new branch, for example 'dev' or 'experiment-1'.",+ "Optional branch, tag or commit SHA the new branch starts from, for example 'main' or 'v1.0'. Leave empty to start from the default branch.": "Optional branch, tag or commit SHA the new branch starts from, for example 'main' or 'v1.0'. Leave empty to start from the default branch.",+ "Create the branch with no history and no files instead of copying a starting point.": "Create the branch with no history and no files instead of copying a starting point.",+ "The branch to delete, for example 'dev'. The 'main' branch cannot be deleted with this action.": "The branch to delete, for example 'dev'. The 'main' branch cannot be deleted with this action.",+ "The tag to create, for example 'v1.0'.": "The tag to create, for example 'v1.0'.",+ "The branch, tag or commit SHA to tag, for example 'main', 'dev' or a commit SHA. Get branch names from List Branches & Tags and commit SHAs from List Repo Commits.": "The branch, tag or commit SHA to tag, for example 'main', 'dev' or a commit SHA. Get branch names from List Branches & Tags and commit SHAs from List Repo Commits.",+ "Optional annotation message stored with the tag.": "Optional annotation message stored with the tag.",+ "The tag to delete, for example 'v1.0'.": "The tag to delete, for example 'v1.0'.",+ "The branch to commit to, for example 'main', 'dev', or 'refs/pr/3' to add a commit to an open pull request. Get the branch names from List Branches & Tags.": "The branch to commit to, for example 'main', 'dev', or 'refs/pr/3' to add a commit to an open pull request. Get the branch names from List Branches & Tags.",+ "A one-line commit summary, for example 'Update README'. Also used as the pull request title.": "A one-line commit summary, for example 'Update README'. Also used as the pull request title.",+ "Optional longer commit message. Also used as the pull request description.": "Optional longer commit message. Also used as the pull request description.",+ "Text files to create or overwrite. Each needs a repository path and its content; binary files and anything over 1 MiB in total are refused.": "Text files to create or overwrite. Each needs a repository path and its content; binary files and anything over 1 MiB in total are refused.",+ "Repository paths to delete in the same commit, for example 'old_notes.txt'. Deleted files are removed from the branch.": "Repository paths to delete in the same commit, for example 'old_notes.txt'. Deleted files are removed from the branch.",+ "Optional 40-character commit SHA the branch must still point to. If someone committed since, the commit fails instead of overwriting their change. Get it from List Repo Commits.": "Optional 40-character commit SHA the branch must still point to. If someone committed since, the commit fails instead of overwriting their change. Get it from List Repo Commits.",+ "Open a pull request with this commit instead of writing directly to the branch.": "Open a pull request with this commit instead of writing directly to the branch.",+ "The discussion title, 3 to 200 characters.": "The discussion title, 3 to 200 characters.",+ "The opening message, in Markdown (up to 65,536 characters).": "The opening message, in Markdown (up to 65,536 characters).",+ "Open an empty draft pull request instead of a discussion.": "Open an empty draft pull request instead of a discussion.",+ "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).": "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ "The comment text, in Markdown (up to 65,536 characters).": "The comment text, in Markdown (up to 65,536 characters).",+ "The new status: Closed or Open (reopen).": "The new status: Closed or Open (reopen).",+ "Optional public comment posted with the status change, for example the reason for closing.": "Optional public comment posted with the status change, for example the reason for closing.",+ "The new title, 3 to 200 characters.": "The new title, 3 to 200 characters.",+ "Pin or unpin the discussion.": "Pin or unpin the discussion.",+ "The paper's arXiv ID, for example '2307.09288'. Find it with Search Papers or List Daily Papers.": "The paper's arXiv ID, for example '2307.09288'. Find it with Search Papers or List Daily Papers.",+ "The public comment text, in Markdown (up to 65,536 characters).": "The public comment text, in Markdown (up to 65,536 characters).",+ "The ID of the comment to reply to, from Get Paper with Include Comments on.": "The ID of the comment to reply to, from Get Paper with Include Comments on.",+ "The public reply text, in Markdown (up to 65,536 characters).": "The public reply text, in Markdown (up to 65,536 characters).",+ "The collection title, 1 to 60 characters.": "The collection title, 1 to 60 characters.",+ "The user or organization that owns the collection. Leave empty for the connected user.": "The user or organization that owns the collection. Leave empty for the connected user.",+ "Optional short description, up to 150 characters.": "Optional short description, up to 150 characters.",+ "Keep the collection private (default). Turn off only to publish it to everyone.": "Keep the collection private (default). Turn off only to publish it to everyone.",+ "Optional type of an item to add right away. Requires First Item ID.": "Optional type of an item to add right away. Requires First Item ID.",+ "Optional ID of the first item: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug. Requires First Item Type.": "Optional ID of the first item: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug. Requires First Item Type.",+ "The full collection slug in 'namespace/title-id' form, for example 'my-user/my-picks-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).": "The full collection slug in 'namespace/title-id' form, for example 'my-user/my-picks-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).",+ "The kind of item to add.": "The kind of item to add.",+ "The item to add: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug.": "The item to add: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug.",+ "Optional note shown next to the item, up to 500 characters.": "Optional note shown next to the item, up to 500 characters.",+ "Gated access exists for models and datasets only.": "Gated access exists for models and datasets only.",+ "Which requests to list. Defaults to pending.": "Which requests to list. Defaults to pending.",+ "Only requests whose requester username, full name, email, email domain or verified organization matches this text.": "Only requests whose requester username, full name, email, email domain or verified organization matches this text.",+ "Only requests made after this date and time (ISO 8601).": "Only requests made after this date and time (ISO 8601).",+ "Only requests made before this date and time (ISO 8601).": "Only requests made before this date and time (ISO 8601).",+ "Maximum number of requests to return (10 to 1000). Defaults to 100.": "Maximum number of requests to return (10 to 1000). Defaults to 100.",+ "The Hub username of the requester, for example 'julien-c' (the 'username' from List Gated Access Requests).": "The Hub username of the requester, for example 'julien-c' (the 'username' from List Gated Access Requests).",+ "Accepted grants access; Rejected refuses it; Pending moves it back to the queue; Reset clears it so the user must request again.": "Accepted grants access; Rejected refuses it; Pending moves it back to the queue; Reset clears it so the user must request again.",+ "Optional reason shown to the requester, up to 200 characters. Only used with Rejected or Reset.": "Optional reason shown to the requester, up to 200 characters. Only used with Rejected or Reset.",+ "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.": "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.",+ "The secret name: starts with a letter, then letters, digits or underscores, for example 'OPENAI_API_KEY'.": "The secret name: starts with a letter, then letters, digits or underscores, for example 'OPENAI_API_KEY'.",+ "The secret value. It is stored encrypted and never shown again.": "The secret value. It is stored encrypted and never shown again.",+ "Optional note about what the secret is for.": "Optional note about what the secret is for.",+ "The name of the secret to delete, for example 'OPENAI_API_KEY'.": "The name of the secret to delete, for example 'OPENAI_API_KEY'.",+ "The variable name: starts with a letter, then letters, digits or underscores, for example 'MODEL_NAME'.": "The variable name: starts with a letter, then letters, digits or underscores, for example 'MODEL_NAME'.",+ "The variable value. It is visible to anyone who can see the Space.": "The variable value. It is visible to anyone who can see the Space.",+ "Optional note about what the variable is for.": "Optional note about what the variable is for.",+ "The name of the variable to delete, for example 'MODEL_NAME'.": "The name of the variable to delete, for example 'MODEL_NAME'.",+ "Return all notifications or only unread ones. Defaults to all.": "Return all notifications or only unread ones. Defaults to all.",+ "All notifications, only threads the user participates in, or only threads where the user is mentioned. Defaults to all.": "All notifications, only threads the user participates in, or only threads where the user is mentioned. Defaults to all.",+ "Only notifications about this kind of repository. Leave empty for every kind.": "Only notifications about this kind of repository. Leave empty for every kind.",+ "Only notifications about this repository, in 'namespace/name' form, for example 'openai-community/gpt2'.": "Only notifications about this repository, in 'namespace/name' form, for example 'openai-community/gpt2'.",+ "The 24-character hexadecimal discussion_id of each notification to delete, for example '6390e855e30d9209411de93b'. Get them from List Notifications.": "The 24-character hexadecimal discussion_id of each notification to delete, for example '6390e855e30d9209411de93b'. Get them from List Notifications.",+ "Users, organizations or repositories to start watching.": "Users, organizations or repositories to start watching.",+ "Users, organizations or repositories to stop watching.": "Users, organizations or repositories to stop watching.",+ "The webhook's 24-character hexadecimal ID. Find it with List Webhooks.": "The webhook's 24-character hexadecimal ID. Find it with List Webhooks.",+ "The https:// address the Hub will POST events to.": "The https:// address the Hub will POST events to.",+ "The users, organizations or repositories whose changes trigger the webhook. At least one.": "The users, organizations or repositories whose changes trigger the webhook. At least one.",+ "Which kinds of events to send: repository changes, discussion and pull-request activity, or both.": "Which kinds of events to send: repository changes, discussion and pull-request activity, or both.",+ "Optional shared secret, sent in the X-Webhook-Secret header of every delivery. Printable ASCII only. It cannot be read back later.": "Optional shared secret, sent in the X-Webhook-Secret header of every delivery. Printable ASCII only. It cannot be read back later.",+ "New https:// address for deliveries. Leave empty to keep the current URL.": "New https:// address for deliveries. Leave empty to keep the current URL.",+ "Replaces the full list of watched users, organizations and repositories. Leave empty to keep the current list.": "Replaces the full list of watched users, organizations and repositories. Leave empty to keep the current list.",+ "Replaces the event domains. Leave empty to keep the current domains.": "Replaces the event domains. Leave empty to keep the current domains.",+ "A new shared secret for the X-Webhook-Secret header. Leave empty to not send one. Printable ASCII only.": "A new shared secret for the X-Webhook-Secret header. Leave empty to not send one. Printable ASCII only.",+ "Checked to enable the webhook, unchecked to disable it.": "Checked to enable the webhook, unchecked to disable it.",+ "The user or organization that owns the endpoints, for example 'my-org'. Leave empty for the connected user. Get organization names from Get Current User & Token.": "The user or organization that owns the endpoints, for example 'my-org'. Leave empty for the connected user. Get organization names from Get Current User & Token.",+ "What to look for, in plain words, for example 'webhook secret header'. Up to 250 characters.": "What to look for, in plain words, for example 'webhook secret header'. Up to 250 characters.",+ "Only search the documentation of this product. Leave empty to search all of them.": "Only search the documentation of this product. Leave empty to search all of them.",+ "Maximum number of passages to return (1 to 25). Defaults to 10.": "Maximum number of passages to return (1 to 25). Defaults to 10.","impira/layoutlm-document-qa (Recommended)": "impira/layoutlm-document-qa (Recommended)","microsoft/layoutlmv3-base": "microsoft/layoutlmv3-base","nielsr/layoutlmv2-finetuned-docvqa": "nielsr/layoutlmv2-finetuned-docvqa",@@ -469,7 +725,6 @@"Spaces": "Spaces","Dataset": "Dataset","Space": "Space",- "Discussions": "Discussions","Pull Requests": "Pull Requests","Open": "Open","Closed": "Closed",@@ -500,5 +755,91 @@"Yes": "Yes","No": "No","Right (keep the start)": "Right (keep the start)",- "Left (keep the end)": "Left (keep the end)"+ "Left (keep the end)": "Left (keep the end)",+ "Base models only": "Base models only",+ "Include fine-tuned models": "Include fine-tuned models",+ "Public": "Public",+ "Static (HTML)": "Static (HTML)",+ "Gradio": "Gradio",+ "Docker": "Docker",+ "Disabled": "Disabled",+ "Not gated": "Not gated",+ "Automatic approval": "Automatic approval",+ "Manual approval": "Manual approval",+ "Real-time (one email per request)": "Real-time (one email per request)",+ "Bulk (daily digest)": "Bulk (daily digest)",+ "Pin": "Pin",+ "Unpin": "Unpin",+ "Paper": "Paper",+ "Collection": "Collection",+ "Pending": "Pending",+ "Accepted": "Accepted",+ "Rejected": "Rejected",+ "Reset": "Reset",+ "Unread only": "Unread only",+ "Participating": "Participating",+ "Mentions": "Mentions",+ "Repository changes (commits, tags, settings)": "Repository changes (commits, tags, settings)",+ "Discussions and pull requests": "Discussions and pull requests",+ "hub": "hub",+ "transformers": "transformers",+ "diffusers": "diffusers",+ "datasets": "datasets",+ "gradio": "gradio",+ "trackio": "trackio",+ "smolagents": "smolagents",+ "huggingface_hub": "huggingface_hub",+ "cli": "cli",+ "huggingface.js": "huggingface.js",+ "transformers.js": "transformers.js",+ "inference-providers": "inference-providers",+ "inference-endpoints": "inference-endpoints",+ "peft": "peft",+ "accelerate": "accelerate",+ "optimum": "optimum",+ "optimum-habana": "optimum-habana",+ "optimum-neuron": "optimum-neuron",+ "optimum-intel": "optimum-intel",+ "optimum-executorch": "optimum-executorch",+ "optimum-tpu": "optimum-tpu",+ "tokenizers": "tokenizers",+ "llm-course": "llm-course",+ "context-course": "context-course",+ "robotics-course": "robotics-course",+ "mcp-course": "mcp-course",+ "smol-course": "smol-course",+ "agents-course": "agents-course",+ "deep-rl-course": "deep-rl-course",+ "computer-vision-course": "computer-vision-course",+ "evaluate": "evaluate",+ "tasks": "tasks",+ "dataset-viewer": "dataset-viewer",+ "trl": "trl",+ "openenv": "openenv",+ "simulate": "simulate",+ "sagemaker": "sagemaker",+ "timm": "timm",+ "safetensors": "safetensors",+ "tgi": "tgi",+ "setfit": "setfit",+ "audio-course": "audio-course",+ "lerobot": "lerobot",+ "reachy_mini": "reachy_mini",+ "autotrain": "autotrain",+ "tei": "tei",+ "bitsandbytes": "bitsandbytes",+ "cookbook": "cookbook",+ "sentence_transformers": "sentence_transformers",+ "ml-games-course": "ml-games-course",+ "diffusion-course": "diffusion-course",+ "ml-for-3d-course": "ml-for-3d-course",+ "chat-ui": "chat-ui",+ "leaderboards": "leaderboards",+ "lighteval": "lighteval",+ "argilla": "argilla",+ "distilabel": "distilabel",+ "microsoft-azure": "microsoft-azure",+ "kernels": "kernels",+ "google-cloud": "google-cloud",+ "xet": "xet"}\ No newline at end of filediff --git a/packages/pieces/community/hugging-face/src/index.ts b/packages/pieces/community/hugging-face/src/index.tsindex ce7e6b4cbe0..8bdddd5d9e1 100644--- a/packages/pieces/community/hugging-face/src/index.ts+++ b/packages/pieces/community/hugging-face/src/index.ts@@ -37,6 +37,53 @@ import { listCollections } from './lib/actions/list-collections';import { getCollection } from './lib/actions/get-collection';import { generateChatCompletion } from './lib/actions/generate-chat-completion';import { generateEmbeddings } from './lib/actions/generate-embeddings';+import { checkDatasetViewerSupport } from './lib/actions/check-dataset-viewer-support';+import { listDatasetSplits } from './lib/actions/list-dataset-splits';+import { previewDatasetRows } from './lib/actions/preview-dataset-rows';+import { getDatasetRows } from './lib/actions/get-dataset-rows';+import { searchDatasetRows } from './lib/actions/search-dataset-rows';+import { filterDatasetRows } from './lib/actions/filter-dataset-rows';+import { getDatasetViewerInfo } from './lib/actions/get-dataset-viewer-info';+import { getDatasetSize } from './lib/actions/get-dataset-size';+import { getDatasetStatistics } from './lib/actions/get-dataset-statistics';+import { listDatasetParquetFiles } from './lib/actions/list-dataset-parquet-files';+import { getDatasetLeaderboard } from './lib/actions/get-dataset-leaderboard';+import { createRepo } from './lib/actions/create-repo';+import { updateRepoSettings } from './lib/actions/update-repo-settings';+import { createRepoBranch } from './lib/actions/create-repo-branch';+import { deleteRepoBranch } from './lib/actions/delete-repo-branch';+import { createRepoTag } from './lib/actions/create-repo-tag';+import { deleteRepoTag } from './lib/actions/delete-repo-tag';+import { commitFiles } from './lib/actions/commit-files';+import { createDiscussion } from './lib/actions/create-discussion';+import { commentOnDiscussion } from './lib/actions/comment-on-discussion';+import { changeDiscussionStatus } from './lib/actions/change-discussion-status';+import { renameDiscussion } from './lib/actions/rename-discussion';+import { pinDiscussion } from './lib/actions/pin-discussion';+import { deleteDiscussion } from './lib/actions/delete-discussion';+import { commentOnPaper } from './lib/actions/comment-on-paper';+import { replyToPaperComment } from './lib/actions/reply-to-paper-comment';+import { createCollection } from './lib/actions/create-collection';+import { addCollectionItem } from './lib/actions/add-collection-item';+import { listGatedAccessRequests } from './lib/actions/list-gated-access-requests';+import { handleGatedAccessRequest } from './lib/actions/handle-gated-access-request';+import { upsertSpaceSecret } from './lib/actions/upsert-space-secret';+import { deleteSpaceSecret } from './lib/actions/delete-space-secret';+import { upsertSpaceVariable } from './lib/actions/upsert-space-variable';+import { deleteSpaceVariable } from './lib/actions/delete-space-variable';+import { listNotifications } from './lib/actions/list-notifications';+import { deleteNotifications } from './lib/actions/delete-notifications';+import { updateWatchList } from './lib/actions/update-watch-list';+import { listWebhooks } from './lib/actions/list-webhooks';+import { getWebhook } from './lib/actions/get-webhook';+import { createWebhook } from './lib/actions/create-webhook';+import { updateWebhook } from './lib/actions/update-webhook';+import { deleteWebhook } from './lib/actions/delete-webhook';+import { setWebhookEnabled } from './lib/actions/set-webhook-enabled';+import { listInferenceEndpoints } from './lib/actions/list-inference-endpoints';+import { getUserSocials } from './lib/actions/get-user-socials';+import { getOrganizationSocials } from './lib/actions/get-organization-socials';+import { searchHfDocs } from './lib/actions/search-hf-docs';import { huggingFaceAuth } from './lib/auth';export const huggingface = createPiece({@@ -86,6 +133,53 @@ export const huggingface = createPiece({getCollection,generateChatCompletion,generateEmbeddings,+ checkDatasetViewerSupport,+ listDatasetSplits,+ previewDatasetRows,+ getDatasetRows,+ searchDatasetRows,+ filterDatasetRows,+ getDatasetViewerInfo,+ getDatasetSize,+ getDatasetStatistics,+ listDatasetParquetFiles,+ getDatasetLeaderboard,+ createRepo,+ updateRepoSettings,+ createRepoBranch,+ deleteRepoBranch,+ createRepoTag,+ deleteRepoTag,+ commitFiles,+ createDiscussion,+ commentOnDiscussion,+ changeDiscussionStatus,+ renameDiscussion,+ pinDiscussion,+ deleteDiscussion,+ commentOnPaper,+ replyToPaperComment,+ createCollection,+ addCollectionItem,+ listGatedAccessRequests,+ handleGatedAccessRequest,+ upsertSpaceSecret,+ deleteSpaceSecret,+ upsertSpaceVariable,+ deleteSpaceVariable,+ listNotifications,+ deleteNotifications,+ updateWatchList,+ listWebhooks,+ getWebhook,+ createWebhook,+ updateWebhook,+ deleteWebhook,+ setWebhookEnabled,+ listInferenceEndpoints,+ getUserSocials,+ getOrganizationSocials,+ searchHfDocs,],triggers: [],});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/add-collection-item.ts b/packages/pieces/community/hugging-face/src/lib/actions/add-collection-item.tsnew file mode 100644index 00000000000..362240dffb3--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/add-collection-item.ts@@ -0,0 +1,91 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { addCollectionItemOutputSchema } from '../output-schemas';++export const addCollectionItem = createAction({+ auth: huggingFaceAuth,+ name: 'add_collection_item',+ classification: 'WRITE',+ displayName: 'Add Item to Collection',+ description: 'Add a model, dataset, Space, paper or collection to a Hugging Face collection.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Adds one model, dataset, Space, paper or nested collection to an existing collection, with an optional note. Get the collection slug from Create Collection, List Collections or the collection URL. If the Hub reports the item as already present the call fails with ITEM_ALREADY_IN_COLLECTION; before retrying a failed call, check the items with Get Collection. Requires a write-role token with write access to the collection owner.",+ idempotent: false,+ },+ outputSchema: addCollectionItemOutputSchema,+ props: {+ slug: Property.ShortText({+ displayName: 'Collection Slug',+ description:+ "The full collection slug in 'namespace/title-id' form, for example 'my-user/my-picks-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).",+ required: true,+ }),+ item_type: Property.StaticDropdown({+ displayName: 'Item Type',+ description: 'The kind of item to add.',+ required: true,+ defaultValue: 'model',+ options: {+ disabled: false,+ options: [+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ { label: 'Space', value: 'space' },+ { label: 'Paper', value: 'paper' },+ { label: 'Collection', value: 'collection' },+ ],+ },+ }),+ item_id: Property.ShortText({+ displayName: 'Item ID',+ description:+ "The item to add: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug.",+ required: true,+ }),+ note: Property.LongText({+ displayName: 'Note',+ description: 'Optional note shown next to the item, up to 500 characters.',+ required: false,+ }),+ },+ async run(context) {+ const { slug, item_type, item_id, note } = context.propsValue;+ const collectionSlug = hfWrite.parseCollectionSlug(slug);+ const itemId = hfWrite.requireText({ value: item_id, name: 'Item ID' });+ const itemNote = hfWrite.optionalText({ value: note, name: 'Note', maxLength: 500 });+ const body: Record<string, unknown> = { item: { type: item_type, id: itemId } };+ if (itemNote !== undefined) {+ body['note'] = itemNote;+ }+ const response = await hfWrite.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `${hfWrite.collectionApiPath(collectionSlug)}/items`,+ body,+ statusErrors: {+ 409: (detail) =>+ new Error(+ `ITEM_ALREADY_IN_COLLECTION: '${itemId}' is already in ${collectionSlug}.${detail ? ` Details: ${detail}` : ''}`+ ),+ },+ });+ const record = hfHub.isRecord(response) ? response : {};+ const items = Array.isArray(record['items']) ? record['items'] : [];+ const added = items.find(+ (item) => hfWrite.readString({ record: item, key: 'id' }) === itemId && hfWrite.readString({ record: item, key: 'type' }) === item_type+ );+ return {+ slug: collectionSlug,+ item_type,+ item_id: itemId,+ item_object_id: hfWrite.readString({ record: added, key: '_id' }),+ item_count: items.length,+ url: `${hfHub.baseUrl}/collections/${collectionSlug}`,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/change-discussion-status.ts b/packages/pieces/community/hugging-face/src/lib/actions/change-discussion-status.tsnew file mode 100644index 00000000000..9d21ec33bdc--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/change-discussion-status.ts@@ -0,0 +1,78 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { changeDiscussionStatusOutputSchema } from '../output-schemas';++export const changeDiscussionStatus = createAction({+ auth: huggingFaceAuth,+ name: 'change_discussion_status',+ classification: 'WRITE',+ displayName: 'Open or Close Discussion',+ description: 'Close or reopen a discussion or pull request of a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Closes or reopens a discussion or pull request of a model, dataset or Space repository, optionally with a public closing comment. Closing is the reversible alternative to Delete Discussion, so prefer it. Every call records a new status event and re-posts the comment, so avoid blind retries. Requires a write-role token and being the thread author or having write access to the repository.",+ idempotent: false,+ },+ outputSchema: changeDiscussionStatusOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ discussion_number: Property.Number({+ displayName: 'Discussion Number',+ description: "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ required: true,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'The new status: Closed or Open (reopen).',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Closed', value: 'closed' },+ { label: 'Open', value: 'open' },+ ],+ },+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'Optional public comment posted with the status change, for example the reason for closing.',+ required: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, discussion_number, status, comment } = context.propsValue;+ const token = context.auth.secret_text;+ const num = hfWrite.assertDiscussionNumber(discussion_number);+ if (status !== 'open' && status !== 'closed') {+ throw new Error("Status must be 'open' or 'closed'.");+ }+ const text = hfWrite.optionalText({ value: comment, name: 'Comment', maxLength: 65536 });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const body: Record<string, unknown> = { status };+ if (text !== undefined) {+ body['comment'] = text;+ }+ const response = await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/discussions/${num}/status`,+ body,+ });+ const event = hfHub.isRecord(response) ? response['newStatus'] : undefined;+ const data = hfHub.isRecord(event) ? event['data'] : undefined;+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ status: hfWrite.readString({ record: data, key: 'status' }) ?? status,+ event_id: hfWrite.readString({ record: event, key: 'id' }),+ created_at: hfWrite.readString({ record: event, key: 'createdAt' }),+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/check-dataset-viewer-support.ts b/packages/pieces/community/hugging-face/src/lib/actions/check-dataset-viewer-support.tsnew file mode 100644index 00000000000..95ad938c395--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/check-dataset-viewer-support.ts@@ -0,0 +1,39 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { checkDatasetViewerSupportOutputSchema } from '../output-schemas';++export const checkDatasetViewerSupport = createAction({+ auth: huggingFaceAuth,+ name: 'check_dataset_viewer_support',+ classification: 'READ',+ displayName: 'Check Dataset Viewer Support',+ description: 'Check which dataset viewer features (preview, rows, search, filter, statistics) a dataset supports.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Capability gate for every dataset viewer action: returns five booleans, preview (Preview Dataset Rows), viewer (Get Dataset Rows, parquet, size, info), search (Search Dataset Rows), filter (Filter Dataset Rows) and statistics (Get Column Statistics), optionally narrowed to one subset or split. Call it first whenever you are unsure whether a dataset is served. Private datasets are only served for PRO or Enterprise owners, gated ones only after access is granted. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: checkDatasetViewerSupportOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.optionalConfig(),+ split: hfViewerProps.optionalSplit(),+ },+ async run(context) {+ const { dataset, config, split } = context.propsValue;+ if (split?.trim() && !config?.trim()) {+ throw new Error('Split can only be checked together with a subset (config). Set Subset (Config) or clear Split.');+ }+ return hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/is-valid',+ dataset,+ query: [+ ['config', config?.trim()],+ ['split', split?.trim()],+ ],+ });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/comment-on-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/comment-on-discussion.tsnew file mode 100644index 00000000000..2f8497e00ff--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/comment-on-discussion.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { commentOnDiscussionOutputSchema } from '../output-schemas';++export const commentOnDiscussion = createAction({+ auth: huggingFaceAuth,+ name: 'comment_on_discussion',+ classification: 'WRITE',+ displayName: 'Comment on Discussion',+ description: 'Post a comment on a discussion or pull request of a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Posts a new comment on an existing discussion or pull request of a model, dataset or Space repository, publicly under the connected user's name. Get the discussion number from List Discussions & PRs. Each call adds another comment, so retries duplicate. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: commentOnDiscussionOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ discussion_number: Property.Number({+ displayName: 'Discussion Number',+ description: "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ required: true,+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'The comment text, in Markdown (up to 65,536 characters).',+ required: true,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, discussion_number, comment } = context.propsValue;+ const token = context.auth.secret_text;+ const num = hfWrite.assertDiscussionNumber(discussion_number);+ const text = hfWrite.requireText({ value: comment, name: 'Comment', maxLength: 65536 });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const response = await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/discussions/${num}/comment`,+ body: { comment: text },+ });+ const newMessage = hfHub.isRecord(response) ? response['newMessage'] : undefined;+ const commentId = hfWrite.readString({ record: newMessage, key: 'id' });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ comment_id: commentId,+ created_at: hfWrite.readString({ record: newMessage, key: 'createdAt' }),+ url: `${repo.webUrl}/discussions/${num}${commentId ? `#${commentId}` : ''}`,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/comment-on-paper.ts b/packages/pieces/community/hugging-face/src/lib/actions/comment-on-paper.tsnew file mode 100644index 00000000000..8edfc72618f--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/comment-on-paper.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { commentOnPaperOutputSchema } from '../output-schemas';++export const commentOnPaper = createAction({+ auth: huggingFaceAuth,+ name: 'comment_on_paper',+ classification: 'WRITE',+ displayName: 'Comment on Paper',+ description: 'Post a public comment on a research paper page on Hugging Face.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Posts a new top-level comment on a Hugging Face Papers page, publicly and permanently visible to everyone under the connected user's name. Only post when the user explicitly asks and approves the text. To answer an existing comment use Reply to Paper Comment instead. Each call adds another comment, so retries duplicate. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: commentOnPaperOutputSchema,+ props: {+ paper_id: Property.ShortText({+ displayName: 'Paper ID',+ description: "The paper's arXiv ID, for example '2307.09288'. Find it with Search Papers or List Daily Papers.",+ required: true,+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'The public comment text, in Markdown (up to 65,536 characters).',+ required: true,+ }),+ },+ async run(context) {+ const { paper_id, comment } = context.propsValue;+ const paperId = hfWrite.requireText({ value: paper_id, name: 'Paper ID' });+ const text = hfWrite.requireText({ value: comment, name: 'Comment', maxLength: 65536 });+ const response = await hfWrite.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/api/papers/${encodeURIComponent(paperId)}/comment`,+ body: { comment: text },+ });+ const newMessage = hfHub.isRecord(response) ? response['newMessage'] : undefined;+ const commentId = hfWrite.readString({ record: newMessage, key: 'id' });+ return {+ paper_id: paperId,+ comment_id: commentId,+ created_at: hfWrite.readString({ record: newMessage, key: 'createdAt' }),+ url: `${hfHub.baseUrl}/papers/${encodeURIComponent(paperId)}${commentId ? `#${commentId}` : ''}`,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/commit-files.ts b/packages/pieces/community/hugging-face/src/lib/actions/commit-files.tsnew file mode 100644index 00000000000..1043a096068--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/commit-files.ts@@ -0,0 +1,266 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { hfRepo } from '../common/repo';+import { hfUtils } from '../common/utils';+import { commitFilesOutputSchema } from '../output-schemas';++function normalizeRepoPath({ value, label }: { value: unknown; label: string }): string {+ if (typeof value !== 'string') {+ throw new Error(`${label} must be a text file path, for example 'README.md' or 'src/app.py'.`);+ }+ const path = value.trim().replace(/^\/+/, '');+ const segments = path.split('/');+ if (path.length === 0 || segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) {+ throw new Error(+ `${label} '${value}' is not a valid repository path. Use a relative path like 'README.md' or 'data/train.csv', without '..' or empty segments.`+ );+ }+ if (path.length > MAX_PATH_LENGTH) {+ throw new Error(`${label} '${path.slice(0, 80)}...' is longer than ${MAX_PATH_LENGTH} characters.`);+ }+ return path;+}++function lfsRequiredError({ path, reason }: { path: string; reason: string }): Error {+ return new Error(+ `LFS_UPLOAD_REQUIRED: '${path}' ${reason}. Large or binary files need the Hub's LFS upload flow, which is not supported; Commit Files only accepts inline text files up to ${MAX_TOTAL_BYTES} bytes in total.`+ );+}++function isBinary(buffer: Buffer): boolean {+ if (buffer.includes(0)) {+ return true;+ }+ try {+ new TextDecoder('utf-8', { fatal: true }).decode(buffer);+ return false;+ } catch {+ return true;+ }+}++function decodeBase64({ path, content }: { path: string; content: string }): Buffer {+ const compact = content.replace(/\s+/g, '');+ if (compact.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) {+ throw new Error(`The content of '${path}' is not valid base64. Use encoding 'utf-8' for plain text.`);+ }+ return Buffer.from(compact, 'base64');+}++function parseFiles(value: unknown[] | undefined): PreparedFiles {+ const files: CommitFile[] = [];+ let totalBytes = 0;+ for (const [index, item] of (value ?? []).entries()) {+ if (!hfHub.isRecord(item)) {+ throw new Error(`File #${index + 1} must be an object with 'path', 'content' and optional 'encoding'.`);+ }+ const path = normalizeRepoPath({ value: item['path'], label: `File #${index + 1} path` });+ const content = item['content'];+ if (typeof content !== 'string') {+ throw new Error(`File '${path}' has no text content. Pass the file body as 'content'.`);+ }+ const rawEncoding = item['encoding'];+ const encoding = rawEncoding === undefined || rawEncoding === null || rawEncoding === '' ? 'utf-8' : rawEncoding;+ if (encoding !== 'utf-8' && encoding !== 'base64') {+ throw new Error(`File '${path}' has an unknown encoding '${String(rawEncoding)}'. Use 'utf-8' or 'base64'.`);+ }+ const bytes = encoding === 'base64' ? decodeBase64({ path, content }) : Buffer.from(content, 'utf-8');+ if (isBinary(bytes)) {+ throw lfsRequiredError({ path, reason: 'is a binary file' });+ }+ if (bytes.length > MAX_TOTAL_BYTES) {+ throw lfsRequiredError({ path, reason: `is ${bytes.length} bytes` });+ }+ totalBytes += bytes.length;+ files.push({ path, content, encoding });+ }+ if (totalBytes > MAX_TOTAL_BYTES) {+ throw lfsRequiredError({ path: files.map((file) => file.path).join("', '"), reason: `add up to ${totalBytes} bytes` });+ }+ return { files, totalBytes };+}++function assertUniquePaths({ filePaths, deletedPaths }: { filePaths: string[]; deletedPaths: string[] }): void {+ const seen = new Set<string>();+ for (const path of [...filePaths, ...deletedPaths]) {+ if (seen.has(path)) {+ throw new Error(`The path '${path}' appears more than once. Each path can be written or deleted only once per commit.`);+ }+ seen.add(path);+ }+}++function pullRequestNumber(url: string | null): number | null {+ const match = url?.match(/\/discussions\/(\d+)/);+ return match ? Number(match[1]) : null;+}++export const commitFiles = createAction({+ auth: huggingFaceAuth,+ name: 'commit_files',+ classification: 'WRITE',+ displayName: 'Commit Files',+ description: 'Create, update or delete text files in a Hub repository in a single commit, optionally as a pull request.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Writes one commit to a branch of a model, dataset or Space repository: adds or overwrites small inline text files (utf-8 or base64 text, 1 MiB total) and can delete paths in the same commit, which is destructive for the deleted files. Binary or large files are refused (LFS uploads are not supported). Turn on Open as Pull Request to propose the change instead of writing to the branch (the safe mode on repositories the user does not own; returns pullRequestUrl); set Parent Commit to fail rather than overwrite a concurrent edit. Each call creates a new commit, so retries duplicate. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: commitFilesOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ branch: Property.ShortText({+ displayName: 'Branch',+ description:+ "The branch to commit to, for example 'main', 'dev', or 'refs/pr/3' to add a commit to an open pull request. Get the branch names from List Branches & Tags.",+ required: true,+ }),+ summary: Property.ShortText({+ displayName: 'Commit Title',+ description: "A one-line commit summary, for example 'Update README'. Also used as the pull request title.",+ required: true,+ }),+ commit_description: Property.LongText({+ displayName: 'Commit Description',+ description: 'Optional longer commit message. Also used as the pull request description.',+ required: false,+ }),+ files: Property.Array({+ displayName: 'Files to Write',+ description:+ 'Text files to create or overwrite. Each needs a repository path and its content; binary files and anything over 1 MiB in total are refused.',+ required: false,+ properties: {+ path: Property.ShortText({+ displayName: 'Path',+ description: "Path inside the repository, for example 'README.md' or 'src/app.py'.",+ required: true,+ }),+ content: Property.LongText({+ displayName: 'Content',+ description: 'The full file content. It replaces the file if it exists.',+ required: true,+ }),+ encoding: Property.StaticDropdown({+ displayName: 'Encoding',+ description: "'utf-8' for plain text (default) or 'base64' when the content is base64-encoded text.",+ required: false,+ defaultValue: 'utf-8',+ options: {+ disabled: false,+ options: [+ { label: 'UTF-8 text', value: 'utf-8' },+ { label: 'Base64', value: 'base64' },+ ],+ },+ }),+ },+ }),+ deleted_paths: Property.Array({+ displayName: 'Paths to Delete',+ description: "Repository paths to delete in the same commit, for example 'old_notes.txt'. Deleted files are removed from the branch.",+ required: false,+ }),+ parent_commit: Property.ShortText({+ displayName: 'Parent Commit',+ description:+ 'Optional 40-character commit SHA the branch must still point to. If someone committed since, the commit fails instead of overwriting their change. Get it from List Repo Commits.',+ required: false,+ }),+ create_pr: Property.Checkbox({+ displayName: 'Open as Pull Request',+ description: 'Open a pull request with this commit instead of writing directly to the branch.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, branch, summary, commit_description, files, deleted_paths, parent_commit, create_pr } =+ context.propsValue;+ const token = context.auth.secret_text;+ const title = hfWrite.requireText({ value: summary, name: 'Commit Title' });+ const prepared = parseFiles(files);+ const deletedPaths = hfUtils+ .toStringArray(deleted_paths)+ .map((value, index) => normalizeRepoPath({ value, label: `Path to delete #${index + 1}` }));+ if (prepared.files.length === 0 && deletedPaths.length === 0) {+ throw new Error('Provide at least one file to write or one path to delete.');+ }+ assertUniquePaths({ filePaths: prepared.files.map((file) => file.path), deletedPaths });+ const parentCommit = hfWrite.optionalText({ value: parent_commit, name: 'Parent Commit' });+ if (parentCommit !== undefined && !/^[0-9a-fA-F]{40}$/.test(parentCommit)) {+ throw new Error('Parent Commit must be a full 40-character commit SHA. Get it from List Repo Commits.');+ }+ const targetBranch = hfWrite.requireText({ value: branch, name: 'Branch' });+ const description = hfWrite.optionalText({ value: commit_description, name: 'Commit Description' });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const body: Record<string, unknown> = {+ summary: title,+ files: prepared.files,+ deletedEntries: deletedPaths.map((path) => ({ path })),+ };+ if (description !== undefined) {+ body['description'] = description;+ }+ if (parentCommit !== undefined) {+ body['parentCommit'] = parentCommit.toLowerCase();+ }+ const conflictError = (detail: string | null): Error =>+ new Error(+ parentCommit !== undefined+ ? `PARENT_COMMIT_MISMATCH: '${targetBranch}' no longer points to ${parentCommit}; someone committed since. Re-read the files, then retry with the new head commit.${detail ? ` Details: ${detail}` : ''}`+ : `COMMIT_CONFLICT: the Hub refused the commit to '${targetBranch}' because of a conflict.${detail ? ` Details: ${detail}` : ''}`+ );+ const response = await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/commit/${hfRepo.encodeRevision(targetBranch)}`,+ query: [['create_pr', create_pr === true ? '1' : undefined]],+ body,+ statusErrors: {+ 409: conflictError,+ 412: conflictError,+ 413: (detail) =>+ lfsRequiredError({+ path: prepared.files.map((file) => file.path).join("', '"),+ reason: `was refused as too large by the Hub${detail ? ` (${detail})` : ''}`,+ }),+ },+ });+ const pullRequestUrl = hfWrite.readString({ record: response, key: 'pullRequestUrl' });+ const prNumber = pullRequestNumber(pullRequestUrl);+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ branch: targetBranch,+ commit_oid: hfWrite.readString({ record: response, key: 'commitOid' }),+ commit_url: hfWrite.readString({ record: response, key: 'commitUrl' }),+ pull_request_url: pullRequestUrl,+ pull_request_number: prNumber,+ pull_request_revision: prNumber === null ? null : `refs/pr/${prNumber}`,+ files_written: prepared.files.map((file) => file.path),+ paths_deleted: deletedPaths,+ total_bytes: prepared.totalBytes,+ };+ },+});++const MAX_TOTAL_BYTES = 1024 * 1024;+const MAX_PATH_LENGTH = 1000;++type CommitFile = {+ path: string;+ content: string;+ encoding: 'utf-8' | 'base64';+};++type PreparedFiles = {+ files: CommitFile[];+ totalBytes: number;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-collection.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-collection.tsnew file mode 100644index 00000000000..a029fadcd5b--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-collection.ts@@ -0,0 +1,163 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { createCollectionOutputSchema } from '../output-schemas';++function summarizeCollection({ body, created }: { body: unknown; created: boolean }) {+ const record = hfHub.isRecord(body) ? body : {};+ const slug = hfWrite.readString({ record, key: 'slug' });+ const items = Array.isArray(record['items']) ? record['items'] : [];+ const isPrivate = record['private'];+ return {+ created,+ slug,+ title: hfWrite.readString({ record, key: 'title' }),+ description: hfWrite.readString({ record, key: 'description' }),+ private: typeof isPrivate === 'boolean' ? isPrivate : null,+ item_count: items.length,+ url: slug ? `${hfHub.baseUrl}/collections/${slug}` : null,+ };+}++async function findCollectionSlugByTitle({ token, owner, title }: FindCollectionParams): Promise<string | null> {+ let cursor: string | null = null;+ for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {+ const response = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: '/api/collections',+ query: [+ ['owner', owner],+ ['q', title],+ ['limit', LOOKUP_PAGE_SIZE],+ ['cursor', cursor],+ ],+ });+ const collections = Array.isArray(response.body) ? response.body : [];+ const match = collections.find((collection) => hfWrite.readString({ record: collection, key: 'title' }) === title);+ const slug = hfWrite.readString({ record: match, key: 'slug' });+ if (slug) {+ return slug;+ }+ cursor = hfHub.parseNextCursor(response.headers);+ if (cursor === null || collections.length === 0) {+ return null;+ }+ }+ return null;+}++export const createCollection = createAction({+ auth: huggingFaceAuth,+ name: 'create_collection',+ classification: 'WRITE',+ displayName: 'Create Collection',+ description: 'Create a Hugging Face collection, or return it if one with the same title already exists.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates a collection (a curated list of models, datasets, Spaces and papers) under the connected user or an organization, private by default, optionally seeded with one item. If a collection with that title already exists in the namespace it is returned unchanged with created:false (the seed item is then not added), so retries are safe. Returns the slug that Add Item to Collection and Get Collection need. Only make it public when the user asks. Requires a write-role token.",+ idempotent: true,+ },+ outputSchema: createCollectionOutputSchema,+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'The collection title, 1 to 60 characters.',+ required: true,+ }),+ namespace: Property.ShortText({+ displayName: 'Namespace',+ description: 'The user or organization that owns the collection. Leave empty for the connected user.',+ required: false,+ }),+ description: Property.ShortText({+ displayName: 'Description',+ description: 'Optional short description, up to 150 characters.',+ required: false,+ }),+ private: Property.Checkbox({+ displayName: 'Private',+ description: 'Keep the collection private (default). Turn off only to publish it to everyone.',+ required: false,+ defaultValue: true,+ }),+ item_type: Property.StaticDropdown({+ displayName: 'First Item Type',+ description: 'Optional type of an item to add right away. Requires First Item ID.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ { label: 'Space', value: 'space' },+ { label: 'Paper', value: 'paper' },+ { label: 'Collection', value: 'collection' },+ ],+ },+ }),+ item_id: Property.ShortText({+ displayName: 'First Item ID',+ description:+ "Optional ID of the first item: a repository ID like 'openai-community/gpt2', an arXiv ID like '2307.09288', or a collection slug. Requires First Item Type.",+ required: false,+ }),+ },+ async run(context) {+ const { title, namespace, description, item_type, item_id } = context.propsValue;+ const token = context.auth.secret_text;+ const collectionTitle = hfWrite.requireText({ value: title, name: 'Title', maxLength: 60 });+ const collectionDescription = hfWrite.optionalText({ value: description, name: 'Description', maxLength: 150 });+ const itemId = hfWrite.optionalText({ value: item_id, name: 'First Item ID' });+ if ((item_type === undefined || item_type === null) !== (itemId === undefined)) {+ throw new Error('Set both First Item Type and First Item ID, or neither.');+ }+ const owner = hfWrite.optionalText({ value: namespace, name: 'Namespace' }) ?? (await hfWrite.currentUsername(token));+ const body: Record<string, unknown> = {+ title: collectionTitle,+ namespace: owner,+ private: context.propsValue.private !== false,+ };+ if (collectionDescription !== undefined) {+ body['description'] = collectionDescription;+ }+ if (item_type && itemId !== undefined) {+ body['item'] = { type: item_type, id: itemId };+ }+ const outcome = await hfWrite.createOrConflict({+ token,+ method: HttpMethod.POST,+ path: '/api/collections',+ body,+ });+ if (!outcome.conflict) {+ return summarizeCollection({ body: outcome.body, created: true });+ }+ const existingSlug =+ hfWrite.readString({ record: outcome.body, key: 'slug' }) ??+ (await findCollectionSlugByTitle({ token, owner, title: collectionTitle }));+ if (!existingSlug) {+ throw new Error(+ `COLLECTION_EXISTS: a collection titled '${collectionTitle}' already exists in '${owner}', but it could not be found by title. Find it with List Collections.`+ );+ }+ const existing = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: hfWrite.collectionApiPath(hfWrite.parseCollectionSlug(existingSlug)),+ });+ return summarizeCollection({ body: existing.body, created: false });+ },+});++const MAX_LOOKUP_PAGES = 5;+const LOOKUP_PAGE_SIZE = 100;++type FindCollectionParams = {+ token: string;+ owner: string;+ title: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-discussion.tsnew file mode 100644index 00000000000..6ecbe2b4f44--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-discussion.ts@@ -0,0 +1,75 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { createDiscussionOutputSchema } from '../output-schemas';++export const createDiscussion = createAction({+ auth: huggingFaceAuth,+ name: 'create_discussion',+ classification: 'WRITE',+ displayName: 'Create Discussion',+ description: 'Open a new discussion or draft pull request on a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Opens a new discussion thread on a model, dataset or Space repository, posted publicly under the connected user's name (visible to everyone who can see the repository). With Open as Pull Request it instead opens an empty draft pull request: add files to it with Commit Files using the returned pull_request_revision (refs/pr/N) as the branch, or use Commit Files with Open as Pull Request to do both in one step. Each call creates a new thread, so retries duplicate. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: createDiscussionOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'The discussion title, 3 to 200 characters.',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'The opening message, in Markdown (up to 65,536 characters).',+ required: true,+ }),+ pull_request: Property.Checkbox({+ displayName: 'Open as Pull Request',+ description: 'Open an empty draft pull request instead of a discussion.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, title, description, pull_request } = context.propsValue;+ const token = context.auth.secret_text;+ const discussionTitle = hfWrite.requireText({ value: title, name: 'Title', maxLength: 200 });+ if (discussionTitle.length < 3) {+ throw new Error('Title must be at least 3 characters.');+ }+ const message = hfWrite.requireText({ value: description, name: 'Description', maxLength: 65536 });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const response = await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/discussions`,+ body: { title: discussionTitle, description: message, pullRequest: pull_request === true },+ });+ const body = hfHub.isRecord(response) ? response : {};+ const num = typeof body['num'] === 'number' ? body['num'] : null;+ const isPullRequest = body['pullRequest'] === true;+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ title: discussionTitle,+ is_pull_request: isPullRequest,+ pull_request_revision: isPullRequest && num !== null ? `refs/pr/${num}` : null,+ url:+ typeof body['url'] === 'string'+ ? body['url']+ : num !== null+ ? `${repo.webUrl}/discussions/${num}`+ : null,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-repo-branch.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-repo-branch.tsnew file mode 100644index 00000000000..97b6116b9f5--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-repo-branch.ts@@ -0,0 +1,82 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { createRepoBranchOutputSchema } from '../output-schemas';++export const createRepoBranch = createAction({+ auth: huggingFaceAuth,+ name: 'create_repo_branch',+ classification: 'WRITE',+ displayName: 'Create Branch',+ description: 'Create a new branch in a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates a new branch in a model, dataset or Space repository, starting from a given branch, tag or commit (the default branch when empty), or as an empty branch. Never overwrites: if the branch already exists the call fails with BRANCH_EXISTS, so a retry after success fails too. Check existing branches with List Branches & Tags; commit to the new branch with Commit Files. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: createRepoBranchOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ branch: Property.ShortText({+ displayName: 'Branch Name',+ description: "The name of the new branch, for example 'dev' or 'experiment-1'.",+ required: true,+ }),+ starting_point: Property.ShortText({+ displayName: 'Starting Point',+ description:+ "Optional branch, tag or commit SHA the new branch starts from, for example 'main' or 'v1.0'. Leave empty to start from the default branch.",+ required: false,+ }),+ empty_branch: Property.Checkbox({+ displayName: 'Empty Branch',+ description: 'Create the branch with no history and no files instead of copying a starting point.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, branch, starting_point, empty_branch } = context.propsValue;+ const token = context.auth.secret_text;+ const branchName = hfWrite.stripRefPrefix({+ value: hfWrite.requireText({ value: branch, name: 'Branch Name' }),+ prefix: 'refs/heads/',+ });+ const startingPoint = hfWrite.optionalText({ value: starting_point, name: 'Starting Point' });+ if (empty_branch === true && startingPoint !== undefined) {+ throw new Error('Use either Starting Point or Empty Branch, not both.');+ }+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const body: Record<string, unknown> = { overwrite: false };+ if (startingPoint !== undefined) {+ body['startingPoint'] = startingPoint;+ }+ if (empty_branch === true) {+ body['emptyBranch'] = true;+ }+ await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/branch/${encodeURIComponent(branchName)}`,+ body,+ statusErrors: {+ 409: (detail) =>+ new Error(+ `BRANCH_EXISTS: branch '${branchName}' already exists in ${repo.repoId}. This action never overwrites a branch; pick another name.${detail ? ` Details: ${detail}` : ''}`+ ),+ },+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ branch: branchName,+ starting_point: startingPoint ?? null,+ empty_branch: empty_branch === true,+ created: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-repo-tag.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-repo-tag.tsnew file mode 100644index 00000000000..779015f59a1--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-repo-tag.ts@@ -0,0 +1,75 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { hfRepo } from '../common/repo';+import { createRepoTagOutputSchema } from '../output-schemas';++export const createRepoTag = createAction({+ auth: huggingFaceAuth,+ name: 'create_repo_tag',+ classification: 'WRITE',+ displayName: 'Create Tag',+ description: 'Create a git tag on a revision of a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates a git tag (for example a release like 'v1.0') pointing at a branch, tag or commit of a model, dataset or Space repository. Fails with TAG_EXISTS if the tag is already there, so a retry after success fails too; check existing tags with List Branches & Tags. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: createRepoTagOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ tag: Property.ShortText({+ displayName: 'Tag Name',+ description: "The tag to create, for example 'v1.0'.",+ required: true,+ }),+ revision: Property.ShortText({+ displayName: 'Revision',+ description: "The branch, tag or commit SHA to tag, for example 'main', 'dev' or a commit SHA. Get branch names from List Branches & Tags and commit SHAs from List Repo Commits.",+ required: true,+ }),+ message: Property.LongText({+ displayName: 'Message',+ description: 'Optional annotation message stored with the tag.',+ required: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, tag, revision, message } = context.propsValue;+ const token = context.auth.secret_text;+ const tagName = hfWrite.stripRefPrefix({+ value: hfWrite.requireText({ value: tag, name: 'Tag Name' }),+ prefix: 'refs/tags/',+ });+ const tagMessage = hfWrite.optionalText({ value: message, name: 'Message' });+ const targetRevision = hfWrite.requireText({ value: revision, name: 'Revision' });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const body: Record<string, unknown> = { tag: tagName };+ if (tagMessage !== undefined) {+ body['message'] = tagMessage;+ }+ await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/tag/${hfRepo.encodeRevision(targetRevision)}`,+ body,+ statusErrors: {+ 409: (detail) =>+ new Error(+ `TAG_EXISTS: tag '${tagName}' already exists in ${repo.repoId}. Pick another name or delete the old tag first.${detail ? ` Details: ${detail}` : ''}`+ ),+ },+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ tag: tagName,+ revision: targetRevision,+ created: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-repo.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-repo.tsnew file mode 100644index 00000000000..60c4dbdf39d--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-repo.ts@@ -0,0 +1,134 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { hfRepo } from '../common/repo';+import { createRepoOutputSchema } from '../output-schemas';++export const createRepo = createAction({+ auth: huggingFaceAuth,+ name: 'create_repo',+ classification: 'WRITE',+ displayName: 'Create Repository',+ description: 'Create a model, dataset or Space repository on the Hugging Face Hub, or return it if it already exists.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates a model, dataset or Space repository under the connected user or an organization, private by default; if a repository with that name already exists it is returned unchanged with created:false, so retries are safe. Only set Visibility to Public when the user explicitly asks, because a public repository is visible to everyone. Spaces need an SDK: 'static' is free for everyone, while 'gradio' and 'docker' need a PRO/Team subscription or billing on the account; no paid hardware is ever requested. Add files afterwards with Commit Files. Requires a write-role token (and write rights in the organization).",+ idempotent: true,+ },+ outputSchema: createRepoOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ name: Property.ShortText({+ displayName: 'Repository Name',+ description:+ "The repository name, for example 'my-model'. You may also pass 'namespace/name' to create it under an organization.",+ required: true,+ }),+ organization: Property.ShortText({+ displayName: 'Organization',+ description:+ 'Optional organization to create the repository in. Leave empty to create it under the connected user.',+ required: false,+ }),+ visibility: Property.StaticDropdown({+ displayName: 'Visibility',+ description:+ 'Private (default) or Public. Public repositories are visible to everyone, so choose Public only when explicitly asked.',+ required: false,+ defaultValue: 'private',+ options: {+ disabled: false,+ options: [+ { label: 'Private', value: 'private' },+ { label: 'Public', value: 'public' },+ ],+ },+ }),+ space_sdk: Property.StaticDropdown({+ displayName: 'Space SDK',+ description: "Required when Repository Type is 'space': the framework the Space runs. 'static' is free for everyone; 'gradio' and 'docker' need a PRO/Team subscription or billing. Ignored for models and datasets.",+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Static (HTML)', value: 'static' },+ { label: 'Gradio', value: 'gradio' },+ { label: 'Docker', value: 'docker' },+ ],+ },+ }),+ },+ async run(context) {+ const { repo_type, name, organization, visibility, space_sdk } = context.propsValue;+ const token = context.auth.secret_text;+ const typeInfo = hfRepo.getTypeInfo(repo_type);+ const rawName = hfWrite.requireText({ value: name, name: 'Repository Name' });+ const parts = rawName.split('/').filter((segment) => segment.length > 0);+ if (parts.length > 2 || parts.length === 0) {+ throw new Error("Repository Name must be 'name' or 'namespace/name'.");+ }+ const repoName = parts[parts.length - 1];+ const namespaceFromName = parts.length === 2 ? parts[0] : undefined;+ const orgInput = hfWrite.optionalText({ value: organization, name: 'Organization' });+ if (namespaceFromName && orgInput && namespaceFromName !== orgInput) {+ throw new Error(+ `The namespace in Repository Name ('${namespaceFromName}') differs from Organization ('${orgInput}'). Pass only one.`+ );+ }+ if (typeInfo.singular === 'space' && !space_sdk) {+ throw new Error("Space SDK is required when creating a Space. Choose 'static', 'gradio' or 'docker'.");+ }+ const username = await hfWrite.currentUsername(token);+ const requestedNamespace = namespaceFromName ?? orgInput;+ const organizationToSend =+ requestedNamespace && requestedNamespace !== username ? requestedNamespace : undefined;+ const namespace = organizationToSend ?? username;+ const isPrivate = visibility !== 'public';+ const body: Record<string, unknown> = {+ type: typeInfo.singular,+ name: repoName,+ private: isPrivate,+ };+ if (organizationToSend) {+ body['organization'] = organizationToSend;+ }+ if (typeInfo.singular === 'space') {+ body['sdk'] = space_sdk;+ }+ const repoId = `${namespace}/${repoName}`;+ const webUrl = `${hfHub.baseUrl}/${typeInfo.resolvePrefix}${repoId}`;+ const outcome = await hfWrite.createOrConflict({+ token,+ method: HttpMethod.POST,+ path: '/api/repos/create',+ body,+ });+ if (!outcome.conflict) {+ return {+ created: true,+ repo_id: repoId,+ repo_type: typeInfo.singular,+ url: hfWrite.readString({ record: outcome.body, key: 'url' }) ?? webUrl,+ private: isPrivate,+ };+ }+ const existing = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `/api/${typeInfo.apiSegment}/${hfRepo.encodeRepoId(repoId)}`,+ });+ const existingBody = hfHub.isRecord(existing.body) ? existing.body : {};+ const existingPrivate = existingBody['private'];+ return {+ created: false,+ repo_id: typeof existingBody['id'] === 'string' ? existingBody['id'] : repoId,+ repo_type: typeInfo.singular,+ url: hfWrite.readString({ record: outcome.body, key: 'url' }) ?? webUrl,+ private: typeof existingPrivate === 'boolean' ? existingPrivate : null,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/create-webhook.ts b/packages/pieces/community/hugging-face/src/lib/actions/create-webhook.tsnew file mode 100644index 00000000000..b9a744587e8--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/create-webhook.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfSettingsApi, hfWebhooks } from '../common/webhooks';+import { webhookOutputSchema } from '../output-schemas';++export const createWebhook = createAction({+ auth: huggingFaceAuth,+ name: 'create_webhook',+ classification: 'WRITE',+ displayName: 'Create Webhook',+ description: 'Create a Hugging Face webhook that calls an https URL when watched items change.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates a user-level Hub webhook that POSTs an event to an https target URL (for example an Activepieces Catch Webhook URL) whenever a watched user, organization or repository changes: repository updates (commits, tags, settings) and/or discussion and pull-request activity. An optional secret is sent back in the X-Webhook-Secret header so the receiver can verify the call; it is never returned by any action. Needs a 'write' role token or a fine-grained token with webhook permission. Each call creates a new webhook, so a retry creates a duplicate; check List Webhooks first.",+ idempotent: false,+ },+ outputSchema: webhookOutputSchema,+ props: {+ url: Property.ShortText({+ displayName: 'Target URL',+ description: 'The https:// address the Hub will POST events to.',+ required: true,+ }),+ watched: hfWebhooks.watchedItemsProp({+ required: true,+ description: 'The users, organizations or repositories whose changes trigger the webhook. At least one.',+ }),+ domains: hfWebhooks.domainsProp({+ required: true,+ description: 'Which kinds of events to send: repository changes, discussion and pull-request activity, or both.',+ }),+ secret: Property.ShortText({+ displayName: 'Secret',+ description:+ 'Optional shared secret, sent in the X-Webhook-Secret header of every delivery. Printable ASCII only. It cannot be read back later.',+ required: false,+ }),+ },+ async run(context) {+ const { url, watched, domains, secret } = context.propsValue;+ const watchedItems = hfWebhooks.parseWatched(watched);+ if (watchedItems.length === 0) {+ throw new Error('Provide at least one watched item.');+ }+ const domainList = hfWebhooks.parseDomains(domains);+ if (domainList.length === 0) {+ throw new Error("Provide at least one domain: 'repo', 'discussion' or both.");+ }+ const body: Record<string, unknown> = {+ url: hfWebhooks.assertHttpsUrl(url),+ watched: watchedItems,+ domains: domainList,+ };+ if (secret !== undefined && secret !== null && secret !== '') {+ body['secret'] = hfWebhooks.assertSecret(secret);+ }+ const response = await hfSettingsApi.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: '/api/settings/webhooks',+ body,+ });+ return hfWebhooks.toOutput(hfWebhooks.unwrap(response.body));+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-discussion.tsnew file mode 100644index 00000000000..f23815830cc--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-discussion.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { deleteDiscussionOutputSchema } from '../output-schemas';++export const deleteDiscussion = createAction({+ auth: huggingFaceAuth,+ name: 'delete_discussion',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Discussion',+ description: 'Permanently delete a discussion or pull request from a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a discussion or pull request, with all its comments, from a model, dataset or Space repository; it cannot be undone. Prefer Open or Close Discussion (closed) unless the user explicitly asks to delete. A retry after success fails because the thread is gone. Requires a write-role token with admin rights on the repository.",+ idempotent: false,+ },+ outputSchema: deleteDiscussionOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ discussion_number: Property.Number({+ displayName: 'Discussion Number',+ description: "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ required: true,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, discussion_number } = context.propsValue;+ const token = context.auth.secret_text;+ const num = hfWrite.assertDiscussionNumber(discussion_number);+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ await hfWrite.request({+ token,+ method: HttpMethod.DELETE,+ path: `${repo.apiPath}/discussions/${num}`,+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ deleted: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-notifications.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-notifications.tsnew file mode 100644index 00000000000..0817b027ae6--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-notifications.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfUtils } from '../common/utils';+import { hfSettingsApi } from '../common/webhooks';+import { deleteNotificationsOutputSchema } from '../output-schemas';++export const deleteNotifications = createAction({+ auth: huggingFaceAuth,+ name: 'delete_notifications',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Notifications',+ description: 'Delete specific notifications from the Hugging Face inbox of the connected account.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently removes the notifications for the given discussions from the connected account's Hub inbox; the discussions themselves are untouched. Pass the 24-character discussion_id values returned by List Notifications, not per-repository discussion numbers. Only the listed notifications are removed, never the whole inbox. Needs a 'write' role token. Cannot be undone, and a retry after success has nothing left to delete.",+ idempotent: false,+ },+ outputSchema: deleteNotificationsOutputSchema,+ props: {+ discussion_ids: Property.Array({+ displayName: 'Discussion IDs',+ description:+ "The 24-character hexadecimal discussion_id of each notification to delete, for example '6390e855e30d9209411de93b'. Get them from List Notifications.",+ required: true,+ }),+ },+ async run(context) {+ const ids = [+ ...new Set(+ hfUtils+ .toStringArray(context.propsValue.discussion_ids)+ .map((value) => hfSettingsApi.assertObjectId({ value, label: 'Discussion ID' }).toLowerCase())+ ),+ ];+ if (ids.length === 0) {+ throw new Error('Provide at least one discussion ID. Get them from List Notifications.');+ }+ await hfSettingsApi.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.DELETE,+ path: '/api/notifications',+ body: { discussionIds: ids },+ });+ return {+ deleted: true,+ deleted_discussion_ids: ids,+ count: ids.length,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-branch.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-branch.tsnew file mode 100644index 00000000000..5d84eb3f6bd--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-branch.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { deleteRepoBranchOutputSchema } from '../output-schemas';++export const deleteRepoBranch = createAction({+ auth: huggingFaceAuth,+ name: 'delete_repo_branch',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Branch',+ description: 'Delete a branch from a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a branch from a model, dataset or Space repository ('main' is always refused); commits reachable only from that branch are lost. Confirm the exact branch with List Branches & Tags first and only delete branches the user asked to remove. A retry after success fails because the branch is gone. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: deleteRepoBranchOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ branch: Property.ShortText({+ displayName: 'Branch Name',+ description: "The branch to delete, for example 'dev'. The 'main' branch cannot be deleted with this action.",+ required: true,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, branch } = context.propsValue;+ const token = context.auth.secret_text;+ const branchName = hfWrite.stripRefPrefix({+ value: hfWrite.requireText({ value: branch, name: 'Branch Name' }),+ prefix: 'refs/heads/',+ });+ if (branchName.toLowerCase() === 'main') {+ throw new Error("PROTECTED_BRANCH: the 'main' branch cannot be deleted with this action.");+ }+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ await hfWrite.request({+ token,+ method: HttpMethod.DELETE,+ path: `${repo.apiPath}/branch/${encodeURIComponent(branchName)}`,+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ branch: branchName,+ deleted: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-tag.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-tag.tsnew file mode 100644index 00000000000..338ea2ab85d--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-repo-tag.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { deleteRepoTagOutputSchema } from '../output-schemas';++export const deleteRepoTag = createAction({+ auth: huggingFaceAuth,+ name: 'delete_repo_tag',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Tag',+ description: 'Delete a git tag from a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a git tag from a model, dataset or Space repository; the tagged commits stay, but anything pinned to that tag loses it. Confirm the exact tag with List Branches & Tags and only delete tags the user asked to remove. A retry after success fails because the tag is gone. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: deleteRepoTagOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ tag: Property.ShortText({+ displayName: 'Tag Name',+ description: "The tag to delete, for example 'v1.0'.",+ required: true,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, tag } = context.propsValue;+ const token = context.auth.secret_text;+ const tagName = hfWrite.stripRefPrefix({+ value: hfWrite.requireText({ value: tag, name: 'Tag Name' }),+ prefix: 'refs/tags/',+ });+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ await hfWrite.request({+ token,+ method: HttpMethod.DELETE,+ path: `${repo.apiPath}/tag/${encodeURIComponent(tagName)}`,+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ tag: tagName,+ deleted: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-space-secret.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-space-secret.tsnew file mode 100644index 00000000000..8e08cf98b87--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-space-secret.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { deleteSpaceSecretOutputSchema } from '../output-schemas';++export const deleteSpaceSecret = createAction({+ auth: huggingFaceAuth,+ name: 'delete_space_secret',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Space Secret',+ description: 'Delete a secret from a Hugging Face Space.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a secret from a Space; the value cannot be recovered and code that reads it will stop working. Deleting a secret restarts the Space. Only delete secrets the user asked to remove. Do not blindly retry: the key is already gone after a success. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: deleteSpaceSecretOutputSchema,+ props: {+ space_id: Property.ShortText({+ displayName: 'Space ID',+ description: "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.",+ required: true,+ }),+ key: Property.ShortText({+ displayName: 'Key',+ description: "The name of the secret to delete, for example 'OPENAI_API_KEY'.",+ required: true,+ }),+ },+ async run(context) {+ const { space_id, key } = context.propsValue;+ const token = context.auth.secret_text;+ const secretKey = hfWrite.assertSpaceKey(key);+ const space = await hfWrite.resolveRepo({ token, repoType: 'space', repoId: space_id });+ await hfWrite.sensitiveRequest({+ token,+ method: HttpMethod.DELETE,+ path: `${space.apiPath}/secrets`,+ body: { key: secretKey },+ });+ return {+ space_id: space.repoId,+ key: secretKey,+ deleted: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-space-variable.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-space-variable.tsnew file mode 100644index 00000000000..60f86b784fb--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-space-variable.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { deleteSpaceVariableOutputSchema } from '../output-schemas';++export const deleteSpaceVariable = createAction({+ auth: huggingFaceAuth,+ name: 'delete_space_variable',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Space Variable',+ description: 'Delete an environment variable from a Hugging Face Space.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a public environment variable from a Space; code that reads it will stop working. Deleting a variable restarts the Space. Only delete variables the user asked to remove. Do not blindly retry: the key is already gone after a success. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: deleteSpaceVariableOutputSchema,+ props: {+ space_id: Property.ShortText({+ displayName: 'Space ID',+ description: "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.",+ required: true,+ }),+ key: Property.ShortText({+ displayName: 'Key',+ description: "The name of the variable to delete, for example 'MODEL_NAME'.",+ required: true,+ }),+ },+ async run(context) {+ const { space_id, key } = context.propsValue;+ const token = context.auth.secret_text;+ const variableKey = hfWrite.assertSpaceKey(key);+ const space = await hfWrite.resolveRepo({ token, repoType: 'space', repoId: space_id });+ await hfWrite.request({+ token,+ method: HttpMethod.DELETE,+ path: `${space.apiPath}/variables`,+ body: { key: variableKey },+ });+ return {+ space_id: space.repoId,+ key: variableKey,+ deleted: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/delete-webhook.ts b/packages/pieces/community/hugging-face/src/lib/actions/delete-webhook.tsnew file mode 100644index 00000000000..34cd3ec02d4--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/delete-webhook.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfSettingsApi, hfWebhooks } from '../common/webhooks';+import { deleteWebhookOutputSchema } from '../output-schemas';++export const deleteWebhook = createAction({+ auth: huggingFaceAuth,+ name: 'delete_webhook',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Webhook',+ description: 'Permanently delete a webhook from the connected Hugging Face account.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Permanently deletes a webhook by its 24-character ID; the Hub stops calling its URL and the configuration, including any signing secret, is lost. To pause deliveries reversibly, prefer Enable or Disable Webhook. Find the ID with List Webhooks. Needs a 'write' role token or a fine-grained token with webhook permission. Cannot be undone, and a retry after success fails with 404.",+ idempotent: false,+ },+ outputSchema: deleteWebhookOutputSchema,+ props: {+ webhook_id: hfWebhooks.webhookIdProp(),+ },+ async run(context) {+ const webhookId = context.propsValue.webhook_id.trim();+ await hfSettingsApi.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.DELETE,+ path: hfWebhooks.path(webhookId),+ });+ return { deleted: true, webhook_id: webhookId };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/filter-dataset-rows.ts b/packages/pieces/community/hugging-face/src/lib/actions/filter-dataset-rows.tsnew file mode 100644index 00000000000..8b7f8059e9e--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/filter-dataset-rows.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetRowsOutputSchema } from '../output-schemas';++export const filterDatasetRows = createAction({+ auth: huggingFaceAuth,+ name: 'filter_dataset_rows',+ classification: 'SEARCH',+ displayName: 'Filter Dataset Rows',+ description: 'Get the rows of a dataset split that match a SQL-like condition, optionally sorted.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns one page of up to 100 rows from a dataset split that match a SQL-like WHERE condition, optionally sorted, plus num_rows_total (total matches) and next_offset for paging. Column names must be double-quoted, for example \"label\"=1 AND \"idx\">100; get column names from Preview Dataset Rows or Get Dataset Schema & Info. Only works when Check Dataset Viewer Support reports filter:true (call it first when unsure); for free-text matching use Search Dataset Rows. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetRowsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.config(),+ split: hfViewerProps.split(),+ where: Property.LongText({+ displayName: 'Where',+ description:+ 'SQL-like condition with double-quoted column names, for example "label"=1 or "score">0.5 AND "lang"=\'en\'. String values use single quotes.',+ required: false,+ }),+ orderby: Property.ShortText({+ displayName: 'Order By',+ description: 'Optional sort with double-quoted column names, for example "idx" DESC or "score" ASC.',+ required: false,+ }),+ offset: hfViewerProps.offset(),+ length: hfViewerProps.length(),+ },+ async run(context) {+ const { dataset, config, split, where, orderby } = context.propsValue;+ const { offset, length } = hfViewer.validatePaging({+ offset: context.propsValue.offset,+ length: context.propsValue.length,+ });+ const condition = where?.trim();+ const order = orderby?.trim();+ if (!condition && !order) {+ throw new Error('Set Where, Order By, or both. To read rows without a condition use Get Dataset Rows.');+ }+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/filter',+ dataset,+ query: [+ ['config', config.trim()],+ ['split', split.trim()],+ ['where', condition],+ ['orderby', order],+ ['offset', offset],+ ['length', length],+ ],+ });+ return hfViewer.withPaging({ body, offset });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-leaderboard.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-leaderboard.tsnew file mode 100644index 00000000000..d1e8f2ae05a--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-leaderboard.ts@@ -0,0 +1,117 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfViewerProps } from '../common/dataset-viewer';+import { hfHub } from '../common/hub-client';+import { hfRepo } from '../common/repo';+import { hfUtils } from '../common/utils';+import { getDatasetLeaderboardOutputSchema } from '../output-schemas';++export const getDatasetLeaderboard = createAction({+ auth: huggingFaceAuth,+ name: 'get_dataset_leaderboard',+ classification: 'SEARCH',+ displayName: 'Get Dataset Leaderboard',+ description: 'Get the models ranked by their evaluation score on a benchmark dataset.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the Hub leaderboard of a benchmark dataset (for example openai/gsm8k or TIGER-Lab/MMLU-Pro): models ranked by their reported evaluation score, each with rank, model_id, score value, whether lower is better, parameter count, verification status and the source of the result. Most non-benchmark datasets return an empty list. Filter by task, maximum model size, or base models versus fine-tunes; use Get Model for details of a ranked model. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetLeaderboardOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ task_id: Property.ShortText({+ displayName: 'Task ID',+ description:+ "Optional benchmark task for datasets with several tasks, for example 'gsm8k'. It matches the eval result file name (.eval_results/<task>.yaml). Leave empty for the default task.",+ required: false,+ }),+ max_params: Property.ShortText({+ displayName: 'Max Parameters',+ description: "Only models up to this size, for example '10B', '500M' or a raw count such as '7000000000'.",+ required: false,+ }),+ base_model: Property.StaticDropdown({+ displayName: 'Model Scope',+ description:+ 'Leave empty for the Hub default (base models only), or include fine-tuned and derived models as well.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Base models only', value: 'true' },+ { label: 'Include fine-tuned models', value: 'false' },+ ],+ },+ }),+ },+ async run(context) {+ const { dataset, task_id, max_params, base_model } = context.propsValue;+ const token = context.auth.secret_text;+ const apiPath = await hfRepo.apiPath({ token, repoType: 'dataset', repoId: dataset });+ const response = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: `${apiPath}/leaderboard`,+ query: [+ ['task_id', task_id?.trim()],+ ['max_params', max_params?.trim()],+ ['base_model', hfUtils.booleanFlag(base_model)],+ ],+ });+ const entries = Array.isArray(response.body) ? response.body.map(flattenEntry) : [];+ return {+ entries,+ count: entries.length,+ };+ },+});++function flattenEntry(entry: unknown): LeaderboardEntry {+ const record = hfHub.isRecord(entry) ? entry : {};+ const author = hfHub.isRecord(record['author']) ? record['author'] : {};+ const source = hfHub.isRecord(record['source']) ? record['source'] : {};+ return {+ rank: numberOrNull(record['rank']),+ model_id: stringOrNull(record['modelId']),+ value: numberOrNull(record['value']),+ lower_is_better: record['lower_is_better'] === true,+ num_parameters: numberOrNull(record['num_parameters']),+ verified: record['verified'] === true,+ author_name: stringOrNull(author['name']),+ author_fullname: stringOrNull(author['fullname']),+ author_type: stringOrNull(author['type']),+ source_name: stringOrNull(source['name']),+ source_url: stringOrNull(source['url']),+ source_is_external: source['isExternal'] === true,+ pull_request: numberOrNull(record['pullRequest']),+ filename: stringOrNull(record['filename']),+ };+}++function numberOrNull(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}++function stringOrNull(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null;+}++type LeaderboardEntry = {+ rank: number | null;+ model_id: string | null;+ value: number | null;+ lower_is_better: boolean;+ num_parameters: number | null;+ verified: boolean;+ author_name: string | null;+ author_fullname: string | null;+ author_type: string | null;+ source_name: string | null;+ source_url: string | null;+ source_is_external: boolean;+ pull_request: number | null;+ filename: string | null;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-rows.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-rows.tsnew file mode 100644index 00000000000..0078657cb79--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-rows.ts@@ -0,0 +1,45 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetRowsOutputSchema } from '../output-schemas';++export const getDatasetRows = createAction({+ auth: huggingFaceAuth,+ name: 'get_dataset_rows',+ classification: 'SEARCH',+ displayName: 'Get Dataset Rows',+ description: 'Get a page of rows (up to 100) from a dataset split, by offset.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns one page of up to 100 rows from a dataset split starting at offset, plus the column features, num_rows_total and next_offset (null on the last page) for paging; partial:true means the viewer only indexed part of a very large split. Needs viewer:true from Check Dataset Viewer Support (call it first when unsure); otherwise use Preview Dataset Rows. For keyword or condition queries use Search Dataset Rows or Filter Dataset Rows. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetRowsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.config(),+ split: hfViewerProps.split(),+ offset: hfViewerProps.offset(),+ length: hfViewerProps.length(),+ },+ async run(context) {+ const { dataset, config, split } = context.propsValue;+ const { offset, length } = hfViewer.validatePaging({+ offset: context.propsValue.offset,+ length: context.propsValue.length,+ });+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/rows',+ dataset,+ query: [+ ['config', config.trim()],+ ['split', split.trim()],+ ['offset', offset],+ ['length', length],+ ],+ });+ return hfViewer.withPaging({ body, offset });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-size.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-size.tsnew file mode 100644index 00000000000..63a19a8f2b0--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-size.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetSizeOutputSchema } from '../output-schemas';++export const getDatasetSize = createAction({+ auth: huggingFaceAuth,+ name: 'get_dataset_size',+ classification: 'READ',+ displayName: 'Get Dataset Size',+ description: 'Get the number of rows and bytes of a dataset, per subset and per split.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns row counts, column counts and byte sizes (original files, parquet, in memory) for the whole dataset, each subset (config) and each split, optionally narrowed to one subset. Use it to decide how many pages Get Dataset Rows would need or whether a download is practical. If unsure the viewer serves this dataset, call Check Dataset Viewer Support first. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetSizeOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.optionalConfig(),+ },+ async run(context) {+ const { dataset, config } = context.propsValue;+ return hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/size',+ dataset,+ query: [['config', config?.trim()]],+ });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-statistics.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-statistics.tsnew file mode 100644index 00000000000..f22986f72af--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-statistics.ts@@ -0,0 +1,36 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetStatisticsOutputSchema } from '../output-schemas';++export const getDatasetStatistics = createAction({+ auth: huggingFaceAuth,+ name: 'get_dataset_statistics',+ classification: 'READ',+ displayName: 'Get Column Statistics',+ description: 'Get per-column statistics (counts, nulls, min/max/mean, histograms, label frequencies) of a dataset split.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns per-column statistics for one dataset split: null counts and proportions, min, max, mean, median, standard deviation and histograms for numeric and text-length columns, and value frequencies for class labels and booleans; partial:true means they were computed on a sample. Only works when Check Dataset Viewer Support reports statistics:true (call it first when unsure). Resolve config and split with List Dataset Subsets & Splits. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetStatisticsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.config(),+ split: hfViewerProps.split(),+ },+ async run(context) {+ const { dataset, config, split } = context.propsValue;+ return hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/statistics',+ dataset,+ query: [+ ['config', config.trim()],+ ['split', split.trim()],+ ],+ });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-viewer-info.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-viewer-info.tsnew file mode 100644index 00000000000..a719b83ee56--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset-viewer-info.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetViewerInfoOutputSchema } from '../output-schemas';++export const getDatasetViewerInfo = createAction({+ auth: huggingFaceAuth,+ name: 'get_dataset_viewer_info',+ classification: 'READ',+ displayName: 'Get Dataset Schema & Info',+ description: 'Get the column schema (features), description, license, citation and split sizes of a dataset.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the dataset viewer's info for a dataset: column features (the schema, including class label names), description, license, citation, homepage and per-split example counts and bytes. With a subset (config), dataset_info describes that subset; without one, dataset_info is keyed by subset name. Use Get Dataset instead for Hub repository metadata (tags, files, downloads); if unsure the viewer serves this dataset, call Check Dataset Viewer Support first. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetViewerInfoOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.optionalConfig(),+ },+ async run(context) {+ const { dataset, config } = context.propsValue;+ return hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/info',+ dataset,+ query: [['config', config?.trim()]],+ });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-organization-socials.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-organization-socials.tsnew file mode 100644index 00000000000..9a502f2a09e--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-organization-socials.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { getOrganizationSocialsOutputSchema } from '../output-schemas';++export const getOrganizationSocials = createAction({+ auth: huggingFaceAuth,+ name: 'get_organization_socials',+ classification: 'READ',+ displayName: 'Get Organization Social Handles',+ description: 'Get the social media handles a Hugging Face organization lists on its profile.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the social media handles a Hugging Face organization has added to its profile (Twitter/X, GitHub, LinkedIn); a handle it has not provided is null. Get Organization Profile has the rest of the profile but no handles; use Get User Social Handles for a person. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getOrganizationSocialsOutputSchema,+ props: {+ organization: Property.ShortText({+ displayName: 'Organization',+ description: "The organization's Hub name, for example 'huggingface'.",+ required: true,+ }),+ },+ async run(context) {+ const organization = context.propsValue.organization.trim();+ const response = await hfHub.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/api/organizations/${encodeURIComponent(organization)}/socials`,+ });+ const body = hfHub.isRecord(response.body) ? response.body : {};+ const handles = hfHub.isRecord(body['socialHandles']) ? body['socialHandles'] : {};+ return {+ organization: typeof body['org'] === 'string' ? body['org'] : organization,+ twitter: readHandle({ handles, key: 'twitter' }),+ github: readHandle({ handles, key: 'github' }),+ linkedin: readHandle({ handles, key: 'linkedin' }),+ };+ },+});++function readHandle({ handles, key }: ReadHandleParams): string | null {+ const value = handles[key];+ return typeof value === 'string' && value.length > 0 ? value : null;+}++type ReadHandleParams = {+ handles: Record<string, unknown>;+ key: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-user-socials.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-user-socials.tsnew file mode 100644index 00000000000..b38682534d1--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-user-socials.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { getUserSocialsOutputSchema } from '../output-schemas';++export const getUserSocials = createAction({+ auth: huggingFaceAuth,+ name: 'get_user_socials',+ classification: 'READ',+ displayName: 'Get User Social Handles',+ description: 'Get the social media handles a Hugging Face user lists on their profile.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the social media handles a Hugging Face user has added to their profile (Twitter/X, GitHub, LinkedIn, Bluesky); a handle the user has not provided is null. Get User Profile has the rest of the profile but no handles; use Get Organization Social Handles for an organization. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getUserSocialsOutputSchema,+ props: {+ username: Property.ShortText({+ displayName: 'Username',+ description: "The user's Hub username, for example 'julien-c'.",+ required: true,+ }),+ },+ async run(context) {+ const response = await hfHub.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/api/users/${encodeURIComponent(context.propsValue.username.trim())}/socials`,+ });+ const body = hfHub.isRecord(response.body) ? response.body : {};+ const handles = hfHub.isRecord(body['socialHandles']) ? body['socialHandles'] : {};+ return {+ username: typeof body['user'] === 'string' ? body['user'] : context.propsValue.username.trim(),+ twitter: readHandle({ handles, key: 'twitter' }),+ github: readHandle({ handles, key: 'github' }),+ linkedin: readHandle({ handles, key: 'linkedin' }),+ bluesky: readHandle({ handles, key: 'bluesky' }),+ };+ },+});++function readHandle({ handles, key }: ReadHandleParams): string | null {+ const value = handles[key];+ return typeof value === 'string' && value.length > 0 ? value : null;+}++type ReadHandleParams = {+ handles: Record<string, unknown>;+ key: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-webhook.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-webhook.tsnew file mode 100644index 00000000000..d2d0c410ef0--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-webhook.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfWebhooks } from '../common/webhooks';+import { webhookOutputSchema } from '../output-schemas';++export const getWebhook = createAction({+ auth: huggingFaceAuth,+ name: 'get_webhook',+ classification: 'READ',+ displayName: 'Get Webhook',+ description: 'Get one webhook of the connected Hugging Face account.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns one webhook by its 24-character ID: target URL, enabled state (or why it is disabled), watched users, organizations and repositories, event domains, whether a signing secret is set and when it last fired. The secret itself is never returned. Find the ID with List Webhooks. Needs a 'write' role token or a fine-grained token with webhook permission. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: webhookOutputSchema,+ props: {+ webhook_id: hfWebhooks.webhookIdProp(),+ },+ async run(context) {+ const webhook = await hfWebhooks.fetch({+ token: context.auth.secret_text,+ webhookId: context.propsValue.webhook_id,+ });+ return hfWebhooks.toOutput(webhook);+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/handle-gated-access-request.ts b/packages/pieces/community/hugging-face/src/lib/actions/handle-gated-access-request.tsnew file mode 100644index 00000000000..e3415b1e3cb--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/handle-gated-access-request.ts@@ -0,0 +1,94 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { handleGatedAccessRequestOutputSchema } from '../output-schemas';++export const handleGatedAccessRequest = createAction({+ auth: huggingFaceAuth,+ name: 'handle_gated_access_request',+ classification: 'WRITE',+ displayName: 'Accept or Reject Access Request',+ description: "Accept, reject, reset or re-queue a user's access request to a gated model or dataset.",+ audience: 'ai',+ aiMetadata: {+ description:+ "Sets the status of one user's access request to a gated model or dataset: accepted (grants that person access to the gated files), rejected, pending, or reset. Only accept when the user explicitly approves that requester. Find requesters with List Gated Access Requests. Setting the same status again converges, so it is safe to retry. Requires a write-role token with owner or admin rights on the repository.",+ idempotent: true,+ },+ outputSchema: handleGatedAccessRequestOutputSchema,+ props: {+ repo_type: Property.StaticDropdown({+ displayName: 'Repository Type',+ description: 'Gated access exists for models and datasets only.',+ required: true,+ defaultValue: 'model',+ options: {+ disabled: false,+ options: [+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ ],+ },+ }),+ repo_id: hfProps.repoId(),+ username: Property.ShortText({+ displayName: 'Username',+ description: "The Hub username of the requester, for example 'julien-c' (the 'username' from List Gated Access Requests).",+ required: true,+ }),+ status: Property.StaticDropdown({+ displayName: 'New Status',+ description: 'Accepted grants access; Rejected refuses it; Pending moves it back to the queue; Reset clears it so the user must request again.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Accepted', value: 'accepted' },+ { label: 'Rejected', value: 'rejected' },+ { label: 'Pending', value: 'pending' },+ { label: 'Reset', value: 'reset' },+ ],+ },+ }),+ reason: Property.ShortText({+ displayName: 'Reason',+ description: 'Optional reason shown to the requester, up to 200 characters. Only used with Rejected or Reset.',+ required: false,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, username, status, reason } = context.propsValue;+ if (repo_type !== 'model' && repo_type !== 'dataset') {+ throw new Error("Repository Type must be 'model' or 'dataset'; Spaces have no gated access.");+ }+ if (status !== 'accepted' && status !== 'rejected' && status !== 'pending' && status !== 'reset') {+ throw new Error("New Status must be 'accepted', 'rejected', 'pending' or 'reset'.");+ }+ const user = hfWrite.requireText({ value: username, name: 'Username' });+ const reasonText = hfWrite.optionalText({ value: reason, name: 'Reason', maxLength: 200 });+ if (reasonText !== undefined && status !== 'rejected' && status !== 'reset') {+ throw new Error('Reason can only be set when New Status is Rejected or Reset.');+ }+ const token = context.auth.secret_text;+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const body: Record<string, unknown> = { user, status };+ if (reasonText !== undefined) {+ body[status === 'rejected' ? 'rejectionReason' : 'resetReason'] = reasonText;+ }+ await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/user-access-request/handle`,+ body,+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ username: user,+ status,+ reason: reasonText ?? null,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-parquet-files.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-parquet-files.tsnew file mode 100644index 00000000000..cb637967b5b--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-parquet-files.ts@@ -0,0 +1,42 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { hfHub } from '../common/hub-client';+import { listDatasetParquetFilesOutputSchema } from '../output-schemas';++export const listDatasetParquetFiles = createAction({+ auth: huggingFaceAuth,+ name: 'list_dataset_parquet_files',+ classification: 'SEARCH',+ displayName: 'List Parquet Files',+ description: 'List the auto-converted Parquet files of a dataset, with their download URLs and sizes.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists the Parquet files the dataset viewer converted a dataset into (under the refs/convert/parquet revision), one entry per file with its subset (config), split, filename, size in bytes and download URL, optionally narrowed to one subset. The URLs are binary download URLs for external tools, not readable with Read Repo File; to read rows use Get Dataset Rows. If unsure the viewer serves this dataset, call Check Dataset Viewer Support first. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: listDatasetParquetFilesOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.optionalConfig(),+ },+ async run(context) {+ const { dataset, config } = context.propsValue;+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/parquet',+ dataset,+ query: [['config', config?.trim()]],+ });+ const record = hfHub.isRecord(body) ? body : {};+ const files = Array.isArray(record['parquet_files']) ? record['parquet_files'] : [];+ return {+ parquet_files: files,+ count: files.length,+ pending: Array.isArray(record['pending']) ? record['pending'] : [],+ failed: Array.isArray(record['failed']) ? record['failed'] : [],+ partial: record['partial'] === true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-splits.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-splits.tsnew file mode 100644index 00000000000..1e1382f4bed--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-dataset-splits.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { hfHub } from '../common/hub-client';+import { listDatasetSplitsOutputSchema } from '../output-schemas';++export const listDatasetSplits = createAction({+ auth: huggingFaceAuth,+ name: 'list_dataset_splits',+ classification: 'SEARCH',+ displayName: 'List Dataset Subsets & Splits',+ description: 'List the subsets (configs) and splits of a dataset in the dataset viewer.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists every subset (config) and split of a dataset, the resolver for the config and split inputs of every other dataset viewer action; pending lists subsets still being processed and failed lists subsets the viewer could not process. If unsure whether the dataset is served at all, call Check Dataset Viewer Support first. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: listDatasetSplitsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.optionalConfig(),+ },+ async run(context) {+ const { dataset, config } = context.propsValue;+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/splits',+ dataset,+ query: [['config', config?.trim()]],+ });+ const record = hfHub.isRecord(body) ? body : {};+ const splits = Array.isArray(record['splits']) ? record['splits'] : [];+ return {+ splits,+ count: splits.length,+ pending: Array.isArray(record['pending']) ? record['pending'] : [],+ failed: Array.isArray(record['failed']) ? record['failed'] : [],+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-gated-access-requests.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-gated-access-requests.tsnew file mode 100644index 00000000000..8f569db9937--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-gated-access-requests.ts@@ -0,0 +1,128 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { hfUtils } from '../common/utils';+import { listGatedAccessRequestsOutputSchema } from '../output-schemas';++function flattenRequest(entry: unknown) {+ const record = hfHub.isRecord(entry) ? entry : {};+ const user = record['user'];+ const grantedBy = record['grantedBy'];+ const fields = record['fields'];+ return {+ username: hfWrite.readString({ record: user, key: 'user' }),+ user_id: hfWrite.readString({ record: user, key: '_id' }),+ fullname: hfWrite.readString({ record: user, key: 'fullname' }),+ email: hfWrite.readString({ record: user, key: 'email' }),+ status: hfWrite.readString({ record, key: 'status' }),+ requested_at: hfWrite.readString({ record, key: 'timestamp' }),+ reviewed_at: hfWrite.readString({ record, key: 'reviewedAt' }),+ granted_by: hfWrite.readString({ record: grantedBy, key: 'user' }),+ fields: hfHub.isRecord(fields) ? fields : {},+ };+}++export const listGatedAccessRequests = createAction({+ auth: huggingFaceAuth,+ name: 'list_gated_access_requests',+ classification: 'SEARCH',+ displayName: 'List Gated Access Requests',+ description: 'List the access requests of a gated model or dataset by status.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists the users who requested access to a gated model or dataset, filtered by status (pending, accepted, rejected or reset) and optionally by requester text or request date, with each requester's username, contact email and the answers to the gate form. Use it to find the username for Accept or Reject Access Request. Page with Requested Before / After using the returned oldest/newest request times. Read-only and safe to retry, but only repository owners or admins can call it (write-role token).",+ idempotent: true,+ },+ outputSchema: listGatedAccessRequestsOutputSchema,+ props: {+ repo_type: Property.StaticDropdown({+ displayName: 'Repository Type',+ description: 'Gated access exists for models and datasets only.',+ required: true,+ defaultValue: 'model',+ options: {+ disabled: false,+ options: [+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ ],+ },+ }),+ repo_id: hfProps.repoId(),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Which requests to list. Defaults to pending.',+ required: true,+ defaultValue: 'pending',+ options: {+ disabled: false,+ options: [+ { label: 'Pending', value: 'pending' },+ { label: 'Accepted', value: 'accepted' },+ { label: 'Rejected', value: 'rejected' },+ { label: 'Reset', value: 'reset' },+ ],+ },+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only requests whose requester username, full name, email, email domain or verified organization matches this text.',+ required: false,+ }),+ after: Property.DateTime({+ displayName: 'Requested After',+ description: 'Only requests made after this date and time (ISO 8601).',+ required: false,+ }),+ before: Property.DateTime({+ displayName: 'Requested Before',+ description: 'Only requests made before this date and time (ISO 8601).',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of requests to return (10 to 1000). Defaults to 100.',+ required: false,+ defaultValue: 100,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, status, search, after, before, limit } = context.propsValue;+ if (repo_type !== 'model' && repo_type !== 'dataset') {+ throw new Error("Repository Type must be 'model' or 'dataset'; Spaces have no gated access.");+ }+ hfUtils.assertLimit({ value: limit, min: 10, max: 1000, name: 'Limit' });+ const query = hfWrite.optionalText({ value: search, name: 'Search', maxLength: 250 });+ const token = context.auth.secret_text;+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const response = await hfWrite.request({+ token,+ method: HttpMethod.GET,+ path: `${repo.apiPath}/user-access-request/${encodeURIComponent(status)}`,+ query: [+ ['limit', limit ?? 100],+ ['q', query],+ ['after', after],+ ['before', before],+ ],+ });+ const requests = (Array.isArray(response) ? response : []).map(flattenRequest);+ const times = requests+ .map((request) => request.requested_at)+ .filter((value): value is string => value !== null)+ .sort();+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ status,+ requests,+ count: requests.length,+ oldest_requested_at: times.length > 0 ? times[0] : null,+ newest_requested_at: times.length > 0 ? times[times.length - 1] : null,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-inference-endpoints.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-inference-endpoints.tsnew file mode 100644index 00000000000..8a8de7933b5--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-inference-endpoints.ts@@ -0,0 +1,136 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { AuthenticationType, httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { listInferenceEndpointsOutputSchema } from '../output-schemas';++export const listInferenceEndpoints = createAction({+ auth: huggingFaceAuth,+ name: 'list_inference_endpoints',+ classification: 'SEARCH',+ displayName: 'List Inference Endpoints',+ description: 'List the dedicated Inference Endpoints of a Hugging Face user or organization.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists the dedicated Inference Endpoints (paid, billing-enabled deployments) of a namespace, which defaults to the connected user: name, model repository, task, framework, state (for example 'running', 'paused' or 'scaledToZero'), public URL, access type, hardware, cloud vendor and region, and replica bounds. Pass an organization name to list its endpoints. A namespace without a payment method has no endpoints and may answer 401. Environment variables and secrets of the endpoints are never returned. For the serverless Inference Providers, use the inference actions instead. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: listInferenceEndpointsOutputSchema,+ props: {+ namespace: Property.ShortText({+ displayName: 'Namespace',+ description:+ "The user or organization that owns the endpoints, for example 'my-org'. Leave empty for the connected user. Get organization names from Get Current User & Token.",+ required: false,+ }),+ },+ async run(context) {+ const token = context.auth.secret_text;+ const namespace = context.propsValue.namespace?.trim() || (await currentUsername(token));+ const path = `/endpoint/${encodeURIComponent(namespace)}`;+ let body: unknown;+ try {+ const response = await httpClient.sendRequest<unknown>({+ method: HttpMethod.GET,+ url: `${INFERENCE_ENDPOINTS_BASE_URL}${path}`,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token },+ });+ body = response.body;+ } catch (error) {+ if (error instanceof HttpError && (error.response.status === 401 || error.response.status === 403)) {+ throw new Error(+ `Inference Endpoints refused the request for namespace '${namespace}' (${error.response.status}). Either the namespace has no payment method (Inference Endpoints are a paid product), this account is not a member of it, or the token lacks the Inference Endpoints read permission.`+ );+ }+ throw hfHub.toError({ error, resource: `Inference Endpoints ${path}` });+ }+ const items = hfHub.isRecord(body) && Array.isArray(body['items']) ? body['items'].filter(hfHub.isRecord) : [];+ const endpoints = items.map(toEndpoint);+ return { namespace, endpoints, count: endpoints.length };+ },+});++async function currentUsername(token: string): Promise<string> {+ const response = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: '/api/whoami-v2',+ });+ const name = hfHub.isRecord(response.body) ? response.body['name'] : undefined;+ if (typeof name !== 'string' || name.length === 0) {+ throw new Error('Could not determine the connected username. Provide Namespace explicitly.');+ }+ return name;+}++function toEndpoint(raw: Record<string, unknown>): EndpointRow {+ const model = pickRecord({ source: raw, key: 'model' });+ const status = pickRecord({ source: raw, key: 'status' });+ const compute = pickRecord({ source: raw, key: 'compute' });+ const scaling = pickRecord({ source: compute, key: 'scaling' });+ const provider = pickRecord({ source: raw, key: 'provider' });+ return {+ name: pickString({ source: raw, key: 'name' }),+ type: pickString({ source: raw, key: 'type' }),+ state: pickString({ source: status, key: 'state' }),+ url: pickString({ source: status, key: 'url' }),+ status_message: pickString({ source: status, key: 'message' }),+ created_at: pickString({ source: status, key: 'createdAt' }),+ updated_at: pickString({ source: status, key: 'updatedAt' }),+ repository: pickString({ source: model, key: 'repository' }),+ revision: pickString({ source: model, key: 'revision' }),+ task: pickString({ source: model, key: 'task' }),+ framework: pickString({ source: model, key: 'framework' }),+ accelerator: pickString({ source: compute, key: 'accelerator' }),+ instance_type: pickString({ source: compute, key: 'instanceType' }),+ instance_size: pickString({ source: compute, key: 'instanceSize' }),+ min_replica: pickNumber({ source: scaling, key: 'minReplica' }),+ max_replica: pickNumber({ source: scaling, key: 'maxReplica' }),+ vendor: pickString({ source: provider, key: 'vendor' }),+ region: pickString({ source: provider, key: 'region' }),+ };+}++function pickRecord({ source, key }: PickParams): Record<string, unknown> | null {+ const value = source?.[key];+ return hfHub.isRecord(value) ? value : null;+}++function pickString({ source, key }: PickParams): string | null {+ const value = source?.[key];+ return typeof value === 'string' ? value : null;+}++function pickNumber({ source, key }: PickParams): number | null {+ const value = source?.[key];+ return typeof value === 'number' ? value : null;+}++const INFERENCE_ENDPOINTS_BASE_URL = 'https://api.endpoints.huggingface.cloud/v2';++type PickParams = {+ source: Record<string, unknown> | null;+ key: string;+};++type EndpointRow = {+ name: string | null;+ type: string | null;+ state: string | null;+ url: string | null;+ status_message: string | null;+ created_at: string | null;+ updated_at: string | null;+ repository: string | null;+ revision: string | null;+ task: string | null;+ framework: string | null;+ accelerator: string | null;+ instance_type: string | null;+ instance_size: string | null;+ min_replica: number | null;+ max_replica: number | null;+ vendor: string | null;+ region: string | null;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-notifications.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-notifications.tsnew file mode 100644index 00000000000..741f2aeabf5--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-notifications.ts@@ -0,0 +1,172 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfProps } from '../common/props';+import { hfUtils } from '../common/utils';+import { listNotificationsOutputSchema } from '../output-schemas';++export const listNotifications = createAction({+ auth: huggingFaceAuth,+ name: 'list_notifications',+ classification: 'SEARCH',+ displayName: 'List Notifications',+ description: 'List the Hugging Face notifications of the connected account.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists the connected account's Hub notifications (discussion and pull-request activity on repositories, paper discussions, posts and community blogs), one page per call with a next_page, optionally only unread ones or only those for one repository or where the user is mentioned. Each entry carries a 24-character discussion_id, which is what Delete Notifications needs (not the per-repository discussion number). Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: listNotificationsOutputSchema,+ props: {+ read_status: Property.StaticDropdown({+ displayName: 'Read Status',+ description: 'Return all notifications or only unread ones. Defaults to all.',+ required: false,+ defaultValue: 'all',+ options: {+ disabled: false,+ options: [+ { label: 'All', value: 'all' },+ { label: 'Unread only', value: 'unread' },+ ],+ },+ }),+ mention: Property.StaticDropdown({+ displayName: 'Involvement',+ description:+ 'All notifications, only threads the user participates in, or only threads where the user is mentioned. Defaults to all.',+ required: false,+ defaultValue: 'all',+ options: {+ disabled: false,+ options: [+ { label: 'All', value: 'all' },+ { label: 'Participating', value: 'participating' },+ { label: 'Mentions', value: 'mentions' },+ ],+ },+ }),+ repo_type: Property.StaticDropdown({+ displayName: 'Repository Type',+ description: 'Only notifications about this kind of repository. Leave empty for every kind.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ { label: 'Space', value: 'space' },+ ],+ },+ }),+ repo_name: Property.ShortText({+ displayName: 'Repository ID',+ description: "Only notifications about this repository, in 'namespace/name' form, for example 'openai-community/gpt2'.",+ required: false,+ }),+ page: hfProps.page(),+ },+ async run(context) {+ const { read_status, mention, repo_type, repo_name, page } = context.propsValue;+ hfUtils.assertLimit({ value: page, min: 0, max: Number.MAX_SAFE_INTEGER, name: 'Page' });+ const currentPage = page ?? 0;+ const response = await hfHub.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/api/notifications',+ query: [+ ['p', currentPage],+ ['readStatus', read_status],+ ['mention', mention],+ ['repoType', repo_type],+ ['repoName', repo_name?.trim()],+ ],+ });+ const body = hfHub.isRecord(response.body) ? response.body : {};+ const rawNotifications = Array.isArray(body['notifications']) ? body['notifications'].filter(hfHub.isRecord) : [];+ const counts = hfHub.isRecord(body['count']) ? body['count'] : {};+ const start = typeof body['start'] === 'number' ? body['start'] : null;+ const matching = typeof counts['view'] === 'number' ? counts['view'] : null;+ const hasMore =+ rawNotifications.length > 0 && start !== null && matching !== null && start + rawNotifications.length < matching;+ return {+ notifications: rawNotifications.map(toNotification),+ count: rawNotifications.length,+ total_matching: matching,+ total_unread: typeof counts['unread'] === 'number' ? counts['unread'] : null,+ total_all: typeof counts['all'] === 'number' ? counts['all'] : null,+ next_page: hasMore ? currentPage + 1 : null,+ };+ },+});++function toNotification(raw: Record<string, unknown>): NotificationRow {+ const type = pickString({ source: raw, key: 'type' });+ const repo = pickRecord({ source: raw, key: 'repo' });+ const discussion = pickRecord({ source: raw, key: 'discussion' });+ const paper = pickRecord({ source: raw, key: 'paper' });+ const paperDiscussion = pickRecord({ source: raw, key: 'paperDiscussion' });+ const post = pickRecord({ source: raw, key: 'post' });+ const blog = pickRecord({ source: raw, key: 'blog' });+ const thread = discussion ?? paperDiscussion ?? post ?? blog;+ const participants = Array.isArray(thread?.['participating']) ? thread['participating'].filter(hfHub.isRecord) : [];+ return {+ type,+ read: raw['read'] === true,+ updated_at: pickString({ source: raw, key: 'updatedAt' }),+ discussion_id: pickString({ source: discussion, key: 'id' }) ?? pickString({ source: paperDiscussion, key: 'id' }),+ title:+ pickString({ source: discussion, key: 'title' }) ??+ pickString({ source: paper, key: 'title' }) ??+ pickString({ source: post, key: 'title' }) ??+ pickString({ source: blog, key: 'title' }),+ repo_id: pickString({ source: repo, key: 'name' }),+ repo_type: pickString({ source: repo, key: 'type' }),+ discussion_num: typeof discussion?.['num'] === 'number' ? discussion['num'] : null,+ discussion_status: pickString({ source: discussion, key: 'status' }),+ is_pull_request: typeof discussion?.['isPullRequest'] === 'boolean' ? discussion['isPullRequest'] : null,+ paper_id: pickString({ source: paper, key: '_id' }),+ post_id: pickString({ source: post, key: 'id' }) ?? pickString({ source: blog, key: 'id' }),+ post_slug: pickString({ source: post, key: 'slug' }) ?? pickString({ source: blog, key: 'slug' }),+ post_author: pickString({ source: post, key: 'authorName' }) ?? pickString({ source: blog, key: 'authorName' }),+ participants: participants+ .map((participant) => pickString({ source: participant, key: 'user' }))+ .filter((user): user is string => user !== null)+ .join(', '),+ };+}++function pickRecord({ source, key }: PickParams): Record<string, unknown> | null {+ const value = source?.[key];+ return hfHub.isRecord(value) ? value : null;+}++function pickString({ source, key }: PickParams): string | null {+ const value = source?.[key];+ return typeof value === 'string' ? value : null;+}++type PickParams = {+ source: Record<string, unknown> | null;+ key: string;+};++type NotificationRow = {+ type: string | null;+ read: boolean;+ updated_at: string | null;+ discussion_id: string | null;+ title: string | null;+ repo_id: string | null;+ repo_type: string | null;+ discussion_num: number | null;+ discussion_status: string | null;+ is_pull_request: boolean | null;+ paper_id: string | null;+ post_id: string | null;+ post_slug: string | null;+ post_author: string | null;+ participants: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-webhooks.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-webhooks.tsnew file mode 100644index 00000000000..f7489d2f1fe--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-webhooks.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfSettingsApi, hfWebhooks } from '../common/webhooks';+import { listWebhooksOutputSchema } from '../output-schemas';++export const listWebhooks = createAction({+ auth: huggingFaceAuth,+ name: 'list_webhooks',+ classification: 'SEARCH',+ displayName: 'List Webhooks',+ description: 'List the webhooks configured on the connected Hugging Face account.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists every webhook on the connected account's Hub settings: ID, target URL, whether it is enabled (or why it is disabled), the watched users, organizations and repositories, the event domains and whether a signing secret is set. The secret itself is never returned. Use it to find a webhook ID for Get, Update, Enable or Disable, or Delete Webhook. Needs a 'write' role token or a fine-grained token with webhook permission. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: listWebhooksOutputSchema,+ props: {},+ async run(context) {+ const response = await hfSettingsApi.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/api/settings/webhooks',+ });+ const webhooks = Array.isArray(response.body) ? response.body.map(hfWebhooks.toOutput) : [];+ return { webhooks, count: webhooks.length };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/pin-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/pin-discussion.tsnew file mode 100644index 00000000000..1f752dd9f77--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/pin-discussion.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { pinDiscussionOutputSchema } from '../output-schemas';++export const pinDiscussion = createAction({+ auth: huggingFaceAuth,+ name: 'pin_discussion',+ classification: 'WRITE',+ displayName: 'Pin or Unpin Discussion',+ description: 'Pin a discussion to the top of a repository Community tab, or unpin it.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Pins a discussion or pull request to the top of a model, dataset or Space repository's Community tab, or unpins it. Setting the same state again is a no-op, so it is safe to retry. Requires a write-role token with write or admin rights on the repository.",+ idempotent: true,+ },+ outputSchema: pinDiscussionOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ discussion_number: Property.Number({+ displayName: 'Discussion Number',+ description: "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ required: true,+ }),+ action: Property.StaticDropdown({+ displayName: 'Action',+ description: 'Pin or unpin the discussion.',+ required: true,+ defaultValue: 'pin',+ options: {+ disabled: false,+ options: [+ { label: 'Pin', value: 'pin' },+ { label: 'Unpin', value: 'unpin' },+ ],+ },+ }),+ },+ async run(context) {+ const { repo_type, repo_id, discussion_number, action } = context.propsValue;+ const token = context.auth.secret_text;+ const num = hfWrite.assertDiscussionNumber(discussion_number);+ if (action !== 'pin' && action !== 'unpin') {+ throw new Error("Action must be 'pin' or 'unpin'.");+ }+ const pinned = action === 'pin';+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/discussions/${num}/pin`,+ body: { pinned },+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ pinned,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/preview-dataset-rows.ts b/packages/pieces/community/hugging-face/src/lib/actions/preview-dataset-rows.tsnew file mode 100644index 00000000000..0f53bfb6bde--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/preview-dataset-rows.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { hfHub } from '../common/hub-client';+import { hfUtils } from '../common/utils';+import { previewDatasetRowsOutputSchema } from '../output-schemas';++export const previewDatasetRows = createAction({+ auth: huggingFaceAuth,+ name: 'preview_dataset_rows',+ classification: 'READ',+ displayName: 'Preview Dataset Rows',+ description: 'Get the first rows (up to 100) of a dataset split, with its column types.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Returns the column features and the first rows (up to 100, default 20) of one dataset split. Works whenever Check Dataset Viewer Support reports preview:true, even when viewer:false makes Get Dataset Rows unavailable; use Get Dataset Rows instead to page past the first rows. Long cell values are cut and listed per row in truncated_cells. Resolve config and split with List Dataset Subsets & Splits. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: previewDatasetRowsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.config(),+ split: hfViewerProps.split(),+ max_rows: Property.Number({+ displayName: 'Max Rows',+ description: 'How many of the first rows to return (1 to 100). Defaults to 20.',+ required: false,+ defaultValue: 20,+ }),+ },+ async run(context) {+ const { dataset, config, split, max_rows } = context.propsValue;+ hfUtils.assertLimit({ value: max_rows, min: 1, max: 100, name: 'Max Rows' });+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/first-rows',+ dataset,+ query: [+ ['config', config.trim()],+ ['split', split.trim()],+ ],+ });+ const record = hfHub.isRecord(body) ? body : {};+ const allRows = Array.isArray(record['rows']) ? record['rows'] : [];+ const rows = allRows.slice(0, max_rows ?? 20);+ return {+ ...record,+ rows,+ count: rows.length,+ rows_available: allRows.length,+ truncated: record['truncated'] === true || rows.length < allRows.length,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/rename-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/rename-discussion.tsnew file mode 100644index 00000000000..db95468af1f--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/rename-discussion.ts@@ -0,0 +1,62 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { renameDiscussionOutputSchema } from '../output-schemas';++export const renameDiscussion = createAction({+ auth: huggingFaceAuth,+ name: 'rename_discussion',+ classification: 'WRITE',+ displayName: 'Rename Discussion',+ description: 'Change the title of a discussion or pull request of a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Changes the title of an existing discussion or pull request of a model, dataset or Space repository; the change is shown publicly in the thread. Re-applying the same title converges, so it is safe to retry. Requires a write-role token and being the thread author or having write access to the repository.",+ idempotent: true,+ },+ outputSchema: renameDiscussionOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ discussion_number: Property.Number({+ displayName: 'Discussion Number',+ description: "The discussion or pull request number within the repository (the 'num' from List Discussions & PRs).",+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'New Title',+ description: 'The new title, 3 to 200 characters.',+ required: true,+ }),+ },+ async run(context) {+ const { repo_type, repo_id, discussion_number, title } = context.propsValue;+ const token = context.auth.secret_text;+ const num = hfWrite.assertDiscussionNumber(discussion_number);+ const newTitle = hfWrite.requireText({ value: title, name: 'New Title', maxLength: 200 });+ if (newTitle.length < 3) {+ throw new Error('New Title must be at least 3 characters.');+ }+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const response = await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${repo.apiPath}/discussions/${num}/title`,+ body: { title: newTitle },+ });+ const event = hfHub.isRecord(response) ? response['newTitle'] : undefined;+ const data = hfHub.isRecord(event) ? event['data'] : undefined;+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ discussion_number: num,+ title: hfWrite.readString({ record: data, key: 'to' }) ?? newTitle,+ previous_title: hfWrite.readString({ record: data, key: 'from' }),+ event_id: hfWrite.readString({ record: event, key: 'id' }),+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/reply-to-paper-comment.ts b/packages/pieces/community/hugging-face/src/lib/actions/reply-to-paper-comment.tsnew file mode 100644index 00000000000..7f39f66e0b4--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/reply-to-paper-comment.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfWrite } from '../common/hub-write';+import { replyToPaperCommentOutputSchema } from '../output-schemas';++export const replyToPaperComment = createAction({+ auth: huggingFaceAuth,+ name: 'reply_to_paper_comment',+ classification: 'WRITE',+ displayName: 'Reply to Paper Comment',+ description: 'Post a public reply to a comment on a research paper page on Hugging Face.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Posts a reply under an existing comment on a Hugging Face Papers page, publicly and permanently visible to everyone under the connected user's name. Only post when the user explicitly asks and approves the text. Get the comment ID from Get Paper with Include Comments on. Each call adds another reply, so retries duplicate. Requires a write-role token.",+ idempotent: false,+ },+ outputSchema: replyToPaperCommentOutputSchema,+ props: {+ paper_id: Property.ShortText({+ displayName: 'Paper ID',+ description: "The paper's arXiv ID, for example '2307.09288'.",+ required: true,+ }),+ comment_id: Property.ShortText({+ displayName: 'Comment ID',+ description: 'The ID of the comment to reply to, from Get Paper with Include Comments on.',+ required: true,+ }),+ comment: Property.LongText({+ displayName: 'Reply',+ description: 'The public reply text, in Markdown (up to 65,536 characters).',+ required: true,+ }),+ },+ async run(context) {+ const { paper_id, comment_id, comment } = context.propsValue;+ const paperId = hfWrite.requireText({ value: paper_id, name: 'Paper ID' });+ const parentId = hfWrite.requireText({ value: comment_id, name: 'Comment ID' });+ const text = hfWrite.requireText({ value: comment, name: 'Reply', maxLength: 65536 });+ const response = await hfWrite.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/api/papers/${encodeURIComponent(paperId)}/comment/${encodeURIComponent(parentId)}/reply`,+ body: { comment: text },+ });+ const newMessage = hfHub.isRecord(response) ? response['newMessage'] : undefined;+ const replyId = hfWrite.readString({ record: newMessage, key: 'id' });+ return {+ paper_id: paperId,+ parent_comment_id: parentId,+ comment_id: replyId,+ created_at: hfWrite.readString({ record: newMessage, key: 'createdAt' }),+ url: `${hfHub.baseUrl}/papers/${encodeURIComponent(paperId)}${replyId ? `#${replyId}` : ''}`,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-dataset-rows.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-dataset-rows.tsnew file mode 100644index 00000000000..f357351e195--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-dataset-rows.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { huggingFaceAuth } from '../auth';+import { hfViewer, hfViewerProps } from '../common/dataset-viewer';+import { getDatasetRowsOutputSchema } from '../output-schemas';++export const searchDatasetRows = createAction({+ auth: huggingFaceAuth,+ name: 'search_dataset_rows',+ classification: 'SEARCH',+ displayName: 'Search Dataset Rows',+ description: 'Full-text search over the text columns of a dataset split.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Full-text searches the string columns of one dataset split and returns one page of up to 100 matching rows with their original row_idx, plus num_rows_total (total matches) and next_offset for paging. Only works when Check Dataset Viewer Support reports search:true (call it first when unsure). For exact column conditions such as label=1 use Filter Dataset Rows instead. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: getDatasetRowsOutputSchema,+ props: {+ dataset: hfViewerProps.dataset(),+ config: hfViewerProps.config(),+ split: hfViewerProps.split(),+ query: Property.ShortText({+ displayName: 'Query',+ description: "Words to look for in the text columns, for example 'wonderful acting'.",+ required: true,+ }),+ offset: hfViewerProps.offset(),+ length: hfViewerProps.length(),+ },+ async run(context) {+ const { dataset, config, split, query } = context.propsValue;+ const { offset, length } = hfViewer.validatePaging({+ offset: context.propsValue.offset,+ length: context.propsValue.length,+ });+ const text = query.trim();+ if (text.length === 0) {+ throw new Error('Query must not be empty.');+ }+ const body = await hfViewer.request<unknown>({+ token: context.auth.secret_text,+ path: '/search',+ dataset,+ query: [+ ['config', config.trim()],+ ['split', split.trim()],+ ['query', text],+ ['offset', offset],+ ['length', length],+ ],+ });+ return hfViewer.withPaging({ body, offset });+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-hf-docs.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-hf-docs.tsnew file mode 100644index 00000000000..056a82de826--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-hf-docs.ts@@ -0,0 +1,148 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfUtils } from '../common/utils';+import { searchHfDocsOutputSchema } from '../output-schemas';++const HEADING_KEYS = ['heading1', 'heading2', 'heading3', 'heading4', 'heading5'];++const DOC_PRODUCTS = [+ 'hub',+ 'transformers',+ 'diffusers',+ 'datasets',+ 'gradio',+ 'trackio',+ 'smolagents',+ 'huggingface_hub',+ 'cli',+ 'huggingface.js',+ 'transformers.js',+ 'inference-providers',+ 'inference-endpoints',+ 'peft',+ 'accelerate',+ 'optimum',+ 'optimum-habana',+ 'optimum-neuron',+ 'optimum-intel',+ 'optimum-executorch',+ 'optimum-tpu',+ 'tokenizers',+ 'llm-course',+ 'context-course',+ 'robotics-course',+ 'mcp-course',+ 'smol-course',+ 'agents-course',+ 'deep-rl-course',+ 'computer-vision-course',+ 'evaluate',+ 'tasks',+ 'dataset-viewer',+ 'trl',+ 'openenv',+ 'simulate',+ 'sagemaker',+ 'timm',+ 'safetensors',+ 'tgi',+ 'setfit',+ 'audio-course',+ 'lerobot',+ 'reachy_mini',+ 'autotrain',+ 'tei',+ 'bitsandbytes',+ 'cookbook',+ 'sentence_transformers',+ 'ml-games-course',+ 'diffusion-course',+ 'ml-for-3d-course',+ 'chat-ui',+ 'leaderboards',+ 'lighteval',+ 'argilla',+ 'distilabel',+ 'microsoft-azure',+ 'kernels',+ 'google-cloud',+ 'xet',+];++export const searchHfDocs = createAction({+ auth: huggingFaceAuth,+ name: 'search_hf_docs',+ classification: 'SEARCH',+ displayName: 'Search Hugging Face Docs',+ description: 'Search the official Hugging Face documentation.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Searches the official Hugging Face documentation (Hub, Transformers, Datasets, Inference Providers, Inference Endpoints, the huggingface_hub client and many more) and returns the best-matching passages, each with its page title, section headings, URL and text. Optionally restrict to one product. Use it to look up how a Hub feature, API parameter or library works. Returns at most 25 passages and no pagination. Read-only and safe to retry.",+ idempotent: true,+ },+ outputSchema: searchHfDocsOutputSchema,+ props: {+ query: Property.ShortText({+ displayName: 'Query',+ description: "What to look for, in plain words, for example 'webhook secret header'. Up to 250 characters.",+ required: true,+ }),+ product: Property.StaticDropdown({+ displayName: 'Product',+ description: 'Only search the documentation of this product. Leave empty to search all of them.',+ required: false,+ options: {+ disabled: false,+ options: DOC_PRODUCTS.map((product) => ({ label: product, value: product })),+ },+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of passages to return (1 to 25). Defaults to 10.',+ required: false,+ defaultValue: 10,+ }),+ },+ async run(context) {+ const { query, product, limit } = context.propsValue;+ const q = query.trim();+ if (q.length === 0 || q.length > 250) {+ throw new Error('Query must be between 1 and 250 characters.');+ }+ hfUtils.assertLimit({ value: limit, min: 1, max: 25, name: 'Limit' });+ const response = await hfHub.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/api/docs/search',+ query: [+ ['q', q],+ ['product', product],+ ['limit', limit],+ ],+ });+ const hits = Array.isArray(response.body) ? response.body.filter(hfHub.isRecord) : [];+ const results = hits.map((hit) => ({+ title: pickString({ source: hit, key: 'source_page_title' }),+ url: pickString({ source: hit, key: 'source_page_url' }),+ product: pickString({ source: hit, key: 'product' }),+ section: HEADING_KEYS.map((key) => pickString({ source: hit, key }))+ .filter((heading): heading is string => heading !== null && heading.length > 0)+ .join(' > '),+ text: pickString({ source: hit, key: 'text' }),+ }));+ return { results, count: results.length };+ },+});++function pickString({ source, key }: PickParams): string | null {+ const value = source[key];+ return typeof value === 'string' ? value : null;+}++type PickParams = {+ source: Record<string, unknown>;+ key: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/set-webhook-enabled.ts b/packages/pieces/community/hugging-face/src/lib/actions/set-webhook-enabled.tsnew file mode 100644index 00000000000..5294aaf23fe--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/set-webhook-enabled.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfSettingsApi, hfWebhooks } from '../common/webhooks';+import { webhookOutputSchema } from '../output-schemas';++export const setWebhookEnabled = createAction({+ auth: huggingFaceAuth,+ name: 'set_webhook_enabled',+ classification: 'WRITE',+ displayName: 'Enable or Disable Webhook',+ description: 'Turn a Hugging Face webhook on or off without deleting it.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Enables or disables a webhook by its 24-character ID without changing its configuration: a disabled webhook keeps its URL, watched items and secret but receives no deliveries. Use it to pause or resume a webhook, including one the Hub suspended after repeated failures; prefer it over Delete Webhook. Find the ID with List Webhooks. Needs a 'write' role token or a fine-grained token with webhook permission. Safe to retry: setting the same state again converges.",+ idempotent: true,+ },+ outputSchema: webhookOutputSchema,+ props: {+ webhook_id: hfWebhooks.webhookIdProp(),+ enabled: Property.Checkbox({+ displayName: 'Enabled',+ description: 'Checked to enable the webhook, unchecked to disable it.',+ required: true,+ defaultValue: true,+ }),+ },+ async run(context) {+ const { webhook_id, enabled } = context.propsValue;+ const response = await hfSettingsApi.request<unknown>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `${hfWebhooks.path(webhook_id)}/${enabled === false ? 'disable' : 'enable'}`,+ });+ return hfWebhooks.toOutput(hfWebhooks.unwrap(response.body));+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/update-repo-settings.ts b/packages/pieces/community/hugging-face/src/lib/actions/update-repo-settings.tsnew file mode 100644index 00000000000..c62a90c80cf--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/update-repo-settings.ts@@ -0,0 +1,158 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { hfProps } from '../common/props';+import { updateRepoSettingsOutputSchema } from '../output-schemas';++function pickOption<T extends string>({ value, allowed, name }: PickOptionParams<T>): T | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const match = allowed.find((option) => option === value);+ if (match === undefined) {+ throw new Error(+ `${name} must be one of ${allowed.map((option) => `'${option}'`).join(', ')}, or empty to keep the current setting.`+ );+ }+ return match;+}++export const updateRepoSettings = createAction({+ auth: huggingFaceAuth,+ name: 'update_repo_settings',+ classification: 'WRITE',+ displayName: 'Update Repo Settings',+ description: 'Change the visibility, discussions or gated-access settings of a Hub repository.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Changes only the settings you provide on a model, dataset or Space repository (visibility, discussions on/off, gated access mode, gated-request notifications); every setting left empty is kept as it is. Warning: switching Visibility to Public exposes the repository and its files to everyone, and setting Gated Access to 'Not gated' removes the access gate, so only do either when the user explicitly asks. Safe to retry. Requires a write-role token with admin rights on the repository.",+ idempotent: true,+ },+ outputSchema: updateRepoSettingsOutputSchema,+ props: {+ repo_type: hfProps.repoType(),+ repo_id: hfProps.repoId(),+ visibility: Property.StaticDropdown({+ displayName: 'Visibility',+ description:+ 'Leave empty to keep the current visibility. Public makes the repository and all its files visible to everyone.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Private', value: 'private' },+ { label: 'Public', value: 'public' },+ ],+ },+ }),+ discussions: Property.StaticDropdown({+ displayName: 'Discussions',+ description: 'Leave empty to keep the current setting. Disabled hides the Community tab and blocks new discussions.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Enabled', value: 'enabled' },+ { label: 'Disabled', value: 'disabled' },+ ],+ },+ }),+ gated: Property.StaticDropdown({+ displayName: 'Gated Access',+ description:+ "Leave empty to keep the current gate. 'Automatic approval' and 'Manual approval' require users to request access; 'Not gated' removes the gate. Not available for Spaces.",+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Not gated', value: 'false' },+ { label: 'Automatic approval', value: 'auto' },+ { label: 'Manual approval', value: 'manual' },+ ],+ },+ }),+ gated_notifications_mode: Property.StaticDropdown({+ displayName: 'Access Request Notifications',+ description: 'Leave empty to keep the current mode. How the owner is notified of new gated-access requests.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Real-time (one email per request)', value: 'real-time' },+ { label: 'Bulk (daily digest)', value: 'bulk' },+ ],+ },+ }),+ gated_notifications_email: Property.ShortText({+ displayName: 'Notification Email',+ description: 'Leave empty to keep the current address. The email address that receives gated-access request notifications.',+ required: false,+ }),+ },+ async run(context) {+ const {+ repo_type,+ repo_id,+ visibility,+ discussions,+ gated,+ gated_notifications_mode,+ gated_notifications_email,+ } = context.propsValue;+ const token = context.auth.secret_text;+ const settings: Record<string, unknown> = {};+ const selectedVisibility = pickOption({ value: visibility, allowed: VISIBILITY_OPTIONS, name: 'Visibility' });+ if (selectedVisibility !== undefined) {+ settings['private'] = selectedVisibility === 'private';+ }+ const selectedDiscussions = pickOption({ value: discussions, allowed: DISCUSSIONS_OPTIONS, name: 'Discussions' });+ if (selectedDiscussions !== undefined) {+ settings['discussionsDisabled'] = selectedDiscussions === 'disabled';+ }+ const selectedGated = pickOption({ value: gated, allowed: GATED_OPTIONS, name: 'Gated Access' });+ if (selectedGated !== undefined) {+ settings['gated'] = selectedGated === 'false' ? false : selectedGated;+ }+ const selectedNotificationsMode = pickOption({+ value: gated_notifications_mode,+ allowed: NOTIFICATIONS_MODE_OPTIONS,+ name: 'Access Request Notifications',+ });+ if (selectedNotificationsMode !== undefined) {+ settings['gatedNotificationsMode'] = selectedNotificationsMode;+ }+ const email = hfWrite.optionalText({ value: gated_notifications_email, name: 'Notification Email' });+ if (email !== undefined) {+ settings['gatedNotificationsEmail'] = email;+ }+ if (Object.keys(settings).length === 0) {+ throw new Error('Provide at least one setting to change. Settings left empty are never modified.');+ }+ const repo = await hfWrite.resolveRepo({ token, repoType: repo_type, repoId: repo_id });+ const response = await hfWrite.request({+ token,+ method: HttpMethod.PUT,+ path: `${repo.apiPath}/settings`,+ body: settings,+ });+ return {+ repo_id: repo.repoId,+ repo_type: repo.repoType,+ updated_settings: Object.keys(settings),+ settings: response ?? settings,+ };+ },+});++const VISIBILITY_OPTIONS: readonly ('private' | 'public')[] = ['private', 'public'];+const DISCUSSIONS_OPTIONS: readonly ('enabled' | 'disabled')[] = ['enabled', 'disabled'];+const GATED_OPTIONS: readonly ('false' | 'auto' | 'manual')[] = ['false', 'auto', 'manual'];+const NOTIFICATIONS_MODE_OPTIONS: readonly ('real-time' | 'bulk')[] = ['real-time', 'bulk'];++type PickOptionParams<T extends string> = {+ value: unknown;+ allowed: readonly T[];+ name: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/update-watch-list.ts b/packages/pieces/community/hugging-face/src/lib/actions/update-watch-list.tsnew file mode 100644index 00000000000..7bf369ba216--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/update-watch-list.ts@@ -0,0 +1,102 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfHub } from '../common/hub-client';+import { hfRepo } from '../common/repo';+import { hfSettingsApi, hfWebhooks, WatchedItem } from '../common/webhooks';+import { updateWatchListOutputSchema } from '../output-schemas';++export const updateWatchList = createAction({+ auth: huggingFaceAuth,+ name: 'update_watch_list',+ classification: 'WRITE',+ displayName: 'Watch or Unwatch',+ description: 'Start or stop watching Hugging Face users, organizations or repositories.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Adds items to, or removes items from, the connected account's Hub watch list, which controls the discussion notifications the user receives. Items are users, organizations, or model, dataset or Space repositories, given by name; each is resolved to its Hub ObjectId first, so an unknown name fails with 404 before anything changes. Only the listed items change; the rest of the watch list is untouched. Needs a 'write' role token. Safe to retry: watching an already-watched item or unwatching one that is not watched is a no-op.",+ idempotent: true,+ },+ outputSchema: updateWatchListOutputSchema,+ props: {+ watch: hfWebhooks.watchedItemsProp({+ required: false,+ description: 'Users, organizations or repositories to start watching.',+ }),+ unwatch: hfWebhooks.watchedItemsProp({+ required: false,+ description: 'Users, organizations or repositories to stop watching.',+ }),+ },+ async run(context) {+ const token = context.auth.secret_text;+ const toWatch = hfWebhooks.parseWatched(context.propsValue.watch);+ const toUnwatch = hfWebhooks.parseWatched(context.propsValue.unwatch);+ if (toWatch.length === 0 && toUnwatch.length === 0) {+ throw new Error('Provide at least one item to watch or unwatch.');+ }+ const added = await Promise.all(toWatch.map((item) => resolveWatchTarget({ token, item })));+ const removed = await Promise.all(toUnwatch.map((item) => resolveWatchTarget({ token, item })));+ await hfSettingsApi.request<unknown>({+ token,+ method: HttpMethod.PATCH,+ path: '/api/settings/watch',+ body: {+ add: added.map(({ id, watch_type }) => ({ id, type: watch_type })),+ delete: removed.map(({ id, watch_type }) => ({ id, type: watch_type })),+ },+ });+ return {+ watched: added,+ unwatched: removed,+ watched_count: added.length,+ unwatched_count: removed.length,+ };+ },+});++async function resolveWatchTarget({ token, item }: ResolveWatchTargetParams): Promise<WatchTarget> {+ const response = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: lookupPath(item),+ });+ const body = hfHub.isRecord(response.body) ? response.body : {};+ const id = body['_id'];+ if (typeof id !== 'string' || !OBJECT_ID_PATTERN.test(id)) {+ throw new Error(`Could not resolve the Hub ID of ${item.type} '${item.name}'. Check the name and type.`);+ }+ const canonicalName = typeof body['id'] === 'string' ? body['id'] : item.name;+ return {+ type: item.type,+ name: item.type === 'user' || item.type === 'org' ? item.name : canonicalName,+ id,+ watch_type: item.type === 'user' || item.type === 'org' ? item.type : 'repo',+ };+}++function lookupPath(item: WatchedItem): string {+ switch (item.type) {+ case 'user':+ return `/api/users/${encodeURIComponent(item.name)}/overview`;+ case 'org':+ return `/api/organizations/${encodeURIComponent(item.name)}/overview`;+ default:+ return `/api/${hfRepo.getTypeInfo(item.type).apiSegment}/${hfRepo.encodeRepoId(item.name)}`;+ }+}++const OBJECT_ID_PATTERN = /^[0-9a-fA-F]{24}$/;++type ResolveWatchTargetParams = {+ token: string;+ item: WatchedItem;+};++type WatchTarget = {+ type: string;+ name: string;+ id: string;+ watch_type: 'user' | 'org' | 'repo';+};diff --git a/packages/pieces/community/hugging-face/src/lib/actions/update-webhook.ts b/packages/pieces/community/hugging-face/src/lib/actions/update-webhook.tsnew file mode 100644index 00000000000..7a710b78730--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/update-webhook.ts@@ -0,0 +1,111 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfSettingsApi, hfWebhooks } from '../common/webhooks';+import { updateWebhookOutputSchema } from '../output-schemas';++export const updateWebhook = createAction({+ auth: huggingFaceAuth,+ name: 'update_webhook',+ classification: 'WRITE',+ displayName: 'Update Webhook',+ description: 'Change the target URL, watched items, domains or secret of a Hugging Face webhook.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Updates a webhook by its 24-character ID. It reads the current webhook first and changes only the fields you provide: Watched Items and Domains, when given, replace the whole existing list, so include every item to keep. The signing secret is sent only when you provide a new one; whether the Hub keeps an existing secret when it is omitted is not yet verified, so the result reports secret_status ('kept', 'replaced', 'set', 'cleared' or 'none') and a warning if it was cleared, in which case call again with the secret. Webhooks that run a Hub Job are refused. To pause deliveries use Enable or Disable Webhook. Needs a 'write' role token or a fine-grained token with webhook permission. Safe to retry with the same values.",+ idempotent: true,+ },+ outputSchema: updateWebhookOutputSchema,+ props: {+ webhook_id: hfWebhooks.webhookIdProp(),+ url: Property.ShortText({+ displayName: 'Target URL',+ description: 'New https:// address for deliveries. Leave empty to keep the current URL.',+ required: false,+ }),+ watched: hfWebhooks.watchedItemsProp({+ required: false,+ description:+ 'Replaces the full list of watched users, organizations and repositories. Leave empty to keep the current list.',+ }),+ domains: hfWebhooks.domainsProp({+ required: false,+ description: 'Replaces the event domains. Leave empty to keep the current domains.',+ }),+ secret: Property.ShortText({+ displayName: 'New Secret',+ description:+ 'A new shared secret for the X-Webhook-Secret header. Leave empty to not send one. Printable ASCII only.',+ required: false,+ }),+ },+ async run(context) {+ const { webhook_id, url, watched, domains, secret } = context.propsValue;+ const token = context.auth.secret_text;+ const newUrl = url !== undefined && url !== null && url.trim() !== '' ? hfWebhooks.assertHttpsUrl(url) : undefined;+ const newWatched = hfWebhooks.parseWatched(watched);+ const newDomains = hfWebhooks.parseDomains(domains);+ const newSecret = secret !== undefined && secret !== null && secret !== '' ? hfWebhooks.assertSecret(secret) : undefined;+ if (newUrl === undefined && newWatched.length === 0 && newDomains.length === 0 && newSecret === undefined) {+ throw new Error('Provide at least one field to change: Target URL, Watched Items, Domains or New Secret.');+ }+ const current = await hfWebhooks.fetch({ token, webhookId: webhook_id });+ const before = hfWebhooks.toOutput(current);+ if (before.runs_job) {+ throw new Error(+ 'This webhook runs a Hugging Face Job instead of calling a URL. Updating Job webhooks is not supported by this action; edit it in the Hub settings.'+ );+ }+ const mergedUrl = newUrl ?? before.url;+ if (mergedUrl === null) {+ throw new Error('The webhook has no target URL. Provide Target URL.');+ }+ const body: Record<string, unknown> = {+ url: mergedUrl,+ watched: newWatched.length > 0 ? newWatched : hfWebhooks.existingWatched(current['watched']),+ domains: newDomains.length > 0 ? newDomains : before.domains,+ };+ if (newSecret !== undefined) {+ body['secret'] = newSecret;+ }+ const response = await hfSettingsApi.request<unknown>({+ token,+ method: HttpMethod.POST,+ path: hfWebhooks.path(webhook_id),+ body,+ });+ const after = hfWebhooks.toOutput(hfWebhooks.unwrap(response.body));+ const secretStatus = describeSecret({+ hadSecret: before.has_secret,+ hasSecret: after.has_secret,+ sentSecret: newSecret !== undefined,+ });+ return {+ ...after,+ secret_status: secretStatus,+ warning:+ secretStatus === 'cleared'+ ? 'The Hub removed the existing signing secret because none was sent. Call Update Webhook again with New Secret to restore it.'+ : null,+ };+ },+});++function describeSecret({ hadSecret, hasSecret, sentSecret }: DescribeSecretParams): SecretStatus {+ if (sentSecret) {+ return hadSecret ? 'replaced' : 'set';+ }+ if (hadSecret) {+ return hasSecret ? 'kept' : 'cleared';+ }+ return 'none';+}++type DescribeSecretParams = {+ hadSecret: boolean;+ hasSecret: boolean;+ sentSecret: boolean;+};++type SecretStatus = 'kept' | 'replaced' | 'set' | 'cleared' | 'none';diff --git a/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-secret.ts b/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-secret.tsnew file mode 100644index 00000000000..099ce45df28--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-secret.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { upsertSpaceSecretOutputSchema } from '../output-schemas';++export const upsertSpaceSecret = createAction({+ auth: huggingFaceAuth,+ name: 'upsert_space_secret',+ classification: 'WRITE',+ displayName: 'Set Space Secret',+ description: 'Create or update a secret environment variable of a Hugging Face Space.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates or overwrites a secret (a private environment variable such as an API key) on a Space, keyed by name. Setting a secret restarts the Space, which briefly takes it offline and, on paid hardware, bills the restart. The value is never returned or readable back; the result only confirms the key. For non-sensitive settings use Set Space Variable. Re-setting the same key and value converges, so it is safe to retry. Requires a write-role token.",+ idempotent: true,+ },+ outputSchema: upsertSpaceSecretOutputSchema,+ props: {+ space_id: Property.ShortText({+ displayName: 'Space ID',+ description: "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.",+ required: true,+ }),+ key: Property.ShortText({+ displayName: 'Key',+ description: "The secret name: starts with a letter, then letters, digits or underscores, for example 'OPENAI_API_KEY'.",+ required: true,+ }),+ value: Property.LongText({+ displayName: 'Value',+ description: 'The secret value. It is stored encrypted and never shown again.',+ required: true,+ }),+ description: Property.ShortText({+ displayName: 'Description',+ description: 'Optional note about what the secret is for.',+ required: false,+ }),+ },+ async run(context) {+ const { space_id, key, value, description } = context.propsValue;+ const token = context.auth.secret_text;+ const secretKey = hfWrite.assertSpaceKey(key);+ if (typeof value !== 'string' || value.length === 0) {+ throw new Error('Value is required.');+ }+ const note = hfWrite.optionalText({ value: description, name: 'Description' });+ const space = await hfWrite.resolveRepo({ token, repoType: 'space', repoId: space_id });+ const body: Record<string, unknown> = { key: secretKey, value };+ if (note !== undefined) {+ body['description'] = note;+ }+ await hfWrite.sensitiveRequest({+ token,+ method: HttpMethod.POST,+ path: `${space.apiPath}/secrets`,+ body,+ });+ return {+ space_id: space.repoId,+ key: secretKey,+ updated: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-variable.ts b/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-variable.tsnew file mode 100644index 00000000000..db665714e7a--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/actions/upsert-space-variable.ts@@ -0,0 +1,67 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { huggingFaceAuth } from '../auth';+import { hfWrite } from '../common/hub-write';+import { upsertSpaceVariableOutputSchema } from '../output-schemas';++export const upsertSpaceVariable = createAction({+ auth: huggingFaceAuth,+ name: 'upsert_space_variable',+ classification: 'WRITE',+ displayName: 'Set Space Variable',+ description: 'Create or update a public environment variable of a Hugging Face Space.',+ audience: 'ai',+ aiMetadata: {+ description:+ "Creates or overwrites a public environment variable (a non-sensitive setting such as a model name) on a Space, keyed by name. Variables are visible to anyone who can see the Space, so put API keys and passwords in Set Space Secret instead. Setting a variable restarts the Space. Re-setting the same key and value converges, so it is safe to retry. Requires a write-role token.",+ idempotent: true,+ },+ outputSchema: upsertSpaceVariableOutputSchema,+ props: {+ space_id: Property.ShortText({+ displayName: 'Space ID',+ description: "The Space ID in 'namespace/name' form, for example 'my-user/my-demo'.",+ required: true,+ }),+ key: Property.ShortText({+ displayName: 'Key',+ description: "The variable name: starts with a letter, then letters, digits or underscores, for example 'MODEL_NAME'.",+ required: true,+ }),+ value: Property.LongText({+ displayName: 'Value',+ description: 'The variable value. It is visible to anyone who can see the Space.',+ required: true,+ }),+ description: Property.ShortText({+ displayName: 'Description',+ description: 'Optional note about what the variable is for.',+ required: false,+ }),+ },+ async run(context) {+ const { space_id, key, value, description } = context.propsValue;+ const token = context.auth.secret_text;+ const variableKey = hfWrite.assertSpaceKey(key);+ if (typeof value !== 'string') {+ throw new Error('Value is required.');+ }+ const note = hfWrite.optionalText({ value: description, name: 'Description' });+ const space = await hfWrite.resolveRepo({ token, repoType: 'space', repoId: space_id });+ const body: Record<string, unknown> = { key: variableKey, value };+ if (note !== undefined) {+ body['description'] = note;+ }+ await hfWrite.request({+ token,+ method: HttpMethod.POST,+ path: `${space.apiPath}/variables`,+ body,+ });+ return {+ space_id: space.repoId,+ key: variableKey,+ updated: true,+ };+ },+});diff --git a/packages/pieces/community/hugging-face/src/lib/common/dataset-viewer.ts b/packages/pieces/community/hugging-face/src/lib/common/dataset-viewer.tsnew file mode 100644index 00000000000..0715e04ba98--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/common/dataset-viewer.ts@@ -0,0 +1,232 @@+import { AuthenticationType, httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { hfHub, QueryEntry } from './hub-client';+import { hfRepo } from './repo';+import { hfUtils } from './utils';++async function resolveDataset({ token, dataset }: ResolveDatasetParams): Promise<string> {+ return hfRepo.resolveRepoId({ token, repoType: 'dataset', repoId: dataset });+}++function buildViewerUrl({ path, query }: BuildViewerUrlParams): string {+ const search = new URLSearchParams();+ for (const [key, value] of query) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ search.append(key, String(value));+ }+ return `${VIEWER_BASE_URL}${path}?${search.toString()}`;+}++function extractViewerDetail(body: unknown): string | null {+ if (typeof body === 'string') {+ const trimmed = body.trim();+ if (trimmed.length === 0 || trimmed.startsWith('<')) {+ return null;+ }+ return trimmed.slice(0, 500);+ }+ if (hfHub.isRecord(body) && typeof body['error'] === 'string') {+ return body['error'];+ }+ return null;+}++function toViewerError({ error, path, dataset }: ToViewerErrorParams): Error {+ if (!(error instanceof HttpError)) {+ return error instanceof Error ? error : new Error(String(error));+ }+ const status = error.response.status;+ const detail = extractViewerDetail(error.response.body);+ const suffix = detail ? ` Details: ${detail}` : '';+ const resource = `${path} for dataset '${dataset}'`;+ switch (status) {+ case 400:+ case 422:+ return new Error(`The dataset viewer rejected the request (${status}) to ${resource}.${suffix}`);+ case 401:+ case 403:+ return new Error(+ `The dataset viewer cannot access '${dataset}' (${status}). The dataset does not exist, or it is private or gated for this token. Private datasets are served only when owned by a PRO user or an Enterprise organization, and gated datasets need a token whose account has been granted access.${suffix}`+ );+ case 404:+ return new Error(+ `Not found (404): ${resource}. Check the subset (config) and split names with List Dataset Subsets & Splits; a renamed dataset must be called with its current 'namespace/name' ID.${suffix}`+ );+ case 429:+ return hfHub.toError({ error, resource });+ case 500:+ case 501:+ case 502:+ case 503:+ return new Error(+ `The dataset viewer cannot serve ${resource} right now (${status}). The result may still be computing, or this capability is not supported for the dataset. Call Check Dataset Viewer Support, and retry later if the capability is available.${suffix}`+ );+ default:+ return new Error(`Dataset viewer request failed (${status}) for ${resource}.${suffix}`);+ }+}++async function viewerRequest<T>({ token, path, dataset, query }: ViewerRequestParams): Promise<T> {+ const datasetId = await resolveDataset({ token, dataset });+ const url = buildViewerUrl({ path, query: [['dataset', datasetId], ...(query ?? [])] });+ const hasToken = token.trim().length > 0;+ try {+ const response = await httpClient.sendRequest<T>({+ method: HttpMethod.GET,+ url,+ authentication: hasToken ? { type: AuthenticationType.BEARER_TOKEN, token } : undefined,+ });+ return response.body;+ } catch (error) {+ throw toViewerError({ error, path, dataset: datasetId });+ }+}++function validatePaging({ offset, length }: PagingInput): PagingValues {+ hfUtils.assertLimit({ value: offset, min: 0, max: Number.MAX_SAFE_INTEGER, name: 'Offset' });+ hfUtils.assertLimit({ value: length, min: 1, max: MAX_ROWS_PER_CALL, name: 'Length' });+ return { offset: offset ?? 0, length: length ?? DEFAULT_ROWS_PER_CALL };+}++function withPaging({ body, offset }: WithPagingParams): Record<string, unknown> {+ const record = hfHub.isRecord(body) ? body : {};+ const rows = Array.isArray(record['rows']) ? record['rows'] : [];+ const total = typeof record['num_rows_total'] === 'number' ? record['num_rows_total'] : null;+ const nextOffset = offset + rows.length;+ const hasMore = rows.length > 0 && (total === null || nextOffset < total);+ return {+ ...record,+ rows,+ num_rows_total: total,+ partial: record['partial'] === true,+ offset,+ count: rows.length,+ next_offset: hasMore ? nextOffset : null,+ };+}++function datasetProp() {+ return Property.ShortText({+ displayName: 'Dataset ID',+ description:+ "The dataset ID in 'namespace/name' form, for example 'stanfordnlp/imdb'. Find it with Search Datasets.",+ required: true,+ });+}++function configProp() {+ return Property.ShortText({+ displayName: 'Subset (Config)',+ description:+ "The subset (config) name, for example 'plain_text' or 'default'. List valid names with List Dataset Subsets & Splits.",+ required: true,+ });+}++function optionalConfigProp() {+ return Property.ShortText({+ displayName: 'Subset (Config)',+ description:+ "Optional subset (config) name, for example 'plain_text'. Leave empty to cover every subset. List valid names with List Dataset Subsets & Splits.",+ required: false,+ });+}++function splitProp() {+ return Property.ShortText({+ displayName: 'Split',+ description:+ "The split name, for example 'train', 'test' or 'validation'. List valid names with List Dataset Subsets & Splits.",+ required: true,+ });+}++function optionalSplitProp() {+ return Property.ShortText({+ displayName: 'Split',+ description: "Optional split name, for example 'train'. Only used together with a subset (config).",+ required: false,+ });+}++function offsetProp() {+ return Property.Number({+ displayName: 'Offset',+ description: 'Zero-based index of the first row to return. Use 0 for the first page, then the returned next_offset value.',+ required: false,+ defaultValue: 0,+ });+}++function lengthProp() {+ return Property.Number({+ displayName: 'Length',+ description: `Number of rows to return in this page (1 to ${MAX_ROWS_PER_CALL}).`,+ required: false,+ defaultValue: DEFAULT_ROWS_PER_CALL,+ });+}++const VIEWER_BASE_URL = 'https://datasets-server.huggingface.co';+const MAX_ROWS_PER_CALL = 100;+const DEFAULT_ROWS_PER_CALL = 20;++export const hfViewer = {+ baseUrl: VIEWER_BASE_URL,+ maxRowsPerCall: MAX_ROWS_PER_CALL,+ request: viewerRequest,+ resolveDataset,+ toError: toViewerError,+ validatePaging,+ withPaging,+};++export const hfViewerProps = {+ dataset: datasetProp,+ config: configProp,+ optionalConfig: optionalConfigProp,+ split: splitProp,+ optionalSplit: optionalSplitProp,+ offset: offsetProp,+ length: lengthProp,+};++type ResolveDatasetParams = {+ token: string;+ dataset: string;+};++type BuildViewerUrlParams = {+ path: string;+ query: QueryEntry[];+};++type ToViewerErrorParams = {+ error: unknown;+ path: string;+ dataset: string;+};++type ViewerRequestParams = {+ token: string;+ path: string;+ dataset: string;+ query?: QueryEntry[];+};++type PagingInput = {+ offset: number | undefined;+ length: number | undefined;+};++type PagingValues = {+ offset: number;+ length: number;+};++type WithPagingParams = {+ body: unknown;+ offset: number;+};diff --git a/packages/pieces/community/hugging-face/src/lib/common/hub-write.ts b/packages/pieces/community/hugging-face/src/lib/common/hub-write.tsnew file mode 100644index 00000000000..089e9e09197--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/common/hub-write.ts@@ -0,0 +1,314 @@+import {+ AuthenticationType,+ httpClient,+ HttpError,+ HttpMethod,+ HttpResponse,+} from '@activepieces/pieces-common';+import { hfHub, QueryEntry } from './hub-client';+import { hfRepo } from './repo';++function buildWriteUrl({ path, query }: { path: string; query?: QueryEntry[] }): string {+ const search = new URLSearchParams();+ for (const [key, value] of query ?? []) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ search.append(key, String(value));+ }+ const queryString = search.toString();+ return queryString ? `${hfHub.baseUrl}${path}?${queryString}` : `${hfHub.baseUrl}${path}`;+}++function errorDetail(body: unknown): string | null {+ if (typeof body === 'string') {+ const trimmed = body.trim();+ return trimmed.length > 0 ? trimmed.slice(0, 500) : null;+ }+ if (hfHub.isRecord(body)) {+ const error = body['error'];+ if (typeof error === 'string') {+ return error;+ }+ const message = body['message'];+ if (typeof message === 'string') {+ return message;+ }+ }+ return null;+}++function toWriteError({ error, resource, statusErrors }: ToWriteErrorParams): Error {+ if (!(error instanceof HttpError)) {+ return hfHub.toError({ error, resource });+ }+ return statusToWriteError({ status: error.response.status, body: error.response.body, resource, statusErrors });+}++function statusToWriteError({ status, body, resource, statusErrors }: StatusToWriteErrorParams): Error {+ const detail = errorDetail(body);+ const custom = statusErrors?.[status];+ if (custom) {+ return custom(detail);+ }+ const suffix = detail ? ` Details: ${detail}` : '';+ switch (status) {+ case 401:+ return new Error(+ `TOKEN_LACKS_WRITE_PERMISSION: Hugging Face refused the token (401) for ${resource}. Write actions need a token with the 'write' role, or a fine-grained token that grants write access to this repository or namespace. A read-only token fails here even though reads still work. Check the token role with Get Current User & Token.${suffix}`+ );+ case 403:+ return new Error(+ `TOKEN_LACKS_WRITE_PERMISSION: access denied (403) for ${resource}. The token lacks write permission on this resource (a read-role token, or a fine-grained token scoped to other repositories), or the account is not an owner/admin of it. Check the token role with Get Current User & Token.${suffix}`+ );+ case 409:+ return new Error(`CONFLICT: Hugging Face reported a conflict (409) for ${resource}.${suffix}`);+ default:+ return hfHub.toError({ error: new HttpError(undefined, { status, responseBody: body }), resource });+ }+}++function parseResponseText(text: string): unknown {+ if (text.length === 0) {+ return null;+ }+ try {+ const parsed: unknown = JSON.parse(text);+ return parsed;+ } catch {+ return text;+ }+}++async function sensitiveWriteRequest({+ token,+ method,+ path,+ body,+ statusErrors,+}: SensitiveWriteRequestParams): Promise<unknown> {+ let response: Response;+ try {+ response = await fetch(buildWriteUrl({ path }), {+ method,+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(SENSITIVE_REQUEST_TIMEOUT_MS),+ });+ } catch (error) {+ const reason = error instanceof Error ? error.name : 'unknown error';+ throw new Error(`Could not reach Hugging Face for ${path} (${reason}). Retry in a moment.`);+ }+ const responseBody = parseResponseText(await response.text());+ if (!response.ok) {+ throw statusToWriteError({ status: response.status, body: responseBody, resource: path, statusErrors });+ }+ return responseBody;+}++async function sendWrite({+ token,+ method,+ path,+ query,+ body,+}: WriteRequestParams): Promise<HttpResponse<unknown>> {+ return httpClient.sendRequest<unknown>({+ method,+ url: buildWriteUrl({ path, query }),+ body,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token },+ });+}++async function writeRequest({+ statusErrors,+ ...params+}: WriteRequestParams & { statusErrors?: StatusErrors }): Promise<unknown> {+ try {+ const response = await sendWrite(params);+ return response.body;+ } catch (error) {+ throw toWriteError({ error, resource: params.path, statusErrors });+ }+}++async function createOrConflict(params: WriteRequestParams): Promise<CreateOutcome> {+ try {+ const response = await sendWrite(params);+ return { conflict: false, body: response.body };+ } catch (error) {+ if (error instanceof HttpError && error.response.status === 409) {+ return { conflict: true, body: error.response.body };+ }+ throw toWriteError({ error, resource: params.path });+ }+}++async function currentUsername(token: string): Promise<string> {+ const response = await hfHub.request<unknown>({+ token,+ method: HttpMethod.GET,+ path: '/api/whoami-v2',+ });+ const name = hfHub.isRecord(response.body) ? response.body['name'] : undefined;+ if (typeof name !== 'string' || name.length === 0) {+ throw new Error('Could not read the username of the connected Hugging Face account from /api/whoami-v2.');+ }+ return name;+}++async function resolveRepo({ token, repoType, repoId }: ResolveRepoParams): Promise<ResolvedRepo> {+ const info = hfRepo.getTypeInfo(repoType);+ const canonical = await hfRepo.resolveRepoId({ token, repoType, repoId });+ return {+ repoId: canonical,+ repoType: info.singular,+ apiPath: `/api/${info.apiSegment}/${hfRepo.encodeRepoId(canonical)}`,+ webUrl: `${hfHub.baseUrl}/${info.resolvePrefix}${canonical}`,+ };+}++function requireText({ value, name, maxLength }: RequireTextParams): string {+ const trimmed = (value ?? '').trim();+ if (trimmed.length === 0) {+ throw new Error(`${name} is required.`);+ }+ if (maxLength !== undefined && trimmed.length > maxLength) {+ throw new Error(`${name} must be at most ${maxLength} characters (got ${trimmed.length}).`);+ }+ return trimmed;+}++function optionalText({ value, name, maxLength }: RequireTextParams): string | undefined {+ const trimmed = (value ?? '').trim();+ if (trimmed.length === 0) {+ return undefined;+ }+ if (maxLength !== undefined && trimmed.length > maxLength) {+ throw new Error(`${name} must be at most ${maxLength} characters (got ${trimmed.length}).`);+ }+ return trimmed;+}++function assertDiscussionNumber(value: number): number {+ if (!Number.isInteger(value) || value < 1) {+ throw new Error('Discussion Number must be a positive whole number.');+ }+ return value;+}++function stripRefPrefix({ value, prefix }: { value: string; prefix: string }): string {+ return value.startsWith(prefix) ? value.slice(prefix.length) : value;+}++function assertSpaceKey(key: string): string {+ const trimmed = key.trim();+ if (!SPACE_KEY_PATTERN.test(trimmed)) {+ throw new Error(+ `Invalid key '${trimmed}'. Keys must start with a letter and contain only letters, digits and underscores, for example 'OPENAI_API_KEY'.`+ );+ }+ return trimmed;+}++function parseCollectionSlug(slug: string): string {+ const segments = slug+ .trim()+ .replace(/^https?:\/\/huggingface\.co\/collections\//, '')+ .split('/')+ .filter((segment) => segment.length > 0);+ if (segments.length !== 2) {+ throw new Error(+ "Invalid collection slug. Use the 'namespace/title-id' form, for example 'my-user/my-picks-66f448ffc8c32f949b04c8cf'."+ );+ }+ return segments.join('/');+}++function collectionApiPath(slug: string): string {+ return `/api/collections/${slug.split('/').map(encodeURIComponent).join('/')}`;+}++function readString({ record, key }: { record: unknown; key: string }): string | null {+ if (!hfHub.isRecord(record)) {+ return null;+ }+ const value = record[key];+ return typeof value === 'string' ? value : null;+}++const SPACE_KEY_PATTERN = /^[a-zA-Z][_a-zA-Z0-9]*$/;+const SENSITIVE_REQUEST_TIMEOUT_MS = 30000;++export const hfWrite = {+ request: writeRequest,+ sensitiveRequest: sensitiveWriteRequest,+ createOrConflict,+ currentUsername,+ resolveRepo,+ requireText,+ optionalText,+ assertDiscussionNumber,+ stripRefPrefix,+ assertSpaceKey,+ parseCollectionSlug,+ collectionApiPath,+ readString,+};++export type StatusErrors = Partial<Record<number, (detail: string | null) => Error>>;++export type ResolvedRepo = {+ repoId: string;+ repoType: 'model' | 'dataset' | 'space';+ apiPath: string;+ webUrl: string;+};++type WriteRequestParams = {+ token: string;+ method: HttpMethod;+ path: string;+ query?: QueryEntry[];+ body?: unknown;+};++type ToWriteErrorParams = {+ error: unknown;+ resource: string;+ statusErrors?: StatusErrors;+};++type SensitiveWriteRequestParams = {+ token: string;+ method: HttpMethod.POST | HttpMethod.DELETE;+ path: string;+ body: Record<string, unknown>;+ statusErrors?: StatusErrors;+};++type StatusToWriteErrorParams = {+ status: number;+ body: unknown;+ resource: string;+ statusErrors?: StatusErrors;+};++type CreateOutcome = { conflict: false; body: unknown } | { conflict: true; body: unknown };++type ResolveRepoParams = {+ token: string;+ repoType: string;+ repoId: string;+};++type RequireTextParams = {+ value: string | undefined | null;+ name: string;+ maxLength?: number;+};diff --git a/packages/pieces/community/hugging-face/src/lib/common/webhooks.ts b/packages/pieces/community/hugging-face/src/lib/common/webhooks.tsnew file mode 100644index 00000000000..e4931f6899e--- /dev/null+++ b/packages/pieces/community/hugging-face/src/lib/common/webhooks.ts@@ -0,0 +1,291 @@+import { Property } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ httpClient,+ HttpError,+ HttpMethod,+ HttpResponse,+} from '@activepieces/pieces-common';+import { hfHub } from './hub-client';++async function settingsRequest<T>({ token, method, path, body }: SettingsRequestParams): Promise<HttpResponse<T>> {+ try {+ return await httpClient.sendRequest<T>({+ method,+ url: `${hfHub.baseUrl}${path}`,+ body,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token },+ });+ } catch (error) {+ if (error instanceof HttpError && (error.response.status === 401 || error.response.status === 403)) {+ throw new Error(+ `Hugging Face refused ${method} ${path} (${error.response.status}). This action needs a 'write' role token, or a fine-grained token with the matching user-settings permission (webhooks, notifications or watch settings). Call Get Current User & Token to check the token role.`+ );+ }+ throw hfHub.toError({ error, resource: path });+ }+}++function assertObjectId({ value, label }: AssertObjectIdParams): string {+ const trimmed = value.trim();+ if (!OBJECT_ID_PATTERN.test(trimmed)) {+ throw new Error(+ `${label} '${value}' is not a valid Hugging Face ID. It must be a 24-character hexadecimal ObjectId, for example '6390e855e30d9209411de93b'.`+ );+ }+ return trimmed;+}++function webhookPath(webhookId: string): string {+ return `/api/settings/webhooks/${encodeURIComponent(assertObjectId({ value: webhookId, label: 'Webhook ID' }))}`;+}++function assertHttpsUrl(value: string): string {+ const trimmed = value.trim();+ let parsed: URL;+ try {+ parsed = new URL(trimmed);+ } catch {+ throw new Error(`Target URL '${value}' is not a valid URL. Use a full https:// address.`);+ }+ if (parsed.protocol !== 'https:') {+ throw new Error(`Target URL must use https://, got '${parsed.protocol}//'.`);+ }+ return parsed.toString();+}++function assertSecret(value: string): string {+ if (value.length === 0 || !SECRET_PATTERN.test(value)) {+ throw new Error('Secret must be a non-empty string of printable ASCII characters.');+ }+ return value;+}++function parseWatched(value: unknown): WatchedItem[] {+ if (!Array.isArray(value)) {+ return [];+ }+ const items: WatchedItem[] = [];+ for (const entry of value) {+ if (!hfHub.isRecord(entry)) {+ continue;+ }+ const type = typeof entry['type'] === 'string' ? entry['type'].trim() : '';+ const name = typeof entry['name'] === 'string' ? entry['name'].trim() : '';+ if (type.length === 0 && name.length === 0) {+ continue;+ }+ if (!isWatchedType(type)) {+ throw new Error(+ `Watched item type '${type}' is not supported. Use one of: ${WATCHED_TYPES.join(', ')}.`+ );+ }+ if (name.length === 0) {+ throw new Error(`Every watched item needs a name (a username, organization name or 'namespace/name' repository ID).`);+ }+ items.push({ type, name });+ }+ return items;+}++function existingWatched(value: unknown): ExistingWatchedItem[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value+ .filter(hfHub.isRecord)+ .filter((item) => typeof item['type'] === 'string' && typeof item['name'] === 'string')+ .map((item) => ({ type: String(item['type']), name: String(item['name']) }));+}++function parseDomains(value: unknown): WebhookDomain[] {+ if (!Array.isArray(value)) {+ return [];+ }+ const domains: WebhookDomain[] = [];+ for (const entry of value) {+ if (entry === 'repo' || entry === 'discussion') {+ if (!domains.includes(entry)) {+ domains.push(entry);+ }+ continue;+ }+ throw new Error(`Domain '${String(entry)}' is not supported. Use 'repo', 'discussion' or both.`);+ }+ return domains;+}++function toWebhookOutput(raw: unknown): WebhookOutput {+ const source = hfHub.isRecord(raw) ? raw : {};+ const disabledRaw = source['disabled'];+ const watchedRaw = Array.isArray(source['watched']) ? source['watched'].filter(hfHub.isRecord) : [];+ const domainsRaw = Array.isArray(source['domains']) ? source['domains'] : [];+ return {+ id: typeof source['id'] === 'string' ? source['id'] : null,+ url: typeof source['url'] === 'string' ? source['url'] : null,+ enabled: disabledRaw === false,+ disabled_reason: typeof disabledRaw === 'string' ? disabledRaw : disabledRaw === true ? 'disabled' : null,+ watched: watchedRaw.map((item) => ({+ type: typeof item['type'] === 'string' ? item['type'] : null,+ name: typeof item['name'] === 'string' ? item['name'] : null,+ })),+ domains: domainsRaw.filter((item): item is string => typeof item === 'string'),+ has_secret: source['hasSecret'] === true,+ runs_job: hfHub.isRecord(source['job']),+ last_trigger_at: typeof source['lastTriggerAt'] === 'string' ? source['lastTriggerAt'] : null,+ };+}++function unwrapWebhook(body: unknown): unknown {+ if (hfHub.isRecord(body) && hfHub.isRecord(body['webhook'])) {+ return body['webhook'];+ }+ return body;+}++async function fetchWebhook({ token, webhookId }: FetchWebhookParams): Promise<Record<string, unknown>> {+ const response = await settingsRequest<unknown>({+ token,+ method: HttpMethod.GET,+ path: webhookPath(webhookId),+ });+ const webhook = unwrapWebhook(response.body);+ if (!hfHub.isRecord(webhook)) {+ throw new Error(`Hugging Face returned no webhook for ID '${webhookId}'.`);+ }+ return webhook;+}++function isWatchedType(value: string): value is WatchedType {+ return WATCHED_TYPES.some((type) => type === value);+}++function watchedItemsProp({ required, description }: WatchedItemsPropParams) {+ return Property.Array({+ displayName: 'Watched Items',+ description,+ required,+ properties: {+ type: Property.StaticDropdown({+ displayName: 'Type',+ description: "What to watch: a user, an organization, or one model, dataset or Space repository.",+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'User', value: 'user' },+ { label: 'Organization', value: 'org' },+ { label: 'Model', value: 'model' },+ { label: 'Dataset', value: 'dataset' },+ { label: 'Space', value: 'space' },+ ],+ },+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: "A username ('julien-c'), organization name ('huggingface') or repository ID ('openai-community/gpt2').",+ required: true,+ }),+ },+ });+}++function domainsProp({ required, description }: DomainsPropParams) {+ return Property.StaticMultiSelectDropdown({+ displayName: 'Domains',+ description,+ required,+ options: {+ disabled: false,+ options: [+ { label: 'Repository changes (commits, tags, settings)', value: 'repo' },+ { label: 'Discussions and pull requests', value: 'discussion' },+ ],+ },+ });+}++function webhookIdProp() {+ return Property.ShortText({+ displayName: 'Webhook ID',+ description: "The webhook's 24-character hexadecimal ID. Find it with List Webhooks.",+ required: true,+ });+}++const OBJECT_ID_PATTERN = /^[0-9a-fA-F]{24}$/;+const SECRET_PATTERN = /^[\x20-\x7F]*$/;+const WATCHED_TYPES: WatchedType[] = ['user', 'org', 'model', 'dataset', 'space'];++export const hfSettingsApi = {+ request: settingsRequest,+ assertObjectId,+};++export const hfWebhooks = {+ path: webhookPath,+ assertHttpsUrl,+ assertSecret,+ parseWatched,+ existingWatched,+ parseDomains,+ toOutput: toWebhookOutput,+ unwrap: unwrapWebhook,+ fetch: fetchWebhook,+ watchedItemsProp,+ domainsProp,+ webhookIdProp,+};++export type WatchedType = 'user' | 'org' | 'model' | 'dataset' | 'space';++export type WatchedItem = {+ type: WatchedType;+ name: string;+};++export type ExistingWatchedItem = {+ type: string;+ name: string;+};++export type WebhookDomain = 'repo' | 'discussion';++export type WebhookOutput = {+ id: string | null;+ url: string | null;+ enabled: boolean;+ disabled_reason: string | null;+ watched: { type: string | null; name: string | null }[];+ domains: string[];+ has_secret: boolean;+ runs_job: boolean;+ last_trigger_at: string | null;+};++type SettingsRequestParams = {+ token: string;+ method: HttpMethod;+ path: string;+ body?: unknown;+};++type AssertObjectIdParams = {+ value: string;+ label: string;+};++type FetchWebhookParams = {+ token: string;+ webhookId: string;+};++type WatchedItemsPropParams = {+ required: boolean;+ description: string;+};++type DomainsPropParams = {+ required: boolean;+ description: string;+};diff --git a/packages/pieces/community/hugging-face/src/lib/output-schemas.ts b/packages/pieces/community/hugging-face/src/lib/output-schemas.tsindex 681de61f716..aee9aa64c0d 100644--- a/packages/pieces/community/hugging-face/src/lib/output-schemas.ts+++ b/packages/pieces/community/hugging-face/src/lib/output-schemas.ts@@ -180,6 +180,137 @@ const collectionFields: OutputSchemaField[] = [},];+const viewerPartialField: OutputSchemaField = {+ key: 'partial',+ label: 'Partial',+ format: 'boolean',+ description: 'True when the viewer only processed part of a very large dataset.',+};++const viewerPendingField: OutputSchemaField = {+ key: 'pending',+ label: 'Pending',+ description: 'Subsets or splits the viewer is still processing.',+};++const viewerFailedField: OutputSchemaField = {+ key: 'failed',+ label: 'Failed',+ description: 'Subsets or splits the viewer could not process.',+};++const datasetSplitRefFields: OutputSchemaField[] = [+ { key: 'dataset', label: 'Dataset ID' },+ { key: 'config', label: 'Subset (Config)' },+ { key: 'split', label: 'Split' },+];++const datasetFeaturesField: OutputSchemaField = {+ key: 'features',+ label: 'Columns',+ labelKey: 'name',+ listItems: [+ { key: 'feature_idx', label: 'Column Index', format: 'number' },+ { key: 'name', label: 'Column Name' },+ {+ key: 'type',+ label: 'Column Type',+ description: "The datasets feature type, for example {dtype: 'string', _type: 'Value'} or a ClassLabel with names.",+ },+ ],+};++const datasetRowsField: OutputSchemaField = {+ key: 'rows',+ label: 'Rows',+ labelKey: 'row_idx',+ listItems: [+ { key: 'row_idx', label: 'Row Index', format: 'number' },+ {+ key: 'row',+ label: 'Row',+ dynamicKey: true,+ description: 'The row values, keyed by column name. Columns differ per dataset; see Columns.',+ },+ {+ key: 'truncated_cells',+ label: 'Truncated Cells',+ description: 'Names of columns whose values were cut short because they were too large.',+ },+ ],+};++const datasetSizeCoreFields: OutputSchemaField[] = [+ { key: 'dataset', label: 'Dataset ID' },+ { key: 'num_rows', label: 'Rows', format: 'number' },+ { key: 'num_bytes_parquet_files', label: 'Parquet Size', format: 'filesize' },+ { key: 'num_bytes_memory', label: 'In-Memory Size', format: 'filesize' },+ {+ key: 'estimated_num_rows',+ label: 'Estimated Rows',+ format: 'number',+ description: 'Only set when the viewer processed part of the data; null otherwise.',+ },+];++const repoRefFields: OutputSchemaField[] = [+ { key: 'repo_id', label: 'Repo ID' },+ { key: 'repo_type', label: 'Repo Type' },+];++const discussionRefFields: OutputSchemaField[] = [+ ...repoRefFields,+ { key: 'discussion_number', label: 'Discussion Number', format: 'number' },+];++const spaceKeyRefFields: OutputSchemaField[] = [+ { key: 'space_id', label: 'Space ID' },+ { key: 'key', label: 'Key' },+];++const collectionWriteFields: OutputSchemaField[] = [+ { key: 'slug', label: 'Collection Slug' },+ { key: 'item_count', label: 'Item Count', format: 'number' },+ { key: 'url', label: 'Collection URL', format: 'url' },+];++const webhookFields: OutputSchemaField[] = [+ { key: 'id', label: 'Webhook ID' },+ { key: 'url', label: 'Target URL', format: 'url' },+ { key: 'enabled', label: 'Enabled', format: 'boolean' },+ {+ key: 'disabled_reason',+ label: 'Disabled Reason',+ description: "Why the webhook is off, for example 'disabled' when turned off by hand. Null while enabled.",+ },+ {+ key: 'watched',+ label: 'Watched Items',+ labelKey: 'name',+ listItems: [+ { key: 'type', label: 'Type', description: "'user', 'org', 'model', 'dataset' or 'space'." },+ { key: 'name', label: 'Name' },+ ],+ },+ { key: 'domains', label: 'Event Domains', description: "'repo', 'discussion' or both." },+ { key: 'has_secret', label: 'Has Secret', format: 'boolean' },+ { key: 'runs_job', label: 'Runs a Job', format: 'boolean' },+ { key: 'last_trigger_at', label: 'Last Triggered At', format: 'datetime' },+];++const socialHandleFields: OutputSchemaField[] = [+ { key: 'twitter', label: 'X (Twitter) Handle' },+ { key: 'github', label: 'GitHub Handle' },+ { key: 'linkedin', label: 'LinkedIn Handle' },+];++const watchTargetFields: OutputSchemaField[] = [+ { key: 'type', label: 'Type', description: "'user', 'org', 'model', 'dataset' or 'space'." },+ { key: 'name', label: 'Name', description: 'The username, organization name or canonical repository ID.' },+ { key: 'id', label: 'Hub ID', description: 'The 24-character Hub ObjectId the name resolved to.' },+ { key: 'watch_type', label: 'Watch Type', description: "'user', 'org' or 'repo', as sent to the Hub." },+];+export const languageTranslationOutputSchema: OutputSchema = {fields: [{ key: 'translatedText', label: 'Translated Text' },@@ -1159,3 +1290,577 @@ export const generateEmbeddingsOutputSchema: OutputSchema = {},],};++export const checkDatasetViewerSupportOutputSchema: OutputSchema = {+ fields: [+ { key: 'preview', label: 'Preview Supported', format: 'boolean' },+ { key: 'viewer', label: 'Viewer Supported', format: 'boolean' },+ { key: 'search', label: 'Search Supported', format: 'boolean' },+ { key: 'filter', label: 'Filter Supported', format: 'boolean' },+ { key: 'statistics', label: 'Statistics Supported', format: 'boolean' },+ ],+};++export const listDatasetSplitsOutputSchema: OutputSchema = {+ fields: [+ { key: 'splits', label: 'Splits', labelKey: 'split', listItems: datasetSplitRefFields },+ countField,+ viewerPendingField,+ viewerFailedField,+ ],+};++export const previewDatasetRowsOutputSchema: OutputSchema = {+ fields: [+ ...datasetSplitRefFields,+ datasetFeaturesField,+ datasetRowsField,+ countField,+ {+ key: 'rows_available',+ label: 'Rows Available in Preview',+ format: 'number',+ description: 'How many preview rows the viewer returned before Max Rows was applied (at most 100).',+ },+ {+ key: 'truncated',+ label: 'Truncated',+ format: 'boolean',+ description: 'True when the returned rows are fewer than the whole split, either because the viewer preview is partial or because Max Rows trimmed it.',+ },+ ],+};++export const getDatasetRowsOutputSchema: OutputSchema = {+ fields: [+ datasetFeaturesField,+ datasetRowsField,+ countField,+ { key: 'offset', label: 'Offset', format: 'number' },+ {+ key: 'next_offset',+ label: 'Next Offset',+ format: 'number',+ description: 'Pass this to Offset to fetch the next page. Null on the last page.',+ },+ { key: 'num_rows_total', label: 'Total Rows', format: 'number' },+ { key: 'num_rows_per_page', label: 'Rows per Page', format: 'number' },+ viewerPartialField,+ ],+};++export const getDatasetViewerInfoOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'dataset_info',+ label: 'Dataset Info',+ description:+ 'With a subset: that subset\'s description, citation, homepage, license, features (column schema keyed by column name), splits (keyed by split name, with num_examples and num_bytes), download_size and dataset_size. Without a subset: the same object keyed by subset name.',+ },+ viewerPartialField,+ ],+};++export const getDatasetSizeOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'size',+ label: 'Size',+ children: [+ {+ key: 'dataset',+ label: 'Whole Dataset',+ description: 'Totals across every subset.',+ children: [+ ...datasetSizeCoreFields,+ { key: 'num_bytes_original_files', label: 'Original Files Size', format: 'filesize' },+ ],+ },+ {+ key: 'configs',+ label: 'Subsets',+ labelKey: 'config',+ listItems: [+ ...datasetSizeCoreFields,+ { key: 'config', label: 'Subset (Config)' },+ { key: 'num_columns', label: 'Columns', format: 'number' },+ { key: 'num_bytes_original_files', label: 'Original Files Size', format: 'filesize' },+ ],+ },+ {+ key: 'splits',+ label: 'Splits',+ labelKey: 'split',+ listItems: [+ ...datasetSizeCoreFields,+ { key: 'config', label: 'Subset (Config)' },+ { key: 'split', label: 'Split' },+ { key: 'num_columns', label: 'Columns', format: 'number' },+ ],+ },+ ],+ },+ viewerPendingField,+ viewerFailedField,+ viewerPartialField,+ ],+};++export const getDatasetStatisticsOutputSchema: OutputSchema = {+ fields: [+ { key: 'num_examples', label: 'Rows in Split', format: 'number' },+ {+ key: 'statistics',+ label: 'Column Statistics',+ labelKey: 'column_name',+ listItems: [+ { key: 'column_name', label: 'Column Name' },+ {+ key: 'column_type',+ label: 'Column Type',+ description: "The viewer's column type, for example 'class_label' or 'string_text'.",+ },+ {+ key: 'column_statistics',+ label: 'Statistics',+ description:+ 'Keys depend on the column type. All include nan_count and nan_proportion; for example string_text adds min, max, mean, median, std and histogram (of text lengths), and class_label adds n_unique and frequencies.',+ },+ ],+ },+ viewerPartialField,+ ],+};++export const listDatasetParquetFilesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'parquet_files',+ label: 'Parquet Files',+ labelKey: 'split',+ listItems: [+ ...datasetSplitRefFields,+ { key: 'filename', label: 'File Name' },+ { key: 'url', label: 'Download URL', format: 'url' },+ { key: 'size', label: 'Size', format: 'filesize' },+ ],+ },+ countField,+ viewerPendingField,+ viewerFailedField,+ viewerPartialField,+ ],+};++export const getDatasetLeaderboardOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'entries',+ label: 'Leaderboard Entries',+ labelKey: 'model_id',+ listItems: [+ { key: 'rank', label: 'Rank', format: 'number' },+ { key: 'model_id', label: 'Model ID' },+ { key: 'value', label: 'Score', format: 'number' },+ { key: 'lower_is_better', label: 'Lower Is Better', format: 'boolean' },+ { key: 'num_parameters', label: 'Parameters', format: 'number' },+ { key: 'verified', label: 'Verified', format: 'boolean' },+ { key: 'author_name', label: 'Author' },+ { key: 'author_fullname', label: 'Author Full Name' },+ { key: 'author_type', label: 'Author Type' },+ { key: 'source_name', label: 'Source' },+ { key: 'source_url', label: 'Source URL', format: 'url' },+ { key: 'source_is_external', label: 'Source Is External', format: 'boolean' },+ { key: 'pull_request', label: 'Pull Request Number', format: 'number' },+ { key: 'filename', label: 'Eval Results File' },+ ],+ },+ countField,+ ],+};++export const createRepoOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'created',+ label: 'Created',+ format: 'boolean',+ description: 'False when the repository already existed and was returned unchanged.',+ },+ ...repoRefFields,+ { key: 'url', label: 'Repo URL', format: 'url' },+ { key: 'private', label: 'Private', format: 'boolean' },+ ],+};++export const updateRepoSettingsOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'updated_settings', label: 'Updated Settings', description: 'Names of the settings that were changed.' },+ {+ key: 'settings',+ label: 'Settings',+ dynamicKey: true,+ description:+ 'The new values of the changed settings, keyed by name: private, discussionsDisabled, gated, gatedNotificationsMode or gatedNotificationsEmail.',+ },+ ],+};++export const createRepoBranchOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'branch', label: 'Branch' },+ {+ key: 'starting_point',+ label: 'Starting Point',+ description: 'The revision the branch was created from. Null means the head of the default branch.',+ },+ { key: 'empty_branch', label: 'Empty Branch', format: 'boolean' },+ { key: 'created', label: 'Created', format: 'boolean' },+ ],+};++export const deleteRepoBranchOutputSchema: OutputSchema = {+ fields: [...repoRefFields, { key: 'branch', label: 'Branch' }, { key: 'deleted', label: 'Deleted', format: 'boolean' }],+};++export const createRepoTagOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'tag', label: 'Tag' },+ { key: 'revision', label: 'Tagged Revision' },+ { key: 'created', label: 'Created', format: 'boolean' },+ ],+};++export const deleteRepoTagOutputSchema: OutputSchema = {+ fields: [...repoRefFields, { key: 'tag', label: 'Tag' }, { key: 'deleted', label: 'Deleted', format: 'boolean' }],+};++export const commitFilesOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'branch', label: 'Branch' },+ { key: 'commit_oid', label: 'Commit SHA' },+ { key: 'commit_url', label: 'Commit URL', format: 'url' },+ {+ key: 'pull_request_url',+ label: 'Pull Request URL',+ format: 'url',+ description: 'Set only when the commit was opened as a pull request; null otherwise.',+ },+ {+ key: 'pull_request_number',+ label: 'Pull Request Number',+ format: 'number',+ description: 'Set only when the commit was opened as a pull request; null otherwise.',+ },+ {+ key: 'pull_request_revision',+ label: 'Pull Request Revision',+ description:+ 'The pull request ref, for example refs/pr/1, when opened as a pull request. Pass it as the branch to add more commits to that pull request.',+ },+ { key: 'files_written', label: 'Files Written' },+ { key: 'paths_deleted', label: 'Paths Deleted' },+ { key: 'total_bytes', label: 'Total Size Written', format: 'filesize' },+ ],+};++export const createDiscussionOutputSchema: OutputSchema = {+ fields: [+ ...discussionRefFields,+ { key: 'title', label: 'Title' },+ { key: 'is_pull_request', label: 'Is Pull Request', format: 'boolean' },+ {+ key: 'pull_request_revision',+ label: 'Pull Request Revision',+ description: 'The pull request ref, for example refs/pr/2, when opened as a pull request; null otherwise.',+ },+ {+ key: 'url',+ label: 'Discussion Path',+ description: 'The discussion path on huggingface.co, for example /user/repo/discussions/2.',+ },+ ],+};++export const commentOnDiscussionOutputSchema: OutputSchema = {+ fields: [+ ...discussionRefFields,+ { key: 'comment_id', label: 'Comment ID' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'Comment URL', format: 'url' },+ ],+};++export const renameDiscussionOutputSchema: OutputSchema = {+ fields: [+ ...discussionRefFields,+ { key: 'title', label: 'New Title' },+ { key: 'previous_title', label: 'Previous Title' },+ { key: 'event_id', label: 'Event ID' },+ ],+};++export const pinDiscussionOutputSchema: OutputSchema = {+ fields: [...discussionRefFields, { key: 'pinned', label: 'Pinned', format: 'boolean' }],+};++export const changeDiscussionStatusOutputSchema: OutputSchema = {+ fields: [+ ...discussionRefFields,+ { key: 'status', label: 'Status' },+ { key: 'event_id', label: 'Event ID' },+ { key: 'created_at', label: 'Changed At', format: 'datetime' },+ ],+};++export const deleteDiscussionOutputSchema: OutputSchema = {+ fields: [...discussionRefFields, { key: 'deleted', label: 'Deleted', format: 'boolean' }],+};++export const createCollectionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'created',+ label: 'Created',+ format: 'boolean',+ description: 'False when a collection with this title already existed and was returned unchanged.',+ },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'private', label: 'Private', format: 'boolean' },+ ...collectionWriteFields,+ ],+};++export const addCollectionItemOutputSchema: OutputSchema = {+ fields: [+ { key: 'item_type', label: 'Item Type' },+ { key: 'item_id', label: 'Item ID' },+ { key: 'item_object_id', label: 'Item Object ID', description: 'The ID of the item entry inside the collection.' },+ ...collectionWriteFields,+ ],+};++export const listGatedAccessRequestsOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'status', label: 'Status Filter' },+ {+ key: 'requests',+ label: 'Access Requests',+ labelKey: 'username',+ listItems: [+ { key: 'username', label: 'Username' },+ { key: 'user_id', label: 'User ID' },+ { key: 'fullname', label: 'Full Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'status', label: 'Status' },+ { key: 'requested_at', label: 'Requested At', format: 'datetime' },+ { key: 'reviewed_at', label: 'Reviewed At', format: 'datetime' },+ { key: 'granted_by', label: 'Granted By' },+ {+ key: 'fields',+ label: 'Gate Form Answers',+ dynamicKey: true,+ description: 'The answers the requester gave on the gate form, keyed by field name.',+ },+ ],+ },+ countField,+ { key: 'oldest_requested_at', label: 'Oldest Requested At', format: 'datetime' },+ { key: 'newest_requested_at', label: 'Newest Requested At', format: 'datetime' },+ ],+};++export const upsertSpaceSecretOutputSchema: OutputSchema = {+ fields: [...spaceKeyRefFields, { key: 'updated', label: 'Updated', format: 'boolean' }],+};++export const deleteSpaceSecretOutputSchema: OutputSchema = {+ fields: [...spaceKeyRefFields, { key: 'deleted', label: 'Deleted', format: 'boolean' }],+};++export const upsertSpaceVariableOutputSchema: OutputSchema = {+ fields: [...spaceKeyRefFields, { key: 'updated', label: 'Updated', format: 'boolean' }],+};++export const deleteSpaceVariableOutputSchema: OutputSchema = {+ fields: [...spaceKeyRefFields, { key: 'deleted', label: 'Deleted', format: 'boolean' }],+};++export const commentOnPaperOutputSchema: OutputSchema = {+ fields: [+ { key: 'paper_id', label: 'Paper ID' },+ { key: 'comment_id', label: 'Comment ID', description: 'Pass this to Reply to Paper Comment. Null if the Hub did not return it.' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'Comment URL', format: 'url' },+ ],+};++export const replyToPaperCommentOutputSchema: OutputSchema = {+ fields: [+ { key: 'paper_id', label: 'Paper ID' },+ { key: 'parent_comment_id', label: 'Parent Comment ID' },+ { key: 'comment_id', label: 'Reply ID', description: 'The ID of the new reply. Null if the Hub did not return it.' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'Reply URL', format: 'url' },+ ],+};++export const handleGatedAccessRequestOutputSchema: OutputSchema = {+ fields: [+ ...repoRefFields,+ { key: 'username', label: 'Username' },+ { key: 'status', label: 'New Status', description: "One of 'accepted', 'rejected', 'pending' or 'reset'." },+ { key: 'reason', label: 'Reason', description: 'The rejection or reset reason sent to the requester. Null when none was given.' },+ ],+};++export const webhookOutputSchema: OutputSchema = {+ fields: webhookFields,+};++export const listWebhooksOutputSchema: OutputSchema = {+ fields: [{ key: 'webhooks', label: 'Webhooks', labelKey: 'url', listItems: webhookFields }, countField],+};++export const updateWebhookOutputSchema: OutputSchema = {+ fields: [+ ...webhookFields,+ {+ key: 'secret_status',+ label: 'Secret Status',+ description: "'kept', 'set', 'replaced', 'cleared' or 'none'.",+ },+ {+ key: 'warning',+ label: 'Warning',+ description: 'Set only when the Hub removed the existing signing secret; null otherwise.',+ },+ ],+};++export const deleteWebhookOutputSchema: OutputSchema = {+ fields: [+ { key: 'webhook_id', label: 'Webhook ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+};++export const listNotificationsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'notifications',+ label: 'Notifications',+ labelKey: 'title',+ listItems: [+ { key: 'type', label: 'Type' },+ { key: 'title', label: 'Title' },+ { key: 'read', label: 'Read', format: 'boolean' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ {+ key: 'discussion_id',+ label: 'Discussion ID',+ description: 'The 24-character ID that Delete Notifications needs, not the discussion number.',+ },+ ...repoRefFields,+ { key: 'discussion_num', label: 'Discussion Number', format: 'number' },+ { key: 'discussion_status', label: 'Discussion Status' },+ { key: 'is_pull_request', label: 'Is Pull Request', format: 'boolean' },+ { key: 'paper_id', label: 'Paper ID' },+ { key: 'post_id', label: 'Post ID' },+ { key: 'post_slug', label: 'Post Slug' },+ { key: 'post_author', label: 'Post Author' },+ { key: 'participants', label: 'Participants', description: 'Comma-separated usernames in the thread.' },+ ],+ },+ countField,+ { key: 'total_matching', label: 'Total Matching', format: 'number' },+ { key: 'total_unread', label: 'Total Unread', format: 'number' },+ { key: 'total_all', label: 'Total Notifications', format: 'number' },+ nextPageField,+ ],+};++export const getUserSocialsOutputSchema: OutputSchema = {+ fields: [{ key: 'username', label: 'Username' }, ...socialHandleFields, { key: 'bluesky', label: 'Bluesky Handle' }],+};++export const getOrganizationSocialsOutputSchema: OutputSchema = {+ fields: [{ key: 'organization', label: 'Organization' }, ...socialHandleFields],+};++export const searchHfDocsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'results',+ label: 'Passages',+ labelKey: 'title',+ listItems: [+ { key: 'title', label: 'Page Title' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'product', label: 'Product' },+ { key: 'section', label: 'Section', description: "The heading path, joined with ' > '." },+ { key: 'text', label: 'Text (Markdown)' },+ ],+ },+ countField,+ ],+};++export const listInferenceEndpointsOutputSchema: OutputSchema = {+ fields: [+ { key: 'namespace', label: 'Namespace' },+ {+ key: 'endpoints',+ label: 'Endpoints',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Access Type', description: "For example 'public', 'protected' or 'private'." },+ { key: 'state', label: 'State', description: "For example 'running', 'paused' or 'scaledToZero'." },+ { key: 'url', label: 'Endpoint URL', format: 'url' },+ { key: 'status_message', label: 'Status Message' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'repository', label: 'Model Repository' },+ { key: 'revision', label: 'Model Revision' },+ { key: 'task', label: 'Task' },+ { key: 'framework', label: 'Framework' },+ { key: 'accelerator', label: 'Accelerator' },+ { key: 'instance_type', label: 'Instance Type' },+ { key: 'instance_size', label: 'Instance Size' },+ { key: 'min_replica', label: 'Min Replicas', format: 'number' },+ { key: 'max_replica', label: 'Max Replicas', format: 'number' },+ { key: 'vendor', label: 'Cloud Vendor' },+ { key: 'region', label: 'Region' },+ ],+ },+ countField,+ ],+};++export const updateWatchListOutputSchema: OutputSchema = {+ fields: [+ { key: 'watched', label: 'Now Watching', labelKey: 'name', listItems: watchTargetFields },+ { key: 'unwatched', label: 'No Longer Watching', labelKey: 'name', listItems: watchTargetFields },+ { key: 'watched_count', label: 'Watched Count', format: 'number' },+ { key: 'unwatched_count', label: 'Unwatched Count', format: 'number' },+ ],+};++export const deleteNotificationsOutputSchema: OutputSchema = {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ {+ key: 'deleted_discussion_ids',+ label: 'Deleted Discussion IDs',+ description: 'The lowercased, de-duplicated discussion IDs whose notifications were removed.',+ },+ countField,+ ],+};diff --git a/packages/pieces/community/hugging-face/test/dataset-viewer.test.ts b/packages/pieces/community/hugging-face/test/dataset-viewer.test.tsnew file mode 100644index 00000000000..6698a7d73c0--- /dev/null+++ b/packages/pieces/community/hugging-face/test/dataset-viewer.test.ts@@ -0,0 +1,153 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { filterDatasetRows } from '../src/lib/actions/filter-dataset-rows';+import { getDatasetRows } from '../src/lib/actions/get-dataset-rows';+import { previewDatasetRows } from '../src/lib/actions/preview-dataset-rows';+import { searchDatasetRows } from '../src/lib/actions/search-dataset-rows';+import { hfViewer } from '../src/lib/common/dataset-viewer';+import { runAction } from './helpers';++function rowsOf(count: number) {+ return Array.from({ length: count }, (_, index) => ({ row_idx: index, row: { text: `row ${index}` }, truncated_cells: [] }));+}++function stubViewer(body: unknown) {+ return vi.spyOn(hfViewer, 'request').mockResolvedValue(body);+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('withPaging', () => {+ it('returns the next offset while more rows remain', () => {+ const result = hfViewer.withPaging({ body: { rows: rowsOf(3), num_rows_total: 10 }, offset: 0 });+ expect(result).toMatchObject({ count: 3, offset: 0, next_offset: 3, num_rows_total: 10, partial: false });+ });++ it('returns a null next offset on the last page', () => {+ const result = hfViewer.withPaging({ body: { rows: rowsOf(2), num_rows_total: 10 }, offset: 8 });+ expect(result).toMatchObject({ count: 2, next_offset: null });+ });++ it('returns a null next offset when the page ends exactly at the total', () => {+ const result = hfViewer.withPaging({ body: { rows: rowsOf(5), num_rows_total: 10 }, offset: 5 });+ expect(result['next_offset']).toBeNull();+ });++ it('returns a null next offset for an empty page', () => {+ const result = hfViewer.withPaging({ body: { rows: [], num_rows_total: 10 }, offset: 10 });+ expect(result).toMatchObject({ count: 0, next_offset: null });+ });++ it('keeps paging when the viewer reports no total', () => {+ const result = hfViewer.withPaging({ body: { rows: rowsOf(4) }, offset: 20 });+ expect(result).toMatchObject({ num_rows_total: null, next_offset: 24 });+ });++ it('passes the partial flag through', () => {+ const result = hfViewer.withPaging({ body: { rows: rowsOf(1), num_rows_total: 5, partial: true }, offset: 0 });+ expect(result['partial']).toBe(true);+ });++ it('treats a malformed body as an empty page', () => {+ const result = hfViewer.withPaging({ body: 'not json', offset: 0 });+ expect(result).toMatchObject({ rows: [], count: 0, next_offset: null, num_rows_total: null });+ });+});++describe('validatePaging', () => {+ it('defaults the offset to 0 and the length to 20', () => {+ expect(hfViewer.validatePaging({ offset: undefined, length: undefined })).toEqual({ offset: 0, length: 20 });+ });++ it('accepts the 100-row maximum', () => {+ expect(hfViewer.validatePaging({ offset: 40, length: 100 })).toEqual({ offset: 40, length: 100 });+ });++ it('rejects more than 100 rows per call', () => {+ expect(() => hfViewer.validatePaging({ offset: 0, length: 101 })).toThrow();+ });++ it('rejects a negative offset', () => {+ expect(() => hfViewer.validatePaging({ offset: -1, length: 10 })).toThrow();+ });+});++describe('row actions', () => {+ it('get_dataset_rows sends offset and length and pages from them', async () => {+ const request = stubViewer({ rows: rowsOf(2), num_rows_total: 6 });+ const result = await runAction({+ action: getDatasetRows,+ propsValue: { dataset: 'stanfordnlp/imdb', config: 'plain_text', split: 'train', offset: 2, length: 2 },+ });+ expect(request).toHaveBeenCalledWith(+ expect.objectContaining({+ path: '/rows',+ query: [+ ['config', 'plain_text'],+ ['split', 'train'],+ ['offset', 2],+ ['length', 2],+ ],+ })+ );+ expect(result).toMatchObject({ offset: 2, count: 2, next_offset: 4 });+ });++ it('search_dataset_rows pages over the matches', async () => {+ const request = stubViewer({ rows: rowsOf(3), num_rows_total: 3 });+ const result = await runAction({+ action: searchDatasetRows,+ propsValue: { dataset: 'stanfordnlp/imdb', config: 'plain_text', split: 'train', query: 'wonderful', offset: 0, length: 3 },+ });+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ path: '/search' }));+ expect(result).toMatchObject({ count: 3, num_rows_total: 3, next_offset: null });+ });++ it('filter_dataset_rows pages over the filtered rows', async () => {+ const request = stubViewer({ rows: rowsOf(2), num_rows_total: 50 });+ const result = await runAction({+ action: filterDatasetRows,+ propsValue: {+ dataset: 'nyu-mll/glue',+ config: 'cola',+ split: 'train',+ where: '"label"=1',+ orderby: undefined,+ offset: 10,+ length: 2,+ },+ });+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ path: '/filter' }));+ expect(result).toMatchObject({ offset: 10, next_offset: 12 });+ });+});++describe('preview_dataset_rows', () => {+ it('marks the preview truncated when Max Rows trims it', async () => {+ stubViewer({ rows: rowsOf(10), truncated: false, features: [] });+ const result = await runAction({+ action: previewDatasetRows,+ propsValue: { dataset: 'stanfordnlp/imdb', config: 'plain_text', split: 'train', max_rows: 3 },+ });+ expect(result).toMatchObject({ count: 3, rows_available: 10, truncated: true });+ });++ it('keeps truncated false when every preview row is returned', async () => {+ stubViewer({ rows: rowsOf(3), truncated: false, features: [] });+ const result = await runAction({+ action: previewDatasetRows,+ propsValue: { dataset: 'stanfordnlp/imdb', config: 'plain_text', split: 'train', max_rows: 20 },+ });+ expect(result).toMatchObject({ count: 3, rows_available: 3, truncated: false });+ });++ it('keeps the viewer truncated flag when the viewer preview is partial', async () => {+ stubViewer({ rows: rowsOf(5), truncated: true, features: [] });+ const result = await runAction({+ action: previewDatasetRows,+ propsValue: { dataset: 'stanfordnlp/imdb', config: 'plain_text', split: 'train', max_rows: 20 },+ });+ expect(result).toMatchObject({ count: 5, truncated: true });+ });+});diff --git a/packages/pieces/community/hugging-face/test/webhooks.test.ts b/packages/pieces/community/hugging-face/test/webhooks.test.tsnew file mode 100644index 00000000000..8f3bc008625--- /dev/null+++ b/packages/pieces/community/hugging-face/test/webhooks.test.ts@@ -0,0 +1,115 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { commitFiles } from '../src/lib/actions/commit-files';+import { updateWebhook } from '../src/lib/actions/update-webhook';+import { runAction } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const WEBHOOK_ID = '6390e855e30d9209411de93b';++function webhook(overrides: Record<string, unknown>) {+ return {+ id: WEBHOOK_ID,+ url: 'https://example.com/hook',+ disabled: false,+ watched: [{ type: 'model', name: 'openai-community/gpt2' }],+ domains: ['repo'],+ hasSecret: true,+ ...overrides,+ };+}++function update({ url, secret }: { url?: string; secret?: string }) {+ return runAction({+ action: updateWebhook,+ propsValue: { webhook_id: WEBHOOK_ID, url, watched: undefined, domains: undefined, secret },+ });+}++beforeEach(() => {+ sendRequest.mockReset();+});++describe('update_webhook secret_status', () => {+ it('reports kept, sends no secret and keeps the current watched items and domains', async () => {+ sendRequest+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({}) } })+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({ url: 'https://example.com/new' }) } });++ const result = await update({ url: 'https://example.com/new' });++ expect(result).toMatchObject({ url: 'https://example.com/new', has_secret: true, secret_status: 'kept', warning: null });+ expect(sendRequest.mock.calls[1][0].body).toEqual({+ url: 'https://example.com/new',+ watched: [{ type: 'model', name: 'openai-community/gpt2' }],+ domains: ['repo'],+ });+ });++ it('reports cleared with a warning when the Hub drops the secret', async () => {+ sendRequest+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({}) } })+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({ hasSecret: false }) } });++ const result = await update({ url: 'https://example.com/hook' });++ expect(result).toMatchObject({ has_secret: false, secret_status: 'cleared' });+ expect(result).toHaveProperty('warning', expect.stringContaining('New Secret'));+ });++ it('reports cleared when the response omits hasSecret', async () => {+ const { hasSecret: _omitted, ...withoutSecretField } = webhook({});+ sendRequest+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({}) } })+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: withoutSecretField } });++ const result = await update({ url: 'https://example.com/hook' });++ expect(result).toMatchObject({ secret_status: 'cleared' });+ });++ it('reports replaced and sends the new secret', async () => {+ sendRequest+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({}) } })+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { webhook: webhook({}) } });++ const result = await update({ secret: 'new-secret' });++ expect(result).toMatchObject({ secret_status: 'replaced', warning: null });+ expect(sendRequest.mock.calls[1][0].body).toMatchObject({ secret: 'new-secret' });+ });+});++describe('commit_files binary check', () => {+ it('refuses base64 content with a NUL byte after the first 8,000 bytes', async () => {+ const content = Buffer.concat([Buffer.from('a'.repeat(9000)), Buffer.from([0]), Buffer.from('b')]).toString('base64');++ await expect(+ runAction({+ action: commitFiles,+ propsValue: {+ repo_type: 'model',+ repo_id: 'user/repo',+ branch: 'main',+ summary: 'Add data',+ commit_description: undefined,+ files: [{ path: 'data.txt', content, encoding: 'base64' }],+ deleted_paths: undefined,+ parent_commit: undefined,+ create_pr: false,+ },+ })+ ).rejects.toThrow(/^LFS_UPLOAD_REQUIRED: 'data.txt' is a binary file/);+ expect(sendRequest).not.toHaveBeenCalled();+ });+});