linkfox-skills
Linkfox skills
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/linkfox-ai/linkfox-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/linkfox-ai/linkfox-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/linkfox-ai-linkfox-skills)HTML
<a href="/listings/linkfox-ai-linkfox-skills"><img src="/api/listings/linkfox-ai-linkfox-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Make sure you have [Node.js](https://nodejs.org/) installed (provides `npx`).
Install all skills
npx skills add linkfox-ai/linkfox-skills
Install specific skills
npx skills add linkfox-ai/linkfox-skills --skill linkfox-amazon-search linkfox-keepa-product-search
List available skills
npx skills add linkfox-ai/linkfox-skills --list
Install for a specific agent
npx skills add linkfox-ai/linkfox-skills --agent claude-code npx skills add linkfox-ai/linkfox-skills --agent cursor
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 454 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # LinkFox Skills
- [](https://opensource.org/licenses/MIT)
- [](https://www.python.org/)
- [](https://agentskills.io)
- [](#skills-catalog)
- **LinkFox Skills** is an AI skill set designed for cross-border e-commerce. It provides 166 API-driven skills covering product research, competitor analysis, keyword tracking, Amazon Ads reporting, patent search, compliance detection, and more.
- Built on the [Agent Skills](https://agentskills.io) open standard, compatible with Claude Code, Cursor, GitHub Copilot, and 30+ AI agent platforms.
- ---
- ## Installation
- Make sure you have [Node.js](https://nodejs.org/) installed (provides `npx`).
- ### Install all skills
- ```bash
- npx skills add linkfox-ai/linkfox-skills
- ```
- ### Install specific skills
- ```bash
- npx skills add linkfox-ai/linkfox-skills --skill linkfox-amazon-search linkfox-keepa-product-search
- ```
- ### List available skills
- ```bash
- npx skills add linkfox-ai/linkfox-skills --list
- ```
- ### Install for a specific agent
- ```bash
- npx skills add linkfox-ai/linkfox-skills --agent claude-code
- npx skills add linkfox-ai/linkfox-skills --agent cursor
- ```
- ## Setup
- Get your API key and configure the environment before using any skill.
- 1. Follow the [LinkFoxAgent API Setup Guide](https://skill.linkfox.com/linkfoxskills/guide.htm) to obtain your key.
- 2. Set the environment variable:
- ```bash
- export LINKFOXAGENT_API_KEY=your-key-here
- ```
- ## Skills Catalog
- ### Amazon
- | Skill | Description |
- | --- | --- |
- | `linkfox-aba-intelligent-query` | Aba Intelligent Query |
- | `linkfox-amazon-ads-auth` | Amazon Ads OAuth authorization, profile discovery, and access-token management |
- | `linkfox-amazon-ads-manager` | Manage Amazon Ads SP/SB/SD entities: list, create, and update campaigns, ad groups, keywords, targets, product ads, and budget rules |
- | `linkfox-amazon-ads-report` | One-stop Amazon Ads SP/SB reporting: request, poll, download, and auto-extract |
- | `linkfox-amazon-ads-sp-insights-report` | Retrieve Sponsored Products audience performance and search-term impression share/rank reports through the beta Amazon Ads Reporting API v1 |
- | `linkfox-amazon-alexa-search` | Amazon Alexa Search |
- | `linkfox-amazon-opportunity-report-by-keyword` | Amazon Opportunity Report By Keyword |
- | `linkfox-amazon-opportunity-search-by-metrics` | Amazon Opportunity Search By Metrics |
- | `linkfox-amazon-policy-feed` | Query Amazon latest policy and regulation feed with AI Chinese summaries, and read full article bodies by record ID |
- | `linkfox-amazon-product-detail` | Get detailed Amazon product info by ASIN (price, BSR, bullets, etc.) |
- | `linkfox-amazon-reviews-list` | Amazon Reviews List |
- | `linkfox-amazon-search` | Search Amazon products by keyword with real-time ranking data |
- | `linkfox-amazon-search-by-image` | Find similar Amazon products using image-based search |
- | `linkfox-amazon-store-aplus-content` | Manage Standard and Premium A+ content, Brand Stories, ASIN associations, approvals, and media for authorized Amazon stores |
- | `linkfox-amazon-store-auth` | Amazon Store Auth |
- | `linkfox-amazon-store-catalog` | Amazon Store Catalog |
- | `linkfox-amazon-store-customer-feedback` | Amazon Store Customer Feedback |
- | `linkfox-amazon-store-external-fulfillment` | Amazon Store External Fulfillment |
- | `linkfox-amazon-store-fba` | Amazon Store Fba |
- | `linkfox-amazon-store-feeds` | Amazon Store Feeds |
- | `linkfox-amazon-store-fulfillment-inbound` | Manage Amazon FBA inbound plans, packing, placement, transportation, shipments, delivery windows, labels, and bills of lading with Fulfillment Inbound v2024-03-20 and retained v0 operations |
- | `linkfox-amazon-store-fulfillment-outbound` | Manage Amazon Multi-Channel Fulfillment quotes, previews, orders, tracking, sandbox status simulations, and related invoice-header discovery with Fulfillment Outbound v2026-07-04 |
- | `linkfox-amazon-store-listings` | Amazon Store Listings |
- | `linkfox-amazon-store-orders` | Amazon Store Orders |
- | `linkfox-amazon-store-pricing` | Amazon Store Pricing |
- | `linkfox-amazon-store-report` | Amazon Store Report |
- | `linkfox-amazon-store-uploads` | Prepare Amazon A+ and Messaging files, create upload destinations, and upload to presigned destinations with PUT or multipart POST |
- ### 1688
- | Skill | Description |
- | --- | --- |
- | `linkfox-dld-product-billboard` | Browse 1688 wholesale product rankings and trending items |
- | `linkfox-dld-product-search` | Search 1688 wholesale marketplace for supplier products |
- ### eBay
- | Skill | Description |
- | --- | --- |
- | `linkfox-ebay-search` | Search eBay listings by keyword with price and seller data |
- ### Walmart
- | Skill | Description |
- | --- | --- |
- | `linkfox-walmart-search` | Search Walmart products by keyword with pricing and availability |
- ### TikTok (EchoTik)
- | Skill | Description |
- | --- | --- |
- | `linkfox-echotik-batch-product-detail` | Batch-fetch detailed TikTok Shop product metrics (multi-period sales and GMV, live, video, influencer, and views data) by product ID or URL |
- | `linkfox-echotik-batch-video-detail` | Batch-fetch detailed TikTok video metrics (views with 1d/7d/30d breakdown, likes with increments, comments, shares, favorites, video sales and GMV, duration, resolution, publish date, creator, and ad/AI/selling flags) by video ID or video URL |
- | `linkfox-echotik-category` | Query EchoTik TikTok category dictionaries, category market details, and historical sales trends |
- | `linkfox-echotik-get-video-download-url` | Resolve a TikTok video URL into no-watermark and watermarked download links, plus playback URL and cover images |
- | `linkfox-echotik-influencer` | Batch-fetch EchoTik TikTok influencer profiles and query historical audience, engagement, and commerce trends |
- | `linkfox-echotik-list-new-product-rank` | Echotik List New Product Rank |
- | `linkfox-echotik-list-product` | Echotik List Product |
- | `linkfox-echotik-list-seller` | List and filter TikTok Shop sellers (stores) by region, category, 30-day GMV, sales trend, listing date, and local/cross-border type, returning store sales, GMV, followers, ratings, reviews, and influencer/video/livestream counts across 16 marketplaces |
- | `linkfox-echotik-list-seller-product` | List the in-store products of a single TikTok Shop seller by sellerId, returning per-product title, price, multi-period (1d/7d/15d/30d/60d/90d/total) sales and GMV, rating, reviews, commission rate, listing date, and sales channel |
- | `linkfox-echotik-list-video` | List and filter TikTok videos by region, creator, product, category, views, duration, publish time, and ad/AI/selling flags, returning views, likes, comments, shares, favorites, video sales, and GMV across 16 marketplaces |
- | `linkfox-echotik-list-video-rank` | Query dated TikTok video rankings by date, region, rank type, and ranking metric, returning views, likes, comments, shares, favorites, video sales, and GMV across 16 marketplaces |
- | `linkfox-echotik-product-video` | Query promotional videos for a TikTok product with engagement and sales metrics |
- | `linkfox-echotik-seller-detail` | Fetch the full profile of a single TikTok Shop seller (store) by sellerId, returning total and multi-period (1d/7d/30d/90d) sales and GMV, followers, rating, reviews, fulfillment rates, product counts, price range, categories, and influencer/video/livestream counts across 16 marketplaces |
- ### TikTok (FastMoss)
- | Skill | Description |
- | --- | --- |
- | `linkfox-fastmoss-product-rank-top-selling` | Fastmoss Product Rank Top Selling |
- | `linkfox-fastmoss-product-search` | Search TikTok products with keyword, category, sales, and creator filters |
- ### TikTok (Kalodata)
- | Skill | Description |
- | --- | --- |
- | `linkfox-kalodata-tiktok-creator` | Browse TikTok Shop creator leaderboards and fetch detailed creator profile and performance data by creator ID via the Kalodata data source |
- | `linkfox-kalodata-tiktok-livestream` | Browse TikTok Shop livestream rankings by region, currency, language, and date range and fetch detailed livestream data by livestream ID via the Kalodata data source |
- | `linkfox-kalodata-tiktok-product` | Browse TikTok Shop product rankings by region, currency, language, and date range and fetch detailed product data by product ID via the Kalodata data source |
- | `linkfox-kalodata-tiktok-shop` | Browse TikTok Shop store leaderboards and fetch detailed store data by shop ID via the Kalodata data source |
- | `linkfox-kalodata-tiktok-video` | Browse top TikTok Shop video leaderboards and fetch detailed shoppable video metrics by video ID via the Kalodata data source |
- ### Ozon (Mpstats)
- | Skill | Description |
- | --- | --- |
- | `linkfox-mpstats-ozon-brand-products` | Drill into all Ozon SKUs under a brand with filters, sorting, and currency conversion via MPSTATS |
- | `linkfox-mpstats-ozon-category-products` | Drill into all Ozon SKUs under a Russian category path with filters for niche mining via MPSTATS |
- | `linkfox-mpstats-ozon-product-detail` | Fetch one full Ozon product card by productId (price, sales, stock, rating, lost profit) via MPSTATS |
- | `linkfox-mpstats-ozon-product-search` | Search Ozon (Russia) products by Russian keyword, SKU list, brand, or seller - the MPSTATS Ozon discovery entry point |
- | `linkfox-mpstats-ozon-product-trend` | Daily time-series for a single Ozon SKU (sales, price, stock, optional search visibility) via MPSTATS |
- | `linkfox-mpstats-ozon-seller-products` | Drill into all Ozon SKUs under a seller ID for shop structure audits via MPSTATS |
- ### Google Trends
- | Skill | Description |
- | --- | --- |
- | `linkfox-google-patent-search` | Search Google Patents by keyword, inventor, assignee, country, date, and status; returns publication numbers, titles, dates, CPC classifications, and PDF links |
- | `linkfox-google-trend-get-trend-by-keys` | Google Trend Get Trend By Keys |
- | `linkfox-google-trend-get-trend-by-time` | Google Trend Get Trend By Time |
- ### Keepa
- | Skill | Description |
- | --- | --- |
- | `linkfox-keepa-product-request` | Keepa Product Request |
- | `linkfox-keepa-product-search` | Advanced Amazon product search with Keepa data (BSR, sales, price filters) |
- | `linkfox-keepa-product-series` | Keepa Product Series |
- ### Jiimore
- | Skill | Description |
- | --- | --- |
- | `linkfox-jiimore-get-niche-info` | Jiimore Get Niche Info |
- | `linkfox-jiimore-get-niche-info-by-asin` | Jiimore Get Niche Info By Asin |
- | `linkfox-jiimore-get-niche-info-by-keyword` | Jiimore Get Niche Info By Keyword |
- | `linkfox-jiimore-get-niche-review-from-keyword` | Jiimore Get Niche Review From Keyword |
- | `linkfox-jiimore-page-asins-by-asin` | Jiimore Page Asins By Asin |
- | `linkfox-jiimore-product-discovery` | Discover profitable products with FBA profitability screening |
- ### JungleScout
- | Skill | Description |
- | --- | --- |
- | `linkfox-junglescout-keyword-by-asin` | Junglescout Keyword By Asin |
- | `linkfox-junglescout-keyword-by-keyword` | Junglescout Keyword By Keyword |
- | `linkfox-junglescout-keyword-history` | Junglescout Keyword History |
- | `linkfox-junglescout-keyword-share-of-voice` | Junglescout Keyword Share Of Voice |
- | `linkfox-junglescout-product-database` | Junglescout Product Database |
- | `linkfox-junglescout-sales-estimates` | Junglescout Sales Estimates |
- ### SellerSprite
- | Skill | Description |
- | --- | --- |
- | `linkfox-sellersprite-competitor-lookup` | Sellersprite Competitor Lookup |
- | `linkfox-sellersprite-market-research` | Sellersprite Market Research |
- | `linkfox-sellersprite-market-statistics` | Sellersprite Market Statistics |
- | `linkfox-sellersprite-product-search` | Search and filter Amazon products using SellerSprite analytics |
- | `linkfox-sellersprite-traffic-keyword` | Sellersprite Traffic Keyword |
- ### SIF (Search Intelligence)
- | Skill | Description |
- | --- | --- |
- | `linkfox-sif-asin-keywords` | Reverse lookup traffic keywords for an ASIN (organic + ad rankings) |
- | `linkfox-sif-asin-summary` | Analyze ASIN traffic sources and distribution |
- | `linkfox-sif-compliance-detection` | SIF design patent detection: find visually similar design registrations from product images or inspect registration details by ID or primary identifier, including holders, designers, status, dates and classification; results do not establish infringement |
- | `linkfox-sif-keyword-overview` | Get keyword search volume, competition, and CPC overview |
- | `linkfox-sif-keyword-summary` | Sif Keyword Summary |
- ### Sorftime
- | Skill | Description |
- | --- | --- |
- | `linkfox-sorftime-amazon-product-detail` | Sorftime Amazon Product Detail |
- | `linkfox-sorftime-amazon-product-query` | Sorftime Amazon Product Query |
- | `linkfox-sorftime-tiktok-seller-data` | Look up TikTok Shop brands through Sorftime across eight markets by product, brand name or seller; one paid page per call |
- | `linkfox-sorftime-walmart-category-market` | Retrieve the Walmart US category tree, match natural-language category names, and analyze category markets with returned Best Seller product data via Sorftime |
- | `linkfox-sorftime-walmart-keyword-research` | Research Walmart keywords, product-keyword relationships, related terms, and saved keyword folders via Sorftime |
- | `linkfox-sorftime-walmart-product-analysis` | Find Walmart products by natural-language name and query product details, trends, and variant sales via Sorftime |
- ### Shopee (YouYing)
- | Skill | Description |
- | --- | --- |
- | `linkfox-youying-shopee-get-product-infos` | Youying Shopee Get Product Infos |
- ### Compliance (Ruiguan)
- | Skill | Description |
- | --- | --- |
- | `linkfox-ruiguan-copyright-detection` | Ruiguan Copyright Detection |
- | `linkfox-ruiguan-detection-patent-design` | Ruiguan Detection Patent Design |
- | `linkfox-ruiguan-gun-parts-search` | Ruiguan Gun Parts Search |
- | `linkfox-ruiguan-text-trademark-detection` | Ruiguan Text Trademark Detection |
- | `linkfox-ruiguan-trademark-graphic-detection` | Ruiguan Trademark Graphic Detection |
- | `linkfox-ruiguan-utility-patent-detection` | Ruiguan Utility Patent Detection |
- ### PatSnap (Zhihuiya) Patent
- | Skill | Description |
- | --- | --- |
- | `linkfox-zhihuiya-abstract-data-translated` | Zhihuiya Abstract Data Translated |
- | `linkfox-zhihuiya-abstract-image` | Retrieve patent abstract images from PatSnap |
- | `linkfox-zhihuiya-bibliography` | Look up patent bibliographic data (applicant, inventor, classification) |
- | `linkfox-zhihuiya-claim-data` | Retrieve patent claim text and structure |
- | `linkfox-zhihuiya-claim-data-translated` | Zhihuiya Claim Data Translated |
- | `linkfox-zhihuiya-description-data` | Zhihuiya Description Data |
- | `linkfox-zhihuiya-description-data-translated` | Zhihuiya Description Data Translated |
- | `linkfox-zhihuiya-fulltext-image` | Retrieve full-text images from a patent document |
- | `linkfox-zhihuiya-legal-status` | Check patent legal status (granted, expired, pending, etc.) |
- | `linkfox-zhihuiya-patent-cited` | Zhihuiya Patent Cited |
- | `linkfox-zhihuiya-patent-family` | Look up INPADOC patent family members |
- | `linkfox-zhihuiya-patent-forward-citation` | Zhihuiya Patent Forward Citation |
- | `linkfox-zhihuiya-patent-image-search` | Search patents by image similarity |
- | `linkfox-zhihuiya-pdf-data` | Zhihuiya Pdf Data |
- | `linkfox-zhihuiya-retrieval-patent-search` | Search patents using PatSnap Analytics query expressions (e.g. TACD: keyword), returning patent IDs, publication numbers, and total hit count |
- | `linkfox-zhihuiya-simple-bibliography` | Get simplified patent metadata (title, date, status) |
- | `linkfox-zhihuiya-utility-patent-image-search` | Zhihuiya Utility Patent Image Search |
- ### AI Multimodal
- | Skill | Description |
- | --- | --- |
- | `linkfox-multimodal-extract-attributes` | Extract product attributes from images using AI |
- | `linkfox-multimodal-generate-image` | Generate or edit product images with AI (text-to-image, background swap) |
- | `linkfox-multimodal-product-similarity` | Compare product image similarity using AI vision |
- | `linkfox-multimodal-recognize-image` | Recognize and describe image content with AI (OCR, visual analysis) |
- ### Other Tools
- | Skill | Description |
- | --- | --- |
- | `linkfox-1688-procurement` | Run authorized 1688 procurement workflows including OAuth checks, SKU and address lookup, order preview, guarded order creation, payment links, order status, logistics, cancellation, and receipt confirmation |
- | `linkfox-1688-product-detail` | Retrieve 1688 product details by offer ID with one-piece retail prices, wholesale tiers for two or more units, SKU stock, logistics, and supplier data |
- | `linkfox-1688-search-by-image` | Find similar 1688 supplier products using image-based visual search |
- | `linkfox-ai-mode-google-search` | Ai Mode Google Search |
- | `linkfox-aigc-clothing-suite` | Generate apparel model, selling-point, seeding, size, white-background and A+ images. |
- | `linkfox-aigc-image-edit` | Edit one source image with an instruction and an explicitly chosen image model. |
- | `linkfox-aigc-image-to-video` | Generate video from one image or multiple images with optional reference videos and templates. |
- | `linkfox-aigc-imagegen` | Aigc Imagegen |
- | `linkfox-aigc-imagegen-brand-gene-extract` | Aigc Imagegen Brand Gene Extract |
- | `linkfox-aigc-imagegen-cloth` | Aigc Imagegen Cloth |
- | `linkfox-aigc-imagegen-product` | Aigc Imagegen Product |
- | `linkfox-aigc-multi-image-edit` | Combine multiple reference images into one coherent edited visual. |
- | `linkfox-aigc-product-suite` | Generate product selling-point, scene, close-up, white-background and A+ images from reference assets. |
- | `linkfox-aigc-sales-video` | Create product sales videos from a supplied script and reference images. |
- | `linkfox-aigc-textgen` | Aigc Textgen |
- | `linkfox-aigc-video-edit` | Edit a source video with an instruction and optional reference images. |
- | `linkfox-aigc-video-reclone` | Recreate a reference video using product images, target market and language. |
- | `linkfox-aigc-video-translate` | Translate speech in an existing video into a target language with optional lip synchronization. |
- | `linkfox-aigc-videogen` | Aigc Videogen |
- | `linkfox-aigc-videogen-multi` | Aigc Videogen Multi |
- | `linkfox-chuhaijiang-tiktok-ads` | Research public TikTok ads and creative assets with filtered discovery, detailed performance data, promoted-product relationships, content-structure analysis, and embeddings |
- | `linkfox-chuhaijiang-tiktok-creator` | Research TikTok creators with multi-filter search, detailed profiles, related livestream/product/video drill-downs, and agency, commerce, and follower-growth rankings |
- | `linkfox-chuhaijiang-tiktok-live` | Research public TikTok livestream commerce with multi-filter discovery, detailed room and performance metrics, and products sold in each livestream |
- | `linkfox-chuhaijiang-tiktok-product` | Research TikTok Shop products with multi-filter search, detailed metrics, creator/live/video/review relationships, three rankings, and image similarity search |
- | `linkfox-chuhaijiang-tiktok-shop` | Research TikTok Shop stores with multi-filter discovery, detailed profiles, creator/product/video relationships, and most-promoted and top-selling rankings |
- | `linkfox-chuhaijiang-tiktok-video` | Research public TikTok videos with multi-filter discovery, detailed performance profiles, promoted-product relationships, and public comment drill-downs |
- | `linkfox-damai-mercado-market-intelligence` | Research Mercado Libre markets across Mexico, Brazil, Argentina, Chile, and Colombia with Damai category, industry, product, sales-trend, image-similarity, and review data through the LinkFox gateway |
- | `linkfox-etsy-category-search` | Etsy Category Search |
- | `linkfox-etsy-product-detail` | Retrieve one public Etsy listing with pricing, images, variants, inventory, shipping, shop, ratings, and review data |
- | `linkfox-etsy-product-query` | Etsy Product Query |
- | `linkfox-etsy-store-query` | Etsy Store Query |
- | `linkfox-geekbi-temu-market-research` | Research Temu category opportunities and buyer-demand keywords by marketplace, demand, revenue, price, supply, semi-managed penetration, and daily, weekly, or monthly growth |
- | `linkfox-geekbi-temu-product` | Search and filter Temu products and retrieve product details and 30-day history via GeekBI, with internal region and category ID resolution |
- | `linkfox-geekbi-temu-search-by-image` | Find visually similar or matching Temu products from an image for product research and competitor discovery |
- | `linkfox-geekbi-temu-shop` | Search and benchmark Temu shops by marketplace, category, sales, revenue, ratings, followers, product count, average order value, hosting mode, and opening date, with internal region and category ID resolution |
- | `linkfox-lazada-store-auth` | Connect and manage Lazada seller stores, and look up store details and performance metrics |
- | `linkfox-lazada-store-finance` | Look up Lazada seller payouts, transaction details, and account transactions |
- | `linkfox-lazada-store-marketing` | Manage Lazada seller vouchers, free shipping, bundle promotions, and Sponsored Max campaigns and reports |
- | `linkfox-lazada-store-orders` | Look up and manage Lazada seller orders, fulfillment, returns, reviews, and store events |
- | `linkfox-lazada-store-product` | Look up and manage Lazada seller products, listings, prices, stock, and media |
- | `linkfox-lingxing-erp` | Lingxing Erp |
- | `linkfox-maidalv-product-tro-detection` | Detect product TRO (Temporary Restraining Order) and trademark/patent/copyright infringement risk from a product image, returning risk level, infringement items, TRO plaintiff info, and an AI legal report |
- | `linkfox-mercado-product-selection` | Query Mercado Libre (Mexico, Brazil, Argentina, Chile, Colombia) product, catalog, keyword, category, trend, seller, review, exchange-rate, and plan-usage data via 24 tools through the LinkFox gateway |
- | `linkfox-product-title-analyze` | Analyze and optimize Amazon product listing titles |
- | `linkfox-seerfar-ozon-category-search` | List an Ozon category's products by categoryId with category aggregates (total sales, total revenue, average price, rating, seasonality) and per-product sales, price, rating, reviews, brand, seller, and fulfillment via Seerfar |
- | `linkfox-seerfar-ozon-keyword-back-search` | Reverse-lookup Ozon (and Wildberries) search keywords by a product SKU list (organic and ad terms), filtered by search volume, growth, competition, natural/ad rank, exposure, and conversion metrics via Seerfar |
- | `linkfox-seerfar-ozon-keyword-mining` | Mine Ozon (and Wildberries) keywords around a seed term, filtered by search volume, growth, competition, price, relevancy, and conversion metrics via Seerfar |
- | `linkfox-seerfar-ozon-market-keyword-search` | Search and filter Ozon (and Wildberries) market keywords by search volume, growth, competition, price, and conversion metrics via Seerfar |
- | `linkfox-seerfar-ozon-product-detail-search` | Fetch full detail of a single Ozon product by SKU (title, price, rating, reviews, QA, windowed total + daily-average + daily-trend sales, revenue, stock, category rank history, brand, seller, fulfillment, weight, listing age) via Seerfar |
- | `linkfox-seerfar-ozon-product-report-search` | Screen and filter Ozon products by sales, revenue, growth, conversion, price, rating, reviews, brand, seller, fulfillment, and listing-age metrics via Seerfar - the Ozon product report / selection screener returning per-product SKU, price (RUB), sales, revenue, conversion, rating, reviews, brand, seller, fulfillment, and listing age |
- | `linkfox-seerfar-ozon-shop-search` | List an Ozon shop's product catalog by seller ID with 30-day sales, price, rating, weight, fulfillment, seller type, return rate, and shop total sales via Seerfar |
- | `linkfox-shopee-product-detail` | Retrieve one public Shopee listing across eight marketplaces with available pricing, sales, stock, variants, media, categories, shop, and rating data |
- | `linkfox-shopee-store-account-health` | Shopee Store Account Health |
- | `linkfox-shopee-store-add-on-deal` | Shopee Store Add On Deal |
- | `linkfox-shopee-store-ads` | Shopee Store Ads |
- | `linkfox-shopee-store-ams` | Shopee Store Ams |
- | `linkfox-shopee-store-auth` | Shopee Store Auth |
- | `linkfox-shopee-store-bundle-deal` | Shopee Store Bundle Deal |
- | `linkfox-shopee-store-discount` | Shopee Store Discount |
- | `linkfox-shopee-store-fbs` | Shopee Store Fbs |
- | `linkfox-shopee-store-first-mile` | Shopee Store First Mile |
- | `linkfox-shopee-store-follow-prize` | Shopee Store Follow Prize |
- | `linkfox-shopee-store-global-product` | Shopee Store Global Product |
- | `linkfox-shopee-store-livestream` | Shopee Store Livestream |
- | `linkfox-shopee-store-logistics` | Shopee Store Logistics |
- | `linkfox-shopee-store-media` | Shopee Store Media |
- | `linkfox-shopee-store-media-space` | Shopee Store Media Space |
- | `linkfox-shopee-store-merchant` | Shopee Store Merchant |
- | `linkfox-shopee-store-orders` | Shopee Store Orders |
- | `linkfox-shopee-store-payment` | Shopee Store Payment |
- | `linkfox-shopee-store-product` | Shopee Store Product |
- | `linkfox-shopee-store-public` | Shopee Store Public |
- | `linkfox-shopee-store-push` | Shopee Store Push |
- | `linkfox-shopee-store-returns` | Shopee Store Returns |
- | `linkfox-shopee-store-sbs` | Shopee Store Sbs |
- | `linkfox-shopee-store-shop` | Shopee Store Shop |
- | `linkfox-shopee-store-shop-category` | Shopee Store Shop Category |
- | `linkfox-shopee-store-shop-flash-sale` | Shopee Store Shop Flash Sale |
- | `linkfox-shopee-store-top-picks` | Shopee Store Top Picks |
- | `linkfox-shopee-store-video` | Shopee Store Video |
- | `linkfox-shopee-store-voucher` | Shopee Store Voucher |
- | `linkfox-shopify-product-query` | Shopify Product Query |
- | `linkfox-shopify-store-query` | Shopify Store Query |
- | `linkfox-smart-table` | Smart Table |
- | `linkfox-temu-add-product-us` | Temu Add Product Us |
- | `linkfox-temu-ads-eu` | Temu Ads Eu |
- | `linkfox-temu-ads-global` | Temu Ads Global |
- | `linkfox-temu-ads-us` | Temu Ads Us |
- | `linkfox-temu-cancel-order-eu` | Temu Cancel Order Eu |
- | `linkfox-temu-cancel-order-global` | Temu Cancel Order Global |
- | `linkfox-temu-cancel-order-us` | Temu Cancel Order Us |
- | `linkfox-temu-category-search` | Temu Category Search |
- | `linkfox-temu-compliance-global` | Temu Compliance Global |
- | `linkfox-temu-fulfillment-eu` | Temu Fulfillment Eu |
- | `linkfox-temu-fulfillment-global` | Temu Fulfillment Global |
- | `linkfox-temu-fulfillment-us` | Temu Fulfillment Us |
- | `linkfox-temu-manage-product-eu` | Temu Manage Product Eu |
- | `linkfox-temu-manage-product-global` | Temu Manage Product Global |
- | `linkfox-temu-manage-product-us` | Temu Manage Product Us |
- | `linkfox-temu-order-eu` | Temu Order Eu |
- | `linkfox-temu-order-global` | Temu Order Global |
- | `linkfox-temu-order-us` | Temu Order Us |
- | `linkfox-temu-price-eu` | Temu Price Eu |
- | `linkfox-temu-price-global` | Temu Price Global |
- | `linkfox-temu-price-us` | Temu Price Us |
- | `linkfox-temu-product-query` | Temu Product Query |
- | `linkfox-temu-promotion-eu` | Temu Promotion Eu |
- | `linkfox-temu-promotion-global` | Temu Promotion Global |
- | `linkfox-temu-promotion-us` | Temu Promotion Us |
- | `linkfox-temu-returns-refunds-eu` | Temu Returns Refunds Eu |
- | `linkfox-temu-returns-refunds-global` | Temu Returns Refunds Global |
- | `linkfox-temu-returns-refunds-us` | Temu Returns Refunds Us |
- | `linkfox-temu-store-query` | Temu Store Query |
- | `linkfox-temu-tax-eu` | Temu Tax Eu |
- | `linkfox-tiktok-shop-product-detail` | Retrieve one public TikTok Shop product with pricing, sales, SKU inventory, media, seller, reviews, shipping, and promotion data |
- | `linkfox-tsearch-search` | Tsearch Search |
- | `linkfox-wallysmarter-product-detail` | Walmart product detail with historical pricing and sales trends via WallySmarter |
- | `linkfox-wb-1688-procurement` | Wb 1688 Procurement |
- | `linkfox-wb-1688-sourcing` | Wb 1688 Sourcing |
- | `linkfox-wb-aigc` | Wb Aigc |
- | `linkfox-wb-amazon-ads` | Wb Amazon Ads |
- | `linkfox-wb-amazon-business-insight` | Wb Amazon Business Insight |
- | `linkfox-wb-amazon-front-data` | Wb Amazon Front Data |
- | `linkfox-wb-amazon-sp-api` | Wb Amazon Sp Api |
- | `linkfox-wb-damai-mercado-intelligence` | Wb Damai Mercado Intelligence |
- | `linkfox-wb-e-commerce-compliance` | Wb E Commerce Compliance |
- | `linkfox-wb-ebay-product-selection` | Wb Ebay Product Selection |
- | `linkfox-wb-echotik-tiktok` | Wb Echotik Tiktok |
- | `linkfox-wb-etsy-data` | Wb Etsy Data |
- | `linkfox-wb-fastmoss-tiktok` | Wb Fastmoss Tiktok |
- | `linkfox-wb-google-tools` | Wb Google Tools |
- | `linkfox-wb-jiimore` | Wb Jiimore |
- | `linkfox-wb-jungle-scout` | Wb Jungle Scout |
- | `linkfox-wb-kalodata-tiktok` | Wb Kalodata Tiktok |
- | `linkfox-wb-keepa` | Wb Keepa |
- | `linkfox-wb-linkfox-aigc` | Wb Linkfox Aigc |
- | `linkfox-wb-maidalv-product-tro-detection` | Wb Maidalv Product Tro Detection |
- | `linkfox-wb-mercado-selection` | Wb Mercado Selection |
- | `linkfox-wb-mpstats-ozon` | Wb Mpstats Ozon |
- | `linkfox-wb-ruiguan-detection` | Wb Ruiguan Detection |
- | `linkfox-wb-seerfar-ozon` | Wb Seerfar Ozon |
- | `linkfox-wb-sellersprite` | Wb Sellersprite |
- | `linkfox-wb-shopee-official-api` | Wb Shopee Official Api |
- | `linkfox-wb-shopee-product-selection` | Wb Shopee Product Selection |
- | `linkfox-wb-shopify-data` | Wb Shopify Data |
- | `linkfox-wb-sif-compliance-detection` | Wb Sif Compliance Detection |
- | `linkfox-wb-sif-search-intelligence` | Wb Sif Search Intelligence |
- | `linkfox-wb-smart-table` | Wb Smart Table |
- | `linkfox-wb-sorftime` | Wb Sorftime |
- | `linkfox-wb-sorftime-walmart` | Wb Sorftime Walmart |
- | `linkfox-wb-temu-data` | Wb Temu Data |
- | `linkfox-wb-tiktok-official-api` | Wb Tiktok Official Api |
- | `linkfox-wb-tiktok-official-video-api` | Wb Tiktok Official Video Api |
- | `linkfox-wb-walmart-product-selection` | Wb Walmart Product Selection |
- | `linkfox-wb-workflow` | Wb Workflow |
- | `linkfox-workflow` | Workflow |
- ## Requirements
- - **Python 3.x** — All scripts use only the standard library. No additional dependencies required.
- - **Environment variable** `LINKFOXAGENT_API_KEY` must be set before use.
- ## Compatible Platforms
- Built on the [Agent Skills](https://agentskills.io) open standard:
- | Platform | Status |
- | --- | --- |
- | Claude Code | Supported |
- | OpenClaw | Supported |
- | Cursor | Supported |
- | GitHub Copilot | Supported |
- | VS Code Copilot | Supported |
- | Gemini CLI | Supported |
- | OpenHands | Supported |
- ## License
- This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
skills/linkfox-1688-procurement/scripts/onboarding.py · Bundled script · 606 lines · 1 finding marked
- #!/usr/bin/env python3
- """LinkFox 账号与环境引导 CLI(单文件版)。
- 子命令:
- send-code <phone> 发送短信验证码
- login <phone> <code> [channel] 验证码登录并获取 API key
- list-plans 列出当前用户可购买的套餐
- order <plan_id> <method> 下单并渲染支付二维码(method: wechat|alipay)
- query <order_id> 查询订单状态
- --help 查看完整帮助
- 所有子命令输出 stdout JSON。stderr 仅日志。自包含,不依赖 _shared/。
- 环境变量配置说明由外层 SKILL.md embed 块直接呈现给用户。
- """
- from __future__ import annotations
- import argparse
- import base64
- import io
- import json
- import os
- import re
- import secrets
- import sys
- import tempfile
- import time
- import urllib.error
- from urllib.request import urlopen, Request
- # Windows 控制台默认 GBK,reconfigure 保证 QR ASCII 与中文可管道输出。
- for _s in (sys.stdout, sys.stderr):
- if hasattr(_s, "reconfigure"):
- try:
- _s.reconfigure(encoding="utf-8")
- except Exception:
- pass
- try:
- import requests
- except ImportError:
- requests = None # 登录/agent-user 链路调用时再报错
- TAG = "[real]"
- UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
- "(KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36")
- # 登录链路固定 uid header(实测可用)
- _LOGIN_FIXED_UID = (os.environ.get("LINKFOX_LOGIN_FIXED_UID")
- or "eyJhX2lkIjoiNmEyMmM4YjA1YmM5MTZhIiwiZF9pZCI6IiJ9")
- Note: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
- Line 49 on GitHub
- AGREEMENTS = {
- "user_agreement": "https://agent.linkfox.com/agreement/term",
- "service_agreement": "https://agent.linkfox.com/agreement/service",
- "privacy_policy": "https://agent.linkfox.com/agreement/privacy",
- }
- PAY_METHOD_MAP = {"wechat": "WX_PAY", "alipay": "ALI_PAY"}
- _ORDER_STATE_MAP = {
- "wait_pay": "unpaid", "paid": "paid", "finished": "paid",
- "expire": "expired", "expired": "expired",
- "cancel": "cancelled", "cancelled": "cancelled",
- }
- # ============================================================
- # Env / 小工具
- # ============================================================
- def _env_base(name: str, default: str, *fallbacks: str) -> str:
- for n in (name, *fallbacks):
- v = os.environ.get(n)
- if v:
- return v.rstrip("/")
- return default.rstrip("/")
- def _agent_base() -> str:
- return _env_base("LINKFOX_AGENT_API_URL", "https://tool-gateway.linkfox.com", "LINKFOX_TOOL_GATEWAY")
- def _login_base() -> str:
- return _env_base("LINKFOX_LOGIN_API_URL", "https://api.linkfox.com")
- def _agent_user_base() -> str:
- return _env_base("LINKFOX_AGENT_USER_API_URL", "https://agent-api.linkfox.com")
- def _api_key() -> str:
- return os.environ.get("LINKFOX_AGENT_API_KEY") or os.environ.get("LINKFOXAGENT_API_KEY") or ""
- def _mask_phone(phone: str) -> str:
- return f"{phone[:3]}****{phone[-4:]}" if len(phone) >= 7 else phone
- def _b64url_json(part: str) -> dict:
- """base64url 解码 JWT 段(自动补 padding),失败返回空 dict。"""
- try:
- return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
- except Exception:
- return {}
- def _uid_header(access_token: str, user_id: str) -> str:
- """base64url({"a_id":<JWT header.a>,"d_id":<userId>})。"""
- parts = (access_token or "").split(".")
- hdr = _b64url_json(parts[1]) if len(parts) >= 2 else {}
- raw = json.dumps({"a_id": hdr.get("a", ""), "d_id": str(user_id)}, separators=(",", ":")).encode()
- return base64.urlsafe_b64encode(raw).decode()
- def _jwt_uid() -> dict:
- """从 LINKFOX_AGENT_API_KEY 的 JWT payload 解出信息。失败返回空 dict。"""
- parts = _api_key().split(".")
- return _b64url_json(parts[1]) if len(parts) >= 2 else {}
- # ============================================================
- # 会话目录 + 二维码
- # ============================================================
- _SESSION_ROOT: str | None = None
- def _linkfox_root() -> str:
- global _SESSION_ROOT
- if _SESSION_ROOT:
- return _SESSION_ROOT
- candidates = []
- acpx = (os.environ.get("ACPX_WORKSPACES") or "").strip().split(os.pathsep)[0].strip()
- if acpx:
- candidates.append(os.path.join(acpx, "linkfox"))
- candidates += [
- os.path.join(os.getcwd(), "linkfox"),
- os.path.join(os.path.expanduser("~"), "linkfox"),
- os.path.join(tempfile.gettempdir(), "linkfox"),
- ]
- for root in candidates:
- try:
- os.makedirs(root, exist_ok=True)
- probe = os.path.join(root, ".write_probe")
- with open(probe, "w", encoding="utf-8"):
- pass
- os.remove(probe)
- _SESSION_ROOT = os.path.abspath(root)
- return _SESSION_ROOT
- except OSError:
- continue
- _SESSION_ROOT = os.path.abspath(candidates[-1])
- return _SESSION_ROOT
- def session_dir() -> str:
- ts = time.time()
- sid = (os.environ.get("SESSION_ID") or "").strip() or (
- time.strftime("%H%M%S", time.localtime(ts)) + "-" + secrets.token_hex(3))
- path = os.path.join(_linkfox_root(), time.strftime("%Y-%m-%d", time.localtime(ts)), sid)
- os.makedirs(path, exist_ok=True)
- return path
- def render_qr(content: str, out_dir: str) -> dict:
- try:
- import qrcode
- except ImportError:
- err = "缺少 qrcode 依赖,请运行: pip install qrcode pillow"
- print(f"{TAG} render_qr: {err}", file=sys.stderr)
- return {"png_path": None, "ascii_qr": None, "error": err}
- os.makedirs(out_dir, exist_ok=True)
- png_path = os.path.join(out_dir, f"qr-{int(time.time() * 1_000_000)}.png")
- qr = qrcode.QRCode(border=1)
- qr.add_data(content)
- qr.make(fit=True)
- qr.make_image(fill_color="black", back_color="white").save(png_path)
- buf = io.StringIO()
- qr.print_ascii(out=buf, invert=True)
- return {"png_path": png_path, "ascii_qr": buf.getvalue()}
- # ============================================================
- # HTTP:requests 走登录/agent-user 链路,urllib 走网关
- # ============================================================
- def _require_requests() -> None:
- if requests is None:
- raise RuntimeError("缺少 requests 依赖,请运行: pip install requests")
- def _http_post(url: str, body: dict, headers: dict, timeout: int = 30) -> dict:
- """通用 requests POST,返回 JSON 或 {_error, _body}。"""
- try:
- _require_requests()
- except RuntimeError as e:
- return {"_error": str(e)}
- try:
- r = requests.post(url, json=body or {}, headers=headers, timeout=timeout)
- return r.json()
- except Exception as e:
- body_text = ""
- resp = getattr(e, "response", None)
- if resp is not None:
- try:
- body_text = resp.text[:500]
- except Exception:
- pass
- return {"_error": str(e), "_body": body_text}
- def _headers(source: str, origin_host: str, *, access_token: str = "",
- user_id: str = "", group_id: str = "") -> dict:
- """构造带浏览器指纹的 headers;access_token 存在则挂 authorization+uid。"""
- h = {
- "Accept": "application/json, text/plain, */*",
- "Content-Type": "application/json;charset=UTF-8",
- "Origin": f"https://{origin_host}",
- "Referer": f"https://{origin_host}/",
- "source": source,
- "User-Agent": UA,
- }
- if access_token:
- h["authorization"] = access_token
- # uid 是登录链路的独立门禁(生产缺失/非法均返回 30021 非法uid),与 authorization 无关,
- # 故不能嵌在 if access_token 内:/user/v*/web/login 不带 token 但同样要求 uid。
- h["uid"] = _uid_header(access_token, user_id) if user_id else _LOGIN_FIXED_UID
- if group_id:
- h["tid"] = group_id
- return h
- def _login_post(path: str, body: dict) -> dict:
- return _http_post(f"{_login_base()}{path}", body,
- _headers("ai-linkfox-web", "ai.linkfox.com", access_token=""))
- def _gateway(method: str, path: str, body: dict | None = None) -> dict:
- """网关 HTTP。401/402/403 明确抛错,5xx 重试 3 次。"""
- url = f"{_agent_base()}{path}"
- body_bytes = json.dumps(body or {}).encode() if method == "POST" else None
- last_exc: Exception = RuntimeError("未知错误")
- for attempt in range(3):
- if attempt:
- time.sleep(1 << (attempt - 1))
- headers = {"Authorization": _api_key()}
- if method == "POST":
- headers["Content-Type"] = "application/json"
- req = Request(url, method=method, data=body_bytes, headers=headers)
- try:
- with urlopen(req, timeout=30) as resp:
- return json.loads(resp.read().decode())
- except urllib.error.HTTPError as e:
- status = e.code
- raw = e.read().decode()[:300]
- if status == 401:
- raise RuntimeError(f"鉴权失败(401),请检查 LINKFOX_AGENT_API_KEY 或 LINKFOXAGENT_API_KEY:{raw}")
- if status == 402:
- raise RuntimeError(f"算力余额不足(402),请充值:{raw}")
- if status == 403:
- raise RuntimeError(f"无权限(403):{raw}")
- last_exc = RuntimeError(f"HTTP {status}: {raw}")
- if status not in (408, 429, 500, 502, 503, 504):
- raise last_exc
- except Exception as e:
- last_exc = RuntimeError(f"网关请求失败: {e}")
- print(f"{TAG} gateway_{method.lower()} attempt {attempt+1}/3 失败: {e}", file=sys.stderr)
- raise last_exc
- # ============================================================
- # 业务:用户信息 / 套餐 / 订单
- # ============================================================
- def _check_biz(resp: dict, tag: str) -> dict:
- if resp.get("errcode") not in (None, 200):
- raise RuntimeError(f"{tag} 业务错误: {resp}")
- return resp
- def fetch_user_info() -> dict:
- return _check_biz(_gateway("GET", "/account/currentByAPI"), "currentByAPI")
- def fetch_packages(package_type: int) -> list:
- resp = _check_biz(_gateway("POST", "/package/getByTypeByAPI", {"packageType": package_type}),
- "getByTypeByAPI")
- return resp.get("packageList") or []
- def normalize_package(p: dict) -> dict | None:
- """免费版(price=0)返回 None 供过滤。"""
- if float(p.get("packagePrice", 0) or 0) == 0:
- return None
- try:
- ext = json.loads(p.get("extJson") or "{}")
- except Exception:
- ext = {}
- return {
- "plan_id": p.get("packageId", ""),
- "name": p.get("packageName", ""),
- "price": p.get("packagePrice", 0),
- "price_string": p.get("packagePriceString", ""),
- "original_price": p.get("originalPrice", 0),
- "original_price_string": p.get("originalPriceString", ""),
- "currency": "CNY",
- "credits": p.get("creditAmount", 0),
- "validity_period": p.get("validityPeriod", ""),
- "validity_period_type": p.get("validityPeriodType", ""),
- "description": p.get("description", ""),
- "is_recommend": bool(ext.get("isRecommend", False)),
- "logo_url": ext.get("logo", ""),
- "features": ext.get("features", []),
- "available_methods": ["wechat", "alipay"],
- }
- def create_order(plan_id: str, method: str) -> dict:
- if method not in PAY_METHOD_MAP:
- raise ValueError(f"不支持的支付方式 {method},仅支持 wechat/alipay")
- user = fetch_user_info()
- is_team = bool(user.get("isTeamUser"))
- # memberId 是 swoosh 路由层必填参数(缺失会被拒为“memberId 为必填参数”),但后端 *ByAPI
- # 下单只认 API key 解出的身份,body 里的值会被丢弃,故传固定占位值而不从 key 解 uid:
- # 一旦 key 格式变更,解析失败会把本可成功的下单误拦为“配置错误”。
- body = {
- "packageId": plan_id, "payType": PAY_METHOD_MAP[method], "payDeviceType": "PC",
- "memberId": "ignored", "groupId": user.get("currentGroupId", ""),
- }
- path = "/order/createTeamOrderByAPI" if is_team else "/order/createByAPI"
- print(f"{TAG} 下单 path={path} isTeamUser={is_team} groupId={body['groupId']}", file=sys.stderr)
- resp = _check_biz(_gateway("POST", path, body), "下单")
- return {
- "order_id": resp.get("orderId", ""),
- "qr_content": resp.get("payQrcode") or resp.get("payUrl", ""),
- "pay_url": resp.get("payUrl", ""),
- "pay_price": resp.get("payPrice", ""),
- "original_price": resp.get("originalPrice", ""),
- "discount_price": resp.get("discountPrice", ""),
- "state": resp.get("state", ""),
- "time_left": resp.get("timeLeft", 0),
- "expire_date": resp.get("expireDate", ""),
- "trade_no": resp.get("tradeNo", ""),
- "product": resp.get("product", ""),
- "pay_type": resp.get("payType", ""),
- }
- def query_order(order_id: str) -> dict:
- resp = _check_biz(_gateway("POST", "/order/getByAPI", {"orderId": order_id}), "查询订单")
- state = resp.get("state", "")
- return {
- "order_id": order_id,
- "status": _ORDER_STATE_MAP.get(state, "unknown"),
- "state": state,
- "paid_at": resp.get("payDate") or None,
- "pay_price": resp.get("payPrice", ""),
- "time_left": resp.get("timeLeft", 0),
- "expire_date": resp.get("expireDate", ""),
- "trade_no": resp.get("tradeNo", ""),
- "product": resp.get("product", ""),
- }
- # ============================================================
- # 发送验证码 + 登录取 key
- # ============================================================
- def send_verify_code(phone: str) -> dict:
- masked = _mask_phone(phone)
- if not re.fullmatch(r"\d{11}", phone):
- return {"sent": False, "phone": masked, "errmsg": f"手机号格式不正确(需 11 位数字): {phone}"}
- resp = _login_post("/user/v1/web/login", {
- "type": "sms", "method": "getVerifyCode",
- "data": {"authPhone": phone, "areaCode": "+86", "clientChannel": "LinkFoxAgent"},
- })
- if "_error" in resp:
- return {"sent": False, "phone": masked, "errmsg": resp.get("_body") or resp["_error"]}
- if resp.get("success") or resp.get("code") == "OK":
- return {"sent": True, "phone": masked, "area_code": "+86", "agreements": AGREEMENTS}
- return {"sent": False, "phone": masked, "errmsg": resp.get("message") or json.dumps(resp, ensure_ascii=False)}
- def _login_v3(phone: str, code: str, channel: str) -> dict:
- resp = _login_post("/user/v3/web/login", {
- "type": "sms", "method": "login", "systemId": "LinkFoxAgent",
- "data": {"areaCode": "+86", "authPhone": phone, "authCode": code,
- "sourceChannel": channel or "skill"},
- })
- if "_error" in resp:
- return {"error": f"login: {resp.get('_body') or resp['_error']}"}
- if not (resp.get("success") or resp.get("code") == "OK"):
- return {"error": f"login: {resp.get('message') or json.dumps(resp, ensure_ascii=False)}"}
- data = resp.get("data") or {}
- access_token, user_id = data.get("accessToken"), data.get("userId")
- if not access_token or not user_id:
- return {"error": f"login: 响应缺 accessToken/userId: {json.dumps(resp, ensure_ascii=False)}"}
- return {
- "access_token": access_token,
- "refresh_token": data.get("refreshToken", "") or "",
- "user_id": str(user_id),
- "nick_name": data.get("userName", ""),
- "is_new_user": bool(data.get("newUser") or data.get("isFirstRegister")),
- }
- def _login_by_token(access_token: str, refresh_token: str) -> dict:
- """新用户送算力。失败不阻断。"""
- resp = _http_post(f"{_agent_user_base()}/account/loginByToken", {
- "token": access_token, "refreshToken": refresh_token,
- "device": {"aid": "3026344186", "did": "", "type": "Windows",
- "os": "10", "model": "149.0.0.0", "brand": "Chrome"},
- }, _headers("agent-linkfox-web", "agent.linkfox.com", access_token=access_token))
- if "_error" in resp:
- return {"error": f"loginByToken: {resp.get('_body') or resp['_error']}"}
- if resp.get("errcode") != 200:
- return {"error": f"loginByToken: {resp.get('errmsg') or json.dumps(resp, ensure_ascii=False)}"}
- print(f"{TAG} loginByToken 成功,新用户算力已触发", file=sys.stderr)
- return {}
- def _fetch_user_info_v3(access_token: str, user_id: str) -> dict:
- """从 userInfo 拿 group_id / member_id。"""
- resp = _http_post(f"{_login_base()}/linkFoxApp/api/userCenter/userInfo", {},
- _headers("agent-linkfox-web", "agent.linkfox.com",
- access_token=access_token, user_id=user_id))
- if "_error" in resp:
- return {"error": f"userInfo: {resp.get('_body') or resp['_error']}"}
- if resp.get("code") != "OK":
- return {"error": f"userInfo: {resp.get('message') or json.dumps(resp, ensure_ascii=False)}"}
- teams = (resp.get("data") or {}).get("teamList") or []
- if not teams:
- return {"error": "userInfo: 用户未开通任何团队空间,请先访问 https://agent.linkfox.com/ 完成开通"}
- selected = (next((t for t in teams if t.get("isSelect") == 1 and t.get("agentTeamId")), None)
- or next((t for t in teams if t.get("agentTeamId")), None))
- if not selected:
- return {"error": "userInfo: 所有团队均未开通 agent 空间,请访问 https://agent.linkfox.com/ 开通"}
- gid, mid = selected.get("agentTeamId"), selected.get("agentMemberId")
- if not gid or not mid:
- return {"error": f"userInfo: 选中团队缺 agentTeamId/agentMemberId: {json.dumps(selected, ensure_ascii=False)}"}
- return {"group_id": str(gid), "member_id": str(mid), "team_name": selected.get("teamName", "")}
- _TOKEN_KEYS = ("token", "apiToken", "api_token", "apiKey", "api_key")
- def _extract_token(resp: dict) -> str:
- if not isinstance(resp, dict):
- return ""
- for src in (resp, resp.get("data") if isinstance(resp.get("data"), dict) else {}):
- for k in _TOKEN_KEYS:
- v = src.get(k)
- if isinstance(v, str) and v:
- return v
- d = resp.get("data")
- return d if isinstance(d, str) and d else ""
- def _get_or_generate_api_token(access_token: str, user_id: str, group_id: str) -> dict:
- hdr = _headers("agent-linkfox-web", "ai.linkfox.com",
- access_token=access_token, user_id=user_id, group_id=group_id)
- for path, source in (("/group/getApiToken", "existing"),
- ("/group/generateApiToken", "generated")):
- resp = _http_post(f"{_agent_user_base()}{path}", {"id": group_id}, hdr)
- if "_error" in resp:
- return {"error": f"{path.rsplit('/', 1)[-1]}: {resp.get('_body') or resp['_error']}"}
- tok = _extract_token(resp)
- if tok:
- return {"api_key": tok, "source": source}
- return {"error": f"generateApiToken: 未拿到 token,响应: {json.dumps(resp, ensure_ascii=False)}"}
- def login_and_get_key(phone: str, code: str, channel: str) -> dict:
- masked = _mask_phone(phone)
- if not re.fullmatch(r"\d{11}", phone):
- return {"error": f"login: 手机号格式不正确: {phone}", "phone": masked}
- if not re.fullmatch(r"\d{4,8}", code):
- return {"error": f"login: 验证码格式不正确: {code}", "phone": masked}
- lg = _login_v3(phone, code, channel)
- if "error" in lg:
- return {"error": lg["error"], "phone": masked}
- if lg.get("is_new_user"):
- lbt = _login_by_token(lg["access_token"], lg["refresh_token"])
- if "error" in lbt:
- print(f"{TAG} {lbt['error']}(不影响拿 key)", file=sys.stderr)
- info = _fetch_user_info_v3(lg["access_token"], lg["user_id"])
- if "error" in info:
- return {"error": info["error"], "phone": masked}
- tok = _get_or_generate_api_token(lg["access_token"], lg["user_id"], info["group_id"])
- if "error" in tok:
- return {"error": tok["error"], "phone": masked}
- return {
- "api_key": tok["api_key"], "phone": masked,
- "group_id": info["group_id"], "member_id": info["member_id"],
- "source": tok["source"], "nick_name": lg.get("nick_name", ""),
- "team_name": info.get("team_name", ""),
- "is_new_user": lg.get("is_new_user", False),
- }
- # ============================================================
- # argparse 分发
- # ============================================================
- def _emit(obj: dict) -> None:
- print(json.dumps(obj, ensure_ascii=False, indent=2))
- def _cmd_send_code(args) -> int:
- r = send_verify_code(args.phone.strip())
- _emit(r)
- if r.get("sent"):
- print(f"{TAG} 验证码已发送到 {r['phone']}", file=sys.stderr)
- return 0 if r.get("sent") else 1
- def _cmd_login(args) -> int:
- r = login_and_get_key(args.phone.strip(), args.code.strip(), args.channel)
- _emit(r)
- if "api_key" in r:
- print(f"{TAG} 成功获取 API key(来源: {r['source']})", file=sys.stderr)
- return 0
- return 1
- def _cmd_list_plans(args) -> int:
- try:
- payload = _jwt_uid()
- if payload:
- print(f"{TAG} JWT uid={payload.get('uid')} name={payload.get('name')}", file=sys.stderr)
- user = fetch_user_info()
- is_team = bool(user.get("isTeamUser"))
- nick = user.get("nickName", "")
- print(f"{TAG} 用户 {nick} isTeamUser={is_team}", file=sys.stderr)
- pkgs = fetch_packages(7 if is_team else 1)
- plans = [n for n in (normalize_package(p) for p in pkgs) if n is not None]
- _emit({"plans": plans, "user": {"nickName": nick, "isTeamUser": is_team}})
- return 0
- except RuntimeError as e:
- _emit({"error": True, "message": str(e)})
- return 1
- def _cmd_order(args) -> int:
- try:
- pkgs = fetch_packages(7 if bool(fetch_user_info().get("isTeamUser")) else 1)
- match = next((n for n in (normalize_package(p) for p in pkgs)
- if n and n["plan_id"] == args.plan_id), None)
- if match is None:
- _emit({"error": True, "message": f"未知套餐 plan_id={args.plan_id}"})
- return 1
- if args.method not in match.get("available_methods", []):
- _emit({"error": True,
- "message": f"套餐 {args.plan_id} 不支持 {args.method},仅支持 {match['available_methods']}"})
- return 1
- order = create_order(args.plan_id, args.method)
- except (RuntimeError, ValueError) as e:
- _emit({"error": True, "message": str(e)})
- return 1
- qr = render_qr(order["qr_content"], session_dir())
- order["png_path"] = qr.get("png_path")
- order["ascii_qr"] = qr.get("ascii_qr")
- if qr.get("error"):
- order["qr_render_error"] = qr["error"]
- _emit(order)
- return 0
- def _cmd_query(args) -> int:
- try:
- _emit(query_order(args.order_id))
- return 0
- except RuntimeError as e:
- _emit({"error": True, "message": str(e)})
- return 1
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(prog="onboarding", description="LinkFox 账号与环境引导 CLI")
- sub = parser.add_subparsers(dest="cmd", required=True)
- p = sub.add_parser("send-code", help="发送短信验证码")
- p.add_argument("phone", help="11 位国内手机号")
- p.set_defaults(func=_cmd_send_code)
- p = sub.add_parser("login", help="验证码登录并获取 API key")
- p.add_argument("phone")
- p.add_argument("code", help="短信验证码")
- p.add_argument("--channel", default="skill",
- help="渠道,默认 skill")
- p.set_defaults(func=_cmd_login)
- sub.add_parser("list-plans", help="列出可购买套餐").set_defaults(func=_cmd_list_plans)
- p = sub.add_parser("order", help="下单并渲染支付二维码")
- p.add_argument("plan_id")
- p.add_argument("method", choices=["wechat", "alipay"])
- p.set_defaults(func=_cmd_order)
- p = sub.add_parser("query", help="查询订单支付状态")
- p.add_argument("order_id")
- p.set_defaults(func=_cmd_query)
- args = parser.parse_args(argv)
- return args.func(args)
- if __name__ == "__main__":
- sys.exit(main())
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.